kryptheon 0.1.63 → 0.1.65

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.
@@ -92,6 +92,163 @@ function handlerAt(parser, ast, line) {
92
92
  return { path: found.path, reqName: first && first.type === 'Identifier' ? first.name : null };
93
93
  }
94
94
 
95
+ const isFnNode = (n) => !!n && /^(FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/.test(n.type);
96
+ // a helper module followed from the handler's file, and from that one (round 30: the router requires
97
+ // ../services/signatures.js, whose verifySignature signs JSON.stringify(body) with createHmac)
98
+ const MAX_MODULE_HOPS = 2;
99
+
100
+ /** The parsed files of the project a handler's helpers live in: abs -> ast (or null), read once per readSigning. */
101
+ function moduleReader(parser) {
102
+ const cache = new Map();
103
+ return (abs) => {
104
+ if (cache.has(abs)) return cache.get(abs);
105
+ let ast = null;
106
+ try {
107
+ const text = fs.readFileSync(abs, 'utf8');
108
+ try {
109
+ ast = parser.babelParse(text, abs, true);
110
+ } catch (err) {
111
+ ast = parser.babelParse(text, abs, false);
112
+ }
113
+ } catch (err) {
114
+ ast = null;
115
+ }
116
+ cache.set(abs, ast);
117
+ return ast;
118
+ };
119
+ }
120
+
121
+ /** A relative module a file names, as a file of the project - or null (a package, or not there). */
122
+ function localModule(fromAbs, spec) {
123
+ if (typeof spec !== 'string' || !/^\.{1,2}(\/|$)/.test(spec)) return null;
124
+ const base = path.resolve(path.dirname(fromAbs), spec);
125
+ const stem = base.replace(/\.(js|mjs|cjs|jsx|ts)$/i, '');
126
+ for (const f of [base, stem + '.js', stem + '.cjs', stem + '.mjs', stem + '.ts', stem + '.jsx', path.join(base, 'index.js'), path.join(base, 'index.ts')]) {
127
+ try {
128
+ if (fs.statSync(f).isFile()) return f;
129
+ } catch (err) {
130
+ /* next */
131
+ }
132
+ }
133
+ return null;
134
+ }
135
+
136
+ /** require('./x') / require('./x').name / await import('./x') as { spec, name } (name null for the whole module), or null. */
137
+ function requiredOf(node) {
138
+ let n = node;
139
+ if (n && n.type === 'AwaitExpression') n = n.argument;
140
+ if (n && n.type === 'MemberExpression' && !n.computed && n.property.type === 'Identifier') {
141
+ const inner = requiredOf(n.object);
142
+ return inner && inner.name === null ? { spec: inner.spec, name: n.property.name === 'default' ? 'default' : n.property.name } : null;
143
+ }
144
+ if (n && n.type === 'CallExpression' && ((n.callee.type === 'Identifier' && n.callee.name === 'require') || n.callee.type === 'Import') && n.arguments[0] && n.arguments[0].type === 'StringLiteral') return { spec: n.arguments[0].value, name: null };
145
+ return null;
146
+ }
147
+
148
+ /**
149
+ * Where a name of a file comes from when it is another file's: { spec, name } - `name` the exported name, 'default'
150
+ * for the module's own value, null for the whole module (a namespace: sigs.verify). Null for anything else.
151
+ */
152
+ function importOf(binding, localName) {
153
+ const bp = binding && binding.path;
154
+ const n = bp && bp.node;
155
+ if (!n) return null;
156
+ if (n.type === 'ImportSpecifier' && bp.parent.source) return { spec: bp.parent.source.value, name: n.imported.type === 'Identifier' ? n.imported.name : n.imported.value };
157
+ if (n.type === 'ImportDefaultSpecifier' && bp.parent.source) return { spec: bp.parent.source.value, name: 'default' };
158
+ if (n.type === 'ImportNamespaceSpecifier' && bp.parent.source) return { spec: bp.parent.source.value, name: null };
159
+ if (n.type !== 'VariableDeclarator') return null;
160
+ const req = requiredOf(n.init);
161
+ if (!req) return null;
162
+ // const verify = require('./sigs') - the module's own value; const sigs = require('./sigs') used as sigs.verify
163
+ if (n.id.type === 'Identifier') return { spec: req.spec, name: req.name === null ? 'default' : req.name, whole: req.name === null };
164
+ if (n.id.type === 'ObjectPattern' && req.name === null) {
165
+ for (const prop of n.id.properties) {
166
+ if (prop.type !== 'ObjectProperty' || prop.computed) continue;
167
+ const v = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value;
168
+ if (v.type === 'Identifier' && v.name === localName) return { spec: req.spec, name: prop.key.type === 'Identifier' ? prop.key.name : prop.key.value };
169
+ }
170
+ }
171
+ return null;
172
+ }
173
+
174
+ /**
175
+ * The function a module exports under a name ('default' for module.exports = fn / export default): its path, or a
176
+ * re-export of another module ({ spec, name }) - or null.
177
+ */
178
+ function exportedFunction(parser, ast, name) {
179
+ let found = null;
180
+ let again = null;
181
+ const fnOf = (valuePath) => {
182
+ const v = valuePath && valuePath.node;
183
+ if (isFnNode(v)) return valuePath;
184
+ if (v && v.type === 'Identifier') {
185
+ const b = valuePath.scope.getBinding(v.name);
186
+ const bn = b && b.path && b.path.node;
187
+ if (bn && bn.type === 'FunctionDeclaration') return b.path;
188
+ if (bn && bn.type === 'VariableDeclarator' && isFnNode(bn.init)) return b.path.get('init');
189
+ if (bn && bn.type === 'VariableDeclarator' && requiredOf(bn.init)) {
190
+ const r = requiredOf(bn.init);
191
+ again = { spec: r.spec, name: r.name === null ? name : r.name };
192
+ }
193
+ const imp = b && importOf(b, v.name);
194
+ if (imp && !again) again = { spec: imp.spec, name: imp.name === null ? name : imp.name };
195
+ }
196
+ const r = v && requiredOf(v);
197
+ if (r && !again) again = { spec: r.spec, name: r.name === null ? name : r.name };
198
+ return null;
199
+ };
200
+ parser.traverse(ast, {
201
+ AssignmentExpression(p) {
202
+ if (found) return;
203
+ const chain = chainOf(p.node.left);
204
+ if (!chain) return;
205
+ const right = p.get('right');
206
+ // module.exports = { verifySignature, sign: signBody } / module.exports = fn
207
+ if (chain.join('.') === 'module.exports') {
208
+ if (right.node.type === 'ObjectExpression') {
209
+ right.get('properties').forEach((prop) => {
210
+ if (found || prop.node.type !== 'ObjectProperty' && prop.node.type !== 'ObjectMethod') return;
211
+ const key = prop.node.key && (prop.node.key.type === 'Identifier' ? prop.node.key.name : prop.node.key.value);
212
+ if (key !== name) return;
213
+ found = prop.node.type === 'ObjectMethod' ? prop : fnOf(prop.get('value'));
214
+ });
215
+ } else if (name === 'default') found = fnOf(right);
216
+ else if (requiredOf(right.node) && requiredOf(right.node).name === null) again = again || { spec: requiredOf(right.node).spec, name: name };
217
+ return;
218
+ }
219
+ // module.exports.verify = ... / exports.verify = ...
220
+ if ((chain.length === 3 && chain[0] === 'module' && chain[1] === 'exports' && chain[2] === name) || (chain.length === 2 && chain[0] === 'exports' && chain[1] === name)) found = fnOf(right);
221
+ },
222
+ ExportNamedDeclaration(p) {
223
+ if (found) return;
224
+ const d = p.node.declaration;
225
+ if (d && d.type === 'FunctionDeclaration' && d.id && d.id.name === name) found = p.get('declaration');
226
+ else if (d && d.type === 'VariableDeclaration') {
227
+ p.get('declaration.declarations').forEach((dp) => {
228
+ if (!found && dp.node.id.type === 'Identifier' && dp.node.id.name === name && isFnNode(dp.node.init)) found = dp.get('init');
229
+ });
230
+ } else if (!d) {
231
+ for (const sp of p.node.specifiers || []) {
232
+ const exported = sp.exported && (sp.exported.type === 'Identifier' ? sp.exported.name : sp.exported.value);
233
+ if (exported !== name || !sp.local) continue;
234
+ if (p.node.source) again = again || { spec: p.node.source.value, name: sp.local.name };
235
+ else {
236
+ const b = p.scope.getBinding(sp.local.name);
237
+ const bn = b && b.path && b.path.node;
238
+ if (bn && bn.type === 'FunctionDeclaration') found = b.path;
239
+ else if (bn && bn.type === 'VariableDeclarator' && isFnNode(bn.init)) found = b.path.get('init');
240
+ }
241
+ }
242
+ }
243
+ },
244
+ ExportDefaultDeclaration(p) {
245
+ if (found || name !== 'default') return;
246
+ found = isFnNode(p.node.declaration) ? p.get('declaration') : fnOf(p.get('declaration'));
247
+ },
248
+ });
249
+ return found || (again ? { reexport: again } : null);
250
+ }
251
+
95
252
  /**
96
253
  * How the handler signs: { ok, header, algorithm, encoding, secret: { env, fallback }, fields, types, why }.
97
254
  * Reading code only. `fields` are the body fields the map saw the route read.
@@ -167,6 +324,8 @@ function readSigning(parser, root, route, fields) {
167
324
  // the helper call being read now: a call found inside it is that call's child, so a secret can be followed back
168
325
  // through each of them to the handler (round 28: hmac(secret, raw) -> signBody(secret, body) -> createHmac)
169
326
  let reading = null;
327
+ // the file the function being read is in: a helper's own requires are that file's
328
+ let readingFile = abs;
170
329
  const readFrom = (fnPath) => fnPath.traverse({
171
330
  CallExpression(p) {
172
331
  const n = p.node;
@@ -186,7 +345,12 @@ function readSigning(parser, root, route, fields) {
186
345
  if (n.callee && n.callee.type === 'Identifier') {
187
346
  // handed the body, or the body's bytes: sign(raw, key) where raw = JSON.stringify(req.body || {})
188
347
  const at = n.arguments.findIndex((a) => isBody(a) || isPayload(resolve(a, 3, p)));
189
- if (at >= 0) helpers.push({ name: n.callee.name, at, scope: p.scope, callPath: p, parent: reading });
348
+ if (at >= 0) helpers.push({ name: n.callee.name, at, scope: p.scope, callPath: p, parent: reading, file: readingFile, hops: reading ? reading.hops : 0 });
349
+ }
350
+ // sigs.verifySignature(req.body, ...): a function of another file of the project, through its module (round 30)
351
+ if (n.callee && n.callee.type === 'MemberExpression' && !n.callee.computed && n.callee.object.type === 'Identifier' && n.callee.property.type === 'Identifier') {
352
+ const at = n.arguments.findIndex((a) => isBody(a) || isPayload(resolve(a, 3, p)));
353
+ if (at >= 0) helpers.push({ name: n.callee.object.name, member: n.callee.property.name, at, scope: p.scope, callPath: p, parent: reading, file: readingFile, hops: reading ? reading.hops : 0 });
190
354
  }
191
355
  // ['payment.captured', 'refund.processed'].includes(payload.type), or TYPES.includes(event.type): every kind in
192
356
  // the list (round 27)
@@ -231,23 +395,54 @@ function readSigning(parser, root, route, fields) {
231
395
  if (p.node.id.type === 'ObjectPattern' && isBody(p.node.init)) for (const prop of p.node.id.properties) if (prop.key && prop.key.type === 'Identifier') destructured.push(prop.key.name);
232
396
  },
233
397
  });
398
+ // the function a helper call names: one of the same file, or one another file of the project exports (a relative
399
+ // require or import, followed at most MAX_MODULE_HOPS files away from the handler's)
400
+ const parsed = moduleReader(parser);
401
+ const fnOfCall = (call) => {
402
+ const b = call.scope.getBinding(call.name);
403
+ if (!b || !b.path) return null;
404
+ if (!call.member) {
405
+ const own = b.path.node.type === 'FunctionDeclaration' ? b.path : b.path.node.type === 'VariableDeclarator' && b.path.node.init && /Function/.test(b.path.node.init.type) ? b.path.get('init') : null;
406
+ if (own) return { fnPath: own, file: call.file };
407
+ }
408
+ const imp = importOf(b, call.name);
409
+ if (!imp) return null;
410
+ // sigs.verify needs the whole module; verify(...) needs a function, not a module's namespace
411
+ if (call.member && !(imp.name === null || imp.whole)) return null;
412
+ if (!call.member && imp.name === null) return null;
413
+ let want = { spec: imp.spec, name: call.member || imp.name };
414
+ let from = call.file;
415
+ for (let hop = call.hops; hop < MAX_MODULE_HOPS; hop++) {
416
+ const abs = localModule(from, want.spec);
417
+ const ast = abs && parsed(abs);
418
+ if (!ast) return null;
419
+ const got = exportedFunction(parser, ast, want.name);
420
+ if (!got) return null;
421
+ if (!got.reexport) return { fnPath: got, file: abs, hops: hop + 1 };
422
+ want = got.reexport;
423
+ from = abs;
424
+ }
425
+ return null;
426
+ };
234
427
  readFrom(h.path);
235
428
  let via = null;
236
429
  if (!hmac) {
237
430
  for (const call of helpers) {
238
- const b = call.scope.getBinding(call.name);
239
- if (!b || !b.path) continue;
240
- const fnPath = b.path.node.type === 'FunctionDeclaration' ? b.path : b.path.node.type === 'VariableDeclarator' && b.path.node.init && /Function/.test(b.path.node.init.type) ? b.path.get('init') : null;
431
+ const target = fnOfCall(call);
432
+ const fnPath = target && target.fnPath;
241
433
  const param = fnPath && fnPath.node.params[call.at];
242
434
  if (!param || param.type !== 'Identifier') continue;
243
435
  bodyNames.add(param.name);
244
436
  scopePath = fnPath;
245
437
  call.fnPath = fnPath;
438
+ if (target.hops !== undefined) call.hops = target.hops;
246
439
  reading = call;
440
+ readingFile = target.file;
247
441
  readFrom(fnPath);
248
442
  reading = null;
443
+ readingFile = abs;
249
444
  if (hmac) {
250
- via = call.name;
445
+ via = call.member ? call.name + '.' + call.member : call.name;
251
446
  // the helper's own parameters are this call's arguments: hmac(secret, body) called as
252
447
  // hmac(process.env.PAYMENT_WEBHOOK_SECRET || '', raw) signs with that secret (round 27)
253
448
  hmac.via = call;
@@ -261,15 +456,17 @@ function readSigning(parser, root, route, fields) {
261
456
  // the other functions handed the body: what they read and the kinds they branch on are the webhook's too, even
262
457
  // once the HMAC is found (round 27: hmac(...) signs, applyPaymentEvent(payload) acts on payload.type)
263
458
  for (const call of helpers) {
264
- if (call.read || call.name === via) continue;
265
- const b = call.scope.getBinding(call.name);
266
- if (!b || !b.path) continue;
267
- const fnPath = b.path.node.type === 'FunctionDeclaration' ? b.path : b.path.node.type === 'VariableDeclarator' && b.path.node.init && /Function/.test(b.path.node.init.type) ? b.path.get('init') : null;
459
+ if (call.read || (call.member ? call.name + '.' + call.member : call.name) === via) continue;
460
+ const target = fnOfCall(call);
461
+ const fnPath = target && target.fnPath;
268
462
  const param = fnPath && fnPath.node.params[call.at];
269
463
  if (!param || param.type !== 'Identifier') continue;
270
464
  call.read = true;
465
+ if (target.hops !== undefined) call.hops = target.hops;
271
466
  bodyNames.add(param.name);
467
+ readingFile = target.file;
272
468
  readFrom(fnPath);
469
+ readingFile = abs;
273
470
  }
274
471
  const known = new Set((fields || []).map((f) => f.name));
275
472
  const allFields = (fields || []).slice().concat(destructured.filter((n) => !known.has(n) && (known.add(n), true)).map((n) => ({ name: n, from: 'body' })));
@@ -277,7 +474,7 @@ function readSigning(parser, root, route, fields) {
277
474
  // inventory). Not "not tried" - its events are sent with no signature, which is the very thing to find out
278
475
  if (!header && !hmac) return { ok: true, open: true, fields: allFields, types: kindsOf(), typeField, why: 'no signature header is read and no HMAC is made in the handler' };
279
476
  if (!header) return { ok: false, why: 'the handler makes an HMAC but reads no signature header (looked for a header with sig, hmac or token in its name)' };
280
- 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)), in itself or in a function of the same file it hands the body to' };
477
+ 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)), in itself, in a function of the same file it hands the body to, or in one a file of the project it requires exports' };
281
478
  const alg = hmac.alg && hmac.alg.type === 'StringLiteral' ? hmac.alg.value.toLowerCase() : null;
282
479
  const enc = hmac.enc && hmac.enc.type === 'StringLiteral' ? hmac.enc.value.toLowerCase() : null;
283
480
  if (!alg || !ALGORITHMS.test(alg)) return { ok: false, why: 'the HMAC algorithm is not a plain name written in the code' };
@@ -587,14 +784,30 @@ async function run(root, options) {
587
784
  // (round 26: the next record was a failed payment, which refuses any capture for its state, not its amount)
588
785
  // a capture-kind event, even when the control was another kind (round 27: payment.created took the control); at the
589
786
  // control's record first, then the others, until one takes a capture at all - a refusal for its state says nothing
590
- 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))) : null;
787
+ // A handler that compares no event type acts on every event it is sent (blind round 32: the type defaulted to
788
+ // 'payment.captured', so the check's own neutral event was a capture): the event it took is then the capture.
789
+ const actsOnAny = !types.length && !(signing.types || []).length;
790
+ 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;
591
791
  const payControl = !!captureType;
792
+ // a record a capture can still land on first, so what changed is the capture and not a record already settled
793
+ const captureOrder = [...capturable, controlRec].concat(records).filter((r, i, all) => r && r.id !== null && all.indexOf(r) === i).slice(0, 3);
592
794
  if (captureType) {
593
- for (const rec of [controlRec].concat(records.filter((r) => r !== controlRec)).slice(0, 3)) {
795
+ for (const rec of captureOrder) {
594
796
  const t = await attempt(S, captureType, rec, (Number(rec[amountKey]) || 0) + 100, 'signed, wrong amount');
595
797
  if (t.took) break;
596
798
  }
597
799
  }
800
+ // the same capture in another currency than the record's (blind round 32: EUR was taken for a USD payment)
801
+ const currencyKey = records[0] && Object.keys(records[0]).find((k) => /^currency(_code)?$/i.test(k));
802
+ if (captureType && shape.currency && currencyKey) {
803
+ for (const rec of captureOrder) {
804
+ const own = String(rec[currencyKey] || '').toUpperCase();
805
+ const other = own === 'EUR' ? 'USD' : 'EUR';
806
+ const body = Object.assign(bodyFor(captureType, rec, amountKey ? Number(rec[amountKey]) || 1 : undefined), { [shape.currency]: /^[a-z]+$/.test(String(rec[currencyKey] || '')) ? other.toLowerCase() : other });
807
+ const t = await attempt(S, captureType, rec, undefined, 'signed, wrong currency', body);
808
+ if (t.took) break;
809
+ }
810
+ }
598
811
  // a refund on a record that was paid: sent twice as the same event, then for more than was paid
599
812
  const refundType = types.find((t) => REFUNDED.test(t)) || signing.types.find((t) => REFUNDED.test(t));
600
813
  const paidRec = refundType && statusKey && records.find((r) => PAID.test(String(r[statusKey])) && !REFUNDED.test(String(r[statusKey])));
@@ -651,6 +864,10 @@ async function run(root, options) {
651
864
  finding('webhook-forged', t.changed ? 'CRITICAL' : 'HIGH', t.changed ? 'confirmed' : 'verification required',
652
865
  name + ' took ' + t.type + ' with a wrong signature' + (t.changed ? ' and changed ' + resource + ' ' + t.record : '') + '.',
653
866
  ['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.');
867
+ } else if (t.label === 'signed, wrong currency' && t.took && t.changed) {
868
+ finding('webhook-currency', 'HIGH', 'confirmed',
869
+ 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(', ')) + ').',
870
+ ['Correctly signed, with the record\'s amount but another currency: ' + lineOf(t)], 'Compare the currency in the event with the currency the ' + resource + ' was created in, and ignore or flag the event when they differ - never store the event\'s currency over the record\'s.');
654
871
  } else if (t.label === 'signed, wrong amount' && t.took && t.changed) {
655
872
  finding('webhook-amount', 'HIGH', 'confirmed',
656
873
  name + ' applied ' + t.type + ' for an amount that is not ' + resource + ' ' + t.record + '\'s, and it changed all the same (' + (t.from !== t.to ? statusKey + ' ' + t.from + ' -> ' + t.to : t.fields.join(', ')) + ').',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kryptheon",
3
- "version": "0.1.63",
3
+ "version": "0.1.65",
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",