Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

feat(relay): store sealed pages and pin readers [H15,H17,H18]

Corey Olson52a2cc581d50
diff --git a/relay/page-store.js b/relay/page-store.js
new file mode 100644
index 00000000..36c1c95d
--- /dev/null
+++ b/relay/page-store.js
@@ -0,0 +1,230 @@
+/** Durable opaque snapshot objects, staged uploads and renewable reader pins; keys stay on devices [H15,H17,H18]. */
+import { createHash, randomUUID } from 'node:crypto';
+import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import { Refused } from '../src/refused.js';
+import { PAGE_CIPHER_BYTES, PAGE_FANOUT, pageReference } from '../src/sealed-pages.js';
+
+const UPLOAD_MS = 3_600_000;
+const READ_MS = 900_000;
+const MAX_DEPTH = 64;
+
+/** Validate content identities without ever treating request text as a filename. */
+function objectId(value) {
+ if (typeof value !== 'string' || !/^[0-9a-f]{64}$/u.test(value)) throw new Refused('BAD_PAGE', 'Use the encrypted page content id returned by this device.');
+ return value;
+}
+
+/** Bind sessions to server-derived user and device attribution, never an uploaded account field. */
+function principalKey(principal) {
+ if (!principal || !['person', 'machine', 'agent'].includes(principal.kind) || typeof principal.userId !== 'string' || !principal.userId ||
+ principal.kind === 'machine' && typeof principal.machine !== 'string' || principal.kind === 'agent' && typeof principal.agent !== 'string') throw new Refused('BAD_SENDER', 'Use the server-authenticated user and device for sealed page access.');
+ return JSON.stringify([principal.userId, principal.kind, principal.machine ?? principal.agent ?? null]);
+}
+
+/** Manage one board's objects; callers authorize and hold the shared auth lifecycle lock around every operation. */
+export function createRelayPages({ directory, boardId, now = Date.now }) {
+ if (typeof directory !== 'string' || !/^[0-9a-f]{32}$/u.test(boardId ?? '') || typeof now !== 'function') throw new Refused('RELAY_CONFIG', 'Configure private page storage for a persistent board id.');
+ const root = resolve(directory);
+ mkdirSync(root, { recursive: true, mode: 0o700 });
+ const parent = lstatSync(root);
+ if (!parent.isDirectory() || parent.isSymbolicLink() || parent.mode & 0o077) throw new Refused('RELAY_STORAGE', 'Keep relay page storage in a private directory.');
+ const file = join(root, boardId + '.pages.sqlite');
+ try { closeSync(openSync(file, 'wx', 0o600)); } catch (error) { if (error.code !== 'EEXIST') throw error; }
+ const entry = lstatSync(file);
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.mode & 0o077) throw new Refused('RELAY_STORAGE', 'Keep relay page databases as private regular files.');
+ const db = new DatabaseSync(file);
+ let closed = false;
+ try {
+ db.exec(`PRAGMA busy_timeout=30000; PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; BEGIN IMMEDIATE;
+ CREATE TABLE IF NOT EXISTS page_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS page_object (id TEXT PRIMARY KEY, sequence INTEGER NOT NULL,
+ payload BLOB NOT NULL, children TEXT NOT NULL, created INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS page_upload (id TEXT PRIMARY KEY, principal TEXT NOT NULL,
+ sequence INTEGER NOT NULL, expires INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS page_upload_object (upload TEXT NOT NULL REFERENCES page_upload(id) ON DELETE CASCADE,
+ object TEXT NOT NULL REFERENCES page_object(id), PRIMARY KEY(upload,object));
+ CREATE TABLE IF NOT EXISTS page_pin (id TEXT PRIMARY KEY, principal TEXT NOT NULL, root TEXT NOT NULL,
+ reference TEXT NOT NULL, expires INTEGER NOT NULL, UNIQUE(principal,root));`);
+ const saved = db.prepare('SELECT key,value FROM page_meta ORDER BY key').all();
+ if (!saved.length) db.prepare('INSERT INTO page_meta(key,value) VALUES (?,?),(?,?)').run('board', boardId, 'format', '1');
+ else if (saved.length !== 2 || saved[0].key !== 'board' || saved[0].value !== boardId || saved[1].key !== 'format' || saved[1].value !== '1') {
+ throw new Refused('RELAY_STORAGE', 'Restore this page database with its original board identity and supported format.');
+ }
+ db.exec('COMMIT');
+ } catch (error) {
+ try { db.exec('ROLLBACK'); } catch { /* Initialization may have failed before its transaction. */ }
+ db.close(); throw error;
+ }
+
+ /** Refuse invalid clocks and use after shutdown without leaking native database messages. */
+ function clock() {
+ if (closed) throw new Refused('RELAY_CLOSED', 'Open the relay page store before using it.');
+ const value = now();
+ if (!Number.isSafeInteger(value) || value < 0) throw new Refused('RELAY_CLOCK', 'Configure a valid relay page-storage clock.');
+ return value;
+ }
+
+ /** Keep staging and collection changes transactional; publication itself is owned by the journal. */
+ function atomic(work) {
+ clock(); db.exec('BEGIN IMMEDIATE');
+ try {
+ const result = work();
+ if (result && typeof result.then === 'function') throw new Refused('RELAY_CONFIG', 'Finish synchronous page storage before awaiting.');
+ db.exec('COMMIT'); return result;
+ } catch (error) { db.exec('ROLLBACK'); throw error; }
+ }
+
+ /** Resolve only the caller's live upload; a guessed upload id is not authority. */
+ function upload(id, principal) {
+ const saved = db.prepare('SELECT * FROM page_upload WHERE id=?').get(String(id));
+ if (!saved || saved.principal !== principalKey(principal) || saved.expires <= clock()) throw new Refused('SNAPSHOT_UPLOAD_EXPIRED', 'Start a new sealed upload or resume this machine’s unexpired upload.');
+ return saved;
+ }
+
+ /** Validate only opaque graph metadata, not encrypted page contents. */
+ function childrenOf(row) {
+ let children;
+ try { children = JSON.parse(row.children); } catch { throw new Refused('RELAY_STORAGE', 'Restore valid opaque page references.'); }
+ if (!Array.isArray(children) || children.length > PAGE_FANOUT) throw new Refused('RELAY_STORAGE', 'Restore valid bounded page references.');
+ return children.map(objectId);
+ }
+
+ /** Find reachable objects, accepting shared subtrees but refusing cycles in a published graph. */
+ function graph(roots, complete) {
+ const found = new Set();
+ const visiting = new Set();
+ /** Walk a bounded depth without interpreting the stored cipher bytes. */
+ function visit(id, depth) {
+ objectId(id);
+ if (found.has(id)) return;
+ if (depth > MAX_DEPTH || visiting.has(id)) {
+ if (complete) throw new Refused('SNAPSHOT_GRAPH', 'Upload a complete, acyclic sealed page index.');
+ return;
+ }
+ const row = db.prepare('SELECT id,children FROM page_object WHERE id=?').get(id);
+ if (!row) {
+ if (complete) throw new Refused('SNAPSHOT_PAGE_MISSING', 'Upload the referenced sealed page before publishing: ' + id);
+ return;
+ }
+ visiting.add(id);
+ for (const child of childrenOf(row)) visit(child, depth + 1);
+ visiting.delete(id); found.add(id);
+ }
+ for (const id of roots) visit(id, 0);
+ return found;
+ }
+
+ /** Start one principal-bound upload; unfinished sessions expire instead of holding data forever. */
+ function begin(principal, sequence) {
+ if (!['person', 'machine'].includes(principal?.kind)) throw new Refused('HUMAN_REQUIRED', 'Upload snapshots from a signed-in person or their linked machine.');
+ const owner = principalKey(principal);
+ if (!Number.isSafeInteger(sequence) || sequence < 0) throw new Refused('BAD_SEQUENCE', 'Name the nonnegative snapshot coverage sequence.');
+ return atomic(() => {
+ if (db.prepare('SELECT COUNT(*) AS count FROM page_upload WHERE expires>?').get(clock()).count >= 64) throw new Refused('RELAY_BUSY', 'Resume an existing upload before starting another one.');
+ const id = randomUUID();
+ db.prepare('INSERT INTO page_upload VALUES (?,?,?,?)').run(id, owner, sequence, clock() + UPLOAD_MS);
+ return { id, sequence };
+ });
+ }
+
+ /** Store an idempotent bounded object, checking the account budget before adding new bytes. */
+ function put(id, principal, object, checkBudget = () => {}) {
+ const identity = objectId(object?.id);
+ if (!(object.bytes instanceof Uint8Array) || !object.bytes.byteLength || object.bytes.byteLength > PAGE_CIPHER_BYTES ||
+ !Number.isSafeInteger(object.sequence) || object.sequence < 0 || !Array.isArray(object.children) || object.children.length > PAGE_FANOUT ||
+ createHash('sha256').update(object.bytes).digest('hex') !== identity) throw new Refused('BAD_PAGE', 'Upload the complete bounded cipher bytes under their own content id.');
+ const children = JSON.stringify(object.children.map(objectId));
+ if (object.children.includes(identity)) throw new Refused('SNAPSHOT_GRAPH', 'A sealed page cannot refer to itself.');
+ return atomic(() => {
+ upload(id, principal);
+ const saved = db.prepare('SELECT * FROM page_object WHERE id=?').get(identity);
+ if (saved && (saved.sequence !== object.sequence || saved.children !== children || !Buffer.from(saved.payload).equals(Buffer.from(object.bytes)))) throw new Refused('SNAPSHOT_PAGE_CONFLICT', 'Retry the original bytes and references for this content id.');
+ if (!saved) {
+ checkBudget(object.bytes.byteLength + Buffer.byteLength(children));
+ db.prepare('INSERT INTO page_object VALUES (?,?,?,?,?)').run(identity, object.sequence, object.bytes, children, clock());
+ }
+ db.prepare('INSERT OR IGNORE INTO page_upload_object VALUES (?,?)').run(id, identity);
+ db.prepare('UPDATE page_upload SET expires=? WHERE id=?').run(clock() + UPLOAD_MS, id);
+ return { id: identity, stored: !saved };
+ });
+ }
+
+ /** Verify every referenced object before atomically publishing the journal's new coverage cursor. */
+ function publish(id, principal, rawReference, publishHead) {
+ const reference = pageReference(rawReference);
+ return atomic(() => {
+ const staged = upload(id, principal);
+ if (reference.sequence !== staged.sequence) throw new Refused('BAD_SEQUENCE', 'Publish the coverage sequence named when this upload began.');
+ const root = db.prepare('SELECT sequence FROM page_object WHERE id=?').get(reference.id);
+ if (!root || root.sequence !== reference.sequence) throw new Refused('SNAPSHOT_PAGE_MISSING', 'Upload this snapshot’s sealed root before publishing it.');
+ graph([reference.id], true);
+ const result = publishHead(reference);
+ if (result && typeof result.then === 'function') throw new Refused('RELAY_CONFIG', 'Commit the journal head synchronously before finishing publication.');
+ db.prepare('DELETE FROM page_upload WHERE id=?').run(id);
+ return result;
+ });
+ }
+
+ /** Pin the journal's current root before returning it, so a concurrent publication cannot delete an in-flight read. */
+ function pin(principal, rawReference) {
+ const owner = principalKey(principal);
+ const reference = pageReference(rawReference);
+ return atomic(() => {
+ graph([reference.id], true);
+ const existing = db.prepare('SELECT id FROM page_pin WHERE principal=? AND root=?').get(owner, reference.id);
+ const id = existing?.id ?? randomUUID();
+ db.prepare('INSERT INTO page_pin VALUES (?,?,?,?,?) ON CONFLICT(principal,root) DO UPDATE SET reference=excluded.reference,expires=excluded.expires').run(id, owner, reference.id, JSON.stringify(reference), clock() + READ_MS);
+ return { id, expires: clock() + READ_MS };
+ });
+ }
+
+ /** Renew a principal's existing read pin; authorization must still run again for every HTTP request. */
+ function get(id, principal, rawObject, parents = []) {
+ const identity = objectId(rawObject);
+ return atomic(() => {
+ const saved = db.prepare('SELECT * FROM page_pin WHERE id=?').get(String(id));
+ if (!saved || saved.principal !== principalKey(principal) || saved.expires <= clock()) throw new Refused('SNAPSHOT_READ_EXPIRED', 'Read the current snapshot head again before fetching its sealed pages.');
+ if (!Array.isArray(parents) || parents.length > MAX_DEPTH) throw new Refused('BAD_PAGE_PATH', 'Fetch a page through the references of the pinned snapshot.');
+ const path = [...parents.map(objectId), identity];
+ if (path[0] !== saved.root || new Set(path).size !== path.length) throw new Refused('BAD_PAGE_PATH', 'Fetch a page through the references of the pinned snapshot.');
+ for (let index = 0; index < path.length - 1; index += 1) {
+ const parent = db.prepare('SELECT children FROM page_object WHERE id=?').get(path[index]);
+ if (!parent || !childrenOf(parent).includes(path[index + 1])) throw new Refused('BAD_PAGE_PATH', 'This sealed page is not referenced by the pinned snapshot.');
+ }
+ const row = db.prepare('SELECT sequence,payload,children FROM page_object WHERE id=?').get(identity);
+ if (!row) throw new Refused('SNAPSHOT_PAGE_MISSING', 'Refresh the snapshot head before retrying this sealed page.');
+ db.prepare('UPDATE page_pin SET expires=? WHERE id=?').run(clock() + READ_MS, id);
+ return { id: identity, sequence: row.sequence, bytes: Buffer.from(row.payload), children: childrenOf(row) };
+ });
+ }
+
+ /** Collect only unreachable objects, preserving current journal roots, all live readers and unfinished uploads. */
+ function prune(currentRoots) {
+ if (!Array.isArray(currentRoots)) throw new Refused('RELAY_CONFIG', 'Supply the journal’s authoritative current page roots before collecting storage.');
+ return atomic(() => {
+ db.prepare('DELETE FROM page_upload WHERE expires<=?').run(clock());
+ db.prepare('DELETE FROM page_pin WHERE expires<=?').run(clock());
+ const keep = graph([...currentRoots, ...db.prepare('SELECT root FROM page_pin').all().map(row => row.root)], true);
+ const staged = graph(db.prepare('SELECT object FROM page_upload_object').all().map(row => row.object), false);
+ for (const id of staged) keep.add(id);
+ const remove = db.prepare('DELETE FROM page_object WHERE id=?');
+ let deleted = 0;
+ for (const row of db.prepare('SELECT id FROM page_object').all()) {
+ if (!keep.has(row.id)) { remove.run(row.id); deleted += 1; }
+ }
+ return { deleted };
+ });
+ }
+
+ /** Account for logical opaque payload and public index bytes; SQLite allocation overhead is not a board limit. */
+ function usage() {
+ clock();
+ return db.prepare('SELECT COUNT(*) AS objects,COALESCE(SUM(length(payload)+length(children)),0) AS bytes FROM page_object').get();
+ }
+
+ /** Close exactly this store; repeated shutdown is harmless. */
+ function close() { if (!closed) { db.close(); closed = true; } }
+ return { begin, put, publish, pin, get, prune, usage, close, file };
+}
diff --git a/src/sealed-pages.js b/src/sealed-pages.js
index 3e3f41be..90e0911b 100644
--- a/src/sealed-pages.js
+++ b/src/sealed-pages.js
@@ -80,6 +80,15 @@ async function writeIndex(children, context) {
return writePage(0, new TextEncoder().encode(JSON.stringify(references)), references, length, context);
}
+/** Seal a bounded typed directory whose encrypted references also bind the relay's opaque reachability edges. */
+export async function writeSealedDescriptor(value, rawLinks, context) {
+ if (!Array.isArray(rawLinks) || rawLinks.length > PAGE_FANOUT) throw invalid();
+ const links = rawLinks.map(pageReference);
+ let body;
+ try { body = new TextEncoder().encode(JSON.stringify({ value, links })); } catch { throw invalid(); }
+ return writePage(2, body, links, body.byteLength, context);
+}
+
/**
* Seal JSON as a stream of bounded objects and bounded-fanout indexes, with no aggregate transport size cap.
* The supplied value is already materialized by its caller; this does not promise constant memory for building that value.
@@ -119,8 +128,8 @@ export async function writeSealedValue(value, context) {
}
/** Authenticate, bound inflation and parse a single object before interpreting its references. */
-async function readPage(reference, context) {
- const received = await context.get(reference.id);
+async function readPage(reference, context, parents = []) {
+ const received = await context.get(reference.id, parents);
if (!(received instanceof Uint8Array) || received.byteLength > PAGE_CIPHER_BYTES || await pageDigest(received) !== reference.id) throw invalid();
const compressed = await unseal(context.key, received, { boardId: context.boardId, kind: 'snapshot', sequence: reference.sequence });
const plain = await transformed(compressed, false, PAGE_BYTES + PREFIX.byteLength + 1);
@@ -131,6 +140,13 @@ async function readPage(reference, context) {
if (body.byteLength !== reference.bytes) throw invalid();
return { body };
}
+ if (kind === 2) {
+ if (body.byteLength !== reference.bytes) throw invalid();
+ let descriptor;
+ try { descriptor = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body)); } catch { throw invalid(); }
+ if (!descriptor || !Object.hasOwn(descriptor, 'value') || !Array.isArray(descriptor.links) || descriptor.links.length > PAGE_FANOUT) throw invalid();
+ return { descriptor: { value: descriptor.value, links: descriptor.links.map(pageReference) } };
+ }
if (kind !== 0) throw invalid();
let children;
try { children = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body)); } catch { throw invalid(); }
@@ -150,16 +166,24 @@ export async function* readSealedBytes(rawReference, context, { maxBytes = Numbe
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || root.bytes > maxBytes || typeof context?.get !== 'function') throw invalid();
const ancestors = new Set();
/** Walk in authenticated byte order, without requesting later siblings before they are consumed. */
- async function* walk(reference, depth) {
+ async function* walk(reference, depth, parents) {
if (depth >= MAX_DEPTH || ancestors.has(reference.id)) throw invalid();
ancestors.add(reference.id);
try {
- const page = await readPage(reference, context);
+ const page = await readPage(reference, context, parents);
if (page.body) yield page.body;
- else for (const child of page.children) yield* walk(child, depth + 1);
+ else if (page.children) for (const child of page.children) yield* walk(child, depth + 1, [...parents, reference.id]);
+ else throw invalid();
} finally { ancestors.delete(reference.id); }
}
- yield* walk(root, 0);
+ yield* walk(root, 0, context.parents ?? []);
+}
+
+/** Read a selected authenticated directory without traversing any of its unrelated children. */
+export async function readSealedDescriptor(reference, context) {
+ const page = await readPage(pageReference(reference), context, context.parents ?? []);
+ if (!page.descriptor) throw invalid();
+ return page.descriptor;
}
/** Read one selected JSON value; unrelated history values are neither fetched nor decrypted here. */
diff --git a/test/relay-page-store.test.js b/test/relay-page-store.test.js
new file mode 100644
index 00000000..eb53e249
--- /dev/null
+++ b/test/relay-page-store.test.js
@@ -0,0 +1,143 @@
+/** Durable upload publication, pinned readers and quota refusal preserve opaque snapshot graphs [H15,H17,H18]. */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { createRelayPages } from '../relay/page-store.js';
+import { Refused } from '../src/refused.js';
+import { generateBoardKey } from '../src/seal.js';
+import { PAGE_BYTES, readSealedValue, writeSealedValue } from '../src/sealed-pages.js';
+
+const machine = { kind: 'machine', userId: '1', machine: 'fixture-native' };
+const agent = { kind: 'agent', userId: '1', agent: 'fixture-reader' };
+
+/** Open only a synthetic private relay database with a controllable lease clock. */
+async function fixture(t) {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-sealed-pages-'));
+ const boardId = 'a'.repeat(32);
+ const key = await generateBoardKey();
+ let time = 1_000;
+ const options = { directory, boardId, now: () => time };
+ const stores = [createRelayPages(options)];
+ t.after(() => { for (const store of stores) store.close(); rmSync(directory, { recursive: true, force: true }); });
+ const box = {
+ key, boardId, store: stores[0],
+ /** Advance the product lease clock without an elapsed-time performance assertion. */
+ advance(ms) { time += ms; },
+ /** Reopen actual on-disk state after a simulated process restart. */
+ reopen() { box.store.close(); box.store = createRelayPages(options); stores.push(box.store); },
+ /** Upload actual encrypted objects without publishing a head prematurely. */
+ async stage(value, sequence = 7, checkBudget) {
+ const upload = box.store.begin(machine, sequence);
+ const objects = [];
+ const reference = await writeSealedValue(value, { key, boardId, sequence,
+ put(object) { objects.push(object); box.store.put(upload.id, machine, object, checkBudget); } });
+ return { upload, reference, objects };
+ },
+ /** Read only through the same principal's root pin and authenticated object path. */
+ read(reference, pin, who = agent) {
+ return readSealedValue(reference, { key, boardId,
+ get(id, parents) { return box.store.get(pin.id, who, id, parents).bytes; } });
+ },
+ };
+ return box;
+}
+
+test('an old pinned reader survives replacement and only expires after its last read [H15,H17,H18]', async t => {
+ const box = await fixture(t);
+ const first = await box.stage({ marker: 'first published snapshot' });
+ let head;
+ box.store.publish(first.upload.id, machine, first.reference, reference => { head = reference; });
+ const pin = box.store.pin(agent, head);
+ const next = await box.stage({ marker: 'new published snapshot' }, 8);
+ box.store.publish(next.upload.id, machine, next.reference, reference => { head = reference; });
+ box.store.prune([head.id]);
+ assert.equal((await box.read(first.reference, pin)).marker, 'first published snapshot');
+ box.advance(899_999);
+ assert.equal((await box.read(first.reference, pin)).marker, 'first published snapshot', 'an active reader renews its own lease');
+ box.advance(899_999);
+ assert.equal((await box.read(first.reference, pin)).marker, 'first published snapshot');
+ box.advance(900_001);
+ box.store.prune([head.id]);
+ await assert.rejects(box.read(first.reference, pin), { code: 'SNAPSHOT_READ_EXPIRED' });
+ const current = box.store.pin(agent, head);
+ assert.equal((await box.read(head, current)).marker, 'new published snapshot');
+ assert.equal(box.store.usage().objects, next.objects.length, 'only unreferenced expired data was collected');
+});
+
+test('quota refusal cannot change a previous head or partially store the refused object [H15,H17]', async t => {
+ const box = await fixture(t);
+ const first = await box.stage({ marker: 'previous readable head' });
+ let head;
+ box.store.publish(first.upload.id, machine, first.reference, reference => { head = reference; });
+ const pin = box.store.pin(agent, head);
+ const before = box.store.usage().bytes;
+ await assert.rejects(box.stage({ marker: 'refused replacement' }, 8, () => {
+ throw new Refused('ACCOUNT_STORAGE_LIMIT', 'Synthetic account storage limit reached.');
+ }), { code: 'ACCOUNT_STORAGE_LIMIT' });
+ assert.equal(box.store.usage().bytes, before);
+ assert.equal((await box.read(head, pin)).marker, 'previous readable head');
+});
+
+test('retrying the exact object is free while changed metadata cannot reuse its identity [H15,H17]', async t => {
+ const box = await fixture(t);
+ let charged = 0;
+ const staged = await box.stage({ marker: 'idempotent object' }, 7, bytes => { charged += bytes; });
+ const before = charged;
+ for (const object of staged.objects) assert.equal(box.store.put(staged.upload.id, machine, object, bytes => { charged += bytes; }).stored, false);
+ assert.equal(charged, before);
+ assert.throws(() => box.store.put(staged.upload.id, machine, { ...staged.objects[0], sequence: 8 }), { code: 'SNAPSHOT_PAGE_CONFLICT' });
+});
+
+test('an agent may read a pinned head but cannot publish or borrow another principal’s session [H15,H17]', async t => {
+ const box = await fixture(t);
+ assert.throws(() => box.store.begin(agent, 7), { code: 'HUMAN_REQUIRED' });
+ const staged = await box.stage({ marker: 'authorized head' });
+ box.store.publish(staged.upload.id, machine, staged.reference, () => {});
+ const pin = box.store.pin(agent, staged.reference);
+ assert.equal((await box.read(staged.reference, pin)).marker, 'authorized head');
+ await assert.rejects(box.read(staged.reference, pin, { ...agent, userId: '2' }), { code: 'SNAPSHOT_READ_EXPIRED' });
+ const other = box.store.begin(machine, 8);
+ assert.throws(() => box.store.put(other.id, { ...machine, machine: 'another-native' }, staged.objects[0]), { code: 'SNAPSHOT_UPLOAD_EXPIRED' });
+});
+
+test('knowing a staged object id does not make it readable through another pinned head [H15,H17]', async t => {
+ const box = await fixture(t);
+ const first = await box.stage({ marker: 'current root', text: 'x'.repeat(PAGE_BYTES * 2) });
+ box.store.publish(first.upload.id, machine, first.reference, () => {});
+ const pin = box.store.pin(agent, first.reference);
+ const future = await box.stage({ marker: 'unpublished future data' }, 8);
+ assert.throws(() => box.store.get(pin.id, agent, future.reference.id), { code: 'BAD_PAGE_PATH' });
+ assert.throws(() => box.store.get(pin.id, agent, future.reference.id, [first.reference.id]), { code: 'BAD_PAGE_PATH' });
+ assert.equal((await box.read(first.reference, pin)).marker, 'current root');
+});
+
+test('missing and cyclic opaque graphs cannot publish or make staging collection permanent [H15,H17,H18]', async t => {
+ const box = await fixture(t);
+ const upload = box.store.begin(machine, 7);
+ const firstBytes = Uint8Array.of(1, 2, 3);
+ const secondBytes = Uint8Array.of(4, 5, 6);
+ const first = createHash('sha256').update(firstBytes).digest('hex');
+ const second = createHash('sha256').update(secondBytes).digest('hex');
+ box.store.put(upload.id, machine, { id: first, sequence: 7, bytes: firstBytes, children: [second] });
+ let published = false;
+ assert.throws(() => box.store.publish(upload.id, machine, { id: first, sequence: 7, bytes: 1 }, () => { published = true; }), { code: 'SNAPSHOT_PAGE_MISSING' });
+ box.store.put(upload.id, machine, { id: second, sequence: 7, bytes: secondBytes, children: [first] });
+ assert.throws(() => box.store.publish(upload.id, machine, { id: first, sequence: 7, bytes: 1 }, () => { published = true; }), { code: 'SNAPSHOT_GRAPH' });
+ assert.equal(published, false);
+ assert.doesNotThrow(() => box.store.prune([]), 'unfinished cyclic metadata does not block collection of other data');
+ box.advance(3_600_001);
+ box.store.prune([]);
+ assert.equal(box.store.usage().objects, 0);
+});
+
+test('published objects and an existing reader pin survive closing the database [H15,H17]', async t => {
+ const box = await fixture(t);
+ const staged = await box.stage({ marker: 'durable encrypted graph' });
+ box.store.publish(staged.upload.id, machine, staged.reference, () => {});
+ const pin = box.store.pin(agent, staged.reference);
+ box.reopen();
+ assert.equal((await box.read(staged.reference, pin)).marker, 'durable encrypted graph');
+});
diff --git a/test/sealed-pages.test.js b/test/sealed-pages.test.js
index 623e12c5..ae68fcdb 100644
--- a/test/sealed-pages.test.js
+++ b/test/sealed-pages.test.js
@@ -9,9 +9,11 @@ import {
PAGE_CIPHER_BYTES,
PAGE_FANOUT,
pageDigest,
+ readSealedDescriptor,
readSealedBytes,
readSealedValue,
writeSealedValue,
+ writeSealedDescriptor,
} from '../src/sealed-pages.js';
/** Retain only synthetic encrypted objects, with a distinct private reuse cache and observable reads. */
@@ -19,6 +21,7 @@ async function storage() {
const objects = new Map();
const fingerprints = new Map();
const requested = [];
+ const paths = [];
const key = await generateBoardKey();
const context = {
key, boardId: 'a'.repeat(32), sequence: 7,
@@ -30,8 +33,9 @@ async function storage() {
objects.set(object.id, { ...object, bytes: Uint8Array.from(object.bytes) });
},
/** Count reads without returning device cache metadata. */
- get(id) {
+ get(id, parents = []) {
requested.push(id);
+ paths.push([...parents, id]);
const found = objects.get(id);
if (!found) throw new Error('Synthetic encrypted object is absent.');
return found.bytes;
@@ -41,7 +45,7 @@ async function storage() {
/** The fingerprint is deliberately absent from every uploaded object. */
remember(fingerprint, reference) { fingerprints.set(fingerprint, reference); },
};
- return { objects, requested, context };
+ return { objects, requested, paths, context };
}
test('sealed JSON exceeds one full index while every uploaded object stays bounded [H15,H17]', async () => {
@@ -102,3 +106,19 @@ test('an authenticated gzip bomb refuses before a complete oversized page is all
box.objects.set(id, { bytes });
await assert.rejects(readSealedValue({ id, sequence: 7, bytes: PAGE_BYTES + 1 }, box.context), { code: 'SNAPSHOT_PAGE_FORMAT' });
});
+
+test('a sealed directory exposes only its selected child and carries its pinned-root path [H15,H17]', async () => {
+ const box = await storage();
+ const selected = await writeSealedValue({ marker: 'SELECTED_ENCRYPTED_HISTORY_VALUE' }, box.context);
+ const unrelated = await writeSealedValue({ marker: 'UNRELATED_ENCRYPTED_HISTORY_VALUE' }, box.context);
+ const root = await writeSealedDescriptor({ selected, unrelated }, [selected, unrelated], box.context);
+ box.requested.length = 0;
+ const directory = await readSealedDescriptor(root, box.context);
+ assert.deepEqual(directory.links, [selected, unrelated]);
+ assert.deepEqual(box.requested, [root.id], 'reading the directory does not fetch its history');
+ const value = await readSealedValue(directory.value.selected, { ...box.context, parents: [root.id] });
+ assert.equal(value.marker, 'SELECTED_ENCRYPTED_HISTORY_VALUE');
+ assert.deepEqual(box.paths.at(-1), [root.id, selected.id]);
+ assert.ok(!box.requested.includes(unrelated.id));
+ assert.deepEqual(box.objects.get(root.id).children, [selected.id, unrelated.id]);
+});