Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
type: signatures sign the content plus a salted commitment to the history (#707)
nyblnet4d161e75c3b7
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex e237537c..3f043f6e 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -10347,6 +10347,77 @@ Mutations, all red by exit code:Naming a content key, an identity key, or a misspelled key in `syncHistory`fails tsc.++## 2026-10-15 — bento/type signatures v2: content plus a salted commitment to the history++Maintainer ruling (3), 2026-10-15. A type signature signs the document's+CONTENT plus a COMMITMENT to its history, not the history itself. A view-only+copy carries the commitment and no drafts, and its signatures verify. This is a+pre-release format change: bento/type was unreleased, so v2 replaces v1 and no+v1 signature exists to honour.++Signed text:++ bento-type-sig.v2|<docId>|<content digest>|<history commitment>|<prev sig or "">|<name>++**What the content digest covers.** Every top-level field except the volatile+set (`modified`, `sync`, `collab`, `preview`, `signatures`, `autosave`) and+every field the class map classes history, capability or mode. That exclusion+is DERIVED from `TYPE_FIELDS`, never hand-listed. Today the digest covers+format, version, docId, title, subtitle, meta, page, body, footnotes, layout,+styles, type, optical, track, merge, fonts and assets, plus any undeclared field+(the exclude list fails safe). `scripts/test-type-canon.ts` derives the same+list from the map and checks that each field moves the digest and each excluded+one does not. Mode is excluded because a view-only copy SETS `readonly: true`;+were it signed, every view-only copy would read "changed". Comments are history+and outside the signature: a comment's author is a self-asserted name and+signing never attested it.++**The commitment.**++ sha256("bento-type-history.v1" || historySalt || canonical(revisions))++- `historySalt` is 16 random bytes per document, carried as 22 base64url+ characters. It is minted at first sign, NEVER rotated (that would orphan+ every signature), and classed history, so it is kept with the full history+ only: dropped from view-only copies, Copy JSON and mail merge, and never+ synced.+- Revision ids carry only 32 bits (`uid()` keeps 8 hex characters of a UUID),+ and timestamps are guessable. Without the salt, a commitment travelling in a+ view-only copy would let someone who suspects a small edit brute-force the+ earlier draft.+- The domain tag stops cross-protocol reuse.+- Salts are per-replica by design, because history does not sync. Two+ replicas' commitments differ even for similar histories.++**Verification reports two things, never folded into one.**++- **Attestation:** the signature is valid and the content is what was signed.+ It works anywhere, including a view-only copy.+- **History:** what the commitment says about the history this copy holds:+ - `matches`;+ - `changed`, e.g. a Snapshot taken after signing, or a re-sign after a trim+ (expected in that case, and the UI must say a trim does this);+ - `missing`, a WARNING for an editable document that lost its revisions or+ salt. Otherwise deleting `revisions` would turn "changed" into a neutral+ grey;+ - `not-included`, neutral, only for a read-only copy, which never carries+ history.++A forged commitment is not a history state: it is in the signed text, so it+breaks the attestation.++Signatures are therefore CONTENT again (classed history only as an interim, so+they could leave view-only copies). They now sync as content and travel in+view-only copies. Listing them in `syncHistory` became a compile error, which+removed them from it.++**Open.** How the Signatures panel shows the history state for a signature made+on ANOTHER replica is a maintainer decision. Its history check would commonly+read "changed", since each replica keeps its own revisions. Security's input:+it must never warn on an expected condition.++## 2026-10-15 — dash: Save a copy and the older-copy banner, per the maintainer rulingDash adopts the maintainer's ruling and slides' wording (#713) verbatim. Two@@ -10363,4 +10434,3 @@ choices are dash's and are recorded because a later change could undo them:must never cost the copy. It stays for the next open, as ✕ already left it.`recoveryLooksOlder` is read against the workbook AS LOADED, because dashstamps `modified` on every edit.-diff --git a/scripts/test-type-canon.ts b/scripts/test-type-canon.tsindex ed2e5152..964fb203 100644--- a/scripts/test-type-canon.ts+++ b/scripts/test-type-canon.ts@@ -31,7 +31,10 @@import {canonicalize, digest, sign, verify, verifyChain, newKey, exportPub, VOLATILE,+ SIGNED_EXCLUDE, historyCommitment, newHistorySalt, historyDisplay,} from '../type/src/canon.ts';+import { readFileSync } from 'node:fs';+import { TYPE_FIELDS } from '../type/src/docclass.ts';let checks = 0, failures = 0;const ok = (c: boolean, m: string) => {@@ -45,10 +48,14 @@ const threw = (fn: () => unknown): string | null => {// A document shaped like the real thing, so the properties are pinned against// something a user could actually produce rather than a toy object.+// v2 signatures commit to the history under the document's own salt, so every+// fixture carries one — the same salt throughout, as a real document's never+// rotates. Minted by the real minter, so it is a real 16-byte salt.+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: [], ...over,+ footnotes: {}, revisions: [], signatures: [], historySalt: SALT, ...over,});// ────────────────────────────────────────────────────────────── 1. determinism@@ -348,5 +355,139 @@ H('signing again after an edit — the chain reports the past honestly');+ '`signatures` is volatile and never enters the digest');}+// ════════════════════════════════════════════════════════════════════ v2+// Signatures sign the CONTENT plus a salted COMMITMENT to the history+// (maintainer ruling 2026-10-15), so a view-only copy — no revisions, no salt,+// read-only — still verifies. Each row below states one property of that.++H('v2: the content digest covers exactly the content — derived from the class map');+{+ // Which fields the digest attests is stated in canon.ts in prose; this is the+ // same statement made by MEASURING. Every content/identity field moves the+ // digest; every excluded field does not. Derived from TYPE_FIELDS, so a field+ // classified later is checked without anyone remembering this rig.+ const base = doc();+ const d0 = await digest(base);+ const moves = async (k: string) => d0 !== await digest({ ...base, [k]: { probe: k } });+ for (const [k, cls] of Object.entries(TYPE_FIELDS)) {+ const excluded = SIGNED_EXCLUDE.has(k);+ if (excluded) ok(!(await moves(k)), `${k} (${cls}) is NOT in the content digest`);+ else ok(await moves(k), `${k} (${cls}) IS in the content digest`);+ }+ for (const k of ['revisions', 'comments', 'historySalt', 'collab', 'readonly', 'template', 'signatures', 'modified'])+ ok(SIGNED_EXCLUDE.has(k), `${k} is excluded by name, as canon.ts says`);+ ok(await moves('undeclaredFutureField'), 'an UNDECLARED field is signed — the exclude list fails safe');+}++H('v2: the history commitment');+{+ const revs = [{ id: 'rev-1', at: 'x', label: 'Revision 1', body: [{ id: 'p1', kind: 'para', text: 'within 30 days' }] }];+ const s2 = newHistorySalt();+ ok(SALT.length === 22 && s2.length === 22 && SALT !== s2, 'a salt is 16 bytes as 22 base64url chars, and fresh each time');+ ok(await historyCommitment(revs, SALT) !== await historyCommitment(revs, s2),+ 'the SAME revisions under two salts commit differently — the salt is what hides the drafts');+ ok(await historyCommitment(revs, SALT) === await historyCommitment(JSON.parse(JSON.stringify(revs)), SALT),+ 'and the same revisions under the same salt commit identically');+ // The domain tag is part of the preimage: recompute without it and compare.+ const enc = new TextEncoder();+ const raw = Uint8Array.from(atob(SALT.replace(/-/g, '+').replace(/_/g, '/') + '=='), c => c.charCodeAt(0));+ const body = enc.encode(canonicalize(revs));+ const untagged = new Uint8Array(raw.length + body.length); untagged.set(raw); untagged.set(body, raw.length);+ const h = await crypto.subtle.digest('SHA-256', untagged);+ const untaggedB64 = btoa(String.fromCharCode(...new Uint8Array(h))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+ ok(await historyCommitment(revs, SALT) !== untaggedB64, 'the commitment is DOMAIN-TAGGED — not a bare sha256(salt||revisions)');+ let threw = false; try { await historyCommitment(revs, 'short'); } catch { threw = true; }+ ok(threw, 'a salt that is not 16 bytes is refused, not silently used');+}++H('v2: attestation and history are reported separately');+{+ const revs = [{ id: 'rev-1', at: 'x', label: 'Revision 1', body: [] }];+ const d = doc({ revisions: revs });+ const k = await newKey();+ const s = await sign(d, k, { name: 'Alice' });+ ok(typeof s.history === 'string' && s.history === await historyCommitment(revs, SALT),+ 'a v2 signature carries the commitment to the history it signed');+ const own = await verify(d, s);+ ok(own.ok && own.history === 'matches', 'on its own document: valid, and the history matches');++ // ⋯ → Snapshot after signing: the TEXT is identical, only history moved.+ const snapped = doc({ revisions: [...revs, { id: 'rev-2', at: 'y', label: 'Revision 2', body: [] }] });+ const r1 = await verify(snapped, s);+ ok(r1.ok, 'a Snapshot does NOT break the attestation — the content is what was signed');+ ok(r1.history === 'changed', 'but the history reports CHANGED — signatures still cover it');++ // A view-only copy: no revisions, no salt, read-only.+ const reader: Record<string, unknown> = { ...d, readonly: true };+ delete reader.revisions; delete reader.historySalt;+ const r2 = await verify(reader as never, s);+ ok(r2.ok && r2.history === 'not-included',+ 'a READER-tier copy verifies, and its missing history is neutral — it never carries history');++ // The SAME document, EDITABLE, with the history deleted: a warning, not grey.+ const stripped: Record<string, unknown> = { ...d };+ delete stripped.revisions;+ const r3 = await verify(stripped as never, s);+ ok(r3.ok && r3.history === 'missing',+ 'an EDITABLE document that lost its revisions reports MISSING — deleting history cannot fake "neutral"');+ const unsalted: Record<string, unknown> = { ...d }; delete unsalted.historySalt;+ ok((await verify(unsalted as never, s)).history === 'missing', 'and so does one that lost its salt');++ const forged = await verify(d, { ...s, history: await historyCommitment([], SALT) });+ ok(!forged.ok && forged.why === 'bad-signature', 'a forged `history` field breaks the signature itself');+ const resalted = await verify({ ...d, historySalt: newHistorySalt() }, s);+ ok(resalted.ok && resalted.history === 'changed', 'swapping the salt reads as changed history, never as a match');++ let threw = false; try { await sign({ docId: 'x', revisions: [] }, k, {}); } catch { threw = true; }+ ok(threw, 'signing a document with no salt is refused — the caller mints it, in the document');+}++H('v2: a re-sign after trimming the history');+{+ const r1 = { id: 'rev-1', at: 'x', label: 'Revision 1', body: [] };+ const r2 = { id: 'rev-2', at: 'y', label: 'Revision 2', body: [] };+ 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]);+ 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 — '+ + 'expected after a trim, and the UI must say a trim does this');+}++H('the panel shows history only where this replica can know it (ruling 8)');+{+ // History does not sync, so another replica's signature routinely reads+ // "changed" or "missing" here — the EXPECTED condition. Showing that as a+ // warning trains people to ignore it. So: compared and shown for THIS+ // device's signatures; neutral for everyone else's.+ const d = (st: Parameters<typeof historyDisplay>[0], mine: boolean) => historyDisplay(st, mine);+ ok(d('changed', true).tone === 'warn' && d('changed', true).line === 'changed', 'MY signature, history changed → a warning');+ ok(d('missing', true).tone === 'warn' && d('missing', true).line === 'missing', 'MY signature, history missing → a warning');+ ok(d('changed', false).tone === 'neutral' && d('changed', false).line === 'elsewhere',+ 'SOMEONE ELSE\'s signature whose history differs → neutral "kept on the signer\'s copy", never a warning');+ ok(d('missing', false).tone === 'neutral' && d('missing', false).line === 'elsewhere',+ 'and the same when this replica holds none of their history');+ ok(d('matches', false).tone === 'ok' && d('matches', true).tone === 'ok',+ 'a match is shown for anyone — this replica demonstrably holds the signed history');+ ok(d('not-included', false).tone === 'neutral' && d('not-included', true).tone === 'neutral',+ 'a view-only copy is neutral either way');+ const tones = (['matches', 'changed', 'missing', 'not-included'] as const).flatMap(st => [d(st, true), d(st, false)]);+ ok(!tones.some(x => x.tone === 'ok' && x.line !== 'matches'),+ 'nothing but an actual match is ever shown as ok — a neutral line never reads as safe');++ // The panel decides "mine" by comparing against THIS device's key, read+ // without minting one. Checked by source: DOM code no rig can run.+ const main = readFileSync(new URL('../type/src/main.ts', import.meta.url), 'utf8');+ ok(/historyDisplay\(r\.history, mine !== null && s\.pub === mine\)/.test(main),+ 'the panel passes "mine" only for a signature made with this device\'s own key');+ const dp = main.slice(main.indexOf('async function devicePub'), main.indexOf('const fingerprint'));+ ok(/if \(!saved\) return null;/.test(dp) && dp.indexOf('if (!saved) return null;') < dp.indexOf('getKey()'),+ 'and devicePub returns null BEFORE getKey can mint a key — painting never creates one');+}+console.log(`\n${checks - failures}/${checks} checks passed`);if (failures) process.exit(1);diff --git a/scripts/test-type-redline.ts b/scripts/test-type-redline.tsindex 9fbc0e4c..70843910 100644--- a/scripts/test-type-redline.ts+++ b/scripts/test-type-redline.ts@@ -16,7 +16,7 @@// here on purpose.import { redline, apply, describe, diffTokens, tokenize } from '../type/src/redline.ts';-import { sign, verify, newKey, digest } from '../type/src/canon.ts';+import { sign, verify, newKey, digest, newHistorySalt } from '../type/src/canon.ts';import type { Block } from '../type/src/model.ts';let checks = 0, failures = 0;@@ -145,8 +145,10 @@ H('a proposal is attributable');const key = await newKey();const set = redline(A, B, { author: 'counsel' });const proposed = apply(A, set, new Set(set.changes.map(c => c.id)));- const sig = await sign({ ...proposed, docId: A.docId }, key, { name: 'counsel' });- ok((await verify({ ...proposed, docId: A.docId }, sig)).ok, 'the proposed document verifies');+ // A signed document carries the salt its history commitment is made under.+ const historySalt = newHistorySalt();+ const sig = await sign({ ...proposed, docId: A.docId, historySalt }, key, { name: 'counsel' });+ ok((await verify({ ...proposed, docId: A.docId, historySalt }, sig)).ok, 'the proposed document verifies');ok(!(await verify({ ...A, docId: A.docId }, sig)).ok, 'and does not verify against the original');const tampered = JSON.parse(JSON.stringify(set));const t = tampered.changes.find((c: { kind: string }) => c.kind === 'text');diff --git a/scripts/test-type-share.ts b/scripts/test-type-share.tsindex 8efd25b6..32d7d63e 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 } = await import('../type/src/canon.ts')+const { sign, newKey, newHistorySalt, verifyChain } = 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'@@ -235,6 +235,7 @@ async function full(): Promise<{ doc: TypeDoc; ownerPriv: string }> {d.revisions = [{ id: 'rev1', at: '2026-10-01T00:00:00.000Z', label: 'Revision 1',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 documentd.signatures = [await sign(d, await newKey(), { name: 'Alice', prev: null })];(d as Record<string, unknown>).futureField = FUTUREconst r = parseDoc(JSON.stringify(d))@@ -254,13 +255,15 @@ async function bare(): Promise<{ doc: TypeDoc; ownerPriv: string }> {const has = (o: unknown, s: string) => JSON.stringify(o).includes(s)const carriesHistory = (o: TypeDoc) =>- (o.revisions?.length ?? 0) > 0 || (o.signatures?.length ?? 0) > 0 || o.comments !== undefined+ (o.revisions?.length ?? 0) > 0 || o.comments !== undefined || o.historySalt !== undefinedH('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(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')ok(typeof (F.doc.collab as { ownerPriv?: string }).ownerPriv === 'string', 'the source holds a real owner private key')@@ -269,7 +272,18 @@ H('a VIEW-ONLY copy carries no history (tier reader)')const r = readerCopy(F.doc)ok(!has(r, DRAFT), 'no earlier draft — the wording negotiated away stays here')ok(!has(r, NOTE), 'no internal comment')- ok(!r.signatures?.length, 'no signatures: one covering history the copy lacks would read "changed" forever')+ // 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')+ 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)+ 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',+ 'with the history reported NEUTRAL — a view-only copy never carries it')+ }for (const k of HISTORY_CLASS) ok(!(k in r), `${k} is absent as a FIELD, not merely emptied`)ok(!has(r, FUTURE), 'an undeclared field does not ride along')ok(r.readonly === true, 'the copy is read-only (set by the tier, not by the source)')@@ -288,7 +302,9 @@ H('a VIEW-ONLY copy carries no history (tier reader)')H('Copy document JSON carries no history and no credentials (tier copyJSON)'){const j = docForExport(F.doc)- ok(!has(j, DRAFT) && !has(j, NOTE) && !j.signatures?.length, 'no draft, no comment, no signature')+ 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(!('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')@@ -371,8 +387,10 @@ H('an INVITE keeps history by default, and leaves it out when asked (tier inviteH('the class map is the single source'){ok(TYPE_FIELDS.revisions === 'history' && TYPE_FIELDS.comments === 'history' &&- TYPE_FIELDS.signatures === 'history', 'revisions, comments and signatures are history')- ok([...HISTORY_CLASS].sort().join() === 'comments,revisions,signatures',+ TYPE_FIELDS.historySalt === 'history', 'revisions, comments and the history salt are history')+ ok(TYPE_FIELDS.signatures === 'content',+ 'signatures are content: they sign a commitment to the history, not the history')+ ok([...HISTORY_CLASS].sort().join() === 'comments,historySalt,revisions','the invite opt-out list is DERIVED from the map, not hand-listed')}diff --git a/type/src/canon.ts b/type/src/canon.tsindex dc105ec2..e12e26b0 100644--- a/type/src/canon.ts+++ b/type/src/canon.ts@@ -26,8 +26,20 @@// same idea made exact enough to sign.import type { Signature } from './model.ts';+import { TYPE_FIELDS } from './docclass.ts';-export interface ChainEntry { ok: boolean; why: string | null; linked: boolean; name: string }+/**+ * What a signature's HISTORY commitment says about the history this copy holds.+ * matches the copy's revisions are exactly the ones that were signed+ * changed the copy holds revisions, and they are not the signed ones+ * missing an EDITABLE document has lost the history the signature+ * committed to (revisions or the salt deleted) — a WARNING:+ * otherwise deleting `revisions` would turn "changed" into a+ * neutral grey+ * 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[] }/**@@ -50,6 +62,38 @@ export const VOLATILE = new Set(['autosave',]);+/**+ * Every top-level field the CONTENT digest leaves out — v2.+ *+ * The digest attests the document's CONTENT: every field the class map+ * (docclass.ts) calls content or identity, plus any field it does not declare+ * at all (fail-safe: a field a later build adds is signed by default). It+ * excludes:+ * - VOLATILE above (bookkeeping, credentials, and `signatures` itself);+ * - every field classed history, capability or mode — DERIVED from the map,+ * never hand-listed, so a field classified later moves with its class.+ * History is not dropped from what a signature covers: it is covered by the+ * separate COMMITMENT (historyCommitment), which is what lets a view-only copy,+ * which carries no history and is read-only, still verify. Mode is excluded+ * because a reader-tier copy SETS readonly:true; were it signed, every+ * view-only copy would read "changed".+ *+ * Today that leaves, at the top level: format version docId title subtitle+ * meta page body footnotes layout styles type optical track merge fonts+ * assets — and anything undeclared. scripts/test-type-canon.ts derives the+ * same list from the map and checks each one moves the digest.+ *+ * Like VOLATILE, it applies at EVERY level of the document: a nested key with+ * one of these names (an embedded document's own `revisions`, say) is left out+ * too. Embedded documents are carried, not attested.+ */+export const SIGNED_EXCLUDE: ReadonlySet<string> = new Set([+ ...VOLATILE,+ ...Object.entries(TYPE_FIELDS)+ .filter(([, c]) => c === 'history' || c === 'capability' || c === 'mode')+ .map(([k]) => k),+]);+/** RFC 8785 number serialization: ECMAScript Number::toString, with -0 → 0. */function num(n: number): string {if (!Number.isFinite(n)) throw new TypeError(`non-finite number in document: ${n}`);@@ -149,11 +193,53 @@ const unb64u = (s: string): Uint8Array => {return out;};+/** The CONTENT digest a v2 signature attests (see SIGNED_EXCLUDE). */export async function digest(doc: unknown): Promise<string> {- const bytes = enc.encode(canonicalize(doc));+ const bytes = enc.encode(canonicalize(doc, { volatile: SIGNED_EXCLUDE }));return b64u(await crypto.subtle.digest('SHA-256', bytes));}+// ---------------------------------------------------------------- history commitment++/** Domain tag: a commitment made here can never be replayed as another+ * protocol's hash of the same bytes. */+const HISTORY_TAG = 'bento-type-history.v1';++/**+ * A fresh 128-bit history salt, base64url.+ *+ * WHY A SALT AT ALL. The commitment travels in every signature — into the room+ * and into view-only copies that carry no history. Without a secret, someone+ * holding a copy who knows the current text and suspects a small edit ("30+ * days" against "60 days") could brute-force the earlier draft. Revision ids do+ * NOT supply that secret: uid() keeps 8 hex chars of a UUID, 32 bits, and the+ * timestamps are guessable. So a per-document salt, kept only with the full+ * history (class 'history': dropped from every copy for someone else, never+ * synced), makes the commitment reveal nothing.+ *+ * NEVER ROTATED: every signature commits to history UNDER this salt, so a new+ * salt would orphan all of them. Salts are per-replica by design — history+ * does not sync — so two replicas' commitments to similar histories differ.+ */+export function newHistorySalt(): string {+ return b64u(crypto.getRandomValues(new Uint8Array(16)));+}++/**+ * sha256("bento-type-history.v1" || salt || canonical(revisions)), base64url.+ * The salt is fixed-length (16 bytes), so the concatenation is unambiguous; the+ * tag in front separates the domain. Absent revisions commit as an empty list.+ */+export async function historyCommitment(revisions: unknown, salt: string): Promise<string> {+ const tag = enc.encode(HISTORY_TAG);+ const s = unb64u(salt);+ if (s.length !== 16) throw new TypeError('historySalt must be 16 bytes');+ const body = enc.encode(canonicalize(revisions ?? []));+ const all = new Uint8Array(tag.length + s.length + body.length);+ all.set(tag, 0); all.set(s, tag.length); all.set(body, tag.length + s.length);+ return b64u(await crypto.subtle.digest('SHA-256', all));+}+// ---------------------------------------------------------------- signaturesconst EC = { name: 'ECDSA', namedCurve: 'P-256' };const SIG = { name: 'ECDSA', hash: 'SHA-256' };@@ -164,9 +250,16 @@ export const exportPub = async (k: CryptoKeyPair): Promise<string> =>b64u(await crypto.subtle.exportKey('raw', k.publicKey));/**- * The bytes a signature is taken over.+ * The bytes a signature is taken over (v2).+ *+ * bento-type-sig.v2|<docId>|<content digest>|<history commitment>|<prev sig or "">|<name>*- * bento-type-sig.v1|<docId>|<content digest>|<prev sig or "">|<name>+ * v2 REPLACES v1 (bento/type was unreleased, so no v1 signature exists to+ * honour). v1 signed one digest of content AND history together, so a+ * view-only copy — which must not carry the history, because every revision+ * is a whole earlier draft — could never verify. v2 signs the content digest+ * and a salted COMMITMENT to the history separately: the copy carries the+ * commitment (inside each signature) and no drafts, and still verifies.** THE NAME IS IN HERE, and it was not always. `name` is self-asserted — the* signer chooses it and no crypto makes it true — but "self-asserted" has to@@ -190,8 +283,8 @@ export const exportPub = async (k: CryptoKeyPair): Promise<string> =>* between them are fixed-alphabet base64url and cannot. Normalizing also means* a name typed on a Mac verifies on Windows, which is rule 1 again.*/-const sigText = (docId: string, content: string, prev: string, name: string) =>- `bento-type-sig.v1|${str(docId)}|${content}|${prev}|${str(name)}`;+const sigText = (docId: string, content: string, history: string, prev: string, name: string) =>+ `bento-type-sig.v2|${str(docId)}|${content}|${history}|${prev}|${str(name)}`;/*** Sign a revision, chaining to the previous signature.@@ -203,29 +296,66 @@ const sigText = (docId: string, content: string, prev: string, name: string) =>* are not. The UI should say "signed after B's revision", never "signed at* 14:32" — see type-design.md §3.3.*/+type Signable = { docId: string; revisions?: unknown; historySalt?: string; readonly?: boolean };++/**+ * Sign, committing to the content AND the history, chaining to `prev`.+ *+ * The document MUST already carry its historySalt: the salt is part of the+ * document (it has to be, to recompute the commitment later), so minting it is+ * the caller's store edit, not something a signature may do behind the+ * document's back. See newHistorySalt.+ */export async function sign(- doc: { docId: string },+ doc: Signable,key: CryptoKeyPair,{ name = '', prev = null }: { name?: string; prev?: { sig: 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, prevSig, name);+ 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, prev: prevSig, sig };+ return { alg: 'ES256', pub: await exportPub(key), name, content, history, prev: prevSig, sig };}-export async function verify(doc: { docId: string }, entry: Signature): Promise<{ ok: boolean; why: string | null }> {+/**+ * Two separate answers, never folded into one.+ *+ * ATTESTATION (`ok`, `why`) — the signature is valid over its own fields, and+ * the copy's CONTENT is what was signed. This works anywhere, including a+ * view-only copy, because neither half needs the history.+ *+ * HISTORY (`history`) — what the commitment says about the history THIS copy+ * holds. Reported, not folded into `ok`: a valid attestation over a copy whose+ * history changed is a different fact from a forgery, and the panel must be+ * able to say which. A forged or edited `history` field is not a history+ * state: it is in the signed text, so it breaks `ok`.+ */+export async function verify(doc: Signable, entry: Signature):+ Promise<{ ok: boolean; why: string | null; history: HistoryState }> {+ const history = await historyState(doc, entry);const content = await digest(doc);- if (content !== entry.content) return { ok: false, why: 'content-changed' };+ 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']);- const text = sigText(doc.docId, entry.content, entry.prev, entry.name ?? '');+ 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));- return { ok, why: ok ? null : 'bad-signature' };+ return { ok, why: ok ? null : 'bad-signature', history };+}++async function historyState(doc: Signable, entry: Signature): Promise<HistoryState> {+ const holds = Array.isArray(doc.revisions) && typeof doc.historySalt === 'string' && doc.historySalt !== '';+ if (!holds) return doc.readonly === true ? 'not-included' : 'missing';+ let mine: string;+ try { mine = await historyCommitment(doc.revisions, doc.historySalt!); }+ catch { return 'missing'; } // a malformed salt is a lost one+ return mine === entry.history ? 'matches' : 'changed';}/** Verify a whole chain: every signature valid, and correctly linked. */-export async function verifyChain(doc: { docId: string }, chain: Signature[]): Promise<ChainResult> {+export async function verifyChain(doc: Signable, chain: Signature[]): Promise<ChainResult> {const out: ChainEntry[] = [];let expectedPrev = '';for (const entry of chain) {@@ -236,3 +366,31 @@ export async function verifyChain(doc: { docId: string }, chain: Signature[]): P}return { ok: out.every(r => r.ok && r.linked), entries: out };}++/**+ * How the Signatures panel presents a history state — maintainer ruling (8),+ * 2026-10-15.+ *+ * History is compared and SHOWN only where this replica can actually know it:+ * for a signature made with THIS device's key, or where the replica demonstrably+ * holds the signed history (`matches`). Every other signature was made on+ * another replica, whose revisions this one never receives (history does not+ * sync), so "changed" or "missing" there is the EXPECTED condition — and a check+ * that routinely warns on an expected condition trains people to ignore it, then+ * miss a real alteration. Those read as the ruling's neutral line instead.+ * Attestation (the signature, the content) is checked for every signature+ * regardless; this governs only the history line.+ *+ * Returns a CODE and a tone, never display text: the panel maps each code to a+ * literal t('…') call, which is what the i18n sweep can find. Never "verified":+ * neutral lines state a fact about this copy, never that something is safe.+ * elsewhere someone else's signature whose history this replica cannot see+ */+export type HistoryTone = 'ok' | 'warn' | 'neutral';+export type HistoryLine = 'matches' | 'not-included' | 'elsewhere' | 'changed' | 'missing';+export function historyDisplay(state: HistoryState, mine: boolean): { tone: HistoryTone; line: HistoryLine } {+ if (state === 'matches') return { tone: 'ok', line: 'matches' };+ if (state === 'not-included') return { tone: 'neutral', line: 'not-included' };+ if (!mine) return { tone: 'neutral', line: 'elsewhere' };+ return { tone: 'warn', line: state }; // 'changed' | 'missing', on THIS device's own signature+}diff --git a/type/src/docclass.ts b/type/src/docclass.tsindex ebbd0369..5567d429 100644--- a/type/src/docclass.ts+++ b/type/src/docclass.ts@@ -54,17 +54,16 @@ export const TYPE_FIELDS = {// negotiated away is exactly what a view-only recipient must// not receive.// comments internal discussion of the text, not the text.- // signatures HISTORY, not content, for now. Signatures cover content AND- // revisions, and a reader copy drops revisions, so a kept- // signature would read "changed" in every reader copy — which- // trains a reader to ignore a red ✗ and hides a real tamper- // the day one happens. Dropped until canon signs a commitment- // to the history rather than the history itself, which a- // reader copy could carry and verify; then this becomes content.+ // historySalt the secret that makes each signature's history commitment+ // reveal nothing (canon.ts). Kept with the full history ONLY.revisions: 'history',comments: 'history',- signatures: 'history',+ historySalt: 'history',// content — the document itself+ // signatures content: each signs the content plus a salted COMMITMENT to+ // the history (canon.ts v2), so a view-only copy — no revisions,+ // no salt — still verifies them, and they travel with it.+ signatures: 'content',format: 'content',version: 'content',title: 'content',diff --git a/type/src/i18n/de.ts b/type/src/i18n/de.tsindex 732b2d91..7534effc 100644--- a/type/src/i18n/de.ts+++ b/type/src/i18n/de.ts@@ -465,4 +465,14 @@ export const de: Catalog = {"Leave version history out": "Versionsverlauf weglassen","Versions include text that was deleted. This file keeps them either way.": "Versionen enthalten auch gelöschten Text. Diese Datei behält sie in jedem Fall.","Save invite…": "Einladung speichern…",+ "✓ 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",+ "This copy doesn’t include the history": "Diese Kopie enthält den Verlauf nicht",+ "History kept on the signer’s copy": "Der Verlauf liegt in der Kopie des Unterzeichners",+ "The history has changed since you signed — a Snapshot or a trim does this": "Der Verlauf hat sich seit Ihrer Signatur geändert — eine Momentaufnahme oder ein Kürzen bewirkt das",+ "The history you signed is missing from this document": "Der von Ihnen signierte Verlauf fehlt in diesem Dokument",}diff --git a/type/src/i18n/es.ts b/type/src/i18n/es.tsindex 6131d573..9d95b3fa 100644--- a/type/src/i18n/es.ts+++ b/type/src/i18n/es.ts@@ -465,4 +465,14 @@ export const es: Catalog = {"Leave version history out": "Dejar fuera el historial de versiones","Versions include text that was deleted. This file keeps them either way.": "Las versiones incluyen texto que se borró. Este archivo las conserva en cualquier caso.","Save invite…": "Guardar invitación…",+ "✓ 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",+ "This copy doesn’t include the history": "Esta copia no incluye el historial",+ "History kept on the signer’s copy": "El historial se conserva en la copia del firmante",+ "The history has changed since you signed — a Snapshot or a trim does this": "El historial ha cambiado desde que firmó: una instantánea o un recorte lo provocan",+ "The history you signed is missing from this document": "El historial que firmó no está en este documento",}diff --git a/type/src/i18n/fr.ts b/type/src/i18n/fr.tsindex 5060f946..53f73916 100644--- a/type/src/i18n/fr.ts+++ b/type/src/i18n/fr.ts@@ -465,4 +465,14 @@ export const fr: Catalog = {"Leave version history out": "Ne pas inclure l’historique des versions","Versions include text that was deleted. This file keeps them either way.": "Les versions contiennent du texte supprimé. Ce fichier les conserve dans tous les cas.","Save invite…": "Enregistrer l’invitation…",+ "✓ 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é",+ "This copy doesn’t include the history": "Cette copie n’inclut pas l’historique",+ "History kept on the signer’s copy": "L’historique est conservé dans la copie du signataire",+ "The history has changed since you signed — a Snapshot or a trim does this": "L’historique a changé depuis votre signature — un instantané ou un élagage en est la cause",+ "The history you signed is missing from this document": "L’historique que vous avez signé est absent de ce document",}diff --git a/type/src/i18n/it.ts b/type/src/i18n/it.tsindex f6414a4e..4a67a7c9 100644--- a/type/src/i18n/it.ts+++ b/type/src/i18n/it.ts@@ -465,4 +465,14 @@ export const it: Catalog = {"Leave version history out": "Escludi la cronologia delle versioni","Versions include text that was deleted. This file keeps them either way.": "Le versioni includono testo eliminato. Questo file le conserva in ogni caso.","Save invite…": "Salva l’invito…",+ "✓ 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",+ "This copy doesn’t include the history": "Questa copia non include la cronologia",+ "History kept on the signer’s copy": "La cronologia è conservata nella copia del firmatario",+ "The history has changed since you signed — a Snapshot or a trim does this": "La cronologia è cambiata dopo la tua firma: un’istantanea o una riduzione lo causano",+ "The history you signed is missing from this document": "La cronologia che hai firmato manca da questo documento",}diff --git a/type/src/i18n/ja.ts b/type/src/i18n/ja.tsindex b5818452..dfea0d45 100644--- a/type/src/i18n/ja.ts+++ b/type/src/i18n/ja.ts@@ -465,4 +465,14 @@ export const ja: Catalog = {"Leave version history out": "バージョン履歴を含めない","Versions include text that was deleted. This file keeps them either way.": "バージョンには削除された本文も含まれます。このファイルにはどちらの場合も残ります。","Save invite…": "招待を保存…",+ "✓ 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": "履歴は署名時のものと一致しています",+ "This copy doesn’t include the history": "このコピーには履歴が含まれていません",+ "History kept on the signer’s copy": "履歴は署名者のコピーに保持されています",+ "The history has changed since you signed — a Snapshot or a trim does this": "署名後に履歴が変更されています — スナップショットや履歴の整理でこうなります",+ "The history you signed is missing from this document": "署名した履歴がこの文書にありません",}diff --git a/type/src/i18n/packed.ts b/type/src/i18n/packed.tsindex 048d2688..34c19553 100644--- a/type/src/i18n/packed.ts+++ b/type/src/i18n/packed.ts@@ -142,6 +142,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Headings": ["見出し","标题","標題","Títulos","Titres","Überschriften","Titoli","Títulos"],"Headings appear here.": ["見出しはここに表示されます。","标题会显示在这里。","標題會顯示在這裡。","Los títulos aparecen aquí.","Les titres apparaissent ici.","Überschriften erscheinen hier.","I titoli appaiono qui.","Os títulos aparecem aqui."],"Hide comments": ["コメントを非表示","隐藏批注","隱藏註解","Ocultar comentarios","Masquer les commentaires","Kommentare ausblenden","Nascondi commenti","Ocultar comentários"],+ "History kept on the signer’s copy": ["履歴は署名者のコピーに保持されています","历史记录保存在签名者的副本中","歷程保存在簽署者的副本中","El historial se conserva en la copia del firmante","L’historique est conservé dans la copie du signataire","Der Verlauf liegt in der Kopie des Unterzeichners","La cronologia è conservata nella copia del firmatario","O histórico fica na cópia de quem assinou"],+ "History matches what was signed": ["履歴は署名時のものと一致しています","历史记录与签名时一致","歷程與簽署時一致","El historial coincide con lo firmado","L’historique correspond à ce qui a été signé","Der Verlauf stimmt mit dem Signierten überein","La cronologia corrisponde a quanto firmato","O histórico corresponde ao que foi assinado"],"How you view a document, not a change to it — nothing here is saved into the file.": ["文書の見え方の設定であり、文書自体を変更するものではありません — ここでの設定はファイルに保存されません。","这只是文档的查看方式,不是对文档的更改——此处的设置不会保存到文件中。","這只是文件的檢視方式,不是對文件的變更 — 這裡的設定不會存進檔案。","Es solo cómo ves el documento, no un cambio en él: nada de esto se guarda en el archivo.","C'est la façon dont vous visualisez le document, pas une modification de celui-ci — rien ici n'est enregistré dans le fichier.","Dies betrifft nur die Ansicht des Dokuments, keine Änderung daran – nichts davon wird in der Datei gespeichert.","È solo il modo in cui visualizzi il documento, non una modifica ad esso: nulla qui viene salvato nel file.","Como você vê um documento, não uma alteração nele — nada aqui é salvo no arquivo."],"Import": ["インポート","导入","匯入","Importar","Importer","Importieren","Importa","Importar"],"Import BibTeX": ["BibTeX をインポート","导入 BibTeX","匯入 BibTeX","Importar BibTeX","Importer BibTeX","BibTeX importieren","Importa BibTeX","Importar BibTeX"],@@ -364,6 +366,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"The document is the interchange unit: hand this JSON to an AI, get one back, and paste it in. `window.bento` exposes the same thing to scripts.": ["文書そのものが交換単位です — この JSON を AI に渡して受け取った JSON を貼り付けてください。スクリプトからは `window.bento` で同じものを利用できます。","文档本身就是交换单元:把这段 JSON 交给 AI,拿到返回结果后粘贴回来即可。脚本可通过 `window.bento` 使用同样的接口。","文件本身就是交換單元:把這段 JSON 交給 AI,拿到回傳結果後貼回來即可。指令碼可透過 `window.bento` 使用相同的介面。","El documento es la unidad de intercambio: entrega este JSON a una IA, recibe otro y pégalo aquí. `window.bento` expone lo mismo a los scripts.","Le document est l'unité d'échange : donnez ce JSON à une IA, récupérez-en un et collez-le ici. `window.bento` expose la même chose aux scripts.","Das Dokument ist die Austauscheinheit: Geben Sie dieses JSON an eine KI weiter, holen Sie eines zurück und fügen Sie es ein. `window.bento` stellt Skripten dasselbe bereit.","Il documento è l'unità di interscambio: consegna questo JSON a un'IA, riceverne uno e incollalo qui. `window.bento` espone la stessa cosa agli script.","O documento é a unidade de intercâmbio: entregue este JSON a uma IA, receba outro de volta e cole-o aqui. `window.bento` expõe a mesma coisa para scripts."],"The first paragraph already starts a page": ["最初の段落はすでにページの先頭です","第一段已经是新的一页","第一段已經是新的一頁","El primer párrafo ya empieza una página","Le premier paragraphe commence déjà une page","Der erste Absatz beginnt bereits eine Seite","Il primo paragrafo inizia già una pagina","O primeiro parágrafo já inicia uma página"],"The formula at the caret. TeX-like source; the document stores the source, never the picture.": ["カーソル位置の数式です。TeX 風のソースであり、文書には画像ではなくソースが保存されます。","光标处的公式。使用类 TeX 语法;文档保存的是源代码,而不是图片。","游標處的公式。使用類 TeX 語法;文件儲存的是原始碼,而非圖片。","La fórmula en el cursor. Fuente similar a TeX; el documento guarda el código fuente, nunca la imagen.","La formule au niveau du curseur. Source de type TeX ; le document stocke la source, jamais l'image.","Die Formel an der Cursorposition. TeX-ähnlicher Quelltext; das Dokument speichert den Quelltext, niemals das Bild.","La formula alla posizione del cursore. Sorgente in stile TeX; il documento memorizza il sorgente, mai l'immagine.","A fórmula no cursor. Código semelhante a TeX; o documento armazena o código-fonte, nunca a imagem."],+ "The history has changed since you signed — a Snapshot or a trim does this": ["署名後に履歴が変更されています — スナップショットや履歴の整理でこうなります","签名后历史记录已更改——快照或裁剪历史会导致这种情况","簽署後歷程已變更——快照或修剪歷程會導致這種情況","El historial ha cambiado desde que firmó: una instantánea o un recorte lo provocan","L’historique a changé depuis votre signature — un instantané ou un élagage en est la cause","Der Verlauf hat sich seit Ihrer Signatur geändert — eine Momentaufnahme oder ein Kürzen bewirkt das","La cronologia è cambiata dopo la tua firma: un’istantanea o una riduzione lo causano","O histórico mudou desde que você assinou — um instantâneo ou um corte faz isso"],+ "The history you signed is missing from this document": ["署名した履歴がこの文書にありません","您签名的历史记录不在此文档中","您簽署的歷程不在此文件中","El historial que firmó no está en este documento","L’historique que vous avez signé est absent de ce document","Der von Ihnen signierte Verlauf fehlt in diesem Dokument","La cronologia che hai firmato manca da questo documento","O histórico que você assinou não está neste documento"],"The table of contents needs the core render hook.": ["目次にはコアのレンダーフックが必要です。","目录需要核心渲染钩子。","目錄需要核心渲染掛鉤。","La tabla de contenido necesita el gancho de renderizado principal.","La table des matières nécessite le point d'ancrage de rendu principal.","Das Inhaltsverzeichnis benötigt den zentralen Render-Hook.","Il sommario richiede l'hook di rendering principale.","O sumário precisa do hook de renderização do núcleo."],"The theme is yours, not the document’s — it is remembered in this browser and never saved into the file. The PAGE stays white in both, because paper is white and somebody proofing a contract at midnight still has to see what will print.": ["テーマはあなた自身のものであり、文書のものではありません — このブラウザに記憶されるだけで、ファイルには決して保存されません。ページ自体はどちらのテーマでも白のままです。紙は白いものであり、深夜に契約書を校正する人にも印刷結果がそのまま見える必要があるからです。","主题是你个人的设置,不是文档的一部分——它只保存在此浏览器中,绝不会写入文件。无论哪种主题,页面本身都保持白色,因为纸张就是白色的,深夜校对合同的人仍需要看清打印后的样子。","主題是你個人的設定,不是文件的一部分 — 它只保存在這個瀏覽器中,絕不會寫入檔案。無論哪種主題,頁面本身都維持白色,因為紙張就是白色的,深夜校對合約的人仍需要看清楚列印後的樣子。","El tema es tuyo, no del documento: se recuerda en este navegador y nunca se guarda en el archivo. La PÁGINA sigue siendo blanca en ambos casos, porque el papel es blanco y quien revisa un contrato a medianoche aún debe ver lo que se imprimirá.","Le thème vous appartient, pas au document — il est mémorisé dans ce navigateur et jamais enregistré dans le fichier. La PAGE reste blanche dans les deux cas, car le papier est blanc et quelqu'un qui relit un contrat à minuit doit quand même voir ce qui sera imprimé.","Das Design gehört Ihnen, nicht dem Dokument – es wird in diesem Browser gemerkt und nie in der Datei gespeichert. Die SEITE bleibt in beiden Fällen weiß, denn Papier ist weiß, und wer mitten in der Nacht einen Vertrag prüft, muss trotzdem sehen, was gedruckt wird.","Il tema è tuo, non del documento: viene ricordato in questo browser e non viene mai salvato nel file. La PAGINA resta bianca in entrambi i casi, perché la carta è bianca e chi rilegge un contratto a mezzanotte deve comunque vedere cosa verrà stampato.","O tema é seu, não do documento — ele é lembrado neste navegador e nunca salvo no arquivo. A PÁGINA permanece branca em ambos, porque o papel é branco e quem revisa um contrato à meia-noite ainda precisa ver o que será impresso."],"Theme": ["テーマ","主题","主題","Tema","Thème","Design","Tema","Tema"],@@ -374,6 +378,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": ["このブラウザはファイルへの書き戻しができないため、保存のたびに新しいコピーが作成されます。パソコン版の Chrome や Edge ならその場に保存できます。","此浏览器无法回写到文件,因此每次保存都会生成新副本。电脑版 Chrome 和 Edge 可以直接原地保存。","這個瀏覽器無法回寫至檔案,因此每次儲存都會產生新副本。電腦版 Chrome 和 Edge 可以直接原地儲存。","Este navegador no puede reescribir el archivo, así que cada vez que guardas se crea una copia nueva. Chrome y Edge en un ordenador pueden guardar en el mismo archivo.","Ce navigateur ne peut pas réécrire le fichier, donc chaque enregistrement crée une nouvelle copie. Chrome et Edge sur ordinateur peuvent enregistrer sur place.","Dieser Browser kann die Datei nicht zurückschreiben, daher erstellt jedes Speichern eine neue Kopie. Chrome und Edge auf einem Computer können direkt speichern.","Questo browser non può riscrivere il file, quindi ogni salvataggio crea una nuova copia. Chrome ed Edge su computer possono salvare direttamente nel file.","Este navegador não consegue escrever de volta no arquivo, então cada vez que você salva ele cria uma nova cópia. O Chrome e o Edge em um computador conseguem salvar no lugar."],"This browser will download each file separately — expect one prompt per row.": ["このブラウザーはファイルを 1 つずつダウンロードします — 行ごとに確認が表示されます。","此浏览器会分别下载每个文件——每一行都会出现一次提示。","此瀏覽器會分別下載每個檔案——每一列都會出現一次提示。","Este navegador descargará cada archivo por separado: habrá un aviso por fila.","Ce navigateur téléchargera chaque fichier séparément — attendez-vous à une invite par ligne.","Dieser Browser lädt jede Datei einzeln herunter – rechnen Sie mit einer Abfrage pro Zeile.","Questo browser scaricherà ogni file separatamente: attendi una richiesta per riga.","Este navegador vai baixar cada arquivo separadamente — espere um aviso por linha."],"This build cannot render captions yet — apply the core patch listed at the top of xref.ts": ["このビルドではまだキャプションを描画できません — xref.ts の先頭に記載されているコアパッチを適用してください","此构建版本尚不能渲染题注——请应用 xref.ts 顶部列出的核心补丁","此建置版本尚無法渲染題注 — 請套用 xref.ts 頂端列出的核心修補","Esta compilación aún no puede renderizar títulos: aplica el parche del núcleo indicado al principio de xref.ts","Cette version ne peut pas encore afficher les légendes — appliquez le correctif du noyau indiqué en haut de xref.ts","Dieser Build kann Beschriftungen noch nicht rendern – wenden Sie den Kern-Patch oben in xref.ts an","Questa build non può ancora renderizzare le didascalie: applica la patch del core indicata in cima a xref.ts","Esta versão ainda não consegue renderizar legendas — aplique o patch do núcleo listado no topo de xref.ts"],+ "This copy doesn’t include the history": ["このコピーには履歴が含まれていません","此副本不包含历史记录","此副本不包含歷程","Esta copia no incluye el historial","Cette copie n’inclut pas l’historique","Diese Kopie enthält den Verlauf nicht","Questa copia non include la cronologia","Esta cópia não inclui o histórico"],"This copy includes the document’s version history.": ["このコピーには、文書のバージョン履歴が含まれます。","此副本包含文档的版本历史。","此副本包含文件的版本歷程。","Esta copia incluye el historial de versiones del documento.","Cette copie inclut l’historique des versions du document.","Diese Kopie enthält den Versionsverlauf des Dokuments.","Questa copia include la cronologia delle versioni del documento.","Esta cópia inclui o histórico de versões do documento."],"This document has no live session to follow": ["この文書には追従できるライブセッションがありません","此文档没有可跟随的实时协作","這份文件沒有可跟隨的即時協作","Este documento no tiene ninguna sesión en directo que seguir","Ce document n'a aucune session en direct à suivre","Dieses Dokument hat keine Live-Sitzung, der man folgen könnte","Questo documento non ha una sessione in diretta da seguire","Este documento não tem sessão ao vivo para acompanhar"],"This document has no sources yet. Import some BibTeX first.": ["この文書にはまだ出典がありません。まず BibTeX をインポートしてください。","本文档尚无来源。请先导入一些 BibTeX。","本文件尚無來源。請先匯入一些 BibTeX。","Este documento aún no tiene fuentes. Importa primero algo de BibTeX.","Ce document n'a pas encore de sources. Importez d'abord du BibTeX.","Dieses Dokument hat noch keine Quellen. Importieren Sie zuerst etwas BibTeX.","Questo documento non ha ancora fonti. Importa prima del BibTeX.","Este documento ainda não tem fontes. Importe algum BibTeX primeiro."],@@ -432,6 +437,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"You": ["あなた","你","你","Tú","Vous","Sie","Tu","Você"],"Your name": ["名前","你的姓名","你的名稱","Tu nombre","Votre nom","Ihr Name","Il tuo nome","Seu nome"],"Your name, so your comments are attributed": ["コメントの記名に使う名前","你的姓名,用于标注你的批注","你的名稱,用於標示你的註解","Tu nombre, para atribuir tus comentarios","Votre nom, pour attribuer vos commentaires","Ihr Name, damit Ihre Kommentare zugeordnet werden können","Il tuo nome, per attribuire i tuoi commenti","Seu nome, para que seus comentários sejam atribuídos"],+ "after {name}": ["{name} の後","在 {name} 之后","在 {name} 之後","después de {name}","après {name}","nach {name}","dopo {name}","depois de {name}"],"bento/type is MIT-licensed. Line breaking uses the Knuth–Plass algorithm via tex-linebreak; hyphenation patterns are Liang’s. Everything runs in this file — nothing is fetched, and nothing is sent anywhere.": ["bento/type は MIT ライセンスです。改行処理は tex-linebreak 経由の Knuth–Plass アルゴリズムを使用し、ハイフネーションパターンは Liang のものです。すべてこのファイル内で完結しており、何も取得されず、どこにも送信されません。","bento/type 采用 MIT 许可证。断行使用 tex-linebreak 提供的 Knuth–Plass 算法;连字规则采用 Liang 的模式。一切都在此文件内运行——不会获取任何内容,也不会向任何地方发送数据。","bento/type 採用 MIT 授權。斷行使用 tex-linebreak 提供的 Knuth–Plass 演算法;斷字規則採用 Liang 的樣式。一切都在此檔案內運作 — 不會擷取任何內容,也不會向任何地方傳送資料。","bento/type tiene licencia MIT. El salto de línea usa el algoritmo Knuth–Plass a través de tex-linebreak; los patrones de guionización son los de Liang. Todo funciona en este archivo: no se obtiene nada externo ni se envía nada a ningún sitio.","bento/type est sous licence MIT. La coupure de ligne utilise l'algorithme de Knuth–Plass via tex-linebreak ; les motifs de césure sont ceux de Liang. Tout s'exécute dans ce fichier — rien n'est récupéré, rien n'est envoyé où que ce soit.","bento/type steht unter der MIT-Lizenz. Der Zeilenumbruch verwendet den Knuth–Plass-Algorithmus über tex-linebreak; die Trennmuster stammen von Liang. Alles läuft in dieser Datei – nichts wird abgerufen und nichts wird irgendwohin gesendet.","bento/type è concesso in licenza MIT. L'interruzione di riga usa l'algoritmo di Knuth–Plass tramite tex-linebreak; i modelli di sillabazione sono quelli di Liang. Tutto viene eseguito in questo file: non viene recuperato né inviato nulla altrove.","O bento/type é licenciado sob MIT. A quebra de linhas usa o algoritmo de Knuth–Plass via tex-linebreak; os padrões de hifenização são os de Liang. Tudo é executado neste arquivo — nada é buscado e nada é enviado a lugar nenhum."],"cited {n} times": ["{n} 回引用","已被引用 {n} 次","已被引用 {n} 次","citada {n} veces","citée {n} fois","{n} Mal zitiert","citata {n} volte","citado {n} vezes"],"default": ["既定","默认","預設","predeterminado","par défaut","Standard","predefinito","padrão"],@@ -472,4 +478,8 @@ 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 e428e283..ca4f563e 100644--- a/type/src/i18n/pt.ts+++ b/type/src/i18n/pt.ts@@ -476,4 +476,14 @@ export const pt: Catalog = {"Leave version history out": "Deixar de fora o histórico de versões","Versions include text that was deleted. This file keeps them either way.": "As versões incluem texto que foi apagado. Este arquivo as mantém de qualquer forma.","Save invite…": "Salvar convite…",+ "✓ 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",+ "This copy doesn’t include the history": "Esta cópia não inclui o histórico",+ "History kept on the signer’s copy": "O histórico fica na cópia de quem assinou",+ "The history has changed since you signed — a Snapshot or a trim does this": "O histórico mudou desde que você assinou — um instantâneo ou um corte faz isso",+ "The history you signed is missing from this document": "O histórico que você assinou não está neste documento",}diff --git a/type/src/i18n/zh-Hans.ts b/type/src/i18n/zh-Hans.tsindex 95340f0e..1104e235 100644--- a/type/src/i18n/zh-Hans.ts+++ b/type/src/i18n/zh-Hans.ts@@ -465,4 +465,14 @@ export const zhHans: Catalog = {"Leave version history out": "不包含版本历史","Versions include text that was deleted. This file keeps them either way.": "版本中包含已删除的文字。无论如何,此文件都会保留它们。","Save invite…": "保存邀请…",+ "✓ 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": "历史记录与签名时一致",+ "This copy doesn’t include the history": "此副本不包含历史记录",+ "History kept on the signer’s copy": "历史记录保存在签名者的副本中",+ "The history has changed since you signed — a Snapshot or a trim does this": "签名后历史记录已更改——快照或裁剪历史会导致这种情况",+ "The history you signed is missing from this document": "您签名的历史记录不在此文档中",}diff --git a/type/src/i18n/zh-Hant.ts b/type/src/i18n/zh-Hant.tsindex bf0a8e62..f6a06b40 100644--- a/type/src/i18n/zh-Hant.ts+++ b/type/src/i18n/zh-Hant.ts@@ -465,4 +465,14 @@ export const zhHant: Catalog = {"Leave version history out": "不包含版本歷程","Versions include text that was deleted. This file keeps them either way.": "版本中包含已刪除的文字。無論如何,此檔案都會保留它們。","Save invite…": "儲存邀請…",+ "✓ 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": "歷程與簽署時一致",+ "This copy doesn’t include the history": "此副本不包含歷程",+ "History kept on the signer’s copy": "歷程保存在簽署者的副本中",+ "The history has changed since you signed — a Snapshot or a trim does this": "簽署後歷程已變更——快照或修剪歷程會導致這種情況",+ "The history you signed is missing from this document": "您簽署的歷程不在此文件中",}diff --git a/type/src/main.ts b/type/src/main.tsindex 09c52dab..3038f194 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 } from './canon.ts';+import { sign as signDoc, verifyChain, 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).@@ -816,6 +816,16 @@ async function getKey(): Promise<CryptoKeyPair> {deviceKey = k;return k;}+/** This device's public key, or null if it has never signed. NEVER mints a+ * key: painting the Signatures panel must not create a signing key as a side+ * effect. (getKey only mints when nothing is saved, and this returns first.) */+async function devicePub(): Promise<string | null> {+ if (deviceKey) return exportPub(deviceKey);+ let saved: string | null = null;+ try { saved = localStorage.getItem(KEYSTORE); } catch { /* storage blocked */ }+ if (!saved) return null;+ return exportPub(await getKey());+}const fingerprint = (pub: string) =>pub.replace(/[^a-zA-Z0-9]/g, '').slice(0, 24).match(/.{1,4}/g)!.join(' ').toUpperCase();@@ -826,6 +836,13 @@ document.getElementById('sign')!.addEventListener('click', async () => {if (!name) return;try { localStorage.setItem('bento-type-name', name); } catch { /* ignore */ }const key = await getKey();+ // The history commitment is salted by the document's own historySalt. The+ // first signature mints it, in the document, and it is never replaced: every+ // later signature commits to history under the same salt (canon.ts).+ if (!store.doc.historySalt) {+ const salt = newHistorySalt();+ store.commit(d => { d.historySalt = salt; });+ }const prev = store.doc.signatures[store.doc.signatures.length - 1] ?? null;const entry = await signDoc(store.doc, key, { name, prev });entry.at = new Date().toISOString();@@ -834,6 +851,17 @@ document.getElementById('sign')!.addEventListener('click', async () => {toast('Signed');});+/** Each history line as a LITERAL t() call, so the i18n sweep finds them. */+function historyLabel(line: HistoryLine): string {+ switch (line) {+ case 'matches': return t('History matches what was signed');+ case 'not-included': return t('This copy doesn’t include the history');+ case 'elsewhere': return t('History kept on the signer’s copy');+ case 'changed': return t('The history has changed since you signed — a Snapshot or a trim does this');+ case 'missing': return t('The history you signed is missing from this document');+ }+}+async function paintSigs() {const box = document.getElementById('sigsPanel')!;const sigs = store.doc.signatures;@@ -848,19 +876,30 @@ async function paintSigs() {return;}const res = await verifyChain(store.doc, sigs);+ const mine = await devicePub();sigs.forEach((s, i) => {const r = res.entries[i];const card = el('div', 't-card');- const state = r.ok && r.linked ? `<span class="t-ok">✓ valid</span>`+ // 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'- ? `<span class="t-bad">✕ the document has changed since this was signed</span>`- : !r.linked ? `<span class="t-warn">⚠ not linked to the previous signature</span>`- : `<span class="t-bad">✕ invalid signature</span>`);+ ? `<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.+ const h = historyDisplay(r.history, mine !== null && s.pub === mine);+ const label = historyLabel(h.line);+ const hist = h.tone === 'neutral'+ ? `<div class="t-note">${esc(label)}</div>`+ : `<div class="t-note"><span class="${h.tone === 'ok' ? 't-ok' : 't-warn'}">${esc(label)}</span></div>`;card.innerHTML =`<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 ? ` · after ${esc(sigs[i - 1].name || 'previous')}` : ''}</div>`;+ `${i > 0 ? ` · ${esc(t('after {name}', { name: sigs[i - 1].name || 'previous' }))}` : ''}</div>` ++ hist;box.appendChild(card);});// two names on one key is exactly what a signature cannot provediff --git a/type/src/model.ts b/type/src/model.tsindex 1b8386e5..79d83228 100644--- a/type/src/model.ts+++ b/type/src/model.ts@@ -225,8 +225,12 @@ export interface Signature {pub: string;/** self-asserted, shown beside the signature and NOT proof of anything */name: string;- /** digest of the canonical content at the moment of signing */+ /** digest of the canonical CONTENT at the moment of signing (canon.ts SIGNED_EXCLUDE) */content: string;+ /** salted commitment to the history at the moment of signing (canon.ts+ * 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 */prev: string;sig: string;@@ -325,6 +329,9 @@ export interface TypeDoc {*/optical?: boolean;revisions: Revision[];+ /** 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[];/*** Is the document recording edits as tracked changes?@@ -794,6 +801,10 @@ export function parseDoc(raw: string): ParseResult {signatures: Array.isArray(json.signatures) ? json.signatures as Signature[] : [],};if (Object.keys(styles).length) doc.styles = styles; else delete doc.styles;+ // A salt is 16 bytes, base64url without padding: exactly 22 characters. Anything+ // else is not a salt — dropped, so its signatures report the history MISSING+ // rather than being checked against something that only looks like a salt.+ if (typeof json.historySalt !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(json.historySalt)) delete doc.historySalt;// only `false` is a value; anything else — including a junk one — is the defaultif (json.optical === false) doc.optical = false; else delete doc.optical;if (typeof json.docId !== 'string' || !json.docId) repaired.push('minted a missing docId');diff --git a/type/src/sync/crdt.ts b/type/src/sync/crdt.tsindex aacefd75..6dc3ac71 100644--- a/type/src/sync/crdt.ts+++ b/type/src/sync/crdt.ts@@ -65,15 +65,14 @@ import type { DocShape } from '../../../kernel/src/sync/crdt.ts';* in the room, readers included, as they did before binding.* Still a whole `comments` register, so the wire is byte-* identical to 1.2.7's and a mixed-version room converges.- * signatures NOT a ruling — this preserves today's behaviour. Signatures- * are 'history' only as an interim (they leave view-only copies- * until signing commits to the history rather than containing- * it); before binding they synced like any other key. Once they- * return to 'content', historySyncKeys refuses them here at- * COMPILE time, so this line cannot be forgotten.- * `revisions` never syncs: each replica keeps its own timeline (skipDoc).+ * Signatures are CONTENT (canon.ts v2 signs a commitment to the history, not the+ * history), so they sync as content without being named here. They were listed+ * while they were 'history' as an interim, and historySyncKeys refused them the+ * moment they became content — at compile time, which is what removed them.+ * `revisions` and `historySalt` never sync: each replica keeps its own timeline+ * and its own salt (revisions is skipDoc; historySalt is history, not listed).*/-const SYNC_HISTORY = ['comments', 'signatures'] as const;+const SYNC_HISTORY = ['comments'] as const;export const TYPE_SHAPE: DocShape = shape('body', null, 'text', ['footnotes'],TYPE_FIELDS, historySyncKeys(TYPE_FIELDS, SYNC_HISTORY));