@bachsproof/core 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,57 @@
1
- # Temporary Holding Version
1
+ # @bachsproof/core
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
+ 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.
9
+
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.
@@ -0,0 +1,396 @@
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";
5
+ /** Minimal shape every provider adapter event must expose to the core engine. */
6
+ interface PaymentEvent {
7
+ reference: string;
8
+ amountMinor: number;
9
+ currency: string;
10
+ status: string;
11
+ [key: string]: unknown;
12
+ }
13
+ /** Context supplied to a financial verifier for one inspected reference. */
14
+ interface FinancialVerificationContext {
15
+ scenario: ScenarioName;
16
+ paymentReference: string;
17
+ expected: ExpectedPaymentState;
18
+ expectedOutcome: {
19
+ eligible: boolean;
20
+ expectedCreditCount: number;
21
+ amountMinor: number;
22
+ currency: string;
23
+ };
24
+ events: PaymentEvent[];
25
+ eventIdentifiers: string[];
26
+ deliveries: DeliveryRecord[];
27
+ }
28
+ /** Test-only input supplied to the application's payment preparation callback. */
29
+ interface PaymentPreparationContext {
30
+ scenario: ScenarioName;
31
+ amountMinor: number;
32
+ currency: string;
33
+ /** Zero-based index within the payments required by this scenario. */
34
+ paymentIndex: number;
35
+ paymentCount: number;
36
+ }
37
+ /** Create a fresh application payment/order and return its reference. */
38
+ type PaymentReferenceCreator = (context: PaymentPreparationContext) => Promise<string> | string;
39
+ /** The state the application should have after processing one synthetic event. */
40
+ interface ExpectedPaymentState {
41
+ reference: string;
42
+ eligible: boolean;
43
+ amountMinor: number;
44
+ currency: string;
45
+ expectedCreditCount: number;
46
+ }
47
+ /** HTTP outcome accepted for one deliberately rejected delivery. */
48
+ type ExpectedHttpStatus = number | number[] | "2xx" | "4xx" | "5xx";
49
+ /** One raw webhook delivery in a provider-defined scenario. */
50
+ interface ProviderScenarioDelivery<TEvent extends PaymentEvent = PaymentEvent> {
51
+ 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
+ participantId?: string;
59
+ delayMs?: number;
60
+ expectedStatus?: ExpectedHttpStatus;
61
+ }
62
+ /** Optional provider-specific delivery plan for a named scenario. */
63
+ interface ProviderScenario<TEvent extends PaymentEvent = PaymentEvent> {
64
+ deliveries: ProviderScenarioDelivery<TEvent>[];
65
+ /** Deliver all entries together when true; otherwise preserve listed order. */
66
+ concurrent?: boolean;
67
+ /** State entries to inspect after delivery, with scenario-specific expectations. */
68
+ verification?: Array<{
69
+ event: TEvent;
70
+ expected?: ExpectedPaymentState;
71
+ }>;
72
+ }
73
+ /**
74
+ * Provider plug-in contract. The core never knows how a Bachs event (or a
75
+ * future provider event) is shaped on the wire; it only uses this contract.
76
+ */
77
+ interface ProviderAdapter<TEvent extends PaymentEvent = PaymentEvent> {
78
+ readonly name: string;
79
+ readonly mode: string;
80
+ createPayment(input?: {
81
+ reference?: string;
82
+ amountMinor?: number;
83
+ currency?: string;
84
+ eligible?: boolean;
85
+ customerId?: string;
86
+ syntheticReferences?: boolean;
87
+ }): TEvent;
88
+ serialize(event: TEvent): string;
89
+ expectedState(event: TEvent): ExpectedPaymentState;
90
+ headers?(event: TEvent): Record<string, string>;
91
+ /** Optional signing hook that receives the exact bytes used for the request. */
92
+ 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;
95
+ }
96
+ /**
97
+ * Normalized persisted financial state returned by a developer-supplied
98
+ * verification callback.
99
+ */
100
+ interface ObservedPaymentState {
101
+ reference: string;
102
+ status: string;
103
+ currency: string;
104
+ creditedAmountMinor: number;
105
+ creditCount: number;
106
+ /** Optional application signal that asynchronous processing is incomplete. */
107
+ pending?: boolean;
108
+ ledgerEntries: Array<{
109
+ id: string;
110
+ type: string;
111
+ amountMinor: number;
112
+ currency?: string;
113
+ }>;
114
+ }
115
+ type InvariantId = "INV-001" | "INV-002" | "INV-003" | "INV-004" | "INV-005";
116
+ interface InvariantViolation {
117
+ id: InvariantId;
118
+ name: string;
119
+ message: string;
120
+ reference: string;
121
+ }
122
+ /** Result of evaluating all configured financial invariants for one reference. */
123
+ interface VerificationResult {
124
+ passed: boolean;
125
+ violations: InvariantViolation[];
126
+ }
127
+ /** One attempted webhook delivery, including its HTTP outcome and timing. */
128
+ interface DeliveryRecord {
129
+ deliveryId: string;
130
+ participantId: string;
131
+ reference: string;
132
+ eventId?: string | undefined;
133
+ eventType?: string | undefined;
134
+ 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;
151
+ }
152
+ /** Structured report persisted by callers when they need a durable failure trace. */
153
+ interface BachsProofReport {
154
+ reportVersion: "1.1";
155
+ scenario: ScenarioName;
156
+ provider: string;
157
+ mode: string;
158
+ paymentReference: string;
159
+ event: PaymentEvent;
160
+ expected: ExpectedPaymentState;
161
+ observed?: ObservedPaymentState;
162
+ 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. */
166
+ financiallyVerified: boolean;
167
+ payments?: Array<{
168
+ event: PaymentEvent;
169
+ expected: ExpectedPaymentState;
170
+ observed: ObservedPaymentState;
171
+ verification: VerificationResult;
172
+ }>;
173
+ deliveries: DeliveryRecord[];
174
+ checkpoints: CheckpointTraceEvent[];
175
+ errors: string[];
176
+ replay: {
177
+ seed: string;
178
+ concurrency: number;
179
+ checkpoint?: string;
180
+ controlled: boolean;
181
+ note: string;
182
+ };
183
+ startedAt: string;
184
+ completedAt?: string;
185
+ }
186
+ interface BachsProofResult {
187
+ passed: boolean;
188
+ report: BachsProofReport;
189
+ }
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. */
197
+ interface FinancialVerificationOptions {
198
+ completionDeadlineMs?: number;
199
+ pollIntervalMs?: number;
200
+ /** How long a negative scenario must remain observed with no credit. */
201
+ negativeObservationWindowMs?: number;
202
+ }
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
+ */
207
+ interface FinancialVerificationInput {
208
+ reference: string;
209
+ creditCount: number;
210
+ creditedAmountMinor: number;
211
+ currency: string;
212
+ status?: string;
213
+ pending?: boolean;
214
+ ledgerEntries?: Array<{
215
+ id: string;
216
+ type: string;
217
+ amountMinor: number;
218
+ currency?: string;
219
+ }>;
220
+ }
221
+ /** One-argument callbacks remain valid; the second argument is optional. */
222
+ type FinancialVerifier = (reference: string, context?: FinancialVerificationContext) => Promise<FinancialVerificationInput> | FinancialVerificationInput;
223
+ interface BachsProofOptions<TEvent extends PaymentEvent = PaymentEvent> {
224
+ 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. */
231
+ financialVerification?: FinancialVerificationOptions;
232
+ checkpoint?: {
233
+ name: string;
234
+ timeoutMs?: number;
235
+ };
236
+ }
237
+ /** Per-run scenario settings, including replay overrides. */
238
+ interface RunOptions {
239
+ scenario: ScenarioName;
240
+ concurrency?: number;
241
+ amountMinor?: number;
242
+ 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
+ }
255
+
256
+ /**
257
+ * High-level BachsProof runner. It owns only test orchestration; the application
258
+ * remains responsible for webhook authentication and business persistence.
259
+ */
260
+ declare class BachsProof<TEvent extends PaymentEvent = PaymentEvent> {
261
+ private readonly options;
262
+ /** Store the immutable configuration used by every run and replay. */
263
+ constructor(options: BachsProofOptions<TEvent>);
264
+ run(input: RunOptions): Promise<BachsProofResult>;
265
+ replay(report: BachsProofReport): Promise<BachsProofResult>;
266
+ private invalidInputResult;
267
+ private runScenarioPlan;
268
+ private settleConcurrentDeliveries;
269
+ private deliver;
270
+ 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;
311
+ }
312
+
313
+ /**
314
+ * 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.
317
+ */
318
+ declare function verifyPaymentState(expected: ExpectedPaymentState, observed: ObservedPaymentState): VerificationResult;
319
+
320
+ /**
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.
378
+ */
379
+ declare function normalizeCallbackState(value: unknown): ObservedPaymentState;
380
+ interface FinancialVerificationWaitOptions {
381
+ pollIntervalMs?: number;
382
+ /** Return only when the independently observed state is complete. */
383
+ isComplete?: (state: ObservedPaymentState) => boolean;
384
+ }
385
+ /**
386
+ * Execute a callback with a hard upper bound. JavaScript cannot forcibly stop
387
+ * arbitrary user code, but the runner will stop waiting and report a timeout.
388
+ */
389
+ declare function verifyWithCallback(verify: FinancialVerifier, reference: string, timeoutMs: number, context?: FinancialVerificationContext, options?: FinancialVerificationWaitOptions): Promise<ObservedPaymentState>;
390
+
391
+ /** Write a human-readable JSON report and create its parent directory. */
392
+ declare function writeReport(report: BachsProofReport, path: string): Promise<void>;
393
+ /** Remove common credential formats before a diagnostic string enters a report. */
394
+ declare function redactSecrets(value: string): string;
395
+
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 };