kryptheon 0.1.56 → 0.1.58

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.
@@ -0,0 +1,407 @@
1
+ // The webhook check for an app that signs its own events: no real payment needed.
2
+ //
3
+ // kryptheon-payments.js needs one real test-mode payment so a provider's own
4
+ // signed webhook can be sent again. Many apps - and every app a person builds
5
+ // to try a provider - also take events they sign themselves, with a secret in
6
+ // their .env. For those the event can be made here:
7
+ //
8
+ // 1. the app's webhook handler is read: which header holds the signature,
9
+ // how it is computed (createHmac, the algorithm, hex or base64, over the
10
+ // body), where the secret comes from (process.env.NAME) and which fields
11
+ // and event types the handler looks at. Anything it signs in a way this
12
+ // file does not know (a timestamp in front, a prefix) is said as not
13
+ // tried, never guessed;
14
+ // 2. a correctly signed event is sent first. If the app refuses even that,
15
+ // nothing else means anything and the check stops, saying so;
16
+ // 3. then, each on a record of its own, and judged from the app's own list
17
+ // of those records before and after (never from a status code alone):
18
+ // - the same event with no signature at all,
19
+ // - with a wrong signature,
20
+ // - correctly signed but for an amount that is not the record's,
21
+ // - a refund event for a record nobody had paid or approved.
22
+ //
23
+ // Promises: only an app on this computer; the secret is read from the app's
24
+ // .env, used to sign, and never printed or saved; nothing is ever deleted;
25
+ // every record an event changed is listed, since a webhook cannot be undone.
26
+
27
+ const fs = require('fs');
28
+ const path = require('path');
29
+ const crypto = require('crypto');
30
+ const secrets = require('./kryptheon-secrets.js');
31
+
32
+ const VOLATILE_KEY = /^(updated_?at|modified_?at|last_?seen|now|server_?time|timestamp|request_?id|etag|generated_?at|processed_?at)$/i;
33
+ const ALGORITHMS = /^(sha1|sha224|sha256|sha384|sha512)$/i;
34
+ const SIG_HEADER = /sig|hmac|token|secret|signature/i;
35
+ const TYPE_NAME = /^(event_?type|type|event|kind|action|topic|eventType)$/i;
36
+ const ID_NAME = /^(event_?id|eventId|id|uuid)$/i;
37
+ const AMOUNT_NAME = /amount|cents|paise|total|price/i;
38
+ const CURRENCY_NAME = /^currency$/i;
39
+ const MAX_TYPES = 3;
40
+ const MAX_TRIES = 12;
41
+
42
+ const wordsOf = (name) => String(name).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
43
+
44
+ /** a.b.c / a['b'].c as ['a','b','c'], or null */
45
+ function chainOf(n) {
46
+ const out = [];
47
+ let c = n;
48
+ while (c && (c.type === 'MemberExpression' || c.type === 'OptionalMemberExpression')) {
49
+ if (!c.computed && c.property.type === 'Identifier') out.unshift(c.property.name);
50
+ else if (c.computed && c.property.type === 'StringLiteral') out.unshift(c.property.value);
51
+ else return null;
52
+ c = c.object;
53
+ }
54
+ if (c && c.type === 'Identifier') {
55
+ out.unshift(c.name);
56
+ return out;
57
+ }
58
+ return null;
59
+ }
60
+
61
+ /** The handler function of the route written at file:line, as { path, reqName } or null. */
62
+ function handlerAt(parser, ast, line) {
63
+ let found = null;
64
+ parser.traverse(ast, {
65
+ CallExpression(p) {
66
+ if (found) return;
67
+ const n = p.node;
68
+ if (!n.loc || n.loc.start.line !== line) return;
69
+ if (!n.callee || n.callee.type !== 'MemberExpression') return;
70
+ const verb = n.callee.property && n.callee.property.name;
71
+ if (!/^(post|put|patch|all)$/.test(verb || '')) return;
72
+ const isFn = (a) => a && (a.type === 'ArrowFunctionExpression' || a.type === 'FunctionExpression');
73
+ const argIndex = n.arguments.map((a) => a.type).lastIndexOf('ArrowFunctionExpression');
74
+ const fnIndex = argIndex >= 0 ? argIndex : n.arguments.map((a) => a.type).lastIndexOf('FunctionExpression');
75
+ if (fnIndex >= 0) {
76
+ found = { path: p.get('arguments.' + fnIndex), node: n.arguments[fnIndex] };
77
+ return;
78
+ }
79
+ // asyncRoute(async (req, res) => ...): the function inside the wrapper (round 25)
80
+ const last = n.arguments.length - 1;
81
+ const wrap = n.arguments[last];
82
+ if (wrap && wrap.type === 'CallExpression' && wrap.arguments.length === 1 && isFn(wrap.arguments[0])) {
83
+ found = { path: p.get('arguments.' + last + '.arguments.0'), node: wrap.arguments[0] };
84
+ }
85
+ },
86
+ });
87
+ if (!found) return null;
88
+ const first = found.node.params[0];
89
+ return { path: found.path, reqName: first && first.type === 'Identifier' ? first.name : null };
90
+ }
91
+
92
+ /**
93
+ * How the handler signs: { ok, header, algorithm, encoding, secret: { env, fallback }, fields, types, why }.
94
+ * Reading code only. `fields` are the body fields the map saw the route read.
95
+ */
96
+ function readSigning(parser, root, route, fields) {
97
+ let source;
98
+ const abs = path.join(root, route.file);
99
+ try {
100
+ source = fs.readFileSync(abs, 'utf8');
101
+ } catch (err) {
102
+ return { ok: false, why: 'the file ' + route.file + ' could not be read' };
103
+ }
104
+ let ast;
105
+ try {
106
+ ast = parser.babelParse(source, abs, true);
107
+ } catch (err) {
108
+ try {
109
+ ast = parser.babelParse(source, abs, false);
110
+ } catch (err2) {
111
+ return { ok: false, why: route.file + ' could not be parsed' };
112
+ }
113
+ }
114
+ const h = handlerAt(parser, ast, route.line);
115
+ if (!h || !h.reqName) return { ok: false, why: 'the handler at ' + route.file + ':' + route.line + ' is not a function written in the route itself' };
116
+ const req = h.reqName;
117
+ const resolve = (node, depth) => {
118
+ let n = node;
119
+ for (let i = 0; i < (depth || 3); i++) {
120
+ if (n && n.type === 'Identifier') {
121
+ const b = h.path.scope.getBinding(n.name);
122
+ const init = b && b.path && b.path.node && b.path.node.type === 'VariableDeclarator' ? b.path.node.init : null;
123
+ if (!init) return n;
124
+ n = init;
125
+ } else if (n && (n.type === 'AwaitExpression' || n.type === 'TSAsExpression' || n.type === 'ParenthesizedExpression')) n = n.argument || n.expression;
126
+ else break;
127
+ }
128
+ return n;
129
+ };
130
+ let header = null;
131
+ let hmac = null;
132
+ const literals = new Set();
133
+ h.path.traverse({
134
+ CallExpression(p) {
135
+ const n = p.node;
136
+ const chain = chainOf(n.callee);
137
+ // req.get('x-sig') / req.header('x-sig')
138
+ if (chain && chain[0] === req && /^(get|header)$/.test(chain[chain.length - 1]) && n.arguments[0] && n.arguments[0].type === 'StringLiteral' && SIG_HEADER.test(n.arguments[0].value) && !header) header = n.arguments[0].value.toLowerCase();
139
+ // .digest('hex') of .update(x) of createHmac(alg, secret)
140
+ if (n.callee && n.callee.type === 'MemberExpression' && n.callee.property.name === 'digest' && n.callee.object && n.callee.object.type === 'CallExpression') {
141
+ const upd = n.callee.object;
142
+ const mk = upd.callee && upd.callee.type === 'MemberExpression' && upd.callee.property.name === 'update' ? upd.callee.object : null;
143
+ const mkName = mk && mk.type === 'CallExpression' ? (mk.callee.type === 'MemberExpression' ? mk.callee.property.name : mk.callee.name) : null;
144
+ if (mkName === 'createHmac' && !hmac) hmac = { alg: mk.arguments[0], key: mk.arguments[1], payload: upd.arguments[0], enc: n.arguments[0] };
145
+ }
146
+ },
147
+ MemberExpression(p) {
148
+ const chain = chainOf(p.node);
149
+ if (chain && chain[0] === req && chain[1] === 'headers' && chain[2] && SIG_HEADER.test(chain[2]) && !header) header = chain[2].toLowerCase();
150
+ },
151
+ BinaryExpression(p) {
152
+ const n = p.node;
153
+ if (!/^[!=]==?$/.test(n.operator)) return;
154
+ const [a, b] = [n.left, n.right];
155
+ const name = (x) => (x.type === 'Identifier' ? x.name : (chainOf(x) || []).slice(-1)[0] || '');
156
+ if (b.type === 'StringLiteral' && TYPE_NAME.test(name(a))) literals.add(b.value);
157
+ if (a.type === 'StringLiteral' && TYPE_NAME.test(name(b))) literals.add(a.value);
158
+ },
159
+ SwitchStatement(p) {
160
+ const d = p.node.discriminant;
161
+ const nm = d.type === 'Identifier' ? d.name : (chainOf(d) || []).slice(-1)[0] || '';
162
+ if (!TYPE_NAME.test(nm)) return;
163
+ for (const c of p.node.cases) if (c.test && c.test.type === 'StringLiteral') literals.add(c.test.value);
164
+ },
165
+ });
166
+ if (!header) return { ok: false, why: 'no signature header is read in the handler (looked for a header with sig, hmac or token in its name)' };
167
+ if (!hmac) return { ok: false, why: 'the handler reads ' + header + ' but does not compute an HMAC the way this check knows (createHmac(alg, secret).update(body).digest(encoding))' };
168
+ const alg = hmac.alg && hmac.alg.type === 'StringLiteral' ? hmac.alg.value.toLowerCase() : null;
169
+ const enc = hmac.enc && hmac.enc.type === 'StringLiteral' ? hmac.enc.value.toLowerCase() : null;
170
+ if (!alg || !ALGORITHMS.test(alg)) return { ok: false, why: 'the HMAC algorithm is not a plain name written in the code' };
171
+ if (enc !== 'hex' && enc !== 'base64') return { ok: false, why: 'the signature is not read out as hex or base64' };
172
+ // what is signed: JSON.stringify(req.body), or the raw body
173
+ const pay = resolve(hmac.payload);
174
+ const payChain = pay && chainOf(pay);
175
+ const stringifies = pay && pay.type === 'CallExpression' && (chainOf(pay.callee) || []).join('.') === 'JSON.stringify' && (chainOf(pay.arguments[0]) || []).join('.') === req + '.body';
176
+ const rawBody = payChain && payChain[0] === req && /^(rawBody|body)$/.test(payChain[1] || '') && payChain.length === 2;
177
+ if (!stringifies && !rawBody) return { ok: false, why: 'what is signed is more than the body (a timestamp or a prefix in front, say), which this check does not make' };
178
+ // the secret
179
+ const key = resolve(hmac.key);
180
+ let secret = null;
181
+ const envName = (n) => { const c = n && chainOf(n); return c && c[0] === 'process' && c[1] === 'env' && c[2] ? c[2] : null; };
182
+ if (key && key.type === 'LogicalExpression' && /^(\|\||\?\?)$/.test(key.operator)) {
183
+ const e = envName(key.left);
184
+ if (e) secret = { env: e, fallback: key.right.type === 'StringLiteral' ? key.right.value : null };
185
+ } else if (envName(key)) secret = { env: envName(key), fallback: null };
186
+ else if (key && key.type === 'StringLiteral') secret = { env: null, fallback: key.value };
187
+ if (!secret) return { ok: false, why: 'the secret is not process.env.NAME or a plain string in the code' };
188
+ return { ok: true, header, algorithm: alg, encoding: enc, secret, fields: (fields || []).slice(), types: Array.from(literals), signs: stringifies ? 'JSON.stringify(req.body)' : 'the raw body' };
189
+ }
190
+
191
+ /** Which body field is which, from names. { id, type, record, amount, currency, others } or why not. */
192
+ function shapeOf(fields) {
193
+ const names = fields.map((f) => f.name);
194
+ const type = names.find((n) => TYPE_NAME.test(n));
195
+ const id = names.find((n) => ID_NAME.test(n) && n !== type);
196
+ const amount = names.find((n) => AMOUNT_NAME.test(n));
197
+ const currency = names.find((n) => CURRENCY_NAME.test(n));
198
+ const record = names.find((n) => n !== id && n !== type && n !== amount && (/_?id$/i.test(n) || /ref$/i.test(n) || /Id$/.test(n)));
199
+ if (!type) return { ok: false, why: 'no field of the body names the kind of event (event_type, type, event ...)' };
200
+ if (!record) return { ok: false, why: 'no field of the body names the record the event is about (return_id, order_id ...)' };
201
+ return { ok: true, id, type, record, amount, currency };
202
+ }
203
+
204
+ /** The signature the app would accept for these exact bytes. Never printed. */
205
+ function sign(signing, secret, body) {
206
+ const mac = crypto.createHmac(signing.algorithm, secret).update(body).digest(signing.encoding);
207
+ return mac;
208
+ }
209
+
210
+ /** A signature of the right shape that is not right. */
211
+ function wrongSignature(signing, secret, body) {
212
+ const good = sign(signing, secret, body);
213
+ // flip the first character, staying inside the alphabet it is written in
214
+ const first = good[0];
215
+ const swap = signing.encoding === 'hex' ? (first === '0' ? '1' : '0') : (first === 'A' ? 'B' : 'A');
216
+ return swap + good.slice(1);
217
+ }
218
+
219
+ const stableItem = (item) => {
220
+ if (!item || typeof item !== 'object') return item;
221
+ const out = {};
222
+ for (const k of Object.keys(item).sort()) if (!VOLATILE_KEY.test(k)) out[k] = item[k];
223
+ return out;
224
+ };
225
+
226
+ const listOf = (json) => {
227
+ if (Array.isArray(json)) return json;
228
+ if (json && typeof json === 'object') for (const k of Object.keys(json)) if (Array.isArray(json[k])) return json[k];
229
+ return null;
230
+ };
231
+
232
+ /** The words of the order a status runs in: what has been paid or approved before a refund. */
233
+ const PAID = /approv|paid|captur|complet|process|settl|success|confirm/i;
234
+ const REFUNDED = /refund/i;
235
+
236
+ /**
237
+ * Tries each signed-event case on the running app. { ran, why, hooks: [...], findings, left }.
238
+ * `options`: origin, env, say, stopped, fetch, map (a map already read), packageDir.
239
+ */
240
+ async function run(root, options) {
241
+ const api = require('./kryptheon-api.js');
242
+ const authz = require('./kryptheon-authz.js');
243
+ const code = require('./kryptheon-code.js');
244
+ const mapper = require('./kryptheon-map.js');
245
+ const opts = options || {};
246
+ const say = typeof opts.say === 'function' ? opts.say : () => {};
247
+ const plan = api.planOf(root, opts);
248
+ if (!plan.ran) return { ran: false, why: plan.why };
249
+ const hooks = (plan.map.routes || []).filter((r) => r.kind === 'webhook' && !r.unmounted && r.method === 'POST' && r.path);
250
+ if (!hooks.length) return { ran: false, why: 'the map found no webhook route' };
251
+ let origin;
252
+ try {
253
+ origin = authz.assertLocalTarget(opts.origin);
254
+ } catch (err) {
255
+ return { ran: false, why: 'the app must be on this computer (localhost or 127.0.0.1): ' + (opts.origin || 'no address was given') };
256
+ }
257
+ const j = plan.journey;
258
+ if (!j.signIn) return { ran: false, why: j.signInWhy };
259
+ if (!j.accounts.usable.length) return { ran: false, why: 'no account has a password in .env, so the records an event is about cannot be read' };
260
+ const parser = code.loadParser(opts.packageDir || __dirname);
261
+ if (!parser) return { ran: false, why: 'the JavaScript parser this check uses was not found' };
262
+ const who = j.accounts.usable[0];
263
+ const appEnv = Object.assign({}, secrets.readEnvFile(secrets.envFileFor(root)), opts.env || {});
264
+ const ctx = authz.makeContext({ baseUrl: origin, allowOrigins: [origin], fetch: opts.fetch, passwords: { [who.email]: who.password }, maxRequests: 200 });
265
+ const reader = authz.makeSession(ctx, 'account', who.email, who.password);
266
+ const fields = { [j.signIn.emailField]: who.email, [j.signIn.passwordField]: who.password };
267
+ const signed = authz.replyOf(await reader.send(j.signIn.method, j.signIn.path, j.signIn.encoding === 'form' ? { form: fields } : { json: fields }));
268
+ if (signed.kind === 'refused' || signed.kind === 'server-error' || signed.kind === 'no-answer') return { ran: false, why: 'could not sign in as ' + who.email + ' (' + signed.note + ')' };
269
+ const out = { ran: true, hooks: [], findings: [], left: [] };
270
+
271
+ for (const route of hooks) {
272
+ const name = route.method + ' ' + route.path;
273
+ const hook = { route: name, from: route.file + ':' + route.line, tried: [], findings: [], notTried: null, control: null };
274
+ out.hooks.push(hook);
275
+ const bodyFields = ((route.validation && route.validation.fields) || []).filter((f) => f.from === 'body');
276
+ const signing = readSigning(parser, root, route, bodyFields);
277
+ if (!signing.ok) { hook.notTried = signing.why; continue; }
278
+ hook.signing = { header: signing.header, algorithm: signing.algorithm, encoding: signing.encoding, secretFrom: signing.secret.env ? signing.secret.env + ' in .env' : 'a string in the code', signs: signing.signs };
279
+ const secret = (signing.secret.env && appEnv[signing.secret.env]) || signing.secret.fallback;
280
+ if (!secret) { hook.notTried = 'the secret ' + signing.secret.env + ' is not in the app\'s .env, and the code has no fallback'; continue; }
281
+ // whatever the app answers is cleaned of it before anything is said
282
+ if (!ctx.secrets.includes(secret)) ctx.secrets.push(secret);
283
+ const shape = shapeOf(bodyFields);
284
+ if (!shape.ok) { hook.notTried = shape.why; continue; }
285
+ const types = signing.types.slice(0, MAX_TYPES);
286
+ if (!types.length) { hook.notTried = 'no event type is written in the handler (an if on ' + shape.type + ' or a switch), so there is nothing to send'; continue; }
287
+ // the records an event is about: the app's own list of them, as the signed-in account sees it
288
+ const resource = wordsOf(shape.record)[0];
289
+ const listRoute = (plan.map.routes || []).find((r) => r.method === 'GET' && !r.unmounted && r.path && !/[:{]/.test(r.path) && new RegExp('(^|/)' + resource + '(s|es)?$', 'i').test(r.path));
290
+ if (!listRoute) { hook.notTried = 'the app has no list of ' + resource + 's (GET /...' + resource + 's) to read the effect of an event from'; continue; }
291
+ const readList = async () => {
292
+ const res = await reader.send('GET', listRoute.path, {});
293
+ return res.status === 200 ? listOf(res.json) : null;
294
+ };
295
+ const items0 = await readList();
296
+ if (!items0 || !items0.length) { hook.notTried = 'GET ' + listRoute.path + ' answered no records to aim an event at'; continue; }
297
+ const records = items0.filter((it) => it && it.id !== undefined);
298
+ const amountKey = records[0] && Object.keys(records[0]).find((k) => AMOUNT_NAME.test(k));
299
+ const statusKey = records[0] && Object.keys(records[0]).find((k) => /^status$|^state$/i.test(k));
300
+ hook.list = listRoute.path;
301
+
302
+ const used = new Set();
303
+ const nextRecord = (want) => records.find((r) => !used.has(r.id) && (!statusKey || !REFUNDED.test(String(r[statusKey]))) && (!want || want(r)));
304
+ // a refund event is tried first on a record nobody has paid or approved: the case it should refuse
305
+ const unpaidFor = (type) => (REFUNDED.test(type) && statusKey ? (r) => !PAID.test(String(r[statusKey])) : null);
306
+ const bodyFor = (type, rec, amount) => {
307
+ const b = {};
308
+ if (shape.id) b[shape.id] = 'kx-evt-' + crypto.randomBytes(5).toString('hex');
309
+ b[shape.type] = type;
310
+ b[shape.record] = rec.id;
311
+ if (shape.amount) b[shape.amount] = amount !== undefined ? amount : amountKey ? rec[amountKey] : 1;
312
+ return b;
313
+ };
314
+ const post = async (mode, body) => {
315
+ const text = JSON.stringify(body);
316
+ const session = authz.makeSession(ctx, null, '(nobody signed in)', null);
317
+ const headers = {};
318
+ if (mode === 'signed') headers[signing.header] = sign(signing, secret, text);
319
+ if (mode === 'wrong') headers[signing.header] = wrongSignature(signing, secret, text);
320
+ return session.send('POST', route.path, { json: body, headers });
321
+ };
322
+ const attempt = async (mode, type, rec, amount, label, same) => {
323
+ const before = await readList();
324
+ const body = same || bodyFor(type, rec, amount);
325
+ used.add(rec.id);
326
+ const res = await post(mode, body);
327
+ const reply = authz.replyOf(res);
328
+ const after = await readList();
329
+ const was = before && before.find((x) => x.id === rec.id);
330
+ const now = after && after.find((x) => x.id === rec.id);
331
+ const changed = !!(was && now && JSON.stringify(stableItem(was)) !== JSON.stringify(stableItem(now)));
332
+ const took = reply.kind === 'accepted' || reply.kind === 'redirect';
333
+ const t = { mode, label: label || mode, type, record: rec.id, status: res.status, took, changed, from: was && statusKey ? was[statusKey] : null, to: now && statusKey ? now[statusKey] : null };
334
+ Object.defineProperty(t, 'body', { value: body, enumerable: false }); // sent again as it was, never printed
335
+ hook.tried.push(t);
336
+ if (changed) out.left.push(name + ' ' + (label || mode) + ' ' + type + ' for ' + resource + ' ' + rec.id + (t.from !== null ? ': ' + statusKey + ' ' + t.from + ' -> ' + t.to : ' changed it'));
337
+ else if (took) out.left.push(name + ' ' + (label || mode) + ' ' + type + ' for ' + resource + ' ' + rec.id + ' answered ' + res.status + ' (no change seen in ' + listRoute.path + '); the event id is in the app\'s webhook table');
338
+ return t;
339
+ };
340
+
341
+ // 1. a correctly signed event first: if the app refuses its own, nothing after it means anything
342
+ say('Sending a correctly signed ' + types[0] + ' to ' + name + ' first...');
343
+ const first = nextRecord(unpaidFor(types[0])) || nextRecord();
344
+ if (!first) { hook.notTried = 'no record left to aim an event at'; continue; }
345
+ const control = await attempt('signed', types[0], first, undefined, 'signed');
346
+ hook.control = control;
347
+ if (!control.took) {
348
+ hook.notTried = 'the app refused even a correctly signed event (' + control.status + '), so either the signature is made differently from how the code reads, or the event needs more than ' + Object.keys(bodyFor(types[0], first)).join(', ') + ': nothing after it would mean anything';
349
+ continue;
350
+ }
351
+ // 2. the very same event again - same id, same signature - as a provider does when it is not sure it was taken
352
+ const replay = await attempt('signed', types[0], first, undefined, 'signed again (same event)', control.body);
353
+ void replay;
354
+ // the tries, in the order that tells the most when records run out
355
+ const cases = [];
356
+ for (const type of types) cases.push({ mode: 'none', type, label: 'unsigned' });
357
+ cases.push({ mode: 'wrong', type: types[0], label: 'wrong signature' });
358
+ for (const type of types.slice(1)) cases.push({ mode: 'signed', type, label: 'signed' });
359
+ if (shape.amount && amountKey) for (const type of types) if (!REFUNDED.test(type) && /pay|captur|charge|paid|success/i.test(type)) { cases.push({ mode: 'signed', type, label: 'signed, wrong amount', wrongAmount: true }); break; }
360
+ for (const c of cases) {
361
+ if (opts.stopped && opts.stopped()) break;
362
+ if (hook.tried.length >= MAX_TRIES) break;
363
+ const rec = (c.mode === 'signed' && nextRecord(unpaidFor(c.type))) || nextRecord();
364
+ if (!rec) break;
365
+ let amount;
366
+ if (c.wrongAmount) amount = (Number(rec[amountKey]) || 0) + 100;
367
+ await attempt(c.mode, c.type, rec, amount, c.label);
368
+ }
369
+
370
+ // judged
371
+ const at = hook.from;
372
+ const finding = (kind, severity, status, headline, proof, fix) => {
373
+ const f = { kind, where: name, from: at, status, severity, headline, proof, fixPrompt: ['Kryptheon sent my running app an event it signs itself, and it was taken when it should not have been:', '', headline, '', 'Where: ' + at, '', fix, '', 'Afterwards I will run: npx kryptheon api'].join(String.fromCharCode(10)) };
374
+ hook.findings.push(f);
375
+ out.findings.push(f);
376
+ };
377
+ const lineOf = (t) => t.label + ' ' + t.type + ' for ' + resource + ' ' + t.record + ': answered ' + t.status + (t.changed ? ', and ' + (t.from !== null ? statusKey + ' went ' + t.from + ' -> ' + t.to : 'the record changed') + ' in GET ' + listRoute.path : t.took ? ', nothing changed in GET ' + listRoute.path : ', refused');
378
+ for (const t of hook.tried) {
379
+ // the first signed event is a control for the signature, but what it did is judged like any other signed event
380
+ if (t === control && !(t.changed && REFUNDED.test(String(t.to)) && t.from !== null && !PAID.test(String(t.from)))) continue;
381
+ if (t.mode === 'none' && t.took) {
382
+ finding('webhook-unsigned', t.changed ? 'CRITICAL' : 'HIGH', t.changed ? 'confirmed' : 'verification required',
383
+ t.changed ? name + ' took ' + t.type + ' with no signature at all and changed ' + resource + ' ' + t.record + (t.from !== null ? ' (' + statusKey + ' ' + t.from + ' -> ' + t.to + ')' : '') + ': anyone who can reach it can send one.' : name + ' answered ' + t.status + ' to ' + t.type + ' with no signature, though no change was seen in ' + listRoute.path + '.',
384
+ ['With nobody signed in and no ' + signing.header + ' header: ' + lineOf(t)], 'Treat a request with no signature as invalid: answer 401 before anything is saved, the same as a wrong signature. The check that reads "if the header is there and it is wrong" lets every request without the header through.');
385
+ } else if (t.mode === 'wrong' && t.took) {
386
+ finding('webhook-forged', t.changed ? 'CRITICAL' : 'HIGH', t.changed ? 'confirmed' : 'verification required',
387
+ name + ' took ' + t.type + ' with a wrong signature' + (t.changed ? ' and changed ' + resource + ' ' + t.record : '') + '.',
388
+ ['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.');
389
+ } else if (t.label === 'signed, wrong amount' && t.took && t.changed) {
390
+ finding('webhook-amount', 'HIGH', 'confirmed',
391
+ name + ' applied ' + t.type + ' for an amount that is not ' + resource + ' ' + t.record + '\'s: the status changed all the same.',
392
+ ['Correctly signed, with the amount 100 higher than the record\'s: ' + lineOf(t)], 'Compare the amount (and currency) in the event with the amount the ' + resource + ' was created for, and ignore or flag the event when they differ.');
393
+ } else if (t.label === 'signed again (same event)' && t.took && t.changed) {
394
+ finding('webhook-replay', 'HIGH', 'confirmed',
395
+ name + ' took the same ' + t.type + ' a second time - same event id, same signature - and changed ' + resource + ' ' + t.record + ' again.',
396
+ ['The correctly signed event, sent again unchanged: ' + lineOf(t)], 'Keep the id of every event you have handled, with a unique rule on it, and answer 200 without doing anything when the same id comes again. Providers resend events whenever they are not sure the first was taken.');
397
+ } else if (t.mode === 'signed' && t.label === 'signed' && t.changed && REFUNDED.test(String(t.to)) && t.from !== null && !PAID.test(String(t.from))) {
398
+ finding('webhook-lifecycle', 'MEDIUM', 'verification required',
399
+ name + ' marked ' + resource + ' ' + t.record + ' as ' + t.to + ' from ' + t.from + ': a refund event for something nobody had paid or approved.',
400
+ ['Correctly signed: ' + lineOf(t)], 'Apply a refund event only to a record that was paid or approved first, in the same tenant, for no more than was paid; answer and log anything else without changing it.');
401
+ }
402
+ }
403
+ }
404
+ return out;
405
+ }
406
+
407
+ module.exports = { readSigning, shapeOf, sign, wrongSignature, run, MAX_TRIES };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kryptheon",
3
- "version": "0.1.56",
3
+ "version": "0.1.58",
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",
@@ -56,7 +56,9 @@
56
56
  "kryptheon-authz.js",
57
57
  "kryptheon-roles.js",
58
58
  "kryptheon-map.js",
59
- "kryptheon-api.js"
59
+ "kryptheon-api.js",
60
+ "kryptheon-webhook.js",
61
+ "kryptheon-csv.js"
60
62
  ],
61
63
  "engines": {
62
64
  "node": ">=20.6.0"
@@ -66,7 +68,7 @@
66
68
  "pg": "^8.23.0"
67
69
  },
68
70
  "scripts": {
69
- "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-package.check.js",
71
+ "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",
70
72
  "check:store": "node kryptheon-store.check.js",
71
73
  "check:code": "node kryptheon-code.check.js",
72
74
  "check:constdata": "node kryptheon-constdata.check.js",
@@ -109,7 +111,9 @@
109
111
  "check:roles": "node kryptheon-roles.check.js",
110
112
  "check:roles-mutants": "node kryptheon-roles.mutants.js",
111
113
  "check:map": "node kryptheon-map.check.js",
112
- "check:api": "node kryptheon-api.check.js"
114
+ "check:api": "node kryptheon-api.check.js",
115
+ "check:webhook": "node kryptheon-webhook.check.js",
116
+ "check:csv": "node kryptheon-csv.check.js"
113
117
  },
114
118
  "keywords": [
115
119
  "playwright",