Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel/sync: doc-level allowlist when an app binds a field-class map (#683)

nyblnet789f23616ddd
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3b959906..c99c7ead 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2276,6 +2276,14 @@ jobs:
# mergeSnapshot), and no prototype-shaped name reaches any object.
run: node --no-warnings scripts/test-sync-inbound-docfields.ts
+ - name: Doc-level sync allowlist (field-class map)
+ # The other half of the never-synced set: when an app binds a class map,
+ # a peer emits only content-class doc keys and ignores non-content ones
+ # inbound, whatever the sender claims; an unknown key (a newer build's
+ # field) is applied but never re-emitted. With no map it is byte-for-byte
+ # the shipped denylist. skipDoc is the floor under both.
+ run: node scripts/test-sync-allowlist.ts
+
- name: the spaces binding of the sync session
# Only what bento/spaces answers DIFFERENTLY, because three of the five
# host answers are not slides' answers and each one is invisible until
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 60c90c5e..80b52d7a 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -10276,3 +10276,23 @@ each level: the library, the table, the CLI and the page's rendering. A
first mutation run showed the library's own default was untested, because
every caller passed the option, so a library-level row was added.
+
+## 2026-10-11 — Doc-level sync allowlist, and a residual for reclassified keys
+
+When a shape binds a field-class map, the sync engine (kernel/src/sync/crdt.ts)
+syncs doc-level keys by allowlist on top of the shipped `skipDoc` denylist: a
+peer emits only content-class keys and ignores non-content keys inbound, and an
+unknown key (one a newer build added) is applied but never re-emitted
+(`APPLY_UNKNOWN_DOC_KEYS = true` — option (a)). `skipDoc` is the floor under
+both directions and beats a content classification, verified by
+`scripts/test-sync-allowlist.ts` (a fixture classing skipDoc keys as content,
+with a red mutation per floor). With no map the engine is byte-identical to the
+shipped denylist, so this is dormant until an app opts in.
+
+RESIDUAL (security): because an unknown key is applied under option (a), a later
+build that newly PROTECTS a once-unknown field — reclassifies it from unknown to
+a non-content class — must treat that field's pre-existing value as UNTRUSTED. A
+peer could have planted it over the wire while the field was still unknown-and-
+applied. The new build stops syncing it, but the value already in the file is
+not evidence of anything; validate or discard it on adoption rather than trust
+it because it is "already there".
diff --git a/kernel/src/sync/crdt.ts b/kernel/src/sync/crdt.ts
index 1723c245..a7406e28 100644
--- a/kernel/src/sync/crdt.ts
+++ b/kernel/src/sync/crdt.ts
@@ -43,10 +43,23 @@
* this and nothing more: a container of parented nodes, each with an `id`,
* under two keys named by the DocShape below. Every app's model satisfies it.
*/
+import type { FieldClass } from '../docfields.ts'
+
type BentoDoc = object
type Slide = { id: string }
type SlideElement = { id: string }
+/**
+ * THE unknown-key switch. A doc-level key absent from the local app's class map
+ * (a field a NEWER build added) — when one arrives in an op or a snapshot, is it
+ * applied (true: a newer build's content survives an older peer, and lands in
+ * this replica's own file) or ignored (false: fail closed — an unknown field
+ * never enters this replica's doc from the room)? Either way this replica never
+ * EMITS an unknown key (diff is content-class only). One line, by design: the
+ * ruling between the two goes here and nowhere else.
+ */
+const APPLY_UNKNOWN_DOC_KEYS = true
+
// ---------------------------------------------------------------------------
// document shape
// ---------------------------------------------------------------------------
@@ -122,6 +135,20 @@ export interface DocShape {
* BODY while both references survive, leaving a marker pointing at nothing.
*/
readonly maps: ReadonlySet<string>
+ /**
+ * The app's field-class map (docfields.ts), when the app has adopted one. With
+ * it, the engine syncs doc-level keys by ALLOWLIST — the sender rule:
+ * - a peer EMITS only keys its own map classes 'content' (plus `maps`), on
+ * every path it mints: the op diff, its snapshot doc + state, and the
+ * stamped SyncStateJSON. An unknown key — from a newer file opened here,
+ * or applied from the wire — is never emitted by this peer.
+ * - a peer IGNORES any incoming key its map knows as non-content (identity,
+ * mode, capability, history) whatever the sender claims, and applies
+ * unknown keys per APPLY_UNKNOWN_DOC_KEYS.
+ * Without it, behaviour is the shipped denylist (skipDoc only). skipDoc keys
+ * are never emitted and never applied in either mode.
+ */
+ readonly classes?: Readonly<Record<string, FieldClass>>
}
/** Derived, never authored: the volatile set is the same for every app apart
@@ -131,10 +158,12 @@ export const shape = (
children: string | null,
text = 'html',
maps: readonly string[] = [],
+ classes?: Readonly<Record<string, FieldClass>>,
): DocShape => {
- // 'revisions'/'trail' are in-file version history (docfields.ts class 'history'):
- // file-local, never synced — each replica keeps its own timeline. (PR2 turns
- // skipDoc into a content-class allowlist so unknown fields don't sync either.)
+ // file-local, never synced — each replica keeps its own timeline. (When an app
+ // passes `classes`, PR2 ALSO refuses any non-content / unknown doc key inbound
+ // and emits only content keys — see DocShape.classes; skipDoc is the floor that
+ // holds whether or not an app has adopted a class map.)
// docId / readonly / template are identity and file modes: never synced, and —
// because skipDoc is ALSO the receive filter (applySet, mergeSnapshot) — never
// adopted from a peer either. A remote op can't rewrite a deck's identity,
@@ -144,7 +173,8 @@ export const shape = (
const skipDoc = new Set([parents, 'modified', 'collab', 'format', 'version', 'policy', 'revisions', 'trail', 'docId', 'readonly', 'template'])
// `assets` and `blobs` are per-key for every app and always have been —
// unioned rather than defaulted so an app naming its own map cannot drop them.
- return { parents, children, text, skipDoc, maps: new Set(['assets', 'blobs', ...maps]) }
+ const out: DocShape = { parents, children, text, skipDoc, maps: new Set(['assets', 'blobs', ...maps]) }
+ return classes ? { ...out, classes } : out
}
/** The parent array of a document, and the child array of a parent. Indexed
@@ -565,6 +595,60 @@ export class SyncEngine {
this.S = shape
}
+ // --- the doc-level sender rule (see DocShape.classes) ----------------------
+
+ /** May THIS peer emit doc-level key `k` (a top-level field, or a map's field
+ * name) on any path it mints? Content-class keys and per-key maps only; never
+ * a skipDoc key, a known non-content key, or an UNKNOWN key. */
+ outboundDocKey(k: string): boolean {
+ if (this.S.skipDoc.has(k)) return false
+ if (this.S.maps.has(k)) return true
+ return !this.S.classes || this.S.classes[k] === 'content'
+ }
+
+ /** Must THIS peer ignore an incoming value for doc-level key `k` (already
+ * resolved through docField)? Always for skipDoc — the never-synced set:
+ * capability, identity, file modes, history, volatile/encoding fields — so a
+ * remote peer or a local page on the channel can't replace the room keys,
+ * rewrite docId, or flip readonly/template in a victim's open deck (which the
+ * next save would write to the file). Also for a key an adopted class map
+ * knows as non-content; for an unknown key, per APPLY_UNKNOWN_DOC_KEYS. With
+ * no class map this is exactly the shipped skipDoc refusal. */
+ private ignoreInboundDocKey(k: string): boolean {
+ if (this.S.skipDoc.has(k)) return true
+ if (this.S.maps.has(k) || !this.S.classes) return false
+ const c = this.S.classes[k]
+ if (c === undefined) return !APPLY_UNKNOWN_DOC_KEYS
+ return c !== 'content'
+ }
+
+ /** The top-level field a doc-level register/op key addresses: `assets.x` →
+ * `assets` for a per-key map, else the key itself. */
+ private docField(k: string): string {
+ return this.mapKey(k)?.[0] ?? k
+ }
+
+ /** `regs` with every doc-level register this peer may not emit removed —
+ * the stamped / snapshot form of the state. Key order is preserved. */
+ private outboundRegs(): Record<string, Reg> {
+ const out: Record<string, Reg> = {}
+ for (const [rk, r] of Object.entries(this.regs)) {
+ if (rk.startsWith(`${DOC_NODE} `) && !this.outboundDocKey(this.docField(rk.slice(DOC_NODE.length + 1)))) continue
+ out[rk] = r
+ }
+ return out
+ }
+
+ /** A shallow copy of `doc` holding only the top-level keys this peer may emit
+ * (plus the structural container), for a snapshot frame: the doc rides beside
+ * the state, so a value the state no longer carries must not travel either. */
+ outboundDoc<T extends object>(doc: T): T {
+ const src = doc as Record<string, unknown>
+ const out: Record<string, unknown> = {}
+ for (const k of Object.keys(src)) if (k === this.S.parents || this.outboundDocKey(k)) out[k] = src[k]
+ return out as T
+ }
+
/** actors with buffered out-of-order ops → catch-up should be requested */
get gappedActors(): string[] {
return Object.keys(this.gap).filter((a) => this.gap[a].length)
@@ -610,7 +694,9 @@ export class SyncEngine {
v: SYNC_V,
lamport: this.lamport,
vv: this.vv,
- regs: this.regs,
+ // the sender rule: a stamped/snapshot state never carries a doc-level
+ // register this peer may not emit (non-content, skipDoc, or unknown)
+ regs: this.outboundRegs(),
pos: this.pos,
births: this.births,
tombs: this.tombs,
@@ -635,7 +721,15 @@ export class SyncEngine {
s.lamport = j.lamport
s.vv = j.vv ?? {}
s.seq = s.vv[actor] ?? 0
- s.regs = j.regs ?? {}
+ // Loaded state follows the same rule as the wire: a doc-level register this
+ // peer would IGNORE inbound (skipDoc, or a key its map knows as non-content)
+ // is dropped, so state stamped before the allowlist can't replay a history /
+ // mode / capability field. Exact by key, so no SYNC_V bump is needed.
+ s.regs = {}
+ for (const [rk, r] of Object.entries(j.regs ?? {})) {
+ if (rk.startsWith(`${DOC_NODE} `) && s.ignoreInboundDocKey(s.docField(rk.slice(DOC_NODE.length + 1)))) continue
+ s.regs[rk] = r
+ }
s.pos = j.pos ?? {}
s.births = j.births ?? {}
s.tombs = j.tombs ?? {}
@@ -686,11 +780,13 @@ export class SyncEngine {
}
// ---- doc-level props
- const SKIP_DOC = this.S.skipDoc
const b = before as unknown as Record<string, unknown>
const a = after as unknown as Record<string, unknown>
for (const k of new Set([...Object.keys(b), ...Object.keys(a)])) {
- if (SKIP_DOC.has(k)) continue
+ // The sender rule: only content-class keys (or per-key maps) are diffed.
+ // A key this build doesn't classify is never emitted — and so a field it
+ // doesn't know can never be DELETED by it either: silence is not a del.
+ if (!this.outboundDocKey(k)) continue
// `assets` and `blobs` are per-KEY registers, not whole-map ones, so two
// people adding different assets concurrently both keep theirs.
if (this.S.maps.has(k)) {
@@ -1085,19 +1181,13 @@ export class SyncEngine {
| undefined
}
- /** A doc-level key this peer must never ADOPT from a remote op or snapshot:
- * the never-synced set (skipDoc) — capability, identity, file modes, history,
- * volatile/encoding fields. Whatever a peer sends for these is refused, so a
- * remote peer or a local page on the channel can't replace the room keys,
- * rewrite docId, or flip readonly/template in a victim's open deck (which the
- * next save would write to the file). `assets.x` → field `assets`. */
- private refusesDocKey(k: string): boolean {
- return this.S.skipDoc.has(this.mapKey(k)?.[0] ?? k)
- }
-
private applySet(doc: BentoDoc, op: SetOp, res: ApplyResult) {
const nodeId = op.el ?? op.sl ?? DOC_NODE
- if (nodeId === DOC_NODE && this.refusesDocKey(op.k)) return // never adopted, whatever the sender claims
+ // A doc-level key this peer's map knows as non-content (or skipDoc) is never
+ // applied, whatever the sender claims — no register, no value. Checked before
+ // any bookkeeping so a hostile or older peer leaves no trace. With no class
+ // map this is exactly the shipped skipDoc refusal.
+ if (nodeId === DOC_NODE && this.ignoreInboundDocKey(this.docField(op.k))) return
const rk = `${nodeId} ${op.k}`
if (!newer(op.l, op.a, this.regs[rk])) return
// birth gate: an ins is a whole-node assignment — sets older than the
@@ -1652,8 +1742,9 @@ export class SyncEngine {
const sp = rk.indexOf(' ')
const nodeId = rk.slice(0, sp)
const key = rk.slice(sp + 1)
- // the snapshot path writes doc fields too: same refusal as applySet
- if (nodeId === DOC_NODE && this.refusesDocKey(key)) continue
+ // The snapshot path writes doc fields too, so it obeys the same receive
+ // rule as applySet: a key this peer knows as non-content never lands.
+ if (nodeId === DOC_NODE && this.ignoreInboundDocKey(this.docField(key))) continue
if (!regNewer(rr, this.regs[rk])) continue
this.regs[rk] = clone(rr) // registers advance even for dead nodes
if (nodeId !== DOC_NODE) {
diff --git a/scripts/test-sync-allowlist.ts b/scripts/test-sync-allowlist.ts
new file mode 100644
index 00000000..aa1cb6ee
--- /dev/null
+++ b/scripts/test-sync-allowlist.ts
@@ -0,0 +1,238 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Doc-level sync allowlist (PR2). When an app binds a field-class map, the
+// engine syncs doc-level keys by ALLOWLIST instead of the shipped denylist:
+//
+// node scripts/test-sync-allowlist.ts
+//
+// The shipped rule is skipDoc — a denylist: a named set is never emitted and
+// never adopted, everything else flows. That is the security floor and it
+// still holds. PR2 adds the other half, OFF until an app passes `classes` to
+// shape():
+// - SENDER: a peer emits a doc-level key only if its own map classes it
+// 'content' (per-key maps aside). A non-content key (identity / mode /
+// capability / history) and an UNKNOWN key — one a newer build added that
+// this build has no class for — are never emitted. Not emitting a key is
+// not deleting it: silence is never a del.
+// - RECEIVER: a key this map knows as non-content is ignored, whatever the
+// sender claims. An unknown key is APPLIED (option (a), APPLY_UNKNOWN_DOC_
+// KEYS = true): a newer build's content survives an older peer and lands in
+// this replica's own file — but this replica still never re-emits it.
+// - skipDoc remains the floor under both: never emitted, never adopted,
+// with or without a class map.
+//
+// With NO class map the engine is byte-for-byte the shipped denylist, so PR2
+// is dormant until an app opts in. That control is the last section.
+//
+// Mutations (edit kernel/src/sync/crdt.ts, re-run — each turns a row red):
+// - outboundDocKey → `return true` : sender emits non-content/unknown
+// - ignoreInboundDocKey non-content → false : receiver adopts identity/mode
+// - APPLY_UNKNOWN_DOC_KEYS = false : unknown key no longer applied
+// - outboundDocKey, drop `skipDoc.has(k)` guard : OUTBOUND floor red (diff + outboundDoc)
+// - ignoreInboundDocKey, drop `skipDoc.has(k)` : INBOUND floor red (applySet + snapshot)
+// The last two matter because a bound map classes some skipDoc keys as content
+// (spaces does), so the skipDoc-first guard is the only thing holding them off.
+
+import { SyncEngine, shape } from '../slides/src/sync/crdt.ts'
+import type { DocShape } from '../slides/src/sync/crdt.ts'
+import type { FieldClass } from '../kernel/src/docfields.ts'
+
+let failures = 0, checks = 0
+const ok = (cond: boolean, msg: string) => { checks++; if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`) }
+const H = (s: string) => console.log(`\n=== ${s} ===`)
+const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x))
+
+// A spaces-shaped doc (pages → blocks) with a doc-level class map. One field is
+// left OUT of the map on purpose: `mystery`, the newer-build key.
+const CLASSES: Record<string, FieldClass> = {
+ title: 'content', mood: 'content',
+ owner: 'identity', locked: 'mode', seat: 'capability', log: 'history',
+}
+const CLASSED: DocShape = shape('pages', 'blocks', 'html', [], CLASSES)
+const PLAIN: DocShape = shape('pages', 'blocks') // the shipped denylist, no map
+// The floor fixture: a map that classes skipDoc keys as `content`. skipDoc must
+// win over the class in BOTH directions, or a map could re-open a never-synced
+// field. This is not hypothetical — spaces' real map classes policy / format /
+// version / modified as content, and the floor is what keeps them off the wire.
+const FLOOR_FIELDS: Record<string, FieldClass> = {
+ ...CLASSES,
+ collab: 'content', docId: 'content', policy: 'content', format: 'content',
+ version: 'content', modified: 'content', revisions: 'content', trail: 'content',
+ readonly: 'content', template: 'content',
+}
+const FLOORED: DocShape = shape('pages', 'blocks', 'html', [], FLOOR_FIELDS)
+class Classed extends SyncEngine { constructor(a: string) { super(a, CLASSED) } }
+class Plain extends SyncEngine { constructor(a: string) { super(a, PLAIN) } }
+class Floored extends SyncEngine { constructor(a: string) { super(a, FLOORED) } }
+
+type Rec = Record<string, unknown>
+const doc = (over: Rec = {}): Rec => ({
+ format: 'bento/spaces', version: 1, docId: 'd-mine', title: 'mine', home: 'p1',
+ collab: { room: 'wMINE', key: 'MINE' },
+ pages: [{ id: 'p1', title: 'Page one', blocks: [{ id: 'b1', type: 'p', html: 'x' }] }],
+ ...over,
+})
+// doc-level set ops a diff produced, by field (maps collapse to their field)
+const docSets = (ops: Array<Rec>) =>
+ ops.filter(o => o.op === 'set' && o.el === undefined && o.sl === undefined)
+ .map(o => String(o.k).split('.')[0])
+
+H('SENDER: a classed peer emits only content keys')
+{
+ const A = new Classed('alice'); const d = doc(); A.adopt(d as never)
+ const before = clone(d)
+ d.mood = 'bright'; d.owner = 'eve'; d.locked = true; d.seat = 'gold'; d.log = [{ at: 't' }]
+ d.mystery = 'from a newer build'; (d.collab as Rec).key = 'ROTATED'
+ const emitted = docSets(A.diff(before, d as never, { text: true }) as never)
+ ok(emitted.includes('mood'), 'a content field (mood) is emitted')
+ ok(!emitted.includes('owner') && !emitted.includes('locked') && !emitted.includes('seat') && !emitted.includes('log'),
+ 'identity / mode / capability / history fields are NOT emitted')
+ ok(!emitted.includes('mystery'), 'an UNKNOWN field (not in the map) is NOT emitted')
+ ok(!emitted.includes('collab'), 'a skipDoc field (collab) is NOT emitted — the floor')
+}
+
+// A realistic wire: a CLASS-LESS peer (old build) emits every non-skip field,
+// so it can hand the classed replica the non-content and unknown ops to refuse
+// or apply. skipDoc is still never emitted by anyone, so that op is hand-made.
+// Each call uses a DISTINCT actor so its op isn't dropped as a duplicate `s`.
+let peerN = 0
+const peerOps = (change: Rec): Array<Rec> => {
+ const P = new Plain(`oldpeer${peerN++}`); const d = doc(); P.adopt(d as never)
+ const before = clone(d); Object.assign(d, change)
+ return P.diff(before, d as never, { text: true }) as never
+}
+
+H('RECEIVER: a classed peer ignores non-content, applies content and unknown')
+{
+ const A = new Classed('alice'); const d = doc(); A.adopt(d as never)
+ A.apply(d as never, peerOps({ mood: 'bright' }) as never)
+ ok(d.mood === 'bright', 'a content field from a peer is applied')
+ A.apply(d as never, peerOps({ owner: 'eve' }) as never)
+ ok(d.owner !== 'eve', 'an identity field from a peer is ignored, whatever it claims')
+ A.apply(d as never, peerOps({ locked: true }) as never)
+ ok(d.locked !== true, 'a mode field from a peer is ignored')
+ // option (a): an unknown field a newer build sent IS applied, and lands here
+ A.apply(d as never, peerOps({ mystery: 'newer content' }) as never)
+ ok(d.mystery === 'newer content', 'an UNKNOWN field from a peer IS applied (option a)')
+ // the floor: a hand-crafted skipDoc op (no honest peer emits one) is refused
+ A.apply(d as never, [{ op: 'set', k: 'collab', v: { room: 'wEVIL', key: 'EVIL' }, a: 'evil', s: 1, l: 9999 }] as never)
+ ok((d.collab as Rec).key === 'MINE', 'a skipDoc field (collab) is refused — the floor')
+}
+
+H('a value applied from an unknown key is NOT re-emitted (applied, never echoed)')
+{
+ const A = new Classed('alice'); const d = doc(); A.adopt(d as never)
+ A.apply(d as never, peerOps({ mystery: 'newer content', mood: 'bright' }) as never)
+ const regs = (A.toJSON() as { regs: Rec }).regs
+ const docRegKeys = Object.keys(regs).filter(k => k.startsWith('#doc ') || k.includes(' ')).filter(k => /(^|\s)(mystery|mood)$/.test(k))
+ ok(docRegKeys.some(k => k.endsWith(' mood')), 'the stamped state carries the content register (mood)')
+ ok(!docRegKeys.some(k => k.endsWith(' mystery')), 'but NOT the unknown one — applied locally, never echoed to peers')
+}
+
+H('LOADING a saved state drops a non-content doc register')
+{
+ // a state stamped by some build that DID carry an identity register
+ const A = new Classed('alice'); const d = doc(); A.adopt(d as never)
+ A.apply(d as never, peerOps({ mood: 'bright' }) as never)
+ const j = A.toJSON() as { regs: Rec }
+ // forge an identity register into the saved state, as a pre-allowlist stamp had
+ const docNode = Object.keys(j.regs).find(k => k.endsWith(' mood'))!.split(' ')[0]
+ j.regs[`${docNode} owner`] = [9999, 'someone']
+ const B = Classed.fromJSON('bob', j as never)
+ const bregs = (B.toJSON() as { regs: Rec }).regs
+ ok(Object.keys(bregs).some(k => k.endsWith(' mood')), 'the content register survives the load')
+ ok(!Object.keys(bregs).some(k => k.endsWith(' owner')), 'the forged identity register is dropped on load')
+}
+
+H('SNAPSHOT merge obeys the same receive rule')
+{
+ const A = new Classed('alice'); const d = doc(); A.adopt(d as never)
+ // a peer's snapshot: a doc carrying content + identity + unknown. The fields
+ // are DIFFED in (not merely adopted) so the state actually carries their
+ // doc-level registers, which is what mergeSnapshot replays.
+ const P = new Plain('snappeer'); const pd = doc(); P.adopt(pd as never)
+ const pbefore = clone(pd); pd.mood = 'bright'; pd.owner = 'eve'; pd.mystery = 'newer'
+ P.diff(pbefore, pd as never, { text: true })
+ const pstate = P.toJSON()
+ const rdoc = A.outboundDoc(clone(pd)) // sender-side projection is content-only…
+ ok(rdoc.owner === undefined && rdoc.mystery === undefined && rdoc.mood === 'bright',
+ 'outboundDoc keeps content + container and drops identity / unknown')
+ // …but merge the RAW peer doc+state to prove the RECEIVE rule, not the send one
+ A.mergeSnapshot(d as never, pd as never, pstate as never)
+ ok(d.mood === 'bright', 'snapshot: a content field lands')
+ ok(d.owner !== 'eve', 'snapshot: an identity field is refused')
+ ok(d.mystery === 'newer', 'snapshot: an unknown field is applied (option a)')
+}
+
+H('FLOOR: skipDoc beats a content classification, both directions')
+{
+ // Every one of these is classed `content` in FLOOR_FIELDS, yet skipDoc must
+ // still refuse it — on the wire and in the file.
+ const FLOORED_KEYS = ['collab', 'docId', 'policy', 'format', 'version', 'modified', 'revisions', 'trail', 'readonly', 'template']
+ // --- outbound: a diff emits none of them, though the map calls them content
+ const A = new Floored('alice'); const d = doc(); A.adopt(d as never)
+ const before = clone(d)
+ ;(d.collab as Rec).key = 'ROTATED'; d.docId = 'EVIL'; d.policy = 'evil'; d.format = 'evil'
+ d.version = 999; d.modified = '1999'; d.revisions = [{ id: 'x' }]; d.trail = [{}]; d.readonly = true; d.template = true
+ const emitted = docSets(A.diff(before, d as never, { text: true }) as never)
+ ok(FLOORED_KEYS.every(k => !emitted.includes(k)),
+ 'a skipDoc key classed content is still never EMITTED by a diff')
+ // --- outbound: the snapshot projection drops them too
+ const proj = A.outboundDoc(clone(d)) as Rec
+ ok(FLOORED_KEYS.every(k => proj[k] === undefined) && proj.pages !== undefined,
+ 'outboundDoc drops every skipDoc key, content-classed or not, and keeps the container')
+ // --- inbound: a hand-crafted op per key (no honest peer emits one) is refused
+ const B = new Floored('bob'); const bd = doc(); B.adopt(bd as never)
+ let act = 0
+ for (const k of FLOORED_KEYS) {
+ B.apply(bd as never, [{ op: 'set', k, v: k === 'collab' ? { key: 'EVIL' } : 'EVIL', a: `evil${act++}`, s: 1, l: 9000 }] as never)
+ }
+ ok((bd.collab as Rec).key === 'MINE' && bd.docId === 'd-mine' && bd.policy === undefined && bd.readonly === undefined,
+ 'a skipDoc key classed content is still REFUSED on receive (applySet)')
+ // --- inbound: the same through a snapshot with a VALID state carrying forged regs
+ const C = new Floored('carol'); const cd = doc(); C.adopt(cd as never)
+ C.apply(cd as never, peerOps({ mood: 'bright' }) as never) // a real content reg, so the state is valid
+ const st = C.toJSON() as { regs: Rec }
+ const node = Object.keys(st.regs).find(k => k.endsWith(' mood'))!.split(' ')[0]
+ const rdoc = doc({ collab: { key: 'EVIL' }, docId: 'EVIL', policy: 'evil', readonly: true }) as Rec
+ for (const k of FLOORED_KEYS) st.regs[`${node} ${k}`] = [9000, 'evil']
+ C.mergeSnapshot(cd as never, rdoc as never, st as never)
+ ok((cd.collab as Rec).key === 'MINE' && cd.docId === 'd-mine' && cd.policy === undefined && cd.readonly === undefined,
+ 'a skipDoc key classed content is still REFUSED on snapshot merge (mergeSnapshot)')
+}
+
+H('CONTROL: with no class map, the engine is the shipped denylist')
+{
+ const A = new Plain('alice'); const d = doc(); A.adopt(d as never)
+ const before = clone(d)
+ d.owner = 'eve'; d.mystery = 'anything'; (d.collab as Rec).key = 'ROTATED'
+ const emitted = docSets(A.diff(before, d as never, { text: true }) as never)
+ ok(emitted.includes('owner') && emitted.includes('mystery'),
+ 'a class-less peer emits every non-skip field, exactly as shipped')
+ ok(!emitted.includes('collab'), 'and still never a skipDoc field')
+ const B = new Plain('bob'); const bd = doc(); B.adopt(bd as never)
+ B.apply(bd as never, peerOps({ owner: 'eve' }) as never)
+ ok(bd.owner === 'eve', 'and a class-less peer adopts a non-content field, exactly as shipped')
+}
+
+H('MIXED VERSION: a new build and an old build converge; silence is not a del')
+{
+ const NEW = new Classed('newbuild'); const OLD = new Plain('oldbuild')
+ const dN = doc(); const dO = doc()
+ NEW.adopt(dN as never); OLD.adopt(dO as never)
+ // OLD (no map) sets content + an unknown + an identity; NEW receives
+ const b = clone(dO)
+ dO.mood = 'bright'; dO.mystery = 'from old'; dO.owner = 'oldowner'
+ NEW.apply(dN as never, OLD.diff(b, dO as never, { text: true }) as never)
+ ok(dN.mood === 'bright', 'content flows old → new')
+ ok(dN.mystery === 'from old', 'an unknown field flows old → new (applied)')
+ ok(dN.owner !== 'oldowner', 'but the old build cannot set the new build\'s identity field')
+ // NEW holds mystery but never emits it. Its stamped state, merged back into
+ // OLD, must not DELETE OLD's mystery — not-emitting is not a del.
+ OLD.mergeSnapshot(dO as never, NEW.outboundDoc(clone(dN)) as never, NEW.toJSON() as never)
+ ok(dO.mystery === 'from old', 'the new build\'s silence on `mystery` did not delete it from the old build')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)