@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/README.md +21 -42
- package/dist/cli.js +215 -321
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +25 -29
- package/dist/index.js +150 -248
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,184 +1,78 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
export { bachsAdapter, signBachsWebhook } from '@bachsproof/bachs';
|
|
4
|
-
import { mkdir, writeFile, access } from 'fs/promises';
|
|
2
|
+
import { writeFile, access } from 'fs/promises';
|
|
5
3
|
import { constants } from 'fs';
|
|
6
|
-
import {
|
|
4
|
+
import { join, resolve } from 'path';
|
|
7
5
|
import { createJiti } from 'jiti';
|
|
8
|
-
import { BachsProof } from '@bachsproof/core';
|
|
6
|
+
import { BachsProof, SUPPORTED_SCENARIOS } from '@bachsproof/core';
|
|
7
|
+
import { bachsAdapter, signBachsWebhook } from '@bachsproof/bachs';
|
|
9
8
|
|
|
10
9
|
// src/config.ts
|
|
11
10
|
function defineConfig(config) {
|
|
12
11
|
return config;
|
|
13
12
|
}
|
|
14
13
|
var configTemplate = `/**
|
|
15
|
-
* BachsProof
|
|
14
|
+
* BachsProof v2 configuration.
|
|
16
15
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
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.
|
|
16
|
+
* Use only an isolated application, test database, queue, and webhook secret.
|
|
17
|
+
* BachsProof creates local simulated events. It never calls Bachs or moves money.
|
|
132
18
|
*/
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
19
|
+
import { defineConfig } from "@bachsproof/cli";
|
|
20
|
+
|
|
21
|
+
export default defineConfig({
|
|
22
|
+
// The complete URL of your isolated application's Bachs webhook route.
|
|
23
|
+
webhookUrl: process.env.BACHSPROOF_WEBHOOK_URL ?? "http://127.0.0.1:3000/webhooks/bachs",
|
|
24
|
+
|
|
25
|
+
// Use a secret that belongs only to your test application.
|
|
26
|
+
secret: process.env.BACHS_WEBHOOK_SECRET ?? "",
|
|
27
|
+
|
|
28
|
+
// 500,000 NGN minor units means NGN 5,000.00.
|
|
29
|
+
amountMinor: 500_000,
|
|
30
|
+
currency: "NGN",
|
|
31
|
+
|
|
32
|
+
// Before BachsProof sends a webhook, create a fresh payment record and
|
|
33
|
+
// return its reference. Replace the example error with your test helper.
|
|
34
|
+
async createPayment({ scenario, amountMinor, currency, paymentIndex, paymentCount }) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
"Implement createPayment in bachsproof.config.mjs. " +
|
|
37
|
+
"Create an isolated test payment and return its non-empty reference for " +
|
|
38
|
+
scenario + " (" + (paymentIndex + 1) + " of " + paymentCount + ")."
|
|
39
|
+
);
|
|
40
|
+
// Example:
|
|
41
|
+
// const payment = await testApplication.createPayment({ amountMinor, currency });
|
|
42
|
+
// return payment.reference;
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
// Read the application's committed payment and ledger records. Do not return
|
|
46
|
+
// the expected values from this file; return what the database contains.
|
|
47
|
+
async verify(reference) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
"Implement verify in bachsproof.config.mjs by reading committed " +
|
|
50
|
+
"financial records for " + reference + "."
|
|
51
|
+
);
|
|
52
|
+
// Example result:
|
|
53
|
+
// return {
|
|
54
|
+
// reference,
|
|
55
|
+
// creditCount: credits.length,
|
|
56
|
+
// creditedAmountMinor: credits.reduce((sum, credit) => sum + credit.amountMinor, 0),
|
|
57
|
+
// currency: payment.currency,
|
|
58
|
+
// status: payment.status,
|
|
59
|
+
// pending: false,
|
|
60
|
+
// ledgerEntries: credits.map((credit) => ({
|
|
61
|
+
// id: String(credit.id),
|
|
62
|
+
// type: String(credit.type),
|
|
63
|
+
// amountMinor: credit.amountMinor,
|
|
64
|
+
// currency: credit.currency
|
|
65
|
+
// }))
|
|
66
|
+
// };
|
|
67
|
+
}
|
|
140
68
|
|
|
141
|
-
//
|
|
142
|
-
//
|
|
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
|
-
);
|
|
69
|
+
// Optional: run only selected scenario identifiers. Omit to run all eleven.
|
|
70
|
+
// scenarios: ["sequential-duplicate-webhook"],
|
|
166
71
|
|
|
167
|
-
//
|
|
168
|
-
//
|
|
169
|
-
//
|
|
170
|
-
|
|
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
|
-
}
|
|
72
|
+
// Optional: increase this only when your isolated application processes
|
|
73
|
+
// webhooks asynchronously. The default is 10 seconds.
|
|
74
|
+
// verificationTimeoutMs: 10_000
|
|
75
|
+
});
|
|
182
76
|
`;
|
|
183
77
|
async function exists(path) {
|
|
184
78
|
try {
|
|
@@ -189,35 +83,63 @@ async function exists(path) {
|
|
|
189
83
|
}
|
|
190
84
|
}
|
|
191
85
|
async function initProject(directory = process.cwd(), force = false) {
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
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
|
-
}
|
|
86
|
+
const configPath = join(resolve(directory), "bachsproof.config.mjs");
|
|
87
|
+
if (!force && await exists(configPath)) {
|
|
88
|
+
throw new Error(`Refusing to overwrite existing BachsProof file: ${configPath}. Use --force only when replacement is intentional.`);
|
|
205
89
|
}
|
|
206
|
-
await mkdir(testDirectory, { recursive: true });
|
|
207
90
|
await writeFile(configPath, configTemplate, "utf8");
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
91
|
+
return [configPath];
|
|
92
|
+
}
|
|
93
|
+
var SCENARIO_LABELS = {
|
|
94
|
+
"sequential-duplicate-webhook": "Sequential duplicate webhook",
|
|
95
|
+
"concurrent-duplicate-credit": "Concurrent duplicate credit",
|
|
96
|
+
"concurrent-unique-payments": "Concurrent unique payments",
|
|
97
|
+
"cross-event-duplicate-payment": "Cross-event duplicate payment",
|
|
98
|
+
"out-of-order-events": "Out-of-order events",
|
|
99
|
+
"incomplete-checkout": "Incomplete checkout",
|
|
100
|
+
"expired-checkout": "Expired checkout",
|
|
101
|
+
"incorrect-payment-amount": "Incorrect payment amount",
|
|
102
|
+
"incorrect-payment-currency": "Incorrect payment currency",
|
|
103
|
+
"underpaid-payment": "Underpaid payment",
|
|
104
|
+
"failed-payment": "Failed payment"
|
|
105
|
+
};
|
|
106
|
+
function scenarioLabel(scenario) {
|
|
107
|
+
return SCENARIO_LABELS[scenario];
|
|
212
108
|
}
|
|
213
109
|
function assertConfig(value) {
|
|
214
110
|
if (!value || typeof value !== "object") throw new Error("BachsProof config must export a default object");
|
|
215
111
|
const config = value;
|
|
216
|
-
if (
|
|
217
|
-
|
|
218
|
-
|
|
112
|
+
if (typeof config.webhookUrl !== "string" || config.webhookUrl.trim().length === 0) {
|
|
113
|
+
throw new Error("BachsProof config requires a complete webhookUrl");
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
const url = new URL(config.webhookUrl);
|
|
117
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("webhookUrl must use http or https");
|
|
118
|
+
} catch (error) {
|
|
119
|
+
throw new Error(`BachsProof config webhookUrl is invalid: ${error instanceof Error ? error.message : String(error)}`);
|
|
120
|
+
}
|
|
121
|
+
if (typeof config.secret !== "string" || config.secret.trim().length === 0) {
|
|
122
|
+
throw new Error("BachsProof config requires a non-empty test webhook secret");
|
|
123
|
+
}
|
|
124
|
+
if (!Number.isSafeInteger(config.amountMinor) || config.amountMinor < 0) {
|
|
125
|
+
throw new Error("BachsProof config amountMinor must be a non-negative safe integer");
|
|
126
|
+
}
|
|
127
|
+
if (typeof config.currency !== "string" || !/^[A-Z]{3}$/.test(config.currency)) {
|
|
128
|
+
throw new Error("BachsProof config currency must be a three-letter ISO currency code");
|
|
129
|
+
}
|
|
130
|
+
if (typeof config.createPayment !== "function") throw new Error("BachsProof config requires a createPayment callback");
|
|
131
|
+
if (typeof config.verify !== "function") throw new Error("BachsProof config requires a verify callback");
|
|
132
|
+
if (config.verificationTimeoutMs !== void 0 && (!Number.isSafeInteger(config.verificationTimeoutMs) || config.verificationTimeoutMs < 1)) {
|
|
133
|
+
throw new Error("BachsProof config verificationTimeoutMs must be a positive safe integer");
|
|
134
|
+
}
|
|
135
|
+
if (config.scenarios !== void 0) {
|
|
136
|
+
if (!Array.isArray(config.scenarios) || config.scenarios.length === 0) throw new Error("BachsProof config scenarios must contain at least one scenario");
|
|
137
|
+
for (const scenario of config.scenarios) {
|
|
138
|
+
if (!SUPPORTED_SCENARIOS.includes(scenario)) {
|
|
139
|
+
throw new Error(`Unknown BachsProof scenario: ${String(scenario)}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
219
142
|
}
|
|
220
|
-
if (!Array.isArray(config.tests) || config.tests.length === 0) throw new Error("BachsProof config requires at least one test");
|
|
221
143
|
}
|
|
222
144
|
async function loadConfig(configPath = "bachsproof.config.mjs") {
|
|
223
145
|
const absolutePath = resolve(process.cwd(), configPath);
|
|
@@ -226,81 +148,61 @@ async function loadConfig(configPath = "bachsproof.config.mjs") {
|
|
|
226
148
|
assertConfig(loaded);
|
|
227
149
|
return loaded;
|
|
228
150
|
}
|
|
229
|
-
function withBachsSigning(provider,
|
|
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");
|
|
151
|
+
function withBachsSigning(provider, secret) {
|
|
233
152
|
return {
|
|
234
153
|
...provider,
|
|
235
154
|
headers(event) {
|
|
236
|
-
const
|
|
155
|
+
const body = provider.serialize(event);
|
|
237
156
|
return {
|
|
238
157
|
...provider.headers?.(event) ?? {},
|
|
239
|
-
...signBachsWebhook(
|
|
158
|
+
...signBachsWebhook(body, secret)
|
|
240
159
|
};
|
|
241
160
|
},
|
|
242
161
|
headersForBody(event, body) {
|
|
243
162
|
return {
|
|
244
163
|
...provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {},
|
|
245
|
-
...signBachsWebhook(body,
|
|
164
|
+
...signBachsWebhook(body, secret)
|
|
246
165
|
};
|
|
247
166
|
}
|
|
248
167
|
};
|
|
249
168
|
}
|
|
169
|
+
function selectedScenarios(config, testName) {
|
|
170
|
+
const scenarios = config.scenarios ?? [...SUPPORTED_SCENARIOS];
|
|
171
|
+
if (!testName) return scenarios;
|
|
172
|
+
const selected = scenarios.find((scenario) => scenarioLabel(scenario) === testName || scenario === testName);
|
|
173
|
+
if (!selected) throw new Error(`Unknown BachsProof scenario or test name "${testName}". Use one of: ${scenarios.map(scenarioLabel).join(", ")}`);
|
|
174
|
+
return [selected];
|
|
175
|
+
}
|
|
250
176
|
async function runConfig(config, options = {}) {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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 = [];
|
|
177
|
+
assertConfig(config);
|
|
178
|
+
const scenarios = selectedScenarios(config, options.testName);
|
|
179
|
+
const provider = withBachsSigning(bachsAdapter({ mode: "mock" }), config.secret);
|
|
258
180
|
const usedReferences = /* @__PURE__ */ new Set();
|
|
259
|
-
|
|
260
|
-
const
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
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
|
-
}
|
|
181
|
+
const createPayment = async (context) => {
|
|
182
|
+
const reference = await config.createPayment(context);
|
|
183
|
+
if (typeof reference !== "string" || reference.trim().length === 0) return reference;
|
|
184
|
+
const normalized = reference.trim();
|
|
185
|
+
if (usedReferences.has(normalized)) {
|
|
186
|
+
throw new Error(`createPayment returned reference ${normalized}, which was already used by another selected scenario`);
|
|
276
187
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
const
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
verify: config.verify,
|
|
294
|
-
financialVerification: config.financialVerification,
|
|
295
|
-
checkpoint: config.checkpoint
|
|
188
|
+
usedReferences.add(normalized);
|
|
189
|
+
return normalized;
|
|
190
|
+
};
|
|
191
|
+
const runner = new BachsProof({
|
|
192
|
+
provider,
|
|
193
|
+
webhookUrl: config.webhookUrl,
|
|
194
|
+
createPayment,
|
|
195
|
+
verify: config.verify,
|
|
196
|
+
financialVerification: config.verificationTimeoutMs === void 0 ? void 0 : { completionDeadlineMs: config.verificationTimeoutMs }
|
|
197
|
+
});
|
|
198
|
+
const results = [];
|
|
199
|
+
for (const scenario of scenarios) {
|
|
200
|
+
const result = await runner.run({
|
|
201
|
+
scenario,
|
|
202
|
+
amountMinor: config.amountMinor,
|
|
203
|
+
currency: config.currency
|
|
296
204
|
});
|
|
297
|
-
|
|
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 });
|
|
205
|
+
results.push({ name: scenarioLabel(scenario), scenario, result });
|
|
304
206
|
}
|
|
305
207
|
return results;
|
|
306
208
|
}
|
|
@@ -320,6 +222,6 @@ function summarizeRuns(results) {
|
|
|
320
222
|
};
|
|
321
223
|
}
|
|
322
224
|
|
|
323
|
-
export { defineConfig, initProject, loadConfig, runConfig, summarizeRuns };
|
|
225
|
+
export { defineConfig, initProject, loadConfig, runConfig, scenarioLabel, summarizeRuns };
|
|
324
226
|
//# sourceMappingURL=index.js.map
|
|
325
227
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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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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"]}
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/init.ts","../src/runner.ts"],"names":["resolve"],"mappings":";;;;;;;;;AAIO,SAAS,aAAyD,MAAA,EAA4D;AACnI,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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAiEvB,eAAe,OAAO,IAAA,EAAgC;AACpD,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,CAAO,IAAA,EAAM,SAAA,CAAU,IAAI,CAAA;AACjC,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAGA,eAAsB,YAAY,SAAA,GAAY,OAAA,CAAQ,GAAA,EAAI,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AA;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 = PaymentEvent>(config: BachsProofConfig<TEvent>): BachsProofConfig<TEvent> {\n return config;\n}\n","import { access, writeFile } from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nconst configTemplate = `/**\n * BachsProof v2 configuration.\n *\n * Use only an isolated application, test database, queue, and webhook secret.\n * BachsProof creates local simulated events. It never calls Bachs or moves money.\n */\nimport { defineConfig } from \"@bachsproof/cli\";\n\nexport default defineConfig({\n // The complete URL of your isolated application's Bachs webhook route.\n webhookUrl: process.env.BACHSPROOF_WEBHOOK_URL ?? \"http://127.0.0.1:3000/webhooks/bachs\",\n\n // Use a secret that belongs only to your test application.\n secret: process.env.BACHS_WEBHOOK_SECRET ?? \"\",\n\n // 500,000 NGN minor units means NGN 5,000.00.\n amountMinor: 500_000,\n currency: \"NGN\",\n\n // Before BachsProof sends a webhook, create a fresh payment record and\n // return its reference. Replace the example error with your test helper.\n async createPayment({ scenario, amountMinor, currency, paymentIndex, paymentCount }) {\n throw new Error(\n \"Implement createPayment in bachsproof.config.mjs. \" +\n \"Create an isolated test payment and return its non-empty reference for \" +\n scenario + \" (\" + (paymentIndex + 1) + \" of \" + paymentCount + \").\"\n );\n // Example:\n // const payment = await testApplication.createPayment({ amountMinor, currency });\n // return payment.reference;\n },\n\n // Read the application's committed payment and ledger records. Do not return\n // the expected values from this file; return what the database contains.\n async verify(reference) {\n throw new Error(\n \"Implement verify in bachsproof.config.mjs by reading committed \" +\n \"financial records for \" + reference + \".\"\n );\n // Example result:\n // return {\n // reference,\n // creditCount: credits.length,\n // creditedAmountMinor: credits.reduce((sum, credit) => sum + credit.amountMinor, 0),\n // currency: payment.currency,\n // status: payment.status,\n // pending: false,\n // ledgerEntries: credits.map((credit) => ({\n // id: String(credit.id),\n // type: String(credit.type),\n // amountMinor: credit.amountMinor,\n // currency: credit.currency\n // }))\n // };\n }\n\n // Optional: run only selected scenario identifiers. Omit to run all eleven.\n // scenarios: [\"sequential-duplicate-webhook\"],\n\n // Optional: increase this only when your isolated application processes\n // webhooks asynchronously. The default is 10 seconds.\n // verificationTimeoutMs: 10_000\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}\n\n/** Create exactly one config file and never overwrite it accidentally. */\nexport async function initProject(directory = process.cwd(), force = false): Promise<string[]> {\n const configPath = join(resolve(directory), \"bachsproof.config.mjs\");\n if (!force && await exists(configPath)) {\n throw new Error(`Refusing to overwrite existing BachsProof file: ${configPath}. Use --force only when replacement is intentional.`);\n }\n await writeFile(configPath, configTemplate, \"utf8\");\n return [configPath];\n}\n","import { createJiti } from \"jiti\";\nimport { resolve } from \"node:path\";\nimport { BachsProof, SUPPORTED_SCENARIOS, type PaymentEvent, type PaymentReferenceCreator, type ProviderAdapter, type ScenarioName } from \"@bachsproof/core\";\nimport { bachsAdapter, signBachsWebhook } from \"@bachsproof/bachs\";\nimport type { BachsProofCliRun, BachsProofConfig, BachsProofSummary, RunConfigOptions } from \"./types.js\";\n\nconst SCENARIO_LABELS: Record<ScenarioName, string> = {\n \"sequential-duplicate-webhook\": \"Sequential duplicate webhook\",\n \"concurrent-duplicate-credit\": \"Concurrent duplicate credit\",\n \"concurrent-unique-payments\": \"Concurrent unique payments\",\n \"cross-event-duplicate-payment\": \"Cross-event duplicate payment\",\n \"out-of-order-events\": \"Out-of-order events\",\n \"incomplete-checkout\": \"Incomplete checkout\",\n \"expired-checkout\": \"Expired checkout\",\n \"incorrect-payment-amount\": \"Incorrect payment amount\",\n \"incorrect-payment-currency\": \"Incorrect payment currency\",\n \"underpaid-payment\": \"Underpaid payment\",\n \"failed-payment\": \"Failed payment\"\n};\n\nexport function scenarioLabel(scenario: ScenarioName): string {\n return SCENARIO_LABELS[scenario];\n}\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 (typeof config.webhookUrl !== \"string\" || config.webhookUrl.trim().length === 0) {\n throw new Error(\"BachsProof config requires a complete webhookUrl\");\n }\n try {\n const url = new URL(config.webhookUrl);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") throw new Error(\"webhookUrl must use http or https\");\n } catch (error) {\n throw new Error(`BachsProof config webhookUrl is invalid: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (typeof config.secret !== \"string\" || config.secret.trim().length === 0) {\n throw new Error(\"BachsProof config requires a non-empty test webhook secret\");\n }\n if (!Number.isSafeInteger(config.amountMinor) || (config.amountMinor as number) < 0) {\n throw new Error(\"BachsProof config amountMinor must be a non-negative safe integer\");\n }\n if (typeof config.currency !== \"string\" || !/^[A-Z]{3}$/.test(config.currency)) {\n throw new Error(\"BachsProof config currency must be a three-letter ISO currency code\");\n }\n if (typeof config.createPayment !== \"function\") throw new Error(\"BachsProof config requires a createPayment callback\");\n if (typeof config.verify !== \"function\") throw new Error(\"BachsProof config requires a verify callback\");\n if (config.verificationTimeoutMs !== undefined && (!Number.isSafeInteger(config.verificationTimeoutMs) || config.verificationTimeoutMs < 1)) {\n throw new Error(\"BachsProof config verificationTimeoutMs must be a positive safe integer\");\n }\n if (config.scenarios !== undefined) {\n if (!Array.isArray(config.scenarios) || config.scenarios.length === 0) throw new Error(\"BachsProof config scenarios must contain at least one scenario\");\n for (const scenario of config.scenarios) {\n if (!(SUPPORTED_SCENARIOS as readonly string[]).includes(scenario)) {\n throw new Error(`Unknown BachsProof scenario: ${String(scenario)}`);\n }\n }\n }\n}\n\n/** Load a JavaScript, MJS, CJS, or TypeScript config file. */\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(provider: ProviderAdapter, secret: string): ProviderAdapter {\n return {\n ...provider,\n headers(event) {\n const body = provider.serialize(event);\n return {\n ...(provider.headers?.(event) ?? {}),\n ...signBachsWebhook(body, secret)\n };\n },\n headersForBody(event, body) {\n return {\n ...(provider.headersForBody?.(event, body) ?? provider.headers?.(event) ?? {}),\n ...signBachsWebhook(body, secret)\n };\n }\n };\n}\n\nfunction selectedScenarios(config: BachsProofConfig, testName?: string): ScenarioName[] {\n const scenarios = config.scenarios ?? [...SUPPORTED_SCENARIOS];\n if (!testName) return scenarios;\n const selected = scenarios.find((scenario) => scenarioLabel(scenario) === testName || scenario === testName);\n if (!selected) throw new Error(`Unknown BachsProof scenario or test name \"${testName}\". Use one of: ${scenarios.map(scenarioLabel).join(\", \")}`);\n return [selected];\n}\n\nexport async function runConfig(config: BachsProofConfig, options: RunConfigOptions = {}): Promise<BachsProofCliRun[]> {\n assertConfig(config);\n const scenarios = selectedScenarios(config, options.testName);\n const provider = withBachsSigning(bachsAdapter({ mode: \"mock\" }), config.secret);\n const usedReferences = new Set<string>();\n const createPayment: PaymentReferenceCreator = 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(`createPayment returned reference ${normalized}, which was already used by another selected scenario`);\n }\n usedReferences.add(normalized);\n return normalized;\n };\n const runner = new BachsProof({\n provider,\n webhookUrl: config.webhookUrl,\n createPayment,\n verify: config.verify,\n financialVerification: config.verificationTimeoutMs === undefined ? undefined : { completionDeadlineMs: config.verificationTimeoutMs }\n });\n const results: BachsProofCliRun[] = [];\n for (const scenario of scenarios) {\n const result = await runner.run({\n scenario,\n amountMinor: config.amountMinor,\n currency: config.currency\n });\n results.push({ name: scenarioLabel(scenario), scenario, 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\nexport { bachsAdapter, signBachsWebhook } from \"@bachsproof/bachs\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bachsproof/cli",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "CLI for BachsProof financial correctness testing",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"payments",
|
|
@@ -45,8 +45,8 @@
|
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
47
|
"jiti": "^2.7.0",
|
|
48
|
-
"@bachsproof/core": "
|
|
49
|
-
"@bachsproof/bachs": "
|
|
48
|
+
"@bachsproof/core": "2.0.0",
|
|
49
|
+
"@bachsproof/bachs": "2.0.0"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@types/node": "^22.10.0",
|