Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(relay): add Railway deployment readiness [H5,H18]
Corey Olsonf6cb95f7a1e6
diff --git a/relay/Dockerfile b/relay/Dockerfilenew file mode 100644index 00000000..f4aec861--- /dev/null+++ b/relay/Dockerfile@@ -0,0 +1,15 @@+FROM node:22.13.1-slim++ENV NODE_ENV=production \+ PULLBOARD_RELAY_DATA=/data++WORKDIR /app+COPY --chown=node:node package.json ./package.json+COPY --chown=node:node src/api-http.js src/json.js src/refused.js ./src/+COPY --chown=node:node relay/auth-http.js relay/auth.js relay/github.js relay/journal.js relay/retention.js relay/server.mjs relay/service.js ./relay/+RUN mkdir -p /data && chown node:node /data && chmod 700 /data++USER node+EXPOSE 3000+HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]+CMD ["node", "relay/server.mjs"]diff --git a/relay/README.md b/relay/README.mdindex 336e6598..fde19000 100644--- a/relay/README.md+++ b/relay/README.md@@ -1,7 +1,54 @@# Relay authentication-This module implements the GitHub App sign-in and authorization boundary for the-opt-in relay. It does not start a public server or change any repository.+## Deploy the service++The container definition is `relay/Dockerfile`; its build context must be the+repository root because the service imports `src/` modules. The service listens on+Railway's `PORT` at `0.0.0.0`, and `GET /health` returns `200` after startup.+It stores the auth database at `/data/auth.sqlite`, board journals under+`/data/boards/`, and private backups under `/data/backups/`. Attach one Railway+volume at `/data`; do not scale this SQLite service to multiple replicas.+The entry point prepares that root-mounted directory, then runs the server as+the image's unprivileged `node` user. For Railway volumes, configure+`RAILWAY_RUN_UID=0` so startup can set the directory ownership before dropping+privileges.++For #113, the person completes these account steps:++1. Create the Pullboard GitHub App. Set its callback to+ `https://app.pullboard.dev/auth/github/callback`, grant repository Metadata+ read-only permission, and enable device flow. Create its client id, client+ secret and RSA private key.+2. Create the Railway project and service for this repository. In service+ settings, keep the root directory `/` so the Docker build can copy `src/`,+ choose `relay/Dockerfile`, set the start command to+ `node relay/server.mjs`, and set the health check path to `/health`. Attach+ one persistent volume at `/data`; the auth database, board journals and+ backups live at `/data/auth.sqlite`, `/data/boards/` and `/data/backups/`.+ Set `RAILWAY_RUN_UID=0` so startup can prepare the root-mounted volume before+ dropping to the image's `node` user. Set+ `PULLBOARD_PUBLIC_ORIGIN=https://app.pullboard.dev`,+ `GITHUB_APP_CLIENT_ID`, `GITHUB_APP_CLIENT_SECRET`, and+ `GITHUB_APP_PRIVATE_KEY` in Railway's service variables. Keep the secret+ values in Railway, never in git.+3. Give the service the `app.pullboard.dev` domain and point DNS at the target+ Railway provides. Wait for the `/health` check to pass before directing+ clients to it.++The smoke command is `node relay/smoke.mjs <address>`. It uses the current+repository as a disposable smoke board: it links, creates one uniquely named+item, reads and unseals its mirrored move, then unlinks. Use a throwaway+repository and relay when running it against a live deployment; unlink deletes+the remote board. Tests run the same script against a private loopback relay.++Railway's current Infrastructure as Code uses the `railway/iac` package. This+dependency-free project keeps the deployment settings in the service checklist+above instead of adding a Railway SDK dependency. Recheck Railway's current+configuration format before creating a new service.++The auth and API modules implement the GitHub App sign-in and authorization+boundary for the opt-in relay. `server.mjs` is the public container entry point;+the library handlers remain embeddable for tests and other local transports.Create the GitHub provider with `createGitHubClient` from `github.js`. Configurationnames are `clientId`, `clientSecret`, `privateKey` (RSA PEM), and `callbackURL`.diff --git a/relay/server.mjs b/relay/server.mjsnew file mode 100644index 00000000..f5d0a147--- /dev/null+++ b/relay/server.mjs@@ -0,0 +1,138 @@+/** Production relay entry point for the Railway container [H5,H18]. */+import { createServer } from 'node:http';+import { chmodSync, chownSync, lstatSync, mkdirSync, readdirSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { createAuthHandler } from './auth-http.js';+import { createRelayAuth } from './auth.js';+import { createGitHubClient } from './github.js';+import { createRelayHandler } from './service.js';+import { Refused } from '../src/refused.js';++const NODE_UID = 1000;+const NODE_GID = 1000;++/** Create private relay directories and hand their contents to the unprivileged service user. */+function prepareStorage(directory) {+ mkdirSync(directory, { recursive: true, mode: 0o700 });+ const root = lstatSync(directory);+ if (!root.isDirectory() || root.isSymbolicLink()) {+ throw new Refused('RELAY_STORAGE', 'mount a private regular volume directory at PULLBOARD_RELAY_DATA and restart the service');+ }+ chmodSync(directory, 0o700);+ for (const name of readdirSync(directory)) {+ const path = join(directory, name);+ const entry = lstatSync(path);+ if (entry.isSymbolicLink()) {+ throw new Refused('RELAY_STORAGE', 'remove symlinks from the private relay volume and restart the service');+ }+ if (entry.isDirectory()) prepareStorage(path);+ else if (entry.isFile()) {+ chmodSync(path, 0o600);+ if (process.getuid?.() === 0) chownSync(path, NODE_UID, NODE_GID);+ } else throw new Refused('RELAY_STORAGE', 'keep only regular files and directories in the private relay volume');+ }+ if (process.getuid?.() === 0) chownSync(directory, NODE_UID, NODE_GID);+}++/** Drop the startup privilege after preparing Railway's root-mounted volume. */+function dropPrivileges() {+ if (process.getuid?.() !== 0) return;+ try {+ process.setgroups([]);+ process.setgid(NODE_GID);+ process.setuid(NODE_UID);+ } catch {+ throw new Refused('RELAY_USER', 'start as the image node user, or set RAILWAY_RUN_UID=0 with permission to drop startup privileges');+ }+}++/** Handle the Railway readiness probe without exposing storage or configuration. */+function health(req, res) {+ if (req.method !== 'GET' || new URL(req.url, 'http://localhost').pathname !== '/health') return false;+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });+ res.end('ok\n');+ return true;+}++/** Start the authenticated opaque relay on Railway's assigned port and public origin. */+async function startRelay() {+ const publicOrigin = process.env.PULLBOARD_PUBLIC_ORIGIN || '';+ const data = resolve(process.env.PULLBOARD_RELAY_DATA || '/data');+ const port = Number(process.env.PORT || 3000);+ if (!Number.isInteger(port) || port < 1 || port > 65535) {+ throw new Refused('RELAY_PORT', 'set PORT to an available TCP port from 1 to 65535 and restart the service');+ }+ const privateKey = (process.env.GITHUB_APP_PRIVATE_KEY || '').replaceAll('\\n', '\n');+ try { prepareStorage(data); }+ catch (error) {+ if (error instanceof Refused) throw error;+ throw new Refused('RELAY_STORAGE', 'make PULLBOARD_RELAY_DATA writable by the startup user, then restart the service');+ }+ dropPrivileges();+ if (process.getuid?.() === 0) {+ throw new Refused('RELAY_USER', 'start as the image node user, or set RAILWAY_RUN_UID=0 so startup can prepare the volume and drop privileges');+ }+ const auth = createRelayAuth({+ database: join(data, 'auth.sqlite'),+ github: createGitHubClient({+ clientId: process.env.GITHUB_APP_CLIENT_ID || '',+ clientSecret: process.env.GITHUB_APP_CLIENT_SECRET || '',+ privateKey,+ callbackURL: callbackURL(publicOrigin),+ }),+ });+ const authHandler = createAuthHandler({ auth, publicOrigin });+ const relayHandler = createRelayHandler({+ directory: join(data, 'boards'),+ backupsDirectory: join(data, 'backups'),+ auth,+ publicOrigin,+ });+ /** Route readiness, GitHub authentication and opaque board relay requests. */+ async function handleRequest(req, res) {+ if (health(req, res)) return;+ if (await authHandler(req, res)) return;+ await relayHandler(req, res);+ }+ const server = createServer(handleRequest);+ server.requestTimeout = 15_000;+ try {+ await new Promise((ready, fail) => {+ server.once('error', fail);+ server.listen(port, '0.0.0.0', ready);+ });+ } catch (error) {+ relayHandler.close();+ auth.close();+ throw new Refused(error?.code === 'EADDRINUSE' ? 'PORT_BUSY' : 'RELAY_LISTEN', 'set Railway PORT to a free listener and restart the relay');+ }+ let closing = false;+ /** Close handlers, connections and SQLite before the container exits. */+ async function stop() {+ if (closing) return;+ closing = true;+ relayHandler.close();+ auth.close();+ server.closeAllConnections();+ await new Promise((done) => server.close(done));+ }+ process.once('SIGTERM', () => { void stop(); });+ process.once('SIGINT', () => { void stop(); });+}++/** Build the callback URL only from the operator-configured trusted public origin. */+function callbackURL(publicOrigin) {+ try { return new URL('/auth/github/callback', publicOrigin).href; }+ catch { throw new Refused('RELAY_CONFIG', 'set PULLBOARD_PUBLIC_ORIGIN to the relay HTTPS origin and restart the service'); }+}++try {+ await startRelay();+} catch (error) {+ const refusal = error instanceof Refused+ ? error+ : new Refused('RELAY_STARTUP', 'check the relay service variables and volume permissions, then restart it');+ const message = refusal.message.replace(/^\[[^\]]+\] /, '');+ process.stderr.write(`relay startup failed: [${refusal.code}] ${message}\n`);+ process.exitCode = 1;+}diff --git a/relay/smoke.mjs b/relay/smoke.mjsnew file mode 100644index 00000000..c41dcdd3--- /dev/null+++ b/relay/smoke.mjs@@ -0,0 +1,135 @@+/** Exercise a real CLI-to-relay round trip without printing device or board secrets [H5,H18]. */+import { spawn } from 'node:child_process';+import { existsSync, readFileSync, statSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { readBoardKey } from '../src/relay-key.js';+import { unseal } from '../src/seal.js';++const REPOSITORY = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const CLI = join(REPOSITORY, 'bin', 'pullboard.js');++/** Run one production CLI command in the current repository and parse only its JSON document. */+function cli(root, args) {+ return new Promise((resolveResult, reject) => {+ const child = spawn(process.execPath, [CLI, ...args, '--json'], { cwd: root, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ const timer = setTimeout(() => child.kill('SIGKILL'), 60_000);+ child.stdout.setEncoding('utf8').on('data', (part) => { stdout += part; });+ child.stderr.setEncoding('utf8').on('data', (part) => process.stderr.write(part));+ child.once('error', (error) => { clearTimeout(timer); reject(error); });+ child.once('close', (code, signal) => {+ clearTimeout(timer);+ if (signal) return reject(new Error('the Pullboard command did not finish before its deadline'));+ if (code !== 0) return reject(new Error('the Pullboard command failed; read its message above and repair the repository before retrying'));+ try { resolveResult(JSON.parse(stdout)); }+ catch { reject(new Error('the Pullboard command did not return its JSON result')); }+ });+ });+}++/** Find the actual common Git directory for this repository, including linked worktrees. */+async function commonDirectory(root) {+ const result = await cliGit(root, ['rev-parse', '--git-common-dir']);+ return resolve(root, result.trim());+}++/** Run Git without a shell and return its bounded textual result. */+function cliGit(root, args) {+ return new Promise((resolveResult, reject) => {+ const child = spawn('git', args, { cwd: root, env: process.env, stdio: ['ignore', 'pipe', 'ignore'] });+ let stdout = '';+ child.stdout.setEncoding('utf8').on('data', (part) => { stdout += part; });+ child.once('error', reject);+ child.once('close', (code) => code === 0 ? resolveResult(stdout) : reject(new Error('run the smoke from an initialized Git repository')));+ });+}++/** Read one authenticated event and prove that the smoke-created item reached the relay. */+async function readMirroredMove({ address, board, token, key, after, item, title }) {+ const path = `/api/v1/boards/${board}/events?after=${after}`;+ const response = await fetch(new URL(path, address), { headers: { authorization: `Bearer ${token}` } });+ if (!response.ok) throw new Error('the relay did not return the mirrored move');+ const document = await response.json();+ const event = document.events?.find((row) => row.event_id === after + 1 && row.kind === 'move');+ if (!event) throw new Error('the relay response did not include the next move');+ const bytes = await unseal(key, Buffer.from(event.sealed, 'base64url'), { boardId: board, kind: 'move', sequence: event.event_id });+ const move = JSON.parse(new TextDecoder().decode(bytes));+ if (move.operation === 'addItem') {+ if (move.args?.[0]?.title !== title) throw new Error('the decrypted relay operation is not the smoke item');+ const stateResponse = await fetch(new URL(`/api/v1/boards/${board}/state`, address), { headers: { authorization: `Bearer ${token}` } });+ if (!stateResponse.ok) throw new Error('the relay did not return its native checkpoint');+ const saved = await stateResponse.json();+ const checkpointBytes = await unseal(key, Buffer.from(saved.state.sealed, 'base64url'), {+ boardId: board, kind: 'snapshot', sequence: saved.state.sequence,+ });+ const checkpoint = JSON.parse(new TextDecoder().decode(checkpointBytes));+ const row = checkpoint.tables?.item?.find((candidate) => candidate.item_id === item.item_id && candidate.item_title === title);+ const applied = checkpoint.tables?.board_meta?.find((candidate) => candidate.meta_key === 'relay_applied_sequence')?.meta_value;+ if (saved.state.sequence !== event.event_id || Number(applied) !== event.event_id || !row) {+ throw new Error('the native checkpoint does not cover the mirrored smoke item');+ }+ } else if (move.version === 1 && move.engine === 1 && move.event?.event_kind === 'add') {+ if (move.event.item_id !== item.item_id || item.item_title !== title) throw new Error('the decrypted relay add does not match the smoke item');+ } else throw new Error('the relay move format is unsupported');+ return event.event_id;+}++/** Run relay on, add and unseal one move, then always issue relay off against the supplied origin. */+async function smoke(address) {+ const root = process.cwd();+ const config = JSON.parse(readFileSync(join(root, 'pullboard.json'), 'utf8'));+ const lane = Object.keys(config.lanes || {})[0];+ if (!lane) throw new Error('the smoke repository must have at least one configured lane');+ const common = await commonDirectory(root);+ const metadata = join(common, 'pullboard', 'relay.json');+ if (existsSync(metadata)) throw new Error('this repository already has a relay link; use an unlinked throwaway repository');+ let on;+ let linked = false;+ let failure;+ let result;+ try {+ on = await cli(root, ['relay', 'on', '--url', address]);+ linked = existsSync(metadata);+ if (!on.linked || on.url !== new URL(address).origin) throw new Error('relay on did not link to the supplied address');+ const title = `Pullboard relay smoke ${Date.now()}`;+ const added = await cli(root, ['add', lane, title]);+ const item = added.item;+ if (!item || typeof item.item_id !== 'number') throw new Error('the local add did not return its item');+ const link = JSON.parse(readFileSync(metadata, 'utf8'));+ if (link.board !== on.board || link.url !== on.url) throw new Error('the saved relay link changed during the smoke');+ const mode = statSync(metadata).mode & 0o777;+ if (mode !== 0o600) throw new Error('the saved relay link is not private');+ const eventId = await readMirroredMove({+ address: on.url,+ board: on.board,+ token: link.token,+ key: readBoardKey(on.board),+ after: on.sequence,+ item,+ title,+ });+ result = { ok: true, board: on.board, item: item.item_id, sequence: eventId };+ } catch (error) {+ linked ||= existsSync(metadata);+ failure = error;+ }+ if (linked) {+ try { await cli(root, ['relay', 'off']); }+ catch (error) { failure ??= error; }+ }+ if (failure) throw failure;+ process.stdout.write(JSON.stringify(result) + '\n');+}++const address = process.argv[2];+if (!address) {+ process.stderr.write('usage: node relay/smoke.mjs <address>\n');+ process.exitCode = 2;+} else {+ try { await smoke(address); }+ catch (error) {+ process.stderr.write(`relay smoke failed: ${error?.message || 'unknown error'}\n`);+ process.exitCode = 1;+ }+}diff --git a/test/relay-deploy.test.js b/test/relay-deploy.test.jsnew file mode 100644index 00000000..c0016045--- /dev/null+++ b/test/relay-deploy.test.js@@ -0,0 +1,126 @@+/** Exercise the deploy smoke script against a private loopback relay [H5,H18]. */+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { createServer } from 'node:http';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { tmpdir } from 'node:os';+import { test } from 'node:test';+import { relayClientFixture } from './relay-client-fixture.js';+import { githubFixture } from './relay-fixture.js';++const SMOKE = resolve(import.meta.dirname, '../relay/smoke.mjs');+const SERVER = resolve(import.meta.dirname, '../relay/server.mjs');++/** Run the checked-in smoke script in a private real repository without retaining its output. */+function runSmoke(box, address) {+ return new Promise((resolveResult, reject) => {+ const child = spawn(process.execPath, [SMOKE, address], { cwd: box.root, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ let safeFailure = '';+ const timer = setTimeout(() => child.kill('SIGKILL'), 90_000);+ child.stdout.setEncoding('utf8').on('data', (part) => { stdout += part; });+ child.stderr.setEncoding('utf8').on('data', (part) => {+ const line = part.split('\n').find((entry) => entry.startsWith('relay smoke failed:'));+ if (line) safeFailure = line;+ });+ child.once('error', (error) => { clearTimeout(timer); reject(error); });+ child.once('close', (code, signal) => {+ clearTimeout(timer);+ if (signal) return reject(new Error('private relay deployment smoke did not complete'));+ if (code !== 0) return resolveResult({ code, failure: safeFailure });+ try { resolveResult({ code, result: JSON.parse(stdout) }); }+ catch { reject(new Error('private relay deployment smoke did not return its safe summary')); }+ });+ });+}++/** Reserve and release an ephemeral loopback port for the real deployment entry point. */+async function unusedPort() {+ const server = createServer();+ await new Promise((ready, fail) => { server.once('error', fail); server.listen(0, '127.0.0.1', ready); });+ const port = server.address().port;+ await new Promise((ready) => server.close(ready));+ return port;+}++/** Wait for the child's private health route while failing promptly if startup exits. */+async function waitHealthy(child, origin) {+ const deadline = Date.now() + 5000;+ while (Date.now() < deadline) {+ if (child.exitCode !== null) throw new Error('the relay container entry point exited before health became ready');+ try {+ const response = await fetch(new URL('/health', origin));+ if (response.status === 200 && (await response.text()) === 'ok\n') return;+ } catch { /* The local listener is not ready yet. */ }+ await new Promise((ready) => setTimeout(ready, 25));+ }+ throw new Error('the relay container entry point did not become healthy');+}++test('[H5,H18] the Railway smoke links, reads one unsealed move and unlinks locally', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ const previous = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ assert.equal((await box.cli('relay', 'off')).code, 0);+ const beforeSmoke = box.calls.length;++ const smoke = await runSmoke(box, previous.url);+ assert.equal(smoke.code, 0, smoke.failure);+ const result = smoke.result;+ assert.equal(result.ok, true);+ assert.equal(typeof result.item, 'number');+ assert.equal(result.sequence, 1);+ assert.equal(existsSync(box.linkFile), false, 'relay off forgets the private link metadata');+ assert.equal(existsSync(box.keyFile), false, 'relay off forgets the device-only board key');+ assert.ok(box.calls.slice(beforeSmoke).some((call) => call.method === 'DELETE' && call.path === `/api/v1/boards/${previous.board}`),+ 'the smoke sends relay off to the supplied local relay');+ const local = (await box.cli('export')).document;+ assert.ok(local.tables.item.some((item) => item.item_id === result.item && item.item_title.startsWith('Pullboard relay smoke ')),+ 'the real CLI move remains in the local board after relay off');+});++test('[H5,H18] a linked repository is refused before the smoke can unlink its board', async (t) => {+ const box = await relayClientFixture(t);+ await box.link();+ const previous = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const before = box.calls.length;+ const smoke = await runSmoke(box, previous.url);+ assert.notEqual(smoke.code, 0);+ assert.match(smoke.failure, /already has a relay link/);+ assert.equal(box.calls.length, before, 'the guard runs before relay on or off can make a network request');+ assert.equal(existsSync(box.linkFile), true, 'the existing private link remains intact');+ assert.equal(existsSync(box.keyFile), true, 'the existing device key remains intact');+ const state = await fetch(`${previous.url}/api/v1/boards/${previous.board}/state`, {+ headers: { authorization: `Bearer ${previous.token}` },+ });+ assert.equal(state.status, 200, 'the linked remote board was not deleted');+});++test('[H5,H18] the container entry point serves readiness and stays available', async (t) => {+ const provider = await githubFixture(t);+ const data = mkdtempSync(join(tmpdir(), 'pullboard-relay-deploy-'));+ t.after(() => rmSync(data, { recursive: true, force: true }));+ const port = await unusedPort();+ const origin = `http://127.0.0.1:${port}`;+ const env = {+ ...process.env,+ PORT: String(port),+ PULLBOARD_RELAY_DATA: data,+ PULLBOARD_PUBLIC_ORIGIN: 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, [SERVER], { cwd: resolve(import.meta.dirname, '..'), env, stdio: ['ignore', 'ignore', 'pipe'] });+ child.stderr.resume();+ t.after(async () => {+ if (child.exitCode === null) child.kill('SIGTERM');+ if (child.exitCode === null) await new Promise((ready) => {+ const timer = setTimeout(() => { child.kill('SIGKILL'); ready(); }, 5000);+ child.once('close', () => { clearTimeout(timer); ready(); });+ });+ });+ await waitHealthy(child, origin);+ assert.equal(child.exitCode, null, 'the long-running relay remains available after its health probe');+});