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): report paired devices and board access [H17]

Corey Olson4abbecfe3cef
diff --git a/docs/api.md b/docs/api.md
index a5a8631d..e9e338f1 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -265,13 +265,13 @@ Only the coordinator sets or edits an item's `--check`. `pullboard check [id]` p
`relay on --all [--url <address>]` returns `{version, linked: [{project, root, board}], failed: [{project, root, reason}], paired, autoLink: true}`. Its status is nonzero when a project failed; successful links remain available. With no paired phone, the command prints one tappable pairing link and QR, then waits in the foreground up to ten minutes. Interruption or expiration leaves completed links intact and exits zero when no link failed. Every explicit invocation signs in afresh; no person session is retained on the Mac. Later project registrations publish one sealed phone-link proposal and keep working locally until its single approval tap. `doctor` and `resume` name the waiting project and its expiry; expiration requires an explicit fresh sign-in rather than silently asking again. `relay off` excludes that project from automatic linking; explicit `relay on` clears the exclusion.
-`relay devices` returns `{version, devices: [{deviceId, label, fingerprint, createdAt}]}` without a private key or credential. `relay revoke <deviceId>` returns `{version, deviceId, revoked: true, notice}` after removing the local recipient and deleting its remote wraps. Native revocation never asks the target device to approve its own removal. Another paired phone can approve it with a short-lived, single-use, RAM-only grant for that exact target. With no other paired approver or no linked publishing board, the person completes a fresh GitHub device-code sign-in on the computer instead. The authenticated account and relay origin must match the saved enrollment; the fresh session stays in memory and is revoked after the action. Agent terminals are refused before any sign-in or network request. A failed or interrupted approval or sign-in needs an explicit retry. Revocation stops future wrapping and refuses the removed browser’s enrolled session with `DEVICE_REVOKED` (HTTP 403), including snapshot/event reads and auth-session, board-list and token-list reads. That same principal boundary refuses its machine or agent credential issuance, so the removed session cannot mint another reader. The public board-free shell still loads to clear local browser data; it grants no person actions. Its next connected page clears the locally held board keys, private device key and board request cache and shows that it was removed; reload retains the refusal. The relay stores only public session ids tied to the enrollment, never an extra bearer credential. A fresh GitHub sign-in remains eligible for recovery; it does not resurrect the revoked device. An offline copy cannot be remotely erased and board key rotation remains separate (#346).
+`relay devices` returns `{version, devices: [{deviceId, pairedHere, label, createdAt, seen, revoked, boards}], computers: [{machine, host, created, seen, boards}]}` without a private key or credential. `devices` are the phones that read this computer's linked boards; `computers` are the other computers that joined one of them with `relay join`. Only the computer that paired a phone keeps its `label` and `createdAt`; a phone paired on another computer has `pairedHere: false`, null `label` and `createdAt`, and prints as paired on another computer with the end of its id. `seen` is the last relay contact in epoch milliseconds, or null when unknown, `revoked` is the relay's revocation status, and `boards` names the linked boards each one can read. The text output names each one with its paired date, last seen and boards. `--verbose` adds ids in the text and, for phones paired here, the key `fingerprint` in both text and JSON. `relay revoke <deviceId>` returns `{version, deviceId, revoked: true, notice}` after removing the local recipient and deleting its remote wraps. Native revocation never asks the target device to approve its own removal. Another paired phone can approve it with a short-lived, single-use, RAM-only grant for that exact target. With no other paired approver or no linked publishing board, the person completes a fresh GitHub device-code sign-in on the computer instead. The authenticated account and relay origin must match the saved enrollment; the fresh session stays in memory and is revoked after the action. Agent terminals are refused before any sign-in or network request. A failed or interrupted approval or sign-in needs an explicit retry. Revocation stops future wrapping and refuses the removed browser’s enrolled session with `DEVICE_REVOKED` (HTTP 403), including snapshot/event reads and auth-session, board-list and token-list reads. That same principal boundary refuses its machine or agent credential issuance, so the removed session cannot mint another reader. The public board-free shell still loads to clear local browser data; it grants no person actions. Its next connected page clears the locally held board keys, private device key and board request cache and shows that it was removed; reload retains the refusal. The relay stores only public session ids tied to the enrollment, never an extra bearer credential. A fresh GitHub sign-in remains eligible for recovery; it does not resurrect the revoked device. An offline copy cannot be remotely erased and board key rotation remains separate (#346).
Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed before sign-in. The secret remains on the phone and Mac. Person-authenticated `/api/v1/devices/session` returns the current account id. `/api/v1/devices/enrollments/:locator` supports POST `{}` to start a ten-minute locator, PUT of the exact public enrollment and MAC, GET of `{version, enrollment}` and DELETE to consume it. A native Mac checks the MAC locally before retaining any recipient. `/api/v1/devices/:deviceId` supports POST `{}` to record an authenticated recipient and DELETE to revoke it. PUT `/api/v1/devices/:deviceId/boards/:boardId` stores `{engine, wrapped}`; GET `/api/v1/devices/:deviceId/boards` returns `{version, wraps: [{board, engine, wrapped}]}` filtered by current board access. `wrapped` is opaque base64url client ciphertext. Enrollment, device listing and direct revocation require a person session. A board-scoped machine credential can PUT only its own board wrap to an already enrolled device. Cookie writes require the exact configured Origin, and all responses are no-store. Device ids and grants belong to the authenticated GitHub account. Revoked ids cannot be registered or uploaded again.
-`POST /auth/machines {board,machine}` requires a foreground person session and returns a `pm_` credential bound to that board and machine. This delegate can mint board-scoped `pa_` tokens through `/auth/tokens` and list only its board’s token ids and metadata. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints. Agent tokens cannot mint any credential.
+`POST /auth/machines {board,machine,host?}` requires a foreground person session and returns a `pm_` credential bound to that board and machine; `relay join` sends its host name as `host`. `GET /api/v1/devices/<deviceId>` with a board's `pm_` credential returns `{version, seen, revoked}` for a phone of the same account, with null fields for an unknown id. `GET /api/v1/devices` with that credential returns `{version, devices: [{deviceId, seen, revoked}]}` for the phones holding that board's key, by id only; names stay on the computer that paired them. This delegate can mint board-scoped `pa_` tokens through `/auth/tokens` and list only its board’s token ids and metadata. It cannot link a board, issue a machine credential, post a phone request, revoke another credential directly, or use person-only cookie endpoints. Agent tokens cannot mint any credential.
-`GET /auth/machines?board=<id>` returns `{version, machines: [{machine}]}` for the live computer credentials on that board, with duplicate computer ids listed once. It requires that board's machine credential or a person session with current repository write access; agent tokens and credentials from another board are refused. `relay off` excludes its own computer from the list and warns which joined computers lose the shared copy if the phone approves deletion. JSON also returns those ids in `affectedMachines`. Local unlink still succeeds when the relay cannot supply the list.
+`GET /auth/machines?board=<id>` returns `{version, machines: [{machine, host, created, seen}]}` for the live computer credentials on that board, with duplicate computer ids listed once. `host` is the host name the computer sent when it joined, or null; `created` is its first join and `seen` its last relay contact, which moves at most once a minute. It requires that board's machine credential or a person session with current repository write access; agent tokens and credentials from another board are refused. `relay off` excludes its own computer from the list and warns which joined computers lose the shared copy if the phone approves deletion. The warning names each computer by its host name, or by the end of its id when the relay has no host for it. JSON also returns those ids in `affectedMachines` and the names in `joined`. Local unlink still succeeds when the relay cannot supply the list.
After phone-approved deletion, a previously live scoped credential receives HTTP 410 / `RELAY_BOARD_DELETED` for that deleted copy. The relay retains only its hash, board id and original expiry as a deletion receipt, prunes expired receipts, and grants no access through them. Unknown, already revoked and already expired credentials receive `AUTH_REQUIRED` as before. Only a versioned deletion response naming this link's own board turns a joined computer back into a local board. The CLI removes the inert link and its device key, excludes the project from automatic relinking, and retains a private credential-free notice that the relay copy was deleted; native board contents remain local. A successful explicit `relay on` starts a new link and clears that notice. A network outage or ordinary credential refusal does not authorize this transition. Before forgetting a deleted copy, the CLI commits any pending native move and its durable receipt locally. The notice keeps only the receipt id and intent digests, so interrupted cleanup or an explicit repeat can return the original outcome without applying that move twice; different local work can continue beside it.
diff --git a/relay/auth.js b/relay/auth.js
index 1172be7f..906ca482 100644
--- a/relay/auth.js
+++ b/relay/auth.js
@@ -51,6 +51,12 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
if (!db.prepare('PRAGMA table_info(relay_credentials)').all().some((column) => column.name === 'created')) {
db.exec('ALTER TABLE relay_credentials ADD COLUMN created INTEGER');
}
+ // A joined computer's host name and last contact let its owner recognise it in relay devices.
+ for (const column of ['host TEXT', 'seen INTEGER']) {
+ if (!db.prepare('PRAGMA table_info(relay_credentials)').all().some((entry) => entry.name === column.split(' ')[0])) {
+ db.exec('ALTER TABLE relay_credentials ADD COLUMN ' + column);
+ }
+ }
// 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');
@@ -108,6 +114,8 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
if (row.kind === 'session') {
for (const guard of sessionGuards) guard({ id: row.id, kind: row.kind, user: { id: row.user_id }, expires: row.expires });
}
+ // Last seen moves at most once a minute, so ordinary sync does not rewrite the row on every request.
+ if (row.kind === 'machine' && !(row.seen > now() - 60_000)) db.prepare('UPDATE relay_credentials SET seen=? WHERE id=?').run(now(), row.id);
return row;
}
@@ -524,14 +532,19 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
return db.prepare("SELECT 1 FROM relay_credentials WHERE board=? AND kind='board' LIMIT 1").get(board) ? 3 : 1;
},
/** Give a foreground person one board-bound machine delegate, never another person credential. */
- async issueMachine(token, { board, machine, expiresIn = MAX_TTL }) {
+ async issueMachine(token, { board, machine, host, expiresIn = MAX_TTL }) {
identifier(board, 'BAD_BOARD');
identifier(machine, 'BAD_MACHINE');
+ if (host !== undefined && (typeof host !== 'string' || !host.trim() || host.length > 255 || /[\u0000-\u001f\u007f]/u.test(host))) {
+ throw new Refused('BAD_REQUEST', 'send the joining computer’s host name as plain text of at most 255 characters');
+ }
if (!Number.isSafeInteger(expiresIn) || expiresIn <= 0 || expiresIn > MAX_TTL) throw new Refused('BAD_EXPIRY', 'choose a machine expiry of at most thirty days');
const principal = await auth.authenticate(token, { board, write: true });
if (principal.kind !== 'session') throw new Refused('HUMAN_REQUIRED', 'approve this machine from the signed-in phone');
credential(token);
- return { ...issue(principal.user, 'machine', board, machine, expiresIn), board, machine };
+ const issued = issue(principal.user, 'machine', board, machine, expiresIn);
+ if (host !== undefined) db.prepare('UPDATE relay_credentials SET host=? WHERE id=?').run(host, issued.id);
+ return { ...issued, board, machine };
},
/** List live computer identities only for this board's machine or a freshly authorized person. */
async listMachines(token, board) {
@@ -539,7 +552,9 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =
const principal = await auth.authenticate(token, { board, write: true });
if (!['session', 'machine'].includes(principal.kind)) throw new Refused('HUMAN_REQUIRED', 'use this board’s machine credential or the signed-in phone to list joined computers');
credential(token);
- return db.prepare("SELECT DISTINCT agent AS machine FROM relay_credentials WHERE board=? AND kind='machine' AND revoked=0 AND expires>? ORDER BY agent").all(board, now());
+ // Each computer is listed once, by the host name it sent when it joined, with its first join and last contact.
+ return db.prepare("SELECT agent AS machine, MAX(host) AS host, MIN(created) AS created, MAX(seen) AS seen FROM relay_credentials WHERE board=? AND kind='machine' AND revoked=0 AND expires>? GROUP BY agent ORDER BY agent")
+ .all(board, now()).map(row => ({ machine: row.machine, host: row.host ?? null, created: row.created ?? null, seen: row.seen ?? null }));
},
/** Mint an agent credential scoped to a single readable board and immutable human identity. */
async issueToken(token, { board, agent, expiresIn = tokenTTL }) {
diff --git a/relay/device-http.js b/relay/device-http.js
index 061d1355..8c2faa08 100644
--- a/relay/device-http.js
+++ b/relay/device-http.js
@@ -76,6 +76,16 @@ export function createDeviceHandler({ authenticate, authorizeBoard, boardsFor, d
}
// A machine may wrap only its own board to an already enrolled device, never enroll or revoke.
if (who.kind === 'machine') {
+ // A joined computer lists its own board's phones by id; their names stay on the computer that paired them.
+ if (url.pathname === '/api/v1/devices' && req.method === 'GET') {
+ await authorizeBoard(req, who.board);
+ apiJson(res, 200, { devices: devices.boardDevices(account, who.board) }); return true;
+ }
+ const seen = /^\/api\/v1\/devices\/(device-[0-9a-f]{32})$/.exec(url.pathname);
+ if (seen && req.method === 'GET') {
+ await authorizeBoard(req, who.board);
+ apiJson(res, 200, devices.status(account, seen[1])); return true;
+ }
const wrap = /^\/api\/v1\/devices\/(device-[0-9a-f]{32})\/boards\/([0-9a-f]{32})$/.exec(url.pathname);
if (!wrap || req.method !== 'PUT' || wrap[2] !== who.board) throw new Refused('HUMAN_REQUIRED', 'approve device management from the paired phone');
await authorizeBoard(req, who.board);
diff --git a/relay/device-store.js b/relay/device-store.js
index bb52ed1c..d2797e1b 100644
--- a/relay/device-store.js
+++ b/relay/device-store.js
@@ -24,6 +24,8 @@ export function createDeviceStore({ directory, now = Date.now }) {
board TEXT NOT NULL, device TEXT NOT NULL, action TEXT NOT NULL, machine TEXT NOT NULL, expires INTEGER NOT NULL,
context TEXT NOT NULL, sealed TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'waiting', response TEXT);
CREATE UNIQUE INDEX IF NOT EXISTS phone_approval_pending ON phone_approval(account,board,action) WHERE state='waiting';`);
+ // The phone's last contact lets its owner see from the linked computer whether it still reads the boards.
+ if (!opened.prepare('PRAGMA table_info(device)').all().some(column => column.name === 'seen')) opened.exec('ALTER TABLE device ADD COLUMN seen INTEGER');
db = opened;
return db;
} catch (error) { opened.close(); throw error; }
@@ -41,6 +43,10 @@ export function createDeviceStore({ directory, now = Date.now }) {
if (!row) throw new Refused('DEVICE_PAIR_EXPIRED', 'Run pullboard relay on --all for a fresh one-time pairing link.');
return row;
}
+ /** Record a phone read as its last contact, at most once a minute. */
+ function touch(account, id) {
+ database().prepare('UPDATE device SET seen=? WHERE account=? AND id=? AND (seen IS NULL OR seen<?)').run(now(), account, id, now() - 60_000);
+ }
/** Keep expired approval metadata visible without renewing it or silently asking the phone again. */
function expireApprovals() {
database().prepare("UPDATE phone_approval SET state='expired', response=NULL WHERE expires<=? AND state IN ('waiting','approved')").run(now());
@@ -95,6 +101,7 @@ export function createDeviceStore({ directory, now = Date.now }) {
/** List only this paired phone's account inbox; a machine never gets the account inventory. */
approvals(account, device) {
active(account, device);
+ touch(account, device);
expireApprovals();
return database().prepare("SELECT * FROM phone_approval WHERE account=? AND device=? AND state='waiting' ORDER BY expires,id").all(account, device).map(approval);
},
@@ -137,13 +144,24 @@ export function createDeviceStore({ directory, now = Date.now }) {
/** List only this account/device's opaque grants; the HTTP boundary rechecks board access. */
wraps(account, id) {
active(account, id);
+ touch(account, id);
return database().prepare('SELECT board,engine,wrapped FROM wrapped_key WHERE account=? AND device=? ORDER BY board').all(account, id);
},
+ /** Return when a phone of this account last read its approvals or keys, and whether it was revoked; null fields for an unknown id. */
+ status(account, id) {
+ const row = database().prepare('SELECT seen, revoked FROM device WHERE account=? AND id=?').get(account, id);
+ return row ? { seen: row.seen ?? null, revoked: row.revoked === 1 } : { seen: null, revoked: null };
+ },
+ /** List the phones of this account that hold this board's key, by id only: names stay on the computer that paired them. */
+ boardDevices(account, board) {
+ return database().prepare('SELECT d.id AS deviceId, d.seen AS seen, d.revoked AS revoked FROM wrapped_key w JOIN device d ON d.account=w.account AND d.id=w.device WHERE w.account=? AND w.board=? ORDER BY d.id')
+ .all(account, board).map(row => ({ deviceId: row.deviceId, seen: row.seen ?? null, revoked: row.revoked === 1 }));
+ },
/** Tombstone first and delete grants atomically, refusing any stale in-flight upload. */
revoke(account, id) {
database().exec('BEGIN IMMEDIATE');
try {
- database().prepare('INSERT INTO device VALUES(?,?,1) ON CONFLICT(account,id) DO UPDATE SET revoked=1').run(account, id);
+ database().prepare('INSERT INTO device(account,id,revoked) VALUES(?,?,1) ON CONFLICT(account,id) DO UPDATE SET revoked=1').run(account, id);
database().prepare('DELETE FROM wrapped_key WHERE account=? AND device=?').run(account, id);
database().exec('COMMIT');
} catch (error) { database().exec('ROLLBACK'); throw error; }
diff --git a/src/cli.js b/src/cli.js
index ea3ef3aa..d4f5f1a2 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -103,7 +103,7 @@ import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } fro
import { addRunner, browserFreeChecksEnabled, gateQueueSettings, gateShortSlots, loadMachineSettings, memoryFloorMB, relayOfferEnabled, setBrowserSlots, setGateShortSlots, setGateSlots } from './settings.js';
import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';
import { autoLinkProject, offerRelayAtInit, relayOnAllCommand, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';
-import { readRelayMachine } from './relay-machine.js';
+import { relayRoster, rosterLines } from './relay-roster.js';
import { relayJoin, relayPair } from './relay-pairing-client.js';
import { executePersonRequests } from './relay-request-execution.js';
import { engineReceipt } from './engine.js';
@@ -313,6 +313,7 @@ const OPTIONS = {
must: { type: 'boolean' },
json: { type: 'boolean' },
history: { type: 'boolean' },
+ verbose: { type: 'boolean' },
since: { type: 'string' },
decision: { type: 'boolean' },
evidence: { type: 'string' },
@@ -4030,11 +4031,10 @@ async function runCommand(argv, io) {
}
if (values.skip) throw new Refused('USAGE', '--skip is only valid with pullboard relay recover');
if (first === 'devices') {
- if (second || rest.length || values.url || values.all) throw new Refused('USAGE', 'pullboard relay devices');
- const devices = readRelayMachine().devices.map(({ deviceId, label, fingerprint, createdAt }) => ({ deviceId, label, fingerprint, createdAt }));
- io.result?.({ devices });
- for (const device of devices) io.say(`${device.deviceId} ${device.label} ${device.fingerprint}`);
- if (!devices.length) io.say('no paired devices; run pullboard relay on --all');
+ if (second || rest.length || values.url || values.all) throw new Refused('USAGE', 'pullboard relay devices [--verbose]');
+ const roster = await relayRoster({ verbose: values.verbose });
+ io.result?.(roster);
+ for (const line of rosterLines(roster, { verbose: values.verbose })) io.say(line);
return 0;
}
if (first === 'revoke' && /^device-[0-9a-f]{32}$/u.test(second ?? '')) {
diff --git a/src/help.js b/src/help.js
index eac08d1c..884b8b78 100644
--- a/src/help.js
+++ b/src/help.js
@@ -45,7 +45,8 @@ Set up
pair prints a one-use machine code; join stores it in another clone
pullboard relay on --all [--url <address>] link every registered project after one sign-in; pair the phone once
keep this command open until pairing finishes; later projects link on registration
- pullboard relay devices list paired device ids and their public-key fingerprints
+ pullboard relay devices [--verbose] paired phones and joined computers by name, with paired date, last seen and boards
+ --verbose adds each id and phone key fingerprint
pullboard relay revoke <device> stop future key delivery; already received keys remain known
approve on another paired phone, or sign in again with GitHub
pullboard relay tokens list this board's agent token ids, agents and expiry, never credentials
diff --git a/src/relay-pairing-client.js b/src/relay-pairing-client.js
index 43dc086b..1cdadb3b 100644
--- a/src/relay-pairing-client.js
+++ b/src/relay-pairing-client.js
@@ -1,6 +1,7 @@
/** CLI pairing flow: the relay stores only a one-use client-encrypted package [H15,H17]. */
import { randomUUID } from 'node:crypto';
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { hostname } from 'node:os';
import { dirname, join } from 'node:path';
import * as store from './board.js';
import { exportBoard, importBoard } from './exchange.js';
@@ -14,6 +15,7 @@ import { ENGINE_VERSION } from './machine.js';
import { Refused } from './refused.js';
import { requirePersonChannel } from './person.js';
import { updateRelayMachine } from './relay-machine.js';
+import { listApiProjects } from './projects.js';
const TOKEN = /^pm_[A-Za-z0-9_-]{43}$/;
const BOARD = /^[0-9a-f]{32}$/;
@@ -223,7 +225,8 @@ export async function relayJoin(root, code, address, io) {
const file = linkFile(root);
if (existsSync(file)) throw new Refused('RELAY_LINKED', 'this clone already has relay link metadata; use a fresh clone to join another device');
const machine = updateRelayMachine(state => state.machine);
- const issued = await relayRequest(url, signed.token, '/auth/machines', { board: bundle.board, machine });
+ // The linked computer lists this one by its host name, in relay devices and before relay off.
+ const issued = await relayRequest(url, signed.token, '/auth/machines', { board: bundle.board, machine, host: hostname() });
if (!TOKEN.test(issued.token) || issued.board !== bundle.board || issued.machine !== machine) throw new Refused('RELAY_RESPONSE', 'the relay did not issue this joined board’s machine credential; pair again');
let keyStorage;
try {
@@ -245,8 +248,10 @@ export async function relayJoin(root, code, address, io) {
throw error;
}
await syncRelay(root, io);
- const result = { linked: true, board: bundle.board, url: bundle.url, sequence: bundle.sequence, behind: 0 };
+ const name = listApiProjects().find(project => project.root === repoInfo(root).root)?.name ?? bundle.repository;
+ const notice = `Joined ${name}. This brought one board; for another, run pullboard relay pair in that board on the linked computer. Run pullboard status to read it.`;
+ const result = { linked: true, board: bundle.board, name, url: bundle.url, sequence: bundle.sequence, behind: 0, notice };
io.result?.(result);
- io.say(`paired board ${bundle.board}; run pullboard status to read it`);
+ io.say(notice);
return 0;
}
diff --git a/src/relay-roster.js b/src/relay-roster.js
new file mode 100644
index 00000000..704faf6f
--- /dev/null
+++ b/src/relay-roster.js
@@ -0,0 +1,124 @@
+/** Who reads this computer's linked boards: paired phones and joined computers, by name [H17]. */
+import { ENGINE_VERSION } from './machine.js';
+import { listApiProjects } from './projects.js';
+import { readRelayMachine } from './relay-machine.js';
+import { relayMachineContext, relayOrigin } from './relay.js';
+
+const MACHINE = /^[A-Za-z0-9_.-]{1,128}$/u;
+const DEVICE = /^device-[0-9a-f]{32}$/u;
+
+/** Read one roster document with a board's machine credential; an older or unreachable relay gives null. */
+async function rosterRead(state, path) {
+ try {
+ const response = await fetch(relayOrigin(state.url) + path, { redirect: 'error', signal: AbortSignal.timeout(5000),
+ headers: { authorization: 'Bearer ' + state.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });
+ return response.ok ? await response.json() : null;
+ } catch {
+ // The roster is a courtesy: local names and dates still print when the relay cannot answer.
+ return null;
+ }
+}
+
+/** Return this computer's registered boards that hold a live machine link, with their names. */
+function linkedBoards() {
+ return listApiProjects().flatMap(project => {
+ let state;
+ try { state = relayMachineContext(project.root); } catch { return []; }
+ return state && !state.unlinking && state.token?.startsWith('pm_') ? [{ name: project.name, state }] : [];
+ });
+}
+
+/** List the other computers that joined one linked board, by host name when the relay recorded it. */
+export async function joinedComputers(state) {
+ const document = await rosterRead(state, '/auth/machines?board=' + state.board);
+ if (!Array.isArray(document?.machines)) return [];
+ return document.machines.filter(entry => MACHINE.test(entry?.machine ?? '') && entry.machine !== state.machine).map(entry => ({
+ machine: entry.machine,
+ host: typeof entry.host === 'string' && entry.host ? entry.host : null,
+ created: Number.isSafeInteger(entry.created) ? entry.created : null,
+ seen: Number.isSafeInteger(entry.seen) ? entry.seen : null,
+ }));
+}
+
+/** Name a joined computer by its host, or by the end of its id when it joined before hosts were recorded. */
+function computerName(computer) {
+ return computer.host ?? 'computer ' + computer.machine.slice(-8);
+}
+
+/** List the phones that hold one linked board's key, by id, with the relay's last seen and revoked status. */
+export async function boardPhones(state) {
+ const document = await rosterRead(state, '/api/v1/devices');
+ if (!Array.isArray(document?.devices)) return [];
+ return document.devices.filter(entry => DEVICE.test(entry?.deviceId ?? '')).map(entry => ({
+ deviceId: entry.deviceId, seen: Number.isSafeInteger(entry.seen) ? entry.seen : null, revoked: entry.revoked === true,
+ }));
+}
+
+/** Gather every paired phone and joined computer with its dates and the boards it can read; fingerprints only when verbose. */
+export async function relayRoster({ verbose = false } = {}) {
+ const boards = linkedBoards();
+ const inventory = new Map();
+ for (const board of boards) inventory.set(board.state, await boardPhones(board.state));
+ const phones = new Map();
+ for (const device of readRelayMachine().devices) {
+ // Local pairing history supplies the label; only each board's current inventory proves access.
+ const reads = boards.filter(board => board.state.account === device.account && board.state.url === device.url);
+ const document = reads.length ? await rosterRead(reads[0].state, '/api/v1/devices/' + device.deviceId) : null;
+ const grants = document?.revoked === true ? [] : reads.filter(board => inventory.get(board.state).some(entry => entry.deviceId === device.deviceId && !entry.revoked));
+ phones.set(device.deviceId, { deviceId: device.deviceId, pairedHere: true, label: device.label, createdAt: device.createdAt,
+ ...(verbose ? { fingerprint: device.fingerprint } : {}),
+ seen: Number.isSafeInteger(document?.seen) ? document.seen : null, revoked: document?.revoked === true, boards: grants.map(board => board.name) });
+ }
+ // A phone paired on another computer is known here only by the id the relay holds for the board; its name stays there.
+ for (const board of boards) {
+ for (const entry of inventory.get(board.state)) {
+ if (entry.revoked) continue;
+ const known = phones.get(entry.deviceId) ?? { deviceId: entry.deviceId, pairedHere: false, label: null, createdAt: null, seen: null, revoked: false, boards: [] };
+ known.seen = Math.max(known.seen ?? -Infinity, entry.seen ?? -Infinity);
+ if (!Number.isFinite(known.seen)) known.seen = null;
+ if (!known.revoked && !known.boards.includes(board.name)) known.boards.push(board.name);
+ phones.set(entry.deviceId, known);
+ }
+ }
+ const devices = [...phones.values()];
+ const computers = new Map();
+ for (const board of boards) {
+ for (const entry of await joinedComputers(board.state)) {
+ const known = computers.get(entry.machine) ?? { ...entry, boards: [] };
+ known.host ??= entry.host;
+ known.created = Math.min(known.created ?? Infinity, entry.created ?? Infinity);
+ known.seen = Math.max(known.seen ?? -Infinity, entry.seen ?? -Infinity);
+ known.boards.push(board.name);
+ computers.set(entry.machine, known);
+ }
+ }
+ const finite = value => Number.isFinite(value) ? value : null;
+ return { devices, computers: [...computers.values()].map(entry => ({ ...entry, created: finite(entry.created), seen: finite(entry.seen) })) };
+}
+
+/** Print a date the way this computer shows dates. */
+function day(value) {
+ return new Date(value).toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' });
+}
+
+/** Print a moment the way this computer shows times. */
+function moment(value) {
+ return value === null ? 'unknown' : new Date(value).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
+}
+
+/** Render one line per phone and computer; ids and fingerprints only when the person asks for them. */
+export function rosterLines(roster, { verbose = false } = {}) {
+ const reads = boards => boards.length ? 'reads ' + boards.join(', ') : 'reads no linked board yet';
+ const lines = [];
+ for (const phone of roster.devices) {
+ const paired = phone.pairedHere ? `${phone.label} (phone): paired ${day(phone.createdAt)}` : `Phone ${phone.deviceId.slice(-8)} (phone): paired on another computer`;
+ lines.push(`${paired}, last seen ${moment(phone.seen)}${phone.revoked ? ', revoked' : ''}; ${reads(phone.boards)}`);
+ if (verbose) lines.push(` ${phone.deviceId}${phone.fingerprint ? ' fingerprint ' + phone.fingerprint : ''}`);
+ }
+ for (const computer of roster.computers) {
+ lines.push(`${computerName(computer)} (computer): joined ${computer.created === null ? 'on an unknown date' : day(computer.created)}, last seen ${moment(computer.seen)}; ${reads(computer.boards)}`);
+ if (verbose) lines.push(` ${computer.machine}`);
+ }
+ if (!lines.length) lines.push('No phones or computers are paired yet. Pair a phone with pullboard relay on --all, or another computer with pullboard relay pair.');
+ return lines;
+}
diff --git a/src/relay.js b/src/relay.js
index f8900245..ffb091f7 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -1540,9 +1540,9 @@ export async function relayOff(root, io) {
let joined = [];
try {
const roster = await request(state, '/auth/machines?board=' + state.board, {}, io);
- if (Array.isArray(roster.machines)) joined = roster.machines.filter(entry => typeof entry.machine === 'string' && /^[A-Za-z0-9_.-]{1,128}$/u.test(entry.machine) && entry.machine !== state.machine).map(entry => entry.machine);
+ if (Array.isArray(roster.machines)) joined = roster.machines.filter(entry => typeof entry.machine === 'string' && /^[A-Za-z0-9_.-]{1,128}$/u.test(entry.machine) && entry.machine !== state.machine).map(entry => ({ machine: entry.machine, name: typeof entry.host === 'string' && entry.host.trim() ? entry.host : entry.machine.slice(-8) }));
} catch { /* Local unlink still completes when the relay cannot inventory joined computers. */ }
- const warning = joined.length ? ' If you approve deletion, joined computers ' + joined.map(machine => machine.slice(-8)).join(', ') + ' lose the shared copy; their local boards keep working.' : '';
+ const warning = joined.length ? ' If you approve deletion, joined computers ' + joined.map(entry => entry.name).join(', ') + ' lose the shared copy; their local boards keep working.' : '';
if (warning) io.err(warning.trim());
// Local unlink always completes, including agent shells, outages and a fenced remote baseline.
@@ -1563,7 +1563,7 @@ export async function relayOff(root, io) {
}
return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, recovery: recoverySummary(null),
...(remote ? { remote } : {}),
- ...(joined.length ? { affectedMachines: joined } : {}),
+ ...(joined.length ? { affectedMachines: joined.map(entry => entry.machine), joined: joined.map(entry => entry.name) } : {}),
notice: 'Local link removed. The relay copy stays until you approve deleting it on your phone.' + warning + (requested ? '' : ' Open the phone to manage the relay copy.') };
});
}
diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.js
index 6e37efc7..d62211f9 100644
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@ -657,7 +657,7 @@ globalThis.fetch = function tracedFetch(input, init) {
const envKey = { ...otherEnv, PULLBOARD_RELAY_KEY: environmentKey };
return childResult(otherRoot, envKey, [CLI, ...args, '--json']);
}
- return { joined: document, machine: link.machine, exported: exported.document, cli: run, syncWithEnvironmentKey,
+ return { joined: document, machine: link.machine, exported: exported.document, cli: run, root: otherRoot, env: otherEnv, syncWithEnvironmentKey,
/** Check that the paired clone still has no persisted board-key file. */
keyFileExists() { return existsSync(otherKeyFile); } };
}
diff --git a/test/relay-machine-auth.test.js b/test/relay-machine-auth.test.js
index 005fe6f0..7ae3860d 100644
--- a/test/relay-machine-auth.test.js
+++ b/test/relay-machine-auth.test.js
@@ -86,7 +86,7 @@ test('deleted-copy receipts grant no access and keep revocation and expiry disti
const other = await auth.issueMachine(person.token, { board: beta, machine: 'joined-beta' });
await auth.revoke(person.token, revoked.id);
now += 2;
- assert.deepEqual((await auth.listMachines(live.token, alpha)).map(row => ({ ...row })), [{ machine: 'joined-alpha' }],
+ assert.deepEqual((await auth.listMachines(live.token, alpha)).map(row => row.machine), ['joined-alpha'],
'the roster excludes revoked and expired computer credentials');
await assert.rejects(auth.listMachines(live.token, beta), { code: 'TOKEN_BOARD' });
auth.forgetBoard(alpha);
diff --git a/test/relay-setup.test.js b/test/relay-setup.test.js
index 8d76ec1c..5b4b873c 100644
--- a/test/relay-setup.test.js
+++ b/test/relay-setup.test.js
@@ -1,13 +1,14 @@
/** The view uses the actual device authorization and all-board linking path without a terminal [H5,N26]. */
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
-import { mkdirSync, readFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { hostname, tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { test } from 'node:test';
import * as setup from '../src/relay-setup.js';
import { relayClientFixture } from './relay-client-fixture.js';
+import { createDeviceKeys, signDeviceEnrollment } from '../src/relay-device-keys.js';
import { runFixtureChild, startFixtureChild } from './fixture-child.js';
/** Run the public view adapter in a process whose complete home, registry and boards are private. */
@@ -238,6 +239,142 @@ test("the view's sign-in links every board without a terminal or a stored sessio
const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');
+/** Pair a stand-in phone through the real relay: Node signs the same enrollment the phone page sends. */
+async function pairPhone(box, t) {
+ const child = startFixtureChild(process.execPath, [CLI, 'relay', 'on', '--all', '--url', box.origin, '--json'], { cwd: box.root, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });
+ t.after(() => { if (child.exitCode === null) child.kill('SIGTERM'); });
+ const exited = new Promise(done => child.once('close', done));
+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine/state.json');
+ const deadline = Date.now() + 20_000; // A hang ceiling for the foreground setup, never a performance assertion.
+ let pending = null;
+ while (!pending && Date.now() < deadline) {
+ if (existsSync(machineFile)) pending = JSON.parse(readFileSync(machineFile, 'utf8')).pending;
+ if (!pending) await new Promise(done => setTimeout(done, 25));
+ }
+ assert.ok(pending, 'the foreground setup publishes one phone enrollment');
+ const headers = { authorization: 'Bearer ' + (await box.phoneSession()).token, 'content-type': 'application/json' };
+ const identity = await (await fetch(box.origin + '/api/v1/devices/session', { headers })).json();
+ const keys = await createDeviceKeys();
+ const createdAt = new Date().toISOString();
+ const body = await signDeviceEnrollment(pending.secret, { v: 1, account: identity.account, locator: pending.locator,
+ deviceId: keys.deviceId, publicKey: keys.publicKey, label: 'Kitchen phone', createdAt });
+ const enrolled = await fetch(box.origin + '/api/v1/devices/enrollments/' + pending.locator, { method: 'PUT', headers, body: JSON.stringify(body) });
+ assert.equal(enrolled.status, 200, 'the relay carries the signed enrollment');
+ assert.equal(await exited, 0, 'the foreground setup pairs the phone');
+ const wraps = await fetch(box.origin + '/api/v1/devices/' + keys.deviceId + '/boards', { headers });
+ assert.equal(wraps.status, 200, 'the paired phone reads its board keys once');
+ return { deviceId: keys.deviceId, createdAt };
+}
+
+/** Pair a phone and join a second computer to this board, the walkthrough's path 5. */
+async function phoneAndJoinedComputer(t) {
+ const box = await relayClientFixture(t);
+ const phone = await pairPhone(box, t);
+ const printed = await box.cli('relay', 'pair');
+ assert.equal(printed.code, 0, 'the linked computer prints a one-time code');
+ const joined = await box.otherDeviceJoin(printed.document.code);
+ return { box, phone, joined };
+}
+
+/** Run relay devices on the linked computer and keep its text lines and its board name. */
+async function devicesText(box, args) {
+ const cliModule = JSON.stringify(pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href);
+ const projectsModule = JSON.stringify(pathToFileURL(resolve(import.meta.dirname, '../src/projects.js')).href);
+ const result = await box.script(`
+import { main } from ${cliModule};
+import { listApiProjects } from ${projectsModule};
+let output = '';
+const streams = { cwd: ${JSON.stringify(box.root)}, stdout: { write: part => { output += part; } }, stderr: { write() {} } };
+const code = await main(${JSON.stringify(['relay', 'devices', ...args])}, streams);
+process.stdout.write(JSON.stringify({ code, lines: output.trim().split('\\n'), names: listApiProjects().map(project => project.name) }));
+`);
+ assert.equal(result.code, 0, 'the private relay devices script completes');
+ assert.equal(result.document.code, 0, 'relay devices succeeds');
+ return result.document;
+}
+
+test('relay devices names phones and joined computers with paired date and boards [H17]', async (t) => {
+ const { box, phone, joined } = await phoneAndJoinedComputer(t);
+ const { lines, names } = await devicesText(box, []);
+ const day = value => new Date(value).toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' });
+ const board = names[0];
+ const phoneLine = lines.find(line => line.startsWith('Kitchen phone (phone): '));
+ assert.ok(phoneLine, 'the phone is named by its label');
+ assert.match(phoneLine, new RegExp(`^Kitchen phone \\(phone\\): paired ${day(phone.createdAt)}, last seen (?!unknown)[^;]+; reads ${board}$`, 'u'),
+ 'the phone line has its paired date, a last seen time and the board it reads');
+ const computerLine = lines.find(line => line.includes('(computer): '));
+ assert.ok(computerLine, 'the joined computer is listed on the linked computer');
+ assert.match(computerLine, new RegExp(`^${hostname().replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')} \\(computer\\): joined ${day(Date.now())}, last seen (?!unknown)[^;]+; reads ${board}$`, 'u'),
+ 'the joined computer is named by its host name, with its joined date, last seen and board');
+ assert.equal(lines.length, 2, 'one line each, with no ids');
+ assert.ok(!/[0-9a-f]{64}/u.test(lines.join('\n')) && !lines.join('\n').includes(phone.deviceId), 'ids and fingerprints stay out of the default view');
+ const verbose = await devicesText(box, ['--verbose']);
+ assert.ok(verbose.lines.some(line => line.includes(phone.deviceId) && /fingerprint [0-9a-f]{64}$/u.test(line)), '--verbose adds the phone id and fingerprint');
+ const json = await box.cli('relay', 'devices');
+ assert.equal(json.code, 0, 'relay devices --json succeeds');
+ const [phoneJson] = json.document.devices;
+ assert.equal(json.document.devices.length, 1, 'the linked computer lists its one paired phone');
+ assert.deepEqual([phoneJson.deviceId, phoneJson.label, phoneJson.pairedHere, phoneJson.createdAt, phoneJson.revoked, phoneJson.boards],
+ [phone.deviceId, 'Kitchen phone', true, phone.createdAt, false, [board]], 'JSON names the phone with its paired date, status and board');
+ assert.ok(Number.isSafeInteger(phoneJson.seen), 'JSON carries the relay last seen time');
+ assert.ok(!('fingerprint' in phoneJson) && !/[0-9a-f]{64}/u.test(JSON.stringify(json.document)), 'default JSON leaves the fingerprint out');
+ const verboseJson = await box.cli('relay', 'devices', '--verbose');
+ assert.match(verboseJson.document.devices[0].fingerprint, /^[0-9a-f]{64}$/u, 'JSON adds the fingerprint only with --verbose');
+ // The joined computer never paired the phone: it lists it by short id from the relay, with its status and board.
+ const there = await joined.cli('relay', 'devices');
+ assert.equal(there.code, 0, 'relay devices succeeds on the joined computer');
+ assert.equal(there.document.devices.length, 1, "the joined computer lists the linked computer's phone");
+ const [phoneThere] = there.document.devices;
+ assert.deepEqual([phoneThere.deviceId, phoneThere.pairedHere, phoneThere.label, phoneThere.revoked, phoneThere.boards],
+ [phone.deviceId, false, null, false, [joined.joined.name]], 'the joined computer knows the phone by id, paired on another computer');
+ assert.ok(Number.isSafeInteger(phoneThere.seen) && !('fingerprint' in phoneThere), 'it carries last seen and no fingerprint');
+ const plain = plainCommand(joined.root, joined.env, ['relay', 'devices']);
+ const shown = await plain.done;
+ assert.equal(shown.code, 0, shown.stderr);
+ const otherLine = shown.stdout.split('\n').find(line => line.includes('(phone): '));
+ assert.match(otherLine ?? '', new RegExp(`^Phone ${phone.deviceId.slice(-8)} \\(phone\\): paired on another computer, last seen (?!unknown)[^;]+; reads ${joined.joined.name}$`, 'u'),
+ 'the joined computer says the phone was paired on another computer, with its short id, last seen and board');
+
+ // Revoke through a separate authenticated person request, leaving this computer's local
+ // pairing record intact. A stale local roster must not claim the phone still reads this board.
+ const person = await box.phoneSession();
+ const headers = { authorization: 'Bearer ' + person.token };
+ const revoked = await fetch(box.origin + '/api/v1/devices/' + phone.deviceId, { method: 'DELETE', headers });
+ assert.equal(revoked.status, 200, 'an authenticated external revoke removes the remote device grant');
+ const phoneGrant = await fetch(box.origin + '/api/v1/devices/' + phone.deviceId + '/boards', { headers });
+ assert.equal(phoneGrant.status, 403, 'the revoked phone cannot read its board grants');
+ assert.equal((await phoneGrant.json()).error.code, 'DEVICE_REVOKED', 'the relay fails closed for the revoked phone');
+ const afterRevoke = await box.cli('relay', 'devices');
+ assert.equal(afterRevoke.code, 0, 'the local roster remains available after the remote revoke');
+ assert.equal(afterRevoke.document.devices.length, 1, 'the paired phone remains in local pairing history');
+ const [stillPaired] = afterRevoke.document.devices;
+ assert.deepEqual([stillPaired.deviceId, stillPaired.pairedHere, stillPaired.label, stillPaired.revoked],
+ [phone.deviceId, true, 'Kitchen phone', true], 'the local phone entry remains and reflects revocation');
+ assert.deepEqual(stillPaired.boards, [], 'the revoked phone no longer appears to read a board');
+ const afterRevokeThere = await joined.cli('relay', 'devices');
+ assert.equal(afterRevokeThere.code, 0, 'the other computer can still read its device roster');
+ assert.deepEqual(afterRevokeThere.document.devices, [], 'the other computer does not restore the revoked phone from local history');
+});
+
+test('relay off names joined computers by host name [H17]', async (t) => {
+ const { box, joined } = await phoneAndJoinedComputer(t);
+ const off = await box.cli('relay', 'off');
+ assert.equal(off.code, 0, 'relay off unlinks this computer');
+ assert.deepEqual(off.document.joined, [hostname()], 'the joined computer is named by its host name');
+ assert.deepEqual(off.document.affectedMachines, [joined.machine], 'the stable machine id stays beside the name');
+ assert.ok(off.document.notice.includes('If you approve deletion, joined computers ' + hostname() + ' lose the shared copy'),
+ 'the warning names the joined computer by host before the phone approves the delete');
+});
+
+test('relay join names the board it joined [H17]', async (t) => {
+ const { joined } = await phoneAndJoinedComputer(t);
+ const { name, board, notice } = joined.joined;
+ assert.equal(typeof name, 'string');
+ assert.equal(notice, 'Joined ' + name + '. This brought one board; for another, run pullboard relay pair in that board on the linked computer. Run pullboard status to read it.',
+ 'join names the board and says it brought one board');
+ assert.ok(!notice.includes(board), 'the board id stays out of the join message');
+});
+
test('relay help lists every relay command, with a whole example [H17]', () => {
const printed = spawnSync(process.execPath, [CLI, 'relay', '--help'], { cwd: tmpdir(), encoding: 'utf8' });
assert.equal(printed.status, 0, printed.stderr);