diff --git a/packages/webui/src/cli.mjs b/packages/webui/src/cli.mjs index 5a18b98e8..2c59adf98 100644 --- a/packages/webui/src/cli.mjs +++ b/packages/webui/src/cli.mjs @@ -34,6 +34,8 @@ import { isAbsolute, join } from 'node:path'; import { actionTrail } from './action-trail.mjs'; import { reviveBuses } from './bus-revive.mjs'; import { createProxyAdmin, orgCatalogue } from './proxy-admin.mjs'; +import { createTriageHost } from './triage-host.mjs'; +import { composeSnapshot, readSystemConfig, readOrgConfig } from './triage-snapshot.mjs'; import { busesStopped } from '../../cli/src/proxy-admin-host.mjs'; import { agentLevelsWriteRoutes } from './agent-levels-write.mjs'; import { RESTART_EXIT } from '../../cli/src/org-console.mjs'; @@ -227,11 +229,29 @@ try { return out; }, }) : null; + // #1873 triage-host: the instance owner's Triage session, hosted by the Console in no organization. + // Nothing starts here; the owner's first message starts it. No model route store exists without a + // schema change, so none is wired: the read says no route is set and nothing launches. + const triage = system && (devOwner || ssoOn) ? createTriageHost({ + dataRoot: system.dataRoot, route: null, log: line => console.log(line), + readSnapshot: () => composeSnapshot({ + orgs: () => listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance }), + busStatus: id => orgBusStatus({ configDir: configDir(), dataRoot: system.dataRoot, instance }, id), + processing: async id => { + const org = (await listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance })).find(o => o.id === id); + if (!org) return null; + return busCaller({ dataRoot: org.root, socket: orgPaths(org.root).socket, business: id, timeoutMs: 5000 })('processing.status'); + }, + orgConfig: id => readOrgConfig(id), + proxy: () => proxyAdmin.status(), + systemConfig: () => readSystemConfig(), + }), + }) : null; let server, testerServer = null; // F3: the restart route closes every listener and connection, then exits RESTART_EXIT for the // supervisor to relaunch. Without --supervised the route answers not-supervised. const restart = supervised ? () => { - sso?.close(); testerServer?.close(); + sso?.close(); testerServer?.close(); triage?.stop(); setTimeout(() => process.exit(RESTART_EXIT), 2000).unref(); server.close(() => process.exit(RESTART_EXIT)); server.closeAllConnections(); @@ -240,7 +260,7 @@ try { // #1873 A2: Settings > Agents writes for the root and project levels, beside the levels read. const agentLevelRoutes = organizations ? [agentLevelsWriteRoutes({ configDir: configDir(), rolesDir: rolesDir(), trail })] : []; try { - server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, routes: agentLevelRoutes, preselect: options.business ?? null }); + server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, triage, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, routes: agentLevelRoutes, preselect: options.business ?? null }); } catch (err) { sso?.close(); throw err; } if (testerSocket) { const call = busCaller({ dataRoot: system.dataRoot, socket: socketPath(system.dataRoot), business: options.business ?? null, cli: TESTER_CLI }); @@ -277,7 +297,7 @@ try { // D2 (P0-3): the dev Console reattaches to the buses that still run and brings back the ones its // unit stop killed. It runs after the Console answers, so a slow bus never delays the page. if (organizations && trail) reviveBuses({ ctx: { configDir: configDir(), dataRoot: system.dataRoot, instance }, listOrgs, busStatus: orgBusStatus, busRevive: orgBusRevive, trail, log: line => console.log(line) }).catch(() => console.log('bus revive: stopped on an unexpected error')); - for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { sso?.close(); server.close(); testerServer?.close(); }); + for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { sso?.close(); server.close(); testerServer?.close(); triage?.stop(); }); } catch (err) { console.error(`refused: ${err.message}`); process.exitCode = 2; diff --git a/packages/webui/src/serve.mjs b/packages/webui/src/serve.mjs index 993632a64..611e34c8f 100644 --- a/packages/webui/src/serve.mjs +++ b/packages/webui/src/serve.mjs @@ -1,6 +1,7 @@ import { AUTONOMY_ROUTE, autonomyHTTP } from './autonomy-http.mjs'; import { proxyHTTP } from './proxy-http.mjs'; import { proxyAdminHTTP } from './proxy-admin.mjs'; +import { triageHTTP, TRIAGE_PATHS } from './triage-http.mjs'; import { createServer } from 'node:http'; import { bindTesterSocket, TESTER_ORIGIN } from './tester-socket.mjs'; import { readFileSync, openSync, fstatSync, closeSync, constants } from 'node:fs'; @@ -811,7 +812,7 @@ async function libraryStatusRead(res, read, search) { // `log` takes one line per send attempt that got past sign-in; never the body. `fieldsFile` is for // tests; the field table is otherwise the committed packages/tasks/fields.json. // `agentWrite` (row 194, D7) is `(verb, args) => Promise` for the Agents section's verbs and instance.request. -export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) { +export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, triage = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) { // org-lan-bind: the dev owner on the LAN is an explicit opt-in. `devAllowHosts` names the Host // names (without a port) a remote browser may use; only the dev owner takes them, and only with // them may it bind a non-loopback IPv4 address. SSO, preview and tester listeners stay loopback. @@ -1048,6 +1049,11 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF if (path.startsWith('/api/proxy/')) return proxyHTTP(req, res, { path, call: proxyCall, named, tester, granted, send, origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user, log }); } + // #1873 triage-host: the Triage session's two routes answer only the instance owner's own session on + // the public name, with no organization selected. Anyone else falls through to the answer an + // unknown route gives them, so the routes are not visible to a caller who cannot use them. + if (TRIAGE_PATHS.includes(path) && triage && !tester && !granted && named && sso !== null && orgId === null && !hook && currentSession?.rootOwner === true) + return triageHTTP(req, res, { path, triage, send: owner.send !== null, origin: localOrigin ?? sso.publicOrigin, log }); // Row 252: Approve and Deny. The tester listener never offers them. Anywhere else without a signed-in // session on the public name under --sso and --send, they are read-only. @@ -1240,7 +1246,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF // `send`: the page shows the composer only where a send can pass (the public name, --send on). // `edit`: the editor shows Save only where a save can pass, the same test as the route's. // `user` and `federation` (FED R6) only when there is one, so the owner's config is unchanged. - if (path === '/api/config') return json(res, 200, { board: upstream, viewer: viewerOf(currentSession), ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), ...(proxyAdmin && !tester && !granted && named && sso !== null && currentSession?.rootOwner === true ? { proxyAdmin: true, proxyAdminSend: owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named }); + if (path === '/api/config') return json(res, 200, { board: upstream, viewer: viewerOf(currentSession), ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), ...(proxyAdmin && !tester && !granted && named && sso !== null && currentSession?.rootOwner === true ? { proxyAdmin: true, proxyAdminSend: owner.send !== null } : {}), ...(triage && !tester && !granted && named && sso !== null && orgId === null && currentSession?.rootOwner === true ? { triage: true, triageSend: owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named }); if (path === '/healthz') return json(res, 200, { ok: true, ...(sso ? { sso: sso.health() } : {}) }); if (path === '/favicon.ico') { res.writeHead(204); return res.end(); } const file = files.get(path); diff --git a/packages/webui/src/triage-host.mjs b/packages/webui/src/triage-host.mjs index d3bf00d5b..c36956371 100644 --- a/packages/webui/src/triage-host.mjs +++ b/packages/webui/src/triage-host.mjs @@ -182,6 +182,7 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async const role = JSON.parse(readFileSync(join(roleDir, "triage.json"), "utf8")); const contract = readFileSync(join(roleDir, role.contract), "utf8"); let last = null; // the last snapshot written + let lastAt = null; // when it was written, in ms let child = null; let relay = null; let starting = null; @@ -225,6 +226,7 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async if (snap && typeof snap === "object") { writeSnapshot(paths.health, snap); last = snap; + lastAt = now().getTime(); } return last; }; @@ -333,6 +335,7 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async }; }, refresh, + snapshotAt: () => lastAt, // The owner's message: checked, admitted by the route, written to the transcript, queued, and // the session started when it isn't running. async message(raw) { diff --git a/packages/webui/src/triage-http.mjs b/packages/webui/src/triage-http.mjs new file mode 100644 index 000000000..19ebc67eb --- /dev/null +++ b/packages/webui/src/triage-http.mjs @@ -0,0 +1,102 @@ +// #1873 triage-host: the two owner routes of the Triage session. serve.mjs sends a request here only +// for the instance owner's own session (rootOwner, signed in on the public name, no organization +// selected); everyone else falls through to the answer an unknown route gives. The read carries the +// transcript, the last health snapshot and the cards; the write carries one owner message and also +// needs --send and the same-origin checks the org admin routes use. No body, path, token or +// exception text reaches a response or a log line. + +export const TRIAGE_PATHS = Object.freeze(["/api/triage", "/api/triage/message"]); +export const BODY_MAX = 16384; +// A read refreshes the snapshot when the one it holds is older than this. +export const SNAPSHOT_MAX_AGE_MS = 30000; +export const NO_ROUTE_MESSAGE = "No model route is set for Triage, so Triage will not start. The instance owner sets the route first."; + +const STATUS = Object.freeze({ + "invalid-request": 400, + "triage-message-empty": 400, + "triage-message-too-long": 400, + "triage-no-route": 409, + "triage-route-refused": 409, + "triage-route-invalid": 409, + "triage-over-cap": 429, + "triage-busy": 429, +}); +// Fixed words for each code; the host's own messages are fixed too, but the route never forwards text. +const MESSAGES = Object.freeze({ + "invalid-request": "the request is not a Triage message", + "triage-message-empty": "the message is empty", + "triage-message-too-long": "the message is too long", + "triage-no-route": NO_ROUTE_MESSAGE, + "triage-route-refused": "the model route refused to start Triage", + "triage-route-invalid": "the model route's answer is not usable", + "triage-route-unreadable": "the model route could not be read", + "triage-over-cap": "Triage is over its daily token cap and starts again after the time shown", + "triage-busy": "Triage has too many messages waiting", + "triage-dir-unsafe": "a Triage directory is not safe to use", + "triage-start-failed": "the Triage session did not start", + "outcome-unknown": "Triage did not answer", +}); + +const json = (res, status, value) => { + res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }); + res.end(JSON.stringify(value)); +}; +const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.headersDistinct[name][0] : null); + +async function readBody(req) { + if ((req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase() !== "application/json") throw Error(); + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > BODY_MAX) throw Error(); + chunks.push(chunk); + } + const value = JSON.parse(Buffer.concat(chunks)); + if (!value || typeof value !== "object" || Array.isArray(value)) throw Error(); + if (Object.keys(value).some((k) => k !== "text") || typeof value.text !== "string") throw Error(); + return value.text; +} + +// The read's answer. `send` tells the drawer whether it may offer the message box. +export async function triageView(triage, { send, now = Date.now } = {}) { + const held = triage.snapshotAt?.() ?? null; + if (held === null || now() - held > SNAPSHOT_MAX_AGE_MS) await triage.refresh(); + const s = await triage.state(); + return { + route: s.route, + ...(s.route === "set" ? {} : { routeMessage: NO_ROUTE_MESSAGE }), + running: s.running, + lastExit: s.lastExit, + snapshot: s.snapshot, + transcript: s.transcript, + send: send === true, + }; +} + +export async function triageHTTP(req, res, { path, triage, send, origin, log = () => {} }) { + const done = (status, value) => { + // Method, path and status only. + log(`${new Date().toISOString()} ${req.method} ${path} ${status}`); + return json(res, status, value); + }; + // `code` is always a key of MESSAGES. + const refuse = (code, extra = {}) => done(STATUS[code] ?? 503, { error: code, message: MESSAGES[code], ...extra }); + if (path === "/api/triage") { + if (req.method !== "GET") return done(405, { error: "method not allowed" }); + try { return done(200, await triageView(triage, { send })); } + catch { return refuse("outcome-unknown"); } + } + if (req.method !== "POST") return done(405, { error: "method not allowed" }); + if (!send) return done(403, { error: "read-only" }); + if (one(req, "origin") !== origin) return done(403, { error: "cross-origin request refused" }); + if (one(req, "sec-fetch-site") !== "same-origin") return done(403, { error: "cross-site request refused" }); + let text; + try { text = await readBody(req); } catch { return refuse("invalid-request"); } + try { + return done(202, await triage.message(text)); + } catch (error) { + const code = typeof error?.code === "string" && Object.hasOwn(MESSAGES, error.code) ? error.code : "outcome-unknown"; + return refuse(code, code === "triage-over-cap" && typeof error.until === "string" ? { until: error.until } : {}); + } +} diff --git a/packages/webui/tests/triage-http.test.mjs b/packages/webui/tests/triage-http.test.mjs new file mode 100644 index 000000000..54b66ba37 --- /dev/null +++ b/packages/webui/tests/triage-http.test.mjs @@ -0,0 +1,214 @@ +// #1873 triage-host: the Triage routes over the real HTTP boundary. Only the instance owner's own +// session reaches them; every other caller gets exactly what an unknown route gives that caller. +// The write also needs --send and the same-origin checks. No body, path or exception text leaves. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { request } from 'node:http'; +import { mkdtempSync, existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { startServer } from '../src/serve.mjs'; +import { createDevOwner } from '../src/dev-owner.mjs'; +import { consoleAccess } from '../src/access.mjs'; +import { createSsoSession } from './helpers/sso-session.mjs'; +import { NO_ROUTE_MESSAGE, triageView, triageHTTP, SNAPSHOT_MAX_AGE_MS } from '../src/triage-http.mjs'; +import { createTriageHost, TriageError } from '../src/triage-host.mjs'; + +const LEAK = '/home/owner/.config/mosaic-dev/secret-token-0123456789'; + +function fakeTriage({ message } = {}) { + const calls = []; + return { + calls, + snapshotAt: () => null, + refresh: async () => { calls.push(['refresh']); return null; }, + state: async () => ({ route: 'set', running: false, lastExit: null, snapshot: { snapshotVersion: 1 }, transcript: [{ at: 't', from: 'owner', id: 'owner-1', text: 'hi' }] }), + message: async text => { calls.push(['message', text]); return message ? message(text) : { id: 'owner-abc', at: '2026-11-16T00:00:00.000Z' }; }, + }; +} + +const send = (port, path, { method = 'GET', headers = {}, body } = {}) => new Promise((resolve, reject) => { + const req = request({ host: '127.0.0.1', port, path, method, headers }, res => { + let text = ''; res.on('data', c => { text += c; }); res.on('end', () => resolve({ status: res.statusCode, text, json: (() => { try { return JSON.parse(text); } catch { return null; } })() })); + }); + req.on('error', reject); req.end(body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body)); +}); + +async function devServer(t, options = {}) { + const logs = []; + const s = await startServer({ port: 0, board: 'http://127.0.0.1:9', sso: createDevOwner(), send: async () => ({}), log: line => logs.push(line), ...options }); + t.after(() => new Promise(r => s.close(r))); + const port = s.address().port; + const headers = { host: `127.0.0.1:${port}`, origin: `http://127.0.0.1:${port}`, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json' }; + return { port, logs, headers }; +} + +// The same request on an unknown path next to the Triage one: status and body must match. +async function sameAsUnknown(port, path, method, headers, body, label) { + const unknown = path.replace('/api/triage', '/api/triagz'); + const [a, b] = [await send(port, path, { method, headers, body }), await send(port, unknown, { method, headers, body })]; + assert.equal(a.status, b.status, `${label} ${method} ${path}: status`); + assert.equal(a.text, b.text, `${label} ${method} ${path}: body`); +} +const EVERY = [['/api/triage', 'GET'], ['/api/triage', 'POST'], ['/api/triage/message', 'GET'], ['/api/triage/message', 'POST']]; + +test('the dev local owner reads the drawer state and sends a message; the config names the drawer', async t => { + const triage = fakeTriage(); + const f = await devServer(t, { triage }); + const read = await send(f.port, '/api/triage', { headers: { host: f.headers.host } }); + assert.equal(read.status, 200); + assert.deepEqual(read.json, { route: 'set', running: false, lastExit: null, snapshot: { snapshotVersion: 1 }, transcript: [{ at: 't', from: 'owner', id: 'owner-1', text: 'hi' }], send: true }); + const sent = await send(f.port, '/api/triage/message', { method: 'POST', headers: f.headers, body: { text: 'why is alpha down?' } }); + assert.equal(sent.status, 202); + assert.deepEqual(sent.json, { id: 'owner-abc', at: '2026-11-16T00:00:00.000Z' }); + assert.deepEqual(triage.calls.filter(c => c[0] === 'message'), [['message', 'why is alpha down?']]); + const config = await send(f.port, '/api/config', { headers: { host: f.headers.host } }); + assert.equal(config.json.triage, true); + assert.equal(config.json.triageSend, true); + assert.equal(f.logs.join('\n').includes('why is alpha down'), false, 'no message text in a log line'); + for (const line of f.logs.filter(l => l.includes('/api/triage'))) assert.match(line, /^\S+ (GET|POST) \/api\/triage(\/message)? \d{3}$/); + // A wrong method on either route. + assert.equal((await send(f.port, '/api/triage', { method: 'POST', headers: f.headers, body: {} })).status, 405); + assert.equal((await send(f.port, '/api/triage/message', { headers: { host: f.headers.host } })).status, 405); +}); + +test('the write is refused without --send, from a foreign Origin, and without same-origin Fetch Metadata', async t => { + const triage = fakeTriage(); + const readOnly = await devServer(t, { triage, send: null }); + const r = await send(readOnly.port, '/api/triage/message', { method: 'POST', headers: readOnly.headers, body: { text: 'hi' } }); + assert.equal(r.status, 403); assert.deepEqual(r.json, { error: 'read-only' }); + assert.equal((await send(readOnly.port, '/api/triage', { headers: { host: readOnly.headers.host } })).json.send, false); + assert.equal((await send(readOnly.port, '/api/config', { headers: { host: readOnly.headers.host } })).json.triageSend, false); + const f = await devServer(t, { triage }); + assert.equal((await send(f.port, '/api/triage/message', { method: 'POST', headers: { ...f.headers, origin: 'http://evil.example' }, body: { text: 'hi' } })).status, 403); + const crossSite = await send(f.port, '/api/triage/message', { method: 'POST', headers: { ...f.headers, 'sec-fetch-site': 'cross-site' }, body: { text: 'hi' } }); + assert.deepEqual([crossSite.status, crossSite.json], [403, { error: 'cross-site request refused' }]); + const noMeta = { ...f.headers }; delete noMeta['sec-fetch-site']; + const missing = await send(f.port, '/api/triage/message', { method: 'POST', headers: noMeta, body: { text: 'hi' } }); + assert.deepEqual([missing.status, missing.json], [403, { error: 'cross-site request refused' }]); + assert.deepEqual(triage.calls.filter(c => c[0] === 'message'), []); +}); + +test('a malformed body is refused before the host sees it; the host refusals map to fixed answers with no leaked text', async t => { + let next = null; + const triage = fakeTriage({ message: () => { throw next; } }); + const f = await devServer(t, { triage }); + const post = (body, headers = f.headers) => send(f.port, '/api/triage/message', { method: 'POST', headers, body }); + for (const body of [{ text: 'hi', extra: 1 }, { text: 5 }, {}, [], '{"text":', `{"text":"${'x'.repeat(17000)}"}`]) + assert.deepEqual((await post(body)).json, { error: 'invalid-request', message: 'the request is not a Triage message' }, JSON.stringify(body).slice(0, 40)); + assert.equal((await post({ text: 'hi' }, { ...f.headers, 'content-type': 'text/plain' })).status, 400); + assert.deepEqual(triage.calls.filter(c => c[0] === 'message'), []); + next = Object.assign(new TriageError('triage-over-cap', LEAK), { until: '2026-11-17T00:00:00.000Z' }); + const cap = await post({ text: 'hi' }); + assert.deepEqual([cap.status, cap.json], [429, { error: 'triage-over-cap', message: 'Triage is over its daily token cap and starts again after the time shown', until: '2026-11-17T00:00:00.000Z' }]); + next = new TriageError('triage-no-route', LEAK); + const none = await post({ text: 'hi' }); + assert.deepEqual([none.status, none.json], [409, { error: 'triage-no-route', message: NO_ROUTE_MESSAGE }]); + next = new TriageError('triage-message-too-long', LEAK); + assert.equal((await post({ text: 'hi' })).status, 400); + next = new TriageError('triage-busy', LEAK); + assert.equal((await post({ text: 'hi' })).status, 429); + next = Object.assign(new Error(LEAK), { code: 'EACCES' }); + const odd = await post({ text: 'hi' }); + assert.deepEqual([odd.status, odd.json], [503, { error: 'outcome-unknown', message: 'Triage did not answer' }]); + for (const r of [cap, none, odd]) assert.equal(r.text.includes('/home/'), false); + assert.equal(f.logs.join('\n').includes('/home/'), false); +}); + +test('a signed-out caller and a granted user get the unknown-route answer on both routes', async t => { + const access = { accessVersion: 1, revision: 1, + users: [{ id: 'alice', home: 'local', subjects: [{ provider: 'writer', sub: 'alice-sub' }] }], + grants: [{ id: 'g-1', user: 'alice', business: 'demo', projects: ['*'], instances: ['*'], level: 'collaborator' }] }; + const auth = await createSsoSession(t, { host: 'console.example', users: consoleAccess({ load: () => access, business: () => 'demo' }) }); + const triage = fakeTriage(); + const s = await startServer({ port: 0, sso: auth.sso, send: async () => ({}), triage, userOptions: () => ({}), log: () => {} }); + t.after(() => new Promise(r => s.close(r))); + const port = s.address().port; + const owner = auth.writeHeaders(await auth.signIn(port)); + assert.equal((await send(port, '/api/triage', { headers: owner })).status, 200, 'the SSO root owner reaches the read'); + assert.equal((await send(port, '/api/triage/message', { method: 'POST', headers: owner, body: { text: 'hi' } })).status, 202, 'and the write'); + const before = triage.calls.length; + const signedOut = auth.writeHeaders(null); + const alice = auth.writeHeaders(await auth.signIn(port, { sub: 'alice-sub' })); + for (const [path, method] of EVERY) { + await sameAsUnknown(port, path, method, signedOut, method === 'POST' ? { text: 'hi' } : undefined, 'signed out'); + await sameAsUnknown(port, path, method, alice, method === 'POST' ? { text: 'hi' } : undefined, 'granted user'); + } + assert.equal((await send(port, '/api/triage', { headers: signedOut })).status, 401); + assert.equal(Object.hasOwn((await send(port, '/api/config', { headers: alice })).json, 'triage'), false); + assert.equal(triage.calls.length, before, 'the host saw nothing from them'); +}); + +test('without a host, on a loopback Host under --sso, and on the tester listener the routes are unknown', async t => { + const none = await devServer(t); + for (const [path, method] of EVERY) await sameAsUnknown(none.port, path, method, none.headers, method === 'POST' ? { text: 'hi' } : undefined, 'no host'); + assert.equal(Object.hasOwn((await send(none.port, '/api/config', { headers: { host: none.headers.host } })).json, 'triage'), false); + const auth = await createSsoSession(t, { host: 'console.example' }); + const triage = fakeTriage(); + const s = await startServer({ port: 0, sso: auth.sso, send: async () => ({}), triage, log: () => {} }); + t.after(() => new Promise(r => s.close(r))); + const port = s.address().port; + const cookie = await auth.signIn(port); + const loop = { host: `127.0.0.1:${port}`, cookie, origin: `http://127.0.0.1:${port}`, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json' }; + for (const [path, method] of EVERY) await sameAsUnknown(port, path, method, loop, method === 'POST' ? { text: 'hi' } : undefined, 'loopback Host'); + const { startTesterSocket } = await import('../src/tester-socket.mjs'); + const { testerRequest } = await import('../../cli/src/tester-http.mjs'); + const root = mkdtempSync(join(process.env.TMPDIR, 'th-')); + const ts = await startTesterSocket({ dataRoot: root, triage, log: () => {} }); + t.after(() => new Promise(r => ts.close(r))); + for (const [path, method] of EVERY) { + const body = method === 'POST' ? { text: 'hi' } : undefined; + const a = await testerRequest({ dataRoot: root, path, method, body }); + const b = await testerRequest({ dataRoot: root, path: path.replace('/api/triage', '/api/triagz'), method, body }); + assert.equal(a.status, b.status, `tester ${method} ${path}`); + } + assert.deepEqual(triage.calls, []); +}); + +test('the read refreshes a missing or stale snapshot and keeps a fresh one', async () => { + let at = null, clock = 1_000_000; + const calls = []; + const triage = { snapshotAt: () => at, refresh: async () => { calls.push(clock); at = clock; }, state: async () => ({ route: 'not set', running: false, lastExit: null, snapshot: null, transcript: [] }) }; + const view = await triageView(triage, { send: true, now: () => clock }); + assert.deepEqual(view, { route: 'not set', routeMessage: NO_ROUTE_MESSAGE, running: false, lastExit: null, snapshot: null, transcript: [], send: true }); + clock += SNAPSHOT_MAX_AGE_MS - 1; await triageView(triage, { now: () => clock }); + clock += 2; await triageView(triage, { now: () => clock }); + assert.deepEqual(calls, [1_000_000, 1_000_000 + SNAPSHOT_MAX_AGE_MS + 1]); +}); + +test('with the real host and no route: the read says so in plain words, the write refuses, nothing launches or is written', async t => { + const dataRoot = join(mkdtempSync(join(process.env.TMPDIR, 'th-')), 'data'); + const host = createTriageHost({ dataRoot, readSnapshot: async () => ({ snapshotVersion: 1, at: '2026-11-16T00:00:00.000Z' }), bwrap: '/nonexistent/bwrap' }); + const f = await devServer(t, { triage: host }); + const read = await send(f.port, '/api/triage', { headers: { host: f.headers.host } }); + assert.equal(read.status, 200); + assert.equal(read.json.route, 'not set'); + assert.equal(read.json.routeMessage, NO_ROUTE_MESSAGE); + assert.deepEqual(read.json.snapshot, { snapshotVersion: 1, at: '2026-11-16T00:00:00.000Z' }); + const sent = await send(f.port, '/api/triage/message', { method: 'POST', headers: f.headers, body: { text: 'hello' } }); + assert.deepEqual([sent.status, sent.json.error], [409, 'triage-no-route']); + assert.equal(host.running, false); + assert.equal(existsSync(host.paths.transcript), false, 'a refused message is not written'); + assert.equal(JSON.parse(readFileSync(join(host.paths.health, 'snapshot.json'), 'utf8')).snapshotVersion, 1, 'the read wrote the snapshot'); +}); + +test('the route module keeps its own write checks when called alone: --send, one exact Origin, one same-origin Fetch Metadata', async () => { + const triage = fakeTriage(); + const call = async (headers, { send = true } = {}) => { + const distinct = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, [v].flat()])); + const req = { method: 'POST', headers: Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, [v].flat()[0]])), headersDistinct: distinct, + async *[Symbol.asyncIterator]() { yield Buffer.from('{"text":"hi"}'); } }; + let status = null, body = ''; + const res = { writeHead: s => { status = s; }, end: b => { body = b; } }; + await triageHTTP(req, res, { path: '/api/triage/message', triage, send, origin: 'https://console.example' }); + return [status, JSON.parse(body).error ?? 'ok']; + }; + const good = { origin: 'https://console.example', 'sec-fetch-site': 'same-origin', 'content-type': 'application/json' }; + assert.deepEqual(await call(good, { send: false }), [403, 'read-only']); + assert.deepEqual(await call({ ...good, origin: 'https://evil.example' }), [403, 'cross-origin request refused']); + assert.deepEqual(await call({ ...good, origin: ['https://console.example', 'https://console.example'] }), [403, 'cross-origin request refused']); + const { origin, ...noOrigin } = good; + assert.deepEqual(await call(noOrigin), [403, 'cross-origin request refused']); + assert.deepEqual(await call({ ...good, 'sec-fetch-site': ['same-origin', 'same-origin'] }), [403, 'cross-site request refused']); + assert.deepEqual(triage.calls, []); + assert.deepEqual(await call(good), [202, 'ok']); +});