@bachsproof/cli 0.0.0-stage → 1.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BachsProof contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # @bachsproof/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Beyond webhook delivery. Verify financial correctness.**
4
+
5
+ Package-installable CLI onboarding for BachsProof, a financial correctness
6
+ testing framework for applications integrating Bachs.
7
+
8
+ pnpm add -D @bachsproof/cli
9
+ pnpm exec bachsproof init
10
+ pnpm exec bachsproof test
11
+
12
+ `bachsproof init` creates a small configuration and test suite in the independent
13
+ application repository:
14
+
15
+ - `bachsproof.config.mjs` for the provider, webhook target, signing secret,
16
+ payment preparation, verification, and polling settings;
17
+ - `tests/bachsproof.test.mjs` with all 15 supported scenario definitions;
18
+ - `tests/bachsproof.setup.mjs` for the optional `createPayment(context)` callback;
19
+ - `tests/bachsproof.verify.mjs` for the `verify(reference, context)` callback.
20
+
21
+ The generated setup and verifier templates fail until implemented. BachsProof does
22
+ not invent application references or treat expected values as financial proof.
23
+
24
+ The target application does not need BachsProof routes, controllers, services, or
25
+ production instrumentation. It only needs a reachable webhook URL. The
26
+ application owns test payment preparation, isolation, cleanup, and committed
27
+ state access.
28
+
29
+ Real application references are the default. Use `createPayment` for fresh test
30
+ records, explicit `reference` or `references` for manual fixtures, and
31
+ `syntheticReferences: true` only for isolated adapter/HTTP fixture tests.
32
+
33
+ The CLI runs configured scenarios sequentially. Delivery waves inside a
34
+ concurrency scenario remain concurrent. `--name` runs one exact test name and
35
+ `--json` emits machine-readable reports:
36
+
37
+ pnpm exec bachsproof test --name "underpaid payment"
38
+ pnpm exec bachsproof test --json
39
+
40
+ Add `requireFinancialVerification: true` when the suite must fail unless the
41
+ callback has observed committed financial state. Without a callback, BachsProof
42
+ can still test HTTP delivery, but it reports the run as financially unverified.
43
+
44
+ For optional controlled concurrency testing, configure a checkpoint and use
45
+ `@bachsproof/sdk` in an explicitly enabled test build. Ordinary black-box HTTP
46
+ concurrency is not deterministic race-condition coverage.
47
+
48
+ See the repository [quickstart](../../docs/quickstart.md) and
49
+ [CLI guide](../../docs/cli.md) for the complete workflow.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ declare function main(args?: string[]): Promise<number>;
2
+
3
+ export { main };
package/dist/cli.js ADDED
@@ -0,0 +1,476 @@
1
+ #!/usr/bin/env node
2
+ import { resolve, join } from 'path';
3
+ import { mkdir, writeFile, access } from 'fs/promises';
4
+ import { constants } from 'fs';
5
+ import { createJiti } from 'jiti';
6
+ import { BachsProof } from '@bachsproof/core';
7
+ import { signBachsWebhook } from '@bachsproof/bachs';
8
+
9
+ var configTemplate = `/**
10
+ * BachsProof test configuration.
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
62
+ */
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
+ );
135
+
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
+ );
161
+
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
+ }
177
+ `;
178
+ async function exists(path) {
179
+ try {
180
+ await access(path, constants.F_OK);
181
+ return true;
182
+ } catch {
183
+ return false;
184
+ }
185
+ }
186
+ 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
+ }
200
+ }
201
+ await mkdir(testDirectory, { recursive: true });
202
+ 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;
207
+ }
208
+ function assertConfig(value) {
209
+ if (!value || typeof value !== "object") throw new Error("BachsProof config must export a default object");
210
+ 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");
214
+ }
215
+ if (!Array.isArray(config.tests) || config.tests.length === 0) throw new Error("BachsProof config requires at least one test");
216
+ }
217
+ async function loadConfig(configPath = "bachsproof.config.mjs") {
218
+ const absolutePath = resolve(process.cwd(), configPath);
219
+ const jiti = createJiti(absolutePath, { interopDefault: true });
220
+ const loaded = await jiti.import(absolutePath, { default: true });
221
+ assertConfig(loaded);
222
+ return loaded;
223
+ }
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");
228
+ return {
229
+ ...provider,
230
+ headers(event) {
231
+ const rawBody = provider.serialize(event);
232
+ return {
233
+ ...provider.headers?.(event) ?? {},
234
+ ...signBachsWebhook(rawBody, config.signing?.secret ?? "", config.signing?.timestamp)
235
+ };
236
+ },
237
+ headersForBody(event, body) {
238
+ return {
239
+ ...provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {},
240
+ ...signBachsWebhook(body, config.signing?.secret ?? "", config.signing?.timestamp)
241
+ };
242
+ }
243
+ };
244
+ }
245
+ 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 = [];
253
+ 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
+ }
271
+ }
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
291
+ });
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 });
299
+ }
300
+ return results;
301
+ }
302
+ function summarizeRuns(results) {
303
+ const durationMs = results.reduce((total, { result }) => {
304
+ if (!result.report.completedAt) return total;
305
+ return total + Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt));
306
+ }, 0);
307
+ return {
308
+ total: results.length,
309
+ passed: results.filter(({ result }) => result.passed).length,
310
+ failed: results.filter(({ result }) => !result.passed).length,
311
+ financiallyVerified: results.filter(({ result }) => result.report.financiallyVerified).length,
312
+ financiallyUnverified: results.filter(({ result }) => !result.report.financiallyVerified).length,
313
+ financialViolations: results.reduce((total, { result }) => total + (result.report.verification?.violations.length ?? 0), 0),
314
+ durationMs
315
+ };
316
+ }
317
+
318
+ // src/cli.ts
319
+ function usage() {
320
+ return `BachsProof payment correctness testing
321
+
322
+ Usage:
323
+ bachsproof init [directory] [--force]
324
+ bachsproof test [--config <path>] [--name <test-name>] [--json]
325
+
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.
330
+ `;
331
+ }
332
+ function explainOnboardingError(error) {
333
+ 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")) {
347
+ return `${message}
348
+ Open tests/bachsproof.setup.mjs or tests/bachsproof.test.mjs and make each selected scenario use a fresh payment reference.`;
349
+ }
350
+ if (message.includes("Financial verification is required")) {
351
+ 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.`;
353
+ }
354
+ if (message.includes("requires target.baseUrl") || message.includes("requires a provider adapter") || message.includes("requires at least one test")) {
355
+ return `${message}
356
+ Open bachsproof.config.mjs and follow its numbered STEP sections. The provider, target URL/path, and tests are required.`;
357
+ }
358
+ if (message.includes("Financial verification returned")) {
359
+ return `${message}
360
+ Open tests/bachsproof.verify.mjs and return the requested reference plus the actual creditCount, creditedAmountMinor, and currency from committed test data.`;
361
+ }
362
+ if (message.includes("Webhook delivery") && message.includes("HTTP 4")) {
363
+ 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.`;
365
+ }
366
+ if (message.includes("Webhook delivery") && message.includes("HTTP 5")) {
367
+ return `${message}
368
+ Open your application's test webhook handler and logs. The application returned a server error while handling the simulated event.`;
369
+ }
370
+ if (message.includes("No BachsProof test named")) {
371
+ return `${message}
372
+ Open tests/bachsproof.test.mjs and copy the exact value from the test's name property, for example "sequential duplicate webhook".`;
373
+ }
374
+ return message;
375
+ }
376
+ function printInitializationGuide() {
377
+ 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
385
+
386
+ Step 1: Open bachsproof.config.mjs
387
+ Set your application's base URL, webhook path, and test-only signing secret.
388
+
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.
392
+
393
+ Step 3: Open tests/bachsproof.verify.mjs
394
+ Show BachsProof how to read the actual payment and credit records from your test data.
395
+
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.
409
+ `);
410
+ }
411
+ function valueAfter(args, flag) {
412
+ const index = args.indexOf(flag);
413
+ if (index >= 0) return args[index + 1];
414
+ const inline = args.find((arg) => arg.startsWith(`${flag}=`));
415
+ if (!inline) return void 0;
416
+ return inline.slice(flag.length + 1).replace(/^("|')(.*)\1$/, "$2");
417
+ }
418
+ function has(args, flag) {
419
+ return args.includes(flag);
420
+ }
421
+ function redact(value, secret) {
422
+ return secret ? value.replaceAll(secret, "[redacted]") : value;
423
+ }
424
+ async function main(args = process.argv.slice(2)) {
425
+ const command = args[0];
426
+ if (!command || command === "--help" || command === "-h") {
427
+ console.log(usage());
428
+ return 0;
429
+ }
430
+ if (command === "init") {
431
+ const directory = args.find((arg, index) => index > 0 && !arg.startsWith("-")) ?? process.cwd();
432
+ const paths = await initProject(directory, has(args, "--force"));
433
+ for (const path of paths) console.log(`created ${path}`);
434
+ printInitializationGuide();
435
+ return 0;
436
+ }
437
+ if (command !== "test") throw new Error(`Unknown command ${command}
438
+
439
+ ${usage()}`);
440
+ const configPath = valueAfter(args, "--config") ?? "bachsproof.config.mjs";
441
+ const testName = valueAfter(args, "--name");
442
+ const config = await loadConfig(configPath);
443
+ const results = await runConfig(config, { testName });
444
+ const summary = summarizeRuns(results);
445
+ const failed = results.some(({ result }) => !result.passed);
446
+ if (has(args, "--json")) {
447
+ const json = JSON.stringify(results, null, 2);
448
+ console.log(redact(json, config.signing?.secret));
449
+ } else {
450
+ console.log(`BachsProof: ${resolve(configPath)}`);
451
+ for (const { name, result } of results) {
452
+ const verification = result.report.financiallyVerified ? "financially verified" : "delivery-only; financial verification not configured";
453
+ 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 ")}`);
458
+ }
459
+ }
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
+ }
464
+ }
465
+ return failed ? 1 : 0;
466
+ }
467
+ main().then((code) => {
468
+ process.exitCode = code;
469
+ }).catch((error) => {
470
+ console.error(explainOnboardingError(error));
471
+ process.exitCode = 1;
472
+ });
473
+
474
+ export { main };
475
+ //# sourceMappingURL=cli.js.map
476
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/init.ts","../src/runner.ts","../src/cli.ts"],"names":["resolve"],"mappings":";;;;;;;;AAIA,IAAM,cAAA,GAAiB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AA4CvB,IAAM,YAAA,GAAe,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAA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AAA,KAAS;AACpB,EAAA,OAAA,CAAQ,QAAA,GAAW,IAAA;AACrB,CAAC,CAAA,CAAE,KAAA,CAAM,CAAC,KAAA,KAAmB;AAC3B,EAAA,OAAA,CAAQ,KAAA,CAAM,sBAAA,CAAuB,KAAK,CAAC,CAAA;AAC3C,EAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrB,CAAC,CAAA","file":"cli.js","sourcesContent":["import { access, mkdir, writeFile } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nconst configTemplate = `/**\n * BachsProof test configuration.\n *\n * Follow the two application-specific steps:\n * 1. createPayment prepares a fresh test payment or order;\n * 2. verify reads the committed payment and ledger state.\n *\n * Both helpers are test-only. BachsProof does not add routes or modify the\n * production application.\n */\nimport { bachsAdapter } from \"@bachsproof/cli\";\nimport { tests } from \"./tests/bachsproof.test.mjs\";\n\nconst provider = bachsAdapter({ mode: \"mock\" });\nconst target = {\n baseUrl: process.env.BACHSPROOF_TARGET_URL ?? \"http://127.0.0.1:3000\",\n webhookPath: process.env.BACHSPROOF_WEBHOOK_PATH ?? \"/webhooks/bachs\"\n};\n\nconst signingSecret = process.env.BACHS_WEBHOOK_SECRET;\nconst signing = signingSecret ? { type: \"bachs\", secret: signingSecret } : undefined;\n\n// Uncomment after implementing tests/bachsproof.setup.mjs.\n// import { createPayment } from \"./tests/bachsproof.setup.mjs\";\n\n// Uncomment after implementing tests/bachsproof.verify.mjs.\n// import { verify } from \"./tests/bachsproof.verify.mjs\";\n\nexport default {\n provider,\n target,\n ...(signing ? { signing } : {}),\n // createPayment,\n // verify,\n // requireFinancialVerification: true,\n // financialVerification: {\n // completionDeadlineMs: 10_000,\n // pollIntervalMs: 25,\n // negativeObservationWindowMs: 250\n // },\n tests\n};\n`;\n\nconst testTemplate = `/**\n * BachsProof scenarios.\n *\n * Real application references are the default. Implement createPayment in\n * bachsproof.setup.mjs to create fresh test records automatically, or put an\n * explicit reference on a selected test. Synthetic references are only for\n * isolated fixture tests.\n *\n * Run one: pnpm exec bachsproof test --name \"sequential duplicate webhook\"\n * Run all: pnpm exec bachsproof test\n */\nconst amountMinor = Number(process.env.BACHSPROOF_AMOUNT_MINOR ?? 5_000_000);\nconst currency = process.env.BACHSPROOF_CURRENCY ?? \"NGN\";\nconst syntheticReferences = process.env.BACHSPROOF_USE_SYNTHETIC_REFERENCES === \"true\";\n\nexport const tests = [\n // Same successful payment twice in sequence: tests idempotency.\n { name: \"sequential duplicate webhook\", scenario: \"sequential-duplicate-webhook\", amountMinor, currency, syntheticReferences },\n\n // Same successful payment concurrently: tests duplicate-credit races.\n { name: \"concurrent duplicate credit\", scenario: \"concurrent-duplicate-credit\", concurrency: 3, amountMinor, currency, syntheticReferences },\n\n // Distinct payments concurrently: tests cross-payment interference.\n { name: \"concurrent unique payments\", scenario: \"concurrent-unique-payments\", amountMinor, currency, syntheticReferences },\n\n // checkout.completed plus collection.succeeded for one payment.\n { name: \"cross-event duplicate payment\", scenario: \"cross-event-duplicate-payment\", amountMinor, currency, syntheticReferences },\n\n // Newer success followed by older expiry: tests state ordering.\n { name: \"out-of-order events\", scenario: \"out-of-order-events\", amountMinor, currency, syntheticReferences },\n\n // Expiry followed by delayed success: tests eventual payment confirmation.\n { name: \"delayed payment confirmation\", scenario: \"delayed-payment-confirmation\", delayMs: 50, amountMinor, currency, syntheticReferences },\n\n // Completed checkout without a collected payment: must not credit.\n { name: \"incomplete checkout\", scenario: \"incomplete-checkout\", amountMinor, currency, syntheticReferences },\n\n // Expired checkout: must not credit.\n { name: \"expired checkout\", scenario: \"expired-checkout\", amountMinor, currency, syntheticReferences },\n\n // Changed body after signing: normally expects a 4xx rejection.\n { name: \"tampered webhook\", scenario: \"tampered-webhook\", expectedStatus: \"4xx\", amountMinor, currency, syntheticReferences },\n\n // Invalid signature: normally expects a 4xx rejection.\n { name: \"invalid webhook signature\", scenario: \"invalid-webhook-signature\", expectedStatus: \"4xx\", amountMinor, currency, syntheticReferences },\n\n // Malformed JSON: normally expects a 4xx rejection.\n { name: \"malformed webhook\", scenario: \"malformed-webhook\", expectedStatus: \"4xx\", amountMinor, currency, syntheticReferences },\n\n // Successful-looking event with the wrong amount: must not credit.\n { name: \"incorrect payment amount\", scenario: \"incorrect-payment-amount\", amountMinor, currency, syntheticReferences },\n\n // Successful-looking event with the wrong currency: must not credit.\n { name: \"incorrect payment currency\", scenario: \"incorrect-payment-currency\", amountMinor, currency, syntheticReferences },\n\n // Underpaid collection: must not credit before the shortfall is paid.\n { name: \"underpaid payment\", scenario: \"underpaid-payment\", amountMinor, currency, syntheticReferences },\n\n // Failed collection: must not credit.\n { name: \"failed payment\", scenario: \"failed-payment\", amountMinor, currency, syntheticReferences }\n];\n`;\n\nconst setupTemplate = `/**\n * Create isolated application payment records for BachsProof.\n *\n * This callback is optional when tests provide real references directly. It is\n * recommended for repeatedly running the complete suite.\n *\n * BachsProof calls it only for selected scenarios that need a reference. Every\n * call must create a fresh test payment or order and return its reference.\n * It must not charge a card, call a live provider, or move real money.\n *\n * Context: scenario, amountMinor, currency, paymentIndex, paymentCount.\n *\n * Use an existing isolated test API, application service, ORM, or seed helper.\n */\nexport async function createPayment(context) {\n throw new Error(\n \"Implement createPayment in tests/bachsproof.setup.mjs. \" +\n \"Create an isolated test payment and return its fresh reference for \" +\n context.scenario + \" (\" + (context.paymentIndex + 1) + \" of \" +\n context.paymentCount + \").\"\n );\n\n // Example:\n // const payment = await testSupport.createPayment({\n // scenario: context.scenario,\n // amountMinor: context.amountMinor,\n // currency: context.currency,\n // paymentIndex: context.paymentIndex\n // });\n // return payment.reference;\n}\n`;\n\nconst verifierTemplate = `/**\n * Read committed financial state for BachsProof.\n *\n * HTTP 200 only proves that the webhook route acknowledged a request. This\n * callback must read the payment and actual credit or ledger records.\n * Do not return hardcoded expected values.\n *\n * Return reference, creditCount, creditedAmountMinor, currency, and optional\n * status, pending, and ledgerEntries fields.\n */\nexport async function verify(reference, context) {\n throw new Error(\n \"Implement verify in tests/bachsproof.verify.mjs by reading committed \" +\n \"financial records for \" + reference + \" before enabling it.\"\n );\n\n // Example:\n // const state = await testSupport.readCommittedFinancialState(reference);\n // return {\n // reference,\n // creditCount: state.credits.length,\n // creditedAmountMinor: state.credits.reduce(\n // (total, credit) => total + credit.amountMinor,\n // 0\n // ),\n // currency: state.currency,\n // status: state.status,\n // pending: state.pending,\n // ledgerEntries: state.credits\n // };\n}\n`;\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\nexport async function initProject(directory = process.cwd(), force = false): Promise<string[]> {\n const root = resolve(directory);\n const configPath = join(root, \"bachsproof.config.mjs\");\n const testDirectory = join(root, \"tests\");\n const testPath = join(testDirectory, \"bachsproof.test.mjs\");\n const setupPath = join(testDirectory, \"bachsproof.setup.mjs\");\n const verifierPath = join(testDirectory, \"bachsproof.verify.mjs\");\n const paths = [configPath, testPath, setupPath, verifierPath];\n if (!force) {\n const existing = [];\n for (const path of paths) if (await exists(path)) existing.push(path);\n if (existing.length > 0) {\n throw new Error(\"Refusing to overwrite existing BachsProof files: \" + existing.join(\", \") + \". Use --force to replace them.\");\n }\n }\n await mkdir(testDirectory, { recursive: true });\n await writeFile(configPath, configTemplate, \"utf8\");\n await writeFile(testPath, testTemplate, \"utf8\");\n await writeFile(setupPath, setupTemplate, \"utf8\");\n await writeFile(verifierPath, verifierTemplate, \"utf8\");\n return paths;\n}\n","import { createJiti } from \"jiti\";\nimport { resolve } from \"node:path\";\nimport { BachsProof, type PaymentEvent, type PaymentReferenceCreator, type ProviderAdapter } from \"@bachsproof/core\";\nimport { signBachsWebhook } from \"@bachsproof/bachs\";\nimport type { BachsProofCliRun, BachsProofConfig, BachsProofSummary, RunConfigOptions } from \"./types.js\";\n\nfunction assertConfig(value: unknown): asserts value is BachsProofConfig {\n if (!value || typeof value !== \"object\") throw new Error(\"BachsProof config must export a default object\");\n const config = value as Partial<BachsProofConfig>;\n if (!config.provider || typeof config.provider !== \"object\") throw new Error(\"BachsProof config requires a provider adapter\");\n if (!config.target || typeof config.target !== \"object\" || typeof config.target.baseUrl !== \"string\" || typeof config.target.webhookPath !== \"string\") {\n throw new Error(\"BachsProof config requires target.baseUrl and target.webhookPath\");\n }\n if (!Array.isArray(config.tests) || config.tests.length === 0) throw new Error(\"BachsProof config requires at least one test\");\n}\n\n/** Load .mjs, .js, .cjs, or TypeScript config without requiring a repo-local loader. */\nexport async function loadConfig(configPath = \"bachsproof.config.mjs\"): Promise<BachsProofConfig> {\n const absolutePath = resolve(process.cwd(), configPath);\n const jiti = createJiti(absolutePath, { interopDefault: true });\n const loaded = await jiti.import(absolutePath, { default: true }) as unknown;\n assertConfig(loaded);\n return loaded;\n}\n\nfunction withBachsSigning<TEvent extends PaymentEvent>(provider: ProviderAdapter<TEvent>, config: BachsProofConfig<TEvent>): ProviderAdapter<TEvent> {\n if (!config.signing) return provider;\n if (config.signing.type !== \"bachs\") throw new Error(`Unsupported signing type ${String(config.signing.type)}`);\n if (!config.signing.secret) throw new Error(\"Bachs signing is configured but its secret is empty\");\n return {\n ...provider,\n headers(event) {\n const rawBody = provider.serialize(event);\n return {\n ...(provider.headers?.(event) ?? {}),\n ...signBachsWebhook(rawBody, config.signing?.secret ?? \"\", config.signing?.timestamp)\n };\n },\n headersForBody(event, body) {\n return {\n ...(provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {}),\n ...signBachsWebhook(body, config.signing?.secret ?? \"\", config.signing?.timestamp)\n };\n }\n };\n}\n\nexport async function runConfig(config: BachsProofConfig, options: RunConfigOptions = {}): Promise<BachsProofCliRun[]> {\n const tests = options.testName ? config.tests.filter((test) => test.name === options.testName) : config.tests;\n if (tests.length === 0) throw new Error(options.testName ? `No BachsProof test named ${options.testName}` : \"BachsProof config contains no tests\");\n if (config.requireFinancialVerification && !config.verify) {\n throw new Error(\"Financial verification is required, but the config has no verify callback\");\n }\n\n const provider = withBachsSigning(config.provider, config);\n const results: BachsProofCliRun[] = [];\n const usedReferences = new Set<string>();\n for (const test of tests) {\n const { name, ...runOptions } = test;\n const normalizedRunOptions = {\n ...runOptions,\n ...(runOptions.reference !== undefined ? { reference: typeof runOptions.reference === \"string\" ? runOptions.reference.trim() : runOptions.reference } : {}),\n ...(runOptions.references !== undefined ? { references: runOptions.references.map((reference) => typeof reference === \"string\" ? reference.trim() : reference) } : {})\n };\n const explicitReferences = normalizedRunOptions.scenario === \"concurrent-unique-payments\"\n ? normalizedRunOptions.references ?? []\n : normalizedRunOptions.reference ? [normalizedRunOptions.reference] : [];\n const normalizedExplicitReferences = explicitReferences.map((reference) => typeof reference === \"string\" ? reference.trim() : reference);\n const conflictingReference = normalizedExplicitReferences.find((reference) => typeof reference === \"string\" && usedReferences.has(reference));\n let preparationFailure: string | undefined;\n if (conflictingReference) {\n preparationFailure = `Payment preparation failed for ${runOptions.scenario}: reference ${conflictingReference} is already assigned to another selected scenario`;\n } else {\n for (const reference of normalizedExplicitReferences) {\n if (typeof reference === \"string\" && reference.trim().length > 0) usedReferences.add(reference.trim());\n }\n }\n const createPayment: PaymentReferenceCreator | undefined = preparationFailure\n ? async () => { throw new Error(preparationFailure); }\n : config.createPayment\n ? async (context) => {\n const reference = await config.createPayment?.(context);\n if (typeof reference !== \"string\" || reference.trim().length === 0) return reference as string;\n const normalized = reference.trim();\n if (usedReferences.has(normalized)) {\n throw new Error(`reference ${normalized} is already assigned to another selected scenario`);\n }\n usedReferences.add(normalized);\n return normalized;\n }\n : undefined;\n const runner = new BachsProof({\n provider,\n target: config.target,\n createPayment,\n verify: config.verify,\n financialVerification: config.financialVerification,\n checkpoint: config.checkpoint\n });\n const input = preparationFailure\n ? { ...normalizedRunOptions, reference: undefined, references: undefined, syntheticReferences: false }\n : normalizedRunOptions;\n const result = await runner.run(input);\n if (config.requireFinancialVerification && !result.report.financiallyVerified) {\n result.report.errors.push(\"Financial verification was required but did not run\");\n result.passed = false;\n }\n results.push({ name, result });\n }\n return results;\n}\n\nexport function summarizeRuns(results: BachsProofCliRun[]): BachsProofSummary {\n const durationMs = results.reduce((total, { result }) => {\n if (!result.report.completedAt) return total;\n return total + Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt));\n }, 0);\n return {\n total: results.length,\n passed: results.filter(({ result }) => result.passed).length,\n failed: results.filter(({ result }) => !result.passed).length,\n financiallyVerified: results.filter(({ result }) => result.report.financiallyVerified).length,\n financiallyUnverified: results.filter(({ result }) => !result.report.financiallyVerified).length,\n financialViolations: results.reduce((total, { result }) => total + (result.report.verification?.violations.length ?? 0), 0),\n durationMs\n };\n}\n\n","import { resolve } from \"node:path\";\nimport { initProject } from \"./init.js\";\nimport { loadConfig, runConfig, summarizeRuns } from \"./runner.js\";\n\nfunction usage(): string {\n return `BachsProof payment correctness testing\n\nUsage:\n bachsproof init [directory] [--force]\n bachsproof test [--config <path>] [--name <test-name>] [--json]\n\ninit creates bachsproof.config.mjs, tests/bachsproof.test.mjs,\ntests/bachsproof.setup.mjs, and a hard-fail tests/bachsproof.verify.mjs template.\ntest sends configured provider events to the target webhook and reports delivery\nand, when configured, committed financial verification results.\n`;\n}\n\nfunction explainOnboardingError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes(\"Refusing to overwrite existing BachsProof files\")) {\n return `${message}\\nOpen the listed files if you want to keep them, or run \"bachsproof init --force\" only when replacing them is intentional.`;\n }\n if (message.includes(\"real application reference is required\") || message.includes(\"A real application reference is required\")) {\n return `${message}\\nOpen 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.`;\n }\n if (message.includes(\"Payment preparation failed\") || message.includes(\"createPayment must return\")) {\n return `${message}\\nOpen 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.`;\n }\n if (message.includes(\"already assigned to another selected scenario\")) {\n return `${message}\\nOpen tests/bachsproof.setup.mjs or tests/bachsproof.test.mjs and make each selected scenario use a fresh payment reference.`;\n }\n if (message.includes(\"Financial verification is required\")) {\n return `${message}\\nOpen tests/bachsproof.verify.mjs, implement verify(reference, context) by reading committed financial records, then enable verify and requireFinancialVerification in bachsproof.config.mjs.`;\n }\n if (message.includes(\"requires target.baseUrl\") || message.includes(\"requires a provider adapter\") || message.includes(\"requires at least one test\")) {\n return `${message}\\nOpen bachsproof.config.mjs and follow its numbered STEP sections. The provider, target URL/path, and tests are required.`;\n }\n if (message.includes(\"Financial verification returned\")) {\n return `${message}\\nOpen tests/bachsproof.verify.mjs and return the requested reference plus the actual creditCount, creditedAmountMinor, and currency from committed test data.`;\n }\n if (message.includes(\"Webhook delivery\") && message.includes(\"HTTP 4\")) {\n return `${message}\\nOpen 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.`;\n }\n if (message.includes(\"Webhook delivery\") && message.includes(\"HTTP 5\")) {\n return `${message}\\nOpen your application's test webhook handler and logs. The application returned a server error while handling the simulated event.`;\n }\n if (message.includes(\"No BachsProof test named\")) {\n return `${message}\\nOpen tests/bachsproof.test.mjs and copy the exact value from the test's name property, for example \"sequential duplicate webhook\".`;\n }\n return message;\n}\n\nfunction printInitializationGuide(): void {\n console.log(`\nBachsProof initialized successfully!\n\nWHAT IS BACHSPROOF?\nBachsProof sends simulated payment webhooks to your application and checks\nwhether your application handles money correctly. It does not move real money.\n\nGET STARTED\n\nStep 1: Open bachsproof.config.mjs\n Set your application's base URL, webhook path, and test-only signing secret.\n\nStep 2: Open tests/bachsproof.setup.mjs\n Show BachsProof how to create an isolated test payment and return its reference.\n This is optional when you provide references manually in the test file.\n\nStep 3: Open tests/bachsproof.verify.mjs\n Show BachsProof how to read the actual payment and credit records from your test data.\n\nStep 4: Enable the two functions\n Uncomment createPayment in bachsproof.config.mjs. If you want financial\n correctness checks, also uncomment verify and requireFinancialVerification.\n\nStep 5: Run your first test\n pnpm exec bachsproof test --name \"sequential duplicate webhook\"\n\nStep 6: Run all payment scenarios\n pnpm exec bachsproof test\n\nIMPORTANT\nOnly use BachsProof against an isolated test environment.\nNever send simulated payment webhooks to a production application.\n`);\n}\n\nfunction valueAfter(args: string[], flag: string): string | undefined {\n const index = args.indexOf(flag);\n if (index >= 0) return args[index + 1];\n const inline = args.find((arg) => arg.startsWith(`${flag}=`));\n if (!inline) return undefined;\n return inline.slice(flag.length + 1).replace(/^(\"|')(.*)\\1$/, \"$2\");\n}\n\nfunction has(args: string[], flag: string): boolean {\n return args.includes(flag);\n}\n\nfunction redact(value: string, secret?: string): string {\n return secret ? value.replaceAll(secret, \"[redacted]\") : value;\n}\n\nexport async function main(args = process.argv.slice(2)): Promise<number> {\n const command = args[0];\n if (!command || command === \"--help\" || command === \"-h\") {\n console.log(usage());\n return 0;\n }\n if (command === \"init\") {\n const directory = args.find((arg, index) => index > 0 && !arg.startsWith(\"-\")) ?? process.cwd();\n const paths = await initProject(directory, has(args, \"--force\"));\n for (const path of paths) console.log(`created ${path}`);\n printInitializationGuide();\n return 0;\n }\n if (command !== \"test\") throw new Error(`Unknown command ${command}\\n\\n${usage()}`);\n\n const configPath = valueAfter(args, \"--config\") ?? \"bachsproof.config.mjs\";\n const testName = valueAfter(args, \"--name\");\n const config = await loadConfig(configPath);\n const results = await runConfig(config, { testName });\n const summary = summarizeRuns(results);\n const failed = results.some(({ result }) => !result.passed);\n if (has(args, \"--json\")) {\n const json = JSON.stringify(results, null, 2);\n console.log(redact(json, config.signing?.secret));\n } else {\n console.log(`BachsProof: ${resolve(configPath)}`);\n for (const { name, result } of results) {\n const verification = result.report.financiallyVerified ? \"financially verified\" : \"delivery-only; financial verification not configured\";\n const duration = result.report.completedAt ? Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt)) : 0;\n const violations = result.report.verification?.violations.length ?? 0;\n console.log(`${result.passed ? \"PASS\" : \"FAIL\"} ${name} (${verification}; ${duration}ms; ${violations} financial violations)`);\n for (const error of result.report.errors) {\n console.log(` ${redact(explainOnboardingError(error), config.signing?.secret).replaceAll(\"\\n\", \"\\n \")}`);\n }\n }\n 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`);\n if (!config.verify) {\n console.log(\"WARNING: black-box delivery success is not deterministic race coverage and does not prove committed financial correctness.\");\n }\n }\n return failed ? 1 : 0;\n}\n\nmain().then((code) => {\n process.exitCode = code;\n}).catch((error: unknown) => {\n console.error(explainOnboardingError(error));\n process.exitCode = 1;\n});\n"]}
@@ -0,0 +1,58 @@
1
+ export { bachsAdapter, signBachsWebhook } from '@bachsproof/bachs';
2
+ import * as _bachsproof_core from '@bachsproof/core';
3
+ import { RunOptions, PaymentEvent, ProviderAdapter, BachsProofTarget, PaymentReferenceCreator, FinancialVerifier, FinancialVerificationOptions } from '@bachsproof/core';
4
+ export { PaymentPreparationContext, PaymentReferenceCreator } from '@bachsproof/core';
5
+
6
+ interface BachsProofCliTest extends Omit<RunOptions, "scenario"> {
7
+ name: string;
8
+ scenario: RunOptions["scenario"];
9
+ }
10
+ interface BachsSigningConfig {
11
+ type: "bachs";
12
+ secret: string;
13
+ timestamp?: number;
14
+ }
15
+ interface BachsProofConfig<TEvent extends PaymentEvent = PaymentEvent> {
16
+ provider: ProviderAdapter<TEvent>;
17
+ target: BachsProofTarget;
18
+ tests: BachsProofCliTest[];
19
+ /** Optional test-only callback that creates fresh application payments. */
20
+ createPayment?: PaymentReferenceCreator;
21
+ verify?: FinancialVerifier;
22
+ financialVerification?: FinancialVerificationOptions;
23
+ checkpoint?: {
24
+ name: string;
25
+ timeoutMs?: number;
26
+ };
27
+ signing?: BachsSigningConfig;
28
+ /** Fail the CLI when the config has no committed-state verifier. */
29
+ requireFinancialVerification?: boolean;
30
+ }
31
+ interface BachsProofCliRun {
32
+ name: string;
33
+ result: _bachsproof_core.BachsProofResult;
34
+ }
35
+ interface BachsProofSummary {
36
+ total: number;
37
+ passed: number;
38
+ failed: number;
39
+ financiallyVerified: number;
40
+ financiallyUnverified: number;
41
+ financialViolations: number;
42
+ durationMs: number;
43
+ }
44
+ interface RunConfigOptions {
45
+ testName?: string;
46
+ }
47
+
48
+ /** Type helper for bachsproof.config.mjs and bachsproof.config.ts files. */
49
+ declare function defineConfig<TEvent extends PaymentEvent>(config: BachsProofConfig<TEvent>): BachsProofConfig<TEvent>;
50
+
51
+ declare function initProject(directory?: string, force?: boolean): Promise<string[]>;
52
+
53
+ /** Load .mjs, .js, .cjs, or TypeScript config without requiring a repo-local loader. */
54
+ declare function loadConfig(configPath?: string): Promise<BachsProofConfig>;
55
+ declare function runConfig(config: BachsProofConfig, options?: RunConfigOptions): Promise<BachsProofCliRun[]>;
56
+ declare function summarizeRuns(results: BachsProofCliRun[]): BachsProofSummary;
57
+
58
+ export { type BachsProofCliRun, type BachsProofCliTest, type BachsProofConfig, type BachsProofSummary, type BachsSigningConfig, type RunConfigOptions, defineConfig, initProject, loadConfig, runConfig, summarizeRuns };
package/dist/index.js ADDED
@@ -0,0 +1,325 @@
1
+ #!/usr/bin/env node
2
+ import { signBachsWebhook } from '@bachsproof/bachs';
3
+ export { bachsAdapter, signBachsWebhook } from '@bachsproof/bachs';
4
+ import { mkdir, writeFile, access } from 'fs/promises';
5
+ import { constants } from 'fs';
6
+ import { resolve, join } from 'path';
7
+ import { createJiti } from 'jiti';
8
+ import { BachsProof } from '@bachsproof/core';
9
+
10
+ // src/config.ts
11
+ function defineConfig(config) {
12
+ return config;
13
+ }
14
+ var configTemplate = `/**
15
+ * BachsProof test configuration.
16
+ *
17
+ * Follow the two application-specific steps:
18
+ * 1. createPayment prepares a fresh test payment or order;
19
+ * 2. verify reads the committed payment and ledger state.
20
+ *
21
+ * Both helpers are test-only. BachsProof does not add routes or modify the
22
+ * production application.
23
+ */
24
+ import { bachsAdapter } from "@bachsproof/cli";
25
+ import { tests } from "./tests/bachsproof.test.mjs";
26
+
27
+ const provider = bachsAdapter({ mode: "mock" });
28
+ const target = {
29
+ baseUrl: process.env.BACHSPROOF_TARGET_URL ?? "http://127.0.0.1:3000",
30
+ webhookPath: process.env.BACHSPROOF_WEBHOOK_PATH ?? "/webhooks/bachs"
31
+ };
32
+
33
+ const signingSecret = process.env.BACHS_WEBHOOK_SECRET;
34
+ const signing = signingSecret ? { type: "bachs", secret: signingSecret } : undefined;
35
+
36
+ // Uncomment after implementing tests/bachsproof.setup.mjs.
37
+ // import { createPayment } from "./tests/bachsproof.setup.mjs";
38
+
39
+ // Uncomment after implementing tests/bachsproof.verify.mjs.
40
+ // import { verify } from "./tests/bachsproof.verify.mjs";
41
+
42
+ export default {
43
+ provider,
44
+ target,
45
+ ...(signing ? { signing } : {}),
46
+ // createPayment,
47
+ // verify,
48
+ // requireFinancialVerification: true,
49
+ // financialVerification: {
50
+ // completionDeadlineMs: 10_000,
51
+ // pollIntervalMs: 25,
52
+ // negativeObservationWindowMs: 250
53
+ // },
54
+ tests
55
+ };
56
+ `;
57
+ var testTemplate = `/**
58
+ * BachsProof scenarios.
59
+ *
60
+ * Real application references are the default. Implement createPayment in
61
+ * bachsproof.setup.mjs to create fresh test records automatically, or put an
62
+ * explicit reference on a selected test. Synthetic references are only for
63
+ * isolated fixture tests.
64
+ *
65
+ * Run one: pnpm exec bachsproof test --name "sequential duplicate webhook"
66
+ * Run all: pnpm exec bachsproof test
67
+ */
68
+ const amountMinor = Number(process.env.BACHSPROOF_AMOUNT_MINOR ?? 5_000_000);
69
+ const currency = process.env.BACHSPROOF_CURRENCY ?? "NGN";
70
+ const syntheticReferences = process.env.BACHSPROOF_USE_SYNTHETIC_REFERENCES === "true";
71
+
72
+ export const tests = [
73
+ // Same successful payment twice in sequence: tests idempotency.
74
+ { name: "sequential duplicate webhook", scenario: "sequential-duplicate-webhook", amountMinor, currency, syntheticReferences },
75
+
76
+ // Same successful payment concurrently: tests duplicate-credit races.
77
+ { name: "concurrent duplicate credit", scenario: "concurrent-duplicate-credit", concurrency: 3, amountMinor, currency, syntheticReferences },
78
+
79
+ // Distinct payments concurrently: tests cross-payment interference.
80
+ { name: "concurrent unique payments", scenario: "concurrent-unique-payments", amountMinor, currency, syntheticReferences },
81
+
82
+ // checkout.completed plus collection.succeeded for one payment.
83
+ { name: "cross-event duplicate payment", scenario: "cross-event-duplicate-payment", amountMinor, currency, syntheticReferences },
84
+
85
+ // Newer success followed by older expiry: tests state ordering.
86
+ { name: "out-of-order events", scenario: "out-of-order-events", amountMinor, currency, syntheticReferences },
87
+
88
+ // Expiry followed by delayed success: tests eventual payment confirmation.
89
+ { name: "delayed payment confirmation", scenario: "delayed-payment-confirmation", delayMs: 50, amountMinor, currency, syntheticReferences },
90
+
91
+ // Completed checkout without a collected payment: must not credit.
92
+ { name: "incomplete checkout", scenario: "incomplete-checkout", amountMinor, currency, syntheticReferences },
93
+
94
+ // Expired checkout: must not credit.
95
+ { name: "expired checkout", scenario: "expired-checkout", amountMinor, currency, syntheticReferences },
96
+
97
+ // Changed body after signing: normally expects a 4xx rejection.
98
+ { name: "tampered webhook", scenario: "tampered-webhook", expectedStatus: "4xx", amountMinor, currency, syntheticReferences },
99
+
100
+ // Invalid signature: normally expects a 4xx rejection.
101
+ { name: "invalid webhook signature", scenario: "invalid-webhook-signature", expectedStatus: "4xx", amountMinor, currency, syntheticReferences },
102
+
103
+ // Malformed JSON: normally expects a 4xx rejection.
104
+ { name: "malformed webhook", scenario: "malformed-webhook", expectedStatus: "4xx", amountMinor, currency, syntheticReferences },
105
+
106
+ // Successful-looking event with the wrong amount: must not credit.
107
+ { name: "incorrect payment amount", scenario: "incorrect-payment-amount", amountMinor, currency, syntheticReferences },
108
+
109
+ // Successful-looking event with the wrong currency: must not credit.
110
+ { name: "incorrect payment currency", scenario: "incorrect-payment-currency", amountMinor, currency, syntheticReferences },
111
+
112
+ // Underpaid collection: must not credit before the shortfall is paid.
113
+ { name: "underpaid payment", scenario: "underpaid-payment", amountMinor, currency, syntheticReferences },
114
+
115
+ // Failed collection: must not credit.
116
+ { name: "failed payment", scenario: "failed-payment", amountMinor, currency, syntheticReferences }
117
+ ];
118
+ `;
119
+ var setupTemplate = `/**
120
+ * Create isolated application payment records for BachsProof.
121
+ *
122
+ * This callback is optional when tests provide real references directly. It is
123
+ * recommended for repeatedly running the complete suite.
124
+ *
125
+ * BachsProof calls it only for selected scenarios that need a reference. Every
126
+ * call must create a fresh test payment or order and return its reference.
127
+ * It must not charge a card, call a live provider, or move real money.
128
+ *
129
+ * Context: scenario, amountMinor, currency, paymentIndex, paymentCount.
130
+ *
131
+ * Use an existing isolated test API, application service, ORM, or seed helper.
132
+ */
133
+ export async function createPayment(context) {
134
+ throw new Error(
135
+ "Implement createPayment in tests/bachsproof.setup.mjs. " +
136
+ "Create an isolated test payment and return its fresh reference for " +
137
+ context.scenario + " (" + (context.paymentIndex + 1) + " of " +
138
+ context.paymentCount + ")."
139
+ );
140
+
141
+ // Example:
142
+ // const payment = await testSupport.createPayment({
143
+ // scenario: context.scenario,
144
+ // amountMinor: context.amountMinor,
145
+ // currency: context.currency,
146
+ // paymentIndex: context.paymentIndex
147
+ // });
148
+ // return payment.reference;
149
+ }
150
+ `;
151
+ var verifierTemplate = `/**
152
+ * Read committed financial state for BachsProof.
153
+ *
154
+ * HTTP 200 only proves that the webhook route acknowledged a request. This
155
+ * callback must read the payment and actual credit or ledger records.
156
+ * Do not return hardcoded expected values.
157
+ *
158
+ * Return reference, creditCount, creditedAmountMinor, currency, and optional
159
+ * status, pending, and ledgerEntries fields.
160
+ */
161
+ export async function verify(reference, context) {
162
+ throw new Error(
163
+ "Implement verify in tests/bachsproof.verify.mjs by reading committed " +
164
+ "financial records for " + reference + " before enabling it."
165
+ );
166
+
167
+ // Example:
168
+ // const state = await testSupport.readCommittedFinancialState(reference);
169
+ // return {
170
+ // reference,
171
+ // creditCount: state.credits.length,
172
+ // creditedAmountMinor: state.credits.reduce(
173
+ // (total, credit) => total + credit.amountMinor,
174
+ // 0
175
+ // ),
176
+ // currency: state.currency,
177
+ // status: state.status,
178
+ // pending: state.pending,
179
+ // ledgerEntries: state.credits
180
+ // };
181
+ }
182
+ `;
183
+ async function exists(path) {
184
+ try {
185
+ await access(path, constants.F_OK);
186
+ return true;
187
+ } catch {
188
+ return false;
189
+ }
190
+ }
191
+ async function initProject(directory = process.cwd(), force = false) {
192
+ const root = resolve(directory);
193
+ const configPath = join(root, "bachsproof.config.mjs");
194
+ const testDirectory = join(root, "tests");
195
+ const testPath = join(testDirectory, "bachsproof.test.mjs");
196
+ const setupPath = join(testDirectory, "bachsproof.setup.mjs");
197
+ const verifierPath = join(testDirectory, "bachsproof.verify.mjs");
198
+ const paths = [configPath, testPath, setupPath, verifierPath];
199
+ if (!force) {
200
+ const existing = [];
201
+ for (const path of paths) if (await exists(path)) existing.push(path);
202
+ if (existing.length > 0) {
203
+ throw new Error("Refusing to overwrite existing BachsProof files: " + existing.join(", ") + ". Use --force to replace them.");
204
+ }
205
+ }
206
+ await mkdir(testDirectory, { recursive: true });
207
+ await writeFile(configPath, configTemplate, "utf8");
208
+ await writeFile(testPath, testTemplate, "utf8");
209
+ await writeFile(setupPath, setupTemplate, "utf8");
210
+ await writeFile(verifierPath, verifierTemplate, "utf8");
211
+ return paths;
212
+ }
213
+ function assertConfig(value) {
214
+ if (!value || typeof value !== "object") throw new Error("BachsProof config must export a default object");
215
+ const config = value;
216
+ if (!config.provider || typeof config.provider !== "object") throw new Error("BachsProof config requires a provider adapter");
217
+ if (!config.target || typeof config.target !== "object" || typeof config.target.baseUrl !== "string" || typeof config.target.webhookPath !== "string") {
218
+ throw new Error("BachsProof config requires target.baseUrl and target.webhookPath");
219
+ }
220
+ if (!Array.isArray(config.tests) || config.tests.length === 0) throw new Error("BachsProof config requires at least one test");
221
+ }
222
+ async function loadConfig(configPath = "bachsproof.config.mjs") {
223
+ const absolutePath = resolve(process.cwd(), configPath);
224
+ const jiti = createJiti(absolutePath, { interopDefault: true });
225
+ const loaded = await jiti.import(absolutePath, { default: true });
226
+ assertConfig(loaded);
227
+ return loaded;
228
+ }
229
+ function withBachsSigning(provider, config) {
230
+ if (!config.signing) return provider;
231
+ if (config.signing.type !== "bachs") throw new Error(`Unsupported signing type ${String(config.signing.type)}`);
232
+ if (!config.signing.secret) throw new Error("Bachs signing is configured but its secret is empty");
233
+ return {
234
+ ...provider,
235
+ headers(event) {
236
+ const rawBody = provider.serialize(event);
237
+ return {
238
+ ...provider.headers?.(event) ?? {},
239
+ ...signBachsWebhook(rawBody, config.signing?.secret ?? "", config.signing?.timestamp)
240
+ };
241
+ },
242
+ headersForBody(event, body) {
243
+ return {
244
+ ...provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {},
245
+ ...signBachsWebhook(body, config.signing?.secret ?? "", config.signing?.timestamp)
246
+ };
247
+ }
248
+ };
249
+ }
250
+ async function runConfig(config, options = {}) {
251
+ const tests = options.testName ? config.tests.filter((test) => test.name === options.testName) : config.tests;
252
+ if (tests.length === 0) throw new Error(options.testName ? `No BachsProof test named ${options.testName}` : "BachsProof config contains no tests");
253
+ if (config.requireFinancialVerification && !config.verify) {
254
+ throw new Error("Financial verification is required, but the config has no verify callback");
255
+ }
256
+ const provider = withBachsSigning(config.provider, config);
257
+ const results = [];
258
+ const usedReferences = /* @__PURE__ */ new Set();
259
+ for (const test of tests) {
260
+ const { name, ...runOptions } = test;
261
+ const normalizedRunOptions = {
262
+ ...runOptions,
263
+ ...runOptions.reference !== void 0 ? { reference: typeof runOptions.reference === "string" ? runOptions.reference.trim() : runOptions.reference } : {},
264
+ ...runOptions.references !== void 0 ? { references: runOptions.references.map((reference) => typeof reference === "string" ? reference.trim() : reference) } : {}
265
+ };
266
+ const explicitReferences = normalizedRunOptions.scenario === "concurrent-unique-payments" ? normalizedRunOptions.references ?? [] : normalizedRunOptions.reference ? [normalizedRunOptions.reference] : [];
267
+ const normalizedExplicitReferences = explicitReferences.map((reference) => typeof reference === "string" ? reference.trim() : reference);
268
+ const conflictingReference = normalizedExplicitReferences.find((reference) => typeof reference === "string" && usedReferences.has(reference));
269
+ let preparationFailure;
270
+ if (conflictingReference) {
271
+ preparationFailure = `Payment preparation failed for ${runOptions.scenario}: reference ${conflictingReference} is already assigned to another selected scenario`;
272
+ } else {
273
+ for (const reference of normalizedExplicitReferences) {
274
+ if (typeof reference === "string" && reference.trim().length > 0) usedReferences.add(reference.trim());
275
+ }
276
+ }
277
+ const createPayment = preparationFailure ? async () => {
278
+ throw new Error(preparationFailure);
279
+ } : config.createPayment ? async (context) => {
280
+ const reference = await config.createPayment?.(context);
281
+ if (typeof reference !== "string" || reference.trim().length === 0) return reference;
282
+ const normalized = reference.trim();
283
+ if (usedReferences.has(normalized)) {
284
+ throw new Error(`reference ${normalized} is already assigned to another selected scenario`);
285
+ }
286
+ usedReferences.add(normalized);
287
+ return normalized;
288
+ } : void 0;
289
+ const runner = new BachsProof({
290
+ provider,
291
+ target: config.target,
292
+ createPayment,
293
+ verify: config.verify,
294
+ financialVerification: config.financialVerification,
295
+ checkpoint: config.checkpoint
296
+ });
297
+ const input = preparationFailure ? { ...normalizedRunOptions, reference: void 0, references: void 0, syntheticReferences: false } : normalizedRunOptions;
298
+ const result = await runner.run(input);
299
+ if (config.requireFinancialVerification && !result.report.financiallyVerified) {
300
+ result.report.errors.push("Financial verification was required but did not run");
301
+ result.passed = false;
302
+ }
303
+ results.push({ name, result });
304
+ }
305
+ return results;
306
+ }
307
+ function summarizeRuns(results) {
308
+ const durationMs = results.reduce((total, { result }) => {
309
+ if (!result.report.completedAt) return total;
310
+ return total + Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt));
311
+ }, 0);
312
+ return {
313
+ total: results.length,
314
+ passed: results.filter(({ result }) => result.passed).length,
315
+ failed: results.filter(({ result }) => !result.passed).length,
316
+ financiallyVerified: results.filter(({ result }) => result.report.financiallyVerified).length,
317
+ financiallyUnverified: results.filter(({ result }) => !result.report.financiallyVerified).length,
318
+ financialViolations: results.reduce((total, { result }) => total + (result.report.verification?.violations.length ?? 0), 0),
319
+ durationMs
320
+ };
321
+ }
322
+
323
+ export { defineConfig, initProject, loadConfig, runConfig, summarizeRuns };
324
+ //# sourceMappingURL=index.js.map
325
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config.ts","../src/init.ts","../src/runner.ts"],"names":["resolve"],"mappings":";;;;;;;;;;AAIO,SAAS,aAA0C,MAAA,EAA4D;AACpH,EAAA,OAAO,MAAA;AACT;ACFA,IAAM,cAAA,GAAiB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AA4CvB,IAAM,YAAA,GAAe,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA,CAAA;AA+DrB,IAAM,aAAA,GAAgB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAiCtB,IAAM,gBAAA,GAAm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Aa,OAAA,CAAQ,MAAA,CAAO,CAAC,KAAA,EAAO,EAAE,QAAO,KAAM;AACvD,IAAA,IAAI,CAAC,MAAA,CAAO,MAAA,CAAO,WAAA,EAAa,OAAO,KAAA;AACvC,IAAA,OAAO,KAAA,GAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,KAAK,KAAA,CAAM,MAAA,CAAO,MAAA,CAAO,WAAW,IAAI,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,MAAA,CAAO,SAAS,CAAC,CAAA;AAAA,EACxG,GAAG,CAAC,CAAA;AACJ,EAAA,OAAO;AAAA,IACL,OAAO,OAAA,CAAQ,MAAA;AAAA,IACf,MAAA,EAAQ,QAAQ,MAAA,CAAO,CAAC,EAAE,MAAA,EAAO,KAAM,MAAA,CAAO,MAAM,CAAA,CAAE,MAAA;AAAA,IACtD,MAAA,EAAQ,OAAA,CAAQ,MAAA,CAAO,CAAC,EAAE,QAAO,KAAM,CAAC,MAAA,CAAO,MAAM,CAAA,CAAE,MAAA;AAAA,IACvD,mBAAA,EAAqB,OAAA,CAAQ,MAAA,CAAO,CAAC,EAAE,QAAO,KAAM,MAAA,CAAO,MAAA,CAAO,mBAAmB,CAAA,CAAE,MAAA;AAAA,IACvF,qBAAA,EAAuB,OAAA,CAAQ,MAAA,CAAO,CAAC,EAAE,MAAA,EAAO,KAAM,CAAC,MAAA,CAAO,MAAA,CAAO,mBAAmB,CAAA,CAAE,MAAA;AAAA,IAC1F,mBAAA,EAAqB,OAAA,CAAQ,MAAA,CAAO,CAAC,OAAO,EAAE,MAAA,EAAO,KAAM,KAAA,IAAS,OAAO,MAAA,CAAO,YAAA,EAAc,UAAA,CAAW,MAAA,IAAU,IAAI,CAAC,CAAA;AAAA,IAC1H;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { PaymentEvent } from \"@bachsproof/core\";\nimport type { BachsProofConfig } from \"./types.js\";\n\n/** Type helper for bachsproof.config.mjs and bachsproof.config.ts files. */\nexport function defineConfig<TEvent extends PaymentEvent>(config: BachsProofConfig<TEvent>): BachsProofConfig<TEvent> {\n return config;\n}\n","import { access, mkdir, writeFile } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nconst configTemplate = `/**\n * BachsProof test configuration.\n *\n * Follow the two application-specific steps:\n * 1. createPayment prepares a fresh test payment or order;\n * 2. verify reads the committed payment and ledger state.\n *\n * Both helpers are test-only. BachsProof does not add routes or modify the\n * production application.\n */\nimport { bachsAdapter } from \"@bachsproof/cli\";\nimport { tests } from \"./tests/bachsproof.test.mjs\";\n\nconst provider = bachsAdapter({ mode: \"mock\" });\nconst target = {\n baseUrl: process.env.BACHSPROOF_TARGET_URL ?? \"http://127.0.0.1:3000\",\n webhookPath: process.env.BACHSPROOF_WEBHOOK_PATH ?? \"/webhooks/bachs\"\n};\n\nconst signingSecret = process.env.BACHS_WEBHOOK_SECRET;\nconst signing = signingSecret ? { type: \"bachs\", secret: signingSecret } : undefined;\n\n// Uncomment after implementing tests/bachsproof.setup.mjs.\n// import { createPayment } from \"./tests/bachsproof.setup.mjs\";\n\n// Uncomment after implementing tests/bachsproof.verify.mjs.\n// import { verify } from \"./tests/bachsproof.verify.mjs\";\n\nexport default {\n provider,\n target,\n ...(signing ? { signing } : {}),\n // createPayment,\n // verify,\n // requireFinancialVerification: true,\n // financialVerification: {\n // completionDeadlineMs: 10_000,\n // pollIntervalMs: 25,\n // negativeObservationWindowMs: 250\n // },\n tests\n};\n`;\n\nconst testTemplate = `/**\n * BachsProof scenarios.\n *\n * Real application references are the default. Implement createPayment in\n * bachsproof.setup.mjs to create fresh test records automatically, or put an\n * explicit reference on a selected test. Synthetic references are only for\n * isolated fixture tests.\n *\n * Run one: pnpm exec bachsproof test --name \"sequential duplicate webhook\"\n * Run all: pnpm exec bachsproof test\n */\nconst amountMinor = Number(process.env.BACHSPROOF_AMOUNT_MINOR ?? 5_000_000);\nconst currency = process.env.BACHSPROOF_CURRENCY ?? \"NGN\";\nconst syntheticReferences = process.env.BACHSPROOF_USE_SYNTHETIC_REFERENCES === \"true\";\n\nexport const tests = [\n // Same successful payment twice in sequence: tests idempotency.\n { name: \"sequential duplicate webhook\", scenario: \"sequential-duplicate-webhook\", amountMinor, currency, syntheticReferences },\n\n // Same successful payment concurrently: tests duplicate-credit races.\n { name: \"concurrent duplicate credit\", scenario: \"concurrent-duplicate-credit\", concurrency: 3, amountMinor, currency, syntheticReferences },\n\n // Distinct payments concurrently: tests cross-payment interference.\n { name: \"concurrent unique payments\", scenario: \"concurrent-unique-payments\", amountMinor, currency, syntheticReferences },\n\n // checkout.completed plus collection.succeeded for one payment.\n { name: \"cross-event duplicate payment\", scenario: \"cross-event-duplicate-payment\", amountMinor, currency, syntheticReferences },\n\n // Newer success followed by older expiry: tests state ordering.\n { name: \"out-of-order events\", scenario: \"out-of-order-events\", amountMinor, currency, syntheticReferences },\n\n // Expiry followed by delayed success: tests eventual payment confirmation.\n { name: \"delayed payment confirmation\", scenario: \"delayed-payment-confirmation\", delayMs: 50, amountMinor, currency, syntheticReferences },\n\n // Completed checkout without a collected payment: must not credit.\n { name: \"incomplete checkout\", scenario: \"incomplete-checkout\", amountMinor, currency, syntheticReferences },\n\n // Expired checkout: must not credit.\n { name: \"expired checkout\", scenario: \"expired-checkout\", amountMinor, currency, syntheticReferences },\n\n // Changed body after signing: normally expects a 4xx rejection.\n { name: \"tampered webhook\", scenario: \"tampered-webhook\", expectedStatus: \"4xx\", amountMinor, currency, syntheticReferences },\n\n // Invalid signature: normally expects a 4xx rejection.\n { name: \"invalid webhook signature\", scenario: \"invalid-webhook-signature\", expectedStatus: \"4xx\", amountMinor, currency, syntheticReferences },\n\n // Malformed JSON: normally expects a 4xx rejection.\n { name: \"malformed webhook\", scenario: \"malformed-webhook\", expectedStatus: \"4xx\", amountMinor, currency, syntheticReferences },\n\n // Successful-looking event with the wrong amount: must not credit.\n { name: \"incorrect payment amount\", scenario: \"incorrect-payment-amount\", amountMinor, currency, syntheticReferences },\n\n // Successful-looking event with the wrong currency: must not credit.\n { name: \"incorrect payment currency\", scenario: \"incorrect-payment-currency\", amountMinor, currency, syntheticReferences },\n\n // Underpaid collection: must not credit before the shortfall is paid.\n { name: \"underpaid payment\", scenario: \"underpaid-payment\", amountMinor, currency, syntheticReferences },\n\n // Failed collection: must not credit.\n { name: \"failed payment\", scenario: \"failed-payment\", amountMinor, currency, syntheticReferences }\n];\n`;\n\nconst setupTemplate = `/**\n * Create isolated application payment records for BachsProof.\n *\n * This callback is optional when tests provide real references directly. It is\n * recommended for repeatedly running the complete suite.\n *\n * BachsProof calls it only for selected scenarios that need a reference. Every\n * call must create a fresh test payment or order and return its reference.\n * It must not charge a card, call a live provider, or move real money.\n *\n * Context: scenario, amountMinor, currency, paymentIndex, paymentCount.\n *\n * Use an existing isolated test API, application service, ORM, or seed helper.\n */\nexport async function createPayment(context) {\n throw new Error(\n \"Implement createPayment in tests/bachsproof.setup.mjs. \" +\n \"Create an isolated test payment and return its fresh reference for \" +\n context.scenario + \" (\" + (context.paymentIndex + 1) + \" of \" +\n context.paymentCount + \").\"\n );\n\n // Example:\n // const payment = await testSupport.createPayment({\n // scenario: context.scenario,\n // amountMinor: context.amountMinor,\n // currency: context.currency,\n // paymentIndex: context.paymentIndex\n // });\n // return payment.reference;\n}\n`;\n\nconst verifierTemplate = `/**\n * Read committed financial state for BachsProof.\n *\n * HTTP 200 only proves that the webhook route acknowledged a request. This\n * callback must read the payment and actual credit or ledger records.\n * Do not return hardcoded expected values.\n *\n * Return reference, creditCount, creditedAmountMinor, currency, and optional\n * status, pending, and ledgerEntries fields.\n */\nexport async function verify(reference, context) {\n throw new Error(\n \"Implement verify in tests/bachsproof.verify.mjs by reading committed \" +\n \"financial records for \" + reference + \" before enabling it.\"\n );\n\n // Example:\n // const state = await testSupport.readCommittedFinancialState(reference);\n // return {\n // reference,\n // creditCount: state.credits.length,\n // creditedAmountMinor: state.credits.reduce(\n // (total, credit) => total + credit.amountMinor,\n // 0\n // ),\n // currency: state.currency,\n // status: state.status,\n // pending: state.pending,\n // ledgerEntries: state.credits\n // };\n}\n`;\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\nexport async function initProject(directory = process.cwd(), force = false): Promise<string[]> {\n const root = resolve(directory);\n const configPath = join(root, \"bachsproof.config.mjs\");\n const testDirectory = join(root, \"tests\");\n const testPath = join(testDirectory, \"bachsproof.test.mjs\");\n const setupPath = join(testDirectory, \"bachsproof.setup.mjs\");\n const verifierPath = join(testDirectory, \"bachsproof.verify.mjs\");\n const paths = [configPath, testPath, setupPath, verifierPath];\n if (!force) {\n const existing = [];\n for (const path of paths) if (await exists(path)) existing.push(path);\n if (existing.length > 0) {\n throw new Error(\"Refusing to overwrite existing BachsProof files: \" + existing.join(\", \") + \". Use --force to replace them.\");\n }\n }\n await mkdir(testDirectory, { recursive: true });\n await writeFile(configPath, configTemplate, \"utf8\");\n await writeFile(testPath, testTemplate, \"utf8\");\n await writeFile(setupPath, setupTemplate, \"utf8\");\n await writeFile(verifierPath, verifierTemplate, \"utf8\");\n return paths;\n}\n","import { createJiti } from \"jiti\";\nimport { resolve } from \"node:path\";\nimport { BachsProof, type PaymentEvent, type PaymentReferenceCreator, type ProviderAdapter } from \"@bachsproof/core\";\nimport { signBachsWebhook } from \"@bachsproof/bachs\";\nimport type { BachsProofCliRun, BachsProofConfig, BachsProofSummary, RunConfigOptions } from \"./types.js\";\n\nfunction assertConfig(value: unknown): asserts value is BachsProofConfig {\n if (!value || typeof value !== \"object\") throw new Error(\"BachsProof config must export a default object\");\n const config = value as Partial<BachsProofConfig>;\n if (!config.provider || typeof config.provider !== \"object\") throw new Error(\"BachsProof config requires a provider adapter\");\n if (!config.target || typeof config.target !== \"object\" || typeof config.target.baseUrl !== \"string\" || typeof config.target.webhookPath !== \"string\") {\n throw new Error(\"BachsProof config requires target.baseUrl and target.webhookPath\");\n }\n if (!Array.isArray(config.tests) || config.tests.length === 0) throw new Error(\"BachsProof config requires at least one test\");\n}\n\n/** Load .mjs, .js, .cjs, or TypeScript config without requiring a repo-local loader. */\nexport async function loadConfig(configPath = \"bachsproof.config.mjs\"): Promise<BachsProofConfig> {\n const absolutePath = resolve(process.cwd(), configPath);\n const jiti = createJiti(absolutePath, { interopDefault: true });\n const loaded = await jiti.import(absolutePath, { default: true }) as unknown;\n assertConfig(loaded);\n return loaded;\n}\n\nfunction withBachsSigning<TEvent extends PaymentEvent>(provider: ProviderAdapter<TEvent>, config: BachsProofConfig<TEvent>): ProviderAdapter<TEvent> {\n if (!config.signing) return provider;\n if (config.signing.type !== \"bachs\") throw new Error(`Unsupported signing type ${String(config.signing.type)}`);\n if (!config.signing.secret) throw new Error(\"Bachs signing is configured but its secret is empty\");\n return {\n ...provider,\n headers(event) {\n const rawBody = provider.serialize(event);\n return {\n ...(provider.headers?.(event) ?? {}),\n ...signBachsWebhook(rawBody, config.signing?.secret ?? \"\", config.signing?.timestamp)\n };\n },\n headersForBody(event, body) {\n return {\n ...(provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {}),\n ...signBachsWebhook(body, config.signing?.secret ?? \"\", config.signing?.timestamp)\n };\n }\n };\n}\n\nexport async function runConfig(config: BachsProofConfig, options: RunConfigOptions = {}): Promise<BachsProofCliRun[]> {\n const tests = options.testName ? config.tests.filter((test) => test.name === options.testName) : config.tests;\n if (tests.length === 0) throw new Error(options.testName ? `No BachsProof test named ${options.testName}` : \"BachsProof config contains no tests\");\n if (config.requireFinancialVerification && !config.verify) {\n throw new Error(\"Financial verification is required, but the config has no verify callback\");\n }\n\n const provider = withBachsSigning(config.provider, config);\n const results: BachsProofCliRun[] = [];\n const usedReferences = new Set<string>();\n for (const test of tests) {\n const { name, ...runOptions } = test;\n const normalizedRunOptions = {\n ...runOptions,\n ...(runOptions.reference !== undefined ? { reference: typeof runOptions.reference === \"string\" ? runOptions.reference.trim() : runOptions.reference } : {}),\n ...(runOptions.references !== undefined ? { references: runOptions.references.map((reference) => typeof reference === \"string\" ? reference.trim() : reference) } : {})\n };\n const explicitReferences = normalizedRunOptions.scenario === \"concurrent-unique-payments\"\n ? normalizedRunOptions.references ?? []\n : normalizedRunOptions.reference ? [normalizedRunOptions.reference] : [];\n const normalizedExplicitReferences = explicitReferences.map((reference) => typeof reference === \"string\" ? reference.trim() : reference);\n const conflictingReference = normalizedExplicitReferences.find((reference) => typeof reference === \"string\" && usedReferences.has(reference));\n let preparationFailure: string | undefined;\n if (conflictingReference) {\n preparationFailure = `Payment preparation failed for ${runOptions.scenario}: reference ${conflictingReference} is already assigned to another selected scenario`;\n } else {\n for (const reference of normalizedExplicitReferences) {\n if (typeof reference === \"string\" && reference.trim().length > 0) usedReferences.add(reference.trim());\n }\n }\n const createPayment: PaymentReferenceCreator | undefined = preparationFailure\n ? async () => { throw new Error(preparationFailure); }\n : config.createPayment\n ? async (context) => {\n const reference = await config.createPayment?.(context);\n if (typeof reference !== \"string\" || reference.trim().length === 0) return reference as string;\n const normalized = reference.trim();\n if (usedReferences.has(normalized)) {\n throw new Error(`reference ${normalized} is already assigned to another selected scenario`);\n }\n usedReferences.add(normalized);\n return normalized;\n }\n : undefined;\n const runner = new BachsProof({\n provider,\n target: config.target,\n createPayment,\n verify: config.verify,\n financialVerification: config.financialVerification,\n checkpoint: config.checkpoint\n });\n const input = preparationFailure\n ? { ...normalizedRunOptions, reference: undefined, references: undefined, syntheticReferences: false }\n : normalizedRunOptions;\n const result = await runner.run(input);\n if (config.requireFinancialVerification && !result.report.financiallyVerified) {\n result.report.errors.push(\"Financial verification was required but did not run\");\n result.passed = false;\n }\n results.push({ name, result });\n }\n return results;\n}\n\nexport function summarizeRuns(results: BachsProofCliRun[]): BachsProofSummary {\n const durationMs = results.reduce((total, { result }) => {\n if (!result.report.completedAt) return total;\n return total + Math.max(0, Date.parse(result.report.completedAt) - Date.parse(result.report.startedAt));\n }, 0);\n return {\n total: results.length,\n passed: results.filter(({ result }) => result.passed).length,\n failed: results.filter(({ result }) => !result.passed).length,\n financiallyVerified: results.filter(({ result }) => result.report.financiallyVerified).length,\n financiallyUnverified: results.filter(({ result }) => !result.report.financiallyVerified).length,\n financialViolations: results.reduce((total, { result }) => total + (result.report.verification?.violations.length ?? 0), 0),\n durationMs\n };\n}\n\n"]}
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@bachsproof/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.1.0",
4
+ "description": "CLI for BachsProof financial correctness testing",
5
+ "keywords": [
6
+ "payments",
7
+ "payment-testing",
8
+ "webhooks",
9
+ "concurrency",
10
+ "cli",
11
+ "typescript"
12
+ ],
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/therealEmma/BachsProof.git",
17
+ "directory": "packages/cli"
18
+ },
19
+ "homepage": "https://github.com/therealEmma/BachsProof#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/therealEmma/BachsProof/issues"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "type": "module",
27
+ "bin": {
28
+ "bachsproof": "./dist/cli.js"
29
+ },
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js"
34
+ }
35
+ },
36
+ "main": "./dist/index.js",
37
+ "types": "./dist/index.d.ts",
38
+ "files": [
39
+ "dist",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "engines": {
44
+ "node": ">=22"
45
+ },
46
+ "dependencies": {
47
+ "jiti": "^2.7.0",
48
+ "@bachsproof/core": "1.1.0",
49
+ "@bachsproof/bachs": "1.1.0"
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "^22.10.0",
53
+ "tsup": "^8.3.5",
54
+ "typescript": "^5.7.2"
55
+ },
56
+ "scripts": {
57
+ "build": "tsup"
58
+ }
6
59
  }