kryptheon 0.1.53 → 0.1.55

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.
@@ -0,0 +1,1332 @@
1
+ // Roles and tenants: what each signed-in person can do, against what the app's
2
+ // own permissions file says they may.
3
+ //
4
+ // What it does, in order:
5
+ // 1. reads permissions-policy.json from the app's folder - which role may do
6
+ // what, and whether organizations are kept apart. It never guesses a
7
+ // policy: no file, no run.
8
+ // 2. replays the person's own recordings once, learning every request the
9
+ // page makes (reads too) and who made it. Nothing else decides what is
10
+ // tried: an action nobody recorded is not tried.
11
+ // 3. signs in as each account the recordings used - one session each, their
12
+ // passwords from the KRYPTHEON_PASSWORD_* names in .env - and asks the
13
+ // app who each one is (role, organization).
14
+ // 4. sends each recorded action as every account: as the roles the policy
15
+ // says may not do it (expected: refused), as those it says may (the
16
+ // control: it must not be reported), and - when the policy keeps
17
+ // organizations apart - to a record of another organization.
18
+ // 5. judges what happened from the answer's content and from what the app
19
+ // stored before and after, never from a 200 or a 403 alone:
20
+ // allowed-as-intended | denied-as-intended | confirmed-failure | ambiguous
21
+ // A confirmed failure needs proof: a record the account may not see came
22
+ // back, or the stored state changed. An answer that only looks like a
23
+ // success is "to check" and never a proven problem.
24
+ //
25
+ // What it never does: run against anything but this computer; create an
26
+ // account; delete anything; keep a password or a session cookie anywhere.
27
+ // It does change data in the app (that is how a missing check shows), puts
28
+ // back what it can, and says what it could not.
29
+
30
+ const fs = require('fs');
31
+ const path = require('path');
32
+ const authz = require('./kryptheon-authz.js');
33
+ const probe = require('./kryptheon-probe.js');
34
+ const replay = require('./kryptheon-replay.js');
35
+ const secrets = require('./kryptheon-secrets.js');
36
+ const store = require('./kryptheon-store.js');
37
+
38
+ const POLICY_FILE = 'permissions-policy.json';
39
+
40
+ // What is said before it runs (the terminal and the page alike), and where it
41
+ // may run. Both the command line and the dashboard read these.
42
+ const WHAT = 'Roles and tenants: signs in as each account your recordings use and tries every action they recorded as every one of them - ' +
43
+ 'as the roles ' + POLICY_FILE + ' says may not do it (it must be refused), as those it says may (it must work), and, if the file keeps organizations apart, ' +
44
+ 'aimed at the records of another organization. Judged from what comes back and what your app stored before and after.';
45
+ const WORDS = {
46
+ dataLines: [
47
+ 'It sends requests that must be refused. If your app lets one through, that changes data in your app - which is how a missing check shows.',
48
+ 'It puts back the edits it makes; records it creates and jobs it runs stay, and every accepted write is listed when it ends.',
49
+ 'Use a test copy of your app. It runs only against an app on this computer (localhost or 127.0.0.1).',
50
+ ],
51
+ };
52
+ const LOCAL_ONLY = true;
53
+ const NONE = 'There is no recording to learn the requests of your app from. Record the flows of each role:';
54
+ const V = authz.VERDICT;
55
+ const MAX_ATTEMPTS = 400;
56
+ const MAX_SNAPSHOT = 12;
57
+ const EXCERPT = 200;
58
+ const IDENTITY_PATHS = ['/api/me', '/api/auth/me', '/api/session', '/api/whoami', '/api/user', '/api/users/me', '/api/profile', '/me'];
59
+
60
+ // --- the policy -----------------------------------------------------------
61
+
62
+ /**
63
+ * The app's permissions file, checked. { ok, file, policy, problems } - and
64
+ * `missing` when there is no file at all, which is not the same as a bad one.
65
+ */
66
+ function loadPolicy(root) {
67
+ const file = path.join(root, POLICY_FILE);
68
+ let raw;
69
+ try {
70
+ raw = fs.readFileSync(file, 'utf8');
71
+ } catch (err) {
72
+ return { ok: false, missing: true, file: file, problems: [POLICY_FILE + ' is not in this folder.'] };
73
+ }
74
+ if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1);
75
+ let json;
76
+ try {
77
+ json = JSON.parse(raw);
78
+ } catch (err) {
79
+ return { ok: false, file: file, problems: [POLICY_FILE + ' is not valid JSON (' + err.message + ').'] };
80
+ }
81
+ return Object.assign({ file: file }, checkPolicy(json));
82
+ }
83
+
84
+ /** A parsed permissions file, checked. { ok, policy, problems }. */
85
+ function checkPolicy(json) {
86
+ const problems = [];
87
+ if (!json || typeof json !== 'object' || Array.isArray(json)) return { ok: false, problems: ['it must be a JSON object with a "roles" section.'] };
88
+ const roles = {};
89
+ if (!json.roles || typeof json.roles !== 'object' || Array.isArray(json.roles)) problems.push('"roles" must say, for each role, the list of permissions it has.');
90
+ else {
91
+ for (const name of Object.keys(json.roles)) {
92
+ const list = json.roles[name];
93
+ if (!Array.isArray(list) || list.some((p) => typeof p !== 'string' || !p.trim())) problems.push('role "' + name + '" must be a list of permission names, like "orders.read".');
94
+ else roles[name] = list.map((p) => p.trim());
95
+ }
96
+ if (Object.keys(roles).length < 2 && !problems.length) problems.push('it needs at least two roles to compare.');
97
+ }
98
+ const k = json.kryptheon && typeof json.kryptheon === 'object' ? json.kryptheon : {};
99
+ if (k.actions !== undefined && (!Array.isArray(k.actions) || k.actions.some((a) => !a || typeof a.permission !== 'string' || typeof a.path !== 'string'))) {
100
+ problems.push('"kryptheon.actions" must be a list of { "permission", "method", "path" }.');
101
+ }
102
+ if (problems.length) return { ok: false, problems: problems };
103
+ const tenants = (typeof json.tenantBoundary === 'string' && json.tenantBoundary.trim() !== '') || json.tenants === true;
104
+ return { ok: true, problems: [], policy: { roles: roles, tenants: tenants, boundary: typeof json.tenantBoundary === 'string' ? json.tenantBoundary : '', extra: k } };
105
+ }
106
+
107
+ /** Whether `role` has `permission` ("*" and "resource.*" are allowed in the file). */
108
+ function holds(policy, role, permission) {
109
+ const key = Object.keys(policy.roles).find((r) => r.toLowerCase() === String(role || '').toLowerCase());
110
+ if (!key) return false;
111
+ return policy.roles[key].some((p) => p === permission || p === '*' || (p.endsWith('.*') && permission.startsWith(p.slice(0, -1))));
112
+ }
113
+
114
+ /** Every permission any role has, by name. */
115
+ function permissionsOf(policy) {
116
+ const out = [];
117
+ for (const list of Object.values(policy.roles)) for (const p of list) if (p !== '*' && !p.endsWith('.*') && !out.includes(p)) out.push(p);
118
+ return out;
119
+ }
120
+
121
+ /** The roles that have this permission. */
122
+ function rolesWith(policy, permission) {
123
+ return Object.keys(policy.roles).filter((r) => holds(policy, r, permission));
124
+ }
125
+
126
+ /** What to put in permissions-policy.json when there is none. The person fills it in. */
127
+ function templateText() {
128
+ return JSON.stringify({
129
+ roles: {
130
+ owner: ['orders.read', 'orders.create', 'orders.update', 'team.invite'],
131
+ member: ['orders.read'],
132
+ },
133
+ tenantBoundary: 'A signed-in user may reach only records of their own organization. Delete this line if your app has one organization.',
134
+ }, null, 2);
135
+ }
136
+
137
+ /** Said when the file is missing: what it is, and the starting point. Never written for them. */
138
+ function missingLines() {
139
+ const lines = [
140
+ POLICY_FILE + ' is not in this folder, so nothing was tried.',
141
+ '',
142
+ 'Kryptheon does not guess who may do what - a guess would call the wrong things a bug. Write it down once:',
143
+ ' - save a file called ' + POLICY_FILE + ' next to your package.json',
144
+ ' - list each role, and the permissions only that role has, named like the addresses they guard (shipments.update, team.invite)',
145
+ ' - keep "tenantBoundary" if one organization must never reach another\'s records',
146
+ '',
147
+ 'A starting point (edit it to match your app):',
148
+ ];
149
+ for (const l of templateText().split('\n')) lines.push(' ' + l);
150
+ lines.push('', 'Then run npx kryptheon roles again.');
151
+ return lines;
152
+ }
153
+
154
+ // --- which permission does a request need ----------------------------------
155
+
156
+ const SKIP_WORDS = new Set(['api', 'rest', 'json']);
157
+ const READ_WORDS = new Set(['read', 'list', 'view', 'get', 'show', 'export', 'download', 'search', 'fetch']);
158
+ const FILE_EXTENSIONS = /\.(csv|xlsx?|pdf|zip|tsv)$/i;
159
+ const METHOD_VERB = { GET: 'read', HEAD: 'read', POST: 'create', PUT: 'update', PATCH: 'update', DELETE: 'delete' };
160
+
161
+ function singular(w) {
162
+ if (w.length > 3 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
163
+ if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1);
164
+ return w;
165
+ }
166
+
167
+ /** Words of a name, lower case, one form of each: "notify_overdue" -> notify, overdue. */
168
+ function wordsOf(text) {
169
+ return String(text || '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).map(singular);
170
+ }
171
+
172
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
173
+
174
+ /** A part of an address that names one record: it has a digit (and is not "v2"), or is a uuid or a long hex id. */
175
+ function isParam(seg) {
176
+ if (/^v\d+$/i.test(seg)) return false;
177
+ if (/^(\{[^}]*\}|:[A-Za-z_]\w*)$/.test(seg)) return true;
178
+ return /\d/.test(seg) || UUID.test(seg) || /^[0-9a-f]{12,}$/i.test(seg);
179
+ }
180
+
181
+ /** An address with its record ids taken out: { template, segs, params: [{ index, value }] }. */
182
+ function parsePath(p) {
183
+ const clean = String(p || '').split(/[?#]/)[0];
184
+ const segs = [];
185
+ const params = [];
186
+ for (const part of clean.split('/').filter(Boolean)) {
187
+ let seg = part;
188
+ try {
189
+ seg = decodeURIComponent(part);
190
+ } catch (err) {
191
+ seg = part;
192
+ }
193
+ if (isParam(seg)) {
194
+ params.push({ index: segs.length, value: seg });
195
+ segs.push('{id}');
196
+ } else {
197
+ segs.push(seg);
198
+ }
199
+ }
200
+ return { template: '/' + segs.join('/'), segs: segs, params: params };
201
+ }
202
+
203
+ /** A written address from the permissions file ({id}, :id, <id>) in the same form. */
204
+ function templateOfWritten(p) {
205
+ return '/' + String(p || '').split(/[?#]/)[0].split('/').filter(Boolean).map((s) => (/^(\{[^}]*\}|:[A-Za-z_]\w*|<[^>]*>|\*)$/.test(s) ? '{id}' : s)).join('/');
206
+ }
207
+
208
+ /**
209
+ * The permission an action needs, found from the words in its address and its
210
+ * method - or null, or `ambiguous`. Strict on purpose: when two permissions
211
+ * fit equally, or the last part of the address names something no permission
212
+ * does ("/shipments/5/notes"), nothing is guessed and the action is not
213
+ * judged. The policy file's own "kryptheon.actions" settle anything it says.
214
+ */
215
+ function permissionFor(method, pathOrTemplate, policy) {
216
+ const parsed = parsePath(pathOrTemplate);
217
+ const m = String(method).toUpperCase();
218
+ for (const a of (policy.extra && policy.extra.actions) || []) {
219
+ if ((!a.method || a.method === '*' || a.method.toUpperCase() === m) && templateOfWritten(a.path) === parsed.template) return { permission: a.permission, how: 'named in ' + POLICY_FILE };
220
+ }
221
+ const statics = parsed.segs.filter((s) => s !== '{id}');
222
+ const extension = (FILE_EXTENSIONS.exec(statics[statics.length - 1] || '') || [])[1];
223
+ const pathWords = new Set();
224
+ for (const s of statics) for (const w of wordsOf(s.replace(FILE_EXTENSIONS, ''))) if (!SKIP_WORDS.has(w) && !/^v\d+$/.test(w)) pathWords.add(w);
225
+ const last = statics.length ? new Set(wordsOf(statics[statics.length - 1].replace(FILE_EXTENSIONS, ''))) : new Set();
226
+ if (extension) last.add(extension.toLowerCase());
227
+ const isGet = m === 'GET' || m === 'HEAD';
228
+ const verb = METHOD_VERB[m];
229
+ const found = [];
230
+ for (const perm of permissionsOf(policy)) {
231
+ const w = wordsOf(perm);
232
+ if (w.length < 2) continue;
233
+ const resource = w[0];
234
+ const actions = w.slice(1);
235
+ if (!pathWords.has(resource)) continue;
236
+ const readish = actions.every((a) => READ_WORDS.has(a));
237
+ if (isGet !== readish) continue;
238
+ let score = 1;
239
+ let lastHit = last.has(resource);
240
+ for (const a of actions) {
241
+ if (pathWords.has(a)) {
242
+ score += 2;
243
+ if (last.has(a)) lastHit = true;
244
+ } else if (a === 'export' && extension) {
245
+ score += 2;
246
+ lastHit = true;
247
+ } else if (a === verb) {
248
+ score += 1;
249
+ }
250
+ }
251
+ found.push({ permission: perm, score: score, lastHit: lastHit });
252
+ }
253
+ if (!found.length) return null;
254
+ const lastWordsAny = statics.length > 0 && parsed.params.length > 0 && statics[statics.length - 1] !== undefined && parsed.segs[parsed.segs.length - 1] !== '{id}';
255
+ found.sort((a, b) => (b.lastHit ? 1 : 0) - (a.lastHit ? 1 : 0) || b.score - a.score);
256
+ const best = found[0];
257
+ // "/shipments/5/notes": the end of the address names something none of the
258
+ // permissions does, so the permission of "shipments" would be a guess.
259
+ if (!best.lastHit && lastWordsAny) return { ambiguous: true, why: 'the end of the address (' + statics[statics.length - 1] + ') matches no permission name' };
260
+ const tied = found.filter((f) => f.lastHit === best.lastHit && f.score === best.score);
261
+ if (tied.length > 1) return { ambiguous: true, why: 'it fits ' + tied.map((t) => t.permission).join(' and ') + ' equally' };
262
+ return { permission: best.permission, how: 'by the words in the address' };
263
+ }
264
+
265
+ // --- the journey: what the recordings did -----------------------------------
266
+
267
+ const LOGOUT = /(^|\/)(log-?out|sign-?out)(\/|$)/i;
268
+
269
+ /**
270
+ * The recordings' own requests, from the events a probe run kept for each:
271
+ * who signed in how, which accounts, and every action (reads and writes)
272
+ * with a sample of what was sent. `runs` is [{ flow, result }].
273
+ */
274
+ function journeyFromRuns(runs) {
275
+ const journey = { origin: null, signIn: null, accounts: [], actions: [], flows: [] };
276
+ const seen = new Map();
277
+ for (const run of runs) {
278
+ const flow = run.flow;
279
+ const result = run.result;
280
+ if (!result) {
281
+ journey.flows.push({ title: flow.title, file: flow.file, state: 'not tested', why: 'the replay did not finish' });
282
+ continue;
283
+ }
284
+ let email = null;
285
+ const events = result.events || [];
286
+ for (const e of events) {
287
+ if (e.kind === 'write' && e.signIn && !email && e.data && typeof e.data === 'object') {
288
+ const keys = Object.keys(e.data);
289
+ const emailField = keys.find((k) => typeof e.data[k] === 'string' && e.data[k] !== '[hidden]' && /mail|user|login|account|phone/i.test(k));
290
+ const passwordField = keys.find((k) => e.data[k] === '[hidden]');
291
+ if (emailField && passwordField) {
292
+ email = String(e.data[emailField]).trim().toLowerCase();
293
+ if (!journey.signIn) {
294
+ const extra = {};
295
+ for (const k of keys) if (k !== emailField && k !== passwordField && ['string', 'number', 'boolean'].includes(typeof e.data[k])) extra[k] = e.data[k];
296
+ journey.signIn = { method: e.method, path: e.path, emailField: emailField, passwordField: passwordField, extra: extra, encoding: e.encoding || 'json' };
297
+ }
298
+ if (e.origin && !journey.origin) journey.origin = e.origin;
299
+ }
300
+ }
301
+ }
302
+ if (email && !journey.accounts.some((a) => a.email === email)) journey.accounts.push({ email: email, flow: flow.file });
303
+ for (const e of events) {
304
+ if ((e.kind !== 'write' && e.kind !== 'read') || e.signIn || !e.path || LOGOUT.test(e.path)) continue;
305
+ if (journey.signIn && e.path === journey.signIn.path && e.method === journey.signIn.method) continue;
306
+ if (e.status >= 500 || e.status === 0) continue;
307
+ if (e.kind === 'write' && !probe.accepted(e)) continue;
308
+ if (e.kind === 'read' && !(e.status >= 200 && e.status < 300)) continue;
309
+ const parsed = parsePath(e.path);
310
+ const key = e.method + ' ' + parsed.template;
311
+ if (seen.has(key)) continue;
312
+ const action = { method: e.method, template: parsed.template, segs: parsed.segs, params: parsed.params, path: e.path, status: e.status, by: email,
313
+ data: e.data && typeof e.data === 'object' && !Array.isArray(e.data) ? e.data : null, encoding: e.encoding || 'json', flow: flow.file };
314
+ seen.set(key, action);
315
+ journey.actions.push(action);
316
+ if (!journey.origin && e.origin) journey.origin = e.origin;
317
+ }
318
+ journey.flows.push({ title: flow.title, file: flow.file, state: 'tested', email: email });
319
+ }
320
+ return journey;
321
+ }
322
+
323
+ /** Every recording replayed once, under the probe fixture that also keeps reads. */
324
+ async function captureJourney(root, flows, options) {
325
+ const opts = options || {};
326
+ const say = typeof opts.say === 'function' ? opts.say : () => {};
327
+ const names = [];
328
+ for (const f of flows) for (const m of String(f.source).matchAll(/process\.env\.([A-Za-z_][A-Za-z0-9_]*)/g)) if (!names.includes(m[1])) names.push(m[1]);
329
+ const skipped = [];
330
+ const chosen = [];
331
+ for (const f of flows) {
332
+ if (replay.findReplayRisks(f.source).some((r) => r.kind === 'signup')) {
333
+ skipped.push({ title: f.title, file: f.file, state: 'skipped', why: 'it creates an account, and this check never creates accounts' });
334
+ continue;
335
+ }
336
+ chosen.push(f);
337
+ }
338
+ const probes = chosen.map((f, i) => ({ id: probe.probeId(i + 1, f.title), source: probe.probeSource(f.source), flow: f }));
339
+ const labels = {};
340
+ for (const p of probes) labels[p.id] = p.flow.title + ' - to learn its requests';
341
+ const handle = probe.runProbes(root, probes, { say: say, labels: labels, secretNames: names, gapMs: opts.gapMs, env: opts.env, hide: opts.hide, childEnv: { KRYPTHEON_PROBE_READS: '1' } });
342
+ if (typeof opts.onHandle === 'function') opts.onHandle(handle);
343
+ const done = await handle.done;
344
+ const journey = journeyFromRuns(probes.map((p) => ({ flow: p.flow, result: done.results[p.id] || null })));
345
+ journey.flows = journey.flows.concat(skipped);
346
+ journey.stopped = done.stopped;
347
+ journey.runs = Object.keys(done.results).length;
348
+ return journey;
349
+ }
350
+
351
+ // --- reading what the app returns -------------------------------------------
352
+
353
+ const VOLATILE_KEY = /^(updated_?at|modified_?at|last_?seen|now|server_?time|timestamp|request_?id|etag|generated_?at)$/i;
354
+
355
+ /** A value without the keys that change on their own. */
356
+ function stable(value) {
357
+ if (Array.isArray(value)) return value.map(stable);
358
+ if (value && typeof value === 'object') {
359
+ const out = {};
360
+ for (const k of Object.keys(value)) if (!VOLATILE_KEY.test(k)) out[k] = stable(value[k]);
361
+ return out;
362
+ }
363
+ return value;
364
+ }
365
+
366
+ /** The first list of records in an answer: the answer itself, or its first array. */
367
+ function listOf(json) {
368
+ if (Array.isArray(json)) return json;
369
+ if (json && typeof json === 'object') for (const k of Object.keys(json)) if (Array.isArray(json[k])) return json[k];
370
+ return null;
371
+ }
372
+
373
+ const idOf = (item) => (item && typeof item === 'object' ? (item.id !== undefined ? item.id : item.sku !== undefined ? item.sku : item.uuid) : undefined);
374
+
375
+ /** What differs between two answers of the same address, in a few plain lines. */
376
+ function diffLines(template, a, b) {
377
+ if (JSON.stringify(a) === JSON.stringify(b)) return [];
378
+ const la = listOf(a);
379
+ const lb = listOf(b);
380
+ const lines = [];
381
+ if (la && lb && la.every((x) => idOf(x) !== undefined) && lb.every((x) => idOf(x) !== undefined)) {
382
+ const was = new Map(la.map((x) => [String(idOf(x)), x]));
383
+ const now = new Map(lb.map((x) => [String(idOf(x)), x]));
384
+ for (const id of now.keys()) if (!was.has(id)) lines.push(template + ': a new record appeared (id ' + id + ')');
385
+ for (const id of was.keys()) if (!now.has(id)) lines.push(template + ': record ' + id + ' is gone');
386
+ for (const [id, x] of now) {
387
+ const y = was.get(id);
388
+ if (!y || JSON.stringify(x) === JSON.stringify(y)) continue;
389
+ const fields = Object.keys(Object.assign({}, x, y)).filter((f) => JSON.stringify(x[f]) !== JSON.stringify(y[f]));
390
+ lines.push(template + ': record ' + id + ' changed - ' + fields.slice(0, 3).map((f) => f + ' ' + authz.clip(JSON.stringify(y[f]), 40) + ' -> ' + authz.clip(JSON.stringify(x[f]), 40)).join('; '));
391
+ }
392
+ if (lines.length) return lines;
393
+ }
394
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
395
+ const fields = Object.keys(Object.assign({}, a, b)).filter((f) => JSON.stringify(a[f]) !== JSON.stringify(b[f]));
396
+ return [template + ': ' + fields.slice(0, 4).map((f) => f + ' ' + authz.clip(JSON.stringify(a[f]), 40) + ' -> ' + authz.clip(JSON.stringify(b[f]), 40)).join('; ')];
397
+ }
398
+ return [template + ': the answer changed'];
399
+ }
400
+
401
+ /** A body for a request: the recorded one without secrets, and a fresh once-only key. */
402
+ function sampleBody(action) {
403
+ if (!action.data) return {};
404
+ const out = {};
405
+ for (const k of Object.keys(action.data)) {
406
+ const v = action.data[k];
407
+ if (v === '[hidden]') continue;
408
+ out[k] = /idempotency|request[_-]?key|nonce/i.test(k) && typeof v === 'string' ? 'kx-' + Math.random().toString(36).slice(2, 10) : v;
409
+ }
410
+ return out;
411
+ }
412
+
413
+ // --- the check ---------------------------------------------------------------
414
+
415
+ /**
416
+ * The accounts the recordings used that can be signed in, and why the others
417
+ * cannot. A password is the KRYPTHEON_PASSWORD_* name for that account, from
418
+ * .env or the environment.
419
+ */
420
+ function accountsFor(journey, root, env) {
421
+ const fromFile = secrets.readEnvFile(secrets.envFileFor(root));
422
+ const here = env || process.env;
423
+ const usable = [];
424
+ const left = [];
425
+ for (const a of journey.accounts) {
426
+ const name = 'KRYPTHEON_PASSWORD_' + replay.accountPart(a.email);
427
+ const value = secrets.isSet(here[name]) ? here[name] : secrets.isSet(fromFile[name]) ? fromFile[name] : '';
428
+ if (value) usable.push({ email: a.email, password: value, envName: name, flow: a.flow });
429
+ else left.push({ email: a.email, why: 'its password is not set: add ' + name + ' to .env (the recording ' + a.flow + ' signs in as it)' });
430
+ }
431
+ return { usable: usable, left: left };
432
+ }
433
+
434
+ function findUser(json) {
435
+ const looks = (o) => o && typeof o === 'object' && !Array.isArray(o) && (typeof o.role === 'string' || (o.role && typeof o.role.name === 'string'));
436
+ const pools = [json, json && json.user, json && json.data, json && json.data && json.data.user, json && json.me, json && json.account, json && json.profile];
437
+ return pools.find(looks) || null;
438
+ }
439
+
440
+ function orgOf(user, extra) {
441
+ const idPath = extra && extra.identity && extra.identity.orgPath;
442
+ const namePath = extra && extra.identity && extra.identity.orgNamePath;
443
+ let id = idPath ? authz.getPath(user, idPath) : undefined;
444
+ let name = namePath ? authz.getPath(user, namePath) : undefined;
445
+ if (id === undefined) {
446
+ const k = Object.keys(user).find((x) => /^(org|organi[sz]ation|tenant|workspace|company|team|account)[_-]?id$/i.test(x));
447
+ if (k) id = user[k];
448
+ else {
449
+ const o = user.organization || user.org || user.tenant || user.workspace;
450
+ if (o && typeof o === 'object') {
451
+ id = o.id;
452
+ name = name || o.name;
453
+ }
454
+ }
455
+ }
456
+ if (name === undefined) {
457
+ const k = Object.keys(user).find((x) => /^(org|organi[sz]ation|tenant|workspace|company)[_-]?name$/i.test(x));
458
+ if (k) name = user[k];
459
+ }
460
+ if (id === undefined && name === undefined) return null;
461
+ return { key: String(id !== undefined ? id : name), name: name !== undefined ? String(name) : String(id) };
462
+ }
463
+
464
+ const holdsAny = (policy, role, perms) => perms.some((p) => holds(policy, role, p));
465
+
466
+ /**
467
+ * Tries the recorded actions as every account and judges each. Pure of the
468
+ * browser: `fetch` is injected for the tests. Returns { attempts, skipped,
469
+ * accounts, mapping, notes }.
470
+ */
471
+ async function checkAccess(input) {
472
+ const policy = input.policy;
473
+ const journey = input.journey;
474
+ const say = typeof input.say === 'function' ? input.say : () => {};
475
+ const stopped = typeof input.stopped === 'function' ? input.stopped : () => false;
476
+ const origin = authz.assertLocalTarget(input.origin, input.allowOrigins || [input.origin]);
477
+ const passwords = {};
478
+ for (const a of input.accounts) passwords[a.email] = a.password;
479
+ const ctx = authz.makeContext({ baseUrl: origin, allowOrigins: [origin], fetch: input.fetch, passwords: passwords, maxRequests: input.maxRequests || 30000, timeoutMs: input.timeoutMs });
480
+ const hide = [].concat(Object.values(passwords));
481
+ const notes = [];
482
+ const skipped = [];
483
+ const out = { attempts: [], skipped: skipped, notes: notes, accounts: [], mapping: [], origin: origin, requests: 0 };
484
+
485
+ // 1. one session per account, and who the app says each one is
486
+ const sessions = [];
487
+ const candidates = (policy.extra.identity && policy.extra.identity.path) ? [policy.extra.identity.path] : IDENTITY_PATHS;
488
+ const login = journey.signIn;
489
+ if (!login) {
490
+ skipped.push({ what: 'all accounts', why: 'no recording signs in through a request this check can repeat (no sign-in request was seen)' });
491
+ return out;
492
+ }
493
+ for (const a of input.accounts) {
494
+ const s = authz.makeSession(ctx, null, a.email, a.password);
495
+ const fields = Object.assign({}, login.extra);
496
+ fields[login.emailField] = a.email;
497
+ fields[login.passwordField] = a.password;
498
+ let res = await s.send(login.method || 'POST', login.path, login.encoding === 'form' ? { form: fields } : { json: fields });
499
+ let reply = authz.replyOf(res);
500
+ if (reply.kind === 'refused' && [400, 415, 422].includes(res.status)) {
501
+ res = await s.send(login.method || 'POST', login.path, login.encoding === 'form' ? { json: fields } : { form: fields });
502
+ reply = authz.replyOf(res);
503
+ }
504
+ if (reply.kind === 'refused' || reply.kind === 'server-error' || reply.kind === 'no-answer') {
505
+ skipped.push({ what: a.email, why: 'the app did not let it sign in (' + reply.note + ') - is the password in .env right?' });
506
+ continue;
507
+ }
508
+ let user = null;
509
+ for (const p of candidates) {
510
+ const me = await s.send('GET', p);
511
+ if (me.status === 200 && me.json) {
512
+ user = findUser(me.json);
513
+ if (user) break;
514
+ }
515
+ }
516
+ if (!user) {
517
+ skipped.push({ what: a.email, why: 'signed in, but the app did not say who it is (looked at ' + candidates.slice(0, 3).join(', ') + '...). Name the address in ' + POLICY_FILE + ' under kryptheon.identity.path' });
518
+ continue;
519
+ }
520
+ const roleName = typeof user.role === 'string' ? user.role : user.role.name;
521
+ const known = Object.keys(policy.roles).find((r) => r.toLowerCase() === roleName.toLowerCase());
522
+ if (!known) {
523
+ skipped.push({ what: a.email, why: 'the app says its role is "' + roleName + '", which ' + POLICY_FILE + ' does not list' });
524
+ continue;
525
+ }
526
+ s.role = known;
527
+ s.org = orgOf(user, policy.extra);
528
+ s.userId = user.id;
529
+ sessions.push(s);
530
+ }
531
+ out.accounts = sessions.map((s) => ({ email: s.email, role: s.role, org: s.org ? s.org.name : null }));
532
+ if (sessions.length < 2) {
533
+ skipped.push({ what: 'accounts', why: 'fewer than two accounts could be signed in, so there is nothing to compare' });
534
+ out.requests = ctx.requests;
535
+ return out;
536
+ }
537
+ const orgs = new Map();
538
+ for (const s of sessions) if (s.org) {
539
+ if (!orgs.has(s.org.key)) orgs.set(s.org.key, { key: s.org.key, name: s.org.name, sessions: [] });
540
+ orgs.get(s.org.key).sessions.push(s);
541
+ }
542
+ const tenants = policy.tenants && orgs.size >= 2;
543
+ if (policy.tenants && !tenants) notes.push('The policy keeps organizations apart, but ' + (orgs.size ? 'all the accounts that could be signed in belong to one organization' : 'the app did not say which organization anyone belongs to') + ' - the organization check was not tried.');
544
+
545
+ // 2. the actions, and the permission each needs
546
+ const mapped = [];
547
+ const reads = [];
548
+ for (const a of journey.actions) {
549
+ if (a.method === 'DELETE') {
550
+ skipped.push({ what: a.method + ' ' + a.template, why: 'not tried: this check never sends a delete' });
551
+ continue;
552
+ }
553
+ const p = permissionFor(a.method, a.template, policy);
554
+ if (p && p.permission) {
555
+ mapped.push(Object.assign({ permission: p.permission, how: p.how }, a));
556
+ out.mapping.push({ method: a.method, template: a.template, permission: p.permission, how: p.how });
557
+ } else {
558
+ skipped.push({ what: a.method + ' ' + a.template, why: p && p.ambiguous ? 'not judged: ' + p.why + '. Name its permission in ' + POLICY_FILE + ' under kryptheon.actions' : 'not judged: no permission in ' + POLICY_FILE + ' is named like this address. Name it under kryptheon.actions to include it' });
559
+ }
560
+ if (a.method === 'GET' && !a.params.length) reads.push(a);
561
+ }
562
+ const getTemplates = new Set(journey.actions.filter((a) => a.method === 'GET').map((a) => a.template));
563
+ const identityPaths = new Set(candidates);
564
+ const snapshotReads = reads.filter((a) => !identityPaths.has(a.template) && !/health|public/i.test(a.template)).slice(0, MAX_SNAPSHOT);
565
+
566
+ const accountsOf = (orgKey) => (orgKey === null ? sessions : (orgs.get(orgKey) || { sessions: [] }).sessions);
567
+ const permOf = new Map(mapped.map((a) => [a.method + ' ' + a.template, a.permission]));
568
+ const readerFor = async (orgKey, template, perm, mustHold) => {
569
+ const list = accountsOf(orgKey).slice().sort((x, y) => (policy.roles[y.role] || []).length - (policy.roles[x.role] || []).length);
570
+ for (const s of list) {
571
+ if (mustHold && perm && !holds(policy, s.role, perm)) continue;
572
+ const res = await s.send('GET', template);
573
+ if (res.status === 200 && res.json !== undefined) return { session: s, res: res };
574
+ }
575
+ return null;
576
+ };
577
+
578
+ // 3. a picture of what the app holds, per organization, before and after each try
579
+ const snapshotCache = new Map();
580
+ const unstable = new Set();
581
+ const snapshot = async (orgKey) => {
582
+ const snap = {};
583
+ for (const a of snapshotReads) {
584
+ if (unstable.has(a.template)) continue;
585
+ const perm = permOf.get('GET ' + a.template) || null;
586
+ const key = orgKey + '|' + a.template;
587
+ let reader = snapshotCache.get(key);
588
+ if (reader === undefined) {
589
+ const found = await readerFor(orgKey, a.template, perm, true);
590
+ reader = found ? found.session : null;
591
+ snapshotCache.set(key, reader);
592
+ }
593
+ if (!reader) continue;
594
+ const res = await reader.send('GET', a.template);
595
+ if (res.status === 200 && res.json !== undefined) snap[a.template] = stable(res.json);
596
+ }
597
+ return snap;
598
+ };
599
+ const compare = (before, after) => {
600
+ const lines = [];
601
+ for (const t of Object.keys(after)) if (before[t] !== undefined) lines.push.apply(lines, diffLines(t, before[t], after[t]));
602
+ return lines;
603
+ };
604
+ for (const key of orgs.keys()) {
605
+ const one = await snapshot(key);
606
+ const two = await snapshot(key);
607
+ for (const t of Object.keys(one)) if (JSON.stringify(one[t]) !== JSON.stringify(two[t])) {
608
+ unstable.add(t);
609
+ notes.push('GET ' + t + ' changes by itself between two reads, so it is not used to see what a try changed.');
610
+ }
611
+ }
612
+
613
+ // 4. the records to aim at, from the app's own lists
614
+ const itemsCache = new Map();
615
+ const itemsOf = async (orgKey, template, fresh) => {
616
+ const k = orgKey + '|' + template;
617
+ if (!fresh && itemsCache.has(k)) return itemsCache.get(k);
618
+ const found = await readerFor(orgKey, template, permOf.get('GET ' + template) || null, true);
619
+ // Records marked as another organization's are not this organization's to aim at, whatever the list holds.
620
+ const list = found ? (listOf(found.res.json) || []).filter((it) => !foreignRecords(it, orgKey).length) : null;
621
+ itemsCache.set(k, list && list.length ? list : null);
622
+ return itemsCache.get(k);
623
+ };
624
+ const fieldCache = new Map();
625
+ const fieldFor = async (action, listing) => {
626
+ const k = action.template + '|' + listing;
627
+ if (fieldCache.has(k)) return fieldCache.get(k);
628
+ let field = 'id';
629
+ const recorder = sessions.find((s) => s.email === action.by);
630
+ const items = recorder && recorder.org ? await itemsOf(recorder.org.key, listing) : null;
631
+ const recorded = action.params[0] && action.params[0].value;
632
+ if (items && recorded !== undefined) {
633
+ for (const it of items) {
634
+ const f = it && typeof it === 'object' ? Object.keys(it).find((x) => String(it[x]) === String(recorded)) : null;
635
+ if (f) {
636
+ field = f;
637
+ break;
638
+ }
639
+ }
640
+ }
641
+ fieldCache.set(k, field);
642
+ return field;
643
+ };
644
+ /** The records of one organization an action's address can be aimed at: [{ value, item }]. */
645
+ const targetsFor = async (action, orgKey) => {
646
+ if (!action.params.length) return [{ value: null, item: null }];
647
+ if (action.params.length > 1) return null;
648
+ const listing = '/' + action.segs.slice(0, action.params[0].index).join('/');
649
+ if (!getTemplates.has(listing)) return null;
650
+ const items = await itemsOf(orgKey, listing);
651
+ if (!items) return null;
652
+ const field = await fieldFor(action, listing);
653
+ const out2 = items.filter((it) => it && it[field] !== undefined).map((it) => ({ value: it[field], item: it, listing: listing, field: field }));
654
+ return out2.length ? out2 : null;
655
+ };
656
+
657
+ // 5. what an account already knows, so only more than that counts as disclosed
658
+ const knownCache = new Map();
659
+ const knownTo = async (s) => {
660
+ if (knownCache.has(s.email)) return knownCache.get(s.email);
661
+ let text = '';
662
+ for (const a of snapshotReads) {
663
+ const perm = permOf.get('GET ' + a.template);
664
+ if (perm && !holds(policy, s.role, perm)) continue;
665
+ const res = await s.send('GET', a.template);
666
+ if (res.status === 200) text += ' ' + res.text;
667
+ }
668
+ knownCache.set(s.email, text);
669
+ return text;
670
+ };
671
+ const markersOf = (value, known, requestText) =>
672
+ Array.from(new Set(authz.stringsOf(value, 5))).filter((m) => !known.includes(m) && !requestText.includes(m)).slice(0, 60);
673
+
674
+ // 6. the tries
675
+ const plan = [];
676
+ const unaimed = new Set();
677
+ const aimable = (action) => action.method === 'GET' || action.params.length > 0 || Boolean(bodyRecord(action, action.data || {}, getTemplates));
678
+ for (const action of mapped) {
679
+ for (const s of sessions) {
680
+ const may = holds(policy, s.role, action.permission);
681
+ if (may) {
682
+ plan.push({ action: action, actor: s, kind: 'role', expected: 'allow', org: s.org ? s.org.key : null });
683
+ if (tenants && s.org) {
684
+ if (aimable(action)) {
685
+ for (const o of orgs.values()) if (o.key !== s.org.key) plan.push({ action: action, actor: s, kind: 'tenant', expected: 'deny', org: o.key });
686
+ } else if (!unaimed.has(action.method + ' ' + action.template)) {
687
+ unaimed.add(action.method + ' ' + action.template);
688
+ skipped.push({ what: action.method + ' ' + action.template, why: 'across organizations: nothing in the request names a record, so it cannot be aimed at another organization' });
689
+ }
690
+ }
691
+ } else {
692
+ plan.push({ action: action, actor: s, kind: 'role', expected: 'deny', org: s.org ? s.org.key : null });
693
+ }
694
+ }
695
+ }
696
+ // Refusals first, so a control that changes things (an archive, a job) cannot make a later refusal look kept.
697
+ const rank = (p) => (p.expected === 'deny' ? 0 : 1);
698
+ plan.sort((a, b) => rank(a) - rank(b));
699
+ const controlsDone = new Set();
700
+ const chosen = [];
701
+ for (const p of plan) {
702
+ if (input.only && !input.only(p)) continue;
703
+ if (p.expected === 'allow' && p.action.method !== 'GET') {
704
+ const k = p.action.method + ' ' + p.action.template;
705
+ if (controlsDone.has(k)) continue;
706
+ controlsDone.add(k);
707
+ }
708
+ chosen.push(p);
709
+ }
710
+ const cap = input.maxAttempts || MAX_ATTEMPTS;
711
+ if (chosen.length > cap) {
712
+ notes.push((chosen.length - cap) + ' tries were left out to stay within ' + cap + ' (refusals were kept first).');
713
+ chosen.length = cap;
714
+ }
715
+ out.planned = chosen.length;
716
+ const rotate = new Map();
717
+ let n = 0;
718
+ for (const p of chosen) {
719
+ if (stopped()) {
720
+ out.stopped = true;
721
+ break;
722
+ }
723
+ n++;
724
+ const a = p.action;
725
+ const label = (p.kind === 'tenant' ? 'across organizations: ' : '') + p.actor.role + ' ' + a.method + ' ' + a.template;
726
+ say(' ' + n + ' of ' + chosen.length + ': ' + label);
727
+ const att = await tryOnce({ p, ctx, policy, orgs, snapshot, compare, targetsFor, itemsOf, markersOf, knownTo, readerFor, rotate, tenants, sessions, hide, getTemplates });
728
+ if (Array.isArray(att)) out.attempts.push.apply(out.attempts, att);
729
+ else if (att) out.attempts.push(att);
730
+ }
731
+ // An action every account was answered 401 for is not reached with a session cookie (an API key, say): nothing can be said about it.
732
+ const groups = new Map();
733
+ for (const a of out.attempts) {
734
+ const k = a.method + ' ' + a.template;
735
+ if (!groups.has(k)) groups.set(k, []);
736
+ groups.get(k).push(a);
737
+ }
738
+ for (const [k, list] of groups) {
739
+ if (list.every((a) => !a.notTried && a.response.status === 401)) {
740
+ out.attempts = out.attempts.filter((a) => !list.includes(a));
741
+ skipped.push({ what: k, why: 'every account was answered 401 (not signed in): it does not take the session, probably its own key, so it was not judged' });
742
+ }
743
+ }
744
+ // What the policy lists that nothing recorded needs: said, so a clean run is not read as covering it.
745
+ const covered = new Set(mapped.map((m) => m.permission));
746
+ const unseen = permissionsOf(policy).filter((perm) => !covered.has(perm));
747
+ if (unseen.length) notes.push('No recording makes a request that needs: ' + unseen.join(', ') + '. Those were not tried - record someone using them.');
748
+ out.requests = ctx.requests;
749
+ return out;
750
+ }
751
+
752
+ /**
753
+ * The key in a request body that names another record (shipmentId, order_id),
754
+ * with a stand-in for the address that lists those records: { key, like }.
755
+ */
756
+ function bodyRecord(action, body, getTemplates) {
757
+ const key = Object.keys(body || {}).find((k) => /^[A-Za-z]+_?[iI]d$/.test(k) && k.toLowerCase() !== 'id' && ['string', 'number'].includes(typeof body[k]));
758
+ if (!key) return null;
759
+ const stem = singular(key.replace(/_?[iI]d$/, '').toLowerCase());
760
+ const listing = Array.from(getTemplates || []).find((t) => !t.includes('{id}') && singular(t.split('/').pop().toLowerCase().replace(/[^a-z]/g, '')) === stem);
761
+ if (!listing) return null;
762
+ const segs = listing.split('/').filter(Boolean).concat('{id}');
763
+ return { key: key, like: { template: listing + '/{id}', segs: segs, params: [{ index: segs.length - 1, value: body[key] }], by: action.by } };
764
+ }
765
+
766
+ /** One try: send, look, judge, put back. Returns the evidence, or null when the try had nothing to aim at. */
767
+ async function tryOnce(x) {
768
+ const { p, policy } = x;
769
+ const a = p.action;
770
+ const actor = p.actor;
771
+ const isGet = a.method === 'GET';
772
+ const targetOrg = p.org;
773
+ const orgName = (key) => (key && x.orgs.get(key) ? x.orgs.get(key).name : null);
774
+ const base = {
775
+ kind: p.kind, permission: a.permission, method: a.method, template: a.template, expected: p.expected,
776
+ actor: { email: actor.email, role: actor.role, org: actor.org ? actor.org.name : null },
777
+ targetOrg: orgName(targetOrg), cross: p.kind === 'tenant',
778
+ };
779
+ const skip = (why) => Object.assign(base, { verdict: V.AMBIGUOUS, reason: why, notTried: true, request: { method: a.method, path: a.template } });
780
+
781
+ // where to aim
782
+ let target = { value: null, item: null };
783
+ if (a.params.length) {
784
+ const targets = await x.targetsFor(a, targetOrg);
785
+ if (!targets) return skip('no record of ' + (orgName(targetOrg) || 'that organization') + ' could be found to aim it at (the app lists none at ' + '/' + a.segs.slice(0, a.params[0].index).join('/') + ')');
786
+ const k = targetOrg + '|' + a.template;
787
+ const i = (x.rotate.get(k) || 0);
788
+ x.rotate.set(k, i + 1);
789
+ // A record that is the actor's own (a user record) is where a refused account
790
+ // would first try to raise its own rights; a control never uses it.
791
+ const mine = (t) => t.item && typeof t.item === 'object' && (t.item.email === actor.email || (t.item.id !== undefined && t.item.email === undefined && false));
792
+ const own = targets.filter(mine);
793
+ const others = targets.filter((t) => !mine(t));
794
+ const pool = p.expected === 'deny' && p.kind === 'role' && own.length ? own.concat(others) : others.length ? others : targets;
795
+ target = pool[i % pool.length];
796
+ if (target.field !== undefined) {
797
+ const fresh = await x.itemsOf(targetOrg, target.listing, true);
798
+ const now = fresh && fresh.find((it) => it && String(it[target.field]) === String(target.value));
799
+ if (now) target = Object.assign({}, target, { item: now });
800
+ }
801
+ }
802
+ const pathNow = a.params.length ? a.template.replace('{id}', encodeURIComponent(String(target.value))) : a.template;
803
+
804
+ // what to send
805
+ let body;
806
+ let bodyItem = null;
807
+ if (!isGet) {
808
+ body = sampleBody(a);
809
+ // a body that names another record (shipmentId, order_id) is pointed at the target's organization too
810
+ const named = bodyRecord(a, body, x.getTemplates);
811
+ if (named) {
812
+ const alt = await x.targetsFor(named.like, targetOrg);
813
+ if (alt && alt.length) {
814
+ const k2 = 'body|' + targetOrg + '|' + a.template;
815
+ const j = x.rotate.get(k2) || 0;
816
+ x.rotate.set(k2, j + 1);
817
+ const pick = alt[j % alt.length];
818
+ body[named.key] = pick.value;
819
+ bodyItem = pick.item;
820
+ }
821
+ }
822
+ // A role named in the body: a refused account tries to make itself the most
823
+ // powerful one - the way rights are raised - and a control a different one.
824
+ const ranked = Object.keys(policy.roles).sort((r1, r2) => policy.roles[r2].length - policy.roles[r1].length);
825
+ const nameOf = (v) => ranked.find((r) => r.toLowerCase() === String(v).toLowerCase());
826
+ for (const k of Object.keys(body)) {
827
+ if (typeof body[k] !== 'string' || !nameOf(body[k])) continue;
828
+ const current = target.item && target.item[k] !== undefined ? String(target.item[k]).toLowerCase() : null;
829
+ const want = p.expected === 'deny' ? ranked[0] : ranked[ranked.length - 1];
830
+ const pick = ranked.find((r) => r.toLowerCase() !== current && r === want) || ranked.find((r) => r.toLowerCase() !== current);
831
+ body[k] = pick;
832
+ }
833
+ if (/^(PATCH|PUT)$/.test(a.method) && !Object.keys(body).some((k) => nameOf(body[k]))) {
834
+ const field = Object.keys(body).find((k) => typeof body[k] === 'string' && body[k].length > 2 && !/status|state|type|role|kind|currency|country|id$/i.test(k));
835
+ if (field) body[field] = body[field] + ' kx-roles';
836
+ }
837
+ }
838
+ const request = { method: a.method, path: pathNow };
839
+ if (!isGet) request.body = body;
840
+ const requestText = pathNow + ' ' + JSON.stringify(body || {});
841
+
842
+ // what the app holds now
843
+ const reader = targetOrg !== null;
844
+ const before = reader ? await x.snapshot(targetOrg) : {};
845
+ const known = await x.knownTo(actor);
846
+
847
+ // truth: the records a read would disclose
848
+ let markers = [];
849
+ let markersKnown = false;
850
+ if (isGet || p.expected === 'deny') {
851
+ if (isGet && !a.params.length) {
852
+ const found = await x.readerFor(targetOrg, a.template, a.permission, true);
853
+ if (found) {
854
+ markers = x.markersOf(found.res.json, known, requestText);
855
+ markersKnown = markers.length > 0;
856
+ }
857
+ } else if (target.item || bodyItem) {
858
+ markers = x.markersOf(target.item || bodyItem, known, requestText);
859
+ markersKnown = markers.length > 0;
860
+ }
861
+ }
862
+
863
+ const res = await actor.send(a.method, pathNow, isGet ? {} : (a.encoding === 'form' ? { form: body } : { json: body }));
864
+ const reply = authz.replyOf(res);
865
+ const foreign = actor.org && isGet ? foreignRecords(res.json, actor.org.key) : [];
866
+ const ownMarked = actor.org && isGet ? ownRecords(res.json, actor.org.key) : 0;
867
+ const found = markers.length ? authz.foundIn(res, markers).length : 0;
868
+ const after = reader ? await x.snapshot(targetOrg) : {};
869
+ const changes = x.compare(before, after);
870
+ const changed = Object.keys(before).length ? changes.length > 0 : null;
871
+
872
+ const att = Object.assign(base, {
873
+ request: request,
874
+ response: { status: res.status, location: res.location || undefined, reading: reply.kind, bodyExcerpt: authz.redact(authz.clip(res.text, EXCERPT), x.hide), keys: res.json && typeof res.json === 'object' && !Array.isArray(res.json) ? Object.keys(res.json).sort().join(',') : undefined },
875
+ target: { organization: orgName(targetOrg), record: target.value },
876
+ changes: changes.slice(0, 6), protectedPiecesSeen: found,
877
+ });
878
+ // An answer to a try that was aimed across organizations is judged for that. For any other try, another
879
+ // organization's records in the answer are a second finding, kept apart from what the role may do.
880
+ att.verdictInfo = judge({ expected: p.expected, isGet: isGet, status: res.status, reply: reply, found: found, foreign: p.kind === 'tenant' ? foreign : [], markersKnown: markersKnown || ownMarked > 0, changed: changed, kind: p.kind });
881
+ att.verdict = att.verdictInfo.verdict;
882
+ att.reason = att.verdictInfo.reason;
883
+ delete att.verdictInfo;
884
+
885
+ // put back what it changed, when it can. An accepted write whose effect no page showed is not claimed as put back.
886
+ att.restored = true;
887
+ if (!changed && !isGet && (reply.kind === 'accepted' || reply.kind === 'redirect')) att.restored = null;
888
+ if (changed) {
889
+ att.restored = false;
890
+ // An edit is put back with the values the record had before: by an account
891
+ // that may edit it, and failing that by the account that did it - the same
892
+ // missing check lets it undo it.
893
+ const original = target.item && /^(PATCH|PUT)$/.test(a.method) ? target.item : null;
894
+ if (original) {
895
+ const back = {};
896
+ for (const k of Object.keys(body || {})) if (original[k] !== undefined) back[k] = original[k];
897
+ if (Object.keys(back).length) {
898
+ const writers = x.orgs.get(targetOrg).sessions.filter((s) => holds(policy, s.role, a.permission)).concat([actor]);
899
+ for (const who of writers) {
900
+ await who.send(a.method, pathNow, a.encoding === 'form' ? { form: back } : { json: back });
901
+ const again = await x.snapshot(targetOrg);
902
+ if (x.compare(before, again).length === 0) {
903
+ att.restored = true;
904
+ break;
905
+ }
906
+ }
907
+ }
908
+ }
909
+ if (!att.restored) att.notPutBack = changes.slice(0, 3);
910
+ }
911
+ if (p.kind !== 'tenant' && foreign.length) {
912
+ const copy = Object.assign({}, att, {
913
+ kind: 'tenant', cross: true, expected: 'deny',
914
+ targetOrg: foreignName(x.orgs, foreign[0].value) || ('organization ' + foreign[0].value),
915
+ protectedPiecesSeen: foreign.length,
916
+ });
917
+ const v = judge({ expected: 'deny', isGet: true, status: res.status, reply: reply, found: 0, foreign: foreign, markersKnown: true, changed: null, kind: 'tenant' });
918
+ copy.verdict = v.verdict;
919
+ copy.reason = v.reason;
920
+ return [att, copy];
921
+ }
922
+ return att;
923
+ }
924
+
925
+ // A record's own mark of the organization it belongs to.
926
+ const ORG_KEY = /^(org|organi[sz]ation|tenant|workspace|company)[_-]?id$/i;
927
+
928
+ /** Records in an answer that carry another organization's mark: [{ key, value }]. */
929
+ function foreignRecords(json, orgKey) {
930
+ const out = [];
931
+ const walk = (v, depth) => {
932
+ if (depth > 4 || v == null || typeof v !== 'object') return;
933
+ if (Array.isArray(v)) {
934
+ for (const x of v) walk(x, depth + 1);
935
+ return;
936
+ }
937
+ for (const k of Object.keys(v)) {
938
+ if (ORG_KEY.test(k) && ['string', 'number'].includes(typeof v[k]) && String(v[k]) !== String(orgKey)) out.push({ key: k, value: v[k] });
939
+ else if (typeof v[k] === 'object') walk(v[k], depth + 1);
940
+ }
941
+ };
942
+ walk(json, 0);
943
+ return out;
944
+ }
945
+
946
+ /** How many records in an answer carry this organization's own mark. */
947
+ function ownRecords(json, orgKey) {
948
+ let n = 0;
949
+ const walk = (v, depth) => {
950
+ if (depth > 4 || v == null || typeof v !== 'object') return;
951
+ if (Array.isArray(v)) {
952
+ for (const x of v) walk(x, depth + 1);
953
+ return;
954
+ }
955
+ for (const k of Object.keys(v)) {
956
+ if (ORG_KEY.test(k) && ['string', 'number'].includes(typeof v[k]) && String(v[k]) === String(orgKey)) n++;
957
+ else if (typeof v[k] === 'object') walk(v[k], depth + 1);
958
+ }
959
+ };
960
+ walk(json, 0);
961
+ return n;
962
+ }
963
+
964
+ const foreignName = (orgs, key) => (orgs.get(String(key)) ? orgs.get(String(key)).name : null);
965
+
966
+ /** One try, judged: allowed-as-intended, denied-as-intended, confirmed-failure or ambiguous. */
967
+ function judge(j) {
968
+ const r = j.reply;
969
+ // A 400, 402, 409, 422, 429...: the app said no for a reason of its own (a field, a balance, a state) - it may never have asked who was calling.
970
+ const other = j.status >= 400 && j.status < 500 && ![401, 403, 404].includes(j.status);
971
+ if (j.foreign && j.foreign.length) {
972
+ const orgs = Array.from(new Set(j.foreign.map((x) => x.key + '=' + x.value))).slice(0, 3).join(', ');
973
+ return { verdict: V.FAILURE, reason: j.foreign.length + ' record(s) of another organization (' + orgs + ') came back in the answer (' + r.note + ')' };
974
+ }
975
+ if (j.expected === 'allow') {
976
+ if (r.kind === 'accepted' || r.kind === 'redirect') return { verdict: V.ALLOWED, reason: 'the account may, and the app took it (' + r.note + ')' };
977
+ if (r.kind === 'refused') return { verdict: V.AMBIGUOUS, reason: 'the policy lets this account do it, but the app refused (' + r.note + ') - to check, not a leak' };
978
+ return { verdict: V.AMBIGUOUS, reason: 'no clear answer (' + r.note + ')' };
979
+ }
980
+ if (j.isGet) {
981
+ if (j.found > 0) return { verdict: V.FAILURE, reason: 'records the account may not see came back: ' + j.found + ' piece(s) of them in the answer (' + r.note + ')' };
982
+ if (r.kind === 'server-error' || r.kind === 'no-answer') return { verdict: V.AMBIGUOUS, reason: 'no clear answer (' + r.note + ') - cannot tell whether anything was held back' };
983
+ if (r.kind === 'refused' && other) return { verdict: V.AMBIGUOUS, reason: 'refused with ' + j.status + ', which is an answer about the request (a field, a balance, a state), not clearly about who asked - to check' };
984
+ if (r.kind === 'refused') return { verdict: V.DENIED, reason: 'refused (' + r.note + ') and none of the protected records came back' };
985
+ if (!j.markersKnown) return { verdict: V.AMBIGUOUS, reason: 'the app answered (' + r.note + ') but there was no record of the other side to compare it with, so it cannot be said whose records came back' };
986
+ return { verdict: V.DENIED, reason: 'the answer held none of the protected records (' + r.note + ')' };
987
+ }
988
+ const info = authz.judgeWrite({ allowed: false, reply: r, changed: j.changed, leaked: j.found > 0 });
989
+ if (info.verdict === V.DENIED && other) return { verdict: V.AMBIGUOUS, reason: 'refused with ' + j.status + ', which is an answer about the request (a field, a balance, a state), not clearly about who asked - to check' };
990
+ return info;
991
+ }
992
+
993
+ // --- findings ---------------------------------------------------------------
994
+
995
+ const where = (a) => a.method + ' ' + a.template;
996
+ const roleList = (list) => (list.length ? list.join(', ') : 'no role');
997
+
998
+ /** The prompt an AI tool is given for a finding. */
999
+ function fixPrompt(f) {
1000
+ const lines = [
1001
+ 'Kryptheon signed in as different test accounts and sent the same request from each. ' + f.headline,
1002
+ '',
1003
+ 'Fix it in the server code that handles ' + f.where + ': decide who may call it from the signed-in user\'s role on the server, ' +
1004
+ 'not in the page. The permissions file (' + POLICY_FILE + ') says ' + f.type + ' is for ' + roleList(f.allowedRoles || []) + ' only.',
1005
+ ];
1006
+ if (f.kind === 'tenant') lines.push('Look the record up together with the signed-in user\'s organization (WHERE id = ? AND org_id = ?), so another organization\'s record is "not found" - for reads, edits and every sub-address of it.');
1007
+ lines.push('', 'What Kryptheon saw:', '');
1008
+ for (const p of f.proof) lines.push(p);
1009
+ return lines.join('\n');
1010
+ }
1011
+
1012
+ /** The proof lines of one try. */
1013
+ function proofOf(att) {
1014
+ const lines = ['As ' + att.actor.role + ' (' + att.actor.email + (att.actor.org ? ', organization ' + att.actor.org : '') + ')' +
1015
+ (att.cross ? ', aiming at a record of ' + att.targetOrg + (att.target.record != null ? ' (' + att.target.record + ')' : '') : (att.target.record != null ? ', on record ' + att.target.record : '')) + ':'];
1016
+ lines.push(' sent: ' + att.request.method + ' ' + att.request.path + (att.request.body && Object.keys(att.request.body).length ? ' body ' + authz.clip(JSON.stringify(att.request.body), 120) : ''));
1017
+ lines.push(' answer: ' + att.response.status + (att.response.location ? ' -> ' + att.response.location : '') + ' ' + authz.clip(att.response.bodyExcerpt, 140));
1018
+ if (att.changes && att.changes.length) {
1019
+ lines.push(' state: changed after the request (read before and after):');
1020
+ for (const c of att.changes.slice(0, 3)) lines.push(' ' + c);
1021
+ } else if (att.protectedPiecesSeen) lines.push(' state: the answer itself held ' + att.protectedPiecesSeen + ' piece(s) of records this account may not see');
1022
+ else lines.push(' state: unchanged');
1023
+ lines.push(' repeat: sign in as ' + att.actor.email + ', send ' + att.request.method + ' ' + att.request.path + (att.request.body && Object.keys(att.request.body).length ? ' with that body' : '') + ', then read the same lists as an allowed account');
1024
+ return lines;
1025
+ }
1026
+
1027
+ /** The findings of a run: one per action and account role (and one per action across organizations). */
1028
+ function findingsOf(attempts, policy) {
1029
+ const findings = [];
1030
+ const groups = new Map();
1031
+ for (const a of attempts) {
1032
+ if (a.notTried) continue;
1033
+ const proven = a.verdict === V.FAILURE;
1034
+ const hint = a.verdict === V.AMBIGUOUS && a.expected === 'deny' && a.hint;
1035
+ if (!proven && !hint) continue;
1036
+ const key = a.kind === 'tenant' ? 'tenant|' + a.method + ' ' + a.template + '|' + (proven ? 'p' : 'h') : 'role|' + a.actor.role + '|' + a.method + ' ' + a.template + '|' + (proven ? 'p' : 'h');
1037
+ if (!groups.has(key)) groups.set(key, []);
1038
+ groups.get(key).push(a);
1039
+ }
1040
+ for (const list of groups.values()) {
1041
+ const first = list[0];
1042
+ const proven = first.verdict === V.FAILURE;
1043
+ const allowed = rolesWith(policy, first.permission);
1044
+ const thing = first.method + ' ' + first.template;
1045
+ const f = {
1046
+ severity: first.kind === 'tenant' ? 'CRITICAL' : 'HIGH',
1047
+ status: proven ? 'confirmed' : 'verification required',
1048
+ where: thing,
1049
+ kind: first.kind,
1050
+ role: first.kind === 'tenant' ? undefined : first.actor.role,
1051
+ type: first.permission,
1052
+ allowedRoles: allowed,
1053
+ headline: first.kind === 'tenant'
1054
+ ? 'A user of one organization can reach another organization\'s record: ' + thing + ' answered for a record of a different organization.'
1055
+ : 'A ' + first.actor.role + ' can use ' + thing + ' (' + first.permission + '), which the policy gives only to ' + roleList(allowed) + '.',
1056
+ proof: [],
1057
+ };
1058
+ if (!proven) {
1059
+ f.severity = 'MEDIUM';
1060
+ f.headline = 'A ' + first.actor.role + ' got the same successful answer as an allowed role from ' + thing + ' (' + first.permission + ') - to check, its effect was not visible.';
1061
+ }
1062
+ for (const a of list.slice(0, 3)) f.proof.push.apply(f.proof, proofOf(a));
1063
+ if (list.length > 3) f.proof.push('... and ' + (list.length - 3) + ' more like it.');
1064
+ if (!proven) f.proof.push('Nothing the recordings read changed, so this is not proven. Check by hand what ' + thing + ' does when a ' + first.actor.role + ' calls it.');
1065
+ f.fixPrompt = fixPrompt(f);
1066
+ findings.push(f);
1067
+ }
1068
+ return findings;
1069
+ }
1070
+
1071
+ /** After the controls ran: a refusal-less answer to a forbidden action that looks exactly like an allowed account's. */
1072
+ function markHints(attempts) {
1073
+ for (const a of attempts) {
1074
+ if (a.verdict !== V.AMBIGUOUS || a.expected !== 'deny' || a.notTried || a.kind !== 'role') continue;
1075
+ if (a.response.reading !== 'accepted' && a.response.reading !== 'redirect') continue;
1076
+ const control = attempts.find((c) => c.expected === 'allow' && c.method === a.method && c.template === a.template && c.verdict === V.ALLOWED);
1077
+ if (control && control.response.status === a.response.status && control.response.keys === a.response.keys) a.hint = true;
1078
+ }
1079
+ }
1080
+
1081
+ // --- the probe-check interface (run, save, recheck, summary) ----------------
1082
+
1083
+ function load(root, env) {
1084
+ return probe.loadReport(root, 'roles', env);
1085
+ }
1086
+
1087
+ function save(root, report, env, options) {
1088
+ if (!(options && options.asIs)) carryOver(load(root, env), report);
1089
+ const file = probe.reportFile(root, 'roles', env);
1090
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1091
+ fs.writeFileSync(file, JSON.stringify(report, null, 2) + '\n', 'utf8');
1092
+ return file;
1093
+ }
1094
+
1095
+ /** Findings of an earlier press for actions this press did not try (it was stopped) stay until a re-check clears them. */
1096
+ function carryOver(previous, report) {
1097
+ if (!previous || !Array.isArray(previous.findings) || !report.stopped) return report;
1098
+ const tried = new Set((report.triedActions || []));
1099
+ for (const f of previous.findings) {
1100
+ if (tried.has(f.where)) continue;
1101
+ report.findings.push(Object.assign({}, f, { carried: f.carried || previous.endedAt || previous.startedAt }));
1102
+ }
1103
+ return report;
1104
+ }
1105
+
1106
+ /** What is checked before the person is asked: the policy. */
1107
+ function preflight(root) {
1108
+ const p = loadPolicy(root);
1109
+ if (p.ok) return { ok: true };
1110
+ return { ok: false, lines: p.missing ? missingLines() : [POLICY_FILE + ' cannot be used:'].concat(p.problems.map((x) => ' - ' + x), ['', 'Fix it, then run npx kryptheon roles again.']) };
1111
+ }
1112
+
1113
+ function emptyReport() {
1114
+ return {
1115
+ check: 'roles', startedAt: new Date().toISOString(), endedAt: null,
1116
+ stopped: false, runsPlanned: 0, runsDone: 0, flows: [], findings: [], held: [], notTested: [], testData: [], writeHosts: [], writeHostsFrom: 'page+vendor',
1117
+ attempts: [], accounts: [], triedActions: [],
1118
+ };
1119
+ }
1120
+
1121
+ /** A run's pieces put into the report the dashboard and the terminal read. */
1122
+ function assemble(report, result, policy) {
1123
+ markHints(result.attempts);
1124
+ report.attempts = result.attempts;
1125
+ report.accounts = result.accounts;
1126
+ report.requests = result.requests;
1127
+ report.runsPlanned += result.planned || 0;
1128
+ report.runsDone += result.attempts.length;
1129
+ report.triedActions = Array.from(new Set(result.attempts.filter((a) => !a.notTried).map((a) => where(a))));
1130
+ report.findings = report.findings.concat(findingsOf(result.attempts, policy));
1131
+ // held: what was refused and what was allowed, said once per action
1132
+ const byAction = new Map();
1133
+ for (const a of result.attempts) {
1134
+ if (a.notTried) continue;
1135
+ const k = where(a) + '|' + a.kind;
1136
+ if (!byAction.has(k)) byAction.set(k, { held: [], allowed: [], open: [] });
1137
+ const g = byAction.get(k);
1138
+ if (a.verdict === V.DENIED) g.held.push(a.actor.role + ' (' + a.response.status + (a.response.reading === 'accepted' ? ', answered without the protected records' : '') + ')');
1139
+ else if (a.verdict === V.ALLOWED) g.allowed.push(a.actor.role);
1140
+ else if (a.verdict === V.AMBIGUOUS) g.open.push(a);
1141
+ }
1142
+ for (const [k, g] of byAction) {
1143
+ const [w, kind] = k.split('|');
1144
+ if (g.held.length) report.held.push({ kind: kind, where: w, step: w, why: (kind === 'tenant' ? 'across organizations, ' : '') + 'held: ' + Array.from(new Set(g.held)).join(', ') });
1145
+ for (const o of g.open) report.notTested.push({ kind: 'ambiguous', where: w, step: w, why: o.actor.role + (o.cross ? ' (across organizations)' : '') + ': ' + o.reason });
1146
+ }
1147
+ for (const a of result.attempts) {
1148
+ if (a.notTried) report.notTested.push({ kind: 'ambiguous', where: a.method + ' ' + a.template, step: a.method + ' ' + a.template, why: a.actor.role + ': ' + a.reason });
1149
+ else if (a.response.reading === 'accepted' || a.response.reading === 'redirect') {
1150
+ if (a.method !== 'GET') report.testData.push({ flow: 'roles', value: a.actor.role + (a.expected === 'allow' ? ' (allowed)' : ' (should have been refused)') + (a.restored === true ? ', put back' : a.restored === null ? ', its effect was not visible so nothing was put back' : ', not put back'), request: a.method + ' ' + a.request.path + ' -> ' + a.response.status });
1151
+ }
1152
+ }
1153
+ for (const s of result.skipped) report.notTested.push({ kind: 'note', where: s.what, step: s.what, why: s.why });
1154
+ for (const n of result.notes) report.notTested.push({ kind: 'note', where: 'roles', step: 'roles', why: n });
1155
+ return report;
1156
+ }
1157
+
1158
+ /**
1159
+ * The whole check: the policy, the recordings replayed once to learn the
1160
+ * app's requests, every account signed in, every action tried. Same shape as
1161
+ * the other probe checks (edge, reliability).
1162
+ */
1163
+ async function run(root, flows, options) {
1164
+ const opts = options || {};
1165
+ const say = typeof opts.say === 'function' ? opts.say : () => {};
1166
+ let stopped = false;
1167
+ let current = null;
1168
+ const control = {
1169
+ stop() {
1170
+ stopped = true;
1171
+ if (current && typeof current.stop === 'function') current.stop();
1172
+ },
1173
+ };
1174
+ if (typeof opts.onControl === 'function') opts.onControl(control);
1175
+ const report = emptyReport();
1176
+ const finish = (why) => {
1177
+ if (why) report.flows.push({ title: 'Roles and tenants', file: POLICY_FILE, state: 'not tested', why: why });
1178
+ report.stopped = stopped;
1179
+ report.endedAt = new Date().toISOString();
1180
+ return report;
1181
+ };
1182
+
1183
+ const pol = loadPolicy(root);
1184
+ if (!pol.ok) return finish(pol.missing ? POLICY_FILE + ' is not in this folder - write it first (it says who may do what), then press again' : POLICY_FILE + ' cannot be used: ' + pol.problems.join(' '));
1185
+
1186
+ say('Replaying ' + flows.length + (flows.length === 1 ? ' recording' : ' recordings') + ' once, to learn the requests your app makes...');
1187
+ const journey = opts.journey || await (opts.capture || captureJourney)(root, flows, { say: say, gapMs: opts.gapMs, env: opts.env, hide: opts.hide, onHandle: (h) => (current = h) });
1188
+ current = null;
1189
+ report.runsDone += journey.runs || 0;
1190
+ report.runsPlanned += journey.runs || 0;
1191
+ for (const f of journey.flows) report.flows.push(f);
1192
+ report.journey = { origin: journey.origin, signIn: journey.signIn, accounts: journey.accounts, actions: journey.actions.map((a) => ({ method: a.method, template: a.template, path: a.path, params: a.params, segs: a.segs, by: a.by, data: a.data, encoding: a.encoding, flow: a.flow })) };
1193
+ if (stopped) return finish();
1194
+ if (!journey.origin || !journey.signIn) return finish('no recording signs in through a request this check can repeat, so there was nothing to sign in with');
1195
+ if (probe.liveLooking([journey.origin]).length || (() => { try { authz.assertLocalTarget(journey.origin); return false; } catch (err) { return true; } })()) {
1196
+ return finish('your app is at ' + journey.origin + ', which is not this computer. This check tries things that must be refused, so it runs only against an app on this computer (localhost or 127.0.0.1)');
1197
+ }
1198
+ report.writeHosts = [journey.origin];
1199
+
1200
+ const accounts = accountsFor(journey, root, opts.secrets);
1201
+ for (const l of accounts.left) report.notTested.push({ kind: 'note', where: l.email, step: l.email, why: l.why });
1202
+ if (accounts.usable.length < 2) return finish('fewer than two accounts have a password in .env, so there is nothing to compare. The recordings sign in as: ' + (journey.accounts.map((a) => a.email).join(', ') || 'nobody'));
1203
+
1204
+ say('Signing in as ' + accounts.usable.length + ' accounts, and trying ' + journey.actions.length + ' recorded actions as each...');
1205
+ const result = await checkAccess({ origin: journey.origin, policy: pol.policy, journey: journey, accounts: accounts.usable, fetch: opts.fetch, say: say, stopped: () => stopped, maxAttempts: opts.maxAttempts });
1206
+ assemble(report, result, pol.policy);
1207
+ report.policy = { file: POLICY_FILE, tenants: pol.policy.tenants, roles: Object.keys(pol.policy.roles) };
1208
+ if (result.attempts.length) report.flows.push({ title: 'Roles and tenants', file: POLICY_FILE, state: 'tested' });
1209
+ else report.flows.push({ title: 'Roles and tenants', file: POLICY_FILE, state: 'not tested', why: (result.skipped[0] && result.skipped[0].why) || 'nothing could be tried' });
1210
+ return finish();
1211
+ }
1212
+
1213
+ const keyOf = (f) => f.where + '|' + f.kind;
1214
+
1215
+ /**
1216
+ * Re-checks one finding: the same action tried again as every account. The
1217
+ * recorded requests are the ones the last press learned, so no browser run is
1218
+ * needed. Fixed only when the action no longer fails for anyone.
1219
+ */
1220
+ async function recheck(root, flows, finding, options) {
1221
+ const opts = options || {};
1222
+ const say = typeof opts.say === 'function' ? opts.say : () => {};
1223
+ const unsure = (why) => ({ verdict: 'could not confirm', why: why, newProblems: [], testData: [] });
1224
+ let stopped = false;
1225
+ if (typeof opts.onControl === 'function') opts.onControl({ stop() { stopped = true; } });
1226
+ const pol = loadPolicy(root);
1227
+ if (!pol.ok) return unsure(POLICY_FILE + ' cannot be used now');
1228
+ const last = load(root, opts.env);
1229
+ if (!last || !last.journey) return unsure('there is no earlier press to take the recorded requests from - press Roles and tenants again');
1230
+ const journey = Object.assign({}, last.journey, { actions: last.journey.actions.slice(), accounts: last.journey.accounts, signIn: last.journey.signIn });
1231
+ if (!journey.origin || (() => { try { authz.assertLocalTarget(journey.origin); return false; } catch (err) { return true; } })()) return unsure('the app is not on this computer');
1232
+ const accounts = accountsFor(journey, root, opts.secrets);
1233
+ if (accounts.usable.length < 2) return unsure('fewer than two accounts have a password in .env');
1234
+ const result = await checkAccess({
1235
+ origin: journey.origin, policy: pol.policy, journey: journey, accounts: accounts.usable, fetch: opts.fetch, say: say, stopped: () => stopped,
1236
+ only: (p) => where(p.action) === finding.where,
1237
+ });
1238
+ if (stopped) return unsure('it was stopped before it finished');
1239
+ const tried = result.attempts.filter((a) => !a.notTried);
1240
+ if (!tried.length) return unsure((result.skipped[0] && result.skipped[0].why) || 'that action could not be tried now');
1241
+ markHints(result.attempts);
1242
+ const fresh = findingsOf(result.attempts, pol.policy);
1243
+ const same = fresh.find((f) => keyOf(f) === keyOf(finding) && f.role === finding.role && f.status === 'confirmed');
1244
+ const unclear = tried.filter((a) => a.expected === 'deny' && a.verdict === V.AMBIGUOUS && a.kind === finding.kind && (finding.kind === 'tenant' || a.actor.role === finding.role));
1245
+ const saved = load(root, opts.env);
1246
+ let verdict;
1247
+ if (same) verdict = { verdict: 'still open', why: same.proof.slice(0, 4).join(' / '), newProblems: [] };
1248
+ else if (unclear.length) verdict = unsure(unclear[0].reason);
1249
+ else {
1250
+ verdict = { verdict: 'fixed', why: 'every account that must be refused was refused, nothing changed, and the accounts that may do it still can', newProblems: [] };
1251
+ if (saved) {
1252
+ saved.findings = saved.findings.filter((f) => !(keyOf(f) === keyOf(finding) && f.role === finding.role));
1253
+ save(root, saved, opts.env, { asIs: true });
1254
+ }
1255
+ }
1256
+ verdict.testData = result.attempts.filter((a) => a.method !== 'GET' && (a.response.reading === 'accepted' || a.response.reading === 'redirect')).map((a) => ({ flow: 'roles', value: a.actor.role, request: a.method + ' ' + a.request.path + ' -> ' + a.response.status }));
1257
+ return verdict;
1258
+ }
1259
+
1260
+ /** What is said when it ends, in the terminal and on the page. */
1261
+ function summaryLines(report) {
1262
+ const lines = [''];
1263
+ const problems = report.findings.filter((f) => f.status === 'confirmed');
1264
+ const toCheck = report.findings.filter((f) => f.status !== 'confirmed');
1265
+ const tried = (report.attempts || []).filter((a) => !a.notTried);
1266
+ if (report.stopped) lines.push('Stopped after ' + report.runsDone + ' of ' + report.runsPlanned + ' runs. What did not run was NOT tested.');
1267
+ lines.push(problems.length ? problems.length + (problems.length === 1 ? ' problem' : ' problems') + ' found:'
1268
+ : tried.length ? 'No problem proven in what was tried.' : 'Nothing was tested - see why below.');
1269
+ for (const f of report.findings) {
1270
+ lines.push('');
1271
+ lines.push(' ' + f.severity + (f.status === 'confirmed' ? '' : ' (to check)') + ' ' + f.headline);
1272
+ for (const p of f.proof) lines.push(' ' + p);
1273
+ }
1274
+ if (toCheck.length && !problems.length) lines.push('', toCheck.length + (toCheck.length === 1 ? ' thing' : ' things') + ' to check above - not proven problems.');
1275
+ if (tried.length) {
1276
+ const c = { allowed: 0, denied: 0, failure: 0, ambiguous: 0 };
1277
+ for (const a of tried) c[a.verdict === V.ALLOWED ? 'allowed' : a.verdict === V.DENIED ? 'denied' : a.verdict === V.FAILURE ? 'failure' : 'ambiguous']++;
1278
+ lines.push('', tried.length + ' tries: ' + c.allowed + ' allowed as intended, ' + c.denied + ' refused as intended, ' + c.failure + ' confirmed failures, ' + c.ambiguous + ' unclear.');
1279
+ }
1280
+ if (report.accounts && report.accounts.length) lines.push('Accounts: ' + report.accounts.map((a) => a.role + (a.org ? ' @ ' + a.org : '')).join(', '));
1281
+ if (report.held.length) {
1282
+ lines.push('', 'Held (' + report.held.length + '):');
1283
+ for (const h of report.held.slice(0, 25)) lines.push(' ' + h.where + ' - ' + h.why);
1284
+ if (report.held.length > 25) lines.push(' ... and ' + (report.held.length - 25) + ' more');
1285
+ }
1286
+ const skipped = report.flows.filter((f) => f.state !== 'tested');
1287
+ if (report.notTested.length || skipped.length) {
1288
+ lines.push('', 'NOT tested / unclear:');
1289
+ for (const f of skipped) lines.push(' ' + f.title + ' - ' + f.why);
1290
+ for (const x of report.notTested.slice(0, 40)) lines.push(' ' + x.where + ' - ' + x.why);
1291
+ if (report.notTested.length > 40) lines.push(' ... and ' + (report.notTested.length - 40) + ' more');
1292
+ }
1293
+ if (report.testData.length) {
1294
+ lines.push('', 'Test data left in your app: ' + report.testData.length + (report.testData.length === 1 ? ' write was' : ' writes were') + ' accepted.');
1295
+ lines.push('Kryptheon puts back what it can (edits); creates and actions stay. The writes:');
1296
+ for (const t of report.testData.slice(0, 15)) lines.push(' ' + t.request + ' (' + t.value + ')');
1297
+ if (report.testData.length > 15) lines.push(' ... and ' + (report.testData.length - 15) + ' more');
1298
+ }
1299
+ lines.push('');
1300
+ return lines;
1301
+ }
1302
+
1303
+ module.exports = {
1304
+ POLICY_FILE: POLICY_FILE,
1305
+ WHAT: WHAT,
1306
+ WORDS: WORDS,
1307
+ LOCAL_ONLY: LOCAL_ONLY,
1308
+ NONE: NONE,
1309
+ loadPolicy: loadPolicy,
1310
+ checkPolicy: checkPolicy,
1311
+ holds: holds,
1312
+ rolesWith: rolesWith,
1313
+ templateText: templateText,
1314
+ missingLines: missingLines,
1315
+ parsePath: parsePath,
1316
+ permissionFor: permissionFor,
1317
+ journeyFromRuns: journeyFromRuns,
1318
+ captureJourney: captureJourney,
1319
+ accountsFor: accountsFor,
1320
+ checkAccess: checkAccess,
1321
+ judge: judge,
1322
+ findingsOf: findingsOf,
1323
+ markHints: markHints,
1324
+ fixPrompt: fixPrompt,
1325
+ preflight: preflight,
1326
+ run: run,
1327
+ recheck: recheck,
1328
+ save: save,
1329
+ load: load,
1330
+ summaryLines: summaryLines,
1331
+ knownAddresses: probe.knownAddresses,
1332
+ };