// SoftwareCannery brintOS image server + loader control plane. // HTTPS + Basic Auth, COOP/COEP for SAB, plus /loader/* SSE push channel so we // can push a station image to a specific phone over WiFi. // // 2026-11-10: every request now runs inside a try/catch (a malformed %-escape or // JSON body used to throw out of the async handler and take the whole process // down), /station// directory URLs fall back to index.html, and process-level // error hooks log instead of exiting. Run under systemd (sc-loader.service). import https from 'node:https'; import * as LIMIT_FS from 'node:fs'; import { readFile } from 'node:fs/promises'; import { extname, join, normalize } from 'node:path'; import { fileURLToPath } from 'node:url'; import { handleInspect } from './inspect-agent.mjs'; const ROOT = fileURLToPath(new URL('./dist/', import.meta.url)); const PORT = process.env.PORT || 8443; const USER = process.env.BRINTOS_USER || 'softwarecannery'; const PASS = process.env.BRINTOS_PASS || ''; const KEY = process.env.TLS_KEY || './tls/key.pem'; const CRT = process.env.TLS_CRT || './tls/cert.pem'; if (!PASS) { console.error('Set BRINTOS_PASS='); process.exit(1); } const TYPES = { '.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.wasm':'application/wasm','.json':'application/json','.png':'image/png','.css':'text/css','.svg':'image/svg+xml','.webmanifest':'application/manifest+json','.crt':'application/x-x509-ca-cert','.pem':'application/x-x509-ca-cert' }; const AUTH = 'Basic ' + Buffer.from(`${USER}:${PASS}`).toString('base64'); const COOP = { 'cross-origin-opener-policy': 'same-origin', 'cross-origin-embedder-policy': 'require-corp', 'cross-origin-resource-policy': 'cross-origin', 'x-content-type-options': 'nosniff', }; // ---- loader control plane (in-memory) ---- const phones = new Map(); // id -> { res, name, lastSeen, station } const sseWrite = (res, event, data) => { try { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); } catch {} }; function readBody(req, limit = 64 * 1024) { return new Promise((resolve, reject) => { let b = ''; req.on('data', c => { b += c; if (b.length > limit) { reject(new Error('body too large')); req.destroy(); } }); req.on('end', () => resolve(b)); req.on('error', reject); }); } async function readJson(req) { const raw = await readBody(req); if (!raw) return {}; const v = JSON.parse(raw); // throws -> 400 via the outer catch if (!v || typeof v !== 'object') throw new Error('body must be a JSON object'); return v; } const json = (res, code, obj) => { res.writeHead(code, { 'content-type':'application/json', ...COOP }); res.end(JSON.stringify(obj)); }; // Login only on the control endpoints; images, station pages and the phone's // loader channel (/loader/events, /loader/state) are served openly (2026-11-12). const OFFICE_IPS = (process.env.OFFICE_IPS || '76.171.180.139').split(',').map(x => x.trim()); const PROTECTED = (p) => false; // 2026-11-13: no login anywhere (Kent). Old rule in .bak-2026-11-13-nologin // Inspection limit: outside the office, at most INSPECT_DAY_MAX AI calls per UTC day in total // and INSPECT_HOUR_MAX per IP per hour. The office IP is never limited. Counts survive restarts. const INSPECT_DAY_MAX = +(process.env.INSPECT_DAY_MAX || 100), INSPECT_HOUR_MAX = +(process.env.INSPECT_HOUR_MAX || 30); const LIMIT_FILE = './inspect-limit.json'; let LIM = { day: '', n: 0, ips: {} }; try { LIM = JSON.parse(LIMIT_FS.readFileSync(LIMIT_FILE, 'utf8')); } catch {} function inspectLimit(ip) { const now = Date.now(), day = new Date(now).toISOString().slice(0, 10); if (LIM.day !== day) LIM = { day, n: 0, ips: {} }; const hits = (LIM.ips[ip] || []).filter((t) => now - t < 3600e3); if (LIM.n >= INSPECT_DAY_MAX) return `daily inspection limit reached (${INSPECT_DAY_MAX} outside the office); resets at 00:00 UTC`; if (hits.length >= INSPECT_HOUR_MAX) return `hourly inspection limit reached (${INSPECT_HOUR_MAX} per device); try again later`; hits.push(now); LIM.ips[ip] = hits; LIM.n++; try { LIMIT_FS.writeFileSync(LIMIT_FILE, JSON.stringify(LIM)); } catch {} return ''; } async function handle(req, res) { let pp = '/'; try { pp = decodeURIComponent(new URL(req.url, 'https://x').pathname); } catch {} // The office network (its public IP) may use the inspector without a login. const ip = String(req.socket.remoteAddress || '').replace(/^::ffff:/, ''); const officeOK = OFFICE_IPS.includes(ip) && pp.startsWith('/inspect/'); if (PROTECTED(pp) && !officeOK && req.headers.authorization !== AUTH) { res.writeHead(401, { 'www-authenticate': 'Basic realm="brintOS"', 'content-type': 'text/plain' }); res.end('auth required'); return; } const url = new URL(req.url, 'https://x'); const p = decodeURIComponent(url.pathname); // throws on a bad %-escape -> 400 // --- loader endpoints --- if (p === '/loader/events') { // phone opens SSE stream const id = (url.searchParams.get('phone') || 'anon').slice(0, 64); const name = (url.searchParams.get('name') || id).slice(0, 64); res.writeHead(200, { 'content-type':'text/event-stream','cache-control':'no-cache','connection':'keep-alive', ...COOP }); const rec = { res, name, lastSeen: Date.now(), station: null }; phones.set(id, rec); sseWrite(res, 'hello', { id, name }); const ping = setInterval(() => { rec.lastSeen = Date.now(); try { res.write(': ping\n\n'); } catch {} }, 20000); req.on('close', () => { clearInterval(ping); if (phones.get(id) === rec) phones.delete(id); }); return; } if (p === '/loader/push' && req.method === 'POST') { // dashboard -> phone const { phone, station, url: boot } = await readJson(req); const targets = phone === '*' ? [...phones.keys()] : [String(phone)]; let sent = 0; for (const id of targets) { const r = phones.get(id); if (r) { sseWrite(r.res, 'boot', { station, url: boot }); sent++; } } json(res, 200, { sent }); return; } if (p === '/loader/state' && req.method === 'POST') { // phone reports what it booted const { phone, station } = await readJson(req); const r = phones.get(String(phone)); if (r) { r.station = station; r.lastSeen = Date.now(); } json(res, 200, {}); return; } if (p === '/loader/phones') { // dashboard lists phones json(res, 200, [...phones.entries()].map(([id, r]) => ({ id, name: r.name, station: r.station, lastSeen: r.lastSeen }))); return; } // --- inspection limit (2026-11-13): AI calls from outside the office are capped --- if (req.method === 'POST' && (p === '/inspect/analyze' || p === '/inspect/feedback')) { const ip = String(req.socket.remoteAddress || '').replace(/^::ffff:/, ''); if (!OFFICE_IPS.includes(ip)) { const why = inspectLimit(ip); if (why) { console.log(`[limit] ${ip} ${p} refused: ${why}`); json(res, 429, { ok: false, error: why }); return; } } } // --- board inspector agent (Claude vision) --- if (p.startsWith('/inspect/') && await handleInspect(req, res, p, url, json)) return; // --- static files --- let fp = p === '/' || p === '' ? '/loader.html' : p; // loader is the landing page if (fp.endsWith('/')) fp += 'index.html'; // /station// -> its index.html const file = normalize(join(ROOT, fp)); const h = { ...COOP, 'cache-control': 'no-store' }; if (!file.startsWith(ROOT)) { res.writeHead(403, h); res.end(); return; } try { h['content-type'] = TYPES[extname(file)] || 'application/octet-stream'; // Pre-compressed twin beside the file (precompress.mjs): serve it with Content-Encoding when accepted. const ae = String(req.headers['accept-encoding'] || ''); for (const [enc, ext] of [['br', '.br'], ['gzip', '.gz']]) { if (!ae.includes(enc)) continue; try { const body = await readFile(file + ext); res.writeHead(200, { ...h, 'content-encoding': enc, 'vary': 'accept-encoding' }); res.end(body); return; } catch {} } const body = await readFile(file); res.writeHead(200, h); res.end(body); } catch { res.writeHead(404, { 'content-type':'text/plain', ...h }); res.end('404 ' + fp); } } const [key, cert] = await Promise.all([readFile(KEY), readFile(CRT)]); const server = https.createServer({ key, cert }, async (req, res) => { try { await handle(req, res); } catch (e) { console.error('[req error]', req.method, req.url, e && e.message || e); try { if (!res.headersSent) res.writeHead(400, { 'content-type': 'text/plain', ...COOP }); res.end('bad request'); } catch {} } }); server.on('clientError', (e, sock) => { try { sock.end('HTTP/1.1 400 Bad Request\r\n\r\n'); } catch {} }); process.on('uncaughtException', e => console.error('[uncaught]', e && e.stack || e)); process.on('unhandledRejection', e => console.error('[unhandled]', e && e.stack || e)); server.listen(PORT, '0.0.0.0', () => console.log(`brintOS image+loader server https://0.0.0.0:${PORT} user=${USER}`));