Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/atomic-local-auth-proof-handoff.md
Original file line number Diff line number Diff line change
@@ -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.
29 changes: 16 additions & 13 deletions docs/sync/v0/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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),
Expand Down Expand Up @@ -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)

Expand All @@ -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,
Expand All @@ -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)
);
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions docs/sync/v0/messages.proto
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -48,9 +48,9 @@ export function usePlaygroundAuthSession(
} = opts;
const [syncAuth, setSyncAuth] = useState<SyncAuth<Operation> | null>(null);
const localAuthSessionRef = useRef<TreecrdtAuthSession | null>(null);
const localIdentityChainPromiseRef = useRef<
Promise<Awaited<ReturnType<typeof createLocalIdentityChainV1>> | null> | null
>(null);
const localIdentityChainPromiseRef = useRef<Promise<Awaited<
ReturnType<typeof createLocalIdentityChainV1>
> | null> | null>(null);

useEffect(() => {
// Local identity chains are doc-bound (replica cert includes `docId`) and depend on the current replica key.
Expand All @@ -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;
});
}
Expand Down Expand Up @@ -127,7 +127,6 @@ export function usePlaygroundAuthSession(
capabilityTokens: localTokens,
},
revokedCapabilityTokenIds: hardRevokedTokenIdBytes,
requireProofRef: true,
identity: {
onPeer: onPeerIdentityChain,
local: getLocalIdentityChain,
Expand Down Expand Up @@ -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]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
);
Expand All @@ -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,
Expand Down Expand Up @@ -138,7 +138,7 @@ export function createOpAuthStore(opts: {

const params: Array<string | number | Uint8Array | null> = [];
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);
Expand All @@ -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<string, OpAuth>();
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);
Expand Down Expand Up @@ -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(),
Expand All @@ -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;
}>(
Expand All @@ -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'
Expand Down
36 changes: 18 additions & 18 deletions packages/sync-protocol/material/sqlite/src/proof-material/sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
);
Expand Down Expand Up @@ -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(),
Expand All @@ -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;
}>;
Expand All @@ -162,17 +161,15 @@ 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}`);
}

return {
op,
auth: { sig, ...(proofRef ? { proofRef } : {}) },
auth: { sig, proofRef },
reason: 'missing_context',
...(r.message ? { message: r.message } : {}),
} satisfies PendingOp<Operation>;
Expand Down Expand Up @@ -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(),
]);
}
},

Expand All @@ -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<string, OpAuth>();
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);
Expand Down
2 changes: 1 addition & 1 deletion packages/sync-protocol/protocol/src/auth.ts
Original file line number Diff line number Diff line change
@@ -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' }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -414,8 +414,8 @@ export const OpsBatchSchema: GenMessage<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.
*
* @generated from message treecrdt.sync.v0.OpAuth
*/
Expand All @@ -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;
*/
Expand Down
Loading
Loading