@bachsproof/core 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +11 -2
- package/dist/index.d.ts +248 -0
- package/dist/index.js +513 -0
- package/dist/index.js.map +1 -0
- package/package.json +52 -3
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,12 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@bachsproof/core`
|
|
2
2
|
|
|
3
|
-
This
|
|
3
|
+
This package contains the internal, provider-neutral execution engine used by
|
|
4
|
+
the CLI. Ordinary developers should install `@bachsproof/cli` instead.
|
|
5
|
+
|
|
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.
|
|
10
|
+
|
|
11
|
+
The active v2 workspace exposes this engine through the CLI's small two-callback
|
|
12
|
+
configuration.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
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];
|
|
4
|
+
/** Minimal shape every provider adapter event must expose to the core engine. */
|
|
5
|
+
interface PaymentEvent {
|
|
6
|
+
reference: string;
|
|
7
|
+
amountMinor: number;
|
|
8
|
+
currency: string;
|
|
9
|
+
status: string;
|
|
10
|
+
[key: string]: unknown;
|
|
11
|
+
}
|
|
12
|
+
/** Context supplied to a financial verifier for one inspected reference. */
|
|
13
|
+
interface FinancialVerificationContext {
|
|
14
|
+
scenario: ScenarioName;
|
|
15
|
+
paymentReference: string;
|
|
16
|
+
expected: ExpectedPaymentState;
|
|
17
|
+
expectedOutcome: {
|
|
18
|
+
eligible: boolean;
|
|
19
|
+
expectedCreditCount: number;
|
|
20
|
+
amountMinor: number;
|
|
21
|
+
currency: string;
|
|
22
|
+
};
|
|
23
|
+
events: PaymentEvent[];
|
|
24
|
+
eventIdentifiers: string[];
|
|
25
|
+
deliveries: DeliveryRecord[];
|
|
26
|
+
}
|
|
27
|
+
/** Information needed to create one fresh application payment. */
|
|
28
|
+
interface PaymentPreparationContext {
|
|
29
|
+
scenario: ScenarioName;
|
|
30
|
+
amountMinor: number;
|
|
31
|
+
currency: string;
|
|
32
|
+
/** Zero-based index within the payments required by this scenario. */
|
|
33
|
+
paymentIndex: number;
|
|
34
|
+
paymentCount: number;
|
|
35
|
+
}
|
|
36
|
+
/** Create a fresh application payment/order and return its reference. */
|
|
37
|
+
type PaymentReferenceCreator = (context: PaymentPreparationContext) => Promise<string> | string;
|
|
38
|
+
/** The state the application should have after processing one synthetic event. */
|
|
39
|
+
interface ExpectedPaymentState {
|
|
40
|
+
reference: string;
|
|
41
|
+
eligible: boolean;
|
|
42
|
+
amountMinor: number;
|
|
43
|
+
currency: string;
|
|
44
|
+
expectedCreditCount: number;
|
|
45
|
+
}
|
|
46
|
+
type ExpectedHttpStatus = number | number[] | "2xx" | "4xx" | "5xx";
|
|
47
|
+
/** One raw webhook delivery in a provider-defined scenario. */
|
|
48
|
+
interface ProviderScenarioDelivery<TEvent extends PaymentEvent = PaymentEvent> {
|
|
49
|
+
event?: TEvent;
|
|
50
|
+
participantId?: string;
|
|
51
|
+
delayMs?: number;
|
|
52
|
+
expectedStatus?: ExpectedHttpStatus;
|
|
53
|
+
}
|
|
54
|
+
/** Optional provider-specific delivery plan for a named scenario. */
|
|
55
|
+
interface ProviderScenario<TEvent extends PaymentEvent = PaymentEvent> {
|
|
56
|
+
deliveries: ProviderScenarioDelivery<TEvent>[];
|
|
57
|
+
/** Deliver all entries together when true; otherwise preserve listed order. */
|
|
58
|
+
concurrent?: boolean;
|
|
59
|
+
/** State entries to inspect after delivery, with scenario-specific expectations. */
|
|
60
|
+
verification?: Array<{
|
|
61
|
+
event: TEvent;
|
|
62
|
+
expected?: ExpectedPaymentState;
|
|
63
|
+
}>;
|
|
64
|
+
}
|
|
65
|
+
/** Internal input available to an adapter after application payment preparation. */
|
|
66
|
+
interface ProviderScenarioInput extends RunOptions {
|
|
67
|
+
reference: string;
|
|
68
|
+
references: string[];
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Provider plug-in contract. The core never knows how a Bachs event (or a
|
|
72
|
+
* future provider event) is shaped on the wire; it only uses this contract.
|
|
73
|
+
*/
|
|
74
|
+
interface ProviderAdapter<TEvent extends PaymentEvent = PaymentEvent> {
|
|
75
|
+
readonly name: string;
|
|
76
|
+
readonly mode: string;
|
|
77
|
+
createPayment(input: {
|
|
78
|
+
reference: string;
|
|
79
|
+
amountMinor: number;
|
|
80
|
+
currency: string;
|
|
81
|
+
eligible?: boolean;
|
|
82
|
+
customerId?: string;
|
|
83
|
+
}): TEvent;
|
|
84
|
+
serialize(event: TEvent): string;
|
|
85
|
+
expectedState(event: TEvent): ExpectedPaymentState;
|
|
86
|
+
headers?(event: TEvent): Record<string, string>;
|
|
87
|
+
/** Optional signing hook that receives the exact bytes used for the request. */
|
|
88
|
+
headersForBody?(event: TEvent, body: string | Uint8Array): Record<string, string>;
|
|
89
|
+
/** Provider adapters expose only the supported financial scenarios. */
|
|
90
|
+
createScenario?(scenario: ScenarioName, input: ProviderScenarioInput): ProviderScenario<TEvent> | undefined;
|
|
91
|
+
}
|
|
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. */
|
|
95
|
+
interface ObservedPaymentState {
|
|
96
|
+
reference: string;
|
|
97
|
+
status: string;
|
|
98
|
+
currency: string;
|
|
99
|
+
creditedAmountMinor: number;
|
|
100
|
+
creditCount: number;
|
|
101
|
+
/** True while relevant application work is still incomplete. */
|
|
102
|
+
pending?: boolean;
|
|
103
|
+
ledgerEntries: Array<{
|
|
104
|
+
id: string;
|
|
105
|
+
type: string;
|
|
106
|
+
amountMinor: number;
|
|
107
|
+
currency?: string;
|
|
108
|
+
}>;
|
|
109
|
+
}
|
|
110
|
+
type InvariantId = "INV-001" | "INV-002" | "INV-003" | "INV-004" | "INV-005";
|
|
111
|
+
interface InvariantViolation {
|
|
112
|
+
id: InvariantId;
|
|
113
|
+
name: string;
|
|
114
|
+
message: string;
|
|
115
|
+
reference: string;
|
|
116
|
+
}
|
|
117
|
+
/** Result of evaluating all five financial invariants for one reference. */
|
|
118
|
+
interface VerificationResult {
|
|
119
|
+
passed: boolean;
|
|
120
|
+
violations: InvariantViolation[];
|
|
121
|
+
}
|
|
122
|
+
/** One attempted webhook delivery, including its HTTP outcome and timing. */
|
|
123
|
+
interface DeliveryRecord {
|
|
124
|
+
deliveryId: string;
|
|
125
|
+
participantId: string;
|
|
126
|
+
reference: string;
|
|
127
|
+
eventId?: string;
|
|
128
|
+
eventType?: string;
|
|
129
|
+
startedAt: string;
|
|
130
|
+
completedAt?: string;
|
|
131
|
+
status?: number;
|
|
132
|
+
responseBody?: string;
|
|
133
|
+
expectedStatus?: ProviderScenarioDelivery["expectedStatus"];
|
|
134
|
+
error?: string;
|
|
135
|
+
}
|
|
136
|
+
type FailureType = "payment-preparation" | "webhook-delivery" | "unexpected-http-response" | "financial-verification" | "financial-verification-timeout" | "invariant-violation";
|
|
137
|
+
/** Structured report for automation and debugging. */
|
|
138
|
+
interface BachsProofReport {
|
|
139
|
+
reportVersion: "2.0";
|
|
140
|
+
scenario: ScenarioName;
|
|
141
|
+
provider: string;
|
|
142
|
+
paymentReference: string;
|
|
143
|
+
event: PaymentEvent;
|
|
144
|
+
expected: ExpectedPaymentState;
|
|
145
|
+
observed?: ObservedPaymentState;
|
|
146
|
+
verification?: VerificationResult;
|
|
147
|
+
/** True only when the verifier returned independently observed state. */
|
|
148
|
+
financiallyVerified: boolean;
|
|
149
|
+
payments?: Array<{
|
|
150
|
+
event: PaymentEvent;
|
|
151
|
+
expected: ExpectedPaymentState;
|
|
152
|
+
observed: ObservedPaymentState;
|
|
153
|
+
verification: VerificationResult;
|
|
154
|
+
}>;
|
|
155
|
+
deliveries: DeliveryRecord[];
|
|
156
|
+
errors: string[];
|
|
157
|
+
failureType?: FailureType;
|
|
158
|
+
startedAt: string;
|
|
159
|
+
completedAt?: string;
|
|
160
|
+
}
|
|
161
|
+
interface BachsProofResult {
|
|
162
|
+
passed: boolean;
|
|
163
|
+
report: BachsProofReport;
|
|
164
|
+
}
|
|
165
|
+
/** Callback polling and observation settings used internally by the CLI. */
|
|
166
|
+
interface FinancialVerificationOptions {
|
|
167
|
+
completionDeadlineMs?: number;
|
|
168
|
+
pollIntervalMs?: number;
|
|
169
|
+
/** How long a negative scenario must remain observed with no credit. */
|
|
170
|
+
negativeObservationWindowMs?: number;
|
|
171
|
+
}
|
|
172
|
+
/** Public shape returned by the developer's financial verification callback. */
|
|
173
|
+
interface FinancialVerificationInput {
|
|
174
|
+
reference: string;
|
|
175
|
+
creditCount: number;
|
|
176
|
+
creditedAmountMinor: MinorUnitValue;
|
|
177
|
+
currency: string;
|
|
178
|
+
status?: string;
|
|
179
|
+
pending?: boolean;
|
|
180
|
+
ledgerEntries?: Array<{
|
|
181
|
+
id: string;
|
|
182
|
+
type: string;
|
|
183
|
+
amountMinor: MinorUnitValue;
|
|
184
|
+
currency?: string;
|
|
185
|
+
}>;
|
|
186
|
+
}
|
|
187
|
+
/** One-argument callbacks remain valid; the second argument is optional. */
|
|
188
|
+
type FinancialVerifier = (reference: string, context?: FinancialVerificationContext) => Promise<FinancialVerificationInput> | FinancialVerificationInput;
|
|
189
|
+
/** Internal runner options. The CLI is the supported public entry point. */
|
|
190
|
+
interface BachsProofOptions<TEvent extends PaymentEvent = PaymentEvent> {
|
|
191
|
+
provider: ProviderAdapter<TEvent>;
|
|
192
|
+
webhookUrl: string;
|
|
193
|
+
createPayment: PaymentReferenceCreator;
|
|
194
|
+
verify: FinancialVerifier;
|
|
195
|
+
financialVerification?: FinancialVerificationOptions;
|
|
196
|
+
}
|
|
197
|
+
/** Per-run settings created by the simplified CLI configuration. */
|
|
198
|
+
interface RunOptions {
|
|
199
|
+
scenario: ScenarioName;
|
|
200
|
+
concurrency?: number;
|
|
201
|
+
amountMinor?: number;
|
|
202
|
+
currency?: string;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* High-level v2 runner. It prepares real application payments, sends signed
|
|
207
|
+
* local events, and always evaluates committed financial state before passing.
|
|
208
|
+
*/
|
|
209
|
+
declare class BachsProof<TEvent extends PaymentEvent = PaymentEvent> {
|
|
210
|
+
private readonly options;
|
|
211
|
+
constructor(options: BachsProofOptions<TEvent>);
|
|
212
|
+
run(input: RunOptions): Promise<BachsProofResult>;
|
|
213
|
+
private runScenarioPlan;
|
|
214
|
+
private deliver;
|
|
215
|
+
private verifyPayments;
|
|
216
|
+
private inspect;
|
|
217
|
+
private invalidInputResult;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Evaluate persisted financial state, not merely webhook HTTP responses.
|
|
222
|
+
* These are the five v1 invariants carried forward unchanged in meaning.
|
|
223
|
+
*/
|
|
224
|
+
declare function verifyPaymentState(expected: ExpectedPaymentState, observed: ObservedPaymentState): VerificationResult;
|
|
225
|
+
|
|
226
|
+
/**
|
|
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.
|
|
230
|
+
*/
|
|
231
|
+
declare function normalizeCallbackState(value: unknown): ObservedPaymentState;
|
|
232
|
+
interface FinancialVerificationWaitOptions {
|
|
233
|
+
pollIntervalMs?: number;
|
|
234
|
+
/** Return only when the independently observed state is complete. */
|
|
235
|
+
isComplete?: (state: ObservedPaymentState) => boolean;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Execute a callback with a hard upper bound. JavaScript cannot forcibly stop
|
|
239
|
+
* arbitrary user code, but the runner will stop waiting and report a timeout.
|
|
240
|
+
*/
|
|
241
|
+
declare function verifyWithCallback(verify: FinancialVerifier, reference: string, timeoutMs: number, context?: FinancialVerificationContext, options?: FinancialVerificationWaitOptions): Promise<ObservedPaymentState>;
|
|
242
|
+
|
|
243
|
+
/** Write a human-readable JSON report and create its parent directory. */
|
|
244
|
+
declare function writeReport(report: BachsProofReport, path: string): Promise<void>;
|
|
245
|
+
/** Remove common credential formats before a diagnostic string enters a report. */
|
|
246
|
+
declare function redactSecrets(value: string): string;
|
|
247
|
+
|
|
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 };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { fetch } from 'undici';
|
|
3
|
+
import { mkdir, writeFile } from 'fs/promises';
|
|
4
|
+
import { dirname } from 'path';
|
|
5
|
+
|
|
6
|
+
// src/orchestrator.ts
|
|
7
|
+
|
|
8
|
+
// src/invariants.ts
|
|
9
|
+
function verifyPaymentState(expected, observed) {
|
|
10
|
+
const violations = [];
|
|
11
|
+
if (observed.creditCount > 1) {
|
|
12
|
+
violations.push({
|
|
13
|
+
id: "INV-001",
|
|
14
|
+
name: "Unique Credit",
|
|
15
|
+
message: `Payment ${expected.reference} created ${observed.creditCount} credits; one credit is allowed for an eligible payment`,
|
|
16
|
+
reference: expected.reference
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
if (observed.creditCount > 0 && (observed.creditedAmountMinor !== expected.amountMinor || observed.currency !== expected.currency)) {
|
|
20
|
+
violations.push({
|
|
21
|
+
id: "INV-002",
|
|
22
|
+
name: "Amount Integrity",
|
|
23
|
+
message: `Expected one credit of ${expected.amountMinor} ${expected.currency} minor units, but observed ${observed.creditedAmountMinor} ${observed.currency} minor units`,
|
|
24
|
+
reference: expected.reference
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
if (expected.eligible && observed.creditCount < expected.expectedCreditCount) {
|
|
28
|
+
violations.push({
|
|
29
|
+
id: "INV-003",
|
|
30
|
+
name: "Completion",
|
|
31
|
+
message: `Expected ${expected.expectedCreditCount} credit for ${expected.reference}, but observed ${observed.creditCount}`,
|
|
32
|
+
reference: expected.reference
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
if (!expected.eligible && observed.creditCount > 0) {
|
|
36
|
+
violations.push({
|
|
37
|
+
id: "INV-004",
|
|
38
|
+
name: "No Unexpected Credit",
|
|
39
|
+
message: `Payment ${expected.reference} was not eligible, but it created ${observed.creditCount} credit(s)`,
|
|
40
|
+
reference: expected.reference
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
if (expected.eligible && observed.creditCount === expected.expectedCreditCount && observed.creditedAmountMinor !== expected.amountMinor) {
|
|
44
|
+
violations.push({
|
|
45
|
+
id: "INV-005",
|
|
46
|
+
name: "Aggregate Integrity",
|
|
47
|
+
message: `Payment ${expected.reference} has the expected number of credits, but their total is not the expected amount`,
|
|
48
|
+
reference: expected.reference
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return { passed: violations.length === 0, violations };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/preparation.ts
|
|
55
|
+
var DEFAULT_AMOUNT_MINOR = 5e5;
|
|
56
|
+
var DEFAULT_CURRENCY = "NGN";
|
|
57
|
+
function hasReference(value) {
|
|
58
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
59
|
+
}
|
|
60
|
+
function preparationError(scenario, index, error) {
|
|
61
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
62
|
+
return new Error(`Payment preparation failed for ${scenario} payment ${index + 1}: ${detail}`);
|
|
63
|
+
}
|
|
64
|
+
async function createReference(input, createPayment, paymentIndex, paymentCount) {
|
|
65
|
+
try {
|
|
66
|
+
const reference = await createPayment({
|
|
67
|
+
scenario: input.scenario,
|
|
68
|
+
amountMinor: input.amountMinor ?? DEFAULT_AMOUNT_MINOR,
|
|
69
|
+
currency: input.currency ?? DEFAULT_CURRENCY,
|
|
70
|
+
paymentIndex,
|
|
71
|
+
paymentCount
|
|
72
|
+
});
|
|
73
|
+
if (!hasReference(reference)) {
|
|
74
|
+
throw new Error("createPayment must return a non-empty reference from the isolated test payment it created");
|
|
75
|
+
}
|
|
76
|
+
return reference.trim();
|
|
77
|
+
} catch (error) {
|
|
78
|
+
throw preparationError(input.scenario, paymentIndex, error);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function preparePaymentReferences(input, createPayment) {
|
|
82
|
+
const paymentCount = input.scenario === "concurrent-unique-payments" ? input.concurrency ?? 2 : 1;
|
|
83
|
+
if (!Number.isInteger(paymentCount) || paymentCount < 1) {
|
|
84
|
+
throw new Error("Payment preparation requires a positive payment count");
|
|
85
|
+
}
|
|
86
|
+
const references = [];
|
|
87
|
+
for (let paymentIndex = 0; paymentIndex < paymentCount; paymentIndex += 1) {
|
|
88
|
+
references.push(await createReference(input, createPayment, paymentIndex, paymentCount));
|
|
89
|
+
}
|
|
90
|
+
if (new Set(references).size !== references.length) {
|
|
91
|
+
throw new Error(`Payment preparation failed for ${input.scenario}: createPayment returned duplicate payment references`);
|
|
92
|
+
}
|
|
93
|
+
return references;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// src/verification.ts
|
|
97
|
+
var INTEGER = /^(?:0|[1-9]\d*)$/;
|
|
98
|
+
function safeMinorUnits(value, path) {
|
|
99
|
+
let normalized;
|
|
100
|
+
if (typeof value === "bigint") {
|
|
101
|
+
normalized = value;
|
|
102
|
+
} else if (typeof value === "number") {
|
|
103
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
104
|
+
throw new Error(`Financial verification callback returned invalid data at ${path}: expected a non-negative safe integer`);
|
|
105
|
+
}
|
|
106
|
+
return value;
|
|
107
|
+
} else if (typeof value === "string" && INTEGER.test(value)) {
|
|
108
|
+
normalized = BigInt(value);
|
|
109
|
+
} else {
|
|
110
|
+
throw new Error(`Financial verification callback returned invalid data at ${path}: expected a non-negative integer minor-unit amount`);
|
|
111
|
+
}
|
|
112
|
+
if (normalized < 0n || normalized > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
113
|
+
throw new Error(`Financial verification callback returned invalid data at ${path}: amount exceeds JavaScript safe integer range`);
|
|
114
|
+
}
|
|
115
|
+
return Number(normalized);
|
|
116
|
+
}
|
|
117
|
+
function callbackError(error) {
|
|
118
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
119
|
+
return message.startsWith("Financial verification") ? new Error(message) : new Error(`Financial verification failed: ${message}`);
|
|
120
|
+
}
|
|
121
|
+
function assertObject(value) {
|
|
122
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
123
|
+
throw new Error("Financial verification callback returned invalid data: expected an object");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function requiredString(value, path) {
|
|
127
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
128
|
+
throw new Error(`Financial verification callback returned invalid data at ${path}: expected a non-empty string`);
|
|
129
|
+
}
|
|
130
|
+
return value;
|
|
131
|
+
}
|
|
132
|
+
function optionalBoolean(value, path) {
|
|
133
|
+
if (value === void 0) return void 0;
|
|
134
|
+
if (typeof value !== "boolean") {
|
|
135
|
+
throw new Error(`Financial verification callback returned invalid data at ${path}: expected boolean`);
|
|
136
|
+
}
|
|
137
|
+
return value;
|
|
138
|
+
}
|
|
139
|
+
function normalizeCallbackState(value) {
|
|
140
|
+
assertObject(value);
|
|
141
|
+
const reference = requiredString(value.reference, "reference");
|
|
142
|
+
if (!Number.isSafeInteger(value.creditCount) || value.creditCount < 0) {
|
|
143
|
+
throw new Error("Financial verification callback returned invalid data at creditCount: expected a non-negative safe integer");
|
|
144
|
+
}
|
|
145
|
+
const currency = requiredString(value.currency, "currency").toUpperCase();
|
|
146
|
+
if (!/^[A-Z]{3}$/.test(currency)) {
|
|
147
|
+
throw new Error("Financial verification callback returned invalid data at currency: expected a three-letter ISO currency");
|
|
148
|
+
}
|
|
149
|
+
const ledgerEntries = [];
|
|
150
|
+
if (value.ledgerEntries !== void 0) {
|
|
151
|
+
if (!Array.isArray(value.ledgerEntries)) {
|
|
152
|
+
throw new Error("Financial verification callback returned invalid data at ledgerEntries: expected an array");
|
|
153
|
+
}
|
|
154
|
+
for (const [index, entryValue] of value.ledgerEntries.entries()) {
|
|
155
|
+
assertObject(entryValue);
|
|
156
|
+
ledgerEntries.push({
|
|
157
|
+
id: requiredString(entryValue.id, `ledgerEntries[${index}].id`),
|
|
158
|
+
type: requiredString(entryValue.type, `ledgerEntries[${index}].type`),
|
|
159
|
+
amountMinor: safeMinorUnits(entryValue.amountMinor, `ledgerEntries[${index}].amountMinor`),
|
|
160
|
+
...entryValue.currency === void 0 ? {} : { currency: requiredString(entryValue.currency, `ledgerEntries[${index}].currency`).toUpperCase() }
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
reference,
|
|
166
|
+
status: value.status === void 0 ? "UNKNOWN" : requiredString(value.status, "status"),
|
|
167
|
+
currency,
|
|
168
|
+
creditedAmountMinor: safeMinorUnits(value.creditedAmountMinor, "creditedAmountMinor"),
|
|
169
|
+
creditCount: value.creditCount,
|
|
170
|
+
...value.pending === void 0 ? {} : { pending: optionalBoolean(value.pending, "pending") },
|
|
171
|
+
ledgerEntries
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
async function verifyWithCallback(verify, reference, timeoutMs, context, options = {}) {
|
|
175
|
+
const deadline = Date.now() + timeoutMs;
|
|
176
|
+
let lastObserved;
|
|
177
|
+
let lastTimeout;
|
|
178
|
+
while (Date.now() <= deadline) {
|
|
179
|
+
const remaining = Math.max(1, deadline - Date.now());
|
|
180
|
+
let timer;
|
|
181
|
+
try {
|
|
182
|
+
const timeout = new Promise((_, reject) => {
|
|
183
|
+
timer = setTimeout(() => reject(new Error(`Financial verification timed out after ${timeoutMs}ms`)), remaining);
|
|
184
|
+
});
|
|
185
|
+
const value = await Promise.race([Promise.resolve().then(() => verify(reference, context)), timeout]);
|
|
186
|
+
const normalized = normalizeCallbackState(value);
|
|
187
|
+
if (normalized.reference !== reference) {
|
|
188
|
+
throw new Error(`Financial verification returned ${normalized.reference} while ${reference} was requested`);
|
|
189
|
+
}
|
|
190
|
+
lastObserved = normalized;
|
|
191
|
+
if (!options.isComplete || options.isComplete(normalized)) return normalized;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
const candidate = callbackError(error);
|
|
194
|
+
if (!candidate.message.startsWith("Financial verification timed out after ")) throw candidate;
|
|
195
|
+
lastTimeout = candidate;
|
|
196
|
+
} finally {
|
|
197
|
+
if (timer) clearTimeout(timer);
|
|
198
|
+
}
|
|
199
|
+
const waitMs = Math.min(options.pollIntervalMs ?? 25, Math.max(1, deadline - Date.now()));
|
|
200
|
+
if (Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, waitMs));
|
|
201
|
+
}
|
|
202
|
+
if (lastObserved && !lastObserved.pending) return lastObserved;
|
|
203
|
+
throw lastTimeout ?? new Error(`Financial verification timed out after ${timeoutMs}ms`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// src/orchestrator.ts
|
|
207
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
208
|
+
var DEFAULT_NEGATIVE_OBSERVATION_MS = 250;
|
|
209
|
+
function eventId(event) {
|
|
210
|
+
for (const key of ["id", "eventId", "providerEventId"]) {
|
|
211
|
+
const value = event[key];
|
|
212
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
213
|
+
}
|
|
214
|
+
return void 0;
|
|
215
|
+
}
|
|
216
|
+
function eventType(event) {
|
|
217
|
+
return typeof event.type === "string" ? event.type : void 0;
|
|
218
|
+
}
|
|
219
|
+
function matchesExpectedStatus(status, expected) {
|
|
220
|
+
if (Array.isArray(expected)) return expected.includes(status);
|
|
221
|
+
if (expected === "2xx") return status >= 200 && status < 300;
|
|
222
|
+
if (expected === "4xx") return status >= 400 && status < 500;
|
|
223
|
+
if (expected === "5xx") return status >= 500 && status < 600;
|
|
224
|
+
return status === expected;
|
|
225
|
+
}
|
|
226
|
+
function formatExpectedStatus(expected) {
|
|
227
|
+
return Array.isArray(expected) ? expected.join(", ") : String(expected);
|
|
228
|
+
}
|
|
229
|
+
function validateRunOptions(input) {
|
|
230
|
+
if (input.concurrency !== void 0 && (!Number.isInteger(input.concurrency) || input.concurrency < 1)) {
|
|
231
|
+
return "concurrency must be a positive integer";
|
|
232
|
+
}
|
|
233
|
+
if (input.amountMinor !== void 0 && (!Number.isSafeInteger(input.amountMinor) || input.amountMinor < 0)) {
|
|
234
|
+
return "amountMinor must be a non-negative safe integer in minor units";
|
|
235
|
+
}
|
|
236
|
+
if (input.currency !== void 0 && !/^[A-Z]{3}$/.test(input.currency)) {
|
|
237
|
+
return "currency must be a three-letter ISO currency code";
|
|
238
|
+
}
|
|
239
|
+
return void 0;
|
|
240
|
+
}
|
|
241
|
+
function verificationComplete(expected, state, negativeDeadline) {
|
|
242
|
+
if (state.pending) return false;
|
|
243
|
+
if (expected.eligible) return state.creditCount > 0;
|
|
244
|
+
return state.creditCount > 0 || Date.now() >= negativeDeadline;
|
|
245
|
+
}
|
|
246
|
+
function failureTypeFor(error) {
|
|
247
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
248
|
+
return message.includes("timed out") ? "financial-verification-timeout" : "financial-verification";
|
|
249
|
+
}
|
|
250
|
+
var BachsProof = class {
|
|
251
|
+
constructor(options) {
|
|
252
|
+
this.options = options;
|
|
253
|
+
if (!options.createPayment) throw new Error("BachsProof requires a createPayment callback");
|
|
254
|
+
if (!options.verify) throw new Error("BachsProof requires a verify callback");
|
|
255
|
+
try {
|
|
256
|
+
const url = new URL(options.webhookUrl);
|
|
257
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("webhookUrl must use http or https");
|
|
258
|
+
} catch (error) {
|
|
259
|
+
throw new Error(`BachsProof requires a complete webhookUrl: ${error instanceof Error ? error.message : String(error)}`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
options;
|
|
263
|
+
async run(input) {
|
|
264
|
+
const requestedInput = input;
|
|
265
|
+
const validationError = validateRunOptions(input);
|
|
266
|
+
if (validationError) return this.invalidInputResult(input, validationError);
|
|
267
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
268
|
+
const amountMinor = input.amountMinor ?? 5e5;
|
|
269
|
+
const currency = input.currency ?? "NGN";
|
|
270
|
+
const concurrency = input.concurrency ?? (input.scenario === "concurrent-duplicate-credit" || input.scenario === "concurrent-unique-payments" ? 2 : 1);
|
|
271
|
+
let references;
|
|
272
|
+
try {
|
|
273
|
+
references = await preparePaymentReferences({ ...input, amountMinor, currency }, this.options.createPayment);
|
|
274
|
+
} catch (error) {
|
|
275
|
+
return this.invalidInputResult(requestedInput, error instanceof Error ? error.message : String(error), "payment-preparation");
|
|
276
|
+
}
|
|
277
|
+
let primaryEvent;
|
|
278
|
+
let scenarioPlan;
|
|
279
|
+
let scenarioEvents;
|
|
280
|
+
let verificationCases;
|
|
281
|
+
try {
|
|
282
|
+
const baseEvent = this.options.provider.createPayment({
|
|
283
|
+
reference: references[0],
|
|
284
|
+
amountMinor,
|
|
285
|
+
currency
|
|
286
|
+
});
|
|
287
|
+
const providerInput = {
|
|
288
|
+
...input,
|
|
289
|
+
amountMinor,
|
|
290
|
+
currency,
|
|
291
|
+
concurrency,
|
|
292
|
+
reference: references[0],
|
|
293
|
+
references
|
|
294
|
+
};
|
|
295
|
+
scenarioPlan = this.options.provider.createScenario?.(input.scenario, providerInput);
|
|
296
|
+
primaryEvent = scenarioPlan?.deliveries.find((delivery) => delivery.event)?.event ?? baseEvent;
|
|
297
|
+
verificationCases = scenarioPlan?.verification?.map((item) => ({
|
|
298
|
+
event: item.event,
|
|
299
|
+
expected: item.expected ?? this.options.provider.expectedState(item.event)
|
|
300
|
+
})) ?? [{ event: primaryEvent, expected: this.options.provider.expectedState(primaryEvent) }];
|
|
301
|
+
scenarioEvents = Array.from(/* @__PURE__ */ new Set([
|
|
302
|
+
primaryEvent,
|
|
303
|
+
...scenarioPlan?.deliveries.map((delivery) => delivery.event).filter((event) => Boolean(event)) ?? [],
|
|
304
|
+
...scenarioPlan?.verification?.map((item) => item.event) ?? []
|
|
305
|
+
]));
|
|
306
|
+
if (input.scenario === "concurrent-unique-payments") {
|
|
307
|
+
const uniqueEvents = references.map((reference) => this.options.provider.createPayment({ reference, amountMinor, currency }));
|
|
308
|
+
primaryEvent = uniqueEvents[0];
|
|
309
|
+
scenarioEvents = uniqueEvents;
|
|
310
|
+
verificationCases = uniqueEvents.map((event) => ({ event, expected: this.options.provider.expectedState(event) }));
|
|
311
|
+
}
|
|
312
|
+
} catch (error) {
|
|
313
|
+
return this.invalidInputResult(input, `Payment preparation failed for ${input.scenario}: ${error instanceof Error ? error.message : String(error)}`, "payment-preparation");
|
|
314
|
+
}
|
|
315
|
+
const expected = verificationCases[0]?.expected ?? this.options.provider.expectedState(primaryEvent);
|
|
316
|
+
const report = {
|
|
317
|
+
reportVersion: "2.0",
|
|
318
|
+
scenario: input.scenario,
|
|
319
|
+
provider: this.options.provider.name,
|
|
320
|
+
paymentReference: primaryEvent.reference,
|
|
321
|
+
event: primaryEvent,
|
|
322
|
+
expected,
|
|
323
|
+
financiallyVerified: false,
|
|
324
|
+
deliveries: [],
|
|
325
|
+
errors: [],
|
|
326
|
+
startedAt
|
|
327
|
+
};
|
|
328
|
+
try {
|
|
329
|
+
if (scenarioPlan) {
|
|
330
|
+
await this.runScenarioPlan(scenarioPlan, primaryEvent, report);
|
|
331
|
+
} else if (input.scenario === "concurrent-duplicate-credit") {
|
|
332
|
+
const participants = Array.from({ length: concurrency }, (_, index) => `participant-${index + 1}`);
|
|
333
|
+
await Promise.all(participants.map((participant) => this.deliver(primaryEvent, participant, report)));
|
|
334
|
+
} else if (input.scenario === "sequential-duplicate-webhook") {
|
|
335
|
+
await this.deliver(primaryEvent, "sequential-1", report);
|
|
336
|
+
await this.deliver(primaryEvent, "sequential-2", report);
|
|
337
|
+
} else if (input.scenario === "concurrent-unique-payments") {
|
|
338
|
+
await Promise.all(scenarioEvents.map((event) => this.deliver(event, `unique-${event.reference}`, report)));
|
|
339
|
+
} else {
|
|
340
|
+
report.errors.push(`Unsupported scenario ${input.scenario}`);
|
|
341
|
+
report.failureType = "webhook-delivery";
|
|
342
|
+
}
|
|
343
|
+
await this.verifyPayments(input.scenario, scenarioEvents, verificationCases, report);
|
|
344
|
+
} catch (error) {
|
|
345
|
+
report.errors.push(error instanceof Error ? error.message : String(error));
|
|
346
|
+
report.failureType ??= "webhook-delivery";
|
|
347
|
+
} finally {
|
|
348
|
+
report.completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
349
|
+
}
|
|
350
|
+
return {
|
|
351
|
+
passed: report.errors.length === 0 && report.financiallyVerified && report.verification?.passed === true,
|
|
352
|
+
report
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
async runScenarioPlan(plan, primaryEvent, report) {
|
|
356
|
+
if (plan.concurrent) {
|
|
357
|
+
await Promise.all(plan.deliveries.map((delivery, index) => this.deliver(
|
|
358
|
+
delivery.event ?? primaryEvent,
|
|
359
|
+
delivery.participantId ?? `scenario-${index + 1}`,
|
|
360
|
+
report,
|
|
361
|
+
delivery
|
|
362
|
+
)));
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
for (const [index, delivery] of plan.deliveries.entries()) {
|
|
366
|
+
await this.deliver(
|
|
367
|
+
delivery.event ?? primaryEvent,
|
|
368
|
+
delivery.participantId ?? `scenario-${index + 1}`,
|
|
369
|
+
report,
|
|
370
|
+
delivery
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
async deliver(event, participantId, report, scenarioDelivery = {}) {
|
|
375
|
+
const delivery = {
|
|
376
|
+
deliveryId: randomUUID(),
|
|
377
|
+
participantId,
|
|
378
|
+
reference: event.reference,
|
|
379
|
+
eventId: eventId(event),
|
|
380
|
+
eventType: eventType(event),
|
|
381
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
382
|
+
expectedStatus: scenarioDelivery.expectedStatus
|
|
383
|
+
};
|
|
384
|
+
try {
|
|
385
|
+
if (scenarioDelivery.delayMs && scenarioDelivery.delayMs > 0) {
|
|
386
|
+
await new Promise((resolve) => setTimeout(resolve, scenarioDelivery.delayMs));
|
|
387
|
+
}
|
|
388
|
+
const body = this.options.provider.serialize(event);
|
|
389
|
+
const headers = {
|
|
390
|
+
"content-type": "application/json",
|
|
391
|
+
...this.options.provider.headersForBody?.(event, body) ?? this.options.provider.headers?.(event) ?? {}
|
|
392
|
+
};
|
|
393
|
+
const response = await fetch(this.options.webhookUrl, { method: "POST", headers, body });
|
|
394
|
+
delivery.status = response.status;
|
|
395
|
+
delivery.responseBody = await response.text();
|
|
396
|
+
const expectedStatus = scenarioDelivery.expectedStatus;
|
|
397
|
+
const accepted = expectedStatus === void 0 ? response.ok : matchesExpectedStatus(response.status, expectedStatus);
|
|
398
|
+
if (!accepted) {
|
|
399
|
+
const expectedText = expectedStatus === void 0 ? "a successful HTTP response" : `HTTP ${formatExpectedStatus(expectedStatus)}`;
|
|
400
|
+
delivery.error = `Webhook delivery ${participantId} expected ${expectedText} but received HTTP ${response.status}`;
|
|
401
|
+
report.errors.push(delivery.error);
|
|
402
|
+
report.failureType ??= "unexpected-http-response";
|
|
403
|
+
}
|
|
404
|
+
} catch (error) {
|
|
405
|
+
delivery.error = error instanceof Error ? error.message : String(error);
|
|
406
|
+
report.errors.push(`Webhook delivery ${participantId} failed: ${delivery.error}`);
|
|
407
|
+
report.failureType ??= "webhook-delivery";
|
|
408
|
+
} finally {
|
|
409
|
+
delivery.completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
410
|
+
report.deliveries.push(delivery);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
async verifyPayments(scenario, scenarioEvents, verificationCases, report) {
|
|
414
|
+
const results = [];
|
|
415
|
+
for (const { event, expected } of verificationCases) {
|
|
416
|
+
const relatedEvents = scenarioEvents.filter((candidate) => candidate.reference === event.reference);
|
|
417
|
+
const context = {
|
|
418
|
+
scenario,
|
|
419
|
+
paymentReference: event.reference,
|
|
420
|
+
expected,
|
|
421
|
+
expectedOutcome: {
|
|
422
|
+
eligible: expected.eligible,
|
|
423
|
+
expectedCreditCount: expected.expectedCreditCount,
|
|
424
|
+
amountMinor: expected.amountMinor,
|
|
425
|
+
currency: expected.currency
|
|
426
|
+
},
|
|
427
|
+
events: relatedEvents,
|
|
428
|
+
eventIdentifiers: relatedEvents.map(eventId).filter((value) => Boolean(value)),
|
|
429
|
+
deliveries: report.deliveries.filter((delivery) => delivery.reference === event.reference)
|
|
430
|
+
};
|
|
431
|
+
try {
|
|
432
|
+
const observed = await this.inspect(event.reference, expected, context);
|
|
433
|
+
results.push({ event, expected, observed, verification: verifyPaymentState(expected, observed) });
|
|
434
|
+
} catch (error) {
|
|
435
|
+
report.errors.push(error instanceof Error ? error.message : String(error));
|
|
436
|
+
report.failureType ??= failureTypeFor(error);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
if (results.length !== verificationCases.length) return;
|
|
440
|
+
report.financiallyVerified = true;
|
|
441
|
+
report.observed = results[0]?.observed;
|
|
442
|
+
report.verification = {
|
|
443
|
+
passed: results.every((result) => result.verification.passed),
|
|
444
|
+
violations: results.flatMap((result) => result.verification.violations)
|
|
445
|
+
};
|
|
446
|
+
if (results.length > 1) report.payments = results;
|
|
447
|
+
if (!report.verification.passed) {
|
|
448
|
+
report.failureType ??= "invariant-violation";
|
|
449
|
+
report.errors.push(...report.verification.violations.map((violation) => `${violation.id}: ${violation.message}`));
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
async inspect(reference, expected, context) {
|
|
453
|
+
const settings = this.options.financialVerification;
|
|
454
|
+
const timeoutMs = settings?.completionDeadlineMs ?? DEFAULT_TIMEOUT_MS;
|
|
455
|
+
const negativeDeadline = Date.now() + (expected.eligible ? 0 : settings?.negativeObservationWindowMs ?? DEFAULT_NEGATIVE_OBSERVATION_MS);
|
|
456
|
+
return verifyWithCallback(this.options.verify, reference, timeoutMs, context, {
|
|
457
|
+
pollIntervalMs: settings?.pollIntervalMs,
|
|
458
|
+
isComplete: (state) => verificationComplete(expected, state, negativeDeadline)
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
invalidInputResult(input, message, failureType = "webhook-delivery") {
|
|
462
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
463
|
+
const reference = "<payment-not-prepared>";
|
|
464
|
+
const event = {
|
|
465
|
+
reference,
|
|
466
|
+
amountMinor: input.amountMinor ?? 0,
|
|
467
|
+
currency: input.currency ?? "NGN",
|
|
468
|
+
status: "NOT_PREPARED"
|
|
469
|
+
};
|
|
470
|
+
const report = {
|
|
471
|
+
reportVersion: "2.0",
|
|
472
|
+
scenario: input.scenario,
|
|
473
|
+
provider: this.options.provider.name,
|
|
474
|
+
paymentReference: reference,
|
|
475
|
+
event,
|
|
476
|
+
expected: { reference, eligible: false, amountMinor: event.amountMinor, currency: event.currency, expectedCreditCount: 0 },
|
|
477
|
+
financiallyVerified: false,
|
|
478
|
+
deliveries: [],
|
|
479
|
+
errors: [message],
|
|
480
|
+
failureType,
|
|
481
|
+
startedAt,
|
|
482
|
+
completedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
483
|
+
};
|
|
484
|
+
return { passed: false, report };
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
async function writeReport(report, path) {
|
|
488
|
+
await mkdir(dirname(path), { recursive: true });
|
|
489
|
+
await writeFile(path, `${JSON.stringify(report, null, 2)}
|
|
490
|
+
`, "utf8");
|
|
491
|
+
}
|
|
492
|
+
function redactSecrets(value) {
|
|
493
|
+
return value.replace(/(authorization\s*[:=]\s*)([^,\s]+)/gi, "$1[REDACTED]").replace(/(token|secret|api[-_]?key)(\s*[:=]\s*)([^,\s]+)/gi, "$1$2[REDACTED]");
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// src/types.ts
|
|
497
|
+
var SUPPORTED_SCENARIOS = [
|
|
498
|
+
"sequential-duplicate-webhook",
|
|
499
|
+
"concurrent-duplicate-credit",
|
|
500
|
+
"concurrent-unique-payments",
|
|
501
|
+
"cross-event-duplicate-payment",
|
|
502
|
+
"out-of-order-events",
|
|
503
|
+
"incomplete-checkout",
|
|
504
|
+
"expired-checkout",
|
|
505
|
+
"incorrect-payment-amount",
|
|
506
|
+
"incorrect-payment-currency",
|
|
507
|
+
"underpaid-payment",
|
|
508
|
+
"failed-payment"
|
|
509
|
+
];
|
|
510
|
+
|
|
511
|
+
export { BachsProof, SUPPORTED_SCENARIOS, normalizeCallbackState, redactSecrets, verifyPaymentState, verifyWithCallback, writeReport };
|
|
512
|
+
//# sourceMappingURL=index.js.map
|
|
513
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/invariants.ts","../src/preparation.ts","../src/verification.ts","../src/orchestrator.ts","../src/reporting.ts","../src/types.ts"],"names":[],"mappings":";;;;;;;;AAMO,SAAS,kBAAA,CAAmB,UAAgC,QAAA,EAAoD;AACrH,EAAA,MAAM,aAAa,EAAC;AACpB,EAAA,IAAI,QAAA,CAAS,cAAc,CAAA,EAAG;AAC5B,IAAA,UAAA,CAAW,IAAA,CAAK;AAAA,MACd,EAAA,EAAI,SAAA;AAAA,MACJ,IAAA,EAAM,eAAA;AAAA,MACN,SAAS,CAAA,QAAA,EAAW,QAAA,CAAS,SAAS,CAAA,SAAA,EAAY,SAAS,WAAW,CAAA,uDAAA,CAAA;AAAA,MACtE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AA,EACA,kBAAA;AAAA,EACA,0BAAA;AAAA,EACA,4BAAA;AAAA,EACA,mBAAA;AAAA,EACA;AACF","file":"index.js","sourcesContent":["import type { ExpectedPaymentState, ObservedPaymentState, VerificationResult } from \"./types.js\";\n\n/**\n * Evaluate persisted financial state, not merely webhook HTTP responses.\n * These are the five v1 invariants carried forward unchanged in meaning.\n */\nexport function verifyPaymentState(expected: ExpectedPaymentState, observed: ObservedPaymentState): VerificationResult {\n const violations = [];\n if (observed.creditCount > 1) {\n violations.push({\n id: \"INV-001\" as const,\n name: \"Unique Credit\",\n message: `Payment ${expected.reference} created ${observed.creditCount} credits; one credit is allowed for an eligible payment`,\n reference: expected.reference\n });\n }\n if (observed.creditCount > 0 && (observed.creditedAmountMinor !== expected.amountMinor || observed.currency !== expected.currency)) {\n violations.push({\n id: \"INV-002\" as const,\n name: \"Amount Integrity\",\n message: `Expected one credit of ${expected.amountMinor} ${expected.currency} minor units, but observed ${observed.creditedAmountMinor} ${observed.currency} minor units`,\n reference: expected.reference\n });\n }\n if (expected.eligible && observed.creditCount < expected.expectedCreditCount) {\n violations.push({\n id: \"INV-003\" as const,\n name: \"Completion\",\n message: `Expected ${expected.expectedCreditCount} credit for ${expected.reference}, but observed ${observed.creditCount}`,\n reference: expected.reference\n });\n }\n if (!expected.eligible && observed.creditCount > 0) {\n violations.push({\n id: \"INV-004\" as const,\n name: \"No Unexpected Credit\",\n message: `Payment ${expected.reference} was not eligible, but it created ${observed.creditCount} credit(s)`,\n reference: expected.reference\n });\n }\n if (expected.eligible && observed.creditCount === expected.expectedCreditCount && observed.creditedAmountMinor !== expected.amountMinor) {\n violations.push({\n id: \"INV-005\" as const,\n name: \"Aggregate Integrity\",\n message: `Payment ${expected.reference} has the expected number of credits, but their total is not the expected amount`,\n reference: expected.reference\n });\n }\n return { passed: violations.length === 0, violations };\n}\n","import type { PaymentReferenceCreator, RunOptions } from \"./types.js\";\n\nconst DEFAULT_AMOUNT_MINOR = 500_000;\nconst DEFAULT_CURRENCY = \"NGN\";\n\nfunction hasReference(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction preparationError(scenario: RunOptions[\"scenario\"], index: number, error: unknown): Error {\n const detail = error instanceof Error ? error.message : String(error);\n return new Error(`Payment preparation failed for ${scenario} payment ${index + 1}: ${detail}`);\n}\n\nasync function createReference(\n input: RunOptions,\n createPayment: PaymentReferenceCreator,\n paymentIndex: number,\n paymentCount: number\n): Promise<string> {\n try {\n const reference = await createPayment({\n scenario: input.scenario,\n amountMinor: input.amountMinor ?? DEFAULT_AMOUNT_MINOR,\n currency: input.currency ?? DEFAULT_CURRENCY,\n paymentIndex,\n paymentCount\n });\n if (!hasReference(reference)) {\n throw new Error(\"createPayment must return a non-empty reference from the isolated test payment it created\");\n }\n return reference.trim();\n } catch (error) {\n throw preparationError(input.scenario, paymentIndex, error);\n }\n}\n\n/** Prepare one fresh application payment for every logical payment in a run. */\nexport async function preparePaymentReferences(\n input: RunOptions,\n createPayment: PaymentReferenceCreator\n): Promise<string[]> {\n const paymentCount = input.scenario === \"concurrent-unique-payments\" ? input.concurrency ?? 2 : 1;\n if (!Number.isInteger(paymentCount) || paymentCount < 1) {\n throw new Error(\"Payment preparation requires a positive payment count\");\n }\n const references: string[] = [];\n for (let paymentIndex = 0; paymentIndex < paymentCount; paymentIndex += 1) {\n references.push(await createReference(input, createPayment, paymentIndex, paymentCount));\n }\n if (new Set(references).size !== references.length) {\n throw new Error(`Payment preparation failed for ${input.scenario}: createPayment returned duplicate payment references`);\n }\n return references;\n}\n","import type { FinancialVerificationContext, FinancialVerifier, MinorUnitValue, ObservedPaymentState } from \"./types.js\";\n\nconst INTEGER = /^(?:0|[1-9]\\d*)$/;\n\nfunction safeMinorUnits(value: MinorUnitValue, path: string): number {\n let normalized: bigint;\n if (typeof value === \"bigint\") {\n normalized = value;\n } else if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`Financial verification callback returned invalid data at ${path}: expected a non-negative safe integer`);\n }\n return value;\n } else if (typeof value === \"string\" && INTEGER.test(value)) {\n normalized = BigInt(value);\n } else {\n throw new Error(`Financial verification callback returned invalid data at ${path}: expected a non-negative integer minor-unit amount`);\n }\n if (normalized < 0n || normalized > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(`Financial verification callback returned invalid data at ${path}: amount exceeds JavaScript safe integer range`);\n }\n return Number(normalized);\n}\n\nfunction callbackError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n return message.startsWith(\"Financial verification\")\n ? new Error(message)\n : new Error(`Financial verification failed: ${message}`);\n}\n\nfunction assertObject(value: unknown): asserts value is Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\"Financial verification callback returned invalid data: expected an object\");\n }\n}\n\nfunction requiredString(value: unknown, path: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new Error(`Financial verification callback returned invalid data at ${path}: expected a non-empty string`);\n }\n return value;\n}\n\nfunction optionalBoolean(value: unknown, path: string): boolean | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"boolean\") {\n throw new Error(`Financial verification callback returned invalid data at ${path}: expected boolean`);\n }\n return value;\n}\n\n/**\n * Normalize the callback contract without converting monetary values through\n * floating-point arithmetic. BigInt and integer database strings are accepted\n * when they fit inside JavaScript's safe integer range.\n */\nexport function normalizeCallbackState(value: unknown): ObservedPaymentState {\n assertObject(value);\n const reference = requiredString(value.reference, \"reference\");\n if (!Number.isSafeInteger(value.creditCount) || (value.creditCount as number) < 0) {\n throw new Error(\"Financial verification callback returned invalid data at creditCount: expected a non-negative safe integer\");\n }\n const currency = requiredString(value.currency, \"currency\").toUpperCase();\n if (!/^[A-Z]{3}$/.test(currency)) {\n throw new Error(\"Financial verification callback returned invalid data at currency: expected a three-letter ISO currency\");\n }\n const ledgerEntries: ObservedPaymentState[\"ledgerEntries\"] = [];\n if (value.ledgerEntries !== undefined) {\n if (!Array.isArray(value.ledgerEntries)) {\n throw new Error(\"Financial verification callback returned invalid data at ledgerEntries: expected an array\");\n }\n for (const [index, entryValue] of value.ledgerEntries.entries()) {\n assertObject(entryValue);\n ledgerEntries.push({\n id: requiredString(entryValue.id, `ledgerEntries[${index}].id`),\n type: requiredString(entryValue.type, `ledgerEntries[${index}].type`),\n amountMinor: safeMinorUnits(entryValue.amountMinor as MinorUnitValue, `ledgerEntries[${index}].amountMinor`),\n ...(entryValue.currency === undefined ? {} : { currency: requiredString(entryValue.currency, `ledgerEntries[${index}].currency`).toUpperCase() })\n });\n }\n }\n return {\n reference,\n status: value.status === undefined ? \"UNKNOWN\" : requiredString(value.status, \"status\"),\n currency,\n creditedAmountMinor: safeMinorUnits(value.creditedAmountMinor as MinorUnitValue, \"creditedAmountMinor\"),\n creditCount: value.creditCount as number,\n ...(value.pending === undefined ? {} : { pending: optionalBoolean(value.pending, \"pending\") }),\n ledgerEntries\n };\n}\n\nexport interface FinancialVerificationWaitOptions {\n pollIntervalMs?: number;\n /** Return only when the independently observed state is complete. */\n isComplete?: (state: ObservedPaymentState) => boolean;\n}\n\n/**\n * Execute a callback with a hard upper bound. JavaScript cannot forcibly stop\n * arbitrary user code, but the runner will stop waiting and report a timeout.\n */\nexport async function verifyWithCallback(\n verify: FinancialVerifier,\n reference: string,\n timeoutMs: number,\n context?: FinancialVerificationContext,\n options: FinancialVerificationWaitOptions = {}\n): Promise<ObservedPaymentState> {\n const deadline = Date.now() + timeoutMs;\n let lastObserved: ObservedPaymentState | undefined;\n let lastTimeout: Error | undefined;\n while (Date.now() <= deadline) {\n const remaining = Math.max(1, deadline - Date.now());\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`Financial verification timed out after ${timeoutMs}ms`)), remaining);\n });\n const value = await Promise.race([Promise.resolve().then(() => verify(reference, context)), timeout]);\n const normalized = normalizeCallbackState(value);\n if (normalized.reference !== reference) {\n throw new Error(`Financial verification returned ${normalized.reference} while ${reference} was requested`);\n }\n lastObserved = normalized;\n if (!options.isComplete || options.isComplete(normalized)) return normalized;\n } catch (error) {\n const candidate = callbackError(error);\n if (!candidate.message.startsWith(\"Financial verification timed out after \")) throw candidate;\n lastTimeout = candidate;\n } finally {\n if (timer) clearTimeout(timer);\n }\n const waitMs = Math.min(options.pollIntervalMs ?? 25, Math.max(1, deadline - Date.now()));\n if (Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, waitMs));\n }\n // A non-pending final state is usable evidence even if it violates a rule;\n // the invariant evaluator will report that violation instead of hiding it as\n // a timeout. A pending state is not a completed financial verification.\n if (lastObserved && !lastObserved.pending) return lastObserved;\n throw lastTimeout ?? new Error(`Financial verification timed out after ${timeoutMs}ms`);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { fetch } from \"undici\";\nimport { verifyPaymentState } from \"./invariants.js\";\nimport { preparePaymentReferences } from \"./preparation.js\";\nimport { verifyWithCallback } from \"./verification.js\";\nimport type {\n BachsProofOptions,\n BachsProofReport,\n BachsProofResult,\n DeliveryRecord,\n ExpectedHttpStatus,\n FinancialVerificationContext,\n ObservedPaymentState,\n PaymentEvent,\n ProviderScenario,\n ProviderScenarioDelivery,\n RunOptions,\n ScenarioName\n} from \"./types.js\";\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_NEGATIVE_OBSERVATION_MS = 250;\n\nfunction eventId(event: PaymentEvent): string | undefined {\n for (const key of [\"id\", \"eventId\", \"providerEventId\"]) {\n const value = event[key];\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return undefined;\n}\n\nfunction eventType(event: PaymentEvent): string | undefined {\n return typeof event.type === \"string\" ? event.type : undefined;\n}\n\nfunction matchesExpectedStatus(status: number, expected: ExpectedHttpStatus): boolean {\n if (Array.isArray(expected)) return expected.includes(status);\n if (expected === \"2xx\") return status >= 200 && status < 300;\n if (expected === \"4xx\") return status >= 400 && status < 500;\n if (expected === \"5xx\") return status >= 500 && status < 600;\n return status === expected;\n}\n\nfunction formatExpectedStatus(expected: ExpectedHttpStatus): string {\n return Array.isArray(expected) ? expected.join(\", \") : String(expected);\n}\n\nfunction validateRunOptions(input: RunOptions): string | undefined {\n if (input.concurrency !== undefined && (!Number.isInteger(input.concurrency) || input.concurrency < 1)) {\n return \"concurrency must be a positive integer\";\n }\n if (input.amountMinor !== undefined && (!Number.isSafeInteger(input.amountMinor) || input.amountMinor < 0)) {\n return \"amountMinor must be a non-negative safe integer in minor units\";\n }\n if (input.currency !== undefined && !/^[A-Z]{3}$/.test(input.currency)) {\n return \"currency must be a three-letter ISO currency code\";\n }\n return undefined;\n}\n\nfunction verificationComplete(expected: import(\"./types.js\").ExpectedPaymentState, state: ObservedPaymentState, negativeDeadline: number): boolean {\n if (state.pending) return false;\n if (expected.eligible) return state.creditCount > 0;\n return state.creditCount > 0 || Date.now() >= negativeDeadline;\n}\n\nfunction failureTypeFor(error: unknown): \"financial-verification\" | \"financial-verification-timeout\" {\n const message = error instanceof Error ? error.message : String(error);\n return message.includes(\"timed out\") ? \"financial-verification-timeout\" : \"financial-verification\";\n}\n\n/**\n * High-level v2 runner. It prepares real application payments, sends signed\n * local events, and always evaluates committed financial state before passing.\n */\nexport class BachsProof<TEvent extends PaymentEvent = PaymentEvent> {\n constructor(private readonly options: BachsProofOptions<TEvent>) {\n if (!options.createPayment) throw new Error(\"BachsProof requires a createPayment callback\");\n if (!options.verify) throw new Error(\"BachsProof requires a verify callback\");\n try {\n const url = new URL(options.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 requires a complete webhookUrl: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n async run(input: RunOptions): Promise<BachsProofResult> {\n const requestedInput = input;\n const validationError = validateRunOptions(input);\n if (validationError) return this.invalidInputResult(input, validationError);\n\n const startedAt = new Date().toISOString();\n const amountMinor = input.amountMinor ?? 500_000;\n const currency = input.currency ?? \"NGN\";\n const concurrency = input.concurrency ?? (input.scenario === \"concurrent-duplicate-credit\" || input.scenario === \"concurrent-unique-payments\" ? 2 : 1);\n\n let references: string[];\n try {\n references = await preparePaymentReferences({ ...input, amountMinor, currency }, this.options.createPayment);\n } catch (error) {\n return this.invalidInputResult(requestedInput, error instanceof Error ? error.message : String(error), \"payment-preparation\");\n }\n\n let primaryEvent: TEvent;\n let scenarioPlan: ProviderScenario<TEvent> | undefined;\n let scenarioEvents: TEvent[];\n let verificationCases: Array<{ event: TEvent; expected: import(\"./types.js\").ExpectedPaymentState }>;\n try {\n const baseEvent = this.options.provider.createPayment({\n reference: references[0]!,\n amountMinor,\n currency\n });\n const providerInput = {\n ...input,\n amountMinor,\n currency,\n concurrency,\n reference: references[0]!,\n references\n };\n scenarioPlan = this.options.provider.createScenario?.(input.scenario, providerInput);\n primaryEvent = scenarioPlan?.deliveries.find((delivery) => delivery.event)?.event ?? baseEvent;\n verificationCases = scenarioPlan?.verification?.map((item) => ({\n event: item.event,\n expected: item.expected ?? this.options.provider.expectedState(item.event)\n })) ?? [{ event: primaryEvent, expected: this.options.provider.expectedState(primaryEvent) }];\n scenarioEvents = Array.from(new Set([\n primaryEvent,\n ...(scenarioPlan?.deliveries.map((delivery) => delivery.event).filter((event): event is TEvent => Boolean(event)) ?? []),\n ...(scenarioPlan?.verification?.map((item) => item.event) ?? [])\n ]));\n\n if (input.scenario === \"concurrent-unique-payments\") {\n const uniqueEvents = references.map((reference) => this.options.provider.createPayment({ reference, amountMinor, currency }));\n primaryEvent = uniqueEvents[0]!;\n scenarioEvents = uniqueEvents;\n verificationCases = uniqueEvents.map((event) => ({ event, expected: this.options.provider.expectedState(event) }));\n }\n } catch (error) {\n return this.invalidInputResult(input, `Payment preparation failed for ${input.scenario}: ${error instanceof Error ? error.message : String(error)}`, \"payment-preparation\");\n }\n\n const expected = verificationCases[0]?.expected ?? this.options.provider.expectedState(primaryEvent);\n const report: BachsProofReport = {\n reportVersion: \"2.0\",\n scenario: input.scenario,\n provider: this.options.provider.name,\n paymentReference: primaryEvent.reference,\n event: primaryEvent,\n expected,\n financiallyVerified: false,\n deliveries: [],\n errors: [],\n startedAt\n };\n\n try {\n if (scenarioPlan) {\n await this.runScenarioPlan(scenarioPlan, primaryEvent, report);\n } else if (input.scenario === \"concurrent-duplicate-credit\") {\n const participants = Array.from({ length: concurrency }, (_, index) => `participant-${index + 1}`);\n await Promise.all(participants.map((participant) => this.deliver(primaryEvent, participant, report)));\n } else if (input.scenario === \"sequential-duplicate-webhook\") {\n await this.deliver(primaryEvent, \"sequential-1\", report);\n await this.deliver(primaryEvent, \"sequential-2\", report);\n } else if (input.scenario === \"concurrent-unique-payments\") {\n await Promise.all(scenarioEvents.map((event) => this.deliver(event, `unique-${event.reference}`, report)));\n } else {\n report.errors.push(`Unsupported scenario ${input.scenario}`);\n report.failureType = \"webhook-delivery\";\n }\n\n await this.verifyPayments(input.scenario, scenarioEvents, verificationCases, report);\n } catch (error) {\n report.errors.push(error instanceof Error ? error.message : String(error));\n report.failureType ??= \"webhook-delivery\";\n } finally {\n report.completedAt = new Date().toISOString();\n }\n\n return {\n passed: report.errors.length === 0 && report.financiallyVerified && report.verification?.passed === true,\n report\n };\n }\n\n private async runScenarioPlan(plan: ProviderScenario<TEvent>, primaryEvent: TEvent, report: BachsProofReport): Promise<void> {\n if (plan.concurrent) {\n await Promise.all(plan.deliveries.map((delivery, index) => this.deliver(\n delivery.event ?? primaryEvent,\n delivery.participantId ?? `scenario-${index + 1}`,\n report,\n delivery\n )));\n return;\n }\n for (const [index, delivery] of plan.deliveries.entries()) {\n await this.deliver(\n delivery.event ?? primaryEvent,\n delivery.participantId ?? `scenario-${index + 1}`,\n report,\n delivery\n );\n }\n }\n\n private async deliver(\n event: TEvent,\n participantId: string,\n report: BachsProofReport,\n scenarioDelivery: ProviderScenarioDelivery<TEvent> = {}\n ): Promise<void> {\n const delivery: DeliveryRecord = {\n deliveryId: randomUUID(),\n participantId,\n reference: event.reference,\n eventId: eventId(event),\n eventType: eventType(event),\n startedAt: new Date().toISOString(),\n expectedStatus: scenarioDelivery.expectedStatus\n };\n try {\n if (scenarioDelivery.delayMs && scenarioDelivery.delayMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, scenarioDelivery.delayMs));\n }\n const body = this.options.provider.serialize(event);\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...(this.options.provider.headersForBody?.(event, body) ?? this.options.provider.headers?.(event) ?? {})\n };\n const response = await fetch(this.options.webhookUrl, { method: \"POST\", headers, body });\n delivery.status = response.status;\n delivery.responseBody = await response.text();\n const expectedStatus = scenarioDelivery.expectedStatus;\n const accepted = expectedStatus === undefined ? response.ok : matchesExpectedStatus(response.status, expectedStatus);\n if (!accepted) {\n const expectedText = expectedStatus === undefined ? \"a successful HTTP response\" : `HTTP ${formatExpectedStatus(expectedStatus)}`;\n delivery.error = `Webhook delivery ${participantId} expected ${expectedText} but received HTTP ${response.status}`;\n report.errors.push(delivery.error);\n report.failureType ??= \"unexpected-http-response\";\n }\n } catch (error) {\n delivery.error = error instanceof Error ? error.message : String(error);\n report.errors.push(`Webhook delivery ${participantId} failed: ${delivery.error}`);\n report.failureType ??= \"webhook-delivery\";\n } finally {\n delivery.completedAt = new Date().toISOString();\n report.deliveries.push(delivery);\n }\n }\n\n private async verifyPayments(\n scenario: ScenarioName,\n scenarioEvents: TEvent[],\n verificationCases: Array<{ event: TEvent; expected: import(\"./types.js\").ExpectedPaymentState }>,\n report: BachsProofReport\n ): Promise<void> {\n const results: Array<{\n event: TEvent;\n expected: import(\"./types.js\").ExpectedPaymentState;\n observed: ObservedPaymentState;\n verification: import(\"./types.js\").VerificationResult;\n }> = [];\n for (const { event, expected } of verificationCases) {\n const relatedEvents = scenarioEvents.filter((candidate) => candidate.reference === event.reference);\n const context: FinancialVerificationContext = {\n scenario,\n paymentReference: event.reference,\n expected,\n expectedOutcome: {\n eligible: expected.eligible,\n expectedCreditCount: expected.expectedCreditCount,\n amountMinor: expected.amountMinor,\n currency: expected.currency\n },\n events: relatedEvents,\n eventIdentifiers: relatedEvents.map(eventId).filter((value): value is string => Boolean(value)),\n deliveries: report.deliveries.filter((delivery) => delivery.reference === event.reference)\n };\n try {\n const observed = await this.inspect(event.reference, expected, context);\n results.push({ event, expected, observed, verification: verifyPaymentState(expected, observed) });\n } catch (error) {\n report.errors.push(error instanceof Error ? error.message : String(error));\n report.failureType ??= failureTypeFor(error);\n }\n }\n\n if (results.length !== verificationCases.length) return;\n report.financiallyVerified = true;\n report.observed = results[0]?.observed;\n report.verification = {\n passed: results.every((result) => result.verification.passed),\n violations: results.flatMap((result) => result.verification.violations)\n };\n if (results.length > 1) report.payments = results;\n if (!report.verification.passed) {\n report.failureType ??= \"invariant-violation\";\n report.errors.push(...report.verification.violations.map((violation) => `${violation.id}: ${violation.message}`));\n }\n }\n\n private async inspect(reference: string, expected: import(\"./types.js\").ExpectedPaymentState, context: FinancialVerificationContext): Promise<ObservedPaymentState> {\n const settings = this.options.financialVerification;\n const timeoutMs = settings?.completionDeadlineMs ?? DEFAULT_TIMEOUT_MS;\n const negativeDeadline = Date.now() + (expected.eligible ? 0 : settings?.negativeObservationWindowMs ?? DEFAULT_NEGATIVE_OBSERVATION_MS);\n return verifyWithCallback(this.options.verify, reference, timeoutMs, context, {\n pollIntervalMs: settings?.pollIntervalMs,\n isComplete: (state) => verificationComplete(expected, state, negativeDeadline)\n });\n }\n\n private invalidInputResult(input: RunOptions, message: string, failureType: \"payment-preparation\" | \"webhook-delivery\" = \"webhook-delivery\"): BachsProofResult {\n const startedAt = new Date().toISOString();\n const reference = \"<payment-not-prepared>\";\n const event: PaymentEvent = {\n reference,\n amountMinor: input.amountMinor ?? 0,\n currency: input.currency ?? \"NGN\",\n status: \"NOT_PREPARED\"\n };\n const report: BachsProofReport = {\n reportVersion: \"2.0\",\n scenario: input.scenario,\n provider: this.options.provider.name,\n paymentReference: reference,\n event,\n expected: { reference, eligible: false, amountMinor: event.amountMinor, currency: event.currency, expectedCreditCount: 0 },\n financiallyVerified: false,\n deliveries: [],\n errors: [message],\n failureType,\n startedAt,\n completedAt: new Date().toISOString()\n };\n return { passed: false, report };\n }\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { BachsProofReport } from \"./types.js\";\n\n/** Write a human-readable JSON report and create its parent directory. */\nexport async function writeReport(report: BachsProofReport, path: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, `${JSON.stringify(report, null, 2)}\\n`, \"utf8\");\n}\n\n/** Remove common credential formats before a diagnostic string enters a report. */\nexport function redactSecrets(value: string): string {\n return value.replace(/(authorization\\s*[:=]\\s*)([^,\\s]+)/gi, \"$1[REDACTED]\").replace(/(token|secret|api[-_]?key)(\\s*[:=]\\s*)([^,\\s]+)/gi, \"$1$2[REDACTED]\");\n}\n","/** The eleven financial correctness scenarios supported by BachsProof v2. */\nexport const SUPPORTED_SCENARIOS = [\n \"sequential-duplicate-webhook\",\n \"concurrent-duplicate-credit\",\n \"concurrent-unique-payments\",\n \"cross-event-duplicate-payment\",\n \"out-of-order-events\",\n \"incomplete-checkout\",\n \"expired-checkout\",\n \"incorrect-payment-amount\",\n \"incorrect-payment-currency\",\n \"underpaid-payment\",\n \"failed-payment\"\n] as const;\n\nexport type ScenarioName = typeof SUPPORTED_SCENARIOS[number];\n\n/** Minimal shape every provider adapter event must expose to the core engine. */\nexport interface PaymentEvent {\n reference: string;\n amountMinor: number;\n currency: string;\n status: string;\n [key: string]: unknown;\n}\n\n/** Context supplied to a financial verifier for one inspected reference. */\nexport interface FinancialVerificationContext {\n scenario: ScenarioName;\n paymentReference: string;\n expected: ExpectedPaymentState;\n expectedOutcome: {\n eligible: boolean;\n expectedCreditCount: number;\n amountMinor: number;\n currency: string;\n };\n events: PaymentEvent[];\n eventIdentifiers: string[];\n deliveries: DeliveryRecord[];\n}\n\n/** Information needed to create one fresh application payment. */\nexport interface PaymentPreparationContext {\n scenario: ScenarioName;\n amountMinor: number;\n currency: string;\n /** Zero-based index within the payments required by this scenario. */\n paymentIndex: number;\n paymentCount: number;\n}\n\n/** Create a fresh application payment/order and return its reference. */\nexport type PaymentReferenceCreator = (context: PaymentPreparationContext) => Promise<string> | string;\n\n/** The state the application should have after processing one synthetic event. */\nexport interface ExpectedPaymentState {\n reference: string;\n eligible: boolean;\n amountMinor: number;\n currency: string;\n expectedCreditCount: number;\n}\n\nexport type ExpectedHttpStatus = number | number[] | \"2xx\" | \"4xx\" | \"5xx\";\n\n/** One raw webhook delivery in a provider-defined scenario. */\nexport interface ProviderScenarioDelivery<TEvent extends PaymentEvent = PaymentEvent> {\n event?: TEvent;\n participantId?: string;\n delayMs?: number;\n expectedStatus?: ExpectedHttpStatus;\n}\n\n/** Optional provider-specific delivery plan for a named scenario. */\nexport interface ProviderScenario<TEvent extends PaymentEvent = PaymentEvent> {\n deliveries: ProviderScenarioDelivery<TEvent>[];\n /** Deliver all entries together when true; otherwise preserve listed order. */\n concurrent?: boolean;\n /** State entries to inspect after delivery, with scenario-specific expectations. */\n verification?: Array<{\n event: TEvent;\n expected?: ExpectedPaymentState;\n }>;\n}\n\n/** Internal input available to an adapter after application payment preparation. */\nexport interface ProviderScenarioInput extends RunOptions {\n reference: string;\n references: string[];\n}\n\n/**\n * Provider plug-in contract. The core never knows how a Bachs event (or a\n * future provider event) is shaped on the wire; it only uses this contract.\n */\nexport interface ProviderAdapter<TEvent extends PaymentEvent = PaymentEvent> {\n readonly name: string;\n readonly mode: string;\n createPayment(input: {\n reference: string;\n amountMinor: number;\n currency: string;\n eligible?: boolean;\n customerId?: string;\n }): TEvent;\n serialize(event: TEvent): string;\n expectedState(event: TEvent): ExpectedPaymentState;\n headers?(event: TEvent): Record<string, string>;\n /** Optional signing hook that receives the exact bytes used for the request. */\n headersForBody?(event: TEvent, body: string | Uint8Array): Record<string, string>;\n /** Provider adapters expose only the supported financial scenarios. */\n createScenario?(scenario: ScenarioName, input: ProviderScenarioInput): ProviderScenario<TEvent> | undefined;\n}\n\n/** Minor-unit values accepted from database adapters without unsafe conversion. */\nexport type MinorUnitValue = number | bigint | string;\n\n/** Normalized persisted financial state returned by a developer verifier. */\nexport interface ObservedPaymentState {\n reference: string;\n status: string;\n currency: string;\n creditedAmountMinor: number;\n creditCount: number;\n /** True while relevant application work is still incomplete. */\n pending?: boolean;\n ledgerEntries: Array<{\n id: string;\n type: string;\n amountMinor: number;\n currency?: string;\n }>;\n}\n\nexport type InvariantId = \"INV-001\" | \"INV-002\" | \"INV-003\" | \"INV-004\" | \"INV-005\";\n\nexport interface InvariantViolation {\n id: InvariantId;\n name: string;\n message: string;\n reference: string;\n}\n\n/** Result of evaluating all five financial invariants for one reference. */\nexport interface VerificationResult {\n passed: boolean;\n violations: InvariantViolation[];\n}\n\n/** One attempted webhook delivery, including its HTTP outcome and timing. */\nexport interface DeliveryRecord {\n deliveryId: string;\n participantId: string;\n reference: string;\n eventId?: string;\n eventType?: string;\n startedAt: string;\n completedAt?: string;\n status?: number;\n responseBody?: string;\n expectedStatus?: ProviderScenarioDelivery[\"expectedStatus\"];\n error?: string;\n}\n\nexport type FailureType =\n | \"payment-preparation\"\n | \"webhook-delivery\"\n | \"unexpected-http-response\"\n | \"financial-verification\"\n | \"financial-verification-timeout\"\n | \"invariant-violation\";\n\n/** Structured report for automation and debugging. */\nexport interface BachsProofReport {\n reportVersion: \"2.0\";\n scenario: ScenarioName;\n provider: string;\n paymentReference: string;\n event: PaymentEvent;\n expected: ExpectedPaymentState;\n observed?: ObservedPaymentState;\n verification?: VerificationResult;\n /** True only when the verifier returned independently observed state. */\n financiallyVerified: boolean;\n payments?: Array<{\n event: PaymentEvent;\n expected: ExpectedPaymentState;\n observed: ObservedPaymentState;\n verification: VerificationResult;\n }>;\n deliveries: DeliveryRecord[];\n errors: string[];\n failureType?: FailureType;\n startedAt: string;\n completedAt?: string;\n}\n\nexport interface BachsProofResult {\n passed: boolean;\n report: BachsProofReport;\n}\n\n/** Callback polling and observation settings used internally by the CLI. */\nexport interface FinancialVerificationOptions {\n completionDeadlineMs?: number;\n pollIntervalMs?: number;\n /** How long a negative scenario must remain observed with no credit. */\n negativeObservationWindowMs?: number;\n}\n\n/** Public shape returned by the developer's financial verification callback. */\nexport interface FinancialVerificationInput {\n reference: string;\n creditCount: number;\n creditedAmountMinor: MinorUnitValue;\n currency: string;\n status?: string;\n pending?: boolean;\n ledgerEntries?: Array<{\n id: string;\n type: string;\n amountMinor: MinorUnitValue;\n currency?: string;\n }>;\n}\n\n/** One-argument callbacks remain valid; the second argument is optional. */\nexport type FinancialVerifier = (reference: string, context?: FinancialVerificationContext) => Promise<FinancialVerificationInput> | FinancialVerificationInput;\n\n/** Internal runner options. The CLI is the supported public entry point. */\nexport interface BachsProofOptions<TEvent extends PaymentEvent = PaymentEvent> {\n provider: ProviderAdapter<TEvent>;\n webhookUrl: string;\n createPayment: PaymentReferenceCreator;\n verify: FinancialVerifier;\n financialVerification?: FinancialVerificationOptions;\n}\n\n/** Per-run settings created by the simplified CLI configuration. */\nexport interface RunOptions {\n scenario: ScenarioName;\n concurrency?: number;\n amountMinor?: number;\n currency?: string;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bachsproof/core",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Core financial correctness test runner for BachsProof applications",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"payments",
|
|
7
|
+
"payment-testing",
|
|
8
|
+
"webhooks",
|
|
9
|
+
"idempotency",
|
|
10
|
+
"concurrency",
|
|
11
|
+
"typescript"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/therealEmma/BachsProof.git",
|
|
17
|
+
"directory": "packages/core"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/therealEmma/BachsProof#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/therealEmma/BachsProof/issues"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"type": "module",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"import": "./dist/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"main": "./dist/index.js",
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=22"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"undici": "^7.4.0",
|
|
45
|
+
"zod": "^3.24.1"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/node": "^22.10.0",
|
|
49
|
+
"tsup": "^8.3.5",
|
|
50
|
+
"typescript": "^5.7.2"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "tsup"
|
|
54
|
+
}
|
|
6
55
|
}
|