Skip to content
Merged
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
46 changes: 46 additions & 0 deletions doc/2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,52 @@ The importing node verifies before ingesting anything:
hosted-origin objects are indistinguishable from self-hosted ones at
the object layer.

### 6.3 Object-model mapping (slice 4b, #13157)

The wiring from a live per-user store to the §6.1 format settles the
mapping between the store's object model and the export's:

- **Bytes.** An export object's bytes are the stored signed envelope
(the p2panda header) **verbatim**. The store of record keeps the
received bytes as the event and never re-encodes or re-signs them;
the export doesn't either. The producer never re-signs an object
with any key — it holds none it could sign with.
- **Hash.** The object's export hash is SHA-256 of the envelope
bytes. It is the export-layer digest: canonical (hash) order and
the manifest's concatenated-hash digest are computed over it. The
envelope's own BLAKE3 operation id remains its identity at the
object layer; neither hash replaces the other.
- **Signer and signature.** The signer is the envelope's author and
the signature is the envelope's own — Ed25519 over the canonical
header encoding, the object's native scheme. §6.2 step 3's "hash
and signature verify" therefore reads: the hash is SHA-256 of the
received bytes, and the signature verifies by decoding the
envelope exactly as the native decoder does, with the decoded
author equal to the named signer and the signer a key in the
binding chain (§6.2 step 2's chain).
- **Blob citations.** A `document.put` envelope cites its content
by BLAKE3 (`DocumentRef.content`, the native blob identity),
while hosted R2 blobs are SHA-256-addressed (the per-user
reference table is the access path). The producer resolves
citations by content: a fetched blob whose BLAKE3 equals the
citation is the cited blob, and the export names it — in the
blob set and in the object's references — by its SHA-256 hash.
A citation no referenced blob satisfies, or a referenced blob R2
cannot produce, fails the export loudly, naming the hash; an
export is never silently incomplete. Blobs no exported object
cites are not exported (§6.1 item 2, §6.2's unreferenced-blob
rule).
- **Object set.** The exported objects are the store's *applied*
events — the graph. Waiting-pool events (dependencies unmet, not
yet graph objects) and fork-proof headers (evidence about the
graph) are not exported.

Production lives in the hosted data plane (`hosted-worker/src/
export.ts`, served by the DO's `GET /v1/bridge/export` route under
the bridge's ID-key proof); assembly into the full export
(manifest, binding record, rebind records) is `build_export` on
the binding-service side.

## 7. Client-side-encryption option

Offered at binding time (and changeable later only by re-encrypting via
Expand Down
11 changes: 11 additions & 0 deletions pkgs/id/hosted-worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,17 @@ serves no authoritative snapshot.
ceiling. Design record:
`doc/2026-11-23T05-00-00Z_design_bridge_v1_implementation/`.
Cross-language fixtures: `pkgs/id/tests/bridge_fixtures.rs`.
- `src/export.ts` — §6 export production (slice 4b of #2852,
#13157): enumerates the DO's applied events and the R2 blobs
they cite into the object/blob sets `build_export`
(`pkgs/id/src/hosted_export.rs`) assembles, under the
object-model mapping recorded in the spec as §6.3. Route:
`GET /v1/bridge/export`, ID-key proof like the other bridge
HTTPS legs; a pure read, available at cap, and a referenced
blob R2 cannot produce fails it loudly (502 naming the hash).
The produced sets are pinned to
`test/fixtures/hosted-export-sets.json`, which the Rust suite
verifies through `build_export` + `verify_import`.

## Tests

Expand Down
2 changes: 1 addition & 1 deletion pkgs/id/hosted-worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"dev": "wrangler dev",
"typecheck": "tsc --noEmit",
"test": "node --experimental-transform-types --test test/routing.test.ts test/admission-gate.test.ts test/provisioning.test.ts test/provisioning-surface.test.ts test/blobs.test.ts test/canonical-cbor.test.ts test/usage.test.ts test/currency.test.ts test/front-door.test.ts test/id-uri-vectors.test.ts test/bridge-blake3.test.ts test/bridge-event.test.ts test/bridge-range.test.ts test/bridge-store.test.ts test/bridge-session.test.ts test/bridge-do.test.ts",
"test": "node --experimental-transform-types --test test/routing.test.ts test/admission-gate.test.ts test/provisioning.test.ts test/provisioning-surface.test.ts test/blobs.test.ts test/canonical-cbor.test.ts test/usage.test.ts test/currency.test.ts test/front-door.test.ts test/id-uri-vectors.test.ts test/bridge-blake3.test.ts test/bridge-event.test.ts test/bridge-range.test.ts test/bridge-store.test.ts test/bridge-session.test.ts test/bridge-do.test.ts test/export.test.ts",
"smoke": "node smoke/smoke.mjs"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion pkgs/id/hosted-worker/src/bridge-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import type { BridgeStore } from "./bridge-store.ts";
export const NONCE_TTL_MS = 5 * 60 * 1000;
export const RESUME_TOKEN_TTL_MS = 24 * 3600 * 1000;

export type AuthContext = "push" | "pull" | "heads" | "ws";
export type AuthContext = "push" | "pull" | "heads" | "ws" | "export";

export function authTranscript(
bindingId: string,
Expand Down
17 changes: 17 additions & 0 deletions pkgs/id/hosted-worker/src/bridge-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,23 @@ export class BridgeStore {
.filter((e): e is HeldEvent => e !== null);
}

/** The applied chain events — the graph itself, in (author, seq)
* order. The §6 export set (export.ts) is exactly these: waiting
* events are not yet graph objects (their dependencies are unmet)
* and fork-proof headers are evidence about the graph, not part
* of it, so neither is enumerated here. */
appliedEvents(): HeldEvent[] {
return this.sql
.exec("SELECT author, seq, id, bytes FROM bridge_events ORDER BY author, seq")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restrict exported events to the applied chain prefix

When a fork is discovered after one branch has already been stored, refreshAuthor() reduces the applied frontier to the fork sequence but retains the branch's rows in bridge_events. This unfiltered query therefore exports events that are no longer applied, while the exporter deliberately omits the competing fork-proof header. In an in-memory reproduction, ingesting e0,a1 followed by conflicting b1 leaves the chain frozen with next_seq: 1, but appliedEvents() returns sequences [0,1]. Restoring that export can reactivate the known-forked branch and its suffix. Filter the enumeration against each author's applied frontier rather than exporting every retained row.

Useful? React with 👍 / 👎.

.toArray()
.map((r) => ({
author: r.author as string,
seq: Number(r.seq),
id: r.id as string,
bytes: blobBytes(r.bytes),
}));
}

/** Bytes stored by this store, for the storage ceiling. */
storedBytes(): number {
const rows = this.sql.exec(
Expand Down
7 changes: 7 additions & 0 deletions pkgs/id/hosted-worker/src/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ export interface SignedEvent {
bytes: Uint8Array;
author: Uint8Array;
authorHex: string;
/** The envelope's own Ed25519 signature (over the signing bytes),
* carried verbatim: the §6 export mapping (export.ts) names it as
* the object's signature — a stored event is never re-signed. */
signature: Uint8Array;
signatureHex: string;
seq: number;
backlink: Uint8Array | null;
backlinkHex: string | null;
Expand Down Expand Up @@ -321,6 +326,8 @@ function parseEventParts(bytes: Uint8Array): EventParts {
bytes,
author,
authorHex: bytesToHex(author),
signature,
signatureHex: bytesToHex(signature),
seq,
backlink,
backlinkHex: backlink ? bytesToHex(backlink) : null,
Expand Down
232 changes: 232 additions & 0 deletions pkgs/id/hosted-worker/src/export.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
// §6 export production (spec §6.1 items 1–2; #2852 slice 4b,
// #13157): enumerate a per-user DO's applied signed objects and the
// R2 blobs they cite, as the object/blob sets `build_export`
// (pkgs/id/src/hosted_export.rs) assembles into a `HostedExport`.
// The binding record, its rebind records, and the manifest live on
// the binding-service side; this module is the data-plane half —
// everything the DO itself can produce, as a pure read. Export
// therefore stays available from a read-only, at-cap store (§5.4):
// nothing here writes.
//
// The object-model mapping this wiring settles (spec §6.3):
//
// - `bytes` is the stored envelope bytes verbatim. The bridge never
// re-encodes or re-signs a stored event; the export doesn't
// either.
// - `hash` is SHA-256 of the envelope bytes: the export-layer
// digest that canonical (hash) order and the manifest's
// concatenated-hash digest are computed over. The envelope's own
// BLAKE3 id remains its identity at the object layer.
// - `signer` is the envelope's author key and `signature` is the
// envelope's own signature, over the canonical header encoding —
// the object's own signature scheme, verified at import by
// decoding the envelope exactly as chain.rs `decode` does. The
// producer never re-signs: it holds no key it could sign with.
// - Payload bodies are not held by this store (the bridge keeps
// headers; a header's payload_hash commits to off-store data)
// and are not §6 blobs of this store — document content is the
// blob path, mapped as follows.
// - Blob citations: a `document.put` envelope cites its content by
// BLAKE3 (`DocumentRef.content`, the native blob identity), while
// this store's R2 blobs are SHA-256-addressed (the slice-A
// reference table). Citations are resolved by content: a fetched
// blob whose BLAKE3 equals the citation is the cited blob, and
// the export names it by its SHA-256 hash (§6 form). A citation
// no referenced blob satisfies — or a referenced blob R2 cannot
// produce — fails the export loudly, naming the hash; an export
// is never silently incomplete. Blobs no applied object cites
// are not exported (§6.1 item 2, §6.2's unreferenced-blob rule).

import { decodeCanonical, type CborValue } from "./canonical-cbor.ts";
import { blake3 } from "./blake3.ts";
import { bytesToHex } from "./ed25519.ts";
import { parseEvent } from "./event.ts";
import type { HeldEvent } from "./bridge-store.ts";

/** One §6 object (§6.1 item 1) in the `ExportObject` wire shape,
* with bytes still binary; `exportSetsToWire` renders the JSON
* form serde expects on the Rust side. */
export interface ExportObjectSet {
hash: string;
signer: string;
signature: string;
blob_refs: string[];
bytes: Uint8Array;
}

/** One §6 blob (§6.1 item 2) in the `ExportBlob` wire shape. */
export interface ExportBlobSet {
hash: string;
bytes: Uint8Array;
}

/** The object/blob sets of a §6 export, in canonical (hash)
* order, with the manifest's counts and concatenated-hash digest
* (§6.1 item 4) computed over exactly these sets. */
export interface ExportSets {
objects: ExportObjectSet[];
blobs: ExportBlobSet[];
object_count: number;
blob_count: number;
objects_digest: string;
}

/** A named export-production failure. `hash` is the hash the
* failure names: the cited content hash (BLAKE3) an object needs
* and no referenced blob produces, or the reference hash (SHA-256)
* whose stored bytes R2 cannot produce or cannot verify. */
export class ExportProductionError extends Error {
readonly hash: string;
constructor(hash: string, message: string) {
super(message);
this.hash = hash;
}
}

async function sha256Hex(bytes: Uint8Array): Promise<string> {
const digest = await crypto.subtle.digest("SHA-256", bytes as BufferSource);
return bytesToHex(new Uint8Array(digest));
}

function mapGet(map: CborValue, key: string): CborValue | undefined {
if (map.kind !== "map") return undefined;
for (const [k, v] of map.value) {
if (k.kind === "text" && k.value === key) return v;
}
return undefined;
}

/** The BLAKE3 content hashes an envelope cites: the `content` of
* its `document` payload (`document.put`), and nothing else — in
* the current `ChainExt` form one envelope cites at most one
* content. The envelope was verified at ingest; a document payload
* that does not carry a 32-byte content hash is corruption, and is
* refused as such rather than silently uncited. */
export function citedContentHashes(bytes: Uint8Array, eventId: string): string[] {
const root = decodeCanonical(bytes);
if (root.kind !== "array" || root.value.length === 0) {
throw new ExportProductionError(eventId, `stored event ${eventId} is not a header array`);
}
const ext = root.value[root.value.length - 1];
const document = mapGet(ext, "document");
if (document === undefined) return [];
Comment on lines +111 to +112

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Include blob citations from notes and chat messages

When content is referenced only by a note or a chat attachment, this early return silently treats it as unreferenced and excludes its bytes from the export. The existing native model also carries blob citations in NoteOp::Create and NoteOp::Revise through their content: DocumentRef fields (crates/id-store/src/notes.rs:41–55), and in chat links with ChatLinkKind::Blob (crates/id-store/src/chat.rs:68–95). A read-only reproduction with a signed note.create and its uploaded content produces one object but zero blobs and empty blob_refs, so restoring the archive loses the note's content despite a successful export. Enumerate all supported blob-carrying payload variants in both this helper and the Rust counterpart.

Useful? React with 👍 / 👎.

const content = mapGet(document, "content");
if (!content || content.kind !== "bytes" || content.value.length !== 32) {
throw new ExportProductionError(
eventId,
`stored event ${eventId} carries a document payload with no 32-byte content hash`,
);
}
return [bytesToHex(content.value)];
}

/** Produce the §6 object/blob sets from a store enumeration.
*
* `events` is the store's applied events (`BridgeStore
* .appliedEvents()`); `blobRefs` is the user's blob reference
* table (SHA-256 hashes, the slice-A access path); `fetchBlob`
* reads one blob's bytes from R2 by its reference hash, returning
* null when R2 cannot produce it. */
export async function produceExportSets(
events: HeldEvent[],
blobRefs: { hash: string }[],
fetchBlob: (hash: string) => Promise<Uint8Array | null>,
): Promise<ExportSets> {
// Fetch and verify every referenced blob first: the export is
// assembled only from bytes that hash to their reference.
const blobsBySha = new Map<string, ExportBlobSet>();
const shaByContent = new Map<string, string>();
for (const ref of blobRefs) {
const bytes = await fetchBlob(ref.hash);
if (bytes === null) {
throw new ExportProductionError(
ref.hash,
`blob ${ref.hash} is referenced by this store but R2 cannot produce it`,
);
}
const actual = await sha256Hex(bytes);
if (actual !== ref.hash) {
throw new ExportProductionError(
ref.hash,
`blob bytes fetched for ${ref.hash} hash to ${actual}; the stored blob is corrupt`,
);
}
blobsBySha.set(ref.hash, { hash: ref.hash, bytes });
shaByContent.set(bytesToHex(blake3(bytes)), ref.hash);
}

const objects: ExportObjectSet[] = [];
const citedShas = new Set<string>();
for (const held of events) {
const event = parseEvent(held.bytes);
const refs: string[] = [];
for (const cited of citedContentHashes(held.bytes, held.id)) {
const sha = shaByContent.get(cited);
if (sha === undefined) {
throw new ExportProductionError(
cited,
`object ${held.id} cites content ${cited} but no referenced blob produces it`,
);
}
refs.push(sha);
citedShas.add(sha);
}
refs.sort();
objects.push({
hash: await sha256Hex(held.bytes),
signer: event.authorHex,
signature: event.signatureHex,
blob_refs: [...new Set(refs)],
bytes: held.bytes,
});
}
objects.sort((a, b) => (a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0));

const blobs = [...citedShas].map((sha) => blobsBySha.get(sha) as ExportBlobSet);
blobs.sort((a, b) => (a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0));

// §6.1 item 4: SHA-256 of the concatenated object hash bytes,
// objects in canonical (hash) order — the same computation
// hosted_export.rs performs over the received set.
const concatenated = new Uint8Array(objects.length * 32);
objects.forEach((object, i) => {
for (let j = 0; j < 32; j++) {
concatenated[i * 32 + j] = parseInt(object.hash.slice(j * 2, j * 2 + 2), 16);
}
});
const objects_digest = await sha256Hex(concatenated);

return {
objects,
blobs,
object_count: objects.length,
blob_count: blobs.length,
objects_digest,
};
}

/** The JSON wire form of the sets: byte fields as number arrays,
* exactly the serde shape of `ExportObject` / `ExportBlob` in
* hosted_export.rs, so the binding-service side can feed the sets
* to `build_export` without a translation layer. */
export function exportSetsToWire(sets: ExportSets): {
objects: { hash: string; signer: string; signature: string; blob_refs: string[]; bytes: number[] }[];
blobs: { hash: string; bytes: number[] }[];
object_count: number;
blob_count: number;
objects_digest: string;
} {
return {
objects: sets.objects.map((o) => ({
hash: o.hash,
signer: o.signer,
signature: o.signature,
blob_refs: o.blob_refs,
bytes: [...o.bytes],
})),
blobs: sets.blobs.map((b) => ({ hash: b.hash, bytes: [...b.bytes] })),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stream blob bytes instead of expanding the whole export in memory

For stores containing moderately large blobs, this expands every buffered blob into a JavaScript number array before user-do.ts additionally stringifies the entire response. The Worker/DO has a 128 MB isolate memory budget, while blob uploads permit up to 100 MiB and aggregate storage is uncapped by default; even a single blob well below the upload limit can exhaust memory during this conversion. Consequently, valid populated stores cannot export their data, including capped stores for which export is explicitly intended to remain available. Use bounded streaming or chunked export rather than retaining the complete binary, numeric-array, and JSON representations simultaneously.

Useful? React with 👍 / 👎.

object_count: sets.object_count,
blob_count: sets.blob_count,
objects_digest: sets.objects_digest,
};
}
Loading