kryptheon 0.1.49 → 0.1.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +435 -333
- package/bin/kryptheon.js +90 -4
- package/kryptheon-code.js +158 -2
- package/kryptheon-dashboard-page.js +78 -6
- package/kryptheon-dashboard.html +9 -0
- package/kryptheon-dashboard.js +240 -12
- package/kryptheon-edge.js +83 -14
- package/kryptheon-heal.js +57 -0
- package/kryptheon-payments-run.js +501 -0
- package/kryptheon-payments.js +626 -0
- package/kryptheon-probe-fixture.js +175 -8
- package/kryptheon-probe.js +368 -317
- package/kryptheon-reliability.js +430 -40
- package/kryptheon-replay.js +0 -0
- package/kryptheon-secrets.js +14 -3
- package/package.json +12 -5
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
// `kryptheon payments`: the payment check as a person runs it.
|
|
2
|
+
//
|
|
3
|
+
// kryptheon-payments.js does the work; this file is what is said around it:
|
|
4
|
+
// the question before anything starts, how the provider's webhook reaches
|
|
5
|
+
// this computer, the refusal of live mode, and the report with a prompt to
|
|
6
|
+
// paste into an AI tool. Nothing here sends anything until the person has
|
|
7
|
+
// said yes and a test-mode payment has arrived by itself.
|
|
8
|
+
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const payments = require('./kryptheon-payments.js');
|
|
12
|
+
const store = require('./kryptheon-store.js');
|
|
13
|
+
|
|
14
|
+
const DEFAULT_PORT = 4790;
|
|
15
|
+
const REPORT_FILE = 'payments-last.json';
|
|
16
|
+
// Every run's own trace, in the store, and how many are kept.
|
|
17
|
+
const TRACE_DIR = 'payments';
|
|
18
|
+
const TRACES_KEPT = 50;
|
|
19
|
+
// How long the proxy waits for the first payment webhook.
|
|
20
|
+
const WAIT_MS = 20 * 60 * 1000;
|
|
21
|
+
// After the first webhook, how long the others from the same payment are
|
|
22
|
+
// collected (payment.authorized, payment.captured, order.paid ...).
|
|
23
|
+
const GATHER_MS = 8000;
|
|
24
|
+
|
|
25
|
+
const ENV_FILES = ['.env', '.env.local', '.env.development', '.env.development.local'];
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* KEY=VALUE pairs from the app's .env files, read only to tell Razorpay's live
|
|
29
|
+
* mode from its test mode. Nothing read here is printed or kept.
|
|
30
|
+
*/
|
|
31
|
+
function appEnv(root) {
|
|
32
|
+
const out = {};
|
|
33
|
+
for (const name of ENV_FILES) {
|
|
34
|
+
let text = '';
|
|
35
|
+
try {
|
|
36
|
+
text = fs.readFileSync(path.join(root, name), 'utf8');
|
|
37
|
+
} catch (err) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
for (const line of text.split(/\r?\n/)) {
|
|
41
|
+
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
|
|
42
|
+
if (m) out[name + ':' + m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* What is said before anything starts. Every line fits in 74 characters: the
|
|
50
|
+
* dashboard shows these in a box about that wide, and a line that wraps there
|
|
51
|
+
* breaks mid-sentence.
|
|
52
|
+
*/
|
|
53
|
+
function consentLines(app, schema, port) {
|
|
54
|
+
return [
|
|
55
|
+
'Does the same payment webhook, sent again, give it again?',
|
|
56
|
+
'',
|
|
57
|
+
'Razorpay and Stripe send a webhook again whenever your server is slow',
|
|
58
|
+
'or answers with an error. If your app gives the plan, the credits or',
|
|
59
|
+
'the order each time, a real customer can get it twice. This finds out',
|
|
60
|
+
'on your own app, with one real test payment.',
|
|
61
|
+
'',
|
|
62
|
+
'What happens:',
|
|
63
|
+
' 1. A small proxy starts on this computer (port ' + port + ') and passes',
|
|
64
|
+
' everything on to your app at ' + app + ', unchanged.',
|
|
65
|
+
' 2. You make test payments in your app in the provider\'s TEST mode,',
|
|
66
|
+
' one at a time. Each one is checked as it comes, until you stop it.',
|
|
67
|
+
' 3. Its webhook reaches your app through the proxy. Kryptheon keeps',
|
|
68
|
+
' a copy, sends that same webhook again, then once more with a',
|
|
69
|
+
' wrong signature.',
|
|
70
|
+
' 4. Kryptheon reads your "' + schema + '" tables before and after each',
|
|
71
|
+
' copy, on this computer, and shows what changed. It never writes',
|
|
72
|
+
' to your database itself.',
|
|
73
|
+
'',
|
|
74
|
+
'Your app WILL process those copies. If it has this bug, your test',
|
|
75
|
+
'account gets the plan or credits again - in this database. Use your',
|
|
76
|
+
'development database, not your live one. A live-mode webhook is',
|
|
77
|
+
'refused: nothing is sent again for a real payment.',
|
|
78
|
+
];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* How the provider's webhook gets to the proxy, which is on this computer.
|
|
83
|
+
* `stopWith` is how this run is ended: Ctrl-C in a terminal, Stop on the page.
|
|
84
|
+
*/
|
|
85
|
+
function tunnelLines(port, stopWith) {
|
|
86
|
+
return [
|
|
87
|
+
'Now point your provider\'s TEST-mode webhook at the proxy:',
|
|
88
|
+
'',
|
|
89
|
+
' Stripe: stripe listen --forward-to localhost:' + port + '/<webhook path>',
|
|
90
|
+
' Razorpay: Razorpay cannot reach this computer by itself. Run',
|
|
91
|
+
' ngrok http ' + port,
|
|
92
|
+
' and in Razorpay Dashboard (Test Mode) > Webhooks, set',
|
|
93
|
+
' the URL to https://<the ngrok address>/<webhook path>',
|
|
94
|
+
'',
|
|
95
|
+
'Then make a test payment in your app, and do not use the app for a',
|
|
96
|
+
'minute after it while the check runs. Kryptheon is waiting for it',
|
|
97
|
+
'(' + (stopWith || 'Ctrl-C') + ' ends the wait).',
|
|
98
|
+
];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const PROVIDER = { razorpay: 'Razorpay', stripe: 'Stripe' };
|
|
102
|
+
|
|
103
|
+
/** The prompt pasted into an AI tool for one finding. */
|
|
104
|
+
function fixPrompt(result, f) {
|
|
105
|
+
const who = PROVIDER[result.provider];
|
|
106
|
+
const where = 'the webhook handler for ' + result.path;
|
|
107
|
+
if (f.kind === 'repeat-grants') {
|
|
108
|
+
return [
|
|
109
|
+
'My app gives a payment twice when ' + who + ' sends the same webhook again.',
|
|
110
|
+
'',
|
|
111
|
+
'I tested it with a real ' + who + ' test payment: the ' + result.event.type + ' webhook was sent to ' + where +
|
|
112
|
+
' a second time, byte for byte, and my database changed again:',
|
|
113
|
+
].concat(f.changes.map((c) => ' ' + c), [
|
|
114
|
+
'',
|
|
115
|
+
who + ' sends a webhook again whenever my server is slow or answers with an error, so a real customer can get this twice.',
|
|
116
|
+
'',
|
|
117
|
+
'Fix ' + where + ' so a repeat changes nothing:',
|
|
118
|
+
'- Keep the id of every event or payment it has handled, in a table with a UNIQUE rule on it' +
|
|
119
|
+
(result.provider === 'razorpay' ? ' (the x-razorpay-event-id header, or the payment id)' : ' (the event id, evt_...)') + '.',
|
|
120
|
+
'- Save that id first, and give the plan, credits or order only if that save succeeded - in one transaction or one',
|
|
121
|
+
' database function, so two copies arriving together cannot both get past it.',
|
|
122
|
+
'- If the id is already there, change nothing and answer 200. Answering with an error makes ' + who + ' send it again.',
|
|
123
|
+
'- Where you can, set values (the period end ' + who + ' sent) instead of adding to them (credits + 100).',
|
|
124
|
+
'',
|
|
125
|
+
'Keep the signature check first. Do not change anything else. Afterwards I will run: npx kryptheon payments',
|
|
126
|
+
]).join('\n');
|
|
127
|
+
}
|
|
128
|
+
if (f.kind === 'refund-nothing') {
|
|
129
|
+
return [
|
|
130
|
+
'When ' + who + ' tells my app a payment was refunded, my app changes nothing.',
|
|
131
|
+
'',
|
|
132
|
+
'I tested it with a real ' + who + ' test refund: the ' + result.event.type + ' webhook reached ' + where +
|
|
133
|
+
', which answered ' + f.status + (f.said ? ' (' + f.said.slice(0, 120) + ')' : '') + ' and wrote nothing but its log.',
|
|
134
|
+
'So the credits, plan or order that payment gave are still there after the money went back.',
|
|
135
|
+
'',
|
|
136
|
+
'First tell me how refunds are meant to work in this app. If they are meant to be automatic:',
|
|
137
|
+
'- handle the refund events ' + who + ' really sends (' + (result.provider === 'razorpay' ? 'refund.created / refund.processed' : 'charge.refunded') +
|
|
138
|
+
') - check the event names my handler listens for against ' + who + '\'s dashboard;',
|
|
139
|
+
'- find what the refunded payment gave and take it back, or mark it for a manual decision;',
|
|
140
|
+
'- make a repeat of the refund event change nothing the second time.',
|
|
141
|
+
'Do not change anything else. Afterwards I will run: npx kryptheon payments',
|
|
142
|
+
].join('\n');
|
|
143
|
+
}
|
|
144
|
+
if (f.kind === 'repeat-refused') {
|
|
145
|
+
return [
|
|
146
|
+
'My app answers ' + f.status + ' when ' + who + ' sends the same webhook again.',
|
|
147
|
+
'',
|
|
148
|
+
'I tested it with a real ' + who + ' test payment: the second copy of ' + result.event.type + ' to ' + where +
|
|
149
|
+
' changed nothing in my database, but was answered ' + f.status + '.',
|
|
150
|
+
who + ' treats that as a failed delivery and keeps sending it' +
|
|
151
|
+
(result.provider === 'razorpay' ? ', and switches a webhook off after it keeps failing.' : '.'),
|
|
152
|
+
'',
|
|
153
|
+
'Fix ' + where + ': when it sees an event or payment it has already handled (for example a unique-key error,',
|
|
154
|
+
'Postgres 23505), treat it as done and answer 200. Change nothing else. Afterwards I will run: npx kryptheon payments',
|
|
155
|
+
].join('\n');
|
|
156
|
+
}
|
|
157
|
+
return [
|
|
158
|
+
f.refused ? 'My payment webhook answers ' + f.status + ' to a request with a wrong signature, but still changes my database.'
|
|
159
|
+
: 'My payment webhook accepts a request with a wrong signature.',
|
|
160
|
+
'',
|
|
161
|
+
'I tested it: a copy of a real ' + who + ' test webhook, with its signature changed by one character, was sent to ' +
|
|
162
|
+
where + ' and answered ' + f.status + '.' + (f.changes.length ? ' It also changed my database:' : ''),
|
|
163
|
+
].concat(f.changes.map((c) => ' ' + c), [
|
|
164
|
+
'',
|
|
165
|
+
'Anyone who can reach this address could send it a payment that never happened.',
|
|
166
|
+
'',
|
|
167
|
+
'Fix ' + where + ': before anything else, check the ' + (result.provider === 'razorpay' ? 'X-Razorpay-Signature header' : 'Stripe-Signature header') +
|
|
168
|
+
' against the RAW request body with the webhook secret' + (result.provider === 'razorpay'
|
|
169
|
+
? ' (HMAC-SHA256, hex - or Razorpay\'s validateWebhookSignature)'
|
|
170
|
+
: ' (stripe.webhooks.constructEvent)') + ', compare it in constant time,',
|
|
171
|
+
'and answer 400 without changing anything when it does not match. Afterwards I will run: npx kryptheon payments',
|
|
172
|
+
]).join('\n');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** One finding, in the words the report uses. */
|
|
176
|
+
function findingLines(result, f) {
|
|
177
|
+
const who = PROVIDER[result.provider];
|
|
178
|
+
if (f.kind === 'repeat-grants') {
|
|
179
|
+
return [
|
|
180
|
+
'HIGH The same ' + who + ' webhook, sent again, gave it again.',
|
|
181
|
+
'',
|
|
182
|
+
' ' + result.event.type + ' to ' + result.path + ' was sent a second time, byte for byte, as ' + who + ' does on a retry.',
|
|
183
|
+
' Your database changed again:',
|
|
184
|
+
].concat(f.changes.map((c) => ' ' + c), f.noise.length ? [' Also changed, which is normal:'].concat(f.noise.map((c) => ' ' + c)) : []);
|
|
185
|
+
}
|
|
186
|
+
if (f.kind === 'refund-nothing') {
|
|
187
|
+
return [
|
|
188
|
+
'MEDIUM A refund took nothing back - to check.',
|
|
189
|
+
'',
|
|
190
|
+
' ' + result.event.type + ' reached ' + result.path + ', which answered ' + f.status +
|
|
191
|
+
(f.said ? ' (' + f.said.slice(0, 80) + ')' : '') + ' and wrote nothing but its log.',
|
|
192
|
+
' Whatever the refunded payment gave (credits, a plan, an order) is still there. Fine if refunds',
|
|
193
|
+
' are handled by hand; a hole if the app is meant to take them back.',
|
|
194
|
+
];
|
|
195
|
+
}
|
|
196
|
+
if (f.kind === 'repeat-refused') {
|
|
197
|
+
return [
|
|
198
|
+
'MEDIUM Your app answers ' + f.status + ' to a repeat, so ' + who + ' keeps sending it.',
|
|
199
|
+
'',
|
|
200
|
+
' The second copy changed nothing - good - but ' + who + ' counts ' + f.status + ' as a failed delivery' +
|
|
201
|
+
(result.provider === 'razorpay' ? ' and switches a webhook off after repeated failures.' : '.'),
|
|
202
|
+
];
|
|
203
|
+
}
|
|
204
|
+
return [
|
|
205
|
+
(f.severity === 'CRITICAL' ? 'CRITICAL ' : 'MEDIUM ') + (f.refused
|
|
206
|
+
? 'Your webhook refused a copy with a wrong signature (answered ' + f.status + '), but still changed your data.'
|
|
207
|
+
: 'Your webhook accepted a copy with a wrong signature (answered ' + f.status + ').'),
|
|
208
|
+
'',
|
|
209
|
+
].concat(f.changes.length
|
|
210
|
+
? [' And it gave it again:'].concat(f.changes.map((c) => ' ' + c), [' Anyone who can reach it can send it a payment that never happened.'])
|
|
211
|
+
: [' It did not change your database, so it may only have ignored it - but it should refuse it with 400.']);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The whole report for one run, as lines. */
|
|
215
|
+
function reportLines(report) {
|
|
216
|
+
const out = [];
|
|
217
|
+
for (const r of report.results) {
|
|
218
|
+
out.push('--------------------------------------------------------------------');
|
|
219
|
+
out.push(PROVIDER[r.provider] + ' ' + r.event.type + (r.event.about ? ' (' + r.event.about + ')' : '') + ' -> ' + r.path);
|
|
220
|
+
out.push('');
|
|
221
|
+
if (r.notTested.length) {
|
|
222
|
+
for (const n of r.notTested) out.push('NOT TESTED ' + n);
|
|
223
|
+
out.push('');
|
|
224
|
+
} else if (!r.findings.length) {
|
|
225
|
+
out.push('Held. The same webhook sent again changed nothing a customer would notice, and a');
|
|
226
|
+
out.push('copy with a wrong signature was refused (' + (r.steps.find((s) => s.step === 'wrong-signature') || {}).status + ').');
|
|
227
|
+
const noise = (r.steps.find((s) => s.step === 'repeat') || { changes: [] }).changes;
|
|
228
|
+
const normal = noise.filter((c) => c.class !== 'elsewhere');
|
|
229
|
+
if (normal.length) out.push('Also changed, which is normal: ' + normal.map((c) => c.line).join('; '));
|
|
230
|
+
out.push('');
|
|
231
|
+
} else {
|
|
232
|
+
for (const f of r.findings) {
|
|
233
|
+
for (const line of findingLines(r, f)) out.push(line);
|
|
234
|
+
out.push('');
|
|
235
|
+
out.push(' Paste this into Lovable, Claude or Cursor:');
|
|
236
|
+
out.push('');
|
|
237
|
+
for (const line of fixPrompt(r, f).split('\n')) out.push(' ' + line);
|
|
238
|
+
out.push('');
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (r.elsewhere && r.elsewhere.length) {
|
|
242
|
+
out.push('Changed at the same time, but not tied to this webhook (not its rows or ids) - perhaps');
|
|
243
|
+
out.push('someone using the app meanwhile. Not counted:');
|
|
244
|
+
for (const line of r.elsewhere) out.push(' ' + line);
|
|
245
|
+
out.push('');
|
|
246
|
+
}
|
|
247
|
+
const trace = traceLines(r);
|
|
248
|
+
if (trace.length) {
|
|
249
|
+
for (const line of trace) out.push(line);
|
|
250
|
+
out.push('');
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (report.traceFile) {
|
|
254
|
+
out.push('The whole trace (every delivery, its answer, and every row it wrote) is kept in');
|
|
255
|
+
out.push(' ' + report.traceFile);
|
|
256
|
+
out.push('on this computer only. Webhook bodies and signatures are not kept; secrets in rows are hidden.');
|
|
257
|
+
}
|
|
258
|
+
out.push('--------------------------------------------------------------------');
|
|
259
|
+
out.push('What this did not test');
|
|
260
|
+
out.push('');
|
|
261
|
+
out.push(' Two copies arriving at the same moment on the first delivery. A handler that looks before');
|
|
262
|
+
out.push(' it saves can pass this check and still give a payment twice when two copies race.');
|
|
263
|
+
out.push(' Work your app does more than ' + Math.round(payments.MIN_WAIT_MS / 1000) + ' seconds after a webhook would be put down to the next copy.');
|
|
264
|
+
return out;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Runs the check. `options`: app, schema, port, database (connection string),
|
|
269
|
+
* yes, ask(question) -> answer, say(line), testMode (the person says it is
|
|
270
|
+
* Razorpay test mode when no key id could be found).
|
|
271
|
+
*/
|
|
272
|
+
async function run(root, options) {
|
|
273
|
+
const say = options.say || ((line) => console.log(line));
|
|
274
|
+
const app = options.app || 'http://localhost:3000';
|
|
275
|
+
const schema = options.schema || 'public';
|
|
276
|
+
const port = options.port !== undefined ? options.port : DEFAULT_PORT;
|
|
277
|
+
if (!payments.isLocalAddress(app)) {
|
|
278
|
+
say('The payment check only runs against an app on this computer, and ' + app + ' is not.');
|
|
279
|
+
say('Start your app locally (npm run dev) and give its address with --app http://localhost:<port>.');
|
|
280
|
+
return { code: 2 };
|
|
281
|
+
}
|
|
282
|
+
if (!options.database) {
|
|
283
|
+
say('The payment check reads your database before and after each copy. Give it your');
|
|
284
|
+
say('DEVELOPMENT database: set KRYPTHEON_DATABASE_URL to its connection string, and run');
|
|
285
|
+
say('this again. On Supabase: Connect > Session pooler (port 5432).');
|
|
286
|
+
return { code: 2 };
|
|
287
|
+
}
|
|
288
|
+
for (const line of consentLines(app, schema, port)) say(line);
|
|
289
|
+
say('');
|
|
290
|
+
if (!options.yes) {
|
|
291
|
+
const answer = options.ask ? await options.ask('Start it? [y/N] ') : '';
|
|
292
|
+
if (!/^\s*y(es)?\s*$/i.test(answer || '')) {
|
|
293
|
+
say('Nothing was started.');
|
|
294
|
+
return { code: 2 };
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const { Client } = require('pg');
|
|
299
|
+
const client = new Client({ connectionString: options.database });
|
|
300
|
+
try {
|
|
301
|
+
await client.connect();
|
|
302
|
+
} catch (err) {
|
|
303
|
+
say('Could not connect to the database: ' + err.message);
|
|
304
|
+
return { code: 2 };
|
|
305
|
+
}
|
|
306
|
+
// The database as it was before the first payment webhook reached the app,
|
|
307
|
+
// so the trace shows what the first delivery wrote, not only the repeat.
|
|
308
|
+
// Read once; if it took longer than the proxy may hold the webhook back,
|
|
309
|
+
// the app may already have written, so it is not used.
|
|
310
|
+
let tables;
|
|
311
|
+
try {
|
|
312
|
+
tables = await payments.tablesOf(client, schema);
|
|
313
|
+
} catch (err) {
|
|
314
|
+
await client.end().catch(() => {});
|
|
315
|
+
say('Could not read the tables of "' + schema + '": ' + err.message);
|
|
316
|
+
return { code: 2 };
|
|
317
|
+
}
|
|
318
|
+
// Read again for every payment: taken when its first webhook arrives, and
|
|
319
|
+
// let go once that payment has been checked. Not while another payment is
|
|
320
|
+
// being checked - what that check sends would be in it.
|
|
321
|
+
let beforeRead = null;
|
|
322
|
+
let checking = false;
|
|
323
|
+
const readBefore = () => {
|
|
324
|
+
if (checking) return Promise.resolve(null);
|
|
325
|
+
return (beforeRead = beforeRead || (async () => {
|
|
326
|
+
const began = Date.now();
|
|
327
|
+
const snap = await payments.snapshot(client, schema, tables);
|
|
328
|
+
return { snap: snap, at: new Date(began).toISOString(), late: Date.now() - began >= payments.BEFORE_FORWARD_MS };
|
|
329
|
+
})());
|
|
330
|
+
};
|
|
331
|
+
let capture;
|
|
332
|
+
try {
|
|
333
|
+
capture = await payments.startCapture({ target: app, port: port, beforeForward: readBefore });
|
|
334
|
+
} catch (err) {
|
|
335
|
+
await client.end().catch(() => {});
|
|
336
|
+
say('Could not start the proxy on port ' + port + ': ' + err.message + '. Try --port <another number>.');
|
|
337
|
+
return { code: 2 };
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
say('');
|
|
341
|
+
say('Proxy running: http://localhost:' + capture.port + ' -> ' + app);
|
|
342
|
+
say('');
|
|
343
|
+
for (const line of tunnelLines(capture.port, options.stopWith)) say(line);
|
|
344
|
+
|
|
345
|
+
const report = { at: new Date().toISOString(), app: app, schema: schema, results: [] };
|
|
346
|
+
// It keeps listening: every payment made while it runs is checked as it
|
|
347
|
+
// comes, until Stop (or Ctrl-C), or until no payment has come for a while.
|
|
348
|
+
// Round 18: it checked one payment and closed, so the next payment's
|
|
349
|
+
// webhook met a closed proxy and every payment needed its own run.
|
|
350
|
+
const idleMs = options.idleMs !== undefined ? options.idleMs : WAIT_MS;
|
|
351
|
+
const stopped = () => Boolean(options.stopped && options.stopped());
|
|
352
|
+
const env = appEnv(root);
|
|
353
|
+
let next = 0;
|
|
354
|
+
try {
|
|
355
|
+
for (;;) {
|
|
356
|
+
const waitFrom = Date.now();
|
|
357
|
+
const arrived = await new Promise((resolve) => {
|
|
358
|
+
const tick = setInterval(() => {
|
|
359
|
+
if (capture.captured.length > next || Date.now() - waitFrom > idleMs || stopped()) {
|
|
360
|
+
clearInterval(tick);
|
|
361
|
+
resolve(capture.captured.length > next);
|
|
362
|
+
}
|
|
363
|
+
}, 200);
|
|
364
|
+
});
|
|
365
|
+
if (!arrived) break;
|
|
366
|
+
const lead = capture.captured[next];
|
|
367
|
+
say('');
|
|
368
|
+
say('A ' + PROVIDER[lead.provider] + ' webhook arrived (' + payments.eventOf(lead).type + '). Waiting a few seconds for the rest of this payment ...');
|
|
369
|
+
await new Promise((r) => setTimeout(r, options.gatherMs !== undefined ? options.gatherMs : GATHER_MS));
|
|
370
|
+
|
|
371
|
+
const hooks = capture.captured.slice(next);
|
|
372
|
+
next = capture.captured.length;
|
|
373
|
+
const before = beforeRead ? await beforeRead.catch(() => null) : null;
|
|
374
|
+
checking = true;
|
|
375
|
+
for (const [i, hook] of hooks.entries()) {
|
|
376
|
+
const mode = payments.modeOf(hook.provider, hook.body, env);
|
|
377
|
+
const event = payments.eventOf(hook);
|
|
378
|
+
if (mode.mode === 'live') {
|
|
379
|
+
report.results.push({ provider: hook.provider, event: event, path: hook.path, steps: [], findings: [],
|
|
380
|
+
notTested: ['this is a LIVE-mode webhook (' + mode.why + '). A real payment is never sent again. Use test mode.'] });
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
if (mode.mode === null && !options.testMode) {
|
|
384
|
+
report.results.push({ provider: hook.provider, event: event, path: hook.path, steps: [], findings: [],
|
|
385
|
+
notTested: ['Kryptheon could not tell whether this is test mode: ' + mode.why + '. If it is, run again with --test-mode.'] });
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
const options_ = { client: client, schema: schema, target: app, hook: hook, say: (l) => say(' ' + l),
|
|
389
|
+
quietMs: options.quietMs, minMs: options.minMs, maxMs: options.maxMs,
|
|
390
|
+
before: i === 0 && before && !before.late ? { snap: before.snap, shared: hooks.length > 1 } : null,
|
|
391
|
+
beforeWhy: i > 0 ? 'what it wrote is counted with the first webhook of this payment, which arrived with it'
|
|
392
|
+
: before && before.late ? 'reading the database first took too long, so the webhook went on before it finished' : '' };
|
|
393
|
+
say('');
|
|
394
|
+
say('Checking ' + event.type + ' ...');
|
|
395
|
+
const seen = capture.captured.length;
|
|
396
|
+
let result = await payments.check(options_);
|
|
397
|
+
// Another payment's webhook came in while this one was being judged:
|
|
398
|
+
// its writes could be read as this one's. Judged once more, now
|
|
399
|
+
// that it is quiet, keeping what the first delivery was seen to write.
|
|
400
|
+
if (capture.captured.length > seen && !result.notTested.length) {
|
|
401
|
+
say(' Another payment arrived during this check - checking this one again once it is quiet ...');
|
|
402
|
+
await new Promise((r) => setTimeout(r, options.gatherMs !== undefined ? options.gatherMs : GATHER_MS));
|
|
403
|
+
const firstDelivery = result.trace && result.trace.deliveries[0];
|
|
404
|
+
const again = await payments.check(Object.assign({}, options_, { before: null, knownFirstWrites: firstDelivery ? firstDelivery.writes : null }));
|
|
405
|
+
again.checkedAgain = 'another payment arrived during the first try';
|
|
406
|
+
if (again.trace && firstDelivery) again.trace.deliveries[0] = firstDelivery;
|
|
407
|
+
result = again;
|
|
408
|
+
}
|
|
409
|
+
report.results.push(result);
|
|
410
|
+
}
|
|
411
|
+
checking = false;
|
|
412
|
+
beforeRead = null;
|
|
413
|
+
save(root, report);
|
|
414
|
+
say('');
|
|
415
|
+
say('Ready for the next payment - make it now, or press ' + (options.stopWith ? 'Stop' : 'Ctrl-C') + ' when you are done.');
|
|
416
|
+
if (stopped()) break;
|
|
417
|
+
}
|
|
418
|
+
if (!report.results.length) {
|
|
419
|
+
say('');
|
|
420
|
+
say('No payment webhook arrived, so nothing was tested.');
|
|
421
|
+
return { code: 2, report: report };
|
|
422
|
+
}
|
|
423
|
+
} finally {
|
|
424
|
+
if (capture) await capture.close().catch(() => {});
|
|
425
|
+
await client.end().catch(() => {});
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
save(root, report);
|
|
429
|
+
say('');
|
|
430
|
+
for (const line of reportLines(report)) say(line);
|
|
431
|
+
const found = report.results.some((r) => r.findings.length);
|
|
432
|
+
const tested = report.results.some((r) => !r.notTested.length);
|
|
433
|
+
return { code: found ? 1 : tested ? 0 : 2, report: report };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Every run is kept as its own trace in the store's payments folder - never
|
|
438
|
+
* overwritten, so the run that found a problem is still there after the
|
|
439
|
+
* re-check that proved it fixed - and the newest is also the last report the
|
|
440
|
+
* dashboard reads. The newest TRACES_KEPT are kept. Webhook bodies, headers
|
|
441
|
+
* and signatures are not kept; secrets in rows are hidden.
|
|
442
|
+
*/
|
|
443
|
+
function save(root, report) {
|
|
444
|
+
const dir = store.pathsFor(root).dir;
|
|
445
|
+
try {
|
|
446
|
+
const traces = path.join(dir, TRACE_DIR);
|
|
447
|
+
fs.mkdirSync(traces, { recursive: true });
|
|
448
|
+
const name = report.at.replace(/[:.]/g, '-') + '.json';
|
|
449
|
+
report.traceFile = path.join(traces, name);
|
|
450
|
+
fs.writeFileSync(report.traceFile, JSON.stringify(report, null, 2));
|
|
451
|
+
const all = fs.readdirSync(traces).filter((f) => /\.json$/.test(f)).sort();
|
|
452
|
+
for (const old of all.slice(0, Math.max(0, all.length - TRACES_KEPT))) fs.rmSync(path.join(traces, old), { force: true });
|
|
453
|
+
} catch (err) {
|
|
454
|
+
report.traceFile = null;
|
|
455
|
+
}
|
|
456
|
+
try {
|
|
457
|
+
fs.writeFileSync(path.join(dir, REPORT_FILE), JSON.stringify(report, null, 2));
|
|
458
|
+
} catch (err) {
|
|
459
|
+
/* the report was printed; a store that cannot be written loses only the copy */
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const STEP_NAME = { first: 'the payment\'s own webhook', repeat: 'the same webhook again', 'wrong-signature': 'a copy with a wrong signature' };
|
|
464
|
+
|
|
465
|
+
/** One result's trace, as lines: each delivery, when, its answer, and what it wrote. */
|
|
466
|
+
function traceLines(r) {
|
|
467
|
+
const t = r.trace;
|
|
468
|
+
if (!t) return [];
|
|
469
|
+
const out = ['Trace - event ' + (t.eventId || '(no event id)') + (t.about ? ', ' + t.about : '') + ', body sha256 ' + t.bodySha256.slice(0, 16) + '...'];
|
|
470
|
+
t.deliveries.forEach((d, i) => {
|
|
471
|
+
const when = d.at ? String(d.at).slice(11, 23) + ' UTC' : '';
|
|
472
|
+
out.push(' ' + (i + 1) + '. ' + STEP_NAME[d.step] + ' (' + (d.from === 'Kryptheon' ? 'sent by Kryptheon' : 'from ' + (PROVIDER[d.from] || d.from)) + ') ' + when);
|
|
473
|
+
out.push(' answered ' + (d.status === null ? 'nothing' : d.status) + (d.ms !== null && d.ms !== undefined ? ' in ' + d.ms + ' ms' : '') +
|
|
474
|
+
'; signature ' + d.signature + '; body ' + (d.bodySha256 === t.bodySha256 ? 'the same bytes' : 'different'));
|
|
475
|
+
if (d.writes === null) {
|
|
476
|
+
out.push(' wrote: not recorded - ' + d.writesWhy);
|
|
477
|
+
} else if (!d.writes.length) {
|
|
478
|
+
out.push(' wrote: nothing');
|
|
479
|
+
} else {
|
|
480
|
+
out.push(' wrote' + (d.writesWhy ? ' (' + d.writesWhy + ')' : '') + ':');
|
|
481
|
+
for (const w of d.writes) out.push(' ' + (w.class === 'business' ? '* ' : ' ') + w.line + (w.key ? ' [row ' + w.key.join(', ') + ']' : ''));
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
return out;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
module.exports = {
|
|
488
|
+
run: run,
|
|
489
|
+
appEnv: appEnv,
|
|
490
|
+
consentLines: consentLines,
|
|
491
|
+
tunnelLines: tunnelLines,
|
|
492
|
+
fixPrompt: fixPrompt,
|
|
493
|
+
findingLines: findingLines,
|
|
494
|
+
reportLines: reportLines,
|
|
495
|
+
traceLines: traceLines,
|
|
496
|
+
save: save,
|
|
497
|
+
DEFAULT_PORT: DEFAULT_PORT,
|
|
498
|
+
REPORT_FILE: REPORT_FILE,
|
|
499
|
+
TRACE_DIR: TRACE_DIR,
|
|
500
|
+
TRACES_KEPT: TRACES_KEPT,
|
|
501
|
+
};
|