@bachsproof/cli 1.1.0 → 2.0.0

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/dist/cli.js CHANGED
@@ -1,179 +1,74 @@
1
1
  #!/usr/bin/env node
2
- import { resolve, join } from 'path';
3
- import { mkdir, writeFile, access } from 'fs/promises';
2
+ import { writeFile, access } from 'fs/promises';
4
3
  import { constants } from 'fs';
4
+ import { join, resolve } from 'path';
5
5
  import { createJiti } from 'jiti';
6
- import { BachsProof } from '@bachsproof/core';
7
- import { signBachsWebhook } from '@bachsproof/bachs';
6
+ import { BachsProof, SUPPORTED_SCENARIOS } from '@bachsproof/core';
7
+ import { bachsAdapter, signBachsWebhook } from '@bachsproof/bachs';
8
8
 
9
9
  var configTemplate = `/**
10
- * BachsProof test configuration.
10
+ * BachsProof v2 configuration.
11
11
  *
12
- * Follow the two application-specific steps:
13
- * 1. createPayment prepares a fresh test payment or order;
14
- * 2. verify reads the committed payment and ledger state.
15
- *
16
- * Both helpers are test-only. BachsProof does not add routes or modify the
17
- * production application.
18
- */
19
- import { bachsAdapter } from "@bachsproof/cli";
20
- import { tests } from "./tests/bachsproof.test.mjs";
21
-
22
- const provider = bachsAdapter({ mode: "mock" });
23
- const target = {
24
- baseUrl: process.env.BACHSPROOF_TARGET_URL ?? "http://127.0.0.1:3000",
25
- webhookPath: process.env.BACHSPROOF_WEBHOOK_PATH ?? "/webhooks/bachs"
26
- };
27
-
28
- const signingSecret = process.env.BACHS_WEBHOOK_SECRET;
29
- const signing = signingSecret ? { type: "bachs", secret: signingSecret } : undefined;
30
-
31
- // Uncomment after implementing tests/bachsproof.setup.mjs.
32
- // import { createPayment } from "./tests/bachsproof.setup.mjs";
33
-
34
- // Uncomment after implementing tests/bachsproof.verify.mjs.
35
- // import { verify } from "./tests/bachsproof.verify.mjs";
36
-
37
- export default {
38
- provider,
39
- target,
40
- ...(signing ? { signing } : {}),
41
- // createPayment,
42
- // verify,
43
- // requireFinancialVerification: true,
44
- // financialVerification: {
45
- // completionDeadlineMs: 10_000,
46
- // pollIntervalMs: 25,
47
- // negativeObservationWindowMs: 250
48
- // },
49
- tests
50
- };
51
- `;
52
- var testTemplate = `/**
53
- * BachsProof scenarios.
54
- *
55
- * Real application references are the default. Implement createPayment in
56
- * bachsproof.setup.mjs to create fresh test records automatically, or put an
57
- * explicit reference on a selected test. Synthetic references are only for
58
- * isolated fixture tests.
59
- *
60
- * Run one: pnpm exec bachsproof test --name "sequential duplicate webhook"
61
- * Run all: pnpm exec bachsproof test
12
+ * Use only an isolated application, test database, queue, and webhook secret.
13
+ * BachsProof creates local simulated events. It never calls Bachs or moves money.
62
14
  */
63
- const amountMinor = Number(process.env.BACHSPROOF_AMOUNT_MINOR ?? 5_000_000);
64
- const currency = process.env.BACHSPROOF_CURRENCY ?? "NGN";
65
- const syntheticReferences = process.env.BACHSPROOF_USE_SYNTHETIC_REFERENCES === "true";
66
-
67
- export const tests = [
68
- // Same successful payment twice in sequence: tests idempotency.
69
- { name: "sequential duplicate webhook", scenario: "sequential-duplicate-webhook", amountMinor, currency, syntheticReferences },
70
-
71
- // Same successful payment concurrently: tests duplicate-credit races.
72
- { name: "concurrent duplicate credit", scenario: "concurrent-duplicate-credit", concurrency: 3, amountMinor, currency, syntheticReferences },
73
-
74
- // Distinct payments concurrently: tests cross-payment interference.
75
- { name: "concurrent unique payments", scenario: "concurrent-unique-payments", amountMinor, currency, syntheticReferences },
76
-
77
- // checkout.completed plus collection.succeeded for one payment.
78
- { name: "cross-event duplicate payment", scenario: "cross-event-duplicate-payment", amountMinor, currency, syntheticReferences },
79
-
80
- // Newer success followed by older expiry: tests state ordering.
81
- { name: "out-of-order events", scenario: "out-of-order-events", amountMinor, currency, syntheticReferences },
82
-
83
- // Expiry followed by delayed success: tests eventual payment confirmation.
84
- { name: "delayed payment confirmation", scenario: "delayed-payment-confirmation", delayMs: 50, amountMinor, currency, syntheticReferences },
85
-
86
- // Completed checkout without a collected payment: must not credit.
87
- { name: "incomplete checkout", scenario: "incomplete-checkout", amountMinor, currency, syntheticReferences },
88
-
89
- // Expired checkout: must not credit.
90
- { name: "expired checkout", scenario: "expired-checkout", amountMinor, currency, syntheticReferences },
91
-
92
- // Changed body after signing: normally expects a 4xx rejection.
93
- { name: "tampered webhook", scenario: "tampered-webhook", expectedStatus: "4xx", amountMinor, currency, syntheticReferences },
94
-
95
- // Invalid signature: normally expects a 4xx rejection.
96
- { name: "invalid webhook signature", scenario: "invalid-webhook-signature", expectedStatus: "4xx", amountMinor, currency, syntheticReferences },
97
-
98
- // Malformed JSON: normally expects a 4xx rejection.
99
- { name: "malformed webhook", scenario: "malformed-webhook", expectedStatus: "4xx", amountMinor, currency, syntheticReferences },
100
-
101
- // Successful-looking event with the wrong amount: must not credit.
102
- { name: "incorrect payment amount", scenario: "incorrect-payment-amount", amountMinor, currency, syntheticReferences },
103
-
104
- // Successful-looking event with the wrong currency: must not credit.
105
- { name: "incorrect payment currency", scenario: "incorrect-payment-currency", amountMinor, currency, syntheticReferences },
106
-
107
- // Underpaid collection: must not credit before the shortfall is paid.
108
- { name: "underpaid payment", scenario: "underpaid-payment", amountMinor, currency, syntheticReferences },
109
-
110
- // Failed collection: must not credit.
111
- { name: "failed payment", scenario: "failed-payment", amountMinor, currency, syntheticReferences }
112
- ];
113
- `;
114
- var setupTemplate = `/**
115
- * Create isolated application payment records for BachsProof.
116
- *
117
- * This callback is optional when tests provide real references directly. It is
118
- * recommended for repeatedly running the complete suite.
119
- *
120
- * BachsProof calls it only for selected scenarios that need a reference. Every
121
- * call must create a fresh test payment or order and return its reference.
122
- * It must not charge a card, call a live provider, or move real money.
123
- *
124
- * Context: scenario, amountMinor, currency, paymentIndex, paymentCount.
125
- *
126
- * Use an existing isolated test API, application service, ORM, or seed helper.
127
- */
128
- export async function createPayment(context) {
129
- throw new Error(
130
- "Implement createPayment in tests/bachsproof.setup.mjs. " +
131
- "Create an isolated test payment and return its fresh reference for " +
132
- context.scenario + " (" + (context.paymentIndex + 1) + " of " +
133
- context.paymentCount + ")."
134
- );
15
+ import { defineConfig } from "@bachsproof/cli";
16
+
17
+ export default defineConfig({
18
+ // The complete URL of your isolated application's Bachs webhook route.
19
+ webhookUrl: process.env.BACHSPROOF_WEBHOOK_URL ?? "http://127.0.0.1:3000/webhooks/bachs",
20
+
21
+ // Use a secret that belongs only to your test application.
22
+ secret: process.env.BACHS_WEBHOOK_SECRET ?? "",
23
+
24
+ // 500,000 NGN minor units means NGN 5,000.00.
25
+ amountMinor: 500_000,
26
+ currency: "NGN",
27
+
28
+ // Before BachsProof sends a webhook, create a fresh payment record and
29
+ // return its reference. Replace the example error with your test helper.
30
+ async createPayment({ scenario, amountMinor, currency, paymentIndex, paymentCount }) {
31
+ throw new Error(
32
+ "Implement createPayment in bachsproof.config.mjs. " +
33
+ "Create an isolated test payment and return its non-empty reference for " +
34
+ scenario + " (" + (paymentIndex + 1) + " of " + paymentCount + ")."
35
+ );
36
+ // Example:
37
+ // const payment = await testApplication.createPayment({ amountMinor, currency });
38
+ // return payment.reference;
39
+ },
40
+
41
+ // Read the application's committed payment and ledger records. Do not return
42
+ // the expected values from this file; return what the database contains.
43
+ async verify(reference) {
44
+ throw new Error(
45
+ "Implement verify in bachsproof.config.mjs by reading committed " +
46
+ "financial records for " + reference + "."
47
+ );
48
+ // Example result:
49
+ // return {
50
+ // reference,
51
+ // creditCount: credits.length,
52
+ // creditedAmountMinor: credits.reduce((sum, credit) => sum + credit.amountMinor, 0),
53
+ // currency: payment.currency,
54
+ // status: payment.status,
55
+ // pending: false,
56
+ // ledgerEntries: credits.map((credit) => ({
57
+ // id: String(credit.id),
58
+ // type: String(credit.type),
59
+ // amountMinor: credit.amountMinor,
60
+ // currency: credit.currency
61
+ // }))
62
+ // };
63
+ }
135
64
 
136
- // Example:
137
- // const payment = await testSupport.createPayment({
138
- // scenario: context.scenario,
139
- // amountMinor: context.amountMinor,
140
- // currency: context.currency,
141
- // paymentIndex: context.paymentIndex
142
- // });
143
- // return payment.reference;
144
- }
145
- `;
146
- var verifierTemplate = `/**
147
- * Read committed financial state for BachsProof.
148
- *
149
- * HTTP 200 only proves that the webhook route acknowledged a request. This
150
- * callback must read the payment and actual credit or ledger records.
151
- * Do not return hardcoded expected values.
152
- *
153
- * Return reference, creditCount, creditedAmountMinor, currency, and optional
154
- * status, pending, and ledgerEntries fields.
155
- */
156
- export async function verify(reference, context) {
157
- throw new Error(
158
- "Implement verify in tests/bachsproof.verify.mjs by reading committed " +
159
- "financial records for " + reference + " before enabling it."
160
- );
65
+ // Optional: run only selected scenario identifiers. Omit to run all eleven.
66
+ // scenarios: ["sequential-duplicate-webhook"],
161
67
 
162
- // Example:
163
- // const state = await testSupport.readCommittedFinancialState(reference);
164
- // return {
165
- // reference,
166
- // creditCount: state.credits.length,
167
- // creditedAmountMinor: state.credits.reduce(
168
- // (total, credit) => total + credit.amountMinor,
169
- // 0
170
- // ),
171
- // currency: state.currency,
172
- // status: state.status,
173
- // pending: state.pending,
174
- // ledgerEntries: state.credits
175
- // };
176
- }
68
+ // Optional: increase this only when your isolated application processes
69
+ // webhooks asynchronously. The default is 10 seconds.
70
+ // verificationTimeoutMs: 10_000
71
+ });
177
72
  `;
178
73
  async function exists(path) {
179
74
  try {
@@ -184,35 +79,63 @@ async function exists(path) {
184
79
  }
185
80
  }
186
81
  async function initProject(directory = process.cwd(), force = false) {
187
- const root = resolve(directory);
188
- const configPath = join(root, "bachsproof.config.mjs");
189
- const testDirectory = join(root, "tests");
190
- const testPath = join(testDirectory, "bachsproof.test.mjs");
191
- const setupPath = join(testDirectory, "bachsproof.setup.mjs");
192
- const verifierPath = join(testDirectory, "bachsproof.verify.mjs");
193
- const paths = [configPath, testPath, setupPath, verifierPath];
194
- if (!force) {
195
- const existing = [];
196
- for (const path of paths) if (await exists(path)) existing.push(path);
197
- if (existing.length > 0) {
198
- throw new Error("Refusing to overwrite existing BachsProof files: " + existing.join(", ") + ". Use --force to replace them.");
199
- }
82
+ const configPath = join(resolve(directory), "bachsproof.config.mjs");
83
+ if (!force && await exists(configPath)) {
84
+ throw new Error(`Refusing to overwrite existing BachsProof file: ${configPath}. Use --force only when replacement is intentional.`);
200
85
  }
201
- await mkdir(testDirectory, { recursive: true });
202
86
  await writeFile(configPath, configTemplate, "utf8");
203
- await writeFile(testPath, testTemplate, "utf8");
204
- await writeFile(setupPath, setupTemplate, "utf8");
205
- await writeFile(verifierPath, verifierTemplate, "utf8");
206
- return paths;
87
+ return [configPath];
88
+ }
89
+ var SCENARIO_LABELS = {
90
+ "sequential-duplicate-webhook": "Sequential duplicate webhook",
91
+ "concurrent-duplicate-credit": "Concurrent duplicate credit",
92
+ "concurrent-unique-payments": "Concurrent unique payments",
93
+ "cross-event-duplicate-payment": "Cross-event duplicate payment",
94
+ "out-of-order-events": "Out-of-order events",
95
+ "incomplete-checkout": "Incomplete checkout",
96
+ "expired-checkout": "Expired checkout",
97
+ "incorrect-payment-amount": "Incorrect payment amount",
98
+ "incorrect-payment-currency": "Incorrect payment currency",
99
+ "underpaid-payment": "Underpaid payment",
100
+ "failed-payment": "Failed payment"
101
+ };
102
+ function scenarioLabel(scenario) {
103
+ return SCENARIO_LABELS[scenario];
207
104
  }
208
105
  function assertConfig(value) {
209
106
  if (!value || typeof value !== "object") throw new Error("BachsProof config must export a default object");
210
107
  const config = value;
211
- if (!config.provider || typeof config.provider !== "object") throw new Error("BachsProof config requires a provider adapter");
212
- if (!config.target || typeof config.target !== "object" || typeof config.target.baseUrl !== "string" || typeof config.target.webhookPath !== "string") {
213
- throw new Error("BachsProof config requires target.baseUrl and target.webhookPath");
108
+ if (typeof config.webhookUrl !== "string" || config.webhookUrl.trim().length === 0) {
109
+ throw new Error("BachsProof config requires a complete webhookUrl");
110
+ }
111
+ try {
112
+ const url = new URL(config.webhookUrl);
113
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("webhookUrl must use http or https");
114
+ } catch (error) {
115
+ throw new Error(`BachsProof config webhookUrl is invalid: ${error instanceof Error ? error.message : String(error)}`);
116
+ }
117
+ if (typeof config.secret !== "string" || config.secret.trim().length === 0) {
118
+ throw new Error("BachsProof config requires a non-empty test webhook secret");
119
+ }
120
+ if (!Number.isSafeInteger(config.amountMinor) || config.amountMinor < 0) {
121
+ throw new Error("BachsProof config amountMinor must be a non-negative safe integer");
122
+ }
123
+ if (typeof config.currency !== "string" || !/^[A-Z]{3}$/.test(config.currency)) {
124
+ throw new Error("BachsProof config currency must be a three-letter ISO currency code");
125
+ }
126
+ if (typeof config.createPayment !== "function") throw new Error("BachsProof config requires a createPayment callback");
127
+ if (typeof config.verify !== "function") throw new Error("BachsProof config requires a verify callback");
128
+ if (config.verificationTimeoutMs !== void 0 && (!Number.isSafeInteger(config.verificationTimeoutMs) || config.verificationTimeoutMs < 1)) {
129
+ throw new Error("BachsProof config verificationTimeoutMs must be a positive safe integer");
130
+ }
131
+ if (config.scenarios !== void 0) {
132
+ if (!Array.isArray(config.scenarios) || config.scenarios.length === 0) throw new Error("BachsProof config scenarios must contain at least one scenario");
133
+ for (const scenario of config.scenarios) {
134
+ if (!SUPPORTED_SCENARIOS.includes(scenario)) {
135
+ throw new Error(`Unknown BachsProof scenario: ${String(scenario)}`);
136
+ }
137
+ }
214
138
  }
215
- if (!Array.isArray(config.tests) || config.tests.length === 0) throw new Error("BachsProof config requires at least one test");
216
139
  }
217
140
  async function loadConfig(configPath = "bachsproof.config.mjs") {
218
141
  const absolutePath = resolve(process.cwd(), configPath);
@@ -221,81 +144,61 @@ async function loadConfig(configPath = "bachsproof.config.mjs") {
221
144
  assertConfig(loaded);
222
145
  return loaded;
223
146
  }
224
- function withBachsSigning(provider, config) {
225
- if (!config.signing) return provider;
226
- if (config.signing.type !== "bachs") throw new Error(`Unsupported signing type ${String(config.signing.type)}`);
227
- if (!config.signing.secret) throw new Error("Bachs signing is configured but its secret is empty");
147
+ function withBachsSigning(provider, secret) {
228
148
  return {
229
149
  ...provider,
230
150
  headers(event) {
231
- const rawBody = provider.serialize(event);
151
+ const body = provider.serialize(event);
232
152
  return {
233
153
  ...provider.headers?.(event) ?? {},
234
- ...signBachsWebhook(rawBody, config.signing?.secret ?? "", config.signing?.timestamp)
154
+ ...signBachsWebhook(body, secret)
235
155
  };
236
156
  },
237
157
  headersForBody(event, body) {
238
158
  return {
239
159
  ...provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {},
240
- ...signBachsWebhook(body, config.signing?.secret ?? "", config.signing?.timestamp)
160
+ ...signBachsWebhook(body, secret)
241
161
  };
242
162
  }
243
163
  };
244
164
  }
165
+ function selectedScenarios(config, testName) {
166
+ const scenarios = config.scenarios ?? [...SUPPORTED_SCENARIOS];
167
+ if (!testName) return scenarios;
168
+ const selected = scenarios.find((scenario) => scenarioLabel(scenario) === testName || scenario === testName);
169
+ if (!selected) throw new Error(`Unknown BachsProof scenario or test name "${testName}". Use one of: ${scenarios.map(scenarioLabel).join(", ")}`);
170
+ return [selected];
171
+ }
245
172
  async function runConfig(config, options = {}) {
246
- const tests = options.testName ? config.tests.filter((test) => test.name === options.testName) : config.tests;
247
- if (tests.length === 0) throw new Error(options.testName ? `No BachsProof test named ${options.testName}` : "BachsProof config contains no tests");
248
- if (config.requireFinancialVerification && !config.verify) {
249
- throw new Error("Financial verification is required, but the config has no verify callback");
250
- }
251
- const provider = withBachsSigning(config.provider, config);
252
- const results = [];
173
+ assertConfig(config);
174
+ const scenarios = selectedScenarios(config, options.testName);
175
+ const provider = withBachsSigning(bachsAdapter({ mode: "mock" }), config.secret);
253
176
  const usedReferences = /* @__PURE__ */ new Set();
254
- for (const test of tests) {
255
- const { name, ...runOptions } = test;
256
- const normalizedRunOptions = {
257
- ...runOptions,
258
- ...runOptions.reference !== void 0 ? { reference: typeof runOptions.reference === "string" ? runOptions.reference.trim() : runOptions.reference } : {},
259
- ...runOptions.references !== void 0 ? { references: runOptions.references.map((reference) => typeof reference === "string" ? reference.trim() : reference) } : {}
260
- };
261
- const explicitReferences = normalizedRunOptions.scenario === "concurrent-unique-payments" ? normalizedRunOptions.references ?? [] : normalizedRunOptions.reference ? [normalizedRunOptions.reference] : [];
262
- const normalizedExplicitReferences = explicitReferences.map((reference) => typeof reference === "string" ? reference.trim() : reference);
263
- const conflictingReference = normalizedExplicitReferences.find((reference) => typeof reference === "string" && usedReferences.has(reference));
264
- let preparationFailure;
265
- if (conflictingReference) {
266
- preparationFailure = `Payment preparation failed for ${runOptions.scenario}: reference ${conflictingReference} is already assigned to another selected scenario`;
267
- } else {
268
- for (const reference of normalizedExplicitReferences) {
269
- if (typeof reference === "string" && reference.trim().length > 0) usedReferences.add(reference.trim());
270
- }
177
+ const createPayment = async (context) => {
178
+ const reference = await config.createPayment(context);
179
+ if (typeof reference !== "string" || reference.trim().length === 0) return reference;
180
+ const normalized = reference.trim();
181
+ if (usedReferences.has(normalized)) {
182
+ throw new Error(`createPayment returned reference ${normalized}, which was already used by another selected scenario`);
271
183
  }
272
- const createPayment = preparationFailure ? async () => {
273
- throw new Error(preparationFailure);
274
- } : config.createPayment ? async (context) => {
275
- const reference = await config.createPayment?.(context);
276
- if (typeof reference !== "string" || reference.trim().length === 0) return reference;
277
- const normalized = reference.trim();
278
- if (usedReferences.has(normalized)) {
279
- throw new Error(`reference ${normalized} is already assigned to another selected scenario`);
280
- }
281
- usedReferences.add(normalized);
282
- return normalized;
283
- } : void 0;
284
- const runner = new BachsProof({
285
- provider,
286
- target: config.target,
287
- createPayment,
288
- verify: config.verify,
289
- financialVerification: config.financialVerification,
290
- checkpoint: config.checkpoint
184
+ usedReferences.add(normalized);
185
+ return normalized;
186
+ };
187
+ const runner = new BachsProof({
188
+ provider,
189
+ webhookUrl: config.webhookUrl,
190
+ createPayment,
191
+ verify: config.verify,
192
+ financialVerification: config.verificationTimeoutMs === void 0 ? void 0 : { completionDeadlineMs: config.verificationTimeoutMs }
193
+ });
194
+ const results = [];
195
+ for (const scenario of scenarios) {
196
+ const result = await runner.run({
197
+ scenario,
198
+ amountMinor: config.amountMinor,
199
+ currency: config.currency
291
200
  });
292
- const input = preparationFailure ? { ...normalizedRunOptions, reference: void 0, references: void 0, syntheticReferences: false } : normalizedRunOptions;
293
- const result = await runner.run(input);
294
- if (config.requireFinancialVerification && !result.report.financiallyVerified) {
295
- result.report.errors.push("Financial verification was required but did not run");
296
- result.passed = false;
297
- }
298
- results.push({ name, result });
201
+ results.push({ name: scenarioLabel(scenario), scenario, result });
299
202
  }
300
203
  return results;
301
204
  }
@@ -317,103 +220,71 @@ function summarizeRuns(results) {
317
220
 
318
221
  // src/cli.ts
319
222
  function usage() {
320
- return `BachsProof payment correctness testing
223
+ return `BachsProof
224
+ Beyond webhook delivery. Verify financial correctness.
321
225
 
322
226
  Usage:
323
227
  bachsproof init [directory] [--force]
324
- bachsproof test [--config <path>] [--name <test-name>] [--json]
228
+ bachsproof test [--config <path>] [--name <scenario-name>] [--json]
325
229
 
326
- init creates bachsproof.config.mjs, tests/bachsproof.test.mjs,
327
- tests/bachsproof.setup.mjs, and a hard-fail tests/bachsproof.verify.mjs template.
328
- test sends configured provider events to the target webhook and reports delivery
329
- and, when configured, committed financial verification results.
230
+ init creates one bachsproof.config.mjs file.
231
+ test runs all eleven financial correctness scenarios unless --name or
232
+ scenarios in the config selects a subset.
330
233
  `;
331
234
  }
332
- function explainOnboardingError(error) {
235
+ function explainError(error) {
333
236
  const message = error instanceof Error ? error.message : String(error);
334
- if (message.includes("Refusing to overwrite existing BachsProof files")) {
335
- return `${message}
336
- Open the listed files if you want to keep them, or run "bachsproof init --force" only when replacing them is intentional.`;
337
- }
338
- if (message.includes("real application reference is required") || message.includes("A real application reference is required")) {
339
- return `${message}
340
- Open tests/bachsproof.setup.mjs and implement createPayment, or add a real reference to the selected test. Use BACHSPROOF_USE_SYNTHETIC_REFERENCES=true only for an isolated fixture run.`;
341
- }
342
- if (message.includes("Payment preparation failed") || message.includes("createPayment must return")) {
343
- return `${message}
344
- Open tests/bachsproof.setup.mjs. Create an isolated test payment and return its non-empty order or payment reference. BachsProof will not send a webhook until preparation succeeds.`;
345
- }
346
- if (message.includes("already assigned to another selected scenario")) {
237
+ if (message.includes("Refusing to overwrite existing BachsProof file")) {
347
238
  return `${message}
348
- Open tests/bachsproof.setup.mjs or tests/bachsproof.test.mjs and make each selected scenario use a fresh payment reference.`;
239
+ Open the existing file if you want to keep it. Use --force only when replacement is intentional.`;
349
240
  }
350
- if (message.includes("Financial verification is required")) {
241
+ if (message.includes("Implement createPayment")) {
351
242
  return `${message}
352
- Open tests/bachsproof.verify.mjs, implement verify(reference, context) by reading committed financial records, then enable verify and requireFinancialVerification in bachsproof.config.mjs.`;
243
+ The callback must create a fresh record in your isolated test application and return its reference.`;
353
244
  }
354
- if (message.includes("requires target.baseUrl") || message.includes("requires a provider adapter") || message.includes("requires at least one test")) {
245
+ if (message.includes("Implement verify")) {
355
246
  return `${message}
356
- Open bachsproof.config.mjs and follow its numbered STEP sections. The provider, target URL/path, and tests are required.`;
247
+ The callback must read committed payment and ledger records. HTTP success alone is not financial proof.`;
357
248
  }
358
- if (message.includes("Financial verification returned")) {
249
+ if (message.includes("already used") || message.includes("duplicate payment references")) {
359
250
  return `${message}
360
- Open tests/bachsproof.verify.mjs and return the requested reference plus the actual creditCount, creditedAmountMinor, and currency from committed test data.`;
251
+ Every selected scenario needs a fresh isolated payment record.`;
361
252
  }
362
- if (message.includes("Webhook delivery") && message.includes("HTTP 4")) {
253
+ if (message.includes("Unknown BachsProof scenario")) {
363
254
  return `${message}
364
- Open bachsproof.config.mjs STEP 2 and check BACHSPROOF_TARGET_URL, BACHSPROOF_WEBHOOK_PATH, and BACHS_WEBHOOK_SECRET. Your application may also be rejecting the test event as expected; set expectedStatus in tests/bachsproof.test.mjs when that rejection is part of the scenario.`;
255
+ Use the exact scenario identifier from the generated configuration comments.`;
365
256
  }
366
- if (message.includes("Webhook delivery") && message.includes("HTTP 5")) {
257
+ if (message.includes("Webhook delivery")) {
367
258
  return `${message}
368
- Open your application's test webhook handler and logs. The application returned a server error while handling the simulated event.`;
259
+ Check the isolated webhook URL and application logs. BachsProof still verifies financial state when it is safe to do so.`;
369
260
  }
370
- if (message.includes("No BachsProof test named")) {
261
+ if (message.includes("Financial verification")) {
371
262
  return `${message}
372
- Open tests/bachsproof.test.mjs and copy the exact value from the test's name property, for example "sequential duplicate webhook".`;
263
+ Check that verify() reads the requested reference and reports actual committed financial state.`;
373
264
  }
374
265
  return message;
375
266
  }
376
267
  function printInitializationGuide() {
377
268
  console.log(`
378
- BachsProof initialized successfully!
379
-
380
- WHAT IS BACHSPROOF?
381
- BachsProof sends simulated payment webhooks to your application and checks
382
- whether your application handles money correctly. It does not move real money.
383
-
384
- GET STARTED
269
+ BachsProof initialized successfully.
385
270
 
386
- Step 1: Open bachsproof.config.mjs
387
- Set your application's base URL, webhook path, and test-only signing secret.
271
+ Open bachsproof.config.mjs and implement two callbacks:
388
272
 
389
- Step 2: Open tests/bachsproof.setup.mjs
390
- Show BachsProof how to create an isolated test payment and return its reference.
391
- This is optional when you provide references manually in the test file.
273
+ 1. createPayment() creates a fresh payment in your isolated test application.
274
+ 2. verify() reads the committed payment and ledger records.
392
275
 
393
- Step 3: Open tests/bachsproof.verify.mjs
394
- Show BachsProof how to read the actual payment and credit records from your test data.
276
+ Then run:
277
+ pnpm exec bachsproof test --name "sequential duplicate webhook"
278
+ pnpm exec bachsproof test
395
279
 
396
- Step 4: Enable the two functions
397
- Uncomment createPayment in bachsproof.config.mjs. If you want financial
398
- correctness checks, also uncomment verify and requireFinancialVerification.
399
-
400
- Step 5: Run your first test
401
- pnpm exec bachsproof test --name "sequential duplicate webhook"
402
-
403
- Step 6: Run all payment scenarios
404
- pnpm exec bachsproof test
405
-
406
- IMPORTANT
407
- Only use BachsProof against an isolated test environment.
408
- Never send simulated payment webhooks to a production application.
280
+ Use a test-only application, database, queue, and webhook secret.
409
281
  `);
410
282
  }
411
283
  function valueAfter(args, flag) {
412
284
  const index = args.indexOf(flag);
413
285
  if (index >= 0) return args[index + 1];
414
286
  const inline = args.find((arg) => arg.startsWith(`${flag}=`));
415
- if (!inline) return void 0;
416
- return inline.slice(flag.length + 1).replace(/^("|')(.*)\1$/, "$2");
287
+ return inline?.slice(flag.length + 1).replace(/^("|')(.*)\1$/, "$2");
417
288
  }
418
289
  function has(args, flag) {
419
290
  return args.includes(flag);
@@ -421,6 +292,26 @@ function has(args, flag) {
421
292
  function redact(value, secret) {
422
293
  return secret ? value.replaceAll(secret, "[redacted]") : value;
423
294
  }
295
+ function reasonFor(report) {
296
+ const violation = report.verification?.violations[0];
297
+ if (violation) {
298
+ switch (violation.id) {
299
+ case "INV-001":
300
+ return "The same payment was credited more than once.";
301
+ case "INV-002":
302
+ case "INV-005":
303
+ return "The credited amount or currency does not match the payment.";
304
+ case "INV-003":
305
+ return "The successful payment did not produce the required credit.";
306
+ case "INV-004":
307
+ return "An ineligible payment created a credit.";
308
+ }
309
+ }
310
+ return report.errors[0];
311
+ }
312
+ function formatState(state) {
313
+ return state ? `${state.creditCount} credit(s) totalling ${state.creditedAmountMinor} ${state.currency} minor units` : "not available";
314
+ }
424
315
  async function main(args = process.argv.slice(2)) {
425
316
  const command = args[0];
426
317
  if (!command || command === "--help" || command === "-h") {
@@ -444,30 +335,33 @@ ${usage()}`);
444
335
  const summary = summarizeRuns(results);
445
336
  const failed = results.some(({ result }) => !result.passed);
446
337
  if (has(args, "--json")) {
447
- const json = JSON.stringify(results, null, 2);
448
- console.log(redact(json, config.signing?.secret));
338
+ console.log(redact(JSON.stringify(results, null, 2), config.secret));
449
339
  } else {
450
- console.log(`BachsProof: ${resolve(configPath)}`);
340
+ console.log("BachsProof\n");
451
341
  for (const { name, result } of results) {
452
- const verification = result.report.financiallyVerified ? "financially verified" : "delivery-only; financial verification not configured";
453
342
  const duration = result.report.completedAt ? Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt)) : 0;
454
- const violations = result.report.verification?.violations.length ?? 0;
455
- console.log(`${result.passed ? "PASS" : "FAIL"} ${name} (${verification}; ${duration}ms; ${violations} financial violations)`);
456
- for (const error of result.report.errors) {
457
- console.log(` ${redact(explainOnboardingError(error), config.signing?.secret).replaceAll("\n", "\n ")}`);
343
+ console.log(`${result.passed ? "PASS" : "FAIL"} ${name}`);
344
+ if (!result.passed) {
345
+ console.log(` Payment reference: ${result.report.paymentReference}`);
346
+ console.log(` Expected: one credit of ${result.report.expected.amountMinor} ${result.report.expected.currency} minor units when eligible`);
347
+ console.log(` Observed: ${formatState(result.report.observed)}`);
348
+ const reason = reasonFor(result.report);
349
+ if (reason) console.log(` Reason: ${redact(reason, config.secret)}`);
458
350
  }
351
+ console.log(` ${result.report.financiallyVerified ? "Financial verification completed" : "Financial verification did not complete"} (${duration}ms)
352
+ `);
459
353
  }
460
- console.log(`Summary: ${summary.passed}/${summary.total} passed, ${summary.failed} failed, ${summary.financiallyVerified} financially verified, ${summary.financiallyUnverified} unverified, ${summary.financialViolations} financial violations, ${summary.durationMs}ms`);
461
- if (!config.verify) {
462
- console.log("WARNING: black-box delivery success is not deterministic race coverage and does not prove committed financial correctness.");
463
- }
354
+ console.log("Summary");
355
+ console.log(`${summary.total} scenarios`);
356
+ console.log(`${summary.passed} passed`);
357
+ console.log(`${summary.failed} failed`);
464
358
  }
465
359
  return failed ? 1 : 0;
466
360
  }
467
361
  main().then((code) => {
468
362
  process.exitCode = code;
469
363
  }).catch((error) => {
470
- console.error(explainOnboardingError(error));
364
+ console.error(explainError(error));
471
365
  process.exitCode = 1;
472
366
  });
473
367