@bachsproof/core 1.1.0 → 2.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/README.md CHANGED
@@ -1,57 +1,12 @@
1
- # @bachsproof/core
1
+ # `@bachsproof/core`
2
2
 
3
- **Beyond webhook delivery. Verify financial correctness.**
3
+ This package contains the internal, provider-neutral execution engine used by
4
+ the CLI. Ordinary developers should install `@bachsproof/cli` instead.
4
5
 
5
- The core package provides the application-side runner for BachsProof, a financial
6
- correctness testing framework for applications integrating Bachs. It sends
7
- controlled test deliveries to an existing webhook endpoint and evaluates state
8
- returned by the application's verification callback.
6
+ The engine prepares application payment references, sends provider events,
7
+ delivers them sequentially or concurrently, polls asynchronous verification,
8
+ and evaluates the five financial invariants. It does not create payment
9
+ records or infer ledger state; those responsibilities stay in the callbacks.
9
10
 
10
- The core runner sends serialized provider events to an existing webhook URL,
11
- records every delivery, optionally coordinates an instrumented checkpoint, and
12
- applies financial invariants to state returned by the application's
13
- verify(reference, context) callback.
14
-
15
- import { BachsProof } from "@bachsproof/core";
16
- import { bachsAdapter } from "@bachsproof/bachs";
17
-
18
- const bachsproof = new BachsProof({
19
- provider: bachsAdapter({ mode: "mock" }),
20
- target: {
21
- baseUrl: "http://127.0.0.1:3000",
22
- webhookPath: "/webhooks/bachs"
23
- },
24
- verify: async (reference) => readCommittedState(reference),
25
- financialVerification: {
26
- completionDeadlineMs: 10_000,
27
- pollIntervalMs: 25,
28
- negativeObservationWindowMs: 250
29
- }
30
- });
31
-
32
- const result = await bachsproof.run({
33
- scenario: "concurrent-duplicate-credit",
34
- reference: "isolated-test-order-001",
35
- amountMinor: 500_000,
36
- currency: "NGN"
37
- });
38
-
39
- verify(reference) remains valid. The optional second argument supplies the
40
- scenario, expected outcome, related event identifiers, and delivery records.
41
- The callback must return independently observed committed state. It must not
42
- return hardcoded expected values.
43
-
44
- If the callback returns pending: true, the core polls until the configured
45
- bounded deadline. Missing or unsuccessful verification never becomes a
46
- financial pass. Omitting verify is valid for delivery-only testing, but
47
- financiallyVerified is false.
48
-
49
- Payment references are real application references by default. Use
50
- createPayment({ scenario, amountMinor, currency, paymentIndex, paymentCount })
51
- for automatic test-record preparation, explicit reference or references for
52
- manual preparation, or syntheticReferences: true for isolated fixture runs.
53
-
54
- The core does not reset application state or call a state-inspection endpoint.
55
- The target application owns preparation, isolation, cleanup, and state access.
56
- For optional controlled concurrency testing, install @bachsproof/sdk only in a
57
- test-enabled application build.
11
+ The active v2 workspace exposes this engine through the CLI's small two-callback
12
+ configuration.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { z } from 'zod';
2
-
3
- /** Scenarios implemented by the provider-neutral runner and provider adapters. */
4
- type ScenarioName = "concurrent-duplicate-credit" | "sequential-duplicate-webhook" | "concurrent-unique-payments" | "cross-event-duplicate-payment" | "out-of-order-events" | "delayed-payment-confirmation" | "incomplete-checkout" | "expired-checkout" | "tampered-webhook" | "invalid-webhook-signature" | "malformed-webhook" | "incorrect-payment-amount" | "incorrect-payment-currency" | "underpaid-payment" | "failed-payment";
1
+ /** The eleven financial correctness scenarios supported by BachsProof v2. */
2
+ declare const SUPPORTED_SCENARIOS: readonly ["sequential-duplicate-webhook", "concurrent-duplicate-credit", "concurrent-unique-payments", "cross-event-duplicate-payment", "out-of-order-events", "incomplete-checkout", "expired-checkout", "incorrect-payment-amount", "incorrect-payment-currency", "underpaid-payment", "failed-payment"];
3
+ type ScenarioName = typeof SUPPORTED_SCENARIOS[number];
5
4
  /** Minimal shape every provider adapter event must expose to the core engine. */
6
5
  interface PaymentEvent {
7
6
  reference: string;
@@ -25,7 +24,7 @@ interface FinancialVerificationContext {
25
24
  eventIdentifiers: string[];
26
25
  deliveries: DeliveryRecord[];
27
26
  }
28
- /** Test-only input supplied to the application's payment preparation callback. */
27
+ /** Information needed to create one fresh application payment. */
29
28
  interface PaymentPreparationContext {
30
29
  scenario: ScenarioName;
31
30
  amountMinor: number;
@@ -44,17 +43,10 @@ interface ExpectedPaymentState {
44
43
  currency: string;
45
44
  expectedCreditCount: number;
46
45
  }
47
- /** HTTP outcome accepted for one deliberately rejected delivery. */
48
46
  type ExpectedHttpStatus = number | number[] | "2xx" | "4xx" | "5xx";
49
47
  /** One raw webhook delivery in a provider-defined scenario. */
50
48
  interface ProviderScenarioDelivery<TEvent extends PaymentEvent = PaymentEvent> {
51
49
  event?: TEvent;
52
- /** Override the provider serialization for malformed/tampered-body tests. */
53
- body?: string | Uint8Array;
54
- /** Sign this body while sending `body`, used for tampered-body tests. */
55
- signingBody?: string | Uint8Array;
56
- /** Explicit headers win over adapter-generated headers. */
57
- headers?: Record<string, string>;
58
50
  participantId?: string;
59
51
  delayMs?: number;
60
52
  expectedStatus?: ExpectedHttpStatus;
@@ -70,6 +62,11 @@ interface ProviderScenario<TEvent extends PaymentEvent = PaymentEvent> {
70
62
  expected?: ExpectedPaymentState;
71
63
  }>;
72
64
  }
65
+ /** Internal input available to an adapter after application payment preparation. */
66
+ interface ProviderScenarioInput extends RunOptions {
67
+ reference: string;
68
+ references: string[];
69
+ }
73
70
  /**
74
71
  * Provider plug-in contract. The core never knows how a Bachs event (or a
75
72
  * future provider event) is shaped on the wire; it only uses this contract.
@@ -77,33 +74,31 @@ interface ProviderScenario<TEvent extends PaymentEvent = PaymentEvent> {
77
74
  interface ProviderAdapter<TEvent extends PaymentEvent = PaymentEvent> {
78
75
  readonly name: string;
79
76
  readonly mode: string;
80
- createPayment(input?: {
81
- reference?: string;
82
- amountMinor?: number;
83
- currency?: string;
77
+ createPayment(input: {
78
+ reference: string;
79
+ amountMinor: number;
80
+ currency: string;
84
81
  eligible?: boolean;
85
82
  customerId?: string;
86
- syntheticReferences?: boolean;
87
83
  }): TEvent;
88
84
  serialize(event: TEvent): string;
89
85
  expectedState(event: TEvent): ExpectedPaymentState;
90
86
  headers?(event: TEvent): Record<string, string>;
91
87
  /** Optional signing hook that receives the exact bytes used for the request. */
92
88
  headersForBody?(event: TEvent, body: string | Uint8Array): Record<string, string>;
93
- /** Provider adapters may expose documented event-lifecycle scenarios. */
94
- createScenario?(scenario: ScenarioName, input: RunOptions): ProviderScenario<TEvent> | undefined;
89
+ /** Provider adapters expose only the supported financial scenarios. */
90
+ createScenario?(scenario: ScenarioName, input: ProviderScenarioInput): ProviderScenario<TEvent> | undefined;
95
91
  }
96
- /**
97
- * Normalized persisted financial state returned by a developer-supplied
98
- * verification callback.
99
- */
92
+ /** Minor-unit values accepted from database adapters without unsafe conversion. */
93
+ type MinorUnitValue = number | bigint | string;
94
+ /** Normalized persisted financial state returned by a developer verifier. */
100
95
  interface ObservedPaymentState {
101
96
  reference: string;
102
97
  status: string;
103
98
  currency: string;
104
99
  creditedAmountMinor: number;
105
100
  creditCount: number;
106
- /** Optional application signal that asynchronous processing is incomplete. */
101
+ /** True while relevant application work is still incomplete. */
107
102
  pending?: boolean;
108
103
  ledgerEntries: Array<{
109
104
  id: string;
@@ -119,7 +114,7 @@ interface InvariantViolation {
119
114
  message: string;
120
115
  reference: string;
121
116
  }
122
- /** Result of evaluating all configured financial invariants for one reference. */
117
+ /** Result of evaluating all five financial invariants for one reference. */
123
118
  interface VerificationResult {
124
119
  passed: boolean;
125
120
  violations: InvariantViolation[];
@@ -129,40 +124,27 @@ interface DeliveryRecord {
129
124
  deliveryId: string;
130
125
  participantId: string;
131
126
  reference: string;
132
- eventId?: string | undefined;
133
- eventType?: string | undefined;
127
+ eventId?: string;
128
+ eventType?: string;
134
129
  startedAt: string;
135
- completedAt?: string | undefined;
136
- status?: number | undefined;
137
- responseBody?: string | undefined;
138
- expectedStatus?: ExpectedHttpStatus | undefined;
139
- error?: string | undefined;
140
- }
141
- /** An append-only event emitted by the race controller for replay/debugging. */
142
- interface CheckpointTraceEvent {
143
- type: "arrival" | "release" | "abort";
144
- at: string;
145
- sessionId: string;
146
- checkpoint: string;
147
- participantId?: string | undefined;
148
- key?: string | undefined;
149
- metadata?: Record<string, unknown> | undefined;
150
- reason?: string | undefined;
130
+ completedAt?: string;
131
+ status?: number;
132
+ responseBody?: string;
133
+ expectedStatus?: ProviderScenarioDelivery["expectedStatus"];
134
+ error?: string;
151
135
  }
152
- /** Structured report persisted by callers when they need a durable failure trace. */
136
+ type FailureType = "payment-preparation" | "webhook-delivery" | "unexpected-http-response" | "financial-verification" | "financial-verification-timeout" | "invariant-violation";
137
+ /** Structured report for automation and debugging. */
153
138
  interface BachsProofReport {
154
- reportVersion: "1.1";
139
+ reportVersion: "2.0";
155
140
  scenario: ScenarioName;
156
141
  provider: string;
157
- mode: string;
158
142
  paymentReference: string;
159
143
  event: PaymentEvent;
160
144
  expected: ExpectedPaymentState;
161
145
  observed?: ObservedPaymentState;
162
146
  verification?: VerificationResult;
163
- /** Which financial verification integration was used for this run. */
164
- verificationMode: "callback" | "none";
165
- /** False means HTTP delivery ran, but financial correctness was not established. */
147
+ /** True only when the verifier returned independently observed state. */
166
148
  financiallyVerified: boolean;
167
149
  payments?: Array<{
168
150
  event: PaymentEvent;
@@ -171,15 +153,8 @@ interface BachsProofReport {
171
153
  verification: VerificationResult;
172
154
  }>;
173
155
  deliveries: DeliveryRecord[];
174
- checkpoints: CheckpointTraceEvent[];
175
156
  errors: string[];
176
- replay: {
177
- seed: string;
178
- concurrency: number;
179
- checkpoint?: string;
180
- controlled: boolean;
181
- note: string;
182
- };
157
+ failureType?: FailureType;
183
158
  startedAt: string;
184
159
  completedAt?: string;
185
160
  }
@@ -187,194 +162,71 @@ interface BachsProofResult {
187
162
  passed: boolean;
188
163
  report: BachsProofReport;
189
164
  }
190
- /** Network details for the application under test. */
191
- interface BachsProofTarget {
192
- baseUrl: string;
193
- webhookPath: string;
194
- headers?: Record<string, string>;
195
- }
196
- /** Callback polling and observation settings. */
165
+ /** Callback polling and observation settings used internally by the CLI. */
197
166
  interface FinancialVerificationOptions {
198
167
  completionDeadlineMs?: number;
199
168
  pollIntervalMs?: number;
200
169
  /** How long a negative scenario must remain observed with no credit. */
201
170
  negativeObservationWindowMs?: number;
202
171
  }
203
- /**
204
- * The intentionally small callback contract recommended for TypeScript users.
205
- * Callers can use Prisma, SQL, an in-memory ledger, or any other test store.
206
- */
172
+ /** Public shape returned by the developer's financial verification callback. */
207
173
  interface FinancialVerificationInput {
208
174
  reference: string;
209
175
  creditCount: number;
210
- creditedAmountMinor: number;
176
+ creditedAmountMinor: MinorUnitValue;
211
177
  currency: string;
212
178
  status?: string;
213
179
  pending?: boolean;
214
180
  ledgerEntries?: Array<{
215
181
  id: string;
216
182
  type: string;
217
- amountMinor: number;
183
+ amountMinor: MinorUnitValue;
218
184
  currency?: string;
219
185
  }>;
220
186
  }
221
187
  /** One-argument callbacks remain valid; the second argument is optional. */
222
188
  type FinancialVerifier = (reference: string, context?: FinancialVerificationContext) => Promise<FinancialVerificationInput> | FinancialVerificationInput;
189
+ /** Internal runner options. The CLI is the supported public entry point. */
223
190
  interface BachsProofOptions<TEvent extends PaymentEvent = PaymentEvent> {
224
191
  provider: ProviderAdapter<TEvent>;
225
- target: BachsProofTarget;
226
- /** Optional test-only application payment/order preparation callback. */
227
- createPayment?: PaymentReferenceCreator;
228
- /** Optional test-only callback that reads committed financial state. */
229
- verify?: FinancialVerifier;
230
- /** Optional polling settings for asynchronous callback verification. */
192
+ webhookUrl: string;
193
+ createPayment: PaymentReferenceCreator;
194
+ verify: FinancialVerifier;
231
195
  financialVerification?: FinancialVerificationOptions;
232
- checkpoint?: {
233
- name: string;
234
- timeoutMs?: number;
235
- };
236
196
  }
237
- /** Per-run scenario settings, including replay overrides. */
197
+ /** Per-run settings created by the simplified CLI configuration. */
238
198
  interface RunOptions {
239
199
  scenario: ScenarioName;
240
200
  concurrency?: number;
241
201
  amountMinor?: number;
242
202
  currency?: string;
243
- reference?: string;
244
- /** Explicit references for concurrent-unique-payments. */
245
- references?: string[];
246
- /** Synthetic references are opt-in; real application references are default. */
247
- syntheticReferences?: boolean;
248
- /** Optional expected HTTP status/outcome for scenario deliveries. */
249
- expectedStatus?: ExpectedHttpStatus;
250
- /** Optional bounded delay used by delayed provider scenarios. */
251
- delayMs?: number;
252
- seed?: string;
253
- replay?: BachsProofReport;
254
203
  }
255
204
 
256
205
  /**
257
- * High-level BachsProof runner. It owns only test orchestration; the application
258
- * remains responsible for webhook authentication and business persistence.
206
+ * High-level v2 runner. It prepares real application payments, sends signed
207
+ * local events, and always evaluates committed financial state before passing.
259
208
  */
260
209
  declare class BachsProof<TEvent extends PaymentEvent = PaymentEvent> {
261
210
  private readonly options;
262
- /** Store the immutable configuration used by every run and replay. */
263
211
  constructor(options: BachsProofOptions<TEvent>);
264
212
  run(input: RunOptions): Promise<BachsProofResult>;
265
- replay(report: BachsProofReport): Promise<BachsProofResult>;
266
- private invalidInputResult;
267
213
  private runScenarioPlan;
268
- private settleConcurrentDeliveries;
269
214
  private deliver;
215
+ private verifyPayments;
270
216
  private inspect;
271
- private url;
272
- }
273
-
274
- /**
275
- * Resolve missing application payment references before event creation. Manual
276
- * references take precedence, followed by the explicit synthetic fixture mode;
277
- * the application callback is used only when neither is supplied.
278
- */
279
- declare function preparePaymentReferences(input: RunOptions, createPayment?: PaymentReferenceCreator): Promise<RunOptions>;
280
-
281
- interface RaceSession {
282
- id: string;
283
- token: string;
284
- controllerUrl: string;
285
- participants: string[];
286
- }
287
- declare class RaceController {
288
- private readonly server;
289
- private readonly sessions;
290
- private address?;
291
- private closed;
292
- constructor();
293
- start(): Promise<void>;
294
- registerSession(input: {
295
- participants: string[];
296
- id?: string;
297
- token?: string;
298
- }): Promise<RaceSession>;
299
- waitForArrivals(sessionId: string, checkpoint: string, count: number, timeoutMs?: number): Promise<void>;
300
- release(sessionId: string, checkpoint: string): void;
301
- abort(sessionId: string, reason: string): void;
302
- getTrace(sessionId: string): CheckpointTraceEvent[];
303
- cleanupSession(sessionId: string): void;
304
- close(): Promise<void>;
305
- private session;
306
- private checkpointState;
307
- private handle;
308
- private resolveReadyWaiters;
309
- private readJson;
310
- private finishResponse;
217
+ private invalidInputResult;
311
218
  }
312
219
 
313
220
  /**
314
221
  * Evaluate persisted financial state, not merely webhook HTTP responses.
315
- * Every comparison uses integer minor units so a floating-point rounding error
316
- * cannot hide a duplicate or incorrect credit.
222
+ * These are the five v1 invariants carried forward unchanged in meaning.
317
223
  */
318
224
  declare function verifyPaymentState(expected: ExpectedPaymentState, observed: ObservedPaymentState): VerificationResult;
319
225
 
320
226
  /**
321
- * Runtime validation is important here because a malformed callback result
322
- * could otherwise make an incorrect financial state look like a passed test.
323
- */
324
- declare const financialVerificationSchema: z.ZodObject<{
325
- reference: z.ZodString;
326
- creditCount: z.ZodNumber;
327
- creditedAmountMinor: z.ZodNumber;
328
- currency: z.ZodString;
329
- status: z.ZodOptional<z.ZodString>;
330
- pending: z.ZodOptional<z.ZodBoolean>;
331
- ledgerEntries: z.ZodOptional<z.ZodArray<z.ZodObject<{
332
- id: z.ZodString;
333
- type: z.ZodString;
334
- amountMinor: z.ZodNumber;
335
- currency: z.ZodOptional<z.ZodString>;
336
- }, "strip", z.ZodTypeAny, {
337
- amountMinor: number;
338
- id: string;
339
- type: string;
340
- currency?: string | undefined;
341
- }, {
342
- amountMinor: number;
343
- id: string;
344
- type: string;
345
- currency?: string | undefined;
346
- }>, "many">>;
347
- }, "strip", z.ZodTypeAny, {
348
- reference: string;
349
- currency: string;
350
- creditCount: number;
351
- creditedAmountMinor: number;
352
- status?: string | undefined;
353
- pending?: boolean | undefined;
354
- ledgerEntries?: {
355
- amountMinor: number;
356
- id: string;
357
- type: string;
358
- currency?: string | undefined;
359
- }[] | undefined;
360
- }, {
361
- reference: string;
362
- currency: string;
363
- creditCount: number;
364
- creditedAmountMinor: number;
365
- status?: string | undefined;
366
- pending?: boolean | undefined;
367
- ledgerEntries?: {
368
- amountMinor: number;
369
- id: string;
370
- type: string;
371
- currency?: string | undefined;
372
- }[] | undefined;
373
- }>;
374
- /**
375
- * Convert the public callback shape into the core's normalized observation
376
- * shape. The default status keeps the callback API small while preserving the
377
- * status field used by the HTTP adapter and reports.
227
+ * Normalize the callback contract without converting monetary values through
228
+ * floating-point arithmetic. BigInt and integer database strings are accepted
229
+ * when they fit inside JavaScript's safe integer range.
378
230
  */
379
231
  declare function normalizeCallbackState(value: unknown): ObservedPaymentState;
380
232
  interface FinancialVerificationWaitOptions {
@@ -393,4 +245,4 @@ declare function writeReport(report: BachsProofReport, path: string): Promise<vo
393
245
  /** Remove common credential formats before a diagnostic string enters a report. */
394
246
  declare function redactSecrets(value: string): string;
395
247
 
396
- export { BachsProof, type BachsProofOptions, type BachsProofReport, type BachsProofResult, type BachsProofTarget, type CheckpointTraceEvent, type DeliveryRecord, type ExpectedHttpStatus, type ExpectedPaymentState, type FinancialVerificationContext, type FinancialVerificationInput, type FinancialVerificationOptions, type FinancialVerifier, type InvariantId, type InvariantViolation, type ObservedPaymentState, type PaymentEvent, type PaymentPreparationContext, type PaymentReferenceCreator, type ProviderAdapter, type ProviderScenario, type ProviderScenarioDelivery, RaceController, type RunOptions, type ScenarioName, type VerificationResult, financialVerificationSchema, normalizeCallbackState, preparePaymentReferences, redactSecrets, verifyPaymentState, verifyWithCallback, writeReport };
248
+ export { BachsProof, type BachsProofOptions, type BachsProofReport, type BachsProofResult, type DeliveryRecord, type ExpectedHttpStatus, type ExpectedPaymentState, type FailureType, type FinancialVerificationContext, type FinancialVerificationInput, type FinancialVerificationOptions, type FinancialVerifier, type InvariantId, type InvariantViolation, type MinorUnitValue, type ObservedPaymentState, type PaymentEvent, type PaymentPreparationContext, type PaymentReferenceCreator, type ProviderAdapter, type ProviderScenario, type ProviderScenarioDelivery, type ProviderScenarioInput, type RunOptions, SUPPORTED_SCENARIOS, type ScenarioName, type VerificationResult, normalizeCallbackState, redactSecrets, verifyPaymentState, verifyWithCallback, writeReport };