kryptheon 0.1.67 → 0.1.69

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.
@@ -1,98 +1,98 @@
1
- // Which files in tests/ are Kryptheon's recordings, and what a new one is
2
- // called.
3
- //
4
- // Found in blind round 13 (a TypeScript service with vitest): its own unit
5
- // test, tests/incidents.test.ts, was taken for a recording - check said it
6
- // "only opens a page and stops", and the dashboard showed "Record your main
7
- // flows: Done, 1 recording held" before anything was recorded. Then the
8
- // first real recording, saved as tests/<name>.spec.js, was picked up by the
9
- // project's own `npm test` (vitest), which failed on it: "Playwright Test did
10
- // not expect test() to be called here". A tool that breaks the app's own
11
- // tests is one nobody keeps.
12
- //
13
- // So: a recording is a file that uses Playwright or Kryptheon's fixture -
14
- // anything else in tests/ belongs to the project and is left alone. And in a
15
- // project whose unit-test runner collects *.spec.js / *.test.js, a new
16
- // recording is saved as <name>.kryptheon.js, which only Kryptheon runs.
17
-
18
- const fs = require('fs');
19
- const path = require('path');
20
-
21
- const SPEC_NAME = /\.(spec|test)\.[cm]?[jt]sx?$/;
22
- const OWN_NAME = /\.kryptheon\.js$/;
23
- // What a recording imports: Playwright directly (older or hand-made ones,
24
- // repaired by check) or the fixture - by package name, or by any path that
25
- // ends in kryptheon-fixture(.js), relative or absolute.
26
- const USES_PLAYWRIGHT = /(['"`])(?:@playwright\/test|[^'"`\r\n]*kryptheon-fixture(?:\.js)?)\1/;
27
-
28
- /** Whether this file in tests/ is one of Kryptheon's recordings. */
29
- function isRecordingFile(name, source) {
30
- if (!SPEC_NAME.test(name) && !OWN_NAME.test(name)) return false;
31
- return USES_PLAYWRIGHT.test(String(source || ''));
32
- }
33
-
34
- /** The recordings in a tests folder, as paths relative to it. */
35
- function recordingNames(testsDir) {
36
- let entries = [];
37
- try {
38
- entries = fs.readdirSync(testsDir, { recursive: true });
39
- } catch (err) {
40
- try {
41
- entries = fs.readdirSync(testsDir);
42
- } catch (err2) {
43
- return [];
44
- }
45
- }
46
- return entries.map(String).filter((name) => {
47
- if (!SPEC_NAME.test(name) && !OWN_NAME.test(name)) return false;
48
- try {
49
- return isRecordingFile(name, fs.readFileSync(path.join(testsDir, name), 'utf8'));
50
- } catch (err) {
51
- return false;
52
- }
53
- });
54
- }
55
-
56
- /**
57
- * The unit-test runner this project uses that would also collect
58
- * tests/*.spec.js or tests/*.test.js: 'vitest', 'jest', 'mocha' - or null.
59
- */
60
- function unitRunnerOf(projectDir) {
61
- let pkg = {};
62
- try {
63
- pkg = JSON.parse(fs.readFileSync(path.join(projectDir, 'package.json'), 'utf8'));
64
- } catch (err) {
65
- pkg = {};
66
- }
67
- const deps = Object.assign({}, pkg.dependencies, pkg.devDependencies);
68
- const script = String((pkg.scripts && pkg.scripts.test) || '');
69
- let files = [];
70
- try {
71
- files = fs.readdirSync(projectDir);
72
- } catch (err) {
73
- files = [];
74
- }
75
- const has = (re) => files.some((f) => re.test(f));
76
- if (deps.vitest || /\bvitest\b/.test(script) || has(/^vitest\.config\./)) return 'vitest';
77
- if (deps.jest || pkg.jest || /\bjest\b/.test(script) || has(/^jest\.config\./)) return 'jest';
78
- if (deps.mocha || /\bmocha\b/.test(script) || has(/^\.mocharc/)) return 'mocha';
79
- return null;
80
- }
81
-
82
- /** What a new recording's file name ends in, in this project. */
83
- function recordingExtension(projectDir) {
84
- return unitRunnerOf(projectDir) ? '.kryptheon.js' : '.spec.js';
85
- }
86
-
87
- /** A recording's name without its ending: "login" for login.spec.js or login.kryptheon.js. */
88
- function bareName(name) {
89
- return String(name).replace(OWN_NAME, '').replace(/\.spec\.js$/, '');
90
- }
91
-
92
- module.exports = {
93
- isRecordingFile: isRecordingFile,
94
- recordingNames: recordingNames,
95
- unitRunnerOf: unitRunnerOf,
96
- recordingExtension: recordingExtension,
97
- bareName: bareName,
98
- };
1
+ // Which files in tests/ are Kryptheon's recordings, and what a new one is
2
+ // called.
3
+ //
4
+ // Found in blind round 13 (a TypeScript service with vitest): its own unit
5
+ // test, tests/incidents.test.ts, was taken for a recording - check said it
6
+ // "only opens a page and stops", and the dashboard showed "Record your main
7
+ // flows: Done, 1 recording held" before anything was recorded. Then the
8
+ // first real recording, saved as tests/<name>.spec.js, was picked up by the
9
+ // project's own `npm test` (vitest), which failed on it: "Playwright Test did
10
+ // not expect test() to be called here". A tool that breaks the app's own
11
+ // tests is one nobody keeps.
12
+ //
13
+ // So: a recording is a file that uses Playwright or Kryptheon's fixture -
14
+ // anything else in tests/ belongs to the project and is left alone. And in a
15
+ // project whose unit-test runner collects *.spec.js / *.test.js, a new
16
+ // recording is saved as <name>.kryptheon.js, which only Kryptheon runs.
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+
21
+ const SPEC_NAME = /\.(spec|test)\.[cm]?[jt]sx?$/;
22
+ const OWN_NAME = /\.kryptheon\.js$/;
23
+ // What a recording imports: Playwright directly (older or hand-made ones,
24
+ // repaired by check) or the fixture - by package name, or by any path that
25
+ // ends in kryptheon-fixture(.js), relative or absolute.
26
+ const USES_PLAYWRIGHT = /(['"`])(?:@playwright\/test|[^'"`\r\n]*kryptheon-fixture(?:\.js)?)\1/;
27
+
28
+ /** Whether this file in tests/ is one of Kryptheon's recordings. */
29
+ function isRecordingFile(name, source) {
30
+ if (!SPEC_NAME.test(name) && !OWN_NAME.test(name)) return false;
31
+ return USES_PLAYWRIGHT.test(String(source || ''));
32
+ }
33
+
34
+ /** The recordings in a tests folder, as paths relative to it. */
35
+ function recordingNames(testsDir) {
36
+ let entries = [];
37
+ try {
38
+ entries = fs.readdirSync(testsDir, { recursive: true });
39
+ } catch (err) {
40
+ try {
41
+ entries = fs.readdirSync(testsDir);
42
+ } catch (err2) {
43
+ return [];
44
+ }
45
+ }
46
+ return entries.map(String).filter((name) => {
47
+ if (!SPEC_NAME.test(name) && !OWN_NAME.test(name)) return false;
48
+ try {
49
+ return isRecordingFile(name, fs.readFileSync(path.join(testsDir, name), 'utf8'));
50
+ } catch (err) {
51
+ return false;
52
+ }
53
+ });
54
+ }
55
+
56
+ /**
57
+ * The unit-test runner this project uses that would also collect
58
+ * tests/*.spec.js or tests/*.test.js: 'vitest', 'jest', 'mocha' - or null.
59
+ */
60
+ function unitRunnerOf(projectDir) {
61
+ let pkg = {};
62
+ try {
63
+ pkg = JSON.parse(fs.readFileSync(path.join(projectDir, 'package.json'), 'utf8'));
64
+ } catch (err) {
65
+ pkg = {};
66
+ }
67
+ const deps = Object.assign({}, pkg.dependencies, pkg.devDependencies);
68
+ const script = String((pkg.scripts && pkg.scripts.test) || '');
69
+ let files = [];
70
+ try {
71
+ files = fs.readdirSync(projectDir);
72
+ } catch (err) {
73
+ files = [];
74
+ }
75
+ const has = (re) => files.some((f) => re.test(f));
76
+ if (deps.vitest || /\bvitest\b/.test(script) || has(/^vitest\.config\./)) return 'vitest';
77
+ if (deps.jest || pkg.jest || /\bjest\b/.test(script) || has(/^jest\.config\./)) return 'jest';
78
+ if (deps.mocha || /\bmocha\b/.test(script) || has(/^\.mocharc/)) return 'mocha';
79
+ return null;
80
+ }
81
+
82
+ /** What a new recording's file name ends in, in this project. */
83
+ function recordingExtension(projectDir) {
84
+ return unitRunnerOf(projectDir) ? '.kryptheon.js' : '.spec.js';
85
+ }
86
+
87
+ /** A recording's name without its ending: "login" for login.spec.js or login.kryptheon.js. */
88
+ function bareName(name) {
89
+ return String(name).replace(OWN_NAME, '').replace(/\.spec\.js$/, '');
90
+ }
91
+
92
+ module.exports = {
93
+ isRecordingFile: isRecordingFile,
94
+ recordingNames: recordingNames,
95
+ unitRunnerOf: unitRunnerOf,
96
+ recordingExtension: recordingExtension,
97
+ bareName: bareName,
98
+ };
@@ -816,7 +816,12 @@ async function run(root, options) {
816
816
  const captureType = shape.amount && amountKey ? (!REFUNDED.test(control.type) && CAPTURE.test(control.type) ? control.type : signing.types.find((t) => !REFUNDED.test(t) && CAPTURE.test(t)) || (actsOnAny ? control.type : null)) : null;
817
817
  const payControl = !!captureType;
818
818
  // a record a capture can still land on first, so what changed is the capture and not a record already settled
819
- const captureOrder = [...capturable, controlRec].concat(records).filter((r, i, all) => r && r.id !== null && all.indexOf(r) === i).slice(0, 3);
819
+ // ... and one no earlier event of this run has touched (blind round 34: the wrong amount and the wrong currency went
820
+ // to the order the control had just paid, nothing more could change on it, and neither was seen) - as long as one
821
+ // untouched record is left over for the unsigned event that follows
822
+ const untouched = () => capturable.filter((r) => r.id !== null && !used.has(r.id));
823
+ const orderNow = () => (untouched().length >= 2 ? untouched().slice(0, 1) : []).concat(capturable, [controlRec], records).filter((r, i, all) => r && r.id !== null && all.indexOf(r) === i).slice(0, 3);
824
+ let captureOrder = orderNow();
820
825
  if (captureType) {
821
826
  for (const rec of captureOrder) {
822
827
  const t = await attempt(S, captureType, rec, (Number(rec[amountKey]) || 0) + 100, 'signed, wrong amount');
@@ -825,6 +830,7 @@ async function run(root, options) {
825
830
  }
826
831
  // the same capture in another currency than the record's (blind round 32: EUR was taken for a USD payment)
827
832
  const currencyKey = records[0] && Object.keys(records[0]).find((k) => /^currency(_code)?$/i.test(k));
833
+ captureOrder = orderNow();
828
834
  if (captureType && shape.currency && currencyKey) {
829
835
  for (const rec of captureOrder) {
830
836
  const own = String(rec[currencyKey] || '').toUpperCase();
@@ -834,6 +840,39 @@ async function run(root, options) {
834
840
  if (t.took) break;
835
841
  }
836
842
  }
843
+ // A correctly signed event that names this organization and a record of ANOTHER one (blind round 34: a signed gate
844
+ // callback with orgId 1 checked in organization 2's ticket - the handler looked the ticket up by its id alone).
845
+ // Needs a field of the event that says whose it is, the list read as an account of another organization, and a
846
+ // record there this account's own list does not carry. Judged from that record, read by its own organization.
847
+ const ownerField = signing.fields.find((x) => OWNER_ID.test(x.name) && !/^(user|owner)_?id$/i.test(x.name));
848
+ if (ownerField && listRoute && control.body && control.body[ownerField.name] !== undefined && j.accounts.usable.length > 1) {
849
+ const mine = new Set(records.map((r) => String(r.id)));
850
+ for (const acc of j.accounts.usable.slice(1)) {
851
+ if (!ctx.secrets.includes(acc.password)) ctx.secrets.push(acc.password);
852
+ const other = authz.makeSession(ctx, 'account', acc.email, acc.password);
853
+ const lf = { [j.signIn.emailField]: acc.email, [j.signIn.passwordField]: acc.password };
854
+ const inOther = authz.replyOf(await other.send(j.signIn.method, j.signIn.path, j.signIn.encoding === 'form' ? { form: lf } : { json: lf }));
855
+ if (inOther.kind === 'refused' || inOther.kind === 'server-error' || inOther.kind === 'no-answer') continue;
856
+ const readTheirs = async () => { const r = await other.send('GET', listRoute.path, {}); return r.status === 200 ? listOf(r.json) : null; };
857
+ const theirs = ((await readTheirs()) || []).filter((r) => r && r.id !== undefined && !mine.has(String(r.id)));
858
+ if (!theirs.length) continue;
859
+ // one whose state the event can still move (a ticket not yet checked in), else the first
860
+ const openOne = statusKey ? theirs.find((r) => records.some((m) => m[statusKey] !== undefined && m[statusKey] !== r[statusKey])) : null;
861
+ const target = openOne || theirs[0];
862
+ const body = bodyFor(control.type, target, undefined);
863
+ body[ownerField.name] = control.body[ownerField.name];
864
+ const res = await post(S, body);
865
+ const reply = authz.replyOf(res);
866
+ const now = ((await readTheirs()) || []).find((x) => String(x.id) === String(target.id));
867
+ const [sw, sn] = [stableItem(target), stableItem(now)];
868
+ const moved = now ? Object.keys(Object.assign({}, sw, sn)).filter((k) => JSON.stringify(sw[k]) !== JSON.stringify(sn[k])) : [];
869
+ const t = { mode: S, label: 'signed, another organization\'s record', type: control.type, record: target.id, status: res.status, took: reply.kind === 'accepted' || reply.kind === 'redirect', changed: moved.length > 0, fields: moved,
870
+ from: statusKey ? target[statusKey] : null, to: now && statusKey ? now[statusKey] : null, foreign: { owner: ownerField.name, sentAs: control.body[ownerField.name], readAs: acc.email } };
871
+ hook.tried.push(t);
872
+ if (t.changed) out.left.push(name + ' signed ' + control.type + ' naming ' + ownerField.name + ' ' + control.body[ownerField.name] + ' for ' + resource + ' ' + target.id + ' of another organization: it changed (' + moved.join(', ') + ')');
873
+ break;
874
+ }
875
+ }
837
876
  // a refund on a record that was paid: sent twice as the same event, then for more than was paid
838
877
  const refundType = types.find((t) => REFUNDED.test(t)) || signing.types.find((t) => REFUNDED.test(t));
839
878
  const paidRec = refundType && statusKey && records.find((r) => PAID.test(String(r[statusKey])) && !REFUNDED.test(String(r[statusKey])));
@@ -893,6 +932,12 @@ async function run(root, options) {
893
932
  finding('webhook-forged', t.changed ? 'CRITICAL' : 'HIGH', t.changed ? 'confirmed' : 'verification required',
894
933
  name + ' took ' + t.type + ' with a wrong signature' + (t.changed ? ' and changed ' + resource + ' ' + t.record : '') + '.',
895
934
  ['A signature of the right length, one character wrong: ' + lineOf(t)], 'Compare the signature with a timing-safe compare (crypto.timingSafeEqual) over the exact raw body, and answer 401 when it does not match, before anything is saved.');
935
+ } else if (t.foreign && t.took && t.changed) {
936
+ finding('webhook-tenant', 'CRITICAL', 'confirmed',
937
+ name + ' took a correctly signed ' + shown(t) + ' that names ' + t.foreign.owner + ' ' + t.foreign.sentAs + ' and changed ' + resource + ' ' + t.record + ' of another organization (' + (t.from !== t.to && t.from !== null ? statusKey + ' ' + t.from + ' -> ' + t.to : t.fields.join(', ')) + '): the record is found by its id alone.',
938
+ ['Correctly signed, ' + t.foreign.owner + ' = ' + t.foreign.sentAs + ', ' + resource + ' ' + t.record + ' (which GET ' + (listRoute ? listRoute.path : '') + ' shows only to ' + t.foreign.readAs + '\'s organization): answered ' + t.status + '.',
939
+ 'Read as ' + t.foreign.readAs + ' before and after: ' + (t.from !== t.to && t.from !== null ? statusKey + ' went ' + t.from + ' -> ' + t.to : t.fields.join(', ') + ' changed') + '.'],
940
+ 'Look the ' + resource + ' up by its id AND the organization the event is for (WHERE id = $1 AND ' + t.foreign.owner.replace(/Id$/, '_id').toLowerCase() + ' = $2), and tie each provider integration to the one organization it belongs to, so a signed event can only ever touch that organization\'s records. Answer 404 when no row matches.');
896
941
  } else if (t.label === 'signed, wrong currency' && t.took && t.changed) {
897
942
  finding('webhook-currency', 'HIGH', 'confirmed',
898
943
  name + ' applied ' + shown(t) + ' in another currency than ' + resource + ' ' + t.record + '\'s, and it changed all the same (' + (t.from !== t.to ? statusKey + ' ' + t.from + ' -> ' + t.to : t.fields.join(', ')) + ').',
@@ -0,0 +1,150 @@
1
+ // The database witness: what the app's own database held before and after a try.
2
+ //
3
+ // The API check judges a try from what the app shows in its lists. Some effects are in no list: a payout paid
4
+ // out twice writes two rows to a transfers table that no route reads (blind round 34: both requests answered
5
+ // 200, the lists showed one payout, and the check said "held"), a seat hold naming another organization's seat
6
+ // is stored though the page shows nothing new. Where the app runs on this computer and its connection string
7
+ // is in its .env (the same file the app reads), the rows themselves are read before and after.
8
+ //
9
+ // Rules, kept by the code and by kryptheon-witness.check.js:
10
+ // - Postgres on this computer only (localhost, 127.0.0.1, ::1): any other host is refused before connecting;
11
+ // - read-only: the session is set read-only and every read runs in a READ ONLY transaction;
12
+ // - nothing of it is saved or printed but table and column names, ids, counts and the plain values of a
13
+ // changed column; a column named like a password, hash, secret, token or key is never shown;
14
+ // - a table of sessions is not read at all; a table over MAX_ROWS rows is counted, not read;
15
+ // - no connection string, or one that fails: the check goes on without a witness and says so.
16
+
17
+ const secrets = require('./kryptheon-secrets.js');
18
+
19
+ const NAMES = ['KRYPTHEON_DATABASE_URL', 'DATABASE_URL', 'POSTGRES_URL', 'POSTGRES_PRISMA_URL', 'PG_URL', 'PGURL'];
20
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
21
+ const MAX_ROWS = 5000;
22
+ const MAX_TABLES = 200;
23
+ const SKIP_TABLE = /session/i;
24
+ const SECRET_COLUMN = /pass(word|wd|code|phrase)?|hash|secret|token|(^|_)key($|_)|credential|salt|otp/i;
25
+
26
+ /** The connection string to witness with: { url, from } or { none: true, why }. Never printed. */
27
+ function urlFor(root, env) {
28
+ const here = env || process.env;
29
+ let file = {};
30
+ try { file = secrets.readEnvFile(secrets.envFileFor(root)); } catch (err) { file = {}; }
31
+ for (const from of [here, file]) {
32
+ for (const name of NAMES) {
33
+ const value = from[name];
34
+ if (typeof value !== 'string' || !value.trim()) continue;
35
+ let u;
36
+ try { u = new URL(value.trim()); } catch (err) { continue; }
37
+ if (!/^postgres(ql)?:$/.test(u.protocol)) continue;
38
+ if (!LOCAL_HOSTS.has(u.hostname.toLowerCase())) return { none: true, why: name + ' names a database that is not on this computer, so it is not read' };
39
+ return { url: value.trim(), from: name };
40
+ }
41
+ }
42
+ return { none: true, why: 'no Postgres connection string for this computer in .env (DATABASE_URL)' };
43
+ }
44
+
45
+ const plain = (v) => (v instanceof Date ? v.toISOString() : Buffer.isBuffer(v) ? '<bytes>' : v);
46
+
47
+ /**
48
+ * Opens the witness. { ok: true, snapshot(), close(), from } or { ok: false, why }. `connect` is for the checks:
49
+ * (url) -> a client with query() and end().
50
+ */
51
+ async function open(root, options) {
52
+ const opts = options || {};
53
+ const found = urlFor(root, opts.env);
54
+ if (found.none) return { ok: false, why: found.why };
55
+ let client;
56
+ try {
57
+ if (opts.connect) client = await opts.connect(found.url);
58
+ else {
59
+ const { Client } = require('pg');
60
+ client = new Client({ connectionString: found.url, connectionTimeoutMillis: 4000, statement_timeout: 8000, application_name: 'kryptheon-witness' });
61
+ await client.connect();
62
+ }
63
+ await client.query('SET default_transaction_read_only = on');
64
+ } catch (err) {
65
+ try { if (client) await client.end(); } catch (e) { /* closed already */ }
66
+ return { ok: false, why: 'the database in ' + found.from + ' could not be read (' + String(err && err.code ? err.code : 'no connection') + ')' };
67
+ }
68
+ let shape = null;
69
+ const shapeOf = async () => {
70
+ if (shape) return shape;
71
+ const t = await client.query("SELECT c.oid::int AS oid, c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind = 'r' ORDER BY c.relname LIMIT " + (MAX_TABLES + 1));
72
+ const pk = await client.query("SELECT i.indrelid::int AS oid, a.attname AS col FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) WHERE i.indisprimary");
73
+ const keys = new Map();
74
+ for (const r of pk.rows) keys.set(r.oid, (keys.get(r.oid) || []).concat(r.col));
75
+ shape = t.rows.slice(0, MAX_TABLES).filter((r) => !SKIP_TABLE.test(r.name)).map((r) => ({ name: r.name, pk: keys.get(r.oid) || [] }));
76
+ return shape;
77
+ };
78
+ const quote = (name) => '"' + String(name).replace(/"/g, '""') + '"';
79
+ return {
80
+ ok: true,
81
+ from: found.from,
82
+ /** Every table's rows by primary key: { tables: { name: { count, big, rows: Map(key -> row) } } } or null when a read failed. */
83
+ async snapshot() {
84
+ try {
85
+ const out = { at: Date.now(), tables: {} };
86
+ await client.query('BEGIN TRANSACTION READ ONLY');
87
+ try {
88
+ for (const t of await shapeOf()) {
89
+ const r = await client.query('SELECT * FROM public.' + quote(t.name) + ' LIMIT ' + (MAX_ROWS + 1));
90
+ if (r.rows.length > MAX_ROWS) {
91
+ const n = await client.query('SELECT count(*)::int AS n FROM public.' + quote(t.name));
92
+ out.tables[t.name] = { count: n.rows[0].n, big: true, rows: new Map() };
93
+ continue;
94
+ }
95
+ const rows = new Map();
96
+ for (const row of r.rows) {
97
+ const o = {};
98
+ for (const k of Object.keys(row)) o[k] = plain(row[k]);
99
+ rows.set(t.pk.length ? t.pk.map((c) => String(o[c])).join('|') : JSON.stringify(o), o);
100
+ }
101
+ out.tables[t.name] = { count: rows.size, big: false, pk: t.pk, rows };
102
+ }
103
+ } finally {
104
+ await client.query('COMMIT');
105
+ }
106
+ return out;
107
+ } catch (err) {
108
+ return null;
109
+ }
110
+ },
111
+ async close() { try { await client.end(); } catch (err) { /* closed already */ } },
112
+ };
113
+ }
114
+
115
+ /**
116
+ * What changed between two snapshots: { table: { added: [row], removed: n, changed: [{ key, row, cols: [{ col, from, to }] }] } }
117
+ * - only tables that changed; a table too big to read gives { grew: n }. Empty when either snapshot is missing.
118
+ */
119
+ function diff(before, after) {
120
+ const out = {};
121
+ if (!before || !after) return out;
122
+ for (const name of Object.keys(after.tables)) {
123
+ const a = before.tables[name];
124
+ const b = after.tables[name];
125
+ if (!a) continue;
126
+ if (a.big || b.big) { if (b.count !== a.count) out[name] = { added: [], removed: 0, changed: [], grew: b.count - a.count }; continue; }
127
+ const added = [];
128
+ const changed = [];
129
+ for (const [key, row] of b.rows) {
130
+ const old = a.rows.get(key);
131
+ if (!old) { added.push(row); continue; }
132
+ const cols = [];
133
+ for (const k of Object.keys(row)) if (JSON.stringify(row[k]) !== JSON.stringify(old[k])) cols.push({ col: k, from: old[k], to: row[k] });
134
+ if (cols.length) changed.push({ key, row, old, cols });
135
+ }
136
+ let removed = 0;
137
+ for (const key of a.rows.keys()) if (!b.rows.has(key)) removed++;
138
+ if (added.length || changed.length || removed) out[name] = { added, removed, changed };
139
+ }
140
+ return out;
141
+ }
142
+
143
+ /** A value as it may be shown: a secret column's is never shown, a long one is clipped. */
144
+ function show(col, value) {
145
+ if (SECRET_COLUMN.test(col)) return '(not shown)';
146
+ const s = typeof value === 'string' ? value : JSON.stringify(value);
147
+ return s === undefined ? 'null' : s.length > 60 ? s.slice(0, 57) + '...' : s;
148
+ }
149
+
150
+ module.exports = { open, urlFor, diff, show, NAMES, MAX_ROWS, SECRET_COLUMN, SKIP_TABLE };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kryptheon",
3
- "version": "0.1.67",
3
+ "version": "0.1.69",
4
4
  "description": "Record what you do in your app and get plain-language reports when it breaks.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "commonjs",
@@ -60,6 +60,9 @@
60
60
  "kryptheon-api.js",
61
61
  "kryptheon-webhook.js",
62
62
  "kryptheon-csv.js",
63
+ "kryptheon-witness.js",
64
+ "kryptheon-questions.js",
65
+ "kryptheon-daily.js",
63
66
  "kryptheon-newer.js"
64
67
  ],
65
68
  "engines": {
@@ -70,7 +73,7 @@
70
73
  "pg": "^8.23.0"
71
74
  },
72
75
  "scripts": {
73
- "check": "node kryptheon-store.check.js && node kryptheon-code.check.js && node kryptheon-constdata.check.js && node kryptheon-listitems.check.js && node kryptheon-accept.check.js && node kryptheon-keys.check.js && node kryptheon-dashboard.check.js && node kryptheon-edge.check.js && node kryptheon-reliability.check.js && node kryptheon-fresh.check.js && node kryptheon-payments-dash.check.js && node kryptheon-embedded.check.js && node kryptheon-autostart.check.js && node kryptheon-changes.check.js && node kryptheon-look.check.js && node kryptheon-verify.check.js && node kryptheon-recheck.check.js && node kryptheon-reporter.check.js && node kryptheon-signature.check.js && node kryptheon-signature.stream.check.js && node kryptheon-signature.baseline.check.js && node kryptheon-signature.settle.check.js && node kryptheon-signature.number.check.js && node kryptheon-signature.rows.check.js && node kryptheon-env.check.js && node kryptheon-watchdog.check.js && node kryptheon-phone.check.js && node kryptheon-homedash.check.js && node kryptheon-record.check.js && node kryptheon-selectors.check.js && node kryptheon-recordings.check.js && node kryptheon-testfiles.check.js && node kryptheon-cleanup.check.js && node kryptheon-orphan.check.js && node kryptheon-project.check.js && node kryptheon-setup.check.js && node kryptheon-browser.check.js && node kryptheon-heal.check.js && node kryptheon-load.check.js && node kryptheon-authz.check.js && node kryptheon-roles.check.js && node kryptheon-map.check.js && node kryptheon-api.check.js && node kryptheon-webhook.check.js && node kryptheon-csv.check.js && node kryptheon-package.check.js && node kryptheon-newer.check.js",
76
+ "check": "node kryptheon-store.check.js && node kryptheon-code.check.js && node kryptheon-constdata.check.js && node kryptheon-listitems.check.js && node kryptheon-accept.check.js && node kryptheon-keys.check.js && node kryptheon-dashboard.check.js && node kryptheon-edge.check.js && node kryptheon-reliability.check.js && node kryptheon-fresh.check.js && node kryptheon-payments-dash.check.js && node kryptheon-embedded.check.js && node kryptheon-autostart.check.js && node kryptheon-changes.check.js && node kryptheon-look.check.js && node kryptheon-verify.check.js && node kryptheon-recheck.check.js && node kryptheon-reporter.check.js && node kryptheon-signature.check.js && node kryptheon-signature.stream.check.js && node kryptheon-signature.baseline.check.js && node kryptheon-signature.settle.check.js && node kryptheon-signature.number.check.js && node kryptheon-signature.rows.check.js && node kryptheon-env.check.js && node kryptheon-watchdog.check.js && node kryptheon-phone.check.js && node kryptheon-homedash.check.js && node kryptheon-record.check.js && node kryptheon-selectors.check.js && node kryptheon-recordings.check.js && node kryptheon-testfiles.check.js && node kryptheon-cleanup.check.js && node kryptheon-orphan.check.js && node kryptheon-project.check.js && node kryptheon-setup.check.js && node kryptheon-browser.check.js && node kryptheon-heal.check.js && node kryptheon-load.check.js && node kryptheon-authz.check.js && node kryptheon-roles.check.js && node kryptheon-map.check.js && node kryptheon-api.check.js && node kryptheon-webhook.check.js && node kryptheon-csv.check.js && node kryptheon-witness.check.js && node kryptheon-round34.check.js && node kryptheon-token.check.js && node kryptheon-questions.check.js && node kryptheon-daily.check.js && node kryptheon-live.check.js && node kryptheon-package.check.js && node kryptheon-newer.check.js",
74
77
  "check:store": "node kryptheon-store.check.js",
75
78
  "check:code": "node kryptheon-code.check.js",
76
79
  "check:constdata": "node kryptheon-constdata.check.js",
@@ -116,6 +119,12 @@
116
119
  "check:api": "node kryptheon-api.check.js",
117
120
  "check:webhook": "node kryptheon-webhook.check.js",
118
121
  "check:csv": "node kryptheon-csv.check.js",
122
+ "check:witness": "node kryptheon-witness.check.js",
123
+ "check:round34": "node kryptheon-round34.check.js",
124
+ "check:token": "node kryptheon-token.check.js",
125
+ "check:questions": "node kryptheon-questions.check.js",
126
+ "check:daily": "node kryptheon-daily.check.js",
127
+ "check:live": "node kryptheon-live.check.js",
119
128
  "check:newer": "node kryptheon-newer.check.js",
120
129
  "check:account": "node kryptheon-account.check.js"
121
130
  },
@@ -1,73 +1,73 @@
1
- // @ts-check
2
- const path = require('path');
3
- const { defineConfig } = require('@playwright/test');
4
-
5
- // Tool files come from the installed package; anything belonging to the person
6
- // running the command comes from the folder they ran it in.
7
- const PACKAGE_DIR = __dirname;
8
- const USER_DIR = process.cwd();
9
-
10
- // Node's built-in .env loader (no dependency). This file is re-evaluated in
11
- // each worker process, so the values reach the tests themselves. A missing
12
- // .env is not fatal: CI can supply the same variables as real env vars.
13
- // loadEnvFile only exists from Node 20.12, and the package supports 20.6, so
14
- // fall back to a small parser rather than silently skipping the file.
15
- // Deliberately not process.loadEnvFile, and this is the whole reason:
16
- //
17
- // On Windows, PowerShell's `Out-File -Encoding utf8` and Notepad's "Save as
18
- // UTF-8" both write a byte order mark. loadEnvFile keeps it, so the first line
19
- // of the file defines "KRYPTHEON_PASSWORD" rather than
20
- // "KRYPTHEON_PASSWORD" - measured, not assumed. The variable then reads as
21
- // undefined, the recording signs in with an empty password, and the login
22
- // fails for a reason nothing in the report mentions. The file is right there,
23
- // so nothing warns either.
24
- //
25
- // One parser, shared with the CLI, is also what stops the command that decides
26
- // whether a password is present from disagreeing with the test that uses it.
27
- function loadEnv(file) {
28
- const secrets = require(path.join(PACKAGE_DIR, 'kryptheon-secrets.js'));
29
- const values = secrets.readEnvFile(file);
30
- for (const name of Object.keys(values)) {
31
- // A real environment variable wins over the file - but only a real one.
32
- // A variable that exists and is empty is how "unset" arrives from a shell
33
- // or a CI job, and letting that beat the file would leave the password
34
- // blank with the answer sitting right there on disk.
35
- if (!secrets.isSet(process.env[name])) process.env[name] = values[name];
36
- }
37
- }
38
-
39
- loadEnv(path.join(USER_DIR, '.env'));
40
-
41
- module.exports = defineConfig({
42
- // The tests belong to the user, so they are found in their folder.
43
- testDir: path.join(USER_DIR, 'tests'),
44
- // Playwright's own pattern, plus <name>.kryptheon.js: the name a recording
45
- // gets in a project whose unit-test runner would also collect *.spec.js.
46
- testMatch: ['**/*.@(spec|test).?(c|m)[jt]s?(x)', '**/*.kryptheon.js'],
47
- // Screenshots and other artefacts default to sitting next to the config,
48
- // which once installed means inside node_modules. They belong to the user's
49
- // project, so they go to its store - outside the project, where a commit of
50
- // "everything that changed" cannot pick them up. Playwright empties this
51
- // folder at the start of every run, so it never grows.
52
- outputDir: require(path.join(PACKAGE_DIR, 'kryptheon-store.js')).pathsFor(USER_DIR).testResults,
53
- // These tests all run against one live site, so in parallel they interfere
54
- // with each other - a shared logged-in session, and rate limiting on the
55
- // real endpoints. Serial is the safe default here.
56
- fullyParallel: false,
57
- workers: 1,
58
- // Only the plain-language reporter: Playwright's 'list' reporter prints its
59
- // own stack-trace block on failure, which is what we are hiding here.
60
- // Resolved from the package so it is found wherever the command is run.
61
- reporter: [[path.join(PACKAGE_DIR, 'kryptheon-reporter.js')]],
62
- use: {
63
- headless: true,
64
- // The full Chromium, run headless - not Playwright's separate headless
65
- // shell. Measured on a Windows 11 machine: the shell took 23 seconds to
66
- // open each new page, every time, and that time counts against the 30
67
- // second test timeout. A correct flow longer than about 7 seconds failed,
68
- // and the report blamed the app. The full Chromium opened the same page in
69
- // 1.5 seconds. It is also the browser `record` checks is installed.
70
- channel: 'chromium',
71
- screenshot: 'only-on-failure',
72
- },
73
- });
1
+ // @ts-check
2
+ const path = require('path');
3
+ const { defineConfig } = require('@playwright/test');
4
+
5
+ // Tool files come from the installed package; anything belonging to the person
6
+ // running the command comes from the folder they ran it in.
7
+ const PACKAGE_DIR = __dirname;
8
+ const USER_DIR = process.cwd();
9
+
10
+ // Node's built-in .env loader (no dependency). This file is re-evaluated in
11
+ // each worker process, so the values reach the tests themselves. A missing
12
+ // .env is not fatal: CI can supply the same variables as real env vars.
13
+ // loadEnvFile only exists from Node 20.12, and the package supports 20.6, so
14
+ // fall back to a small parser rather than silently skipping the file.
15
+ // Deliberately not process.loadEnvFile, and this is the whole reason:
16
+ //
17
+ // On Windows, PowerShell's `Out-File -Encoding utf8` and Notepad's "Save as
18
+ // UTF-8" both write a byte order mark. loadEnvFile keeps it, so the first line
19
+ // of the file defines "KRYPTHEON_PASSWORD" rather than
20
+ // "KRYPTHEON_PASSWORD" - measured, not assumed. The variable then reads as
21
+ // undefined, the recording signs in with an empty password, and the login
22
+ // fails for a reason nothing in the report mentions. The file is right there,
23
+ // so nothing warns either.
24
+ //
25
+ // One parser, shared with the CLI, is also what stops the command that decides
26
+ // whether a password is present from disagreeing with the test that uses it.
27
+ function loadEnv(file) {
28
+ const secrets = require(path.join(PACKAGE_DIR, 'kryptheon-secrets.js'));
29
+ const values = secrets.readEnvFile(file);
30
+ for (const name of Object.keys(values)) {
31
+ // A real environment variable wins over the file - but only a real one.
32
+ // A variable that exists and is empty is how "unset" arrives from a shell
33
+ // or a CI job, and letting that beat the file would leave the password
34
+ // blank with the answer sitting right there on disk.
35
+ if (!secrets.isSet(process.env[name])) process.env[name] = values[name];
36
+ }
37
+ }
38
+
39
+ loadEnv(path.join(USER_DIR, '.env'));
40
+
41
+ module.exports = defineConfig({
42
+ // The tests belong to the user, so they are found in their folder.
43
+ testDir: path.join(USER_DIR, 'tests'),
44
+ // Playwright's own pattern, plus <name>.kryptheon.js: the name a recording
45
+ // gets in a project whose unit-test runner would also collect *.spec.js.
46
+ testMatch: ['**/*.@(spec|test).?(c|m)[jt]s?(x)', '**/*.kryptheon.js'],
47
+ // Screenshots and other artefacts default to sitting next to the config,
48
+ // which once installed means inside node_modules. They belong to the user's
49
+ // project, so they go to its store - outside the project, where a commit of
50
+ // "everything that changed" cannot pick them up. Playwright empties this
51
+ // folder at the start of every run, so it never grows.
52
+ outputDir: require(path.join(PACKAGE_DIR, 'kryptheon-store.js')).pathsFor(USER_DIR).testResults,
53
+ // These tests all run against one live site, so in parallel they interfere
54
+ // with each other - a shared logged-in session, and rate limiting on the
55
+ // real endpoints. Serial is the safe default here.
56
+ fullyParallel: false,
57
+ workers: 1,
58
+ // Only the plain-language reporter: Playwright's 'list' reporter prints its
59
+ // own stack-trace block on failure, which is what we are hiding here.
60
+ // Resolved from the package so it is found wherever the command is run.
61
+ reporter: [[path.join(PACKAGE_DIR, 'kryptheon-reporter.js')]],
62
+ use: {
63
+ headless: true,
64
+ // The full Chromium, run headless - not Playwright's separate headless
65
+ // shell. Measured on a Windows 11 machine: the shell took 23 seconds to
66
+ // open each new page, every time, and that time counts against the 30
67
+ // second test timeout. A correct flow longer than about 7 seconds failed,
68
+ // and the report blamed the app. The full Chromium opened the same page in
69
+ // 1.5 seconds. It is also the browser `record` checks is installed.
70
+ channel: 'chromium',
71
+ screenshot: 'only-on-failure',
72
+ },
73
+ });