Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: the identity agent contract (bento/id K1) (#759)

nyblnetbb9fb8c0d2b1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 42db3d8b..eef65e0e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -135,9 +135,17 @@ jobs:
# and the restore DIRECTION matters: a version restore ('back') keeps a
# live field; crash recovery ('recover') reconciles a live history field
# with the newer snapshot. Recover hooks (newestListWins for unsigned
- # lists) vs the default (signed-safe). Absent never wipes on recover.
+ # lists) vs the default (signed-safe). On recover, a field absent from a
+ # whole snapshot stays removed (deleted or cleared stays so) unless the
+ # rules opt it out (keepLiveWhenAbsent); a projection keeps the live value.
run: node scripts/test-restore.ts
+ - name: identity agent contract
+ # bento/id: how a document finds the host's identity agent. A valid
+ # agent only, null otherwise (today's behaviour), never a throw, and
+ # once found it cannot be swapped. Contract only: nothing calls it yet.
+ run: node scripts/test-identity.ts
+
- name: Typecheck convert (standalone)
# convert/ is a library beside the apps (the CLI and bento.page/import
# use it; no shell does), so no app's tsc -b reaches it. Its own flags,
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 5639f7a9..e689828c 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -10939,3 +10939,38 @@ Mutations, all red:
`test-spaces-restore-gate.ts`, including every cleared-stays-cleared row
(before this change, only the 2 pins caught it);
- removing the list: 6 + 1, covering the trail rows.
+
+## 2026-10-18 — bento/id: the identity agent contract (kernel/src/identity.ts)
+
+The document's side of the identity agent is ONE kernel module, so the hosts
+build against a single definition instead of each inventing one. The host
+defines `globalThis.__bentoIdentity` before the runtime boots, and only on a
+verified, signed shell (gate 1). `identityAgent()` returns it, or null when it
+is absent or malformed. On null every caller keeps today's behaviour.
+
+Settled here, so other zones don't redefine them:
+- **The contract version** is `IDENTITY_CONTRACT = 1`, an exact match. A host
+ advertising another version is treated as absent, never misread. Optional
+ members are additions within a version, and a breaking change bumps it.
+- **The calls.** Phase 1 has `whoami`, `sign(purpose, payload)` and
+ `resolve({pub} | {email})`. `unwrap` and `share` (phase 2) are typed as
+ optional members now, so the contract doesn't churn.
+- **No call takes a docId or a caller name.** The host identifies the calling
+ document from what the platform reports, never from the page.
+- **Results only.** A signature is raw r‖s (64 bytes, base64url), never DER.
+ Private keys never cross the bridge.
+- **`SignPurpose`** is one word per existing statement family: `frame`, `prove`,
+ `delegate`, `show`, `invite`, `revoke`. A signature is locked to its purpose.
+ The shared payload matcher and its vectors come with the statement formats
+ (K2).
+- **What a host must define.** The global is a non-writable, non-configurable
+ DATA property, never a getter. The agent object is frozen. Its methods are
+ closures, because they are called with `this` undefined. Anything else is
+ treated as no agent. Together these rules mean neither the page nor anything
+ later can redirect a call after capture: not by swapping the global, not by
+ patching the object, and not through `this` (security, #759).
+- **Capture.** A valid agent is captured once. An absent agent is not cached,
+ so a host that defines it late is still found.
+
+This change is contract only, with no callers. `scripts/test-identity.ts` pins
+that no runtime module imports it yet.
diff --git a/kernel/src/identity.ts b/kernel/src/identity.ts
new file mode 100644
index 00000000..54ecca34
--- /dev/null
+++ b/kernel/src/identity.ts
@@ -0,0 +1,198 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento/id — the document's side of the identity agent contract.
+//
+// A document is a file, and a file cannot keep a secret, so it cannot hold a
+// person's keys. The agent can: bento/home (the extension, the iOS, Android and
+// desktop apps) keeps the account and device keys and acts for the person when
+// a document asks. This module is the ONE definition of what a document may ask
+// and what it gets back. Each host implements it over its own channel
+// (home/bridge.js on the native hosts, the extension's served page), and the
+// document only ever talks to the object below.
+//
+// Three rules shape the contract:
+// - PRIVATE KEYS NEVER CROSS. Every call returns a result: a public identity,
+// a signature, a public binding. The only secret that ever comes back is a
+// document key the person was given (`unwrap`, phase 2).
+// - THE HOST KNOWS WHO IS ASKING. No call takes a docId or a caller name: the
+// host identifies the calling document from what the platform reports (the
+// file path, the opened URL), never from the page, and exposes this object
+// only to a verified, signed Bento shell (gate 1).
+// - NO HOST, NO CHANGE. `identityAgent()` returns null wherever there is no
+// agent — a bare file:// tab, an older host, a doctored file — and every
+// caller then does exactly what it did before identity existed.
+
+/** The contract version a host's agent object must carry. Members marked
+ * optional are additions within this version; a breaking change bumps it, and
+ * a document then sees no agent rather than one it would misread. */
+export const IDENTITY_CONTRACT = 1
+
+/** The global the host defines, before the runtime boots, on a verified shell. */
+export const IDENTITY_GLOBAL = '__bentoIdentity'
+
+/** Who is using this document, as vouched for. Public fields only. */
+export interface PublicIdentity {
+ /** display name, as the binding states it */
+ name: string
+ /** the verified address, exactly as bound (lower-case) */
+ email: string
+ /** who vouched: 'id.bento.page', an organisation's domain, or a vault id */
+ vouchedBy: string
+ /** the person's account public key: raw P-256 point, base64url */
+ accountPub: string
+ /** this device's key, the one `sign` uses: raw P-256 point, base64url */
+ devicePub: string
+}
+
+/**
+ * What a signature is for. The agent signs only a payload whose shape matches
+ * the purpose, so a prompt shown for one kind of action can never yield a
+ * signature on another. The payloads are the existing dot-joined statements
+ * (docs/collab-design.md):
+ * frame — `${i}.${d}`, an op batch or snapshot (routine)
+ * prove — `prove.${nonce}.${room}`, the per-socket possession proof (routine)
+ * delegate — `dlg.${devicePub}`, an invite key admitting a device (routine)
+ * show — `live`/`end` and `${kind}.aud.${i}`, presenting controls (routine)
+ * invite — `inv.${pub}.${role}.${exp}`, an owner granting a role (high authority)
+ * revoke — `rev.${pub}`, an owner removing a key (high authority)
+ * High-authority purposes get the host's own consent prompt and the consent
+ * key every time; routine ones ride the session (security §2e). The shared
+ * payload matcher and its test vectors land with the statement formats (K2).
+ */
+export type SignPurpose = 'frame' | 'prove' | 'delegate' | 'show' | 'invite' | 'revoke'
+
+/** Why a signature was not given. */
+export type SignRefusal =
+ /** the person said no at the host's prompt */
+ | 'declined'
+ /** past the idle or overall timeout: refused until the person re-authenticates (§2e B) */
+ | 'reauth'
+ /** the payload does not match the purpose */
+ | 'purpose'
+ /** no identity is set up on this device */
+ | 'no-identity'
+ /** the agent cannot sign right now (locked, busy, no key store) */
+ | 'unavailable'
+
+export type SignResult =
+ /** `sig` is raw r‖s (64 bytes) base64url, low-S normalised — never DER;
+ * `pub` is the key that signed */
+ | { ok: true; sig: string; pub: string }
+ | { ok: false; reason: SignRefusal }
+
+/** Look up a person by a key already in the room, or (phase 2) by address. */
+export type ResolveQuery = { pub: string } | { email: string }
+
+/** A public binding the agent found and checked. */
+export interface ResolvedIdentity {
+ name: string
+ email: string
+ vouchedBy: string
+ accountPub: string
+ /** when this agent first saw this binding (epoch ms) — trust on first use */
+ firstSeen: number
+ /** true if the binding differs from the one this agent saw before */
+ changed: boolean
+}
+
+/** Roles a person can be given in a document (phase 2). */
+export type ShareRole = 'reader' | 'editor' | 'owner'
+
+export interface IdentityAgent {
+ readonly contract: number
+ /** The person using this document, or null when no identity is set up or
+ * they declined to use it here (consent is per document). */
+ whoami(): Promise<PublicIdentity | null>
+ /** Sign `payload` (the exact UTF-8 text) for `purpose` with this device's key. */
+ sign(purpose: SignPurpose, payload: string): Promise<SignResult>
+ /** Who a key in the room (or, phase 2, an address) belongs to; null if unknown.
+ * A lookup by `{email}` is consent-gated and rate-limited by the HOST, so a
+ * document cannot use it to probe which addresses have an identity. */
+ resolve(query: ResolveQuery): Promise<ResolvedIdentity | null>
+ /** PHASE 2: open the document key wrapped to this person (`collab.wraps`).
+ * Returns the raw key, or null when no wrap here is theirs. */
+ unwrap?(wrap: { to: string; kw: string }): Promise<Uint8Array | null>
+ /** PHASE 2: share this document with a person, after the host's own consent. */
+ share?(email: string, role: ShareRole): Promise<{ ok: true } | { ok: false; reason: string }>
+}
+
+let held: IdentityAgent | undefined
+
+/**
+ * The host's identity agent for this page, or null when there is none — in
+ * which case the caller does what it always did.
+ *
+ * WHAT A HOST MUST DEFINE, or the document sees no agent:
+ * - the global as a DATA property that is non-writable and non-configurable
+ * (`Object.defineProperty(globalThis, '__bentoIdentity', { value, writable:
+ * false, configurable: false })`) — never a getter, which could answer
+ * differently on each read;
+ * - the agent object itself FROZEN;
+ * - its methods as CLOSURES that do not use `this`. They are called with
+ * `this` undefined, so a method that reaches its transport through `this`
+ * (or through anything page code could rewrite later) fails here instead of
+ * being redirectable after capture. Capture the transport at definition time.
+ *
+ * A valid agent is captured once; later changes cannot redirect a call. An
+ * absent or malformed one is not cached, so an agent the host defines a moment
+ * late is still found on a later call.
+ */
+export function identityAgent(): IdentityAgent | null {
+ if (held) return held
+ const agent = detect(globalThis)
+ if (agent) held = agent
+ return agent
+}
+
+function detect(scope: object): IdentityAgent | null {
+ let candidate: unknown
+ try {
+ const d = Object.getOwnPropertyDescriptor(scope, IDENTITY_GLOBAL)
+ // a data property the page can neither overwrite nor redefine; no getters
+ if (!d || !('value' in d) || d.writable !== false || d.configurable !== false) return null
+ candidate = d.value
+ } catch { return null }
+ return capture(candidate)
+}
+
+/** detect() against a stand-in global, without caching. For the rig only: a
+ * non-configurable property on the real globalThis could never be reset. */
+export function detectIdentityAgentForTest(scope: object): IdentityAgent | null {
+ return detect(scope)
+}
+
+function capture(c: unknown): IdentityAgent | null {
+ try {
+ if (!c || typeof c !== 'object') return null
+ // a frozen host object: no member can be swapped after this check
+ if (!Object.isFrozen(c)) return null
+ const o = c as Record<string, unknown>
+ if (o.contract !== IDENTITY_CONTRACT) return null
+ const fn = (k: string) => (typeof o[k] === 'function' ? (o[k] as (...a: unknown[]) => unknown) : null)
+ const whoami = fn('whoami'), sign = fn('sign'), resolve = fn('resolve')
+ if (!whoami || !sign || !resolve) return null
+ // phase-2 members are optional, but if present they must be callable
+ for (const k of ['unwrap', 'share']) if (o[k] !== undefined && !fn(k)) return null
+ const unwrap = fn('unwrap'), share = fn('share')
+ // `this` undefined: a host method gets nothing a page could later rewrite
+ const call = <F>(f: (...a: unknown[]) => unknown) =>
+ ((...args: unknown[]) => Reflect.apply(f, undefined, args)) as unknown as F
+ return Object.freeze({
+ contract: IDENTITY_CONTRACT,
+ whoami: call<IdentityAgent['whoami']>(whoami),
+ sign: call<IdentityAgent['sign']>(sign),
+ resolve: call<IdentityAgent['resolve']>(resolve),
+ ...(unwrap ? { unwrap: call<NonNullable<IdentityAgent['unwrap']>>(unwrap) } : {}),
+ ...(share ? { share: call<NonNullable<IdentityAgent['share']>>(share) } : {}),
+ })
+ } catch {
+ // a hostile getter, a revoked proxy: no agent, never a throw into the caller
+ return null
+ }
+}
+
+/** Forget the captured agent. For rigs that toggle the host between cases. */
+export function resetIdentityAgentForTest(): void {
+ held = undefined
+}
diff --git a/scripts/test-identity.ts b/scripts/test-identity.ts
new file mode 100644
index 00000000..779ac420
--- /dev/null
+++ b/scripts/test-identity.ts
@@ -0,0 +1,209 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/id contract rig: kernel/src/identity.ts.
+//
+// node scripts/test-identity.ts
+//
+// WHAT THIS PROVES. `identityAgent()` is how a document finds the host's
+// identity agent. It must return the agent ONLY when a host defined a valid one,
+// and null in every other case, so the caller falls back to today's behaviour.
+// It must never throw into the caller, whatever sits on the global. And once
+// found, the agent must not be redirectable: not by swapping the global, not by
+// patching the host object, and not through `this` (a method that reaches its
+// transport through `this` is called with `this` undefined, so it can't be
+// pointed somewhere else after capture). This PR ships the contract only, so the
+// rig also pins that nothing in the runtime calls it yet.
+//
+// Most cases run against a STAND-IN global (detectIdentityAgentForTest): the
+// contract requires a non-configurable property, which on the real globalThis
+// could never be reset between cases. The real path (identityAgent() over
+// globalThis, with its capture-once cache) runs last.
+
+import { readFileSync, readdirSync, statSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import {
+ identityAgent, detectIdentityAgentForTest as detect, IDENTITY_CONTRACT, IDENTITY_GLOBAL,
+} from '../kernel/src/identity.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+/** A stand-in global holding `value` the way a host must define it. */
+const scopeWith = (value: unknown, d: PropertyDescriptor = { writable: false, configurable: false }) => {
+ const s = {}
+ Object.defineProperty(s, IDENTITY_GLOBAL, { value, enumerable: true, ...d })
+ return s
+}
+
+/** A well-formed, FROZEN phase-1 agent whose methods are closures. */
+function fakeAgent(tag = 'A', extra: Record<string, unknown> = {}) {
+ const calls: string[] = []
+ const agent = Object.freeze({
+ contract: IDENTITY_CONTRACT,
+ async whoami() { calls.push('whoami'); return null },
+ async sign(purpose: string, payload: string) { calls.push(`sign:${purpose}:${payload}`); return { ok: true as const, sig: tag, pub: tag } },
+ async resolve() { calls.push('resolve'); return null },
+ ...extra,
+ })
+ return { agent, calls }
+}
+
+console.log('\nno host → null, the caller keeps today\'s behaviour')
+{
+ ok(detect({}) === null, 'no property → null')
+ for (const [v, label] of [[undefined, 'undefined'], [null, 'null'], ['agent', 'a string'], [() => 0, 'a function']] as const) {
+ ok(detect(scopeWith(v)) === null, `${label} → null`)
+ }
+}
+
+console.log('\nthe global must be a locked data property')
+{
+ const { agent } = fakeAgent()
+ ok(detect(scopeWith(agent)) !== null, 'control: a non-writable, non-configurable data property with a frozen agent → found')
+ ok(detect(scopeWith(agent, { writable: true, configurable: false })) === null, 'a WRITABLE property → null (the page could overwrite it)')
+ ok(detect(scopeWith(agent, { writable: false, configurable: true })) === null, 'a CONFIGURABLE property → null (the page could redefine it)')
+ const getterScope = {}
+ Object.defineProperty(getterScope, IDENTITY_GLOBAL, { get: () => agent, configurable: false })
+ ok(detect(getterScope) === null, 'a GETTER, even one returning a valid agent → null (it could answer differently each read)')
+ const plain = { [IDENTITY_GLOBAL]: agent }
+ ok(detect(plain) === null, 'a plain assignment (writable + configurable) → null')
+}
+
+console.log('\nthe agent object must be frozen')
+{
+ const { agent } = fakeAgent()
+ const unfrozen = { ...agent }
+ ok(detect(scopeWith(unfrozen)) === null, 'an unfrozen agent → null (a member could be swapped after capture)')
+ const sealedOnly = Object.seal({ ...agent })
+ ok(detect(scopeWith(sealedOnly)) === null, 'a sealed-but-writable agent → null')
+}
+
+console.log('\na malformed agent is refused, never half-used')
+{
+ const base = fakeAgent().agent
+ const f = (o: Record<string, unknown>) => detect(scopeWith(Object.freeze(o)))
+ ok(f({ ...base, contract: undefined }) === null, 'no contract version → null')
+ ok(f({ ...base, contract: IDENTITY_CONTRACT + 1 }) === null, 'a newer, unknown contract → null (not misread)')
+ ok(f({ ...base, contract: String(IDENTITY_CONTRACT) }) === null, 'a contract given as a string → null')
+ for (const k of ['whoami', 'sign', 'resolve'] as const) {
+ const bad: Record<string, unknown> = { ...base }; delete bad[k]
+ ok(f(bad) === null, `missing ${k} → null`)
+ ok(f({ ...base, [k]: 'not a function' }) === null, `${k} not callable → null`)
+ }
+ ok(f({ ...base, unwrap: 42 }) === null, 'a phase-2 member present but not callable → null')
+ ok(f({ ...base, share: {} }) === null, 'share present but not callable → null')
+}
+
+console.log('\nhostile values never throw into the caller')
+{
+ const tryDetect = (s: object) => { try { return { r: detect(s), threw: false } } catch { return { r: undefined, threw: true } } }
+ const trap = new Proxy({}, { get() { throw new Error('trap') }, isExtensible() { throw new Error('trap') } })
+ let t = tryDetect(scopeWith(trap))
+ ok(!t.threw && t.r === null, 'a trapping proxy → null, no throw')
+ const { proxy, revoke } = Proxy.revocable(fakeAgent().agent, {})
+ revoke()
+ t = tryDetect(scopeWith(proxy))
+ ok(!t.threw && t.r === null, 'a revoked proxy → null, no throw')
+ const descTrap = new Proxy({}, { getOwnPropertyDescriptor() { throw new Error('trap') } })
+ t = tryDetect(descTrap)
+ ok(!t.threw && t.r === null, 'a global whose descriptor read throws → null, no throw')
+}
+
+console.log('\na valid agent is found, phase-2 members optional')
+{
+ const { agent, calls } = fakeAgent()
+ const a = detect(scopeWith(agent))
+ ok(a !== null && a.contract === IDENTITY_CONTRACT, `a phase-1 agent is accepted and reports contract ${IDENTITY_CONTRACT}`)
+ ok(a?.unwrap === undefined && a?.share === undefined, 'phase-2 members absent → not invented')
+ const r = await a!.sign('frame', '1.abc')
+ ok(r.ok === true && calls.includes('sign:frame:1.abc'), 'calls reach the host agent with their arguments')
+ const b = detect(scopeWith(fakeAgent('B', { async unwrap() { return null }, async share() { return { ok: true } } }).agent))
+ ok(!!b && typeof b.unwrap === 'function' && typeof b.share === 'function', 'an agent with phase-2 members exposes them')
+ ok(Object.isFrozen(a), 'the captured agent is itself frozen')
+}
+
+console.log('\nno redirect through `this` (security, #759)')
+{
+ // Methods are called with `this` undefined, so they can only use closures.
+ let seenThis: unknown = 'unset'
+ const spy = Object.freeze({
+ contract: IDENTITY_CONTRACT,
+ async whoami() { return null },
+ async sign(this: unknown) { seenThis = this; return { ok: true as const, sig: 'S', pub: 'P' } },
+ async resolve() { return null },
+ })
+ await detect(scopeWith(spy))!.sign('frame', '1.x')
+ ok(seenThis === undefined, `a host method is called with this === undefined (got ${String(seenThis)})`)
+
+ // The measured attack: a host whose sign reaches its transport through
+ // `this.post`. With the host frozen the page cannot rewrite post — and with
+ // `this` undefined the method cannot even find it, so it fails CLOSED rather
+ // than signing through anything a page could reach.
+ const viaThis = Object.freeze({
+ contract: IDENTITY_CONTRACT,
+ post: (p: string) => ({ ok: true as const, sig: `genuine:${p}`, pub: 'P' }),
+ async whoami() { return null },
+ async sign(this: { post: (p: string) => unknown }, _purpose: string, payload: string) { return this.post(payload) },
+ async resolve() { return null },
+ })
+ let res: unknown, rejected = false
+ try { res = await detect(scopeWith(viaThis))!.sign('frame', '1.x') } catch { rejected = true }
+ ok(rejected && res === undefined, 'a `this`-dependent host method fails closed — no signature, never a redirected one')
+}
+
+console.log('\nonce found, the agent cannot be reassigned')
+{
+ const a = detect(scopeWith(fakeAgent('FIRST').agent))!
+ const orig = a.sign
+ let threw = false
+ try { (a as unknown as Record<string, unknown>).sign = () => 0 } catch { threw = true }
+ ok(threw && a.sign === orig, 'a write to the captured agent throws (strict mode) and changes nothing')
+}
+
+// K1 is contract only. Pin that no runtime file imports it yet, so this PR is
+// provably free of behaviour change; the bridge (B1) and the apps add callers.
+console.log('\ncontract only: nothing calls it yet')
+{
+ const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+ const hits: string[] = []
+ const walk = (dir: string) => {
+ for (const f of readdirSync(dir)) {
+ if (f === 'node_modules' || f.startsWith('.') || f === 'dist' || f === 'dist-single') continue
+ const p = join(dir, f)
+ if (statSync(p).isDirectory()) walk(p)
+ else if (/\.(ts|tsx|js|mjs)$/.test(f) && p !== join(root, 'kernel/src/identity.ts') &&
+ /from ['"][^'"]*\/identity(\.ts)?['"]/.test(readFileSync(p, 'utf8'))) hits.push(p.slice(root.length + 1))
+ }
+ }
+ for (const d of ['kernel/src', 'slides/src', 'spaces/src', 'type/src', 'dash/src']) walk(join(root, d))
+ ok(hits.length === 0, `no runtime module imports kernel/src/identity.ts (${hits.join(', ') || 'none'})`)
+}
+
+// The real path, last: identityAgent() over globalThis, with its capture-once
+// cache. Once the property is defined non-configurable it can never be removed,
+// which is exactly why this runs at the end.
+console.log('\nthe real globalThis path')
+{
+ ok(identityAgent() === null, 'nothing on globalThis yet → null')
+ const G = globalThis as Record<string, unknown>
+ G[IDENTITY_GLOBAL] = fakeAgent('PLAIN').agent // a plain assignment
+ ok(identityAgent() === null, 'a plain assignment on globalThis → still null (absent results are not cached)')
+ delete G[IDENTITY_GLOBAL]
+ const first = fakeAgent('REAL').agent
+ Object.defineProperty(globalThis, IDENTITY_GLOBAL, { value: first, writable: false, configurable: false })
+ const a = identityAgent()
+ ok(a !== null, 'a host defining it correctly, a moment late → found on the next call')
+ ok(identityAgent() === a, 'the same captured agent on every later call')
+ const r = await a!.sign('frame', '3.x')
+ ok(r.ok === true && r.sig === 'REAL', 'it signs through the host that defined it')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)