@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,397 @@
1
+ import { insist, parse } from './errors.js';
2
+ import { Schemas } from './schema.js';
3
+
4
+ export const modelItems = (model) =>
5
+ model
6
+ ? ['threatActors', 'roles', 'protectedAssets', 'invariants', 'components', 'edges'].flatMap(
7
+ (key) => model[key],
8
+ )
9
+ : [];
10
+ export const rankedThreats = (project) =>
11
+ [...(project.artifacts.stride?.data.threats || [])].sort(
12
+ (a, b) => b.likelihood * b.impact - a.likelihood * a.impact || a.id.localeCompare(b.id),
13
+ );
14
+ export function validateFullTrees(data, project) {
15
+ const required = rankedThreats(project)
16
+ .slice(0, 3)
17
+ .map((t) => t.id);
18
+ insist(
19
+ data.trees.length === required.length &&
20
+ required.every((id) => data.trees.some((tree) => tree.threatId === id)),
21
+ `Full pipeline requires an attack tree for each top STRIDE threat: ${required.join(', ') || 'none (no threats identified)'}. Top threats cannot be omitted.`,
22
+ );
23
+ }
24
+ const setOf = (items) => new Set(items.map((x) => x.id));
25
+ function unique(items, label) {
26
+ insist(setOf(items).size === items.length, `Duplicate ${label} IDs.`);
27
+ }
28
+ function links(values, allowed, label) {
29
+ for (const value of values) insist(allowed.has(value), `Unknown ${label} reference: ${value}.`);
30
+ }
31
+
32
+ // Providers can copy a real quote while miscounting numbered lines. Resolve only
33
+ // a unique, byte-for-byte quote in its claimed file; never fuzzy-match or invent evidence.
34
+ export function resolveEvidence(phase, raw, project) {
35
+ const data = parse(Schemas[phase], raw);
36
+ const files = new Map(project.sources.flatMap((s) => s.files.map((f) => [f.id, f])));
37
+ const corrections = [];
38
+ function visit(value, location = phase) {
39
+ if (!value || typeof value !== 'object') return;
40
+ if ('evidence' in value && 'assumption' in value)
41
+ for (const [index, ref] of value.evidence.entries()) {
42
+ const file = files.get(ref.fileId);
43
+ if (!file || !ref.quote.trim()) continue;
44
+ const cited = file.text
45
+ .split('\n')
46
+ .slice(ref.startLine - 1, ref.endLine)
47
+ .join('\n');
48
+ if (ref.endLine >= ref.startLine && ref.endLine <= file.lines && cited.includes(ref.quote))
49
+ continue;
50
+ const quote = ref.quote.trim();
51
+ const start = file.text.indexOf(quote);
52
+ if (start < 0 || file.text.indexOf(quote, start + 1) >= 0) continue;
53
+ const startLine = file.text.slice(0, start).split('\n').length;
54
+ const endLine = startLine + quote.split('\n').length - 1;
55
+ corrections.push({
56
+ path: `${location}.evidence[${index}]`,
57
+ fileId: ref.fileId,
58
+ from: [ref.startLine, ref.endLine],
59
+ to: [startLine, endLine],
60
+ });
61
+ ref.startLine = startLine;
62
+ ref.endLine = endLine;
63
+ ref.quote = quote;
64
+ }
65
+ for (const [key, child] of Object.entries(value))
66
+ if (typeof child === 'object') visit(child, `${location}.${key}`);
67
+ }
68
+ visit(data);
69
+ return { data, corrections };
70
+ }
71
+
72
+ function citationIssue(ref, files) {
73
+ const file = files.get(ref.fileId);
74
+ if (!file) return `Unknown evidence file: ${ref.fileId}.`;
75
+ if (ref.endLine < ref.startLine || ref.endLine > file.lines)
76
+ return `Evidence line range is outside its source (${file.lines} lines).`;
77
+ const excerpt = file.text
78
+ .split('\n')
79
+ .slice(ref.startLine - 1, ref.endLine)
80
+ .join('\n');
81
+ if (!ref.quote.trim() || !excerpt.includes(ref.quote))
82
+ return `Evidence quote does not match ${ref.fileId}:${ref.startLine}-${ref.endLine}. Cited text begins ${JSON.stringify(excerpt.slice(0, 300))}. Copy a short exact substring, preserve whitespace, or correct the line numbers.`;
83
+ return null;
84
+ }
85
+
86
+ // A questionable citation is not a broken TRACE model. Retain the claim as an
87
+ // explicit unverified assumption; never pass the rejected quote off as evidence.
88
+ export function deferEvidence(phase, data, project) {
89
+ const files = new Map(project.sources.flatMap((s) => s.files.map((f) => [f.id, f])));
90
+ const warnings = [];
91
+ function visit(value, location = phase) {
92
+ if (!value || typeof value !== 'object') return;
93
+ if ('evidence' in value && 'assumption' in value) {
94
+ const rejected = value.evidence.flatMap((ref, index) => {
95
+ const reason = citationIssue(ref, files);
96
+ return reason ? [{ ...ref, path: `${location}.evidence[${index}]`, reason }] : [];
97
+ });
98
+ const missing = !value.evidence.length && !value.assumption.trim();
99
+ if (rejected.length || missing) {
100
+ const claim = value.name || value.title || value.label || value.id || location;
101
+ const reason = rejected.length
102
+ ? 'Source citations could not be verified.'
103
+ : 'No supporting evidence or assumption was supplied.';
104
+ warnings.push({ path: location, claim, reason, rejectedEvidence: rejected });
105
+ value.evidence = value.evidence.filter((ref) => !citationIssue(ref, files));
106
+ value.assumption = [
107
+ `Evidence review required: ${reason} Treat this claim as unverified until reviewed.`,
108
+ value.assumption,
109
+ ]
110
+ .filter(Boolean)
111
+ .join('\n')
112
+ .slice(0, 12000);
113
+ if (!value.evidence.length) {
114
+ if ('confidence' in value) value.confidence = 'low';
115
+ if ('speculative' in value) value.speculative = true;
116
+ }
117
+ }
118
+ }
119
+ for (const [key, child] of Object.entries(value))
120
+ if (typeof child === 'object') visit(child, `${location}.${key}`);
121
+ }
122
+ visit(data);
123
+ return warnings;
124
+ }
125
+
126
+ export function evidenceReviewNotes(data) {
127
+ const notes = [];
128
+ function visit(value, location = '') {
129
+ if (!value || typeof value !== 'object') return;
130
+ if (
131
+ typeof value.assumption === 'string' &&
132
+ /(?:Evidence|Reference) review required:/.test(value.assumption)
133
+ )
134
+ notes.push({
135
+ path: location,
136
+ claim: value.name || value.title || value.label || value.id || location,
137
+ note: value.assumption
138
+ .split('\n')
139
+ .find((line) => /(?:Evidence|Reference) review required:/.test(line))
140
+ .slice(0, 500),
141
+ });
142
+ for (const [key, child] of Object.entries(value))
143
+ if (typeof child === 'object') visit(child, location ? `${location}.${key}` : key);
144
+ }
145
+ visit(data);
146
+ return notes;
147
+ }
148
+
149
+ // Coverage is an index of threat references, not a second independent source of
150
+ // truth. Keep uncovered rationales, but explicitly flag any newly exposed gap.
151
+ export function resolveCoverage(data, project) {
152
+ const model = project.artifacts.model.data;
153
+ const required = [...model.protectedAssets, ...model.invariants, ...model.edges];
154
+ const rows = [...data.coverage];
155
+ for (const object of required)
156
+ if (!rows.some((row) => row.objectId === object.id))
157
+ rows.push({ objectId: object.id, threatIds: [], explanation: '' });
158
+ const corrections = [];
159
+ for (const row of rows) {
160
+ const linked = data.threats
161
+ .filter((threat) =>
162
+ [
163
+ ...threat.targetIds,
164
+ ...threat.actorIds,
165
+ ...threat.assetIds,
166
+ ...threat.invariantIds,
167
+ ].includes(row.objectId),
168
+ )
169
+ .map((threat) => threat.id);
170
+ const same =
171
+ JSON.stringify([...new Set(row.threatIds)].sort()) === JSON.stringify([...linked].sort());
172
+ if (same && (linked.length || row.explanation.trim())) continue;
173
+ corrections.push({ objectId: row.objectId, from: row.threatIds, to: linked });
174
+ row.threatIds = linked;
175
+ row.explanation = linked.length
176
+ ? 'Coverage computed from the threats that explicitly reference this object.'
177
+ : 'No generated threat references this object. Expert review of this coverage gap is required.';
178
+ if (!linked.length && data.openQuestions.length < 200)
179
+ data.openQuestions.push(
180
+ `Review coverage gap for ${row.objectId}: no generated threat references this object.`,
181
+ );
182
+ }
183
+ data.coverage = rows;
184
+ return corrections;
185
+ }
186
+
187
+ export function validateArtifact(phase, raw, project) {
188
+ const data = parse(Schemas[phase], raw);
189
+ const files = new Map(project.sources.flatMap((s) => s.files.map((f) => [f.id, f])));
190
+ const evidenceErrors = [];
191
+ function ground(value, location = phase) {
192
+ if (!value || typeof value !== 'object') return;
193
+ if ('evidence' in value && 'assumption' in value) {
194
+ if (!value.evidence.length && !value.assumption.trim())
195
+ evidenceErrors.push(`${location}: needs evidence or an explicit inferred assumption.`);
196
+ for (const [index, ref] of value.evidence.entries()) {
197
+ const at = `${location}.evidence[${index}]`;
198
+ const issue = citationIssue(ref, files);
199
+ if (issue) evidenceErrors.push(`${at}: ${issue}`);
200
+ }
201
+ }
202
+ for (const [key, child] of Object.entries(value))
203
+ if (typeof child === 'object') ground(child, `${location}.${key}`);
204
+ }
205
+ ground(data);
206
+ insist(
207
+ !evidenceErrors.length,
208
+ `${evidenceErrors.length} evidence error(s): ${evidenceErrors.slice(0, 12).join('\n')}`,
209
+ );
210
+ const model = phase === 'model' ? data : project.artifacts.model?.data;
211
+ const objects = modelItems(model),
212
+ modelIds = setOf(objects);
213
+ const threatData = project.artifacts.stride?.data.threats || [];
214
+ const threatIds = setOf(threatData);
215
+ if (phase === 'ingest') unique(data.candidates, 'candidate');
216
+ if (phase === 'model') {
217
+ unique(objects, 'model object');
218
+ const endpoints = setOf([
219
+ ...model.components,
220
+ ...model.roles,
221
+ ...model.threatActors,
222
+ ...model.protectedAssets,
223
+ ]);
224
+ for (const edge of model.edges) links([edge.from, edge.to], endpoints, 'edge endpoint');
225
+ }
226
+ if (phase === 'stride') {
227
+ unique(data.threats, 'threat');
228
+ const targets = setOf([...model.components, ...model.roles, ...model.edges]);
229
+ for (const threat of data.threats) {
230
+ insist(!modelIds.has(threat.id), 'Threat IDs must differ from model IDs.');
231
+ links(threat.targetIds, targets, 'target');
232
+ links(threat.actorIds, setOf(model.threatActors), 'actor');
233
+ links(threat.assetIds, setOf(model.protectedAssets), 'asset');
234
+ links(threat.invariantIds, setOf(model.invariants), 'invariant');
235
+ insist(
236
+ threat.assetIds.length + threat.invariantIds.length > 0 ||
237
+ threat.targetIds.some(
238
+ (id) => model.roles.some((x) => x.id === id) || model.edges.some((x) => x.id === id),
239
+ ),
240
+ 'A material threat must map to an asset, invariant, role or edge.',
241
+ );
242
+ }
243
+ const covered = new Set();
244
+ for (const row of data.coverage) {
245
+ insist(!covered.has(row.objectId), 'Duplicate coverage row.');
246
+ covered.add(row.objectId);
247
+ links([row.objectId], modelIds, 'coverage object');
248
+ links(row.threatIds, setOf(data.threats), 'coverage threat');
249
+ insist(row.threatIds.length || row.explanation.trim(), 'Uncovered objects need a reason.');
250
+ for (const threatId of row.threatIds) {
251
+ const threat = data.threats.find((t) => t.id === threatId);
252
+ insist(
253
+ [
254
+ ...threat.targetIds,
255
+ ...threat.assetIds,
256
+ ...threat.invariantIds,
257
+ ...threat.actorIds,
258
+ ].includes(row.objectId),
259
+ 'Coverage must match the threat references.',
260
+ );
261
+ }
262
+ }
263
+ for (const item of [...model.protectedAssets, ...model.invariants, ...model.edges])
264
+ insist(covered.has(item.id), `Missing coverage for ${item.id}.`);
265
+ }
266
+ if (phase === 'trees') {
267
+ const addressed = new Set(),
268
+ nodeIds = new Set();
269
+ for (const tree of data.trees) {
270
+ links([tree.threatId], threatIds, 'tree threat');
271
+ insist(!addressed.has(tree.threatId), 'Duplicate attack tree.');
272
+ addressed.add(tree.threatId);
273
+ unique(tree.nodes, 'tree node');
274
+ const nodes = new Map(tree.nodes.map((n) => [n.id, n]));
275
+ insist(
276
+ tree.nodes.filter((n) => n.parentId === null).length === 1,
277
+ 'Each attack tree needs exactly one root.',
278
+ );
279
+ for (const node of tree.nodes) {
280
+ insist(
281
+ !nodeIds.has(node.id) && !modelIds.has(node.id) && !threatIds.has(node.id),
282
+ 'Tree node IDs must be globally unique.',
283
+ );
284
+ nodeIds.add(node.id);
285
+ const visited = new Set([node.id]);
286
+ let current = node;
287
+ while (current.parentId !== null) {
288
+ insist(
289
+ nodes.has(current.parentId) && !visited.has(current.parentId),
290
+ 'Attack tree has a missing parent or cycle.',
291
+ );
292
+ visited.add(current.parentId);
293
+ current = nodes.get(current.parentId);
294
+ }
295
+ const children = tree.nodes.filter((n) => n.parentId === node.id);
296
+ insist(
297
+ node.operator === 'LEAF' ? children.length === 0 : children.length > 0,
298
+ 'Tree operators must match the branch structure.',
299
+ );
300
+ if (node.operator === 'LEAF')
301
+ insist(node.mitigations.length > 0, 'Attack-tree leaves need mitigations.');
302
+ }
303
+ }
304
+ for (const omitted of data.omitted) {
305
+ links([omitted.threatId], threatIds, 'omitted threat');
306
+ insist(!addressed.has(omitted.threatId), 'Threat cannot have both a tree and an omission.');
307
+ addressed.add(omitted.threatId);
308
+ }
309
+ for (const threat of rankedThreats(project).slice(0, project.config.treeLimit))
310
+ insist(
311
+ addressed.has(threat.id),
312
+ `Top threat ${threat.id} needs a tree or a documented omission.`,
313
+ );
314
+ }
315
+ if (phase === 'coordination') {
316
+ unique(data.scenarios, 'coordination scenario');
317
+ for (const scenario of data.scenarios) {
318
+ insist(
319
+ !modelIds.has(scenario.id) && !threatIds.has(scenario.id),
320
+ 'Coordination IDs must differ from model and threat IDs.',
321
+ );
322
+ links(
323
+ scenario.actorIds,
324
+ setOf([...model.threatActors, ...model.roles]),
325
+ 'coordination actor',
326
+ );
327
+ links(scenario.assetIds, setOf(model.protectedAssets), 'coordination asset');
328
+ }
329
+ }
330
+ if (phase === 'report') {
331
+ const allowed = new Set([
332
+ ...modelIds,
333
+ ...threatIds,
334
+ ...(project.artifacts.trees?.data.trees || []).flatMap((t) => t.nodes.map((n) => n.id)),
335
+ ...(project.artifacts.coordination?.data.scenarios || []).map((s) => s.id),
336
+ ]);
337
+ unique(data.roadmap, 'recommendation');
338
+ for (const row of data.roadmap) links(row.linkedIds, allowed, 'roadmap');
339
+ insist(
340
+ !threatData.length || data.roadmap.length > 0,
341
+ 'A model with threats needs a mitigation roadmap.',
342
+ );
343
+ }
344
+ return data;
345
+ }
346
+ // The engine owns accumulation. Models may return only the objects discussed in
347
+ // the current batch; keep prior validated objects unless they return an update.
348
+ export function retainContinuation(previous, raw) {
349
+ const retained = [];
350
+ function merge(old, next, location = 'previousDraft') {
351
+ if (!old || !next || Array.isArray(next) || typeof next !== 'object') return next;
352
+ const result = structuredClone(next);
353
+ for (const [key, value] of Object.entries(old)) {
354
+ if (
355
+ !Array.isArray(value) ||
356
+ !Array.isArray(result[key]) ||
357
+ key === 'omitted' ||
358
+ !value.length
359
+ )
360
+ continue;
361
+ const identity = ['id', 'objectId', 'threatId'].find((field) =>
362
+ value.every((item) => item && typeof item === 'object' && item[field]),
363
+ );
364
+ if (!identity) continue;
365
+ const prior = new Map(value.map((item) => [item[identity], item]));
366
+ result[key] = result[key].map((item) =>
367
+ merge(prior.get(item?.[identity]), item, `${location}.${key}.${item?.[identity]}`),
368
+ );
369
+ for (const item of value) {
370
+ if (result[key].some((candidate) => candidate?.[identity] === item[identity])) continue;
371
+ result[key].push(structuredClone(item));
372
+ retained.push(`${location}.${key}.${item[identity]}`);
373
+ }
374
+ }
375
+ return result;
376
+ }
377
+ return { data: merge(previous, raw), retained };
378
+ }
379
+
380
+ // Check the accumulated result before publishing the completed phase.
381
+ export function validateContinuation(previous, next, path = 'previousDraft') {
382
+ for (const [key, value] of Object.entries(previous)) {
383
+ if (!Array.isArray(value) || key === 'omitted' || !value.length) continue;
384
+ const identity = ['id', 'objectId', 'threatId'].find((field) =>
385
+ value.every((item) => item && typeof item === 'object' && item[field]),
386
+ );
387
+ if (!identity) continue;
388
+ for (const item of value) {
389
+ const kept = next[key]?.find((candidate) => candidate[identity] === item[identity]);
390
+ insist(
391
+ kept,
392
+ `Retain ${path}.${key} ${item[identity]} from earlier source batches; extend or revise it instead of dropping it.`,
393
+ );
394
+ validateContinuation(item, kept, `${path}.${key}.${item[identity]}`);
395
+ }
396
+ }
397
+ }
@@ -0,0 +1,70 @@
1
+ import { fromBufferPromise } from 'yauzl';
2
+ import { addAbortSignal } from 'node:stream';
3
+ import { insist, AppError } from './errors.js';
4
+
5
+ // Sequential, bounded archive reads. No archive path or symlink is ever executed.
6
+ export async function readZip(buffer, { signal, accept, onFile, warn, limits }) {
7
+ let archive;
8
+ try {
9
+ signal?.throwIfAborted();
10
+ archive = await fromBufferPromise(buffer, { strictFileNames: true, validateEntrySizes: true });
11
+ insist(archive.entryCount <= 10000, 'ZIP has too many entries (maximum 10,000).');
12
+ let expanded = 0;
13
+ const seen = new Set();
14
+ for await (const entry of archive.eachEntry()) {
15
+ signal?.throwIfAborted();
16
+ const name = entry.fileName.replace(/\/$/, '');
17
+ insist(
18
+ name.length > 0 &&
19
+ name.length <= 500 &&
20
+ !/[\\:\x00-\x1f\x7f]/.test(name) &&
21
+ name.split('/').every((part) => part && part !== '.' && part !== '..'),
22
+ 'ZIP contains an unsafe file path.',
23
+ );
24
+ const key = name.normalize('NFC').toLowerCase();
25
+ insist(!seen.has(key), 'ZIP contains duplicate or ambiguous file paths.');
26
+ seen.add(key);
27
+ expanded += entry.uncompressedSize;
28
+ insist(
29
+ Number.isSafeInteger(expanded) && expanded <= limits.totalBytes,
30
+ 'ZIP expands beyond the 32 MiB limit.',
31
+ );
32
+ insist(!(entry.generalPurposeBitFlag & 1), 'Encrypted ZIP files are not supported.');
33
+ const kind = (entry.externalFileAttributes >>> 16) & 0xf000;
34
+ if (kind === 0xa000) {
35
+ warn(`${name}: symlink skipped.`);
36
+ continue;
37
+ }
38
+ insist(
39
+ !kind || kind === 0x8000 || kind === 0x4000,
40
+ 'ZIP contains a special device or unsupported file type.',
41
+ );
42
+ if (entry.fileName.endsWith('/') || kind === 0x4000 || !accept(name)) continue;
43
+ insist(entry.uncompressedSize <= limits.fileBytes, `${name}: ZIP entry exceeds 8 MiB.`);
44
+ const stream = await archive.openReadStreamPromise(entry);
45
+ if (signal) addAbortSignal(signal, stream);
46
+ const chunks = [];
47
+ let size = 0;
48
+ for await (const chunk of stream) {
49
+ size += chunk.length;
50
+ insist(
51
+ size <= limits.fileBytes && size <= entry.uncompressedSize,
52
+ 'ZIP entry expands beyond its declared size.',
53
+ );
54
+ chunks.push(chunk);
55
+ }
56
+ insist(size === entry.uncompressedSize, 'ZIP entry size does not match its directory.');
57
+ await onFile(name, Buffer.concat(chunks));
58
+ }
59
+ } catch (error) {
60
+ signal?.throwIfAborted();
61
+ if (error instanceof AppError) throw error;
62
+ throw new AppError(
63
+ 422,
64
+ 'invalid_archive',
65
+ 'Could not read this ZIP. Use a valid, unencrypted repository ZIP with safe relative paths.',
66
+ );
67
+ } finally {
68
+ archive?.close();
69
+ }
70
+ }
package/src/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { Engine } from './engine/engine.js';
2
+ export { Providers } from './engine/providers.js';
3
+ export { PHASES, Schemas, enabledPhases } from './engine/schema.js';
4
+ export { markdownReport, pdfReport } from './engine/report.js';
5
+ export { startServer } from './api/server.js';
@@ -0,0 +1,32 @@
1
+ import path from 'node:path';
2
+ import os from 'node:os';
3
+
4
+ export function sourceInput(value, cwd = process.cwd()) {
5
+ if (typeof value !== 'string' || !value.trim())
6
+ throw new Error('Choose a source explicitly: a file, folder or public HTTPS URL.');
7
+ let selected = value.trim();
8
+ if (
9
+ (selected.startsWith('"') && selected.endsWith('"')) ||
10
+ (selected.startsWith("'") && selected.endsWith("'"))
11
+ )
12
+ selected = selected.slice(1, -1);
13
+ if (!selected.trim()) throw new Error('Provide a file, directory or HTTPS repository path.');
14
+ if (/^\w+:\/\//.test(selected)) {
15
+ const url = new URL(selected);
16
+ if (url.protocol !== 'https:') throw new Error('Use an HTTPS URL, or a local file/directory.');
17
+ const repository = ['github.com', 'bitbucket.org'].includes(url.hostname)
18
+ ? /^\/[\w.-]+\/[\w.-]+\/?$/.test(url.pathname)
19
+ : url.hostname === 'gitlab.com' &&
20
+ !url.pathname.includes('/-/') &&
21
+ !/\.(pdf|docx?|md|txt)$/i.test(url.pathname);
22
+ if (url.hostname === 'github.com' && /^\/[^/]+\/[^/]+\/blob\//.test(url.pathname)) {
23
+ url.hostname = 'raw.githubusercontent.com';
24
+ url.pathname = url.pathname.replace('/blob/', '/');
25
+ }
26
+ url.hash = '';
27
+ return { kind: repository ? 'git' : 'url', url: url.toString() };
28
+ }
29
+ if (selected === '~' || selected.startsWith('~/'))
30
+ selected = path.join(os.homedir(), selected.slice(2));
31
+ return { kind: 'local', path: path.resolve(cwd, selected) };
32
+ }
package/src/token.js ADDED
@@ -0,0 +1,59 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ renameSync,
8
+ unlinkSync,
9
+ writeFileSync,
10
+ } from 'node:fs';
11
+ import { randomBytes, randomUUID } from 'node:crypto';
12
+ import path from 'node:path';
13
+ import os from 'node:os';
14
+
15
+ // Node built-ins only: the API client imports this module without the engine.
16
+ export const configDir = () =>
17
+ path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'aitm');
18
+
19
+ export function readPrivate(file) {
20
+ if (!existsSync(file)) return null;
21
+ const stat = lstatSync(file);
22
+ if (!stat.isFile() || stat.isSymbolicLink())
23
+ throw new Error('Credential configuration must be a regular file.');
24
+ if (process.platform !== 'win32' && stat.mode & 0o077)
25
+ throw new Error(`Credential file must be owner-readable only: chmod 600 ${file}`);
26
+ return readFileSync(file, 'utf8');
27
+ }
28
+
29
+ export function writePrivate(directory, name, content) {
30
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
31
+ chmodSync(directory, 0o700);
32
+ const temporary = path.join(directory, `${name}-${randomUUID()}.tmp`);
33
+ try {
34
+ writeFileSync(temporary, content, { flag: 'wx', mode: 0o600 });
35
+ renameSync(temporary, path.join(directory, name));
36
+ } finally {
37
+ if (existsSync(temporary)) unlinkSync(temporary);
38
+ }
39
+ }
40
+
41
+ export const TOKEN_PATTERN = /^[A-Za-z0-9_-]{32,128}$/;
42
+ export const newToken = () => randomBytes(32).toString('base64url');
43
+ export const tokenFile = (directory = configDir()) => path.join(directory, 'token');
44
+
45
+ // The saved API access token, or '' when none exists. Never creates one.
46
+ export function readToken(directory = configDir()) {
47
+ const saved = readPrivate(tokenFile(directory))?.trim() || '';
48
+ return TOKEN_PATTERN.test(saved) ? saved : '';
49
+ }
50
+
51
+ // One persistent token per user, so browser sessions and scripts survive a restart.
52
+ export function loadToken(directory = configDir(), { rotate = false } = {}) {
53
+ const saved = rotate ? '' : readToken(directory);
54
+ if (saved) return saved;
55
+ readPrivate(tokenFile(directory)); // refuse to replace a symlink or shared file
56
+ const token = newToken();
57
+ writePrivate(directory, 'token', `${token}\n`);
58
+ return token;
59
+ }