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): expire idle links and retain private backups [H18]

Corey Olson2981d46f0070
diff --git a/relay/README.md b/relay/README.md
index 3a7d1243..f9a426e0 100644
--- a/relay/README.md
+++ b/relay/README.md
@@ -104,7 +104,7 @@ The client owns the encryption format and engine-version checks.
the need to fetch state and resume after its coverage cursor.
- DELETE /api/v1/boards/:id removes that board's database and SQLite sidecars.
It requires a person's signed-in session and current write access.
- GitHub link/credential lifecycle remains owned by the sign-in/linking layer.
+ It removes the link and its board-scoped credentials too; other boards and person sessions remain valid.
All responses and refusals retain API version 1. Moves use the shared 100,000
byte JSON-body limit. Snapshots allow a bounded 14,000,000 byte JSON body and
@@ -137,3 +137,49 @@ actual loopback sign-in stand-in, and checks order, snapshots, live delivery,
revocation, deletion and absence of known plaintext/client keys in database
bytes. Test encryption is client-only; it is not a public client pairing API.
The relay/ service stays outside the npm package.
+
+
+## Retention and private backups
+
+`createRelayHandler` and `serveRelay` accept `now` (nonnegative integer milliseconds),
+`backupsDirectory` (default: the journal directory plus `-backups`), and
+`maintenanceMs` (default: 60000; zero delegates scheduling to the caller).
+The service checks expiry on each authorized board contact and every maintenance tick.
+A new sealed move or request resets inactivity; merely reading or replacing a snapshot does not.
+The activity timestamp survives compaction and restart. Links without a move use their original
+link time; older unshipped auth databases receive a full grace period during migration.
+
+At sixty idle days, authorized `GET state` and `PUT state` responses include
+`state.warning`; the board listing includes `warnings`. A warning contains only public board
+identity, `BOARD_INACTIVE`, idle days, the ninety-day deletion deadline and next steps.
+Linked CLI and view consumers must display this on their next contact; this backend has no
+notification delivery and never reads a seal. At ninety idle days, a contact or maintenance
+sweep removes the board's journal, sidecars, backups, link and scoped credentials.
+Explicit person-authorized unlink does the same immediately, including backups. The complete
+local board is unaffected.
+
+Every service journal operation and retention decision takes the same cross-process lock
+in the auth database. All workers for a storage directory must share that auth database.
+Unlink first commits access revocation and a durable cleanup intent; cleanup prevents relinking
+until all managed files are gone. Maintenance retries an unfinished purge after an I/O failure
+or restart. A pending purge is never exposed as an active linked board.
+
+The backup job uses SQLite `VACUUM INTO` to copy a consistent compact database, including
+committed WAL contents, into a private temporary file and atomically publishes it.
+It preserves opaque snapshots, the uncovered tail and public ordering metadata; it needs no key.
+Backups run once per UTC day while the service is running. A restart can produce an extra
+backup that day. Only managed backups and unfinished temporary outputs older than fourteen
+days are pruned; unrelated operator files remain untouched. Directories are mode 700 and
+files mode 600; managed symlinks are refused.
+
+Trusted operators can call `handler.maintenance()` / `relay.maintenance()` or `.backup()`
+for external scheduling. `.maintenanceStatus()` reports a stable error code after a failed
+scheduled tick; it clears after a successful retry. It contains no native error, credential,
+key or storage path. Monitor that status when running a public host: background failures do
+not claim success. Shutdown clears the timer; authentication shutdown remains caller-owned.
+
+`test/relay-retention.test.js` uses an injected lifecycle clock, real SQLite, real loopback
+GitHub sign-in and HTTP. It checks exact sixty/ninety/fourteen-day boundaries, contact warnings,
+compaction/restart, scoped revocation, crash-intent recovery, consistent private backups,
+symlink refusal and retryable maintenance failures. Sign-in's separate clock retains normal
+credential validity during these simulated long lifecycle intervals.
diff --git a/relay/auth.js b/relay/auth.js
index b10760a7..c220f321 100644
--- a/relay/auth.js
+++ b/relay/auth.js
@@ -36,19 +36,43 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
if (database !== ':memory:') mkdirSync(dirname(database), { recursive: true, mode: 0o700 });
const db = new DatabaseSync(database);
if (database !== ':memory:') chmodSync(database, 0o600);
- db.exec(`PRAGMA foreign_keys=ON;
- CREATE TABLE IF NOT EXISTS relay_users (id TEXT PRIMARY KEY, login TEXT NOT NULL);
- CREATE TABLE IF NOT EXISTS relay_boards (id TEXT PRIMARY KEY, repository TEXT NOT NULL, repository_id TEXT NOT NULL);
- CREATE TABLE IF NOT EXISTS relay_credentials (id TEXT PRIMARY KEY, hash TEXT UNIQUE NOT NULL, kind TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES relay_users(id), board TEXT REFERENCES relay_boards(id), agent TEXT, expires INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
- `);
+ db.exec('PRAGMA foreign_keys=ON; PRAGMA busy_timeout=30000; BEGIN IMMEDIATE');
+ try {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS relay_users (id TEXT PRIMARY KEY, login TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS relay_boards (id TEXT PRIMARY KEY, repository TEXT NOT NULL, repository_id TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS relay_cleanup (board TEXT PRIMARY KEY);
+ CREATE TABLE IF NOT EXISTS relay_credentials (id TEXT PRIMARY KEY, hash TEXT UNIQUE NOT NULL, kind TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES relay_users(id), board TEXT REFERENCES relay_boards(id), agent TEXT, expires INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
+ `);
+ // Older unshipped links receive a full retention grace period, rather than guessing their age.
+ if (!db.prepare('PRAGMA table_info(relay_boards)').all().some((column) => column.name === 'linked_at')) {
+ db.exec('ALTER TABLE relay_boards ADD COLUMN linked_at INTEGER');
+ }
+ db.prepare('UPDATE relay_boards SET linked_at=? WHERE linked_at IS NULL').run(now());
+ db.exec('COMMIT');
+ } catch (error) { try { db.exec('ROLLBACK'); } finally { db.close(); } throw error; }
const permissions = new Map();
const webFlows = new Map();
const deviceFlows = new Map();
let closed = false;
+ let locked = false;
/** Refuse operation after closing instead of surfacing a raw SQLite error. */
function open() { if (closed) throw new Refused('RELAY_CLOSED', 'start the relay before signing in or using a credential'); }
+ /** Serialize synchronous lifecycle work across relay processes sharing this auth database. */
+ function lifecycle(work) {
+ open();
+ if (locked) return work();
+ db.exec('BEGIN IMMEDIATE'); locked = true;
+ try {
+ const result = work();
+ if (result && typeof result.then === 'function') throw new Refused('RELAY_CONFIG', 'finish synchronous lifecycle work before awaiting');
+ db.exec('COMMIT'); return result;
+ } catch (error) { db.exec('ROLLBACK'); throw error; }
+ finally { locked = false; }
+ }
+
/** Resolve a current credential and latest account login without storing its plaintext. */
function credential(token) {
open();
@@ -111,6 +135,8 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
if (error.code === 'NO_REPO_ACCESS' && (!permissions.has(key) || permissions.get(key).checked <= started)) permissions.set(key, { checked: started, allowed: false });
throw error;
}
+ const current = db.prepare('SELECT repository_id FROM relay_boards WHERE id=?').get(board);
+ if (!current || current.repository_id !== linked.repository_id) throw new Refused('BOARD_NOT_LINKED', 'link this board again before using it');
const canRead = ['read', 'triage', 'write', 'maintain', 'admin'].includes(repo.permission);
const hidden = repo.public && !['triage', 'write', 'maintain', 'admin'].includes(repo.permission);
const checked = { checked: started, allowed: canRead && !hidden, hidden, role: repo.permission, public: repo.public };
@@ -179,6 +205,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
if (board !== undefined) {
identifier(board, 'BAD_BOARD');
repository = await access(row, board, write);
+ if (board !== null && board !== undefined && !db.prepare('SELECT 1 FROM relay_boards WHERE id=?').get(board)) throw new Refused('BOARD_NOT_LINKED', 'link this board again before using it');
credential(token); // A revocation or expiry during the awaited provider call must take effect.
}
return { id: row.id, kind: row.kind, user: { id: row.user_id, login: row.login }, ...(row.board ? { board: row.board, agent: row.agent } : {}), ...(repository ? { permission: repository.permission, public: repository.public } : {}), expires: row.expires };
@@ -193,12 +220,48 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
authorize({ allowed: true, hidden: false, role: repo.permission, public: repo.public }, {}, true);
credential(token);
open();
- const existing = db.prepare('SELECT * FROM relay_boards WHERE id=?').get(board);
- if (existing && existing.repository_id !== String(repo.id)) throw new Refused('BOARD_LINK_CONFLICT', 'use a new board identifier for a different repository');
- db.prepare('INSERT INTO relay_boards (id,repository,repository_id) VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET repository=excluded.repository').run(board, repo.name, String(repo.id));
- permissions.delete(row.user_id + ':' + board);
+ lifecycle(() => {
+ if (db.prepare('SELECT 1 FROM relay_cleanup WHERE board=?').get(board)) throw new Refused('RELAY_CLEANUP', 'finish pending board cleanup before linking again');
+ const existing = db.prepare('SELECT * FROM relay_boards WHERE id=?').get(board);
+ if (existing && existing.repository_id !== String(repo.id)) throw new Refused('BOARD_LINK_CONFLICT', 'use a new board identifier for a different repository');
+ db.prepare('INSERT INTO relay_boards (id,repository,repository_id,linked_at) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET repository=excluded.repository').run(board, repo.name, String(repo.id), now());
+ permissions.delete(row.user_id + ':' + board);
+ });
return { id: board, repository: repo.name, repositoryID: String(repo.id) };
},
+ /** Internal maintenance inventory; HTTP callers must still pass the normal authorization boundary. */
+ linkedBoards() {
+ open();
+ return db.prepare('SELECT id,repository,linked_at AS linkedAt FROM relay_boards ORDER BY id').all();
+ },
+ /** Hold one shared lifecycle lock through every journal use and expiry decision. */
+ withBoard(board, work) {
+ identifier(board, 'BAD_BOARD');
+ return lifecycle(() => {
+ const link = db.prepare('SELECT id,repository,linked_at AS linkedAt FROM relay_boards WHERE id=?').get(board);
+ if (!link) throw new Refused('BOARD_NOT_LINKED', 'link this board again before using it');
+ return work(link);
+ });
+ },
+ /** Persist unlink intent and revoke scoped access before files are removed; retry after crashes. */
+ forgetBoard(board) {
+ identifier(board, 'BAD_BOARD');
+ lifecycle(() => {
+ db.prepare('INSERT OR IGNORE INTO relay_cleanup (board) VALUES (?)').run(board);
+ db.prepare('DELETE FROM relay_credentials WHERE board=?').run(board);
+ db.prepare('DELETE FROM relay_boards WHERE id=?').run(board);
+ });
+ for (const key of permissions.keys()) if (key.endsWith(':' + board)) permissions.delete(key);
+ },
+ /** Keep retrying cleanup exclusive through file removal and intent completion, blocking relink races. */
+ withCleanup(board, work) {
+ identifier(board, 'BAD_BOARD');
+ return lifecycle(() => db.prepare('SELECT 1 FROM relay_cleanup WHERE board=?').get(board) ? work() : undefined);
+ },
+ /** Inventory durable unlink intents without exposing them through the HTTP boundary. */
+ pendingCleanup() { open(); return db.prepare('SELECT board FROM relay_cleanup ORDER BY board').all().map((row) => row.board); },
+ /** Remove an unlink intent only after its journal, sidecars and managed backups are gone. */
+ finishCleanup(board) { identifier(board, 'BAD_BOARD'); lifecycle(() => db.prepare('DELETE FROM relay_cleanup WHERE board=?').run(board)); },
/** List only linked boards the current credential and GitHub account may read. */
async boardsFor(token) {
const row = credential(token);
diff --git a/relay/journal.js b/relay/journal.js
index 9a30a89e..e66b6771 100644
--- a/relay/journal.js
+++ b/relay/journal.js
@@ -33,7 +33,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
const db = new DatabaseSync(file);
let closed = false;
try {
- db.exec('PRAGMA busy_timeout = 30000; PRAGMA journal_mode = WAL; BEGIN IMMEDIATE');
+ db.exec('PRAGMA busy_timeout = 30000; PRAGMA journal_mode = WAL; PRAGMA secure_delete = ON; BEGIN IMMEDIATE');
db.exec(`CREATE TABLE IF NOT EXISTS journal_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS journal_record (sequence INTEGER PRIMARY KEY, received_at TEXT NOT NULL,
kind TEXT NOT NULL CHECK(kind IN ('move','request')), payload BLOB NOT NULL,
@@ -52,6 +52,10 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
received_at TEXT NOT NULL, payload BLOB NOT NULL, sender_kind TEXT NOT NULL CHECK(sender_kind='person'),
sender_user TEXT NOT NULL, sender_agent TEXT CHECK(sender_agent IS NULL))`);
db.exec('INSERT OR IGNORE INTO journal_head (slot,sequence) SELECT 1, COALESCE(MAX(sequence),0) FROM journal_record');
+ if (!db.prepare('PRAGMA table_info(journal_head)').all().some((column) => column.name === 'last_activity_at')) {
+ db.exec('ALTER TABLE journal_head ADD COLUMN last_activity_at TEXT');
+ db.exec('UPDATE journal_head SET last_activity_at=(SELECT MAX(received_at) FROM journal_record)');
+ }
db.exec('COMMIT');
} catch (error) {
try { db.exec('ROLLBACK'); } catch { /* Initialization may have failed before its transaction. */ }
@@ -86,6 +90,12 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
return db.prepare('SELECT sequence FROM journal_head WHERE slot=1').get().sequence;
}
+ /** Last sealed move/request receipt survives snapshot compaction and a service restart. */
+ function activity() {
+ open();
+ return db.prepare('SELECT last_activity_at FROM journal_head WHERE slot=1').get().last_activity_at;
+ }
+
/** 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');
@@ -109,7 +119,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
const at = now();
if (!(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_record (sequence,received_at,kind,payload,sender_kind,sender_user,sender_agent) VALUES (?,?,?,?,?,?,?)').run(sequence, at.toISOString(), kind, sealed, who.kind, who.userId, who.agent);
- db.prepare('UPDATE journal_head SET sequence=? WHERE slot=1').run(sequence);
+ db.prepare('UPDATE journal_head SET sequence=?,last_activity_at=? WHERE slot=1').run(sequence, at.toISOString());
const result = record(db.prepare('SELECT * FROM journal_record WHERE sequence=?').get(sequence));
db.exec('COMMIT');
return result;
@@ -167,5 +177,5 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
closed = true;
}
- return { board: id, latest, append, appendNext, after, snapshot, saveSnapshot, close };
+ return { board: id, latest, activity, append, appendNext, after, snapshot, saveSnapshot, close };
}
diff --git a/relay/retention.js b/relay/retention.js
new file mode 100644
index 00000000..0ae49dfc
--- /dev/null
+++ b/relay/retention.js
@@ -0,0 +1,203 @@
+/** Private, clock-controlled relay expiry and consistent SQLite backups, without opening seals [H18]. */
+import { DatabaseSync } from 'node:sqlite';
+import { randomUUID } from 'node:crypto';
+import { closeSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, unlinkSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { Refused } from '../src/refused.js';
+import { createRelayJournal } from './journal.js';
+
+const DAY = 86_400_000;
+const WARN = 60 * DAY;
+const EXPIRE = 90 * DAY;
+const KEEP = 14 * DAY;
+const BACKUP = /^([0-9a-f]{32})\.(\d+)\.sqlite$/;
+const PENDING = /^([0-9a-f]{32})\.(\d+)\.[0-9a-f-]{36}\.pending$/;
+
+/** Only persistent board ids can derive storage or backup filenames. */
+function identity(id) {
+ if (typeof id !== 'string' || !/^[0-9a-f]{32}$/.test(id)) throw new Refused('BAD_BOARD', 'use the persistent board id');
+ return id;
+}
+
+/** Refuse unexpected file types and public permissions; never follow a managed symlink. */
+function regular(file) {
+ let stat;
+ try { stat = lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return false; throw error; }
+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077)) throw new Refused('RELAY_STORAGE', 'restore relay files as private regular files');
+ return true;
+}
+
+/** Create/check a private directory without accepting a substituted symlink. */
+function privateDirectory(directory) {
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
+ const stat = lstatSync(directory);
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077)) throw new Refused('RELAY_STORAGE', 'use a private relay directory with mode 700');
+}
+
+/** Keep lifecycle mutations in the host's trusted process; this is never an unauthenticated HTTP API. */
+export function createRelayRetention({ directory, backupsDirectory = directory + '-backups', auth, now = Date.now }) {
+ if (typeof directory !== 'string' || !directory.trim() || typeof backupsDirectory !== 'string' ||
+ !backupsDirectory.trim() || typeof now !== 'function' || !auth?.linkedBoards || !auth?.forgetBoard || !auth?.withBoard || !auth?.pendingCleanup || !auth?.finishCleanup || !auth?.withCleanup) {
+ throw new Refused('RELAY_CONFIG', 'configure private relay storage, authentication and a retention clock');
+ }
+ const root = resolve(directory);
+ const backups = resolve(backupsDirectory);
+ if (root === backups) throw new Refused('RELAY_CONFIG', 'keep backups in a separate private directory');
+ privateDirectory(root);
+ let lastBackupDay = null;
+
+ /** Require a usable clock before changing files, expiry or backup retention. */
+ function time() {
+ const value = now();
+ if (!Number.isSafeInteger(value) || value < 0 || !Number.isFinite(new Date(value).getTime())) {
+ throw new Refused('RELAY_CLOCK', 'configure a valid nonnegative millisecond clock before maintenance');
+ }
+ return value;
+ }
+
+ /** Existing managed backup names, with validated regular files; unrelated files remain untouched. */
+ function backupFiles() {
+ try {
+ const stat = lstatSync(backups);
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077)) throw new Refused('RELAY_STORAGE', 'restore the private backup directory');
+ } catch (error) { if (error.code === 'ENOENT') return []; throw error; }
+ return readdirSync(backups).flatMap((name) => {
+ const match = BACKUP.exec(name) ?? PENDING.exec(name);
+ if (!match) return [];
+ if (!Number.isSafeInteger(Number(match[2]))) throw new Refused('RELAY_STORAGE', 'restore backup filenames with valid creation times');
+ const file = join(backups, name);
+ regular(file);
+ return [{ board: match[1], createdAt: Number(match[2]), file, name }];
+ });
+ }
+
+ /** Last append, or original link time before the first move; snapshots do not reset inactivity. */
+ function lastActivity(link) {
+ const file = join(root, identity(link.id) + '.journal.sqlite');
+ if (!regular(file)) {
+ if (!Number.isSafeInteger(link.linkedAt) || link.linkedAt < 0) throw new Refused('RELAY_CLOCK', 'restore a valid link time before retention maintenance');
+ return link.linkedAt;
+ }
+ const journal = createRelayJournal({ directory: root, boardId: link.id, maxBytes: 10_000_000 });
+ try {
+ const activity = journal.activity();
+ const at = activity === null ? link.linkedAt : Date.parse(activity);
+ if (!Number.isSafeInteger(at) || at < 0) throw new Refused('RELAY_CLOCK', 'restore a valid last-activity time before retention maintenance');
+ return at;
+ } finally { journal.close(); }
+ }
+
+ /** A next-contact warning carries only public board identity and an actionable deadline. */
+ function notice(id) {
+ let activity;
+ try { activity = auth.withBoard(identity(id), lastActivity); }
+ catch (error) { if (error.code === 'BOARD_NOT_LINKED') return null; throw error; }
+ const age = time() - activity;
+ if (age < WARN) return null;
+ return { board: id, code: 'BOARD_INACTIVE', inactiveDays: Math.floor(age / DAY),
+ deletesAt: new Date(activity + EXPIRE).toISOString(),
+ message: 'This linked board is inactive and will be deleted after 90 days without a new sealed move.',
+ next: 'Send a new move before the deadline, or unlink; the local board stays complete.' };
+ }
+
+ /** Validate all managed paths before any deletion, leaving unrelated files untouched. */
+ function affected(id) {
+ identity(id);
+ const files = ['', '-wal', '-shm'].map((suffix) => join(root, id + '.journal.sqlite' + suffix)).filter(regular);
+ return [...files, ...backupFiles().filter((entry) => entry.board === id).map((entry) => entry.file)];
+ }
+
+ /** Finish a durable unlink intent; a crash or I/O failure leaves it eligible for retry. */
+ function cleanup(id) {
+ auth.withCleanup(id, () => {
+ const files = affected(id);
+ for (const file of files) {
+ try { unlinkSync(file); } catch (error) { if (error.code !== 'ENOENT') throw error; }
+ }
+ auth.finishCleanup(id);
+ });
+ }
+
+ /** Revoke access and commit unlink intent before purging files, so crashes cannot revive a board. */
+ function unlink(id) {
+ auth.withBoard(identity(id), () => { affected(id); auth.forgetBoard(id); });
+ cleanup(id);
+ return { deleted: id };
+ }
+
+ /** Decide inactivity under the same cross-process lock used by every service journal operation. */
+ function expire(id) {
+ identity(id);
+ let expired;
+ try {
+ expired = auth.withBoard(id, (link) => {
+ if (time() - lastActivity(link) < EXPIRE) return false;
+ affected(id); auth.forgetBoard(id); return true;
+ });
+ } catch (error) { if (error.code === 'BOARD_NOT_LINKED') return false; throw error; }
+ if (expired) cleanup(id);
+ return expired;
+ }
+
+ /** Retry unfinished purges, then sweep valid persistent board identities. */
+ function sweep() {
+ time();
+ for (const id of auth.pendingCleanup()) if (/^[0-9a-f]{32}$/.test(id)) cleanup(id);
+ return auth.linkedBoards().filter((link) => /^[0-9a-f]{32}$/.test(link.id) && expire(link.id)).map((link) => link.id);
+ }
+
+ /** Prune only our dated backups/partial outputs, strictly older than fourteen days. */
+ function prune() {
+ const cutoff = time() - KEEP;
+ const expired = backupFiles().filter((entry) => entry.createdAt < cutoff);
+ for (const entry of expired) unlinkSync(entry.file);
+ return expired.map((entry) => entry.name);
+ }
+
+ /**
+ * VACUUM INTO makes a consistent, compact logical SQLite snapshot even with WAL present.
+ * Publish a completed private file without overwriting another job's result.
+ */
+ function backup() {
+ const at = time();
+ sweep();
+ const written = [];
+ for (const link of auth.linkedBoards()) {
+ if (!/^[0-9a-f]{32}$/.test(link.id)) continue;
+ try { auth.withBoard(link.id, () => {
+ const source = join(root, link.id + '.journal.sqlite');
+ if (!regular(source)) return;
+ privateDirectory(backups);
+ const name = link.id + '.' + at + '.sqlite';
+ const target = join(backups, name);
+ if (regular(target)) return;
+ const pending = join(backups, link.id + '.' + at + '.' + randomUUID() + '.pending');
+ closeSync(openSync(pending, 'wx', 0o600));
+ let db;
+ try {
+ db = new DatabaseSync(source, { readOnly: true });
+ db.prepare('VACUUM INTO ?').run(pending);
+ db.close(); db = null;
+ try { linkSync(pending, target); written.push(name); }
+ catch (error) { if (error.code !== 'EEXIST' || !regular(target)) throw error; }
+ } finally {
+ db?.close();
+ unlinkSync(pending);
+ }
+ }); } catch (error) { if (error.code !== 'BOARD_NOT_LINKED') throw error; }
+ }
+ return { written, removed: prune() };
+ }
+
+ /** Run expiry each tick and backups once per UTC day; errors leave the next tick able to retry. */
+ function maintain() {
+ const at = time();
+ const deleted = sweep();
+ const day = Math.floor(at / DAY);
+ let copied = { written: [], removed: prune() };
+ if (day !== lastBackupDay) { copied = backup(); lastBackupDay = day; }
+ return { deleted, ...copied };
+ }
+
+ return { notice, unlink, expire, sweep, prune, backup, maintain, directory: root, backupsDirectory: backups };
+}
diff --git a/relay/service.js b/relay/service.js
index 4b948c10..28f3e61a 100644
--- a/relay/service.js
+++ b/relay/service.js
@@ -1,10 +1,11 @@
/** Opt-in sealed API v1 relay: authorization, opaque persistence and ordered live delivery [A4,H7]. */
import { createServer } from 'node:http';
-import { lstatSync, mkdirSync, unlinkSync } from 'node:fs';
+import { lstatSync, mkdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { createApiHandler, apiJson, apiRefusal, apiStatus, readApiBody } from '../src/api-http.js';
import { Refused } from '../src/refused.js';
import { createRelayJournal } from './journal.js';
+import { createRelayRetention } from './retention.js';
const SNAPSHOT_BODY = 14_000_000;
const STORED_BYTES = 10_000_000;
@@ -68,7 +69,7 @@ function sender(who, personOnly = false) {
}
/** Create a private relay handler; the caller owns sign-in lifecycle and service shutdown. */
-export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin }) {
+export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin, now = Date.now, backupsDirectory, maintenanceMs = 60_000 }) {
const origin = trustedOrigin(publicOrigin);
if (typeof directory !== 'string' || !directory.trim() || !auth) throw new Refused('RELAY_CONFIG', 'configure a private relay directory and sign-in component');
const root = resolve(directory);
@@ -76,6 +77,33 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
const stat = lstatSync(root);
if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0) throw new Refused('RELAY_STORAGE', 'use a private directory with mode 700 for relay storage');
+ if (!Number.isSafeInteger(maintenanceMs) || maintenanceMs < 0 || maintenanceMs > 2_147_483_647 || (maintenanceMs > 0 && maintenanceMs < 10)) {
+ throw new Refused('RELAY_CONFIG', 'use a maintenance interval of at least ten milliseconds, or zero for an external scheduler');
+ }
+ const retention = createRelayRetention({ directory: root, backupsDirectory, auth, now });
+ let maintenanceError = null;
+
+ /** Expose only a stable failure code to the trusted operator; never log paths, keys or provider errors. */
+ function maintain() {
+ try { const result = retention.maintain(); maintenanceError = null; return result; }
+ catch (error) { maintenanceError = error instanceof Refused ? error.code : 'RELAY_MAINTENANCE'; throw error; }
+ }
+ const timer = maintenanceMs ? setInterval(() => { try { maintain(); } catch { /* operator reads maintenanceStatus */ } }, maintenanceMs) : null;
+ timer?.unref();
+
+ /** Check expiry only after normal authorization; the first authorized contact also purges overdue data. */
+ async function authorized(token, id, write = false) {
+ const who = await auth.authenticate(token, { board: identity(id), write });
+ if (retention.expire(id)) throw new Refused('NO_BOARD', 'this inactive link expired; link and upload the local board again');
+ return who;
+ }
+
+ /** Add an authorized next-contact warning without exposing any plaintext board contents. */
+ function annotated(row, id) {
+ const warning = retention.notice(id);
+ return { ...state(row), ...(warning ? { warning } : {}) };
+ }
+
/** Open only an existing journal on reads; each synchronous operation closes its connection. */
function withJournal(id, work, create = false) {
const file = join(root, identity(id) + '.journal.sqlite');
@@ -88,15 +116,17 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
throw error;
}
}
- const journal = createRelayJournal({ directory: root, boardId: id, maxBytes: STORED_BYTES });
- try { return work(journal); } finally { journal.close(); }
+ return auth.withBoard(id, () => {
+ const journal = createRelayJournal({ directory: root, boardId: id, maxBytes: STORED_BYTES, now: () => new Date(now()) });
+ try { return work(journal); } finally { journal.close(); }
+ });
}
/** Append ciphertext under its server-allocated sequence, with no engine or filesystem access. */
async function append(board, body, who, kind = 'move') {
const bytes = sealed(body);
if (!Number.isSafeInteger(body.sequence) || body.sequence < 1) throw new Refused('BAD_SEQUENCE', 'seal this move for the next positive sequence after the latest committed prefix');
- const principal = sender(await auth.authenticate(who.credential, { board: board.id, write: true }));
+ const principal = sender(await authorized(who.credential, board.id, true));
return withJournal(board.id, (journal) => {
const row = journal.append(body.sequence, bytes, kind, principal);
return { status: 200, body: { event: event(row), result: { sequence: row.sequence } } };
@@ -107,14 +137,18 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
authenticate: async (req, { board, write }) => {
const token = credential(req, origin, write);
return board === null ? { visible: await auth.boardsFor(token) }
- : { ...await auth.authenticate(token, { board: identity(board), write }), credential: token };
+ : { ...await authorized(token, board, write), credential: token };
+ },
+ boards: (who) => {
+ const boards = who.visible.filter((board) => !retention.expire(board.id));
+ const warnings = boards.map((board) => retention.notice(board.id)).filter(Boolean);
+ return { boards, ...(warnings.length ? { warnings } : {}) };
},
- boards: (who) => who.visible,
board: (id) => { withJournal(id, () => undefined); return { id }; },
state: (board) => withJournal(board.id, (journal) => {
const snapshot = journal.snapshot();
if (!snapshot) throw new Refused('NO_SNAPSHOT', 'upload a sealed snapshot before reading this board');
- return state(snapshot);
+ return annotated(snapshot, board.id);
}),
events: (board, after) => withJournal(board.id, (journal) => {
const snapshot = journal.snapshot();
@@ -135,22 +169,18 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
const deletion = /^\/api\/v1\/boards\/([^/]+)$/.exec(url.pathname);
if (req.method === 'PUT' && snapshot) {
const id = identity(snapshot[1]);
- sender(await auth.authenticate(credential(req, origin, true), { board: id, write: true }), true);
+ sender(await authorized(credential(req, origin, true), id, true), true);
const body = await readApiBody(req, { maxBytes: SNAPSHOT_BODY });
const bytes = sealed(body);
if (!Number.isSafeInteger(body.sequence) || body.sequence < 0) throw new Refused('BAD_SEQUENCE', 'name the nonnegative sequence covered by the sealed snapshot');
- const principal = sender(await auth.authenticate(credential(req, origin, true), { board: id, write: true }), true);
+ const principal = sender(await authorized(credential(req, origin, true), id, true), true);
const saved = withJournal(id, (journal) => journal.saveSnapshot(body.sequence, bytes, principal), true);
- return apiJson(res, 200, { state: state(saved) });
+ return apiJson(res, 200, { state: annotated(saved, id) });
}
if (req.method === 'DELETE' && deletion) {
const id = identity(deletion[1]);
- sender(await auth.authenticate(credential(req, origin, true), { board: id, write: true }), true);
- withJournal(id, () => undefined);
- const file = join(root, id + '.journal.sqlite');
- for (const suffix of ['', '-wal', '-shm']) {
- try { unlinkSync(file + suffix); } catch (error) { if (error.code !== 'ENOENT') throw error; }
- }
+ sender(await authorized(credential(req, origin, true), id, true), true);
+ retention.unlink(id);
return apiJson(res, 200, { deleted: id });
}
return await common(req, res);
@@ -159,19 +189,25 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
else res.end();
}
}
- handle.close = () => common.close();
+ handle.maintenance = maintain;
+ handle.backup = retention.backup;
+ handle.maintenanceStatus = () => ({ error: maintenanceError });
+ handle.close = () => { clearInterval(timer); common.close(); };
return handle;
}
/** Start the opt-in service on a configured address; tests use loopback and an ephemeral port. */
-export function serveRelay({ directory, auth, port = 0, host = '127.0.0.1', pollMs = 200, publicOrigin }) {
- const handler = createRelayHandler({ directory, auth, pollMs, publicOrigin });
+export function serveRelay({ directory, auth, port = 0, host = '127.0.0.1', pollMs = 200, publicOrigin, now, backupsDirectory, maintenanceMs }) {
+ const handler = createRelayHandler({ directory, auth, pollMs, publicOrigin, now, backupsDirectory, maintenanceMs });
const server = createServer(handler);
server.requestTimeout = 15_000;
return new Promise((ready, fail) => {
server.once('error', (error) => { handler.close(); fail(new Refused(error.code === 'EADDRINUSE' ? 'PORT_BUSY' : 'RELAY_LISTEN', 'cannot listen on the configured relay address; choose a free port and retry')); });
server.listen(port, host, () => ready({
port: server.address().port,
+ maintenance: handler.maintenance,
+ backup: handler.backup,
+ maintenanceStatus: handler.maintenanceStatus,
close: () => new Promise((done) => { handler.close(); server.close(done); server.closeAllConnections(); }),
}));
});
diff --git a/test/relay-retention.test.js b/test/relay-retention.test.js
new file mode 100644
index 00000000..05325a6b
--- /dev/null
+++ b/test/relay-retention.test.js
@@ -0,0 +1,285 @@
+/** Real private relay lifecycle storage, controlled clocks and HTTP authorization [H18]. */
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { DatabaseSync } from 'node:sqlite';
+import { createCipheriv, randomBytes } from 'node:crypto';
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { createRelayAuth } from '../relay/auth.js';
+import { createGitHubClient } from '../relay/github.js';
+import { createRelayJournal } from '../relay/journal.js';
+import { createRelayRetention } from '../relay/retention.js';
+import { serveRelay } from '../relay/service.js';
+import { githubFixture } from './relay-fixture.js';
+
+const DAY = 86_400_000;
+const A = 'a'.repeat(32);
+const B = 'b'.repeat(32);
+const PERSON = { kind: 'person', userId: '7' };
+
+/** Use actual sign-in with an independent lifecycle clock, so long inactivity does not fake token validity. */
+async function fixture(t) {
+ const root = mkdtempSync(join(tmpdir(), 'pullboard-retention-'));
+ const data = join(root, 'data');
+ const backups = join(root, 'backups');
+ let clock = Date.UTC(2026, 0, 1);
+ const provider = await githubFixture(t);
+ const auth = createRelayAuth({ database: join(root, 'auth.sqlite'), github: createGitHubClient(provider.config), now: () => Date.now() });
+ const flow = auth.beginWeb();
+ const redirect = await fetch(flow.authorizationURL, { redirect: 'manual' });
+ const url = new URL(redirect.headers.get('location'));
+ const signed = await auth.finishWeb(url.searchParams.get('state'), url.searchParams.get('code'), flow.binding);
+ // Real auth link time uses its own wall clock; journal activity below is the controlled inactivity origin.
+ await auth.linkBoard(signed.token, A, 'fixture/repository');
+ await auth.linkBoard(signed.token, B, 'fixture/repository');
+ const agent = await auth.issueToken(signed.token, { board: A, agent: 'worker' });
+ const other = await auth.issueToken(signed.token, { board: B, agent: 'other' });
+ const config = { directory: data, backupsDirectory: backups, auth, now: () => clock };
+ const retention = createRelayRetention(config);
+ const relay = await serveRelay({ ...config, maintenanceMs: 0, pollMs: 10 });
+ t.after(async () => { await relay.close(); auth.close(); rmSync(root, { recursive: true, force: true }); });
+ const key = randomBytes(32);
+ const marker = 'PRIVATE_RETENTION_PAYLOAD';
+ /** Seal only on the client; neither plaintext nor key is ever handed to the retention component. */
+ function encrypted() {
+ const nonce = randomBytes(12);
+ const cipher = createCipheriv('aes-256-gcm', key, nonce);
+ return Buffer.concat([Buffer.from([1]), nonce, cipher.update(marker), cipher.final(), cipher.getAuthTag()]);
+ }
+ /** Close each journal after one trusted fixture operation. */
+ function journal(id, work) {
+ return auth.withBoard(id, () => {
+ const db = createRelayJournal({ directory: data, boardId: id, now: () => new Date(clock) });
+ try { return work(db); } finally { db.close(); }
+ });
+ }
+ const payload = encrypted();
+ for (const id of [A, B]) journal(id, (db) => { db.saveSnapshot(0, payload, PERSON); db.append(1, payload, 'move', PERSON); });
+ /** Return status/body without ever placing credentials in diagnostic text or URLs. */
+ async function call(id, { path = '/state', method = 'GET', token = signed.token, body } = {}) {
+ const response = await fetch('http://127.0.0.1:' + relay.port + '/api/v1/boards' + (id ? '/' + id + path : ''), {
+ method, headers: { authorization: 'Bearer ' + token, ...(body ? { 'content-type': 'application/json' } : {}) },
+ ...(body ? { body: JSON.stringify(body) } : {}),
+ });
+ return { status: response.status, body: await response.json() };
+ }
+ return { root, data, backups, auth, signed, agent, other, config, retention, relay, payload, marker, key, journal, call,
+ set(value) { clock = value; }, at: () => clock, advance(days) { clock += days * DAY; } };
+}
+
+test('[H18] warnings begin at sixty days on authorized contact; compaction and restart preserve activity', async (t) => {
+ const box = await fixture(t);
+ const start = box.at();
+ box.set(start + 60 * DAY - 1);
+ assert.equal((await box.call(A)).body.state.warning, undefined);
+ box.advance(1 / DAY);
+ const warned = await box.call(A);
+ assert.equal(warned.status, 200);
+ assert.equal(warned.body.state.warning.code, 'BOARD_INACTIVE');
+ assert.equal(warned.body.state.warning.inactiveDays, 60);
+ assert.equal(warned.body.state.warning.deletesAt, new Date(start + 90 * DAY).toISOString());
+ assert.equal((await box.call(null)).body.warnings.length, 2);
+ const snapshot = await box.call(A, { method: 'PUT', body: { sequence: 1, sealed: box.payload.toString('base64url') } });
+ assert.equal(snapshot.body.state.warning.inactiveDays, 60, 'snapshot upload does not reset inactivity');
+ assert.equal(box.journal(A, (db) => db.after(0).length), 0, 'all covered history is folded into the snapshot');
+ const restarted = createRelayRetention(box.config);
+ assert.equal(restarted.notice(A).deletesAt, new Date(start + 90 * DAY).toISOString());
+ const move = await box.call(A, { method: 'POST', path: '/moves', token: box.agent.token, body: { sequence: 2, sealed: box.payload.toString('base64url') } });
+ assert.equal(move.status, 200);
+ assert.equal((await box.call(A)).body.state.warning, undefined, 'a new sealed record resets the warning');
+ assert.equal(restarted.notice(A), null);
+ const before = readdirSync(box.data);
+ const crossed = await box.call(B, { token: box.agent.token });
+ assert.equal(crossed.status, 403);
+ assert.deepEqual(readdirSync(box.data), before, 'unauthorized contact cannot mutate retention');
+});
+
+test('[H18] ninety-day expiry unlinks data and credentials while preserving the other board and person session', async (t) => {
+ const box = await fixture(t);
+ box.advance(89);
+ assert.equal((await box.call(A)).status, 200);
+ box.journal(B, (db) => db.append(2, box.payload, 'move', PERSON));
+ box.advance(1);
+ const expired = await box.call(A);
+ assert.equal(expired.status, 404);
+ for (const suffix of ['', '-wal', '-shm']) assert.equal(existsSync(join(box.data, A + '.journal.sqlite' + suffix)), false);
+ assert.equal((await box.call(A, { token: box.agent.token })).status, 401);
+ assert.equal((await box.call(B, { token: box.other.token })).status, 200);
+ assert.equal((await box.auth.authenticate(box.signed.token)).kind, 'session');
+ assert.deepEqual(box.auth.linkedBoards().map((row) => row.id), [B]);
+ assert.deepEqual(box.auth.pendingCleanup(), []);
+});
+
+test('[H18] explicit unlink removes managed backups immediately and a durable crash intent is finished after restart', async (t) => {
+ const box = await fixture(t);
+ const saved = box.retention.backup();
+ assert.equal(saved.written.length, 2);
+ const removed = await box.call(A, { method: 'DELETE', path: '' });
+ assert.equal(removed.status, 200);
+ assert.equal(readdirSync(box.backups).some((name) => name.startsWith(A)), false);
+ assert.equal(readdirSync(box.backups).some((name) => name.startsWith(B)), true);
+ // Model a process crash after committing revocation but before deleting any files.
+ box.auth.forgetBoard(B);
+ assert.ok(existsSync(join(box.data, B + '.journal.sqlite')));
+ assert.deepEqual(box.auth.pendingCleanup(), [B]);
+ await assert.rejects(box.auth.authenticate(box.other.token, { board: B }), { code: 'AUTH_REQUIRED' });
+ await assert.rejects(box.auth.linkBoard(box.signed.token, B, 'fixture/repository'), { code: 'RELAY_CLEANUP' });
+ const freshAuth = createRelayAuth({ database: join(box.root, 'auth.sqlite'), github: {} });
+ try {
+ assert.deepEqual(freshAuth.pendingCleanup(), [B], 'the intent comes from persisted auth state');
+ const restarted = createRelayRetention({ ...box.config, auth: freshAuth });
+ restarted.maintain();
+ assert.equal(existsSync(join(box.data, B + '.journal.sqlite')), false);
+ assert.deepEqual(readdirSync(box.backups), []);
+ assert.deepEqual(freshAuth.pendingCleanup(), []);
+ } finally { freshAuth.close(); }
+ await box.auth.linkBoard(box.signed.token, B, 'fixture/repository');
+});
+
+test('[H18] SQLite backups contain current compacted state, stay private, and prune only after fourteen days', async (t) => {
+ const box = await fixture(t);
+ box.journal(A, (db) => { db.append(2, box.payload, 'move', PERSON); db.saveSnapshot(1, box.payload, PERSON); });
+ const at = box.at();
+ let saved;
+ box.auth.withBoard(A, () => {
+ const active = createRelayJournal({ directory: box.data, boardId: A, now: () => new Date(box.at()) });
+ try {
+ active.append(3, box.payload, 'move', PERSON);
+ assert.ok(existsSync(join(box.data, A + '.journal.sqlite-wal')), 'the source has live committed WAL contents');
+ saved = box.retention.backup();
+ } finally { active.close(); }
+ });
+ const name = A + '.' + at + '.sqlite';
+ assert.ok(saved.written.includes(name));
+ assert.equal(statSync(box.backups).mode & 0o777, 0o700);
+ assert.equal(statSync(join(box.backups, name)).mode & 0o777, 0o600);
+ const copy = new DatabaseSync(join(box.backups, name), { readOnly: true });
+ try {
+ assert.equal(copy.prepare('SELECT sequence FROM journal_head').get().sequence, 3);
+ assert.equal(copy.prepare('SELECT sequence FROM journal_snapshot').get().sequence, 1);
+ assert.deepEqual(copy.prepare('SELECT sequence FROM journal_record').all().map((row) => row.sequence), [2, 3]);
+ assert.deepEqual(Buffer.from(copy.prepare('SELECT payload FROM journal_snapshot').get().payload), box.payload);
+ } finally { copy.close(); }
+ for (const file of readdirSync(box.backups)) {
+ const bytes = readFileSync(join(box.backups, file));
+ assert.equal(bytes.includes(box.key), false);
+ assert.equal(bytes.includes(Buffer.from(box.marker)), false);
+ }
+ writeFileSync(join(box.backups, 'operator.txt'), 'keep', { mode: 0o600 });
+ box.advance(14);
+ assert.deepEqual(box.retention.prune(), []);
+ box.set(box.at() + 1);
+ assert.equal(box.retention.prune().length, 2);
+ assert.deepEqual(readdirSync(box.backups), ['operator.txt']);
+});
+
+test('[H18] maintenance is daily, retries storage failures, and refuses symlink or invalid-clock deletion', async (t) => {
+ const box = await fixture(t);
+ const first = box.relay.maintenance();
+ assert.equal(first.written.length, 2);
+ assert.equal(box.relay.maintenance().written.length, 0);
+ box.advance(1);
+ assert.equal(box.relay.maintenance().written.length, 2);
+ const outside = join(box.root, 'outside');
+ writeFileSync(outside, 'keep', { mode: 0o600 });
+ const link = join(box.backups, A + '.0.sqlite');
+ symlinkSync(outside, link);
+ assert.throws(() => box.relay.maintenance(), { code: 'RELAY_STORAGE' });
+ assert.deepEqual(box.relay.maintenanceStatus(), { error: 'RELAY_STORAGE' });
+ assert.equal(readFileSync(outside, 'utf8'), 'keep');
+ rmSync(link);
+ assert.doesNotThrow(() => box.relay.maintenance());
+ assert.deepEqual(box.relay.maintenanceStatus(), { error: null });
+ const before = readdirSync(box.backups);
+ box.set(NaN);
+ assert.throws(() => box.retention.maintain(), { code: 'RELAY_CLOCK' });
+ assert.deepEqual(readdirSync(box.backups), before);
+});
+
+test('[H18] a never-uploaded link expires from its original link time without manufacturing a journal', async (t) => {
+ const box = await fixture(t);
+ const C = 'c'.repeat(32);
+ await box.auth.linkBoard(box.signed.token, C, 'fixture/repository');
+ const linked = box.auth.linkedBoards().find((row) => row.id === C).linkedAt;
+ box.set(linked + 60 * DAY);
+ assert.equal(box.retention.notice(C).inactiveDays, 60);
+ assert.equal(existsSync(join(box.data, C + '.journal.sqlite')), false);
+ box.set(linked + 90 * DAY);
+ assert.equal(box.retention.expire(C), true);
+ assert.equal(box.auth.linkedBoards().some((row) => row.id === C), false);
+ assert.equal(existsSync(join(box.data, C + '.journal.sqlite')), false);
+});
+
+
+test('[H18] a move holding the shared process lock refreshes activity before an expiry decision', async (t) => {
+ const box = await fixture(t);
+ const code = `
+ import { createRelayAuth } from ${JSON.stringify(new URL('../relay/auth.js', import.meta.url).href)};
+ import { createRelayJournal } from ${JSON.stringify(new URL('../relay/journal.js', import.meta.url).href)};
+ import { createRelayRetention } from ${JSON.stringify(new URL('../relay/retention.js', import.meta.url).href)};
+ const [database, directory, backupsDirectory, board, clock] = process.argv.slice(1);
+ const auth = createRelayAuth({ database, github: {} });
+ const now = Number(clock);
+ process.send({ kind: 'ready' });
+ process.once('message', (command) => {
+ try {
+ if (command === 'append') auth.withBoard(board, () => {
+ process.send({ kind: 'locked' });
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 350);
+ const journal = createRelayJournal({ directory, boardId: board, now: () => new Date(now + 89 * 86400000) });
+ try { journal.append(2, Uint8Array.of(3, 4, 5), 'move', { kind: 'person', userId: '7' }); }
+ finally { journal.close(); }
+ process.send({ kind: 'appended' });
+ });
+ else {
+ const retention = createRelayRetention({ directory, backupsDirectory, auth, now: () => now + 90 * 86400000 });
+ process.send({ kind: 'expired', value: retention.expire(board) });
+ }
+ } catch (error) { process.send({ kind: 'failed', code: error.code ?? 'NATIVE' }); }
+ finally { auth.close(); process.disconnect(); }
+ });`;
+ /** Launch only our fixture worker; capture safe IPC records and never raw credentials or payloads. */
+ function worker() {
+ const child = spawn(process.execPath, ['--input-type=module', '-e', code, join(box.root, 'auth.sqlite'), box.data, box.backups, A, String(box.at())], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
+ const messages = [];
+ const waiters = new Set();
+ child.on('message', (value) => { messages.push(value); for (const wake of waiters) wake(); });
+ t.after(() => { if (child.exitCode === null) child.kill('SIGTERM'); });
+ /** Await a specific worker phase with a bounded deadline, without relying on a startup sleep. */
+ function phase(kind) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => { waiters.delete(check); reject(new Error('fixture worker phase timed out')); }, 10_000);
+ /** Resolve only the requested safe phase, and surface a fixed refusal code on worker failure. */
+ function check() {
+ const failure = messages.find((entry) => entry.kind === 'failed');
+ const result = messages.find((entry) => entry.kind === kind);
+ if (!failure && !result) return;
+ clearTimeout(timer); waiters.delete(check);
+ if (failure) reject(new Error('fixture worker refused: ' + failure.code)); else resolve(result);
+ }
+ waiters.add(check); check();
+ });
+ }
+ return { child, phase };
+ }
+ const holder = worker();
+ const expiry = worker();
+ await Promise.all([holder.phase('ready'), expiry.phase('ready')]);
+ holder.child.send('append');
+ await holder.phase('locked');
+ expiry.child.send('expire');
+ assert.equal((await expiry.phase('expired')).value, false);
+ await holder.phase('appended');
+ assert.equal(box.journal(A, (db) => db.latest()), 2);
+ assert.ok(existsSync(join(box.data, A + '.journal.sqlite')));
+ // A stale cleaner must do nothing after intent completion and relinking.
+ box.retention.unlink(A);
+ await box.auth.linkBoard(box.signed.token, A, 'fixture/repository');
+ box.journal(A, (db) => db.saveSnapshot(0, box.payload, PERSON));
+ let staleCleanerRan = false;
+ box.auth.withCleanup(A, () => { staleCleanerRan = true; });
+ assert.equal(staleCleanerRan, false);
+ assert.ok(existsSync(join(box.data, A + '.journal.sqlite')));
+});
diff --git a/test/relay-sealed.test.js b/test/relay-sealed.test.js
index f4f8c6b4..78a5edd1 100644
--- a/test/relay-sealed.test.js
+++ b/test/relay-sealed.test.js
@@ -144,7 +144,8 @@ test('[A4,H7] snapshots compact covered moves, preserve the tail and deletion re
assert.equal((await box.call(otherPath + '/state', { method: 'PUT', token: box.person.token, body: { sequence: 0, sealed: box.clientSeal({ other: true }, 'snapshot', 0, other) } })).status, 200);
assert.equal((await box.call(box.path, { method: 'DELETE', token: box.person.token })).status, 200);
for (const suffix of ['', '-wal', '-shm']) assert.equal(existsSync(join(box.data, box.id + '.journal.sqlite' + suffix)), false);
- assert.equal((await box.call(box.path + '/state')).status, 404);
+ assert.equal((await box.call(box.path + '/state', { token: box.person.token })).status, 404);
+ assert.equal((await box.call(box.path + '/state')).status, 401, 'unlink revokes board-scoped credentials');
assert.deepEqual(box.clientOpen((await box.call(otherPath + '/state', { token: box.person.token })).body.state.sealed, 'snapshot', 0, other), { other: true });
assert.deepEqual(JSON.parse(box.cli('export')), box.document);
});