Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

autosave: the sealed purge reaches the legacy shared database too (#807)

nyblnetc4e7a50ff78e
diff --git a/kernel/src/autosave.ts b/kernel/src/autosave.ts
index 3b9e9edc..9f54d451 100644
--- a/kernel/src/autosave.ts
+++ b/kernel/src/autosave.ts
@@ -96,6 +96,29 @@ function open(name: string): Promise<IDBDatabase | null> {
})
}
+/**
+ * Open a database ONLY if it already exists. indexedDB.open() creates a
+ * missing one, and the sealed purge runs on every sealed boot: in a browser
+ * that never had the legacy database it would leave an empty one behind, a new
+ * side effect whose name alone says something (security). So when the open has
+ * to create it (an upgrade from version 0), abort that upgrade: the browser
+ * then discards the database it was creating, and this resolves null.
+ */
+function openExisting(name: string): Promise<IDBDatabase | null> {
+ return new Promise((resolve) => {
+ if (typeof indexedDB === 'undefined') { resolve(null); return }
+ let req: IDBOpenDBRequest
+ try { req = indexedDB.open(name) } catch { resolve(null); return }
+ let created = false
+ req.onupgradeneeded = (e) => {
+ if (e.oldVersion === 0) { created = true; req.transaction?.abort() }
+ }
+ req.onsuccess = () => { if (created) { req.result.close(); resolve(null) } else resolve(req.result) }
+ req.onerror = (e) => { e.preventDefault(); resolve(null) } // the abort lands here
+ req.onblocked = () => resolve(null)
+ })
+}
+
/** Everything in one store of a database, or [] on any failure. */
function readAll(db: IDBDatabase, store: string): Promise<Snapshot[]> {
return new Promise((resolve) => {
@@ -297,6 +320,7 @@ export async function clearRecovery(docId: string): Promise<void> {
} catch { /* host unavailable: nothing to clear there */ }
}
await tx(RECOVERY, 'readwrite', (s) => s.delete(docId))
+ if (isBodySealed()) await purgeLegacy(docId, RECOVERY)
}
/** Delete every version-history snapshot for a docId. Used when a deck is
@@ -305,6 +329,41 @@ export async function clearRecovery(docId: string): Promise<void> {
export async function clearVersions(docId: string): Promise<void> {
const all = await versionsOf(docId) // NOT listVersions: it reads nothing while sealed, and this must still delete
await Promise.all(all.map((v) => tx(VERSIONS, 'readwrite', (s) => s.delete(v.id!))))
+ if (isBodySealed()) await purgeLegacy(docId, VERSIONS)
+}
+
+/**
+ * The sealed purge reaches the LEGACY shared database too (security). Shells
+ * shipped before the per-app scoping go on writing to 'bento-autosave' forever,
+ * so a document's plaintext from before it was sealed can sit there long after
+ * this app's own copy is gone, until pruneOld ages it out. While the body is
+ * sealed, purging a document deletes its rows there as well: that document
+ * only, by docId. Outside a seal, clearRecovery/clearVersions leave the legacy
+ * database alone, as before.
+ */
+async function purgeLegacy(docId: string, store: typeof RECOVERY | typeof VERSIONS): Promise<void> {
+ let name: string
+ try { name = dbName() } catch { return }
+ if (name === LEGACY_DB_NAME) return // already purged above
+ const legacy = await openExisting(LEGACY_DB_NAME)
+ if (!legacy) return
+ try {
+ await new Promise<void>((resolve) => {
+ let t: IDBTransaction
+ try { t = legacy.transaction(store, 'readwrite') } catch { resolve(); return }
+ const os = t.objectStore(store)
+ if (store === RECOVERY) os.delete(docId)
+ else {
+ const cur = os.index('docId').openCursor(IDBKeyRange.only(docId))
+ cur.onsuccess = () => { const c = cur.result; if (c) { c.delete(); c.continue() } }
+ }
+ t.oncomplete = () => resolve()
+ t.onerror = () => resolve()
+ t.onabort = () => resolve()
+ })
+ } finally {
+ legacy.close()
+ }
}
export async function addVersion(doc: KernelDoc): Promise<void> {
diff --git a/scripts/test-store-backstop.ts b/scripts/test-store-backstop.ts
index 66e16767..1e8d9269 100644
--- a/scripts/test-store-backstop.ts
+++ b/scripts/test-store-backstop.ts
@@ -81,5 +81,58 @@ ok((await listVersions('doc-a')).length === 0, 'clearVersions deleted the plaint
ok((await getRecovery('doc-b'))?.title === 'ZZ B ZZ', "another document's recovery copy survives")
ok((await listVersions('doc-b')).length === 1, "another document's versions survive")
+console.log('\nthe sealed purge reaches the legacy shared database too (shipped shells write there)')
+{
+ const LEGACY = 'bento-autosave'
+ // FIRST: a browser that never had the legacy database must not gain one.
+ // indexedDB.open() creates a missing database, and the purge runs on every
+ // sealed boot (security).
+ const names = async () => (await indexedDB.databases()).map((d) => d.name)
+ await new Promise<void>((res) => { const q = indexedDB.deleteDatabase(LEGACY); q.onsuccess = q.onerror = q.onblocked = () => res() })
+ ok(!(await names()).includes(LEGACY), 'setup: no legacy database in this browser')
+ setIdentitySeal(kdoc)
+ await clearRecovery('doc-x'); await clearVersions('doc-x')
+ setIdentitySeal(null)
+ ok(!(await names()).includes(LEGACY), 'a sealed purge in a browser with no legacy database leaves none behind')
+ const openLegacy = (): Promise<IDBDatabase> => new Promise((res, rej) => {
+ const q = indexedDB.open(LEGACY, 1)
+ q.onupgradeneeded = () => {
+ const d = q.result
+ if (!d.objectStoreNames.contains('recovery')) d.createObjectStore('recovery', { keyPath: 'docId' })
+ if (!d.objectStoreNames.contains('versions')) d.createObjectStore('versions', { keyPath: 'id', autoIncrement: true }).createIndex('docId', 'docId', { unique: false })
+ }
+ q.onsuccess = () => res(q.result); q.onerror = () => rej(q.error)
+ })
+ const run = <T,>(db: IDBDatabase, store: string, mode: IDBTransactionMode, f: (s: IDBObjectStore) => IDBRequest<T>) =>
+ new Promise<T>((res, rej) => { const r = f(db.transaction(store, mode).objectStore(store)); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
+ const countIn = async (docId: string) => {
+ const db = await openLegacy()
+ const rec = await run(db, 'recovery', 'readonly', (s) => s.get(docId))
+ const ver = await run(db, 'versions', 'readonly', (s) => s.index('docId').count(IDBKeyRange.only(docId)))
+ db.close()
+ return { rec: !!rec, ver }
+ }
+ // what an OLD shell left behind: plaintext for two documents in the shared DB
+ {
+ const db = await openLegacy()
+ for (const id of ['doc-l', 'doc-other']) {
+ await run(db, 'recovery', 'readwrite', (s) => s.put({ docId: id, at: 1, title: 'ZZ OLD ZZ', json: '{}' }))
+ await run(db, 'versions', 'readwrite', (s) => s.add({ docId: id, at: 1, title: 'ZZ OLD ZZ', json: '{}' }))
+ await run(db, 'versions', 'readwrite', (s) => s.add({ docId: id, at: 2, title: 'ZZ OLD ZZ', json: '{}' }))
+ }
+ db.close()
+ }
+ ok((await countIn('doc-l')).rec && (await countIn('doc-l')).ver === 2, 'setup: an old shell left doc-l plaintext in the legacy database')
+ // unsealed, a purge leaves the legacy database alone, as before
+ await clearRecovery('doc-l'); await clearVersions('doc-l')
+ ok((await countIn('doc-l')).rec && (await countIn('doc-l')).ver === 2, 'unsealed: clearRecovery/clearVersions leave the legacy database alone')
+ setIdentitySeal(kdoc)
+ await clearRecovery('doc-l'); await clearVersions('doc-l')
+ setIdentitySeal(null)
+ const l = await countIn('doc-l'), o = await countIn('doc-other')
+ ok(!l.rec && l.ver === 0, "sealed: the purge deletes doc-l's recovery copy and versions from the legacy database")
+ ok(o.rec && o.ver === 2, "another document's legacy rows survive")
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
process.exit(failures ? 1 : 0)