Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
type: a signature made since the last write survives crash recovery (#662)
nyblneta182f7b8c436
diff --git a/scripts/test-type-autosave.ts b/scripts/test-type-autosave.tsindex 43446f39..c90c8c9d 100644--- a/scripts/test-type-autosave.ts+++ b/scripts/test-type-autosave.ts@@ -8,11 +8,13 @@// module — this rig does not re-test IndexedDB. What is app-specific, and// what this pins instead://-// 1. docContentKey ignores volatile fields (modified, signatures, sync,-// collab, preview, autosave — canon.ts's VOLATILE set) but is sensitive-// to real content, so the boot-time "is this actually different from-// what's on disk" check neither nags on every reload nor stays silent-// when there really is unsaved work.+// 1. docContentKey ignores BOOKKEEPING (modified, preview, autosave) and+// capability (collab, and the sync state inside it), but counts every+// piece of work the file on disk could lack — including a signature, a+// comment and a Snapshot. So the boot-time "is this actually different+// from what's on disk" check neither nags on every reload nor stays+// silent when there really is unsaved work. It is NOT canon.ts's+// signing set: see autosave.ts docContentKey for why those differ.// 2. canSnapshot() — the encryption guard — refuses the moment the kernel's// encryption state goes active, and un-refuses when it clears. This is// the one line responsible for "never write plaintext to IndexedDB@@ -26,6 +28,7 @@ import { setEncryptionPassword } from '../kernel/src/save.ts'import { docContentKey, canSnapshot } from '../type/src/autosave.ts'import { emptyDoc, uid, type TypeDoc } from '../type/src/model.ts'import { Store } from '../type/src/store.ts'+import { gateRestored } from '../type/src/restoregate.ts'configureApp({ appId: 'bento-type-test', appName: 'bento/type (test)', manifestUrl: 'https://example.invalid/m.json' })@@ -40,21 +43,20 @@ const doc = (): TypeDoc => {return d}-H('docContentKey ignores fields that churn without a real edit')+H('docContentKey ignores bookkeeping, which churns without any work done'){const a = doc()const b: TypeDoc = JSON.parse(JSON.stringify(a))- // Touch every volatile field canon.ts's VOLATILE set names, none of which- // is a content edit — a save, a sync round-trip, and re-signing all churn- // these without the author having typed anything.+ // A save stamps `modified`, a sync round-trip rewrites collab's state, and+ // neither is anything the author would want offered back on reload.a.modified = '2026-01-01T00:00:00.000Z'b.modified = '2099-12-31T23:59:59.000Z'- a.signatures = []- b.signatures = [{ alg: 'ES256', pub: 'x', name: 'Alice', content: 'x', prev: '', sig: 'x' }];(a as any).collab = { room: 'r1', key: 'k1' };(b as any).collab = { room: 'r2', key: 'k2', sync: { v: 1 } }+ ;(a as any).preview = '<div>old</div>'+ ;(b as any).preview = '<div>new</div>'ok(docContentKey(a) === docContentKey(b),- 'modified/signatures/collab differ but the content key agrees')+ 'modified/collab/preview differ but the content key agrees')const c = doc()c.body[0].text = 'Payment is due within 45 days.'@@ -111,5 +113,57 @@ H('restoring a recovered snapshot round-trips the document exactly')ok(store.doc.body[0].text === openDoc.body[0].text, 'undo reverts the restore back to what was open before it')}+H('work the file on disk lacks is unsaved work — even when no text changed')+{+ // This rig USED to assert the opposite for signatures ("re-signing churns+ // these without the author having typed anything"), and so certified the+ // bug: the recovery key reused canon.ts's SIGNING set, a signature is+ // rightly outside what it signs, and that same exclusion made it invisible+ // to recovery. The question here is not "did anyone type?" but "does the+ // snapshot hold work the file lacks?" — and a signature is exactly that.+ const base = doc()+ const signed: TypeDoc = JSON.parse(JSON.stringify(base))+ signed.signatures = [{ alg: 'ES256', pub: 'P', name: 'Alice', content: 'C', prev: '', sig: 'S' } as any]+ ok(docContentKey(base) !== docContentKey(signed),+ 'a signature added since the last write changes the content key')++ const commented: TypeDoc = JSON.parse(JSON.stringify(base))+ ;(commented as any).comments = { c1: { id: 'c1', text: 'check clause 4', author: 'Bob', at: 'x', replies: [] } }+ ok(docContentKey(base) !== docContentKey(commented),+ 'a comment added since the last write changes the content key')++ const snapped: TypeDoc = JSON.parse(JSON.stringify(base))+ snapped.revisions = [{ id: 'rev1', at: 'x', label: 'Revision 1', body: JSON.parse(JSON.stringify(base.body)) }]+ ok(docContentKey(base) !== docContentKey(snapped),+ 'a Snapshot taken since the last write changes the content key')+}++H('THE CRASH CASE: sign, crash before the file is written, reload')+{+ // Through the real decision path checkRecovery takes — gateRestored, then+ // the key comparison — minus IndexedDB, which test-autosave.ts already+ // proves against the kernel. The file on disk is `live`: opened, never+ // re-written. The recovery snapshot is what the crashed session last held.+ const live = doc()+ const snapshot: TypeDoc = JSON.parse(JSON.stringify(live))+ snapshot.modified = '2099-01-01T00:00:00.000Z'+ snapshot.signatures = [{ alg: 'ES256', pub: 'P', name: 'Alice', content: 'C', prev: '', sig: 'S' } as any]++ const recovered = gateRestored(JSON.stringify(snapshot), live)+ ok(recovered !== null, 'the snapshot passes the restore gate')+ ok(docContentKey(recovered!) !== docContentKey(live),+ 'the Restore banner is OFFERED — the snapshot holds a signature the file lacks')+ ok(recovered!.signatures.length === 1 && recovered!.signatures[0].name === 'Alice',+ 'and restoring it brings the signature back, not just the banner')+ ok(recovered!.docId === live.docId, 'while identity still comes from the live file, never the snapshot')++ // The control: a snapshot that differs only by bookkeeping must NOT nag.+ const churn: TypeDoc = JSON.parse(JSON.stringify(live))+ churn.modified = '2099-01-01T00:00:00.000Z'+ const quiet = gateRestored(JSON.stringify(churn), live)+ ok(quiet !== null && docContentKey(quiet) === docContentKey(live),+ 'a snapshot differing only in modified offers nothing — no banner on every reload')+}+console.log(`\n${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/type/src/autosave.ts b/type/src/autosave.tsindex 6aac1bcb..377f3322 100644--- a/type/src/autosave.ts+++ b/type/src/autosave.ts@@ -14,13 +14,18 @@//// docContentKey stays HERE, not in the kernel, for the same reason slides// keeps its own: "what counts as content" is a per-app model question the-// kernel must never see. UNLIKE slides, bento/type already has a canonical,-// volatile-field-excluding serialization built for the signature chain —-// canon.ts's `canonicalize`, which drops exactly the fields that churn-// without a real edit (modified, sync, collab, preview, signatures,-// autosave — see canon.ts's VOLATILE set). Reusing it means there is only-// ONE notion of "same content" in this app, not two that could quietly-// drift apart.+// kernel must never see. It reuses canon.ts's `canonicalize` for the+// SERIALIZATION — canonical key order, NFC, volatile fields dropped at every+// level — but NOT canon.ts's VOLATILE set, and that distinction is the whole+// point of `NOT_EDIT` below.+//+// This file used to reuse VOLATILE too, on the argument that "one notion of+// same content" beats two that could drift. But they are not one notion.+// VOLATILE answers "what may a SIGNATURE not cover?", and a signature must+// exclude itself. NOT_EDIT answers "what may the recovery snapshot hold that+// is NOT work the file on disk lacks?" — and a signature is work. Sharing the+// set made every signature invisible to recovery: sign, crash before anything+// wrote the file, reload, and the snapshot holding it was silently discarded.//// Feature registration: this module is wired through the feature registry// (features.ts registerReady), not main.ts — see registry.ts for the one@@ -43,17 +48,30 @@ export { putRecovery, getRecovery, clearRecovery, addVersion, listVersions, prunexport type { Snapshot };/**- * The content that actually matters for "did this change" — everything- * except the volatile fields canon.ts already knows to exclude (see its- * VOLATILE set: modified, sync, collab, preview, signatures, autosave).+ * What a recovery snapshot may differ in WITHOUT holding any unsaved work.+ *+ * Bookkeeping — a save stamps `modified`, a save rewrites the cached+ * `preview`, autosave tags its own `autosave`. These three are the set kernel+ * agreed to use for a shared NOT_EDIT when it adds a shared docContentKey+ * (not on main as of this commit), so type lines up if it ever moves onto that+ * helper. Capability — `collab`, and the CRDT `sync` state+ * that lives inside it — churns on every round-trip and is never something to+ * offer back.*- * Reusing `canonicalize` rather than hand-picking fields (as slides does)- * means a new content field added to TypeDoc later is covered automatically- * — the same fail-safe reasoning canon.ts documents for the signature chain- * applies here for free.+ * Deliberately NOT here: `signatures`, `comments`, `revisions`. Each is work an+ * author did that the file on disk can lack, so each must trip the banner.+ * This is a denylist on purpose, for the reason canon.ts gives for its own: a+ * field added to TypeDoc later is counted as work by default, and the failure+ * that default buys is an extra Restore banner rather than lost work.*/+export const NOT_EDIT: ReadonlySet<string> = new Set([+ 'modified', 'preview', 'autosave', // bookkeeping+ 'collab', 'sync', // capability+]);++/** The content that matters for "is the snapshot different from the file". */export function docContentKey(doc: TypeDoc): string {- return canonicalize(doc);+ return canonicalize(doc, { volatile: NOT_EDIT });}/**diff --git a/type/src/canon.ts b/type/src/canon.tsindex 5c30e835..dc105ec2 100644--- a/type/src/canon.ts+++ b/type/src/canon.ts@@ -30,7 +30,17 @@ import type { Signature } from './model.ts';export interface ChainEntry { ok: boolean; why: string | null; linked: boolean; name: string }export interface ChainResult { ok: boolean; entries: ChainEntry[] }-/** Fields that never enter a signature. Everything else is signed. */+/**+ * Fields that never enter a signature. Everything else is signed — including+ * `revisions`, deliberately: signatures cover content AND history, so trimming+ * history on a signed document is a re-sign by the signer, never a silent fold.+ *+ * This set answers ONE question — what may a signature not cover — and must+ * not be reused to answer "what counts as unsaved work". A signature excludes+ * itself, but losing a signature on crash recovery is still lost work. The+ * recovery key has its own set (autosave.ts NOT_EDIT); reusing this one there+ * is exactly how signatures became invisible to recovery.+ */export const VOLATILE = new Set(['modified', // touched by every save'sync', // CRDT state, per-replica@@ -94,7 +104,8 @@ function str(s: string): string {* insertion order, which is neither valid JSON nor deterministic. That is* refused rather than serialized.*/-export function canonicalize(value: unknown, { volatile = VOLATILE } = {}): string {+export function canonicalize(value: unknown,+ { volatile = VOLATILE }: { volatile?: ReadonlySet<string> } = {}): string {const go = (v: unknown): string => {if (v === null) return 'null';if (typeof v === 'boolean') return v ? 'true' : 'false';