kryptheon 0.1.65 → 0.1.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/kryptheon.js CHANGED
@@ -190,6 +190,9 @@ function ensureBrowser() {
190
190
  console.log('');
191
191
  console.log(' Downloading a browser to run your app in.');
192
192
  console.log(' This is about 200MB and only happens once.');
193
+ // A new user took Playwright's own box for an error (2026-11-10): said before it appears.
194
+ console.log(' Playwright may print a WARNING box about installing dependencies first -');
195
+ console.log(' that is harmless here. Wait for the download to finish.');
193
196
  console.log('');
194
197
  // Playwright's install deletes every browser it thinks no other copy of
195
198
  // Playwright still uses. With Kryptheon installed in a project and run by
@@ -1354,6 +1357,12 @@ async function finaliseRecording(outFile, context) {
1354
1357
  // npx, not the bare name: somebody who started with `npx kryptheon record`
1355
1358
  // has no `kryptheon` command, and would be told it does not exist.
1356
1359
  console.log(' Run it any time with: npx kryptheon check');
1360
+ // Recording is only the first step: a new user read the line above and thought Kryptheon just records the
1361
+ // screen (2026-11-10). Where the app is actually checked is said here.
1362
+ console.log('');
1363
+ console.log(' Next: open the dashboard and press "Check my whole app" - that is where your');
1364
+ console.log(' app is checked for bugs and security holes, each with a prompt to fix it:');
1365
+ console.log(' npx kryptheon@latest dashboard');
1357
1366
  console.log('');
1358
1367
 
1359
1368
  reportTidying(tidied);
@@ -3490,7 +3499,11 @@ function dashboardAlreadyRunning(port) {
3490
3499
  const same = (a) => (process.platform === 'win32' ? path.resolve(a).toLowerCase() : path.resolve(a));
3491
3500
  if (res.statusCode !== 200 || typeof root !== 'string' || same(root) !== same(USER_DIR)) return resolve(false);
3492
3501
  // Before 0.1.41 a dashboard did not say which it was: an old one.
3493
- resolve({ version: typeof state.kryptheon === 'string' ? state.kryptheon : null });
3502
+ // From 0.1.67 it also says which process it is.
3503
+ resolve({
3504
+ version: typeof state.kryptheon === 'string' ? state.kryptheon : null,
3505
+ pid: Number.isInteger(state.pid) && state.pid > 0 ? state.pid : null,
3506
+ });
3494
3507
  } catch (err) {
3495
3508
  resolve(false);
3496
3509
  }
@@ -3501,16 +3514,36 @@ function dashboardAlreadyRunning(port) {
3501
3514
  });
3502
3515
  }
3503
3516
 
3504
- /** The process listening on 127.0.0.1:port, or null. */
3517
+ /** The process listening on 127.0.0.1:port in netstat's lines, or null. */
3518
+ function listenerInNetstat(out, port) {
3519
+ for (const line of String(out || '').split(/\r?\n/)) {
3520
+ const m = line.trim().split(/\s+/);
3521
+ if (m.length >= 5 && m[0] === 'TCP' && m[1] === '127.0.0.1:' + port && m[3] === 'LISTENING' && /^\d+$/.test(m[4]) && Number(m[4]) > 0) return Number(m[4]);
3522
+ }
3523
+ return null;
3524
+ }
3525
+
3526
+ /**
3527
+ * The process listening on 127.0.0.1:port, or null. On Windows netstat is
3528
+ * asked twice, with and without -p TCP, then PowerShell: on one Windows 11
3529
+ * build `netstat -p TCP` left the port out, and plain netstat did not always
3530
+ * list it either.
3531
+ */
3505
3532
  function listenerOn(port) {
3533
+ // For the check that a dashboard's stated process is enough on its own.
3534
+ if (process.env.KRYPTHEON_NO_LISTENER_LOOKUP === '1') return null;
3506
3535
  try {
3507
3536
  if (process.platform === 'win32') {
3508
- const out = spawnSync('netstat', ['-ano', '-p', 'TCP'], { encoding: 'utf8', windowsHide: true, timeout: 10000 }).stdout || '';
3509
- for (const line of out.split(/\r?\n/)) {
3510
- const m = line.trim().split(/\s+/);
3511
- if (m.length >= 5 && m[1] === '127.0.0.1:' + port && m[3] === 'LISTENING' && /^\d+$/.test(m[4])) return Number(m[4]);
3537
+ for (const args of [['-ano'], ['-ano', '-p', 'TCP']]) {
3538
+ const out = spawnSync('netstat', args, { encoding: 'utf8', windowsHide: true, timeout: 10000 }).stdout;
3539
+ const pid = listenerInNetstat(out, port);
3540
+ if (pid) return pid;
3512
3541
  }
3513
- return null;
3542
+ const ps = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
3543
+ '(Get-NetTCPConnection -LocalAddress 127.0.0.1 -LocalPort ' + Number(port) + ' -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1).OwningProcess'],
3544
+ { encoding: 'utf8', windowsHide: true, timeout: 15000 }).stdout || '';
3545
+ const pid = Number(ps.trim());
3546
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
3514
3547
  }
3515
3548
  const out = spawnSync('lsof', ['-nP', '-iTCP@127.0.0.1:' + port, '-sTCP:LISTEN', '-t'], { encoding: 'utf8', timeout: 10000 }).stdout || '';
3516
3549
  const pid = Number(out.trim().split(/\s+/)[0]);
@@ -3528,8 +3561,12 @@ function listenerOn(port) {
3528
3561
  * Only the process that answered as this folder's Kryptheon dashboard is
3529
3562
  * stopped. Whether the port came free is the answer.
3530
3563
  */
3531
- async function replaceOldDashboard(port) {
3532
- const pid = listenerOn(port);
3564
+ async function replaceOldDashboard(port, said) {
3565
+ // The process the system says holds the port comes first. A dashboard from
3566
+ // 0.1.67 on also says which process it is: used when the system does not
3567
+ // say, and only if that process is Node.
3568
+ const stated = said && said.pid ? said.pid : null;
3569
+ const pid = listenerOn(port) || (stated && isNodeProcess(stated) ? stated : null) || onlyOtherDashboard();
3533
3570
  if (!pid || pid === process.pid) return false;
3534
3571
  try {
3535
3572
  if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(pid), '/F'], { windowsHide: true, timeout: 10000 });
@@ -3537,13 +3574,72 @@ async function replaceOldDashboard(port) {
3537
3574
  } catch (err) {
3538
3575
  return false;
3539
3576
  }
3577
+ // Whether the port came free is asked of the port itself, not of netstat.
3540
3578
  for (let i = 0; i < 50; i++) {
3541
- if (listenerOn(port) === null) return true;
3579
+ if (!(await portAnswers(port))) return true;
3542
3580
  await new Promise((r) => setTimeout(r, 100));
3543
3581
  }
3544
3582
  return false;
3545
3583
  }
3546
3584
 
3585
+ /** Whether something accepts connections on 127.0.0.1:port. */
3586
+ function portAnswers(port) {
3587
+ return new Promise((resolve) => {
3588
+ const socket = require('net').connect({ host: '127.0.0.1', port: port });
3589
+ const done = (yes) => { socket.destroy(); resolve(yes); };
3590
+ socket.setTimeout(1000, () => done(false));
3591
+ socket.once('connect', () => done(true));
3592
+ socket.once('error', () => done(false));
3593
+ });
3594
+ }
3595
+
3596
+ /**
3597
+ * A dashboard from before 0.1.67 does not say which process it is. When the
3598
+ * system will not say who holds the port either, the one other process
3599
+ * running `kryptheon.js dashboard` is it - only when there is exactly one,
3600
+ * and never this process or the one that started it (from the home folder a
3601
+ * dashboard runs itself again inside kryptheon-tests).
3602
+ */
3603
+ function onlyOtherDashboard() {
3604
+ if (process.env.KRYPTHEON_NO_LISTENER_LOOKUP === '1') return null;
3605
+ const isDashboard = (line) => /kryptheon[\\/]bin[\\/]kryptheon\.js"?\s+dashboard(\s|$)/i.test(line);
3606
+ let rows = [];
3607
+ try {
3608
+ if (process.platform === 'win32') {
3609
+ const out = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
3610
+ "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | ForEach-Object { [string]$_.ProcessId + ' ' + $_.CommandLine }"],
3611
+ { encoding: 'utf8', windowsHide: true, timeout: 15000 }).stdout || '';
3612
+ rows = out.split(/\r?\n/);
3613
+ } else {
3614
+ rows = (spawnSync('ps', ['-eo', 'pid=,args='], { encoding: 'utf8', timeout: 10000 }).stdout || '').split(/\n/);
3615
+ }
3616
+ } catch (err) {
3617
+ return null;
3618
+ }
3619
+ const found = [];
3620
+ for (const row of rows) {
3621
+ const m = /^\s*(\d+)\s+(.*)$/.exec(row);
3622
+ if (!m || !isDashboard(m[2])) continue;
3623
+ const pid = Number(m[1]);
3624
+ if (pid !== process.pid && pid !== process.ppid) found.push(pid);
3625
+ }
3626
+ return found.length === 1 ? found[0] : null;
3627
+ }
3628
+
3629
+ /** Whether the process with this id is Node - the only kind a dashboard is. */
3630
+ function isNodeProcess(pid) {
3631
+ try {
3632
+ if (process.platform === 'win32') {
3633
+ const out = spawnSync('tasklist', ['/FI', 'PID eq ' + Number(pid), '/FO', 'CSV', '/NH'], { encoding: 'utf8', windowsHide: true, timeout: 10000 }).stdout || '';
3634
+ return /^"node\.exe","\d+"/im.test(out.trim()) && out.includes('"' + Number(pid) + '"');
3635
+ }
3636
+ const out = spawnSync('ps', ['-p', String(Number(pid)), '-o', 'comm='], { encoding: 'utf8', timeout: 10000 }).stdout || '';
3637
+ return /node/i.test(out);
3638
+ } catch (err) {
3639
+ return false;
3640
+ }
3641
+ }
3642
+
3547
3643
  /**
3548
3644
  * The dashboard, started from the home folder: kept in a kryptheon-tests
3549
3645
  * folder there, the one record already uses - set up the first time, asked
@@ -3636,7 +3732,7 @@ async function dashboardCommand() {
3636
3732
  if (running && running.version !== mine) {
3637
3733
  const was = running.version || 'from before 0.1.41';
3638
3734
  console.log('');
3639
- console.log(await replaceOldDashboard(DASHBOARD_PORT)
3735
+ console.log(await replaceOldDashboard(DASHBOARD_PORT, running)
3640
3736
  ? ' An older Kryptheon dashboard (' + was + ') was running for this folder.\n It was closed, and ' + mine + ' starts in its place.'
3641
3737
  : ' An older Kryptheon dashboard (' + was + ') is still running and could not be\n closed. This one starts at another address; close the old window when you can.');
3642
3738
  }
@@ -4090,4 +4186,19 @@ module.exports = {
4090
4186
  nodeIsTooOld: nodeIsTooOld,
4091
4187
  };
4092
4188
 
4093
- if (require.main === module) main();
4189
+ if (require.main === module) {
4190
+ // A newer version on npm, said once at the end of a command (npx can keep handing out an old cached copy, and an
4191
+ // install in a project stays where it was). Not in a dashboard's own jobs: the dashboard says it once, on its page.
4192
+ const newer = require(path.join(__dirname, '..', 'kryptheon-newer.js'));
4193
+ const own = (() => { try { return JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8')).version; } catch (err) { return null; } })();
4194
+ let latestSeen = null;
4195
+ if (own && !process.env.KRYPTHEON_DASHBOARD_JOB) {
4196
+ newer.latestOf('kryptheon').then((v) => { latestSeen = v; });
4197
+ process.on('exit', () => {
4198
+ const words = process.argv.slice(2).filter((a) => !/:\/\/[^@/]*@/.test(a)).join(' ');
4199
+ const said = newer.notice('kryptheon', own, latestSeen, 'npx kryptheon@latest' + (words ? ' ' + words : ''));
4200
+ if (said) process.stderr.write('\n ' + said + '\n\n');
4201
+ });
4202
+ }
4203
+ main();
4204
+ }
@@ -0,0 +1,183 @@
1
+ // The local dashboard's connection to a kryptheon.tech account (owner's decision, 2026-11-10).
2
+ //
3
+ // A connect code (kd_...) is made on the account page for one of the person's apps, and pasted once into the
4
+ // dashboard's "Your account" box. It is kept in this project's own store (account.json, outside the project, like
5
+ // everything else Kryptheon remembers), and is only ever sent to kryptheon.tech's entitlement function. That
6
+ // answers with the plan, and opens Starter's five fix prompts a month for this app, counted there - never here.
7
+ //
8
+ // What leaves this computer: the code, and for each prompt opened on Starter a fingerprint - a hash of the finding's
9
+ // id. Never a finding's words, a route, a file, the app's code or its data.
10
+ //
11
+ // lock() decides what the dashboard's page is sent:
12
+ // - not connected: every finding and its proof; no fix prompt (reason "connect");
13
+ // - Starter: the prompts of findings opened this month; the rest locked (reason "free-left" while some of the five
14
+ // are left, "used" after);
15
+ // - Pro and Studio: everything, and the one prompt for all.
16
+ // buildState itself is not changed: verify, recheck and the other checks read prompts as before.
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const crypto = require('crypto');
21
+ const store = require('./kryptheon-store.js');
22
+
23
+ const ENTITLEMENT = 'https://dkheqkynldupnxorqscd.supabase.co/functions/v1/entitlement';
24
+ const CODE = /^kd_[A-Za-z0-9_-]{20,100}$/;
25
+ const FILE = 'account.json';
26
+ const PAID = new Set(['pro', 'studio']);
27
+ const PRICING = 'https://kryptheon.tech/pricing/';
28
+ const ACCOUNT_PAGE = 'https://kryptheon.tech/dashboard/#computer';
29
+
30
+ const fileOf = (root, env) => path.join(store.pathsFor(root, env).dir, FILE);
31
+ const monthNow = () => new Date().toISOString().slice(0, 7);
32
+
33
+ /** The fingerprint kryptheon.tech counts a finding by: a hash of its id, nothing of its words. */
34
+ function fingerprintOf(findingId) {
35
+ return crypto.createHash('sha256').update('kryptheon-finding:' + String(findingId)).digest('hex').slice(0, 32);
36
+ }
37
+
38
+ function read(root, env) {
39
+ try {
40
+ const a = JSON.parse(fs.readFileSync(fileOf(root, env), 'utf8'));
41
+ return a && typeof a === 'object' ? a : null;
42
+ } catch (err) {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ function write(root, env, value) {
48
+ const file = fileOf(root, env);
49
+ fs.mkdirSync(path.dirname(file), { recursive: true });
50
+ // Readable by this computer's account only, where the file system lets it say so.
51
+ fs.writeFileSync(file, JSON.stringify(value, null, 2), { mode: 0o600 });
52
+ }
53
+
54
+ function forget(root, env) {
55
+ try {
56
+ fs.unlinkSync(fileOf(root, env));
57
+ } catch (err) {
58
+ /* not there */
59
+ }
60
+ }
61
+
62
+ /** Asks kryptheon.tech, with the code: { status, body } or { status: 0, why } when it cannot be reached. */
63
+ async function ask(env, code, body) {
64
+ const url = (env && env.KRYPTHEON_ACCOUNT_URL) || ENTITLEMENT;
65
+ try {
66
+ const res = await fetch(url, {
67
+ method: 'POST',
68
+ headers: { authorization: 'Bearer ' + code, 'content-type': 'application/json' },
69
+ body: JSON.stringify(body || {}),
70
+ signal: AbortSignal.timeout(8000),
71
+ });
72
+ const answer = await res.json().catch(() => ({}));
73
+ return { status: res.status, body: answer };
74
+ } catch (err) {
75
+ return { status: 0, why: 'kryptheon.tech could not be reached - check your internet connection and try again' };
76
+ }
77
+ }
78
+
79
+ /** What kryptheon.tech said about the plan, kept with the code. */
80
+ function keep(root, env, code, body, unlocked) {
81
+ const month = body.month || monthNow();
82
+ const was = unlocked && unlocked.month === month ? unlocked.ids : [];
83
+ write(root, env, {
84
+ code: code,
85
+ app: String(body.project || ''),
86
+ plan: String(body.plan || 'starter'),
87
+ clientReport: !!body.clientReport,
88
+ prompts: body.prompts || { limit: 5, used: 0, left: 5 },
89
+ month: month,
90
+ unlocked: { month: month, ids: was },
91
+ checkedAt: new Date().toISOString(),
92
+ });
93
+ return read(root, env);
94
+ }
95
+
96
+ /** Connects with a code from the account page: { ok, account } or { ok: false, why }. */
97
+ async function connect(root, env, code) {
98
+ const c = String(code || '').trim();
99
+ if (!CODE.test(c)) return { ok: false, why: 'that is not a connect code - it starts with kd_; get it from your account page on kryptheon.tech' };
100
+ const r = await ask(env, c, {});
101
+ if (r.status === 0) return { ok: false, why: r.why };
102
+ if (r.status !== 200) return { ok: false, why: (r.body && r.body.error) || 'kryptheon.tech did not accept that code' };
103
+ const before = read(root, env);
104
+ return { ok: true, account: summary(keep(root, env, c, r.body, before && before.code === c ? before.unlocked : null)) };
105
+ }
106
+
107
+ /** Asks again with the kept code: the plan may have changed, or the code been replaced. */
108
+ async function refresh(root, env) {
109
+ const a = read(root, env);
110
+ if (!a || !a.code) return { ok: true, account: summary(null) };
111
+ const r = await ask(env, a.code, {});
112
+ if (r.status === 0) return { ok: false, why: r.why, account: summary(a) };
113
+ if (r.status === 401) {
114
+ // Replaced on the account page, or the app removed: not connected any more, and said why.
115
+ write(root, env, { problem: (r.body && r.body.error) || 'this connect code no longer works - get a new one from your account on kryptheon.tech' });
116
+ return { ok: true, account: summary(read(root, env)) };
117
+ }
118
+ if (r.status !== 200) return { ok: false, why: (r.body && r.body.error) || 'kryptheon.tech did not answer', account: summary(a) };
119
+ return { ok: true, account: summary(keep(root, env, a.code, r.body, a.unlocked)) };
120
+ }
121
+
122
+ /** Opens one finding's fix prompt: free on Pro and Studio; on Starter, one of the five this month. */
123
+ async function unlock(root, env, findingId) {
124
+ const a = read(root, env);
125
+ if (!a || !a.code) return { ok: false, status: 401, why: 'connect your free Kryptheon account first' };
126
+ if (PAID.has(a.plan)) return { ok: true, account: summary(a) };
127
+ const r = await ask(env, a.code, { unlock: fingerprintOf(findingId) });
128
+ if (r.status === 0) return { ok: false, status: 503, why: r.why };
129
+ if (r.status === 401) {
130
+ write(root, env, { problem: (r.body && r.body.error) || 'this connect code no longer works' });
131
+ return { ok: false, status: 401, why: (r.body && r.body.error) || 'this connect code no longer works' };
132
+ }
133
+ const month = r.body.month || monthNow();
134
+ const ids = a.unlocked && a.unlocked.month === month ? a.unlocked.ids.slice() : [];
135
+ if (r.status === 200 && r.body.unlocked) {
136
+ if (!ids.includes(findingId)) ids.push(findingId);
137
+ }
138
+ write(root, env, Object.assign({}, a, { plan: r.body.plan || a.plan, prompts: r.body.prompts || a.prompts, month: month, unlocked: { month: month, ids: ids }, checkedAt: new Date().toISOString() }));
139
+ if (r.status === 402) return { ok: false, status: 402, why: 'this month\'s free fix prompts are used - Pro opens every one', account: summary(read(root, env)) };
140
+ if (r.status !== 200) return { ok: false, status: r.status, why: (r.body && r.body.error) || 'kryptheon.tech did not answer' };
141
+ return { ok: true, account: summary(read(root, env)) };
142
+ }
143
+
144
+ function disconnect(root, env) {
145
+ forget(root, env);
146
+ return { ok: true, account: summary(null) };
147
+ }
148
+
149
+ /** What the page may know about the account: never the code. */
150
+ function summary(a) {
151
+ if (!a || !a.code) {
152
+ return { connected: false, problem: a && a.problem ? a.problem : '', accountPage: ACCOUNT_PAGE, pricing: PRICING };
153
+ }
154
+ return {
155
+ connected: true, app: a.app, plan: a.plan, clientReport: !!a.clientReport, prompts: a.prompts, month: a.month,
156
+ checkedAt: a.checkedAt, accountPage: ACCOUNT_PAGE, pricing: PRICING,
157
+ };
158
+ }
159
+
160
+ /** The dashboard state as the page may see it, for this account. A new object; `state` is not changed. */
161
+ function lock(state, root, env) {
162
+ const a = read(root, env);
163
+ const out = Object.assign({}, state, { account: summary(a) });
164
+ if (a && a.code && PAID.has(a.plan)) return out;
165
+ const connected = !!(a && a.code);
166
+ const month = monthNow();
167
+ const opened = new Set(connected && a.unlocked && a.unlocked.month === month ? a.unlocked.ids : []);
168
+ const left = connected && a.prompts && typeof a.prompts.left === 'number' ? a.prompts.left : 0;
169
+ out.findings = (state.findings || []).map((f) => {
170
+ if (!f.fixPrompt || opened.has(f.id)) return f;
171
+ const firstLine = String(f.fixPrompt).split('\n').map((l) => l.trim()).find(Boolean) || '';
172
+ return Object.assign({}, f, {
173
+ fixPrompt: '',
174
+ promptLock: { reason: !connected ? 'connect' : left > 0 ? 'free-left' : 'used', left: left, preview: firstLine.slice(0, 160) },
175
+ });
176
+ });
177
+ // The one prompt for every finding at once is Pro's: on Starter it would open them all.
178
+ out.allFixPrompt = '';
179
+ out.allFixPromptLocked = !!state.allFixPrompt;
180
+ return out;
181
+ }
182
+
183
+ module.exports = { connect, refresh, unlock, disconnect, lock, summary, fingerprintOf, read, ENTITLEMENT, CODE };
package/kryptheon-api.js CHANGED
@@ -146,6 +146,8 @@ function sampleValue(field, known, roleNames) {
146
146
  if (roleNames && roleNames.length && wordsOf(field.name).includes('role')) return roleNames[0];
147
147
  const en = (field.checks || []).find((c) => c.kind === 'enum' && c.values && c.values.length);
148
148
  if (en) return en.values[0];
149
+ // read by the code as Number(...) / parseInt(...): a number (round 33)
150
+ if (field.numeric) return 1;
149
151
  if (known && known.has(field.name)) return known.get(field.name)[0];
150
152
  // the column of the same name, as the app's own CREATE TABLE declares it (round 25: text into a boolean, NaN into an integer)
151
153
  const declared = known && known.types && known.types[String(field.name).toLowerCase()];
@@ -744,7 +746,34 @@ async function runInvalid(root, options) {
744
746
  const probes = probesOf(a);
745
747
  if (!probes.length) continue;
746
748
  if (a.params.length || a.method !== 'POST') {
747
- out.notTried.push({ what: what, why: 'it changes an existing record, and bad values are only tried on routes that create one' });
749
+ // A step on one record that changes it by an amount (PATCH /stock/{id}/adjust, delta): only a change larger than
750
+ // what is held, at a record its own list shows, then the opposite change, then the starting change undone (round 33:
751
+ // stock adjusted to -999 was never tried, as the route changes an existing record). Nothing else is sent there.
752
+ const over = probes.filter((pr) => pr.mode === 'overdraw');
753
+ const listT = a.params.length === 1 ? a.template.split('/{id}')[0] : null;
754
+ const rec = over.length && listT && getTemplates.has(listT) ? ((rowsOfReply(await session.send('GET', listT, {})) || []).find((r) => r && r.id !== undefined)) : null;
755
+ if (!rec) {
756
+ out.notTried.push({ what: what, why: 'it changes an existing record, and bad values are only tried on routes that create one' });
757
+ continue;
758
+ }
759
+ reaching = a;
760
+ const at = a.template.replace('{id}', encodeURIComponent(String(rec.id)));
761
+ const sendAt = (b) => session.send(a.method, at, a.encoding === 'form' ? { form: b } : { json: b });
762
+ const base = a.fullData || {};
763
+ const first = await sendAt(base);
764
+ if (!isTaken(first)) {
765
+ out.notTried.push({ what: what, why: 'the app refused the request (' + first.status + ') before any bad value was added, so no bad value could be judged' });
766
+ continue;
767
+ }
768
+ for (const pr of over) {
769
+ if (opts.stopped && opts.stopped()) return out;
770
+ await overdraw(a, pr.field, pr, base, Object.assign({}, base, { [pr.field.name]: pr.value }), sendAt);
771
+ }
772
+ // the starting change, undone
773
+ const undo = Object.assign({}, base);
774
+ for (const pr of over) if (typeof base[pr.field.name] === 'number') undo[pr.field.name] = -base[pr.field.name];
775
+ const undone = await sendAt(undo);
776
+ out.left.push(what.replace('{id}', rec.id) + ' with a valid body (' + Object.keys(base).join(', ') + ') - the starting point of the tries' + (isTaken(undone) ? ', undone by the opposite change' : ' (the opposite change was refused: ' + undone.status + ')'));
748
777
  continue;
749
778
  }
750
779
  // A bad value means something only if the same request without it is taken. The full body first; if the app
@@ -1905,6 +1934,11 @@ function doubleEffects(before, after, rec, listTemplate, body, stepTemplate) {
1905
1934
  // a log: each request writes its own audit or activity line (harness, rounds 27-28)
1906
1935
  for (const l of addsToList ? [] : Object.keys(after)) {
1907
1936
  if (HISTORY_LIST.test(String(l).split('/').filter(Boolean).pop() || '')) continue;
1937
+ // the log as one array of a summary address (GET /dashboard -> { metrics, activity: [...] }) - round 33
1938
+ const aj = after[l];
1939
+ const compared = rowsOfReply({ status: 200, json: aj });
1940
+ const arrayKey = aj && typeof aj === 'object' && !Array.isArray(aj) ? Object.keys(aj).find((k) => aj[k] === compared) : undefined;
1941
+ if (arrayKey && wordsOf(arrayKey).some((w) => HISTORY_LIST.test(w))) continue;
1908
1942
  const had = new Set((rowsOfReply({ status: 200, json: before[l] }) || []).map((x) => x && JSON.stringify(x.id)));
1909
1943
  const fresh = (rowsOfReply({ status: 200, json: after[l] }) || []).filter((x) => x && typeof x === 'object' && x.id !== undefined && !had.has(JSON.stringify(x.id)));
1910
1944
  const tied = fresh.filter((x) => Object.keys(x).some((k) => k !== 'id' && pointerKey(k, listTemplate) && String(x[k]) === String(rec.id)));
@@ -1943,6 +1977,8 @@ function doubleEffects(before, after, rec, listTemplate, body, stepTemplate) {
1943
1977
  }
1944
1978
 
1945
1979
  // Lists that write a line per request (two lines for two requests is the log doing its job).
1980
+ // A word of an address or a body field about who may do what (round 33): such a change is the roles check's to try.
1981
+ const ACCESS_WORD = /^(role|roles|permission|permissions|privilege|privileges|grant|revoke|promote|demote|elevate|password|passwd|passcode|passphrase|pin|secret|token|otp|totp|mfa|2fa|apikey|credential|credentials)$/;
1946
1982
  const HISTORY_LIST = /^(audit|audits|audit[-_]?logs?|logs?|activity|activities|activity[-_]?logs?|history|histories|timeline|notifications?|events[-_]?log)$/i;
1947
1983
  // A last path word that is a step done to the record, though it ends in "s" (process, access, address, pass, status).
1948
1984
  const STEP_VERB = /^(process|access|address|pass|bypass|status|progress|dismiss|redress|reassess|assess)$/i;
@@ -1992,15 +2028,45 @@ async function scarceClaim(s, c, j, lists, snap, taken) {
1992
2028
  const col = cols.find((k) => rows[0][k] !== undefined);
1993
2029
  if (!col) continue;
1994
2030
  const ids = new Set(rows.map((r) => String(r.id)));
1995
- // the field of the create body that names a row of this list: its value is one of that list's ids
1996
- const pointer = Object.keys(create.fullData).find((k) => /(^|_)id$|Id$/.test(k) && ids.has(String(create.fullData[k])));
1997
- if (!pointer) continue;
2031
+ // The fields of the create body, and of its first line when it carries a list of lines (blind round 33: items:
2032
+ // [{ productId, quantity }]): [{ path, key, value }]
2033
+ const leaves = [];
2034
+ for (const k of Object.keys(create.fullData)) {
2035
+ const v = create.fullData[k];
2036
+ if (Array.isArray(v) && v[0] && typeof v[0] === 'object' && !Array.isArray(v[0])) for (const k2 of Object.keys(v[0])) leaves.push({ path: [k, 0, k2], key: k2, value: v[0][k2] });
2037
+ else if (v === null || typeof v !== 'object') leaves.push({ path: [k], key: k, value: v });
2038
+ }
2039
+ const flat = (k) => String(k).replace(/_/g, '').toLowerCase();
2040
+ const isPointer = (k) => /(^|_)id$|Id$/.test(k);
1998
2041
  const scarce = rows.filter((r) => Number(r[col]) > 0).sort((x, y) => Number(x[col]) - Number(y[col]))[0];
1999
2042
  if (!scarce) continue;
2043
+ // What each pointer of the body is set to. Named like a field of the row (productId -> product_id, warehouseId ->
2044
+ // warehouse_id: the stock found by product and place), that field's value - every such field, so the new record
2045
+ // claims exactly that row. Only when none is named so, the one pointer whose value is a row's own id (round 32:
2046
+ // productId = a catalog row's id). A value that merely equals some row's id is not taken as naming it.
2047
+ const sets = [];
2048
+ for (const l2 of leaves) {
2049
+ if (!isPointer(l2.key)) continue;
2050
+ const rk = Object.keys(scarce).find((x) => x !== 'id' && flat(x) === flat(l2.key));
2051
+ if (rk && scarce[rk] !== null && scarce[rk] !== undefined) sets.push({ path: l2.path, value: scarce[rk] });
2052
+ }
2053
+ if (!sets.length) {
2054
+ const byId = leaves.find((l2) => isPointer(l2.key) && ids.has(String(l2.value)));
2055
+ if (byId) sets.push({ path: byId.path, value: scarce.id });
2056
+ }
2057
+ if (!sets.length) continue;
2000
2058
  const units = Number(scarce[col]);
2001
- const qty = Object.keys(create.fullData).find((k) => CLAIM_QTY.test(k));
2059
+ const qty = leaves.find((l2) => CLAIM_QTY.test(l2.key));
2002
2060
  if (!qty && units > 1) continue; // one unit per record and more than one left: two records cannot overdraw it
2003
- const body = Object.assign({}, create.fullData, { [pointer]: scarce.id }, qty ? { [qty]: units } : {});
2061
+ if (qty) sets.push({ path: qty.path, value: units });
2062
+ // one line only, the one claiming the scarce row
2063
+ const body = JSON.parse(JSON.stringify(create.fullData));
2064
+ for (const k of Object.keys(body)) if (Array.isArray(body[k]) && body[k].length > 1 && sets.some((x) => x.path[0] === k && x.path.length === 3)) body[k] = body[k].slice(0, 1);
2065
+ for (const x of sets) {
2066
+ let o = body;
2067
+ for (const p of x.path.slice(0, -1)) o = o[p];
2068
+ o[x.path[x.path.length - 1]] = x.value;
2069
+ }
2004
2070
  const made = [];
2005
2071
  for (let n = 0; n < 2; n++) {
2006
2072
  const before = rowsOfReply(await s.send('GET', c.listTemplate, {})) || [];
@@ -2038,8 +2104,17 @@ async function runStepsAtOnce(root, options) {
2038
2104
  const known = allowedByName(plan.map);
2039
2105
  const confirms = (plan.map.routes || []).filter((r) => !r.unmounted && r.path && /^(POST|PUT|PATCH)$/.test(r.method) && /\/:\w+\*?\/confirm$/i.test(r.path) && !SIGN_IN.test(r.path) && !SIGN_OUT.test(r.path))
2040
2106
  .map((r) => actionOf(r, known, null)).filter((a) => !a.leftOut.length && !j.actions.some((x) => x.method === a.method && x.template === a.template));
2107
+ // A change of who may do what - a role, a permission, a password, a key - is never sent twice at once here: the roles
2108
+ // check tries it, as the account it is about, and puts it back. Not blind, round 33: PATCH /team/1/role {"role":"support"}
2109
+ // was sent twice at the signed-in owner's own record, demoting it, and every check after it ran as support.
2110
+ const setAside = [];
2041
2111
  for (const a of j.actions.concat(confirms)) {
2042
2112
  if (!/^(POST|PUT|PATCH)$/.test(a.method) || a.params.length !== 1 || a.segs.length !== a.params[0].index + 2 || JOB_PATH.test(a.template)) continue;
2113
+ const words = [].concat(...a.segs.filter((s) => s !== '{id}').map((s) => wordsOf(s)), ...Object.keys(a.fullData || {}).map((k) => wordsOf(k)));
2114
+ if (words.some((w) => ACCESS_WORD.test(w))) {
2115
+ setAside.push({ what: a.method + ' ' + a.template, verdict: 'not sent: it changes who may do what (a role, a permission or a credential) - the roles check tries that, and puts it back' });
2116
+ continue;
2117
+ }
2043
2118
  const route = (plan.map.routes || []).find((r) => !r.unmounted && r.method === a.method && normRoute(r.path || '') === a.template);
2044
2119
  const effect = route && stepEffectOf(root, route);
2045
2120
  const listTemplate = '/' + a.segs.slice(0, a.params[0].index).join('/');
@@ -2074,7 +2149,7 @@ async function runStepsAtOnce(root, options) {
2074
2149
  // What one step costs here: per account a list and a read of every list, two sends and another read; and the same
2075
2150
  // again for two records. Sized to the app, never past 3000 (the limit of the whole run is kept: ctx.limit only goes up).
2076
2151
  if (opts.maxRequests === undefined) ctx.limit = Math.min(3000, Math.max(ctx.limit, ctx.requests + 20 + candidates.length * (sessions.length * (lists.length + 3) + 2 * (2 * lists.length + 4))));
2077
- const out = { ran: true, tried: [], findings: [], left: [] };
2152
+ const out = { ran: true, tried: setAside.slice(), findings: [], left: [] };
2078
2153
  const headFor = (c) => c.a.method + ' ' + c.a.template;
2079
2154
  const finish = (c, what, s, atText, answers, effects, mode, body) => {
2080
2155
  const sure = effects.some((e) => e.sure);
@@ -330,6 +330,43 @@ function holdersOf(records, marker) {
330
330
  * proves nothing. A marker held anywhere else in the answer, or by a record
331
331
  * carrying the other organization's id, still counts.
332
332
  */
333
+ /**
334
+ * The markers that are a default both organizations are given at an address
335
+ * that names no record (round 33: GET /settings gave each organization its own
336
+ * name and the same time zone; the time zone, found in the caller's answer, was
337
+ * called the other organization's record). A marker counts as such only when
338
+ * the two answers differ somewhere (the app does tell the organizations apart
339
+ * here), and every place the caller's answer holds it is the same place in the
340
+ * other organization's answer, outside any record with an id of its own. The
341
+ * same answer for both, a record, or a value held anywhere else still counts.
342
+ */
343
+ function sameDefaults(answerJson, theirsJson, markers) {
344
+ if (!answerJson || typeof answerJson !== 'object' || !theirsJson || typeof theirsJson !== 'object') return [];
345
+ if (JSON.stringify(answerJson) === JSON.stringify(theirsJson)) return [];
346
+ // every string leaf: its path, and whether an enclosing object is a record with an id of its own
347
+ const leaves = (root) => {
348
+ const out = [];
349
+ (function walk(v, at, inRecord, depth) {
350
+ if (depth > 8 || v == null) return;
351
+ if (typeof v === 'string') { out.push({ at: at.join('\u0001'), value: v, inRecord: inRecord }); return; }
352
+ if (typeof v !== 'object') return;
353
+ const record = !Array.isArray(v) && Object.keys(v).some((k) => OWN_ID_KEY.test(k) && ['string', 'number'].includes(typeof v[k]));
354
+ for (const k of Object.keys(v)) walk(v[k], at.concat(k), inRecord || record, depth + 1);
355
+ })(root, [], false, 0);
356
+ return out;
357
+ };
358
+ const ours = leaves(answerJson);
359
+ const theirs = new Map(leaves(theirsJson).map((l) => [l.at, l.value]));
360
+ const out = [];
361
+ for (const m of markers) {
362
+ const held = ours.filter((l) => l.value.includes(m));
363
+ if (!held.length) continue;
364
+ if (!held.every((l) => l.value === m && !l.inRecord && theirs.get(l.at) === m)) continue;
365
+ out.push(m);
366
+ }
367
+ return out;
368
+ }
369
+
333
370
  function sharedOnly(answerJson, theirsJson, markers) {
334
371
  if (answerJson === undefined || answerJson === null || typeof answerJson !== 'object') return [];
335
372
  const answer = idRecordsOf(answerJson);
@@ -893,6 +930,7 @@ module.exports = {
893
930
  discover: discover,
894
931
  replyOf: replyOf,
895
932
  sharedOnly: sharedOnly,
933
+ sameDefaults: sameDefaults,
896
934
  judgeRead: judgeRead,
897
935
  judgeWrite: judgeWrite,
898
936
  runAuthz: runAuthz,
@@ -174,6 +174,13 @@
174
174
  dbInput.autocomplete = 'off';
175
175
  dbInput.spellcheck = false;
176
176
  dbInput.addEventListener('input', function () { if (pending) { pending = null; renderSteps(); } });
177
+ // The connect code from the account page: kept like the boxes above, and gone once it is sent.
178
+ var connectInput = el('input', 'field');
179
+ connectInput.type = 'password';
180
+ connectInput.placeholder = 'Paste your connect code (kd_...)';
181
+ connectInput.setAttribute('aria-label', 'Your connect code');
182
+ connectInput.autocomplete = 'off';
183
+ connectInput.spellcheck = false;
177
184
 
178
185
  /* ------------------------------------ jobs ------------------------------------ */
179
186
 
@@ -377,7 +384,8 @@
377
384
  byId('builtNote').textContent = (state.checks.length - built) + ' more are coming soon - never shown as passed.';
378
385
  var name = state.project.name || 'Project';
379
386
  var last = (state.looks || [])[0];
380
- byId('subline').textContent = name + ' - ' + (last ? 'watching, last look ' + ago(last.at) : 'watching for changes');
387
+ byId('subline').textContent = name + ' - ' + (last ? 'watching, last look ' + ago(last.at) : 'watching for changes') +
388
+ (state.update ? ' - A newer Kryptheon is out (' + state.update.current + ' -> ' + state.update.latest + '): close this and run ' + state.update.command : '');
381
389
  }
382
390
 
383
391
  /* ------------------------------ right now + steps ------------------------------ */
@@ -773,8 +781,11 @@
773
781
  if (f.fixPrompt) {
774
782
  box.appendChild(el('div', 'd-step', 'STEP 1 - PASTE THIS INTO YOUR AI TOOL'));
775
783
  box.appendChild(el('pre', null, f.fixPrompt));
784
+ } else if (f.promptLock) {
785
+ box.appendChild(el('div', 'd-step', 'STEP 1 - THE FIX PROMPT FOR YOUR AI TOOL'));
786
+ box.appendChild(lockedPrompt(f, false));
776
787
  }
777
- box.appendChild(el('div', 'd-step', f.fixPrompt ? 'STEP 2 - AFTER IT CHANGES THE CODE, RE-CHECK' : 'RE-CHECK'));
788
+ box.appendChild(el('div', 'd-step', f.fixPrompt || f.promptLock ? 'STEP 2 - AFTER IT CHANGES THE CODE, RE-CHECK' : 'RE-CHECK'));
778
789
  var actions = el('div', 'd-actions');
779
790
  if (f.fixPrompt) {
780
791
  actions.appendChild(button('', 'copy', 'Copy fix prompt', function (e) {
@@ -840,6 +851,13 @@
840
851
  whole.appendChild(el('pre', null, state.allFixPrompt));
841
852
  all.appendChild(whole);
842
853
  body.appendChild(all);
854
+ } else if (state.allFixPromptLocked) {
855
+ var allLocked = el('div', 'fix-all');
856
+ var lockedWords = el('div', 'fix-all-words');
857
+ lockedWords.appendChild(el('b', null, 'Fix all at once'));
858
+ lockedWords.appendChild(el('span', null, 'One prompt with every fix is part of Pro. Each finding still shows what is wrong and its proof.'));
859
+ allLocked.appendChild(lockedWords);
860
+ body.appendChild(allLocked);
843
861
  }
844
862
  if (!shown.length) {
845
863
  body.appendChild(el('p', 'empty', state.findings.length ? 'Nothing matches.' : 'Nothing found by the checks that are on and have run. That is not the same as nothing wrong - see which checks are not built yet.'));
@@ -888,6 +906,7 @@
888
906
  // The two things to do with a finding, without opening it first.
889
907
  var quick = el('div', 'f-quick');
890
908
  if (f.fixPrompt) quick.appendChild(button('sm', 'copy', 'Copy fix prompt', function () { copy(f.fixPrompt, 'Fix prompt copied - paste it into your AI tool'); }));
909
+ else if (f.promptLock) quick.appendChild(lockedPrompt(f, true));
891
910
  var qre = button('sm', 'refresh', 'Re-check', function () { recheck(f); });
892
911
  qre.setAttribute('data-action', 'recheck');
893
912
  qre.disabled = busy;
@@ -1470,12 +1489,102 @@
1470
1489
  }
1471
1490
  }
1472
1491
 
1492
+ /* ---------------------------------- account ---------------------------------- */
1493
+
1494
+ // Your account: the kryptheon.tech plan this dashboard is connected to, by the connect code from the account page.
1495
+ // The code itself never comes back to this page - only the plan and the fix prompts left.
1496
+ var PLAN_WORD = { starter: 'Starter', pro: 'Pro', studio: 'Studio' };
1497
+ function renderAccount() {
1498
+ var box = byId('accountBox');
1499
+ if (!box) return;
1500
+ var a = state.account || { connected: false };
1501
+ clear(box);
1502
+ if (a.connected) {
1503
+ var line = el('p', 'app-here');
1504
+ line.appendChild(el('b', null, 'Connected - ' + (a.app || 'your app')));
1505
+ box.appendChild(line);
1506
+ var left = a.prompts && typeof a.prompts.left === 'number'
1507
+ ? PLAN_WORD[a.plan] + ' - ' + a.prompts.left + ' of ' + a.prompts.limit + ' free fix prompts left this month'
1508
+ : (PLAN_WORD[a.plan] || a.plan) + ' - every fix prompt';
1509
+ box.appendChild(el('div', 'fallback', left));
1510
+ var row = el('div', 'field-row');
1511
+ row.appendChild(button('sm', 'refresh', 'Check my plan again', function () {
1512
+ post('/api/account/refresh', {}).then(function () { toast('Checked.'); load(); }, function (err) { toast(err.message); });
1513
+ }));
1514
+ row.appendChild(button('sm', '', 'Disconnect', function () {
1515
+ post('/api/account/disconnect', {}).then(function () { toast('Disconnected from this computer.'); load(); }, function (err) { toast(err.message); });
1516
+ }));
1517
+ box.appendChild(row);
1518
+ return;
1519
+ }
1520
+ if (a.problem) box.appendChild(el('div', 'fallback', a.problem.charAt(0).toUpperCase() + a.problem.slice(1) + '.'));
1521
+ box.appendChild(el('label', 'app-label', 'Connect your free Kryptheon account to get 5 free fix prompts a month'));
1522
+ var row2 = el('div', 'field-row');
1523
+ row2.appendChild(connectInput);
1524
+ row2.appendChild(button('sun sm', 'check', 'Connect', function () {
1525
+ var code = connectInput.value.trim();
1526
+ if (!code) { toast('Paste your connect code first.'); return; }
1527
+ post('/api/account/connect', { code: code }).then(function () {
1528
+ connectInput.value = '';
1529
+ toast('Connected.');
1530
+ load();
1531
+ }, function (err) { toast(err.message); });
1532
+ }));
1533
+ box.appendChild(row2);
1534
+ var help = el('div', 'fallback');
1535
+ help.appendChild(document.createTextNode('Already have a Kryptheon account? Get your connect code from your account page - your apps and plan carry over: '));
1536
+ help.appendChild(el('span', 'app-path', a.accountPage || 'kryptheon.tech/dashboard'));
1537
+ box.appendChild(help);
1538
+ }
1539
+
1540
+ // A finding's fix prompt that the plan does not open yet: its first line, and what opens the rest.
1541
+ function lockedPrompt(f, small) {
1542
+ var lock = f.promptLock;
1543
+ var a = state.account || {};
1544
+ var wrap = el('div', small ? 'f-locked sm' : 'f-locked');
1545
+ if (!small) {
1546
+ wrap.appendChild(el('pre', 'locked-preview', lock.preview));
1547
+ // Not the prompt: it never reached this page. A blurred stand-in, so it reads as "there is more".
1548
+ var blur = el('div', 'locked-blur', 'In the same change, also check every other place that does this, keep the rest as it is, and tell me what you changed.');
1549
+ blur.setAttribute('aria-hidden', 'true');
1550
+ wrap.appendChild(blur);
1551
+ }
1552
+ if (lock.reason === 'connect') {
1553
+ if (!small) wrap.appendChild(el('div', 'd-text', 'Connect your free account to get 5 free fix prompts a month.'));
1554
+ wrap.appendChild(button('sm', 'arrow', small ? 'Fix prompt: connect your free account' : 'Connect my account', function (e) {
1555
+ if (e) e.stopPropagation();
1556
+ if (window.location.hash !== '#dashboard') window.location.hash = 'dashboard';
1557
+ setTimeout(function () {
1558
+ var card = byId('accountCard');
1559
+ if (card) card.scrollIntoView({ behavior: 'smooth', block: 'center' });
1560
+ connectInput.focus();
1561
+ }, 50);
1562
+ }));
1563
+ } else if (lock.reason === 'free-left') {
1564
+ // Quiet in the list (one per finding); the bright one only inside an opened finding.
1565
+ var open = button(small ? 'sm' : 'sun sm', 'copy', 'Show fix prompt (uses 1 of your ' + lock.left + ' free this month)', function (e) {
1566
+ if (e) e.stopPropagation();
1567
+ open.disabled = true;
1568
+ post('/api/prompt/unlock', { id: f.id }).then(function () { load(); }, function (err) { toast(err.message); load(); });
1569
+ });
1570
+ wrap.appendChild(open);
1571
+ } else {
1572
+ if (!small) wrap.appendChild(el('div', 'd-text', 'This month\'s 5 free fix prompts are used.'));
1573
+ wrap.appendChild(button('sm', 'arrow', 'Unlock with Pro - ₹499/month', function (e) {
1574
+ if (e) e.stopPropagation();
1575
+ copy(a.pricing || 'https://kryptheon.tech/pricing/', 'Pricing page address copied - open it in your browser');
1576
+ }));
1577
+ }
1578
+ return wrap;
1579
+ }
1580
+
1473
1581
  function render(next) {
1474
1582
  if (!next) return;
1475
1583
  state = next;
1476
1584
  renderSide();
1477
1585
  renderTop();
1478
1586
  renderApp();
1587
+ renderAccount();
1479
1588
  renderNow();
1480
1589
  renderSteps();
1481
1590
  renderKeep();
@@ -1520,7 +1629,7 @@
1520
1629
  // Not while something runs, not while a finding is open being read, not
1521
1630
  // while a yes is being asked for, and not while someone is typing.
1522
1631
  setInterval(function () {
1523
- var typing = document.activeElement === dbInput || document.activeElement === recordInput;
1632
+ var typing = document.activeElement === dbInput || document.activeElement === recordInput || document.activeElement === connectInput;
1524
1633
  if (!busy && !openRow && !pending && !probeAsking && !paymentsAsking && !typing) load();
1525
1634
  }, 5000);
1526
1635
  })();
@@ -360,6 +360,10 @@
360
360
  .fix-all-text summary { width: max-content; font: 11px var(--mono); letter-spacing: 0.12em; text-transform: uppercase; cursor: pointer; opacity: 0.75; }
361
361
  .fix-all-text pre { max-height: 320px; margin: 10px 0 0; padding: 14px 16px; overflow: auto; font: 12px/1.6 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; border: 1px solid var(--line); }
362
362
  .rechecked { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; padding: 14px 8px 14px 20px; font-size: 14px; border-bottom: 1px solid var(--line); box-shadow: inset 3px 0 0 var(--on-light); }
363
+ .f-locked { display: grid; gap: 10px; justify-items: start; }
364
+ .f-locked.sm { display: contents; }
365
+ .locked-preview { margin: 0; padding: 12px 14px 0; font: 12px/1.6 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
366
+ .locked-blur { margin-top: -6px; padding: 0 14px 6px; font: 12px/1.6 var(--mono); filter: blur(4px); opacity: 0.55; user-select: none; pointer-events: none; }
363
367
 
364
368
  .toast { position: fixed; left: 50%; bottom: calc(24px + var(--job-room, 0px)); z-index: 10; max-width: calc(100vw - 32px); padding: 14px 20px; font-size: 14px; color: var(--on-dark); background: var(--ink); border-left: 2px solid var(--orange); opacity: 0; transform: translate(-50%, 20px); transition: opacity 0.35s var(--ease), transform 0.35s var(--ease); pointer-events: none; }
365
369
  .toast.show { opacity: 1; transform: translate(-50%, 0); }
@@ -405,6 +409,10 @@
405
409
  <div class="card-head"><div><h3>Your app</h3><div class="c-sub">What this dashboard checks</div></div></div>
406
410
  <div id="appBox"></div>
407
411
  </div>
412
+ <div class="card app-card gap" id="accountCard">
413
+ <div class="card-head"><div><h3>Your account</h3><div class="c-sub">Your kryptheon.tech plan, and your fix prompts</div></div></div>
414
+ <div id="accountBox"></div>
415
+ </div>
408
416
  <div class="sky" id="sky">
409
417
  <div class="s-chip" id="skyIcon"></div>
410
418
  <div class="s-text">
@@ -23,11 +23,13 @@ const http = require('http');
23
23
  const crypto = require('crypto');
24
24
  const { spawnSync } = require('child_process');
25
25
  const store = require('./kryptheon-store.js');
26
+ const account = require('./kryptheon-account.js');
26
27
  const changes = require('./kryptheon-changes.js');
27
28
  const autostart = require('./kryptheon-autostart.js');
28
29
  const selectors = require('./kryptheon-selectors.js');
29
30
  const replay = require('./kryptheon-replay.js');
30
31
  const VERSION = require('./package.json').version;
32
+ const newer = require('./kryptheon-newer.js');
31
33
 
32
34
  /**
33
35
  * Every check the dashboard knows the name of, in the order the person asked
@@ -1002,6 +1004,15 @@ function buildState(root, env) {
1002
1004
  // Which kryptheon this dashboard is: a newer `dashboard` asks, and takes
1003
1005
  // the place of an older one still running, instead of opening it.
1004
1006
  kryptheon: VERSION,
1007
+ // Its process, so that newer one can close exactly it. Found when
1008
+ // netstat on Windows left the dashboard's port out of its list, and an
1009
+ // old dashboard kept the port.
1010
+ pid: process.pid,
1011
+ // a newer kryptheon on npm (from the day's answer, asked when the dashboard started), or null
1012
+ update: (() => {
1013
+ const latest = newer.cachedLatest('kryptheon');
1014
+ return latest && newer.compare(latest, VERSION) > 0 ? { current: VERSION, latest: latest, command: 'npx kryptheon@latest dashboard' } : null;
1015
+ })(),
1005
1016
  looks: looks,
1006
1017
  proven: proven,
1007
1018
  checks: checks,
@@ -1055,11 +1066,11 @@ function apiVerdictLine(apiLast, item) {
1055
1066
  return v ? '\nOn the running app (' + String(apiLast.checkedAt || '').slice(0, 10) + '): ' + v.verdict + (v.why ? ' - ' + v.why : '') + '.' : '';
1056
1067
  }
1057
1068
  const DB_ACTIONS = {
1058
- scan: { title: 'Checking your database', command: 'npx kryptheon-night' },
1059
- install: { title: 'Setting up the nightly check', command: 'npx kryptheon-night install' },
1060
- night: { title: 'Reading last night\'s result', command: 'npx kryptheon-night night' },
1061
- uninstall: { title: 'Removing the nightly check', command: 'npx kryptheon-night uninstall' },
1062
- recheck: { title: 'Re-checking in your database', command: 'npx kryptheon-night' },
1069
+ scan: { title: 'Checking your database', command: 'npx kryptheon-night@latest' },
1070
+ install: { title: 'Setting up the nightly check', command: 'npx kryptheon-night@latest install' },
1071
+ night: { title: 'Reading last night\'s result', command: 'npx kryptheon-night@latest night' },
1072
+ uninstall: { title: 'Removing the nightly check', command: 'npx kryptheon-night@latest uninstall' },
1073
+ recheck: { title: 'Re-checking in your database', command: 'npx kryptheon-night@latest' },
1063
1074
  };
1064
1075
 
1065
1076
  /**
@@ -1275,6 +1286,8 @@ function createJobs() {
1275
1286
  * page this server hands out, which another site cannot read.
1276
1287
  */
1277
1288
  function createServer(root, options) {
1289
+ // ask npm once for a newer kryptheon; the page reads the day's answer from then on (never waits for it)
1290
+ if (!(options && options.fetch)) newer.latestOf('kryptheon');
1278
1291
  const opts = options || {};
1279
1292
  const env = opts.env || process.env;
1280
1293
  const token = crypto.randomBytes(24).toString('hex');
@@ -1324,7 +1337,8 @@ function createServer(root, options) {
1324
1337
  return send(res, 200, type, body);
1325
1338
  }
1326
1339
  if (req.method === 'GET' && url.pathname === '/api/state') {
1327
- return json(res, 200, buildState(root, env));
1340
+ // What the page is sent, for this computer's account: fix prompts past what the plan opens never leave here.
1341
+ return json(res, 200, account.lock(buildState(root, env), root, env));
1328
1342
  }
1329
1343
  if (req.method === 'GET' && url.pathname === '/api/job') {
1330
1344
  return json(res, 200, { job: jobs.get() });
@@ -1347,6 +1361,17 @@ function createServer(root, options) {
1347
1361
  const r = setCheck(store.pathsFor(root, env), String(input.id || ''), input.on);
1348
1362
  return json(res, r.ok ? 200 : 400, r);
1349
1363
  }
1364
+ // The account: a connect code from kryptheon.tech, and Starter's fix prompts opened one at a time.
1365
+ const answer = (p) => p.then((r) => json(res, r.ok ? 200 : (r.status === 402 ? 402 : 400), r))
1366
+ .catch(() => json(res, 500, { ok: false, why: 'something went wrong' }));
1367
+ if (url.pathname === '/api/account/connect') return answer(account.connect(root, env, input.code));
1368
+ if (url.pathname === '/api/account/refresh') return answer(account.refresh(root, env));
1369
+ if (url.pathname === '/api/account/disconnect') return json(res, 200, account.disconnect(root, env));
1370
+ if (url.pathname === '/api/prompt/unlock') {
1371
+ const id = String(input.id || '');
1372
+ if (!buildState(root, env).findings.some((f) => f.id === id && f.fixPrompt)) return json(res, 404, { ok: false, why: 'no finding with that id has a fix prompt' });
1373
+ return answer(account.unlock(root, env, id));
1374
+ }
1350
1375
  if (url.pathname === '/api/autostart') {
1351
1376
  const r = autostart.setAutostart(root, input.on, env);
1352
1377
  return json(res, r.ok ? 200 : 400, { ok: r.ok, on: !!r.on, why: r.why || '' });
package/kryptheon-map.js CHANGED
@@ -345,7 +345,18 @@ function resolveRef(ctx, mod, p, depth = 0, seen = new Set()) {
345
345
  }
346
346
 
347
347
  /** What a binding names, as a path resolveRef can follow: a declaration's value, an import's local name, a function. */
348
- const bindingTarget = (b) => (b.path.isVariableDeclarator() ? b.path.get('init') : b.path.isImportSpecifier() || b.path.isImportDefaultSpecifier() || b.path.isImportNamespaceSpecifier() ? b.path.get('local') : b.path);
348
+ const bindingTarget = (b) => {
349
+ if (b.path.isVariableDeclarator()) {
350
+ // const { sameHex } = require('./sig'): the name inside the pattern, which resolveRef follows into that file - not the
351
+ // whole module (round 33: an app's own compare helper was not followed, and a real signature check read as none)
352
+ if (b.path.node.id && b.path.node.id.type === 'ObjectPattern') {
353
+ const hit = b.path.get('id.properties').find((q) => q.isObjectProperty() && q.get('value').isIdentifier({ name: b.identifier.name }));
354
+ if (hit) return hit.get('value');
355
+ }
356
+ return b.path.get('init');
357
+ }
358
+ return b.path.isImportSpecifier() || b.path.isImportDefaultSpecifier() || b.path.isImportNamespaceSpecifier() ? b.path.get('local') : b.path;
359
+ };
349
360
 
350
361
  const calleeText = (p) => (memberChain(p.node.callee) || ['(call)']).join('.');
351
362
 
@@ -2310,6 +2321,10 @@ function readValidation(ctx, fnRef, elements, db) {
2310
2321
  const fs2 = fieldsIn(init);
2311
2322
  if (fs2.length === 1 && reshapes(init)) {
2312
2323
  localField.set(id.name, fs2[0]);
2324
+ // const delta = Number(req.body.delta): the code reads a number (round 33: sent as text, the route crashed and
2325
+ // nothing about the stock was ever tried)
2326
+ const conv = init.type === 'CallExpression' ? init : init.type === 'UnaryExpression' && init.operator === '+' ? { unary: true } : null;
2327
+ if (conv && (conv.unary || /^(Number|parseInt|parseFloat)$/.test((memberChain(conv.callee) || ['']).slice(-1)[0]))) note(fs2[0], q.node.loc.start.line).numeric = true;
2313
2328
  // Math.min(100, Math.max(1, Number(req.query.limit))): kept in bounds rather than turned away
2314
2329
  if (clamps(init)) note(fs2[0], q.node.loc.start.line).checks.push({ kind: 'clamped', file: mod.rel, line: q.node.loc.start.line, code: snippet(mod, q.node.loc.start.line) });
2315
2330
  }
@@ -2488,7 +2503,7 @@ function readValidation(ctx, fnRef, elements, db) {
2488
2503
  let status = e.checks.length ? STATUS.DETECTED : (e.schemaUnread || unread ? STATUS.UNKNOWN : STATUS.NOT);
2489
2504
  const items = itemNames.get(key(e.from, e.name));
2490
2505
  return Object.assign({ name: e.name, from: e.from, line: e.line, file: mod.rel, status, checks: e.checks, reachesWrite: e.reachesWrite || [], why: status === STATUS.UNKNOWN ? 'checked by a schema or middleware whose rules are not read' : null },
2491
- items && items.size ? { items: Array.from(items).sort() } : {});
2506
+ items && items.size ? { items: Array.from(items).sort() } : {}, e.numeric ? { numeric: true } : {});
2492
2507
  });
2493
2508
  return { fields: out.sort((a, b) => a.line - b.line), schemas };
2494
2509
  }
@@ -0,0 +1,87 @@
1
+ // Is a newer version of this package on npm?
2
+ //
3
+ // Someone who ran `npx kryptheon` once can keep getting that same copy
4
+ // from npx's cache, and a nightly check installed in a database never updates
5
+ // itself - so without this, a fix released later never reaches them.
6
+ //
7
+ // One request, to the npm registry npx itself talks to, at most once a day (the
8
+ // answer is kept in ~/.kryptheon). It gives up after 1.5 seconds and never fails
9
+ // a run. KRYPTHEON_NO_UPDATE_CHECK=1, or CI, turns it off.
10
+
11
+ const https = require('https');
12
+ const fs = require('fs');
13
+ const os = require('os');
14
+ const path = require('path');
15
+
16
+ const DAY = 24 * 60 * 60 * 1000;
17
+
18
+ /** -1, 0 or 1, for versions written 1.2.3. */
19
+ function compare(a, b) {
20
+ const x = String(a || '').split('.').map((n) => parseInt(n, 10) || 0);
21
+ const y = String(b || '').split('.').map((n) => parseInt(n, 10) || 0);
22
+ for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) < (y[i] || 0) ? -1 : 1;
23
+ return 0;
24
+ }
25
+
26
+ function cacheFile(name) {
27
+ return path.join(process.env.KRYPTHEON_HOME || path.join(os.homedir(), '.kryptheon'), 'newer-' + name + '.json');
28
+ }
29
+
30
+ /** The cached latest version, or null - never a request. */
31
+ function cachedLatest(name) {
32
+ try {
33
+ const c = JSON.parse(fs.readFileSync(cacheFile(name), 'utf8'));
34
+ return typeof c.latest === 'string' ? c.latest : null;
35
+ } catch (err) {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ /** The latest version on npm (from the day's cache, or one request), or null. Never throws. */
41
+ function latestOf(name, options) {
42
+ const opts = options || {};
43
+ if (process.env.KRYPTHEON_NO_UPDATE_CHECK || process.env.CI) return Promise.resolve(null);
44
+ try {
45
+ const c = JSON.parse(fs.readFileSync(cacheFile(name), 'utf8'));
46
+ if (c && typeof c.latest === 'string' && Date.now() - c.at < DAY) return Promise.resolve(c.latest);
47
+ } catch (err) {
48
+ /* no cache yet */
49
+ }
50
+ return new Promise((resolve) => {
51
+ let done = false;
52
+ const finish = (v) => { if (!done) { done = true; resolve(v); } };
53
+ try {
54
+ const req = https.get('https://registry.npmjs.org/' + encodeURIComponent(name) + '/latest',
55
+ { timeout: opts.timeoutMs || 1500, headers: { accept: 'application/json' } }, (res) => {
56
+ let text = '';
57
+ res.on('data', (d) => { text += d; if (text.length > 200000) req.destroy(); });
58
+ res.on('end', () => {
59
+ try {
60
+ const v = JSON.parse(text).version;
61
+ if (typeof v !== 'string') return finish(null);
62
+ try {
63
+ fs.mkdirSync(path.dirname(cacheFile(name)), { recursive: true });
64
+ fs.writeFileSync(cacheFile(name), JSON.stringify({ at: Date.now(), latest: v }));
65
+ } catch (err) { /* a cache that cannot be written only means asking again tomorrow */ }
66
+ finish(v);
67
+ } catch (err) {
68
+ finish(null);
69
+ }
70
+ });
71
+ });
72
+ req.on('timeout', () => { req.destroy(); finish(null); });
73
+ req.on('error', () => finish(null));
74
+ if (req.unref) req.unref();
75
+ } catch (err) {
76
+ finish(null);
77
+ }
78
+ });
79
+ }
80
+
81
+ /** The line to show when a newer version is out, or null. */
82
+ function notice(name, current, latest, command) {
83
+ if (!latest || compare(latest, current) <= 0) return null;
84
+ return 'A newer ' + name + ' is out (' + current + ' -> ' + latest + '). Run: ' + command;
85
+ }
86
+
87
+ module.exports = { compare, latestOf, cachedLatest, notice, cacheFile };
@@ -312,8 +312,12 @@ function permissionFor(method, pathOrTemplate, policy) {
312
312
  if (isGet !== readish) continue;
313
313
  let score = hits;
314
314
  let lastHit = resource.some((r) => last.has(r));
315
+ const firstWords = (statics.map((s) => wordsOf(s).filter((w) => !SKIP_WORDS.has(w) && !/^v\d+$/.test(w))).find((ws) => ws.length)) || [];
316
+ const firstHit = resource.some((r) => firstWords.includes(r));
317
+ let actionInPath = false;
315
318
  for (const a of actions) {
316
319
  if (pathWords.has(a)) {
320
+ actionInPath = true;
317
321
  score += 2;
318
322
  if (last.has(a)) lastHit = true;
319
323
  } else if (a === 'export' && extension) {
@@ -331,13 +335,22 @@ function permissionFor(method, pathOrTemplate, policy) {
331
335
  lastHit = true;
332
336
  }
333
337
  }
334
- found.push({ permission: perm, score: score, lastHit: lastHit });
338
+ found.push({ permission: perm, score: score, lastHit: lastHit, firstHit: firstHit, actionInPath: actionInPath });
335
339
  }
336
340
  const strict = (() => {
337
341
  if (!found.length) return null;
338
342
  const lastWordsAny = statics.length > 0 && parsed.params.length > 0 && statics[statics.length - 1] !== undefined && parsed.segs[parsed.segs.length - 1] !== '{id}';
339
343
  found.sort((a, b) => (b.lastHit ? 1 : 0) - (a.lastHit ? 1 : 0) || b.score - a.score);
340
344
  const best = found[0];
345
+ // A named action at the end of an address with no record in it (POST /jobs/reconcile-client): a permission found
346
+ // only by a noun inside that name (clients.write - "write" is nowhere in the address) is what the action works on,
347
+ // not what it is; the permission of the address's first word (jobs.run) is. Round 33: finance, which may run jobs,
348
+ // was called a role failure for running one.
349
+ const lastSeg = statics.length > 1 ? wordsOf(statics[statics.length - 1].replace(FILE_EXTENSIONS, '')) : [];
350
+ if (!parsed.params.length && lastSeg.length > 1 && best.lastHit && !best.actionInPath && !best.firstHit) {
351
+ const own = found.filter((f) => f.firstHit && f.permission !== best.permission);
352
+ if (own.length === 1) return { permission: own[0].permission, how: 'by the first word of the address (its end names what it works on)' };
353
+ }
341
354
  // "/shipments/5/notes": the end of the address names something none of the
342
355
  // permissions does, so the permission of "shipments" would be a guess.
343
356
  if (!best.lastHit && lastWordsAny) return { ambiguous: true, why: 'the end of the address (' + statics[statics.length - 1] + ') matches no permission name' };
@@ -1242,7 +1255,11 @@ async function tryOnce(x) {
1242
1255
  // rows alike). A role's try is another matter: its own organization's records are what it may not see.
1243
1256
  // A value that came back only inside records with ids of their own, none of them the other organization's, is a
1244
1257
  // name both organizations' records happen to share, not their record (round 30: an integration of the same name).
1245
- const shared = p.kind === 'tenant' && isGet && markers.length ? authz.sharedOnly(res.json, theirs, markers) : [];
1258
+ // At an address that names no record, a default both organizations are given at the same place (a time zone in the
1259
+ // settings) is not theirs either (round 33).
1260
+ const shared = p.kind === 'tenant' && isGet && markers.length
1261
+ ? authz.sharedOnly(res.json, theirs, markers).concat(!a.params.length ? authz.sameDefaults(res.json, theirs, markers) : [])
1262
+ : [];
1246
1263
  let found = markers.length ? authz.foundIn(p.kind === 'tenant' && isGet && actor.org ? withoutOwn(res, actor.org.key) : res, markers.filter((m) => !shared.includes(m))).length : 0;
1247
1264
  // their record's own words now in our lists: a record of ours points at theirs (round 25: a transfer whose
1248
1265
  // destination was another organization's location, shown by name in our list of transfers)
@@ -1266,8 +1283,14 @@ async function tryOnce(x) {
1266
1283
  // Harness, round 27: a finance account's create was refused 403 while two rows appeared in /api/overview.
1267
1284
  const ownList = '/' + a.segs.slice(0, a.params.length ? a.params[0].index : a.segs.length).join('/');
1268
1285
  const refusedOutright = res.status === 401 || res.status === 403;
1286
+ // Likewise a row gone from another list (an overview of the 6 soonest work orders, while another check moves them):
1287
+ // not this refused request's effect, unless the request named that row (a refused delete that deleted it anyway).
1288
+ // Harness, round 27: a viewer's POST /api/maintenance/run was refused 403 while rows 6, 9, 11 left /api/overview.
1289
+ const namedIds = new Set(String(pathNow).split('?')[0].split('/').filter(Boolean)
1290
+ .concat(Object.values(body || {}).filter((v) => ['string', 'number'].includes(typeof v)).map(String)));
1291
+ const goneElsewhere = (l) => { const m = / record (.+) is gone$/.exec(String(l)); return !!m && !namedIds.has(m[1]); };
1269
1292
  const changes = x.compare(before, after).filter((l) => !ownIds.some((v) => l.includes(': record ' + v + ' changed - ')))
1270
- .filter((l) => !(refusedOutright && / a new record appeared /.test(' ' + l + ' ') && String(l).split(':')[0] !== ownList));
1293
+ .filter((l) => !(refusedOutright && String(l).split(':')[0] !== ownList && (/ a new record appeared /.test(' ' + l + ' ') || goneElsewhere(l))));
1271
1294
  const changed = Object.keys(before).length ? changes.length > 0 : null;
1272
1295
 
1273
1296
  const att = Object.assign(base, {
@@ -699,9 +699,12 @@ async function run(root, options) {
699
699
  if (shape.amount) b[shape.amount] = amount !== undefined ? amount : amountKey ? Number(rec[amountKey]) : 1;
700
700
  return b;
701
701
  };
702
+ // who sends: nobody signed in, as a provider does - or, for a route the app keeps behind its own sign-in (blind
703
+ // round 33: every address under /api needed a session, the webhooks too), the signed-in account
704
+ let via = null;
702
705
  const post = async (mode, body) => {
703
706
  const text = JSON.stringify(body);
704
- const session = authz.makeSession(ctx, null, '(nobody signed in)', null);
707
+ const session = via || authz.makeSession(ctx, null, '(nobody signed in)', null);
705
708
  const headers = {};
706
709
  if (mode === 'signed') headers[signing.header] = sign(signing, secret, text);
707
710
  if (mode === 'wrong') headers[signing.header] = wrongSignature(signing, secret, text);
@@ -741,29 +744,52 @@ async function run(root, options) {
741
744
  say('Sending ' + (open ? 'an unsigned' : 'a correctly signed') + ' ' + ctypes[0] + ' to ' + name + ' first...');
742
745
  const first = nextRecord(unpaidFor(ctypes[0])) || nextRecord();
743
746
  if (!first) { hook.notTried = 'no record left to aim an event at'; continue; }
744
- let control = await attempt(S, ctypes[0], first, undefined, open ? 'unsigned' : 'signed');
745
- // a refusal can be the record's state, not the signature (round 26: "captured" sent to a failed payment is 409):
746
- // the same type at the other records, then the next type, three sends at most - a refusal changes nothing
747
- const refusals = [control];
748
- // a plain control refused (round 26 refuses payment.created for the record's state): the usual order then, with the
749
- // usual three sends besides it
750
- const order = plain && !control.took ? types : ctypes;
751
- const budget = plain && !control.took ? 4 : 3;
752
- for (const type of order) {
753
- for (const rec of records) {
754
- if (control.took || refusals.length >= budget) break;
755
- if (refusals.some((t) => t.type === type && t.record === rec.id) || (statusKey && REFUNDED.test(String(rec[statusKey])))) continue;
756
- control = await attempt(S, type, rec, undefined, open ? 'unsigned' : 'signed');
757
- refusals.push(control);
747
+ const controlPhase = async () => {
748
+ let control = await attempt(S, ctypes[0], first, undefined, open ? 'unsigned' : 'signed');
749
+ // a refusal can be the record's state, not the signature (round 26: "captured" sent to a failed payment is 409):
750
+ // the same type at the other records, then the next type, three sends at most - a refusal changes nothing
751
+ const refusals = [control];
752
+ // a plain control refused (round 26 refuses payment.created for the record's state): the usual order then, with the
753
+ // usual three sends besides it
754
+ const order = plain && !control.took ? types : ctypes;
755
+ const budget = plain && !control.took ? 4 : 3;
756
+ for (const type of order) {
757
+ for (const rec of records) {
758
+ if (control.took || refusals.length >= budget) break;
759
+ if (refusals.some((t) => t.type === type && t.record === rec.id) || (statusKey && REFUNDED.test(String(rec[statusKey])))) continue;
760
+ control = await attempt(S, type, rec, undefined, open ? 'unsigned' : 'signed');
761
+ refusals.push(control);
762
+ }
758
763
  }
759
- }
760
- // every real event refused, or none could be built (round 22: Razorpay's nested body): a signed event of a type
761
- // no handler acts on. Taken, it shows the signature is made right - and the same event unsigned or wrongly
762
- // signed then shows whether the app checks it before anything else (round 22 checked the length only)
763
- if (!control.took && !open && ctypes[0] !== NEUTRAL) {
764
- const neutral = await attempt('signed', NEUTRAL, first, undefined, 'signed');
765
- refusals.push(neutral);
766
- if (neutral.took) control = neutral;
764
+ // every real event refused, or none could be built (round 22: Razorpay's nested body): a signed event of a type
765
+ // no handler acts on. Taken, it shows the signature is made right - and the same event unsigned or wrongly
766
+ // signed then shows whether the app checks it before anything else (round 22 checked the length only)
767
+ if (!control.took && !open && ctypes[0] !== NEUTRAL) {
768
+ const neutral = await attempt('signed', NEUTRAL, first, undefined, 'signed');
769
+ refusals.push(neutral);
770
+ if (neutral.took) control = neutral;
771
+ }
772
+ return { control, refusals };
773
+ };
774
+ let { control, refusals } = await controlPhase();
775
+ // Every correctly signed event answered 401 with nobody signed in: the app keeps this route behind its own sign-in.
776
+ // A provider never signs in, so its events cannot arrive - said as a thing to check. The same tries are then made as
777
+ // the signed-in account, and everything found after that says so: any account of the app can send these events.
778
+ if (!control.took && !open && refusals.every((t) => t.status === 401)) {
779
+ const gated = refusals;
780
+ via = reader;
781
+ hook.signedIn = who.email;
782
+ say('Every correctly signed event to ' + name + ' was answered 401 with nobody signed in - sending them again as ' + who.email + '...');
783
+ ({ control, refusals } = await controlPhase());
784
+ hook.loginGate = { refusals: gated.map((t) => t.type + ': ' + t.status), tookSignedIn: control.took };
785
+ const headline = name + ' answers 401 to a correctly signed event when nobody is signed in' + (control.took ? ', and takes it from a signed-in account' : '') + ': a provider never signs in to your app, so its events cannot arrive.';
786
+ const gate = { kind: 'webhook-login-gate', where: name, from: route.file + ':' + route.line, status: 'verification required', severity: 'MEDIUM', headline,
787
+ proof: ['Correctly signed with ' + (signing.secret.env || 'the secret in the code') + ', nobody signed in: ' + gated.map((t) => t.type + (t.record !== null ? ' for ' + resource + ' ' + t.record : '') + ' answered ' + t.status).join('; '),
788
+ control.took ? 'The same event as ' + who.email + ': answered ' + control.status : 'As ' + who.email + ' too: ' + refusals.map((t) => t.status).join(', ')],
789
+ fixPrompt: ['Kryptheon sent my running app a correctly signed webhook event, and it was refused because nobody was signed in:', '', headline, '', 'Where: ' + route.file + ':' + route.line, '',
790
+ 'Mount the webhook route before the sign-in middleware (or exclude it from it), so that only the signature decides whether an event is taken - and keep the signature check strict: answer 401 when it is missing or wrong.', '', 'Afterwards I will run: npx kryptheon api'].join(String.fromCharCode(10)) };
791
+ hook.findings.push(gate);
792
+ out.findings.push(gate);
767
793
  }
768
794
  hook.control = control;
769
795
  hook.neutral = control.type === NEUTRAL && !open;
@@ -835,7 +861,10 @@ async function run(root, options) {
835
861
 
836
862
  // judged
837
863
  const at = hook.from;
838
- const finding = (kind, severity, status, headline, proof, fix) => {
864
+ const finding = (kind, severity, status, headline0, proof0, fix) => {
865
+ // sent while signed in: the app answers only signed-in people here, so it is any account of the app that can do it
866
+ const headline = via ? headline0.replace(/\.$/, '') + ' - sent while signed in as ' + who.email + ', since this route answers 401 to anyone not signed in: any account of your app can do it.' : headline0;
867
+ const proof = via ? ['Sent with ' + who.email + '\'s sign-in (with nobody signed in, every correctly signed event was answered 401).'].concat(proof0) : proof0;
839
868
  const f = { kind, where: name, from: at, status, severity, headline, proof, fixPrompt: ['Kryptheon sent my running app an event it signs itself, and it was taken when it should not have been:', '', headline, '', 'Where: ' + at, '', fix, '', 'Afterwards I will run: npx kryptheon api'].join(String.fromCharCode(10)) };
840
869
  hook.findings.push(f);
841
870
  out.findings.push(f);
@@ -858,7 +887,7 @@ async function run(root, options) {
858
887
  if (t.mode === 'none' && t.took) {
859
888
  finding('webhook-unsigned', t.changed ? 'CRITICAL' : 'HIGH', t.changed ? 'confirmed' : 'verification required',
860
889
  t.changed ? name + ' took ' + shown(t) + ' with no signature at all and changed ' + resource + ' ' + t.record + (t.from !== null && t.from !== t.to ? ' (' + statusKey + ' ' + t.from + ' -> ' + t.to + ')' : ' (' + t.fields.join(', ') + ')') + ': anyone who can reach it can send one.' : name + ' answered ' + t.status + ' to ' + shown(t) + ' with no signature, though no change was seen' + seen + '.',
861
- [(open ? 'With nobody signed in, and no signature - the handler reads none: ' : 'With nobody signed in and no ' + signing.header + ' header: ') + lineOf(t)],
890
+ [(open ? (via ? 'With' : 'With nobody signed in, and') + ' no signature - the handler reads none: ' : (via ? 'With' : 'With nobody signed in and') + ' no ' + signing.header + ' header: ') + lineOf(t)],
862
891
  open ? 'This webhook checks no signature at all. Have the sender sign each event (an HMAC of the exact raw body with a shared secret, in a header) and answer 401 before anything is saved when the signature is missing or wrong, using a timing-safe compare.' : 'Treat a request with no signature as invalid: answer 401 before anything is saved, the same as a wrong signature. The check that reads "if the header is there and it is wrong" lets every request without the header through.');
863
892
  } else if (t.mode === 'wrong' && t.took) {
864
893
  finding('webhook-forged', t.changed ? 'CRITICAL' : 'HIGH', t.changed ? 'confirmed' : 'verification required',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kryptheon",
3
- "version": "0.1.65",
3
+ "version": "0.1.67",
4
4
  "description": "Record what you do in your app and get plain-language reports when it breaks.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "commonjs",
@@ -38,6 +38,7 @@
38
38
  "kryptheon-dashboard.js",
39
39
  "kryptheon-dashboard.html",
40
40
  "kryptheon-dashboard-page.js",
41
+ "kryptheon-account.js",
41
42
  "kryptheon-logo.png",
42
43
  "kryptheon-fonts-OFL.txt",
43
44
  "kryptheon-spacemono.woff2",
@@ -58,7 +59,8 @@
58
59
  "kryptheon-map.js",
59
60
  "kryptheon-api.js",
60
61
  "kryptheon-webhook.js",
61
- "kryptheon-csv.js"
62
+ "kryptheon-csv.js",
63
+ "kryptheon-newer.js"
62
64
  ],
63
65
  "engines": {
64
66
  "node": ">=20.6.0"
@@ -68,7 +70,7 @@
68
70
  "pg": "^8.23.0"
69
71
  },
70
72
  "scripts": {
71
- "check": "node kryptheon-store.check.js && node kryptheon-code.check.js && node kryptheon-constdata.check.js && node kryptheon-listitems.check.js && node kryptheon-accept.check.js && node kryptheon-keys.check.js && node kryptheon-dashboard.check.js && node kryptheon-edge.check.js && node kryptheon-reliability.check.js && node kryptheon-fresh.check.js && node kryptheon-payments-dash.check.js && node kryptheon-embedded.check.js && node kryptheon-autostart.check.js && node kryptheon-changes.check.js && node kryptheon-look.check.js && node kryptheon-verify.check.js && node kryptheon-recheck.check.js && node kryptheon-reporter.check.js && node kryptheon-signature.check.js && node kryptheon-signature.stream.check.js && node kryptheon-signature.baseline.check.js && node kryptheon-signature.settle.check.js && node kryptheon-signature.number.check.js && node kryptheon-signature.rows.check.js && node kryptheon-env.check.js && node kryptheon-watchdog.check.js && node kryptheon-phone.check.js && node kryptheon-homedash.check.js && node kryptheon-record.check.js && node kryptheon-selectors.check.js && node kryptheon-recordings.check.js && node kryptheon-testfiles.check.js && node kryptheon-cleanup.check.js && node kryptheon-orphan.check.js && node kryptheon-project.check.js && node kryptheon-setup.check.js && node kryptheon-browser.check.js && node kryptheon-heal.check.js && node kryptheon-load.check.js && node kryptheon-authz.check.js && node kryptheon-roles.check.js && node kryptheon-map.check.js && node kryptheon-api.check.js && node kryptheon-webhook.check.js && node kryptheon-csv.check.js && node kryptheon-package.check.js",
73
+ "check": "node kryptheon-store.check.js && node kryptheon-code.check.js && node kryptheon-constdata.check.js && node kryptheon-listitems.check.js && node kryptheon-accept.check.js && node kryptheon-keys.check.js && node kryptheon-dashboard.check.js && node kryptheon-edge.check.js && node kryptheon-reliability.check.js && node kryptheon-fresh.check.js && node kryptheon-payments-dash.check.js && node kryptheon-embedded.check.js && node kryptheon-autostart.check.js && node kryptheon-changes.check.js && node kryptheon-look.check.js && node kryptheon-verify.check.js && node kryptheon-recheck.check.js && node kryptheon-reporter.check.js && node kryptheon-signature.check.js && node kryptheon-signature.stream.check.js && node kryptheon-signature.baseline.check.js && node kryptheon-signature.settle.check.js && node kryptheon-signature.number.check.js && node kryptheon-signature.rows.check.js && node kryptheon-env.check.js && node kryptheon-watchdog.check.js && node kryptheon-phone.check.js && node kryptheon-homedash.check.js && node kryptheon-record.check.js && node kryptheon-selectors.check.js && node kryptheon-recordings.check.js && node kryptheon-testfiles.check.js && node kryptheon-cleanup.check.js && node kryptheon-orphan.check.js && node kryptheon-project.check.js && node kryptheon-setup.check.js && node kryptheon-browser.check.js && node kryptheon-heal.check.js && node kryptheon-load.check.js && node kryptheon-authz.check.js && node kryptheon-roles.check.js && node kryptheon-map.check.js && node kryptheon-api.check.js && node kryptheon-webhook.check.js && node kryptheon-csv.check.js && node kryptheon-package.check.js && node kryptheon-newer.check.js",
72
74
  "check:store": "node kryptheon-store.check.js",
73
75
  "check:code": "node kryptheon-code.check.js",
74
76
  "check:constdata": "node kryptheon-constdata.check.js",
@@ -113,7 +115,9 @@
113
115
  "check:map": "node kryptheon-map.check.js",
114
116
  "check:api": "node kryptheon-api.check.js",
115
117
  "check:webhook": "node kryptheon-webhook.check.js",
116
- "check:csv": "node kryptheon-csv.check.js"
118
+ "check:csv": "node kryptheon-csv.check.js",
119
+ "check:newer": "node kryptheon-newer.check.js",
120
+ "check:account": "node kryptheon-account.check.js"
117
121
  },
118
122
  "keywords": [
119
123
  "playwright",