kryptheon 0.1.58 → 0.1.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,38 +1,38 @@
1
- Kryptheon Software License
2
-
3
- Copyright (c) 2026 Kryptheon (https://kryptheon.tech). All rights reserved.
4
-
5
- This software is proprietary. It is not open source.
6
-
7
- 1. Use. You may install and run this software, as published by Kryptheon,
8
- at no charge, to check software and databases that you own or are
9
- authorised to test. Features that kryptheon.tech offers on a paid plan
10
- are provided only under that plan and the Terms at
11
- https://kryptheon.tech/terms.
12
-
13
- 2. Restrictions. Without Kryptheon's written permission you may not:
14
- (a) copy, modify, translate or create derivative works of this software,
15
- except as needed to run it;
16
- (b) sell, sublicense, rent, publish or otherwise distribute it, or offer
17
- it, or anything derived from it, as a hosted or managed service;
18
- (c) remove, disable or work around any licence, plan or usage limit, or
19
- any part of the software that enforces them;
20
- (d) use it, or any part of it, to build a competing product.
21
-
22
- 3. No warranty. The software is provided "as is", without warranty of any
23
- kind, express or implied, including fitness for a particular purpose.
24
- It may miss problems; a check that finds nothing does not mean that
25
- nothing is wrong. You are responsible for what you test and for keeping
26
- your own backups.
27
-
28
- 4. Limitation of liability. To the extent the law allows, Kryptheon is not
29
- liable for any damages arising from the use of, or inability to use,
30
- this software.
31
-
32
- 5. Earlier versions. Versions published before this licence was added keep
33
- the licence they were published with.
34
-
35
- 6. Termination. This licence ends automatically if you break it. When it
36
- ends, you must stop using the software and delete your copies.
37
-
38
- Questions: company@kryptheon.tech
1
+ Kryptheon Software License
2
+
3
+ Copyright (c) 2026 Kryptheon (https://kryptheon.tech). All rights reserved.
4
+
5
+ This software is proprietary. It is not open source.
6
+
7
+ 1. Use. You may install and run this software, as published by Kryptheon,
8
+ at no charge, to check software and databases that you own or are
9
+ authorised to test. Features that kryptheon.tech offers on a paid plan
10
+ are provided only under that plan and the Terms at
11
+ https://kryptheon.tech/terms.
12
+
13
+ 2. Restrictions. Without Kryptheon's written permission you may not:
14
+ (a) copy, modify, translate or create derivative works of this software,
15
+ except as needed to run it;
16
+ (b) sell, sublicense, rent, publish or otherwise distribute it, or offer
17
+ it, or anything derived from it, as a hosted or managed service;
18
+ (c) remove, disable or work around any licence, plan or usage limit, or
19
+ any part of the software that enforces them;
20
+ (d) use it, or any part of it, to build a competing product.
21
+
22
+ 3. No warranty. The software is provided "as is", without warranty of any
23
+ kind, express or implied, including fitness for a particular purpose.
24
+ It may miss problems; a check that finds nothing does not mean that
25
+ nothing is wrong. You are responsible for what you test and for keeping
26
+ your own backups.
27
+
28
+ 4. Limitation of liability. To the extent the law allows, Kryptheon is not
29
+ liable for any damages arising from the use of, or inability to use,
30
+ this software.
31
+
32
+ 5. Earlier versions. Versions published before this licence was added keep
33
+ the licence they were published with.
34
+
35
+ 6. Termination. This licence ends automatically if you break it. When it
36
+ ends, you must stop using the software and delete your copies.
37
+
38
+ Questions: company@kryptheon.tech
package/kryptheon-api.js CHANGED
@@ -144,6 +144,8 @@ function sampleValue(field, known, roleNames) {
144
144
  if (/^(date|day)$/.test(last) || last === 'at' || last === 'on') return new Date().toISOString().slice(0, 10);
145
145
  if (/^(is|has)$/.test(w[0]) || /^(enabled|active|private|public)$/.test(last)) return true;
146
146
  if (last === 'id' && w.length > 1) return 1;
147
+ // a list of ids (work_order_ids): one id in a list, never text
148
+ if (last === 'ids' && w.length > 1) return [1];
147
149
  if (w.some((x) => NUMBER_WORDS.has(x))) return 1;
148
150
  if ((field.checks || []).some((c) => /^(type|range)$/.test(c.kind) && /Number|parse(Int|Float)|isFinite|isInteger/.test(c.code || ''))) return 1;
149
151
  if (w.some((x) => /^(url|link|website)$/.test(x))) return 'https://kryptheon.invalid/test';
@@ -409,16 +411,35 @@ function fixPrompt(f) {
409
411
  */
410
412
  function findingsOf(attempts, journey) {
411
413
  const groups = new Map();
414
+ // another organization's record named in the body and taken, with nothing any list shows moving: a thing to check
415
+ // (round 27: a dispatch run took the other organization's work order ids; no read of the app shows them)
416
+ const taken = (a) => a.kind === 'tenant' && a.verdict === V.AMBIGUOUS && a.namedInBody && (a.response.reading === 'accepted' || a.response.reading === 'redirect');
412
417
  for (const a of attempts) {
413
- if (a.notTried || a.verdict !== V.FAILURE || (a.kind !== 'tenant' && a.kind !== 'signin')) continue;
414
- const k = a.kind + '|' + a.method + ' ' + a.template;
418
+ if (a.notTried || !(a.verdict === V.FAILURE || taken(a)) || (a.kind !== 'tenant' && a.kind !== 'signin')) continue;
419
+ const k = a.kind + '|' + a.method + ' ' + a.template + '|' + (a.verdict === V.FAILURE ? 'p' : 'h');
415
420
  if (!groups.has(k)) groups.set(k, []);
416
421
  groups.get(k).push(a);
417
422
  }
418
423
  const out = [];
419
- for (const list of groups.values()) {
424
+ for (const [key, list] of groups) {
420
425
  const first = list[0];
421
426
  const where = first.method + ' ' + first.template;
427
+ if (key.endsWith('|h')) {
428
+ // said only where the same route is not already proven
429
+ if (groups.has(key.slice(0, -1) + 'p')) continue;
430
+ const action = (journey.actions || []).find((x) => x.method === first.method && x.template === first.template) || {};
431
+ const f = {
432
+ kind: 'tenant', where: where, from: action.from ? action.from.file + ':' + action.from.line : null, severity: 'MEDIUM', status: 'verification required',
433
+ headline: 'Sent another organization\'s record (' + first.namedInBody + ') to ' + where + ', the app took it (' + first.response.status + ') - to check, its effect was not visible.',
434
+ proof: [],
435
+ };
436
+ for (const a of list.slice(0, 3)) f.proof.push.apply(f.proof, proofOf(a));
437
+ if (list.length > 3) f.proof.push('... and ' + (list.length - 3) + ' more like it.');
438
+ f.proof.push('Nothing the app shows changed, so this is not proven: the app may have stored it, or ignored it. Check by hand whether ' + where + ' looks up ' + first.namedInBody + ' in the caller\'s own organization.');
439
+ f.fixPrompt = fixPrompt(f);
440
+ out.push(f);
441
+ continue;
442
+ }
422
443
  const action = (journey.actions || []).find((x) => x.method === first.method && x.template === first.template) || {};
423
444
  const unguarded = action.mapAuth === map.STATUS.NOT;
424
445
  const f = {
@@ -790,6 +811,9 @@ const GHOST_ID = '999999999';
790
811
  // Never changed to see if a change is kept: what decides who may do what, money, or a way in.
791
812
  const NOT_TO_CHANGE = /^(id|uuid|email|mail|password|secret|token|key|url|link|role|roles|status|state|type|kind|owner|org|organization|tenant|team|workspace|plan|amount|price|cost|total|currency|deleted|archived|created|updated|limit|cents)$/i;
792
813
 
814
+ // A field that holds where a record is in its life: open, approved, closed.
815
+ const STATE_FIELD = /^(status|state|stage)$/i;
816
+
793
817
  /** The value of a field in an answer, at the top or one level down (settings.timezone); camelCase and snake_case are the same. */
794
818
  function valueIn(json, field) {
795
819
  const flat = (k) => String(k).split('_').join('').toLowerCase();
@@ -824,9 +848,10 @@ async function runKept(root, options) {
824
848
  const plan = planOf(root, opts);
825
849
  if (!plan.ran) return { ran: false, why: plan.why };
826
850
  const j = plan.journey;
827
- const reads = new Set((plan.map.routes || []).filter((r) => r.method === 'GET' && !r.unmounted && r.path).map((r) => r.path));
851
+ const reads = new Set((plan.map.routes || []).filter((r) => r.method === 'GET' && !r.unmounted && r.path).map((r) => normRoute(r.path)));
828
852
  const routes = j.actions.filter((a) => /^(PATCH|PUT)$/.test(a.method) && !a.params.length && reads.has(a.template));
829
- if (!routes.length) return { ran: false, why: 'no change route is also read at the same address' };
853
+ const states = j.actions.filter((a) => /^(PATCH|PUT|POST)$/.test(a.method) && a.params.length === 1 && (a.fields || []).some((f) => STATE_FIELD.test(f.name)));
854
+ if (!routes.length && !states.length) return { ran: false, why: 'no change route is also read at the same address, and none sets a status on one record' };
830
855
  let origin;
831
856
  try {
832
857
  origin = authz.assertLocalTarget(opts.origin);
@@ -883,16 +908,93 @@ async function runKept(root, options) {
883
908
  break;
884
909
  }
885
910
  }
911
+ // A status set on one record (PATCH /api/tickets/{id}/status { status }): a word that is no status is sent to a
912
+ // record the account can list, then read back on the record's own address or in the list. Kept = any word is a
913
+ // status, with no list of the allowed ones or of the moves between them (round 26 W26-07, round 27 R27-19). It is
914
+ // put back at once; only the status is sent, so nothing else moves.
915
+ const recordsIn = (r) => (r.status === 200 ? (Array.isArray(r.json) ? r.json : r.json && typeof r.json === 'object' ? Object.values(r.json).find(Array.isArray) : null) : null);
916
+ for (const a of states) {
917
+ const what = a.method + ' ' + a.template;
918
+ const field = a.fields.find((f) => STATE_FIELD.test(f.name)).name;
919
+ const t = { what, field, verdict: 'no account was let in' };
920
+ out.tried.push(t);
921
+ const listTemplate = '/' + a.segs.slice(0, a.params[0].index).join('/');
922
+ const detail = listTemplate + '/{id}';
923
+ for (const s of sessions) {
924
+ const recs = recordsIn(await s.send('GET', listTemplate, {}));
925
+ // the record's own address first: a list may leave the status out
926
+ const readBack = async (rec) => {
927
+ if (reads.has(detail)) {
928
+ const d = await s.send('GET', detail.replace('{id}', encodeURIComponent(String(rec.id))), {});
929
+ const v = d.status === 200 ? valueIn(d.json, field) : undefined;
930
+ if (v !== undefined) return v;
931
+ }
932
+ const again = recordsIn(await s.send('GET', listTemplate, {}));
933
+ const x = again && again.find((y) => y && String(y.id) === String(rec.id));
934
+ return x ? valueIn(x, field) : undefined;
935
+ };
936
+ const rec = recs && recs.find((x) => x && x.id !== undefined);
937
+ const old = rec ? await readBack(rec) : undefined;
938
+ if (old === undefined) { t.verdict = 'no record with a ' + field + ' at GET ' + listTemplate + (reads.has(detail) ? ' or GET ' + detail : ''); continue; }
939
+ const word = 'kx-no-such-' + field.toLowerCase();
940
+ const at = a.template.replace('{id}', encodeURIComponent(String(rec.id)));
941
+ const sendState = (v) => s.send(a.method, at, a.encoding === 'form' ? { form: { [field]: v } } : { json: { [field]: v } });
942
+ const res = await sendState(word);
943
+ const reply = authz.replyOf(res);
944
+ t.by = s.email;
945
+ t.record = rec.id;
946
+ if (reply.kind !== 'accepted' && reply.kind !== 'redirect') {
947
+ t.verdict = 'turned away (' + res.status + ')';
948
+ // not this account's to change: the next one may be; any other refusal is about the value
949
+ if ([401, 403, 404].includes(res.status)) continue;
950
+ break;
951
+ }
952
+ const now = await readBack(rec);
953
+ if (now !== word) {
954
+ t.verdict = 'answered ' + res.status + ', but ' + field + ' is still "' + now + '"';
955
+ break;
956
+ }
957
+ t.verdict = 'kept';
958
+ const back = await sendState(old);
959
+ const again = await readBack(rec);
960
+ const putBack = again === old;
961
+ if (!putBack) out.left.push(at + ': ' + field + ' is now "' + again + '" (it was "' + old + '"; putting it back answered ' + back.status + ')');
962
+ const finding = {
963
+ kind: 'state-any', where: what, field, from: a.from.file + ':' + a.from.line, status: 'confirmed', severity: 'MEDIUM',
964
+ headline: what + ' stored ' + field + ' "' + word + '", a word that is no ' + field + ': any value is taken, with no list of the allowed ones or of the moves between them.',
965
+ proof: ['As ' + s.email + ', read record ' + rec.id + ': ' + field + ' = "' + old + '".', 'Sent ' + a.method + ' ' + at + ' with only ' + field + ' = "' + word + '": answered ' + res.status + ' (' + reply.note + ').', 'Read it back: ' + field + ' = "' + now + '".', putBack ? 'Then put it back to "' + old + '".' : 'Putting it back did NOT work - look at it.'],
966
+ };
967
+ finding.fixPrompt = ['Kryptheon set a status on my running app that is not one of its statuses, and it was stored:', '', finding.headline, '', 'Where: ' + finding.from, '',
968
+ 'First check this is real. If it is, keep the list of allowed values of ' + field + ' and which one may follow which (for example open -> in_progress -> done), and refuse anything else with a 400 or 409, on the server, before anything is stored. Change nothing else.', '', 'Afterwards I will run: npx kryptheon api'].join(String.fromCharCode(10));
969
+ out.findings.push(finding);
970
+ break;
971
+ }
972
+ }
886
973
  return out;
887
974
  }
888
975
 
889
976
  // --- a job run twice ------------------------------------------------------------
890
977
 
891
- // A route that runs a job: /jobs/..., or one named for what jobs do.
892
- const JOB_PATH = /(^|\/)(jobs?|cron|tasks?\/run|reminders?|digest|notify[\w-]*|sync|overdue|batch)(\/|$)/i;
978
+ // A route that runs a job: /jobs/..., one named for what jobs do, or one that ends in "run" (/maintenance/run, round 27).
979
+ const JOB_PATH = /(^|\/)(jobs?|cron|tasks?\/run|reminders?|digest|notify[\w-]*|sync|overdue|batch)(\/|$)|\/run$/i;
893
980
  // What a job's answer counts: created 3, sent: 12, notified: 2.
894
981
  const COUNT_KEY = /^(created|inserted|sent|queued|notified|processed|affected|rows|count|total|emails|events|reminders|jobs)$/i;
895
982
 
983
+ /** The organizations the records in an answer are marked with (organization_id: 2), as text. */
984
+ function orgsIn(json) {
985
+ const out = new Set();
986
+ const walk = (v, depth) => {
987
+ if (depth > 4 || v == null || typeof v !== 'object') return;
988
+ if (Array.isArray(v)) return v.forEach((x) => walk(x, depth + 1));
989
+ for (const k of Object.keys(v)) {
990
+ if (roles.ORG_KEY.test(k) && ['string', 'number'].includes(typeof v[k])) out.add(String(v[k]));
991
+ else walk(v[k], depth + 1);
992
+ }
993
+ };
994
+ walk(json, 0);
995
+ return out;
996
+ }
997
+
896
998
  /** The counts a job's answer gives: { created: 3 }. */
897
999
  function countsIn(json) {
898
1000
  const out = {};
@@ -920,7 +1022,7 @@ async function runJobs(root, options) {
920
1022
  return { ran: false, why: 'the app must be on this computer (localhost or 127.0.0.1): ' + (opts.origin || 'no address was given') };
921
1023
  }
922
1024
  if (!j.signIn) return { ran: false, why: j.signInWhy };
923
- const ctx = authz.makeContext({ baseUrl: origin, allowOrigins: [origin], fetch: opts.fetch, passwords: Object.fromEntries(j.accounts.usable.map((a) => [a.email, a.password])), maxRequests: 80 });
1025
+ const ctx = authz.makeContext({ baseUrl: origin, allowOrigins: [origin], fetch: opts.fetch, passwords: Object.fromEntries(j.accounts.usable.map((a) => [a.email, a.password])), maxRequests: 200 });
924
1026
  const sessions = [];
925
1027
  for (const a of j.accounts.usable) {
926
1028
  const s = authz.makeSession(ctx, 'account', a.email, a.password);
@@ -929,23 +1031,61 @@ async function runJobs(root, options) {
929
1031
  if (r.kind !== 'refused' && r.kind !== 'server-error' && r.kind !== 'no-answer') sessions.push(s);
930
1032
  }
931
1033
  if (!sessions.length) return { ran: false, why: 'no account with a password in .env could sign in' };
1034
+ const lists = j.actions.filter((x) => x.method === 'GET' && !x.params.length).map((x) => x.template);
932
1035
  const out = { ran: true, tried: [], findings: [], left: [] };
933
1036
  for (const a of routes) {
934
1037
  const what = a.method + ' ' + a.template;
935
1038
  const send = (s) => s.send(a.method, a.template, a.encoding === 'form' ? { form: a.fullData || {} } : { json: a.fullData || {} });
936
1039
  let first = null;
937
1040
  let by = null;
1041
+ let crash = null;
938
1042
  for (const s of sessions) {
939
1043
  const res = await send(s);
940
1044
  const reply = authz.replyOf(res);
941
1045
  if (reply.kind === 'accepted' || reply.kind === 'redirect') { first = res; by = s; break; }
1046
+ if (res.status >= 500 && !crash) crash = { res, s };
1047
+ }
1048
+ // a job that fails when it runs is not a refusal (round 28: the settlement job answered 500 whenever there was a
1049
+ // paid order to settle - its own SQL named a column the table does not have)
1050
+ if (!first && crash) {
1051
+ out.tried.push({ what, by: crash.s.email, verdict: 'crashed (' + crash.res.status + ')' });
1052
+ const finding = {
1053
+ kind: 'job-crash', where: what, from: a.from.file + ':' + a.from.line, status: 'confirmed', severity: 'LOW',
1054
+ headline: what + ' answered ' + crash.res.status + ' when ' + crash.s.email + ' ran it, with nothing wrong in the request: the job fails when it has work to do.',
1055
+ proof: ['As ' + crash.s.email + ', sent ' + what + '.', 'The answer: ' + crash.res.status + ' ' + authz.clip(crash.res.text, 120)],
1056
+ };
1057
+ finding.fixPrompt = ['Kryptheon ran a job of my app and it failed:', '', finding.headline, '', 'Where: ' + finding.from, '',
1058
+ 'Look at the server log for this request: the job\'s query or code fails on the data it reads. Fix that one cause, then run the job twice in a row to see it does its work once. Change nothing else.', '', 'Afterwards I will run: npx kryptheon api'].join(String.fromCharCode(10));
1059
+ out.findings.push(finding);
1060
+ continue;
942
1061
  }
943
1062
  if (!first) { out.tried.push({ what, verdict: 'no account was let in' }); continue; }
1063
+ // The rows a job's answer gives, each marked with its organization (round 27 R27-22: /maintenance/run made every
1064
+ // organization's reminders). The caller's own organization is the one its own lists are marked with; one the job's answer holds that none of
1065
+ // them shows is another's (round 27: maya of organization 1 made organization 2's reminder). With no marks in the
1066
+ // lists, two organizations in one answer still tell.
1067
+ const orgs = orgsIn(first.json);
1068
+ const own = new Set();
1069
+ if (orgs.size) for (const t of lists) {
1070
+ const r = await by.send('GET', t, {});
1071
+ if (r.status === 200) for (const o of orgsIn(r.json)) own.add(o);
1072
+ }
1073
+ const foreign = Array.from(orgs).filter((o) => !own.has(o));
1074
+ if (own.size ? foreign.length > 0 : orgs.size >= 2) {
1075
+ const finding = {
1076
+ kind: 'tenant-job', where: what, from: a.from.file + ':' + a.from.line, status: 'confirmed', severity: 'HIGH',
1077
+ headline: 'Run once by ' + by.email + ', ' + what + ' answered with records of ' + (own.size ? 'organization ' + foreign.slice(0, 3).join(', ') + ', which none of ' + by.email + '\'s own lists shows (theirs: ' + Array.from(own).slice(0, 3).join(', ') + ')' : orgs.size + ' organizations (' + Array.from(orgs).slice(0, 4).join(', ') + ')') + ': the job works on, and shows, other organizations\' records.',
1078
+ proof: ['As ' + by.email + ', sent ' + what + ' once.', 'The answer: ' + authz.clip(first.text, 160)],
1079
+ };
1080
+ finding.fixPrompt = ['Kryptheon ran a job of my app as one organization\'s account:', '', finding.headline, '', 'Where: ' + finding.from, '',
1081
+ 'First check this is real. If it is, limit what the job reads and writes to the caller\'s organization (WHERE organization_id = the signed-in user\'s), or make it a job only the system runs, not a route an organization can call. Change nothing else.', '', 'Afterwards I will run: npx kryptheon api'].join(String.fromCharCode(10));
1082
+ out.findings.push(finding);
1083
+ }
944
1084
  const second = await send(by);
945
1085
  const c1 = countsIn(first.json);
946
1086
  const c2 = countsIn(second.json);
947
1087
  const again = Object.keys(c1).filter((k) => c1[k] > 0 && c2[k] === c1[k]);
948
- out.tried.push({ what, by: by.email, first: c1, second: c2, verdict: again.length ? 'made the same again' : Object.keys(c1).length ? 'held' : 'no count to compare' });
1088
+ out.tried.push({ what, by: by.email, first: c1, second: c2, verdict: again.length ? 'made the same again' : !Object.keys(c1).length ? 'no count to compare' : Object.values(c1).every((v) => !v) && Object.values(c2).every((v) => !v) ? 'nothing to do either time' : 'held' });
949
1089
  out.left.push(what + ' run twice as ' + by.email + (Object.keys(c1).length ? ' (' + JSON.stringify(c1) + ', then ' + JSON.stringify(c2) + ')' : ''));
950
1090
  if (!again.length) continue;
951
1091
  const k = again[0];
@@ -961,6 +1101,132 @@ async function runJobs(root, options) {
961
1101
  return out;
962
1102
  }
963
1103
 
1104
+ // --- a create sent twice at once ------------------------------------------------
1105
+
1106
+ // Records a second copy of costs something: money, a delivery, someone's time.
1107
+ const COSTLY_RECORD = /(^|[\/_-])(orders?|payments?|invoices?|deliver(y|ies)|shipments?|bookings?|reservations?|transfers?|refunds?|payouts?|charges?|subscriptions?|appointments?)$/i;
1108
+
1109
+ /**
1110
+ * Each create route for a costly record (POST /api/work-orders, /api/payments) that the app also lists at the same
1111
+ * address: the same body sent twice at once, as a double click sends it. Two new records with the same fields = no
1112
+ * guard against a repeated submit (round 26 W26-20/25, round 27 R27-13). One new record = held. Nothing is deleted;
1113
+ * what was made is listed as left. { ran, why, tried, findings, left }.
1114
+ */
1115
+ async function runCreates(root, options) {
1116
+ const opts = options || {};
1117
+ const plan = planOf(root, opts);
1118
+ if (!plan.ran) return { ran: false, why: plan.why };
1119
+ const j = plan.journey;
1120
+ const lists = new Set(j.actions.filter((x) => x.method === 'GET' && !x.params.length).map((x) => x.template));
1121
+ // a create with its parent's id in the address (POST /api/invoices/{orderId}/payment-order, round 28): aimed at a
1122
+ // record of the list its id is named for (orderId: /api/orders), or of the list its address starts with
1123
+ const singular = (w) => w.replace(/ies$/, 'y').replace(/s$/, '');
1124
+ const parentListOf = (a) => {
1125
+ const r = (plan.map.routes || []).find((x) => x.method === a.method && normRoute(x.path || '') === a.template);
1126
+ const m = r && /:(\w+)/.exec(r.path);
1127
+ const stem = m ? singular(m[1].replace(/_?[iI]d$/, '').toLowerCase()) : '';
1128
+ const named = stem && Array.from(lists).find((l) => singular(l.split('/').pop().toLowerCase().replace(/[^a-z]/g, '')) === stem);
1129
+ const head = '/' + a.segs.slice(0, a.params[0].index).join('/');
1130
+ return named || (lists.has(head) ? head : null);
1131
+ };
1132
+ const routes = j.actions.filter((a) => a.method === 'POST' && COSTLY_RECORD.test(a.template) && !JOB_PATH.test(a.template) &&
1133
+ (a.params.length ? a.params.length === 1 && parentListOf(a) : lists.has(a.template)));
1134
+ if (!routes.length) return { ran: false, why: 'no create route of an order, payment or delivery is also listed at its address' };
1135
+ let origin;
1136
+ try {
1137
+ origin = authz.assertLocalTarget(opts.origin);
1138
+ } catch (err) {
1139
+ return { ran: false, why: 'the app must be on this computer (localhost or 127.0.0.1): ' + (opts.origin || 'no address was given') };
1140
+ }
1141
+ if (!j.signIn) return { ran: false, why: j.signInWhy };
1142
+ const ctx = authz.makeContext({ baseUrl: origin, allowOrigins: [origin], fetch: opts.fetch, passwords: Object.fromEntries(j.accounts.usable.map((a) => [a.email, a.password])), maxRequests: 120 });
1143
+ const sessions = [];
1144
+ for (const a of j.accounts.usable) {
1145
+ const s = authz.makeSession(ctx, 'account', a.email, a.password);
1146
+ const f = { [j.signIn.emailField]: a.email, [j.signIn.passwordField]: a.password };
1147
+ const r = authz.replyOf(await s.send(j.signIn.method, j.signIn.path, j.signIn.encoding === 'form' ? { form: f } : { json: f }));
1148
+ if (r.kind !== 'refused' && r.kind !== 'server-error' && r.kind !== 'no-answer') sessions.push(s);
1149
+ }
1150
+ if (!sessions.length) return { ran: false, why: 'no account with a password in .env could sign in' };
1151
+ const recordsIn = (r) => (r.status === 200 ? (Array.isArray(r.json) ? r.json : r.json && typeof r.json === 'object' ? Object.values(r.json).find(Array.isArray) : null) : null);
1152
+ const taken = (res) => { const r = authz.replyOf(res); return r.kind === 'accepted' || r.kind === 'redirect'; };
1153
+ const out = { ran: true, tried: [], findings: [], left: [] };
1154
+ for (const a of routes) {
1155
+ const what = a.method + ' ' + a.template;
1156
+ const t = { what, verdict: 'no account was let in' };
1157
+ out.tried.push(t);
1158
+ const minimal = {};
1159
+ for (const f of a.fields || []) if (f.kinds.length) minimal[f.name] = f.sample;
1160
+ const bodies = [a.fullData || {}].concat(Object.keys(minimal).length && JSON.stringify(minimal) !== JSON.stringify(a.fullData || {}) ? [minimal] : []);
1161
+ for (const s of sessions) {
1162
+ let at = a.template;
1163
+ let parentId = null;
1164
+ if (a.params.length) {
1165
+ const parents = recordsIn(await s.send('GET', parentListOf(a), {}));
1166
+ const parent = parents && parents.find((x) => x && x.id !== undefined);
1167
+ if (!parent) { t.verdict = 'no record at GET ' + parentListOf(a) + ' to aim it at'; continue; }
1168
+ parentId = parent.id;
1169
+ at = a.template.replace('{id}', encodeURIComponent(String(parent.id)));
1170
+ }
1171
+ // its own list, or - when the record it makes lives elsewhere - every list the account reads
1172
+ const watch = a.params.length ? Array.from(lists) : [a.template];
1173
+ const readAll = async () => {
1174
+ const o = {};
1175
+ for (const l of watch) { const r = recordsIn(await s.send('GET', l, {})); if (r) o[l] = r; }
1176
+ return o;
1177
+ };
1178
+ const beforeAll = await readAll();
1179
+ if (!Object.keys(beforeAll).length) continue;
1180
+ let done = null;
1181
+ let answered = [];
1182
+ for (const body of bodies) {
1183
+ const send = () => s.send(a.method, at, a.encoding === 'form' ? { form: body } : { json: body });
1184
+ const [r1, r2] = await Promise.all([send(), send()]);
1185
+ answered = [r1.status, r2.status];
1186
+ if (!taken(r1) && !taken(r2)) continue;
1187
+ done = { body, r1, r2 };
1188
+ break;
1189
+ }
1190
+ // refused both times: the next account may be let in
1191
+ if (!done) { t.verdict = 'refused (' + answered.join(' and ') + ')'; continue; }
1192
+ // the list that gained the most records is where the creates went
1193
+ const afterAll = await readAll();
1194
+ let made = [];
1195
+ let madeIn = watch[0];
1196
+ for (const l of Object.keys(afterAll)) {
1197
+ const had = new Set((beforeAll[l] || []).map((x) => x && JSON.stringify(x.id)));
1198
+ const fresh = afterAll[l].filter((x) => x && x.id !== undefined && !had.has(JSON.stringify(x.id)));
1199
+ if (fresh.length > made.length) { made = fresh; madeIn = l; }
1200
+ }
1201
+ const before = beforeAll[madeIn] || [];
1202
+ const after = afterAll[madeIn] || [];
1203
+ t.by = s.email;
1204
+ t.answers = [done.r1.status, done.r2.status];
1205
+ t.made = made.map((x) => x.id);
1206
+ if (made.length) out.left.push(what + ' sent twice at once as ' + s.email + ': record(s) ' + made.map((x) => x.id).join(', ') + ' (Kryptheon never deletes)');
1207
+ // the same fields the body set, on both records
1208
+ const keys = Object.keys(done.body).filter((k) => made.length && made.every((x) => valueIn(x, k) !== undefined))
1209
+ // and the field that points at the parent the address named (order_id = 1 on both payment orders)
1210
+ .concat(parentId === null || !made.length ? [] : Object.keys(made[0]).filter((k) => k !== 'id' && String(made[0][k]) === String(parentId)));
1211
+ const alike = made.length >= 2 && keys.every((k) => JSON.stringify(valueIn(made[0], k)) === JSON.stringify(valueIn(made[1], k)));
1212
+ t.verdict = alike ? 'made twice' : made.length === 1 ? 'held: one record' : made.length ? 'made ' + made.length + ' different records' : 'nothing new in the list';
1213
+ if (t.verdict === 'made twice') {
1214
+ const finding = {
1215
+ kind: 'create-twice', where: what, from: a.from.file + ':' + a.from.line, status: 'verification required', severity: 'MEDIUM',
1216
+ headline: 'Sent twice at once, as a double click sends it, ' + what + ' made ' + made.length + ' records with the same ' + (keys.slice(0, 3).join(', ') || 'fields') + ' (' + made.map((x) => x.id).join(', ') + '): nothing stops a repeated submit.',
1217
+ proof: ['As ' + s.email + ', sent ' + a.method + ' ' + at + ' twice at the same moment with the same body: ' + authz.clip(JSON.stringify(done.body), 120), 'Answered ' + done.r1.status + ' and ' + done.r2.status + '.', 'GET ' + madeIn + ' before: ' + before.length + ' records; after: ' + after.length + ', new ' + made.map((x) => x.id).join(', ') + '.'],
1218
+ };
1219
+ finding.fixPrompt = ['Kryptheon sent the same create to my running app twice at once, as a double click does:', '', finding.headline, '', 'Where: ' + finding.from, '',
1220
+ 'First check this is real: is a second, identical record ever wanted here? If not, accept an idempotency key from the client (or a fingerprint of the request) and return the first record for a repeat, with a unique index behind it; and disable the submit button while the request is pending. Change nothing else.', '', 'Afterwards I will run: npx kryptheon api'].join(String.fromCharCode(10));
1221
+ out.findings.push(finding);
1222
+ }
1223
+ break;
1224
+ }
1225
+ }
1226
+ return out;
1227
+ }
1228
+
1229
+
964
1230
  /**
965
1231
  * The map's "a status set with no look at the status now" items, tried: the
966
1232
  * step sent for one record, then sent again for the same record. Judged by
@@ -1153,6 +1419,33 @@ const normRoute = (name) => String(name).replace(/:\w+\*?/g, '{id}');
1153
1419
  * organizations; no-role <- the roles run (needs the owner's permissions file);
1154
1420
  * a webhook is the payments check's.
1155
1421
  */
1422
+ /**
1423
+ * How much a "held" says. Strong: some try was refused, or it was a write (a write is held only when refused and
1424
+ * the stored state did not change). Weak: every try was a read the app answered, just without the other side's
1425
+ * records - which may only mean there were none (round 24: notes of a return that had no notes).
1426
+ */
1427
+ function heldStrength(tries) {
1428
+ const denied = tries.filter((a) => a.verdict === V.DENIED);
1429
+ return denied.some((a) => a.method !== 'GET' || (a.response && a.response.reading === 'refused')) ? 'strong' : 'weak';
1430
+ }
1431
+
1432
+ /**
1433
+ * The confidence step between the map and the running app (round 26: five map items the run itself had held were
1434
+ * still shown as HIGH and MEDIUM problems - three of them the answer key's decoys). A map item the running app
1435
+ * strongly held is no longer a thing to fix: it moves to `held`, with what was tried. One held weakly stays, with
1436
+ * why it says little. Everything else stays as it is. { shown, held }
1437
+ */
1438
+ function reconcile(toCheck, verdicts) {
1439
+ const shown = [];
1440
+ const held = [];
1441
+ for (const t of toCheck || []) {
1442
+ const v = (verdicts || []).find((x) => x.route === t.route && x.kind === t.kind);
1443
+ if (v && v.verdict === 'held' && v.strength === 'strong') held.push(Object.assign({}, t, { verdict: v }));
1444
+ else shown.push(Object.assign({}, t, v ? { verdict: v } : {}));
1445
+ }
1446
+ return { shown, held };
1447
+ }
1448
+
1156
1449
  function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1157
1450
  const out = [];
1158
1451
  const attempts = wall && wall.ran ? wall.result.attempts : [];
@@ -1171,6 +1464,7 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1171
1464
  v.finding = hit.headline;
1172
1465
  } else if (tried && /^(refused the second time|nothing moved the second time)$/.test(tried.verdict)) {
1173
1466
  v.verdict = 'held';
1467
+ v.strength = 'strong';
1174
1468
  } else {
1175
1469
  v.verdict = 'not tried';
1176
1470
  v.why = tried ? tried.why || tried.verdict : steps && !steps.ran ? steps.why : 'the step was not sent twice';
@@ -1178,6 +1472,7 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1178
1472
  } else if (t.kind === 'identity-from-request') {
1179
1473
  const hit = forged && forged.ran && forged.findings.find((f) => f.from === t.where);
1180
1474
  v.verdict = hit ? 'confirmed' : forged && forged.ran && forged.tried.length ? 'held' : 'not tried';
1475
+ if (v.verdict === 'held') v.strength = 'strong';
1181
1476
  if (hit) v.finding = hit.headline;
1182
1477
  if (v.verdict === 'not tried') v.why = forged ? forged.why || 'not tried' : 'the forged identity was not tried';
1183
1478
  } else if (/^webhook/.test(t.kind)) {
@@ -1188,6 +1483,7 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1188
1483
  v.finding = hit.headline;
1189
1484
  } else if (hook && hook.control && hook.control.took && hook.tried.some((x) => x.mode === 'none') && !hook.findings.some((f) => /^webhook-(unsigned|forged)$/.test(f.kind))) {
1190
1485
  v.verdict = 'held';
1486
+ v.strength = 'strong';
1191
1487
  } else if (hook && hook.findings.some((f) => /^webhook-(unsigned|forged)$/.test(f.kind))) {
1192
1488
  v.verdict = 'not judged';
1193
1489
  v.why = 'the app answered success without a valid signature, but no change was seen in ' + hook.list;
@@ -1207,6 +1503,8 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1207
1503
  v.finding = rf[0].headline;
1208
1504
  } else if (tries.length && tries.every((a) => a.verdict === V.DENIED || a.verdict === V.ALLOWED)) {
1209
1505
  v.verdict = 'held';
1506
+ v.strength = heldStrength(tries);
1507
+ if (v.strength === 'weak') v.why = 'it answered without the protected records, which may only mean there were none to show';
1210
1508
  } else if (tries.length) {
1211
1509
  v.verdict = 'not judged';
1212
1510
  v.why = (tries.find((a) => a.verdict === V.AMBIGUOUS) || tries[0]).reason;
@@ -1226,6 +1524,8 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1226
1524
  v.finding = hit.headline;
1227
1525
  } else if (mine.length && mine.some((a) => a.verdict === V.DENIED || a.verdict === V.ALLOWED) && !mine.some((a) => a.verdict === V.AMBIGUOUS)) {
1228
1526
  v.verdict = 'held';
1527
+ v.strength = heldStrength(mine);
1528
+ if (v.strength === 'weak') v.why = 'it answered without the other organization\'s records, which may only mean it had none to show';
1229
1529
  } else if (mine.length) {
1230
1530
  v.verdict = 'not judged';
1231
1531
  v.why = (mine.find((a) => a.verdict === V.AMBIGUOUS) || mine[0]).reason;
@@ -1336,12 +1636,15 @@ async function runApi(root, options) {
1336
1636
  if (!m.ran) return { ran: false, why: m.why };
1337
1637
  const toCheck = opts.toCheck || map.toCheck(m);
1338
1638
  const shared = Object.assign({}, opts, { map: m, say: say });
1639
+ // jobs first, on the app as it was seeded: the tries after them cancel and refund the records a job works on
1640
+ // (round 28: the settlement job found no paid order left and made nothing either time)
1641
+ const jobsRun = await runJobs(root, shared);
1339
1642
  const wall = await runWall(root, shared);
1340
1643
  const forged = await runForged(root, shared);
1341
1644
  const webhooks = await webhook.run(root, shared);
1342
1645
  const exportsRun = await csv.run(root, shared);
1343
- const jobsRun = await runJobs(root, shared);
1344
1646
  const keptRun = await runKept(root, shared);
1647
+ const createsRun = await runCreates(root, shared);
1345
1648
  const stepsRun = await runSteps(root, Object.assign({}, shared, { toCheck: toCheck }));
1346
1649
  let roleRun = null;
1347
1650
  if (opts.roles) roleRun = await runRoles(root, shared);
@@ -1349,14 +1652,14 @@ async function runApi(root, options) {
1349
1652
  const invalid = await runInvalid(root, shared);
1350
1653
  const verdicts = verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, stepsRun);
1351
1654
  const seen = new Set();
1352
- const findings = (wall.ran ? wall.findings : []).concat(forged.ran ? forged.findings : []).concat(webhooks.ran ? webhooks.findings : []).concat(exportsRun.ran ? exportsRun.findings : []).concat(jobsRun.ran ? jobsRun.findings : []).concat(keptRun.ran ? keptRun.findings : []).concat(stepsRun.ran ? stepsRun.findings : []).concat(roleRun && roleRun.ran ? roleRun.findings : []).concat(invalid.ran ? invalid.findings : []).filter((f) => {
1655
+ const findings = (wall.ran ? wall.findings : []).concat(forged.ran ? forged.findings : []).concat(webhooks.ran ? webhooks.findings : []).concat(exportsRun.ran ? exportsRun.findings : []).concat(jobsRun.ran ? jobsRun.findings : []).concat(keptRun.ran ? keptRun.findings : []).concat(createsRun.ran ? createsRun.findings : []).concat(stepsRun.ran ? stepsRun.findings : []).concat(roleRun && roleRun.ran ? roleRun.findings : []).concat(invalid.ran ? invalid.findings : []).filter((f) => {
1353
1656
  const k = f.kind + '|' + f.where + '|' + (f.field || '');
1354
1657
  return seen.has(k) ? false : (seen.add(k), true);
1355
1658
  });
1356
- const left = (webhooks.ran ? webhooks.left : []).concat(exportsRun.ran ? exportsRun.left : []).concat(jobsRun.ran ? jobsRun.left : []).concat(keptRun.ran ? keptRun.left : []).concat(stepsRun.ran ? stepsRun.left : []).concat(wall.ran ? wall.result.seeded || [] : []).concat(roleRun && roleRun.ran ? roleRun.result.seeded || [] : []).concat(wall.ran ? leftBehind(wall.result.attempts) : []).concat(invalid.ran ? invalid.left : []).concat(roleRun && roleRun.ran ? leftBehind(roleRun.result.attempts) : []);
1659
+ const left = (webhooks.ran ? webhooks.left : []).concat(exportsRun.ran ? exportsRun.left : []).concat(jobsRun.ran ? jobsRun.left : []).concat(keptRun.ran ? keptRun.left : []).concat(createsRun.ran ? createsRun.left : []).concat(stepsRun.ran ? stepsRun.left : []).concat(wall.ran ? wall.result.seeded || [] : []).concat(roleRun && roleRun.ran ? roleRun.result.seeded || [] : []).concat(wall.ran ? leftBehind(wall.result.attempts) : []).concat(invalid.ran ? invalid.left : []).concat(roleRun && roleRun.ran ? leftBehind(roleRun.result.attempts) : []);
1357
1660
  return {
1358
1661
  ran: wall.ran || invalid.ran, why: wall.ran || invalid.ran ? null : wall.why, checkedAt: new Date().toISOString(),
1359
- origin: opts.origin, wall: wall, forged: forged, webhooks: webhooks, exports: exportsRun, jobs: jobsRun, kept: keptRun, steps: stepsRun, invalid: invalid, roles: roleRun, verdicts: verdicts, findings: findings, left: left,
1662
+ origin: opts.origin, wall: wall, forged: forged, webhooks: webhooks, exports: exportsRun, jobs: jobsRun, kept: keptRun, creates: createsRun, steps: stepsRun, invalid: invalid, roles: roleRun, verdicts: verdicts, findings: findings, left: left,
1360
1663
  notTried: (wall.plan ? wall.plan.notTried : []).concat(invalid.ran ? invalid.notTried : []),
1361
1664
  };
1362
1665
  }
@@ -1416,7 +1719,10 @@ function apiLines(run) {
1416
1719
  out.push(' Webhook ' + h.route + ': not tried - ' + h.notTried);
1417
1720
  continue;
1418
1721
  }
1419
- out.push(' Webhook ' + h.route + ' (' + h.signing.header + ', ' + h.signing.algorithm + ' ' + h.signing.encoding + ' over ' + h.signing.signs + '): a correctly signed event was taken; ' + h.tried.filter((t) => t !== h.control && t.took).length + ' of ' + (h.tried.length - 1) + ' other tries were taken, ' + h.tried.filter((t) => t.changed && t !== h.control).length + ' changed a record');
1722
+ const how = h.signing.open
1723
+ ? ' (it checks no signature at all): an event with none was taken'
1724
+ : ' (' + h.signing.header + ', ' + h.signing.algorithm + ' ' + h.signing.encoding + ' over ' + h.signing.signs + '): a correctly signed ' + (h.neutral ? 'event of a type it does not act on' : 'event') + ' was taken';
1725
+ out.push(' Webhook ' + h.route + how + '; ' + h.tried.filter((t) => t !== h.control && t.took).length + ' of ' + (h.tried.length - 1) + ' other tries were taken, ' + h.tried.filter((t) => t.changed && t !== h.control).length + ' changed a record' + (h.list ? '' : ' (no list to read a change from)'));
1420
1726
  for (const f of h.findings) {
1421
1727
  out.push(' ' + (f.status === 'confirmed' ? 'PROBLEM' : 'TO CHECK') + ' ' + f.severity + ' ' + f.headline + ' (' + f.from + ')');
1422
1728
  for (const l of f.proof) out.push(' ' + l);
@@ -1450,6 +1756,14 @@ function apiLines(run) {
1450
1756
  }
1451
1757
  out.push('');
1452
1758
  }
1759
+ if (run.creates && run.creates.ran) {
1760
+ for (const t of run.creates.tried) out.push(' Create ' + t.what + ' sent twice at once: ' + t.verdict + (t.answers ? ' (answered ' + t.answers.join(' and ') + (t.made && t.made.length ? '; new ' + t.made.join(', ') : '') + ')' : ''));
1761
+ for (const f of run.creates.findings) {
1762
+ out.push(' TO CHECK ' + f.severity + ' ' + f.headline + ' (' + f.from + ')');
1763
+ for (const l of f.proof) out.push(' ' + l);
1764
+ }
1765
+ out.push('');
1766
+ }
1453
1767
  if (run.steps && run.steps.ran) {
1454
1768
  for (const t of run.steps.tried) out.push(' Step ' + t.what + ' sent twice: ' + t.verdict + (t.record !== undefined ? ' (record ' + t.record + ', answered ' + t.first + ', then ' + t.second + ')' : ''));
1455
1769
  for (const f of run.steps.findings) {
@@ -1475,7 +1789,9 @@ function apiLines(run) {
1475
1789
  }
1476
1790
  if (run.verdicts.length) {
1477
1791
  out.push(' What the map pointed at (' + run.verdicts.length + '): ' + counts.confirmed + ' confirmed on the running app, ' + counts.held + ' held, ' + counts['not judged'] + ' not judged, ' + counts['not tried'] + ' not tried');
1478
- for (const v of run.verdicts) out.push(' ' + v.verdict.toUpperCase() + ' ' + v.route + ' - ' + v.kind + (v.why ? ' (' + v.why + ')' : ''));
1792
+ for (const v of run.verdicts) out.push(' ' + (v.verdict === 'held' && v.strength === 'weak' ? 'HELD WEAKLY' : v.verdict.toUpperCase()) + ' ' + v.route + ' - ' + v.kind + (v.why ? ' (' + v.why + ')' : ''));
1793
+ const strong = run.verdicts.filter((v) => v.verdict === 'held' && v.strength === 'strong').length;
1794
+ if (strong) out.push(' The ' + strong + ' held for certain (refused, or nothing changed) are no longer things to fix: the dashboard keeps them apart.');
1479
1795
  out.push('');
1480
1796
  }
1481
1797
  const extra = run.invalid && run.invalid.ran ? run.invalid.left : [];
@@ -1487,4 +1803,4 @@ function apiLines(run) {
1487
1803
  return out;
1488
1804
  }
1489
1805
 
1490
- module.exports = { runSteps, numbersMoved, runKept, valueIn, plainFieldOf, runJobs, countsIn, JOB_PATH, runForged, personIn, REPORT_FILE, verdictsFor, runApi, reportOf, saveReport, apiLines, badValueFor, runInvalid, signInOf, emailsIn, accountsOf, wordsOf, sampleValue, allowedByName, actionOf, journeyFromMap, planOf, planLines, wallPolicy, runWall, findingsOf, fixPrompt, leftBehind, wallLines, DRAFT_FILE, permissionName, draftPolicy, writeDraft, runRoles };
1806
+ module.exports = { reconcile, heldStrength, runSteps, numbersMoved, runKept, runCreates, COSTLY_RECORD, valueIn, plainFieldOf, runJobs, countsIn, JOB_PATH, runForged, personIn, REPORT_FILE, verdictsFor, runApi, reportOf, saveReport, apiLines, badValueFor, runInvalid, signInOf, emailsIn, accountsOf, wordsOf, sampleValue, allowedByName, actionOf, journeyFromMap, planOf, planLines, wallPolicy, runWall, findingsOf, fixPrompt, leftBehind, wallLines, DRAFT_FILE, permissionName, draftPolicy, writeDraft, runRoles };