@oaksecurity/aitm 0.0.0-stage → 2.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.
Files changed (63) hide show
  1. package/.env.example +11 -0
  2. package/CHANGELOG.md +100 -0
  3. package/LICENSE +21 -0
  4. package/README.md +229 -2
  5. package/SECURITY.md +49 -0
  6. package/SPEC.md +304 -0
  7. package/docs/api.md +332 -0
  8. package/docs/inputs-and-limits.md +78 -0
  9. package/docs/usage.md +351 -0
  10. package/examples/custody-architecture.md +27 -0
  11. package/package.json +67 -4
  12. package/src/api/server.js +591 -0
  13. package/src/api/web.js +38 -0
  14. package/src/application.js +32 -0
  15. package/src/assessments.js +37 -0
  16. package/src/assets/BDOGrotesk-Bold.ttf +0 -0
  17. package/src/assets/BDOGrotesk-Regular.ttf +0 -0
  18. package/src/assets/OFL.txt +93 -0
  19. package/src/assets/README.md +10 -0
  20. package/src/cli.js +224 -0
  21. package/src/client.js +88 -0
  22. package/src/config.js +105 -0
  23. package/src/doctor.js +128 -0
  24. package/src/engine/credentials.js +31 -0
  25. package/src/engine/download.js +135 -0
  26. package/src/engine/engine.js +783 -0
  27. package/src/engine/errors.js +23 -0
  28. package/src/engine/generation.js +121 -0
  29. package/src/engine/ingest.js +444 -0
  30. package/src/engine/pdf-layout.js +204 -0
  31. package/src/engine/pdf-report.js +573 -0
  32. package/src/engine/prompts.js +82 -0
  33. package/src/engine/providers.js +476 -0
  34. package/src/engine/references.js +112 -0
  35. package/src/engine/report.js +200 -0
  36. package/src/engine/schema.js +267 -0
  37. package/src/engine/store.js +115 -0
  38. package/src/engine/validate.js +397 -0
  39. package/src/engine/zip.js +70 -0
  40. package/src/index.js +5 -0
  41. package/src/source-input.js +32 -0
  42. package/src/token.js +59 -0
  43. package/src/tui/app.js +694 -0
  44. package/src/tui/editor.js +34 -0
  45. package/src/tui/file-picker.js +111 -0
  46. package/src/tui/logo.js +8 -0
  47. package/src/tui/progress.js +90 -0
  48. package/src/tui/report-reader.js +105 -0
  49. package/src/tui/select.js +63 -0
  50. package/src/tui/workbench.js +377 -0
  51. package/src/version.js +5 -0
  52. package/src/web/app.js +729 -0
  53. package/src/web/assets/BDOGrotesk-Bold.woff2 +0 -0
  54. package/src/web/assets/BDOGrotesk-Medium.woff2 +0 -0
  55. package/src/web/assets/BDOGrotesk-Regular.woff2 +0 -0
  56. package/src/web/assets/README.md +5 -0
  57. package/src/web/assets/aitm-mark.svg +12 -0
  58. package/src/web/assets/oak-white.svg +166 -0
  59. package/src/web/html.js +32 -0
  60. package/src/web/index.html +26 -0
  61. package/src/web/markdown.js +48 -0
  62. package/src/web/styles.css +1450 -0
  63. package/src/web/views.js +254 -0
@@ -0,0 +1,591 @@
1
+ import http from 'node:http';
2
+ import { createHash, timingSafeEqual } from 'node:crypto';
3
+ import { z } from 'zod';
4
+ import { AppError, insist, parse } from '../engine/errors.js';
5
+ import {
6
+ CreateProject,
7
+ UpdateProject,
8
+ SourceInput,
9
+ RunInput,
10
+ Review,
11
+ PhaseId,
12
+ ProviderId,
13
+ PHASES,
14
+ Schemas,
15
+ jsonSchema,
16
+ enabledPhases,
17
+ DEFAULT_SCOPE,
18
+ } from '../engine/schema.js';
19
+ import { markdownReport, pdfReport } from '../engine/report.js';
20
+ import { openAssessment } from '../assessments.js';
21
+ import { sourceInput } from '../source-input.js';
22
+ import { serveWeb, PAGE_HEADERS } from './web.js';
23
+ import { VERSION } from '../version.js';
24
+ import { newToken, TOKEN_PATTERN } from '../token.js';
25
+
26
+ const MAX_BODY = 16 * 1024 * 1024;
27
+ const LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5}$/;
28
+ const json = (res, status, body) => {
29
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
30
+ res.end(JSON.stringify(body));
31
+ };
32
+ const digest = (value) => createHash('sha256').update(String(value)).digest();
33
+ const same = (a, b) => timingSafeEqual(digest(a), digest(b));
34
+ const SIGN_IN = `<!doctype html><html lang="en"><meta charset="utf-8"><title>AiTM · access link needed</title>
35
+ <body><h1>AiTM needs its access link</h1>
36
+ <p>This local workbench accepts only requests that carry its private access token.</p>
37
+ <p>Open the complete URL that AiTM printed in the terminal where it runs. It ends with <code>?token=…</code>.
38
+ In the terminal interface, press <code>?</code> to show it again.</p></body></html>`;
39
+
40
+ // Every request needs the access token, except the public routes below. Without it,
41
+ // any process or user on this host could read local files through source intake.
42
+ export async function startServer(
43
+ engine,
44
+ { port = 8790, host = '127.0.0.1', token = newToken(), allowedHosts = [] } = {},
45
+ ) {
46
+ insist(
47
+ ['127.0.0.1', '::1', 'localhost'].includes(host),
48
+ 'AiTM is a single-user local server. Bind to loopback only.',
49
+ );
50
+ insist(TOKEN_PATTERN.test(token), 'The API access token is invalid.');
51
+ insist(
52
+ Array.isArray(allowedHosts) && allowedHosts.every((h) => LOOPBACK_HOST.test(h)),
53
+ 'An allowed host must be a loopback name with a port, for example 127.0.0.1:9000.',
54
+ );
55
+ const streams = new Set();
56
+ const shutdown = new AbortController();
57
+ const routes = [];
58
+ const route = (method, path, summary, body, handler, { open = false } = {}) =>
59
+ routes.push({
60
+ method,
61
+ path,
62
+ summary,
63
+ body,
64
+ handler,
65
+ open,
66
+ names: [...path.matchAll(/:([\w]+)/g)].map((m) => m[1]),
67
+ pattern: new RegExp(`^${path.replace(/:[\w]+/g, '([^/]+)')}$`),
68
+ });
69
+ route(
70
+ 'GET',
71
+ '/v1/health',
72
+ 'Server identity and health (no access token needed)',
73
+ null,
74
+ () => ({ service: 'aitm', version: VERSION, apiVersion: 1 }),
75
+ { open: true },
76
+ );
77
+ route('GET', '/v1/instance', 'Process and storage details of this instance', null, () => ({
78
+ version: VERSION,
79
+ pid: process.pid,
80
+ dataDir: engine.store.directory,
81
+ keyFile: engine.providers.keyFile,
82
+ }));
83
+ route('GET', '/v1/meta', 'TRACE phase registry and artifact schemas', null, () => ({
84
+ phases: PHASES,
85
+ defaultScope: DEFAULT_SCOPE,
86
+ schemas: Object.fromEntries(Object.entries(Schemas).map(([k, v]) => [k, jsonSchema(v)])),
87
+ }));
88
+ route('GET', '/v1/providers', 'Provider configuration (no credentials)', null, () =>
89
+ engine.providers.status(),
90
+ );
91
+ route(
92
+ 'PUT',
93
+ '/v1/providers/:provider/credentials',
94
+ 'Save or replace a private provider key',
95
+ z.strictObject({
96
+ apiKey: z.string().max(2048).optional(),
97
+ workspaceId: z.string().max(300).optional(),
98
+ }),
99
+ ({ params, body }) => {
100
+ const provider = parse(ProviderId, params.provider);
101
+ insist(
102
+ body.apiKey !== undefined || body.workspaceId !== undefined,
103
+ 'Provide a key or workspace setting.',
104
+ );
105
+ insist(
106
+ provider === 'anthropic' || body.workspaceId === undefined,
107
+ 'Workspace ID is an Anthropic setting.',
108
+ );
109
+ engine.providers.configure({
110
+ ...(body.apiKey !== undefined ? { [provider]: body.apiKey } : {}),
111
+ ...(body.workspaceId !== undefined ? { anthropicWorkspaceId: body.workspaceId } : {}),
112
+ });
113
+ engine.events.emit('change', null);
114
+ return engine.providers.status();
115
+ },
116
+ );
117
+ route(
118
+ 'GET',
119
+ '/v1/providers/:provider/models',
120
+ 'List account models or offline defaults',
121
+ null,
122
+ ({ params }) => engine.providers.models(parse(ProviderId, params.provider), shutdown.signal),
123
+ );
124
+ route(
125
+ 'POST',
126
+ '/v1/providers/:provider/test',
127
+ 'Verify a provider and model with a small API request',
128
+ z.strictObject({ model: z.string().min(1).max(300) }),
129
+ ({ params, body }) =>
130
+ engine.providers.test(
131
+ parse(ProviderId, params.provider),
132
+ body.model,
133
+ AbortSignal.any([shutdown.signal, AbortSignal.timeout(30000)]),
134
+ ),
135
+ );
136
+ route('GET', '/v1/projects', 'List projects', null, () => engine.list());
137
+ route(
138
+ 'POST',
139
+ '/v1/projects/open',
140
+ 'Open or reuse an assessment from one source',
141
+ z.strictObject({ source: z.union([z.string().min(1).max(2000), SourceInput]) }),
142
+ ({ body }) => {
143
+ let input = body.source;
144
+ if (typeof input === 'string' || input === undefined) {
145
+ try {
146
+ input = sourceInput(input);
147
+ } catch (error) {
148
+ throw new AppError(422, 'invalid_source', error.message);
149
+ }
150
+ }
151
+ return openAssessment(engine, input);
152
+ },
153
+ );
154
+ route('POST', '/v1/projects', 'Create a project', CreateProject, ({ body }) =>
155
+ engine.create(body),
156
+ );
157
+ route(
158
+ 'POST',
159
+ '/v1/projects/import',
160
+ 'Import a portable project snapshot',
161
+ z.object({
162
+ format: z.literal('aitm-project'),
163
+ version: z.literal(2),
164
+ project: z.record(z.string(), z.unknown()),
165
+ }),
166
+ ({ body }) => engine.import(body),
167
+ );
168
+ route('GET', '/v1/projects/:projectId', 'Read project state', null, ({ params }) =>
169
+ engine.get(params.projectId),
170
+ );
171
+ route(
172
+ 'PATCH',
173
+ '/v1/projects/:projectId',
174
+ 'Edit scope, name or configuration with revision check',
175
+ UpdateProject,
176
+ ({ params, body }) => engine.update(params.projectId, body),
177
+ );
178
+ route('DELETE', '/v1/projects/:projectId', 'Delete a project', null, ({ params }) => {
179
+ engine.remove(params.projectId);
180
+ return { deleted: true };
181
+ });
182
+ route(
183
+ 'PUT',
184
+ '/v1/projects/:projectId/source',
185
+ 'Replace the primary source using a path or URL',
186
+ z.strictObject({ source: z.string().min(1).max(2000) }),
187
+ ({ params, body }) => {
188
+ let input;
189
+ try {
190
+ input = sourceInput(body.source);
191
+ } catch (error) {
192
+ throw new AppError(422, 'invalid_source', error.message);
193
+ }
194
+ const project = engine.get(params.projectId);
195
+ insist(
196
+ project.sources.length <= 1,
197
+ 'This imported assessment has multiple sources. Remove extra snapshots before replacing its primary source.',
198
+ );
199
+ return engine.addSource(project.id, input, project.sources[0]?.id);
200
+ },
201
+ );
202
+ route('GET', '/v1/projects/:projectId/phases', 'Get enabled TRACE phases', null, ({ params }) =>
203
+ enabledPhases(engine.get(params.projectId)),
204
+ );
205
+ route(
206
+ 'POST',
207
+ '/v1/projects/:projectId/sources/import',
208
+ 'Import multiple explicit sources atomically',
209
+ z.strictObject({
210
+ sources: z
211
+ .array(z.union([z.string().min(1).max(2000), SourceInput]))
212
+ .min(1)
213
+ .max(100),
214
+ }),
215
+ ({ params, body }) => {
216
+ const inputs = body.sources.map((source) => {
217
+ if (typeof source !== 'string') return source;
218
+ try {
219
+ return sourceInput(source);
220
+ } catch (error) {
221
+ throw new AppError(422, 'invalid_source', error.message);
222
+ }
223
+ });
224
+ return engine.addSources(params.projectId, inputs);
225
+ },
226
+ );
227
+ route(
228
+ 'POST',
229
+ '/v1/projects/:projectId/sources',
230
+ 'Ingest local, repository, document or synced evidence',
231
+ SourceInput,
232
+ ({ params, body }) => engine.addSource(params.projectId, body),
233
+ );
234
+ route(
235
+ 'PUT',
236
+ '/v1/projects/:projectId/sources/:sourceId',
237
+ 'Replace a source snapshot and invalidate dependent analysis',
238
+ z.union([SourceInput, z.strictObject({ source: z.string().min(1).max(2000) })]),
239
+ ({ params, body }) => {
240
+ let input = body;
241
+ if (body.source !== undefined) {
242
+ try {
243
+ input = sourceInput(body.source);
244
+ } catch (error) {
245
+ throw new AppError(422, 'invalid_source', error.message);
246
+ }
247
+ }
248
+ return engine.addSource(params.projectId, input, params.sourceId);
249
+ },
250
+ );
251
+ route(
252
+ 'POST',
253
+ '/v1/projects/:projectId/sources/:sourceId/sync',
254
+ 'Refresh a local path or repository snapshot',
255
+ z.strictObject({}),
256
+ ({ params }) => engine.syncSource(params.projectId, params.sourceId),
257
+ );
258
+ route(
259
+ 'DELETE',
260
+ '/v1/projects/:projectId/sources/:sourceId',
261
+ 'Remove a source',
262
+ null,
263
+ ({ params }) => engine.removeSource(params.projectId, params.sourceId),
264
+ );
265
+ route(
266
+ 'PUT',
267
+ '/v1/projects/:projectId/artifacts/:phase',
268
+ 'Edit a phase artifact and invalidate its dependents',
269
+ z.strictObject({ revision: z.int().min(1), data: z.unknown() }),
270
+ ({ params, body }) => engine.editArtifact(params.projectId, parse(PhaseId, params.phase), body),
271
+ );
272
+ route(
273
+ 'POST',
274
+ '/v1/projects/:projectId/artifacts/:phase/approve',
275
+ 'Record an explicit human review',
276
+ Review,
277
+ ({ params, body }) => engine.approve(params.projectId, parse(PhaseId, params.phase), body),
278
+ );
279
+ route(
280
+ 'POST',
281
+ '/v1/projects/:projectId/runs',
282
+ 'Start or resume a TRACE pipeline job',
283
+ RunInput,
284
+ ({ params, body }) => engine.run(params.projectId, body),
285
+ );
286
+ route(
287
+ 'GET',
288
+ '/v1/projects/:projectId/runs/:runId',
289
+ 'Get durable job state and progress',
290
+ null,
291
+ ({ params }) => engine.getRun(params.projectId, params.runId),
292
+ );
293
+ route(
294
+ 'POST',
295
+ '/v1/projects/:projectId/runs/:runId/cancel',
296
+ 'Cancel a running job',
297
+ z.strictObject({}),
298
+ ({ params }) => engine.cancel(params.projectId, params.runId),
299
+ );
300
+ route(
301
+ 'GET',
302
+ '/v1/projects/:projectId/export',
303
+ 'Export a portable project snapshot',
304
+ null,
305
+ ({ params }) => engine.export(params.projectId),
306
+ );
307
+ route(
308
+ 'GET',
309
+ '/v1/projects/:projectId/report',
310
+ 'Export a report as Markdown or PDF (?format=pdf)',
311
+ null,
312
+ async ({ params, url, res }) => {
313
+ const p = engine.get(params.projectId),
314
+ format = url.searchParams.get('format') || 'markdown';
315
+ insist(['markdown', 'pdf'].includes(format), 'Report format must be markdown or pdf.');
316
+ const body = format === 'pdf' ? await pdfReport(p) : markdownReport(p);
317
+ res.writeHead(200, {
318
+ 'content-type': format === 'pdf' ? 'application/pdf' : 'text/markdown; charset=utf-8',
319
+ 'content-disposition': `attachment; filename="aitm-${p.id}.${format === 'pdf' ? 'pdf' : 'md'}"`,
320
+ });
321
+ res.end(body);
322
+ },
323
+ );
324
+ route(
325
+ 'GET',
326
+ '/v1/projects/:projectId/runs/:runId/events',
327
+ 'Replay and stream job events using Last-Event-ID',
328
+ null,
329
+ ({ params, req, res, url }) => {
330
+ const run = engine.getRun(params.projectId, params.runId);
331
+ const after = Number(req.headers['last-event-id'] || url.searchParams.get('after') || 0);
332
+ insist(
333
+ Number.isSafeInteger(after) && after >= 0 && after <= run.lastEventId,
334
+ 'Invalid event cursor.',
335
+ );
336
+ res.writeHead(200, {
337
+ 'content-type': 'text/event-stream',
338
+ connection: 'keep-alive',
339
+ 'cache-control': 'no-cache',
340
+ 'x-accel-buffering': 'no',
341
+ });
342
+ streams.add(res);
343
+ const terminal = (event) =>
344
+ ['completed', 'failed', 'cancelled', 'interrupted', 'awaiting_review'].includes(event.type);
345
+ const send = (event) => {
346
+ if (res.destroyed) return;
347
+ if (res.writableLength > 1024 * 1024) {
348
+ res.destroy();
349
+ return;
350
+ }
351
+ res.write(`id: ${event.id}\nevent: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
352
+ if (terminal(event)) res.end();
353
+ };
354
+ for (const event of run.events.filter((e) => e.id > after)) send(event);
355
+ if (!['queued', 'running'].includes(run.status)) {
356
+ res.end();
357
+ streams.delete(res);
358
+ return;
359
+ }
360
+ engine.events.on(params.runId, send);
361
+ const heartbeat = setInterval(() => res.write(': heartbeat\n\n'), 15000);
362
+ heartbeat.unref();
363
+ res.on('close', () => {
364
+ clearInterval(heartbeat);
365
+ streams.delete(res);
366
+ engine.events.off(params.runId, send);
367
+ });
368
+ },
369
+ );
370
+ route(
371
+ 'GET',
372
+ '/v1/openapi.json',
373
+ 'Machine-readable API contract and artifact schemas',
374
+ null,
375
+ () => ({
376
+ openapi: '3.1.0',
377
+ info: { title: 'AiTM engine API', version: VERSION },
378
+ security: [{ accessToken: [] }],
379
+ paths: routes.reduce((paths, r) => {
380
+ const p = r.path.replace(/:([\w]+)/g, '{$1}');
381
+ paths[p] ||= {};
382
+ paths[p][r.method.toLowerCase()] = {
383
+ summary: r.summary,
384
+ ...(r.open ? { security: [] } : {}),
385
+ parameters: r.names.map((name) => ({
386
+ name,
387
+ in: 'path',
388
+ required: true,
389
+ schema: { type: 'string' },
390
+ })),
391
+ ...(r.body
392
+ ? {
393
+ requestBody: {
394
+ required: true,
395
+ content: { 'application/json': { schema: jsonSchema(r.body) } },
396
+ },
397
+ }
398
+ : {}),
399
+ responses: {
400
+ 200: {
401
+ description:
402
+ 'Successful result; runs return 202 and project creation/import return 201.',
403
+ },
404
+ 401: { description: 'Missing or invalid access token' },
405
+ 422: { description: 'Validation error' },
406
+ 409: { description: 'Conflict or review gate' },
407
+ },
408
+ };
409
+ return paths;
410
+ }, {}),
411
+ components: {
412
+ securitySchemes: {
413
+ accessToken: {
414
+ type: 'http',
415
+ scheme: 'bearer',
416
+ description: 'The private token that `aitm token` prints.',
417
+ },
418
+ },
419
+ schemas: Object.fromEntries(Object.entries(Schemas).map(([k, v]) => [k, jsonSchema(v)])),
420
+ },
421
+ }),
422
+ );
423
+ route(
424
+ 'GET',
425
+ '/v1/events',
426
+ 'Watch project and provider changes; refetch after reconnect',
427
+ null,
428
+ ({ res }) => {
429
+ res.writeHead(200, {
430
+ 'content-type': 'text/event-stream',
431
+ 'cache-control': 'no-cache',
432
+ connection: 'keep-alive',
433
+ });
434
+ streams.add(res);
435
+ const send = (projectId) => {
436
+ if (res.destroyed) return;
437
+ if (res.writableLength > 1024 * 1024) return res.destroy();
438
+ res.write(`data: ${JSON.stringify({ projectId })}\n\n`);
439
+ };
440
+ send(null);
441
+ engine.events.on('change', send);
442
+ const heartbeat = setInterval(() => res.write(': heartbeat\n\n'), 15000);
443
+ heartbeat.unref();
444
+ res.on('close', () => {
445
+ clearInterval(heartbeat);
446
+ streams.delete(res);
447
+ engine.events.off('change', send);
448
+ });
449
+ },
450
+ );
451
+ const server = http.createServer(async (req, res) => {
452
+ res.setHeader('x-content-type-options', 'nosniff');
453
+ res.setHeader('cache-control', 'no-store');
454
+ try {
455
+ const address = server.address(),
456
+ actualPort = address.port;
457
+ const hosts = new Set([
458
+ `127.0.0.1:${actualPort}`,
459
+ `localhost:${actualPort}`,
460
+ `[::1]:${actualPort}`,
461
+ ...allowedHosts,
462
+ ]);
463
+ insist(hosts.has(req.headers.host), 'Invalid Host header.', 403, 'forbidden');
464
+ if (req.headers.origin)
465
+ insist(
466
+ [...hosts].some((h) => req.headers.origin === `http://${h}`),
467
+ 'Cross-origin access is not allowed.',
468
+ 403,
469
+ 'forbidden',
470
+ );
471
+ if (req.headers['sec-fetch-site'])
472
+ insist(
473
+ ['none', 'same-origin'].includes(req.headers['sec-fetch-site']),
474
+ 'Cross-site access is not allowed.',
475
+ 403,
476
+ 'forbidden',
477
+ );
478
+ const url = new URL(req.url, `http://${req.headers.host}`);
479
+ const cookie = `aitm_token_${actualPort}`;
480
+ const presented =
481
+ /^Bearer (\S+)$/.exec(req.headers.authorization || '')?.[1] ||
482
+ (req.headers.cookie || '')
483
+ .split(';')
484
+ .map((part) => part.trim().split('='))
485
+ .find(([name]) => name === cookie)?.[1] ||
486
+ '';
487
+ const page = url.pathname === '/' && ['GET', 'HEAD'].includes(req.method);
488
+ // The launch URL carries the token once; the browser keeps it in a cookie.
489
+ if (page && url.searchParams.has('token') && same(url.searchParams.get('token'), token)) {
490
+ res.writeHead(303, {
491
+ location: '/',
492
+ 'referrer-policy': 'no-referrer',
493
+ 'set-cookie': `${cookie}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=31536000`,
494
+ });
495
+ res.end();
496
+ return;
497
+ }
498
+ const authorized = same(presented, token);
499
+ if (page && !authorized) {
500
+ res.writeHead(401, PAGE_HEADERS);
501
+ res.end(req.method === 'HEAD' ? undefined : SIGN_IN);
502
+ return;
503
+ }
504
+ if (await serveWeb(req, res, url.pathname)) return;
505
+ const selected = routes.find((r) => r.method === req.method && r.pattern.test(url.pathname));
506
+ if (!selected?.open && !authorized) {
507
+ res.setHeader('www-authenticate', 'Bearer');
508
+ throw new AppError(
509
+ 401,
510
+ 'unauthorized',
511
+ 'Missing or invalid access token. Send Authorization: Bearer <token>; aitm token prints it.',
512
+ );
513
+ }
514
+ insist(selected, 'API route not found. See /v1/openapi.json.', 404, 'not_found');
515
+ const matches = selected.pattern.exec(url.pathname);
516
+ const params = Object.fromEntries(
517
+ selected.names.map((name, i) => [name, decodeURIComponent(matches[i + 1])]),
518
+ );
519
+ for (const key of ['projectId', 'sourceId', 'runId'])
520
+ if (params[key]) parse(z.uuid(), params[key]);
521
+ let body;
522
+ if (selected.body) {
523
+ insist(
524
+ req.headers['content-type']?.split(';')[0] === 'application/json',
525
+ 'Use Content-Type: application/json.',
526
+ 415,
527
+ 'unsupported_media',
528
+ );
529
+ const chunks = [];
530
+ let size = 0;
531
+ for await (const chunk of req) {
532
+ size += chunk.length;
533
+ insist(size <= MAX_BODY, 'Request exceeds 16 MiB.', 413, 'body_too_large');
534
+ chunks.push(chunk);
535
+ }
536
+ try {
537
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
538
+ } catch {
539
+ throw new AppError(400, 'invalid_json', 'Request body is not valid JSON.');
540
+ }
541
+ body = parse(selected.body, body);
542
+ }
543
+ const result = await selected.handler({ params, body, url, req, res });
544
+ if (!res.headersSent) {
545
+ const status =
546
+ req.method === 'POST' && selected.path.endsWith('/runs')
547
+ ? 202
548
+ : req.method === 'POST' &&
549
+ ['/v1/projects', '/v1/projects/import'].includes(selected.path)
550
+ ? 201
551
+ : 200;
552
+ json(res, status, result);
553
+ }
554
+ } catch (error) {
555
+ if (res.headersSent) {
556
+ res.destroy();
557
+ return;
558
+ }
559
+ const known = error instanceof AppError;
560
+ json(res, known ? error.status : 500, {
561
+ error: {
562
+ code: known ? error.code : 'internal_error',
563
+ message: known
564
+ ? engine.providers.redact(error.message)
565
+ : 'The operation could not be completed. Check the selected input and retry.',
566
+ },
567
+ });
568
+ }
569
+ });
570
+ server.requestTimeout = 120000;
571
+ await new Promise((resolve, reject) => {
572
+ server.once('error', reject);
573
+ server.listen(port, host, resolve);
574
+ });
575
+ const address = server.address();
576
+ const url = `http://${host === '::1' ? '[::1]' : host}:${address.port}`;
577
+ return {
578
+ url,
579
+ token,
580
+ webUrl: (hash = '') => `${url}/?token=${token}${hash}`,
581
+ server,
582
+ close: async () => {
583
+ shutdown.abort();
584
+ for (const res of streams) res.end();
585
+ await new Promise((resolve) => {
586
+ server.close(resolve);
587
+ server.closeAllConnections();
588
+ });
589
+ },
590
+ };
591
+ }
package/src/api/web.js ADDED
@@ -0,0 +1,38 @@
1
+ import { readFile } from 'node:fs/promises';
2
+
3
+ // Explicit public assets: never resolve an arbitrary URL against the filesystem.
4
+ const assets = new Map([
5
+ ['/', ['index.html', 'text/html; charset=utf-8']],
6
+ ...['app.js', 'views.js', 'html.js', 'markdown.js'].map((file) => [
7
+ `/ui/${file}`,
8
+ [file, 'text/javascript; charset=utf-8'],
9
+ ]),
10
+ ['/ui/styles.css', ['styles.css', 'text/css; charset=utf-8']],
11
+ ...['aitm-mark.svg', 'oak-white.svg'].map((file) => [
12
+ `/ui/assets/${file}`,
13
+ [`assets/${file}`, 'image/svg+xml'],
14
+ ]),
15
+ ...['Regular', 'Medium', 'Bold'].map((weight) => {
16
+ const file = `assets/BDOGrotesk-${weight}.woff2`;
17
+ return [`/ui/${file}`, [file, 'font/woff2']];
18
+ }),
19
+ ]);
20
+ export const PAGE_HEADERS = {
21
+ 'content-type': 'text/html; charset=utf-8',
22
+ 'content-security-policy':
23
+ "default-src 'self'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",
24
+ 'referrer-policy': 'no-referrer',
25
+ 'x-frame-options': 'DENY',
26
+ };
27
+ export async function serveWeb(req, res, pathname) {
28
+ const asset = assets.get(pathname);
29
+ if (!asset || !['GET', 'HEAD'].includes(req.method)) return false;
30
+ const content = await readFile(new URL(`../web/${asset[0]}`, import.meta.url));
31
+ res.writeHead(200, {
32
+ ...PAGE_HEADERS,
33
+ 'content-type': asset[1],
34
+ 'content-length': content.length,
35
+ });
36
+ res.end(req.method === 'HEAD' ? undefined : content);
37
+ return true;
38
+ }
@@ -0,0 +1,32 @@
1
+ import { Engine } from './engine/engine.js';
2
+ import { startServer } from './api/server.js';
3
+
4
+ // Both interfaces share this engine. The caller owns the application's lifetime.
5
+ export async function startApplication({ dataDir, providers, port = 8790, token, allowedHosts }) {
6
+ const engine = await Engine.open({ dataDir, providers });
7
+ let api;
8
+ try {
9
+ api = await startServer(engine, { port, token, allowedHosts });
10
+ } catch (error) {
11
+ await engine.close();
12
+ throw error;
13
+ }
14
+ let closing;
15
+ return {
16
+ engine,
17
+ url: api.url,
18
+ token: api.token,
19
+ webUrl: api.webUrl,
20
+ close() {
21
+ return (closing ||= (async () => {
22
+ try {
23
+ await engine.close();
24
+ } finally {
25
+ await api.close();
26
+ }
27
+ })());
28
+ },
29
+ };
30
+ }
31
+
32
+ export { openAssessment } from './assessments.js';
@@ -0,0 +1,37 @@
1
+ import path from 'node:path';
2
+ import { realpath } from 'node:fs/promises';
3
+ import { DEFAULT_SCOPE } from './engine/schema.js';
4
+
5
+ const repositoryKey = (url) => url.replace(/\/+$/, '').replace(/\.git$/, '');
6
+
7
+ export async function openAssessment(engine, input) {
8
+ const locator = input.kind === 'local' ? await realpath(input.path) : input.url;
9
+ const reusable = ['local', 'git', 'url'].includes(input.kind);
10
+ const key = input.kind === 'git' ? repositoryKey(locator) : locator;
11
+ for (const summary of engine.list()) {
12
+ const project = engine.get(summary.id);
13
+ if (
14
+ reusable &&
15
+ project.sources.some(
16
+ (source) =>
17
+ source.kind === input.kind &&
18
+ (input.kind === 'git' ? repositoryKey(source.locator) : source.locator) === key,
19
+ )
20
+ )
21
+ return { project, reused: true };
22
+ }
23
+ const name = reusable
24
+ ? path.basename(input.kind === 'local' ? locator : new URL(key).pathname)
25
+ : input.label;
26
+ const project = engine.create({
27
+ name: name || 'Assessment',
28
+ scope: DEFAULT_SCOPE,
29
+ });
30
+ try {
31
+ return { project: await engine.addSource(project.id, input), reused: false };
32
+ } catch (error) {
33
+ // Failed intake must not accumulate empty assessments.
34
+ if (!engine.closed) engine.remove(project.id);
35
+ throw error;
36
+ }
37
+ }