kryptheon 0.1.64 → 0.1.66

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,109 @@ 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
+ /**
334
+ * The markers that are a default both organizations are given at an address
335
+ * that names no record (round 33: GET /settings gave each organization its own
336
+ * name and the same time zone; the time zone, found in the caller's answer, was
337
+ * called the other organization's record). A marker counts as such only when
338
+ * the two answers differ somewhere (the app does tell the organizations apart
339
+ * here), and every place the caller's answer holds it is the same place in the
340
+ * other organization's answer, outside any record with an id of its own. The
341
+ * same answer for both, a record, or a value held anywhere else still counts.
342
+ */
343
+ function sameDefaults(answerJson, theirsJson, markers) {
344
+ if (!answerJson || typeof answerJson !== 'object' || !theirsJson || typeof theirsJson !== 'object') return [];
345
+ if (JSON.stringify(answerJson) === JSON.stringify(theirsJson)) return [];
346
+ // every string leaf: its path, and whether an enclosing object is a record with an id of its own
347
+ const leaves = (root) => {
348
+ const out = [];
349
+ (function walk(v, at, inRecord, depth) {
350
+ if (depth > 8 || v == null) return;
351
+ if (typeof v === 'string') { out.push({ at: at.join('\u0001'), value: v, inRecord: inRecord }); return; }
352
+ if (typeof v !== 'object') return;
353
+ const record = !Array.isArray(v) && Object.keys(v).some((k) => OWN_ID_KEY.test(k) && ['string', 'number'].includes(typeof v[k]));
354
+ for (const k of Object.keys(v)) walk(v[k], at.concat(k), inRecord || record, depth + 1);
355
+ })(root, [], false, 0);
356
+ return out;
357
+ };
358
+ const ours = leaves(answerJson);
359
+ const theirs = new Map(leaves(theirsJson).map((l) => [l.at, l.value]));
360
+ const out = [];
361
+ for (const m of markers) {
362
+ const held = ours.filter((l) => l.value.includes(m));
363
+ if (!held.length) continue;
364
+ if (!held.every((l) => l.value === m && !l.inRecord && theirs.get(l.at) === m)) continue;
365
+ out.push(m);
366
+ }
367
+ return out;
368
+ }
369
+
370
+ function sharedOnly(answerJson, theirsJson, markers) {
371
+ if (answerJson === undefined || answerJson === null || typeof answerJson !== 'object') return [];
372
+ const answer = idRecordsOf(answerJson);
373
+ const theirIds = new Set(idRecordsOf(theirsJson).map((r) => r.id));
374
+ if (!answer.length || !theirIds.size) return [];
375
+ // the fields a string is held at, in a record of its own (not in its nested records)
376
+ const keysOf = (record, m) => Object.keys(record).filter((k) => record[k] === m || (Array.isArray(record[k]) && record[k].includes(m)));
377
+ const theirRecords = idRecordsOf(theirsJson);
378
+ const out = [];
379
+ for (const m of markers) {
380
+ // an email is a person's, never a name two records happen to share
381
+ if (/@/.test(m)) continue;
382
+ const holders = holdersOf(answer, m);
383
+ if (!holders.length || holders.some((h) => theirIds.has(h.id))) continue;
384
+ // held as the same field by the other organization's record (both are "name"): the same kind of value, not theirs
385
+ const theirKeys = new Set([].concat.apply([], holdersOf(theirRecords, m).map((t) => keysOf(t.record, m))));
386
+ if (!holders.every((h) => keysOf(h.record, m).some((k) => theirKeys.has(k)))) continue;
387
+ // and nowhere else: with those records taken out, the answer no longer holds it
388
+ const rest = (function strip(v, depth) {
389
+ if (depth > 6 || v == null || typeof v !== 'object') return v;
390
+ if (Array.isArray(v)) return v.filter((x) => !holders.some((h) => h.record === x)).map((x) => strip(x, depth + 1));
391
+ if (holders.some((h) => h.record === v)) return null;
392
+ const o = {};
393
+ for (const k of Object.keys(v)) o[k] = strip(v[k], depth + 1);
394
+ return o;
395
+ })(answerJson, 0);
396
+ if (!stringsOf(rest, 1).includes(m) && !JSON.stringify(rest).includes(m)) out.push(m);
397
+ }
398
+ return out;
399
+ }
400
+
293
401
  // --- judging --------------------------------------------------------------
294
402
 
295
403
  /**
@@ -372,12 +480,21 @@ function makeContext(options) {
372
480
  const origin = assertLocalTarget(options.baseUrl, options.allowOrigins);
373
481
  const fetchImpl = options.fetch || globalThis.fetch;
374
482
  const secrets = Object.values(options.passwords || {}).filter(Boolean);
375
- const ctx = { origin: origin, requests: 0, secrets: secrets };
483
+ // ctx.limit can be raised by a check that knows how big the app is (runSteps); it never goes away.
484
+ const ctx = { origin: origin, requests: 0, secrets: secrets, limit: options.maxRequests || MAX_REQUESTS };
376
485
  ctx.request = async function (session, method, p, opts) {
377
486
  method = String(method).toUpperCase();
378
487
  if (method === 'DELETE') throw new Error('authz: this check never deletes anything');
379
488
  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');
489
+ if (ctx.requests + 1 > ctx.limit) {
490
+ // A stop, not a crash: the caller keeps what it found so far and says it stopped (blind round 32,
491
+ // where this error ended the whole API check with a stack trace and no report).
492
+ const stop = new Error('authz: stopped - more than ' + ctx.limit + ' requests in one run');
493
+ stop.code = REQUEST_LIMIT;
494
+ stop.limit = ctx.limit;
495
+ throw stop;
496
+ }
497
+ ctx.requests++;
381
498
  const url = new URL(p, origin);
382
499
  if (url.origin !== origin) throw new Error('authz: refused a request to another origin');
383
500
  const headers = { accept: 'application/json, text/html;q=0.8' };
@@ -812,12 +929,15 @@ module.exports = {
812
929
  journeyFromHar: journeyFromHar,
813
930
  discover: discover,
814
931
  replyOf: replyOf,
932
+ sharedOnly: sharedOnly,
933
+ sameDefaults: sameDefaults,
815
934
  judgeRead: judgeRead,
816
935
  judgeWrite: judgeWrite,
817
936
  runAuthz: runAuthz,
818
937
  reportLines: reportLines,
819
938
  // Used by kryptheon-roles.js, which tries the same thing for any app.
820
939
  makeContext: makeContext,
940
+ isRequestLimit: isRequestLimit,
821
941
  makeSession: makeSession,
822
942
  stringsOf: stringsOf,
823
943
  identifierLike: identifierLike,
@@ -174,6 +174,13 @@
174
174
  dbInput.autocomplete = 'off';
175
175
  dbInput.spellcheck = false;
176
176
  dbInput.addEventListener('input', function () { if (pending) { pending = null; renderSteps(); } });
177
+ // The connect code from the account page: kept like the boxes above, and gone once it is sent.
178
+ var connectInput = el('input', 'field');
179
+ connectInput.type = 'password';
180
+ connectInput.placeholder = 'Paste your connect code (kd_...)';
181
+ connectInput.setAttribute('aria-label', 'Your connect code');
182
+ connectInput.autocomplete = 'off';
183
+ connectInput.spellcheck = false;
177
184
 
178
185
  /* ------------------------------------ jobs ------------------------------------ */
179
186
 
@@ -377,7 +384,8 @@
377
384
  byId('builtNote').textContent = (state.checks.length - built) + ' more are coming soon - never shown as passed.';
378
385
  var name = state.project.name || 'Project';
379
386
  var last = (state.looks || [])[0];
380
- byId('subline').textContent = name + ' - ' + (last ? 'watching, last look ' + ago(last.at) : 'watching for changes');
387
+ byId('subline').textContent = name + ' - ' + (last ? 'watching, last look ' + ago(last.at) : 'watching for changes') +
388
+ (state.update ? ' - A newer Kryptheon is out (' + state.update.current + ' -> ' + state.update.latest + '): close this and run ' + state.update.command : '');
381
389
  }
382
390
 
383
391
  /* ------------------------------ right now + steps ------------------------------ */
@@ -773,8 +781,11 @@
773
781
  if (f.fixPrompt) {
774
782
  box.appendChild(el('div', 'd-step', 'STEP 1 - PASTE THIS INTO YOUR AI TOOL'));
775
783
  box.appendChild(el('pre', null, f.fixPrompt));
784
+ } else if (f.promptLock) {
785
+ box.appendChild(el('div', 'd-step', 'STEP 1 - THE FIX PROMPT FOR YOUR AI TOOL'));
786
+ box.appendChild(lockedPrompt(f, false));
776
787
  }
777
- box.appendChild(el('div', 'd-step', f.fixPrompt ? 'STEP 2 - AFTER IT CHANGES THE CODE, RE-CHECK' : 'RE-CHECK'));
788
+ box.appendChild(el('div', 'd-step', f.fixPrompt || f.promptLock ? 'STEP 2 - AFTER IT CHANGES THE CODE, RE-CHECK' : 'RE-CHECK'));
778
789
  var actions = el('div', 'd-actions');
779
790
  if (f.fixPrompt) {
780
791
  actions.appendChild(button('', 'copy', 'Copy fix prompt', function (e) {
@@ -840,6 +851,13 @@
840
851
  whole.appendChild(el('pre', null, state.allFixPrompt));
841
852
  all.appendChild(whole);
842
853
  body.appendChild(all);
854
+ } else if (state.allFixPromptLocked) {
855
+ var allLocked = el('div', 'fix-all');
856
+ var lockedWords = el('div', 'fix-all-words');
857
+ lockedWords.appendChild(el('b', null, 'Fix all at once'));
858
+ lockedWords.appendChild(el('span', null, 'One prompt with every fix is part of Pro. Each finding still shows what is wrong and its proof.'));
859
+ allLocked.appendChild(lockedWords);
860
+ body.appendChild(allLocked);
843
861
  }
844
862
  if (!shown.length) {
845
863
  body.appendChild(el('p', 'empty', state.findings.length ? 'Nothing matches.' : 'Nothing found by the checks that are on and have run. That is not the same as nothing wrong - see which checks are not built yet.'));
@@ -888,6 +906,7 @@
888
906
  // The two things to do with a finding, without opening it first.
889
907
  var quick = el('div', 'f-quick');
890
908
  if (f.fixPrompt) quick.appendChild(button('sm', 'copy', 'Copy fix prompt', function () { copy(f.fixPrompt, 'Fix prompt copied - paste it into your AI tool'); }));
909
+ else if (f.promptLock) quick.appendChild(lockedPrompt(f, true));
891
910
  var qre = button('sm', 'refresh', 'Re-check', function () { recheck(f); });
892
911
  qre.setAttribute('data-action', 'recheck');
893
912
  qre.disabled = busy;
@@ -1470,12 +1489,102 @@
1470
1489
  }
1471
1490
  }
1472
1491
 
1492
+ /* ---------------------------------- account ---------------------------------- */
1493
+
1494
+ // Your account: the kryptheon.tech plan this dashboard is connected to, by the connect code from the account page.
1495
+ // The code itself never comes back to this page - only the plan and the fix prompts left.
1496
+ var PLAN_WORD = { starter: 'Starter', pro: 'Pro', studio: 'Studio' };
1497
+ function renderAccount() {
1498
+ var box = byId('accountBox');
1499
+ if (!box) return;
1500
+ var a = state.account || { connected: false };
1501
+ clear(box);
1502
+ if (a.connected) {
1503
+ var line = el('p', 'app-here');
1504
+ line.appendChild(el('b', null, 'Connected - ' + (a.app || 'your app')));
1505
+ box.appendChild(line);
1506
+ var left = a.prompts && typeof a.prompts.left === 'number'
1507
+ ? PLAN_WORD[a.plan] + ' - ' + a.prompts.left + ' of ' + a.prompts.limit + ' free fix prompts left this month'
1508
+ : (PLAN_WORD[a.plan] || a.plan) + ' - every fix prompt';
1509
+ box.appendChild(el('div', 'fallback', left));
1510
+ var row = el('div', 'field-row');
1511
+ row.appendChild(button('sm', 'refresh', 'Check my plan again', function () {
1512
+ post('/api/account/refresh', {}).then(function () { toast('Checked.'); load(); }, function (err) { toast(err.message); });
1513
+ }));
1514
+ row.appendChild(button('sm', '', 'Disconnect', function () {
1515
+ post('/api/account/disconnect', {}).then(function () { toast('Disconnected from this computer.'); load(); }, function (err) { toast(err.message); });
1516
+ }));
1517
+ box.appendChild(row);
1518
+ return;
1519
+ }
1520
+ if (a.problem) box.appendChild(el('div', 'fallback', a.problem.charAt(0).toUpperCase() + a.problem.slice(1) + '.'));
1521
+ box.appendChild(el('label', 'app-label', 'Connect your free Kryptheon account to get 5 free fix prompts a month'));
1522
+ var row2 = el('div', 'field-row');
1523
+ row2.appendChild(connectInput);
1524
+ row2.appendChild(button('sun sm', 'check', 'Connect', function () {
1525
+ var code = connectInput.value.trim();
1526
+ if (!code) { toast('Paste your connect code first.'); return; }
1527
+ post('/api/account/connect', { code: code }).then(function () {
1528
+ connectInput.value = '';
1529
+ toast('Connected.');
1530
+ load();
1531
+ }, function (err) { toast(err.message); });
1532
+ }));
1533
+ box.appendChild(row2);
1534
+ var help = el('div', 'fallback');
1535
+ help.appendChild(document.createTextNode('Already have a Kryptheon account? Get your connect code from your account page - your apps and plan carry over: '));
1536
+ help.appendChild(el('span', 'app-path', a.accountPage || 'kryptheon.tech/dashboard'));
1537
+ box.appendChild(help);
1538
+ }
1539
+
1540
+ // A finding's fix prompt that the plan does not open yet: its first line, and what opens the rest.
1541
+ function lockedPrompt(f, small) {
1542
+ var lock = f.promptLock;
1543
+ var a = state.account || {};
1544
+ var wrap = el('div', small ? 'f-locked sm' : 'f-locked');
1545
+ if (!small) {
1546
+ wrap.appendChild(el('pre', 'locked-preview', lock.preview));
1547
+ // Not the prompt: it never reached this page. A blurred stand-in, so it reads as "there is more".
1548
+ var blur = el('div', 'locked-blur', 'In the same change, also check every other place that does this, keep the rest as it is, and tell me what you changed.');
1549
+ blur.setAttribute('aria-hidden', 'true');
1550
+ wrap.appendChild(blur);
1551
+ }
1552
+ if (lock.reason === 'connect') {
1553
+ if (!small) wrap.appendChild(el('div', 'd-text', 'Connect your free account to get 5 free fix prompts a month.'));
1554
+ wrap.appendChild(button('sm', 'arrow', small ? 'Fix prompt: connect your free account' : 'Connect my account', function (e) {
1555
+ if (e) e.stopPropagation();
1556
+ if (window.location.hash !== '#dashboard') window.location.hash = 'dashboard';
1557
+ setTimeout(function () {
1558
+ var card = byId('accountCard');
1559
+ if (card) card.scrollIntoView({ behavior: 'smooth', block: 'center' });
1560
+ connectInput.focus();
1561
+ }, 50);
1562
+ }));
1563
+ } else if (lock.reason === 'free-left') {
1564
+ // Quiet in the list (one per finding); the bright one only inside an opened finding.
1565
+ var open = button(small ? 'sm' : 'sun sm', 'copy', 'Show fix prompt (uses 1 of your ' + lock.left + ' free this month)', function (e) {
1566
+ if (e) e.stopPropagation();
1567
+ open.disabled = true;
1568
+ post('/api/prompt/unlock', { id: f.id }).then(function () { load(); }, function (err) { toast(err.message); load(); });
1569
+ });
1570
+ wrap.appendChild(open);
1571
+ } else {
1572
+ if (!small) wrap.appendChild(el('div', 'd-text', 'This month\'s 5 free fix prompts are used.'));
1573
+ wrap.appendChild(button('sm', 'arrow', 'Unlock with Pro - ₹499/month', function (e) {
1574
+ if (e) e.stopPropagation();
1575
+ copy(a.pricing || 'https://kryptheon.tech/pricing/', 'Pricing page address copied - open it in your browser');
1576
+ }));
1577
+ }
1578
+ return wrap;
1579
+ }
1580
+
1473
1581
  function render(next) {
1474
1582
  if (!next) return;
1475
1583
  state = next;
1476
1584
  renderSide();
1477
1585
  renderTop();
1478
1586
  renderApp();
1587
+ renderAccount();
1479
1588
  renderNow();
1480
1589
  renderSteps();
1481
1590
  renderKeep();
@@ -1520,7 +1629,7 @@
1520
1629
  // Not while something runs, not while a finding is open being read, not
1521
1630
  // while a yes is being asked for, and not while someone is typing.
1522
1631
  setInterval(function () {
1523
- var typing = document.activeElement === dbInput || document.activeElement === recordInput;
1632
+ var typing = document.activeElement === dbInput || document.activeElement === recordInput || document.activeElement === connectInput;
1524
1633
  if (!busy && !openRow && !pending && !probeAsking && !paymentsAsking && !typing) load();
1525
1634
  }, 5000);
1526
1635
  })();
@@ -360,6 +360,10 @@
360
360
  .fix-all-text summary { width: max-content; font: 11px var(--mono); letter-spacing: 0.12em; text-transform: uppercase; cursor: pointer; opacity: 0.75; }
361
361
  .fix-all-text pre { max-height: 320px; margin: 10px 0 0; padding: 14px 16px; overflow: auto; font: 12px/1.6 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; border: 1px solid var(--line); }
362
362
  .rechecked { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; padding: 14px 8px 14px 20px; font-size: 14px; border-bottom: 1px solid var(--line); box-shadow: inset 3px 0 0 var(--on-light); }
363
+ .f-locked { display: grid; gap: 10px; justify-items: start; }
364
+ .f-locked.sm { display: contents; }
365
+ .locked-preview { margin: 0; padding: 12px 14px 0; font: 12px/1.6 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
366
+ .locked-blur { margin-top: -6px; padding: 0 14px 6px; font: 12px/1.6 var(--mono); filter: blur(4px); opacity: 0.55; user-select: none; pointer-events: none; }
363
367
 
364
368
  .toast { position: fixed; left: 50%; bottom: calc(24px + var(--job-room, 0px)); z-index: 10; max-width: calc(100vw - 32px); padding: 14px 20px; font-size: 14px; color: var(--on-dark); background: var(--ink); border-left: 2px solid var(--orange); opacity: 0; transform: translate(-50%, 20px); transition: opacity 0.35s var(--ease), transform 0.35s var(--ease); pointer-events: none; }
365
369
  .toast.show { opacity: 1; transform: translate(-50%, 0); }
@@ -405,6 +409,10 @@
405
409
  <div class="card-head"><div><h3>Your app</h3><div class="c-sub">What this dashboard checks</div></div></div>
406
410
  <div id="appBox"></div>
407
411
  </div>
412
+ <div class="card app-card gap" id="accountCard">
413
+ <div class="card-head"><div><h3>Your account</h3><div class="c-sub">Your kryptheon.tech plan, and your fix prompts</div></div></div>
414
+ <div id="accountBox"></div>
415
+ </div>
408
416
  <div class="sky" id="sky">
409
417
  <div class="s-chip" id="skyIcon"></div>
410
418
  <div class="s-text">
@@ -23,11 +23,13 @@ const http = require('http');
23
23
  const crypto = require('crypto');
24
24
  const { spawnSync } = require('child_process');
25
25
  const store = require('./kryptheon-store.js');
26
+ const account = require('./kryptheon-account.js');
26
27
  const changes = require('./kryptheon-changes.js');
27
28
  const autostart = require('./kryptheon-autostart.js');
28
29
  const selectors = require('./kryptheon-selectors.js');
29
30
  const replay = require('./kryptheon-replay.js');
30
31
  const VERSION = require('./package.json').version;
32
+ const newer = require('./kryptheon-newer.js');
31
33
 
32
34
  /**
33
35
  * Every check the dashboard knows the name of, in the order the person asked
@@ -614,6 +616,30 @@ function movingStep(root, t) {
614
616
  return { line: line, selector: hit.selector, why: reason.why + (reason.kind === 'number' ? ' that can change as data is added' : '') };
615
617
  }
616
618
 
619
+ /**
620
+ * For night's "to verify" finding (rows that may name another organization's record): the routes of the app that
621
+ * write those tables, from the last API run, said as tried across organizations or NOT tried - with why. Lines.
622
+ */
623
+ function tenantRoutesLines(f, apiLast) {
624
+ const tables = [];
625
+ for (const m of f.members || []) if (m.table && !tables.includes(m.table)) tables.push(m.table);
626
+ if (!apiLast || !apiLast.ran) {
627
+ 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.'];
628
+ }
629
+ const routes = (apiLast.writes || []).filter((w) => (w.tables || []).some((t) => tables.includes(t)));
630
+ if (!routes.length) return ['The last API check found no route that writes ' + (tables.length === 1 ? tables[0] : 'these tables') + ' to try.'];
631
+ const tried = routes.filter((w) => w.acrossOrgs === 'tried');
632
+ const not = routes.filter((w) => w.acrossOrgs !== 'tried');
633
+ const out = ['Routes that write these tables (last API check, ' + String(apiLast.checkedAt || '').slice(0, 10) + '):'];
634
+ 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.');
635
+ if (not.length) {
636
+ out.push('NOT tried across organizations, so not known: ' + not.length + ' route' + (not.length === 1 ? '' : 's') + ':');
637
+ for (const w of not.slice(0, 12)) out.push('- ' + w.route + (w.why ? ' (' + w.why + ')' : ''));
638
+ if (not.length > 12) out.push('- and ' + (not.length - 12) + ' more');
639
+ }
640
+ return out;
641
+ }
642
+
617
643
  function buildState(root, env) {
618
644
  const paths = store.pathsFor(root, env);
619
645
  const config = readConfig(paths);
@@ -808,6 +834,10 @@ function buildState(root, env) {
808
834
  }
809
835
  if (night && config.enabled.data) {
810
836
  for (const f of night.findings || []) {
837
+ // A row the database lets name another organization's record is "to verify": say which routes that write
838
+ // those tables the API check tried across organizations, and which it did NOT - never more than what ran.
839
+ let detail = f.body || '';
840
+ if (f.kind === 'tenantparents') detail += (detail ? '\n\n' : '') + tenantRoutesLines(f, apiLast).join('\n');
811
841
  findings.push({
812
842
  check: 'data',
813
843
  severity: f.severity,
@@ -816,7 +846,7 @@ function buildState(root, env) {
816
846
  confidence: (f.status || 'confirmed') === 'confirmed' ? 'high' : 'medium',
817
847
  where: f.table + (f.column ? '.' + f.column : ''),
818
848
  headline: f.headline,
819
- detail: f.body || '',
849
+ detail: detail,
820
850
  fixPrompt: f.fixPrompt || '',
821
851
  when: nightWhen,
822
852
  });
@@ -974,6 +1004,11 @@ function buildState(root, env) {
974
1004
  // Which kryptheon this dashboard is: a newer `dashboard` asks, and takes
975
1005
  // the place of an older one still running, instead of opening it.
976
1006
  kryptheon: VERSION,
1007
+ // a newer kryptheon on npm (from the day's answer, asked when the dashboard started), or null
1008
+ update: (() => {
1009
+ const latest = newer.cachedLatest('kryptheon');
1010
+ return latest && newer.compare(latest, VERSION) > 0 ? { current: VERSION, latest: latest, command: 'npx kryptheon@latest dashboard' } : null;
1011
+ })(),
977
1012
  looks: looks,
978
1013
  proven: proven,
979
1014
  checks: checks,
@@ -1027,11 +1062,11 @@ function apiVerdictLine(apiLast, item) {
1027
1062
  return v ? '\nOn the running app (' + String(apiLast.checkedAt || '').slice(0, 10) + '): ' + v.verdict + (v.why ? ' - ' + v.why : '') + '.' : '';
1028
1063
  }
1029
1064
  const DB_ACTIONS = {
1030
- scan: { title: 'Checking your database', command: 'npx kryptheon-night' },
1031
- install: { title: 'Setting up the nightly check', command: 'npx kryptheon-night install' },
1032
- night: { title: 'Reading last night\'s result', command: 'npx kryptheon-night night' },
1033
- uninstall: { title: 'Removing the nightly check', command: 'npx kryptheon-night uninstall' },
1034
- recheck: { title: 'Re-checking in your database', command: 'npx kryptheon-night' },
1065
+ scan: { title: 'Checking your database', command: 'npx kryptheon-night@latest' },
1066
+ install: { title: 'Setting up the nightly check', command: 'npx kryptheon-night@latest install' },
1067
+ night: { title: 'Reading last night\'s result', command: 'npx kryptheon-night@latest night' },
1068
+ uninstall: { title: 'Removing the nightly check', command: 'npx kryptheon-night@latest uninstall' },
1069
+ recheck: { title: 'Re-checking in your database', command: 'npx kryptheon-night@latest' },
1035
1070
  };
1036
1071
 
1037
1072
  /**
@@ -1247,6 +1282,8 @@ function createJobs() {
1247
1282
  * page this server hands out, which another site cannot read.
1248
1283
  */
1249
1284
  function createServer(root, options) {
1285
+ // ask npm once for a newer kryptheon; the page reads the day's answer from then on (never waits for it)
1286
+ if (!(options && options.fetch)) newer.latestOf('kryptheon');
1250
1287
  const opts = options || {};
1251
1288
  const env = opts.env || process.env;
1252
1289
  const token = crypto.randomBytes(24).toString('hex');
@@ -1296,7 +1333,8 @@ function createServer(root, options) {
1296
1333
  return send(res, 200, type, body);
1297
1334
  }
1298
1335
  if (req.method === 'GET' && url.pathname === '/api/state') {
1299
- return json(res, 200, buildState(root, env));
1336
+ // What the page is sent, for this computer's account: fix prompts past what the plan opens never leave here.
1337
+ return json(res, 200, account.lock(buildState(root, env), root, env));
1300
1338
  }
1301
1339
  if (req.method === 'GET' && url.pathname === '/api/job') {
1302
1340
  return json(res, 200, { job: jobs.get() });
@@ -1319,6 +1357,17 @@ function createServer(root, options) {
1319
1357
  const r = setCheck(store.pathsFor(root, env), String(input.id || ''), input.on);
1320
1358
  return json(res, r.ok ? 200 : 400, r);
1321
1359
  }
1360
+ // The account: a connect code from kryptheon.tech, and Starter's fix prompts opened one at a time.
1361
+ const answer = (p) => p.then((r) => json(res, r.ok ? 200 : (r.status === 402 ? 402 : 400), r))
1362
+ .catch(() => json(res, 500, { ok: false, why: 'something went wrong' }));
1363
+ if (url.pathname === '/api/account/connect') return answer(account.connect(root, env, input.code));
1364
+ if (url.pathname === '/api/account/refresh') return answer(account.refresh(root, env));
1365
+ if (url.pathname === '/api/account/disconnect') return json(res, 200, account.disconnect(root, env));
1366
+ if (url.pathname === '/api/prompt/unlock') {
1367
+ const id = String(input.id || '');
1368
+ if (!buildState(root, env).findings.some((f) => f.id === id && f.fixPrompt)) return json(res, 404, { ok: false, why: 'no finding with that id has a fix prompt' });
1369
+ return answer(account.unlock(root, env, id));
1370
+ }
1322
1371
  if (url.pathname === '/api/autostart') {
1323
1372
  const r = autostart.setAutostart(root, input.on, env);
1324
1373
  return json(res, r.ok ? 200 : 400, { ok: r.ok, on: !!r.on, why: r.why || '' });
@@ -1535,6 +1584,7 @@ function createServer(root, options) {
1535
1584
  }
1536
1585
 
1537
1586
  module.exports = {
1587
+ tenantRoutesLines: tenantRoutesLines,
1538
1588
  CHECKS: CHECKS,
1539
1589
  everythingPlan: everythingPlan,
1540
1590
  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.