@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,173 @@
1
+ import type { ColumnType, Generated, Kysely, Transaction } from "kysely";
2
+ import { expressionBuilder, sql } from "kysely";
3
+ import { z } from "zod";
4
+ import { idSchema, instructionSchema, REJECTION_REASONS } from "./domain.js";
5
+ import type { Effect, Notification, RejectedRequest } from "./domain.js";
6
+
7
+ type InstructionColumn = ColumnType<unknown, string, never>;
8
+ type Timestamp = ColumnType<Date, never, never>;
9
+ type Sequence = Generated<string>;
10
+ export type Database = Readonly<{
11
+ idempotency_bindings: {
12
+ provider: string;
13
+ provider_account: string;
14
+ idempotency_key: string;
15
+ instruction_sha256: string;
16
+ effect_id: string;
17
+ };
18
+ effects: {
19
+ commit_sequence: Sequence;
20
+ effect_id: string;
21
+ provider: string;
22
+ provider_account: string;
23
+ operation: string;
24
+ idempotency_key: string;
25
+ instruction: InstructionColumn;
26
+ committed_at: Timestamp;
27
+ };
28
+ notifications: {
29
+ delivery_sequence: Sequence;
30
+ effect_id: string;
31
+ delivered_at: ColumnType<Date, string, never>;
32
+ delivery_id: string;
33
+ issued: number;
34
+ sent_at: ColumnType<Date | null, string | null, never>;
35
+ status: number | null;
36
+ };
37
+ rejected_requests: {
38
+ rejection_sequence: Sequence;
39
+ provider: string;
40
+ idempotency_key: string;
41
+ instruction: InstructionColumn;
42
+ provider_account: string;
43
+ operation: string;
44
+ reason: string;
45
+ payment_from_key: boolean;
46
+ rejected_at: Timestamp;
47
+ };
48
+ }>;
49
+ export type Queries = Kysely<Database>;
50
+ export type Client = Transaction<Database>;
51
+
52
+ export type Observations = Readonly<{
53
+ effects: readonly Effect[];
54
+ notifications: readonly Notification[];
55
+ rejected: readonly RejectedRequest[];
56
+ }>;
57
+
58
+ const UTC_MICROSECONDS = 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"';
59
+
60
+ /** Postgres renders microseconds, which a JavaScript date would lose. */
61
+ function utcText(column: string) {
62
+ const builder = expressionBuilder<Database, keyof Database>();
63
+ return builder.fn<string>("to_char", [
64
+ builder.fn("timezone", [builder.val("UTC"), sql.ref(column)]),
65
+ builder.val(UTC_MICROSECONDS),
66
+ ]);
67
+ }
68
+
69
+ const effectSchema = z
70
+ .object({
71
+ effectId: idSchema,
72
+ provider: idSchema,
73
+ key: idSchema,
74
+ instruction: instructionSchema,
75
+ providerAccount: idSchema,
76
+ operation: idSchema,
77
+ idempotencyScope: idSchema,
78
+ committedAt: z.string(),
79
+ })
80
+ .strict();
81
+ const rejectedSchema = z
82
+ .object({
83
+ provider: idSchema,
84
+ key: idSchema,
85
+ instruction: instructionSchema,
86
+ providerAccount: idSchema,
87
+ operation: idSchema,
88
+ reason: z.enum(REJECTION_REASONS),
89
+ paymentFromKey: z.boolean(),
90
+ rejectedAt: z.string(),
91
+ })
92
+ .strict();
93
+ const notificationSchema = z
94
+ .object({
95
+ effectId: idSchema,
96
+ deliveredAt: z.string(),
97
+ deliveryId: idSchema,
98
+ issued: z.number().int().positive(),
99
+ sentAt: z.string().nullable(),
100
+ status: z.number().int().nullable(),
101
+ })
102
+ .strict();
103
+
104
+ const effectRows = (client: Client) =>
105
+ client
106
+ .selectFrom("effects")
107
+ .select([
108
+ "effect_id as effectId",
109
+ "provider",
110
+ "idempotency_key as key",
111
+ "instruction",
112
+ "provider_account as providerAccount",
113
+ "operation",
114
+ utcText("committed_at").as("committedAt"),
115
+ ]);
116
+
117
+ const scoped = (
118
+ row: object | undefined,
119
+ idempotencyScope: string,
120
+ ): unknown => ({
121
+ ...row,
122
+ idempotencyScope,
123
+ });
124
+
125
+ export async function loadEffect(
126
+ client: Client,
127
+ effectId: string,
128
+ scope: string,
129
+ ): Promise<Effect> {
130
+ const row = await effectRows(client)
131
+ .where("effect_id", "=", effectId)
132
+ .executeTakeFirst();
133
+ return effectSchema.parse(scoped(row, scope));
134
+ }
135
+
136
+ /** Every record in its order; the caller supplies the one snapshot. */
137
+ export async function readObservations(
138
+ client: Client,
139
+ scope: string,
140
+ ): Promise<Observations> {
141
+ const effects = await effectRows(client).orderBy("commit_sequence").execute();
142
+ const notifications = await client
143
+ .selectFrom("notifications")
144
+ .select([
145
+ "effect_id as effectId",
146
+ utcText("delivered_at").as("deliveredAt"),
147
+ "delivery_id as deliveryId",
148
+ "issued",
149
+ utcText("sent_at").as("sentAt"),
150
+ "status",
151
+ ])
152
+ .orderBy("delivery_sequence")
153
+ .execute();
154
+ const rejected = await client
155
+ .selectFrom("rejected_requests")
156
+ .select([
157
+ "provider",
158
+ "idempotency_key as key",
159
+ "instruction",
160
+ "provider_account as providerAccount",
161
+ "operation",
162
+ "reason",
163
+ "payment_from_key as paymentFromKey",
164
+ utcText("rejected_at").as("rejectedAt"),
165
+ ])
166
+ .orderBy("rejection_sequence")
167
+ .execute();
168
+ return {
169
+ effects: effects.map((row) => effectSchema.parse(scoped(row, scope))),
170
+ notifications: notifications.map((row) => notificationSchema.parse(row)),
171
+ rejected: rejected.map((row) => rejectedSchema.parse(row)),
172
+ };
173
+ }
@@ -0,0 +1,114 @@
1
+ import { sql } from "kysely";
2
+ import type { ColumnDefinitionBuilder, Kysely } from "kysely";
3
+
4
+ // The schema belongs to a disposable audit_lab_* database only.
5
+ // Effects are a stock with an inflow only: rows are inserted, never updated or
6
+ // deleted. The authorised fresh-run reset uses TRUNCATE, which row triggers do
7
+ // not intercept by design.
8
+
9
+ const stampedNow = (column: ColumnDefinitionBuilder) =>
10
+ column.notNull().defaultTo(sql`clock_timestamp()`);
11
+
12
+ // Kysely has no builder for functions or triggers, so these stay as text.
13
+ const appendOnlyTriggers = `
14
+ CREATE OR REPLACE FUNCTION reject_provider_record_change() RETURNS trigger LANGUAGE plpgsql AS $$
15
+ BEGIN RAISE EXCEPTION 'append-only provider record'; END $$;
16
+ DROP TRIGGER IF EXISTS append_only_bindings ON idempotency_bindings;
17
+ CREATE TRIGGER append_only_bindings BEFORE UPDATE OR DELETE ON idempotency_bindings
18
+ FOR EACH ROW EXECUTE FUNCTION reject_provider_record_change();
19
+ DROP TRIGGER IF EXISTS append_only_effects ON effects;
20
+ CREATE TRIGGER append_only_effects BEFORE UPDATE OR DELETE ON effects
21
+ FOR EACH ROW EXECUTE FUNCTION reject_provider_record_change();
22
+ DROP TRIGGER IF EXISTS append_only_rejected ON rejected_requests;
23
+ CREATE TRIGGER append_only_rejected BEFORE UPDATE OR DELETE ON rejected_requests
24
+ FOR EACH ROW EXECUTE FUNCTION reject_provider_record_change();
25
+ DROP TRIGGER IF EXISTS append_only_notifications ON notifications;
26
+ CREATE TRIGGER append_only_notifications BEFORE UPDATE OR DELETE ON notifications
27
+ FOR EACH ROW EXECUTE FUNCTION reject_provider_record_change();
28
+ `;
29
+
30
+ /** Creates the provider's tables and their append-only triggers. */
31
+ export async function createSchema<Tables>(
32
+ database: Kysely<Tables>,
33
+ ): Promise<void> {
34
+ await database.transaction().execute(async (owner) => {
35
+ await owner.schema
36
+ .createTable("idempotency_bindings")
37
+ .ifNotExists()
38
+ .addColumn("provider", "text", (column) => column.notNull())
39
+ .addColumn("provider_account", "text", (column) => column.notNull())
40
+ .addColumn("idempotency_key", "text", (column) => column.notNull())
41
+ .addColumn("instruction_sha256", "text", (column) =>
42
+ column.notNull().check(sql`instruction_sha256 ~ '^[0-9a-f]{64}$'`),
43
+ )
44
+ .addColumn("effect_id", "text", (column) => column.notNull().unique())
45
+ .addPrimaryKeyConstraint("idempotency_bindings_pkey", [
46
+ "provider",
47
+ "provider_account",
48
+ "idempotency_key",
49
+ ])
50
+ .execute();
51
+ await owner.schema
52
+ .createTable("effects")
53
+ .ifNotExists()
54
+ .addColumn("commit_sequence", "bigserial", (column) =>
55
+ column.primaryKey(),
56
+ )
57
+ .addColumn("effect_id", "text", (column) =>
58
+ column.notNull().unique().references("idempotency_bindings.effect_id"),
59
+ )
60
+ .addColumn("provider", "text", (column) => column.notNull())
61
+ .addColumn("provider_account", "text", (column) => column.notNull())
62
+ .addColumn("operation", "text", (column) => column.notNull())
63
+ .addColumn("idempotency_key", "text", (column) => column.notNull())
64
+ .addColumn("instruction", "jsonb", (column) => column.notNull())
65
+ .addColumn("committed_at", "timestamptz", stampedNow)
66
+ .addUniqueConstraint("effects_key_unique", [
67
+ "provider",
68
+ "provider_account",
69
+ "idempotency_key",
70
+ ])
71
+ .addForeignKeyConstraint(
72
+ "effects_binding_fkey",
73
+ ["provider", "provider_account", "idempotency_key"],
74
+ "idempotency_bindings",
75
+ ["provider", "provider_account", "idempotency_key"],
76
+ )
77
+ .execute();
78
+ await owner.schema
79
+ .createTable("notifications")
80
+ .ifNotExists()
81
+ .addColumn("delivery_sequence", "bigserial", (column) =>
82
+ column.primaryKey(),
83
+ )
84
+ .addColumn("effect_id", "text", (column) =>
85
+ column.notNull().references("effects.effect_id"),
86
+ )
87
+ .addColumn("delivered_at", "timestamptz", (column) => column.notNull())
88
+ .addColumn("delivery_id", "text", (column) => column.notNull().unique())
89
+ .addColumn("issued", "integer", (column) =>
90
+ column.notNull().check(sql`issued >= 1`),
91
+ )
92
+ .addColumn("sent_at", "timestamptz")
93
+ .addColumn("status", "integer", (column) =>
94
+ column.check(sql`status BETWEEN 100 AND 599`),
95
+ )
96
+ .execute();
97
+ await owner.schema
98
+ .createTable("rejected_requests")
99
+ .ifNotExists()
100
+ .addColumn("rejection_sequence", "bigserial", (column) =>
101
+ column.primaryKey(),
102
+ )
103
+ .addColumn("provider", "text", (column) => column.notNull())
104
+ .addColumn("idempotency_key", "text", (column) => column.notNull())
105
+ .addColumn("instruction", "jsonb", (column) => column.notNull())
106
+ .addColumn("provider_account", "text", (column) => column.notNull())
107
+ .addColumn("operation", "text", (column) => column.notNull())
108
+ .addColumn("reason", "text", (column) => column.notNull())
109
+ .addColumn("payment_from_key", "boolean", (column) => column.notNull())
110
+ .addColumn("rejected_at", "timestamptz", stampedNow)
111
+ .execute();
112
+ await sql.raw(appendOnlyTriggers).execute(owner);
113
+ });
114
+ }
@@ -0,0 +1,86 @@
1
+ import { createHash, createPrivateKey, createPublicKey } from "node:crypto";
2
+ import type { KeyObject } from "node:crypto";
3
+ import { jwtVerify } from "jose";
4
+ import { BEARER, sameSecret } from "./auth.js";
5
+ import { MAX_RECORDS_PER_RUN, ProviderError } from "./domain.js";
6
+ import type { IncomingCall, RequestAuthenticator } from "./wire.js";
7
+
8
+ const REQUIRED_CLAIMS = ["uri", "nonce", "sub", "bodyHash", "exp", "iat"];
9
+
10
+ const unauthorised = () => new ProviderError(401, "unauthorised");
11
+
12
+ /** The lab token of a signed format is the hex of a PEM key; only its public half is used. */
13
+ function publicKeyOf(token: string): KeyObject {
14
+ return createPublicKey(
15
+ createPrivateKey(Buffer.from(token, "hex").toString("utf8")),
16
+ );
17
+ }
18
+
19
+ /** What a signed format is checked with. */
20
+ export type SignedJwtSettings = Readonly<{
21
+ token: string;
22
+ maxAgeSeconds: number;
23
+ now?: () => Date;
24
+ }>;
25
+
26
+ /**
27
+ * Verifies an RS256 token bound to one request: its path, its exact body and
28
+ * the caller's key, used once. A bad key refuses to build, so at startup. A
29
+ * nonce, string or number, is kept for the run; past the bound the run stops
30
+ * with its own error rather than reading as a bad credential.
31
+ */
32
+ export function signedJwtAuthenticator({
33
+ token,
34
+ maxAgeSeconds,
35
+ now = () => new Date(),
36
+ }: SignedJwtSettings): RequestAuthenticator {
37
+ const publicKey = publicKeyOf(token);
38
+ const nonces = new Set<string>();
39
+
40
+ const claimsOf = async (call: IncomingCall) => {
41
+ const header = call.headers["authorization"];
42
+ if (typeof header !== "string" || !header.startsWith(BEARER))
43
+ throw unauthorised();
44
+ const verified = await jwtVerify(header.slice(BEARER.length), publicKey, {
45
+ algorithms: ["RS256"],
46
+ maxTokenAge: `${String(maxAgeSeconds)}s`,
47
+ requiredClaims: REQUIRED_CLAIMS,
48
+ currentDate: now(),
49
+ }).catch(() => {
50
+ throw unauthorised();
51
+ });
52
+ return verified.payload;
53
+ };
54
+
55
+ return {
56
+ needsBody: true,
57
+ authenticate: async (call) => {
58
+ if (call.rawBody === undefined) throw unauthorised();
59
+ const { uri, nonce, sub, bodyHash } = await claimsOf(call);
60
+ const caller = call.headers["x-api-key"];
61
+ const digest = createHash("sha256").update(call.rawBody).digest("hex");
62
+ const spent =
63
+ typeof nonce === "string" || typeof nonce === "number"
64
+ ? `${typeof nonce}:${String(nonce)}`
65
+ : undefined;
66
+ if (
67
+ spent === undefined ||
68
+ typeof uri !== "string" ||
69
+ typeof sub !== "string" ||
70
+ typeof bodyHash !== "string" ||
71
+ typeof caller !== "string" ||
72
+ uri !== call.url ||
73
+ !sameSecret(sub, caller) ||
74
+ !sameSecret(bodyHash, digest) ||
75
+ nonces.has(spent)
76
+ )
77
+ throw unauthorised();
78
+ if (nonces.size >= MAX_RECORDS_PER_RUN)
79
+ throw new ProviderError(409, "nonce_limit");
80
+ nonces.add(spent);
81
+ },
82
+ reset: () => {
83
+ nonces.clear();
84
+ },
85
+ };
86
+ }
@@ -0,0 +1,318 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+
4
+ import { minorUnits } from "./amount.js";
5
+ import { BEARER } from "./auth.js";
6
+ import {
7
+ canonicalInstruction,
8
+ idSchema,
9
+ instructionSchema,
10
+ MAX_RECORDS_PER_RUN,
11
+ ProviderError,
12
+ recordKey,
13
+ requireRoom,
14
+ routeSchema,
15
+ } from "./domain.js";
16
+ import type { Instruction } from "./domain.js";
17
+ import { changedTermsOf } from "./profile.js";
18
+ import type { CalibratedProfile, ChangedTerms } from "./profile.js";
19
+ import { financialFlowSchema } from "./flow.js";
20
+ import { staticCredential } from "./wire.js";
21
+ import type { PaymentWire, PreparatoryAnswer, WireReply } from "./wire.js";
22
+
23
+ const declarationSchema = z
24
+ .object({
25
+ /** The provider the SDK built this format for; read by the record only. */
26
+ provider: idSchema.optional(),
27
+ flow: z.literal("wise"),
28
+ /** What the format's flow is, so each request can be placed against it. */
29
+ financialFlow: financialFlowSchema,
30
+ fixed: z
31
+ .object({
32
+ tenant: idSchema,
33
+ agent: idSchema,
34
+ delegation: idSchema,
35
+ network: idSchema,
36
+ })
37
+ .strict(),
38
+ /** Every supported currency's places: any other is refused, never assumed. */
39
+ scales: z.record(idSchema, z.number().int().min(0).max(18)),
40
+ routes: z
41
+ .object({
42
+ quotes: routeSchema.refine((path) => path.includes(":profileId")),
43
+ transfers: routeSchema,
44
+ fund: routeSchema.refine(
45
+ (path) => path.includes(":profileId") && path.includes(":transferId"),
46
+ ),
47
+ })
48
+ .strict(),
49
+ })
50
+ .strict();
51
+ const decimalSchema = z.union([z.number(), z.string()]);
52
+ const quoteSchema = z.object({
53
+ sourceCurrency: idSchema,
54
+ targetCurrency: idSchema,
55
+ sourceAmount: decimalSchema.optional(),
56
+ targetAmount: decimalSchema.optional(),
57
+ });
58
+ const transferSchema = z.object({
59
+ targetAccount: z.union([z.number().int().positive(), idSchema]),
60
+ quoteUuid: idSchema,
61
+ customerTransactionId: idSchema,
62
+ });
63
+ const profileParamsSchema = z.object({ profileId: idSchema });
64
+ const fundParamsSchema = profileParamsSchema.extend({ transferId: idSchema });
65
+
66
+ type Quote = Readonly<{
67
+ profileId: string;
68
+ sourceCurrency: string;
69
+ targetCurrency: string;
70
+ sourceAmount: unknown;
71
+ amountMinor: string;
72
+ }>;
73
+ type PendingTransfer = Readonly<{
74
+ id: number;
75
+ key: string;
76
+ sentKey: string;
77
+ quoteUuid: string;
78
+ instruction: Instruction;
79
+ }>;
80
+
81
+ /** A rate is not imitated, so a target amount fixes the source only 1:1. */
82
+ function sourceOf({
83
+ sourceCurrency,
84
+ targetCurrency,
85
+ sourceAmount,
86
+ targetAmount,
87
+ }: z.infer<typeof quoteSchema>): unknown {
88
+ if (sourceAmount !== undefined) return sourceAmount;
89
+ if (targetAmount !== undefined && sourceCurrency === targetCurrency)
90
+ return targetAmount;
91
+ throw new ProviderError(400, "source_amount_required");
92
+ }
93
+
94
+ const WAITING = "incoming_payment_waiting";
95
+ const CANCELLED = "cancelled";
96
+ /** Without a calibrated observation, a funded transfer reads as processing. */
97
+ export const DECLARED_FUNDED_STATE = "processing";
98
+
99
+ const reply = (status: number, body: unknown): WireReply => ({
100
+ status,
101
+ body,
102
+ headers: {},
103
+ });
104
+
105
+ /**
106
+ * Wise's quote, transfer and fund calls. Only funding moves money: a quote or
107
+ * an unfunded transfer is process state, reset per run, and never an effect.
108
+ * The fund call goes through the same store, barrier and refusal as any other
109
+ * format's payment. The account is the quote's profile and the asset its
110
+ * target currency, so neither is declared. Whether a repeat fund or a reused
111
+ * `customerTransactionId` with other terms answers as it does here is
112
+ * unverified, as are the recipient call and the strong customer step. A quote
113
+ * may serve several transfers here even if Wise refuses that, as refusing it
114
+ * would hide a second payment from the checker.
115
+ */
116
+ /** A repeated `customerTransactionId` with other terms: see `ChangedTerms`. */
117
+ export type WiseOptions = Readonly<{
118
+ changedTerms: ChangedTerms;
119
+ /** The state a funded transfer reads as; a profile may have observed it. */
120
+ fundedState: string;
121
+ /** Most quotes and transfers one run keeps. */
122
+ recordLimit: number;
123
+ }>;
124
+
125
+ /** The staged options a profile supports; the declared ones without one. */
126
+ export function wiseOptionsOf(
127
+ profile: CalibratedProfile | undefined,
128
+ recordLimit: number,
129
+ ): WiseOptions {
130
+ const funded = profile?.replica.fundedState;
131
+ return {
132
+ changedTerms: profile ? changedTermsOf(profile) : "refused",
133
+ fundedState: funded?.observed ? funded.state : DECLARED_FUNDED_STATE,
134
+ recordLimit,
135
+ };
136
+ }
137
+
138
+ export function wiseWire(
139
+ declaration: unknown,
140
+ token: string,
141
+ { changedTerms, fundedState, recordLimit }: WiseOptions = {
142
+ changedTerms: "refused",
143
+ fundedState: DECLARED_FUNDED_STATE,
144
+ recordLimit: MAX_RECORDS_PER_RUN,
145
+ },
146
+ ): PaymentWire {
147
+ const { fixed, scales, routes, financialFlow } =
148
+ declarationSchema.parse(declaration);
149
+ const quotes = new Map<string, Quote>();
150
+ const transfers = new Map<string, PendingTransfer>();
151
+ const transferByKey = new Map<string, PendingTransfer>();
152
+ /** Each transfer's state: waiting, funded or cancelled. */
153
+ const states = new Map<string, string>();
154
+ const stateOf = (transfer: PendingTransfer): string =>
155
+ states.get(String(transfer.id)) ?? WAITING;
156
+
157
+ const digitsOf = (currency: string): number => {
158
+ const digits = Object.hasOwn(scales, currency)
159
+ ? scales[currency]
160
+ : undefined;
161
+ if (digits === undefined) throw new ProviderError(400, "unsupported_asset");
162
+ return digits;
163
+ };
164
+
165
+ const quoted = (body: unknown, params: unknown): PreparatoryAnswer => {
166
+ requireRoom(quotes, recordLimit);
167
+ const { profileId } = profileParamsSchema.parse(params);
168
+ const request = quoteSchema.parse(body);
169
+ const { sourceCurrency, targetCurrency } = request;
170
+ const sourceAmount = sourceOf(request);
171
+ digitsOf(targetCurrency);
172
+ const id = randomUUID();
173
+ quotes.set(id, {
174
+ profileId,
175
+ sourceCurrency,
176
+ targetCurrency,
177
+ sourceAmount,
178
+ amountMinor: minorUnits(sourceAmount, digitsOf(sourceCurrency)),
179
+ });
180
+ return {
181
+ reply: reply(200, { id, sourceCurrency, targetCurrency, sourceAmount }),
182
+ };
183
+ };
184
+
185
+ const transferReply = (transfer: PendingTransfer): WireReply => {
186
+ const quote = quotes.get(transfer.quoteUuid);
187
+ return reply(200, {
188
+ id: transfer.id,
189
+ targetAccount: transfer.instruction.destination,
190
+ quoteUuid: transfer.quoteUuid,
191
+ status: stateOf(transfer),
192
+ sourceCurrency: quote?.sourceCurrency,
193
+ sourceValue: quote?.sourceAmount,
194
+ targetCurrency: quote?.targetCurrency,
195
+ customerTransactionId: transfer.sentKey,
196
+ });
197
+ };
198
+
199
+ const created = (body: unknown): PreparatoryAnswer => {
200
+ const { targetAccount, quoteUuid, customerTransactionId } =
201
+ transferSchema.parse(body);
202
+ const quote = quotes.get(quoteUuid);
203
+ if (!quote) throw new ProviderError(404, "quote_not_found");
204
+ const key = recordKey(customerTransactionId);
205
+ const instruction = instructionSchema.parse({
206
+ ...fixed,
207
+ payment: key,
208
+ account: quote.profileId,
209
+ destination: String(targetAccount),
210
+ currency: quote.sourceCurrency,
211
+ asset: quote.targetCurrency,
212
+ amount: quote.amountMinor,
213
+ });
214
+ const existing = transferByKey.get(key);
215
+ if (existing) {
216
+ const sameTerms =
217
+ canonicalInstruction(existing.instruction) ===
218
+ canonicalInstruction(instruction);
219
+ if (!sameTerms && changedTerms === "refused")
220
+ return {
221
+ reply: reply(422, { error: "transaction_id_conflict" }),
222
+ refused: { key, paymentFromKey: true, instruction },
223
+ };
224
+ return { reply: transferReply(existing) };
225
+ }
226
+ requireRoom(transfers, recordLimit);
227
+ const transfer = {
228
+ id: transfers.size + 1,
229
+ key,
230
+ sentKey: customerTransactionId,
231
+ quoteUuid,
232
+ instruction,
233
+ };
234
+ transfers.set(String(transfer.id), transfer);
235
+ transferByKey.set(key, transfer);
236
+ return { reply: transferReply(transfer) };
237
+ };
238
+
239
+ const transferParams = z.object({ transferId: idSchema });
240
+ const known = (params: unknown): PendingTransfer => {
241
+ const { transferId } = transferParams.parse(params);
242
+ const transfer = transfers.get(transferId);
243
+ if (!transfer) throw new ProviderError(404, "transfer_not_found");
244
+ return transfer;
245
+ };
246
+ const read = (_body: unknown, params: unknown): PreparatoryAnswer => ({
247
+ reply: transferReply(known(params)),
248
+ });
249
+ // Cancelling a funded transfer is not imitated beyond a refusal.
250
+ const cancel = (_body: unknown, params: unknown): PreparatoryAnswer => {
251
+ const transfer = known(params);
252
+ const state = stateOf(transfer);
253
+ if (state !== WAITING && state !== CANCELLED)
254
+ return {
255
+ reply: reply(422, { errors: [{ code: "cancellation_not_allowed" }] }),
256
+ };
257
+ states.set(String(transfer.id), CANCELLED);
258
+ return { reply: transferReply(transfer) };
259
+ };
260
+
261
+ return {
262
+ path: routes.fund,
263
+ financialFlow,
264
+ committed: (effect) => {
265
+ const transfer = transferByKey.get(effect.key);
266
+ if (transfer) states.set(String(transfer.id), fundedState);
267
+ },
268
+ form: false,
269
+ jsonType: undefined,
270
+ authenticator: staticCredential("authorization", BEARER, token),
271
+ refusals: "retryable",
272
+ read: (_headers, _body, params) => {
273
+ const { profileId, transferId } = fundParamsSchema.parse(params);
274
+ const transfer = transfers.get(transferId);
275
+ if (transfer?.instruction.account !== profileId)
276
+ throw new ProviderError(404, "transfer_not_found");
277
+ if (stateOf(transfer) === CANCELLED)
278
+ throw new ProviderError(422, "transfer_cancelled");
279
+ return {
280
+ key: transfer.key,
281
+ paymentFromKey: true,
282
+ instruction: transfer.instruction,
283
+ };
284
+ },
285
+ paid: ({ key }) =>
286
+ reply(201, {
287
+ type: "BALANCE",
288
+ status: "COMPLETED",
289
+ errorCode: null,
290
+ balanceTransactionId: transferByKey.get(key)?.id,
291
+ }),
292
+ // Documented as a REJECTED status; its HTTP status is unverified.
293
+ declined: () =>
294
+ reply(201, {
295
+ type: "BALANCE",
296
+ status: "REJECTED",
297
+ errorCode: "transfer.insufficient_funds",
298
+ }),
299
+ // Unreached: a key names one transfer, so a fund cannot change its terms.
300
+ conflict: () => reply(409, {}),
301
+ preparatory: [
302
+ { path: routes.quotes, answer: quoted },
303
+ { path: routes.transfers, answer: created },
304
+ { method: "GET", path: `${routes.transfers}/:transferId`, answer: read },
305
+ {
306
+ method: "PUT",
307
+ path: `${routes.transfers}/:transferId/cancel`,
308
+ answer: cancel,
309
+ },
310
+ ],
311
+ reset: () => {
312
+ states.clear();
313
+ quotes.clear();
314
+ transfers.clear();
315
+ transferByKey.clear();
316
+ },
317
+ };
318
+ }