660 lines
48 KiB
JavaScript
660 lines
48 KiB
JavaScript
import { createServer } from 'node:http';
|
||
import { bindTesterSocket, TESTER_ORIGIN } from './tester-socket.mjs';
|
||
import { readFileSync, openSync, fstatSync, closeSync, constants } from 'node:fs';
|
||
import { timingSafeEqual } from 'node:crypto';
|
||
import { resolve } from 'node:path';
|
||
import { isIP } from 'node:net';
|
||
import { BusReadError, busStatus as coreBusStatus, subjectOk, sendOutcome } from './bus.mjs';
|
||
// Row 176, sage-1111: HTTP-only tester refusals; the row-164 transport pin stays untouched.
|
||
const busStatus = code => ['tester-off', 'tester-required'].includes(code) ? 403 : coreBusStatus(code);
|
||
import { ReadError, readStatus, fieldTable } from './reads.mjs';
|
||
import { chatHTTP } from './chat-http.mjs';
|
||
|
||
export const DEFAULT_BOARD = 'http://127.0.0.1:7331';
|
||
export function isLoopback(host) {
|
||
return host === 'localhost' || host === '::1' || (isIP(host) === 4 && host.startsWith('127.'));
|
||
}
|
||
export function boardURL(value) {
|
||
const url = new URL(value);
|
||
if (url.protocol !== 'http:' || !isLoopback(url.hostname.replace(/^\[|\]$/g, '')) || url.username || url.password || url.search || url.hash || url.pathname !== '/') {
|
||
throw new Error('board must be an HTTP loopback origin without credentials, path, query or fragment');
|
||
}
|
||
// Avoid hostname resolution for localhost.
|
||
if (url.hostname === 'localhost') url.hostname = '127.0.0.1';
|
||
return url.origin;
|
||
}
|
||
const root = resolve(import.meta.dirname, 'public');
|
||
const files = new Map([
|
||
['/', ['index.html', 'text/html; charset=utf-8']],
|
||
...['app.js', 'brand.js', 'bus.js', 'markdown-preview.js', 'chat.js'].map(f => ['/' + f, [f, 'text/javascript; charset=utf-8']]),
|
||
...['shared/app.css', 'tokens.css', 'console.css', 'live.css', 'bus.css', 'shell.css', 'chat.css'].map(f => ['/' + f, [f, 'text/css; charset=utf-8']]),
|
||
['/editor.js', ['editor.js', 'text/javascript; charset=utf-8']],
|
||
['/editor.css', ['editor.css', 'text/css; charset=utf-8']],
|
||
['/icons.svg', ['icons.svg', 'image/svg+xml']],
|
||
...[400, 500, 600, 700].map(w => [`/assets/fonts/manrope-${w}.woff2`, [`assets/fonts/manrope-${w}.woff2`, 'font/woff2']]),
|
||
...[400, 500, 700].map(w => [`/assets/fonts/jetbrains-mono-${w}.woff2`, [`assets/fonts/jetbrains-mono-${w}.woff2`, 'font/woff2']]),
|
||
]);
|
||
function json(res, status, body) {
|
||
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
||
res.end(JSON.stringify(body));
|
||
}
|
||
async function body(req, max = 4096) {
|
||
if ((req.headers['content-type'] || '').split(';')[0].trim().toLowerCase() !== 'application/json') throw new Error('Content-Type must be application/json');
|
||
const chunks = [];
|
||
let size = 0;
|
||
for await (const chunk of req) {
|
||
size += chunk.length;
|
||
if (size > max) throw new Error(`body larger than ${max} bytes`);
|
||
chunks.push(chunk);
|
||
}
|
||
const bytes = Buffer.concat(chunks);
|
||
const value = JSON.parse(bytes.toString('utf8'));
|
||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('body must be a JSON object');
|
||
return bytes;
|
||
}
|
||
// Slice 1 S5 (#1522): GET only, the four Q1 verbs, nothing else (lead decision 56, Q4).
|
||
// Row 57 (#1546) adds `decisions`, also a read, for the Inbox tabs. Row 60
|
||
// (#1549) adds `credentials`: what the bus host loaded, metadata only. Row 81
|
||
// (#1575) adds `replies`: the messages answering one message, for the send receipt. Row 125
|
||
// (#1619, REQ-LIMIT-3) adds `limits`: only the token limits' report, never the document. Row 155
|
||
// (#1649) adds `names`: each instance's current seat name, for the Assistant section. Row 165
|
||
// (#1662) adds `instances`: the business file's role instances and the definitions add accepts.
|
||
// Row 65 (mos-0840) adds `routes`: each instance's harness, model, thinking and fallback.
|
||
const BUS_VERBS = ['inbox', 'tasks', 'agents', 'trail', 'decisions', 'credentials', 'replies', 'messages', 'usage', 'limits', 'names', 'instances', 'routes'];
|
||
const DECISION_LISTS = ['roles', 'recent'];
|
||
// Q175 phase 1 (#1690, F8): either sign-in cookie, which the tester listener refuses under --sso.
|
||
const SIGN_IN_COOKIE = /(?:^|;)\s*__host-mosaic_(?:session|login)\s*=/i;
|
||
// Row 177 (#1675): the chat writes the tester listener lets through, exactly the four chatHTTP routes.
|
||
const TESTER_CHAT_WRITE = /^\/api\/chat\/(?:projects|threads|threads\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/(?:messages|open))$/i;
|
||
async function busRead(res, bus, verb, search) {
|
||
let arg;
|
||
if (verb === 'usage') {
|
||
if (search) return json(res, 400, { error: 'invalid-request', message: 'usage takes no arguments' });
|
||
if (!bus) return json(res, 503, { error: 'not-configured', message: 'the Console has no bus configured' });
|
||
try {
|
||
const value = await bus.usage();
|
||
if (!value || typeof value.total !== 'object' || !Array.isArray(value.byInstance)) throw new BusReadError('invalid-response');
|
||
return json(res, 200, { rows: [value], at: new Date().toISOString() });
|
||
} catch (err) {
|
||
const code = err instanceof BusReadError ? err.code : 'invalid-response';
|
||
return json(res, busStatus(code), { error: code, message: code });
|
||
}
|
||
}
|
||
if (verb === 'limits') {
|
||
if (search) return json(res, 400, { error: 'invalid-request', message: 'limits takes no arguments' });
|
||
if (!bus) return json(res, 503, { error: 'not-configured', message: 'the Console has no bus configured' });
|
||
try {
|
||
const value = await bus.limits();
|
||
if (!value || !Array.isArray(value.tokens)) throw new BusReadError('invalid-response');
|
||
return json(res, 200, { rows: value.tokens, at: new Date().toISOString() });
|
||
} catch (err) {
|
||
const code = err instanceof BusReadError ? err.code : 'invalid-response';
|
||
return json(res, busStatus(code), { error: code, message: code });
|
||
}
|
||
}
|
||
if (verb === 'instances') {
|
||
if (search) return json(res, 400, { error: 'invalid-request', message: 'instances takes no arguments' });
|
||
if (!bus?.instances) return json(res, 503, { error: 'not-configured', message: 'the Console has no bus configured' });
|
||
try {
|
||
const value = await bus.instances();
|
||
if (!/^[a-f0-9]{64}$/.test(value?.revision ?? '') || !value.instances || typeof value.instances !== 'object' || !value.definitions || typeof value.definitions !== 'object') throw new BusReadError('invalid-response');
|
||
return json(res, 200, { rows: [value], at: new Date().toISOString() });
|
||
} catch (err) {
|
||
const code = err instanceof BusReadError ? err.code : 'invalid-response';
|
||
return json(res, busStatus(code), { error: code, message: code });
|
||
}
|
||
}
|
||
if (verb === 'routes') {
|
||
if (search) return json(res, 400, { error: 'invalid-request', message: 'routes takes no arguments' });
|
||
if (!bus?.routes) return json(res, 503, { error: 'not-configured', message: 'the Console has no bus configured' });
|
||
try {
|
||
const value = await bus.routes();
|
||
if (!routesAnswer(value)) throw new BusReadError('invalid-response');
|
||
return json(res, 200, { rows: [value], at: new Date().toISOString() });
|
||
} catch (err) {
|
||
const code = err instanceof BusReadError ? err.code : 'invalid-response';
|
||
return json(res, busStatus(code), { error: code, message: code });
|
||
}
|
||
}
|
||
if (verb === 'trail') {
|
||
arg = new URLSearchParams(search).get('subject');
|
||
if (!subjectOk(arg)) return json(res, 400, { error: 'invalid-request', message: 'subject must be a decision id, message id or task ref' });
|
||
}
|
||
if (verb === 'decisions') {
|
||
arg = new URLSearchParams(search).get('list');
|
||
if (!DECISION_LISTS.includes(arg)) return json(res, 400, { error: 'invalid-request', message: 'list must be roles or recent' });
|
||
}
|
||
if (verb === 'replies') {
|
||
arg = new URLSearchParams(search).get('id');
|
||
if (!subjectOk(arg)) return json(res, 400, { error: 'invalid-request', message: 'id must be a message id' });
|
||
}
|
||
if (verb === 'messages') {
|
||
const query = new URLSearchParams(search), args = {};
|
||
const invalid = [...query.keys()].some(k => !['limit', 'after'].includes(k) || query.getAll(k).length !== 1);
|
||
if (invalid || (query.has('limit') && (!/^[1-9]\d*$/.test(query.get('limit')) || Number(query.get('limit')) > 200)) ||
|
||
(query.has('after') && !subjectOk(query.get('after'))))
|
||
return json(res, 400, { error: 'invalid-request', message: 'messages takes limit (1–200) and an after message id' });
|
||
if (query.has('limit')) args.limit = Number(query.get('limit'));
|
||
if (query.has('after')) args.after = query.get('after');
|
||
if (!bus) return json(res, 503, { error: 'not-configured', message: 'the Console has no bus configured' });
|
||
try {
|
||
const page = await bus.messages(args);
|
||
if (!page || !Array.isArray(page.messages)) throw new BusReadError('invalid-response');
|
||
const { messages: rows, ...metadata } = page;
|
||
return json(res, 200, { rows, ...metadata, at: new Date().toISOString() });
|
||
} catch (err) {
|
||
const code = err instanceof BusReadError ? err.code : 'invalid-response';
|
||
return json(res, busStatus(code), { error: code, message: err instanceof BusReadError ? err.message : code });
|
||
}
|
||
}
|
||
if (!bus) return json(res, 503, { error: 'not-configured', message: 'the Console has no bus configured' });
|
||
try {
|
||
const rows = await bus[verb](arg);
|
||
if (!Array.isArray(rows)) throw new BusReadError('invalid-response');
|
||
return json(res, 200, { rows, at: new Date().toISOString() });
|
||
} catch (err) {
|
||
const code = err instanceof BusReadError ? err.code : 'invalid-response';
|
||
return json(res, busStatus(code), { error: code, message: err instanceof BusReadError ? err.message : code });
|
||
}
|
||
}
|
||
// Row 76 (#1570, lead decision 95): with --send, the one POST preview mode allows, a human
|
||
// message to a role. Checked here again whatever passed above: the header on this request, its own
|
||
// Origin, Sec-Fetch-Site same-origin, JSON, 16 KiB, and only these keys. `to` and the body are the
|
||
// broker's to refuse. Nothing retries; an outcome the bus can't confirm is reported as unknown.
|
||
const SEND_KEYS = ['to', 'body', 'in_reply_to'];
|
||
const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.headersDistinct[name][0] : null);
|
||
// Q175 phase 1 (#1690): under --sso the writer comes from a session the handler already checked,
|
||
// so it carries `sso: true` and the public origin; the preview writer still checks its header.
|
||
const signedIn = (req, p) => p.sso === true || one(req, p.header) === p.user;
|
||
const ownOrigin = p => p.origin ?? `https://${p.host}`;
|
||
async function busSend(req, res, { send, preview, log }) {
|
||
if (!signedIn(req, preview)) return json(res, 401, { error: 'sign-in required' });
|
||
let to = null;
|
||
// `to` is quoted and cut short so a crafted value can't forge a log line.
|
||
const line = outcome => log(`${new Date().toISOString()} send user=${JSON.stringify(preview.user)} to=${typeof to === 'string' ? JSON.stringify(to.slice(0, 64)) : 'none'} ${outcome}`);
|
||
// `sent` tells the page which it was: false, nothing was written; 'unknown', it may have been.
|
||
const refuse = (status, error, message, sent = false) => { line(`error=${error}`); return json(res, status, { error, message, sent }); };
|
||
if (one(req, 'origin') !== ownOrigin(preview)) return refuse(403, 'cross-origin request refused', 'a send needs the Console\'s own Origin');
|
||
if (one(req, 'sec-fetch-site') !== 'same-origin') return refuse(403, 'cross-site request refused', 'a send needs Sec-Fetch-Site: same-origin');
|
||
let value;
|
||
try { value = JSON.parse((await body(req, 16384)).toString('utf8')); } catch (err) { return refuse(400, 'invalid-request', err.message); }
|
||
if (value === null || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(k => !SEND_KEYS.includes(k)) || !('to' in value) || !('body' in value)) return refuse(400, 'invalid-request', 'a send takes to, body and an optional in_reply_to, nothing else');
|
||
({ to } = value);
|
||
const args = { to: value.to, body: value.body };
|
||
if ('in_reply_to' in value) args.in_reply_to = value.in_reply_to;
|
||
let result;
|
||
try { result = await send(args); } catch (err) {
|
||
const { code, sent } = sendOutcome(err);
|
||
return sent === false
|
||
? refuse(busStatus(code), code, `not sent: the bus refused it (${code})`)
|
||
: refuse(503, 'outcome-unknown', 'the message may have been sent; nothing was retried. Check the trail before sending again', 'unknown');
|
||
}
|
||
if (!subjectOk(result?.id)) return refuse(503, 'outcome-unknown', 'the bus answered without a message id; the message may have been sent. Check the trail before sending again', 'unknown');
|
||
line(`id=${result.id}`);
|
||
return json(res, 200, { id: result.id, at: new Date().toISOString() });
|
||
}
|
||
// Row 54 (#1543): GET only. `reads` is consoleReads() from reads.mjs; its
|
||
// bodies and messages arrive redacted. No route here writes or calls out.
|
||
const QUEUE_ID = /^[1-9]\d{0,5}$/;
|
||
async function consoleRead(res, read) {
|
||
try { return json(res, 200, await read()); } catch (err) {
|
||
const code = err instanceof ReadError ? err.code : 'invalid-response';
|
||
return json(res, readStatus(code), { error: code, message: err instanceof ReadError ? err.message : code });
|
||
}
|
||
}
|
||
// Row 74 (#1568, lead decision 93): the preview mode behind the edge proxy. Off unless
|
||
// all three are given. The bind stays loopback; the proxy signs the user in
|
||
// and sets the header; the Console checks it against the one user id and serves reads only.
|
||
// Nothing here names an identity provider: one header name and one user id, from the flags.
|
||
const HOSTNAME = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
|
||
const HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
||
const USER = /^[\x21-\x2b\x2d-\x7e]{1,256}$/;
|
||
export function previewOptions({ publicHost, authHeader, allowUser } = {}) {
|
||
const given = [publicHost, authHeader, allowUser].filter(v => v !== undefined && v !== null);
|
||
if (!given.length) return null;
|
||
if (given.length !== 3) throw new Error('preview mode needs --public-host, --auth-header and --allow-user together');
|
||
const host = String(publicHost).toLowerCase(), header = String(authHeader).toLowerCase();
|
||
if (!HOSTNAME.test(host) || isIP(host)) throw new Error('public host must be a DNS name without scheme or port');
|
||
if (!HEADER.test(header) || ['host', 'origin'].includes(header)) throw new Error('auth header must be a header name other than Host or Origin');
|
||
if (typeof allowUser !== 'string' || !USER.test(allowUser)) throw new Error('allowed user must be 1..256 visible ASCII characters without a comma');
|
||
return { host, header, user: allowUser };
|
||
}
|
||
// Row 178: read the proof once, without following a final symlink. Refusals never
|
||
// include the path, bytes, or an underlying fs error. The tester gets only its header name.
|
||
export function proofOptions({ proofHeader, proofFile } = {}, preview = null) {
|
||
if (proofHeader === undefined && proofFile === undefined) return null;
|
||
if (!proofHeader || !proofFile || !preview) throw new Error('proxy proof needs both flags and preview mode');
|
||
const header = String(proofHeader).toLowerCase();
|
||
if (!HEADER.test(header) || ['host', 'origin', 'x-mosaic-tester', preview.header].includes(header)) {
|
||
throw new Error('proxy proof header must be distinct from Host, Origin, tester and auth headers');
|
||
}
|
||
let fd;
|
||
try {
|
||
fd = openSync(proofFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||
const st = fstatSync(fd);
|
||
if (!st.isFile() || st.uid !== process.getuid() || ![0o600, 0o400].includes(st.mode & 0o7777)) {
|
||
throw new Error('invalid proof metadata');
|
||
}
|
||
const text = readFileSync(fd, 'utf8');
|
||
const line = text.endsWith('\n') ? text.slice(0, -1) : text;
|
||
if (line.length < 32 || /[^A-Za-z0-9_-]/.test(line)) throw new Error('invalid proof bytes');
|
||
return { header, value: Buffer.from(line, 'ascii') };
|
||
} catch {
|
||
throw new Error('proxy proof file must be a regular owned 0400 or 0600 file with one base64url line of at least 32 bytes');
|
||
} finally {
|
||
if (fd !== undefined) closeSync(fd);
|
||
}
|
||
}
|
||
// REQ-WEB-1: same signed-in send boundary, a distinct strict settings payload.
|
||
async function settingsSend(req, res, { settingsWrite, preview, log }) {
|
||
const refuse = (status, error, message) => json(res, status, { error, message, sent: false });
|
||
if (!signedIn(req, preview)) {
|
||
return refuse(401, 'sign-in required', 'sign in again');
|
||
}
|
||
if (one(req, 'origin') !== ownOrigin(preview)) {
|
||
return refuse(403, 'cross-origin request refused', 'settings need the Console origin');
|
||
}
|
||
if (one(req, 'sec-fetch-site') !== 'same-origin') {
|
||
return refuse(403, 'cross-site request refused', 'settings need same-origin Fetch Metadata');
|
||
}
|
||
let value;
|
||
try {
|
||
value = JSON.parse((await body(req, 16384)).toString('utf8'));
|
||
} catch {
|
||
return refuse(400, 'invalid-request', 'settings need a JSON object within 16 KiB');
|
||
}
|
||
// Row 155 (#1649, Q169): `assistants` carries an assistant's vars, tracker and definition.
|
||
// Row 125 (#1619, REQ-LIMIT-3): `reset` names token limit paths to count again from now.
|
||
const writable = ['limits', 'models', 'instances', 'reset', 'assistants'];
|
||
if (Object.keys(value).some(key => !['revision', ...writable].includes(key)) ||
|
||
typeof value.revision !== 'string' || !/^[a-f0-9]{64}$/.test(value.revision) ||
|
||
!writable.some(key => Object.hasOwn(value, key))) {
|
||
return refuse(400, 'invalid-request', 'settings need a revision and limits, models, instance selections, a reset or assistant settings');
|
||
}
|
||
try {
|
||
const result = await settingsWrite(value);
|
||
log(`${new Date().toISOString()} settings user=${JSON.stringify(preview.user)} changed`);
|
||
return json(res, 200, result);
|
||
} catch (err) {
|
||
const { code, sent } = sendOutcome(err);
|
||
log(`${new Date().toISOString()} settings user=${JSON.stringify(preview.user)} error=${code}`);
|
||
if (sent === 'unknown') {
|
||
return json(res, 503, {
|
||
error: 'outcome-unknown', message: 'Outcome unknown. Read settings before trying again.', sent: 'unknown',
|
||
});
|
||
}
|
||
return refuse(busStatus(code), code, 'Settings refused; read the current values before trying again.');
|
||
}
|
||
}
|
||
// Row 155 (#1649, Q169): the human names a seat and stops the assistant. Each route has the
|
||
// Settings boundary (header user, exact Origin, same-origin Fetch Metadata, JSON within 4 KiB,
|
||
// strict keys, all text) and one bus call through the human transport, `name.set` or
|
||
// `assistant.stop`. The broker checks the human and the instance.
|
||
const SEAT_ROUTES = {
|
||
'/api/name': { kind: 'name', keys: ['instance', 'name'], done: r => typeof r?.instance === 'string' && typeof r.name === 'string' },
|
||
'/api/assistant-stop': { kind: 'assistant-stop', keys: ['instance'], done: r => Array.isArray(r?.stopped) && r.stopped.every(x => typeof x?.thread === 'string' && typeof x.run === 'string') },
|
||
};
|
||
async function seatSend(req, res, { route, write, preview, log }) {
|
||
let instance = null;
|
||
// The instance is quoted and cut short so a crafted value can't forge a log line.
|
||
const line = outcome => log(`${new Date().toISOString()} ${route.kind} user=${JSON.stringify(preview.user)} instance=${quoted(instance)} ${outcome}`);
|
||
const refuse = (status, error, message, sent = false) => { line(`error=${error}`); return json(res, status, { error, message, sent }); };
|
||
if (!preview.tester && !signedIn(req, preview)) return json(res, 401, { error: 'sign-in required', message: 'sign in again', sent: false });
|
||
if (one(req, 'origin') !== ownOrigin(preview)) return refuse(403, 'cross-origin request refused', 'this needs the Console\'s own Origin');
|
||
if (one(req, 'sec-fetch-site') !== 'same-origin') return refuse(403, 'cross-site request refused', 'this needs same-origin Fetch Metadata');
|
||
let value;
|
||
try { value = JSON.parse((await body(req)).toString('utf8')); } catch (err) { return refuse(400, 'invalid-request', err.message); }
|
||
if (Object.keys(value).length !== route.keys.length || !route.keys.every(k => typeof value[k] === 'string')) {
|
||
return refuse(400, 'invalid-request', `this takes ${route.keys.join(' and ')}, all text, nothing else`);
|
||
}
|
||
({ instance } = value);
|
||
let result;
|
||
try { result = await write(Object.fromEntries(route.keys.map(k => [k, value[k]]))); } catch (err) {
|
||
const { code, sent } = sendOutcome(err);
|
||
return sent === false
|
||
? refuse(busStatus(code), code, `refused by the bus (${code}); nothing changed`)
|
||
: refuse(503, 'outcome-unknown', 'the change may have been made; nothing was retried. Read the Settings again before trying', 'unknown');
|
||
}
|
||
if (!route.done(result)) return refuse(503, 'outcome-unknown', 'the bus answered in an unexpected shape; the change may have been made. Read the Settings again before trying', 'unknown');
|
||
line('done');
|
||
return json(res, 200, { ...result, at: new Date().toISOString() });
|
||
}
|
||
// Row 165 (#1662, Q171): the human adds a role instance or changes one's definition, vars and
|
||
// launch membership. The Settings boundary (header user, exact Origin, same-origin Fetch Metadata,
|
||
// JSON within 16 KiB, strict keys) and one bus call, `instances.set`, through the human transport.
|
||
// The writer refuses a definition that declares credentials. The answer's `restart` says whether
|
||
// the running bus must restart before the change counts; the Console never restarts it.
|
||
const INSTANCE_KEYS = ['revision', 'instance', 'op', 'definition', 'vars', 'launch'];
|
||
// The bus answers a refusal with its code alone, so the reason the page shows is here.
|
||
const INSTANCE_REASONS = {
|
||
'organization-credentials-out-of-scope': 'that definition declares credentials, or the instance holds them. The Console binds no credentials, so that stays a hand edit of the business file',
|
||
'organization-instance-exists': 'the business already has that instance; change it instead',
|
||
'organization-unknown-instance': 'the business has no such instance; add it instead',
|
||
'organization-definition-refused': 'this form neither adds nor changes an assistant, and moves no instance to the assistant definition; an assistant changes only in the Assistant section',
|
||
'organization-launch-not-configured': 'the business file has no launch block, so launch membership can\'t change',
|
||
'organization-no-change': 'the business file already says that',
|
||
'organization-project-mismatch': 'a project file\'s id differs from its key in the business file; mosaic business validate shows it',
|
||
'organization-unresolvable-instance': 'an instance wouldn\'t resolve against a project file; mosaic business validate shows why',
|
||
'revision-conflict': 'the business file changed since you read it. Read the role instances again',
|
||
};
|
||
async function instanceSend(req, res, { instancesWrite, preview, log }) {
|
||
let instance = null;
|
||
// The instance is quoted and cut short so a crafted value can't forge a log line. Vars are never logged.
|
||
const line = outcome => log(`${new Date().toISOString()} instance user=${JSON.stringify(preview.user)} instance=${quoted(instance)} ${outcome}`);
|
||
const refuse = (status, error, message, sent = false) => { line(`error=${error}`); return json(res, status, { error, message, sent }); };
|
||
if (!preview.tester && !signedIn(req, preview)) return json(res, 401, { error: 'sign-in required', message: 'sign in again', sent: false });
|
||
if (one(req, 'origin') !== ownOrigin(preview)) return refuse(403, 'cross-origin request refused', 'this needs the Console\'s own Origin');
|
||
if (one(req, 'sec-fetch-site') !== 'same-origin') return refuse(403, 'cross-site request refused', 'this needs same-origin Fetch Metadata');
|
||
let value;
|
||
try { value = JSON.parse((await body(req, 16384)).toString('utf8')); } catch (err) { return refuse(400, 'invalid-request', err.message); }
|
||
const has = key => Object.hasOwn(value, key);
|
||
if (Object.keys(value).some(key => !INSTANCE_KEYS.includes(key)) || typeof value.revision !== 'string' || !/^[a-f0-9]{64}$/.test(value.revision) ||
|
||
typeof value.instance !== 'string' || !['add', 'change'].includes(value.op) || (has('definition') && typeof value.definition !== 'string') ||
|
||
(has('vars') && (!value.vars || typeof value.vars !== 'object' || Array.isArray(value.vars))) || (has('launch') && typeof value.launch !== 'boolean')) {
|
||
return refuse(400, 'invalid-request', 'this takes a revision, an instance, op add or change, and a definition, vars or launch, nothing else');
|
||
}
|
||
({ instance } = value);
|
||
let result;
|
||
try { result = await instancesWrite(Object.fromEntries(INSTANCE_KEYS.filter(has).map(k => [k, value[k]]))); } catch (err) {
|
||
const { code, sent } = sendOutcome(err);
|
||
return sent === false
|
||
? refuse(busStatus(code), code, `${code}: ${Object.hasOwn(INSTANCE_REASONS, code) ? INSTANCE_REASONS[code] : 'refused by the bus'}. Nothing changed.`)
|
||
: refuse(503, 'outcome-unknown', 'the change may have been made; nothing was retried. Read the role instances again before trying', 'unknown');
|
||
}
|
||
const object = o => o && typeof o === 'object' && !Array.isArray(o);
|
||
if (!/^[a-f0-9]{64}$/.test(result?.revision ?? '') || typeof result.restart !== 'boolean' || !object(result.definitions) || !object(result.instances) || !result.instances[instance]) {
|
||
return refuse(503, 'outcome-unknown', 'the bus answered in an unexpected shape; the change may have been made. Read the role instances again before trying', 'unknown');
|
||
}
|
||
line(`done restart=${result.restart}`);
|
||
return json(res, 200, { ...result, at: new Date().toISOString() });
|
||
}
|
||
// Row 65 (mos-0840): the routing table. The Settings boundary and one bus call, `routes.set`,
|
||
// through the human transport. It is human-only and outside ORGANIZATION_KEYS, so the chief of
|
||
// staff's tool never reaches it. The bus checks the route rules; a refusal comes back with its code.
|
||
const ROUTE_KEYS = ['revision', 'routes'];
|
||
const ROUTE_REASONS = {
|
||
'harness-off': ['400', 'that harness isn\'t switched on in the business file\'s plugins.harness, which `mosaic plugins set` changes'],
|
||
'harness-refused': ['400', 'that harness module didn\'t load on the bus host, so its thinking levels are unknown'],
|
||
'thinking-unsupported': ['400', 'that harness doesn\'t apply that thinking level'],
|
||
'unknown-model': ['400', 'a model or fallback model isn\'t a key in the model table'],
|
||
'organization-partial-fallback': ['400', 'a fallback sets its harness, model and thinking together, or is cleared'],
|
||
'organization-unknown-instance': ['400', 'the business has no such instance'],
|
||
'organization-no-change': ['400', 'the business file already says that'],
|
||
'revision-conflict': ['409', 'the business file changed since you read it. Read the routes again'],
|
||
};
|
||
const routeObject = o => o && typeof o === 'object' && !Array.isArray(o);
|
||
const routesAnswer = v => /^[a-f0-9]{64}$/.test(v?.revision ?? '') && Array.isArray(v.harnesses) && Array.isArray(v.models) && routeObject(v.levels) && routeObject(v.instances);
|
||
async function routesSend(req, res, { routesWrite, preview, log }) {
|
||
// Instance names only; routes are never logged.
|
||
let names = [];
|
||
const line = outcome => log(`${new Date().toISOString()} routes user=${JSON.stringify(preview.user)} instances=${quoted(names.join(','))} ${outcome}`);
|
||
const refuse = (status, error, message, sent = false) => { line(`error=${error}`); return json(res, status, { error, message, sent }); };
|
||
if (!preview.tester && !signedIn(req, preview)) return json(res, 401, { error: 'sign-in required', message: 'sign in again', sent: false });
|
||
if (one(req, 'origin') !== ownOrigin(preview)) return refuse(403, 'cross-origin request refused', 'this needs the Console\'s own Origin');
|
||
if (one(req, 'sec-fetch-site') !== 'same-origin') return refuse(403, 'cross-site request refused', 'this needs same-origin Fetch Metadata');
|
||
let value;
|
||
try { value = JSON.parse((await body(req, 16384)).toString('utf8')); } catch (err) { return refuse(400, 'invalid-request', err.message); }
|
||
if (!routeObject(value) || Object.keys(value).some(key => !ROUTE_KEYS.includes(key)) || typeof value.revision !== 'string' || !/^[a-f0-9]{64}$/.test(value.revision) ||
|
||
!routeObject(value.routes) || Object.keys(value.routes).length === 0) {
|
||
return refuse(400, 'invalid-request', 'this takes a revision and routes by instance, nothing else');
|
||
}
|
||
names = Object.keys(value.routes);
|
||
let result;
|
||
try { result = await routesWrite({ revision: value.revision, routes: value.routes }); } catch (err) {
|
||
const { code, sent } = sendOutcome(err);
|
||
if (sent !== false) return refuse(503, 'outcome-unknown', 'the change may have been made; nothing was retried. Read the routes again before trying', 'unknown');
|
||
const [status, reason] = Object.hasOwn(ROUTE_REASONS, code) ? ROUTE_REASONS[code] : [String(busStatus(code)), 'refused by the bus'];
|
||
return refuse(Number(status), code, `${code}: ${reason}. Nothing changed.`);
|
||
}
|
||
if (!routesAnswer(result) || names.some(name => !result.instances[name])) {
|
||
return refuse(503, 'outcome-unknown', 'the bus answered in an unexpected shape; the change may have been made. Read the routes again before trying', 'unknown');
|
||
}
|
||
line('done');
|
||
return json(res, 200, { ...result, at: new Date().toISOString() });
|
||
}
|
||
// Row 148 (#1642): the spec and docs editor. Two reads and one save, all through the human transport.
|
||
// The save has the Settings boundary (header user, exact Origin, same-origin Fetch Metadata, JSON,
|
||
// strict keys) with a 1 MiB body on this route only; every other POST keeps its own smaller limit.
|
||
// The bus decides the path (spec/north-star.md and docs/*.md), the base commit and the author.
|
||
const FILE_SAVE_MAX = 1024 * 1024;
|
||
const FILE_SAVE_KEYS = ['project', 'path', 'base', 'content'];
|
||
const COMMIT = /^[0-9a-f]{40}$/;
|
||
const PATH_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,200}$/;
|
||
const quoted = value => JSON.stringify(typeof value === 'string' ? value.slice(0, 200) : null);
|
||
async function projectFileSend(req, res, { projectSave, preview, log }) {
|
||
let target = null;
|
||
// The project and path are quoted and cut short so a crafted value can't forge a log line. The content is never logged.
|
||
const line = outcome => log(`${new Date().toISOString()} project-file user=${JSON.stringify(preview.user)} project=${quoted(target?.project)} path=${quoted(target?.path)} ${outcome}`);
|
||
// `sent` tells the page which it was: false, nothing was written; 'unknown', it may have been.
|
||
const refuse = (status, error, message, sent = false) => { line(`error=${error}`); return json(res, status, { error, message, sent }); };
|
||
if (!signedIn(req, preview)) return json(res, 401, { error: 'sign-in required', message: 'sign in again', sent: false });
|
||
if (one(req, 'origin') !== ownOrigin(preview)) return refuse(403, 'cross-origin request refused', 'a save needs the Console\'s own Origin');
|
||
if (one(req, 'sec-fetch-site') !== 'same-origin') return refuse(403, 'cross-site request refused', 'a save needs same-origin Fetch Metadata');
|
||
let value;
|
||
try { value = JSON.parse((await body(req, FILE_SAVE_MAX)).toString('utf8')); } catch (err) { return refuse(400, 'invalid-request', err.message); }
|
||
if (Object.keys(value).length !== FILE_SAVE_KEYS.length || !FILE_SAVE_KEYS.every(k => typeof value[k] === 'string')) {
|
||
return refuse(400, 'invalid-request', 'a save takes project, path, base and content, all text, nothing else');
|
||
}
|
||
target = value;
|
||
let result;
|
||
try { result = await projectSave({ project: value.project, path: value.path, base: value.base, content: value.content }); } catch (err) {
|
||
const { code, sent } = sendOutcome(err);
|
||
return sent === false
|
||
? refuse(busStatus(code), code, code === 'stale-base' ? 'not saved: the file changed since you opened it. Reload it, then make your edit again.' : `not saved: the bus refused it (${code}).`)
|
||
: refuse(503, 'outcome-unknown', 'the save may have been made; nothing was retried. Reload the file before saving again', 'unknown');
|
||
}
|
||
if (!COMMIT.test(result?.commit) || result.path !== value.path) return refuse(503, 'outcome-unknown', 'the bus answered without the new commit; the save may have been made. Reload the file before saving again', 'unknown');
|
||
line(`commit=${result.commit}`);
|
||
return json(res, 200, { path: result.path, commit: result.commit, at: new Date().toISOString() });
|
||
}
|
||
// GET only. The bus is asked for a file list, or for one file with its current commit; a result
|
||
// that is not the expected shape is an invalid response, never passed on.
|
||
async function projectFileRead(res, read, path, search) {
|
||
const query = new URLSearchParams(search), file = path === '/api/project-file';
|
||
const keys = file ? ['project', 'path'] : ['project'];
|
||
if ([...query.keys()].some(k => !keys.includes(k)) || keys.some(k => query.getAll(k).length !== 1 || !PATH_SHAPE.test(query.get(k))))
|
||
return json(res, 400, { error: 'invalid-request', message: file ? 'a file read takes a project and a path' : 'a file list takes a project' });
|
||
if (!read) return json(res, 503, { error: 'not-configured', message: 'the Console has no bus configured' });
|
||
try {
|
||
const result = await read(Object.fromEntries(keys.map(k => [k, query.get(k)])));
|
||
const valid = file
|
||
? typeof result?.content === 'string' && COMMIT.test(result.commit) && COMMIT.test(result.head) && typeof result.path === 'string'
|
||
: COMMIT.test(result?.head) && Array.isArray(result.files) && result.files.every(f => typeof f?.path === 'string');
|
||
if (!valid) throw new BusReadError('invalid-response');
|
||
return json(res, 200, { ...result, at: new Date().toISOString() });
|
||
} catch (err) {
|
||
const code = err instanceof BusReadError ? err.code : 'invalid-response';
|
||
return json(res, busStatus(code), { error: code, message: err instanceof BusReadError ? err.message : code });
|
||
}
|
||
}
|
||
// `send` is the bus write (row 76): `args => Promise<{id}>`, only with the preview mode or `sso`.
|
||
// `sso` is createSso() from sso.mjs (Q175 phase 1): the human listener signs people in itself.
|
||
// `testerNoSignIn` makes the tester listener refuse anything that looks like a sign-in (--sso). `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.
|
||
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, testerNoSignIn = false, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, log = line => console.log(line), fieldsFile = undefined } = {}) {
|
||
if (!isLoopback(host)) throw new Error('refusing to bind to non-loopback host');
|
||
if (host === 'localhost') host = '127.0.0.1';
|
||
if (tester && preview !== null) throw new Error('tester listener cannot use preview mode');
|
||
if (tester && sso !== null) throw new Error('tester listener cannot use sso');
|
||
if (sso !== null && (preview !== null || proof !== null)) throw new Error('--sso cannot be combined with --auth-header, --allow-user or --proof-*');
|
||
if (tester && host !== '127.0.0.1') throw new Error('tester listener must bind 127.0.0.1');
|
||
// Row 177 (#1675): chat is allowed. The tester listener's chat binds the tester, so the bus keeps it on tester threads.
|
||
if (tester && [send, settingsWrite, projectSave, assistantStop].some(value => value !== null)) throw new Error('tester listener permits only instance, route, name and chat writes');
|
||
if (tester && !testerSocket) throw new Error('tester listener requires private socket');
|
||
if (!tester && testerSocket) throw new Error('tester socket requires tester listener');
|
||
const upstream = boardURL(board);
|
||
// An object with none of the three is refused too: asking for the preview never serves without it.
|
||
if (preview !== null && !(preview = previewOptions({ publicHost: preview.host, authHeader: preview.header, allowUser: preview.user }))) {
|
||
throw new Error('preview mode needs --public-host, --auth-header and --allow-user together');
|
||
}
|
||
if (proof !== null && (preview === null || tester)) throw new Error('proxy proof needs preview mode');
|
||
if (send !== null && ((preview === null && sso === null) || typeof send !== 'function')) throw new Error('--send needs the preview mode (--public-host, --auth-header and --allow-user) or --sso');
|
||
const server = createServer(async (req, res) => {
|
||
res.setHeader('x-content-type-options', 'nosniff');
|
||
res.setHeader('referrer-policy', 'no-referrer');
|
||
// Under --sso the Sign out form's POST is redirected to the provider's end-session endpoint, and
|
||
// browsers apply form-action to that redirect, so those origins (from discovery) are allowed too.
|
||
res.setHeader('content-security-policy', `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'${sso ? sso.formTargets().map(o => ` ${o}`).join('') : ''}`);
|
||
// Presence, even with an empty value: never turn the public listener into a tester ingress.
|
||
if (!tester && Object.hasOwn(req.headers, 'x-mosaic-tester')) return json(res, 403, { error: 'tester listener required' });
|
||
if (tester && testerAuthHeader && Object.hasOwn(req.headers, testerAuthHeader.toLowerCase())) return json(res, 403, { error: 'proxy header refused' });
|
||
if (tester && testerProofHeader && Object.hasOwn(req.headers, testerProofHeader.toLowerCase())) return json(res, 403, { error: 'proxy proof header refused' });
|
||
if (tester && (Object.hasOwn(req.headers, 'authorization') || SIGN_IN_COOKIE.test(req.headers.cookie ?? '') || Object.keys(req.headers).some(h => h.startsWith('x-authentik-')))) return json(res, 403, { error: 'tester listener takes no sign-in' });
|
||
let path, search;
|
||
// Node keeps the first of repeated Host headers; a second one (a loopback Host, then NAME) is
|
||
// never legitimate, so it is refused before any check reads the Host.
|
||
if ((req.headersDistinct.host?.length ?? 0) > 1) return json(res, 400, { error: 'repeated Host refused' });
|
||
// Preview mode: a request for the public name, exactly, as the proxy forwards it.
|
||
const named = preview !== null ? (req.headers.host ?? '').toLowerCase() === preview.host : sso !== null && (req.headers.host ?? '').toLowerCase() === sso.publicHost;
|
||
// The proof precedes every auth-header read, including the wrong-Host fence.
|
||
if (proof !== null) {
|
||
const values = req.headersDistinct[proof.header];
|
||
if (!named && values) return json(res, 403, { error: 'proxy proof Host refused' });
|
||
if (named) {
|
||
const value = values?.length === 1 ? Buffer.from(values[0], 'utf8') : null;
|
||
if (!value || value.length !== proof.value.length || !timingSafeEqual(value, proof.value)) {
|
||
return json(res, 401, { error: 'proxy proof required' });
|
||
}
|
||
}
|
||
}
|
||
// HEADER with any other Host comes from a proxy that rewrote Host (nginx's default) and would
|
||
// otherwise land on the loopback path unchecked. The operator's browser never sends it.
|
||
if (preview !== null && !named && req.headersDistinct[preview.header]) return json(res, 403, { error: 'proxy Host refused', message: 'the proxy must forward Host unchanged' });
|
||
try {
|
||
if (tester) {
|
||
if (req.headers.host !== new URL(TESTER_ORIGIN).host) return json(res, 403, { error: 'non-local Host refused' });
|
||
} else if (!named) {
|
||
const authority = new URL(`http://${req.headers.host}`);
|
||
if (!isLoopback(authority.hostname.replace(/^\[|\]$/g, '')) || Number(authority.port || 80) !== server.address().port) return json(res, 403, { error: 'non-local Host refused' });
|
||
}
|
||
({ pathname: path, search } = new URL(req.url, 'http://localhost'));
|
||
} catch { return json(res, 400, { error: 'invalid URL' }); }
|
||
// Under --sso the human listener serves only the public Host, whatever its port; GET /healthz
|
||
// alone stays open on a loopback Host for the status and release gates (Q-C).
|
||
if (sso !== null && !named && !(path === '/healthz' && req.method === 'GET')) return json(res, 403, { error: 'public Host required' });
|
||
// No CORS. JSON content type and same-origin checks keep browser forms out.
|
||
if (req.headers.origin && req.headers.origin !== (named ? (sso ? sso.publicOrigin : `https://${preview.host}`) : `http://${req.headers.host}`)) return json(res, 403, { error: 'cross-origin request refused' });
|
||
let signer = preview;
|
||
if (sso !== null && named) {
|
||
if (path.startsWith('/auth/')) return sso.handle(req, res, path, search);
|
||
// Only a page load or a write keeps a session alive; the page's background reads don't (Q-D).
|
||
const session = path === '/healthz' ? null : sso.session(req, { touch: req.method === 'POST' || (req.method === 'GET' && !path.startsWith('/api/')) });
|
||
if (!session && path !== '/healthz') {
|
||
if (path.startsWith('/api/') || req.method !== 'GET') return json(res, 401, { error: 'sign-in required' });
|
||
res.writeHead(303, { location: `/auth/login?return=${encodeURIComponent(path + search)}`, 'cache-control': 'no-store' });
|
||
return res.end();
|
||
}
|
||
if (session) signer = { sso: true, user: session.name, host: sso.publicHost, origin: sso.publicOrigin };
|
||
}
|
||
if (named && preview !== null) {
|
||
// One value, equal to the user id; the proxy strips client copies and sets it after sign-in.
|
||
const values = req.headersDistinct[preview.header];
|
||
if (!values || values.length !== 1 || values[0] !== preview.user) return json(res, 401, { error: 'sign-in required' });
|
||
}
|
||
const writer = tester ? { tester: true, user: 'tester', origin: TESTER_ORIGIN } : signer;
|
||
if (tester && !['GET', 'HEAD'].includes(req.method) && !['/api/instances', '/api/routes', '/api/name'].includes(path) && !TESTER_CHAT_WRITE.test(path))
|
||
return json(res, 403, { error: 'read-only', sent: false });
|
||
if(path==='/api/settings'&&req.method==='POST'){
|
||
if(!send||!settingsWrite||!named)return json(res,403,{error:'read-only',sent:false});
|
||
return settingsSend(req,res,{settingsWrite,preview:signer,log});
|
||
}
|
||
if (Object.hasOwn(SEAT_ROUTES, path)) {
|
||
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
|
||
const write = path === '/api/name' ? nameWrite : assistantStop;
|
||
if ((!tester && (!send || !named)) || !write) return json(res, 403, { error: 'read-only', sent: false });
|
||
return seatSend(req, res, { route: SEAT_ROUTES[path], write, preview: writer, log });
|
||
}
|
||
if (path === '/api/instances') {
|
||
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
|
||
if ((!tester && (!send || !named)) || !instancesWrite) return json(res, 403, { error: 'read-only', sent: false });
|
||
return instanceSend(req, res, { instancesWrite, preview: writer, log });
|
||
}
|
||
if (path === '/api/routes') {
|
||
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
|
||
if ((!tester && (!send || !named)) || !routesWrite) return json(res, 403, { error: 'read-only', sent: false });
|
||
return routesSend(req, res, { routesWrite, preview: writer, log });
|
||
}
|
||
if (path === '/api/project-file' && req.method === 'POST') {
|
||
if (!send || !projectSave || !named) return json(res, 403, { error: 'read-only', sent: false });
|
||
return projectFileSend(req, res, { projectSave, preview: signer, log });
|
||
}
|
||
// Message sending has its own bounded payload and repeats the identity check.
|
||
if (send && path === '/api/bus/message') {
|
||
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
|
||
return busSend(req, res, { send, preview: signer, log });
|
||
}
|
||
if (path === '/api/chat' || path.startsWith('/api/chat/')) {
|
||
return chatHTTP(req, res, { path, search, chat, named, send, preview: writer, log });
|
||
}
|
||
// Nothing else but GET and HEAD gets past here in preview mode, whatever the Host.
|
||
if ((preview !== null || sso !== null) && req.method !== 'GET' && req.method !== 'HEAD') return json(res, 403, { error: 'read-only', message: 'the Console preview is read-only' });
|
||
// The conversation routes (#1507, CHAT-02) keep their query; the board validates it.
|
||
const conversation = path === '/api/conversations' || path === '/api/conversation';
|
||
const allowed = path === '/api/board' || conversation ? 'GET' : ['/api/seen', '/api/reply'].includes(path) ? 'POST' : null;
|
||
if (allowed) {
|
||
if (req.method !== allowed) return json(res, 405, { error: 'method not allowed' });
|
||
let bytes;
|
||
if (allowed === 'POST') {
|
||
try { bytes = await body(req); } catch (err) { return json(res, 400, { error: err.message }); }
|
||
}
|
||
try {
|
||
const response = await fetch(upstream + path + (conversation ? search : ''), {
|
||
method: allowed, headers: bytes ? { 'content-type': 'application/json' } : {}, body: bytes,
|
||
redirect: 'error', signal: AbortSignal.timeout(timeout),
|
||
});
|
||
const text = await response.text();
|
||
JSON.parse(text); // Never serve upstream HTML or scripts as API data.
|
||
res.writeHead(response.status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
||
return res.end(text);
|
||
} catch {
|
||
return json(res, 502, { error: `Board unreachable or invalid response at ${upstream}. Check the board server. No automatic action retry.`, board: upstream });
|
||
}
|
||
}
|
||
if (path.startsWith('/api/bus/')) {
|
||
const verb = path.slice('/api/bus/'.length);
|
||
if (!BUS_VERBS.includes(verb)) return json(res, 404, { error: 'not found' });
|
||
if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' });
|
||
return busRead(res, bus, verb, search);
|
||
}
|
||
if (path === '/api/task-fields') {
|
||
if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' });
|
||
return consoleRead(res, () => fieldTable(fieldsFile));
|
||
}
|
||
if (path === '/api/project-files' || path === '/api/project-file') {
|
||
if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' });
|
||
return projectFileRead(res, path === '/api/project-file' ? projectFile : projectFiles, path, search);
|
||
}
|
||
if (path === '/api/queue' || path.startsWith('/api/queue/') || path === '/api/business' || path === '/api/settings' || path === '/api/bus-status') {
|
||
if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' });
|
||
const a = server.address(), address = `http://${a.family === 'IPv6' ? `[${a.address}]` : a.address}:${a.port}/`;
|
||
if (path === '/api/settings') return consoleRead(res, async () => ({ ...(reads ? await reads.settings() : { release: null, business: null, notifier: { refused: 'not-configured', message: 'the Console has no reads configured' } }), board: upstream, address }));
|
||
if (!reads) return json(res, 503, { error: 'not-configured', message: 'the Console has no reads configured' });
|
||
if (path === '/api/business') return consoleRead(res, () => reads.business());
|
||
if (path === '/api/bus-status') return consoleRead(res, () => reads.busStatus());
|
||
if (path === '/api/queue') return consoleRead(res, () => reads.queue());
|
||
const id = path.slice('/api/queue/'.length);
|
||
if (!QUEUE_ID.test(id)) return json(res, 400, { error: 'invalid-request', message: 'a queue row id is a positive integer' });
|
||
return consoleRead(res, () => reads.row(Number(id)));
|
||
}
|
||
if (req.method !== 'GET' && req.method !== 'HEAD') return json(res, 405, { error: 'method not allowed' });
|
||
// `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.
|
||
if (path === '/api/config') return json(res, 200, { board: upstream, ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), send: !tester && Boolean(send) && named, edit: !tester && Boolean(send) && Boolean(projectSave) && 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);
|
||
if (!file) return json(res, 404, { error: 'not found' });
|
||
try {
|
||
const content = readFileSync(resolve(root, file[0]));
|
||
res.writeHead(200, { 'content-type': file[1], 'cache-control': 'no-store' });
|
||
res.end(req.method === 'HEAD' ? undefined : content);
|
||
} catch { json(res, 500, { error: 'WebUI asset unavailable' }); }
|
||
});
|
||
if (tester) return bindTesterSocket(server, testerSocket);
|
||
return new Promise((resolvePromise, reject) => {
|
||
server.once('error', reject);
|
||
server.listen(port, host, () => { server.off('error', reject); resolvePromise(server); });
|
||
});
|
||
}
|