kryptheon 0.1.44 → 0.1.47

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.
@@ -1,1009 +1,1132 @@
1
- // The local dashboard: one page on this machine that shows everything
2
- // Kryptheon knows about one project, and switches its checks on and off.
3
- //
4
- // npx kryptheon (in a terminal) or npx kryptheon dashboard
5
- //
6
- // Everything here reads the project's store (kryptheon-store.js); nothing is
7
- // kept anywhere else, and nothing leaves the machine. The server listens on
8
- // 127.0.0.1 only.
9
- //
10
- // Two rules the page is built around:
11
- //
12
- // - A check that does not exist yet is shown as "not available". Never as
13
- // passed, never as green, never counted. An empty row that looks like a
14
- // clean one is the most expensive lie this product could tell.
15
- // - Every value shown comes from a file that may hold text from the app being
16
- // checked - a failing page's heading, a line of the app's own code. The page
17
- // writes all of it with textContent, so the dashboard cannot become the XSS
18
- // it is there to find. Its own code is read by kryptheon-code.js in its check.
19
-
20
- const fs = require('fs');
21
- const path = require('path');
22
- const http = require('http');
23
- const crypto = require('crypto');
24
- const { spawnSync } = require('child_process');
25
- const store = require('./kryptheon-store.js');
26
- const changes = require('./kryptheon-changes.js');
27
- const autostart = require('./kryptheon-autostart.js');
28
- const VERSION = require('./package.json').version;
29
-
30
- /**
31
- * Every check the dashboard knows the name of, in the order the person asked
32
- * for them. `available` is true only for what is actually built. What runs it
33
- * and where its results come from is said here, once.
34
- */
35
- const CHECKS = [
36
- { id: 'regression', label: 'Regression (recorded flows)', available: true,
37
- what: 'Replays every recording in tests/ and compares each page with the last time it worked.' },
38
- { id: 'frontend', label: 'Frontend: text inserted as HTML', available: true,
39
- what: 'Reads your frontend code for values put into the page with innerHTML and similar (npx kryptheon code).' },
40
- { id: 'data', label: 'Database: access rules, duplicates, orphans', available: true,
41
- what: 'Attacks a copy of your Postgres/Supabase database (kryptheon-night). Paste the connection string in Start here; it is used for one run and never saved.' },
42
- { id: 'build', label: 'Build', available: false },
43
- { id: 'backend', label: 'Backend', available: false },
44
- { id: 'api', label: 'API', available: false },
45
- { id: 'integration', label: 'Integration', available: false },
46
- { id: 'dependency', label: 'Dependencies', available: false },
47
- { id: 'runtime', label: 'Runtime', available: false },
48
- { id: 'performance', label: 'Performance', available: false },
49
- { id: 'edge', label: 'Input and edge cases', available: false },
50
- { id: 'reliability', label: 'Reliability', available: false },
51
- { id: 'synthetic', label: 'Synthetic test users', available: false },
52
- { id: 'eligibility', label: 'Age and eligibility rules', available: false },
53
- ];
54
-
55
- const CHECK_IDS = new Set(CHECKS.map((c) => c.id));
56
-
57
- function readJson(file) {
58
- try {
59
- let raw = fs.readFileSync(file, 'utf8');
60
- if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1);
61
- return JSON.parse(raw);
62
- } catch (err) {
63
- return null;
64
- }
65
- }
66
-
67
- function readHistory(file, keep) {
68
- let raw;
69
- try {
70
- raw = fs.readFileSync(file, 'utf8');
71
- } catch (err) {
72
- return [];
73
- }
74
- const runs = [];
75
- for (const line of raw.split('\n')) {
76
- if (!line.trim()) continue;
77
- try {
78
- runs.push(JSON.parse(line));
79
- } catch (err) {
80
- /* a damaged line is skipped, not fatal */
81
- }
82
- }
83
- return runs.slice(-keep);
84
- }
85
-
86
- /** Which checks are switched on. Available checks default to on; others can never be. */
87
- function readConfig(paths) {
88
- const saved = readJson(paths.config) || {};
89
- const enabled = {};
90
- for (const c of CHECKS) {
91
- enabled[c.id] = c.available ? (saved.enabled && typeof saved.enabled[c.id] === 'boolean' ? saved.enabled[c.id] : true) : false;
92
- }
93
- return { enabled: enabled };
94
- }
95
-
96
- /**
97
- * Switches one check on or off, and keeps it. Refuses what does not exist and
98
- * what is not built: a "not available" check switched on would read as a
99
- * promise that something is being checked.
100
- */
101
- function setCheck(paths, id, on) {
102
- if (!CHECK_IDS.has(id)) return { ok: false, why: 'there is no check called "' + id + '"' };
103
- const check = CHECKS.find((c) => c.id === id);
104
- if (!check.available) return { ok: false, why: check.label + ' is not available yet, so it cannot be switched on' };
105
- if (typeof on !== 'boolean') return { ok: false, why: 'on must be true or false' };
106
- const config = readConfig(paths);
107
- config.enabled[id] = on;
108
- fs.mkdirSync(path.dirname(paths.config), { recursive: true });
109
- fs.writeFileSync(paths.config, JSON.stringify(config, null, 2) + '\n', 'utf8');
110
- return { ok: true, config: config };
111
- }
112
-
113
- /** What git says changed, read only. Null when this is not a git repository. */
114
- function recentChanges(root) {
115
- const git = (args) => {
116
- const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 5000 });
117
- return r.status === 0 ? String(r.stdout || '') : null;
118
- };
119
- const inside = git(['rev-parse', '--is-inside-work-tree']);
120
- if (!inside || inside.trim() !== 'true') return null;
121
- const log = git(['log', '-5', '--pretty=format:%h%x09%cI%x09%s']) || '';
122
- const status = git(['status', '--porcelain']) || '';
123
- return {
124
- commits: log.split('\n').filter(Boolean).map((l) => {
125
- const [hash, when, subject] = l.split('\t');
126
- return { hash: hash, when: when, subject: subject };
127
- }),
128
- uncommitted: status.split('\n').filter(Boolean).map((l) => ({ state: l.slice(0, 2).trim(), file: l.slice(3) })),
129
- };
130
- }
131
-
132
- /** " - the risky part: x" for a frontend finding that names one, else "". */
133
- function riskyPartsLine(f) {
134
- const parts = (f.parts || []).filter((p) => p && p.text && p.text !== f.expression);
135
- if (!parts.length) return '';
136
- return ' - the risky part' + (parts.length === 1 ? ': ' : 's: ') + parts.map((p) => p.text).join(', ');
137
- }
138
-
139
- /** When this flow last passed, from the run history, or null. */
140
- function lastPassOf(history, title) {
141
- for (let i = history.length - 1; i >= 0; i--) {
142
- const t = (history[i].tests || []).find((x) => x.title === title);
143
- if (t && t.status === 'passed') return history[i].runAt;
144
- }
145
- return null;
146
- }
147
-
148
- /**
149
- * The fix prompt for a broken recorded flow, from what the run kept: what was
150
- * seen, what was expected, where, the evidence, and how to see it again. Only
151
- * what the run recorded is said; nothing is guessed.
152
- */
153
- function flowPrompt(t, lastPass) {
154
- const f = t.failure || {};
155
- const o = f.observations || {};
156
- const file = String(f.file || t.specFile || 'tests').split('\\').join('/');
157
- const extra = String(f.rawMessage || '').split(/\r?\n/).slice(1)
158
- .map((l) => l.trim()).filter((l) => l && !/^\s*at\s/.test(l) && l.length < 200).slice(0, 6);
159
- const lines = [
160
- 'My app has a broken flow. Please fix the app - and nothing else.',
161
- '',
162
- 'Kryptheon replayed the recorded flow "' + t.title + '" (' + file + (f.line ? ', line ' + f.line : '') + ') and it failed.',
163
- '',
164
- 'Observed: ' + (f.plainLanguage || 'the replay failed'),
165
- ].concat(extra.map((l) => ' ' + l), [
166
- 'Expected: the same result as ' + (lastPass ? 'the last time it passed (' + lastPass + ')' : 'when it was recorded') + '.',
167
- ]);
168
- if (o.url) lines.push('Where: the browser was on ' + o.url + (o.pageShowed ? ', and the page showed ' + o.pageShowed : '') + '.');
169
- if (f.locator) lines.push('Step that failed: ' + f.locator);
170
- if (o.failedRequests && o.failedRequests.length) lines.push('Failed requests: ' + o.failedRequests.slice(0, 5).map((r) => (r.method || 'GET') + ' ' + (r.path || r.url) + ' -> ' + r.status).join('; '));
171
- if (o.consoleErrors && o.consoleErrors.length) lines.push('Console errors: ' + o.consoleErrors.slice(0, 3).join(' | '));
172
- if (f.screenshot) lines.push('Evidence: a screenshot of the failure at ' + f.screenshot);
173
- lines.push('');
174
- lines.push('To see it yourself: open ' + (o.url || 'the app') + ' and repeat the steps in ' + file + ', or run npx kryptheon check');
175
- lines.push('');
176
- lines.push('Fix the app so this flow works again. Do not edit the recording to make it pass. If the new behaviour ' +
177
- 'is intended, say so instead of changing code - it can be accepted with npx kryptheon accept "' + t.title + '"');
178
- return lines.join('\n');
179
- }
180
-
181
- function countRecordings(root) {
182
- try {
183
- // Recordings only - not the project's own unit tests in tests/.
184
- return require('./kryptheon-testfiles.js').recordingNames(path.join(root, 'tests')).length;
185
- } catch (err) {
186
- return 0;
187
- }
188
- }
189
-
190
- /**
191
- * The order someone new should go in, one step at a time. A step is "done"
192
- * only when it has actually run and left a record - never because nothing was
193
- * found - and a switched-off check says "off", so an empty list is never read
194
- * as a clean one.
195
- */
196
- // How often a step is done. Said on every step and button, because the two
197
- // kinds are done at different moments and mixing them up is how a check stops
198
- // being run: "one time" is setting up, "after every change" is the habit.
199
- const ONE_TIME = 'one time';
200
- const EVERY_CHANGE = 'after every change';
201
-
202
- function startSteps(checks, seen) {
203
- const on = (id) => (checks.find((c) => c.id === id) || {}).enabled;
204
- const nightly = seen.nightly || null;
205
- // With no code on this computer - the home folder's dashboard - there is
206
- // no code to read, and "Read your frontend code" would only say it read
207
- // nothing. The app is checked by its address.
208
- return startStepList(on, seen, nightly).filter((s) => !(seen.webOnly && s.id === 'frontend'));
209
- }
210
-
211
- function startStepList(on, seen, nightly) {
212
- return [
213
- {
214
- id: 'frontend',
215
- title: 'Read your frontend code',
216
- when: EVERY_CHANGE,
217
- why: 'Finds places where text could be put into your page as HTML. Needs nothing from you.',
218
- state: !on('frontend') ? 'off' : seen.codeAt ? 'done' : 'todo',
219
- at: seen.codeAt,
220
- action: on('frontend') ? { kind: 'run', check: 'frontend', label: seen.codeAt ? 'Read it again' : 'Read my code', command: RUN_COMMAND.frontend } : null,
221
- },
222
- {
223
- id: 'record',
224
- title: 'Record your main flows',
225
- when: ONE_TIME,
226
- whenMore: 'again only when that flow changes',
227
- // The lesson of a test where 26 bugs were planted before recording and
228
- // none was caught: what is recorded is taken as right.
229
- why: 'Sign up, log in, pay - do each once while Kryptheon watches. Record while your app works: what it sees is taken as right, so a bug already there when you record becomes part of "working". Start your app first, then put its address here.',
230
- state: seen.recordings ? 'done' : 'todo',
231
- at: null,
232
- count: seen.recordings,
233
- action: { kind: 'record', label: seen.recordings ? 'Record another' : 'Record', command: 'npx kryptheon record <your app address>' },
234
- },
235
- {
236
- id: 'regression',
237
- title: 'Replay them',
238
- when: EVERY_CHANGE,
239
- why: 'Runs every recording against your app and compares each page with the last time it worked. Start your app first.',
240
- state: !on('regression') ? 'off' : !seen.recordings ? 'waiting' : seen.lastRunAt ? 'done' : 'todo',
241
- at: seen.lastRunAt,
242
- action: on('regression') && seen.recordings ? { kind: 'run', check: 'regression', label: seen.lastRunAt ? 'Replay again' : 'Replay now', command: RUN_COMMAND.regression } : null,
243
- },
244
- {
245
- id: 'connect',
246
- title: 'Connect your database',
247
- when: ONE_TIME,
248
- why: 'Paste your connection string - the steps are next to the box. It goes only to this dashboard on your machine and to kryptheon-night for the length of one run. It is never saved and never shown again; reload the page and it is gone. Try it on a test project first.',
249
- state: !on('data') ? 'off' : seen.nightAt ? 'done' : 'todo',
250
- at: null,
251
- action: on('data') ? { kind: 'connect' } : null,
252
- },
253
- {
254
- id: 'data',
255
- title: 'Check your database',
256
- when: EVERY_CHANGE,
257
- why: 'Attacks a copy inside your Postgres or Supabase database and reports what got in; your own rows are not touched. You are shown exactly what it will do, and it waits for your yes.',
258
- state: !on('data') ? 'off' : seen.nightAt ? 'done' : 'todo',
259
- at: seen.nightAt,
260
- action: on('data') ? { kind: 'db', action: 'scan', label: 'Check my database', command: DB_ACTIONS.scan.command } : null,
261
- },
262
- {
263
- id: 'nightly',
264
- title: 'Check it every night',
265
- when: ONE_TIME,
266
- // Offered, never pressed for: an app can be checked well without it,
267
- // so it is not what "do this next" points at.
268
- optional: true,
269
- why: 'Sets the same check up inside your database, to run by itself every night, and keeps the answer there for this page. It stays until you remove it.',
270
- state: !on('data') ? 'off' : nightly && nightly.installed && nightly.active ? 'done' : 'todo',
271
- at: nightly && nightly.ranAt ? nightly.ranAt : null,
272
- action: on('data') ? { kind: 'nightly', installed: Boolean(nightly && nightly.installed), at: nightly ? nightly.scheduled || null : null } : null,
273
- },
274
- ];
275
- }
276
-
277
- /**
278
- * The one thing to do now. Open confirmed problems come before everything; then
279
- * the first step not taken; then what only needs a look; then nothing.
280
- */
281
- function nextAction(findings, steps) {
282
- const confirmed = findings.filter((f) => f.status === 'confirmed').length;
283
- const toVerify = findings.length - confirmed;
284
- if (confirmed) {
285
- return { kind: 'fix', view: 'findings', count: confirmed,
286
- title: confirmed === 1 ? 'Fix 1 confirmed problem' : 'Fix ' + confirmed + ' confirmed problems' };
287
- }
288
- const step = steps.find((s) => s.state === 'todo' && !s.optional);
289
- if (step) return { kind: 'step', step: step.id, title: step.title };
290
- if (toVerify) {
291
- return { kind: 'verify', view: 'findings', count: toVerify,
292
- title: toVerify === 1 ? 'Look at 1 thing to verify' : 'Look at ' + toVerify + ' things to verify' };
293
- }
294
- return { kind: 'quiet', title: 'Nothing open' };
295
- }
296
-
297
- /**
298
- * One prompt that fixes every open finding at once, for pasting into an AI
299
- * tool, or '' when fewer than two findings have a prompt (one is its own).
300
- * Each finding's own prompt goes in as it is, in the order the page shows
301
- * them, most severe first. Around them are the rules that keep a fix from
302
- * breaking something else: only what is listed, the smallest change, one at
303
- * a time with the app checked between, nothing weakened to make a finding go
304
- * away, ask rather than guess. The re-checks come once, at the end.
305
- *
306
- * items: [{ id, severity, headline, where, prompt }] - prompt without its
307
- * re-check line.
308
- */
309
- function combinedPrompt(items) {
310
- const withPrompt = items.filter((f) => f.prompt);
311
- if (withPrompt.length < 2) return '';
312
- const n = withPrompt.length;
313
- const lines = [
314
- 'Kryptheon checked this project and found ' + n + ' problems. Fix all ' + n + ', carefully - not breaking anything matters more than speed.',
315
- '',
316
- 'Rules for every fix:',
317
- '1. Fix only the problems listed below. Do not refactor, rename, reformat or "improve" anything else, and do not touch a file a fix does not need.',
318
- '2. Make the smallest change that fixes each one. Every feature must keep working exactly as it does now for the people meant to use it.',
319
- '3. Never delete or weaken a check, test, validation or security rule to make a problem go away, and never delete or rewrite existing data.',
320
- '4. Do them one at a time, in the order below. After each one, make sure the app still builds and its existing tests still pass before starting the next.',
321
- '5. If a fix needs a decision only I can make, or you are not sure a change is safe, stop and ask me instead of guessing.',
322
- '6. When you are done, list every file you changed and why, one line each.',
323
- ];
324
- withPrompt.forEach((f, i) => {
325
- lines.push('', '======== Problem ' + (i + 1) + ' of ' + n + ' - ' + f.severity + ': ' + f.headline + (f.where ? ' (' + f.where + ')' : ''), '', f.prompt.trim());
326
- });
327
- lines.push('', '======== When all ' + n + ' are fixed',
328
- '',
329
- 'Prove each fix: run these one at a time (or press Re-check on each finding in the Kryptheon dashboard). A fix counts only when it says FIXED, and a re-check also says if anything else newly broke - if it does, fix that before anything else.',
330
- '');
331
- withPrompt.forEach((f) => lines.push(' npx kryptheon recheck ' + f.id));
332
- return lines.join('\n');
333
- }
334
-
335
- /**
336
- * One sentence about the nightly run inside the database, or null when
337
- * kryptheon-night has never been asked. Its four states are four different
338
- * answers, and none of the other three may read as "nothing found": not set
339
- * up, set up and never run, set up with nothing scheduled, and stopped.
340
- */
341
- function nightlyLine(nightly) {
342
- if (!nightly) return null;
343
- // The database runs on UTC. Found on a real read-back: "03:00" was 08:30
344
- // in India, and nothing said so - so both are said, and the moment it was
345
- // read is said in this computer's own time.
346
- const local = (iso) => new Date(iso).toLocaleString('en-GB', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
347
- const day = (iso) => String(iso || '').slice(0, 16).replace('T', ' ') + ' UTC (' + local(iso) + ' your time)';
348
- const read = ' (read ' + local(nightly.readAt) + ')';
349
- if (!nightly.installed) return 'Nightly run in your database: not set up. Press "Set up nightly check" in Start here.' + read;
350
- const idle = nightly.active ? '' : ' Nothing is scheduled, so it is not running - press "Set it up again" in Start here.';
351
- if (!nightly.ranAt) return 'Nightly run in your database: set up, and it has not run yet.' + idle + read;
352
- const when = 'Nightly run in your database, ' + day(nightly.ranAt) + ': ';
353
- if (nightly.stopped) return when + 'it could not check - ' + nightly.stopped + idle + read;
354
- // A function anyone can call is a thing to check, not a problem proven -
355
- // counted apart, the way the terminal counts it.
356
- const n = (nightly.findings || []).filter((f) => f.status !== 'verification required').length;
357
- const toCheck = (nightly.findings || []).length - n;
358
- const skipped = (nightly.notChecked || []).length;
359
- return when + (n ? n + (n === 1 ? ' problem found.' : ' problems found.')
360
- : 'nothing got through ' + (nightly.attacksRun || 0) + ' attacks.') +
361
- (toCheck ? ' ' + toCheck + (toCheck === 1 ? ' thing' : ' things') + ' to check.' : '') +
362
- (skipped ? ' ' + skipped + ' ' + (skipped === 1 ? 'part was' : 'parts were') + ' not tested.' : '') + idle + read;
363
- }
364
-
365
- /**
366
- * Everything the page shows, from the store alone. Findings from every check
367
- * are put into one list, each carrying the same fields - severity, status,
368
- * evidence, confidence, where, what, and the fix - so the page can show them
369
- * the same way whichever check found them.
370
- */
371
- function buildState(root, env) {
372
- const paths = store.pathsFor(root, env);
373
- const config = readConfig(paths);
374
- const history = readHistory(paths.history, 20);
375
- const baselines = readJson(paths.baselines) || {};
376
- const code = readJson(paths.codeFindings);
377
- const night = readJson(paths.nightLast);
378
- // What the nightly run inside the database last said, kept by
379
- // kryptheon-night whenever it connects. Not the same answer as night:
380
- // that one is the scan last run from this terminal.
381
- const nightly = readJson(paths.nightNightly);
382
-
383
- const findings = [];
384
-
385
- // Recorded flows: the last run's broken tests are the findings. They were
386
- // replayed in a real browser, so they are confirmed at runtime.
387
- const lastRun = history.length ? history[history.length - 1] : null;
388
- if (lastRun && config.enabled.regression) {
389
- for (const t of lastRun.tests || []) {
390
- if (t.status !== 'failed' && t.status !== 'timedOut') continue;
391
- findings.push({
392
- check: 'regression',
393
- severity: 'HIGH',
394
- status: 'confirmed',
395
- evidence: 'runtime confirmed',
396
- confidence: 'high',
397
- where: String((t.failure && t.failure.file) || t.specFile || 'tests').split('\\').join('/') +
398
- (t.failure && t.failure.line ? ':' + t.failure.line : ''),
399
- headline: 'The recorded flow "' + t.title + '" broke.',
400
- detail: (t.failure && t.failure.plainLanguage) || '',
401
- fixPrompt: flowPrompt(t, lastPassOf(history, t.title)),
402
- when: lastRun.runAt,
403
- });
404
- }
405
- }
406
-
407
- if (code && config.enabled.frontend) {
408
- for (const f of code.findings || []) {
409
- findings.push({
410
- check: 'frontend',
411
- severity: f.severity,
412
- status: f.status,
413
- evidence: f.evidence,
414
- confidence: f.confidence,
415
- where: f.file + ':' + f.line,
416
- headline: f.headline,
417
- // The part of a long template that decides it, so the person reading
418
- // it looks at one value instead of sixty lines of markup.
419
- detail: f.sink + ': ' + f.expression + riskyPartsLine(f),
420
- fixPrompt: f.fixPrompt,
421
- when: code.checkedAt,
422
- });
423
- }
424
- }
425
-
426
- let nightWhen = null;
427
- try {
428
- nightWhen = fs.statSync(paths.nightLast).mtime.toISOString();
429
- } catch (err) {
430
- /* never run */
431
- }
432
- if (night && config.enabled.data) {
433
- for (const f of night.findings || []) {
434
- findings.push({
435
- check: 'data',
436
- severity: f.severity,
437
- status: f.status || 'confirmed',
438
- evidence: (f.status || 'confirmed') === 'confirmed' ? 'runtime confirmed' : 'code analysis',
439
- confidence: (f.status || 'confirmed') === 'confirmed' ? 'high' : 'medium',
440
- where: f.table + (f.column ? '.' + f.column : ''),
441
- headline: f.headline,
442
- detail: f.body || '',
443
- fixPrompt: f.fixPrompt || '',
444
- when: nightWhen,
445
- });
446
- }
447
- }
448
-
449
- // The nightly run's findings, said as coming from it. One both answers
450
- // share is shown once, with the newer date - the same problem found twice
451
- // is still one problem to fix.
452
- if (nightly && nightly.ranAt && config.enabled.data) {
453
- for (const f of nightly.findings || []) {
454
- const item = {
455
- check: 'data',
456
- from: 'nightly',
457
- severity: f.severity,
458
- status: f.status || 'confirmed',
459
- evidence: (f.status || 'confirmed') === 'confirmed' ? 'runtime confirmed' : 'code analysis',
460
- confidence: (f.status || 'confirmed') === 'confirmed' ? 'high' : 'medium',
461
- where: f.table + (f.column ? '.' + f.column : ''),
462
- headline: f.headline,
463
- detail: f.body || '',
464
- fixPrompt: f.fixPrompt || '',
465
- when: nightly.ranAt,
466
- };
467
- const same = findings.find((o) => o.check === 'data' && changes.findingKey(o) === changes.findingKey(item));
468
- if (!same) findings.push(item);
469
- else {
470
- same.from = 'both';
471
- if (!same.when || item.when > same.when) same.when = item.when;
472
- }
473
- }
474
- }
475
-
476
- const rank = { 'HIGH CRITICAL': 0, CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3 };
477
- findings.sort((a, b) => (rank[a.severity] ?? 9) - (rank[b.severity] ?? 9) ||
478
- (a.status === 'confirmed' ? 0 : 1) - (b.status === 'confirmed' ? 0 : 1));
479
-
480
- // Every finding gets a short id and the last word of its fix prompt: how to
481
- // prove the fix. Added here, where the loop lives, so every check's prompt
482
- // ends the same way and the detection code itself stays untouched.
483
- const attempts = readHistory(paths.fixes, 500);
484
- const forAll = [];
485
- for (const f of findings) {
486
- f.id = changes.findingId(f);
487
- f.attempts = attempts.filter((a) => a.id === f.id).map((a) => ({ at: a.at, verdict: a.verdict, why: a.why || '', newProblems: (a.newProblems || []).length }));
488
- forAll.push({ id: f.id, severity: f.severity, headline: f.headline, where: f.where, prompt: f.fixPrompt || '' });
489
- if (f.fixPrompt) {
490
- f.fixPrompt += '\n\nWhen you have fixed it, prove it: run npx kryptheon recheck ' + f.id +
491
- ' (or press Re-check on this finding in the Kryptheon dashboard). It is fixed only when that says FIXED.';
492
- }
493
- }
494
- // Fixes that were proven, newest first, while their finding is still gone.
495
- const open = new Set(findings.map((f) => f.id));
496
- const proven = attempts.filter((a) => a.verdict === 'fixed' && !open.has(a.id)).reverse().slice(0, 10)
497
- .map((a) => ({ id: a.id, at: a.at, where: a.where, headline: a.headline, newProblems: (a.newProblems || []).length }));
498
-
499
- const recordings = countRecordings(root);
500
- const checks = CHECKS.map((c) => {
501
- let state;
502
- if (!c.available) state = 'not available';
503
- else if (!config.enabled[c.id]) state = 'switched off';
504
- else if (c.id === 'regression') state = !recordings ? 'no recordings yet' : !lastRun ? 'never run' : lastRun.failed ? 'problems found' : 'last run held';
505
- else if (c.id === 'frontend') state = !code ? 'never run' : (code.findings || []).length ? 'things to check' : 'nothing found';
506
- else if (c.id === 'data') {
507
- const ranNightly = nightly && nightly.ranAt && !nightly.stopped;
508
- state = !night && !ranNightly ? 'never run here'
509
- : findings.some((f) => f.check === 'data') ? 'problems found' : 'last run held';
510
- }
511
- return {
512
- id: c.id, label: c.label, available: c.available, enabled: config.enabled[c.id], state: state, what: c.what || '',
513
- nightly: c.id === 'data' ? nightlyLine(nightly) : null,
514
- // Runnable from the page: what needs nothing the page cannot supply. The
515
- // database check needs a connection string, which stays in the terminal.
516
- runnable: c.available && (c.id === 'frontend' || (c.id === 'regression' && recordings > 0)),
517
- };
518
- });
519
-
520
- const webOnly = isHomeKept(root, env);
521
- const steps = startSteps(checks, {
522
- webOnly: webOnly,
523
- codeAt: code ? code.checkedAt : null,
524
- recordings: recordings,
525
- lastRunAt: lastRun ? lastRun.runAt : null,
526
- nightAt: [night ? nightWhen : null, nightly && nightly.ranAt].filter(Boolean).sort().pop() || null,
527
- nightly: nightly,
528
- });
529
-
530
- // Every look Kryptheon took - by `verify`, or by the dashboard's own watch -
531
- // newest first: what changed, what was run, and what came of it.
532
- const looks = readHistory(paths.changes, 15).reverse().map((e) => ({
533
- at: e.at,
534
- by: e.by || 'verify',
535
- first: !!e.first,
536
- files: (e.files || []).slice(0, 30),
537
- fileCount: (e.files || []).length,
538
- parts: e.parts || [],
539
- dependencies: e.dependencies || [],
540
- checks: e.checks || [],
541
- newFindings: e.newFindings || 0,
542
- fixed: e.fixed || 0,
543
- goneWithFile: e.goneWithFile || 0,
544
- }));
545
-
546
- return {
547
- project: { name: path.basename(root), root: root, storeDir: paths.dir },
548
- // Which kryptheon this dashboard is: a newer `dashboard` asks, and takes
549
- // the place of an older one still running, instead of opening it.
550
- kryptheon: VERSION,
551
- looks: looks,
552
- proven: proven,
553
- checks: checks,
554
- findings: findings,
555
- allFixPrompt: combinedPrompt(forAll),
556
- runs: history.slice().reverse().map((r) => ({ runAt: r.runAt, status: r.status, passed: r.passed, failed: r.failed, durationMs: r.durationMs })),
557
- recordings: recordings,
558
- steps: steps,
559
- // Which app this dashboard is for: its web address, kept here, and whether
560
- // its code is on this computer at all. The dashboard started from the home
561
- // folder (Win+R) holds recordings only - the app is a web address.
562
- app: {
563
- address: readAppAddress(paths),
564
- webOnly: webOnly,
565
- folder: root,
566
- canChooseFolder: process.platform === 'win32' || process.platform === 'darwin',
567
- },
568
- next: nextAction(findings, steps),
569
- baselines: Object.keys(baselines).length,
570
- changes: recentChanges(root),
571
- // Part 3 is where a version gets verified. Until then this says so,
572
- // rather than leaving a blank that could be read either way.
573
- verification: { state: 'not verified', why: 'Kryptheon Verified is not built yet. No version of this project has been verified.' },
574
- // Whether this dashboard starts by itself when the person signs in.
575
- autostart: (() => { const s = autostart.status(root, env); return { available: s.available, on: s.on, why: s.why || '' }; })(),
576
- };
577
- }
578
-
579
- /* --------------------------------------------------------------------------
580
- Jobs: what the page starts, one at a time, with its progress and its end.
581
- -------------------------------------------------------------------------- */
582
-
583
- // What each run is called on the page, and the command that does the same in
584
- // a terminal - shown under every button, for when the page cannot be used.
585
- const RUN_TITLE = { frontend: 'Reading your code', regression: 'Replaying your recordings' };
586
- const RUN_COMMAND = { frontend: 'npx kryptheon code', regression: 'npx kryptheon check' };
587
- const DB_ACTIONS = {
588
- scan: { title: 'Checking your database', command: 'npx kryptheon-night' },
589
- install: { title: 'Setting up the nightly check', command: 'npx kryptheon-night install' },
590
- night: { title: 'Reading last night\'s result', command: 'npx kryptheon-night night' },
591
- uninstall: { title: 'Removing the nightly check', command: 'npx kryptheon-night uninstall' },
592
- recheck: { title: 'Re-checking in your database', command: 'npx kryptheon-night' },
593
- };
594
-
595
- /**
596
- * What a fresh database check says about one database finding. Fixed only
597
- * when the check ran, the finding is gone, and nothing about its table went
598
- * untested - a table that could not be tested loses its findings too, and
599
- * that is not a fix. A finding still shown only from the nightly run is the
600
- * nightly run's older answer, not this one's.
601
- */
602
- function databaseVerdict(target, before, after, ran, saved) {
603
- const tableOf = (where) => String(where || '').split('.')[0];
604
- let verdict;
605
- let why = '';
606
- const untested = ((saved && saved.notChecked) || []).find((n) => tableOf(n.table) === tableOf(target.where));
607
- if (!ran || !ran.ok) {
608
- verdict = 'could not confirm';
609
- why = (ran && ran.why) || 'the database check could not run';
610
- } else if (after.some((f) => f.id === target.id && f.from !== 'nightly')) {
611
- verdict = 'still open';
612
- } else if (untested) {
613
- verdict = 'could not confirm';
614
- why = 'part of ' + tableOf(target.where) + ' could not be tested this time: ' + untested.why;
615
- } else {
616
- verdict = 'fixed';
617
- }
618
- const had = new Set(before.map((f) => f.id));
619
- return {
620
- id: target.id,
621
- at: new Date().toISOString(),
622
- check: 'data',
623
- where: target.where,
624
- headline: target.headline,
625
- verdict: verdict,
626
- why: why,
627
- newProblems: after.filter((f) => !had.has(f.id) && f.check === 'data').map((f) => ({
628
- id: f.id, check: f.check, severity: f.severity, status: f.status, where: f.where, headline: f.headline,
629
- })),
630
- };
631
- }
632
- const JOB_LINES = 400;
633
-
634
- /**
635
- * The address to record, or null. Refused: anything that is not one line,
636
- * anything that could be read as an option by the command it is passed to,
637
- * and anything with a scheme other than http(s).
638
- */
639
- /**
640
- * The dashboard started from the home folder: the kryptheon-tests folder
641
- * there, which holds recordings and nothing of the app's own code.
642
- */
643
- function isHomeKept(root, env) {
644
- const environment = env || process.env;
645
- const home = environment.USERPROFILE || environment.HOME || require('os').homedir();
646
- const tidy = (p) => (process.platform === 'win32' ? path.resolve(p).toLowerCase() : path.resolve(p));
647
- return path.basename(root) === 'kryptheon-tests' && tidy(path.dirname(root)) === tidy(home);
648
- }
649
-
650
- /** The app's web address, as saved on the page - or empty. */
651
- function readAppAddress(paths) {
652
- const saved = readJson(path.join(paths.dir, 'app.json'));
653
- return saved && typeof saved.address === 'string' ? saved.address : '';
654
- }
655
-
656
- function saveAppAddress(paths, address) {
657
- try {
658
- fs.mkdirSync(paths.dir, { recursive: true });
659
- fs.writeFileSync(path.join(paths.dir, 'app.json'), JSON.stringify({ address: address, savedAt: new Date().toISOString() }, null, 2));
660
- return true;
661
- } catch (err) {
662
- return false;
663
- }
664
- }
665
-
666
- function appAddress(value) {
667
- if (typeof value !== 'string') return null;
668
- const text = value.trim();
669
- if (!text || text.length > 2000 || /[\s\x00-\x1f]/.test(text) || text.startsWith('-')) return null;
670
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) return /^https?:\/\/[^/]/i.test(text) ? text : null;
671
- // A path never starts with "//": "http//localhost:3000" is a mistyped
672
- // scheme, not a host called "http".
673
- return /^[a-z0-9.-]+(:\d{1,5})?(\/(?!\/)\S*)?$/i.test(text) ? text : null;
674
- }
675
-
676
- /**
677
- * What was meant, when an address was typed with its start mistyped:
678
- * "ttp://127.0.0.1:4180" (blind round 13, the first letter lost), "htp://",
679
- * "http//", "http:/", "htps://". Null when it does not look like that.
680
- */
681
- function meantAddress(value) {
682
- const text = String(value || '').trim();
683
- const m = /^(h?t{1,3}p{1,2}(s?)|htps|hhttps?)(:\/{0,3}|\/{1,3}|:)(?!\/)(\S+)$/i.exec(text);
684
- if (!m) return null;
685
- const secure = /s$/i.test(m[1]);
686
- const fixed = (secure ? 'https://' : 'http://') + m[4];
687
- return fixed !== text && appAddress(fixed) ? fixed : null;
688
- }
689
-
690
- function notAnAddress(value, example) {
691
- const meant = meantAddress(value);
692
- return meant
693
- ? 'that is not a web address - did you mean ' + meant + '?'
694
- : 'that is not a web address - it should look like ' + example;
695
- }
696
-
697
- /** The connection string as given, or null when there is none or it is absurd. */
698
- function connectionFrom(value) {
699
- if (typeof value !== 'string') return null;
700
- const text = value.trim();
701
- return text && text.length <= 4000 ? text : null;
702
- }
703
-
704
- /**
705
- * Every form in which a connection string could leak back out: the whole
706
- * string, without the quotes it may have been pasted with, and its password
707
- * both as typed and decoded. Longest first, so a password inside the whole
708
- * string is never left half-hidden.
709
- */
710
- function secretsOf(connection) {
711
- const raw = String(connection || '').trim();
712
- if (!raw) return [];
713
- const found = [raw, raw.replace(/^["']|["']$/g, '')];
714
- try {
715
- const password = new URL(found[1]).password;
716
- if (password) {
717
- found.push(password);
718
- try { found.push(decodeURIComponent(password)); } catch (err) { /* kept as typed */ }
719
- }
720
- } catch (err) {
721
- /* not a URL: the string itself is still hidden */
722
- }
723
- return Array.from(new Set(found.filter((s) => s.length >= 4))).sort((a, b) => b.length - a.length);
724
- }
725
-
726
- function hideSecrets(text, secrets) {
727
- let out = String(text);
728
- for (const s of secrets || []) out = out.split(s).join('[hidden]');
729
- return out;
730
- }
731
-
732
- /** The same, through every string in a value. */
733
- function hideSecretsIn(value, secrets) {
734
- if (!secrets || !secrets.length) return value;
735
- if (typeof value === 'string') return hideSecrets(value, secrets);
736
- if (Array.isArray(value)) return value.map((v) => hideSecretsIn(v, secrets));
737
- if (value && typeof value === 'object') {
738
- const out = {};
739
- for (const k of Object.keys(value)) out[k] = hideSecretsIn(value[k], secrets);
740
- return out;
741
- }
742
- return value;
743
- }
744
-
745
- /**
746
- * The one job that may run, and the last one that did. Its lines are what the
747
- * work said as it went, scrubbed of any secret it was given before they are
748
- * kept; when it ends, the secrets are let go.
749
- */
750
- function createJobs() {
751
- let current = null;
752
- let count = 0;
753
- const view = (job) => job && {
754
- id: job.id, kind: job.kind, title: job.title, command: job.command,
755
- startedAt: job.startedAt, endedAt: job.endedAt, running: job.running,
756
- lines: job.lines.slice(), result: job.result,
757
- };
758
- return {
759
- get: () => view(current),
760
- busy: () => Boolean(current && current.running),
761
- start(kind, title, command, work, givenSecrets) {
762
- if (current && current.running) return null;
763
- let secrets = givenSecrets || [];
764
- const job = {
765
- id: ++count, kind: kind, title: title, command: command || '',
766
- startedAt: new Date().toISOString(), endedAt: null, running: true, lines: [], result: null,
767
- };
768
- current = job;
769
- const say = (text) => {
770
- if (!job.running) return;
771
- // Colour codes are for terminals; on the page they are noise.
772
- const clean = hideSecrets(String(text == null ? '' : text), secrets).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '');
773
- for (const line of clean.split(/\r?\n/)) job.lines.push(line.slice(0, 500));
774
- if (job.lines.length > JOB_LINES) job.lines.splice(0, job.lines.length - JOB_LINES);
775
- };
776
- const finish = (result) => {
777
- job.result = hideSecretsIn(result && typeof result === 'object' ? result : { ok: false, why: 'the run gave no answer' }, secrets);
778
- job.running = false;
779
- job.endedAt = new Date().toISOString();
780
- secrets = null;
781
- };
782
- Promise.resolve()
783
- .then(() => work(say))
784
- .then(finish, (err) => finish({ ok: false, why: err && err.message ? err.message : String(err) }));
785
- return view(job);
786
- },
787
- };
788
- }
789
-
790
- /**
791
- * The server. Local only, and closed to other web pages:
792
- * - it listens on 127.0.0.1, never on the network;
793
- * - it answers only when the Host header is this address, so a page on some
794
- * other site cannot reach it through DNS rebinding;
795
- * - anything that changes something needs the token that is written into the
796
- * page this server hands out, which another site cannot read.
797
- */
798
- function createServer(root, options) {
799
- const opts = options || {};
800
- const env = opts.env || process.env;
801
- const token = crypto.randomBytes(24).toString('hex');
802
- const page = fs.readFileSync(path.join(__dirname, 'kryptheon-dashboard.html'), 'utf8');
803
- let port = 0;
804
- const jobs = createJobs();
805
-
806
- const allowedHosts = () => new Set(['127.0.0.1:' + port, 'localhost:' + port]);
807
- const send = (res, code, type, body) => {
808
- res.writeHead(code, {
809
- 'content-type': type,
810
- 'cache-control': 'no-store',
811
- 'x-content-type-options': 'nosniff',
812
- 'referrer-policy': 'no-referrer',
813
- // The page loads nothing from anywhere else, and says so.
814
- 'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
815
- });
816
- res.end(body);
817
- };
818
- // Files served as they are from next to this one. A missing one is a
819
- // missing picture or font, never a stopped dashboard.
820
- const ASSETS = {
821
- '/logo.png': ['image/png', opts.logoFile || path.join(__dirname, 'kryptheon-logo.png')],
822
- '/fonts/archivo.woff2': ['font/woff2', path.join(__dirname, 'kryptheon-archivo.woff2')],
823
- '/fonts/spacemono.woff2': ['font/woff2', path.join(__dirname, 'kryptheon-spacemono.woff2')],
824
- };
825
- const json = (res, code, value) => send(res, code, 'application/json; charset=utf-8', JSON.stringify(value));
826
-
827
- const server = http.createServer((req, res) => {
828
- if (!allowedHosts().has(String(req.headers.host || ''))) return send(res, 403, 'text/plain', 'Forbidden');
829
- const url = new URL(req.url, 'http://127.0.0.1');
830
-
831
- if (req.method === 'GET' && url.pathname === '/') {
832
- return send(res, 200, 'text/html; charset=utf-8', page.replace('%%TOKEN%%', token));
833
- }
834
- if (req.method === 'GET' && url.pathname === '/dashboard.js') {
835
- return send(res, 200, 'text/javascript; charset=utf-8', fs.readFileSync(path.join(__dirname, 'kryptheon-dashboard-page.js'), 'utf8'));
836
- }
837
- if (req.method === 'GET' && Object.prototype.hasOwnProperty.call(ASSETS, url.pathname)) {
838
- const [type, file] = ASSETS[url.pathname];
839
- let body;
840
- try {
841
- body = fs.readFileSync(file);
842
- } catch (err) {
843
- return send(res, 404, 'text/plain', 'Not found');
844
- }
845
- return send(res, 200, type, body);
846
- }
847
- if (req.method === 'GET' && url.pathname === '/api/state') {
848
- return json(res, 200, buildState(root, env));
849
- }
850
- if (req.method === 'GET' && url.pathname === '/api/job') {
851
- return json(res, 200, { job: jobs.get() });
852
- }
853
- if (req.method === 'POST') {
854
- if (req.headers['x-kryptheon-token'] !== token) return json(res, 403, { ok: false, why: 'missing or wrong token' });
855
- let body = '';
856
- req.on('data', (chunk) => {
857
- body += chunk;
858
- if (body.length > 10000) req.destroy();
859
- });
860
- req.on('end', () => {
861
- let input;
862
- try {
863
- input = JSON.parse(body || '{}');
864
- } catch (err) {
865
- return json(res, 400, { ok: false, why: 'not JSON' });
866
- }
867
- if (url.pathname === '/api/check') {
868
- const r = setCheck(store.pathsFor(root, env), String(input.id || ''), input.on);
869
- return json(res, r.ok ? 200 : 400, r);
870
- }
871
- if (url.pathname === '/api/autostart') {
872
- const r = autostart.setAutostart(root, input.on, env);
873
- return json(res, r.ok ? 200 : 400, { ok: r.ok, on: !!r.on, why: r.why || '' });
874
- }
875
- // Everything below starts a job: it answers at once with the job, and
876
- // the page follows it on /api/job. One at a time - two browsers
877
- // replaying against one app, or two attacks on one database, would
878
- // interfere, and the results would describe neither.
879
- const begin = (kind, title, command, work, secrets) => {
880
- const job = jobs.start(kind, title, command, work, secrets);
881
- return job ? json(res, 202, { ok: true, job: job }) : json(res, 409, { ok: false, why: 'a run is already going', job: jobs.get() });
882
- };
883
- if (url.pathname === '/api/recheck' && typeof opts.recheck === 'function') {
884
- const id = String(input.id || '');
885
- if (!/^[0-9a-f]{8}$/.test(id)) return json(res, 400, { ok: false, why: 'not a finding id' });
886
- const open = buildState(root, env).findings.find((f) => f.id === id);
887
- if (!open) return json(res, 404, { ok: false, why: 'no open finding with that id' });
888
- return begin('recheck', 'Re-checking: ' + open.headline, 'npx kryptheon recheck ' + id, (say) => opts.recheck(id, say));
889
- }
890
- if (url.pathname === '/api/run' && typeof opts.run === 'function') {
891
- const id = String(input.id || '');
892
- const check = buildState(root, env).checks.find((c) => c.id === id);
893
- if (!check || !check.runnable || !check.enabled) {
894
- return json(res, 400, { ok: false, why: (check ? check.label : '"' + id + '"') + ' cannot be run from here' });
895
- }
896
- return begin('run', RUN_TITLE[id] || check.label, RUN_COMMAND[id] || '', (say) => opts.run(id, say));
897
- }
898
- if (url.pathname === '/api/record' && typeof opts.record === 'function') {
899
- const address = appAddress(input.url);
900
- if (!address) return json(res, 400, { ok: false, why: notAnAddress(input.url, 'http://localhost:3000') });
901
- const phone = input.phone === true;
902
- return begin('record', 'Recording ' + address + (phone ? ' at phone size' : ''),
903
- 'npx kryptheon record ' + address + (phone ? ' --phone' : ''), (say) => opts.record(address, say, { phone: phone }));
904
- }
905
- if (url.pathname === '/api/db' && typeof opts.db === 'function') {
906
- const action = String(input.action || '');
907
- if (!DB_ACTIONS[action]) return json(res, 400, { ok: false, why: 'no database action called "' + action + '"' });
908
- const connection = connectionFrom(input.connection);
909
- if (!connection) return json(res, 400, { ok: false, why: 'paste your connection string first' });
910
- if (action === 'recheck') {
911
- // One database finding, re-checked: the check runs again and that
912
- // finding is judged, the way `npx kryptheon recheck` judges the rest.
913
- const id = String(input.id || '');
914
- if (!/^[0-9a-f]{8}$/.test(id)) return json(res, 400, { ok: false, why: 'not a finding id' });
915
- const target = buildState(root, env).findings.find((f) => f.id === id && f.check === 'data');
916
- if (!target) return json(res, 404, { ok: false, why: 'no open database finding with that id' });
917
- return begin('db', 'Re-checking: ' + target.headline, DB_ACTIONS.recheck.command, (say) => {
918
- const before = buildState(root, env).findings;
919
- return Promise.resolve(opts.db('scan', connection, say)).then((ran) => {
920
- const attempt = databaseVerdict(target, before, buildState(root, env).findings, ran, readJson(store.pathsFor(root, env).nightLast));
921
- try {
922
- fs.appendFileSync(store.pathsFor(root, env).fixes, JSON.stringify(attempt) + '\n', 'utf8');
923
- } catch (err) {
924
- attempt.saveError = err.message;
925
- }
926
- return Object.assign({ ok: true, summary: attempt.verdict }, attempt);
927
- });
928
- }, secretsOf(connection));
929
- }
930
- // Handed to the job and nowhere else. The job's lines and result are
931
- // scrubbed of it, and it is dropped the moment the job ends.
932
- return begin('db', DB_ACTIONS[action].title, DB_ACTIONS[action].command,
933
- (say) => opts.db(action, connection, say), secretsOf(connection));
934
- }
935
- if (url.pathname === '/api/app') {
936
- // The app's web address: saved for this project, so Record and the
937
- // outside check start from it. Empty clears it.
938
- const raw = typeof input.address === 'string' ? input.address.trim() : '';
939
- const address = raw ? appAddress(raw) : '';
940
- if (address === null) return json(res, 400, { ok: false, why: notAnAddress(raw, 'https://my-app.lovable.app') });
941
- const full = address && !/^https?:\/\//i.test(address) ? 'https://' + address : address;
942
- return saveAppAddress(store.pathsFor(root, env), full)
943
- ? json(res, 200, { ok: true, address: full })
944
- : json(res, 500, { ok: false, why: 'it could not be saved on this computer' });
945
- }
946
- if (url.pathname === '/api/choose-folder' && typeof opts.chooseFolder === 'function' && typeof opts.openFolder === 'function') {
947
- // The person's own folder picker, on this computer; then a dashboard
948
- // for that folder in a window of its own. Nothing is run in it here.
949
- return Promise.resolve(opts.chooseFolder()).then((folder) => {
950
- if (!folder) return json(res, 200, { ok: false, cancelled: true, why: 'no folder was chosen' });
951
- const opened = opts.openFolder(folder);
952
- return json(res, opened.ok ? 200 : 400, Object.assign({ folder: folder }, opened));
953
- }, (err) => json(res, 500, { ok: false, why: err.message }));
954
- }
955
- if (url.pathname === '/api/db/words' && typeof opts.words === 'function') {
956
- // What kryptheon-night itself would say about this string - its help,
957
- // its consent screens, its warnings - asked of it without connecting.
958
- const connection = input.connection == null || input.connection === '' ? '' : connectionFrom(input.connection);
959
- if (connection === null) return json(res, 400, { ok: false, why: 'that connection string is too long' });
960
- const secrets = secretsOf(connection);
961
- return Promise.resolve(opts.words(connection)).then(
962
- (words) => json(res, 200, hideSecretsIn({ ok: true, words: words }, secrets)),
963
- (err) => json(res, 500, hideSecretsIn({ ok: false, why: err.message }, secrets)),
964
- );
965
- }
966
- return json(res, 404, { ok: false, why: 'no such action' });
967
- });
968
- return;
969
- }
970
- return send(res, 404, 'text/plain', 'Not found');
971
- });
972
-
973
- return {
974
- server: server,
975
- token: token,
976
- listen(wanted) {
977
- return new Promise((resolve, reject) => {
978
- server.once('error', reject);
979
- server.listen(wanted || 0, '127.0.0.1', () => {
980
- port = server.address().port;
981
- resolve(port);
982
- });
983
- });
984
- },
985
- close() {
986
- return new Promise((resolve) => server.close(() => resolve()));
987
- },
988
- };
989
- }
990
-
991
- module.exports = {
992
- CHECKS: CHECKS,
993
- buildState: buildState,
994
- flowPrompt: flowPrompt,
995
- appAddress: appAddress,
996
- meantAddress: meantAddress,
997
- secretsOf: secretsOf,
998
- hideSecrets: hideSecrets,
999
- hideSecretsIn: hideSecretsIn,
1000
- createJobs: createJobs,
1001
- DB_ACTIONS: DB_ACTIONS,
1002
- databaseVerdict: databaseVerdict,
1003
- startSteps: startSteps,
1004
- nextAction: nextAction,
1005
- combinedPrompt: combinedPrompt,
1006
- readConfig: readConfig,
1007
- setCheck: setCheck,
1008
- createServer: createServer,
1009
- };
1
+ // The local dashboard: one page on this machine that shows everything
2
+ // Kryptheon knows about one project, and switches its checks on and off.
3
+ //
4
+ // npx kryptheon (in a terminal) or npx kryptheon dashboard
5
+ //
6
+ // Everything here reads the project's store (kryptheon-store.js); nothing is
7
+ // kept anywhere else, and nothing leaves the machine. The server listens on
8
+ // 127.0.0.1 only.
9
+ //
10
+ // Two rules the page is built around:
11
+ //
12
+ // - A check that does not exist yet is shown as "coming soon". Never as
13
+ // passed, never as green, never counted. An empty row that looks like a
14
+ // clean one is the most expensive lie this product could tell.
15
+ // - Every value shown comes from a file that may hold text from the app being
16
+ // checked - a failing page's heading, a line of the app's own code. The page
17
+ // writes all of it with textContent, so the dashboard cannot become the XSS
18
+ // it is there to find. Its own code is read by kryptheon-code.js in its check.
19
+
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+ const http = require('http');
23
+ const crypto = require('crypto');
24
+ const { spawnSync } = require('child_process');
25
+ const store = require('./kryptheon-store.js');
26
+ const changes = require('./kryptheon-changes.js');
27
+ const autostart = require('./kryptheon-autostart.js');
28
+ const VERSION = require('./package.json').version;
29
+
30
+ /**
31
+ * Every check the dashboard knows the name of, in the order the person asked
32
+ * for them. `available` is true only for what is actually built. What runs it
33
+ * and where its results come from is said here, once.
34
+ */
35
+ const CHECKS = [
36
+ { id: 'regression', label: 'Regression (recorded flows)', available: true,
37
+ what: 'Replays every recording in tests/ and compares each page with the last time it worked.' },
38
+ { id: 'frontend', label: 'Frontend: text inserted as HTML', available: true,
39
+ what: 'Reads your frontend code for values put into the page with innerHTML and similar (npx kryptheon code).' },
40
+ { id: 'data', label: 'Database: access rules, duplicates, orphans', available: true,
41
+ what: 'Attacks a copy of your Postgres/Supabase database (kryptheon-night). Paste the connection string in Start here; it is used for one run and never saved.' },
42
+ // Coming soon, in the order they are being built (2026-10-13). Integration
43
+ // and age/eligibility rules were taken off: neither can be checked without
44
+ // the app's own rules, so listing them promised what is not planned.
45
+ { id: 'build', label: 'Build', available: false },
46
+ { id: 'dependency', label: 'Dependencies', available: false },
47
+ { id: 'runtime', label: 'Runtime', available: false },
48
+ { id: 'performance', label: 'Performance', available: false },
49
+ { id: 'edge', label: 'Input and edge cases', available: true, asks: true,
50
+ what: 'Replays your recorded forms with one field at a time given an unusual value - empty, 5000 characters, an HTML tag, emoji, a negative number, a date that does not exist - and reports only what it can prove: a page error, a 5xx, a bad value saved, a tag shown as HTML. It adds test data to your app, so it runs only when you press its button.' },
51
+ { id: 'reliability', label: 'Reliability', available: true, asks: true,
52
+ what: 'Replays each recorded flow three times and reports one that sometimes works and sometimes fails, with the failed run as proof; and clicks each step that saves twice, quickly, reporting when that saves twice, with both answers as proof. It adds test data to your app, so it runs only when you press its button.' },
53
+ { id: 'api', label: 'API', available: false },
54
+ { id: 'backend', label: 'Backend', available: false },
55
+ { id: 'synthetic', label: 'Synthetic test users', available: false },
56
+ ];
57
+
58
+ const CHECK_IDS = new Set(CHECKS.map((c) => c.id));
59
+
60
+ function readJson(file) {
61
+ try {
62
+ let raw = fs.readFileSync(file, 'utf8');
63
+ if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1);
64
+ return JSON.parse(raw);
65
+ } catch (err) {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ function readHistory(file, keep) {
71
+ let raw;
72
+ try {
73
+ raw = fs.readFileSync(file, 'utf8');
74
+ } catch (err) {
75
+ return [];
76
+ }
77
+ const runs = [];
78
+ for (const line of raw.split('\n')) {
79
+ if (!line.trim()) continue;
80
+ try {
81
+ runs.push(JSON.parse(line));
82
+ } catch (err) {
83
+ /* a damaged line is skipped, not fatal */
84
+ }
85
+ }
86
+ return runs.slice(-keep);
87
+ }
88
+
89
+ /** Which checks are switched on. Available checks default to on; others can never be. */
90
+ function readConfig(paths) {
91
+ const saved = readJson(paths.config) || {};
92
+ const enabled = {};
93
+ for (const c of CHECKS) {
94
+ enabled[c.id] = c.available ? (saved.enabled && typeof saved.enabled[c.id] === 'boolean' ? saved.enabled[c.id] : true) : false;
95
+ }
96
+ return { enabled: enabled };
97
+ }
98
+
99
+ /**
100
+ * Switches one check on or off, and keeps it. Refuses what does not exist and
101
+ * what is not built: a "coming soon" check switched on would read as a
102
+ * promise that something is being checked.
103
+ */
104
+ function setCheck(paths, id, on) {
105
+ if (!CHECK_IDS.has(id)) return { ok: false, why: 'there is no check called "' + id + '"' };
106
+ const check = CHECKS.find((c) => c.id === id);
107
+ if (!check.available) return { ok: false, why: check.label + ' is coming soon - not built yet, so it cannot be switched on' };
108
+ if (typeof on !== 'boolean') return { ok: false, why: 'on must be true or false' };
109
+ const config = readConfig(paths);
110
+ config.enabled[id] = on;
111
+ fs.mkdirSync(path.dirname(paths.config), { recursive: true });
112
+ fs.writeFileSync(paths.config, JSON.stringify(config, null, 2) + '\n', 'utf8');
113
+ return { ok: true, config: config };
114
+ }
115
+
116
+ /** What git says changed, read only. Null when this is not a git repository. */
117
+ function recentChanges(root) {
118
+ const git = (args) => {
119
+ const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 5000 });
120
+ return r.status === 0 ? String(r.stdout || '') : null;
121
+ };
122
+ const inside = git(['rev-parse', '--is-inside-work-tree']);
123
+ if (!inside || inside.trim() !== 'true') return null;
124
+ const log = git(['log', '-5', '--pretty=format:%h%x09%cI%x09%s']) || '';
125
+ const status = git(['status', '--porcelain']) || '';
126
+ return {
127
+ commits: log.split('\n').filter(Boolean).map((l) => {
128
+ const [hash, when, subject] = l.split('\t');
129
+ return { hash: hash, when: when, subject: subject };
130
+ }),
131
+ uncommitted: status.split('\n').filter(Boolean).map((l) => ({ state: l.slice(0, 2).trim(), file: l.slice(3) })),
132
+ };
133
+ }
134
+
135
+ /** " - the risky part: x" for a frontend finding that names one, else "". */
136
+ function riskyPartsLine(f) {
137
+ const parts = (f.parts || []).filter((p) => p && p.text && p.text !== f.expression);
138
+ if (!parts.length) return '';
139
+ return ' - the risky part' + (parts.length === 1 ? ': ' : 's: ') + parts.map((p) => p.text).join(', ');
140
+ }
141
+
142
+ /** When this flow last passed, from the run history, or null. */
143
+ function lastPassOf(history, title) {
144
+ for (let i = history.length - 1; i >= 0; i--) {
145
+ const t = (history[i].tests || []).find((x) => x.title === title);
146
+ if (t && t.status === 'passed') return history[i].runAt;
147
+ }
148
+ return null;
149
+ }
150
+
151
+ /**
152
+ * The fix prompt for a broken recorded flow, from what the run kept: what was
153
+ * seen, what was expected, where, the evidence, and how to see it again. Only
154
+ * what the run recorded is said; nothing is guessed.
155
+ */
156
+ function flowPrompt(t, lastPass) {
157
+ const f = t.failure || {};
158
+ const o = f.observations || {};
159
+ const file = String(f.file || t.specFile || 'tests').split('\\').join('/');
160
+ const extra = String(f.rawMessage || '').split(/\r?\n/).slice(1)
161
+ .map((l) => l.trim()).filter((l) => l && !/^\s*at\s/.test(l) && l.length < 200).slice(0, 6);
162
+ const lines = [
163
+ 'My app has a broken flow. Please fix the app - and nothing else.',
164
+ '',
165
+ 'Kryptheon replayed the recorded flow "' + t.title + '" (' + file + (f.line ? ', line ' + f.line : '') + ') and it failed.',
166
+ '',
167
+ 'Observed: ' + (f.plainLanguage || 'the replay failed'),
168
+ ].concat(extra.map((l) => ' ' + l), [
169
+ 'Expected: the same result as ' + (lastPass ? 'the last time it passed (' + lastPass + ')' : 'when it was recorded') + '.',
170
+ ]);
171
+ if (o.url) lines.push('Where: the browser was on ' + o.url + (o.pageShowed ? ', and the page showed ' + o.pageShowed : '') + '.');
172
+ if (f.locator) lines.push('Step that failed: ' + f.locator);
173
+ if (o.failedRequests && o.failedRequests.length) lines.push('Failed requests: ' + o.failedRequests.slice(0, 5).map((r) => (r.method || 'GET') + ' ' + (r.path || r.url) + ' -> ' + r.status).join('; '));
174
+ if (o.consoleErrors && o.consoleErrors.length) lines.push('Console errors: ' + o.consoleErrors.slice(0, 3).join(' | '));
175
+ if (f.screenshot) lines.push('Evidence: a screenshot of the failure at ' + f.screenshot);
176
+ lines.push('');
177
+ lines.push('To see it yourself: open ' + (o.url || 'the app') + ' and repeat the steps in ' + file + ', or run npx kryptheon check');
178
+ lines.push('');
179
+ lines.push('Fix the app so this flow works again. Do not edit the recording to make it pass. If the new behaviour ' +
180
+ 'is intended, say so instead of changing code - it can be accepted with npx kryptheon accept "' + t.title + '"');
181
+ return lines.join('\n');
182
+ }
183
+
184
+ function countRecordings(root) {
185
+ try {
186
+ // Recordings only - not the project's own unit tests in tests/.
187
+ return require('./kryptheon-testfiles.js').recordingNames(path.join(root, 'tests')).length;
188
+ } catch (err) {
189
+ return 0;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * What a probe check asks before it runs: the addresses the recordings open,
195
+ * and the words said about them (kryptheon-probe.js). Read from the
196
+ * recordings every time, so what the page shows is what would really run.
197
+ */
198
+ function probeAsk(root, what, env, options) {
199
+ const probe = require('./kryptheon-probe.js');
200
+ const sources = [];
201
+ try {
202
+ const dir = path.join(root, 'tests');
203
+ for (const name of require('./kryptheon-testfiles.js').recordingNames(dir)) sources.push(fs.readFileSync(path.join(dir, name), 'utf8'));
204
+ } catch (err) {
205
+ /* no recordings: nothing to ask about */
206
+ }
207
+ // The pages, and where the app was last seen saving (kryptheon-probe.js).
208
+ const addresses = probe.knownAddresses(root, sources, env);
209
+ return { addresses: addresses, live: probe.liveLooking(addresses), lines: probe.consentLines(what, addresses, options) };
210
+ }
211
+
212
+ const PROBE_WHAT = {
213
+ edge: 'Input and edge cases: replays your recorded forms with one field at a time given an unusual value (empty, 5000 characters, an HTML tag, emoji, a negative number, a date that does not exist). At most 40 runs.',
214
+ reliability: 'Reliability: replays each recorded flow three times, and clicks each step that saves (Save, Add, Create...) twice, quickly. At most 40 runs.',
215
+ };
216
+ // The reliability check types nothing of its own, so nothing it saves can
217
+ // carry the kryptheon-test marker - and its words do not promise one.
218
+ const PROBE_WORDS = { reliability: { marker: false } };
219
+ const PROBE_CHECKS = ['edge', 'reliability'];
220
+
221
+ /**
222
+ * The order someone new should go in, one step at a time. A step is "done"
223
+ * only when it has actually run and left a record - never because nothing was
224
+ * found - and a switched-off check says "off", so an empty list is never read
225
+ * as a clean one.
226
+ */
227
+ // How often a step is done. Said on every step and button, because the two
228
+ // kinds are done at different moments and mixing them up is how a check stops
229
+ // being run: "one time" is setting up, "after every change" is the habit.
230
+ const ONE_TIME = 'one time';
231
+ const EVERY_CHANGE = 'after every change';
232
+
233
+ function startSteps(checks, seen) {
234
+ const on = (id) => (checks.find((c) => c.id === id) || {}).enabled;
235
+ const nightly = seen.nightly || null;
236
+ // With no code on this computer - the home folder's dashboard - there is
237
+ // no code to read, and "Read your frontend code" would only say it read
238
+ // nothing. The app is checked by its address.
239
+ return startStepList(on, seen, nightly).filter((s) => !(seen.webOnly && s.id === 'frontend'));
240
+ }
241
+
242
+ function startStepList(on, seen, nightly) {
243
+ return [
244
+ {
245
+ id: 'frontend',
246
+ title: 'Read your frontend code',
247
+ when: EVERY_CHANGE,
248
+ why: 'Finds places where text could be put into your page as HTML. Needs nothing from you.',
249
+ state: !on('frontend') ? 'off' : seen.codeAt ? 'done' : 'todo',
250
+ at: seen.codeAt,
251
+ action: on('frontend') ? { kind: 'run', check: 'frontend', label: seen.codeAt ? 'Read it again' : 'Read my code', command: RUN_COMMAND.frontend } : null,
252
+ },
253
+ {
254
+ id: 'record',
255
+ title: 'Record your main flows',
256
+ when: ONE_TIME,
257
+ whenMore: 'again only when that flow changes',
258
+ // The lesson of a test where 26 bugs were planted before recording and
259
+ // none was caught: what is recorded is taken as right.
260
+ why: 'Sign up, log in, pay - do each once while Kryptheon watches. Record while your app works: what it sees is taken as right, so a bug already there when you record becomes part of "working". Start your app first, then put its address here.',
261
+ state: seen.recordings ? 'done' : 'todo',
262
+ at: null,
263
+ count: seen.recordings,
264
+ action: { kind: 'record', label: seen.recordings ? 'Record another' : 'Record', command: 'npx kryptheon record <your app address>' },
265
+ },
266
+ {
267
+ id: 'regression',
268
+ title: 'Replay them',
269
+ when: EVERY_CHANGE,
270
+ why: 'Runs every recording against your app and compares each page with the last time it worked. Start your app first.',
271
+ state: !on('regression') ? 'off' : !seen.recordings ? 'waiting' : seen.lastRunAt ? 'done' : 'todo',
272
+ at: seen.lastRunAt,
273
+ action: on('regression') && seen.recordings ? { kind: 'run', check: 'regression', label: seen.lastRunAt ? 'Replay again' : 'Replay now', command: RUN_COMMAND.regression } : null,
274
+ },
275
+ {
276
+ id: 'connect',
277
+ title: 'Connect your database',
278
+ when: ONE_TIME,
279
+ why: 'Paste your connection string - the steps are next to the box. It goes only to this dashboard on your machine and to kryptheon-night for the length of one run. It is never saved and never shown again; reload the page and it is gone. Try it on a test project first.',
280
+ state: !on('data') ? 'off' : seen.nightAt ? 'done' : 'todo',
281
+ at: null,
282
+ action: on('data') ? { kind: 'connect' } : null,
283
+ },
284
+ {
285
+ id: 'data',
286
+ title: 'Check your database',
287
+ when: EVERY_CHANGE,
288
+ why: 'Attacks a copy inside your Postgres or Supabase database and reports what got in; your own rows are not touched. You are shown exactly what it will do, and it waits for your yes.',
289
+ state: !on('data') ? 'off' : seen.nightAt ? 'done' : 'todo',
290
+ at: seen.nightAt,
291
+ action: on('data') ? { kind: 'db', action: 'scan', label: 'Check my database', command: DB_ACTIONS.scan.command } : null,
292
+ },
293
+ {
294
+ id: 'nightly',
295
+ title: 'Check it every night',
296
+ when: ONE_TIME,
297
+ // Offered, never pressed for: an app can be checked well without it,
298
+ // so it is not what "do this next" points at.
299
+ optional: true,
300
+ why: 'Sets the same check up inside your database, to run by itself every night, and keeps the answer there for this page. It stays until you remove it.',
301
+ state: !on('data') ? 'off' : nightly && nightly.installed && nightly.active ? 'done' : 'todo',
302
+ at: nightly && nightly.ranAt ? nightly.ranAt : null,
303
+ action: on('data') ? { kind: 'nightly', installed: Boolean(nightly && nightly.installed), at: nightly ? nightly.scheduled || null : null } : null,
304
+ },
305
+ ];
306
+ }
307
+
308
+ /**
309
+ * The one thing to do now. Open confirmed problems come before everything; then
310
+ * the first step not taken; then what only needs a look; then nothing.
311
+ */
312
+ function nextAction(findings, steps) {
313
+ const confirmed = findings.filter((f) => f.status === 'confirmed').length;
314
+ const toVerify = findings.length - confirmed;
315
+ if (confirmed) {
316
+ return { kind: 'fix', view: 'findings', count: confirmed,
317
+ title: confirmed === 1 ? 'Fix 1 confirmed problem' : 'Fix ' + confirmed + ' confirmed problems' };
318
+ }
319
+ const step = steps.find((s) => s.state === 'todo' && !s.optional);
320
+ if (step) return { kind: 'step', step: step.id, title: step.title };
321
+ if (toVerify) {
322
+ return { kind: 'verify', view: 'findings', count: toVerify,
323
+ title: toVerify === 1 ? 'Look at 1 thing to verify' : 'Look at ' + toVerify + ' things to verify' };
324
+ }
325
+ return { kind: 'quiet', title: 'Nothing open' };
326
+ }
327
+
328
+ /**
329
+ * One prompt that fixes every open finding at once, for pasting into an AI
330
+ * tool, or '' when fewer than two findings have a prompt (one is its own).
331
+ * Each finding's own prompt goes in as it is, in the order the page shows
332
+ * them, most severe first. Around them are the rules that keep a fix from
333
+ * breaking something else: only what is listed, the smallest change, one at
334
+ * a time with the app checked between, nothing weakened to make a finding go
335
+ * away, ask rather than guess. The re-checks come once, at the end.
336
+ *
337
+ * items: [{ id, severity, headline, where, prompt }] - prompt without its
338
+ * re-check line.
339
+ */
340
+ function combinedPrompt(items) {
341
+ const withPrompt = items.filter((f) => f.prompt);
342
+ if (withPrompt.length < 2) return '';
343
+ const n = withPrompt.length;
344
+ const lines = [
345
+ 'Kryptheon checked this project and found ' + n + ' problems. Fix all ' + n + ', carefully - not breaking anything matters more than speed.',
346
+ '',
347
+ 'Rules for every fix:',
348
+ '1. Fix only the problems listed below. Do not refactor, rename, reformat or "improve" anything else, and do not touch a file a fix does not need.',
349
+ '2. Make the smallest change that fixes each one. Every feature must keep working exactly as it does now for the people meant to use it.',
350
+ '3. Never delete or weaken a check, test, validation or security rule to make a problem go away, and never delete or rewrite existing data.',
351
+ '4. Do them one at a time, in the order below. After each one, make sure the app still builds and its existing tests still pass before starting the next.',
352
+ '5. If a fix needs a decision only I can make, or you are not sure a change is safe, stop and ask me instead of guessing.',
353
+ '6. When you are done, list every file you changed and why, one line each.',
354
+ ];
355
+ withPrompt.forEach((f, i) => {
356
+ lines.push('', '======== Problem ' + (i + 1) + ' of ' + n + ' - ' + f.severity + ': ' + f.headline + (f.where ? ' (' + f.where + ')' : ''), '', f.prompt.trim());
357
+ });
358
+ lines.push('', '======== When all ' + n + ' are fixed',
359
+ '',
360
+ 'Prove each fix: run these one at a time (or press Re-check on each finding in the Kryptheon dashboard). A fix counts only when it says FIXED, and a re-check also says if anything else newly broke - if it does, fix that before anything else.',
361
+ '');
362
+ withPrompt.forEach((f) => lines.push(' npx kryptheon recheck ' + f.id));
363
+ return lines.join('\n');
364
+ }
365
+
366
+ /**
367
+ * One sentence about the nightly run inside the database, or null when
368
+ * kryptheon-night has never been asked. Its four states are four different
369
+ * answers, and none of the other three may read as "nothing found": not set
370
+ * up, set up and never run, set up with nothing scheduled, and stopped.
371
+ */
372
+ function nightlyLine(nightly) {
373
+ if (!nightly) return null;
374
+ // The database runs on UTC. Found on a real read-back: "03:00" was 08:30
375
+ // in India, and nothing said so - so both are said, and the moment it was
376
+ // read is said in this computer's own time.
377
+ const local = (iso) => new Date(iso).toLocaleString('en-GB', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
378
+ const day = (iso) => String(iso || '').slice(0, 16).replace('T', ' ') + ' UTC (' + local(iso) + ' your time)';
379
+ const read = ' (read ' + local(nightly.readAt) + ')';
380
+ if (!nightly.installed) return 'Nightly run in your database: not set up. Press "Set up nightly check" in Start here.' + read;
381
+ const idle = nightly.active ? '' : ' Nothing is scheduled, so it is not running - press "Set it up again" in Start here.';
382
+ if (!nightly.ranAt) return 'Nightly run in your database: set up, and it has not run yet.' + idle + read;
383
+ const when = 'Nightly run in your database, ' + day(nightly.ranAt) + ': ';
384
+ if (nightly.stopped) return when + 'it could not check - ' + nightly.stopped + idle + read;
385
+ // A function anyone can call is a thing to check, not a problem proven -
386
+ // counted apart, the way the terminal counts it.
387
+ const n = (nightly.findings || []).filter((f) => f.status !== 'verification required').length;
388
+ const toCheck = (nightly.findings || []).length - n;
389
+ const skipped = (nightly.notChecked || []).length;
390
+ return when + (n ? n + (n === 1 ? ' problem found.' : ' problems found.')
391
+ : 'nothing got through ' + (nightly.attacksRun || 0) + ' attacks.') +
392
+ (toCheck ? ' ' + toCheck + (toCheck === 1 ? ' thing' : ' things') + ' to check.' : '') +
393
+ (skipped ? ' ' + skipped + ' ' + (skipped === 1 ? 'part was' : 'parts were') + ' not tested.' : '') + idle + read;
394
+ }
395
+
396
+ /**
397
+ * Everything the page shows, from the store alone. Findings from every check
398
+ * are put into one list, each carrying the same fields - severity, status,
399
+ * evidence, confidence, where, what, and the fix - so the page can show them
400
+ * the same way whichever check found them.
401
+ */
402
+ function buildState(root, env) {
403
+ const paths = store.pathsFor(root, env);
404
+ const config = readConfig(paths);
405
+ const history = readHistory(paths.history, 20);
406
+ const baselines = readJson(paths.baselines) || {};
407
+ const code = readJson(paths.codeFindings);
408
+ const night = readJson(paths.nightLast);
409
+ // What the nightly run inside the database last said, kept by
410
+ // kryptheon-night whenever it connects. Not the same answer as night:
411
+ // that one is the scan last run from this terminal.
412
+ const nightly = readJson(paths.nightNightly);
413
+
414
+ const findings = [];
415
+
416
+ // Recorded flows: the last run's broken tests are the findings. They were
417
+ // replayed in a real browser, so they are confirmed at runtime.
418
+ const lastRun = history.length ? history[history.length - 1] : null;
419
+ if (lastRun && config.enabled.regression) {
420
+ for (const t of lastRun.tests || []) {
421
+ if (t.status !== 'failed' && t.status !== 'timedOut') continue;
422
+ findings.push({
423
+ check: 'regression',
424
+ severity: 'HIGH',
425
+ status: 'confirmed',
426
+ evidence: 'runtime confirmed',
427
+ confidence: 'high',
428
+ where: String((t.failure && t.failure.file) || t.specFile || 'tests').split('\\').join('/') +
429
+ (t.failure && t.failure.line ? ':' + t.failure.line : ''),
430
+ headline: 'The recorded flow "' + t.title + '" broke.',
431
+ detail: (t.failure && t.failure.plainLanguage) || '',
432
+ fixPrompt: flowPrompt(t, lastPassOf(history, t.title)),
433
+ when: lastRun.runAt,
434
+ });
435
+ }
436
+ }
437
+
438
+ if (code && config.enabled.frontend) {
439
+ for (const f of code.findings || []) {
440
+ findings.push({
441
+ check: 'frontend',
442
+ severity: f.severity,
443
+ status: f.status,
444
+ evidence: f.evidence,
445
+ confidence: f.confidence,
446
+ where: f.file + ':' + f.line,
447
+ headline: f.headline,
448
+ // The part of a long template that decides it, so the person reading
449
+ // it looks at one value instead of sixty lines of markup.
450
+ detail: f.sink + ': ' + f.expression + riskyPartsLine(f),
451
+ fixPrompt: f.fixPrompt,
452
+ when: code.checkedAt,
453
+ });
454
+ }
455
+ }
456
+
457
+ // Input and edge cases, and reliability: the last press of each one's
458
+ // button. Each finding carries its proof, and what it was about - the
459
+ // field and value, the flow, the step - so a re-check can try exactly that
460
+ // again.
461
+ const probeLast = {};
462
+ for (const id of PROBE_CHECKS) {
463
+ const last = (probeLast[id] = readJson(path.join(paths.dir, require('./kryptheon-probe.js').REPORT_FILES[id])));
464
+ if (!last || !config.enabled[id]) continue;
465
+ for (const f of last.findings || []) {
466
+ findings.push({
467
+ check: id,
468
+ severity: f.severity,
469
+ status: f.status,
470
+ evidence: f.status === 'confirmed' ? 'runtime confirmed' : 'seen once',
471
+ confidence: f.status === 'confirmed' ? 'high' : 'medium',
472
+ where: f.where,
473
+ headline: f.headline,
474
+ detail: (f.proof || []).join('\n'),
475
+ fixPrompt: f.fixPrompt || '',
476
+ when: last.endedAt || last.startedAt,
477
+ kind: f.kind,
478
+ type: f.type,
479
+ });
480
+ }
481
+ }
482
+
483
+ let nightWhen = null;
484
+ try {
485
+ nightWhen = fs.statSync(paths.nightLast).mtime.toISOString();
486
+ } catch (err) {
487
+ /* never run */
488
+ }
489
+ if (night && config.enabled.data) {
490
+ for (const f of night.findings || []) {
491
+ findings.push({
492
+ check: 'data',
493
+ severity: f.severity,
494
+ status: f.status || 'confirmed',
495
+ evidence: (f.status || 'confirmed') === 'confirmed' ? 'runtime confirmed' : 'code analysis',
496
+ confidence: (f.status || 'confirmed') === 'confirmed' ? 'high' : 'medium',
497
+ where: f.table + (f.column ? '.' + f.column : ''),
498
+ headline: f.headline,
499
+ detail: f.body || '',
500
+ fixPrompt: f.fixPrompt || '',
501
+ when: nightWhen,
502
+ });
503
+ }
504
+ }
505
+
506
+ // The nightly run's findings, said as coming from it. One both answers
507
+ // share is shown once, with the newer date - the same problem found twice
508
+ // is still one problem to fix.
509
+ if (nightly && nightly.ranAt && config.enabled.data) {
510
+ for (const f of nightly.findings || []) {
511
+ const item = {
512
+ check: 'data',
513
+ from: 'nightly',
514
+ severity: f.severity,
515
+ status: f.status || 'confirmed',
516
+ evidence: (f.status || 'confirmed') === 'confirmed' ? 'runtime confirmed' : 'code analysis',
517
+ confidence: (f.status || 'confirmed') === 'confirmed' ? 'high' : 'medium',
518
+ where: f.table + (f.column ? '.' + f.column : ''),
519
+ headline: f.headline,
520
+ detail: f.body || '',
521
+ fixPrompt: f.fixPrompt || '',
522
+ when: nightly.ranAt,
523
+ };
524
+ const same = findings.find((o) => o.check === 'data' && changes.findingKey(o) === changes.findingKey(item));
525
+ if (!same) findings.push(item);
526
+ else {
527
+ same.from = 'both';
528
+ if (!same.when || item.when > same.when) same.when = item.when;
529
+ }
530
+ }
531
+ }
532
+
533
+ const rank = { 'HIGH CRITICAL': 0, CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3 };
534
+ findings.sort((a, b) => (rank[a.severity] ?? 9) - (rank[b.severity] ?? 9) ||
535
+ (a.status === 'confirmed' ? 0 : 1) - (b.status === 'confirmed' ? 0 : 1));
536
+
537
+ // Every finding gets a short id and the last word of its fix prompt: how to
538
+ // prove the fix. Added here, where the loop lives, so every check's prompt
539
+ // ends the same way and the detection code itself stays untouched.
540
+ const attempts = readHistory(paths.fixes, 500);
541
+ const forAll = [];
542
+ for (const f of findings) {
543
+ f.id = changes.findingId(f);
544
+ f.attempts = attempts.filter((a) => a.id === f.id).map((a) => ({ at: a.at, verdict: a.verdict, why: a.why || '', newProblems: (a.newProblems || []).length }));
545
+ forAll.push({ id: f.id, severity: f.severity, headline: f.headline, where: f.where, prompt: f.fixPrompt || '' });
546
+ if (f.fixPrompt && PROBE_CHECKS.includes(f.check)) {
547
+ // Re-checking runs the flow in the app again, so it adds a little test
548
+ // data: --yes says yes for an app on this computer, and is refused for
549
+ // any other address - there the person must answer.
550
+ f.fixPrompt += '\n\nWhen you have fixed it, prove it: run npx kryptheon recheck ' + f.id + ' --yes' +
551
+ ' (it runs the flow in the app again, adding a little test data; --yes works only for an app running on this computer). ' +
552
+ 'It is fixed only when that says FIXED.';
553
+ } else if (f.fixPrompt) {
554
+ f.fixPrompt += '\n\nWhen you have fixed it, prove it: run npx kryptheon recheck ' + f.id +
555
+ ' (or press Re-check on this finding in the Kryptheon dashboard). It is fixed only when that says FIXED.';
556
+ }
557
+ }
558
+ // Fixes that were proven, newest first, while their finding is still gone.
559
+ const open = new Set(findings.map((f) => f.id));
560
+ const proven = attempts.filter((a) => a.verdict === 'fixed' && !open.has(a.id)).reverse().slice(0, 10)
561
+ .map((a) => ({ id: a.id, at: a.at, where: a.where, headline: a.headline, newProblems: (a.newProblems || []).length }));
562
+
563
+ const recordings = countRecordings(root);
564
+ const checks = CHECKS.map((c) => {
565
+ let state;
566
+ if (!c.available) state = 'coming soon';
567
+ else if (!config.enabled[c.id]) state = 'switched off';
568
+ else if (c.id === 'regression') state = !recordings ? 'no recordings yet' : !lastRun ? 'never run' : lastRun.failed ? 'problems found' : 'last run held';
569
+ else if (PROBE_CHECKS.includes(c.id)) {
570
+ const last = probeLast[c.id];
571
+ state = !last ? 'never run'
572
+ : findings.some((f) => f.check === c.id && f.status === 'confirmed') ? 'problems found'
573
+ : findings.some((f) => f.check === c.id) ? 'things to check'
574
+ : last.stopped ? 'stopped part way'
575
+ : !(last.flows || []).some((x) => x.state === 'tested') ? 'nothing was tested'
576
+ : 'last run held';
577
+ }
578
+ else if (c.id === 'frontend') state = !code ? 'never run' : (code.findings || []).length ? 'things to check' : 'nothing found';
579
+ else if (c.id === 'data') {
580
+ const ranNightly = nightly && nightly.ranAt && !nightly.stopped;
581
+ state = !night && !ranNightly ? 'never run here'
582
+ : findings.some((f) => f.check === 'data') ? 'problems found' : 'last run held';
583
+ }
584
+ return {
585
+ id: c.id, label: c.label, available: c.available, enabled: config.enabled[c.id], state: state, what: c.what || '',
586
+ nightly: c.id === 'data' ? nightlyLine(nightly) : null,
587
+ // A check that adds data to the app: never in "Run all", never on its
588
+ // own - only its own button, after the page has shown these words.
589
+ asks: c.asks && config.enabled[c.id] && recordings > 0 ? probeAsk(root, PROBE_WHAT[c.id], env, PROBE_WORDS[c.id]) : null,
590
+ lastRun: probeLast[c.id] ? {
591
+ at: probeLast[c.id].endedAt, stopped: !!probeLast[c.id].stopped, runsDone: probeLast[c.id].runsDone, runsPlanned: probeLast[c.id].runsPlanned,
592
+ held: (probeLast[c.id].held || []).length,
593
+ notTested: (probeLast[c.id].notTested || []).length + (probeLast[c.id].flows || []).filter((x) => x.state !== 'tested').length,
594
+ testData: (probeLast[c.id].testData || []).length,
595
+ } : null,
596
+ // Runnable from the page: what needs nothing the page cannot supply. The
597
+ // database check needs a connection string, which stays in the terminal.
598
+ runnable: c.available && (c.id === 'frontend' || (c.id === 'regression' && recordings > 0)),
599
+ };
600
+ });
601
+
602
+ const webOnly = isHomeKept(root, env);
603
+ const steps = startSteps(checks, {
604
+ webOnly: webOnly,
605
+ codeAt: code ? code.checkedAt : null,
606
+ recordings: recordings,
607
+ lastRunAt: lastRun ? lastRun.runAt : null,
608
+ nightAt: [night ? nightWhen : null, nightly && nightly.ranAt].filter(Boolean).sort().pop() || null,
609
+ nightly: nightly,
610
+ });
611
+
612
+ // Every look Kryptheon took - by `verify`, or by the dashboard's own watch -
613
+ // newest first: what changed, what was run, and what came of it.
614
+ const looks = readHistory(paths.changes, 15).reverse().map((e) => ({
615
+ at: e.at,
616
+ by: e.by || 'verify',
617
+ first: !!e.first,
618
+ files: (e.files || []).slice(0, 30),
619
+ fileCount: (e.files || []).length,
620
+ parts: e.parts || [],
621
+ dependencies: e.dependencies || [],
622
+ checks: e.checks || [],
623
+ newFindings: e.newFindings || 0,
624
+ fixed: e.fixed || 0,
625
+ goneWithFile: e.goneWithFile || 0,
626
+ }));
627
+
628
+ return {
629
+ project: { name: path.basename(root), root: root, storeDir: paths.dir },
630
+ // Which kryptheon this dashboard is: a newer `dashboard` asks, and takes
631
+ // the place of an older one still running, instead of opening it.
632
+ kryptheon: VERSION,
633
+ looks: looks,
634
+ proven: proven,
635
+ checks: checks,
636
+ findings: findings,
637
+ allFixPrompt: combinedPrompt(forAll),
638
+ runs: history.slice().reverse().map((r) => ({ runAt: r.runAt, status: r.status, passed: r.passed, failed: r.failed, durationMs: r.durationMs })),
639
+ recordings: recordings,
640
+ steps: steps,
641
+ // Which app this dashboard is for: its web address, kept here, and whether
642
+ // its code is on this computer at all. The dashboard started from the home
643
+ // folder (Win+R) holds recordings only - the app is a web address.
644
+ app: {
645
+ address: readAppAddress(paths),
646
+ webOnly: webOnly,
647
+ folder: root,
648
+ canChooseFolder: process.platform === 'win32' || process.platform === 'darwin',
649
+ },
650
+ next: nextAction(findings, steps),
651
+ baselines: Object.keys(baselines).length,
652
+ changes: recentChanges(root),
653
+ // Part 3 is where a version gets verified. Until then this says so,
654
+ // rather than leaving a blank that could be read either way.
655
+ verification: { state: 'not verified', why: 'Kryptheon Verified is not built yet. No version of this project has been verified.' },
656
+ // Whether this dashboard starts by itself when the person signs in.
657
+ autostart: (() => { const s = autostart.status(root, env); return { available: s.available, on: s.on, why: s.why || '' }; })(),
658
+ };
659
+ }
660
+
661
+ /* --------------------------------------------------------------------------
662
+ Jobs: what the page starts, one at a time, with its progress and its end.
663
+ -------------------------------------------------------------------------- */
664
+
665
+ // What each run is called on the page, and the command that does the same in
666
+ // a terminal - shown under every button, for when the page cannot be used.
667
+ const RUN_TITLE = { frontend: 'Reading your code', regression: 'Replaying your recordings', edge: 'Trying unusual inputs in your forms', reliability: 'Replaying your flows three times, and double-clicking' };
668
+ const RUN_COMMAND = { frontend: 'npx kryptheon code', regression: 'npx kryptheon check', edge: 'npx kryptheon edge', reliability: 'npx kryptheon reliability' };
669
+ const DB_ACTIONS = {
670
+ scan: { title: 'Checking your database', command: 'npx kryptheon-night' },
671
+ install: { title: 'Setting up the nightly check', command: 'npx kryptheon-night install' },
672
+ night: { title: 'Reading last night\'s result', command: 'npx kryptheon-night night' },
673
+ uninstall: { title: 'Removing the nightly check', command: 'npx kryptheon-night uninstall' },
674
+ recheck: { title: 'Re-checking in your database', command: 'npx kryptheon-night' },
675
+ };
676
+
677
+ /**
678
+ * What a fresh database check says about one database finding. Fixed only
679
+ * when the check ran, the finding is gone, and nothing about its table went
680
+ * untested - a table that could not be tested loses its findings too, and
681
+ * that is not a fix. A finding still shown only from the nightly run is the
682
+ * nightly run's older answer, not this one's.
683
+ */
684
+ function databaseVerdict(target, before, after, ran, saved) {
685
+ const tableOf = (where) => String(where || '').split('.')[0];
686
+ let verdict;
687
+ let why = '';
688
+ const untested = ((saved && saved.notChecked) || []).find((n) => tableOf(n.table) === tableOf(target.where));
689
+ if (!ran || !ran.ok) {
690
+ verdict = 'could not confirm';
691
+ why = (ran && ran.why) || 'the database check could not run';
692
+ } else if (after.some((f) => f.id === target.id && f.from !== 'nightly')) {
693
+ verdict = 'still open';
694
+ } else if (untested) {
695
+ verdict = 'could not confirm';
696
+ why = 'part of ' + tableOf(target.where) + ' could not be tested this time: ' + untested.why;
697
+ } else {
698
+ verdict = 'fixed';
699
+ }
700
+ const had = new Set(before.map((f) => f.id));
701
+ return {
702
+ id: target.id,
703
+ at: new Date().toISOString(),
704
+ check: 'data',
705
+ where: target.where,
706
+ headline: target.headline,
707
+ verdict: verdict,
708
+ why: why,
709
+ newProblems: after.filter((f) => !had.has(f.id) && f.check === 'data').map((f) => ({
710
+ id: f.id, check: f.check, severity: f.severity, status: f.status, where: f.where, headline: f.headline,
711
+ })),
712
+ };
713
+ }
714
+ const JOB_LINES = 400;
715
+
716
+ /**
717
+ * The address to record, or null. Refused: anything that is not one line,
718
+ * anything that could be read as an option by the command it is passed to,
719
+ * and anything with a scheme other than http(s).
720
+ */
721
+ /**
722
+ * The dashboard started from the home folder: the kryptheon-tests folder
723
+ * there, which holds recordings and nothing of the app's own code.
724
+ */
725
+ function isHomeKept(root, env) {
726
+ const environment = env || process.env;
727
+ const home = environment.USERPROFILE || environment.HOME || require('os').homedir();
728
+ const tidy = (p) => (process.platform === 'win32' ? path.resolve(p).toLowerCase() : path.resolve(p));
729
+ return path.basename(root) === 'kryptheon-tests' && tidy(path.dirname(root)) === tidy(home);
730
+ }
731
+
732
+ /** The app's web address, as saved on the page - or empty. */
733
+ function readAppAddress(paths) {
734
+ const saved = readJson(path.join(paths.dir, 'app.json'));
735
+ return saved && typeof saved.address === 'string' ? saved.address : '';
736
+ }
737
+
738
+ function saveAppAddress(paths, address) {
739
+ try {
740
+ fs.mkdirSync(paths.dir, { recursive: true });
741
+ fs.writeFileSync(path.join(paths.dir, 'app.json'), JSON.stringify({ address: address, savedAt: new Date().toISOString() }, null, 2));
742
+ return true;
743
+ } catch (err) {
744
+ return false;
745
+ }
746
+ }
747
+
748
+ function appAddress(value) {
749
+ if (typeof value !== 'string') return null;
750
+ const text = value.trim();
751
+ if (!text || text.length > 2000 || /[\s\x00-\x1f]/.test(text) || text.startsWith('-')) return null;
752
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) return /^https?:\/\/[^/]/i.test(text) ? text : null;
753
+ // A path never starts with "//": "http//localhost:3000" is a mistyped
754
+ // scheme, not a host called "http".
755
+ return /^[a-z0-9.-]+(:\d{1,5})?(\/(?!\/)\S*)?$/i.test(text) ? text : null;
756
+ }
757
+
758
+ /**
759
+ * What was meant, when an address was typed with its start mistyped:
760
+ * "ttp://127.0.0.1:4180" (blind round 13, the first letter lost), "htp://",
761
+ * "http//", "http:/", "htps://". Null when it does not look like that.
762
+ */
763
+ function meantAddress(value) {
764
+ const text = String(value || '').trim();
765
+ const m = /^(h?t{1,3}p{1,2}(s?)|htps|hhttps?)(:\/{0,3}|\/{1,3}|:)(?!\/)(\S+)$/i.exec(text);
766
+ if (!m) return null;
767
+ const secure = /s$/i.test(m[1]);
768
+ const fixed = (secure ? 'https://' : 'http://') + m[4];
769
+ return fixed !== text && appAddress(fixed) ? fixed : null;
770
+ }
771
+
772
+ function notAnAddress(value, example) {
773
+ const meant = meantAddress(value);
774
+ return meant
775
+ ? 'that is not a web address - did you mean ' + meant + '?'
776
+ : 'that is not a web address - it should look like ' + example;
777
+ }
778
+
779
+ /** The connection string as given, or null when there is none or it is absurd. */
780
+ function connectionFrom(value) {
781
+ if (typeof value !== 'string') return null;
782
+ const text = value.trim();
783
+ return text && text.length <= 4000 ? text : null;
784
+ }
785
+
786
+ /**
787
+ * Every form in which a connection string could leak back out: the whole
788
+ * string, without the quotes it may have been pasted with, and its password
789
+ * both as typed and decoded. Longest first, so a password inside the whole
790
+ * string is never left half-hidden.
791
+ */
792
+ function secretsOf(connection) {
793
+ const raw = String(connection || '').trim();
794
+ if (!raw) return [];
795
+ const found = [raw, raw.replace(/^["']|["']$/g, '')];
796
+ try {
797
+ const password = new URL(found[1]).password;
798
+ if (password) {
799
+ found.push(password);
800
+ try { found.push(decodeURIComponent(password)); } catch (err) { /* kept as typed */ }
801
+ }
802
+ } catch (err) {
803
+ /* not a URL: the string itself is still hidden */
804
+ }
805
+ return Array.from(new Set(found.filter((s) => s.length >= 4))).sort((a, b) => b.length - a.length);
806
+ }
807
+
808
+ function hideSecrets(text, secrets) {
809
+ let out = String(text);
810
+ for (const s of secrets || []) out = out.split(s).join('[hidden]');
811
+ return out;
812
+ }
813
+
814
+ /** The same, through every string in a value. */
815
+ function hideSecretsIn(value, secrets) {
816
+ if (!secrets || !secrets.length) return value;
817
+ if (typeof value === 'string') return hideSecrets(value, secrets);
818
+ if (Array.isArray(value)) return value.map((v) => hideSecretsIn(v, secrets));
819
+ if (value && typeof value === 'object') {
820
+ const out = {};
821
+ for (const k of Object.keys(value)) out[k] = hideSecretsIn(value[k], secrets);
822
+ return out;
823
+ }
824
+ return value;
825
+ }
826
+
827
+ /**
828
+ * The one job that may run, and the last one that did. Its lines are what the
829
+ * work said as it went, scrubbed of any secret it was given before they are
830
+ * kept; when it ends, the secrets are let go.
831
+ */
832
+ function createJobs() {
833
+ let current = null;
834
+ let count = 0;
835
+ const view = (job) => job && {
836
+ id: job.id, kind: job.kind, title: job.title, command: job.command,
837
+ startedAt: job.startedAt, endedAt: job.endedAt, running: job.running,
838
+ lines: job.lines.slice(), result: job.result,
839
+ // A run that can be ended part way says so, and the page shows Stop.
840
+ stoppable: Boolean(job.running && job.stopper), stopping: Boolean(job.stopping),
841
+ };
842
+ return {
843
+ get: () => view(current),
844
+ busy: () => Boolean(current && current.running),
845
+ /** Ends the running job part way, if it can be. What it finished is kept. */
846
+ stop() {
847
+ if (!current || !current.running || !current.stopper) return false;
848
+ current.stopping = true;
849
+ current.stopper();
850
+ return true;
851
+ },
852
+ start(kind, title, command, work, givenSecrets) {
853
+ if (current && current.running) return null;
854
+ let secrets = givenSecrets || [];
855
+ const job = {
856
+ id: ++count, kind: kind, title: title, command: command || '',
857
+ startedAt: new Date().toISOString(), endedAt: null, running: true, lines: [], result: null,
858
+ };
859
+ current = job;
860
+ const say = (text) => {
861
+ if (!job.running) return;
862
+ // Colour codes are for terminals; on the page they are noise.
863
+ const clean = hideSecrets(String(text == null ? '' : text), secrets).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '');
864
+ for (const line of clean.split(/\r?\n/)) job.lines.push(line.slice(0, 500));
865
+ if (job.lines.length > JOB_LINES) job.lines.splice(0, job.lines.length - JOB_LINES);
866
+ };
867
+ const finish = (result) => {
868
+ job.result = hideSecretsIn(result && typeof result === 'object' ? result : { ok: false, why: 'the run gave no answer' }, secrets);
869
+ job.running = false;
870
+ job.endedAt = new Date().toISOString();
871
+ secrets = null;
872
+ };
873
+ Promise.resolve()
874
+ .then(() => work(say, { onStop: (fn) => (job.stopper = fn) }))
875
+ .then(finish, (err) => finish({ ok: false, why: err && err.message ? err.message : String(err) }));
876
+ return view(job);
877
+ },
878
+ };
879
+ }
880
+
881
+ /**
882
+ * The server. Local only, and closed to other web pages:
883
+ * - it listens on 127.0.0.1, never on the network;
884
+ * - it answers only when the Host header is this address, so a page on some
885
+ * other site cannot reach it through DNS rebinding;
886
+ * - anything that changes something needs the token that is written into the
887
+ * page this server hands out, which another site cannot read.
888
+ */
889
+ function createServer(root, options) {
890
+ const opts = options || {};
891
+ const env = opts.env || process.env;
892
+ const token = crypto.randomBytes(24).toString('hex');
893
+ const page = fs.readFileSync(path.join(__dirname, 'kryptheon-dashboard.html'), 'utf8');
894
+ let port = 0;
895
+ const jobs = createJobs();
896
+
897
+ const allowedHosts = () => new Set(['127.0.0.1:' + port, 'localhost:' + port]);
898
+ const send = (res, code, type, body) => {
899
+ res.writeHead(code, {
900
+ 'content-type': type,
901
+ 'cache-control': 'no-store',
902
+ 'x-content-type-options': 'nosniff',
903
+ 'referrer-policy': 'no-referrer',
904
+ // The page loads nothing from anywhere else, and says so.
905
+ 'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
906
+ });
907
+ res.end(body);
908
+ };
909
+ // Files served as they are from next to this one. A missing one is a
910
+ // missing picture or font, never a stopped dashboard.
911
+ const ASSETS = {
912
+ '/logo.png': ['image/png', opts.logoFile || path.join(__dirname, 'kryptheon-logo.png')],
913
+ '/fonts/archivo.woff2': ['font/woff2', path.join(__dirname, 'kryptheon-archivo.woff2')],
914
+ '/fonts/spacemono.woff2': ['font/woff2', path.join(__dirname, 'kryptheon-spacemono.woff2')],
915
+ };
916
+ const json = (res, code, value) => send(res, code, 'application/json; charset=utf-8', JSON.stringify(value));
917
+
918
+ const server = http.createServer((req, res) => {
919
+ if (!allowedHosts().has(String(req.headers.host || ''))) return send(res, 403, 'text/plain', 'Forbidden');
920
+ const url = new URL(req.url, 'http://127.0.0.1');
921
+
922
+ if (req.method === 'GET' && url.pathname === '/') {
923
+ return send(res, 200, 'text/html; charset=utf-8', page.replace('%%TOKEN%%', token));
924
+ }
925
+ if (req.method === 'GET' && url.pathname === '/dashboard.js') {
926
+ return send(res, 200, 'text/javascript; charset=utf-8', fs.readFileSync(path.join(__dirname, 'kryptheon-dashboard-page.js'), 'utf8'));
927
+ }
928
+ if (req.method === 'GET' && Object.prototype.hasOwnProperty.call(ASSETS, url.pathname)) {
929
+ const [type, file] = ASSETS[url.pathname];
930
+ let body;
931
+ try {
932
+ body = fs.readFileSync(file);
933
+ } catch (err) {
934
+ return send(res, 404, 'text/plain', 'Not found');
935
+ }
936
+ return send(res, 200, type, body);
937
+ }
938
+ if (req.method === 'GET' && url.pathname === '/api/state') {
939
+ return json(res, 200, buildState(root, env));
940
+ }
941
+ if (req.method === 'GET' && url.pathname === '/api/job') {
942
+ return json(res, 200, { job: jobs.get() });
943
+ }
944
+ if (req.method === 'POST') {
945
+ if (req.headers['x-kryptheon-token'] !== token) return json(res, 403, { ok: false, why: 'missing or wrong token' });
946
+ let body = '';
947
+ req.on('data', (chunk) => {
948
+ body += chunk;
949
+ if (body.length > 10000) req.destroy();
950
+ });
951
+ req.on('end', () => {
952
+ let input;
953
+ try {
954
+ input = JSON.parse(body || '{}');
955
+ } catch (err) {
956
+ return json(res, 400, { ok: false, why: 'not JSON' });
957
+ }
958
+ if (url.pathname === '/api/check') {
959
+ const r = setCheck(store.pathsFor(root, env), String(input.id || ''), input.on);
960
+ return json(res, r.ok ? 200 : 400, r);
961
+ }
962
+ if (url.pathname === '/api/autostart') {
963
+ const r = autostart.setAutostart(root, input.on, env);
964
+ return json(res, r.ok ? 200 : 400, { ok: r.ok, on: !!r.on, why: r.why || '' });
965
+ }
966
+ // Everything below starts a job: it answers at once with the job, and
967
+ // the page follows it on /api/job. One at a time - two browsers
968
+ // replaying against one app, or two attacks on one database, would
969
+ // interfere, and the results would describe neither.
970
+ const begin = (kind, title, command, work, secrets) => {
971
+ const job = jobs.start(kind, title, command, work, secrets);
972
+ return job ? json(res, 202, { ok: true, job: job }) : json(res, 409, { ok: false, why: 'a run is already going', job: jobs.get() });
973
+ };
974
+ if (url.pathname === '/api/stop') {
975
+ return jobs.stop() ? json(res, 200, { ok: true, job: jobs.get() }) : json(res, 409, { ok: false, why: 'nothing that can be stopped is running' });
976
+ }
977
+ // A check that adds test data to the app. Only with the person's yes
978
+ // from the page, and for an address that is not this computer, with
979
+ // their tick that it is their own test copy as well. The addresses
980
+ // are read again here, from the recordings - never taken from the page.
981
+ // The addresses the person said yes to that are not this computer:
982
+ // exactly the ones the page showed when it was ticked.
983
+ let confirmed = [];
984
+ const probeRefusal = (id) => {
985
+ const check = buildState(root, env).checks.find((c) => c.id === id);
986
+ if (!check || !check.asks) return (check ? check.label : '"' + id + '"') + ' cannot be run from here';
987
+ if (input.consent !== true) return 'it adds test data to your app, so it runs only after you say yes';
988
+ if (check.asks.live.length && input.liveConfirmed !== true) {
989
+ return check.asks.live.join(', ') + ' is not this computer - tick that it is your own test copy first';
990
+ }
991
+ confirmed = input.liveConfirmed === true ? check.asks.live : [];
992
+ return null;
993
+ };
994
+ if (url.pathname === '/api/probe' && typeof opts.probe === 'function') {
995
+ const id = String(input.id || '');
996
+ const refused = probeRefusal(id);
997
+ if (refused) return json(res, 400, { ok: false, why: refused });
998
+ return begin('probe', RUN_TITLE[id], RUN_COMMAND[id], (say, control) => opts.probe(id, say, control, confirmed));
999
+ }
1000
+ if (url.pathname === '/api/recheck' && typeof opts.recheck === 'function') {
1001
+ const id = String(input.id || '');
1002
+ if (!/^[0-9a-f]{8}$/.test(id)) return json(res, 400, { ok: false, why: 'not a finding id' });
1003
+ const open = buildState(root, env).findings.find((f) => f.id === id);
1004
+ if (!open) return json(res, 404, { ok: false, why: 'no open finding with that id' });
1005
+ if (PROBE_CHECKS.includes(open.check)) {
1006
+ const refused = probeRefusal(open.check);
1007
+ if (refused) return json(res, 400, { ok: false, why: refused });
1008
+ if (typeof opts.probeRecheck !== 'function') return json(res, 400, { ok: false, why: 'this finding cannot be re-checked from here' });
1009
+ return begin('recheck', 'Re-checking: ' + open.headline, 'npx kryptheon recheck ' + id, (say, control) => opts.probeRecheck(id, say, control, confirmed));
1010
+ }
1011
+ return begin('recheck', 'Re-checking: ' + open.headline, 'npx kryptheon recheck ' + id, (say) => opts.recheck(id, say));
1012
+ }
1013
+ if (url.pathname === '/api/run' && typeof opts.run === 'function') {
1014
+ const id = String(input.id || '');
1015
+ const check = buildState(root, env).checks.find((c) => c.id === id);
1016
+ if (!check || !check.runnable || !check.enabled) {
1017
+ return json(res, 400, { ok: false, why: (check ? check.label : '"' + id + '"') + ' cannot be run from here' });
1018
+ }
1019
+ return begin('run', RUN_TITLE[id] || check.label, RUN_COMMAND[id] || '', (say) => opts.run(id, say));
1020
+ }
1021
+ if (url.pathname === '/api/record' && typeof opts.record === 'function') {
1022
+ const address = appAddress(input.url);
1023
+ if (!address) return json(res, 400, { ok: false, why: notAnAddress(input.url, 'http://localhost:3000') });
1024
+ const phone = input.phone === true;
1025
+ return begin('record', 'Recording ' + address + (phone ? ' at phone size' : ''),
1026
+ 'npx kryptheon record ' + address + (phone ? ' --phone' : ''), (say) => opts.record(address, say, { phone: phone }));
1027
+ }
1028
+ if (url.pathname === '/api/db' && typeof opts.db === 'function') {
1029
+ const action = String(input.action || '');
1030
+ if (!DB_ACTIONS[action]) return json(res, 400, { ok: false, why: 'no database action called "' + action + '"' });
1031
+ const connection = connectionFrom(input.connection);
1032
+ if (!connection) return json(res, 400, { ok: false, why: 'paste your connection string first' });
1033
+ if (action === 'recheck') {
1034
+ // One database finding, re-checked: the check runs again and that
1035
+ // finding is judged, the way `npx kryptheon recheck` judges the rest.
1036
+ const id = String(input.id || '');
1037
+ if (!/^[0-9a-f]{8}$/.test(id)) return json(res, 400, { ok: false, why: 'not a finding id' });
1038
+ const target = buildState(root, env).findings.find((f) => f.id === id && f.check === 'data');
1039
+ if (!target) return json(res, 404, { ok: false, why: 'no open database finding with that id' });
1040
+ return begin('db', 'Re-checking: ' + target.headline, DB_ACTIONS.recheck.command, (say) => {
1041
+ const before = buildState(root, env).findings;
1042
+ return Promise.resolve(opts.db('scan', connection, say)).then((ran) => {
1043
+ const attempt = databaseVerdict(target, before, buildState(root, env).findings, ran, readJson(store.pathsFor(root, env).nightLast));
1044
+ try {
1045
+ fs.appendFileSync(store.pathsFor(root, env).fixes, JSON.stringify(attempt) + '\n', 'utf8');
1046
+ } catch (err) {
1047
+ attempt.saveError = err.message;
1048
+ }
1049
+ return Object.assign({ ok: true, summary: attempt.verdict }, attempt);
1050
+ });
1051
+ }, secretsOf(connection));
1052
+ }
1053
+ // Handed to the job and nowhere else. The job's lines and result are
1054
+ // scrubbed of it, and it is dropped the moment the job ends.
1055
+ return begin('db', DB_ACTIONS[action].title, DB_ACTIONS[action].command,
1056
+ (say) => opts.db(action, connection, say), secretsOf(connection));
1057
+ }
1058
+ if (url.pathname === '/api/app') {
1059
+ // The app's web address: saved for this project, so Record and the
1060
+ // outside check start from it. Empty clears it.
1061
+ const raw = typeof input.address === 'string' ? input.address.trim() : '';
1062
+ const address = raw ? appAddress(raw) : '';
1063
+ if (address === null) return json(res, 400, { ok: false, why: notAnAddress(raw, 'https://my-app.lovable.app') });
1064
+ const full = address && !/^https?:\/\//i.test(address) ? 'https://' + address : address;
1065
+ return saveAppAddress(store.pathsFor(root, env), full)
1066
+ ? json(res, 200, { ok: true, address: full })
1067
+ : json(res, 500, { ok: false, why: 'it could not be saved on this computer' });
1068
+ }
1069
+ if (url.pathname === '/api/choose-folder' && typeof opts.chooseFolder === 'function' && typeof opts.openFolder === 'function') {
1070
+ // The person's own folder picker, on this computer; then a dashboard
1071
+ // for that folder in a window of its own. Nothing is run in it here.
1072
+ return Promise.resolve(opts.chooseFolder()).then((folder) => {
1073
+ if (!folder) return json(res, 200, { ok: false, cancelled: true, why: 'no folder was chosen' });
1074
+ const opened = opts.openFolder(folder);
1075
+ return json(res, opened.ok ? 200 : 400, Object.assign({ folder: folder }, opened));
1076
+ }, (err) => json(res, 500, { ok: false, why: err.message }));
1077
+ }
1078
+ if (url.pathname === '/api/db/words' && typeof opts.words === 'function') {
1079
+ // What kryptheon-night itself would say about this string - its help,
1080
+ // its consent screens, its warnings - asked of it without connecting.
1081
+ const connection = input.connection == null || input.connection === '' ? '' : connectionFrom(input.connection);
1082
+ if (connection === null) return json(res, 400, { ok: false, why: 'that connection string is too long' });
1083
+ const secrets = secretsOf(connection);
1084
+ return Promise.resolve(opts.words(connection)).then(
1085
+ (words) => json(res, 200, hideSecretsIn({ ok: true, words: words }, secrets)),
1086
+ (err) => json(res, 500, hideSecretsIn({ ok: false, why: err.message }, secrets)),
1087
+ );
1088
+ }
1089
+ return json(res, 404, { ok: false, why: 'no such action' });
1090
+ });
1091
+ return;
1092
+ }
1093
+ return send(res, 404, 'text/plain', 'Not found');
1094
+ });
1095
+
1096
+ return {
1097
+ server: server,
1098
+ token: token,
1099
+ listen(wanted) {
1100
+ return new Promise((resolve, reject) => {
1101
+ server.once('error', reject);
1102
+ server.listen(wanted || 0, '127.0.0.1', () => {
1103
+ port = server.address().port;
1104
+ resolve(port);
1105
+ });
1106
+ });
1107
+ },
1108
+ close() {
1109
+ return new Promise((resolve) => server.close(() => resolve()));
1110
+ },
1111
+ };
1112
+ }
1113
+
1114
+ module.exports = {
1115
+ CHECKS: CHECKS,
1116
+ buildState: buildState,
1117
+ flowPrompt: flowPrompt,
1118
+ appAddress: appAddress,
1119
+ meantAddress: meantAddress,
1120
+ secretsOf: secretsOf,
1121
+ hideSecrets: hideSecrets,
1122
+ hideSecretsIn: hideSecretsIn,
1123
+ createJobs: createJobs,
1124
+ DB_ACTIONS: DB_ACTIONS,
1125
+ databaseVerdict: databaseVerdict,
1126
+ startSteps: startSteps,
1127
+ nextAction: nextAction,
1128
+ combinedPrompt: combinedPrompt,
1129
+ readConfig: readConfig,
1130
+ setCheck: setCheck,
1131
+ createServer: createServer,
1132
+ };