kryptheon 0.1.53 → 0.1.55

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.
@@ -62,14 +62,25 @@ function isLocalAddress(url) {
62
62
  host.endsWith('.local') || host.endsWith('.localhost') || host.endsWith('.test');
63
63
  }
64
64
 
65
- /** Which provider signed this request, from its headers, or null. */
66
- function providerOf(headers) {
65
+ /**
66
+ * Which provider signed this request, from its headers, or null. An app's
67
+ * own signed webhook - its own header, named by the person with
68
+ * --signature-header - is 'signed'. Found on blind round 23: the app signed
69
+ * its payment webhooks in x-test-signature, and nothing was tested.
70
+ */
71
+ function providerOf(headers, signatureHeader) {
67
72
  const h = headers || {};
68
73
  if (h['x-razorpay-signature']) return 'razorpay';
69
74
  if (h['stripe-signature']) return 'stripe';
75
+ if (signatureHeader && h[String(signatureHeader).toLowerCase()]) return 'signed';
70
76
  return null;
71
77
  }
72
78
 
79
+ /** The header a hook's signature is in. */
80
+ function signatureHeaderOf(hook) {
81
+ return hook.signatureHeader || SIGNATURE_HEADER[hook.provider];
82
+ }
83
+
73
84
  function parsed(body) {
74
85
  try {
75
86
  return JSON.parse(Buffer.isBuffer(body) ? body.toString('utf8') : String(body));
@@ -96,6 +107,7 @@ function modeOf(provider, body, env) {
96
107
  if (keys.some((v) => /^rzp_test_/.test(v))) return { mode: 'test', why: 'your app has a test Razorpay key (rzp_test_)' };
97
108
  return { mode: null, why: 'no Razorpay key id (rzp_test_ or rzp_live_) was found in your app\'s .env files' };
98
109
  }
110
+ if (provider === 'signed') return { mode: null, why: 'an app\'s own signed webhook does not say whether it is live' };
99
111
  return { mode: null, why: 'not a payment webhook' };
100
112
  }
101
113
 
@@ -114,13 +126,18 @@ function eventOf(hook) {
114
126
  const object = json.data && json.data.object;
115
127
  return { type: json.type || 'a Stripe event', id: json.id || null, about: object && object.id ? object.id : null };
116
128
  }
129
+ if (hook.provider === 'signed') {
130
+ const pick = (...keys) => { for (const k of keys) if (json[k] !== undefined && json[k] !== null && typeof json[k] !== 'object') return String(json[k]); return null; };
131
+ return { type: pick('event', 'type', 'eventType', 'event_type') || 'a signed event', id: pick('eventId', 'event_id', 'id'), about: pick('paymentId', 'payment_id', 'refundId', 'refund_id') };
132
+ }
117
133
  return { type: 'a request', id: null, about: null };
118
134
  }
119
135
 
120
136
  /** The headers a copy is sent with, taken from what arrived. */
121
- function keptHeaders(headers) {
137
+ function keptHeaders(headers, signatureHeader) {
122
138
  const out = {};
123
- for (const name of KEPT_HEADERS) if (headers[name] !== undefined) out[name] = headers[name];
139
+ const names = signatureHeader ? KEPT_HEADERS.concat([String(signatureHeader).toLowerCase()]) : KEPT_HEADERS;
140
+ for (const name of names) if (headers[name] !== undefined) out[name] = headers[name];
124
141
  return out;
125
142
  }
126
143
 
@@ -142,7 +159,7 @@ function startCapture(options) {
142
159
  req.on('end', async () => {
143
160
  const body = Buffer.concat(chunks);
144
161
  const receivedAt = new Date().toISOString();
145
- const signed = providerOf(req.headers) && req.method === 'POST';
162
+ const signed = providerOf(req.headers, options.signatureHeader) && req.method === 'POST';
146
163
  // The caller may read the database once before the first payment
147
164
  // webhook reaches the app, so that delivery's own writes can be shown.
148
165
  // Capped: the provider is waiting, and Razorpay gives up after 5 s.
@@ -172,10 +189,11 @@ function startCapture(options) {
172
189
  res.end(said);
173
190
  if (signed) {
174
191
  const hook = {
175
- provider: providerOf(req.headers),
192
+ provider: providerOf(req.headers, options.signatureHeader),
193
+ signatureHeader: providerOf(req.headers, options.signatureHeader) === 'signed' ? String(options.signatureHeader).toLowerCase() : undefined,
176
194
  method: req.method,
177
195
  path: req.url,
178
- headers: keptHeaders(req.headers),
196
+ headers: keptHeaders(req.headers, options.signatureHeader),
179
197
  body: body,
180
198
  status: answer.statusCode,
181
199
  at: Date.now(),
@@ -220,16 +238,18 @@ function spoiled(provider, value) {
220
238
 
221
239
  /**
222
240
  * Sends a kept webhook to the app again, byte for byte. With `badSignature`,
223
- * the same bytes under a signature that does not match them.
241
+ * the same bytes under a signature that does not match them; with
242
+ * `noSignature`, the same bytes with no signature header at all.
224
243
  */
225
244
  function send(target, hook, options) {
226
245
  const url = new URL(target);
227
246
  if (!isLocalAddress(url.href)) return Promise.reject(new Error(url.origin + ' is not this computer'));
228
247
  const headers = Object.assign({}, hook.headers, { 'content-length': Buffer.byteLength(hook.body), host: url.host });
229
248
  if (options && options.badSignature) {
230
- const name = SIGNATURE_HEADER[hook.provider];
249
+ const name = signatureHeaderOf(hook);
231
250
  headers[name] = spoiled(hook.provider, headers[name]);
232
251
  }
252
+ if (options && options.noSignature) delete headers[signatureHeaderOf(hook)];
233
253
  const sentAt = new Date().toISOString();
234
254
  const began = Date.now();
235
255
  const timed = (status, said) => ({ status: status, said: said, sentAt: sentAt, answeredAt: new Date().toISOString(), ms: Date.now() - began });
@@ -402,6 +422,32 @@ const ok = (status) => status !== null && status >= 200 && status < 300;
402
422
  // Events that say a payment was refunded, on either provider.
403
423
  const REFUND_EVENT = /^(refund\.(created|processed)|payment\.refunded|charge\.refunded)$/;
404
424
 
425
+ // Events that say a payment went through: payment.captured, order.paid,
426
+ // subscription.charged, checkout.session.completed, invoice.paid,
427
+ // payment_intent.succeeded - and an app's own "payment.succeeded". Not
428
+ // payment.authorized (not taken yet) or Razorpay's subscription.completed
429
+ // (its last cycle ended).
430
+ const PAID_EVENT = /(^|[._])(paid|captured|succeeded|completed|charged|activated)$/i;
431
+ const NOT_PAID_EVENT = /^subscription\.completed$/;
432
+ const isPaidEvent = (type) => PAID_EVENT.test(String(type || '')) && !NOT_PAID_EVENT.test(String(type || ''));
433
+
434
+ // What a payment gives, by column or by table: written before its webhook
435
+ // (at checkout, from the page), it was given there.
436
+ const GRANT_COLUMN = /plan|tier|premium|(^|_)pro($|_)|credit|balance|quota|access|role|status|paid|active|subscri|expir|period|valid_until|wallet|seats/i;
437
+ const GRANT_TABLE = /subscri|entitle|purchase|payment|credit|licen|wallet|transaction/i;
438
+
439
+ /**
440
+ * Whether what changed between the start of the check and a payment's first
441
+ * webhook gave the customer something: the app may grant at checkout, from
442
+ * the page, and use the webhook only as a back-up. An order row made when
443
+ * checkout began is not that.
444
+ */
445
+ function givenElsewhere(writes) {
446
+ return (writes || []).some((w) => (w.class || 'business') === 'business' && (
447
+ (w.kind === 'changed' && (w.columns || []).some((c) => GRANT_COLUMN.test(c.name))) ||
448
+ ((w.kind === 'added' || w.kind === 'count') && GRANT_TABLE.test(w.table))));
449
+ }
450
+
405
451
  // Columns whose values are never written into a trace, whatever the table.
406
452
  const SECRET_COLUMN = /pass(word|wd)?|secret|token|api_?key|access_?key|private|signature|card|cvv|otp|(^|_)(pan|pin|ssn|aadhaar)(_|$)|(^|_)keys?$/i;
407
453
  const SHORT = 200;
@@ -493,6 +539,7 @@ async function check(options) {
493
539
  const say = options.say || (() => {});
494
540
  const event = eventOf(hook);
495
541
  const result = { provider: hook.provider, event: event, path: hook.path, firstStatus: hook.status, steps: [], findings: [], notTested: [] };
542
+ if (hook.signatureHeader) result.signatureHeader = hook.signatureHeader;
496
543
 
497
544
  // The trace: every delivery of this webhook, when it went, what came back,
498
545
  // and what it wrote. The body is never kept - its SHA-256 shows the repeat
@@ -547,9 +594,19 @@ async function check(options) {
547
594
  !firstDelivery.writes.some((w) => w.class === 'business')) {
548
595
  result.findings.push({ kind: 'refund-nothing', severity: 'MEDIUM', toCheck: true, status: hook.status, said: hook.said || '' });
549
596
  }
597
+ // A payment that gave nothing: the customer paid, and neither its webhooks
598
+ // nor anything before them (checkout, the page) gave a plan, credits or an
599
+ // order. Seen, not proven wrong: an app may give it by hand or elsewhere.
600
+ const types = options.groupTypes && options.groupTypes.length ? options.groupTypes : [event.type];
601
+ const paid = types.filter(isPaidEvent);
602
+ if (paid.length && firstDelivery.writes && !firstDelivery.writes.some((w) => w.class === 'business') &&
603
+ !givenElsewhere(options.sinceWrites)) {
604
+ result.findings.push({ kind: 'paid-nothing', severity: 'HIGH', toCheck: true, status: hook.status, said: hook.said || '',
605
+ events: paid, logged: firstDelivery.writes.length > 0, before: Array.isArray(options.sinceWrites) });
606
+ }
550
607
 
551
608
  // 1. The same webhook again.
552
- say('Sending the same webhook again, exactly as ' + (hook.provider === 'razorpay' ? 'Razorpay' : 'Stripe') + ' would on a retry ...');
609
+ say('Sending the same webhook again, exactly as ' + (hook.provider === 'razorpay' ? 'Razorpay' : hook.provider === 'stripe' ? 'Stripe' : 'your provider') + ' would on a retry ...');
553
610
  const again = await send(target, hook);
554
611
  const second = await settle(client, schema, tables, options);
555
612
  const related = relatedTo(firstDelivery.writes, idsOf(hook));
@@ -592,8 +649,28 @@ async function check(options) {
592
649
  changes: forgedBusiness.map(changeLine),
593
650
  });
594
651
  }
652
+ // 3. The same bytes with no signature at all. Found on blind round 23: a
653
+ // webhook that refused a wrong signature took a request that had none.
654
+ // Said only when the wrong one was refused: otherwise it is the same hole.
655
+ say('Sending a copy with no signature ...');
656
+ const bare = await send(target, hook, { noSignature: true });
657
+ const fourth = await settle(client, schema, tables, options);
658
+ const bareChanges = diff(third.snap, fourth.snap).map(judged);
659
+ const bareBusiness = bareChanges.filter((c) => c.class === 'business');
660
+ result.steps.push({ step: 'no-signature', status: bare.status, changes: bareChanges.map((c) => ({ class: c.class, line: changeLine(c) })) });
661
+ result.trace.deliveries.push(delivered('no-signature', bare, 'none', bareChanges, fourth.settled));
662
+ const forgedRefused = !ok(forged.status) && !forgedBusiness.length;
663
+ if (forgedRefused && (ok(bare.status) || bareBusiness.length)) {
664
+ result.findings.push({
665
+ kind: 'no-signature',
666
+ severity: bareBusiness.length ? 'CRITICAL' : 'MEDIUM',
667
+ status: bare.status,
668
+ refused: !ok(bare.status),
669
+ changes: bareBusiness.map(changeLine),
670
+ });
671
+ }
595
672
  // What changed meanwhile but is not this webhook's, said so it is not lost.
596
- const elsewhere = changes.concat(forgedChanges).filter((c) => c.class === 'elsewhere').map(changeLine);
673
+ const elsewhere = changes.concat(forgedChanges, bareChanges).filter((c) => c.class === 'elsewhere').map(changeLine);
597
674
  if (elsewhere.length) result.elsewhere = elsewhere;
598
675
  return result;
599
676
  }
@@ -635,7 +712,10 @@ function lifecycle(result, earlier) {
635
712
  }
636
713
 
637
714
  module.exports = {
715
+ signatureHeaderOf: signatureHeaderOf,
638
716
  lifecycle: lifecycle,
717
+ isPaidEvent: isPaidEvent,
718
+ givenElsewhere: givenElsewhere,
639
719
  isLocalAddress: isLocalAddress,
640
720
  providerOf: providerOf,
641
721
  modeOf: modeOf,
@@ -17,6 +17,7 @@ const crypto = require('crypto');
17
17
  const base = require('@playwright/test');
18
18
 
19
19
  const OUT = process.env.KRYPTHEON_PROBE_OUT || '';
20
+ const READS = process.env.KRYPTHEON_PROBE_READS === '1';
20
21
  const GAP_MS = Number(process.env.KRYPTHEON_PROBE_GAP_MS || 1000);
21
22
  // After a "too many requests", the app is asked to wait this long before the
22
23
  // next run, so one 429 does not turn every run after it into another.
@@ -512,7 +513,8 @@ const test = base.test.extend({
512
513
  // keeps - it is never listed as test data left behind.
513
514
  const signIn = JSON.stringify(kept).indexOf('[hidden]') !== -1;
514
515
  const event = Object.assign({ kind: 'write', method: method, host: at.host, origin: at.origin, path: at.path, status: status, signIn: signIn },
515
- redirectOf(res.url(), status, req.headers(), res.headers(), secrets), kept);
516
+ redirectOf(res.url(), status, req.headers(), res.headers(), secrets), kept,
517
+ READS ? { encoding: /json/i.test(type) ? 'json' : /x-www-form-urlencoded/i.test(type) ? 'form' : 'other' } : {});
516
518
  const placed = add(event);
517
519
  // What the server answered - often the record it saved, with its id.
518
520
  // That is the proof that two saves made two records, and of what was
@@ -532,6 +534,18 @@ const test = base.test.extend({
532
534
  answers.add(reading);
533
535
  }
534
536
  }
537
+ // What the app was asked to show, for the roles check, which learns the
538
+ // app's own requests from the recordings. Off unless asked for: no other
539
+ // check reads these, and a page makes a great many of them.
540
+ else if (READS && method === 'GET' && /^(fetch|xhr)$/.test(req.resourceType()) && siteOf(res.url()) === siteOf(page.url())) {
541
+ let query = '';
542
+ try {
543
+ query = new URL(res.url()).search;
544
+ } catch (err) {
545
+ query = '';
546
+ }
547
+ add({ kind: 'read', method: 'GET', host: at.host, origin: at.origin, path: at.path, query: hideValues(query, secrets).slice(0, 200), status: status });
548
+ }
535
549
  });
536
550
  // Answers still being read. Counted before a mark and before the end.
537
551
  const answers = new Set();
@@ -89,8 +89,7 @@ function consentLines(what, addresses, options) {
89
89
  what,
90
90
  '',
91
91
  'It runs against: ' + (addresses.length ? addresses.join(', ') : 'the addresses in your recordings'),
92
- 'It ADDS TEST DATA to your app, and that data STAYS there - Kryptheon does not delete it.',
93
- ].concat(marked ? [
92
+ ].concat(options && options.dataLines ? ['It CHANGES DATA in your app.'] : ['It ADDS TEST DATA to your app, and that data STAYS there - Kryptheon does not delete it.']).concat(options && options.dataLines ? options.dataLines : marked ? [
94
93
  'Most of it contains the word "' + TEST_WORD + '", so you can find it. Empty, negative and date values cannot carry it;',
95
94
  'every write that was accepted is listed when it ends.',
96
95
  ] : [
@@ -261,7 +260,7 @@ function runProbes(root, probes, options) {
261
260
  }
262
261
 
263
262
  // Each probe check keeps its last press in the store under this name.
264
- const REPORT_FILES = { edge: 'edge-last.json', reliability: 'reliability-last.json' };
263
+ const REPORT_FILES = { edge: 'edge-last.json', reliability: 'reliability-last.json', roles: 'roles-last.json' };
265
264
 
266
265
  function reportFile(root, check, env) {
267
266
  return path.join(store.pathsFor(root, env).dir, REPORT_FILES[check]);
@@ -238,7 +238,38 @@ function sameValue(a, b) {
238
238
  const x = String(a == null ? '' : a).trim();
239
239
  const y = String(b == null ? '' : b).trim();
240
240
  if (x === y) return true;
241
- return x !== '' && y !== '' && Number.isFinite(Number(x)) && Number.isFinite(Number(y)) && Number(x) === Number(y);
241
+ if (x !== '' && y !== '' && Number.isFinite(Number(x)) && Number.isFinite(Number(y)) && Number(x) === Number(y)) return true;
242
+ // A date field's "2026-10-14" and the server's "2026-10-13T18:30:00.000Z"
243
+ // (the same day, stored at a timezone's midnight) are the same date.
244
+ const day = /^\d{4}-\d{2}-\d{2}(T[\d:.]+(Z|[+-]\d{2}:?\d{2})?)?$/;
245
+ return day.test(x) && day.test(y) && (x.length === 10 || y.length === 10) && Math.abs(Date.parse(x) - Date.parse(y)) < 86400000;
246
+ }
247
+
248
+ /**
249
+ * What the save's own answer says a field now holds, when it names it: the
250
+ * field "Pickup date" as pickup_date, pickupDate or "pickup date", in the
251
+ * answer or one named record inside it ({ shipment: {...} }). The server's
252
+ * word beats the form opened again. Found on blind round 23: the form opened
253
+ * again in a new tab was another form with an empty "Pickup date", and a date
254
+ * the app never cleared was read as cleared. undefined when not named.
255
+ */
256
+ function answeredValue(writes, field) {
257
+ const key = String((field && field.name) || '').toLowerCase().replace(/[^a-z0-9]/g, '');
258
+ if (!key) return undefined;
259
+ for (const w of writes || []) {
260
+ const a = w && w.answer;
261
+ if (!a || typeof a !== 'object' || Array.isArray(a)) continue;
262
+ const rows = [a].concat(Object.values(a).filter((v) => v && typeof v === 'object' && !Array.isArray(v)));
263
+ for (const row of rows) {
264
+ for (const k of Object.keys(row)) {
265
+ if (k.toLowerCase().replace(/[^a-z0-9]/g, '') !== key) continue;
266
+ const v = row[k];
267
+ if (v === null) return '';
268
+ if (typeof v !== 'object') return String(v);
269
+ }
270
+ }
271
+ }
272
+ return undefined;
242
273
  }
243
274
 
244
275
  /**
@@ -286,10 +317,12 @@ function judgeKept(flow, step, runs) {
286
317
  judged += 1;
287
318
  for (const e of back) {
288
319
  const f = fields.find((x) => x.line === e.line);
289
- if (notEdit(f, e) || e.now === null) continue;
290
- const item = { run: counted.indexOf(r) + 1, field: f, was: e.was, now: e.now, write: took[0] };
291
- if (sameValue(e.now, f.value)) kept += 1;
292
- else if (sameValue(e.now, e.was)) lost.push(item);
320
+ const said = f ? answeredValue(took, f) : undefined;
321
+ const now = said !== undefined ? said : e.now;
322
+ if (notEdit(f, e) || now === null) continue;
323
+ const item = { run: counted.indexOf(r) + 1, field: f, was: e.was, now: now, write: took[0], said: said !== undefined };
324
+ if (sameValue(now, f.value)) kept += 1;
325
+ else if (sameValue(now, e.was)) lost.push(item);
293
326
  else changed.push(item);
294
327
  }
295
328
  }
@@ -316,12 +349,14 @@ function judgeKept(flow, step, runs) {
316
349
  findings.push({
317
350
  flow: flow.title, where: flow.file + ':' + step.line, kind: 'kept', type: 'lost', step: step.name, field: first.field.name || 'line ' + first.field.line,
318
351
  severity: sure ? 'MEDIUM' : 'LOW', status: sure ? 'confirmed' : 'verification required',
319
- headline: 'After "' + step.name + '", ' + thing(first) + ' was ' + typedWords(first) + ', but the form opened again still shows ' + JSON.stringify(first.was) + ' - the change was not kept.',
352
+ headline: 'After "' + step.name + '", ' + thing(first) + ' was ' + typedWords(first) + ', but ' + (first.said ? 'the app\'s answer still has ' : 'the form opened again still shows ') +
353
+ JSON.stringify(first.was) + ' - the change was not kept.',
320
354
  proof: [
321
355
  'Flow: ' + flow.title + ' (' + flow.file + ':' + first.field.line + ', saved at line ' + step.line + ')',
322
356
  'Before typing, ' + thing(first) + ' held ' + JSON.stringify(first.was) + '; the recording ' + (String(first.field.value).trim() === '' ? 'cleared it' : 'typed ' + JSON.stringify(first.field.value)) + '.',
323
357
  'The save: ' + words(first.write) + ' - the app took it.',
324
- 'The same form opened again in a new tab: ' + thing(first) + ' shows ' + JSON.stringify(first.now) + ', what it held before.',
358
+ first.said ? 'The server\'s own answer to that save: ' + thing(first) + ' is ' + JSON.stringify(first.now) + ', what it held before.'
359
+ : 'The same form opened again in a new tab: ' + thing(first) + ' shows ' + JSON.stringify(first.now) + ', what it held before.',
325
360
  'Seen in ' + runsLost + ' of ' + judged + (judged === 1 ? ' run' : ' runs') + ' that saved.',
326
361
  ],
327
362
  });
@@ -1383,6 +1418,8 @@ module.exports = {
1383
1418
  judgeDouble: judgeDouble,
1384
1419
  judgeShown: judgeShown,
1385
1420
  judgeKept: judgeKept,
1421
+ sameValue: sameValue,
1422
+ answeredValue: answeredValue,
1386
1423
  keepSteps: keepSteps,
1387
1424
  keptFields: keptFields,
1388
1425
  judgeTwice: judgeTwice,
@@ -447,6 +447,7 @@ module.exports = {
447
447
  scrubSecrets: scrubSecrets,
448
448
  dropTrailingLogout: dropTrailingLogout,
449
449
  isSecretField: isSecretField,
450
+ accountPart: accountPart,
450
451
  nameInLine: nameInLine,
451
452
  CREATES: CREATES,
452
453
  ROW_PICK: ROW_PICK,