commit 53811160230431de145e23f5b21f39a4b71a189d
parent 007a4b57097829194e641d39f20ccd8959753968
Author: Florian Dold <dold@taler.net>
Date: Wed, 25 Nov 2026 21:51:31 +0100
wallet storage: open existing browser wallet databases safely
Read the SQLite wallet schema without initializing a file, and support
existing-only and read-only opens in the browser adapter. Open the
published IndexedDB database before cleaning up an interrupted import.
Diffstat:
6 files changed, 104 insertions(+), 14 deletions(-)
diff --git a/packages/idb-bridge/src/browser-sqlite3-impl.test.ts b/packages/idb-bridge/src/browser-sqlite3-impl.test.ts
@@ -96,3 +96,32 @@ test("official SQLite WASM finalizes statements before database close", async ()
await assert.rejects(db.exec("SELECT 1"), /database is closed/);
await assert.rejects(db.prepare("SELECT 1"), /database is closed/);
});
+
+test("SQLite browser opens can require an existing file or read it without writing", async () => {
+ const impl = createBrowserSqlite3Impl(await sqlite3InitModule());
+ const path = "/wallet-open-mode-test.db";
+ await assert.rejects(impl.open(path, { create: false }), /open/);
+ await assert.rejects(impl.open(path, { readonly: true }), /open/);
+ const created = await impl.open(path);
+ try {
+ await created.exec("CREATE TABLE entries (id INTEGER)");
+ } finally {
+ await created.close();
+ }
+ const existing = await impl.open(path, { create: false });
+ try {
+ await existing.exec("INSERT INTO entries VALUES (7)");
+ } finally {
+ await existing.close();
+ }
+ const read = await impl.open(path, { readonly: true });
+ try {
+ assert.deepEqual(
+ await (await read.prepare("SELECT id FROM entries")).getFirst(),
+ { id: 7 },
+ );
+ await assert.rejects(read.exec("DELETE FROM entries"), /readonly/);
+ } finally {
+ await read.close();
+ }
+});
diff --git a/packages/idb-bridge/src/browser-sqlite3-impl.ts b/packages/idb-bridge/src/browser-sqlite3-impl.ts
@@ -32,7 +32,14 @@ export interface OfficialSqliteWasmOptions {
wasmUrl?: string;
}
-type OpenOo1Database = (filename: string) => Database;
+type OpenOo1Database = (filename: string, flags: "r" | "w" | "c") => Database;
+
+interface BrowserSqlite3Interface extends Sqlite3Interface {
+ open(
+ filename: string,
+ options?: { readonly?: boolean; immutable?: boolean; create?: boolean },
+ ): Promise<Sqlite3Database>;
+}
export interface BrowserSqlite3Options {
/** Override the OO1 database constructor, for example with OpfsSAHPoolDb. */
@@ -47,7 +54,7 @@ export interface OpfsSahPoolOptions {
}
export interface OpfsSahPoolSqlite3 {
- sqlite3: Sqlite3Interface;
+ sqlite3: BrowserSqlite3Interface;
pool: SAHPoolUtil;
}
@@ -212,16 +219,21 @@ function prepareStatement(
export function createBrowserSqlite3Impl(
sqlite3: Sqlite3Static,
options: BrowserSqlite3Options = {},
-): Sqlite3Interface {
+): BrowserSqlite3Interface {
const openDatabase =
options.openDatabase ??
- ((filename: string): Database => new sqlite3.oo1.DB(filename, "c"));
+ ((filename, flags): Database => new sqlite3.oo1.DB(filename, flags));
return {
- async open(filename: string): Promise<Sqlite3Database> {
+ async open(filename, options): Promise<Sqlite3Database> {
let db: Database;
try {
- db = openDatabase(filename);
+ const flags = options?.readonly
+ ? "r"
+ : options?.create === false
+ ? "w"
+ : "c";
+ db = openDatabase(filename, flags);
} catch (error) {
const resultCode = (error as { resultCode?: unknown } | undefined)
?.resultCode;
@@ -308,11 +320,11 @@ export async function createOpfsSahPoolSqlite3Impl(
return {
pool,
sqlite3: createBrowserSqlite3Impl(sqlite3, {
- openDatabase(filename) {
+ openDatabase(filename, flags) {
if (!filename.startsWith("/")) {
throw new Error("opfs-sahpool database names must be absolute");
}
- return new pool.OpfsSAHPoolDb(filename);
+ return new sqlite3.oo1.DB(filename, flags, pool.vfsName);
},
}),
};
diff --git a/packages/taler-wallet-core/src/db/indexeddb/database.ts b/packages/taler-wallet-core/src/db/indexeddb/database.ts
@@ -267,13 +267,18 @@ export async function openActiveTalerDatabase(
onUpgradeStart?: (oldVersion: number, newVersion: number) => void,
): Promise<TalerDatabaseGeneration> {
const state = await readMainDbState(idbFactory, true);
- await cleanInterruptedDatabaseReplacement(idbFactory, state);
const handle = await openTalerDatabaseGeneration(
idbFactory,
state.current,
onVersionChange,
onUpgradeStart,
);
+ try {
+ await cleanInterruptedDatabaseReplacement(idbFactory, state);
+ } catch (error) {
+ handle.close();
+ throw error;
+ }
return { name: state.current, handle };
}
@@ -442,7 +447,12 @@ async function cleanupGeneration(
marker: string,
current: string,
): Promise<void> {
- if (!name || name === current) return;
+ if (
+ typeof name !== "string" ||
+ !isCurrentGenerationName(name) ||
+ name === current
+ )
+ return;
try {
if (await tryDeleteDatabase(idbFactory, name)) {
await clearMetaMarker(idbFactory, marker, name);
diff --git a/packages/taler-wallet-core/src/db/sqlite/database.test.ts b/packages/taler-wallet-core/src/db/sqlite/database.test.ts
@@ -98,3 +98,20 @@ test("native exports use one snapshot and recover after a read failure", async (
await rm(dir, { recursive: true, force: true });
}
});
+
+test("opening an existing SQLite wallet never initializes an empty file", async () => {
+ const impl = await createNodeHelperSqlite3Impl({ enableTracing: false });
+ const db = await impl.open(":memory:");
+ try {
+ await assert.rejects(
+ openNativeSqliteWalletDb(db, { requireExisting: true }),
+ /no readable wallet schema/,
+ );
+ const tables = await (
+ await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
+ ).getAll();
+ assert.deepEqual(tables, []);
+ } finally {
+ await db.close();
+ }
+});
diff --git a/packages/taler-wallet-core/src/db/sqlite/database.ts b/packages/taler-wallet-core/src/db/sqlite/database.ts
@@ -368,12 +368,30 @@ export class TxQueue {
}
}
-/**
- * Open a native sqlite wallet database and bring its schema up to date.
- */
+/** Inspect a stored file without applying the wallet schema to it. */
+export async function hasNativeSqliteWalletSchema(
+ db: Sqlite3Database,
+): Promise<boolean> {
+ const statement = await db.prepare(
+ "SELECT 1 FROM pragma_user_version WHERE user_version BETWEEN 1 AND $version" +
+ " AND (SELECT count(*) FROM sqlite_master WHERE type = 'table'" +
+ " AND name IN ('schema_migrations', 'config')) = 2",
+ );
+ try {
+ return !!(await statement.getFirst({ version: SQLITE_SCHEMA_VERSION }));
+ } finally {
+ await statement.finalize();
+ }
+}
+
+/** Open a native SQLite wallet and bring its schema up to date. */
export async function openNativeSqliteWalletDb(
db: Sqlite3Database,
+ options: { requireExisting?: boolean } = {},
): Promise<NativeSqliteWalletDb> {
+ if (options.requireExisting && !(await hasNativeSqliteWalletSchema(db))) {
+ throw Error("the stored file has no readable wallet schema");
+ }
await initSqliteWalletDb(db);
const txc = await SqliteTxControl.create(db);
return {
diff --git a/packages/taler-wallet-core/src/index.ts b/packages/taler-wallet-core/src/index.ts
@@ -42,6 +42,7 @@ export { createPairTimeline } from "./denominations.js";
export { WithdrawalGroupStatus } from "./db/records.js";
export { exportDb, importDb } from "./db/indexeddb/dump.js";
export {
+ CURRENT_DB_CONFIG_KEY,
TALER_WALLET_DB_GENERATION_PREFIX,
TALER_WALLET_MAIN_DB_NAME,
TALER_WALLET_META_DB_NAME,
@@ -57,7 +58,10 @@ export type { DbAccess } from "./db/query.js";
export type { WalletDbHandle } from "./db/handle.js";
export { IdbWalletDbHandle } from "./db/indexeddb/handle.js";
export { SqliteWalletDbHandle } from "./db/sqlite/handle.js";
-export { openNativeSqliteWalletDb } from "./db/sqlite/database.js";
+export {
+ hasNativeSqliteWalletSchema,
+ openNativeSqliteWalletDb,
+} from "./db/sqlite/database.js";
export { convertWalletDb } from "./db/migration/converter.js";
export {
benchmarkOneBackend,