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.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(relay): publish sealed size refusals [H5,H17]
Corey Olson7452477fd7d7
diff --git a/relay/browser-client.js b/relay/browser-client.jsindex df304433..d889f953 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -13,6 +13,7 @@ import { browserJSON, withBrowserDeadline } from './browser-deadline.js';import { phoneApprovalStatus, placePhoneApprovals, forgetPhoneApprovals } from './browser-approval-card.js';import { phoneSnapshotPages } from './browser-pages.js';import { createPhoneHistory } from './browser-history.js';+import { readUploadSize } from './browser-upload-status.js';const CHECKPOINT_WAIT_MS = 15_000;const KEYS = 'pullboard.relay.keys.v1';@@ -113,6 +114,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>const approvedBoards = new Set();let pendingLinks = [];let pendingLinksFailure = '';+ let sizeProblems = new Map();let warnings = [];let failure = '';let failureBoard = null;@@ -223,7 +225,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>entry.key = null;}paired.clear();- available = []; waitingBoards.clear(); pendingLinks = []; pendingLinksFailure = ''; warnings = []; pair = null;+ available = []; waitingBoards.clear(); sizeProblems.clear(); pendingLinks = []; pendingLinksFailure = ''; warnings = []; pair = null;for (const id of Object.keys(keys)) delete keys[id];document.querySelector('main')?.replaceChildren();if (error?.code !== 'DEVICE_REVOKED') { location.replace('/'); return; }@@ -259,7 +261,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>try { state = storedOwnedRequestState(localStorage, key, entry.state?.personRequests); } catch { /* Missing device storage can only hide this device's own notice. */ }ownedRequestIds.set(id, state.owned);}- const lines = noticeLines({ available, paired, ownedRequestIds, waitingBoards, approvedBoards, pendingLinks, warnings,+ const lines = noticeLines({ available, paired, ownedRequestIds, waitingBoards, sizeProblems, approvedBoards, pendingLinks, warnings,failure: failure || pendingLinksFailure });for (const text of lines) {const paragraph = document.createElement('p');@@ -275,7 +277,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>// A phone has no local-view screen to fall back to: keep its shell and the real reason until a board is readable.const root = document.documentElement;const phoneWaiting = root.dataset.relayDevice === 'phone' && (!rendered || paired.size === 0);- const step = emptyBoardStep({ available, waitingBoards, approvedBoards, loaded: inventoryLoaded, browserPaired, failure });+ const step = emptyBoardStep({ available, waitingBoards, sizeProblems, approvedBoards, loaded: inventoryLoaded, browserPaired, failure });showRelayScreen(root, phoneWaiting || paired.size === 0 ? 'share' : null,phoneWaiting && (failure || waitingBoards.size || warnings.some(value => ['ACCOUNT_STORAGE_WARNING', 'ACCOUNT_STORAGE_LIMIT'].includes(value?.code))) ? lines.join(' ') : '', step);placePhoneApprovals(document);@@ -565,6 +567,7 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>available = document.boards.filter(board => BOARD.test(board.id) && typeof board.repository === 'string');inventoryLoaded = true;waitingBoards = new Map();+ sizeProblems = new Map();warnings = document.warnings ?? [];const visible = new Set(available.map(board => board.id));for (const [id, entry] of paired) if (!visible.has(id)) { entry.stream?.close(); entry.history?.close(); entry.pageCache?.clear(); paired.delete(id); }@@ -574,7 +577,10 @@ export async function createTransport({ onUpdate = () => {}, onOpenBoard = () =>if (!encoded) continue;try {const entry = { id: board.id, repository: board.repository, key: decodeBoardKey(encoded), cursor: -1, checkpointCursor: -1, state: null, shouts: null, outbox: null };+ const size = await readUploadSize(path => documentAt(path, denied), entry);+ if (size) sizeProblems.set(board.id, size);await snapshot(entry);+ sizeProblems.delete(board.id);await catchUp(entry);if (accessLost) throw new Error('Sign in again to read this board.');paired.get(board.id)?.stream?.close(); paired.get(board.id)?.history?.close(); paired.get(board.id)?.pageCache?.clear();diff --git a/relay/browser-notice.js b/relay/browser-notice.jsindex 4db4b773..256caeec 100644--- a/relay/browser-notice.js+++ b/relay/browser-notice.js@@ -32,7 +32,7 @@ export function storedOwnedRequestState(storage, key, requests) {}/** Build truthful device notices from authorized boards and their decrypted pending requests. */-export function noticeLines({ available, paired, ownedRequestIds = new Map(), waitingBoards = new Map(), approvedBoards = new Set(), pendingLinks = [], warnings = [], failure = '' }) {+export function noticeLines({ available, paired, ownedRequestIds = new Map(), waitingBoards = new Map(), sizeProblems = new Map(), approvedBoards = new Set(), pendingLinks = [], warnings = [], failure = '' }) {const lines = [];const waiting = [...paired.entries()].reduce((count, [id, entry]) => {const owned = ownedRequestIds.get(id) ?? new Set();@@ -46,6 +46,7 @@ export function noticeLines({ available, paired, ownedRequestIds = new Map(), wa}const pairedRepositories = new Set(available.filter(board => paired.has(board.id)).map(board => board.repository));for (const board of available.filter(value => !paired.has(value.id))) {+ if (sizeProblems.has(board.id)) { lines.push(uploadSizeLine(sizeProblems.get(board.id))); continue; }// This phone just approved the link: its key is on the way, so asking to pair would be wrong.if (approvedBoards.has(board.id)) {lines.push(`${board.repository} · board ${board.id.slice(0, 8)}: approved; waiting for the computer to send this phone its key.`);@@ -82,6 +83,11 @@ export function noticeLines({ available, paired, ownedRequestIds = new Map(), wareturn lines;}+/** Describe only authenticated publisher measurements, without guessing from an absent snapshot. */+export function uploadSizeLine(value) {+ return `${value.repository}: too big to share (${value.sealedBytes} bytes; relay limit ${value.limit} bytes). Upgrade the configured relay for bounded snapshots.`;+}+/** The approved words of the two first screens another device can show (#757); the view may draw them from these. */export const RELAY_SCREEN_WORDS = Object.freeze({signIn: Object.freeze({ title: 'Your boards, on your phone', say: 'Sign in with the GitHub account you use on your computer.',@@ -92,10 +98,12 @@ export const RELAY_SCREEN_WORDS = Object.freeze({});/** Select guidance from observed inventory and key delivery, never infer why a computer has not uploaded. */-export function emptyBoardStep({ available = [], waitingBoards = new Map(), approvedBoards = new Set(), loaded = false, browserPaired = false, failure = '' } = {}) {+export function emptyBoardStep({ available = [], waitingBoards = new Map(), sizeProblems = new Map(), approvedBoards = new Set(), loaded = false, browserPaired = false, failure = '' } = {}) {const pair = { command: 'pullboard relay pair --new-browser', ask: 'Help me pair this browser with my boards.',small: 'On the computer with the boards, run this, then open the link it prints here or scan its QR.' };if (!loaded) return { title: 'Checking your linked boards', say: failure || 'Waiting for this account’s board list.', command: '', ask: '', small: '', waiting: failure || 'Checking your boards' };+ if (sizeProblems.size) return { title: 'Board too big to share', say: [...sizeProblems.values()].map(uploadSizeLine).join(' '),+ command: '', ask: 'Help me upgrade my relay for bounded snapshots.', small: 'Local work remains available on the computer.', waiting: 'Board exceeds the relay limit' };if (approvedBoards.size) return { title: 'Finishing this pairing', say: 'Approved; waiting for the computer to send this browser its board keys.',command: '', ask: '', small: 'Keep the setup command open on the computer with the boards.', waiting: failure || 'Waiting for this browser’s keys' };if (waitingBoards.size) return { title: 'Waiting for the first board copy',diff --git a/relay/browser-page.js b/relay/browser-page.jsindex b32cee3f..26a0ee33 100644--- a/relay/browser-page.js+++ b/relay/browser-page.js@@ -52,6 +52,7 @@ export function createRelayBrowserHandler({ authenticate }) {['/relay/relay-limits.js', ['text/javascript', readFileSync(new URL('../src/relay-limits.js', import.meta.url), 'utf8')]],['/relay/sign-in.js', ['text/javascript', SIGN_IN_TRANSPORT]],['/relay/browser-notice.js', ['text/javascript', readFileSync(new URL('./browser-notice.js', import.meta.url), 'utf8')]],+ ['/relay/browser-upload-status.js', ['text/javascript', readFileSync(new URL('./browser-upload-status.js', import.meta.url), 'utf8')]],['/relay/browser-deadline.js', ['text/javascript', readFileSync(new URL('./browser-deadline.js', import.meta.url), 'utf8').replace("'../src/refused.js'", "'./refused.js'")]],['/relay/browser-stream.js', ['text/javascript', readFileSync(new URL('./browser-stream.js', import.meta.url), 'utf8')]],['/relay/browser-pages.js', ['text/javascript', readFileSync(new URL('./browser-pages.js', import.meta.url), 'utf8').replaceAll("'../src/relay-page-layout.js'", "'./page-layout.js'").replaceAll("'../src/sealed-pages.js'", "'./sealed-pages.js'").replaceAll("'../src/refused.js'", "'./refused.js'")]],diff --git a/relay/browser-upload-status.js b/relay/browser-upload-status.jsnew file mode 100644index 00000000..76b07443--- /dev/null+++ b/relay/browser-upload-status.js@@ -0,0 +1,30 @@+/** Authenticate a publisher's size refusal with the board key before showing any diagnosis [H5,H17]. */+import { unseal } from './seal.js';+import { ENGINE_VERSION } from './engine.js';+import { withBrowserDeadline } from './browser-deadline.js';+import { SNAPSHOT_BODY_BYTES, SEALED_SNAPSHOT_BYTES } from './relay-limits.js';+import { Refused } from './refused.js';++/** An absent or older endpoint is not evidence of an oversized board. */+export async function readUploadSize(documentAt, entry) {+ let document;+ try { document = await documentAt('/api/v1/boards/' + entry.id + '/upload-status'); }+ catch (error) { if (['NO_BOARD', 'NO_ENDPOINT', 'BAD_ROUTE'].includes(error.code)) return null; throw error; }+ if (document.status === null) return null;+ const encoded = document.status?.sealed;+ if (typeof encoded !== 'string' || !/^[A-Za-z0-9_-]{39,21846}$/u.test(encoded)) {+ throw new Refused('RELAY_RESPONSE', 'Refresh this board to read its sealed upload notice.');+ }+ const binary = atob(encoded.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - encoded.length % 4) % 4));+ const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));+ const plain = await withBrowserDeadline(() => unseal(entry.key, bytes, { boardId: entry.id, kind: 'snapshot', sequence: 0 }));+ const value = JSON.parse(new TextDecoder().decode(plain));+ if (Object.keys(value).sort().join(',') !== 'board,engine,kind,limit,sealedBytes,version'+ || value.version !== 1 || value.kind !== 'snapshot-size-refusal' || value.board !== entry.id || value.engine !== ENGINE_VERSION+ || !Number.isSafeInteger(value.limit) || value.limit < 1 || value.limit > SEALED_SNAPSHOT_BYTES+ || !Number.isSafeInteger(value.sealedBytes) || value.sealedBytes <= value.limit || value.sealedBytes > SNAPSHOT_BODY_BYTES) {+ throw new Refused('RELAY_RESPONSE', 'Refresh this board to read its authenticated upload notice.');+ }+ return { repository: entry.repository, sealedBytes: value.sealedBytes, limit: value.limit };+}+diff --git a/relay/journal.js b/relay/journal.jsindex 9492cf09..26899558 100644--- a/relay/journal.js+++ b/relay/journal.js@@ -54,7 +54,8 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE} else if (saved.length !== 2 || saved[0].key !== 'board' || saved[0].value !== id || saved[1].key !== 'format' || !['2', '3', String(FORMAT)].includes(saved[1].value)) {throw new Refused('RELAY_STORAGE', 'open this journal with its original board identity and supported transport format');}- db.exec(`CREATE TABLE IF NOT EXISTS journal_head (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL);+ db.exec(`CREATE TABLE IF NOT EXISTS journal_upload_status (slot INTEGER PRIMARY KEY CHECK(slot=1), payload BLOB NOT NULL);+ CREATE TABLE IF NOT EXISTS journal_head (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS journal_snapshot (slot INTEGER PRIMARY KEY CHECK(slot=1), sequence INTEGER NOT NULL,received_at TEXT NOT NULL, payload BLOB NOT NULL, sender_kind TEXT NOT NULL CHECK(sender_kind IN ('person','machine')),sender_user TEXT NOT NULL, sender_agent TEXT, CHECK((sender_kind='person' AND sender_agent IS NULL) OR@@ -186,7 +187,12 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE/** Require detached bounded opaque bytes before opening a write transaction. */function payload(bytes) {- if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > maxBytes) throw new Refused('BAD_UPLOAD', 'send nonempty opaque bytes within the configured upload limit');+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) throw new Refused('BAD_UPLOAD', 'send nonempty opaque bytes within the configured upload limit');+ if (bytes.byteLength > maxBytes) {+ const error = new Refused('BAD_UPLOAD', 'send nonempty opaque bytes within the configured upload limit');+ error.snapshotLimit = { sealedBytes: bytes.byteLength, limit: maxBytes };+ throw error;+ }return Buffer.from(bytes);}@@ -254,6 +260,25 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEreturn row ? record(row) : null;}+ /** Retain only a small opaque publisher notice, never a readable size or repository name. */+ function saveUploadStatus(bytes) {+ open();+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 29 || bytes.byteLength > 16_384) {+ throw new Refused('BAD_UPLOAD', 'Send one bounded sealed upload notice.');+ }+ return transaction(() => {+ if (snapshot()) return false;+ db.prepare('INSERT INTO journal_upload_status VALUES(1,?) ON CONFLICT(slot) DO UPDATE SET payload=excluded.payload').run(bytes);+ return true;+ });+ }++ /** Read an opaque notice without treating it as an uploaded board snapshot. */+ function uploadStatus() {+ open();+ return db.prepare('SELECT payload FROM journal_upload_status WHERE slot=1').get()?.payload ?? null;+ }+/** Replace a covered snapshot and compact only its acknowledged prefix, keeping the head. */function saveSnapshot(sequence, bytes, principal, { initialOnly = false, apiVersion = 1, pageBytes = null } = {}) {open();@@ -270,6 +295,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEif (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new Refused('RELAY_CONFIG', 'the journal clock must return a valid Date');db.prepare('INSERT INTO journal_snapshot (slot,sequence,received_at,payload,sender_kind,sender_user,sender_agent,api_version,page_bytes) VALUES (1,?,?,?,?,?,?,?,?) ON CONFLICT(slot) DO UPDATE SET sequence=excluded.sequence,received_at=excluded.received_at,payload=excluded.payload,sender_kind=excluded.sender_kind,sender_user=excluded.sender_user,sender_agent=excluded.sender_agent,api_version=excluded.api_version,page_bytes=excluded.page_bytes').run(sequence, at.toISOString(), sealed, who.kind, who.userId, who.agent, apiVersion, apiVersion === 2 ? pageBytes : null);db.prepare('DELETE FROM journal_record WHERE sequence <= ?').run(sequence);+ db.prepare('DELETE FROM journal_upload_status').run();const result = snapshot();return result;});@@ -299,5 +325,6 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTEclosed = true;}- return { board: id, latest, activity, append, appendNext, recordAt, registrationFor, after, snapshot, saveSnapshot, snapshotDelta, pages, close };+ return { board: id, latest, activity, append, appendNext, recordAt, registrationFor, after, snapshot, saveSnapshot, snapshotDelta,+ saveUploadStatus, uploadStatus, pages, close };}diff --git a/relay/service.js b/relay/service.jsindex c4143ba6..631fd1e2 100644--- a/relay/service.js+++ b/relay/service.js@@ -16,6 +16,7 @@ import { VERIFIER_STANDING_ENGINE } from '../src/machine.js';import { SEALED_SNAPSHOT_BYTES, SNAPSHOT_BODY_BYTES } from '../src/relay-limits.js';import { createRelayPagesHandler, snapshotPageRoot } from './pages-http.js';import { createStorageQuota } from './storage-quota.js';+import { createUploadStatusHandler } from './upload-status.js';const SNAPSHOT_BODY = SNAPSHOT_BODY_BYTES;const STORED_BYTES = SEALED_SNAPSHOT_BYTES;@@ -340,6 +341,8 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginrequest: async (board, body, who) => (await append(board, body, who, 'request')).body,}, { pollMs });+ const uploadStatus = createUploadStatusHandler({ authorize: authorizedRequest, withJournal, sender });+/** Add authenticated snapshot replacement and deletion to the common versioned read/move paths. */async function handle(req, res) {if (await pagesHandler(req, res)) return;@@ -350,6 +353,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOriginlet url;try { url = new URL(req.url ?? '/', 'http://127.0.0.1'); }catch { throw new Refused('BAD_REQUEST', 'use a valid path under /api/v1/boards'); }+ if (await uploadStatus(req, res, url)) return;const approvers = /^\/api\/v1\/boards\/([^/]+)\/approvers$/.exec(url.pathname);if (approvers && req.method === 'GET') {const id = identity(approvers[1]);@@ -404,7 +408,15 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin}return await common(req, res);} catch (error) {- if (!res.headersSent) apiJson(res, apiStatus(error), apiRefusal(error));+ if (!res.headersSent) {+ const document = apiRefusal(error);+ const size = error.snapshotLimit;+ if (error.code === 'BAD_UPLOAD' && Number.isSafeInteger(size?.sealedBytes) && Number.isSafeInteger(size?.limit)+ && size.limit > 0 && size.sealedBytes > size.limit) {+ document.error.snapshotLimit = { sealedBytes: size.sealedBytes, limit: size.limit };+ }+ apiJson(res, apiStatus(error), document);+ }else res.end();}}diff --git a/relay/upload-status.js b/relay/upload-status.jsnew file mode 100644index 00000000..c262afb2--- /dev/null+++ b/relay/upload-status.js@@ -0,0 +1,28 @@+/** Board-authorized opaque upload notices; contents stay with the board's device keys [H5,H17]. */+import { apiJson, readApiBody } from '../src/api-http.js';+import { Refused } from '../src/refused.js';++/** Reuse the normal live board authorization and journal lifetime for this bounded metadata record. */+export function createUploadStatusHandler({ authorize, withJournal, sender }) {+ return async function uploadStatus(req, res, url) {+ const route = /^\/api\/v1\/boards\/([0-9a-f]{32})\/upload-status$/u.exec(url.pathname);+ if (!route) return false;+ if (url.search || !['GET', 'PUT'].includes(req.method)) throw new Refused('BAD_REQUEST', 'Read or replace this board’s sealed upload notice without URL parameters.');+ const id = route[1];+ const who = await authorize(req, id, req.method === 'PUT');+ if (req.method === 'PUT') {+ sender(who, 'snapshot');+ const body = await readApiBody(req, { maxBytes: 24_000 });+ if (!body || Object.keys(body).join(',') !== 'sealed' || typeof body.sealed !== 'string'+ || !/^[A-Za-z0-9_-]{39,21846}$/u.test(body.sealed)) throw new Refused('BAD_UPLOAD', 'Send only a bounded sealed upload notice.');+ const bytes = Buffer.from(body.sealed, 'base64url');+ if (bytes.toString('base64url') !== body.sealed) throw new Refused('BAD_UPLOAD', 'Send canonical sealed upload bytes.');+ const recorded = withJournal(id, journal => journal.saveUploadStatus(bytes), true, who.engineVersion);+ apiJson(res, 200, { recorded });+ } else {+ const bytes = withJournal(id, journal => journal.uploadStatus(), false, who.engineVersion);+ apiJson(res, 200, { status: bytes ? { sealed: Buffer.from(bytes).toString('base64url') } : null });+ }+ return true;+ };+}diff --git a/src/relay.js b/src/relay.jsindex 7ae99f97..c40536bd 100644--- a/src/relay.js+++ b/src/relay.js@@ -376,6 +376,7 @@ async function rawRequest(state, path, { method = 'GET', body, allowMissing = faerror.relayVersion = document.version;error.relayCode = document.error?.code;error.relayMessage = document.error?.message;+ if (document.version === 1 && document.error?.code === 'BAD_UPLOAD') error.snapshotLimit = document.error.snapshotLimit;if (/^[0-9a-f]{64}$/u.test(document.error?.page ?? '')) error.page = document.error.page;const storage = relayStorage(document.error?.storage);if (storage) error.storage = storage;@@ -452,6 +453,33 @@ function snapshotSize(state) {return { board: state.board, sealedBytes: bytes.byteLength, limit: SEALED_SNAPSHOT_LIMIT };}+/** Accept a structured relay limit only when its measurement matches the exact refused ciphertext. */+function reportedSnapshotSize(error, state) {+ const value = error.snapshotLimit;+ if (!value || Object.keys(value).sort().join(',') !== 'limit,sealedBytes'+ || !Number.isSafeInteger(value.sealedBytes) || !Number.isSafeInteger(value.limit)+ || value.limit < 1 || value.limit > SEALED_SNAPSHOT_LIMIT || value.sealedBytes <= value.limit+ || ![400, 413].includes(error.httpStatus) || typeof state.snapshot?.sealed !== 'string') return null;+ const bytes = Buffer.from(state.snapshot.sealed, 'base64url');+ if (bytes.toString('base64url') !== state.snapshot.sealed || bytes.byteLength !== value.sealedBytes) return null;+ return { sealedBytes: bytes.byteLength, limit: value.limit };+}++/** Publish only an actually received, measured refusal, sealed to the existing board key. */+async function publishSnapshotSize(state, io) {+ const pause = state.baselinePause;+ if (!pause?.reportedSize || pause.sizeNoticePublished) return;+ const value = { version: 1, kind: 'snapshot-size-refusal', board: state.board, engine: ENGINE_VERSION, ...pause.size };+ try {+ const sealed = Buffer.from(await seal(readBoardKey(state.board), new TextEncoder().encode(JSON.stringify(value)),+ { boardId: state.board, kind: 'snapshot', sequence: 0 })).toString('base64url');+ await rawRequest(state, '/api/v1/boards/' + state.board + '/upload-status', { method: 'PUT', body: { sealed } }, io);+ pause.sizeNoticePublished = true;+ const file = STATE_FILES.get(state);+ if (file) saveLink(file, state);+ } catch { io.err('The board is paused locally; its sealed size notice could not reach the relay. Retry when the relay is reachable.'); }+}+/** Return the local pending snapshot's oversize details without contacting the relay. */export function pendingSnapshotSize(root) {return snapshotSize(loadLink(linkFile(root)));@@ -669,15 +697,18 @@ async function uploadInitialBaseline(root, file, state, io) {rememberBaselineFailure(io, file, uncertain);throw uncertain;}- const size = pendingSnapshotSize(root);+ const reported = reportedSnapshotSize(error, state);+ const size = reported ?? pendingSnapshotSize(root);state.baselinePause = {status: error.httpStatus,code: safePauseCode(error),message: safePauseMessage(error),...(size ? { size: { sealedBytes: size.sealedBytes, limit: size.limit } } : {}),+ ...(reported ? { reportedSize: true } : {}),};// Retain the refused ciphertext and its source cursor; blocked commands do not re-seal it.saveLink(file, state);+ await publishSnapshotSize(state, io);reportBaselinePause(state, io);return false;}@@ -688,6 +719,7 @@ async function retryPausedBaseline(root, file, state, io) {if (!(state.baselinePause || state.baselineStale) || attemptedBaselineThisCommand(io, file)) return !(state.baselinePause || state.baselineStale);try {if (!await uploadRetryReady(state, state.baselinePause, path => request(state, path, {}, io))) {+ await publishSnapshotSize(state, io);saveLink(file, state); reportBaselinePause(state, io); return false;}const document = relaySnapshot(root);diff --git a/test/relay-upload-status.test.js b/test/relay-upload-status.test.jsnew file mode 100644index 00000000..c2f22127--- /dev/null+++ b/test/relay-upload-status.test.js@@ -0,0 +1,51 @@+/** Real HTTP authorization, private ciphertext and accepted-snapshot recovery for size notices [H5,H15,H17]. */+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { test } from 'node:test';+import { relayClientFixture } from './relay-client-fixture.js';+import { decodeBoardKey, unseal } from '../src/seal.js';+import { ENGINE_VERSION } from '../src/machine.js';++test('a real refused upload produces only board-scoped sealed status and accepted data clears it [H5,H15,H17]', async t => {+ const box = await relayClientFixture(t);+ box.legacySnapshotApi(true);+ box.limitSnapshots(128);+ await box.link();+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const path = '/api/v1/boards/' + state.board + '/upload-status';+ const headers = { authorization: 'Bearer ' + state.token, 'x-pullboard-engine': String(ENGINE_VERSION) };+ const response = await fetch(box.origin + path, { headers });+ assert.equal(response.status, 200);+ const document = await response.json();+ assert.deepEqual(Object.keys(document.status), ['sealed'], 'the relay returns no readable name, path, size or key');+ const encodedKey = readFileSync(box.keyFile, 'utf8').trim();+ const plain = await unseal(decodeBoardKey(encodedKey), new Uint8Array(Buffer.from(document.status.sealed, 'base64url')),+ { boardId: state.board, kind: 'snapshot', sequence: 0 });+ const value = JSON.parse(new TextDecoder().decode(plain));+ assert.equal(value.sealedBytes, Buffer.from(state.snapshot.sealed, 'base64url').byteLength);+ assert.equal(value.limit, 128);+ assert.equal(value.kind, 'snapshot-size-refusal');+ assert.equal((await fetch(box.origin + path)).status, 401, 'the status is never anonymous');+ const agent = await box.auth.issueToken(state.token, { board: state.board, agent: 'size-status-reader' });+ const body = JSON.stringify(document.status);+ assert.equal((await fetch(box.origin + path, { method: 'PUT', headers: { ...headers,+ authorization: 'Bearer ' + agent.token, 'content-type': 'application/json' }, body })).status, 403,+ 'an agent cannot publish a machine refusal');+ assert.equal((await fetch(box.origin + '/api/v1/boards/' + 'f'.repeat(32) + '/upload-status', { headers })).ok, false,+ 'the credential cannot read another board’s status');+ assert.equal((await fetch(box.origin + path, { method: 'PUT', headers: { ...headers, 'content-type': 'application/json' },+ body: JSON.stringify({ ...document.status, limit: 128 }) })).status, 400, 'plaintext status fields are refused');+ const person = await box.phoneSession();+ assert.equal((await fetch(box.origin + path, { method: 'PUT', headers: { cookie: 'pb_session=' + person.token,+ origin: 'https://foreign.invalid', 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' }, body })).status, 403,+ 'a foreign page cannot publish through a person cookie');+ box.limitSnapshots(null);+ box.legacySnapshotApi(false);+ assert.equal((await box.cli('status')).code, 0);+ assert.equal((await (await fetch(box.origin + path, { headers })).json()).status, null,+ 'accepting the actual bounded snapshot clears its stale notice');+ const late = await fetch(box.origin + path, { method: 'PUT', headers: { ...headers, 'content-type': 'application/json' }, body });+ assert.equal(late.status, 200);+ assert.equal((await late.json()).recorded, false, 'a late notice cannot replace an already accepted board copy');+ assert.equal((await (await fetch(box.origin + path, { headers })).json()).status, null);+});