Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
type: signatures sync one by one, each verified on its own (ruling 7, part A) (#788)
nyblnet9112ab5278fe
diff --git a/scripts/test-sync-type.ts b/scripts/test-sync-type.tsindex be4b026a..ee048209 100644--- a/scripts/test-sync-type.ts+++ b/scripts/test-sync-type.ts@@ -274,7 +274,7 @@ console.log('\n=== what that looks like on one paragraph ===');page: { width: 816, height: 1056, marginX: 104, marginTop: 104, marginBottom: 104 },body: [{ id: 'p1', kind: 'para', text: TEXT,marks: [{ t: 'b', from: TEXT.indexOf(TERM), to: TEXT.indexOf(TERM) + TERM.length }] } as Block],- footnotes: {}, revisions: [], signatures: [],+ footnotes: {}, revisions: [], signatures: {},} as unknown as Doc);const A = new Replica('alice', mk());@@ -329,7 +329,7 @@ console.log('\n=== what that looks like on one paragraph ===');.filter(o => o.op === 'set' && !o.el && !o.sl).map(o => o.k);const COMMENT = { c1: { id: 'c1', text: 'check clause 4', author: 'Bob', at: 'x', replies: [],anchor: { block: 'p1', from: 0, to: 7 } } };- const SIG = [{ alg: 'ES256', pub: 'P', name: 'Alice', content: 'C', prev: '', sig: 'S' }];+ const SIG = { k1: { alg: 'ES256', pub: 'P', name: 'Alice', content: 'C', prev: '', sig: 'S' } };H('with the map bound, what a type replica emits');{@@ -342,12 +342,12 @@ console.log('\n=== what that looks like on one paragraph ===');const ops = A.diff(before as never, dA as never, { text: true });const keys = docKeys(ops);ok(keys.includes('comments'), 'comments IS emitted — synced to the room (ruling 2026-10-15)');- ok(keys.includes('signatures'), 'signatures IS emitted — as before binding');+ ok(keys.some(k => k.startsWith('signatures.')), 'signatures IS emitted — each one as its own key (ruling 7)');ok(!keys.includes('revisions'), 'revisions is NOT emitted — each replica keeps its own timeline');ok(!keys.some(k => k === 'mystery' || k.startsWith('mystery.')),'an UNDECLARED key is NOT emitted — the allowlist, not the denylist');const hist = ['revisions', 'comments', 'signatures'];- ok(keys.filter(k => hist.includes(k.split('.')[0])).every(k => k === 'comments' || k === 'signatures'),+ ok(keys.filter(k => hist.includes(k.split('.')[0])).every(k => k === 'comments' || k.startsWith('signatures.')),'no history key other than comments and signatures leaves this replica');B.apply(dB as never, ops);ok(JSON.stringify(dB.comments) === JSON.stringify(COMMENT), 'a bound peer receives the comment');@@ -383,6 +383,49 @@ console.log('\n=== what that looks like on one paragraph ===');ok(dO2.mystery === 'from old', 'the bound peer\'s silence on an undeclared key is not a delete');ok(JSON.stringify(dO2.comments) === JSON.stringify(COMMENT), 'and the comment survives the round trip');}+ H('RULING 7: concurrent signers both survive, on both replicas (row 1)');+ {+ // Two real engines, one document, each signing at the same moment. With+ // the old whole-list register one signature was silently lost (measured:+ // both replicas held only Bob's). Keyed by SigId, each is its own key.+ const A = new TypeSync('a'); const B = new TypeSync('b');+ const dA = mk(); const dB = clone(dA); A.adopt(dA as never); B.adopt(dB as never);+ const bA = clone(dA), bB = clone(dB);+ const sa = { alg: 'ES256', pub: 'PA', name: 'Alice', content: 'C', history: 'H', prev: '', sig: 'SA' };+ const sb = { alg: 'ES256', pub: 'PB', name: 'Bob', content: 'C', history: 'H', prev: '', sig: 'SB' };+ (dA.signatures as Record<string, unknown>).idAlice = sa;+ (dB.signatures as Record<string, unknown>).idBob = sb;+ const oA = A.diff(bA as never, dA as never, { text: true }), oB = B.diff(bB as never, dB as never, { text: true });+ A.apply(dA as never, oB); B.apply(dB as never, oA);+ const names = (d: Record<string, unknown>) => Object.values(d.signatures as object).map((x: any) => x.name).sort().join('+');+ ok(names(dA) === 'Alice+Bob' && names(dB) === 'Alice+Bob',+ `both signatures survive on BOTH replicas (alice holds ${names(dA)}, bob holds ${names(dB)})`);+ ok(['idAlice', 'idBob'].every(k => JSON.stringify((dA.signatures as any)[k]) === JSON.stringify(k === 'idAlice' ? sa : sb)+ && JSON.stringify((dB.signatures as any)[k]) === JSON.stringify(k === 'idAlice' ? sa : sb)),+ 'each under its own key, byte for byte, on both');+ }++ H('RULING 7: a SigId arriving as a remote map sub-key is inert when it is a prototype or dotted name (row 9)');+ {+ const A = new TypeSync('a'); const B = new TypeSync('b');+ const dA = mk(); const dB = clone(dA); A.adopt(dA as never); B.adopt(dB as never);+ const bA = clone(dA);+ const sigs = dA.signatures as Record<string, unknown>;+ const entry = { alg: 'ES256', pub: 'P', name: 'X', content: 'C', history: 'H', prev: '', sig: 'S' };+ Object.defineProperty(sigs, '__proto__', { value: entry, enumerable: true, configurable: true, writable: true });+ sigs['constructor'] = entry;+ sigs['a.b'] = entry;+ sigs['ok-id'] = entry;+ const ops = A.diff(bA as never, dA as never, { text: true });+ B.apply(dB as never, ops);+ const got = dB.signatures as Record<string, unknown>;+ ok(Object.getPrototypeOf(got) === Object.prototype || Object.getPrototypeOf(got) === null,+ "a '__proto__' SigId never swaps the receiving map's prototype");+ ok(!Object.hasOwn(got, '__proto__') && !Object.hasOwn(got, 'constructor'), 'prototype names are not installed as signatures');+ ok(!Object.hasOwn(got, 'a') && !(got as any).a?.b, "a dotted SigId is never split into a nested path");+ ok(Object.hasOwn(got, 'ok-id'), 'while an ordinary SigId arrives as one key');+ }+void DOC_NODE;}diff --git a/scripts/test-type-autosave.ts b/scripts/test-type-autosave.tsindex f7c0d77f..8a7cc6c2 100644--- a/scripts/test-type-autosave.ts+++ b/scripts/test-type-autosave.ts@@ -28,7 +28,9 @@ import { fileURLToPath } from 'node:url'import { configureApp } from '../kernel/src/app.ts'import { setEncryptionPassword, setIdentitySeal, isBodySealed } from '../kernel/src/save.ts'import { docContentKey, canSnapshot, recoveryBanner } from '../type/src/autosave.ts'-import { sign, newKey, verifyChain, newHistorySalt } from '../type/src/canon.ts'+import { sign, newKey, verifyAll, sigId, newHistorySalt } from '../type/src/canon.ts'+const one = (d: { docId: string }, x: any) => ({ [sigId(d.docId, x)]: x })+const vals = (m: Record<string, any>) => Object.values(m ?? {})import { RESTORE_RULES } from '../type/src/restorerules.ts'import { validateRestoreRules } from '../kernel/src/docfields.ts'import { emptyDoc, uid, type TypeDoc } from '../type/src/model.ts'@@ -133,7 +135,7 @@ H('work the file on disk lacks is unsaved work — even when no text changed')// 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]+ signed.signatures = { k1: { 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')@@ -157,13 +159,13 @@ H('THE CRASH CASE: sign, crash before the file is written, reload')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]+ snapshot.signatures = { k1: { 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',+ ok(vals(recovered!.signatures).length === 1 && vals(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')@@ -208,8 +210,8 @@ H('a recovery snapshot with NO signatures never pairs its revisions with the livconst live = doc()live.revisions = [{ id: 'r1', at: '2026-01-01T00:00:00.000Z', label: 'Revision 1',body: JSON.parse(JSON.stringify(live.body)) }]- live.signatures = [{ alg: 'ES256', pub: 'P', name: 'Bob', content: 'C', prev: '', sig: 'S' } as any]- ok(live.signatures.length === 1 && live.signatures[0].name === 'Bob',+ live.signatures = { k1: { alg: 'ES256', pub: 'P', name: 'Bob', content: 'C', prev: '', sig: 'S' } as any }+ ok(vals(live.signatures).length === 1 && vals(live.signatures)[0].name === 'Bob','the FILE really is signed (Bob) — so "no signatures after restore" is a result, not a fixture')// The crashed session held a NEWER revision and no signatures at all — and@@ -226,9 +228,9 @@ H('a recovery snapshot with NO signatures never pairs its revisions with the livstore.replace(gated!)ok(store.doc.revisions.length === 2 && store.doc.revisions[1].id === 'r2','the restore takes the snapshot\'s revisions')- ok(Array.isArray(store.doc.signatures) && store.doc.signatures.length === 0,+ ok(store.doc.signatures !== null && typeof store.doc.signatures === 'object' && vals(store.doc.signatures).length === 0,'and NO signatures — the snapshot\'s unsigned state, not an absent field')- ok(!JSON.stringify(store.doc.signatures ?? []).includes('Bob'),+ ok(!JSON.stringify(store.doc.signatures ?? {}).includes('Bob'),'the file\'s signatures are never paired with the snapshot\'s revisions')}@@ -284,18 +286,18 @@ H('crash recovery brings content AND history back TOGETHER (recover)')const k = await newKey()const file = doc()file.revisions = [rev('r1', 'a'), rev('r2', 'b'), rev('r3', 'c')]- file.signatures = [await sign(file, k, { name: 'Alice' })]+ file.signatures = one(file, await sign(file, k, { name: 'Alice' }))const snap = JSON.parse(JSON.stringify(file)) as TypeDocsnap.revisions = [rev('r3', 'c')] // trimmed…- snap.signatures = [await sign({ ...snap, signatures: [] }, k, { name: 'Alice' })] // …and re-signed+ snap.signatures = one(snap, await sign({ ...snap, signatures: {} }, k, { name: 'Alice' })) // …and re-signedconst store = new Store(JSON.parse(JSON.stringify(file)))const gated = gateRestored(JSON.stringify(snap), store.doc)!store.restore(gated, 'recover')ok(store.doc.revisions.map(r => r.id).join() === 'r3', 'the TRIMMED list comes back from the snapshot')- ok(store.doc.signatures.length === 1 && store.doc.signatures[0].sig === snap.signatures[0].sig,+ ok(vals(store.doc.signatures).length === 1 && vals(store.doc.signatures)[0].sig === vals(snap.signatures)[0].sig,'with the signature made over it — revisions and signatures are never split')- const v = await verifyChain(store.doc, store.doc.signatures)+ const v = await verifyAll(store.doc, store.doc.signatures)ok(v.ok && v.entries[0].ok, 'so the re-signed signature VERIFIES after recovery')ok(store.doc.docId === file.docId, 'identity still comes from the live file')ok(store.undo() && store.doc.revisions.map(r => r.id).join() === 'r3',@@ -392,9 +394,9 @@ H('restoring an older version of a SIGNED document reports changed, and does notconst older = JSON.parse(JSON.stringify(store.doc)) as TypeDocstore.commit(d => { d.body[0].text = 'Payment is due within 60 days.' })const signed = await sign(store.doc, k, { name: 'Alice' })- store.commit(d => { d.signatures.push(signed) })+ store.commit(d => { d.signatures[sigId(d.docId, signed)] = signed })store.restore(older, 'back')- const v = await verifyChain(store.doc, store.doc.signatures)+ const v = await verifyAll(store.doc, store.doc.signatures)ok(v.entries.length === 1 && !v.entries[0].ok,'the live signature is kept and honestly reads changed — the content it signed is not what is open')}@@ -444,12 +446,12 @@ H('Sign is not undoable (ruling 7)')const store = new Store(doc())store.commit(d => { d.body[0].text = 'Payment is due within 60 days.' })const signed = await sign(store.doc, k, { name: 'Alice' })- store.commit(d => { d.signatures.push(signed) }, { undoable: false })+ store.commit(d => { d.signatures[sigId(d.docId, signed)] = signed }, { undoable: false })ok(store.undo(), 'undo takes back the edit made BEFORE signing')- ok(store.doc.signatures.length === 1 && store.doc.signatures[0].sig === signed.sig,+ ok(vals(store.doc.signatures).length === 1 && vals(store.doc.signatures)[0].sig === signed.sig,'and the signature stays — ⌘Z never removes one')const main = readFileSync(fileURLToPath(new URL('../type/src/main.ts', import.meta.url)), 'utf8')- ok(/store\.commit\(d => \{ d\.signatures\.push\(entry\); \}, \{ undoable: false \}\)/.test(main),+ ok(/store\.commit\(d => \{ d\.signatures\[id\] = entry; \}, \{ undoable: false \}\)/.test(main),'the Sign button really commits with undoable: false')ok(/store\.commit\(d => \{ d\.historySalt = salt; \}, \{ undoable: false \}\)/.test(main),'and so does minting the history salt')diff --git a/scripts/test-type-canon.ts b/scripts/test-type-canon.tsindex 964fb203..933b2984 100644--- a/scripts/test-type-canon.ts+++ b/scripts/test-type-canon.ts@@ -30,7 +30,7 @@// where a false "✓ valid" would actually mislead someone.import {- canonicalize, digest, sign, verify, verifyChain, newKey, exportPub, VOLATILE,+ canonicalize, digest, sign, verify, verifyAll, sigId, signatureOrder, latestSignature, isLowS, newKey, exportPub, VOLATILE,SIGNED_EXCLUDE, historyCommitment, newHistorySalt, historyDisplay,} from '../type/src/canon.ts';import { readFileSync } from 'node:fs';@@ -55,7 +55,7 @@ const SALT = newHistorySalt();const doc = (over: Record<string, unknown> = {}) => ({format: 'bento/type', version: 1, docId: 'doc-1', title: 'Agreement',body: [{ id: 'p1', kind: 'para', text: 'The fee is due within 30 days.' }],- footnotes: {}, revisions: [], signatures: [], historySalt: SALT, ...over,+ footnotes: {}, revisions: [], signatures: {}, historySalt: SALT, ...over,});// ────────────────────────────────────────────────────────────── 1. determinism@@ -80,7 +80,7 @@ H('determinism — insertion order must not change one byte');'and reordering an array therefore changes the document');// The real thing: two hand-built copies of the same document, keys shuffled.- const shuffled = { title: 'Agreement', docId: 'doc-1', signatures: [], revisions: [],+ const shuffled = { title: 'Agreement', docId: 'doc-1', signatures: {}, revisions: [],footnotes: {}, body: [{ text: 'The fee is due within 30 days.', kind: 'para', id: 'p1' }],version: 1, format: 'bento/type' };ok(await digest(doc()) === await digest(shuffled),@@ -285,74 +285,177 @@ H('a signature verifies its own document and nothing else');'RELABELLING a valid signature breaks it — the name is beside the ✓ and must be covered');}-// ─────────────────────────────────────────────────────────────────── 8. the chain-H('the chain — order without a trusted clock');+// ───────────────────────────────────────────── 8. each signature on its own (ruling 7)+// Signatures are keyed by SigId and verified independently: `prev` is ordering+// information, and a fork or a missing predecessor never makes one invalid.+const keyed = (d: { docId: string }, ...sigs: Signature[]): Record<string, Signature> =>+ Object.fromEntries(sigs.map(x => [sigId(d.docId, x), x]));+const idOf = (d: { docId: string }, x: Signature) => sigId(d.docId, x);++H('ruling 7: each signature stands on its own; `prev` is ordering');{const d = doc();const [ka, kb, kc] = [await newKey(), await newKey(), await newKey()];const a = await sign(d, ka, { name: 'Alice' });- const b = await sign(d, kb, { name: 'Bob', prev: a });- const c = await sign(d, kc, { name: 'Carol', prev: b });-- const good = await verifyChain(d, [a, b, c]);- ok(good.ok, 'three signatures in sequence verify');- ok(good.entries.length === 3 && good.entries.every(e => e.ok && e.linked && e.why === null),- 'and every entry is individually valid and linked');- ok(good.entries.map(e => e.name).join(',') === 'Alice,Bob,Carol',- 'the entries carry the names the panel renders, in order');- ok(b.prev === a.sig && c.prev === b.sig, 'each signature commits to the one before it');-- const swapped = await verifyChain(d, [a, c, b]);- ok(!swapped.ok, 'reordering the chain fails');- ok(swapped.entries[0].linked && !swapped.entries[1].linked,- 'and `linked` points at WHERE it broke, which is what the panel shows');- ok(swapped.entries.every(e => e.ok),- 'while every signature is still individually valid — only the ORDER is wrong, '- + 'so "not linked" and "invalid" are genuinely different messages');-- const dropped = await verifyChain(d, [a, c]);- ok(!dropped.ok && dropped.entries[0].linked && !dropped.entries[1].linked,- 'removing a middle signature is detectable — c no longer follows what it committed to');-- const truncated = await verifyChain(d, [a, b]);- ok(truncated.ok, 'truncating the END is NOT detectable — a chain proves order, not completeness');-- ok(!(await verifyChain(d, [b, c])).entries[0].linked,- 'and dropping the FIRST signature is detectable, because b commits to a');-- const forged = await verifyChain(d, [a, { ...b, name: 'Mallory' }, c]);- ok(!forged.ok && !forged.entries[1].ok, 'relabelling a signature inside a chain is caught');-- ok((await verifyChain(d, [])).ok && (await verifyChain(d, [])).entries.length === 0,- 'an empty chain is vacuously ok — the panel must not render it as "verified" '- + '(it early-returns on `!sigs.length`, which is what makes this safe)');+ const b = await sign(d, kb, { name: 'Bob', prev: idOf(d, a) });+ const c = await sign(d, kc, { name: 'Carol', prev: idOf(d, b) });+ const all = await verifyAll(d, keyed(d, a, b, c));+ ok(all.ok && all.entries.every(e => e.ok && e.why === null), 'three signatures each verify');+ ok(all.entries.map(e => e.sig.name).join(',') === 'Alice,Bob,Carol', 'shown in `prev` order, whatever the map order');+ ok(b.prev === idOf(d, a) && c.prev === idOf(d, b), '`prev` holds the SigId of the signature followed');+ ok(all.entries[1].after === idOf(d, a) && all.entries[0].after === null, 'and each entry says which one it follows');+ const reversed = await verifyAll(d, Object.fromEntries(Object.entries(keyed(d, a, b, c)).reverse()));+ ok(reversed.entries.map(e => e.sig.name).join(',') === 'Alice,Bob,Carol', 'the order does not depend on key order in the file');++ // ROW 7: a fork — two signatures following the same one — is never invalid+ const c2 = await sign(d, kc, { name: 'Carol', prev: idOf(d, a) });+ const fork = await verifyAll(d, keyed(d, a, b, c2));+ ok(fork.ok && fork.entries.every(e => e.ok), 'a fork (two signatures after the same one): every signature valid');+ ok(fork.entries[0].sig.name === 'Alice' && fork.entries.filter(e => e.after === idOf(d, a)).length === 2,+ 'both siblings shown after the one they follow');+ // a signature whose predecessor this copy does not hold is still valid+ const orphan = await verifyAll(d, keyed(d, c));+ ok(orphan.ok && orphan.entries[0].after === null, 'a signature whose `prev` is not on this copy is still valid, just first');+ ok(latestSignature(keyed(d, a, b, c)) === idOf(d, c), 'a new signature follows the latest in display order');+ ok(latestSignature({}) === null, 'and the first follows none');++ const forged = await verifyAll(d, keyed(d, a, { ...b, name: 'Mallory' }));+ ok(!forged.entries.find(e => e.sig.name === 'Mallory')!.ok, 'relabelling a signature is caught');+ ok((await verifyAll(d, {})).ok && (await verifyAll(d, {})).entries.length === 0,+ 'no signatures is vacuously ok — the panel early-returns on an empty map');}-H('signing again after an edit — the chain reports the past honestly');+H('ruling 7: SigId is derived from what was signed (row 8)');{- const v1 = doc();- const ka = await newKey(), kb = await newKey();- const a = await sign(v1, ka, { name: 'Alice' });+ const d = doc();+ const k = await newKey();+ const a = await sign(d, k, { name: 'Alice' });+ const id = idOf(d, a);+ ok(/^[A-Za-z0-9_-]{43}$/.test(id), 'a SigId is a 256-bit base64url digest');+ const again = await sign(d, k, { name: 'Alice' });+ ok(again.sig !== a.sig && idOf(d, again) === id,+ 'the same act of signing (same key, same text) has the same id whatever bytes ECDSA drew');+ ok(idOf(d, { ...a, name: 'Alicia' }) !== id && idOf({ docId: 'doc-2' }, a) !== id,+ 'a different name, or a different document, is a different id');+ const misfiled = await verifyAll(d, { ['A'.repeat(43)]: a });+ ok(!misfiled.ok && misfiled.entries[0].why === 'bad-id', 'an entry under a key its own fields do not produce is INVALID');+ const both = await verifyAll(d, { [id]: a, [idOf(d, again)]: again });+ ok(both.entries.length === 1, 'the same signature delivered twice is ONE key');++ // TWO SIGNERS, IDENTICAL TEXT. The signed text holds no key, so two people+ // co-signing the same version under the same (or an empty) name sign the very+ // same bytes. The key is what tells them apart: without it in the SigId one+ // would overwrite the other in the map.+ const { parseDoc } = await import('../type/src/model.ts');+ const k1 = await newKey(), k2 = await newKey();+ for (const nm of ['', 'Same Name']) {+ const s1 = await sign(d, k1, { name: nm }), s2 = await sign(d, k2, { name: nm });+ ok(s1.content === s2.content && s1.history === s2.history && s1.prev === s2.prev && s1.name === s2.name && s1.pub !== s2.pub,+ ` (two keys signed identical text, name ${JSON.stringify(nm)})`);+ ok(idOf(d, s1) !== idOf(d, s2), `two signers of identical text get DISTINCT SigIds (name ${JSON.stringify(nm)})`);+ const merged = await verifyAll(d, keyed(d, s1, s2));+ ok(merged.entries.length === 2 && merged.ok, 'and both survive side by side, and both verify');+ const conv = parseDoc(JSON.stringify({ ...d, signatures: [s1, s2] }));+ ok(conv.ok && Object.keys(conv.doc.signatures).length === 2, 'an old array holding both converts to two keys, not one');+ }+}- const v2 = doc({ body: [{ id: 'p1', kind: 'para', text: 'The fee is due within 60 days.' }],- signatures: [a] });- const b = await sign(v2, kb, { name: 'Bob', prev: a });- const chain = [a, b];+H('ruling 7: old files convert on open (row 10)');+{+ const { parseDoc } = await import('../type/src/model.ts');+ // a document as a real file holds it (parseDoc fills defaults such as the+ // page, which is content — so sign the parsed form, as Sign does)+ const p0 = parseDoc(JSON.stringify(doc()));+ if (!p0.ok) throw new Error('fixture did not parse');+ const d = p0.doc;+ const ka = await newKey(), kb = await newKey();+ const a = await sign(d, ka, { name: 'Alice' });+ // made before ids: `prev` holds the earlier signature's BYTES+ const b = await sign(d, kb, { name: 'Bob', prev: a.sig });+ const old = { ...d, signatures: [a, b, { junk: true }, a] }; // an ARRAY, a junk entry, a duplicate+ const p1 = parseDoc(JSON.stringify(old));+ ok(p1.ok, 'an array-shaped file opens');+ const m = p1.ok ? p1.doc.signatures : {};+ ok(!Array.isArray(m) && Object.keys(m).sort().join() === [idOf(d, a), idOf(d, b)].sort().join(),+ 'and converts to the map, each keyed by its derived SigId (junk dropped, the duplicate one key)');+ const res = await verifyAll(p1.ok ? p1.doc : d, m);+ ok(res.ok && res.entries.map(e => e.sig.name).join(',') === 'Alice,Bob',+ 'the converted signatures verify, in order — a byte-valued `prev` still orders them');+ ok(res.entries[1].after === idOf(d, a), 'and the old byte link resolves to the earlier SigId');+ const absent = { ...d } as Record<string, unknown>; delete absent.signatures;+ const p2 = parseDoc(JSON.stringify(absent));+ ok(p2.ok && !('length' in (p2.doc.signatures as object)) && Object.keys(p2.doc.signatures).length === 0,+ 'a file with NO signatures key opens, with an empty map (the absent-field case)');+ const asMap = parseDoc(JSON.stringify({ ...d, signatures: { [idOf(d, a)]: a, bogus: 'not an object' } }));+ ok(asMap.ok && Object.keys(asMap.doc.signatures).join() === idOf(d, a), 'a map keeps its object entries and drops anything else');+}- const res = await verifyChain(v2, chain);- ok(!res.ok, 'the chain as a whole no longer verifies, because the text moved under Alice');- ok(!res.entries[0].ok && res.entries[0].why === 'content-changed',- "Alice's signature honestly reports that this is not the text she signed");- ok(res.entries[1].ok && res.entries[1].linked,- "and Bob's is valid and linked — he signed the document as it now stands");- ok(res.entries[0].linked, 'Alice is still LINKED — the order is intact, the content is not');+H('ruling 7: LOW-S (row 13)');+{+ const d = doc();+ const k = await newKey();+ const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;+ const b64 = (u: Uint8Array) => Buffer.from(u).toString('base64url');+ const raw = (x: Signature) => new Uint8Array(Buffer.from(x.sig, 'base64url'));+ let high = 0;+ for (let i = 0; i < 48; i++) if (!isLowS(raw(await sign(d, k, { name: 'Alice' })))) high++;+ ok(high === 0, `sign() never emits a high s, sampled over 48 signatures (${high} high)`);+ // its malleated twin: (r, n − s), a second VALID ECDSA signature over the same text+ const a = await sign(d, k, { name: 'Alice' });+ const r = raw(a), s = BigInt('0x' + Buffer.from(r.slice(32)).toString('hex'));+ const twin = new Uint8Array(64); twin.set(r.slice(0, 32));+ twin.set(Buffer.from((N - s).toString(16).padStart(64, '0'), 'hex'), 32);+ const pub = await crypto.subtle.importKey('raw', Buffer.from(a.pub, 'base64url'), { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);+ const text = new TextEncoder().encode(`bento-type-sig.v2|"${d.docId}"|${a.content}|${a.history}||"Alice"`);+ ok(await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, pub, twin, text),+ 'control: WebCrypto DOES accept the high-S twin, so the rejection below is ours');+ const hi = { ...a, sig: b64(twin) };+ ok(!(await verify(d, hi)).ok, 'verify REJECTS the high-S twin');+ ok(idOf(d, hi) === idOf(d, a), 'and the twin lands on the SAME SigId, so it can never pose as a new signature');+}- ok((await verifyChain(v1, chain)).entries[0].ok,- 'and against the ORIGINAL text Alice verifies again — nothing was destroyed');+H('the synchronous SHA-256 behind SigId (sha256.ts)');+{+ const { sha256 } = await import('../type/src/sha256.ts');+ const hex = (u: Uint8Array) => Buffer.from(u).toString('hex');+ const te = new TextEncoder();+ ok(hex(sha256(te.encode('abc'))) === 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', 'FIPS 180-4 vector "abc"');+ ok(hex(sha256(new Uint8Array(0))) === 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'and the empty string');+ ok(hex(sha256(te.encode('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'))) === '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1',+ 'and the 448-bit two-block vector');+ let bad = 0;+ for (let n = 0; n <= 200; n++) {+ const data = crypto.getRandomValues(new Uint8Array(n));+ if (hex(sha256(data)) !== hex(new Uint8Array(await crypto.subtle.digest('SHA-256', data)))) bad++;+ }+ ok(bad === 0, `matches WebCrypto on random input of every length 0..200 (${bad} mismatches)`);+ let big = 0;+ for (const n of [4095, 4096, 4097, 65535, 65536, 1 << 20]) {+ const data = crypto.getRandomValues(new Uint8Array(Math.min(n, 65536)));+ const full = new Uint8Array(n); for (let i = 0; i < n; i += data.length) full.set(data.subarray(0, Math.min(data.length, n - i)), i);+ if (hex(sha256(full)) !== hex(new Uint8Array(await crypto.subtle.digest('SHA-256', full)))) big++;+ }+ ok(big === 0, `and on large inputs around block and buffer boundaries, up to 1 MiB (${big} mismatches)`);+ const backing = crypto.getRandomValues(new Uint8Array(500));+ const view = backing.subarray(13, 13 + 333); // an offset VIEW into a bigger buffer+ ok(hex(sha256(view)) === hex(new Uint8Array(await crypto.subtle.digest('SHA-256', view.slice()))),+ 'and on a subarray view at an offset (it hashes the view, not the whole buffer)');+}+H('signing again after an edit — the past is reported honestly');+{+ const v1 = doc();+ const ka = await newKey(), kb = await newKey();+ const a = await sign(v1, ka, { name: 'Alice' });+ const v2 = doc({ body: [{ id: 'p1', kind: 'para', text: 'The fee is due within 60 days.' }], signatures: keyed(v1, a) });+ const b = await sign(v2, kb, { name: 'Bob', prev: idOf(v2, a) });+ const res = await verifyAll(v2, keyed(v2, a, b));+ ok(!res.ok, 'the set as a whole no longer verifies, because the text moved under Alice');+ ok(!res.entries[0].ok && res.entries[0].why === 'content-changed', "Alice's signature honestly reports that this is not the text she signed");+ ok(res.entries[1].ok && res.entries[1].after === idOf(v2, a), "and Bob's is valid, shown after Alice's");+ ok((await verifyAll(v1, keyed(v1, a))).entries[0].ok, 'and against the ORIGINAL text Alice verifies again — nothing was destroyed');ok(await digest(v2) === b.content,- 'signing digests the document INCLUDING the signature it chains from, because '- + '`signatures` is volatile and never enters the digest');+ 'signing digests the document INCLUDING the signature it follows, because `signatures` never enters the digest');}// ════════════════════════════════════════════════════════════════════ v2@@ -449,9 +552,9 @@ H('v2: a re-sign after trimming the history');const full = doc({ revisions: [r1, r2] });const ka = await newKey(), kb = await newKey();const before = await sign(full, ka, { name: 'Alice' });- const trimmed = doc({ revisions: [r2], signatures: [before] });- const after = await sign(trimmed, kb, { name: 'Bob', prev: before });- const res = await verifyChain(trimmed, [before, after]);+ const trimmed = doc({ revisions: [r2], signatures: keyed(full, before) });+ const after = await sign(trimmed, kb, { name: 'Bob', prev: idOf(trimmed, before) });+ const res = await verifyAll(trimmed, keyed(trimmed, before, after));ok(res.entries[1].ok && res.entries[1].history === 'matches', 'the re-sign attests the TRIMMED history');ok(res.entries[0].ok && res.entries[0].history === 'changed','and the pre-trim signature still attests the content but reports its history CHANGED — 'diff --git a/scripts/test-type-share.ts b/scripts/test-type-share.tsindex 32d7d63e..54e97f5b 100644--- a/scripts/test-type-share.ts+++ b/scripts/test-type-share.ts@@ -30,7 +30,7 @@ const { emptyDoc, parseDoc, docForExport } = await import('../type/src/model.ts'const { mintCollab } = await import('../kernel/src/sync/online.ts')const { mergeDoc } = await import('../type/src/merge.ts')const { newThread, writeThreads } = await import('../type/src/comments.ts')-const { sign, newKey, newHistorySalt, verifyChain } = await import('../type/src/canon.ts')+const { sign, newKey, newHistorySalt, verifyAll, sigId } = await import('../type/src/canon.ts')const { TYPE_FIELDS, HISTORY_CLASS, keepLiveHistory } = await import('../type/src/docclass.ts')const { Store } = await import('../type/src/store.ts')import type { TypeDoc } from '../type/src/model.ts'@@ -236,7 +236,7 @@ async function full(): Promise<{ doc: TypeDoc; ownerPriv: string }> {body: [{ id: 'p1', kind: 'para', text: DRAFT }] }]writeThreads(d, [newThread(d.body[0], 0, 7, 'Bob', NOTE)])d.historySalt = newHistorySalt() // the first signature mints it, in the document- d.signatures = [await sign(d, await newKey(), { name: 'Alice', prev: null })]+ { const sg = await sign(d, await newKey(), { name: 'Alice', prev: null }); d.signatures = { [sigId(d.docId, sg)]: sg } };(d as Record<string, unknown>).futureField = FUTUREconst r = parseDoc(JSON.stringify(d))if (!r.ok) throw new Error('FULL fixture did not parse')@@ -261,7 +261,7 @@ H('the FULL fixture really carries everything a leak would show')const F = await full()ok(has(F.doc, DRAFT), 'the source holds a whole earlier draft in revisions')ok(has(F.doc, NOTE), 'the source holds an internal comment thread (it survived parseDoc)')-ok(F.doc.signatures.length === 1, 'the source holds a real signature')+ok(Object.keys(F.doc.signatures).length === 1, 'the source holds a real signature')ok(typeof F.doc.historySalt === 'string' && F.doc.historySalt.length === 22,'and the history salt that signature committed under (it survived parseDoc)')ok(has(F.doc, FUTURE), 'the source holds a field this build does not declare')@@ -274,11 +274,11 @@ H('a VIEW-ONLY copy carries no history (tier reader)')ok(!has(r, NOTE), 'no internal comment')// Signatures travel WITH a view-only copy now (canon.ts v2): each signs the// content plus a salted commitment to the history, so the copy — no drafts,- // no salt — verifies them. Run through the real verifyChain on the COPY.- ok(r.signatures?.length === 1, 'the signature travels with the view-only copy')+ // no salt — verifies them. Run through the real verifyAll on the COPY.+ ok(Object.keys(r.signatures ?? {}).length === 1, 'the signature travels with the view-only copy')ok(!('historySalt' in r), 'but the history salt does not — without it the commitment reveals nothing'){- const v = await verifyChain(r as never, r.signatures)+ const v = await verifyAll(r as never, r.signatures)ok(v.ok && v.entries[0].ok && v.entries[0].why === null,'and it VERIFIES on the copy: the content attested is exactly what the copy holds')ok(v.entries[0].history === 'not-included',@@ -304,7 +304,7 @@ H('Copy document JSON carries no history and no credentials (tier copyJSON)')const j = docForExport(F.doc)ok(!has(j, DRAFT) && !has(j, NOTE), 'no draft, no comment')ok(!('historySalt' in j), 'no history salt')- ok(j.signatures?.length === 1, 'the signature is content now, so it travels as text too')+ ok(Object.keys(j.signatures ?? {}).length === 1, 'the signature is content now, so it travels as text too')ok(!('collab' in j), 'no collaboration block at all')ok(!has(j, FUTURE), 'no undeclared field')ok(j.body[0].text === F.doc.body[0].text && j.docId === F.doc.docId, 'content and identity intact')@@ -320,7 +320,7 @@ H('mail merge: every letter is a new document with no history (the \'merge\' tieok(a.docId !== F.doc.docId && b.docId !== F.doc.docId, 'neither reuses the source document\'s identity')for (const [n, m] of [['first', a], ['second', b]] as const) {ok(!has(m, DRAFT) && !has(m, NOTE), `the ${n} letter carries no draft and no comment`)- ok(!m.signatures.length && !m.revisions.length, `the ${n} letter carries no signatures and no revisions`)+ ok(!Object.keys(m.signatures).length && !m.revisions.length, `the ${n} letter carries no signatures and no revisions`)ok(!('collab' in m), `the ${n} letter carries no collaboration block`)}const B = await bare()@@ -367,7 +367,7 @@ H('mail merge: an EMBEDDED document\'s keys never reach a letter')H('an INVITE keeps history by default, and leaves it out when asked (tier invite)'){const keep = await inviteCopy(F.doc, F.ownerPriv)- ok(has(keep, DRAFT) && has(keep, NOTE) && keep.signatures.length === 1,+ ok(has(keep, DRAFT) && has(keep, NOTE) && Object.keys(keep.signatures).length === 1,'by default the invitee gets the history — the kernel\'s invite rule')ok(!('ownerPriv' in (keep.collab as object)), 'but never the owner key')ok(keep.collab?.on === true, 'and joins live')diff --git a/type/src/canon.ts b/type/src/canon.tsindex e12e26b0..a3d42d04 100644--- a/type/src/canon.ts+++ b/type/src/canon.ts@@ -26,6 +26,7 @@// same idea made exact enough to sign.import type { Signature } from './model.ts';+import { sha256 } from './sha256.ts';import { TYPE_FIELDS } from './docclass.ts';/**@@ -39,8 +40,15 @@ import { TYPE_FIELDS } from './docclass.ts';* not-included a READER-TIER copy (readonly) never carries history; neutral*/export type HistoryState = 'matches' | 'changed' | 'missing' | 'not-included';-export interface ChainEntry { ok: boolean; why: string | null; linked: boolean; name: string; history: HistoryState }-export interface ChainResult { ok: boolean; entries: ChainEntry[] }+/** One signature, verified ON ITS OWN (ruling 7): no other signature can make+ * it invalid. `after` is the SigId of the signature it says it follows, when+ * this copy holds that one — ordering information, never validity. */+export interface SigEntry {+ id: string; sig: Signature;+ ok: boolean; why: string | null; history: HistoryState;+ after: string | null;+}+export interface SigResult { ok: boolean; entries: SigEntry[] }/*** Fields that never enter a signature. Everything else is signed — including@@ -286,6 +294,46 @@ export const exportPub = async (k: CryptoKeyPair): Promise<string> =>const sigText = (docId: string, content: string, history: string, prev: string, name: string) =>`bento-type-sig.v2|${str(docId)}|${content}|${history}|${prev}|${str(name)}`;+/**+ * A signature's id (ruling 7): derived from WHAT WAS SIGNED, never from the+ * signature bytes.+ *+ * SigId = base64url(sha256("bento-type-sigid.v1|" + pub + "|" + signed text))+ *+ * ECDSA is malleable — (r, n−s) is a second valid signature over the same text+ * (measured: WebCrypto accepts it) — so an id taken from the bytes would let+ * anyone mint a fresh key for a signature already on the document. This one is+ * the same for every copy of the same act of signing, including a malleated+ * one, on every replica. An entry stored under any other key is INVALID:+ * verify recomputes it. Synchronous (sha256.ts) because parseDoc derives it+ * while converting an old file. `pub` is base64url, so it cannot contain the+ * separator.+ */+export function sigId(docId: string, s: Pick<Signature, 'pub' | 'content' | 'history' | 'prev' | 'name'>): string {+ const text = sigText(docId, s.content, s.history, s.prev ?? '', s.name ?? '');+ return b64u(sha256(enc.encode(`bento-type-sigid.v1|${s.pub}|${text}`)));+}++/**+ * LOW-S (ruling 7). P-256's group order n; a signature's s is canonical when+ * s ≤ n/2. WebCrypto emits either half at random, so sign() folds a high s to+ * n − s (an equally valid signature over the same text), and verify() REJECTS+ * a high s — one canonical encoding per signature.+ */+const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;+const HALF_N = N >> 1n;+const toBig = (b: Uint8Array) => b.reduce((acc, x) => (acc << 8n) | BigInt(x), 0n);+const fromBig = (v: bigint) => { const o = new Uint8Array(32); for (let i = 31; i >= 0; i--) { o[i] = Number(v & 0xffn); v >>= 8n; } return o; };+/** Exported for the rig: is this raw r||s signature in canonical low-S form? */+export const isLowS = (raw: Uint8Array): boolean => raw.length === 64 && toBig(raw.slice(32)) <= HALF_N;+function lowS(raw: Uint8Array): Uint8Array {+ const s = toBig(raw.slice(32));+ if (s <= HALF_N) return raw;+ const out = new Uint8Array(64);+ out.set(raw.slice(0, 32)); out.set(fromBig(N - s), 32);+ return out;+}+/*** Sign a revision, chaining to the previous signature.*@@ -309,15 +357,17 @@ type Signable = { docId: string; revisions?: unknown; historySalt?: string; readexport async function sign(doc: Signable,key: CryptoKeyPair,- { name = '', prev = null }: { name?: string; prev?: { sig: string } | null } = {},+ { name = '', prev = null }: { name?: string; prev?: string | null } = {},): Promise<Signature> {if (!doc.historySalt) throw new Error('sign: the document has no historySalt — mint one first');const content = await digest(doc);const history = await historyCommitment(doc.revisions, doc.historySalt);- const prevSig = prev ? prev.sig : '';- const text = sigText(doc.docId, content, history, prevSig, name);- const sig = b64u(await crypto.subtle.sign(SIG, key.privateKey, enc.encode(text)));- return { alg: 'ES256', pub: await exportPub(key), name, content, history, prev: prevSig, sig };+ // `prev` is the SigId of the signature this one follows (ordering only, ruling+ // 7). It is signed, so it cannot be re-pointed after the fact.+ const prevId = prev ?? '';+ const text = sigText(doc.docId, content, history, prevId, name);+ const raw = lowS(new Uint8Array(await crypto.subtle.sign(SIG, key.privateKey, enc.encode(text))));+ return { alg: 'ES256', pub: await exportPub(key), name, content, history, prev: prevId, sig: b64u(raw) };}/**@@ -339,9 +389,16 @@ export async function verify(doc: Signable, entry: Signature):const content = await digest(doc);if (content !== entry.content) return { ok: false, why: 'content-changed', history };if (typeof entry.history !== 'string') return { ok: false, why: 'bad-signature', history };- const pub = await crypto.subtle.importKey('raw', unb64u(entry.pub), EC, false, ['verify']);+ let raw: Uint8Array;+ try { raw = unb64u(entry.sig); } catch { return { ok: false, why: 'bad-signature', history }; }+ // one canonical encoding: a high-S copy is a second spelling of a signature,+ // and is not accepted as one (ruling 7)+ if (!isLowS(raw)) return { ok: false, why: 'bad-signature', history };+ let pub: CryptoKey;+ try { pub = await crypto.subtle.importKey('raw', unb64u(entry.pub), EC, false, ['verify']); }+ catch { return { ok: false, why: 'bad-signature', history }; }const text = sigText(doc.docId, entry.content, entry.history, entry.prev, entry.name ?? '');- const ok = await crypto.subtle.verify(SIG, pub, unb64u(entry.sig), enc.encode(text));+ const ok = await crypto.subtle.verify(SIG, pub, raw as BufferSource, enc.encode(text));return { ok, why: ok ? null : 'bad-signature', history };}@@ -354,17 +411,67 @@ async function historyState(doc: Signable, entry: Signature): Promise<HistoryStareturn mine === entry.history ? 'matches' : 'changed';}-/** Verify a whole chain: every signature valid, and correctly linked. */-export async function verifyChain(doc: Signable, chain: Signature[]): Promise<ChainResult> {- const out: ChainEntry[] = [];- let expectedPrev = '';- for (const entry of chain) {- const r = await verify(doc, entry);- const linked = entry.prev === expectedPrev;- out.push({ ...r, linked, name: entry.name });- expectedPrev = entry.sig;+/**+ * The display order (ruling 7): by `prev`, which is ordering information only.+ * A signature comes after the one it follows when this copy holds that one;+ * otherwise it starts a run of its own. Signatures that follow the same one (a+ * fork, which concurrent signing produces routinely) and runs that start+ * together are ordered by `at`, then by key, then by id, so every replica+ * shows the same order. `prev` resolves by SigId, or for a signature made+ * before ids existed, by the earlier signature's bytes.+ */+export function signatureOrder(sigs: Readonly<Record<string, Signature>>): Array<{ id: string; after: string | null }> {+ const ids = Object.keys(sigs);+ const bySigBytes = new Map(ids.map(id => [sigs[id].sig, id] as const));+ const afterOf = (id: string): string | null => {+ const p = sigs[id].prev;+ if (!p) return null;+ if (p !== id && Object.hasOwn(sigs, p)) return p;+ const legacy = bySigBytes.get(p);+ return legacy !== undefined && legacy !== id ? legacy : null;+ };+ const cmp = (x: string, y: string) => {+ const a = sigs[x], b = sigs[y];+ return (a.at ?? '').localeCompare(b.at ?? '') || a.pub.localeCompare(b.pub) || x.localeCompare(y);+ };+ const kids = new Map<string | null, string[]>();+ for (const id of ids) { const k = afterOf(id); if (!kids.has(k)) kids.set(k, []); kids.get(k)!.push(id); }+ const out: Array<{ id: string; after: string | null }> = [];+ const seen = new Set<string>();+ const walk = (id: string) => {+ if (seen.has(id)) return;+ seen.add(id); out.push({ id, after: afterOf(id) });+ for (const k of (kids.get(id) ?? []).sort(cmp)) walk(k);+ };+ for (const root of (kids.get(null) ?? []).sort(cmp)) walk(root);+ // a malformed file can make a cycle with no root; show those too, never drop one+ for (const id of ids.sort(cmp)) if (!seen.has(id)) walk(id);+ return out;+}++/** The signature a new one follows: the last in display order, or none. */+export function latestSignature(sigs: Readonly<Record<string, Signature>>): string | null {+ const order = signatureOrder(sigs);+ return order.length ? order[order.length - 1].id : null;+}++/**+ * Verify every signature, each ON ITS OWN (ruling 7). An entry is valid when+ * its key is its own derived SigId, its s is low, the signature verifies over+ * its own fields, and the copy's content is what was signed. A fork, or a+ * `prev` this copy does not hold, never makes one invalid.+ */+export async function verifyAll(doc: Signable, sigs: Readonly<Record<string, Signature>>): Promise<SigResult> {+ const entries: SigEntry[] = [];+ for (const { id, after } of signatureOrder(sigs)) {+ const s = sigs[id];+ const r = await verify(doc, s);+ let derived = '';+ try { derived = sigId(doc.docId, s); } catch { /* malformed: not its own id */ }+ const ok = r.ok && derived === id;+ entries.push({ id, sig: s, ok, why: r.ok && !ok ? 'bad-id' : r.why, history: r.history, after });}- return { ok: out.every(r => r.ok && r.linked), entries: out };+ return { ok: entries.every(e => e.ok), entries };}/**diff --git a/type/src/i18n/de.ts b/type/src/i18n/de.tsindex 7d00b6dc..0cde4666 100644--- a/type/src/i18n/de.ts+++ b/type/src/i18n/de.ts@@ -471,7 +471,6 @@ export const de: Catalog = {"Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.": "Die Absturzwiederherstellung ist für dieses Dokument deaktiviert – es ist zu groß für eine Sicherungskopie. Speichern Sie häufig.","✓ valid": "✓ gültig","✕ the content has changed since this was signed": "✕ der Inhalt wurde seit der Signatur geändert",- "⚠ not linked to the previous signature": "⚠ nicht mit der vorherigen Signatur verknüpft","✕ invalid signature": "✕ ungültige Signatur","after {name}": "nach {name}","History matches what was signed": "Der Verlauf stimmt mit dem Signierten überein",diff --git a/type/src/i18n/es.ts b/type/src/i18n/es.tsindex edbf337f..1b53295a 100644--- a/type/src/i18n/es.ts+++ b/type/src/i18n/es.ts@@ -471,7 +471,6 @@ export const es: Catalog = {"Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.": "La recuperación tras fallos está desactivada para este documento: es demasiado grande para guardar una copia de seguridad. Guarda a menudo.","✓ valid": "✓ válida","✕ the content has changed since this was signed": "✕ el contenido ha cambiado desde que se firmó",- "⚠ not linked to the previous signature": "⚠ no está enlazada con la firma anterior","✕ invalid signature": "✕ firma no válida","after {name}": "después de {name}","History matches what was signed": "El historial coincide con lo firmado",diff --git a/type/src/i18n/fr.ts b/type/src/i18n/fr.tsindex 83b0a06d..3c5257fd 100644--- a/type/src/i18n/fr.ts+++ b/type/src/i18n/fr.ts@@ -471,7 +471,6 @@ export const fr: Catalog = {"Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.": "La récupération après plantage est désactivée pour ce document : il est trop volumineux pour en garder une copie de secours. Enregistrez souvent.","✓ valid": "✓ valide","✕ the content has changed since this was signed": "✕ le contenu a changé depuis la signature",- "⚠ not linked to the previous signature": "⚠ non liée à la signature précédente","✕ invalid signature": "✕ signature non valide","after {name}": "après {name}","History matches what was signed": "L’historique correspond à ce qui a été signé",diff --git a/type/src/i18n/it.ts b/type/src/i18n/it.tsindex 99f7b5f2..e2cbfd71 100644--- a/type/src/i18n/it.ts+++ b/type/src/i18n/it.ts@@ -471,7 +471,6 @@ export const it: Catalog = {"Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.": "Il ripristino dopo un arresto anomalo è disattivato per questo documento: è troppo grande per conservarne una copia di backup. Salva spesso.","✓ valid": "✓ valida","✕ the content has changed since this was signed": "✕ il contenuto è cambiato dopo la firma",- "⚠ not linked to the previous signature": "⚠ non collegata alla firma precedente","✕ invalid signature": "✕ firma non valida","after {name}": "dopo {name}","History matches what was signed": "La cronologia corrisponde a quanto firmato",diff --git a/type/src/i18n/ja.ts b/type/src/i18n/ja.tsindex 7d918f34..bed5ef88 100644--- a/type/src/i18n/ja.ts+++ b/type/src/i18n/ja.ts@@ -471,7 +471,6 @@ export const ja: Catalog = {"Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.": "この文書のクラッシュ復旧はオフです — 大きすぎてバックアップを保存できません。こまめに保存してください。","✓ valid": "✓ 有効","✕ the content has changed since this was signed": "✕ 署名後に内容が変更されています",- "⚠ not linked to the previous signature": "⚠ 前の署名とつながっていません","✕ invalid signature": "✕ 無効な署名","after {name}": "{name} の後","History matches what was signed": "履歴は署名時のものと一致しています",diff --git a/type/src/i18n/packed.ts b/type/src/i18n/packed.tsindex cb91fa9b..6a65de33 100644--- a/type/src/i18n/packed.ts+++ b/type/src/i18n/packed.ts@@ -482,7 +482,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"○ Not live — turns on when you share": ["○ ライブではありません — 共有するとオンになります","○ 未实时协作 — 共享后开启","○ 未即時協作 — 共用後開啟","○ No está en directo: se activa al compartir","○ Pas en direct — s'active lorsque vous partagez","○ Nicht live – wird beim Freigeben aktiviert","○ Non in diretta: si attiva quando condividi","○ Não está ao vivo — ativa quando você compartilha"],"● Connecting…": ["● 接続中…","● 正在连接…","● 正在連線…","● Conectando…","● Connexion…","● Verbinden …","● Connessione…","● Conectando…"],"● Live — {n} connected": ["● ライブ — {n} 人が接続中","● 实时协作 — 已连接 {n} 人","● 即時協作 — 已連線 {n} 人","● En directo: {n} conectados","● En direct — {n} connectés","● Live – {n} verbunden","● In diretta: {n} connessi","● Ao vivo — {n} conectados"],- "⚠ not linked to the previous signature": ["⚠ 前の署名とつながっていません","⚠ 未与上一个签名关联","⚠ 未與上一個簽署連結","⚠ no está enlazada con la firma anterior","⚠ non liée à la signature précédente","⚠ nicht mit der vorherigen Signatur verknüpft","⚠ non collegata alla firma precedente","⚠ não vinculada à assinatura anterior"],"✓ valid": ["✓ 有効","✓ 有效","✓ 有效","✓ válida","✓ valide","✓ gültig","✓ valida","✓ válida"],"✕ invalid signature": ["✕ 無効な署名","✕ 签名无效","✕ 簽署無效","✕ firma no válida","✕ signature non valide","✕ ungültige Signatur","✕ firma non valida","✕ assinatura inválida"],"✕ the content has changed since this was signed": ["✕ 署名後に内容が変更されています","✕ 签名后内容已被更改","✕ 簽署後內容已被變更","✕ el contenido ha cambiado desde que se firmó","✕ le contenu a changé depuis la signature","✕ der Inhalt wurde seit der Signatur geändert","✕ il contenuto è cambiato dopo la firma","✕ o conteúdo mudou desde que foi assinado"],diff --git a/type/src/i18n/pt.ts b/type/src/i18n/pt.tsindex 2901e3d7..ea640f82 100644--- a/type/src/i18n/pt.ts+++ b/type/src/i18n/pt.ts@@ -482,7 +482,6 @@ export const pt: Catalog = {"Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.": "A recuperação de falhas está desativada para este documento: ele é grande demais para manter uma cópia de segurança. Salve com frequência.","✓ valid": "✓ válida","✕ the content has changed since this was signed": "✕ o conteúdo mudou desde que foi assinado",- "⚠ not linked to the previous signature": "⚠ não vinculada à assinatura anterior","✕ invalid signature": "✕ assinatura inválida","after {name}": "depois de {name}","History matches what was signed": "O histórico corresponde ao que foi assinado",diff --git a/type/src/i18n/zh-Hans.ts b/type/src/i18n/zh-Hans.tsindex f77507ac..09b4f767 100644--- a/type/src/i18n/zh-Hans.ts+++ b/type/src/i18n/zh-Hans.ts@@ -471,7 +471,6 @@ export const zhHans: Catalog = {"Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.": "此文档的崩溃恢复已关闭 — 文件太大,无法保留备份。请经常保存。","✓ valid": "✓ 有效","✕ the content has changed since this was signed": "✕ 签名后内容已被更改",- "⚠ not linked to the previous signature": "⚠ 未与上一个签名关联","✕ invalid signature": "✕ 签名无效","after {name}": "在 {name} 之后","History matches what was signed": "历史记录与签名时一致",diff --git a/type/src/i18n/zh-Hant.ts b/type/src/i18n/zh-Hant.tsindex e78d8173..e8da6343 100644--- a/type/src/i18n/zh-Hant.ts+++ b/type/src/i18n/zh-Hant.ts@@ -471,7 +471,6 @@ export const zhHant: Catalog = {"Crash recovery is off for this document — it’s too large to keep a backup copy. Save often.": "此文件的當機復原已關閉 — 檔案太大,無法保留備份。請經常儲存。","✓ valid": "✓ 有效","✕ the content has changed since this was signed": "✕ 簽署後內容已被變更",- "⚠ not linked to the previous signature": "⚠ 未與上一個簽署連結","✕ invalid signature": "✕ 簽署無效","after {name}": "在 {name} 之後","History matches what was signed": "歷程與簽署時一致",diff --git a/type/src/main.ts b/type/src/main.tsindex a271d719..337bd75e 100644--- a/type/src/main.ts+++ b/type/src/main.ts@@ -25,7 +25,7 @@ import { Editor } from './editor.ts';import { paginate, drawPages, type Metrics } from './paginate.ts';import { takeSnapshot, startReview } from './redlineview.ts';import { printDocument, buildPrintDocument } from './print.ts';-import { sign as signDoc, verifyChain, newKey, newHistorySalt, exportPub, historyDisplay, type HistoryLine } from './canon.ts';+import { sign as signDoc, verifyAll, sigId, latestSignature, newKey, newHistorySalt, exportPub, historyDisplay, type HistoryLine } from './canon.ts';// Tell the kernel who this app is — must precede any kernel module use// (window title suffix, save-picker label, update manifest).@@ -872,13 +872,16 @@ document.getElementById('sign')!.addEventListener('click', async () => {const salt = newHistorySalt();store.commit(d => { d.historySalt = salt; }, { undoable: false });}- const prev = store.doc.signatures[store.doc.signatures.length - 1] ?? null;+ // follows the latest signature in display order — ORDERING only (ruling 7)+ const prev = latestSignature(store.doc.signatures);const entry = await signDoc(store.doc, key, { name, prev });+ const id = sigId(store.doc.docId, entry);entry.at = new Date().toISOString();// NOT undoable (ruling 7): a signature leaves only by its signer's or the// owner's removal, never by ⌘Z — and a 'back' restore keeps signatures live// (restorerules.ts), so an undo step here would only be a step that does nothing.- store.commit(d => { d.signatures.push(entry); }, { undoable: false });+ // its OWN key, so a concurrent signer's lands beside it rather than over it+ store.commit(d => { d.signatures[id] = entry; }, { undoable: false });markDirty(); showTab('sigs'); await paintSigs();toast('Signed');});@@ -898,7 +901,7 @@ async function paintSigs() {const box = document.getElementById('sigsPanel')!;const sigs = store.doc.signatures;box.replaceChildren();- if (!sigs.length) {+ if (!Object.keys(sigs).length) {const h = el('div', 't-hint');h.innerHTML = `Nothing signed yet.<br><br>A signature covers the document's <b>content</b> —not its timestamp, not which theme you are using — so re-saving never breaks one, but@@ -907,17 +910,18 @@ async function paintSigs() {box.appendChild(h);return;}- const res = await verifyChain(store.doc, sigs);+ const res = await verifyAll(store.doc, sigs);const mine = await devicePub();- sigs.forEach((s, i) => {- const r = res.entries[i];+ res.entries.forEach(r => {+ const s = r.sig;const card = el('div', 't-card');// ATTESTATION — checked for every signature: is it valid, and is the// content what was signed?- const state = r.ok && r.linked ? `<span class="t-ok">${esc(t('✓ valid'))}</span>`- : (!r.ok && r.why === 'content-changed'+ // Each signature stands on its own (ruling 7): which one it follows is+ // ordering, shown below, and never makes it invalid.+ const state = r.ok ? `<span class="t-ok">${esc(t('✓ valid'))}</span>`+ : (r.why === 'content-changed'? `<span class="t-bad">${esc(t('✕ the content has changed since this was signed'))}</span>`- : !r.linked ? `<span class="t-warn">${esc(t('⚠ not linked to the previous signature'))}</span>`: `<span class="t-bad">${esc(t('✕ invalid signature'))}</span>`);// HISTORY — shown as a state only where this replica can know it (ruling// (8), canon.ts historyDisplay); someone else's reads neutral.@@ -930,13 +934,13 @@ async function paintSigs() {`<div class="what" style="font-weight:600">${esc(s.name || 'unnamed')}</div>` +`<div class="t-fp">${fingerprint(s.pub)}</div>` +`<div class="who" style="margin:5px 0 0">${state}` +- `${i > 0 ? ` · ${esc(t('after {name}', { name: sigs[i - 1].name || 'previous' }))}` : ''}</div>` ++ `${r.after ? ` · ${esc(t('after {name}', { name: sigs[r.after].name || 'previous' }))}` : ''}</div>` +hist;box.appendChild(card);});// two names on one key is exactly what a signature cannot proveconst byKey = new Map<string, Set<string>>();- for (const s of sigs) {+ for (const s of Object.values(sigs)) {if (!byKey.has(s.pub)) byKey.set(s.pub, new Set());byKey.get(s.pub)!.add(s.name || 'unnamed');}diff --git a/type/src/merge.ts b/type/src/merge.tsindex 51c2d99d..41979609 100644--- a/type/src/merge.ts+++ b/type/src/merge.ts@@ -306,7 +306,7 @@ export function mergeDoc(template: TypeDoc, row: Record<string, string>,// has its own stable identity from the moment it is written.out.docId = newDocId();// TypeDoc declares these as required arrays; the tier dropped what they held.- out.signatures = [];+ out.signatures = {};out.revisions = [];// The template's last-saved stamp says nothing true about a new letter.delete out.modified;diff --git a/type/src/model.ts b/type/src/model.tsindex 79d83228..f6b26963 100644--- a/type/src/model.ts+++ b/type/src/model.ts@@ -14,6 +14,7 @@import { normalize, shift as shiftMarks, type Mark } from './inline.ts';import { withoutCaps, projectForCopy } from '../../kernel/src/docfields.ts';import { TYPE_FIELDS } from './docclass.ts';+import { sigId } from './canon.ts';// value import is safe: xref.ts imports only TYPES from this module, precisely// so the core can call into it without a cycleimport { shiftRefs } from './xref.ts';@@ -231,7 +232,9 @@ export interface Signature {* historyCommitment). Reveals nothing about the revisions without the* document's historySalt, so it travels in view-only copies. */history: string;- /** the signature this one commits to, chaining the order */+ /** the SigId (canon.ts sigId) of the signature this one follows — ORDERING+ * only (ruling 7): a signature is valid on its own, whatever this says. A+ * signature made before ids existed holds the earlier signature's bytes. */prev: string;sig: string;/** self-asserted wall clock. Display only — order comes from `prev`. */@@ -332,7 +335,12 @@ export interface TypeDoc {/** 128-bit, base64url. Salts the history commitment every signature carries.* Minted at first sign, NEVER rotated, never synced (canon.ts newHistorySalt). */historySalt?: string;- signatures: Signature[];+ /**+ * Keyed by SigId (canon.ts sigId: derived from what was signed), so each+ * signature syncs as its OWN key and concurrent signers both survive (ruling+ * 7). An entry under any key but its own SigId is invalid.+ */+ signatures: Record<string, Signature>;/*** Is the document recording edits as tracked changes?*@@ -532,7 +540,7 @@ export function emptyDoc(): TypeDoc {format: FORMAT, version: VERSION, docId: newDocId(),title: 'Untitled', page: { ...LETTER },body: [{ id: uid(), kind: 'para', text: '' }],- footnotes: {}, revisions: [], signatures: [],+ footnotes: {}, revisions: [], signatures: {},};}@@ -560,6 +568,33 @@ const isObj = (v: unknown): v is Record<string, unknown> =>* the redline aligns blocks by id, and two parties whose copies disagree would* see phantom changes.*/+/**+ * The `signatures` map, from whatever the file holds (ruling 7).+ * - the per-signature map: kept as it is, entries that are not objects+ * dropped; a key that is not its entry's own SigId is left for verify to+ * report as invalid, never silently re-keyed;+ * - an OLD array (before ruling 7): each entry keyed by its derived SigId,+ * once, here — the same act of signing gets the same key on every replica;+ * - absent or anything else: none.+ * The docId is the FILE's: a SigId commits to it.+ */+function readSignatures(raw: unknown, docId: string): Record<string, Signature> {+ const out: Record<string, Signature> = {};+ const usable = (v: unknown): v is Signature =>+ isObj(v) && typeof v.pub === 'string' && typeof v.sig === 'string';+ if (Array.isArray(raw)) {+ for (const v of raw) {+ if (!usable(v)) continue;+ let id: string;+ try { id = sigId(docId, v); } catch { continue; }+ if (!Object.hasOwn(out, id)) out[id] = v;+ }+ } else if (isObj(raw)) {+ for (const [k, v] of Object.entries(raw)) if (usable(v)) out[k] = v;+ }+ return out;+}+export function parseDoc(raw: string): ParseResult {const trimmed = raw.trim();if (!trimmed) return { ok: false, err: 'empty' };@@ -798,7 +833,7 @@ export function parseDoc(raw: string): ParseResult {body, footnotes,revisions: Array.isArray(json.revisions) ? json.revisions as Revision[] : [],...(json.track === true ? { track: true } : {}),- signatures: Array.isArray(json.signatures) ? json.signatures as Signature[] : [],+ signatures: readSignatures(json.signatures, typeof json.docId === 'string' ? json.docId : ''),};if (Object.keys(styles).length) doc.styles = styles; else delete doc.styles;// A salt is 16 bytes, base64url without padding: exactly 22 characters. Anythingdiff --git a/type/src/sha256.ts b/type/src/sha256.tsnew file mode 100644index 00000000..40e64827--- /dev/null+++ b/type/src/sha256.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// SHA-256, SYNCHRONOUS (FIPS 180-4). WebCrypto's digest is the one to use+// wherever a promise is fine; this exists for the one place that cannot wait:+// parseDoc deriving a signature's id (canon.ts sigId) while it converts an+// old file, which is synchronous because opening a document is.+//+// Not a security boundary on its own: a SigId is RECOMPUTED by verify from the+// signature's own fields, so a wrong hash here would show up as ids that do+// not match, never as a forgery accepted. scripts/test-type-canon.ts checks+// this against the published test vectors and against WebCrypto on random+// inputs of every length across several block boundaries.++const K = new Uint32Array([+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,+]);++const rotr = (x: number, n: number) => (x >>> n) | (x << (32 - n));++export function sha256(data: Uint8Array): Uint8Array {+ // padding: a 1 bit, zeros, then the bit length as a 64-bit big-endian integer+ const bitLen = data.length * 8;+ const total = Math.ceil((data.length + 9) / 64) * 64;+ const m = new Uint8Array(total);+ m.set(data);+ m[data.length] = 0x80;+ const dv = new DataView(m.buffer);+ dv.setUint32(total - 8, Math.floor(bitLen / 0x100000000));+ dv.setUint32(total - 4, bitLen >>> 0);++ const H = new Uint32Array([+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,+ ]);+ const W = new Uint32Array(64);+ for (let off = 0; off < total; off += 64) {+ for (let t = 0; t < 16; t++) W[t] = dv.getUint32(off + t * 4);+ for (let t = 16; t < 64; t++) {+ const s0 = rotr(W[t - 15], 7) ^ rotr(W[t - 15], 18) ^ (W[t - 15] >>> 3);+ const s1 = rotr(W[t - 2], 17) ^ rotr(W[t - 2], 19) ^ (W[t - 2] >>> 10);+ W[t] = (W[t - 16] + s0 + W[t - 7] + s1) >>> 0;+ }+ let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];+ for (let t = 0; t < 64; t++) {+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);+ const ch = (e & f) ^ (~e & g);+ const t1 = (h + S1 + ch + K[t] + W[t]) >>> 0;+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);+ const maj = (a & b) ^ (a & c) ^ (b & c);+ const t2 = (S0 + maj) >>> 0;+ h = g; g = f; f = e; e = (d + t1) >>> 0;+ d = c; c = b; b = a; a = (t1 + t2) >>> 0;+ }+ H[0] = (H[0] + a) >>> 0; H[1] = (H[1] + b) >>> 0; H[2] = (H[2] + c) >>> 0; H[3] = (H[3] + d) >>> 0;+ H[4] = (H[4] + e) >>> 0; H[5] = (H[5] + f) >>> 0; H[6] = (H[6] + g) >>> 0; H[7] = (H[7] + h) >>> 0;+ }+ const out = new Uint8Array(32);+ const ov = new DataView(out.buffer);+ for (let i = 0; i < 8; i++) ov.setUint32(i * 4, H[i]);+ return out;+}diff --git a/type/src/sync/crdt.ts b/type/src/sync/crdt.tsindex 6dc3ac71..1391ab19 100644--- a/type/src/sync/crdt.ts+++ b/type/src/sync/crdt.ts@@ -74,7 +74,7 @@ import type { DocShape } from '../../../kernel/src/sync/crdt.ts';*/const SYNC_HISTORY = ['comments'] as const;-export const TYPE_SHAPE: DocShape = shape('body', null, 'text', ['footnotes'],+export const TYPE_SHAPE: DocShape = shape('body', null, 'text', ['footnotes', 'signatures'],TYPE_FIELDS, historySyncKeys(TYPE_FIELDS, SYNC_HISTORY));/** The engine bound to bento/type. */