@mandateops/cli-linux-x64 0.0.0-stage → 0.7.2

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.
Files changed (68) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +181 -2
  3. package/audit-lab/README.md +194 -0
  4. package/audit-lab/bin/mandateops +0 -0
  5. package/audit-lab/contracts/contact-plain-text.vectors.json +85 -0
  6. package/audit-lab/contracts/history-reading.md +185 -0
  7. package/audit-lab/contracts/history-reading.vectors.json +284 -0
  8. package/audit-lab/contracts/profiles.md +161 -0
  9. package/audit-lab/contracts/properties.md +512 -0
  10. package/audit-lab/contracts/sdk-config.md +155 -0
  11. package/audit-lab/contracts/system-under-test.md +385 -0
  12. package/audit-lab/contracts/test-provider.md +350 -0
  13. package/audit-lab/lab/compose.audit.yml +181 -0
  14. package/audit-lab/lab/config/fault-control.json +14 -0
  15. package/audit-lab/lab/examples/agents/Dockerfile +28 -0
  16. package/audit-lab/lab/examples/agents/codeloc.cjs +199 -0
  17. package/audit-lab/lab/examples/agents/load.cjs +9 -0
  18. package/audit-lab/lab/examples/agents/package-lock.json +2840 -0
  19. package/audit-lab/lab/examples/agents/package.json +9 -0
  20. package/audit-lab/lab/examples/agents/python/mandateops_codeloc.py +271 -0
  21. package/audit-lab/lab/examples/agents/python/sitecustomize.py +51 -0
  22. package/audit-lab/lab/examples/agents/requirements-python.txt +522 -0
  23. package/audit-lab/lab/examples/agents/telemetry-router.cjs +272 -0
  24. package/audit-lab/lab/examples/test-provider/.dockerignore +4 -0
  25. package/audit-lab/lab/examples/test-provider/Dockerfile +28 -0
  26. package/audit-lab/lab/examples/test-provider/bun.lock +405 -0
  27. package/audit-lab/lab/examples/test-provider/package.json +42 -0
  28. package/audit-lab/lab/examples/test-provider/src/amount.ts +32 -0
  29. package/audit-lab/lab/examples/test-provider/src/app.ts +538 -0
  30. package/audit-lab/lab/examples/test-provider/src/auth.ts +30 -0
  31. package/audit-lab/lab/examples/test-provider/src/barrier.ts +262 -0
  32. package/audit-lab/lab/examples/test-provider/src/codeloc.ts +27 -0
  33. package/audit-lab/lab/examples/test-provider/src/config.ts +311 -0
  34. package/audit-lab/lab/examples/test-provider/src/connect.ts +204 -0
  35. package/audit-lab/lab/examples/test-provider/src/declaration.ts +270 -0
  36. package/audit-lab/lab/examples/test-provider/src/declared.ts +198 -0
  37. package/audit-lab/lab/examples/test-provider/src/domain.ts +193 -0
  38. package/audit-lab/lab/examples/test-provider/src/egress.ts +396 -0
  39. package/audit-lab/lab/examples/test-provider/src/flow.ts +263 -0
  40. package/audit-lab/lab/examples/test-provider/src/gate.ts +301 -0
  41. package/audit-lab/lab/examples/test-provider/src/main.ts +31 -0
  42. package/audit-lab/lab/examples/test-provider/src/notify.ts +157 -0
  43. package/audit-lab/lab/examples/test-provider/src/owner.ts +60 -0
  44. package/audit-lab/lab/examples/test-provider/src/payment.ts +103 -0
  45. package/audit-lab/lab/examples/test-provider/src/profile.ts +417 -0
  46. package/audit-lab/lab/examples/test-provider/src/request.ts +201 -0
  47. package/audit-lab/lab/examples/test-provider/src/rows.ts +173 -0
  48. package/audit-lab/lab/examples/test-provider/src/schema.ts +114 -0
  49. package/audit-lab/lab/examples/test-provider/src/signature.ts +86 -0
  50. package/audit-lab/lab/examples/test-provider/src/staged.ts +318 -0
  51. package/audit-lab/lab/examples/test-provider/src/store.ts +432 -0
  52. package/audit-lab/lab/examples/test-provider/src/traffic.ts +50 -0
  53. package/audit-lab/lab/examples/test-provider/src/webauthn.d.ts +11 -0
  54. package/audit-lab/lab/examples/test-provider/src/wire.ts +153 -0
  55. package/audit-lab/lab/examples/test-provider/tsconfig.build.json +9 -0
  56. package/audit-lab/lab/examples/test-provider/tsconfig.json +24 -0
  57. package/audit-lab/lab/images/capture/Dockerfile +15 -0
  58. package/audit-lab/lab/images/capture/LICENSE +201 -0
  59. package/audit-lab/lab/images/fault-control/Dockerfile +13 -0
  60. package/audit-lab/lab/images/fault-control/LICENSE +21 -0
  61. package/audit-lab/lab/images/provider-store/Dockerfile +4 -0
  62. package/audit-lab/lab/images/provider-store/LICENSE +23 -0
  63. package/audit-lab/lab/images/telemetry/Dockerfile +14 -0
  64. package/audit-lab/lab/images/telemetry/LICENSE +201 -0
  65. package/audit-lab/lab/scripts/compose-down.sh +148 -0
  66. package/audit-lab/lab/scripts/compose-lib.sh +663 -0
  67. package/audit-lab/lab/scripts/compose-up.sh +240 -0
  68. package/package.json +16 -4
@@ -0,0 +1,432 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { sql } from "kysely";
3
+ import type { IsolationLevel } from "kysely";
4
+ import type { Pool } from "pg";
5
+ import { z } from "zod";
6
+ import {
7
+ instructionDigest,
8
+ instructionSchema,
9
+ MAX_NAMED_DUPLICATES,
10
+ ProviderError,
11
+ } from "./domain.js";
12
+ import type {
13
+ Effect,
14
+ EffectSummary,
15
+ ExecutionResult,
16
+ Instruction,
17
+ RejectionReason,
18
+ } from "./domain.js";
19
+ import { claimDatabase, ownerPool, queriesOver, servingPool } from "./owner.js";
20
+ import type { PoolConfig } from "./owner.js";
21
+ import type { DeclineCheck } from "./payment.js";
22
+ import { loadEffect, readObservations } from "./rows.js";
23
+ import type { Client, Database, Observations, Queries } from "./rows.js";
24
+ import type { RefusalReplay } from "./wire.js";
25
+ import type { DeliveryRecord } from "./notify.js";
26
+
27
+ export type { Observations } from "./rows.js";
28
+
29
+ export const COMMIT_ORDER_LOCK = 718304;
30
+
31
+ const declinedSchema = z.object({ instruction: instructionSchema }).strict();
32
+ const countSchema = z.object({ count: z.coerce.number().int() }).strict();
33
+
34
+ export type ExecuteInput = Readonly<{
35
+ /** The provider in the run's list the request reached; keys are its own. */
36
+ provider: string;
37
+ key: string;
38
+ paymentFromKey: boolean;
39
+ instruction: Instruction;
40
+ }>;
41
+ export type StoreConfig = PoolConfig &
42
+ Readonly<{
43
+ providerAccount: string;
44
+ providerOperation: string;
45
+ idempotencyScope: string;
46
+ /** Most effects, refusals and deliveries one run keeps. */
47
+ recordLimit: number;
48
+ }>;
49
+ /** A request and how its format treats a refusal, on its way to an answer. */
50
+ type Settling = Readonly<{
51
+ input: ExecuteInput;
52
+ digest: string;
53
+ refusals: RefusalReplay;
54
+ declines: DeclineCheck;
55
+ }>;
56
+
57
+ /** Sole owner of durable provider effects, key bindings and notifications. */
58
+ export class Store {
59
+ private healthy = true;
60
+ private constructor(
61
+ private readonly queries: Queries,
62
+ private readonly owner: Queries,
63
+ pools: readonly Pool[],
64
+ private readonly config: StoreConfig,
65
+ ) {
66
+ const lost = () => {
67
+ this.healthy = false;
68
+ };
69
+ for (const pool of pools) {
70
+ pool.on("error", lost);
71
+ // The pool hears only idle clients; one in a transaction would crash us.
72
+ pool.on("connect", (client) => client.on("error", lost));
73
+ }
74
+ }
75
+
76
+ /** Opens and initialises a disposable audit_lab_* database owned by one process. */
77
+ static async open(config: StoreConfig): Promise<Store> {
78
+ const held = ownerPool(config);
79
+ const owner = queriesOver(held);
80
+ try {
81
+ await claimDatabase(owner);
82
+ } catch (error) {
83
+ await owner.destroy();
84
+ throw error;
85
+ }
86
+ const pool = servingPool(config);
87
+ return new Store(queriesOver(pool), owner, [held, pool], config);
88
+ }
89
+
90
+ async close(): Promise<void> {
91
+ this.healthy = false;
92
+ await this.owner.destroy();
93
+ await this.queries.destroy();
94
+ }
95
+
96
+ private async transaction<Value>(
97
+ work: (client: Client) => Promise<Value>,
98
+ isolation?: IsolationLevel,
99
+ ): Promise<Value> {
100
+ if (!this.healthy) throw new ProviderError(503, "database_unavailable");
101
+ const builder = this.queries.transaction();
102
+ return (isolation ? builder.setIsolationLevel(isolation) : builder).execute(
103
+ work,
104
+ );
105
+ }
106
+
107
+ async ping(): Promise<void> {
108
+ await this.transaction(async (client) => {
109
+ await client
110
+ .selectNoFrom((builder) => builder.val(1).as("alive"))
111
+ .execute();
112
+ });
113
+ }
114
+
115
+ /**
116
+ * Binds the key to the instruction digest and records a new effect in one
117
+ * transaction, or returns the effect already bound to that key. A reused
118
+ * key with different terms creates nothing. The returned effect is durable
119
+ * once this promise resolves. A key with no outcome may instead be declined,
120
+ * asked under the commit order lock so one armed refusal has one taker.
121
+ */
122
+ async execute(
123
+ input: ExecuteInput,
124
+ refusals: RefusalReplay,
125
+ declines: DeclineCheck,
126
+ ): Promise<ExecutionResult> {
127
+ const digest = instructionDigest(input.instruction);
128
+ return this.transaction(async (client) => {
129
+ await this.serialise(client);
130
+ const settled = await this.settledOutcome(client, {
131
+ input,
132
+ digest,
133
+ refusals,
134
+ declines,
135
+ });
136
+ if (settled) return settled;
137
+ if (declines(input.instruction)) {
138
+ await this.recordRejection(client, input, "declined");
139
+ return { kind: "declined", repeated: false };
140
+ }
141
+ if (
142
+ (await this.countOf(client, "effects", "commit_sequence")) >=
143
+ this.config.recordLimit
144
+ )
145
+ throw new ProviderError(409, "effect_limit");
146
+ const effectId = randomUUID();
147
+ const { providerAccount, providerOperation } = this.config;
148
+ await client
149
+ .insertInto("idempotency_bindings")
150
+ .values({
151
+ provider: input.provider,
152
+ provider_account: providerAccount,
153
+ idempotency_key: input.key,
154
+ instruction_sha256: digest,
155
+ effect_id: effectId,
156
+ })
157
+ .execute();
158
+ await client
159
+ .insertInto("effects")
160
+ .values({
161
+ effect_id: effectId,
162
+ provider: input.provider,
163
+ provider_account: providerAccount,
164
+ operation: providerOperation,
165
+ idempotency_key: input.key,
166
+ instruction: JSON.stringify(input.instruction),
167
+ })
168
+ .execute();
169
+ return {
170
+ kind: "effect",
171
+ effect: await loadEffect(
172
+ client,
173
+ effectId,
174
+ this.config.idempotencyScope,
175
+ ),
176
+ created: true,
177
+ };
178
+ });
179
+ }
180
+
181
+ /** Serialises effect creation so commit_sequence order is commit order. */
182
+ private async serialise(client: Client): Promise<void> {
183
+ await client
184
+ .selectNoFrom((builder) =>
185
+ builder
186
+ .fn("pg_advisory_xact_lock", [builder.val(COMMIT_ORDER_LOCK)])
187
+ .as("locked"),
188
+ )
189
+ .execute();
190
+ }
191
+
192
+ /**
193
+ * Rows in a table, read from its sequence's highest value: rows are never
194
+ * deleted and reset restarts the sequence, so it equals the count, and the
195
+ * primary-key index answers it without a scan as a run grows.
196
+ */
197
+ private async countOf(
198
+ client: Client,
199
+ table: keyof Database,
200
+ sequence: string,
201
+ ): Promise<number> {
202
+ const row = await client
203
+ .selectFrom(table)
204
+ .select((builder) =>
205
+ builder.fn
206
+ .coalesce(builder.fn.max(sql.ref(sequence)), sql.lit(0))
207
+ .as("count"),
208
+ )
209
+ .executeTakeFirst();
210
+ return countSchema.parse(row).count;
211
+ }
212
+
213
+ /** The answer a key already has, bound or finally refused, if any. */
214
+ private async settledOutcome(
215
+ client: Client,
216
+ { input, digest, refusals, declines }: Settling,
217
+ ): Promise<ExecutionResult | undefined> {
218
+ const bound = await this.boundOutcome(client, input, digest);
219
+ if (bound || refusals !== "final") return bound;
220
+ return this.finalRefusal(client, { input, digest, refusals, declines });
221
+ }
222
+
223
+ /** What a key already bound answers; a key's first outcome always stands. */
224
+ private async boundOutcome(
225
+ client: Client,
226
+ input: ExecuteInput,
227
+ digest: string,
228
+ ): Promise<ExecutionResult | undefined> {
229
+ const binding = await client
230
+ .selectFrom("idempotency_bindings")
231
+ .select(["instruction_sha256", "effect_id"])
232
+ .where("provider", "=", input.provider)
233
+ .where("provider_account", "=", this.config.providerAccount)
234
+ .where("idempotency_key", "=", input.key)
235
+ .executeTakeFirst();
236
+ if (!binding) return undefined;
237
+ if (binding.instruction_sha256 !== digest) {
238
+ await this.recordRejection(client, input, "idempotency_key_conflict");
239
+ return { kind: "key_conflict" };
240
+ }
241
+ return {
242
+ kind: "effect",
243
+ effect: await loadEffect(
244
+ client,
245
+ binding.effect_id,
246
+ this.config.idempotencyScope,
247
+ ),
248
+ created: false,
249
+ };
250
+ }
251
+
252
+ /**
253
+ * A declined key whose refusal stands: repeated, or in conflict if changed. An
254
+ * armed refusal a repeat meets is spent on it and recorded, so every arming a
255
+ * run made shows its own declined record.
256
+ */
257
+ private async finalRefusal(
258
+ client: Client,
259
+ { input, digest, declines }: Settling,
260
+ ): Promise<ExecutionResult | undefined> {
261
+ const reason: RejectionReason = "declined";
262
+ const declined = await client
263
+ .selectFrom("rejected_requests")
264
+ .select("instruction")
265
+ .where("provider", "=", input.provider)
266
+ .where("provider_account", "=", this.config.providerAccount)
267
+ .where("idempotency_key", "=", input.key)
268
+ .where("reason", "=", reason)
269
+ .executeTakeFirst();
270
+ if (!declined) return undefined;
271
+ const { instruction } = declinedSchema.parse(declined);
272
+ if (instructionDigest(instruction) === digest) {
273
+ if (declines(input.instruction))
274
+ await this.recordRejection(client, input, "declined");
275
+ return { kind: "declined", repeated: true };
276
+ }
277
+ await this.recordRejection(client, input, "idempotency_key_conflict");
278
+ return { kind: "key_conflict" };
279
+ }
280
+
281
+ /** Records a refusal a format made before any money step. */
282
+ async reject(input: ExecuteInput, reason: RejectionReason): Promise<void> {
283
+ await this.transaction((client) =>
284
+ this.recordRejection(client, input, reason),
285
+ );
286
+ }
287
+
288
+ /** Records a refused request; a full table refuses the run, never drops. */
289
+ private async recordRejection(
290
+ client: Client,
291
+ input: ExecuteInput,
292
+ reason: RejectionReason,
293
+ ): Promise<void> {
294
+ if (
295
+ (await this.countOf(client, "rejected_requests", "rejection_sequence")) >=
296
+ this.config.recordLimit
297
+ )
298
+ throw new ProviderError(409, "rejection_limit");
299
+ await client
300
+ .insertInto("rejected_requests")
301
+ .values({
302
+ provider: input.provider,
303
+ idempotency_key: input.key,
304
+ instruction: JSON.stringify(input.instruction),
305
+ provider_account: this.config.providerAccount,
306
+ operation: this.config.providerOperation,
307
+ reason,
308
+ payment_from_key: input.paymentFromKey,
309
+ })
310
+ .execute();
311
+ }
312
+
313
+ /**
314
+ * Effects in commit order, deliveries and refused requests in record order,
315
+ * read from one snapshot. Each is bounded by the record limit at insertion.
316
+ */
317
+ async observations(): Promise<Observations> {
318
+ return this.transaction(
319
+ (client) => readObservations(client, this.config.idempotencyScope),
320
+ "repeatable read",
321
+ );
322
+ }
323
+
324
+ /**
325
+ * Effects per key, for the keys asked about, in this account, summed across
326
+ * every provider of the run: one key paid on two providers counts twice.
327
+ */
328
+ async effectCounts(
329
+ keys: readonly string[],
330
+ ): Promise<ReadonlyMap<string, number>> {
331
+ const rows = await this.queries
332
+ .selectFrom("effects")
333
+ .select((builder) => [
334
+ "idempotency_key",
335
+ builder.fn.count("effect_id").as("count"),
336
+ ])
337
+ .where("provider_account", "=", this.config.providerAccount)
338
+ .where("idempotency_key", "in", [...keys])
339
+ .groupBy("idempotency_key")
340
+ .execute();
341
+ return new Map(
342
+ rows.map((row) => [
343
+ row.idempotency_key,
344
+ countSchema.parse({ count: row.count }).count,
345
+ ]),
346
+ );
347
+ }
348
+
349
+ /**
350
+ * Totals over the run, across every provider; duplicate keys named up to a
351
+ * bound and counted.
352
+ */
353
+ async effectSummary(): Promise<EffectSummary> {
354
+ return this.transaction(async (client) => {
355
+ const account = this.config.providerAccount;
356
+ const totals = await client
357
+ .selectFrom("effects")
358
+ .select((builder) => [
359
+ builder.fn.count("effect_id").as("effects"),
360
+ builder.fn.count("idempotency_key").distinct().as("keys"),
361
+ ])
362
+ .where("provider_account", "=", account)
363
+ .executeTakeFirstOrThrow();
364
+ const duplicated = client
365
+ .selectFrom("effects")
366
+ .select("idempotency_key")
367
+ .where("provider_account", "=", account)
368
+ .groupBy("idempotency_key")
369
+ .having((builder) => builder.fn.count("effect_id"), ">", 1);
370
+ const named = await duplicated
371
+ .orderBy("idempotency_key")
372
+ .limit(MAX_NAMED_DUPLICATES)
373
+ .execute();
374
+ const counted = await client
375
+ .selectFrom(duplicated.as("duplicated"))
376
+ .select((builder) => builder.fn.countAll().as("count"))
377
+ .executeTakeFirstOrThrow();
378
+ return {
379
+ effects: countSchema.parse({ count: totals.effects }).count,
380
+ keys: countSchema.parse({ count: totals.keys }).count,
381
+ duplicateKeys: named.map((row) => row.idempotency_key),
382
+ duplicateKeyCount: countSchema.parse(counted).count,
383
+ };
384
+ }, "repeatable read");
385
+ }
386
+
387
+ /** The committed effect a notification is about; 404 when none is. */
388
+ async effect(effectId: string): Promise<Effect> {
389
+ return this.transaction(async (client) => {
390
+ const known = await client
391
+ .selectFrom("effects")
392
+ .select("effect_id")
393
+ .where("effect_id", "=", effectId)
394
+ .executeTakeFirst();
395
+ if (!known) throw new ProviderError(404, "effect_not_found");
396
+ return loadEffect(client, effectId, this.config.idempotencyScope);
397
+ });
398
+ }
399
+
400
+ /** Records one ended delivery of an existing effect; never a new effect. */
401
+ async recordDelivery(delivery: DeliveryRecord): Promise<void> {
402
+ await this.transaction(async (client) => {
403
+ if (
404
+ (await this.countOf(client, "notifications", "delivery_sequence")) >=
405
+ this.config.recordLimit
406
+ )
407
+ throw new ProviderError(409, "notification_limit");
408
+ await client
409
+ .insertInto("notifications")
410
+ .values({
411
+ effect_id: delivery.effectId,
412
+ delivered_at: delivery.deliveredAt,
413
+ delivery_id: delivery.deliveryId,
414
+ issued: delivery.issued,
415
+ sent_at: delivery.sentAt,
416
+ status: delivery.status,
417
+ })
418
+ .execute();
419
+ });
420
+ }
421
+
422
+ /** Destructive fresh-run control: clears every provider record. */
423
+ async reset(): Promise<void> {
424
+ await this.transaction(async (client) => {
425
+ await this.serialise(client);
426
+ // The one raw statement: no TRUNCATE builder, and triggers refuse DELETE.
427
+ await sql`TRUNCATE ${sql.table("notifications")}, ${sql.table("rejected_requests")}, ${sql.table("effects")}, ${sql.table("idempotency_bindings")} RESTART IDENTITY`.execute(
428
+ client,
429
+ );
430
+ });
431
+ }
432
+ }
@@ -0,0 +1,50 @@
1
+ import { lookup } from "node:dns/promises";
2
+
3
+ /** What arrived at the payment endpoint, as this provider saw it. */
4
+ export type TrafficView = Readonly<{
5
+ proxied: number;
6
+ direct: number;
7
+ unrecorded: number;
8
+ }>;
9
+
10
+ const IPV4_MAPPED = "::ffff:";
11
+ const plain = (address: string) =>
12
+ address.startsWith(IPV4_MAPPED) ? address.slice(IPV4_MAPPED.length) : address;
13
+
14
+ /**
15
+ * Counts every payment request by the route it took and whether it left a
16
+ * record, so a request refused before it was recorded is never silent.
17
+ */
18
+ export class Traffic {
19
+ private proxied = 0;
20
+ private direct = 0;
21
+ private recordedRequests = 0;
22
+
23
+ constructor(private readonly proxyHost: string | undefined) {}
24
+
25
+ async received(address: string): Promise<void> {
26
+ const proxy = this.proxyHost
27
+ ? await lookup(this.proxyHost, { family: 4 }).catch(() => undefined)
28
+ : undefined;
29
+ if (proxy?.address === plain(address)) this.proxied += 1;
30
+ else this.direct += 1;
31
+ }
32
+
33
+ recorded(): void {
34
+ this.recordedRequests += 1;
35
+ }
36
+
37
+ view(): TrafficView {
38
+ return {
39
+ proxied: this.proxied,
40
+ direct: this.direct,
41
+ unrecorded: this.proxied + this.direct - this.recordedRequests,
42
+ };
43
+ }
44
+
45
+ reset(): void {
46
+ this.proxied = 0;
47
+ this.direct = 0;
48
+ this.recordedRequests = 0;
49
+ }
50
+ }
@@ -0,0 +1,11 @@
1
+ /* eslint-disable @typescript-eslint/consistent-type-definitions -- ox reads these as the DOM declares them. */
2
+ /**
3
+ * Names viem's `ox` dependency reads from the DOM library, which a server has
4
+ * no use for. Declared empty so its types check without pulling in that library.
5
+ */
6
+ interface AuthenticatorAttestationResponse {
7
+ readonly clientDataJSON: ArrayBuffer;
8
+ }
9
+ interface AuthenticationExtensionsClientOutputs {
10
+ readonly appid?: boolean;
11
+ }
@@ -0,0 +1,153 @@
1
+ import type { FinancialFlow } from "./flow.js";
2
+ import { BEARER, requireCredential } from "./auth.js";
3
+ import { idSchema, instructionSchema, recordKey } from "./domain.js";
4
+ import type { Effect, Instruction } from "./domain.js";
5
+
6
+ /** What one payment request means, in the provider's normalised terms. */
7
+ export type PaymentRequest = Readonly<{
8
+ key: string;
9
+ /** The key as the client wrote it, when the record holds a digest of it. */
10
+ sentKey?: string;
11
+ /** The request named no payment, so the instruction's payment is its key. */
12
+ paymentFromKey: boolean;
13
+ instruction: Instruction;
14
+ }>;
15
+ export type WireReply = Readonly<{
16
+ status: number;
17
+ body: unknown;
18
+ headers: Readonly<Record<string, string>>;
19
+ }>;
20
+ export type RequestHeaders = Readonly<Record<string, unknown>>;
21
+ /** What a request's credential may be checked against. */
22
+ export type IncomingCall = Readonly<{
23
+ headers: RequestHeaders;
24
+ url: string;
25
+ /** The exact bytes received; absent where no parser captured them. */
26
+ rawBody: string | undefined;
27
+ }>;
28
+ /** Decides whether a payment call may proceed; it throws when it may not. */
29
+ export type RequestAuthenticator = Readonly<{
30
+ /** Signed formats cover the body, so they run after parsing; others before. */
31
+ needsBody: boolean;
32
+ authenticate: (call: IncomingCall) => void | Promise<void>;
33
+ /** Clears anything held between calls, for a fresh run. */
34
+ reset: () => void;
35
+ }>;
36
+ /** A preparatory call's reply, and the request it refused if it refused one. */
37
+ export type PreparatoryAnswer = Readonly<{
38
+ reply: WireReply;
39
+ refused?: PaymentRequest;
40
+ }>;
41
+ /** The HTTP methods a format's calls use. */
42
+ export type RouteMethod = "GET" | "POST" | "PUT";
43
+
44
+ /** A call a format needs around its payment; it moves no money. */
45
+ export type PreparatoryRoute = Readonly<{
46
+ /** POST unless the format says otherwise. */
47
+ method?: RouteMethod;
48
+ path: string;
49
+ answer: (
50
+ body: unknown,
51
+ params: unknown,
52
+ headers?: RequestHeaders,
53
+ ) => PreparatoryAnswer;
54
+ }>;
55
+ /**
56
+ * One payout a format paid out of a balance its payments funded. It is not
57
+ * a payment effect: it moves money that a committed payment already moved,
58
+ * so the checker compares it with those payments and never counts it as one.
59
+ */
60
+ export type PayoutRecord = Readonly<{
61
+ payoutId: string;
62
+ /** The account the payout drew on: a payment's destination. */
63
+ account: string;
64
+ /** Minor units, as the request wrote them. */
65
+ amount: string;
66
+ currency: string;
67
+ /** The idempotency key the payout carried, if any. */
68
+ key: string | null;
69
+ paidAt: string;
70
+ }>;
71
+ /** Whether a declined key may be tried again, or its refusal stands. */
72
+ export const REFUSAL_REPLAYS = ["retryable", "final"] as const;
73
+ export type RefusalReplay = (typeof REFUSAL_REPLAYS)[number];
74
+
75
+ /**
76
+ * The provider's public face: where payments arrive, how they read, and how
77
+ * each outcome is answered. Records, faults and the checker never see it.
78
+ * `read` refuses whatever a reply could not answer, because `paid`, `declined`
79
+ * and `conflict` run after the ledger and must not fail.
80
+ */
81
+ export type PaymentWire = Readonly<{
82
+ path: string;
83
+ /** The declared flow every request is placed against. */
84
+ financialFlow: FinancialFlow;
85
+ form: boolean;
86
+ /** A JSON media type other than `application/json`, when the format has one. */
87
+ jsonType: string | undefined;
88
+ authenticator: RequestAuthenticator;
89
+ refusals: RefusalReplay;
90
+ read: (
91
+ headers: RequestHeaders,
92
+ body: unknown,
93
+ params?: unknown,
94
+ ) => PaymentRequest;
95
+ paid: (effect: Effect, created: boolean, sentKey?: string) => WireReply;
96
+ declined: (request: PaymentRequest) => WireReply;
97
+ conflict: (request: PaymentRequest) => WireReply;
98
+ preparatory: readonly PreparatoryRoute[];
99
+ /**
100
+ * Told once of each new payment as it commits, before any fault can drop
101
+ * its reply; a replay or refusal is never told.
102
+ */
103
+ committed?: (effect: Effect) => void;
104
+ /** Each payout drawn on a funded balance, in the order paid; none if absent. */
105
+ payouts?: () => readonly PayoutRecord[];
106
+ /** Clears state a format holds between its calls, for a fresh run. */
107
+ reset: () => void;
108
+ }>;
109
+
110
+ /** A credential compared whole, the same on every call. */
111
+ export const staticCredential = (
112
+ header: string,
113
+ prefix: string,
114
+ token: string,
115
+ ): RequestAuthenticator => ({
116
+ needsBody: false,
117
+ authenticate: ({ headers }) => {
118
+ requireCredential(headers[header], prefix, token);
119
+ },
120
+ reset: () => undefined,
121
+ });
122
+
123
+ /** The lab's own format, used when a run declares no other. */
124
+ export const nativeWire = (token: string): PaymentWire => ({
125
+ path: "/payouts",
126
+ financialFlow: { operation: "payout", moneyRoutes: {} },
127
+ form: false,
128
+ jsonType: undefined,
129
+ authenticator: staticCredential("authorization", BEARER, token),
130
+ refusals: "retryable",
131
+ read: (headers, body) => ({
132
+ key: recordKey(idSchema.parse(headers["idempotency-key"])),
133
+ paymentFromKey: false,
134
+ instruction: instructionSchema.parse(body),
135
+ }),
136
+ paid: (effect) => ({
137
+ status: 200,
138
+ body: { instruction: effect.instruction, effectId: effect.effectId },
139
+ headers: {},
140
+ }),
141
+ declined: () => ({
142
+ status: 402,
143
+ body: { error: "payment_declined" },
144
+ headers: {},
145
+ }),
146
+ conflict: () => ({
147
+ status: 422,
148
+ body: { error: "idempotency_key_conflict" },
149
+ headers: {},
150
+ }),
151
+ preparatory: [],
152
+ reset: () => undefined,
153
+ });
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": "src",
5
+ "outDir": "dist",
6
+ "noEmit": false
7
+ },
8
+ "include": ["src/**/*.ts"]
9
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2022"],
7
+ "types": ["bun", "node"],
8
+ "strict": true,
9
+ "noUncheckedIndexedAccess": true,
10
+ "exactOptionalPropertyTypes": true,
11
+ "useUnknownInCatchVariables": true,
12
+ "noImplicitOverride": true,
13
+ "noFallthroughCasesInSwitch": true,
14
+ "noPropertyAccessFromIndexSignature": true,
15
+ "forceConsistentCasingInFileNames": true,
16
+ "verbatimModuleSyntax": true,
17
+ "isolatedModules": true,
18
+ "skipLibCheck": false,
19
+ "noUnusedLocals": true,
20
+ "noUnusedParameters": true,
21
+ "noEmit": true
22
+ },
23
+ "include": ["src/**/*.ts", "test/**/*.ts", "verification/**/*.ts"]
24
+ }
@@ -0,0 +1,15 @@
1
+ # The per-service capture under a MandateOps name. The upstream image is
2
+ # pinned by digest; only its binary, certificates and notices are kept, under
3
+ # a neutral name, so operator views show this image's own entrypoint and no
4
+ # exposed ports. The lab mounts nothing into this container, and the binary
5
+ # sits under /usr/local/bin apart from every path a sidecar is given.
6
+ # Its licence ships with it.
7
+ FROM otel/ebpf-instrument:v0.15.2@sha256:101b5c773ac84545cac007ce3dbaf38bfb0e7091f26e813c08d649f35dca253e AS upstream
8
+
9
+ FROM scratch
10
+ COPY --from=upstream /etc/ssl/certs /etc/ssl/certs
11
+ COPY --from=upstream /NOTICES /licenses/capture/NOTICES
12
+ COPY --from=upstream /NOTICE /licenses/capture/NOTICE
13
+ COPY --from=upstream /obi /usr/local/bin/capture
14
+ COPY LICENSE /licenses/capture/LICENSE
15
+ ENTRYPOINT ["/usr/local/bin/capture"]