@bachsproof/core 1.1.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -54
- package/dist/index.d.ts +50 -198
- package/dist/index.js +291 -510
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,214 +1,9 @@
|
|
|
1
1
|
import { randomUUID } from 'crypto';
|
|
2
2
|
import { fetch } from 'undici';
|
|
3
|
-
import { createServer } from 'http';
|
|
4
|
-
import { z } from 'zod';
|
|
5
3
|
import { mkdir, writeFile } from 'fs/promises';
|
|
6
4
|
import { dirname } from 'path';
|
|
7
5
|
|
|
8
6
|
// src/orchestrator.ts
|
|
9
|
-
var RaceController = class {
|
|
10
|
-
server;
|
|
11
|
-
sessions = /* @__PURE__ */ new Map();
|
|
12
|
-
address;
|
|
13
|
-
closed = false;
|
|
14
|
-
constructor() {
|
|
15
|
-
this.server = createServer((request, response) => {
|
|
16
|
-
void this.handle(request, response);
|
|
17
|
-
});
|
|
18
|
-
}
|
|
19
|
-
async start() {
|
|
20
|
-
if (this.address) return;
|
|
21
|
-
await new Promise((resolve, reject) => {
|
|
22
|
-
const onError = (error) => {
|
|
23
|
-
this.server.off("listening", onListening);
|
|
24
|
-
reject(error);
|
|
25
|
-
};
|
|
26
|
-
const onListening = () => {
|
|
27
|
-
this.server.off("error", onError);
|
|
28
|
-
const address = this.server.address();
|
|
29
|
-
if (!address || typeof address === "string") {
|
|
30
|
-
reject(new Error("BachsProof race controller did not receive a network address"));
|
|
31
|
-
return;
|
|
32
|
-
}
|
|
33
|
-
this.address = { host: "127.0.0.1", port: address.port };
|
|
34
|
-
resolve();
|
|
35
|
-
};
|
|
36
|
-
this.server.once("error", onError);
|
|
37
|
-
this.server.once("listening", onListening);
|
|
38
|
-
this.server.listen(0, "127.0.0.1");
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
async registerSession(input) {
|
|
42
|
-
await this.start();
|
|
43
|
-
if (this.closed) throw new Error("BachsProof race controller is closed");
|
|
44
|
-
if (input.participants.length === 0 || new Set(input.participants).size !== input.participants.length) {
|
|
45
|
-
throw new Error("A race session requires one or more unique participants");
|
|
46
|
-
}
|
|
47
|
-
const id = input.id ?? randomUUID();
|
|
48
|
-
const token = input.token ?? randomUUID();
|
|
49
|
-
this.sessions.set(id, {
|
|
50
|
-
id,
|
|
51
|
-
token,
|
|
52
|
-
participants: new Set(input.participants),
|
|
53
|
-
checkpoints: /* @__PURE__ */ new Map(),
|
|
54
|
-
trace: [],
|
|
55
|
-
waiters: []
|
|
56
|
-
});
|
|
57
|
-
return {
|
|
58
|
-
id,
|
|
59
|
-
token,
|
|
60
|
-
controllerUrl: `http://${this.address?.host}:${this.address?.port}`,
|
|
61
|
-
participants: [...input.participants]
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
async waitForArrivals(sessionId, checkpoint, count, timeoutMs = 1e4) {
|
|
65
|
-
const session = this.session(sessionId);
|
|
66
|
-
const state = this.checkpointState(session, checkpoint);
|
|
67
|
-
if (state.arrivals.size >= count) return;
|
|
68
|
-
await new Promise((resolve, reject) => {
|
|
69
|
-
const timer = setTimeout(() => {
|
|
70
|
-
session.waiters = session.waiters.filter((waiter) => waiter.resolve !== resolve);
|
|
71
|
-
reject(new Error(`Timed out waiting for ${count} participants at checkpoint ${checkpoint}`));
|
|
72
|
-
}, timeoutMs);
|
|
73
|
-
session.waiters.push({ checkpoint, count, resolve, reject, timer });
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
release(sessionId, checkpoint) {
|
|
77
|
-
const session = this.session(sessionId);
|
|
78
|
-
const state = this.checkpointState(session, checkpoint);
|
|
79
|
-
if (state.released) return;
|
|
80
|
-
state.released = true;
|
|
81
|
-
session.trace.push({
|
|
82
|
-
type: "release",
|
|
83
|
-
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
84
|
-
sessionId,
|
|
85
|
-
checkpoint
|
|
86
|
-
});
|
|
87
|
-
for (const pending of state.pending.values()) {
|
|
88
|
-
this.finishResponse(pending.response, 200, { released: true });
|
|
89
|
-
}
|
|
90
|
-
state.pending.clear();
|
|
91
|
-
}
|
|
92
|
-
abort(sessionId, reason) {
|
|
93
|
-
const session = this.session(sessionId);
|
|
94
|
-
for (const [checkpoint, state] of session.checkpoints) {
|
|
95
|
-
session.trace.push({ type: "abort", at: (/* @__PURE__ */ new Date()).toISOString(), sessionId, checkpoint, reason });
|
|
96
|
-
for (const pending of state.pending.values()) {
|
|
97
|
-
this.finishResponse(pending.response, 409, { error: reason });
|
|
98
|
-
}
|
|
99
|
-
state.pending.clear();
|
|
100
|
-
state.released = true;
|
|
101
|
-
state.aborted = true;
|
|
102
|
-
state.abortReason = reason;
|
|
103
|
-
}
|
|
104
|
-
for (const waiter of session.waiters) {
|
|
105
|
-
clearTimeout(waiter.timer);
|
|
106
|
-
waiter.reject(new Error(reason));
|
|
107
|
-
}
|
|
108
|
-
session.waiters = [];
|
|
109
|
-
}
|
|
110
|
-
getTrace(sessionId) {
|
|
111
|
-
return [...this.session(sessionId).trace];
|
|
112
|
-
}
|
|
113
|
-
cleanupSession(sessionId) {
|
|
114
|
-
if (!this.sessions.has(sessionId)) return;
|
|
115
|
-
try {
|
|
116
|
-
this.abort(sessionId, "session-cleanup");
|
|
117
|
-
} catch {
|
|
118
|
-
}
|
|
119
|
-
this.sessions.delete(sessionId);
|
|
120
|
-
}
|
|
121
|
-
async close() {
|
|
122
|
-
if (this.closed) return;
|
|
123
|
-
this.closed = true;
|
|
124
|
-
for (const sessionId of this.sessions.keys()) this.cleanupSession(sessionId);
|
|
125
|
-
await new Promise((resolve) => this.server.close(() => resolve()));
|
|
126
|
-
}
|
|
127
|
-
session(id) {
|
|
128
|
-
const session = this.sessions.get(id);
|
|
129
|
-
if (!session) throw new Error(`Unknown BachsProof session ${id}`);
|
|
130
|
-
return session;
|
|
131
|
-
}
|
|
132
|
-
checkpointState(session, name) {
|
|
133
|
-
let state = session.checkpoints.get(name);
|
|
134
|
-
if (!state) {
|
|
135
|
-
state = { arrivals: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map(), released: false, aborted: false };
|
|
136
|
-
session.checkpoints.set(name, state);
|
|
137
|
-
}
|
|
138
|
-
return state;
|
|
139
|
-
}
|
|
140
|
-
async handle(request, response) {
|
|
141
|
-
try {
|
|
142
|
-
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
143
|
-
const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
|
|
144
|
-
if (request.method !== "POST" || parts.length !== 5 || parts[0] !== "sessions" || parts[2] !== "checkpoints" || parts[4] !== "arrive") {
|
|
145
|
-
this.finishResponse(response, 404, { error: "not-found" });
|
|
146
|
-
return;
|
|
147
|
-
}
|
|
148
|
-
const sessionId = parts[1];
|
|
149
|
-
const checkpoint = parts[3];
|
|
150
|
-
if (!sessionId || !checkpoint) {
|
|
151
|
-
this.finishResponse(response, 400, { error: "invalid-route" });
|
|
152
|
-
return;
|
|
153
|
-
}
|
|
154
|
-
const session = this.session(sessionId);
|
|
155
|
-
if (request.headers.authorization !== `Bearer ${session.token}`) {
|
|
156
|
-
this.finishResponse(response, 401, { error: "unauthorized" });
|
|
157
|
-
return;
|
|
158
|
-
}
|
|
159
|
-
const body = await this.readJson(request);
|
|
160
|
-
if (!body.participantId || !session.participants.has(body.participantId)) {
|
|
161
|
-
this.finishResponse(response, 400, { error: "unknown-participant" });
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
const state = this.checkpointState(session, checkpoint);
|
|
165
|
-
if (state.arrivals.has(body.participantId)) {
|
|
166
|
-
this.finishResponse(response, 409, { error: "duplicate-arrival" });
|
|
167
|
-
return;
|
|
168
|
-
}
|
|
169
|
-
state.arrivals.set(body.participantId, body);
|
|
170
|
-
session.trace.push({
|
|
171
|
-
type: "arrival",
|
|
172
|
-
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
173
|
-
sessionId,
|
|
174
|
-
checkpoint,
|
|
175
|
-
participantId: body.participantId,
|
|
176
|
-
key: body.key,
|
|
177
|
-
metadata: body.metadata
|
|
178
|
-
});
|
|
179
|
-
this.resolveReadyWaiters(session, checkpoint, state.arrivals.size);
|
|
180
|
-
if (state.aborted) {
|
|
181
|
-
this.finishResponse(response, 409, { error: state.abortReason ?? "session-aborted" });
|
|
182
|
-
} else if (state.released) {
|
|
183
|
-
this.finishResponse(response, 200, { released: true });
|
|
184
|
-
} else {
|
|
185
|
-
state.pending.set(body.participantId, { response, sessionId, checkpoint });
|
|
186
|
-
}
|
|
187
|
-
} catch (error) {
|
|
188
|
-
this.finishResponse(response, 500, { error: error instanceof Error ? error.message : "controller-error" });
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
resolveReadyWaiters(session, checkpoint, arrivalCount) {
|
|
192
|
-
for (const waiter of [...session.waiters]) {
|
|
193
|
-
if (waiter.checkpoint !== checkpoint || arrivalCount < waiter.count) continue;
|
|
194
|
-
clearTimeout(waiter.timer);
|
|
195
|
-
session.waiters = session.waiters.filter((candidate) => candidate !== waiter);
|
|
196
|
-
waiter.resolve();
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
async readJson(request) {
|
|
200
|
-
const chunks = [];
|
|
201
|
-
for await (const chunk of request) chunks.push(Buffer.from(chunk));
|
|
202
|
-
if (chunks.length === 0) return {};
|
|
203
|
-
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
204
|
-
}
|
|
205
|
-
finishResponse(response, status, body) {
|
|
206
|
-
if (response.writableEnded) return;
|
|
207
|
-
response.statusCode = status;
|
|
208
|
-
response.setHeader("content-type", "application/json");
|
|
209
|
-
response.end(JSON.stringify(body));
|
|
210
|
-
}
|
|
211
|
-
};
|
|
212
7
|
|
|
213
8
|
// src/invariants.ts
|
|
214
9
|
function verifyPaymentState(expected, observed) {
|
|
@@ -217,7 +12,7 @@ function verifyPaymentState(expected, observed) {
|
|
|
217
12
|
violations.push({
|
|
218
13
|
id: "INV-001",
|
|
219
14
|
name: "Unique Credit",
|
|
220
|
-
message: `Payment ${expected.reference}
|
|
15
|
+
message: `Payment ${expected.reference} created ${observed.creditCount} credits; one credit is allowed for an eligible payment`,
|
|
221
16
|
reference: expected.reference
|
|
222
17
|
});
|
|
223
18
|
}
|
|
@@ -225,7 +20,7 @@ function verifyPaymentState(expected, observed) {
|
|
|
225
20
|
violations.push({
|
|
226
21
|
id: "INV-002",
|
|
227
22
|
name: "Amount Integrity",
|
|
228
|
-
message: `Expected ${expected.amountMinor} ${expected.currency}, observed ${observed.creditedAmountMinor} ${observed.currency}`,
|
|
23
|
+
message: `Expected one credit of ${expected.amountMinor} ${expected.currency} minor units, but observed ${observed.creditedAmountMinor} ${observed.currency} minor units`,
|
|
229
24
|
reference: expected.reference
|
|
230
25
|
});
|
|
231
26
|
}
|
|
@@ -233,7 +28,7 @@ function verifyPaymentState(expected, observed) {
|
|
|
233
28
|
violations.push({
|
|
234
29
|
id: "INV-003",
|
|
235
30
|
name: "Completion",
|
|
236
|
-
message: `Expected ${expected.expectedCreditCount} credit for ${expected.reference}, observed ${observed.creditCount}`,
|
|
31
|
+
message: `Expected ${expected.expectedCreditCount} credit for ${expected.reference}, but observed ${observed.creditCount}`,
|
|
237
32
|
reference: expected.reference
|
|
238
33
|
});
|
|
239
34
|
}
|
|
@@ -241,7 +36,7 @@ function verifyPaymentState(expected, observed) {
|
|
|
241
36
|
violations.push({
|
|
242
37
|
id: "INV-004",
|
|
243
38
|
name: "No Unexpected Credit",
|
|
244
|
-
message: `
|
|
39
|
+
message: `Payment ${expected.reference} was not eligible, but it created ${observed.creditCount} credit(s)`,
|
|
245
40
|
reference: expected.reference
|
|
246
41
|
});
|
|
247
42
|
}
|
|
@@ -249,7 +44,7 @@ function verifyPaymentState(expected, observed) {
|
|
|
249
44
|
violations.push({
|
|
250
45
|
id: "INV-005",
|
|
251
46
|
name: "Aggregate Integrity",
|
|
252
|
-
message: `
|
|
47
|
+
message: `Payment ${expected.reference} has the expected number of credits, but their total is not the expected amount`,
|
|
253
48
|
reference: expected.reference
|
|
254
49
|
});
|
|
255
50
|
}
|
|
@@ -257,7 +52,7 @@ function verifyPaymentState(expected, observed) {
|
|
|
257
52
|
}
|
|
258
53
|
|
|
259
54
|
// src/preparation.ts
|
|
260
|
-
var DEFAULT_AMOUNT_MINOR =
|
|
55
|
+
var DEFAULT_AMOUNT_MINOR = 5e5;
|
|
261
56
|
var DEFAULT_CURRENCY = "NGN";
|
|
262
57
|
function hasReference(value) {
|
|
263
58
|
return typeof value === "string" && value.trim().length > 0;
|
|
@@ -276,7 +71,7 @@ async function createReference(input, createPayment, paymentIndex, paymentCount)
|
|
|
276
71
|
paymentCount
|
|
277
72
|
});
|
|
278
73
|
if (!hasReference(reference)) {
|
|
279
|
-
throw new Error("createPayment must return a non-empty payment
|
|
74
|
+
throw new Error("createPayment must return a non-empty reference from the isolated test payment it created");
|
|
280
75
|
}
|
|
281
76
|
return reference.trim();
|
|
282
77
|
} catch (error) {
|
|
@@ -284,53 +79,102 @@ async function createReference(input, createPayment, paymentIndex, paymentCount)
|
|
|
284
79
|
}
|
|
285
80
|
}
|
|
286
81
|
async function preparePaymentReferences(input, createPayment) {
|
|
287
|
-
|
|
288
|
-
if (
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
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`);
|
|
295
105
|
}
|
|
296
|
-
return
|
|
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`);
|
|
297
111
|
}
|
|
298
|
-
if (
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
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;
|
|
303
138
|
}
|
|
304
|
-
var financialVerificationSchema = z.object({
|
|
305
|
-
reference: z.string().min(1),
|
|
306
|
-
creditCount: z.number().int().nonnegative(),
|
|
307
|
-
creditedAmountMinor: z.number().int().nonnegative(),
|
|
308
|
-
currency: z.string().length(3),
|
|
309
|
-
status: z.string().min(1).optional(),
|
|
310
|
-
pending: z.boolean().optional(),
|
|
311
|
-
ledgerEntries: z.array(z.object({
|
|
312
|
-
id: z.string().min(1),
|
|
313
|
-
type: z.string().min(1),
|
|
314
|
-
amountMinor: z.number().int().nonnegative(),
|
|
315
|
-
currency: z.string().length(3).optional()
|
|
316
|
-
})).optional()
|
|
317
|
-
});
|
|
318
139
|
function normalizeCallbackState(value) {
|
|
319
|
-
|
|
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
|
+
}
|
|
320
164
|
return {
|
|
321
|
-
reference
|
|
322
|
-
status:
|
|
323
|
-
currency
|
|
324
|
-
creditedAmountMinor:
|
|
325
|
-
creditCount:
|
|
326
|
-
pending:
|
|
327
|
-
ledgerEntries
|
|
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
|
|
328
172
|
};
|
|
329
173
|
}
|
|
330
174
|
async function verifyWithCallback(verify, reference, timeoutMs, context, options = {}) {
|
|
331
175
|
const deadline = Date.now() + timeoutMs;
|
|
332
|
-
let lastError;
|
|
333
176
|
let lastObserved;
|
|
177
|
+
let lastTimeout;
|
|
334
178
|
while (Date.now() <= deadline) {
|
|
335
179
|
const remaining = Math.max(1, deadline - Date.now());
|
|
336
180
|
let timer;
|
|
@@ -346,9 +190,9 @@ async function verifyWithCallback(verify, reference, timeoutMs, context, options
|
|
|
346
190
|
lastObserved = normalized;
|
|
347
191
|
if (!options.isComplete || options.isComplete(normalized)) return normalized;
|
|
348
192
|
} catch (error) {
|
|
349
|
-
const candidate =
|
|
193
|
+
const candidate = callbackError(error);
|
|
350
194
|
if (!candidate.message.startsWith("Financial verification timed out after ")) throw candidate;
|
|
351
|
-
|
|
195
|
+
lastTimeout = candidate;
|
|
352
196
|
} finally {
|
|
353
197
|
if (timer) clearTimeout(timer);
|
|
354
198
|
}
|
|
@@ -356,38 +200,12 @@ async function verifyWithCallback(verify, reference, timeoutMs, context, options
|
|
|
356
200
|
if (Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, waitMs));
|
|
357
201
|
}
|
|
358
202
|
if (lastObserved && !lastObserved.pending) return lastObserved;
|
|
359
|
-
throw
|
|
203
|
+
throw lastTimeout ?? new Error(`Financial verification timed out after ${timeoutMs}ms`);
|
|
360
204
|
}
|
|
361
205
|
|
|
362
206
|
// src/orchestrator.ts
|
|
363
207
|
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
364
208
|
var DEFAULT_NEGATIVE_OBSERVATION_MS = 250;
|
|
365
|
-
function validateRunOptions(input, canPreparePayment = false) {
|
|
366
|
-
if (input.concurrency !== void 0 && (!Number.isInteger(input.concurrency) || input.concurrency < 1)) {
|
|
367
|
-
return "concurrency must be a positive integer";
|
|
368
|
-
}
|
|
369
|
-
if (input.scenario === "concurrent-unique-payments") {
|
|
370
|
-
if (input.reference !== void 0 && input.references !== void 0) return "concurrent-unique-payments accepts references, not both reference and references";
|
|
371
|
-
if (input.references !== void 0) {
|
|
372
|
-
if (input.references.length < 2) return "concurrent-unique-payments requires at least two distinct references";
|
|
373
|
-
if (input.references.some((reference) => typeof reference !== "string" || reference.trim().length === 0)) return "all payment references must be non-empty strings";
|
|
374
|
-
if (new Set(input.references).size !== input.references.length) return "payment references must be distinct for concurrent-unique-payments";
|
|
375
|
-
if (input.concurrency !== void 0 && input.references.length !== input.concurrency) return "concurrency must match the number of supplied payment references";
|
|
376
|
-
} else if (!input.syntheticReferences && !canPreparePayment && !input.replay?.event?.reference) {
|
|
377
|
-
return "real application references are required; provide references or explicitly set syntheticReferences: true";
|
|
378
|
-
}
|
|
379
|
-
} else {
|
|
380
|
-
if (input.references !== void 0) return `${input.scenario} accepts one reference; use references only with concurrent-unique-payments`;
|
|
381
|
-
const replayReference = input.replay?.event?.reference;
|
|
382
|
-
if (input.reference !== void 0 && (typeof input.reference !== "string" || input.reference.trim().length === 0)) {
|
|
383
|
-
return `reference must be a non-empty string for ${input.scenario}`;
|
|
384
|
-
}
|
|
385
|
-
if ((!input.reference || input.reference.trim().length === 0) && (!replayReference || replayReference.trim().length === 0) && !input.syntheticReferences && !canPreparePayment) {
|
|
386
|
-
return `real application reference is required for ${input.scenario}; explicitly set syntheticReferences: true to use generated fixtures`;
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
return void 0;
|
|
390
|
-
}
|
|
391
209
|
function eventId(event) {
|
|
392
210
|
for (const key of ["id", "eventId", "providerEventId"]) {
|
|
393
211
|
const value = event[key];
|
|
@@ -398,13 +216,6 @@ function eventId(event) {
|
|
|
398
216
|
function eventType(event) {
|
|
399
217
|
return typeof event.type === "string" ? event.type : void 0;
|
|
400
218
|
}
|
|
401
|
-
function observedStateComplete(expected, state, negativeDeadline) {
|
|
402
|
-
if (state.pending) return false;
|
|
403
|
-
const verification = verifyPaymentState(expected, state);
|
|
404
|
-
if (expected.eligible) return verification.passed;
|
|
405
|
-
if (state.creditCount > 0) return true;
|
|
406
|
-
return Date.now() >= negativeDeadline;
|
|
407
|
-
}
|
|
408
219
|
function matchesExpectedStatus(status, expected) {
|
|
409
220
|
if (Array.isArray(expected)) return expected.includes(status);
|
|
410
221
|
if (expected === "2xx") return status >= 200 && status < 300;
|
|
@@ -415,307 +226,262 @@ function matchesExpectedStatus(status, expected) {
|
|
|
415
226
|
function formatExpectedStatus(expected) {
|
|
416
227
|
return Array.isArray(expected) ? expected.join(", ") : String(expected);
|
|
417
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
|
+
}
|
|
418
250
|
var BachsProof = class {
|
|
419
|
-
/** Store the immutable configuration used by every run and replay. */
|
|
420
251
|
constructor(options) {
|
|
421
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
|
+
}
|
|
422
261
|
}
|
|
423
262
|
options;
|
|
424
263
|
async run(input) {
|
|
425
264
|
const requestedInput = input;
|
|
426
|
-
const validationError = validateRunOptions(input
|
|
265
|
+
const validationError = validateRunOptions(input);
|
|
427
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;
|
|
428
272
|
try {
|
|
429
|
-
|
|
273
|
+
references = await preparePaymentReferences({ ...input, amountMinor, currency }, this.options.createPayment);
|
|
430
274
|
} catch (error) {
|
|
431
|
-
return this.invalidInputResult(requestedInput, error instanceof Error ? error.message : String(error));
|
|
275
|
+
return this.invalidInputResult(requestedInput, error instanceof Error ? error.message : String(error), "payment-preparation");
|
|
432
276
|
}
|
|
433
|
-
|
|
434
|
-
if (preparedValidationError) return this.invalidInputResult(input, preparedValidationError);
|
|
435
|
-
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
436
|
-
const concurrency = Math.max(1, input.references?.length ?? input.concurrency ?? (input.scenario === "concurrent-duplicate-credit" || input.scenario === "concurrent-unique-payments" ? 2 : 1));
|
|
437
|
-
const seed = input.seed ?? input.replay?.replay.seed ?? randomUUID();
|
|
438
|
-
let generatedEvent;
|
|
277
|
+
let primaryEvent;
|
|
439
278
|
let scenarioPlan;
|
|
279
|
+
let scenarioEvents;
|
|
280
|
+
let verificationCases;
|
|
440
281
|
try {
|
|
441
|
-
|
|
442
|
-
reference:
|
|
443
|
-
amountMinor
|
|
444
|
-
currency
|
|
445
|
-
syntheticReferences: input.syntheticReferences
|
|
282
|
+
const baseEvent = this.options.provider.createPayment({
|
|
283
|
+
reference: references[0],
|
|
284
|
+
amountMinor,
|
|
285
|
+
currency
|
|
446
286
|
});
|
|
447
|
-
|
|
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
|
+
}
|
|
448
312
|
} catch (error) {
|
|
449
|
-
return this.invalidInputResult(input, `Payment preparation failed for ${input.scenario}: ${error instanceof Error ? error.message : String(error)}
|
|
313
|
+
return this.invalidInputResult(input, `Payment preparation failed for ${input.scenario}: ${error instanceof Error ? error.message : String(error)}`, "payment-preparation");
|
|
450
314
|
}
|
|
451
|
-
const
|
|
452
|
-
const verificationCases = scenarioPlan?.verification?.map((item) => ({
|
|
453
|
-
event: item.event,
|
|
454
|
-
expected: item.expected ?? this.options.provider.expectedState(item.event)
|
|
455
|
-
})) ?? [{ event, expected: this.options.provider.expectedState(event) }];
|
|
456
|
-
const expected = verificationCases[0]?.expected ?? this.options.provider.expectedState(event);
|
|
457
|
-
let scenarioEvents = Array.from(/* @__PURE__ */ new Set([
|
|
458
|
-
event,
|
|
459
|
-
...scenarioPlan?.deliveries.map((delivery) => delivery.event).filter((candidate) => Boolean(candidate)) ?? [],
|
|
460
|
-
...scenarioPlan?.verification?.map((item) => item.event) ?? []
|
|
461
|
-
]));
|
|
462
|
-
const checkpoint = input.scenario === "concurrent-duplicate-credit" ? this.options.checkpoint?.name : void 0;
|
|
463
|
-
let eventsForVerification = verificationCases;
|
|
315
|
+
const expected = verificationCases[0]?.expected ?? this.options.provider.expectedState(primaryEvent);
|
|
464
316
|
const report = {
|
|
465
|
-
reportVersion: "
|
|
317
|
+
reportVersion: "2.0",
|
|
466
318
|
scenario: input.scenario,
|
|
467
319
|
provider: this.options.provider.name,
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
event,
|
|
320
|
+
paymentReference: primaryEvent.reference,
|
|
321
|
+
event: primaryEvent,
|
|
471
322
|
expected,
|
|
472
|
-
verificationMode: this.options.verify ? "callback" : "none",
|
|
473
323
|
financiallyVerified: false,
|
|
474
324
|
deliveries: [],
|
|
475
|
-
checkpoints: [],
|
|
476
325
|
errors: [],
|
|
477
|
-
replay: {
|
|
478
|
-
seed,
|
|
479
|
-
concurrency,
|
|
480
|
-
checkpoint,
|
|
481
|
-
controlled: checkpoint !== void 0,
|
|
482
|
-
note: "Replay controls explicitly instrumented checkpoints when configured; it does not claim deterministic OS, network, or database scheduling."
|
|
483
|
-
},
|
|
484
326
|
startedAt
|
|
485
327
|
};
|
|
486
|
-
let controller;
|
|
487
|
-
let sessionId;
|
|
488
328
|
try {
|
|
489
329
|
if (scenarioPlan) {
|
|
490
|
-
await this.runScenarioPlan(scenarioPlan,
|
|
491
|
-
} else if (checkpoint) {
|
|
492
|
-
controller = new RaceController();
|
|
493
|
-
const participants = Array.from({ length: concurrency }, (_, index) => `participant-${index + 1}`);
|
|
494
|
-
const session = await controller.registerSession({ participants });
|
|
495
|
-
sessionId = session.id;
|
|
496
|
-
const deliveries = participants.map((participantId) => this.deliver(event, participantId, session, report));
|
|
497
|
-
try {
|
|
498
|
-
await controller.waitForArrivals(session.id, checkpoint, concurrency, this.options.checkpoint?.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
499
|
-
controller.release(session.id, checkpoint);
|
|
500
|
-
} catch (error) {
|
|
501
|
-
report.errors.push(error instanceof Error ? error.message : String(error));
|
|
502
|
-
controller.abort(session.id, "arrival-timeout");
|
|
503
|
-
}
|
|
504
|
-
await this.settleConcurrentDeliveries(deliveries, report);
|
|
505
|
-
report.checkpoints = controller.getTrace(session.id);
|
|
330
|
+
await this.runScenarioPlan(scenarioPlan, primaryEvent, report);
|
|
506
331
|
} else if (input.scenario === "concurrent-duplicate-credit") {
|
|
507
332
|
const participants = Array.from({ length: concurrency }, (_, index) => `participant-${index + 1}`);
|
|
508
|
-
await
|
|
333
|
+
await Promise.all(participants.map((participant) => this.deliver(primaryEvent, participant, report)));
|
|
509
334
|
} else if (input.scenario === "sequential-duplicate-webhook") {
|
|
510
|
-
await this.deliver(
|
|
511
|
-
await this.deliver(
|
|
335
|
+
await this.deliver(primaryEvent, "sequential-1", report);
|
|
336
|
+
await this.deliver(primaryEvent, "sequential-2", report);
|
|
512
337
|
} else if (input.scenario === "concurrent-unique-payments") {
|
|
513
|
-
|
|
514
|
-
if (references.length !== concurrency) throw new Error("references must contain exactly one entry per concurrent unique payment");
|
|
515
|
-
const events = references.map((reference) => this.options.provider.createPayment({
|
|
516
|
-
amountMinor: input.amountMinor,
|
|
517
|
-
currency: input.currency,
|
|
518
|
-
reference,
|
|
519
|
-
syntheticReferences: input.syntheticReferences
|
|
520
|
-
}));
|
|
521
|
-
await this.settleConcurrentDeliveries(events.map((uniqueEvent) => this.deliver(uniqueEvent, `unique-${uniqueEvent.reference}`, void 0, report)), report);
|
|
522
|
-
eventsForVerification = events.map((uniqueEvent) => ({
|
|
523
|
-
event: uniqueEvent,
|
|
524
|
-
expected: this.options.provider.expectedState(uniqueEvent)
|
|
525
|
-
}));
|
|
526
|
-
scenarioEvents = events;
|
|
338
|
+
await Promise.all(scenarioEvents.map((event) => this.deliver(event, `unique-${event.reference}`, report)));
|
|
527
339
|
} else {
|
|
528
340
|
report.errors.push(`Unsupported scenario ${input.scenario}`);
|
|
341
|
+
report.failureType = "webhook-delivery";
|
|
529
342
|
}
|
|
530
|
-
|
|
531
|
-
report.financiallyVerified = false;
|
|
532
|
-
} else {
|
|
533
|
-
const paymentResults = await Promise.all(eventsForVerification.map(async ({ event: paymentEvent, expected: paymentExpected }) => {
|
|
534
|
-
const relatedEvents = scenarioEvents.filter((scenarioEvent) => scenarioEvent.reference === paymentEvent.reference);
|
|
535
|
-
const context = {
|
|
536
|
-
scenario: input.scenario,
|
|
537
|
-
paymentReference: paymentEvent.reference,
|
|
538
|
-
expected: paymentExpected,
|
|
539
|
-
expectedOutcome: {
|
|
540
|
-
eligible: paymentExpected.eligible,
|
|
541
|
-
expectedCreditCount: paymentExpected.expectedCreditCount,
|
|
542
|
-
amountMinor: paymentExpected.amountMinor,
|
|
543
|
-
currency: paymentExpected.currency
|
|
544
|
-
},
|
|
545
|
-
events: relatedEvents,
|
|
546
|
-
eventIdentifiers: relatedEvents.map(eventId).filter((identifier) => Boolean(identifier)),
|
|
547
|
-
deliveries: report.deliveries.filter((delivery) => delivery.reference === paymentEvent.reference)
|
|
548
|
-
};
|
|
549
|
-
const paymentObserved = await this.inspect(paymentEvent.reference, paymentExpected, context);
|
|
550
|
-
return {
|
|
551
|
-
event: paymentEvent,
|
|
552
|
-
expected: paymentExpected,
|
|
553
|
-
observed: paymentObserved,
|
|
554
|
-
verification: verifyPaymentState(paymentExpected, paymentObserved)
|
|
555
|
-
};
|
|
556
|
-
}));
|
|
557
|
-
report.financiallyVerified = true;
|
|
558
|
-
report.observed = paymentResults[0]?.observed;
|
|
559
|
-
report.verification = {
|
|
560
|
-
passed: paymentResults.every((payment) => payment.verification.passed),
|
|
561
|
-
violations: paymentResults.flatMap((payment) => payment.verification.violations)
|
|
562
|
-
};
|
|
563
|
-
if (paymentResults.length > 1) report.payments = paymentResults;
|
|
564
|
-
if (!report.verification.passed) {
|
|
565
|
-
report.errors.push(...report.verification.violations.map((violation) => `${violation.id}: ${violation.message}`));
|
|
566
|
-
}
|
|
567
|
-
}
|
|
343
|
+
await this.verifyPayments(input.scenario, scenarioEvents, verificationCases, report);
|
|
568
344
|
} catch (error) {
|
|
569
345
|
report.errors.push(error instanceof Error ? error.message : String(error));
|
|
346
|
+
report.failureType ??= "webhook-delivery";
|
|
570
347
|
} finally {
|
|
571
|
-
if (controller && sessionId) {
|
|
572
|
-
report.checkpoints = controller.getTrace(sessionId);
|
|
573
|
-
controller.cleanupSession(sessionId);
|
|
574
|
-
}
|
|
575
|
-
if (controller) await controller.close();
|
|
576
348
|
report.completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
577
349
|
}
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
async replay(report) {
|
|
582
|
-
return this.run({
|
|
583
|
-
scenario: report.scenario,
|
|
584
|
-
concurrency: report.replay.concurrency,
|
|
585
|
-
seed: report.replay.seed,
|
|
586
|
-
replay: report
|
|
587
|
-
});
|
|
588
|
-
}
|
|
589
|
-
invalidInputResult(input, message) {
|
|
590
|
-
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
591
|
-
const reference = input.reference ?? input.references?.[0] ?? "<missing-reference>";
|
|
592
|
-
const event = {
|
|
593
|
-
reference,
|
|
594
|
-
amountMinor: input.amountMinor ?? 0,
|
|
595
|
-
currency: input.currency ?? "NGN",
|
|
596
|
-
status: "INVALID_INPUT"
|
|
597
|
-
};
|
|
598
|
-
const report = {
|
|
599
|
-
reportVersion: "1.1",
|
|
600
|
-
scenario: input.scenario,
|
|
601
|
-
provider: this.options.provider.name,
|
|
602
|
-
mode: this.options.provider.mode,
|
|
603
|
-
paymentReference: reference,
|
|
604
|
-
event,
|
|
605
|
-
expected: { reference, eligible: false, amountMinor: event.amountMinor, currency: event.currency, expectedCreditCount: 0 },
|
|
606
|
-
verificationMode: this.options.verify ? "callback" : "none",
|
|
607
|
-
financiallyVerified: false,
|
|
608
|
-
deliveries: [],
|
|
609
|
-
checkpoints: [],
|
|
610
|
-
errors: [message],
|
|
611
|
-
replay: {
|
|
612
|
-
seed: input.seed ?? randomUUID(),
|
|
613
|
-
concurrency: input.concurrency ?? 1,
|
|
614
|
-
controlled: false,
|
|
615
|
-
note: "No webhook was sent because payment preparation or run configuration validation failed."
|
|
616
|
-
},
|
|
617
|
-
startedAt,
|
|
618
|
-
completedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
350
|
+
return {
|
|
351
|
+
passed: report.errors.length === 0 && report.financiallyVerified && report.verification?.passed === true,
|
|
352
|
+
report
|
|
619
353
|
};
|
|
620
|
-
return { passed: false, report };
|
|
621
354
|
}
|
|
622
355
|
async runScenarioPlan(plan, primaryEvent, report) {
|
|
623
356
|
if (plan.concurrent) {
|
|
624
|
-
await
|
|
357
|
+
await Promise.all(plan.deliveries.map((delivery, index) => this.deliver(
|
|
625
358
|
delivery.event ?? primaryEvent,
|
|
626
359
|
delivery.participantId ?? `scenario-${index + 1}`,
|
|
627
|
-
void 0,
|
|
628
360
|
report,
|
|
629
361
|
delivery
|
|
630
|
-
))
|
|
362
|
+
)));
|
|
631
363
|
return;
|
|
632
364
|
}
|
|
633
365
|
for (const [index, delivery] of plan.deliveries.entries()) {
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
delivery
|
|
641
|
-
);
|
|
642
|
-
} catch (error) {
|
|
643
|
-
report.errors.push(error instanceof Error ? error.message : String(error));
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
async settleConcurrentDeliveries(deliveries, report) {
|
|
648
|
-
const settled = await Promise.allSettled(deliveries);
|
|
649
|
-
for (const result of settled) {
|
|
650
|
-
if (result.status === "rejected") {
|
|
651
|
-
report.errors.push(result.reason instanceof Error ? result.reason.message : String(result.reason));
|
|
652
|
-
}
|
|
366
|
+
await this.deliver(
|
|
367
|
+
delivery.event ?? primaryEvent,
|
|
368
|
+
delivery.participantId ?? `scenario-${index + 1}`,
|
|
369
|
+
report,
|
|
370
|
+
delivery
|
|
371
|
+
);
|
|
653
372
|
}
|
|
654
373
|
}
|
|
655
|
-
async deliver(event, participantId,
|
|
374
|
+
async deliver(event, participantId, report, scenarioDelivery = {}) {
|
|
656
375
|
const delivery = {
|
|
657
376
|
deliveryId: randomUUID(),
|
|
658
377
|
participantId,
|
|
659
378
|
reference: event.reference,
|
|
660
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
661
379
|
eventId: eventId(event),
|
|
662
380
|
eventType: eventType(event),
|
|
381
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
663
382
|
expectedStatus: scenarioDelivery.expectedStatus
|
|
664
383
|
};
|
|
665
|
-
const body = scenarioDelivery.body ?? this.options.provider.serialize(event);
|
|
666
|
-
const signingBody = scenarioDelivery.signingBody ?? body;
|
|
667
|
-
const headers = {
|
|
668
|
-
"content-type": "application/json",
|
|
669
|
-
...this.options.target.headers,
|
|
670
|
-
...this.options.provider.headersForBody?.(event, signingBody) ?? this.options.provider.headers?.(event) ?? {},
|
|
671
|
-
...scenarioDelivery.headers
|
|
672
|
-
};
|
|
673
|
-
if (session) {
|
|
674
|
-
headers["x-bachsproof-enabled"] = "true";
|
|
675
|
-
headers["x-bachsproof-controller"] = session.controllerUrl;
|
|
676
|
-
headers["x-bachsproof-session"] = session.id;
|
|
677
|
-
headers["x-bachsproof-participant"] = participantId;
|
|
678
|
-
headers["x-bachsproof-token"] = session.token;
|
|
679
|
-
}
|
|
680
384
|
try {
|
|
681
385
|
if (scenarioDelivery.delayMs && scenarioDelivery.delayMs > 0) {
|
|
682
386
|
await new Promise((resolve) => setTimeout(resolve, scenarioDelivery.delayMs));
|
|
683
387
|
}
|
|
684
|
-
const
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
body
|
|
688
|
-
}
|
|
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 });
|
|
689
394
|
delivery.status = response.status;
|
|
690
395
|
delivery.responseBody = await response.text();
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
|
|
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";
|
|
697
403
|
}
|
|
698
404
|
} catch (error) {
|
|
699
405
|
delivery.error = error instanceof Error ? error.message : String(error);
|
|
700
|
-
|
|
406
|
+
report.errors.push(`Webhook delivery ${participantId} failed: ${delivery.error}`);
|
|
407
|
+
report.failureType ??= "webhook-delivery";
|
|
701
408
|
} finally {
|
|
702
409
|
delivery.completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
703
410
|
report.deliveries.push(delivery);
|
|
704
411
|
}
|
|
705
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
|
+
}
|
|
706
452
|
async inspect(reference, expected, context) {
|
|
707
|
-
const
|
|
708
|
-
const
|
|
709
|
-
const negativeDeadline = Date.now() + (expected.eligible ? 0 :
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
pollIntervalMs: financialVerification?.pollIntervalMs,
|
|
714
|
-
isComplete
|
|
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)
|
|
715
459
|
});
|
|
716
460
|
}
|
|
717
|
-
|
|
718
|
-
|
|
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 };
|
|
719
485
|
}
|
|
720
486
|
};
|
|
721
487
|
async function writeReport(report, path) {
|
|
@@ -727,6 +493,21 @@ function redactSecrets(value) {
|
|
|
727
493
|
return value.replace(/(authorization\s*[:=]\s*)([^,\s]+)/gi, "$1[REDACTED]").replace(/(token|secret|api[-_]?key)(\s*[:=]\s*)([^,\s]+)/gi, "$1$2[REDACTED]");
|
|
728
494
|
}
|
|
729
495
|
|
|
730
|
-
|
|
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 };
|
|
731
512
|
//# sourceMappingURL=index.js.map
|
|
732
513
|
//# sourceMappingURL=index.js.map
|