kryptheon 0.1.58 → 0.1.61

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,6 +1031,7 @@ 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;
@@ -941,6 +1044,27 @@ async function runJobs(root, options) {
941
1044
  if (reply.kind === 'accepted' || reply.kind === 'redirect') { first = res; by = s; break; }
942
1045
  }
943
1046
  if (!first) { out.tried.push({ what, verdict: 'no account was let in' }); continue; }
1047
+ // The rows a job's answer gives, each marked with its organization (round 27 R27-22: /maintenance/run made every
1048
+ // 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
1049
+ // them shows is another's (round 27: maya of organization 1 made organization 2's reminder). With no marks in the
1050
+ // lists, two organizations in one answer still tell.
1051
+ const orgs = orgsIn(first.json);
1052
+ const own = new Set();
1053
+ if (orgs.size) for (const t of lists) {
1054
+ const r = await by.send('GET', t, {});
1055
+ if (r.status === 200) for (const o of orgsIn(r.json)) own.add(o);
1056
+ }
1057
+ const foreign = Array.from(orgs).filter((o) => !own.has(o));
1058
+ if (own.size ? foreign.length > 0 : orgs.size >= 2) {
1059
+ const finding = {
1060
+ kind: 'tenant-job', where: what, from: a.from.file + ':' + a.from.line, status: 'confirmed', severity: 'HIGH',
1061
+ 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.',
1062
+ proof: ['As ' + by.email + ', sent ' + what + ' once.', 'The answer: ' + authz.clip(first.text, 160)],
1063
+ };
1064
+ finding.fixPrompt = ['Kryptheon ran a job of my app as one organization\'s account:', '', finding.headline, '', 'Where: ' + finding.from, '',
1065
+ '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));
1066
+ out.findings.push(finding);
1067
+ }
944
1068
  const second = await send(by);
945
1069
  const c1 = countsIn(first.json);
946
1070
  const c2 = countsIn(second.json);
@@ -961,6 +1085,94 @@ async function runJobs(root, options) {
961
1085
  return out;
962
1086
  }
963
1087
 
1088
+ // --- a create sent twice at once ------------------------------------------------
1089
+
1090
+ // Records a second copy of costs something: money, a delivery, someone's time.
1091
+ const COSTLY_RECORD = /(^|[\/_-])(orders?|payments?|invoices?|deliver(y|ies)|shipments?|bookings?|reservations?|transfers?|refunds?|payouts?|charges?|subscriptions?|appointments?)$/i;
1092
+
1093
+ /**
1094
+ * Each create route for a costly record (POST /api/work-orders, /api/payments) that the app also lists at the same
1095
+ * address: the same body sent twice at once, as a double click sends it. Two new records with the same fields = no
1096
+ * guard against a repeated submit (round 26 W26-20/25, round 27 R27-13). One new record = held. Nothing is deleted;
1097
+ * what was made is listed as left. { ran, why, tried, findings, left }.
1098
+ */
1099
+ async function runCreates(root, options) {
1100
+ const opts = options || {};
1101
+ const plan = planOf(root, opts);
1102
+ if (!plan.ran) return { ran: false, why: plan.why };
1103
+ const j = plan.journey;
1104
+ const lists = new Set(j.actions.filter((x) => x.method === 'GET' && !x.params.length).map((x) => x.template));
1105
+ const routes = j.actions.filter((a) => a.method === 'POST' && !a.params.length && lists.has(a.template) && COSTLY_RECORD.test(a.template) && !JOB_PATH.test(a.template));
1106
+ if (!routes.length) return { ran: false, why: 'no create route of an order, payment or delivery is also listed at its address' };
1107
+ let origin;
1108
+ try {
1109
+ origin = authz.assertLocalTarget(opts.origin);
1110
+ } catch (err) {
1111
+ return { ran: false, why: 'the app must be on this computer (localhost or 127.0.0.1): ' + (opts.origin || 'no address was given') };
1112
+ }
1113
+ if (!j.signIn) return { ran: false, why: j.signInWhy };
1114
+ 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 });
1115
+ const sessions = [];
1116
+ for (const a of j.accounts.usable) {
1117
+ const s = authz.makeSession(ctx, 'account', a.email, a.password);
1118
+ const f = { [j.signIn.emailField]: a.email, [j.signIn.passwordField]: a.password };
1119
+ const r = authz.replyOf(await s.send(j.signIn.method, j.signIn.path, j.signIn.encoding === 'form' ? { form: f } : { json: f }));
1120
+ if (r.kind !== 'refused' && r.kind !== 'server-error' && r.kind !== 'no-answer') sessions.push(s);
1121
+ }
1122
+ if (!sessions.length) return { ran: false, why: 'no account with a password in .env could sign in' };
1123
+ 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);
1124
+ const taken = (res) => { const r = authz.replyOf(res); return r.kind === 'accepted' || r.kind === 'redirect'; };
1125
+ const out = { ran: true, tried: [], findings: [], left: [] };
1126
+ for (const a of routes) {
1127
+ const what = a.method + ' ' + a.template;
1128
+ const t = { what, verdict: 'no account was let in' };
1129
+ out.tried.push(t);
1130
+ const minimal = {};
1131
+ for (const f of a.fields || []) if (f.kinds.length) minimal[f.name] = f.sample;
1132
+ const bodies = [a.fullData || {}].concat(Object.keys(minimal).length && JSON.stringify(minimal) !== JSON.stringify(a.fullData || {}) ? [minimal] : []);
1133
+ for (const s of sessions) {
1134
+ const before = recordsIn(await s.send('GET', a.template, {}));
1135
+ if (!before) continue;
1136
+ const had = new Set(before.map((x) => x && JSON.stringify(x.id)));
1137
+ let done = null;
1138
+ let answered = [];
1139
+ for (const body of bodies) {
1140
+ const send = () => s.send(a.method, a.template, a.encoding === 'form' ? { form: body } : { json: body });
1141
+ const [r1, r2] = await Promise.all([send(), send()]);
1142
+ answered = [r1.status, r2.status];
1143
+ if (!taken(r1) && !taken(r2)) continue;
1144
+ done = { body, r1, r2 };
1145
+ break;
1146
+ }
1147
+ // refused both times: the next account may be let in
1148
+ if (!done) { t.verdict = 'refused (' + answered.join(' and ') + ')'; continue; }
1149
+ const after = recordsIn(await s.send('GET', a.template, {})) || [];
1150
+ const made = after.filter((x) => x && x.id !== undefined && !had.has(JSON.stringify(x.id)));
1151
+ t.by = s.email;
1152
+ t.answers = [done.r1.status, done.r2.status];
1153
+ t.made = made.map((x) => x.id);
1154
+ 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)');
1155
+ // the same fields the body set, on both records
1156
+ const keys = Object.keys(done.body).filter((k) => made.length && made.every((x) => valueIn(x, k) !== undefined));
1157
+ const alike = made.length >= 2 && keys.every((k) => JSON.stringify(valueIn(made[0], k)) === JSON.stringify(valueIn(made[1], k)));
1158
+ t.verdict = alike ? 'made twice' : made.length === 1 ? 'held: one record' : made.length ? 'made ' + made.length + ' different records' : 'nothing new in the list';
1159
+ if (t.verdict === 'made twice') {
1160
+ const finding = {
1161
+ kind: 'create-twice', where: what, from: a.from.file + ':' + a.from.line, status: 'verification required', severity: 'MEDIUM',
1162
+ 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.',
1163
+ proof: ['As ' + s.email + ', sent ' + what + ' 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 ' + a.template + ' before: ' + before.length + ' records; after: ' + after.length + ', new ' + made.map((x) => x.id).join(', ') + '.'],
1164
+ };
1165
+ finding.fixPrompt = ['Kryptheon sent the same create to my running app twice at once, as a double click does:', '', finding.headline, '', 'Where: ' + finding.from, '',
1166
+ '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));
1167
+ out.findings.push(finding);
1168
+ }
1169
+ break;
1170
+ }
1171
+ }
1172
+ return out;
1173
+ }
1174
+
1175
+
964
1176
  /**
965
1177
  * The map's "a status set with no look at the status now" items, tried: the
966
1178
  * step sent for one record, then sent again for the same record. Judged by
@@ -1153,6 +1365,33 @@ const normRoute = (name) => String(name).replace(/:\w+\*?/g, '{id}');
1153
1365
  * organizations; no-role <- the roles run (needs the owner's permissions file);
1154
1366
  * a webhook is the payments check's.
1155
1367
  */
1368
+ /**
1369
+ * How much a "held" says. Strong: some try was refused, or it was a write (a write is held only when refused and
1370
+ * the stored state did not change). Weak: every try was a read the app answered, just without the other side's
1371
+ * records - which may only mean there were none (round 24: notes of a return that had no notes).
1372
+ */
1373
+ function heldStrength(tries) {
1374
+ const denied = tries.filter((a) => a.verdict === V.DENIED);
1375
+ return denied.some((a) => a.method !== 'GET' || (a.response && a.response.reading === 'refused')) ? 'strong' : 'weak';
1376
+ }
1377
+
1378
+ /**
1379
+ * The confidence step between the map and the running app (round 26: five map items the run itself had held were
1380
+ * still shown as HIGH and MEDIUM problems - three of them the answer key's decoys). A map item the running app
1381
+ * strongly held is no longer a thing to fix: it moves to `held`, with what was tried. One held weakly stays, with
1382
+ * why it says little. Everything else stays as it is. { shown, held }
1383
+ */
1384
+ function reconcile(toCheck, verdicts) {
1385
+ const shown = [];
1386
+ const held = [];
1387
+ for (const t of toCheck || []) {
1388
+ const v = (verdicts || []).find((x) => x.route === t.route && x.kind === t.kind);
1389
+ if (v && v.verdict === 'held' && v.strength === 'strong') held.push(Object.assign({}, t, { verdict: v }));
1390
+ else shown.push(Object.assign({}, t, v ? { verdict: v } : {}));
1391
+ }
1392
+ return { shown, held };
1393
+ }
1394
+
1156
1395
  function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1157
1396
  const out = [];
1158
1397
  const attempts = wall && wall.ran ? wall.result.attempts : [];
@@ -1171,6 +1410,7 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1171
1410
  v.finding = hit.headline;
1172
1411
  } else if (tried && /^(refused the second time|nothing moved the second time)$/.test(tried.verdict)) {
1173
1412
  v.verdict = 'held';
1413
+ v.strength = 'strong';
1174
1414
  } else {
1175
1415
  v.verdict = 'not tried';
1176
1416
  v.why = tried ? tried.why || tried.verdict : steps && !steps.ran ? steps.why : 'the step was not sent twice';
@@ -1178,6 +1418,7 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1178
1418
  } else if (t.kind === 'identity-from-request') {
1179
1419
  const hit = forged && forged.ran && forged.findings.find((f) => f.from === t.where);
1180
1420
  v.verdict = hit ? 'confirmed' : forged && forged.ran && forged.tried.length ? 'held' : 'not tried';
1421
+ if (v.verdict === 'held') v.strength = 'strong';
1181
1422
  if (hit) v.finding = hit.headline;
1182
1423
  if (v.verdict === 'not tried') v.why = forged ? forged.why || 'not tried' : 'the forged identity was not tried';
1183
1424
  } else if (/^webhook/.test(t.kind)) {
@@ -1188,6 +1429,7 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1188
1429
  v.finding = hit.headline;
1189
1430
  } 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
1431
  v.verdict = 'held';
1432
+ v.strength = 'strong';
1191
1433
  } else if (hook && hook.findings.some((f) => /^webhook-(unsigned|forged)$/.test(f.kind))) {
1192
1434
  v.verdict = 'not judged';
1193
1435
  v.why = 'the app answered success without a valid signature, but no change was seen in ' + hook.list;
@@ -1207,6 +1449,8 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1207
1449
  v.finding = rf[0].headline;
1208
1450
  } else if (tries.length && tries.every((a) => a.verdict === V.DENIED || a.verdict === V.ALLOWED)) {
1209
1451
  v.verdict = 'held';
1452
+ v.strength = heldStrength(tries);
1453
+ if (v.strength === 'weak') v.why = 'it answered without the protected records, which may only mean there were none to show';
1210
1454
  } else if (tries.length) {
1211
1455
  v.verdict = 'not judged';
1212
1456
  v.why = (tries.find((a) => a.verdict === V.AMBIGUOUS) || tries[0]).reason;
@@ -1226,6 +1470,8 @@ function verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, steps) {
1226
1470
  v.finding = hit.headline;
1227
1471
  } else if (mine.length && mine.some((a) => a.verdict === V.DENIED || a.verdict === V.ALLOWED) && !mine.some((a) => a.verdict === V.AMBIGUOUS)) {
1228
1472
  v.verdict = 'held';
1473
+ v.strength = heldStrength(mine);
1474
+ if (v.strength === 'weak') v.why = 'it answered without the other organization\'s records, which may only mean it had none to show';
1229
1475
  } else if (mine.length) {
1230
1476
  v.verdict = 'not judged';
1231
1477
  v.why = (mine.find((a) => a.verdict === V.AMBIGUOUS) || mine[0]).reason;
@@ -1342,6 +1588,7 @@ async function runApi(root, options) {
1342
1588
  const exportsRun = await csv.run(root, shared);
1343
1589
  const jobsRun = await runJobs(root, shared);
1344
1590
  const keptRun = await runKept(root, shared);
1591
+ const createsRun = await runCreates(root, shared);
1345
1592
  const stepsRun = await runSteps(root, Object.assign({}, shared, { toCheck: toCheck }));
1346
1593
  let roleRun = null;
1347
1594
  if (opts.roles) roleRun = await runRoles(root, shared);
@@ -1349,14 +1596,14 @@ async function runApi(root, options) {
1349
1596
  const invalid = await runInvalid(root, shared);
1350
1597
  const verdicts = verdictsFor(toCheck, wall, invalid, roleRun, forged, webhooks, stepsRun);
1351
1598
  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) => {
1599
+ 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
1600
  const k = f.kind + '|' + f.where + '|' + (f.field || '');
1354
1601
  return seen.has(k) ? false : (seen.add(k), true);
1355
1602
  });
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) : []);
1603
+ 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
1604
  return {
1358
1605
  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,
1606
+ 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
1607
  notTried: (wall.plan ? wall.plan.notTried : []).concat(invalid.ran ? invalid.notTried : []),
1361
1608
  };
1362
1609
  }
@@ -1416,7 +1663,10 @@ function apiLines(run) {
1416
1663
  out.push(' Webhook ' + h.route + ': not tried - ' + h.notTried);
1417
1664
  continue;
1418
1665
  }
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');
1666
+ const how = h.signing.open
1667
+ ? ' (it checks no signature at all): an event with none was taken'
1668
+ : ' (' + 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';
1669
+ 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
1670
  for (const f of h.findings) {
1421
1671
  out.push(' ' + (f.status === 'confirmed' ? 'PROBLEM' : 'TO CHECK') + ' ' + f.severity + ' ' + f.headline + ' (' + f.from + ')');
1422
1672
  for (const l of f.proof) out.push(' ' + l);
@@ -1450,6 +1700,14 @@ function apiLines(run) {
1450
1700
  }
1451
1701
  out.push('');
1452
1702
  }
1703
+ if (run.creates && run.creates.ran) {
1704
+ 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(', ') : '') + ')' : ''));
1705
+ for (const f of run.creates.findings) {
1706
+ out.push(' TO CHECK ' + f.severity + ' ' + f.headline + ' (' + f.from + ')');
1707
+ for (const l of f.proof) out.push(' ' + l);
1708
+ }
1709
+ out.push('');
1710
+ }
1453
1711
  if (run.steps && run.steps.ran) {
1454
1712
  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
1713
  for (const f of run.steps.findings) {
@@ -1475,7 +1733,9 @@ function apiLines(run) {
1475
1733
  }
1476
1734
  if (run.verdicts.length) {
1477
1735
  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 + ')' : ''));
1736
+ 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 + ')' : ''));
1737
+ const strong = run.verdicts.filter((v) => v.verdict === 'held' && v.strength === 'strong').length;
1738
+ 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
1739
  out.push('');
1480
1740
  }
1481
1741
  const extra = run.invalid && run.invalid.ran ? run.invalid.left : [];
@@ -1487,4 +1747,4 @@ function apiLines(run) {
1487
1747
  return out;
1488
1748
  }
1489
1749
 
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 };
1750
+ 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 };