Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
test(relay): a redeploy keeps every pairing and board [H5,H7,H15]
Corey Olson31e2197055cb
diff --git a/test/relay-deploy.test.js b/test/relay-deploy.test.jsindex 5179d324..39cd8655 100644--- a/test/relay-deploy.test.js+++ b/test/relay-deploy.test.js@@ -13,7 +13,11 @@ import { ENGINE_VERSION } from '../src/machine.js';import { relayClientFixture } from './relay-client-fixture.js';import { githubFixture } from './relay-fixture.js';import { createRelayBrowserHandler } from '../relay/browser-page.js';-import { encodeBoardKey, generateBoardKey, seal } from '../src/seal.js';+import { encodeBoardKey, generateBoardKey, seal, unseal } from '../src/seal.js';+import { createHash, randomBytes } from 'node:crypto';+import { createDeviceKeys, signDeviceEnrollment, unwrapDeviceBoardKey, wrapDeviceBoardKey } from '../src/relay-device-keys.js';+import { approvalContext, openApproval, sealApproval, signApprovalIntent, verifyApprovalIntent } from '../src/relay-approval.js';+import { RELAY_REQUEST_BOUND_MS } from './relay-budget.js';const SMOKE = resolve(import.meta.dirname, '../relay/smoke.mjs');const SERVER = resolve(import.meta.dirname, '../relay/server.mjs');@@ -380,6 +384,246 @@ test('[H5,H18] the container entry point serves readiness and stays available',assert.equal(child.exitCode, null, 'the long-running relay remains available after its health probe');});+const REDEPLOY_GITHUB_HOSTS = ['https://github.com', 'https://api.github.com'];++/**+ * Write a preload that sends the production entry point's GitHub calls to the loopback provider.+ * The relay keeps its real GitHub client; this only swaps the network target, and refuses any+ * request that would leave the machine, so a drill can never reach a real deployment.+ */+function loopbackGitHubPreload(folder) {+ const file = join(folder, 'loopback-github.mjs');+ writeFileSync(file, [+ '/** Route the relay\'s GitHub requests to the private loopback provider and refuse every other host. */',+ 'const target = new URL(process.env.PULLBOARD_DRILL_GITHUB_ORIGIN);',+ 'const real = globalThis.fetch;',+ `const hosts = new Set(${JSON.stringify(REDEPLOY_GITHUB_HOSTS)});`,+ 'globalThis.fetch = (input, init) => {',+ ' let url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);',+ ' if (hosts.has(url.origin)) url = new URL(url.pathname + url.search, target);',+ ' if (!["127.0.0.1", "[::1]", "localhost"].includes(url.hostname)) return Promise.reject(new Error("the redeploy drill stays on loopback"));',+ ' return real(url, init);',+ '};',+ ].join('\n'), { mode: 0o600 });+ return file;+}++/**+ * Start the production relay entry point as its own process on one data directory and port.+ * A redeploy is exactly this: a new process, the same volume, the same public address.+ */+async function startRelayProcess(t, { data, port, provider, preload, home }) {+ const origin = `http://127.0.0.1:${port}`;+ const env = {+ PATH: process.env.PATH ?? '/usr/bin:/bin', NODE_ENV: 'production', HOME: home,+ PULLBOARD_HOME: join(home, 'pullboard-home'), PULLBOARD_MACHINE_HOME: join(home, 'machine-home'),+ PULLBOARD_RELAY_DATA: data, PULLBOARD_PUBLIC_ORIGIN: origin, PORT: String(port),+ PULLBOARD_DRILL_GITHUB_ORIGIN: provider.origin,+ GITHUB_APP_CLIENT_ID: provider.config.clientId,+ GITHUB_APP_CLIENT_SECRET: provider.config.clientSecret,+ GITHUB_APP_PRIVATE_KEY: provider.config.privateKey,+ };+ const child = spawn(process.execPath, ['--import', pathToFileURL(preload).href, SERVER], { cwd: ROOT, env, stdio: ['ignore', 'ignore', 'pipe'] });+ t.after(async () => {+ if (child.exitCode !== null || child.signalCode !== null) return;+ child.kill('SIGKILL');+ await childClosesWithin(child, 5000); // budget: cleanup ceiling for a relay a failed drill left running.+ });+ await waitHealthy(child, origin);+ return { child, origin };+}++/** Stop a relay the way a platform redeploy does: SIGTERM, then wait for its own clean shutdown. */+async function stopRelayProcess(relay) {+ relay.child.kill('SIGTERM');+ const closed = await childClosesWithin(relay.child, 10_000); // budget: graceful SIGTERM shutdown closes SQLite and the listener.+ if (!closed) relay.child.kill('SIGKILL');+ return { closed, code: relay.child.exitCode, signal: relay.child.signalCode };+}++/** Send one JSON request to a drill relay with a bearer credential; the credential never enters a message. */+async function relayCall(origin, path, { method = 'GET', token, body, engine = true } = {}) {+ const headers = { accept: 'application/json' };+ if (token) headers.authorization = 'Bearer ' + token;+ if (engine) headers['x-pullboard-engine'] = String(ENGINE_VERSION);+ if (body !== undefined) headers['content-type'] = 'application/json';+ const response = await fetch(origin + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body),+ signal: AbortSignal.timeout(RELAY_REQUEST_BOUND_MS) }); // budget: one relay request bound, shared with the other relay fixtures.+ const text = await response.text();+ return { status: response.status, body: text ? JSON.parse(text) : null };+}++/** Read one cookie value from a response's Set-Cookie headers. */+function setCookie(response, name) {+ for (const line of response.headers.getSetCookie()) {+ const match = new RegExp(`^${name}=([^;]*)`, 'u').exec(line);+ if (match) return match[1];+ }+ return null;+}++/** Sign a person in through the relay's real GitHub web flow, answered by the loopback provider. */+async function signInPerson(origin, provider) {+ const start = await fetch(origin + '/auth/github/start', { redirect: 'manual' });+ assert.equal(start.status, 302, 'the relay starts a GitHub web sign-in');+ const binding = setCookie(start, 'pb_oauth_binding');+ const authorize = new URL(start.headers.get('location'));+ const granted = await fetch(provider.origin + authorize.pathname + authorize.search, { redirect: 'manual' });+ assert.equal(granted.status, 303, 'the loopback provider grants the sign-in');+ const callback = await fetch(granted.headers.get('location'), { redirect: 'manual', headers: { cookie: 'pb_oauth_binding=' + binding } });+ assert.equal(callback.status, 303, 'the relay finishes the sign-in');+ const token = setCookie(callback, 'pb_session');+ assert.match(token ?? '', /^ps_[A-Za-z0-9_-]{43}$/u, 'the relay sets a person session');+ const session = await relayCall(origin, '/auth/session', { token, engine: false });+ assert.equal(session.status, 200);+ return { token, id: session.body.session.id };+}++/** Encode a JSON value as the canonical base64url transport the relay stores without parsing. */+function opaque(value) {+ return Buffer.from(JSON.stringify(value)).toString('base64url');+}++/** Decode a relay-stored base64url JSON transport back into its value. */+function unopaque(value) {+ return JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));+}++/** Seal a board record with the board key, bound to its board, kind and sequence. */+async function sealRecord(key, board, kind, sequence, value) {+ return Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(value)), { boardId: board, kind, sequence })).toString('base64url');+}++/** Unseal a relay-held board record and parse its JSON contents. */+async function unsealRecord(key, board, kind, sequence, sealed) {+ return JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(sealed, 'base64url'), { boardId: board, kind, sequence })));+}++/**+ * Link a board, sign a person in, enroll a phone and publish one sealed approval on a fresh relay.+ * Every step uses the relay's public HTTP routes, the way the Mac and the phone use them.+ */+async function pairEverything(origin, provider) {+ const board = createHash('sha256').update('redeploy-drill-board').digest('hex').slice(0, 32);+ const machine = 'redeploy-drill-mac';+ const person = await signInPerson(origin, provider);+ const linked = await relayCall(origin, '/auth/boards/link', { method: 'POST', token: person.token, engine: false, body: { board, repository: 'fixture/repository' } });+ assert.equal(linked.status, 200, 'the person links the board');+ const issued = await relayCall(origin, '/auth/machines', { method: 'POST', token: person.token, engine: false, body: { board, machine } });+ assert.equal(issued.status, 201, 'the person issues the Mac its board machine credential');+ const mac = issued.body.token;++ const key = await generateBoardKey();+ const snapshotValue = { version: 1, drill: 'snapshot before the redeploy' };+ const snapshot = await sealRecord(key, board, 'snapshot', 0, snapshotValue);+ assert.equal((await relayCall(origin, `/api/v1/boards/${board}/state`, { method: 'PUT', token: mac, body: { sequence: 0, sealed: snapshot } })).status, 200, 'the Mac uploads the sealed snapshot');+ const firstMove = await sealRecord(key, board, 'move', 1, { drill: 'move one' });+ const moved = await relayCall(origin, `/api/v1/boards/${board}/moves`, { method: 'POST', token: mac, body: { sequence: 1, sealed: firstMove } });+ assert.equal(moved.status, 200, 'the Mac publishes its first sealed move');++ const account = (await relayCall(origin, '/api/v1/devices/session', { token: person.token, engine: false })).body.account;+ const phone = await createDeviceKeys();+ const locator = randomBytes(16).toString('base64url');+ const secret = randomBytes(32);+ assert.equal((await relayCall(origin, `/api/v1/devices/enrollments/${locator}`, { method: 'POST', token: person.token, engine: false, body: {} })).status, 200, 'the Mac opens a one-use phone pairing');+ const enrollment = await signDeviceEnrollment(secret, { v: 1, account, locator, deviceId: phone.deviceId, publicKey: phone.publicKey, label: 'Drill phone', createdAt: new Date().toISOString() });+ assert.equal((await relayCall(origin, `/api/v1/devices/enrollments/${locator}`, { method: 'PUT', token: person.token, engine: false, body: enrollment })).status, 200, 'the phone posts its signed enrollment');+ assert.equal((await relayCall(origin, `/api/v1/devices/${phone.deviceId}`, { method: 'POST', token: person.token, engine: false, body: {} })).status, 200, 'the Mac registers the authenticated phone');+ const wrap = await wrapDeviceBoardKey(key, phone.publicKey, { board, device: phone.deviceId, engine: ENGINE_VERSION });+ assert.equal((await relayCall(origin, `/api/v1/devices/${phone.deviceId}/boards/${board}`, { method: 'PUT', token: mac, body: { engine: ENGINE_VERSION, wrapped: opaque(wrap) } })).status, 200, 'the Mac wraps the board key to the phone');+ assert.equal((await relayCall(origin, `/api/v1/devices/enrollments/${locator}`, { method: 'DELETE', token: person.token, engine: false })).status, 200, 'the one-use pairing is consumed');++ const context = approvalContext({ id: 'redeploy-drill-approval', account, publisher: board, board, device: phone.deviceId,+ action: 'revoke-token', target: 'redeploy-drill-token', machine, command: 'pullboard relay revoke redeploy-drill-token', expires: Date.now() + 600_000 });+ const envelope = await sealApproval({ context, drill: 'approval before the redeploy' }, phone.publicKey, context, 'intent');+ const sealedApproval = opaque({ envelope, mac: await signApprovalIntent(key, envelope) });+ const published = await relayCall(origin, '/api/v1/devices/approvals', { method: 'POST', token: mac, body: { context, sealed: sealedApproval } });+ assert.equal(published.status, 200, 'the Mac publishes a sealed approval for the phone');+ return { board, machine, person, mac, key, account, phone, snapshot, snapshotValue, firstMove, context, sealedApproval };+}++/** Read what the phone sees: its waiting approvals and its board key, opened with its own private key. */+async function phoneReads(origin, paired) {+ const inbox = await relayCall(origin, `/api/v1/devices/${paired.phone.deviceId}/approvals`, { token: paired.person.token, engine: false });+ const wraps = await relayCall(origin, `/api/v1/devices/${paired.phone.deviceId}/boards`, { token: paired.person.token, engine: false });+ return { inbox, wraps };+}++test('a relay redeploy keeps every pairing, session and board [H5,H7,H15]', { timeout: 120_000 }, async (t) => { // budget: three relay boots, two shutdowns and about forty loopback requests.+ const provider = await githubFixture(t);+ const scratch = mkdtempSync(join(tmpdir(), 'pullboard-relay-redeploy-'));+ t.after(() => rmSync(scratch, { recursive: true, force: true }));+ const volume = join(scratch, 'volume');+ const freshVolume = join(scratch, 'fresh-volume');+ const home = join(scratch, 'home');+ mkdirSync(home, { mode: 0o700 });+ const preload = loopbackGitHubPreload(scratch);+ const port = await unusedPort();++ const first = await startRelayProcess(t, { data: volume, port, provider, preload, home });+ const paired = await pairEverything(first.origin, provider);+ const before = await phoneReads(first.origin, paired);+ assert.deepEqual(before.inbox.body.approvals.map(row => row.context.id), [paired.context.id], 'the phone sees the approval before the redeploy');+ const stopped = await stopRelayProcess(first);+ assert.deepEqual(stopped, { closed: true, code: 0, signal: null }, 'the old relay shuts down cleanly on SIGTERM, as a redeploy stops it'); // budget: graceful SIGTERM shutdown closes SQLite and the listener.++ const second = await startRelayProcess(t, { data: volume, port, provider, preload, home });+ const callsBefore = provider.calls.length;+ const origin = second.origin;++ const session = await relayCall(origin, '/auth/session', { token: paired.person.token, engine: false });+ assert.equal(session.status, 200, 'REDEPLOY_SESSION: the person session still authenticates after the redeploy');+ assert.equal(session.body.session.id, paired.person.id, 'the redeploy keeps the same session, not a new sign-in');+ assert.equal(session.body.session.user.id, paired.account);+ const machine = await relayCall(origin, `/auth/session?board=${paired.board}`, { token: paired.mac, engine: false });+ assert.equal(machine.status, 200, 'REDEPLOY_MACHINE: the Mac machine credential still authenticates for its board, with no re-link');+ assert.equal(machine.body.session.machine, paired.machine);+ const listed = await relayCall(origin, '/auth/boards', { token: paired.person.token, engine: false });+ assert.deepEqual(listed.body.boards.map(row => row.id), [paired.board], 'the board is still linked');++ const after = await phoneReads(origin, paired);+ assert.equal(after.inbox.status, 200, 'REDEPLOY_DEVICE: the paired phone still reads its approvals after the redeploy');+ assert.deepEqual(after.inbox.body.approvals.map(row => row.context.id), [paired.context.id], 'the waiting approval survives the redeploy');+ assert.equal(after.inbox.body.approvals[0].sealed, paired.sealedApproval, 'the sealed approval bytes are unchanged');+ const packet = unopaque(after.inbox.body.approvals[0].sealed);+ assert.equal(after.wraps.status, 200, 'the phone still reads its wrapped board key');+ const wrap = after.wraps.body.wraps.find(row => row.board === paired.board);+ const phoneKey = await unwrapDeviceBoardKey(paired.phone.privateKey, unopaque(wrap.wrapped), { board: paired.board, device: paired.phone.deviceId, engine: ENGINE_VERSION });+ assert.deepEqual(phoneKey, paired.key, 'the phone opens the same board key with its own private key, with no re-pair');+ assert.deepEqual(await verifyApprovalIntent(phoneKey, packet), packet.envelope, 'the approval still authenticates with the phone board key');+ const opened = await openApproval(paired.phone.privateKey, packet.envelope, paired.context, 'intent');+ assert.equal(opened.drill, 'approval before the redeploy', 'the phone opens the sealed approval it was sent before the redeploy');++ const state = await relayCall(origin, `/api/v1/boards/${paired.board}/state`, { token: paired.person.token });+ assert.equal(state.status, 200, 'REDEPLOY_BOARD: the board snapshot is still served after the redeploy');+ assert.equal(state.body.state.sequence, 0);+ assert.equal(state.body.state.sealed, paired.snapshot, 'the sealed snapshot bytes are intact');+ assert.deepEqual(await unsealRecord(phoneKey, paired.board, 'snapshot', 0, state.body.state.sealed), paired.snapshotValue);+ const events = await relayCall(origin, `/api/v1/boards/${paired.board}/events?after=0`, { token: paired.mac });+ assert.deepEqual(events.body.events.map(row => [row.event_id, row.sealed]), [[1, paired.firstMove]], 'the board sequence is intact at one sealed move');++ const nextMove = await sealRecord(paired.key, paired.board, 'move', 2, { drill: 'move after the redeploy' });+ const moved = await relayCall(origin, `/api/v1/boards/${paired.board}/moves`, { method: 'POST', token: paired.mac, body: { sequence: 2, sealed: nextMove } });+ assert.equal(moved.status, 200, 'REDEPLOY_MOVE: a new move is accepted after the redeploy');+ assert.equal(moved.body.result.sequence, 2, 'the new move continues the sequence instead of restarting it');+ const read = await relayCall(origin, `/api/v1/boards/${paired.board}/events?after=1`, { token: paired.person.token });+ assert.deepEqual(read.body.events.map(row => row.event_id), [2]);+ assert.deepEqual(await unsealRecord(phoneKey, paired.board, 'move', 2, read.body.events[0].sealed), { drill: 'move after the redeploy' }, 'the new move round-trips');+ assert.equal(provider.calls.slice(callsBefore).some(call => call.path.startsWith('/login/')), false, 'nobody signed in again after the redeploy');+ await stopRelayProcess(second);++ const control = await startRelayProcess(t, { data: freshVolume, port, provider, preload, home });+ const lost = await relayCall(control.origin, '/auth/session', { token: paired.person.token, engine: false });+ assert.equal(lost.status, 401, 'CONTROL: a relay without the old volume refuses the old session');+ assert.equal(lost.body.error.code, 'AUTH_REQUIRED');+ assert.equal((await relayCall(control.origin, `/auth/session?board=${paired.board}`, { token: paired.mac, engine: false })).status, 401, 'CONTROL: the Mac would have to link again');+ const again = await signInPerson(control.origin, provider);+ const unpaired = await phoneReads(control.origin, { ...paired, person: again });+ assert.equal(unpaired.inbox.body.error?.code, 'DEVICE_NOT_ENROLLED', 'CONTROL: the phone would have to pair again');+ assert.deepEqual((await relayCall(control.origin, '/auth/boards', { token: again.token, engine: false })).body.boards, [], 'CONTROL: no board is linked on a fresh volume');+ await stopRelayProcess(control);+});+test('[H5,H18] Docker COPY sources boot the relay and serve its browser page, while omitted runtime files refuse startup', async (t) => {const provider = await githubFixture(t);const image = copiedImage(t);