@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.
- package/.env.example +11 -0
- package/CHANGELOG.md +100 -0
- package/LICENSE +21 -0
- package/README.md +229 -2
- package/SECURITY.md +49 -0
- package/SPEC.md +304 -0
- package/docs/api.md +332 -0
- package/docs/inputs-and-limits.md +78 -0
- package/docs/usage.md +351 -0
- package/examples/custody-architecture.md +27 -0
- package/package.json +67 -4
- package/src/api/server.js +591 -0
- package/src/api/web.js +38 -0
- package/src/application.js +32 -0
- package/src/assessments.js +37 -0
- package/src/assets/BDOGrotesk-Bold.ttf +0 -0
- package/src/assets/BDOGrotesk-Regular.ttf +0 -0
- package/src/assets/OFL.txt +93 -0
- package/src/assets/README.md +10 -0
- package/src/cli.js +224 -0
- package/src/client.js +88 -0
- package/src/config.js +105 -0
- package/src/doctor.js +128 -0
- package/src/engine/credentials.js +31 -0
- package/src/engine/download.js +135 -0
- package/src/engine/engine.js +783 -0
- package/src/engine/errors.js +23 -0
- package/src/engine/generation.js +121 -0
- package/src/engine/ingest.js +444 -0
- package/src/engine/pdf-layout.js +204 -0
- package/src/engine/pdf-report.js +573 -0
- package/src/engine/prompts.js +82 -0
- package/src/engine/providers.js +476 -0
- package/src/engine/references.js +112 -0
- package/src/engine/report.js +200 -0
- package/src/engine/schema.js +267 -0
- package/src/engine/store.js +115 -0
- package/src/engine/validate.js +397 -0
- package/src/engine/zip.js +70 -0
- package/src/index.js +5 -0
- package/src/source-input.js +32 -0
- package/src/token.js +59 -0
- package/src/tui/app.js +694 -0
- package/src/tui/editor.js +34 -0
- package/src/tui/file-picker.js +111 -0
- package/src/tui/logo.js +8 -0
- package/src/tui/progress.js +90 -0
- package/src/tui/report-reader.js +105 -0
- package/src/tui/select.js +63 -0
- package/src/tui/workbench.js +377 -0
- package/src/version.js +5 -0
- package/src/web/app.js +729 -0
- package/src/web/assets/BDOGrotesk-Bold.woff2 +0 -0
- package/src/web/assets/BDOGrotesk-Medium.woff2 +0 -0
- package/src/web/assets/BDOGrotesk-Regular.woff2 +0 -0
- package/src/web/assets/README.md +5 -0
- package/src/web/assets/aitm-mark.svg +12 -0
- package/src/web/assets/oak-white.svg +166 -0
- package/src/web/html.js +32 -0
- package/src/web/index.html +26 -0
- package/src/web/markdown.js +48 -0
- package/src/web/styles.css +1450 -0
- package/src/web/views.js +254 -0
package/src/web/app.js
ADDED
|
@@ -0,0 +1,729 @@
|
|
|
1
|
+
import { esc, pretty, human, button, field, select, options } from './html.js';
|
|
2
|
+
import { activeRun, sidebar, topbar, progress, view, sourceForm } from './views.js';
|
|
3
|
+
|
|
4
|
+
const $ = (selector) => document.querySelector(selector);
|
|
5
|
+
const state = {
|
|
6
|
+
projects: [],
|
|
7
|
+
project: null,
|
|
8
|
+
phases: [],
|
|
9
|
+
providers: {},
|
|
10
|
+
catalogs: {},
|
|
11
|
+
view: 'overview',
|
|
12
|
+
health: {},
|
|
13
|
+
meta: { phases: [] },
|
|
14
|
+
dirty: false,
|
|
15
|
+
report: null,
|
|
16
|
+
busy: '',
|
|
17
|
+
event: null,
|
|
18
|
+
};
|
|
19
|
+
let refreshNumber = 0,
|
|
20
|
+
routeNumber = 0,
|
|
21
|
+
stream,
|
|
22
|
+
streamId,
|
|
23
|
+
changeTimer,
|
|
24
|
+
toastTimer,
|
|
25
|
+
onDialogSubmit,
|
|
26
|
+
dialogReturnFocus;
|
|
27
|
+
const terminalEvents = ['completed', 'failed', 'cancelled', 'interrupted', 'awaiting_review'];
|
|
28
|
+
|
|
29
|
+
async function api(path, method = 'GET', body) {
|
|
30
|
+
const response = await fetch(`/v1${path}`, {
|
|
31
|
+
method,
|
|
32
|
+
cache: 'no-store',
|
|
33
|
+
...(body === undefined
|
|
34
|
+
? {}
|
|
35
|
+
: { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }),
|
|
36
|
+
});
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
const data = await response.json().catch(() => ({}));
|
|
39
|
+
if (response.status === 401)
|
|
40
|
+
throw new Error(
|
|
41
|
+
'This browser session has no valid access token. Open the complete URL that AiTM printed in its terminal.',
|
|
42
|
+
);
|
|
43
|
+
throw new Error(data.error?.message || `Request failed (${response.status}).`);
|
|
44
|
+
}
|
|
45
|
+
return response.headers.get('content-type')?.includes('application/json')
|
|
46
|
+
? response.json()
|
|
47
|
+
: response.text();
|
|
48
|
+
}
|
|
49
|
+
function error(message) {
|
|
50
|
+
const box = $('#dialog').open ? $('#dialog-error') : $('#error');
|
|
51
|
+
box.hidden = !message;
|
|
52
|
+
box.textContent = message || '';
|
|
53
|
+
}
|
|
54
|
+
function toast(message) {
|
|
55
|
+
$('#toast').textContent = message;
|
|
56
|
+
$('#toast').hidden = false;
|
|
57
|
+
clearTimeout(toastTimer);
|
|
58
|
+
toastTimer = setTimeout(() => {
|
|
59
|
+
$('#toast').hidden = true;
|
|
60
|
+
}, 4500);
|
|
61
|
+
}
|
|
62
|
+
function chrome() {
|
|
63
|
+
const menuOpen = $('#sidebar').classList.contains('open');
|
|
64
|
+
$('#sidebar').innerHTML = sidebar(state);
|
|
65
|
+
$('#topbar').innerHTML = topbar(state);
|
|
66
|
+
$('#topbar [data-action="menu"]').setAttribute('aria-expanded', String(menuOpen));
|
|
67
|
+
$('#activity').innerHTML = progress(state);
|
|
68
|
+
}
|
|
69
|
+
function render() {
|
|
70
|
+
const y = $('#workspace').scrollTop;
|
|
71
|
+
chrome();
|
|
72
|
+
if (!state.dirty) {
|
|
73
|
+
$('#workspace').innerHTML = `<div class="view">${view(state)}</div>`;
|
|
74
|
+
state.routeNeedsRender = false;
|
|
75
|
+
$('#workspace').scrollTop = y;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function projectPath(suffix = '') {
|
|
79
|
+
if (!state.project) throw new Error('Open an assessment first.');
|
|
80
|
+
return `/projects/${state.project.id}${suffix}`;
|
|
81
|
+
}
|
|
82
|
+
async function refresh(force = false) {
|
|
83
|
+
const id = state.routeId,
|
|
84
|
+
turn = ++refreshNumber;
|
|
85
|
+
const [projects, providers, project, phases] = await Promise.all([
|
|
86
|
+
api('/projects'),
|
|
87
|
+
api('/providers'),
|
|
88
|
+
id
|
|
89
|
+
? api(`/projects/${id}`).catch((e) => {
|
|
90
|
+
if (e.message.includes('not found')) return null;
|
|
91
|
+
throw e;
|
|
92
|
+
})
|
|
93
|
+
: null,
|
|
94
|
+
id ? api(`/projects/${id}/phases`).catch(() => []) : [],
|
|
95
|
+
]);
|
|
96
|
+
if (turn !== refreshNumber || state.routeId !== id) return;
|
|
97
|
+
const changed =
|
|
98
|
+
force ||
|
|
99
|
+
state.routeNeedsRender ||
|
|
100
|
+
state.project?.revision !== project?.revision ||
|
|
101
|
+
JSON.stringify(state.projects) !== JSON.stringify(projects);
|
|
102
|
+
const reportKey = project?.artifacts.report?.generatedAt;
|
|
103
|
+
if (state.project?.id !== project?.id || state.reportKey !== reportKey) state.report = null;
|
|
104
|
+
Object.assign(state, { projects, providers, project, phases, reportKey });
|
|
105
|
+
connectRun();
|
|
106
|
+
if (changed) render();
|
|
107
|
+
else chrome();
|
|
108
|
+
if (state.view === 'report' && project?.artifacts.report && state.report == null) {
|
|
109
|
+
const text = await api(`/projects/${id}/report`);
|
|
110
|
+
if (state.routeId === id && state.reportKey === reportKey) {
|
|
111
|
+
state.report = text;
|
|
112
|
+
if (state.view === 'report') render();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (state.view === 'settings')
|
|
116
|
+
await loadModels(state.settingsProvider || project?.config.provider || 'openai');
|
|
117
|
+
}
|
|
118
|
+
function queueRefresh() {
|
|
119
|
+
clearTimeout(changeTimer);
|
|
120
|
+
changeTimer = setTimeout(() => refresh().catch((e) => error(e.message)), 100);
|
|
121
|
+
}
|
|
122
|
+
function connectRun() {
|
|
123
|
+
const run = activeRun(state.project);
|
|
124
|
+
if (run?.id === streamId) return;
|
|
125
|
+
stream?.close();
|
|
126
|
+
stream = null;
|
|
127
|
+
streamId = run?.id;
|
|
128
|
+
state.event = run?.events.at(-1) || null;
|
|
129
|
+
state.request = run?.events.findLast((e) => e.type === 'request') || null;
|
|
130
|
+
if (!run) return;
|
|
131
|
+
stream = new EventSource(
|
|
132
|
+
`/v1/projects/${state.project.id}/runs/${run.id}/events?after=${run.lastEventId}`,
|
|
133
|
+
);
|
|
134
|
+
for (const type of [
|
|
135
|
+
'running',
|
|
136
|
+
'request',
|
|
137
|
+
'progress',
|
|
138
|
+
'validating',
|
|
139
|
+
'validation_retry',
|
|
140
|
+
'repair_fallback',
|
|
141
|
+
'evidence_review',
|
|
142
|
+
'reference_review',
|
|
143
|
+
'source_refresh',
|
|
144
|
+
'artifact',
|
|
145
|
+
'reused',
|
|
146
|
+
'skipped',
|
|
147
|
+
'review_notes',
|
|
148
|
+
'batch_complete',
|
|
149
|
+
...terminalEvents,
|
|
150
|
+
]) {
|
|
151
|
+
stream.addEventListener(type, (message) => {
|
|
152
|
+
if (streamId !== run.id) return;
|
|
153
|
+
state.event = JSON.parse(message.data);
|
|
154
|
+
if (type === 'request') state.request = state.event;
|
|
155
|
+
$('#activity').innerHTML = progress(state);
|
|
156
|
+
if (terminalEvents.includes(type)) {
|
|
157
|
+
stream?.close();
|
|
158
|
+
stream = null;
|
|
159
|
+
streamId = null;
|
|
160
|
+
toast(['completed', 'awaiting_review'].includes(type) ? state.event.message : human(type));
|
|
161
|
+
queueRefresh();
|
|
162
|
+
} else if (['artifact', 'source_refresh', 'running'].includes(type)) queueRefresh();
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
stream.onerror = () => {
|
|
166
|
+
$('#activity').innerHTML =
|
|
167
|
+
'<span class="spinner"></span>Reconnecting to the engine… Saved progress will be restored.';
|
|
168
|
+
queueRefresh();
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
async function route() {
|
|
172
|
+
const turn = ++routeNumber;
|
|
173
|
+
const parts = location.hash.slice(1).split('/').filter(Boolean);
|
|
174
|
+
const id = parts[0] === 'projects' && /^[\da-f-]{36}$/i.test(parts[1] || '') ? parts[1] : null;
|
|
175
|
+
state.view = id ? parts[2] || 'overview' : parts[0] === 'settings' ? 'settings' : 'overview';
|
|
176
|
+
if (state.routeId !== id) {
|
|
177
|
+
state.project = null;
|
|
178
|
+
state.report = null;
|
|
179
|
+
state.settingsProvider = null;
|
|
180
|
+
}
|
|
181
|
+
state.routeId = id;
|
|
182
|
+
state.dirty = false;
|
|
183
|
+
state.rawReport = false;
|
|
184
|
+
$('#sidebar').classList.remove('open');
|
|
185
|
+
closeDialog();
|
|
186
|
+
error('');
|
|
187
|
+
$('#workspace').innerHTML = '<div class="loading">Opening assessment…</div>';
|
|
188
|
+
state.routeNeedsRender = true;
|
|
189
|
+
$('#workspace').scrollTop = 0;
|
|
190
|
+
await refresh(true);
|
|
191
|
+
if (turn === routeNumber) {
|
|
192
|
+
document.title = `${state.project?.name || 'AiTM'} · ${human(state.view)} · AiTM`;
|
|
193
|
+
$('#workspace').focus({ preventScroll: true });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function navigate(id, selectedView = 'overview') {
|
|
197
|
+
location.hash = id ? `/projects/${id}/${selectedView}` : '/';
|
|
198
|
+
}
|
|
199
|
+
function dialog(title, content, submit) {
|
|
200
|
+
if (!$('#dialog').open) dialogReturnFocus = document.activeElement;
|
|
201
|
+
$('#dialog').innerHTML =
|
|
202
|
+
`<div class="dialog-heading"><h2 id="dialog-title">${esc(title)}</h2>${button('close-dialog', '×', 'aria-label="Close dialog"', 'icon')}</div><div id="dialog-error" class="notice warn" role="alert" hidden></div>${content}`;
|
|
203
|
+
onDialogSubmit = submit;
|
|
204
|
+
if (!$('#dialog').open) $('#dialog').showModal();
|
|
205
|
+
$('#dialog').querySelector('input,textarea,select')?.focus();
|
|
206
|
+
}
|
|
207
|
+
function closeDialog() {
|
|
208
|
+
if (!$('#dialog').open) return;
|
|
209
|
+
$('#dialog').close();
|
|
210
|
+
$('#dialog').innerHTML = '';
|
|
211
|
+
onDialogSubmit = null;
|
|
212
|
+
if (dialogReturnFocus?.isConnected) dialogReturnFocus.focus();
|
|
213
|
+
}
|
|
214
|
+
function confirm(title, message, label, action) {
|
|
215
|
+
dialog(
|
|
216
|
+
title,
|
|
217
|
+
`<form data-form="dialog"><p>${esc(message)}</p><div class="row">${button('close-dialog', 'Cancel')}<button class="btn danger">${esc(label)}</button></div></form>`,
|
|
218
|
+
action,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
async function act(label, task, { close = true, preserveForm = false } = {}) {
|
|
222
|
+
if (state.busy) return;
|
|
223
|
+
state.busy = label;
|
|
224
|
+
error('');
|
|
225
|
+
chrome();
|
|
226
|
+
const buttons = [...document.querySelectorAll('main button, dialog button')].filter(
|
|
227
|
+
(b) => !b.disabled,
|
|
228
|
+
);
|
|
229
|
+
buttons.forEach((b) => {
|
|
230
|
+
b.disabled = true;
|
|
231
|
+
});
|
|
232
|
+
try {
|
|
233
|
+
await task();
|
|
234
|
+
if (!preserveForm) state.dirty = false;
|
|
235
|
+
if (close) closeDialog();
|
|
236
|
+
await refresh(true);
|
|
237
|
+
} catch (e) {
|
|
238
|
+
error(e.message);
|
|
239
|
+
} finally {
|
|
240
|
+
state.busy = '';
|
|
241
|
+
buttons.forEach((b) => {
|
|
242
|
+
if (b.isConnected) b.disabled = false;
|
|
243
|
+
});
|
|
244
|
+
chrome();
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
async function startRun(input) {
|
|
248
|
+
await act('Starting TRACE…', async () => {
|
|
249
|
+
await api(projectPath('/runs'), 'POST', input);
|
|
250
|
+
toast(input.mode === 'review' ? 'Review flow started.' : 'Full pipeline started.');
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
async function loadModels(provider, force = false) {
|
|
254
|
+
if (state.catalogs[provider] && !force) return;
|
|
255
|
+
const catalog = await api(`/providers/${provider}/models`);
|
|
256
|
+
state.catalogs[provider] = catalog;
|
|
257
|
+
// Updating options in place preserves unsaved keys and phase preferences.
|
|
258
|
+
const form = document.querySelector(`form[data-form="models"][data-provider="${provider}"]`);
|
|
259
|
+
if (!form) return;
|
|
260
|
+
for (const key of ['fastModel', 'deepModel']) {
|
|
261
|
+
const el = form.elements[key],
|
|
262
|
+
current = el.value;
|
|
263
|
+
const choices = catalog.models.some((m) => m.id === current)
|
|
264
|
+
? catalog.models
|
|
265
|
+
: [{ id: current }, ...catalog.models];
|
|
266
|
+
el.innerHTML = options(choices, current);
|
|
267
|
+
}
|
|
268
|
+
$('#catalog-notice').textContent = catalog.notice || 'Compatible account models.';
|
|
269
|
+
}
|
|
270
|
+
async function upload(files) {
|
|
271
|
+
if (!files.length) throw new Error('Choose at least one file.');
|
|
272
|
+
if (files.length > 1000) throw new Error('Choose at most 1,000 files.');
|
|
273
|
+
if (files.reduce((sum, file) => sum + file.size, 0) > 11 * 1024 * 1024)
|
|
274
|
+
throw new Error('This upload exceeds 11 MiB. Use a local folder path for larger sources.');
|
|
275
|
+
const encoded = [];
|
|
276
|
+
for (const file of files) {
|
|
277
|
+
if (file.size > 8 * 1024 * 1024) throw new Error('Each source file must be at most 8 MiB.');
|
|
278
|
+
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
279
|
+
let binary = '';
|
|
280
|
+
for (let i = 0; i < bytes.length; i += 32768)
|
|
281
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
282
|
+
encoded.push({
|
|
283
|
+
path: file.webkitRelativePath || file.name,
|
|
284
|
+
content: btoa(binary),
|
|
285
|
+
encoding: 'base64',
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
return encoded.map((file) => ({ kind: 'files', label: file.path, files: [file] }));
|
|
289
|
+
}
|
|
290
|
+
function newProject() {
|
|
291
|
+
dialog(
|
|
292
|
+
'New project',
|
|
293
|
+
`<form data-form="new-project">${field('name', 'Project name', '', { required: true })}${field('scope', 'Scope (optional)', '', { area: true })}<p class="hint">Create the project first, then add any number of source documents, URLs or ZIP repositories.</p><div class="row"><button class="btn primary">Create project</button>${button('close-dialog', 'Cancel')}</div></form>`,
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
function openProject() {
|
|
297
|
+
dialog(
|
|
298
|
+
'Open project',
|
|
299
|
+
state.projects.length
|
|
300
|
+
? `<div class="project-list">${state.projects.map((p) => button('select-project', `${esc(p.name)} <span>${p.sources} source(s) · ${esc(p.lastRun || 'not run')}</span>`, `data-project="${p.id}"`, 'file-row')).join('')}</div>`
|
|
301
|
+
: '<p>No saved projects yet. Create a new project to begin.</p>',
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
function sourceDialog(sourceId = null) {
|
|
305
|
+
state.replacing = sourceId;
|
|
306
|
+
dialog(sourceId ? 'Replace source' : 'Add sources', sourceForm(Boolean(sourceId)));
|
|
307
|
+
}
|
|
308
|
+
async function importSources(inputs) {
|
|
309
|
+
const autorun = $('#run-after-import')?.checked;
|
|
310
|
+
if (!inputs.length) throw new Error('Choose at least one explicit source.');
|
|
311
|
+
if (state.replacing) {
|
|
312
|
+
if (inputs.length !== 1)
|
|
313
|
+
throw new Error('Choose one replacement. Use Add sources to import several sources.');
|
|
314
|
+
await api(
|
|
315
|
+
projectPath(`/sources/${state.replacing}`),
|
|
316
|
+
'PUT',
|
|
317
|
+
typeof inputs[0] === 'string' ? { source: inputs[0] } : inputs[0],
|
|
318
|
+
);
|
|
319
|
+
} else await api(projectPath('/sources/import'), 'POST', { sources: inputs });
|
|
320
|
+
if (autorun) await api(projectPath('/runs'), 'POST', { mode: 'full' });
|
|
321
|
+
toast(`${inputs.length} source(s) imported.${autorun ? ' Full pipeline started.' : ''}`);
|
|
322
|
+
}
|
|
323
|
+
function editArtifact(phase, key, index) {
|
|
324
|
+
const baseline = structuredClone(state.project),
|
|
325
|
+
artifact = baseline.artifacts[phase];
|
|
326
|
+
if (!artifact) throw new Error('Generate this step first.');
|
|
327
|
+
const item = key ? artifact.data[key][index] : null;
|
|
328
|
+
const editable = item
|
|
329
|
+
? Object.entries(item).filter(
|
|
330
|
+
([name, value]) =>
|
|
331
|
+
name !== 'id' &&
|
|
332
|
+
(['string', 'number', 'boolean'].includes(typeof value) ||
|
|
333
|
+
(Array.isArray(value) && value.every((v) => typeof v === 'string'))),
|
|
334
|
+
)
|
|
335
|
+
: [];
|
|
336
|
+
dialog(
|
|
337
|
+
key ? `Edit ${item.name || item.title || item.id}` : `Edit ${human(phase)} draft`,
|
|
338
|
+
`<form data-form="dialog"><p class="hint">Saving validates this artifact and clears its downstream analysis. Evidence and references must remain valid.</p>${key ? editable.map(([name, value]) => (typeof value === 'boolean' ? select(name, human(name), ['true', 'false'], String(value)) : field(name, human(name), Array.isArray(value) ? value.join('\n') : value, { area: typeof value !== 'number', type: typeof value === 'number' ? 'number' : 'text' }))).join('') : field('json', 'Artifact JSON', pretty(artifact.data), { area: true, code: true, required: true })}<div class="row"><button class="btn primary">Save draft</button>${button('close-dialog', 'Cancel')}</div></form>`,
|
|
339
|
+
async (values) => {
|
|
340
|
+
let updated;
|
|
341
|
+
if (!key) {
|
|
342
|
+
try {
|
|
343
|
+
updated = JSON.parse(values.json);
|
|
344
|
+
} catch {
|
|
345
|
+
throw new Error('Artifact JSON is not valid. Fix the syntax and try again.');
|
|
346
|
+
}
|
|
347
|
+
} else {
|
|
348
|
+
updated = artifact.data;
|
|
349
|
+
for (const [name, original] of editable)
|
|
350
|
+
updated[key][index][name] = Array.isArray(original)
|
|
351
|
+
? values[name]
|
|
352
|
+
.split('\n')
|
|
353
|
+
.map((v) => v.trim())
|
|
354
|
+
.filter(Boolean)
|
|
355
|
+
: typeof original === 'number'
|
|
356
|
+
? Number(values[name])
|
|
357
|
+
: typeof original === 'boolean'
|
|
358
|
+
? values[name] === 'true'
|
|
359
|
+
: values[name];
|
|
360
|
+
}
|
|
361
|
+
await api(`/projects/${baseline.id}/artifacts/${phase}`, 'PUT', {
|
|
362
|
+
revision: baseline.revision,
|
|
363
|
+
data: updated,
|
|
364
|
+
});
|
|
365
|
+
toast('Draft saved. Review its downstream steps.');
|
|
366
|
+
},
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
function evidence(fileId, start = 1, end = start) {
|
|
370
|
+
const file = state.project.sources.flatMap((s) => s.files).find((f) => f.id === fileId);
|
|
371
|
+
if (!file) throw new Error('This evidence file is not in the current source snapshot.');
|
|
372
|
+
const lines = file.text.split('\n');
|
|
373
|
+
const first = Math.max(1, Math.min(start, lines.length)),
|
|
374
|
+
last = Math.min(lines.length, first + 199);
|
|
375
|
+
state.evidence = { fileId, start: first, end };
|
|
376
|
+
dialog(
|
|
377
|
+
file.path,
|
|
378
|
+
`<p class="hint">${esc(fileId)} · Lines ${first}–${last} of ${lines.length.toLocaleString()} · Full accepted source retained.</p><pre class="source-code">${lines
|
|
379
|
+
.slice(first - 1, last)
|
|
380
|
+
.map(
|
|
381
|
+
(line, i) =>
|
|
382
|
+
`<span class="source-line ${first + i <= end ? 'selected' : ''}"><b>${first + i}</b>${esc(line) || ' '}</span>`,
|
|
383
|
+
)
|
|
384
|
+
.join(
|
|
385
|
+
'',
|
|
386
|
+
)}</pre><div class="row">${button('evidence-page', 'Previous 200 lines', `data-start="${Math.max(1, first - 200)}" ${first === 1 ? 'disabled' : ''}`)}${button('evidence-page', 'Next 200 lines', `data-start="${last + 1}" ${last === lines.length ? 'disabled' : ''}`)}</div>`,
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
function importProject() {
|
|
390
|
+
dialog(
|
|
391
|
+
'Import an assessment',
|
|
392
|
+
`<p>Choose an AiTM v2 JSON export. The engine validates it before saving a new assessment.</p><label class="btn primary file-button">Choose project JSON<input type="file" accept=".json,application/json" data-upload="import" aria-label="Choose project JSON"></label>`,
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
const actions = {
|
|
396
|
+
menu: () => {
|
|
397
|
+
const open = $('#sidebar').classList.toggle('open');
|
|
398
|
+
$('#topbar [data-action="menu"]').setAttribute('aria-expanded', String(open));
|
|
399
|
+
},
|
|
400
|
+
'new-project': newProject,
|
|
401
|
+
'open-project': openProject,
|
|
402
|
+
'select-project': (el) => {
|
|
403
|
+
closeDialog();
|
|
404
|
+
navigate(el.dataset.project);
|
|
405
|
+
},
|
|
406
|
+
'add-sources': () => sourceDialog(),
|
|
407
|
+
'replace-source': (el) => sourceDialog(el.dataset.source),
|
|
408
|
+
import: importProject,
|
|
409
|
+
'close-dialog': closeDialog,
|
|
410
|
+
'run-full': () => startRun({ mode: 'full' }),
|
|
411
|
+
'run-review': () => startRun({ mode: 'review' }),
|
|
412
|
+
restart: () =>
|
|
413
|
+
confirm(
|
|
414
|
+
'Restart full pipeline?',
|
|
415
|
+
'Generated analysis and reviews will be cleared and rebuilt using the saved source snapshot. Provider usage will be charged again.',
|
|
416
|
+
'Restart pipeline',
|
|
417
|
+
() => api(projectPath('/runs'), 'POST', { mode: 'full', resume: false }),
|
|
418
|
+
),
|
|
419
|
+
generate: (el) => {
|
|
420
|
+
const phase = el.dataset.phase;
|
|
421
|
+
const run = () => api(projectPath('/runs'), 'POST', { mode: 'review', phase });
|
|
422
|
+
if (state.project.artifacts[phase])
|
|
423
|
+
confirm(
|
|
424
|
+
`Regenerate ${human(phase)}?`,
|
|
425
|
+
'This clears the current phase and downstream analysis. Earlier review gates must be approved.',
|
|
426
|
+
'Regenerate step',
|
|
427
|
+
run,
|
|
428
|
+
);
|
|
429
|
+
else return act('Starting step…', run);
|
|
430
|
+
},
|
|
431
|
+
'cancel-run': () =>
|
|
432
|
+
act('Cancelling run…', () =>
|
|
433
|
+
api(projectPath(`/runs/${activeRun(state.project).id}/cancel`), 'POST', {}),
|
|
434
|
+
),
|
|
435
|
+
approve: (el) => {
|
|
436
|
+
const p = state.project,
|
|
437
|
+
phase = el.dataset.phase;
|
|
438
|
+
dialog(
|
|
439
|
+
`Review ${human(phase)}`,
|
|
440
|
+
`<form data-form="dialog"><p>Approve this artifact to continue. Notes are optional; no reviewer name is required.</p>${field('notes', 'Review notes', '', { area: true })}<div class="row"><button class="btn primary">Approve review</button>${button('close-dialog', 'Cancel')}</div></form>`,
|
|
441
|
+
(values) =>
|
|
442
|
+
api(`/projects/${p.id}/artifacts/${phase}/approve`, 'POST', {
|
|
443
|
+
revision: p.revision,
|
|
444
|
+
...values,
|
|
445
|
+
}),
|
|
446
|
+
);
|
|
447
|
+
},
|
|
448
|
+
'edit-artifact': (el) => editArtifact(el.dataset.phase),
|
|
449
|
+
'edit-item': (el) => editArtifact(el.dataset.phase, el.dataset.key, Number(el.dataset.index)),
|
|
450
|
+
evidence: (el) =>
|
|
451
|
+
evidence(el.dataset.file, Number(el.dataset.line || 1), Number(el.dataset.end || 1)),
|
|
452
|
+
'evidence-page': (el) => evidence(state.evidence.fileId, Number(el.dataset.start), 0),
|
|
453
|
+
sync: (el) =>
|
|
454
|
+
confirm(
|
|
455
|
+
'Refresh source snapshot?',
|
|
456
|
+
'Read the source again and invalidate analysis if its content changed.',
|
|
457
|
+
'Refresh snapshot',
|
|
458
|
+
() => api(projectPath(`/sources/${el.dataset.source}/sync`), 'POST', {}),
|
|
459
|
+
),
|
|
460
|
+
'remove-source': (el) =>
|
|
461
|
+
confirm(
|
|
462
|
+
'Remove source?',
|
|
463
|
+
'This removes the saved snapshot and clears dependent analysis. The original file or repository is unchanged.',
|
|
464
|
+
'Remove source',
|
|
465
|
+
() => api(projectPath(`/sources/${el.dataset.source}`), 'DELETE'),
|
|
466
|
+
),
|
|
467
|
+
delete: () => {
|
|
468
|
+
const id = state.project.id;
|
|
469
|
+
confirm(
|
|
470
|
+
'Delete assessment?',
|
|
471
|
+
`Permanently delete “${state.project.name}” and its saved analysis from AiTM.`,
|
|
472
|
+
'Delete assessment',
|
|
473
|
+
async () => {
|
|
474
|
+
await api(`/projects/${id}`, 'DELETE');
|
|
475
|
+
navigate(null);
|
|
476
|
+
},
|
|
477
|
+
);
|
|
478
|
+
},
|
|
479
|
+
'export-project': () => {
|
|
480
|
+
const link = document.createElement('a');
|
|
481
|
+
link.href = `/v1${projectPath('/export')}`;
|
|
482
|
+
link.download = `aitm-${state.project.id}.json`;
|
|
483
|
+
link.click();
|
|
484
|
+
},
|
|
485
|
+
'report-preview': () => {
|
|
486
|
+
state.rawReport = false;
|
|
487
|
+
render();
|
|
488
|
+
},
|
|
489
|
+
'report-raw': () => {
|
|
490
|
+
state.rawReport = true;
|
|
491
|
+
render();
|
|
492
|
+
},
|
|
493
|
+
'refresh-models': (el) =>
|
|
494
|
+
act('Loading account models…', () => loadModels(el.dataset.provider, true), {
|
|
495
|
+
close: false,
|
|
496
|
+
preserveForm: true,
|
|
497
|
+
}),
|
|
498
|
+
'test-provider': (el) =>
|
|
499
|
+
act(
|
|
500
|
+
'Testing provider connection…',
|
|
501
|
+
async () => {
|
|
502
|
+
const model = document.querySelector('[name="fastModel"]').value;
|
|
503
|
+
await api(`/providers/${el.dataset.provider}/test`, 'POST', { model });
|
|
504
|
+
toast('Provider connection verified.');
|
|
505
|
+
},
|
|
506
|
+
{ close: false, preserveForm: true },
|
|
507
|
+
),
|
|
508
|
+
};
|
|
509
|
+
document.addEventListener('click', (event) => {
|
|
510
|
+
const section = event.target.closest('[data-section]');
|
|
511
|
+
if (section) {
|
|
512
|
+
event.preventDefault();
|
|
513
|
+
document
|
|
514
|
+
.getElementById(section.dataset.section)
|
|
515
|
+
?.scrollIntoView({ behavior: 'auto', block: 'start' });
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
const anchor = event.target.closest('a[href^="#/"]');
|
|
519
|
+
if (anchor && state.dirty && anchor.hash !== location.hash) {
|
|
520
|
+
event.preventDefault();
|
|
521
|
+
confirm(
|
|
522
|
+
'Discard unsaved changes?',
|
|
523
|
+
'Your unsaved form changes will be lost when you leave this view.',
|
|
524
|
+
'Discard changes',
|
|
525
|
+
() => {
|
|
526
|
+
state.dirty = false;
|
|
527
|
+
location.hash = anchor.hash;
|
|
528
|
+
},
|
|
529
|
+
);
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const el = event.target.closest('[data-action]');
|
|
533
|
+
if (!el || el.disabled) return;
|
|
534
|
+
event.preventDefault();
|
|
535
|
+
Promise.resolve()
|
|
536
|
+
.then(() => actions[el.dataset.action]?.(el))
|
|
537
|
+
.catch((e) => error(e.message));
|
|
538
|
+
});
|
|
539
|
+
document.addEventListener('submit', (event) => {
|
|
540
|
+
const form = event.target.closest('form[data-form]');
|
|
541
|
+
if (!form) return;
|
|
542
|
+
event.preventDefault();
|
|
543
|
+
const values = Object.fromEntries(new FormData(form));
|
|
544
|
+
const submit = onDialogSubmit;
|
|
545
|
+
act(
|
|
546
|
+
'Saving changes…',
|
|
547
|
+
async () => {
|
|
548
|
+
switch (form.dataset.form) {
|
|
549
|
+
case 'dialog':
|
|
550
|
+
await submit(values);
|
|
551
|
+
break;
|
|
552
|
+
case 'new-project': {
|
|
553
|
+
const p = await api('/projects', 'POST', {
|
|
554
|
+
name: values.name.trim(),
|
|
555
|
+
scope: values.scope.trim() || state.meta.defaultScope,
|
|
556
|
+
});
|
|
557
|
+
navigate(p.id, 'scope');
|
|
558
|
+
toast('Project created. Add its sources to begin.');
|
|
559
|
+
break;
|
|
560
|
+
}
|
|
561
|
+
case 'sources':
|
|
562
|
+
await importSources(
|
|
563
|
+
values.locations
|
|
564
|
+
.split('\n')
|
|
565
|
+
.map((value) => value.trim())
|
|
566
|
+
.filter(Boolean),
|
|
567
|
+
);
|
|
568
|
+
break;
|
|
569
|
+
case 'scope':
|
|
570
|
+
await api(projectPath(), 'PATCH', { ...values, revision: Number(form.dataset.revision) });
|
|
571
|
+
toast('Scope saved.');
|
|
572
|
+
break;
|
|
573
|
+
case 'credentials': {
|
|
574
|
+
const patch = {
|
|
575
|
+
...(values.apiKey.trim() ? { apiKey: values.apiKey } : {}),
|
|
576
|
+
...(values.workspaceId?.trim() ? { workspaceId: values.workspaceId.trim() } : {}),
|
|
577
|
+
};
|
|
578
|
+
if (!Object.keys(patch).length) throw new Error('Enter a new API key or workspace ID.');
|
|
579
|
+
const statuses = await api(
|
|
580
|
+
`/providers/${form.dataset.provider}/credentials`,
|
|
581
|
+
'PUT',
|
|
582
|
+
patch,
|
|
583
|
+
);
|
|
584
|
+
form.elements.apiKey.value = '';
|
|
585
|
+
form.dataset.dirty = 'false';
|
|
586
|
+
state.dirty = Boolean(document.querySelector('main form[data-dirty="true"]'));
|
|
587
|
+
form.querySelector('.pill').textContent = 'Key configured';
|
|
588
|
+
form.querySelector('[data-key-source]').textContent =
|
|
589
|
+
`Current source: ${statuses[form.dataset.provider].keySource}. A saved replacement takes precedence over environment settings.`;
|
|
590
|
+
delete state.catalogs[form.dataset.provider];
|
|
591
|
+
toast('Private key settings saved.');
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
case 'models':
|
|
595
|
+
await api(projectPath(), 'PATCH', {
|
|
596
|
+
revision: Number(form.dataset.revision),
|
|
597
|
+
config: {
|
|
598
|
+
provider: form.dataset.provider,
|
|
599
|
+
fastModel: values.fastModel,
|
|
600
|
+
deepModel: values.deepModel,
|
|
601
|
+
effort: values.effort,
|
|
602
|
+
trees: values.trees === 'true',
|
|
603
|
+
treeLimit: Number(values.treeLimit),
|
|
604
|
+
coordination: values.coordination,
|
|
605
|
+
},
|
|
606
|
+
});
|
|
607
|
+
toast('Assessment settings saved.');
|
|
608
|
+
break;
|
|
609
|
+
}
|
|
610
|
+
},
|
|
611
|
+
{ preserveForm: form.dataset.form === 'credentials' },
|
|
612
|
+
);
|
|
613
|
+
});
|
|
614
|
+
document.addEventListener('input', (event) => {
|
|
615
|
+
const form = event.target.closest('main form');
|
|
616
|
+
if (form) {
|
|
617
|
+
form.dataset.dirty = 'true';
|
|
618
|
+
state.dirty = true;
|
|
619
|
+
}
|
|
620
|
+
if (event.target.name === 'threat-search') filterThreats();
|
|
621
|
+
});
|
|
622
|
+
document.addEventListener('change', (event) => {
|
|
623
|
+
const el = event.target;
|
|
624
|
+
if (el.id === 'project-picker') {
|
|
625
|
+
if (state.dirty) {
|
|
626
|
+
const id = el.value;
|
|
627
|
+
el.value = state.project?.id || '';
|
|
628
|
+
confirm(
|
|
629
|
+
'Discard unsaved changes?',
|
|
630
|
+
'Changing assessments will discard the current unsaved form.',
|
|
631
|
+
'Discard changes',
|
|
632
|
+
() => {
|
|
633
|
+
state.dirty = false;
|
|
634
|
+
navigate(id);
|
|
635
|
+
},
|
|
636
|
+
);
|
|
637
|
+
} else navigate(el.value);
|
|
638
|
+
}
|
|
639
|
+
if (el.name === 'settings-provider') {
|
|
640
|
+
const provider = el.value;
|
|
641
|
+
const change = () => {
|
|
642
|
+
state.settingsProvider = provider;
|
|
643
|
+
state.dirty = false;
|
|
644
|
+
render();
|
|
645
|
+
return loadModels(provider);
|
|
646
|
+
};
|
|
647
|
+
if (state.dirty)
|
|
648
|
+
confirm(
|
|
649
|
+
'Change provider?',
|
|
650
|
+
'This resets unsaved settings in this view. Saved settings stay active until you save the new selection.',
|
|
651
|
+
'Change provider',
|
|
652
|
+
change,
|
|
653
|
+
);
|
|
654
|
+
else change().catch((e) => error(e.message));
|
|
655
|
+
}
|
|
656
|
+
if (el.name === 'threat-category') filterThreats();
|
|
657
|
+
if (el.matches('[data-upload]')) {
|
|
658
|
+
const files = [...el.files];
|
|
659
|
+
if (!files.length) return;
|
|
660
|
+
act('Reading source…', async () => {
|
|
661
|
+
if (el.dataset.upload === 'import') {
|
|
662
|
+
if (files[0].size > 16 * 1024 * 1024) throw new Error('Project import exceeds 16 MiB.');
|
|
663
|
+
let snapshot;
|
|
664
|
+
try {
|
|
665
|
+
snapshot = JSON.parse(await files[0].text());
|
|
666
|
+
} catch {
|
|
667
|
+
throw new Error('Choose a valid AiTM project JSON export.');
|
|
668
|
+
}
|
|
669
|
+
const p = await api('/projects/import', 'POST', snapshot);
|
|
670
|
+
navigate(p.id);
|
|
671
|
+
toast('Assessment imported.');
|
|
672
|
+
} else {
|
|
673
|
+
await importSources(await upload(files));
|
|
674
|
+
}
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
});
|
|
678
|
+
function filterThreats() {
|
|
679
|
+
const term = document.querySelector('[name="threat-search"]').value.trim().toLowerCase(),
|
|
680
|
+
category = document.querySelector('[name="threat-category"]').value;
|
|
681
|
+
let visible = 0;
|
|
682
|
+
document.querySelectorAll('[data-threat]').forEach((el) => {
|
|
683
|
+
el.hidden =
|
|
684
|
+
!el.dataset.threat.includes(term) ||
|
|
685
|
+
(category !== 'All categories' && category !== el.dataset.category);
|
|
686
|
+
if (!el.hidden) visible++;
|
|
687
|
+
});
|
|
688
|
+
$('#no-threats').hidden = visible > 0;
|
|
689
|
+
}
|
|
690
|
+
$('#dialog').addEventListener('cancel', (event) => {
|
|
691
|
+
event.preventDefault();
|
|
692
|
+
if (!state.busy) closeDialog();
|
|
693
|
+
});
|
|
694
|
+
window.addEventListener('hashchange', () => route().catch((e) => error(e.message)));
|
|
695
|
+
window.addEventListener('beforeunload', (event) => {
|
|
696
|
+
if (state.dirty) {
|
|
697
|
+
event.preventDefault();
|
|
698
|
+
event.returnValue = '';
|
|
699
|
+
}
|
|
700
|
+
});
|
|
701
|
+
window.addEventListener('focus', () => refresh().catch((e) => error(e.message)));
|
|
702
|
+
setInterval(() => {
|
|
703
|
+
if (activeRun(state.project) && !state.busy) $('#activity').innerHTML = progress(state);
|
|
704
|
+
}, 1000);
|
|
705
|
+
try {
|
|
706
|
+
[state.health, state.meta] = await Promise.all([api('/instance'), api('/meta')]);
|
|
707
|
+
// First run: analysis cannot start without a provider key, so begin in Settings.
|
|
708
|
+
if (
|
|
709
|
+
!location.hash.slice(1).replace('/', '') &&
|
|
710
|
+
!Object.values(await api('/providers')).some((provider) => provider.configured)
|
|
711
|
+
) {
|
|
712
|
+
history.replaceState(null, '', '#/settings');
|
|
713
|
+
toast(
|
|
714
|
+
'Add an API key to run analysis. You can create projects and import sources without one.',
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
await route();
|
|
718
|
+
const changes = new EventSource('/v1/events');
|
|
719
|
+
changes.onmessage = (message) => {
|
|
720
|
+
const { projectId } = JSON.parse(message.data);
|
|
721
|
+
if (!projectId || projectId !== state.project?.id || !streamId) queueRefresh();
|
|
722
|
+
};
|
|
723
|
+
changes.onopen = () => queueRefresh();
|
|
724
|
+
changes.onerror = () => {
|
|
725
|
+
$('#activity').innerHTML = 'Connection interrupted. Reconnecting to the local engine…';
|
|
726
|
+
};
|
|
727
|
+
} catch (e) {
|
|
728
|
+
error(e.message);
|
|
729
|
+
}
|