cohorte 3.1.3 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,544 @@
1
+ "use strict";
2
+ // cohorte ui — a local dashboard over every project registered in the registry.
3
+ //
4
+ // Security model (this origin will launch commands in a later release, so it is hardened now):
5
+ // - listens on 127.0.0.1 only;
6
+ // - every /api request needs the session token (Authorization: Bearer), a loopback Host (DNS
7
+ // rebinding) and, when the browser sends one, an Origin equal to this server's own;
8
+ // - state-changing requests must be application/json (a cross-site form cannot send that);
9
+ // - reads address a project by the id of a REGISTERED project, never by a path;
10
+ // - the page is served with a strict CSP and renders project content with textContent only.
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.create = create;
49
+ const fs_1 = __importDefault(require("fs"));
50
+ const http_1 = __importDefault(require("http"));
51
+ const path_1 = __importDefault(require("path"));
52
+ const crypto_1 = __importDefault(require("crypto"));
53
+ const child_process_1 = require("child_process");
54
+ const legacy_1 = require("./legacy");
55
+ const jobs_1 = require("./jobs");
56
+ const runs_1 = require("./runs");
57
+ const history_1 = require("./history");
58
+ const gitinfo = __importStar(require("./gitinfo"));
59
+ const ops = __importStar(require("./ops"));
60
+ const docker = __importStar(require("./docker"));
61
+ const pipeline_1 = require("./pipeline");
62
+ const findings_1 = require("./findings");
63
+ const { state, scanSpecs } = legacy_1.doctor;
64
+ const pkgRoot = legacy_1.repo;
65
+ const PUBLIC = path_1.default.join(legacy_1.uiDir, 'dist-web');
66
+ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.json': 'application/json; charset=utf-8', '.ico': 'image/x-icon' };
67
+ const CSP = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
68
+ const REPORT_KINDS = ['readiness', 'build', 'verdict', 'verify', 'loop'];
69
+ const SPEC_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/;
70
+ const MAX_BODY = 16 * 1024;
71
+ // A small TTL cache keyed by string; concurrent callers share one in-flight computation.
72
+ function memo(ttlMs) {
73
+ const m = new Map();
74
+ const run = (key, fn) => {
75
+ const hit = m.get(key);
76
+ if (hit && (hit.pending || Date.now() - hit.at < ttlMs))
77
+ return hit.value;
78
+ const value = Promise.resolve().then(fn);
79
+ const entry = { at: Date.now(), value, pending: true };
80
+ m.set(key, entry);
81
+ value.then(() => { entry.pending = false; entry.at = Date.now(); }, () => m.delete(key));
82
+ return value;
83
+ };
84
+ run.clear = (key) => m.delete(key);
85
+ return run;
86
+ }
87
+ function runMetrics(root, args) {
88
+ return new Promise((resolve, reject) => {
89
+ const script = path_1.default.join(pkgRoot, 'scripts', 'metrics', 'collect.mjs');
90
+ const child = (0, child_process_1.spawn)(process.execPath, [script, root, '--json', ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
91
+ let out = '';
92
+ child.stdout.on('data', (d) => { out += d; });
93
+ const timer = setTimeout(() => { child.kill(); reject(new Error('metrics timed out')); }, 60000);
94
+ child.on('error', (e) => { clearTimeout(timer); reject(e); });
95
+ child.on('close', (code) => {
96
+ clearTimeout(timer);
97
+ if (code !== 0)
98
+ return reject(new Error(`metrics exited ${code}`));
99
+ try {
100
+ resolve(JSON.parse(out));
101
+ }
102
+ catch {
103
+ reject(new Error('metrics returned no JSON'));
104
+ }
105
+ });
106
+ });
107
+ }
108
+ function readJson(p) { try {
109
+ return JSON.parse(fs_1.default.readFileSync(p, 'utf8'));
110
+ }
111
+ catch {
112
+ return null;
113
+ } }
114
+ function create({ globalDir, version, token = crypto_1.default.randomBytes(24).toString('hex'), storePath }) {
115
+ const cacheDoctor = memo(8000);
116
+ const cacheMetrics = memo(60000);
117
+ const jobs = new jobs_1.Jobs();
118
+ const runs = new runs_1.Runs({ store: new history_1.RunStore(path_1.default.join(globalDir, 'cohorte-ui', 'runs')) });
119
+ const cachePulls = memo(60000);
120
+ let ghOk = null;
121
+ // --- live updates: change NOTICES (not payloads) pushed over one authenticated event stream, coalesced ---
122
+ const subs = new Set();
123
+ const queued = new Map();
124
+ let flushTimer = null;
125
+ const notify = (e) => {
126
+ if (!subs.size)
127
+ return;
128
+ queued.set(`${e.type}:${e.id}`, e);
129
+ if (flushTimer)
130
+ return;
131
+ flushTimer = setTimeout(() => {
132
+ flushTimer = null;
133
+ const batch = [...queued.values()];
134
+ queued.clear();
135
+ const frame = `data: ${JSON.stringify(batch)}\n\n`;
136
+ for (const r of subs) {
137
+ try {
138
+ r.write(frame);
139
+ }
140
+ catch {
141
+ subs.delete(r);
142
+ }
143
+ }
144
+ }, 120);
145
+ };
146
+ jobs.onChange = (j) => notify({ type: 'job', projectId: j.projectId, id: j.id, status: j.status });
147
+ runs.onChange = (r) => notify({ type: 'run', projectId: r.projectId, id: r.id, status: r.status, pending: r.pending.size });
148
+ let origin = null; // set once listening
149
+ const doctorOf = (root) => cacheDoctor(root, () => state({ projectRoot: root, globalDir, cliVersion: version, offline: true }));
150
+ async function summary(p) {
151
+ const base = { id: p.id, root: p.root, name: path_1.default.basename(p.root), addedAt: p.addedAt };
152
+ if (!fs_1.default.existsSync(p.root))
153
+ return { ...base, missing: true };
154
+ try {
155
+ const s = await doctorOf(p.root);
156
+ const counts = {};
157
+ for (const sp of s.specs)
158
+ counts[sp.status || 'unknown'] = (counts[sp.status || 'unknown'] || 0) + 1;
159
+ return { ...base, missing: false, title: s.profile && s.profile.name || base.name,
160
+ oneLiner: s.profile && s.profile.one_liner || '', summary: s.summary, specCounts: counts,
161
+ specTotal: s.specs.length, core: s.versions && s.versions.core || null };
162
+ }
163
+ catch (e) {
164
+ return { ...base, missing: false, error: String(e?.message || e) };
165
+ }
166
+ }
167
+ async function detail(p) {
168
+ const s = await doctorOf(p.root);
169
+ const specs = legacy_1.report.specRecords(p.root, scanSpecs).map((sp) => ({ ...sp, pipeline: (0, pipeline_1.pipelineOf)(p.root, sp) }));
170
+ const wt = legacy_1.registry.worktrees(p.root);
171
+ const dev = ops.devInfo(p.root);
172
+ const scripts = ops.isolationScripts(p.root);
173
+ const withDev = wt.map((w, i) => { const j = jobs.find(p.id, 'dev', w.path); return { ...w, main: i === 0, dev: j ? jobs.view(j) : null }; });
174
+ return { id: p.id, root: p.root, name: path_1.default.basename(p.root), doctor: s, specs, worktrees: withDev,
175
+ dev: { command: dev.command, ready: dev.ready }, isolation: scripts,
176
+ docker: (() => { const c = docker.composeFile(p.root); return c ? { file: c.rel } : null; })(),
177
+ runs: runs.forProject(p.id).map((r) => runs.view(r)) };
178
+ }
179
+ function specDetail(p, specId) {
180
+ if (!SPEC_ID.test(specId))
181
+ return null;
182
+ const spec = scanSpecs(p.root).find((s) => s.id === specId);
183
+ if (!spec)
184
+ return null;
185
+ let body = '';
186
+ try {
187
+ body = fs_1.default.readFileSync(path_1.default.join(p.root, 'specs', path_1.default.basename(spec.file)), 'utf8');
188
+ }
189
+ catch { /* listed, then removed */ }
190
+ const reports = {};
191
+ for (const k of REPORT_KINDS)
192
+ reports[k] = readJson(path_1.default.join(p.root, 'specs', 'reports', `${specId}.${k}.json`));
193
+ let raw = '';
194
+ try {
195
+ raw = fs_1.default.readFileSync(path_1.default.join(p.root, 'specs', 'reports', `${specId}.md`), 'utf8').slice(0, 200000);
196
+ }
197
+ catch { /* no review report yet */ }
198
+ return { spec: spec, body: body.slice(0, 200000), reports, pipeline: (0, pipeline_1.pipelineOf)(p.root, spec), review: { ...(0, findings_1.parseReviewReport)(raw), raw } };
199
+ }
200
+ // --- http plumbing -------------------------------------------------------
201
+ const send = (res, code, obj) => {
202
+ const body = JSON.stringify(obj);
203
+ res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
204
+ res.end(body);
205
+ };
206
+ const fail = (res, code, message) => send(res, code, { error: message });
207
+ function hostOk(req) {
208
+ const h = String(req.headers.host || '');
209
+ return /^(127\.0\.0\.1|localhost|\[::1\]):\d+$/.test(h);
210
+ }
211
+ function tokenOk(req) {
212
+ const m = /^Bearer (.+)$/.exec(String(req.headers.authorization || ''));
213
+ if (!m)
214
+ return false;
215
+ const a = Buffer.from(m[1]);
216
+ const b = Buffer.from(token);
217
+ return a.length === b.length && crypto_1.default.timingSafeEqual(a, b);
218
+ }
219
+ function readBody(req) {
220
+ return new Promise((resolve, reject) => {
221
+ let n = 0;
222
+ const chunks = [];
223
+ req.on('data', (c) => { n += c.length; if (n > MAX_BODY) {
224
+ reject(new Error('body too large'));
225
+ req.destroy();
226
+ }
227
+ else
228
+ chunks.push(c); });
229
+ req.on('end', () => { try {
230
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
231
+ }
232
+ catch {
233
+ reject(new Error('invalid JSON'));
234
+ } });
235
+ req.on('error', reject);
236
+ });
237
+ }
238
+ async function api(req, res, url) {
239
+ const method = req.method;
240
+ const parts = url.pathname.split('/').filter(Boolean).slice(1); // drop "api"
241
+ if (method === 'POST' || method === 'DELETE') {
242
+ if (method === 'POST' && !/^application\/json\b/i.test(String(req.headers['content-type'] || '')))
243
+ return fail(res, 415, 'application/json required');
244
+ }
245
+ if (parts[0] === 'state' && method === 'GET') {
246
+ const list = legacy_1.registry.load(globalDir);
247
+ const out = { version, projects: await Promise.all(list.map(summary)) };
248
+ return send(res, 200, out);
249
+ }
250
+ if (parts[0] === 'stream' && method === 'GET') {
251
+ res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', Connection: 'keep-alive', 'X-Content-Type-Options': 'nosniff' });
252
+ res.write(': cohorte ui\n\n');
253
+ subs.add(res);
254
+ const beat = setInterval(() => { try {
255
+ res.write(': keep-alive\n\n');
256
+ }
257
+ catch { /* closed */ } }, 20000);
258
+ beat.unref();
259
+ req.on('close', () => { clearInterval(beat); subs.delete(res); });
260
+ return;
261
+ }
262
+ if (parts[0] === 'activity' && method === 'GET') {
263
+ const names = new Map(legacy_1.registry.load(globalDir).map((p) => [p.id, path_1.default.basename(p.root)]));
264
+ const items = [];
265
+ for (const j of jobs.jobs.values())
266
+ if (jobs.isLive(j) && names.has(j.projectId))
267
+ items.push({ projectId: j.projectId, projectName: names.get(j.projectId), kind: j.kind === 'dev' ? 'dev' : j.kind.startsWith('docker') ? 'docker' : 'job', id: j.id, label: j.label, status: j.status, pending: 0, startedAt: j.startedAt });
268
+ for (const r of runs.runs.values())
269
+ if ((r.status === 'running' || r.pending.size) && names.has(r.projectId))
270
+ items.push({ projectId: r.projectId, projectName: names.get(r.projectId), kind: 'run', id: r.id, label: r.command, status: r.status, pending: r.pending.size, startedAt: r.startedAt });
271
+ return send(res, 200, { items });
272
+ }
273
+ if (parts[0] === 'commands' && method === 'GET')
274
+ return send(res, 200, { commands: ops.listCommands(globalDir) });
275
+ if (parts[0] === 'discover' && method === 'GET') {
276
+ return send(res, 200, { suggestions: legacy_1.registry.discover(globalDir, storePath) });
277
+ }
278
+ if (parts[0] === 'projects' && parts.length === 1 && method === 'POST') {
279
+ let body;
280
+ try {
281
+ body = await readBody(req);
282
+ }
283
+ catch (e) {
284
+ return fail(res, 400, e.message);
285
+ }
286
+ try {
287
+ const r = legacy_1.registry.add(globalDir, body.path);
288
+ return send(res, r.created ? 201 : 200, { project: await summary(r.project), created: r.created });
289
+ }
290
+ catch (e) {
291
+ if (e instanceof legacy_1.registry.RegistryError)
292
+ return fail(res, 400, e.message);
293
+ throw e;
294
+ }
295
+ }
296
+ if (parts[0] === 'projects' && parts[1]) {
297
+ const p = legacy_1.registry.get(globalDir, parts[1]);
298
+ if (!p)
299
+ return fail(res, 404, 'unknown project');
300
+ if (parts.length === 2 && method === 'DELETE') {
301
+ legacy_1.registry.remove(globalDir, p.id);
302
+ return send(res, 200, { removed: true });
303
+ }
304
+ if (!fs_1.default.existsSync(p.root))
305
+ return fail(res, 410, `${p.root} no longer exists — remove it from the list`);
306
+ if (parts.length === 2 && method === 'GET')
307
+ return send(res, 200, await detail(p));
308
+ if (parts[2] === 'jobs') {
309
+ if (parts.length === 3 && method === 'GET')
310
+ return send(res, 200, { jobs: jobs.forProject(p.id).map((j) => jobs.view(j)) });
311
+ const job = parts[3] && jobs.get(parts[3]);
312
+ if (!job || job.projectId !== p.id)
313
+ return fail(res, 404, 'unknown job');
314
+ if (parts[4] === 'logs' && method === 'GET')
315
+ return send(res, 200, jobs.view(job, Math.max(0, parseInt(url.searchParams.get('since') ?? '', 10) || 0)));
316
+ if (parts[4] === 'stop' && method === 'POST')
317
+ return send(res, 200, { stopped: ops.stopJob(jobs, p, job.id) });
318
+ }
319
+ if (parts[2] === 'runs') {
320
+ if (parts.length === 3 && method === 'GET')
321
+ return send(res, 200, { runs: runs.forProject(p.id).map((r) => runs.view(r)) });
322
+ if (parts.length === 3 && method === 'POST') {
323
+ let body;
324
+ try {
325
+ body = await readBody(req);
326
+ }
327
+ catch (e) {
328
+ return fail(res, 400, e.message);
329
+ }
330
+ try {
331
+ return send(res, 202, { run: runs.view(ops.startRun(runs, p, globalDir, body), 0) });
332
+ }
333
+ catch (e) {
334
+ if (e instanceof ops.OpError)
335
+ return send(res, e.code, { error: e.message, untrusted: e.untrusted || false, fix: e.fix });
336
+ throw e;
337
+ }
338
+ }
339
+ const run = parts[3] && runs.get(parts[3]);
340
+ if (!run || run.projectId !== p.id)
341
+ return fail(res, 404, 'unknown run');
342
+ if (parts.length === 4 && method === 'GET')
343
+ return send(res, 200, runs.view(run, Math.max(0, parseInt(url.searchParams.get('since') ?? '', 10) || 0)));
344
+ if (parts[4] === 'stop' && method === 'POST')
345
+ return send(res, 200, { stopped: runs.stop(run) });
346
+ if (parts[4] === 'reply' && method === 'POST') {
347
+ let body;
348
+ try {
349
+ body = await readBody(req);
350
+ }
351
+ catch (e) {
352
+ return fail(res, 400, e.message);
353
+ }
354
+ const err = runs.reply(run, body.text);
355
+ return err ? fail(res, 409, err) : send(res, 202, { run: runs.view(run, 0) });
356
+ }
357
+ if (parts[4] === 'respond' && method === 'POST') {
358
+ let body;
359
+ try {
360
+ body = await readBody(req);
361
+ }
362
+ catch (e) {
363
+ return fail(res, 400, e.message);
364
+ }
365
+ if (body.behavior !== 'allow' && body.behavior !== 'deny')
366
+ return fail(res, 400, 'behavior must be allow or deny');
367
+ return runs.respond(run, String(body.requestId), body.behavior, body.answers) ? send(res, 200, { ok: true }) : fail(res, 404, 'no such pending request');
368
+ }
369
+ }
370
+ if (parts[2] === 'docker' && parts.length === 3) {
371
+ if (method === 'GET')
372
+ return send(res, 200, await docker.status(p.root));
373
+ if (method === 'POST') {
374
+ let body;
375
+ try {
376
+ body = await readBody(req);
377
+ }
378
+ catch (e) {
379
+ return fail(res, 400, e.message);
380
+ }
381
+ try {
382
+ return send(res, 202, { job: jobs.view(await docker.act(jobs, p, { action: body.action, service: body.service, confirmed: body.confirmed === true })) });
383
+ }
384
+ catch (e) {
385
+ if (e instanceof ops.OpError)
386
+ return send(res, e.code, { error: e.message, needsConfirmation: e.needsConfirmation || false, command: e.command, reason: e.reason, dockerDown: e.dockerDown || false });
387
+ throw e;
388
+ }
389
+ }
390
+ }
391
+ if (method === 'POST' && (parts[2] === 'dev' || parts[2] === 'worktrees')) {
392
+ let body;
393
+ try {
394
+ body = await readBody(req);
395
+ }
396
+ catch (e) {
397
+ return fail(res, 400, e.message);
398
+ }
399
+ const confirmed = body.confirmed === true;
400
+ try {
401
+ let job;
402
+ if (parts[2] === 'worktrees' && parts.length === 3 && body.skipDockerCheck !== true) {
403
+ const pre = await docker.preflight(p.root);
404
+ if (pre && !pre.ok)
405
+ return send(res, 409, { error: pre.reason, dockerPreflight: pre });
406
+ }
407
+ if (parts[2] === 'dev' && parts.length === 3)
408
+ job = ops.startDev(jobs, p, body.worktree, { confirmed });
409
+ else if (parts[2] === 'worktrees' && parts.length === 3)
410
+ job = ops.createWorktree(jobs, p, body.feature, { confirmed });
411
+ else if (parts[2] === 'worktrees' && parts[3] === 'remove')
412
+ job = ops.removeWorktree(jobs, p, body.path, { confirmed });
413
+ else
414
+ return fail(res, 404, 'not found');
415
+ cacheDoctor.clear(p.root);
416
+ return send(res, 202, { job: jobs.view(job) });
417
+ }
418
+ catch (e) {
419
+ if (e instanceof ops.OpError)
420
+ return send(res, e.code, { error: e.message, needsConfirmation: e.needsConfirmation || false, command: e.command, reason: e.reason });
421
+ throw e;
422
+ }
423
+ }
424
+ if (parts[2] === 'git' && parts.length === 3 && method === 'GET') {
425
+ const def = ops.readProfile(p.root).vcs?.default_branch || 'main';
426
+ const wts = legacy_1.registry.worktrees(p.root);
427
+ if (ghOk === null)
428
+ ghOk = gitinfo.ghAvailable();
429
+ const gh = await ghOk;
430
+ const out = { worktrees: {}, gh };
431
+ await Promise.all(wts.map(async (w, i) => {
432
+ const info = await gitinfo.worktreeGit(w.path, def);
433
+ const pull = gh && i > 0 && info.branch ? await cachePulls(`${p.root}|${info.branch}`, () => gitinfo.pullFor(p.root, info.branch)) : null;
434
+ out.worktrees[w.path] = { ...info, pull };
435
+ }));
436
+ return send(res, 200, out);
437
+ }
438
+ if (parts[2] === 'diff' && parts.length === 3 && method === 'GET') {
439
+ let wt;
440
+ try {
441
+ wt = ops.resolveWorktree(p.root, url.searchParams.get('worktree'));
442
+ }
443
+ catch (e) {
444
+ if (e instanceof ops.OpError)
445
+ return fail(res, e.code, e.message);
446
+ throw e;
447
+ }
448
+ const base = await gitinfo.baseRef(wt.path, ops.readProfile(p.root).vcs?.default_branch || 'main');
449
+ const file = url.searchParams.get('file');
450
+ if (file === null) {
451
+ const out = { base, files: await gitinfo.changedFiles(wt.path, base) };
452
+ return send(res, 200, out);
453
+ }
454
+ const d = await gitinfo.fileDiff(wt.path, base, file);
455
+ return d ? send(res, 200, d) : fail(res, 404, 'not a changed file of this worktree');
456
+ }
457
+ if (parts[2] === 'metrics' && method === 'GET') {
458
+ const days = Math.min(365, Math.max(1, parseInt(url.searchParams.get('days') ?? '', 10) || 30));
459
+ try {
460
+ return send(res, 200, await cacheMetrics(`${p.root}|${days}`, () => runMetrics(p.root, [`--days=${days}`, '--runs'])));
461
+ }
462
+ catch (e) {
463
+ return fail(res, 502, e.message);
464
+ }
465
+ }
466
+ if (parts[2] === 'specs' && parts[3] && method === 'GET') {
467
+ const d = specDetail(p, parts[3]);
468
+ return d ? send(res, 200, d) : fail(res, 404, 'unknown spec');
469
+ }
470
+ }
471
+ return fail(res, 404, 'not found');
472
+ }
473
+ function serveStatic(req, res, url) {
474
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
475
+ res.writeHead(405);
476
+ res.end();
477
+ return;
478
+ }
479
+ const rel = url.pathname === '/' ? 'index.html' : url.pathname.slice(1);
480
+ const file = path_1.default.join(PUBLIC, rel);
481
+ const ext = path_1.default.extname(file);
482
+ if (!file.startsWith(PUBLIC + path_1.default.sep) || !TYPES[ext]) {
483
+ res.writeHead(404);
484
+ res.end('not found');
485
+ return;
486
+ }
487
+ fs_1.default.readFile(file, (err, buf) => {
488
+ if (err) {
489
+ res.writeHead(404);
490
+ res.end('not found');
491
+ return;
492
+ }
493
+ res.writeHead(200, { 'Content-Type': TYPES[ext], 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer', 'Cache-Control': 'no-store' });
494
+ res.end(buf);
495
+ });
496
+ }
497
+ const server = http_1.default.createServer(async (req, res) => {
498
+ try {
499
+ if (!hostOk(req)) {
500
+ res.writeHead(403);
501
+ return res.end('bad host');
502
+ }
503
+ const url = new URL(req.url || '/', 'http://x');
504
+ if (url.pathname === '/api' || url.pathname.startsWith('/api/')) {
505
+ const o = req.headers.origin;
506
+ if (o && o !== origin)
507
+ return fail(res, 403, 'bad origin');
508
+ if (!tokenOk(req))
509
+ return fail(res, 401, 'missing or invalid token');
510
+ return await api(req, res, url);
511
+ }
512
+ serveStatic(req, res, url);
513
+ }
514
+ catch (e) {
515
+ if (!res.headersSent)
516
+ fail(res, 500, String(e?.message || e));
517
+ else
518
+ res.end();
519
+ }
520
+ });
521
+ function listen(port = 0) {
522
+ return new Promise((resolve, reject) => {
523
+ server.once('error', reject);
524
+ server.listen(port, '127.0.0.1', () => {
525
+ const p = server.address().port;
526
+ origin = `http://127.0.0.1:${p}`;
527
+ resolve({ port: p, url: `${origin}/#token=${token}`, token, origin });
528
+ });
529
+ });
530
+ }
531
+ return { server, listen, token, jobs, runs, close: () => {
532
+ jobs.stopAll();
533
+ runs.stopAll();
534
+ runs.flush();
535
+ for (const r of subs) {
536
+ try {
537
+ r.end();
538
+ }
539
+ catch { /* closed */ }
540
+ }
541
+ subs.clear();
542
+ return new Promise((r) => { server.close(() => r()); server.closeAllConnections?.(); });
543
+ } };
544
+ }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ // The wire contract between `cohorte ui`'s server (server/*.ts) and its page (web/src). Types only.
3
+ // Strings that come from a project (titles, paths, report text) are DATA: the page renders them as text.
4
+ Object.defineProperty(exports, "__esModule", { value: true });