From e41701360b1db582cb615fdb5278013779fbb081 Mon Sep 17 00:00:00 2001 From: Marcus Pousette Date: Sat, 11 Jul 2026 23:36:53 +0200 Subject: [PATCH] fix(auth): expose durable local proof handoff --- .changeset/atomic-local-auth-proof-handoff.md | 11 + docs/sync/v0/auth.md | 29 +- docs/sync/v0/messages.proto | 6 +- .../hooks/usePlaygroundAuthSession.ts | 29 +- .../postgres/src/proof-material/postgres.ts | 22 +- .../sqlite/src/proof-material/sqlite.ts | 36 +-- packages/sync-protocol/protocol/src/auth.ts | 2 +- .../protocol/src/gen/sync/v0/messages_pb.ts | 6 +- .../sync-protocol/protocol/src/protobuf.ts | 20 +- packages/sync-protocol/protocol/src/types.ts | 2 +- .../pending-proof-material-contract.ts | 8 +- .../tests/helpers/proof-material-contract.ts | 10 +- .../helpers/replay-only-auth-contract.ts | 2 +- .../protocol/tests/smoke.test.ts | 55 +++- .../src/internal/cose-cwt-auth.ts | 185 +++++++------ packages/treecrdt-auth/src/internal/op-sig.ts | 35 ++- packages/treecrdt-auth/src/session.ts | 17 +- packages/treecrdt-auth/tests/auth.test.ts | 258 +++++++++++------- packages/treecrdt-auth/tests/op-sig.test.ts | 32 ++- .../treecrdt-engine-conformance/src/index.ts | 75 ++--- .../tests/conformance.test.ts | 1 + .../tests/conformance.test.ts | 1 + packages/treecrdt-ts/src/engine.ts | 8 +- packages/treecrdt-wa-sqlite/e2e/src/sync.ts | 1 + 24 files changed, 520 insertions(+), 331 deletions(-) create mode 100644 .changeset/atomic-local-auth-proof-handoff.md diff --git a/.changeset/atomic-local-auth-proof-handoff.md b/.changeset/atomic-local-auth-proof-handoff.md new file mode 100644 index 00000000..a2682745 --- /dev/null +++ b/.changeset/atomic-local-auth-proof-handoff.md @@ -0,0 +1,11 @@ +--- +'@treecrdt/auth': patch +'@treecrdt/interface': patch +'@treecrdt/sync-postgres': patch +'@treecrdt/sync-protocol': patch +'@treecrdt/sync-sqlite': patch +--- + +Return verified, backend-neutral local operation proofs directly from `authorizeLocalOps` so storage adapters can commit proof rows atomically with their operations. + +An auth entry is now one complete, durable unit: its 64-byte signature binds the selected 16-byte `proofRef`, and verifiers resolve only that referenced capability. Outbound sync reuses an exact retained proof and never mints auth after the local write has already committed. diff --git a/docs/sync/v0/auth.md b/docs/sync/v0/auth.md index 9f141ff9..85aafca1 100644 --- a/docs/sync/v0/auth.md +++ b/docs/sync/v0/auth.md @@ -58,8 +58,10 @@ If present, `auth` MUST be either empty (no auth) or exactly the same length as Each op may carry: - `sig`: Ed25519 signature bytes (64 bytes) -- `proof_ref` (optional but RECOMMENDED): 16-byte reference to the capability token used - to authorize this op +- `proof_ref`: 16-byte reference to the capability token used to authorize this op + +Auth is optional at the batch level. If an `OpAuth` entry is present, both fields are required +and must have the exact lengths above. Rationale: @@ -116,7 +118,7 @@ their current tree view is not delegation authority. Wire format (reference implementation): -- Delegated tokens are still COSE_Sign1 + CWT, but they are signed by the **subject key** of a *proof token*. +- Delegated tokens are still COSE_Sign1 + CWT, but they are signed by the **subject key** of a _proof token_. - The delegated token carries exactly one proof token in the COSE unprotected header: - key: `"treecrdt.delegation_proof_v1"` - value: a single `bstr` (or a 1-element array of `bstr`) containing the proof token bytes @@ -186,6 +188,7 @@ Ops are signed with the doc-scoped Ed25519 key. The signature covers: - explicit defensive-delete `known_state` presence and bytes - op kind + fields - payload bytes (ciphertext bytes if payloads are encrypted) +- the selected `proof_ref` ### Canonical signing bytes @@ -194,6 +197,7 @@ All integers are big-endian. Strings are UTF-8 with length prefixes. ``` sig_input = concat( "treecrdt/op-sig/v1", 0x00, + proof_ref, // exactly 16 bytes u32_be(len(doc_id)), doc_id_utf8, u32_be(len(replica_id)), replica_id_bytes, u64_be(counter), @@ -292,9 +296,9 @@ database as the CRDT state (not separate files). Two useful sidecar concepts: -1) **Verified proof cache** (optional): re-verify later without re-downloading proofs. -2) **Pending ops** (recommended): store ops that are validly signed and well-formed but not yet authorizable. -3) **Op auth cache** (recommended for forwarders): persist per-op auth (`sig` + `proof_ref`) for already-applied ops so a peer/server can re-serve ops it did not author after restart. +1. **Verified proof cache** (optional): re-verify later without re-downloading proofs. +2. **Pending ops** (recommended): store ops that are validly signed and well-formed but not yet authorizable. +3. **Op auth cache** (recommended for forwarders): persist per-op auth (`sig` + `proof_ref`) for already-applied ops so a peer/server can re-serve ops it did not author after restart. ### Suggested SQLite schema (illustrative) @@ -311,8 +315,8 @@ CREATE TABLE IF NOT EXISTS treecrdt_sync_pending_ops ( doc_id TEXT NOT NULL, op_ref BLOB NOT NULL, -- 16 bytes op BLOB NOT NULL, -- encoded sync/v0 Operation protobuf bytes (not a full SyncMessage) - sig BLOB NOT NULL, - proof_ref BLOB, + sig BLOB NOT NULL CHECK(length(sig) = 64), + proof_ref BLOB NOT NULL CHECK(length(proof_ref) = 16), reason TEXT NOT NULL, -- e.g. "missing_context" message TEXT, created_at_ms INTEGER NOT NULL, @@ -327,8 +331,8 @@ metadata for already-applied ops: CREATE TABLE IF NOT EXISTS treecrdt_sync_op_auth ( doc_id TEXT NOT NULL, op_ref BLOB NOT NULL, -- 16 bytes - sig BLOB NOT NULL, -- 64 bytes (Ed25519) - proof_ref BLOB, -- 16 bytes (token id), nullable + sig BLOB NOT NULL CHECK(length(sig) = 64), + proof_ref BLOB NOT NULL CHECK(length(proof_ref) = 16), created_at_ms INTEGER NOT NULL, PRIMARY KEY (doc_id, op_ref) ); @@ -339,14 +343,13 @@ CREATE TABLE IF NOT EXISTS treecrdt_sync_op_auth ( TreeCRDT’s JS SQLite adapters intentionally use a minimal `SqliteRunner` API (`exec` + `getText`). This has two practical implications for sidecar tables: -1) **DML via `getText`**: some runners implement `getText` using a “query” primitive (for example `better-sqlite3`’s +1. **DML via `getText`**: some runners implement `getText` using a “query” primitive (for example `better-sqlite3`’s `.get()`), which fails for statements that return no rows. A portable pattern is to use `RETURNING` so the statement yields a row: - - `INSERT ... RETURNING 1` - `DELETE ... RETURNING 1` -2) **BLOB reads via text**: if the bridge only returns strings, read `BLOB` columns with `hex(blob_col)` and decode on +2. **BLOB reads via text**: if the bridge only returns strings, read `BLOB` columns with `hex(blob_col)` and decode on the JS side. For bulk reads, SQLite’s JSON1 functions are convenient (`json_object`, `json_group_array`). ## Subscription note: push vs catch-up diff --git a/docs/sync/v0/messages.proto b/docs/sync/v0/messages.proto index 4ead6699..6f67c16e 100644 --- a/docs/sync/v0/messages.proto +++ b/docs/sync/v0/messages.proto @@ -111,15 +111,15 @@ message OpsBatch { // Auth metadata attached to a single operation. // -// This is an optional extension to Sync v0. Implementations that do not support -// auth MUST ignore these fields. +// The entire OpsBatch.auth array is optional. When an entry is present, both +// fields below are required by the application protocol. message OpAuth { reserved 1; // Signature bytes (Ed25519: 64 bytes) over the canonical signing input. bytes sig = 2; - // Optional reference to an authorization proof (e.g. token id / hash). + // 16-byte reference to the authorization proof selected before signing. bytes proof_ref = 3; } diff --git a/examples/playground/src/playground/hooks/usePlaygroundAuthSession.ts b/examples/playground/src/playground/hooks/usePlaygroundAuthSession.ts index e3ed399f..471f12c0 100644 --- a/examples/playground/src/playground/hooks/usePlaygroundAuthSession.ts +++ b/examples/playground/src/playground/hooks/usePlaygroundAuthSession.ts @@ -1,13 +1,13 @@ -import React, { useEffect, useMemo, useRef, useState } from "react"; -import type { Operation } from "@treecrdt/interface"; -import type { LocalWriteOptions } from "@treecrdt/interface/engine"; -import { bytesToHex } from "@treecrdt/interface/ids"; -import { base64urlDecode, type TreecrdtAuthSession } from "@treecrdt/auth"; -import type { SyncAuth } from "@treecrdt/sync-protocol"; -import type { TreecrdtSqliteAuthApi } from "@treecrdt/sync-sqlite/auth"; +import React, { useEffect, useMemo, useRef, useState } from 'react'; +import type { Operation } from '@treecrdt/interface'; +import type { LocalWriteOptions } from '@treecrdt/interface/engine'; +import { bytesToHex } from '@treecrdt/interface/ids'; +import { base64urlDecode, type TreecrdtAuthSession } from '@treecrdt/auth'; +import type { SyncAuth } from '@treecrdt/sync-protocol'; +import type { TreecrdtSqliteAuthApi } from '@treecrdt/sync-sqlite/auth'; -import { createLocalIdentityChainV1, type StoredAuthMaterial } from "../../auth"; -import { hexToBytes16 } from "../../sync-v0"; +import { createLocalIdentityChainV1, type StoredAuthMaterial } from '../../auth'; +import { hexToBytes16 } from '../../sync-v0'; type UsePlaygroundAuthSessionOptions = { authEnabled: boolean; @@ -48,9 +48,9 @@ export function usePlaygroundAuthSession( } = opts; const [syncAuth, setSyncAuth] = useState | null>(null); const localAuthSessionRef = useRef(null); - const localIdentityChainPromiseRef = useRef< - Promise> | null> | null - >(null); + const localIdentityChainPromiseRef = useRef + > | null> | null>(null); useEffect(() => { // Local identity chains are doc-bound (replica cert includes `docId`) and depend on the current replica key. @@ -68,7 +68,7 @@ export function usePlaygroundAuthSession( docId, replicaPublicKey: replicaPk, }).catch((err) => { - console.error("Failed to create identity chain", err); + console.error('Failed to create identity chain', err); return null; }); } @@ -127,7 +127,6 @@ export function usePlaygroundAuthSession( capabilityTokens: localTokens, }, revokedCapabilityTokenIds: hardRevokedTokenIdBytes, - requireProofRef: true, identity: { onPeer: onPeerIdentityChain, local: getLocalIdentityChain, @@ -176,7 +175,7 @@ export function usePlaygroundAuthSession( const getLocalWriteOptions = React.useCallback((): LocalWriteOptions | undefined => { if (!authEnabled) return; const session = localAuthSessionRef.current; - if (!session) throw new Error("auth is enabled but not configured"); + if (!session) throw new Error('auth is enabled but not configured'); return { authSession: session }; }, [authEnabled]); diff --git a/packages/sync-protocol/material/postgres/src/proof-material/postgres.ts b/packages/sync-protocol/material/postgres/src/proof-material/postgres.ts index 06945c4d..16938894 100644 --- a/packages/sync-protocol/material/postgres/src/proof-material/postgres.ts +++ b/packages/sync-protocol/material/postgres/src/proof-material/postgres.ts @@ -38,8 +38,8 @@ const OP_AUTH_SCHEMA_SQL = ` CREATE TABLE IF NOT EXISTS treecrdt_sync_op_auth ( doc_id TEXT NOT NULL, op_ref BYTEA NOT NULL, - sig BYTEA NOT NULL, - proof_ref BYTEA, + sig BYTEA NOT NULL CHECK (octet_length(sig) = 64), + proof_ref BYTEA NOT NULL CHECK (octet_length(proof_ref) = 16), created_at_ms BIGINT NOT NULL, PRIMARY KEY (doc_id, op_ref) ); @@ -60,8 +60,8 @@ CREATE TABLE IF NOT EXISTS treecrdt_sync_pending_ops ( doc_id TEXT NOT NULL, op_ref BYTEA NOT NULL, op BYTEA NOT NULL, - sig BYTEA NOT NULL, - proof_ref BYTEA, + sig BYTEA NOT NULL CHECK (octet_length(sig) = 64), + proof_ref BYTEA NOT NULL CHECK (octet_length(proof_ref) = 16), reason TEXT NOT NULL, message TEXT, created_at_ms BIGINT NOT NULL, @@ -138,7 +138,7 @@ export function createOpAuthStore(opts: { const params: Array = []; for (const entry of deduped) { - params.push(docId, entry.opRef, entry.auth.sig, entry.auth.proofRef ?? null, nowMs()); + params.push(docId, entry.opRef, entry.auth.sig, entry.auth.proofRef, nowMs()); } await pool.query(insertOpAuthSql(deduped.length), params); @@ -150,15 +150,15 @@ export function createOpAuthStore(opts: { const res = await pool.query<{ op_ref: Buffer; sig: Buffer; - proof_ref: Buffer | null; + proof_ref: Buffer; }>(selectOpAuthByRefsSql(opRefs.length), [docId, ...opRefs]); const byOpRefHex = new Map(); for (const row of res.rows) { const opRef = toBytes(row.op_ref); const sig = toBytes(row.sig); - const proofRef = row.proof_ref ? toBytes(row.proof_ref) : undefined; - byOpRefHex.set(bytesToHex(opRef), { sig, ...(proofRef ? { proofRef } : {}) }); + const proofRef = toBytes(row.proof_ref); + byOpRefHex.set(bytesToHex(opRef), { sig, proofRef }); } return opRefs.map((opRef) => byOpRefHex.get(bytesToHex(opRef)) ?? null); @@ -290,7 +290,7 @@ export function createPendingOpsStore(opts: { opRefForOp(docId, entry.op), encodeTreecrdtSyncV0Operation(entry.op), entry.auth.sig, - entry.auth.proofRef ?? null, + entry.auth.proofRef, entry.reason, entry.message ?? null, nowMs(), @@ -303,7 +303,7 @@ export function createPendingOpsStore(opts: { const res = await pool.query<{ op: Buffer; sig: Buffer; - proof_ref: Buffer | null; + proof_ref: Buffer; reason: string; message: string | null; }>( @@ -320,7 +320,7 @@ ORDER BY created_at_ms ASC, op_ref ASC op: decodeTreecrdtSyncV0Operation(toBytes(row.op)), auth: { sig: toBytes(row.sig), - ...(row.proof_ref ? { proofRef: toBytes(row.proof_ref) } : {}), + proofRef: toBytes(row.proof_ref), }, reason: row.reason === 'missing_context' diff --git a/packages/sync-protocol/material/sqlite/src/proof-material/sqlite.ts b/packages/sync-protocol/material/sqlite/src/proof-material/sqlite.ts index 81a6066c..4310fea5 100644 --- a/packages/sync-protocol/material/sqlite/src/proof-material/sqlite.ts +++ b/packages/sync-protocol/material/sqlite/src/proof-material/sqlite.ts @@ -42,8 +42,8 @@ CREATE TABLE IF NOT EXISTS treecrdt_sync_pending_ops ( doc_id TEXT NOT NULL, op_ref BLOB NOT NULL, -- 16 bytes op BLOB NOT NULL, -- protobuf bytes (sync/v0 Operation) - sig BLOB NOT NULL, -- 64 bytes (Ed25519) - proof_ref BLOB, -- 16 bytes (token id), nullable + sig BLOB NOT NULL CHECK(length(sig) = 64), + proof_ref BLOB NOT NULL CHECK(length(proof_ref) = 16), reason TEXT NOT NULL, -- e.g. "missing_context" message TEXT, created_at_ms INTEGER NOT NULL, @@ -55,8 +55,8 @@ const OP_AUTH_SCHEMA_SQL = ` CREATE TABLE IF NOT EXISTS treecrdt_sync_op_auth ( doc_id TEXT NOT NULL, op_ref BLOB NOT NULL, -- 16 bytes - sig BLOB NOT NULL, -- 64 bytes (Ed25519) - proof_ref BLOB, -- 16 bytes (token id), nullable + sig BLOB NOT NULL CHECK(length(sig) = 64), + proof_ref BLOB NOT NULL CHECK(length(proof_ref) = 16), created_at_ms INTEGER NOT NULL, PRIMARY KEY (doc_id, op_ref) ); @@ -131,14 +131,13 @@ RETURNING 1 for (const p of pending) { const opRef = opRefForOp(p.op); const opBytes = encodeTreecrdtSyncV0Operation(p.op); - const proofRef = p.auth.proofRef ?? null; const message = p.message ?? null; await opts.runner.getText(insertSql, [ opts.docId, opRef, opBytes, p.auth.sig, - proofRef, + p.auth.proofRef, p.reason, message, nowMs(), @@ -152,7 +151,7 @@ RETURNING 1 const rows = JSON.parse(text) as Array<{ op_hex: string; sig_hex: string; - proof_ref_hex: string | null; + proof_ref_hex: string; reason: string; message: string | null; }>; @@ -162,9 +161,7 @@ RETURNING 1 const op = decodeTreecrdtSyncV0Operation(opBytes); const sig = hexToBytesStrict(r.sig_hex, 64, 'pending sig'); - const proofRef = r.proof_ref_hex - ? hexToBytesStrict(r.proof_ref_hex, 16, 'pending proof_ref') - : undefined; + const proofRef = hexToBytesStrict(r.proof_ref_hex, 16, 'pending proof_ref'); if (r.reason !== 'missing_context') { throw new Error(`unexpected pending reason: ${r.reason}`); @@ -172,7 +169,7 @@ RETURNING 1 return { op, - auth: { sig, ...(proofRef ? { proofRef } : {}) }, + auth: { sig, proofRef }, reason: 'missing_context', ...(r.message ? { message: r.message } : {}), } satisfies PendingOp; @@ -236,8 +233,13 @@ FROM ( if (entries.length === 0) return; for (const e of entries) { - const proofRef = e.auth.proofRef ?? null; - await opts.runner.getText(insertSql, [opts.docId, e.opRef, e.auth.sig, proofRef, nowMs()]); + await opts.runner.getText(insertSql, [ + opts.docId, + e.opRef, + e.auth.sig, + e.auth.proofRef, + nowMs(), + ]); } }, @@ -250,17 +252,15 @@ FROM ( const rows = JSON.parse(text) as Array<{ op_ref_hex: string; sig_hex: string; - proof_ref_hex: string | null; + proof_ref_hex: string; }>; const byHex = new Map(); for (const r of rows) { const opRefHex = String(r.op_ref_hex).toLowerCase(); const sig = hexToBytesStrict(r.sig_hex, 64, 'op_auth sig'); - const proofRef = r.proof_ref_hex - ? hexToBytesStrict(r.proof_ref_hex, 16, 'op_auth proof_ref') - : undefined; - byHex.set(opRefHex, { sig, ...(proofRef ? { proofRef } : {}) }); + const proofRef = hexToBytesStrict(r.proof_ref_hex, 16, 'op_auth proof_ref'); + byHex.set(opRefHex, { sig, proofRef }); } return opRefs.map((ref) => byHex.get(bytesToHex(ref)) ?? null); diff --git a/packages/sync-protocol/protocol/src/auth.ts b/packages/sync-protocol/protocol/src/auth.ts index 24c27275..f93d0a0f 100644 --- a/packages/sync-protocol/protocol/src/auth.ts +++ b/packages/sync-protocol/protocol/src/auth.ts @@ -1,7 +1,7 @@ import type { Capability, Hello, HelloAck, OpAuth } from './types.js'; import type { Filter } from './types.js'; -export type SyncOpPurpose = 'reconcile' | 'subscribe' | 'reprocess_pending'; +export type SyncOpPurpose = 'local_write' | 'reconcile' | 'subscribe' | 'reprocess_pending'; export type SyncAuthOpDisposition = | { status: 'allow' } diff --git a/packages/sync-protocol/protocol/src/gen/sync/v0/messages_pb.ts b/packages/sync-protocol/protocol/src/gen/sync/v0/messages_pb.ts index 6a129d2d..e164a521 100644 --- a/packages/sync-protocol/protocol/src/gen/sync/v0/messages_pb.ts +++ b/packages/sync-protocol/protocol/src/gen/sync/v0/messages_pb.ts @@ -414,8 +414,8 @@ export const OpsBatchSchema: GenMessage = /** * Auth metadata attached to a single operation. * - * This is an optional extension to Sync v0. Implementations that do not support - * auth MUST ignore these fields. + * The entire OpsBatch.auth array is optional. When an entry is present, both + * fields below are required by the application protocol. * * @generated from message treecrdt.sync.v0.OpAuth */ @@ -428,7 +428,7 @@ export type OpAuth = Message<'treecrdt.sync.v0.OpAuth'> & { sig: Uint8Array; /** - * Optional reference to an authorization proof (e.g. token id / hash). + * 16-byte reference to the authorization proof selected before signing. * * @generated from field: bytes proof_ref = 3; */ diff --git a/packages/sync-protocol/protocol/src/protobuf.ts b/packages/sync-protocol/protocol/src/protobuf.ts index e77b0f06..606708cb 100644 --- a/packages/sync-protocol/protocol/src/protobuf.ts +++ b/packages/sync-protocol/protocol/src/protobuf.ts @@ -364,20 +364,28 @@ function fromProtoOperation(op: any): Operation { } function toProtoOpAuth(auth: OpAuth) { + if (!(auth.sig instanceof Uint8Array) || auth.sig.length !== 64) { + throw new Error('OpAuth.sig must be 64 bytes'); + } + if (!(auth.proofRef instanceof Uint8Array) || auth.proofRef.length !== 16) { + throw new Error('OpAuth.proofRef must be 16 bytes'); + } return create(OpAuthSchema, { sig: auth.sig, - ...(auth.proofRef ? { proofRef: auth.proofRef } : {}), + proofRef: auth.proofRef, }); } function fromProtoOpAuth(auth: any): OpAuth { const sig = auth.sig as Uint8Array | undefined; const proofRef = auth.proofRef as Uint8Array | undefined; - if (!sig) throw new Error('OpAuth.sig missing'); - return { - sig, - ...(proofRef && proofRef.length > 0 ? { proofRef } : {}), - }; + if (!(sig instanceof Uint8Array) || sig.length !== 64) { + throw new Error('OpAuth.sig must be 64 bytes'); + } + if (!(proofRef instanceof Uint8Array) || proofRef.length !== 16) { + throw new Error('OpAuth.proofRef must be 16 bytes'); + } + return { sig, proofRef }; } function toProtoOpsBatch(batch: OpsBatch) { diff --git a/packages/sync-protocol/protocol/src/types.ts b/packages/sync-protocol/protocol/src/types.ts index 33e802b4..41edd026 100644 --- a/packages/sync-protocol/protocol/src/types.ts +++ b/packages/sync-protocol/protocol/src/types.ts @@ -72,7 +72,7 @@ export type RibltStatus = { export type OpAuth = { sig: Bytes; - proofRef?: Bytes; + proofRef: Bytes; }; export type PendingOpReason = 'missing_context'; diff --git a/packages/sync-protocol/protocol/tests/helpers/pending-proof-material-contract.ts b/packages/sync-protocol/protocol/tests/helpers/pending-proof-material-contract.ts index 999622b3..4d8e621c 100644 --- a/packages/sync-protocol/protocol/tests/helpers/pending-proof-material-contract.ts +++ b/packages/sync-protocol/protocol/tests/helpers/pending-proof-material-contract.ts @@ -41,14 +41,14 @@ function makePending( replicaFill: number, counter: number, sigFill: number, - proofFill?: number, + proofFill: number, message?: string, ): PendingOp { return { op: makeInsertOp(replicaFill, counter), auth: { sig: new Uint8Array(64).fill(sigFill), - ...(proofFill === undefined ? {} : { proofRef: new Uint8Array(16).fill(proofFill) }), + proofRef: new Uint8Array(16).fill(proofFill), }, reason: 'missing_context', ...(message ? { message } : {}), @@ -70,7 +70,7 @@ function normalizePending(value: PendingOp) { lamport: value.op.meta.lamport, kind, sigHex: bytesToHex(value.auth.sig), - proofRefHex: value.auth.proofRef ? bytesToHex(value.auth.proofRef) : null, + proofRefHex: bytesToHex(value.auth.proofRef), reason: value.reason, message: value.message ?? null, }; @@ -96,7 +96,7 @@ export function definePendingProofMaterialStoreContract( const docId = `doc-pending-${randomUUID()}`; const pending = await harness.createPendingStore(docId); const first = makePending(7, 1, 9, 4, 'need ancestry'); - const second = makePending(7, 2, 8); + const second = makePending(7, 2, 8, 5); await pending.init(); await pending.storePendingOps([first, second]); diff --git a/packages/sync-protocol/protocol/tests/helpers/proof-material-contract.ts b/packages/sync-protocol/protocol/tests/helpers/proof-material-contract.ts index 64993025..9d68c0f6 100644 --- a/packages/sync-protocol/protocol/tests/helpers/proof-material-contract.ts +++ b/packages/sync-protocol/protocol/tests/helpers/proof-material-contract.ts @@ -24,10 +24,10 @@ function makeOpRef(fill: number): OpRef { return new Uint8Array(16).fill(fill); } -function makeOpAuth(sigFill: number, proofFill?: number): OpAuth { +function makeOpAuth(sigFill: number, proofFill: number): OpAuth { return { sig: new Uint8Array(64).fill(sigFill), - ...(proofFill === undefined ? {} : { proofRef: new Uint8Array(16).fill(proofFill) }), + proofRef: new Uint8Array(16).fill(proofFill), }; } @@ -38,7 +38,7 @@ function sortCapabilities(caps: Capability[]): Capability[] { function normalizeOpAuth(value: OpAuth): OpAuth { return { sig: Uint8Array.from(value.sig), - ...(value.proofRef ? { proofRef: Uint8Array.from(value.proofRef) } : {}), + proofRef: Uint8Array.from(value.proofRef), }; } @@ -58,7 +58,7 @@ export function defineProofMaterialStoreContract( const refB = makeOpRef(2); const missing = makeOpRef(3); const authA = makeOpAuth(9, 4); - const authB = makeOpAuth(7); + const authB = makeOpAuth(7, 5); await opAuth.storeOpAuth([ { opRef: refA, auth: authA }, @@ -83,7 +83,7 @@ export function defineProofMaterialStoreContract( const docB = await harness.createDocStores(`doc-b-${randomUUID()}`); const authA1 = makeOpAuth(1, 2); const authA2 = makeOpAuth(3, 4); - const authB = makeOpAuth(8); + const authB = makeOpAuth(8, 6); await docA.opAuth.storeOpAuth([{ opRef: sharedRef, auth: authA1 }]); await docA.opAuth.storeOpAuth([{ opRef: sharedRef, auth: authA2 }]); diff --git a/packages/sync-protocol/protocol/tests/helpers/replay-only-auth-contract.ts b/packages/sync-protocol/protocol/tests/helpers/replay-only-auth-contract.ts index 8e5e3ace..f039bc55 100644 --- a/packages/sync-protocol/protocol/tests/helpers/replay-only-auth-contract.ts +++ b/packages/sync-protocol/protocol/tests/helpers/replay-only-auth-contract.ts @@ -98,7 +98,7 @@ function makeInsertOp(replicaFill: number, counter: number): Operation { function normalizeOpAuth(value: OpAuth): OpAuth { return { sig: Uint8Array.from(value.sig), - ...(value.proofRef ? { proofRef: Uint8Array.from(value.proofRef) } : {}), + proofRef: Uint8Array.from(value.proofRef), }; } diff --git a/packages/sync-protocol/protocol/tests/smoke.test.ts b/packages/sync-protocol/protocol/tests/smoke.test.ts index 75acfb45..0734ff7a 100644 --- a/packages/sync-protocol/protocol/tests/smoke.test.ts +++ b/packages/sync-protocol/protocol/tests/smoke.test.ts @@ -1824,7 +1824,7 @@ test('a stale failing HelloAck rejects its real filtered session', async () => { test('pushOps refreshes replay capabilities before uploading newly authorized ops', async () => { const docId = 'doc-push-capability-refresh'; const root = '0'.repeat(32); - const proofRef = new Uint8Array([0x12, 0x34, 0x56, 0x78]); + const proofRef = new Uint8Array(16).fill(0x12); const replayCapValue = bytesToHex(proofRef); const knownReplayCaps = new Set(); let senderHelloCaps: Array<{ name: string; value: string }> = []; @@ -1842,7 +1842,7 @@ test('pushOps refreshes replay capabilities before uploading newly authorized op const peerA = new SyncPeer(a, { auth: { helloCapabilities: async () => senderHelloCaps, - signOps: async (ops) => ops.map(() => ({ sig: new Uint8Array([1]), proofRef })), + signOps: async (ops) => ops.map(() => ({ sig: new Uint8Array(64), proofRef })), }, maxOpsPerBatch: 1, }); @@ -1912,6 +1912,53 @@ test('syncOnce protobuf roundtrips ribltStatus.more', () => { expect(treecrdtSyncV0ProtobufCodec.decode(treecrdtSyncV0ProtobufCodec.encode(msg))).toEqual(msg); }); +test('protobuf requires complete, fixed-width op auth entries', () => { + const op = makeOp(replicas.a, 1, 1, { + type: 'insert', + parent: '0'.repeat(32), + node: nodeIdFromInt(1), + orderKey: new Uint8Array([1]), + }); + const msg: SyncMessage = { + v: 0, + docId: 'doc-op-auth-codec', + payload: { + case: 'opsBatch', + value: { + filterId: 'all', + ops: [op], + auth: [{ sig: new Uint8Array(64), proofRef: new Uint8Array(16) }], + done: true, + }, + }, + }; + + expect(treecrdtSyncV0ProtobufCodec.decode(treecrdtSyncV0ProtobufCodec.encode(msg))).toEqual(msg); + + const withAuth = msg.payload.case === 'opsBatch' ? msg.payload.value : undefined; + expect(() => + treecrdtSyncV0ProtobufCodec.encode({ + ...msg, + payload: { + case: 'opsBatch', + value: { ...withAuth!, auth: [{ sig: new Uint8Array(64) }] }, + }, + } as SyncMessage), + ).toThrow(/proofRef must be 16 bytes/i); + expect(() => + treecrdtSyncV0ProtobufCodec.encode({ + ...msg, + payload: { + case: 'opsBatch', + value: { + ...withAuth!, + auth: [{ sig: new Uint8Array(63), proofRef: new Uint8Array(16) }], + }, + }, + }), + ).toThrow(/sig must be 64 bytes/i); +}); + test('syncOnce waits for ribltStatus.more before sending another codeword batch', async () => { const docId = 'doc-sync-more-flow-control'; const root = '0'.repeat(32); @@ -2516,7 +2563,7 @@ test('subscribe pushes exact all-filter deltas without rescanning full state', a test('subscribe refreshes replay capabilities before pushing newly authorized ops', async () => { const docId = 'doc-subscribe-capability-refresh'; const root = '0'.repeat(32); - const proofRef = new Uint8Array([0x12, 0x34, 0x56, 0x78]); + const proofRef = new Uint8Array(16).fill(0x12); const replayCapValue = bytesToHex(proofRef); const a = new MemoryBackend(docId); @@ -2530,7 +2577,7 @@ test('subscribe refreshes replay capabilities before pushing newly authorized op auth: { helloCapabilities: async () => serverHelloCaps, onHello: async () => serverHelloCaps, - signOps: async (ops) => ops.map(() => ({ sig: new Uint8Array([1]), proofRef })), + signOps: async (ops) => ops.map(() => ({ sig: new Uint8Array(64), proofRef })), }, maxOpsPerBatch: 1, }); diff --git a/packages/treecrdt-auth/src/internal/cose-cwt-auth.ts b/packages/treecrdt-auth/src/internal/cose-cwt-auth.ts index 0e3ba49d..d89c94a7 100644 --- a/packages/treecrdt-auth/src/internal/cose-cwt-auth.ts +++ b/packages/treecrdt-auth/src/internal/cose-cwt-auth.ts @@ -84,7 +84,6 @@ export type TreecrdtCoseCwtAuthOptions = { ctx: TreecrdtCoseCwtRevocationCheckContext, ) => boolean | Promise; allowUnsigned?: boolean; - requireProofRef?: boolean; now?: () => number; }; @@ -107,7 +106,6 @@ export type TreecrdtCoseCwtRevocationCheckContext = export function createTreecrdtCoseCwtAuth(opts: TreecrdtCoseCwtAuthOptions): SyncAuth { const now = opts.now ?? (() => Math.floor(Date.now() / 1000)); const allowUnsigned = opts.allowUnsigned ?? false; - const requireProofRef = opts.requireProofRef ?? false; const localTokens = opts.localCapabilityTokens ?? []; const localTokenIds = localTokens.map((t) => deriveTokenIdV1(t)); @@ -494,6 +492,30 @@ export function createTreecrdtCoseCwtAuth(opts: TreecrdtCoseCwtAuthOptions): Syn } }; + const opAuthMatches = async (docId: string, op: Operation, auth: OpAuth): Promise => { + if ( + !(auth?.sig instanceof Uint8Array) || + auth.sig.length !== 64 || + !(auth?.proofRef instanceof Uint8Array) || + auth.proofRef.length !== 16 + ) { + return false; + } + + const publicKey = replicaIdToBytes(op.meta.id.replica); + try { + return await verifyTreecrdtOp({ + docId, + op, + proofRef: auth.proofRef, + signature: auth.sig, + publicKey, + }); + } catch { + return false; + } + }; + return { helloCapabilities: async (ctx) => helloCaps(ctx.docId), onHello: async (hello: Hello, ctx) => { @@ -554,73 +576,83 @@ export function createTreecrdtCoseCwtAuth(opts: TreecrdtCoseCwtAuthOptions): Syn const localKeyIdHex = bytesToHex(deriveKeyIdV1(opts.localPublicKey)); const out: OpAuth[] = new Array(ops.length); - const missingOpRefs: OpRef[] = []; - const missingIndices: number[] = []; + const opRefs = ops.map((op) => { + const replica = replicaIdToBytes(op.meta.id.replica); + return deriveOpRefV0(ctx.docId, { replica, counter: op.meta.id.counter }); + }); + const unresolved: number[] = []; + + for (let i = 0; i < ops.length; i += 1) { + const opRefHex = bytesToHex(opRefs[i]!); + const existing = opAuthByOpRefHex.get(opRefHex); + if (existing && (await opAuthMatches(ctx.docId, ops[i]!, existing))) { + out[i] = existing; + } else { + if (existing) opAuthByOpRefHex.delete(opRefHex); + unresolved.push(i); + } + } + + if (opts.opAuthStore && unresolved.length > 0) { + await ensureOpAuthStoreReady(); + const listed = await opts.opAuthStore.getOpAuthByOpRefs( + unresolved.map((index) => opRefs[index]!), + ); + if (listed.length !== unresolved.length) { + throw new Error('op auth store returned misaligned entries'); + } + for (let j = 0; j < listed.length; j += 1) { + const index = unresolved[j]!; + const found = listed[j]; + if (found && (await opAuthMatches(ctx.docId, ops[index]!, found))) { + out[index] = found; + opAuthByOpRefHex.set(bytesToHex(opRefs[index]!), found); + } + } + } for (let i = 0; i < ops.length; i += 1) { const op = ops[i]!; const opReplica = replicaIdToBytes(op.meta.id.replica); const opReplicaHex = bytesToHex(opReplica); - const opRef = deriveOpRefV0(ctx.docId, { replica: opReplica, counter: op.meta.id.counter }); - const opRefHex = bytesToHex(opRef); + const opRefHex = bytesToHex(opRefs[i]!); + + if (out[i]) continue; + if (ctx.purpose !== 'local_write') { + throw new Error('missing exact retained op auth; outbound sync cannot mint auth'); + } if (opReplicaHex !== localReplicaHex) { - const existing = opAuthByOpRefHex.get(opRefHex); - if (existing) { - out[i] = existing; - } else { - missingOpRefs.push(opRef); - missingIndices.push(i); - } - continue; + throw new Error('missing op auth or exact proof is invalid for non-local replica'); } - let proofRef: Uint8Array | undefined; - if (localTokenIds.length > 0) { - const byToken = grantsByKeyIdHex.get(localKeyIdHex); - const currentLocalGrants = byToken - ? Array.from(byToken.entries()) - .filter(([tokenIdHex]) => localTokenIdHexes.has(tokenIdHex)) - .map(([, grant]) => grant) - : []; - if (currentLocalGrants.length === 0) - throw new Error('auth enabled but no local capability tokens are recorded'); - const selected = await selectGrantForOp({ - docId: ctx.docId, - op, - candidates: currentLocalGrants, - purpose: 'sign_op', - }); - proofRef = selected.tokenId; + const byToken = grantsByKeyIdHex.get(localKeyIdHex); + const currentLocalGrants = byToken + ? Array.from(byToken.entries()) + .filter(([tokenIdHex]) => localTokenIdHexes.has(tokenIdHex)) + .map(([, grant]) => grant) + : []; + if (currentLocalGrants.length === 0) { + throw new Error('auth enabled but no local capability tokens are recorded'); } + const selected = await selectGrantForOp({ + docId: ctx.docId, + op, + candidates: currentLocalGrants, + purpose: 'sign_op', + }); + const proofRef = selected.tokenId; const sig = await signTreecrdtOp({ docId: ctx.docId, op, + proofRef, privateKey: opts.localPrivateKey, }); - const entry: OpAuth = { sig, ...(proofRef ? { proofRef } : {}) }; + const entry: OpAuth = { sig, proofRef }; opAuthByOpRefHex.set(opRefHex, entry); out[i] = entry; } - if (missingOpRefs.length > 0) { - const store = opts.opAuthStore; - if (!store) { - throw new Error('missing op auth for non-local replica; cannot forward unsigned op'); - } - await ensureOpAuthStoreReady(); - const listed = await store.getOpAuthByOpRefs(missingOpRefs); - for (let j = 0; j < listed.length; j += 1) { - const found = listed[j]; - if (!found) { - throw new Error('missing op auth for non-local replica; cannot forward unsigned op'); - } - const opRefHex = bytesToHex(missingOpRefs[j]!); - opAuthByOpRefHex.set(opRefHex, found); - out[missingIndices[j]!] = found; - } - } - return out; }, verifyOps: async (ops, auth, ctx) => { @@ -630,51 +662,39 @@ export function createTreecrdtCoseCwtAuth(opts: TreecrdtCoseCwtAuthOptions): Syn if (allowUnsigned) return; throw new Error('missing op auth'); } + if (auth.length !== ops.length) { + throw new Error(`op auth length ${auth.length} does not match ops length ${ops.length}`); + } const toPersist: Array<{ opRef: OpRef; auth: OpAuth }> = []; for (let i = 0; i < ops.length; i += 1) { const op = ops[i]!; const a = auth[i]!; + if ( + !(a?.sig instanceof Uint8Array) || + a.sig.length !== 64 || + !(a?.proofRef instanceof Uint8Array) || + a.proofRef.length !== 16 + ) { + throw new Error('op auth requires a 64-byte sig and 16-byte proof_ref'); + } const replica = replicaIdToBytes(op.meta.id.replica); const keyId = deriveKeyIdV1(replica); const keyHex = bytesToHex(keyId); const byToken = grantsByKeyIdHex.get(keyHex); if (!byToken || byToken.size === 0) throw new Error(`unknown author: ${keyHex}`); - const candidates = Array.from(byToken.values()); - let grant: CapabilityGrant; - - if (requireProofRef) { - if (!a.proofRef) throw new Error('missing proof_ref'); - const g = byToken.get(bytesToHex(a.proofRef)); - if (!g) throw new Error('proof_ref does not match known token'); - if ( - await isGrantRevoked({ - grant: g, - docId: ctx.docId, - purpose: 'verify_op', - op, - }) - ) { - throw new Error('capability token revoked'); - } - grant = g; - } else { - const preferred = a.proofRef ? byToken.get(bytesToHex(a.proofRef)) : undefined; - const orderedCandidates = preferred - ? [ - preferred, - ...candidates.filter( - (c) => bytesToHex(c.tokenId) !== bytesToHex(preferred.tokenId), - ), - ] - : candidates; - grant = await selectGrantForOp({ + const grant = byToken.get(bytesToHex(a.proofRef)); + if (!grant) throw new Error('proof_ref does not match known token'); + if ( + await isGrantRevoked({ + grant, docId: ctx.docId, - op, - candidates: orderedCandidates, purpose: 'verify_op', - }); + op, + }) + ) { + throw new Error('capability token revoked'); } if (bytesToHex(grant.publicKey) !== bytesToHex(replica)) { @@ -694,6 +714,7 @@ export function createTreecrdtCoseCwtAuth(opts: TreecrdtCoseCwtAuthOptions): Syn const ok = await verifyTreecrdtOp({ docId: ctx.docId, op, + proofRef: a.proofRef, signature: a.sig, publicKey: replica, }); diff --git a/packages/treecrdt-auth/src/internal/op-sig.ts b/packages/treecrdt-auth/src/internal/op-sig.ts index 5c14c4f6..10b08639 100644 --- a/packages/treecrdt-auth/src/internal/op-sig.ts +++ b/packages/treecrdt-auth/src/internal/op-sig.ts @@ -187,26 +187,53 @@ function assertPolicyOperation(op: Operation): void { } } -export function encodeTreecrdtOpSigInput(opts: { docId: string; op: Operation }): Uint8Array { +function assertProofRef(proofRef: Uint8Array): Uint8Array { + if (!(proofRef instanceof Uint8Array) || proofRef.length !== 16) { + throw new Error('proofRef must be 16 bytes'); + } + return proofRef; +} + +export function encodeTreecrdtOpSigInput(opts: { + docId: string; + op: Operation; + proofRef: Uint8Array; +}): Uint8Array { assertPolicyOperation(opts.op); - return concatBytes(OP_SIG_DOMAIN, u8(0), encodeTreecrdtOpFields(opts), encodeKnownState(opts.op)); + return concatBytes( + OP_SIG_DOMAIN, + u8(0), + assertProofRef(opts.proofRef), + encodeTreecrdtOpFields(opts), + encodeKnownState(opts.op), + ); } export async function signTreecrdtOp(opts: { docId: string; op: Operation; + proofRef: Uint8Array; privateKey: Uint8Array; }): Promise { - const msg = encodeTreecrdtOpSigInput({ docId: opts.docId, op: opts.op }); + const msg = encodeTreecrdtOpSigInput({ + docId: opts.docId, + op: opts.op, + proofRef: opts.proofRef, + }); return signEd25519(msg, opts.privateKey); } export async function verifyTreecrdtOp(opts: { docId: string; op: Operation; + proofRef: Uint8Array; signature: Uint8Array; publicKey: Uint8Array; }): Promise { - const msg = encodeTreecrdtOpSigInput({ docId: opts.docId, op: opts.op }); + const msg = encodeTreecrdtOpSigInput({ + docId: opts.docId, + op: opts.op, + proofRef: opts.proofRef, + }); return await verifyEd25519(opts.signature, msg, opts.publicKey); } diff --git a/packages/treecrdt-auth/src/session.ts b/packages/treecrdt-auth/src/session.ts index d801e988..e7cdb5e8 100644 --- a/packages/treecrdt-auth/src/session.ts +++ b/packages/treecrdt-auth/src/session.ts @@ -1,8 +1,8 @@ import type { Operation } from '@treecrdt/interface'; +import type { LocalWriteAuthProof } from '@treecrdt/interface/engine'; import type { Capability, Hello, - OpAuth, SyncAuth, SyncAuthHelloContext, SyncAuthOpsContext, @@ -54,8 +54,6 @@ export type TreecrdtAuthSessionLocal = { revocationRecords?: Uint8Array[]; }; -export type TreecrdtAuthSessionLocalAuthorizeOptions = Partial; - export type TreecrdtAuthSessionOptions = Omit< TreecrdtCoseCwtAuthOptions, | 'localIdentityChain' @@ -83,10 +81,7 @@ export type TreecrdtAuthSession = { readonly ready: Promise>; getState: () => TreecrdtAuthSessionState; refresh: () => Promise>; - authorizeLocalOps: ( - ops: readonly Operation[], - opts?: TreecrdtAuthSessionLocalAuthorizeOptions, - ) => Promise; + authorizeLocalOps: (ops: readonly Operation[]) => Promise; }; /** @@ -161,19 +156,15 @@ export function createTreecrdtAuthSession(opts: TreecrdtAuthSessionOptions): Tre let ready = warm(); - const authorizeLocalOps: TreecrdtAuthSession['authorizeLocalOps'] = async ( - ops, - ctxOverrides = {}, - ) => { + const authorizeLocalOps: TreecrdtAuthSession['authorizeLocalOps'] = async (ops) => { if (ops.length === 0) return []; if (!syncAuth.signOps || !syncAuth.verifyOps) { throw new Error('auth session is missing local op signing/verification hooks'); } const ctx: SyncAuthOpsContext = { docId, - purpose: 'reconcile', + purpose: 'local_write', filterId: '__local__', - ...ctxOverrides, }; const auth = await syncAuth.signOps(ops, ctx); if (auth.length !== ops.length) { diff --git a/packages/treecrdt-auth/tests/auth.test.ts b/packages/treecrdt-auth/tests/auth.test.ts index 69e8d0d5..52e63864 100644 --- a/packages/treecrdt-auth/tests/auth.test.ts +++ b/packages/treecrdt-auth/tests/auth.test.ts @@ -166,15 +166,15 @@ test('syncOnce with COSE+CWT auth converges and verifies ops', async () => { const aHex = bytesToHex(aPk); const bHex = bytesToHex(bPk); - await a.applyOps([ + const aOps = [ makeOp(aPk, 1, 1, { type: 'insert', parent: root, node: nodeIdFromInt(1), orderKey: orderKeyFromPosition(0), }), - ]); - await b.applyOps([ + ]; + const bOps = [ makeOp(bPk, 1, 2, { type: 'insert', parent: root, @@ -187,7 +187,9 @@ test('syncOnce with COSE+CWT auth converges and verifies ops', async () => { node: nodeIdFromInt(3), orderKey: orderKeyFromPosition(0), }), - ]); + ]; + await a.applyOps(aOps); + await b.applyOps(bOps); const tokenA = issueTreecrdtCapabilityTokenV1({ issuerPrivateKey: issuerSk, @@ -207,7 +209,6 @@ test('syncOnce with COSE+CWT auth converges and verifies ops', async () => { localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ @@ -215,8 +216,9 @@ test('syncOnce with COSE+CWT auth converges and verifies ops', async () => { localPrivateKey: bSk, localPublicKey: bPk, localCapabilityTokens: [tokenB], - requireProofRef: true, }); + await authA.signOps?.(aOps, { docId, purpose: 'local_write', filterId: 'all' }); + await authB.signOps?.(bOps, { docId, purpose: 'local_write', filterId: 'all' }); const { peerA: pa, @@ -295,7 +297,6 @@ test('auth: direct upload requires a live reader grant from the responder', asyn localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); // B can verify A's token, but has no live token of its own. Its HelloAck only // relays A's token as replay proof material, which must not authorize reading A. @@ -303,7 +304,6 @@ test('auth: direct upload requires a live reader grant from the responder', asyn issuerPublicKeys: [issuerPk], localPrivateKey: bSk, localPublicKey: bPk, - requireProofRef: true, }); const { peerA, transportA, detach } = createInMemoryConnectedPeers({ @@ -356,14 +356,12 @@ test('auth: signOps selects proof_ref per op when multiple tokens exist', async localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenStructure, tokenDelete], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: bSk, localPublicKey: bPk, - requireProofRef: true, }); const helloCapsA = await authA.helloCapabilities?.({ docId }); @@ -389,9 +387,10 @@ test('auth: signOps selects proof_ref per op when multiple tokens exist', async }; const ops = [opInsert, opDelete]; + const signCtx = { docId, purpose: 'local_write' as const, filterId: 'all' }; const ctx = { docId, purpose: 'reconcile' as const, filterId: 'all' }; - const auth = await authA.signOps?.(ops, ctx); + const auth = await authA.signOps?.(ops, signCtx); expect(auth).toBeTruthy(); expect(auth?.length).toBe(2); expect(auth?.[0]?.proofRef).toBeTruthy(); @@ -417,7 +416,7 @@ test('auth: signOps selects proof_ref per op when multiple tokens exist', async ...opDelete, meta: { id: opDelete.meta.id, lamport: opDelete.meta.lamport }, }; - await expect(authA.signOps?.([strippedState], ctx)).rejects.toThrow(/require.*knownState/i); + await expect(authA.signOps?.([strippedState], signCtx)).rejects.toThrow(/require.*knownState/i); await expect(authB.verifyOps?.([strippedState], [auth![1]!], ctx)).rejects.toThrow( /require.*knownState/i, ); @@ -428,6 +427,54 @@ test('auth: signOps selects proof_ref per op when multiple tokens exist', async ); }); +test('auth: restart reuses only a retained proof for the exact local operation', async () => { + const docId = 'doc-auth-retained-local-proof'; + const issuerSk = ed25519Utils.randomSecretKey(); + const issuerPk = await getPublicKey(issuerSk); + const writerSk = ed25519Utils.randomSecretKey(); + const writerPk = await getPublicKey(writerSk); + const token = issueTreecrdtCapabilityTokenV1({ + issuerPrivateKey: issuerSk, + subjectPublicKey: writerPk, + docId, + actions: ['delete'], + }); + const knownState = (frontier: number) => + new TextEncoder().encode( + JSON.stringify({ entries: [{ replica: Array.from(writerPk), frontier, ranges: [] }] }), + ); + const op = makeOp(writerPk, 1, 1, { type: 'delete', node: nodeIdFromInt(1) }); + op.meta.knownState = knownState(1); + const proofRef = deriveTokenIdV1(token); + const retained = { + sig: await signTreecrdtOp({ docId, op, proofRef, privateKey: writerSk }), + proofRef, + }; + const auth = createTreecrdtCoseCwtAuth({ + issuerPublicKeys: [issuerPk], + localPrivateKey: writerSk, + localPublicKey: writerPk, + localCapabilityTokens: [token], + // A fresh auth object simulates restart; only the standard proof sidecar survives. + opAuthStore: { + storeOpAuth: async () => {}, + getOpAuthByOpRefs: async (opRefs) => opRefs.map(() => retained), + }, + }); + const ctx = { docId, purpose: 'reconcile' as const, filterId: 'all' }; + + await expect(auth.signOps?.([op], ctx)).resolves.toEqual([retained]); + + const differentBody: Operation = { + ...op, + // v0 op_ref does not bind the body, so keep the same replica/counter and change signed state. + meta: { ...op.meta, knownState: knownState(2) }, + }; + await expect(auth.signOps?.([differentBody], ctx)).rejects.toThrow( + /outbound sync cannot mint auth/i, + ); +}); + test('auth: operation writes require a state-independent doc-wide grant', async () => { const docId = 'doc-auth-doc-wide-writes-only'; const scopeRoot = nodeIdFromInt(1); @@ -475,7 +522,6 @@ test('auth: operation writes require a state-independent doc-wide grant', async issuerPublicKeys: [issuerPk], localPrivateKey: verifierSk, localPublicKey: verifierPk, - requireProofRef: true, }); await verifier.onHello?.( helloWithCapabilities([{ name: 'auth.capability', value: base64urlEncode(token) }]), @@ -540,24 +586,27 @@ test('auth: operation writes require a state-independent doc-wide grant', async ]; const ctx = { docId, purpose: 'reconcile' as const, filterId: 'all' }; for (const { label, op } of operations) { - const proof = { - sig: await signTreecrdtOp({ docId, op, privateKey: writerSk }), - }; - for (const restricted of restrictedVerifiers) { + const proofRef = deriveTokenIdV1(restricted.token); + const proof = { + sig: await signTreecrdtOp({ docId, op, proofRef, privateKey: writerSk }), + proofRef, + }; await expect( - restricted.verifier.verifyOps?.( - [op], - [{ ...proof, proofRef: deriveTokenIdV1(restricted.token) }], - ctx, - ), + restricted.verifier.verifyOps?.([op], [proof], ctx), `${restricted.label} ${label}`, ).rejects.toThrow(/capability does not allow op/i); } + const proofRef = deriveTokenIdV1(docWideToken); await expect( docWideVerifier.verifyOps?.( [op], - [{ ...proof, proofRef: deriveTokenIdV1(docWideToken) }], + [ + { + sig: await signTreecrdtOp({ docId, op, proofRef, privateKey: writerSk }), + proofRef, + }, + ], ctx, ), `doc-wide ${label}`, @@ -598,13 +647,11 @@ test('auth ignores foreign peer capability tokens during hello and still verifie localPrivateKey: writerSk, localPublicKey: writerPk, localCapabilityTokens: [writerToken], - requireProofRef: true, }); const authVerifier = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: verifierSk, localPublicKey: verifierPk, - requireProofRef: true, }); const writerHelloCaps = (await authWriter.helloCapabilities?.({ docId })) ?? []; @@ -630,7 +677,7 @@ test('auth ignores foreign peer capability tokens during hello and still verifie node: nodeIdFromInt(1), orderKey: orderKeyFromPosition(0), }); - const auth = await authWriter.signOps?.([op], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth = await authWriter.signOps?.([op], { docId, purpose: 'local_write', filterId: 'all' }); await expect( authWriter.filterOutgoingOps?.([op], { docId, @@ -688,7 +735,6 @@ test('auth re-advertises trusted author capability tokens from the capability st localPrivateKey: writerSk, localPublicKey: writerPk, localCapabilityTokens: [writerToken], - requireProofRef: true, }); const authRelay = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], @@ -696,7 +742,6 @@ test('auth re-advertises trusted author capability tokens from the capability st localPublicKey: relayPk, localCapabilityTokens: [relayToken], capabilityStore, - requireProofRef: true, }); const writerHelloCaps = (await authWriter.helloCapabilities?.({ docId })) ?? []; @@ -708,13 +753,11 @@ test('auth re-advertises trusted author capability tokens from the capability st localPublicKey: relayPk, localCapabilityTokens: [relayToken], capabilityStore, - requireProofRef: true, }); const authJoiner = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: joinerSk, localPublicKey: joinerPk, - requireProofRef: true, }); const relayHelloCaps = (await reloadedRelay.helloCapabilities?.({ docId })) ?? []; @@ -733,7 +776,11 @@ test('auth re-advertises trusted author capability tokens from the capability st node: nodeIdFromInt(7), orderKey: orderKeyFromPosition(0), }); - const signed = await authWriter.signOps?.([op], { docId, purpose: 'reconcile', filterId: 'all' }); + const signed = await authWriter.signOps?.([op], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await expect( authJoiner.verifyOps?.([op], signed, { docId, purpose: 'reconcile', filterId: 'all' }), ).resolves.toBeUndefined(); @@ -815,7 +862,6 @@ test('auth: replayed author capability tokens do not widen peer filter scope', a localPrivateKey: writerSk, localPublicKey: writerPk, localCapabilityTokens: [writerToken], - requireProofRef: true, }); const authScopedPeer = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], @@ -823,13 +869,11 @@ test('auth: replayed author capability tokens do not widen peer filter scope', a localPublicKey: scopedPeerPk, localCapabilityTokens: [scopedToken], capabilityStore, - requireProofRef: true, }); const authSender = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: senderSk, localPublicKey: senderPk, - requireProofRef: true, scopeEvaluator, }); @@ -842,7 +886,6 @@ test('auth: replayed author capability tokens do not widen peer filter scope', a localPublicKey: scopedPeerPk, localCapabilityTokens: [scopedToken], capabilityStore, - requireProofRef: true, }); const scopedPeerCaps = (await reloadedScopedPeer.helloCapabilities?.({ docId })) ?? []; @@ -922,7 +965,6 @@ test('auth: cached stale local tokens cannot authorize new local writes after an localPublicKey: localPk, localCapabilityTokens: [newReadOnlyToken], capabilityStore, - requireProofRef: true, }); const op = makeOp(localPk, 1, 1, { @@ -933,7 +975,7 @@ test('auth: cached stale local tokens cannot authorize new local writes after an }); await expect( - auth.signOps?.([op], { docId, purpose: 'reconcile', filterId: root }), + auth.signOps?.([op], { docId, purpose: 'local_write', filterId: root }), ).rejects.toThrow(/capability does not allow op/i); }); @@ -979,7 +1021,6 @@ test('auth: helloCapabilities ignores locally cached revoked replay tokens', asy localCapabilityTokens: [localToken], capabilityStore, revokedCapabilityTokenIds: [deriveTokenIdV1(revokedPeerToken)], - requireProofRef: true, }); await expect(auth.helloCapabilities?.({ docId })).resolves.toEqual([ @@ -1093,7 +1134,6 @@ test('syncOnce fails when responder requires auth but initiator sends unsigned o localPrivateKey: bSk, localPublicKey: bPk, localCapabilityTokens: [tokenB], - requireProofRef: true, }); const { @@ -1138,15 +1178,15 @@ test('syncOnce fails when op signatures do not match the claimed replica_id', as const aHex = bytesToHex(aClaimPk); - await a.applyOps([ + const aOps = [ makeOp(aClaimPk, 1, 1, { type: 'insert', parent: root, node: nodeIdFromInt(1), orderKey: orderKeyFromPosition(0), }), - ]); - await b.applyOps([ + ]; + const bOps = [ makeOp(bPk, 1, 2, { type: 'insert', parent: root, @@ -1159,7 +1199,9 @@ test('syncOnce fails when op signatures do not match the claimed replica_id', as node: nodeIdFromInt(3), orderKey: orderKeyFromPosition(0), }), - ]); + ]; + await a.applyOps(aOps); + await b.applyOps(bOps); const tokenA = issueTreecrdtCapabilityTokenV1({ issuerPrivateKey: issuerSk, @@ -1179,7 +1221,6 @@ test('syncOnce fails when op signatures do not match the claimed replica_id', as localPrivateKey: aSignSk, localPublicKey: aClaimPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ @@ -1187,8 +1228,9 @@ test('syncOnce fails when op signatures do not match the claimed replica_id', as localPrivateKey: bSk, localPublicKey: bPk, localCapabilityTokens: [tokenB], - requireProofRef: true, }); + await authA.signOps?.(aOps, { docId, purpose: 'local_write', filterId: 'all' }); + await authB.signOps?.(bOps, { docId, purpose: 'local_write', filterId: 'all' }); const { peerA: pa, @@ -1205,7 +1247,9 @@ test('syncOnce fails when op signatures do not match the claimed replica_id', as try { await expect( pa.syncOnce(ta, { all: {} }, { maxCodewords: 10_000, codewordsPerMessage: 256 }), - ).rejects.toThrow(/invalid op signature|unknown author|capability/i); + ).rejects.toThrow( + /invalid op signature|missing exact retained op auth|unknown author|capability/i, + ); await tick(); expect(b.hasOp(aHex, 1)).toBe(false); } finally { @@ -1251,14 +1295,12 @@ test('auth: syncOnce rejects filters when capability scope does not allow read a localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: bSk, localPublicKey: bPk, - requireProofRef: true, scopeEvaluator, }); @@ -1331,14 +1373,12 @@ test('auth: subscribe rejects filters when capability scope does not allow read localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: bSk, localPublicKey: bPk, - requireProofRef: true, scopeEvaluator, }); @@ -1401,14 +1441,12 @@ test('auth: filters require read_structure action (read_payload alone is insuffi localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: bSk, localPublicKey: bPk, - requireProofRef: true, }); const { @@ -1468,21 +1506,21 @@ test('auth: syncOnce accepts doc-wide read_structure capability for filter(all)' }); // Put one op on B so A has something to fetch (A won't send ops). - await b.applyOps([ + const bOps = [ makeOp(bPk, 1, 1, { type: 'insert', parent: root, node: nodeIdFromInt(1), orderKey: orderKeyFromPosition(0), }), - ]); + ]; + await b.applyOps(bOps); const authA = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ @@ -1490,8 +1528,8 @@ test('auth: syncOnce accepts doc-wide read_structure capability for filter(all)' localPrivateKey: bSk, localPublicKey: bPk, localCapabilityTokens: [tokenB], - requireProofRef: true, }); + await authB.signOps?.(bOps, { docId, purpose: 'local_write', filterId: 'all' }); const { peerA: pa, @@ -1552,14 +1590,12 @@ test('auth: reference COSE/CWT rejects scoped filter(children)', async () => { localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: bSk, localPublicKey: bPk, - requireProofRef: true, scopeEvaluator, }); @@ -1628,14 +1664,12 @@ test('auth: syncOnce rejects filter(children) when capability scope does not mat localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: bSk, localPublicKey: bPk, - requireProofRef: true, scopeEvaluator, }); @@ -1707,7 +1741,6 @@ test('auth: scoped projections cannot reveal excluded destinations or private hi issuerPublicKeys: [issuerPk], localPrivateKey: senderSk, localPublicKey: senderPk, - requireProofRef: true, scopeEvaluator, }); @@ -1716,7 +1749,6 @@ test('auth: scoped projections cannot reveal excluded destinations or private hi localPrivateKey: receiverSk, localPublicKey: receiverPk, localCapabilityTokens: [tokenReceiver], - requireProofRef: true, }); const receiverCaps = await authReceiver.helloCapabilities?.({ docId }); @@ -1805,7 +1837,6 @@ test('auth: document-wide projection requires read_payload for every payload-sta localPrivateKey: peerSk, localPublicKey: peerPk, localCapabilityTokens, - requireProofRef: true, }); return (await auth.helloCapabilities?.({ docId })) ?? []; }; @@ -1817,7 +1848,6 @@ test('auth: document-wide projection requires read_payload for every payload-sta issuerPublicKeys: [issuerPk], localPrivateKey: peerSk, localPublicKey: peerPk, - requireProofRef: true, scopeEvaluator: () => { throw new Error('document-wide fast path must not consult materialized ancestry'); }, @@ -1942,7 +1972,6 @@ test('auth: delegated capability token can be verified via issuer-signed proof', issuerPublicKeys: [issuerPk], localPrivateKey: verifierSk, localPublicKey: verifierPk, - requireProofRef: true, }); const authRecipient = createTreecrdtCoseCwtAuth({ @@ -1950,7 +1979,6 @@ test('auth: delegated capability token can be verified via issuer-signed proof', localPrivateKey: recipientSk, localPublicKey: recipientPk, localCapabilityTokens: [delegated], - requireProofRef: true, }); const helloCaps = await authRecipient.helloCapabilities?.({ docId }); @@ -1966,7 +1994,7 @@ test('auth: delegated capability token can be verified via issuer-signed proof', }); const auth = await authRecipient.signOps?.([op], { docId, - purpose: 'reconcile', + purpose: 'local_write', filterId: 'all', }); expect(auth).toBeTruthy(); @@ -2155,7 +2183,6 @@ test('auth: onHello rejects revoked peer capability tokens', async () => { localPrivateKey: senderSk, localPublicKey: senderPk, localCapabilityTokens: [tokenSender], - requireProofRef: true, }); const authReceiver = createTreecrdtCoseCwtAuth({ @@ -2163,7 +2190,6 @@ test('auth: onHello rejects revoked peer capability tokens', async () => { localPrivateKey: receiverSk, localPublicKey: receiverPk, revokedCapabilityTokenIds: [deriveTokenIdV1(tokenSender)], - requireProofRef: true, }); const helloCaps = await authSender.helloCapabilities?.({ docId }); @@ -2206,7 +2232,6 @@ test('auth: onHello ignores revoked replay capability tokens', async () => { localPrivateKey: receiverSk, localPublicKey: receiverPk, revokedCapabilityTokenIds: [deriveTokenIdV1(revokedReplayToken)], - requireProofRef: true, }); await expect( @@ -2247,14 +2272,12 @@ test('auth: late hard revocation rejects future ops and re-verification of past localPrivateKey: writerSk, localPublicKey: writerPk, localCapabilityTokens: [writerToken], - requireProofRef: true, }); const authVerifier = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: verifierSk, localPublicKey: verifierPk, - requireProofRef: true, isCapabilityTokenRevoked: ({ stage }) => stage === 'runtime' && hardRevoked.value, }); @@ -2267,7 +2290,11 @@ test('auth: late hard revocation rejects future ops and re-verification of past node: nodeIdFromInt(1), orderKey: orderKeyFromPosition(0), }); - const auth1 = await authWriter.signOps?.([op1], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth1 = await authWriter.signOps?.([op1], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await authVerifier.verifyOps?.([op1], auth1 ?? undefined, { docId, purpose: 'reconcile', @@ -2282,7 +2309,11 @@ test('auth: late hard revocation rejects future ops and re-verification of past node: nodeIdFromInt(2), orderKey: orderKeyFromPosition(1), }); - const auth2 = await authWriter.signOps?.([op2], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth2 = await authWriter.signOps?.([op2], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await expect( authVerifier.verifyOps?.([op2], auth2 ?? undefined, { @@ -2327,14 +2358,12 @@ test('auth: runtime revocation callback supports counter cutover policy', async localPrivateKey: writerSk, localPublicKey: writerPk, localCapabilityTokens: [writerToken], - requireProofRef: true, }); const authVerifier = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: verifierSk, localPublicKey: verifierPk, - requireProofRef: true, isCapabilityTokenRevoked: ({ stage, tokenIdHex, op }) => { if (tokenIdHex !== writerTokenIdHex) return false; if (stage !== 'runtime') return false; @@ -2352,7 +2381,11 @@ test('auth: runtime revocation callback supports counter cutover policy', async node: nodeIdFromInt(3), orderKey: orderKeyFromPosition(0), }); - const auth1 = await authWriter.signOps?.([op1], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth1 = await authWriter.signOps?.([op1], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await authVerifier.verifyOps?.([op1], auth1 ?? undefined, { docId, purpose: 'reconcile', @@ -2367,7 +2400,11 @@ test('auth: runtime revocation callback supports counter cutover policy', async node: nodeIdFromInt(4), orderKey: orderKeyFromPosition(1), }); - const auth2 = await authWriter.signOps?.([op2], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth2 = await authWriter.signOps?.([op2], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await expect( authVerifier.verifyOps?.([op2], auth2 ?? undefined, { @@ -2417,20 +2454,17 @@ test('auth: revocation record from hello capabilities hard-revokes token across localPrivateKey: writerSk, localPublicKey: writerPk, localCapabilityTokens: [writerToken], - requireProofRef: true, }); const authVerifier = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: verifierSk, localPublicKey: verifierPk, - requireProofRef: true, }); const authRevoker = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: revokerSk, localPublicKey: revokerPk, localRevocationRecords: [revocationRecord], - requireProofRef: true, }); const writerHelloCaps = await authWriter.helloCapabilities?.({ docId }); @@ -2442,7 +2476,11 @@ test('auth: revocation record from hello capabilities hard-revokes token across node: nodeIdFromInt(10), orderKey: orderKeyFromPosition(0), }); - const auth1 = await authWriter.signOps?.([op1], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth1 = await authWriter.signOps?.([op1], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await authVerifier.verifyOps?.([op1], auth1 ?? undefined, { docId, purpose: 'reconcile', @@ -2458,7 +2496,11 @@ test('auth: revocation record from hello capabilities hard-revokes token across node: nodeIdFromInt(11), orderKey: orderKeyFromPosition(1), }); - const auth2 = await authWriter.signOps?.([op2], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth2 = await authWriter.signOps?.([op2], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await expect( authVerifier.verifyOps?.([op2], auth2 ?? undefined, { @@ -2553,27 +2595,23 @@ test('auth: highest rev_seq revocation record wins for a token', async () => { localPrivateKey: writerSk, localPublicKey: writerPk, localCapabilityTokens: [writerToken], - requireProofRef: true, }); const authVerifier = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: verifierSk, localPublicKey: verifierPk, - requireProofRef: true, }); const authLowSeq = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: lowSeqSk, localPublicKey: lowSeqPk, localRevocationRecords: [lowSeqHard], - requireProofRef: true, }); const authHighSeq = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: highSeqSk, localPublicKey: highSeqPk, localRevocationRecords: [highSeqCutover], - requireProofRef: true, }); const writerHelloCaps = await authWriter.helloCapabilities?.({ docId }); @@ -2585,7 +2623,11 @@ test('auth: highest rev_seq revocation record wins for a token', async () => { node: nodeIdFromInt(20), orderKey: orderKeyFromPosition(0), }); - const auth1 = await authWriter.signOps?.([op1], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth1 = await authWriter.signOps?.([op1], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await authVerifier.verifyOps?.([op1], auth1 ?? undefined, { docId, purpose: 'reconcile', @@ -2618,7 +2660,11 @@ test('auth: highest rev_seq revocation record wins for a token', async () => { node: nodeIdFromInt(21), orderKey: orderKeyFromPosition(1), }); - const auth2 = await authWriter.signOps?.([op2], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth2 = await authWriter.signOps?.([op2], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await expect( authVerifier.verifyOps?.([op2], auth2 ?? undefined, { @@ -2676,27 +2722,23 @@ test('auth: out-of-order revocation records use highest rev_seq even when it arr localPrivateKey: writerSk, localPublicKey: writerPk, localCapabilityTokens: [writerToken], - requireProofRef: true, }); const authVerifier = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: verifierSk, localPublicKey: verifierPk, - requireProofRef: true, }); const authLowSeqPeer = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: lowSeqPeerSk, localPublicKey: lowSeqPeerPk, localRevocationRecords: [lowSeqHard], - requireProofRef: true, }); const authHighSeqPeer = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: highSeqPeerSk, localPublicKey: highSeqPeerPk, localRevocationRecords: [highSeqCutover], - requireProofRef: true, }); const writerHelloCaps = await authWriter.helloCapabilities?.({ docId }); @@ -2708,7 +2750,11 @@ test('auth: out-of-order revocation records use highest rev_seq even when it arr node: nodeIdFromInt(30), orderKey: orderKeyFromPosition(0), }); - const auth1 = await authWriter.signOps?.([op1], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth1 = await authWriter.signOps?.([op1], { + docId, + purpose: 'local_write', + filterId: 'all', + }); const lowSeqCaps = await authLowSeqPeer.helloCapabilities?.({ docId }); await authVerifier.onHello?.(helloWithCapabilities(lowSeqCaps ?? []), { docId }); @@ -2734,7 +2780,11 @@ test('auth: out-of-order revocation records use highest rev_seq even when it arr node: nodeIdFromInt(31), orderKey: orderKeyFromPosition(1), }); - const auth2 = await authWriter.signOps?.([op2], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth2 = await authWriter.signOps?.([op2], { + docId, + purpose: 'local_write', + filterId: 'all', + }); await expect( authVerifier.verifyOps?.([op2], auth2 ?? undefined, { docId, @@ -2795,19 +2845,16 @@ test('auth: same rev_seq revocation conflicts converge regardless delivery order localPrivateKey: writerSk, localPublicKey: writerPk, localCapabilityTokens: [writerToken], - requireProofRef: true, }); const authVerifierA = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: verifierASk, localPublicKey: verifierAPk, - requireProofRef: true, }); const authVerifierB = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: verifierBSk, localPublicKey: verifierBPk, - requireProofRef: true, }); const authHardPeer = createTreecrdtCoseCwtAuth({ @@ -2815,14 +2862,12 @@ test('auth: same rev_seq revocation conflicts converge regardless delivery order localPrivateKey: hardPeerSk, localPublicKey: hardPeerPk, localRevocationRecords: [hardRecord], - requireProofRef: true, }); const authCutoverPeer = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], localPrivateKey: cutoverPeerSk, localPublicKey: cutoverPeerPk, localRevocationRecords: [cutoverRecord], - requireProofRef: true, }); const writerHelloCaps = await authWriter.helloCapabilities?.({ docId }); @@ -2835,7 +2880,11 @@ test('auth: same rev_seq revocation conflicts converge regardless delivery order node: nodeIdFromInt(40), orderKey: orderKeyFromPosition(0), }); - const auth1 = await authWriter.signOps?.([op1], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth1 = await authWriter.signOps?.([op1], { + docId, + purpose: 'local_write', + filterId: 'all', + }); const op2: Operation = makeOp(writerPk, 2, 2, { type: 'insert', @@ -2843,7 +2892,11 @@ test('auth: same rev_seq revocation conflicts converge regardless delivery order node: nodeIdFromInt(41), orderKey: orderKeyFromPosition(1), }); - const auth2 = await authWriter.signOps?.([op2], { docId, purpose: 'reconcile', filterId: 'all' }); + const auth2 = await authWriter.signOps?.([op2], { + docId, + purpose: 'local_write', + filterId: 'all', + }); const hardCaps = await authHardPeer.helloCapabilities?.({ docId }); const cutoverCaps = await authCutoverPeer.helloCapabilities?.({ docId }); @@ -3029,7 +3082,6 @@ test('auth: records peer identity chain capability via onPeerIdentityChain', asy issuerPublicKeys: [issuerPk], localPrivateKey: localSk, localPublicKey: localPk, - requireProofRef: true, onPeerIdentityChain: (c) => { seen = { identityPkHex: bytesToHex(c.identityPublicKey), diff --git a/packages/treecrdt-auth/tests/op-sig.test.ts b/packages/treecrdt-auth/tests/op-sig.test.ts index 32796c70..b3c951b7 100644 --- a/packages/treecrdt-auth/tests/op-sig.test.ts +++ b/packages/treecrdt-auth/tests/op-sig.test.ts @@ -12,6 +12,7 @@ import { ed25519Hashes.sha512 = sha512; const node = '00112233445566778899aabbccddeeff'; +const proofRef = new Uint8Array(16).fill(7); const meta = { id: { replica: new Uint8Array(32), counter: 1 }, lamport: 1, @@ -33,20 +34,33 @@ test('one signature format binds the explicit knownState field', async () => { const state = knownState(); const op = operation({ type: 'delete', node }, state); - const input = encodeTreecrdtOpSigInput({ docId: 'doc', op }); + const input = encodeTreecrdtOpSigInput({ docId: 'doc', op, proofRef }); const domain = new TextEncoder().encode('treecrdt/op-sig/v1'); expect(input.slice(0, domain.length + 1)).toEqual(Uint8Array.from([...domain, 0])); + expect(input.slice(domain.length + 1, domain.length + 17)).toEqual(proofRef); expect(input.slice(-(state.length + 5), -state.length)).toEqual( Uint8Array.from([1, 0, 0, 0, state.length]), ); expect(input.slice(-state.length)).toEqual(state); - const signature = await signTreecrdtOp({ docId: 'doc', op, privateKey }); - await expect(verifyTreecrdtOp({ docId: 'doc', op, signature, publicKey })).resolves.toBe(true); + const signature = await signTreecrdtOp({ docId: 'doc', op, proofRef, privateKey }); + await expect( + verifyTreecrdtOp({ docId: 'doc', op, proofRef, signature, publicKey }), + ).resolves.toBe(true); + await expect( + verifyTreecrdtOp({ + docId: 'doc', + op, + proofRef: new Uint8Array(16).fill(8), + signature, + publicKey, + }), + ).resolves.toBe(false); await expect( verifyTreecrdtOp({ docId: 'doc', op: { ...op, meta: { ...op.meta, knownState: knownState(1) } }, + proofRef, signature, publicKey, }), @@ -55,6 +69,7 @@ test('one signature format binds the explicit knownState field', async () => { verifyTreecrdtOp({ docId: 'doc', op: operation(op.kind), + proofRef, signature, publicKey, }), @@ -64,6 +79,7 @@ test('one signature format binds the explicit knownState field', async () => { encodeTreecrdtOpSigInput({ docId: 'doc', op: operation({ type: 'delete', node }, new TextEncoder().encode('{ "entries": [] }')), + proofRef, }), ).toThrow(/canonical/i); }); @@ -78,6 +94,7 @@ test('canonical knownState accepts normalized gapped ranges', () => { encodeTreecrdtOpSigInput({ docId: 'doc', op: operation({ type: 'delete', node }, state), + proofRef, }), ).not.toThrow(); }); @@ -117,6 +134,7 @@ test.each<[string, number, Array<[number, number]>]>([ encodeTreecrdtOpSigInput({ docId: 'doc', op: operation({ type: 'delete', node }, knownState(frontier, ranges)), + proofRef, }), ).toThrow(/Number\.MAX_SAFE_INTEGER/); }); @@ -144,14 +162,14 @@ test('signature policy only allows knownState on deletes', async () => { for (const kind of nonDeleteKinds) { await expect( - signTreecrdtOp({ docId: 'doc', op: operation(kind, state), privateKey }), + signTreecrdtOp({ docId: 'doc', op: operation(kind, state), proofRef, privateKey }), ).rejects.toThrow(/only allowed on delete/i); } const tombstone = operation({ type: 'tombstone', node }); - expect(encodeTreecrdtOpSigInput({ docId: 'doc', op: tombstone }).at(-1)).toBe(0); - const signature = await signTreecrdtOp({ docId: 'doc', op: tombstone, privateKey }); + expect(encodeTreecrdtOpSigInput({ docId: 'doc', op: tombstone, proofRef }).at(-1)).toBe(0); + const signature = await signTreecrdtOp({ docId: 'doc', op: tombstone, proofRef, privateKey }); await expect( - verifyTreecrdtOp({ docId: 'doc', op: tombstone, signature, publicKey }), + verifyTreecrdtOp({ docId: 'doc', op: tombstone, proofRef, signature, publicKey }), ).resolves.toBe(true); }); diff --git a/packages/treecrdt-engine-conformance/src/index.ts b/packages/treecrdt-engine-conformance/src/index.ts index 819dd828..602ffb69 100644 --- a/packages/treecrdt-engine-conformance/src/index.ts +++ b/packages/treecrdt-engine-conformance/src/index.ts @@ -5,6 +5,7 @@ import type { SqliteRunner } from '@treecrdt/interface/sqlite'; import type { Filter, OpRef } from '@treecrdt/sync-protocol'; import { + createTreecrdtAuthSession, createTreecrdtCoseCwtAuth, createTreecrdtSqliteSubtreeScopeEvaluator, getEd25519PublicKey, @@ -1435,6 +1436,22 @@ function makeCapabilityTokenV1(opts: { }); } +async function createReadyAuthSession( + docId: string, + issuerPublicKey: Uint8Array, + privateKey: Uint8Array, + publicKey: Uint8Array, + capabilityTokens: Uint8Array[], +) { + const session = createTreecrdtAuthSession({ + docId, + trust: { issuerPublicKeys: [issuerPublicKey] }, + local: { privateKey, publicKey, capabilityTokens }, + }); + await session.ready; + return session; +} + function maxLamportFromOps(ops: Operation[]): number { return ops.reduce((max, op) => Math.max(max, op.meta.lamport), 0); } @@ -1535,11 +1552,6 @@ async function scenarioSyncAuthSignedOps(ctx: TreecrdtEngineConformanceContext): const bSk = randomEd25519SecretKey(); const bPk = await getEd25519PublicKey(bSk); - const root = nodeIdFromInt(0); - await a.local.insert(aPk, root, nodeIdFromInt(1), { type: 'last' }, null); - await b.local.insert(bPk, root, nodeIdFromInt(2), { type: 'last' }, null); - await b.local.insert(bPk, root, nodeIdFromInt(3), { type: 'last' }, null); - const tokenA = makeCapabilityTokenV1({ issuerPrivateKey: issuerSk, subjectPublicKey: aPk, @@ -1551,20 +1563,18 @@ async function scenarioSyncAuthSignedOps(ctx: TreecrdtEngineConformanceContext): docId, }); - const authA = createTreecrdtCoseCwtAuth({ - issuerPublicKeys: [issuerPk], - localPrivateKey: aSk, - localPublicKey: aPk, - localCapabilityTokens: [tokenA], - requireProofRef: true, - }); + const sessionA = await createReadyAuthSession(docId, issuerPk, aSk, aPk, [tokenA]); + const sessionB = await createReadyAuthSession(docId, issuerPk, bSk, bPk, [tokenB]); - const authB = createTreecrdtCoseCwtAuth({ - issuerPublicKeys: [issuerPk], - localPrivateKey: bSk, - localPublicKey: bPk, - localCapabilityTokens: [tokenB], - requireProofRef: true, + const root = nodeIdFromInt(0); + await a.local.insert(aPk, root, nodeIdFromInt(1), { type: 'last' }, null, { + authSession: sessionA, + }); + await b.local.insert(bPk, root, nodeIdFromInt(2), { type: 'last' }, null, { + authSession: sessionB, + }); + await b.local.insert(bPk, root, nodeIdFromInt(3), { type: 'last' }, null, { + authSession: sessionB, }); const backendA = createEngineSyncBackend(a); @@ -1574,8 +1584,8 @@ async function scenarioSyncAuthSignedOps(ctx: TreecrdtEngineConformanceContext): backendA, backendB, codec: treecrdtSyncV0ProtobufCodec, - peerAOptions: { auth: authA }, - peerBOptions: { auth: authB, maxOpsPerBatch: 1 }, + peerAOptions: { auth: sessionA.syncAuth }, + peerBOptions: { auth: sessionB.syncAuth, maxOpsPerBatch: 1 }, }); try { @@ -1617,8 +1627,8 @@ async function scenarioSyncAuthScopedTokenRejectsAllFilter( const aPk = await getEd25519PublicKey(aSk); const bSk = randomEd25519SecretKey(); const bPk = await getEd25519PublicKey(bSk); - const root = nodeIdFromInt(0); + // Seed operations without auth: this case must reject the scoped filter before reconciliation. await a.local.insert(aPk, root, nodeIdFromInt(1), { type: 'last' }, null); await b.local.insert(bPk, root, nodeIdFromInt(2), { type: 'last' }, null); @@ -1643,7 +1653,6 @@ async function scenarioSyncAuthScopedTokenRejectsAllFilter( localPrivateKey: aSk, localPublicKey: aPk, localCapabilityTokens: [tokenA], - requireProofRef: true, }); const authB = createTreecrdtCoseCwtAuth({ @@ -1651,7 +1660,6 @@ async function scenarioSyncAuthScopedTokenRejectsAllFilter( localPrivateKey: bSk, localPublicKey: bPk, localCapabilityTokens: [tokenB], - requireProofRef: true, }); const backendA = createEngineSyncBackend(a); @@ -1793,13 +1801,7 @@ async function scenarioSyncAuthRestartRelayReServesSignedOps( docId, }); - const authA = createTreecrdtCoseCwtAuth({ - issuerPublicKeys: [issuerPk], - localPrivateKey: aSk, - localPublicKey: aPk, - localCapabilityTokens: [tokenA], - requireProofRef: true, - }); + const sessionA = await createReadyAuthSession(docId, issuerPk, aSk, aPk, [tokenA]); const authRelay1 = createTreecrdtCoseCwtAuth({ issuerPublicKeys: [issuerPk], @@ -1807,15 +1809,18 @@ async function scenarioSyncAuthRestartRelayReServesSignedOps( localPublicKey: bPk, // Advertise tokenA so downstream peers can verify A's ops (A is offline after relay restart). localCapabilityTokens: [tokenB, tokenA], - requireProofRef: true, opAuthStore: opAuthRelay1, }); const root = nodeIdFromInt(0); const subtreeRoot = nodeIdFromInt(1); const child = nodeIdFromInt(2); - await a.local.insert(aPk, root, subtreeRoot, { type: 'last' }, null); - await a.local.insert(aPk, subtreeRoot, child, { type: 'last' }, null); + await a.local.insert(aPk, root, subtreeRoot, { type: 'last' }, null, { + authSession: sessionA, + }); + await a.local.insert(aPk, subtreeRoot, child, { type: 'last' }, null, { + authSession: sessionA, + }); const backendA = createEngineSyncBackend(a); const backendRelay1 = createEngineSyncBackend(relay1); @@ -1828,7 +1833,7 @@ async function scenarioSyncAuthRestartRelayReServesSignedOps( backendA, backendB: backendRelay1, codec: treecrdtSyncV0ProtobufCodec, - peerAOptions: { auth: authA }, + peerAOptions: { auth: sessionA.syncAuth }, peerBOptions: { auth: authRelay1 }, }); @@ -1856,7 +1861,6 @@ async function scenarioSyncAuthRestartRelayReServesSignedOps( localPrivateKey: bSk, localPublicKey: bPk, localCapabilityTokens: [tokenB, tokenA], - requireProofRef: true, opAuthStore: opAuthRelay2, }); @@ -1865,7 +1869,6 @@ async function scenarioSyncAuthRestartRelayReServesSignedOps( localPrivateKey: cSk, localPublicKey: cPk, localCapabilityTokens: [tokenC], - requireProofRef: true, }); const c = await ctx.createEngine({ docId, name: 'peer-c' }); diff --git a/packages/treecrdt-postgres-napi/tests/conformance.test.ts b/packages/treecrdt-postgres-napi/tests/conformance.test.ts index 715ded92..00e7052e 100644 --- a/packages/treecrdt-postgres-napi/tests/conformance.test.ts +++ b/packages/treecrdt-postgres-napi/tests/conformance.test.ts @@ -117,6 +117,7 @@ maybeDescribe('engine conformance scenarios (postgres-napi engine)', () => { const authSession = { authorizeLocalOps: vi.fn(async () => { expect(events).toHaveLength(0); + return [{ sig: new Uint8Array(64), proofRef: new Uint8Array(16) }]; }), }; const node = nodeIdFromInt(11); diff --git a/packages/treecrdt-sqlite-node/tests/conformance.test.ts b/packages/treecrdt-sqlite-node/tests/conformance.test.ts index 2fac6a18..43e0cb20 100644 --- a/packages/treecrdt-sqlite-node/tests/conformance.test.ts +++ b/packages/treecrdt-sqlite-node/tests/conformance.test.ts @@ -73,6 +73,7 @@ test('sqlite auth-aware local write emits materialization after auth succeeds', const authSession = { authorizeLocalOps: vi.fn(async () => { expect(events).toHaveLength(0); + return [{ sig: new Uint8Array(64), proofRef: new Uint8Array(16) }]; }), }; const node = nodeIdFromInt(11); diff --git a/packages/treecrdt-ts/src/engine.ts b/packages/treecrdt-ts/src/engine.ts index c6e8a58e..bc9871ae 100644 --- a/packages/treecrdt-ts/src/engine.ts +++ b/packages/treecrdt-ts/src/engine.ts @@ -128,8 +128,14 @@ export type WriteOptions = { writeId?: string; }; +/** Standard proof material that a backend can persist atomically with a local operation. */ +export type LocalWriteAuthProof = { + sig: Uint8Array; + proofRef: Uint8Array; +}; + export type LocalWriteAuthSession = { - authorizeLocalOps: (ops: readonly Operation[]) => Promise; + authorizeLocalOps: (ops: readonly Operation[]) => Promise; }; export type LocalWriteOptions = { diff --git a/packages/treecrdt-wa-sqlite/e2e/src/sync.ts b/packages/treecrdt-wa-sqlite/e2e/src/sync.ts index 0cfd80ff..40014f40 100644 --- a/packages/treecrdt-wa-sqlite/e2e/src/sync.ts +++ b/packages/treecrdt-wa-sqlite/e2e/src/sync.ts @@ -363,6 +363,7 @@ async function runAuthLocalWriteCase(opts: { storage: 'memory' | 'opfs' }): Prom const allowAuth: LocalWriteOptions['authSession'] = { authorizeLocalOps: async () => { authorizedBeforeEvent = events.length === 0; + return [{ sig: new Uint8Array(64), proofRef: new Uint8Array(16) }]; }, };