kryptheon 0.1.63 → 0.1.65

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.
@@ -39,6 +39,11 @@ const VERDICT = {
39
39
  const KINDS = ['roleChange', 'workOrderRead', 'finance', 'workOrderModify', 'job'];
40
40
  const LOCAL_HOSTS = ['localhost', '127.0.0.1', '[::1]', '::1'];
41
41
  const MAX_REQUESTS = 600;
42
+ const REQUEST_LIMIT = 'KRYPTHEON_REQUEST_LIMIT';
43
+ /** Did a check stop because it reached its request limit (and not because something broke)? */
44
+ function isRequestLimit(err) {
45
+ return !!err && err.code === REQUEST_LIMIT;
46
+ }
42
47
  const MAX_TEXT = 300000;
43
48
  const EXCERPT = 240;
44
49
 
@@ -290,6 +295,72 @@ function foundIn(res, markers) {
290
295
  return found;
291
296
  }
292
297
 
298
+ // A record's own id: the key that tells one record from another.
299
+ const OWN_ID_KEY = /^(id|_id|uuid|guid)$/i;
300
+
301
+ /** The records (plain objects with an id of their own) in a value, innermost last: [{ id, record }]. */
302
+ function idRecordsOf(value, depth, out) {
303
+ const into = out || [];
304
+ const d = depth || 0;
305
+ if (d > 6 || value == null || typeof value !== 'object') return into;
306
+ if (Array.isArray(value)) {
307
+ value.forEach((x) => idRecordsOf(x, d + 1, into));
308
+ return into;
309
+ }
310
+ const key = Object.keys(value).find((k) => OWN_ID_KEY.test(k) && ['string', 'number'].includes(typeof value[k]));
311
+ if (key !== undefined) into.push({ id: String(value[key]), record: value });
312
+ Object.keys(value).forEach((k) => idRecordsOf(value[k], d + 1, into));
313
+ return into;
314
+ }
315
+
316
+ /** The innermost record with an id of its own that holds this string as one of its values, for each place it is held. */
317
+ function holdersOf(records, marker) {
318
+ const all = records.filter((r) => stringsOf(r.record, 1).includes(marker));
319
+ const held = new Set(all.map((r) => r.record));
320
+ // innermost: a holder none of whose nested records also holds it
321
+ return all.filter((r) => !idRecordsOf(r.record).some((n) => n.record !== r.record && held.has(n.record)));
322
+ }
323
+
324
+ /**
325
+ * The markers that came back only as a value shared by two records - one the
326
+ * caller's own, one the other organization's: every record of the answer that
327
+ * holds it has an id of its own, and none of those ids is one of the other
328
+ * organization's records (round 30: both organizations had an integration of
329
+ * the same name; a list scoped right held only the caller's own). Such a value
330
+ * proves nothing. A marker held anywhere else in the answer, or by a record
331
+ * carrying the other organization's id, still counts.
332
+ */
333
+ function sharedOnly(answerJson, theirsJson, markers) {
334
+ if (answerJson === undefined || answerJson === null || typeof answerJson !== 'object') return [];
335
+ const answer = idRecordsOf(answerJson);
336
+ const theirIds = new Set(idRecordsOf(theirsJson).map((r) => r.id));
337
+ if (!answer.length || !theirIds.size) return [];
338
+ // the fields a string is held at, in a record of its own (not in its nested records)
339
+ const keysOf = (record, m) => Object.keys(record).filter((k) => record[k] === m || (Array.isArray(record[k]) && record[k].includes(m)));
340
+ const theirRecords = idRecordsOf(theirsJson);
341
+ const out = [];
342
+ for (const m of markers) {
343
+ // an email is a person's, never a name two records happen to share
344
+ if (/@/.test(m)) continue;
345
+ const holders = holdersOf(answer, m);
346
+ if (!holders.length || holders.some((h) => theirIds.has(h.id))) continue;
347
+ // held as the same field by the other organization's record (both are "name"): the same kind of value, not theirs
348
+ const theirKeys = new Set([].concat.apply([], holdersOf(theirRecords, m).map((t) => keysOf(t.record, m))));
349
+ if (!holders.every((h) => keysOf(h.record, m).some((k) => theirKeys.has(k)))) continue;
350
+ // and nowhere else: with those records taken out, the answer no longer holds it
351
+ const rest = (function strip(v, depth) {
352
+ if (depth > 6 || v == null || typeof v !== 'object') return v;
353
+ if (Array.isArray(v)) return v.filter((x) => !holders.some((h) => h.record === x)).map((x) => strip(x, depth + 1));
354
+ if (holders.some((h) => h.record === v)) return null;
355
+ const o = {};
356
+ for (const k of Object.keys(v)) o[k] = strip(v[k], depth + 1);
357
+ return o;
358
+ })(answerJson, 0);
359
+ if (!stringsOf(rest, 1).includes(m) && !JSON.stringify(rest).includes(m)) out.push(m);
360
+ }
361
+ return out;
362
+ }
363
+
293
364
  // --- judging --------------------------------------------------------------
294
365
 
295
366
  /**
@@ -372,12 +443,21 @@ function makeContext(options) {
372
443
  const origin = assertLocalTarget(options.baseUrl, options.allowOrigins);
373
444
  const fetchImpl = options.fetch || globalThis.fetch;
374
445
  const secrets = Object.values(options.passwords || {}).filter(Boolean);
375
- const ctx = { origin: origin, requests: 0, secrets: secrets };
446
+ // ctx.limit can be raised by a check that knows how big the app is (runSteps); it never goes away.
447
+ const ctx = { origin: origin, requests: 0, secrets: secrets, limit: options.maxRequests || MAX_REQUESTS };
376
448
  ctx.request = async function (session, method, p, opts) {
377
449
  method = String(method).toUpperCase();
378
450
  if (method === 'DELETE') throw new Error('authz: this check never deletes anything');
379
451
  if (String(p).startsWith('//') || /^[a-z]+:/i.test(String(p))) throw new Error('authz: refused a request to "' + p + '" - paths only, on the allowed origin');
380
- if (++ctx.requests > (options.maxRequests || MAX_REQUESTS)) throw new Error('authz: stopped - more than ' + (options.maxRequests || MAX_REQUESTS) + ' requests in one run');
452
+ if (ctx.requests + 1 > ctx.limit) {
453
+ // A stop, not a crash: the caller keeps what it found so far and says it stopped (blind round 32,
454
+ // where this error ended the whole API check with a stack trace and no report).
455
+ const stop = new Error('authz: stopped - more than ' + ctx.limit + ' requests in one run');
456
+ stop.code = REQUEST_LIMIT;
457
+ stop.limit = ctx.limit;
458
+ throw stop;
459
+ }
460
+ ctx.requests++;
381
461
  const url = new URL(p, origin);
382
462
  if (url.origin !== origin) throw new Error('authz: refused a request to another origin');
383
463
  const headers = { accept: 'application/json, text/html;q=0.8' };
@@ -812,12 +892,14 @@ module.exports = {
812
892
  journeyFromHar: journeyFromHar,
813
893
  discover: discover,
814
894
  replyOf: replyOf,
895
+ sharedOnly: sharedOnly,
815
896
  judgeRead: judgeRead,
816
897
  judgeWrite: judgeWrite,
817
898
  runAuthz: runAuthz,
818
899
  reportLines: reportLines,
819
900
  // Used by kryptheon-roles.js, which tries the same thing for any app.
820
901
  makeContext: makeContext,
902
+ isRequestLimit: isRequestLimit,
821
903
  makeSession: makeSession,
822
904
  stringsOf: stringsOf,
823
905
  identifierLike: identifierLike,
@@ -103,6 +103,7 @@
103
103
  function setBusy(on) {
104
104
  busy = on;
105
105
  Array.prototype.forEach.call(document.querySelectorAll('[data-action]'), function (b) { b.disabled = on; });
106
+ if (state) renderLaunch();
106
107
  }
107
108
  // The clipboard, and when a browser refuses it, the older way: the text
108
109
  // put in a box off the screen, selected and copied.
@@ -1287,15 +1288,65 @@
1287
1288
  // page's own reloads while the box is open.
1288
1289
  var everyOpen = false;
1289
1290
  var everyTicked = false;
1290
- byId('runAll').addEventListener('click', function () {
1291
+ function openEvery() {
1291
1292
  if (!state || !state.everything) return;
1292
1293
  var plan = state.everything;
1293
1294
  if (!plan.steps.length) { toast('Nothing can run from here yet' + (plan.skipped[0] ? ' - ' + plan.skipped[0].label + ': ' + plan.skipped[0].why : '')); return; }
1294
1295
  everyOpen = true;
1295
1296
  everyTicked = false;
1296
1297
  renderEvery();
1297
- byId('everyBox').scrollIntoView({ block: 'nearest' });
1298
- });
1298
+ byId('everyBox').scrollIntoView({ block: 'start', behavior: 'smooth' });
1299
+ }
1300
+ byId('runAll').addEventListener('click', openEvery);
1301
+
1302
+ // The same press, made to be seen first on the dashboard: what one press
1303
+ // runs, as chips, and what it leaves out, dimmed.
1304
+ function renderLaunch() {
1305
+ var box = byId('launch');
1306
+ if (!box || !state || !state.everything) return;
1307
+ var plan = state.everything;
1308
+ clear(box);
1309
+ var text = el('div');
1310
+ var eyebrow = el('div', 'eyebrow');
1311
+ eyebrow.appendChild(el('span', 'live-dot'));
1312
+ eyebrow.appendChild(document.createTextNode('One press - every check'));
1313
+ text.appendChild(eyebrow);
1314
+ var h = el('h2');
1315
+ h.appendChild(document.createTextNode('Check my '));
1316
+ h.appendChild(el('em', null, 'whole app'));
1317
+ text.appendChild(h);
1318
+ text.appendChild(el('p', null, plan.steps.length
1319
+ ? plural(plan.steps.length, 'check') + ' run one after another while you wait. You say yes once; Kryptheon never deletes anything, and every problem comes with its proof and a prompt to fix it.'
1320
+ : 'Nothing can run from here yet' + (plan.skipped[0] ? ': ' + plan.skipped[0].why : '') + '.'));
1321
+ var chips = el('ul', 'launch-steps');
1322
+ plan.steps.forEach(function (s, i) {
1323
+ var li = el('li');
1324
+ li.appendChild(el('b', null, (i < 9 ? '0' : '') + (i + 1)));
1325
+ li.appendChild(document.createTextNode(s.label));
1326
+ chips.appendChild(li);
1327
+ });
1328
+ plan.skipped.forEach(function (s) {
1329
+ var li = el('li', 'out', s.label);
1330
+ li.title = s.why;
1331
+ chips.appendChild(li);
1332
+ });
1333
+ text.appendChild(chips);
1334
+ box.appendChild(text);
1335
+ var go = el('div', 'launch-go');
1336
+ var b = el('button', 'btn go');
1337
+ b.type = 'button';
1338
+ b.setAttribute('data-action', 'everything');
1339
+ b.appendChild(icon('play', 18));
1340
+ b.appendChild(el('span', null, busy ? 'Checking...' : 'Check my app'));
1341
+ var arrow = icon('arrow', 18);
1342
+ arrow.setAttribute('class', 'go-arrow');
1343
+ b.appendChild(arrow);
1344
+ b.disabled = busy || !plan.steps.length;
1345
+ b.addEventListener('click', openEvery);
1346
+ go.appendChild(b);
1347
+ go.appendChild(el('div', 'launch-note', busy ? 'Running - follow it below' : plan.addsData ? 'Asks before adding test data' : 'Reads only'));
1348
+ box.appendChild(go);
1349
+ }
1299
1350
  function startEvery() {
1300
1351
  var plan = state.everything;
1301
1352
  everyOpen = false;
@@ -1357,6 +1408,7 @@
1357
1408
  var run = byId('runAll');
1358
1409
  if (!busy) { clear(run); run.appendChild(icon('play', 15)); run.appendChild(el('span', null, 'Check my app')); }
1359
1410
  renderEvery();
1411
+ renderLaunch();
1360
1412
  }
1361
1413
 
1362
1414
  /* ------------------------------ your app ------------------------------ */
@@ -318,6 +318,28 @@
318
318
  .every-why, .every-out li { color: var(--muted); }
319
319
  .every-out { font-size: 13px; line-height: 1.5; }
320
320
  .every-out ul { margin: 6px 0 0; padding-left: 18px; display: grid; gap: 3px; }
321
+ /* --- Check my app: the one press, made to be seen -------------------- */
322
+ .launch { position: relative; overflow: hidden; display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 28px 40px; margin-bottom: 28px; padding: 38px 36px 40px; color: var(--on-dark); background: radial-gradient(90% 160% at 100% 0%, rgba(255, 77, 0, 0.34), rgba(255, 77, 0, 0) 60%), var(--ink); border-left: 3px solid var(--orange); }
323
+ .launch::after { content: ""; position: absolute; left: 0; top: 0; width: 34%; height: 2px; background: linear-gradient(90deg, rgba(255, 77, 0, 0), var(--orange), rgba(255, 77, 0, 0)); animation: sweep 3.6s var(--ease) infinite; }
324
+ @keyframes sweep { from { transform: translateX(-100%); } to { transform: translateX(300%); } }
325
+ .launch .eyebrow { display: flex; align-items: center; gap: 10px; font-size: 10px; color: var(--orange); }
326
+ .launch h2 { margin-top: 12px; color: var(--white); font-size: clamp(2.4rem, 5.4vw, 4.2rem); }
327
+ .launch h2 em { font-style: normal; color: var(--orange); }
328
+ .launch p { max-width: 60ch; margin: 14px 0 0; font-size: 15px; line-height: 1.6; color: rgba(233, 237, 242, 0.72); }
329
+ .launch-steps { display: flex; flex-wrap: wrap; gap: 6px; margin: 18px 0 0; padding: 0; list-style: none; }
330
+ .launch-steps li { padding: 6px 10px; font: 10px/1.2 var(--mono); letter-spacing: 0.06em; text-transform: uppercase; color: var(--on-dark); border: 1px solid var(--line-dark); background: rgba(233, 237, 242, 0.04); }
331
+ .launch-steps li b { margin-right: 6px; color: var(--orange); font-weight: 400; }
332
+ .launch-steps li.out { color: rgba(233, 237, 242, 0.4); border-style: dashed; }
333
+ .launch-go { display: grid; justify-items: center; gap: 10px; }
334
+ .btn.go { height: 68px; padding: 0 34px; gap: 12px; font-size: 13px; letter-spacing: 0.1em; color: var(--white); background: var(--orange); border-color: var(--orange); animation: ring 2.4s var(--ease) infinite; }
335
+ .btn.go:hover:not(:disabled) { color: var(--white); background: var(--orange-deep); border-color: var(--orange-deep); }
336
+ .btn.go .go-arrow { transition: transform 0.3s var(--ease); }
337
+ .btn.go:hover:not(:disabled) .go-arrow { transform: translateX(5px); }
338
+ .btn.go:disabled, #runAll:disabled { animation: none; }
339
+ .launch-note { font: 10px var(--mono); letter-spacing: 0.06em; color: rgba(233, 237, 242, 0.5); text-transform: uppercase; }
340
+ #runAll { animation: ring 2.4s var(--ease) infinite; }
341
+ @keyframes ring { 0% { box-shadow: 0 0 0 0 rgba(255, 77, 0, 0.55); } 70% { box-shadow: 0 0 0 16px rgba(255, 77, 0, 0); } 100% { box-shadow: 0 0 0 0 rgba(255, 77, 0, 0); } }
342
+ @media (max-width: 760px) { .launch { grid-template-columns: 1fr; padding: 28px 20px 30px; } .launch-go { justify-items: stretch; } .btn.go { width: 100%; } }
321
343
  .act { display: inline-flex; flex-direction: column; align-items: flex-start; gap: 4px; }
322
344
  .act .btn, .step .act .btn { margin-top: 0; }
323
345
  .step .act { margin-top: 14px; }
@@ -378,6 +400,7 @@
378
400
  <section class="job" id="job" hidden aria-live="polite"></section>
379
401
 
380
402
  <section class="view" id="view-dashboard">
403
+ <div class="launch" id="launch"></div>
381
404
  <div class="card app-card" id="appCard">
382
405
  <div class="card-head"><div><h3>Your app</h3><div class="c-sub">What this dashboard checks</div></div></div>
383
406
  <div id="appBox"></div>
@@ -614,6 +614,30 @@ function movingStep(root, t) {
614
614
  return { line: line, selector: hit.selector, why: reason.why + (reason.kind === 'number' ? ' that can change as data is added' : '') };
615
615
  }
616
616
 
617
+ /**
618
+ * For night's "to verify" finding (rows that may name another organization's record): the routes of the app that
619
+ * write those tables, from the last API run, said as tried across organizations or NOT tried - with why. Lines.
620
+ */
621
+ function tenantRoutesLines(f, apiLast) {
622
+ const tables = [];
623
+ for (const m of f.members || []) if (m.table && !tables.includes(m.table)) tables.push(m.table);
624
+ if (!apiLast || !apiLast.ran) {
625
+ return ['The API check has not run on this app, so no route that writes ' + (tables.length === 1 ? tables[0] : 'these tables') + ' has been tried across organizations. Run it (Check my app) to know whether your app lets one through.'];
626
+ }
627
+ const routes = (apiLast.writes || []).filter((w) => (w.tables || []).some((t) => tables.includes(t)));
628
+ if (!routes.length) return ['The last API check found no route that writes ' + (tables.length === 1 ? tables[0] : 'these tables') + ' to try.'];
629
+ const tried = routes.filter((w) => w.acrossOrgs === 'tried');
630
+ const not = routes.filter((w) => w.acrossOrgs !== 'tried');
631
+ const out = ['Routes that write these tables (last API check, ' + String(apiLast.checkedAt || '').slice(0, 10) + '):'];
632
+ if (tried.length) out.push('Tried across organizations: ' + tried.map((w) => w.route).join(', ') + '. A route that let one through is its own finding above.');
633
+ if (not.length) {
634
+ out.push('NOT tried across organizations, so not known: ' + not.length + ' route' + (not.length === 1 ? '' : 's') + ':');
635
+ for (const w of not.slice(0, 12)) out.push('- ' + w.route + (w.why ? ' (' + w.why + ')' : ''));
636
+ if (not.length > 12) out.push('- and ' + (not.length - 12) + ' more');
637
+ }
638
+ return out;
639
+ }
640
+
617
641
  function buildState(root, env) {
618
642
  const paths = store.pathsFor(root, env);
619
643
  const config = readConfig(paths);
@@ -808,6 +832,10 @@ function buildState(root, env) {
808
832
  }
809
833
  if (night && config.enabled.data) {
810
834
  for (const f of night.findings || []) {
835
+ // A row the database lets name another organization's record is "to verify": say which routes that write
836
+ // those tables the API check tried across organizations, and which it did NOT - never more than what ran.
837
+ let detail = f.body || '';
838
+ if (f.kind === 'tenantparents') detail += (detail ? '\n\n' : '') + tenantRoutesLines(f, apiLast).join('\n');
811
839
  findings.push({
812
840
  check: 'data',
813
841
  severity: f.severity,
@@ -816,7 +844,7 @@ function buildState(root, env) {
816
844
  confidence: (f.status || 'confirmed') === 'confirmed' ? 'high' : 'medium',
817
845
  where: f.table + (f.column ? '.' + f.column : ''),
818
846
  headline: f.headline,
819
- detail: f.body || '',
847
+ detail: detail,
820
848
  fixPrompt: f.fixPrompt || '',
821
849
  when: nightWhen,
822
850
  });
@@ -1535,6 +1563,7 @@ function createServer(root, options) {
1535
1563
  }
1536
1564
 
1537
1565
  module.exports = {
1566
+ tenantRoutesLines: tenantRoutesLines,
1538
1567
  CHECKS: CHECKS,
1539
1568
  everythingPlan: everythingPlan,
1540
1569
  localOrigin: localOrigin,
package/kryptheon-keys.js CHANGED
@@ -118,6 +118,11 @@ function looksLikeNamedSecret(name, value) {
118
118
  return (value.match(/[0-9]/g) || []).length >= 3 && (value.match(/[A-Za-z]/g) || []).length >= 3;
119
119
  }
120
120
 
121
+ // <prefix>_live_<random> / _secret_ / _prod_: how providers mark a live secret key. Quoted, so a word in a
122
+ // sentence is never one.
123
+ const SHAPED_SECRET = /(["'`])([a-z][a-z0-9]{0,11}_(?:live|secret|prod|private|priv)_[A-Za-z0-9_-]{12,})\1/g;
124
+ const PUBLISHABLE_PREFIX = /^(pk|pub|publishable|public|anon|client)_/i;
125
+
121
126
  /** First characters and length - enough to find it, too little to use it. */
122
127
  function masked(value) {
123
128
  return value.slice(0, 6) + '... (' + value.length + ' characters, not shown)';
@@ -326,6 +331,25 @@ function secretsIn(rel, source, loadedBy) {
326
331
  }, 'medium');
327
332
  }
328
333
 
334
+ // A value shaped like a vendor's live secret key whose vendor is not one I know: <prefix>_live_<random>,
335
+ // _secret_, _prod_ (blind round 32: 'nsk_live_demo_31_7KQ9P2X8' in a browser bundle, under a name that
336
+ // said nothing). Publishable prefixes are public by design and left alone; so are tests.
337
+ SHAPED_SECRET.lastIndex = 0;
338
+ let k;
339
+ while (!inTest && (k = SHAPED_SECRET.exec(source))) {
340
+ const value = k[2];
341
+ if (PUBLISHABLE_PREFIX.test(value) || /your|example|placeholder|changeme|x{4,}|<|\$\{/i.test(value)) continue;
342
+ if ((value.match(/[0-9]/g) || []).length < 2) continue;
343
+ add(k.index + k[0].indexOf(value), value, {
344
+ label: 'key-shaped value ("' + value.split('_').slice(0, 2).join('_') + '_...")',
345
+ opens: 'It is written the way a provider writes a live secret key, and anyone who opens your site can read it. ' +
346
+ 'Its provider is not one I know, so check whether it is a real key.',
347
+ rotate: 'wherever it was issued, issue a new one and revoke this one',
348
+ instead: 'a call to your own server, which holds the key',
349
+ severity: runs.browser ? 'HIGH' : 'MEDIUM',
350
+ }, 'medium');
351
+ }
352
+
329
353
  // Only where it is read from the environment, and never in a test: found on
330
354
  // Kryptheon's own code, a constant called PUBLIC_SECRET_NAME is a name in a
331
355
  // program, not a variable the build ships - and a test file ships nothing.
package/kryptheon-map.js CHANGED
@@ -826,6 +826,12 @@ function readGuardFn(ctx, ref, opts = {}) {
826
826
  if (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') {
827
827
  const chain = memberChain(n);
828
828
  if (chain && ROLE_SEGS.test(chain[chain.length - 1]) && (identityChain(n.object) || identityLocals.has(chain[0]))) return true;
829
+ // user(req).role: the role of whoever a helper says is calling. Found on
830
+ // blind round 30 (StudioPulse): permit(resource, action) compared
831
+ // user(req).role with permissions-policy.json and the map said no route
832
+ // checked a role.
833
+ const prop = !n.computed && n.property ? n.property.name : n.property && n.property.type === 'StringLiteral' ? n.property.value : null;
834
+ if (prop && ROLE_SEGS.test(prop) && (n.object.type === 'CallExpression' || n.object.type === 'OptionalCallExpression') && isIdentityNode(n.object)) return true;
829
835
  }
830
836
  if (n.type === 'Identifier' && roleLocals.has(n.name)) return true;
831
837
  if (n.type === 'CallExpression' || n.type === 'OptionalCallExpression') {
@@ -1045,7 +1051,18 @@ function readGuardFn(ctx, ref, opts = {}) {
1045
1051
  else if (id && mixed) out.authPartial = out.authPartial || ev('a sign-in check that applies only in some cases');
1046
1052
  else if (!s && !k && !present) anyOther = true;
1047
1053
  }
1048
- if (anyRole) out.role = out.role || Object.assign(ev('turns away a role that is not allowed'), { roles: roleList.length ? roleList : rolesIn(t, testNode) });
1054
+ if (anyRole && !out.role) {
1055
+ // requireRole('admin'): the factory's words are roles when the check compares
1056
+ // with them. permit('products', 'read') looks a rule up instead (blind round
1057
+ // 30): its words name a permission, and the roles are in the policy file.
1058
+ const comparesList = roleList.length && refersTo(testNode, (x) => x.type === 'Identifier' && factoryParams.includes(x.name));
1059
+ const looksLikePermission = roleList.length && (roleList.some((a) => /[.:]/.test(a)) ||
1060
+ (roleList.length === 2 && /^(read|write|create|update|delete|destroy|remove|manage|approve|view|edit|list|export|refund|admin)$/i.test(roleList[1])));
1061
+ const asPermission = looksLikePermission && !comparesList;
1062
+ const found = roleList.length && !asPermission ? roleList : rolesIn(t, testNode);
1063
+ out.role = Object.assign(ev('turns away a role that is not allowed'), found.length ? { roles: found } : {},
1064
+ asPermission ? { permission: roleList.join('.') } : {});
1065
+ }
1049
1066
  if (anyIdentity || (anyRole && !out.auth)) {
1050
1067
  if (anyIdentity) out.auth = out.auth || ev('turns away a request with nobody signed in');
1051
1068
  }
@@ -1299,6 +1316,7 @@ function judge(route, elements) {
1299
1316
  out.partial = partial;
1300
1317
  const roleEv = out.role.evidence;
1301
1318
  if (roleEv && roleEv.roles) out.role.roles = roleEv.roles;
1319
+ if (roleEv && roleEv.permission) out.role.permission = roleEv.permission;
1302
1320
  return out;
1303
1321
  }
1304
1322
 
@@ -2081,6 +2099,104 @@ function scopeVerdict(mod, line, st, filters, insertCols, schema, via, partlyUnr
2081
2099
  return Object.assign(base, { scoping: { status: STATUS.NOT, applies: true, why: (isInsert ? 'the row is written without an organisation or owner column' : 'no organisation or owner limit in the statement') } });
2082
2100
  }
2083
2101
 
2102
+ // --- redirects: an address the request names, sent back as Location -------------------------
2103
+
2104
+ const REQUEST_PARTS = /^(query|body|params|headers|cookies)$/;
2105
+ const CHECKS_A_PLACE = /^(startsWith|endsWith|test|match|includes|indexOf|has|isSafe\w*|isLocal\w*|isAllowed\w*|isRelative\w*|isValid\w*)$/;
2106
+
2107
+ /**
2108
+ * Redirects whose address comes from the request with nothing testing it first: res.redirect(req.query.next || '/').
2109
+ * One that passes the value through a test (startsWith('/'), a regex, an allow list, new URL(...).origin)
2110
+ * before it is used is left alone. Found on blind round 32 (Northstar): the sign-in answered 302 to any
2111
+ * address given as ?next=. [{ line, code, field, from }]
2112
+ */
2113
+ function readRedirects(ctx, fnRef) {
2114
+ const t = ctx.t;
2115
+ const fn = fnRef && fnRef.path;
2116
+ if (!fn || !fn.node || !fn.node.params) return [];
2117
+ const p0 = fn.node.params[0];
2118
+ const p1 = fn.node.params[1];
2119
+ const reqName = p0 && p0.type === 'Identifier' ? p0.name : null;
2120
+ const resName = p1 && p1.type === 'Identifier' ? p1.name : null;
2121
+ if (!reqName || !resName) return [];
2122
+ const mod = fnRef.mod;
2123
+ // tests anywhere in the handler: an if, a ternary, a && / || used as a condition
2124
+ const tests = [];
2125
+ fn.traverse({
2126
+ IfStatement(p) { tests.push(p.node.test); },
2127
+ ConditionalExpression(p) { tests.push(p.node.test); },
2128
+ CallExpression(p) {
2129
+ const name = calledName(p.node);
2130
+ if (CHECKS_A_PLACE.test(name)) tests.push(p.node);
2131
+ if ((name === 'URL' || (p.node.callee && p.node.callee.type === 'Identifier' && p.node.callee.name === 'URL'))) tests.push(p.node);
2132
+ },
2133
+ NewExpression(p) { if (p.node.callee && p.node.callee.type === 'Identifier' && p.node.callee.name === 'URL') tests.push(p.node); },
2134
+ });
2135
+ const mentions = (node, name) => {
2136
+ let hit = false;
2137
+ t.traverseFast(node, (x) => { if (x.type === 'Identifier' && x.name === name) hit = true; });
2138
+ return hit;
2139
+ };
2140
+ const tested = (name) => tests.some((n) => {
2141
+ if (!mentions(n, name)) return false;
2142
+ let isCheck = false;
2143
+ t.traverseFast(n, (x) => { if ((x.type === 'CallExpression' && (CHECKS_A_PLACE.test(calledName(x)) || calledName(x) === 'URL')) || x.type === 'NewExpression' || (x.type === 'BinaryExpression' && /^(===|!==|==|!=)$/.test(x.operator))) isCheck = true; });
2144
+ return isCheck;
2145
+ });
2146
+ // where a value comes from: { field, from } when it is the request's own, null otherwise; 'tested' when a test stands on the way
2147
+ const origin = (node, depth) => {
2148
+ if (!node || depth > 4) return null;
2149
+ if (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') {
2150
+ const chain = memberChain(node);
2151
+ if (chain && chain[0] === reqName && REQUEST_PARTS.test(chain[1] || '')) return { field: chain[2] || chain[1], from: chain[1] };
2152
+ return null;
2153
+ }
2154
+ if (node.type === 'LogicalExpression' && (node.operator === '||' || node.operator === '??')) return origin(node.left, depth + 1);
2155
+ if (node.type === 'ConditionalExpression') return 'tested';
2156
+ if (node.type === 'CallExpression') {
2157
+ const name = calledName(node);
2158
+ if (/^(String|decodeURIComponent|decodeURI|trim|toString)$/.test(name)) {
2159
+ const inner = node.arguments[0] || (node.callee && node.callee.object);
2160
+ return origin(inner, depth + 1);
2161
+ }
2162
+ return null;
2163
+ }
2164
+ if (node.type === 'TemplateLiteral' && node.expressions.length) {
2165
+ const head = node.quasis[0].value.cooked || '';
2166
+ if (/^\/[^/\\]/.test(head)) return null; // '/app/' + ... stays on this site
2167
+ return origin(node.expressions[0], depth + 1);
2168
+ }
2169
+ if (node.type === 'BinaryExpression' && node.operator === '+') {
2170
+ if (node.left.type === 'StringLiteral' && /^\/[^/\\]/.test(node.left.value)) return null;
2171
+ return node.left.type === 'StringLiteral' ? origin(node.right, depth + 1) : origin(node.left, depth + 1);
2172
+ }
2173
+ if (node.type === 'Identifier') {
2174
+ if (tested(node.name)) return 'tested';
2175
+ const b = fn.scope.getBinding(node.name);
2176
+ if (!b || !b.path.isVariableDeclarator() || b.constantViolations.length) return null;
2177
+ return origin(b.path.node.init, depth + 1);
2178
+ }
2179
+ return null;
2180
+ };
2181
+ const out = [];
2182
+ fn.traverse({
2183
+ CallExpression(p) {
2184
+ const chain = memberChain(p.node.callee);
2185
+ if (!chain || chain[0] !== resName) return;
2186
+ let target = null;
2187
+ if (chain[1] === 'redirect') target = p.node.arguments[p.node.arguments.length - 1];
2188
+ else if (chain[1] === 'location') target = p.node.arguments[0];
2189
+ else if (/^(set|header|setHeader)$/.test(chain[1] || '') && p.node.arguments[0] && p.node.arguments[0].type === 'StringLiteral' && /^location$/i.test(p.node.arguments[0].value)) target = p.node.arguments[1];
2190
+ if (!target) return;
2191
+ const o = origin(target, 0);
2192
+ if (!o || o === 'tested') return;
2193
+ const line = p.node.loc ? p.node.loc.start.line : null;
2194
+ out.push({ line: line, code: line && mod ? snippet(mod, line) : '', field: o.field, from: o.from, file: mod ? mod.rel : null });
2195
+ },
2196
+ });
2197
+ return out;
2198
+ }
2199
+
2084
2200
  /** The handler of a route: the last element in front of it that is the app's own code. */
2085
2201
  function handlerOf(r) {
2086
2202
  for (let i = r.chain.length - 1; i >= 0; i--) if (r.chain[i].ref.kind === 'fn' && !r.chain[i].inherited) return r.chain[i].ref;
@@ -2893,6 +3009,7 @@ function mapProject(root, options) {
2893
3009
  const h = handlerOf(r);
2894
3010
  const db = h ? readDb(ctx, h, schema) : [];
2895
3011
  const validation = h ? readValidation(ctx, h, elements, db) : { fields: [], schemas: [], why: 'the handler could not be followed' };
3012
+ const redirects = h ? readRedirects(ctx, h) : [];
2896
3013
  return {
2897
3014
  method: r.method,
2898
3015
  path: r.path,
@@ -2907,6 +3024,7 @@ function mapProject(root, options) {
2907
3024
  partialChecks: g.partial,
2908
3025
  db,
2909
3026
  validation,
3027
+ redirects,
2910
3028
  };
2911
3029
  });
2912
3030
  routes.push(...edgeRoutes(ctx, root, schema));
@@ -2940,6 +3058,7 @@ const ADVICE = {
2940
3058
  'tenant-from-request': 'take the organisation from the signed-in person\'s session, never from the request body or query string; for an id the request sends, look the record up with the organisation condition before using it.',
2941
3059
  'tenant-unscoped': 'add the signed-in person\'s organisation (or owner) to the statement - WHERE org_id = <the session\'s org> - or, for a row found by its id, check that the row belongs to that organisation before using it.',
2942
3060
  'no-role': 'allow only the roles that should be able to do this, and answer 403 for the others.',
3061
+ 'open-redirect': 'send the browser only to an address on this site: accept a path that starts with a single "/" (not "//", not "/\\\\", no "http"), or a name from a fixed list of places, and fall back to "/" for anything else. Keep the rest of the route as it is.',
2943
3062
  'no-state-check': 'look at the record\'s status first and refuse the step when the record is not in the status it must come from (WHERE status = <the one before> in the same statement, or a check that answers 409). A second call must change nothing - no stock, money or log entry added again.',
2944
3063
  'identity-from-request': 'take who is calling only from something the server itself issued and can check - a signed session cookie (express-session, a signed JWT) - never from a bare user id in a cookie or a header the browser can set. Look the session up on the server and set req.user from that.',
2945
3064
  };
@@ -2983,6 +3102,10 @@ function toCheck(map) {
2983
3102
  }
2984
3103
  continue;
2985
3104
  }
3105
+ // an address the request names, sent back as the place to go: a link that signs a person in and lands them on another site
3106
+ for (const rd of r.redirects || []) {
3107
+ add(r, 'open-redirect', 'MEDIUM', name + ' sends the browser to the address in ' + rd.from + '.' + rd.field + ' with nothing checking it first: a link to your app can land people on any other site', [(rd.file || r.file) + ':' + rd.line + ' ' + rd.code]);
3108
+ }
2986
3109
  // a route with no sign-in that changes something - sign-in and sign-up routes are open by nature
2987
3110
  if (writes && r.auth.status === STATUS.NOT && changing.length && !AUTH_PATH.test(r.path || '')) {
2988
3111
  add(r, 'no-sign-in', 'HIGH', name + ' ' + tables(changing) + ', and no sign-in check was found in front of it', [r.file + ':' + r.line].concat(changing.slice(0, 3).map((d) => d.file + ':' + d.line + ' ' + d.sql)));
@@ -65,8 +65,19 @@ const ROW_PICK = /getByRole\(\s*['"](row|cell|gridcell|listitem|article)['"]\s*,
65
65
  // Fields whose value should never be committed to a file.
66
66
  const SECRET_FIELD = /(password|passcode|\bpin\b|secret|security[\s_-]?code|card[\s_-]?number|cvv)/i;
67
67
 
68
+ // A field known only by its id or selector, with no words: #pw, #pwd,
69
+ // input[name=pass], [type=password]. Found on blind round 30 (StudioPulse):
70
+ // the password box was locator('#pw'), so the typed password stayed in the
71
+ // recording as plain text. Only for names without spaces, so a label like
72
+ // "Bus pass number" is not taken for a password.
73
+ const SECRET_SELECTOR = /(^|[^a-z0-9])(pw|pwd|pword|psw|pswd|passwd|pass|passwort)([^a-z0-9]|$)|type\s*=\s*['"]?password/i;
74
+
75
+ function isPasswordSelector(name) {
76
+ return !!name && !/\s/.test(String(name).trim()) && SECRET_SELECTOR.test(String(name));
77
+ }
78
+
68
79
  function isSecretField(name) {
69
- return !!name && SECRET_FIELD.test(name);
80
+ return !!name && (SECRET_FIELD.test(name) || isPasswordSelector(name));
70
81
  }
71
82
 
72
83
  // A recording is only useful if running it again does the same thing. These
@@ -224,7 +235,10 @@ function accountPart(account) {
224
235
  // real value never reaches the file. Named for the account when one was typed
225
236
  // before it, so each account has its own - in every recording that uses it.
226
237
  function envNameFor(fieldName, taken, account) {
227
- const field = String(fieldName || 'password')
238
+ // '#pw' is a password box: KRYPTHEON_PASSWORD_<account>, the name api and
239
+ // roles already read, not KRYPTHEON_PW_<account>.
240
+ const selectorOnly = isPasswordSelector(fieldName) && !SECRET_FIELD.test(fieldName);
241
+ const field = String(selectorOnly ? 'password' : fieldName || 'password')
228
242
  .toUpperCase()
229
243
  .replace(/[^A-Z0-9]+/g, '_')
230
244
  .replace(/^_+|_+$/g, '')
@@ -242,7 +256,18 @@ function envNameFor(fieldName, taken, account) {
242
256
 
243
257
  // Replaces literal secrets with process.env references. Returns the new source
244
258
  // plus what the user now has to put in .env.
245
- function scrubSecrets(source) {
259
+ //
260
+ // options.known: { NAME: value } of passwords already set (KRYPTHEON_PASSWORD_*
261
+ // in .env). A literal equal to one of them is taken out whatever the field is
262
+ // called, and points at that same name - the second guard for a password box
263
+ // whose name says nothing (blind round 30).
264
+ function scrubSecrets(source, options) {
265
+ const known = [];
266
+ const given = (options && options.known) || {};
267
+ for (const name of Object.keys(given)) {
268
+ const value = given[name];
269
+ if (/^KRYPTHEON_PASSWORD/.test(name) && typeof value === 'string' && value.length >= 4) known.push({ name: name, value: value });
270
+ }
246
271
  const text = String(source || '');
247
272
  const lines = text.split('\n');
248
273
  const replacements = [];
@@ -255,13 +280,29 @@ function scrubSecrets(source) {
255
280
  const updated = lines.map((line, index) => {
256
281
  if (!/\.fill\(/.test(line)) return line;
257
282
  const fieldName = nameInLine(line);
258
- if (!isSecretField(fieldName)) return line;
259
283
 
260
284
  // Only a literal is a problem; an existing process.env reference is fine.
261
285
  const filled = line.match(/\.fill\(\s*(['"])((?:\\.|(?!\1).)*)\1\s*\)/);
262
286
  if (!filled) return line;
263
287
  if (!filled[2]) return line; // nothing typed
264
288
 
289
+ const typed = filled[2].replace(/\\(.)/g, '$1');
290
+ // Accounts that share one password all match it: the name of the account typed in this form is the one meant
291
+ // (round 30: every recording pointed at the first account's name, KRYPTHEON_PASSWORD_OWNER_...); the first
292
+ // match only when the account has no name of its own that holds this value.
293
+ const matches = known.filter((k) => k.value === typed);
294
+ const typedFor = matches.length > 1 ? accountBefore(lines, index) : null;
295
+ const ownName = typedFor ? 'KRYPTHEON_PASSWORD_' + accountPart(typedFor) : null;
296
+ const knownHit = (ownName && matches.find((k) => k.name.toUpperCase() === ownName)) || matches[0];
297
+ if (knownHit) {
298
+ if (!replacements.some((r) => r.envName === knownHit.name)) {
299
+ taken.push(knownHit.name);
300
+ replacements.push({ envName: knownHit.name, field: fieldName || 'password', known: true });
301
+ }
302
+ return line.replace(filled[0], '.fill(process.env.' + knownHit.name + " || '')");
303
+ }
304
+ if (!isSecretField(fieldName)) return line;
305
+
265
306
  const account = accountBefore(lines, index);
266
307
  const key = String(fieldName) + '\u0000' + (account || '') + '\u0000' + filled[2];
267
308
  let envName = seen[key];
@@ -447,6 +488,7 @@ module.exports = {
447
488
  scrubSecrets: scrubSecrets,
448
489
  dropTrailingLogout: dropTrailingLogout,
449
490
  isSecretField: isSecretField,
491
+ isPasswordSelector: isPasswordSelector,
450
492
  accountPart: accountPart,
451
493
  nameInLine: nameInLine,
452
494
  CREATES: CREATES,