@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.
- package/LICENSE +55 -0
- package/README.md +181 -2
- package/audit-lab/README.md +194 -0
- package/audit-lab/bin/mandateops +0 -0
- package/audit-lab/contracts/contact-plain-text.vectors.json +85 -0
- package/audit-lab/contracts/history-reading.md +185 -0
- package/audit-lab/contracts/history-reading.vectors.json +284 -0
- package/audit-lab/contracts/profiles.md +161 -0
- package/audit-lab/contracts/properties.md +512 -0
- package/audit-lab/contracts/sdk-config.md +155 -0
- package/audit-lab/contracts/system-under-test.md +385 -0
- package/audit-lab/contracts/test-provider.md +350 -0
- package/audit-lab/lab/compose.audit.yml +181 -0
- package/audit-lab/lab/config/fault-control.json +14 -0
- package/audit-lab/lab/examples/agents/Dockerfile +28 -0
- package/audit-lab/lab/examples/agents/codeloc.cjs +199 -0
- package/audit-lab/lab/examples/agents/load.cjs +9 -0
- package/audit-lab/lab/examples/agents/package-lock.json +2840 -0
- package/audit-lab/lab/examples/agents/package.json +9 -0
- package/audit-lab/lab/examples/agents/python/mandateops_codeloc.py +271 -0
- package/audit-lab/lab/examples/agents/python/sitecustomize.py +51 -0
- package/audit-lab/lab/examples/agents/requirements-python.txt +522 -0
- package/audit-lab/lab/examples/agents/telemetry-router.cjs +272 -0
- package/audit-lab/lab/examples/test-provider/.dockerignore +4 -0
- package/audit-lab/lab/examples/test-provider/Dockerfile +28 -0
- package/audit-lab/lab/examples/test-provider/bun.lock +405 -0
- package/audit-lab/lab/examples/test-provider/package.json +42 -0
- package/audit-lab/lab/examples/test-provider/src/amount.ts +32 -0
- package/audit-lab/lab/examples/test-provider/src/app.ts +538 -0
- package/audit-lab/lab/examples/test-provider/src/auth.ts +30 -0
- package/audit-lab/lab/examples/test-provider/src/barrier.ts +262 -0
- package/audit-lab/lab/examples/test-provider/src/codeloc.ts +27 -0
- package/audit-lab/lab/examples/test-provider/src/config.ts +311 -0
- package/audit-lab/lab/examples/test-provider/src/connect.ts +204 -0
- package/audit-lab/lab/examples/test-provider/src/declaration.ts +270 -0
- package/audit-lab/lab/examples/test-provider/src/declared.ts +198 -0
- package/audit-lab/lab/examples/test-provider/src/domain.ts +193 -0
- package/audit-lab/lab/examples/test-provider/src/egress.ts +396 -0
- package/audit-lab/lab/examples/test-provider/src/flow.ts +263 -0
- package/audit-lab/lab/examples/test-provider/src/gate.ts +301 -0
- package/audit-lab/lab/examples/test-provider/src/main.ts +31 -0
- package/audit-lab/lab/examples/test-provider/src/notify.ts +157 -0
- package/audit-lab/lab/examples/test-provider/src/owner.ts +60 -0
- package/audit-lab/lab/examples/test-provider/src/payment.ts +103 -0
- package/audit-lab/lab/examples/test-provider/src/profile.ts +417 -0
- package/audit-lab/lab/examples/test-provider/src/request.ts +201 -0
- package/audit-lab/lab/examples/test-provider/src/rows.ts +173 -0
- package/audit-lab/lab/examples/test-provider/src/schema.ts +114 -0
- package/audit-lab/lab/examples/test-provider/src/signature.ts +86 -0
- package/audit-lab/lab/examples/test-provider/src/staged.ts +318 -0
- package/audit-lab/lab/examples/test-provider/src/store.ts +432 -0
- package/audit-lab/lab/examples/test-provider/src/traffic.ts +50 -0
- package/audit-lab/lab/examples/test-provider/src/webauthn.d.ts +11 -0
- package/audit-lab/lab/examples/test-provider/src/wire.ts +153 -0
- package/audit-lab/lab/examples/test-provider/tsconfig.build.json +9 -0
- package/audit-lab/lab/examples/test-provider/tsconfig.json +24 -0
- package/audit-lab/lab/images/capture/Dockerfile +15 -0
- package/audit-lab/lab/images/capture/LICENSE +201 -0
- package/audit-lab/lab/images/fault-control/Dockerfile +13 -0
- package/audit-lab/lab/images/fault-control/LICENSE +21 -0
- package/audit-lab/lab/images/provider-store/Dockerfile +4 -0
- package/audit-lab/lab/images/provider-store/LICENSE +23 -0
- package/audit-lab/lab/images/telemetry/Dockerfile +14 -0
- package/audit-lab/lab/images/telemetry/LICENSE +201 -0
- package/audit-lab/lab/scripts/compose-down.sh +148 -0
- package/audit-lab/lab/scripts/compose-lib.sh +663 -0
- package/audit-lab/lab/scripts/compose-up.sh +240 -0
- package/package.json +16 -4
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
idSchema,
|
|
5
|
+
MAX_RECORDS_PER_RUN,
|
|
6
|
+
ProviderError,
|
|
7
|
+
requireRoom,
|
|
8
|
+
} from "./domain.js";
|
|
9
|
+
import type { DeclaredWire } from "./declaration.js";
|
|
10
|
+
import type {
|
|
11
|
+
PaymentWire,
|
|
12
|
+
PayoutRecord,
|
|
13
|
+
PreparatoryAnswer,
|
|
14
|
+
RequestHeaders,
|
|
15
|
+
WireReply,
|
|
16
|
+
} from "./wire.js";
|
|
17
|
+
|
|
18
|
+
/** Where Stripe Connect's setup and payout calls sit. */
|
|
19
|
+
export type ConnectRoutes = NonNullable<DeclaredWire["connect"]>;
|
|
20
|
+
|
|
21
|
+
/** The header naming the connected account a payout draws on. */
|
|
22
|
+
const CONNECTED_ACCOUNT_HEADER = "stripe-account";
|
|
23
|
+
/** The header a payout may carry its idempotency key in. */
|
|
24
|
+
const IDEMPOTENCY_HEADER = "idempotency-key";
|
|
25
|
+
/**
|
|
26
|
+
* A minor-unit amount: a positive integer of at most 15 digits, so the
|
|
27
|
+
* number a reply carries is the amount drawn, exactly.
|
|
28
|
+
*/
|
|
29
|
+
const MINOR_AMOUNT = /^[1-9][0-9]{0,14}$/;
|
|
30
|
+
|
|
31
|
+
const externalParamsSchema = z.object({ accountId: idSchema });
|
|
32
|
+
const payoutSchema = z.object({
|
|
33
|
+
amount: z.union([z.string(), z.number()]).transform(String),
|
|
34
|
+
currency: idSchema,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
/** A payout made under an idempotency key. */
|
|
38
|
+
type KeyedPayout = Readonly<{ terms: string; reply: WireReply }>;
|
|
39
|
+
|
|
40
|
+
const reply = (status: number, body: unknown): WireReply => ({
|
|
41
|
+
status,
|
|
42
|
+
body,
|
|
43
|
+
headers: {},
|
|
44
|
+
});
|
|
45
|
+
const stripeError = (status: number, code: string, message: string) =>
|
|
46
|
+
reply(status, { error: { type: "invalid_request_error", code, message } });
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Stripe Connect around a transfer format: create a connected account, attach its bank
|
|
50
|
+
* account, transfer to it, then pay out from it.
|
|
51
|
+
*
|
|
52
|
+
* Only the transfer is a payment: it goes through the same store, barrier,
|
|
53
|
+
* refusal and idempotency as the format it wraps, and its destination must
|
|
54
|
+
* be an account created here. Creating an account or a bank account moves no
|
|
55
|
+
* money and is process state, reset per run. A payout draws on the connected
|
|
56
|
+
* account's balance, which only committed transfers add to, so a payout
|
|
57
|
+
* beyond what reached the account is refused for insufficient funds, as
|
|
58
|
+
* Stripe refuses it. A payout under an `Idempotency-Key` it has already used
|
|
59
|
+
* replays the first payout and draws nothing more; without a key each payout
|
|
60
|
+
* is new, as at Stripe. A payout is not an effect: each one paid is listed
|
|
61
|
+
* apart from effects, so the checker can hold it against the transfers that
|
|
62
|
+
* funded its account without counting it as a second payment. A replay is
|
|
63
|
+
* not listed again, and a refused payout drew nothing. Currencies compare
|
|
64
|
+
* in lower case, as Stripe writes them. Account fields beyond the
|
|
65
|
+
* identifier, bank details, and payout timing are not imitated.
|
|
66
|
+
*/
|
|
67
|
+
export function connectWire(
|
|
68
|
+
transfer: PaymentWire,
|
|
69
|
+
routes: ConnectRoutes,
|
|
70
|
+
): PaymentWire {
|
|
71
|
+
const accounts = new Map<string, Map<string, bigint>>();
|
|
72
|
+
const externalAccounts = new Map<string, string>();
|
|
73
|
+
/** Each keyed payout's terms and reply, so a retry replays it. */
|
|
74
|
+
const keyedPayouts = new Map<string, KeyedPayout>();
|
|
75
|
+
/** Every payout paid, in order; a replay adds none. */
|
|
76
|
+
const drawn: PayoutRecord[] = [];
|
|
77
|
+
|
|
78
|
+
const balances = (accountId: string): Map<string, bigint> => {
|
|
79
|
+
const found = accounts.get(accountId);
|
|
80
|
+
if (!found) throw new ProviderError(404, "resource_missing");
|
|
81
|
+
return found;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const createdAccount = (): PreparatoryAnswer => {
|
|
85
|
+
requireRoom(accounts);
|
|
86
|
+
const id = `acct_${String(accounts.size + 1).padStart(16, "0")}`;
|
|
87
|
+
accounts.set(id, new Map());
|
|
88
|
+
return { reply: reply(200, { id, object: "account" }) };
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const createdExternal = (
|
|
92
|
+
_body: unknown,
|
|
93
|
+
params: unknown,
|
|
94
|
+
): PreparatoryAnswer => {
|
|
95
|
+
const { accountId } = externalParamsSchema.parse(params);
|
|
96
|
+
balances(accountId);
|
|
97
|
+
requireRoom(externalAccounts);
|
|
98
|
+
const id = `ba_${String(externalAccounts.size + 1).padStart(16, "0")}`;
|
|
99
|
+
externalAccounts.set(id, accountId);
|
|
100
|
+
return {
|
|
101
|
+
reply: reply(200, { id, object: "bank_account", account: accountId }),
|
|
102
|
+
};
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const paidOut = (
|
|
106
|
+
body: unknown,
|
|
107
|
+
_params: unknown,
|
|
108
|
+
headers: RequestHeaders = {},
|
|
109
|
+
): PreparatoryAnswer => {
|
|
110
|
+
const accountId = idSchema.parse(headers[CONNECTED_ACCOUNT_HEADER]);
|
|
111
|
+
const held = balances(accountId);
|
|
112
|
+
const parsed = payoutSchema.parse(body);
|
|
113
|
+
const amount = parsed.amount;
|
|
114
|
+
const currency = parsed.currency.toLowerCase();
|
|
115
|
+
if (!MINOR_AMOUNT.test(amount))
|
|
116
|
+
throw new ProviderError(400, "invalid_amount");
|
|
117
|
+
const sentKey = headers[IDEMPOTENCY_HEADER];
|
|
118
|
+
const key = sentKey === undefined ? undefined : idSchema.parse(sentKey);
|
|
119
|
+
const terms = JSON.stringify([accountId, amount, currency]);
|
|
120
|
+
const earlier = key === undefined ? undefined : keyedPayouts.get(key);
|
|
121
|
+
if (earlier)
|
|
122
|
+
return {
|
|
123
|
+
reply:
|
|
124
|
+
earlier.terms === terms
|
|
125
|
+
? earlier.reply
|
|
126
|
+
: stripeError(
|
|
127
|
+
400,
|
|
128
|
+
"idempotency_key_in_use",
|
|
129
|
+
"Keys can only be used with the same parameters",
|
|
130
|
+
),
|
|
131
|
+
};
|
|
132
|
+
if (key !== undefined) requireRoom(keyedPayouts);
|
|
133
|
+
const wanted = BigInt(amount);
|
|
134
|
+
const available = held.get(currency) ?? 0n;
|
|
135
|
+
if (wanted > available)
|
|
136
|
+
return {
|
|
137
|
+
reply: stripeError(
|
|
138
|
+
400,
|
|
139
|
+
"balance_insufficient",
|
|
140
|
+
"Insufficient funds in the connected account",
|
|
141
|
+
),
|
|
142
|
+
};
|
|
143
|
+
if (drawn.length >= MAX_RECORDS_PER_RUN)
|
|
144
|
+
throw new ProviderError(409, "stage_limit");
|
|
145
|
+
held.set(currency, available - wanted);
|
|
146
|
+
const payoutId = `po_${String(drawn.length + 1).padStart(16, "0")}`;
|
|
147
|
+
drawn.push({
|
|
148
|
+
payoutId,
|
|
149
|
+
account: accountId,
|
|
150
|
+
amount,
|
|
151
|
+
currency,
|
|
152
|
+
key: key ?? null,
|
|
153
|
+
paidAt: new Date().toISOString(),
|
|
154
|
+
});
|
|
155
|
+
const paid = reply(200, {
|
|
156
|
+
id: payoutId,
|
|
157
|
+
object: "payout",
|
|
158
|
+
amount: Number(wanted),
|
|
159
|
+
currency,
|
|
160
|
+
status: "paid",
|
|
161
|
+
failure_code: null,
|
|
162
|
+
failure_message: null,
|
|
163
|
+
});
|
|
164
|
+
if (key !== undefined) keyedPayouts.set(key, { terms, reply: paid });
|
|
165
|
+
return { reply: paid };
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
...transfer,
|
|
170
|
+
read: (headers, body, params) => {
|
|
171
|
+
const payment = transfer.read(headers, body, params);
|
|
172
|
+
// Stripe refuses a transfer to an account it does not hold.
|
|
173
|
+
balances(payment.instruction.destination);
|
|
174
|
+
return payment;
|
|
175
|
+
},
|
|
176
|
+
// Runs after the effect is committed, so it never throws: a reset that
|
|
177
|
+
// removed the account meanwhile leaves nothing to credit, and the
|
|
178
|
+
// client still receives the committed transfer's reply.
|
|
179
|
+
committed: (effect) => {
|
|
180
|
+
transfer.committed?.(effect);
|
|
181
|
+
const held = accounts.get(effect.instruction.destination);
|
|
182
|
+
if (!held) return;
|
|
183
|
+
const currency = effect.instruction.currency.toLowerCase();
|
|
184
|
+
held.set(
|
|
185
|
+
currency,
|
|
186
|
+
(held.get(currency) ?? 0n) + BigInt(effect.instruction.amount),
|
|
187
|
+
);
|
|
188
|
+
},
|
|
189
|
+
payouts: () => [...drawn],
|
|
190
|
+
preparatory: [
|
|
191
|
+
...transfer.preparatory,
|
|
192
|
+
{ path: routes.accounts, answer: createdAccount },
|
|
193
|
+
{ path: routes.externalAccounts, answer: createdExternal },
|
|
194
|
+
{ path: routes.payouts, answer: paidOut },
|
|
195
|
+
],
|
|
196
|
+
reset: () => {
|
|
197
|
+
transfer.reset();
|
|
198
|
+
accounts.clear();
|
|
199
|
+
externalAccounts.clear();
|
|
200
|
+
keyedPayouts.clear();
|
|
201
|
+
drawn.length = 0;
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { getAddress, isAddress } from "viem";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { BEARER } from "./auth.js";
|
|
4
|
+
import { financialFlowSchema } from "./flow.js";
|
|
5
|
+
import { idSchema, instructionSchema, routeSchema } from "./domain.js";
|
|
6
|
+
import { REFUSAL_REPLAYS } from "./wire.js";
|
|
7
|
+
|
|
8
|
+
const TERM_NAMES = Object.keys(instructionSchema.shape);
|
|
9
|
+
export const TOKEN = /\{\{([a-zA-Z]+)(:number)?\}\}/g;
|
|
10
|
+
const REQUEST_TOKENS = [
|
|
11
|
+
...TERM_NAMES,
|
|
12
|
+
"key",
|
|
13
|
+
"amount:number",
|
|
14
|
+
"amountMajor",
|
|
15
|
+
] as const;
|
|
16
|
+
const EFFECT_TOKENS = new Set([...REQUEST_TOKENS, "effectId"]);
|
|
17
|
+
const REFUSAL_TOKENS = new Set<string>(REQUEST_TOKENS);
|
|
18
|
+
export const AMOUNT_NUMBER = "{{amount:number}}";
|
|
19
|
+
export const AMOUNT_NUMBER_TOKEN = "amount:number";
|
|
20
|
+
const MAX_MINOR_DIGITS = 18;
|
|
21
|
+
const DEFAULT_TOKEN_AGE_SECONDS = 60;
|
|
22
|
+
/** A field path of this form reads a route parameter, not the body. */
|
|
23
|
+
export const ROUTE_PARAMETER = ":";
|
|
24
|
+
const ARRAY_STEP = /^[0-9]+$/;
|
|
25
|
+
|
|
26
|
+
const headerName = z.string().regex(/^[a-z0-9-]{1,64}$/);
|
|
27
|
+
const bodyPath = z.string().min(1).max(128);
|
|
28
|
+
const termName = z.enum(TERM_NAMES);
|
|
29
|
+
|
|
30
|
+
const replySchema = z
|
|
31
|
+
.object({
|
|
32
|
+
status: z.number().int().min(200).max(599),
|
|
33
|
+
body: z.json(),
|
|
34
|
+
headers: z.record(headerName, z.string().max(256)).default({}),
|
|
35
|
+
})
|
|
36
|
+
.strict();
|
|
37
|
+
export type DeclaredReply = z.infer<typeof replySchema>;
|
|
38
|
+
export type ReplyValues = Readonly<Record<string, string>>;
|
|
39
|
+
|
|
40
|
+
const contractKey = z
|
|
41
|
+
.string()
|
|
42
|
+
.regex(/^[a-zA-Z0-9_-]{1,80}@[a-zA-Z0-9_-]{1,80}$/);
|
|
43
|
+
/** EIP-55 only: a contract is declared once, in the form evidence shows it. */
|
|
44
|
+
const addressSchema = z
|
|
45
|
+
.string()
|
|
46
|
+
.refine((value) => isAddress(value) && getAddress(value) === value);
|
|
47
|
+
/** Where a format states no limit: Stripe's, the longest documented here. */
|
|
48
|
+
const DEFAULT_KEY_LENGTH = 255;
|
|
49
|
+
const keyLength = z.number().int().min(1).max(1024).default(DEFAULT_KEY_LENGTH);
|
|
50
|
+
|
|
51
|
+
const KEY_SHAPE_NAMES = ["uuid_v4", "lowercase_slug"] as const;
|
|
52
|
+
type KeyShape = (typeof KEY_SHAPE_NAMES)[number];
|
|
53
|
+
export const KEY_SHAPES: Readonly<Record<KeyShape, z.ZodType<string>>> = {
|
|
54
|
+
uuid_v4: z.uuid({ version: "v4" }),
|
|
55
|
+
lowercase_slug: z.string().regex(/^[a-z0-9_-]+$/),
|
|
56
|
+
};
|
|
57
|
+
const WIRE_REPLAYS = ["same_reply", "duplicate_reply"] as const;
|
|
58
|
+
|
|
59
|
+
const digitsSchema = z.number().int().min(0).max(MAX_MINOR_DIGITS);
|
|
60
|
+
|
|
61
|
+
const declaredSchema = z
|
|
62
|
+
.object({
|
|
63
|
+
/** The provider the SDK built this format for; read by the record only. */
|
|
64
|
+
provider: idSchema.optional(),
|
|
65
|
+
path: routeSchema,
|
|
66
|
+
encoding: z.enum(["json", "form"]).default("json"),
|
|
67
|
+
jsonType: z
|
|
68
|
+
.string()
|
|
69
|
+
.regex(/^application\/[a-z0-9.+-]{1,64}$/)
|
|
70
|
+
.refine((type) => type !== "application/json", "already accepted")
|
|
71
|
+
.optional(),
|
|
72
|
+
credential: z
|
|
73
|
+
.union([
|
|
74
|
+
z.object({ header: headerName, prefix: z.string().max(32) }).strict(),
|
|
75
|
+
z.object({ basic: z.literal(true) }).strict(),
|
|
76
|
+
z
|
|
77
|
+
.object({
|
|
78
|
+
signedJwt: z.literal(true),
|
|
79
|
+
maxAgeSeconds: z
|
|
80
|
+
.number()
|
|
81
|
+
.int()
|
|
82
|
+
.min(1)
|
|
83
|
+
.max(3600)
|
|
84
|
+
.default(DEFAULT_TOKEN_AGE_SECONDS),
|
|
85
|
+
})
|
|
86
|
+
.strict(),
|
|
87
|
+
])
|
|
88
|
+
.default({ header: "authorization", prefix: BEARER }),
|
|
89
|
+
key: z.union([
|
|
90
|
+
z
|
|
91
|
+
.object({
|
|
92
|
+
header: headerName,
|
|
93
|
+
maxLength: keyLength,
|
|
94
|
+
/** Absent means no idempotency: each request is its own payment. */
|
|
95
|
+
optional: z.boolean().default(false),
|
|
96
|
+
})
|
|
97
|
+
.strict(),
|
|
98
|
+
z
|
|
99
|
+
.object({
|
|
100
|
+
field: bodyPath,
|
|
101
|
+
maxLength: keyLength,
|
|
102
|
+
/** Absent means no idempotency: each request is its own payment. */
|
|
103
|
+
optional: z.boolean().default(false),
|
|
104
|
+
/** A narrower form the format requires of its key. */
|
|
105
|
+
shape: z.enum(KEY_SHAPE_NAMES).optional(),
|
|
106
|
+
})
|
|
107
|
+
.strict(),
|
|
108
|
+
]),
|
|
109
|
+
/** Where each term sits, as a dotted body path or `:routeParameter`. */
|
|
110
|
+
fields: z.partialRecord(termName, bodyPath),
|
|
111
|
+
/** Terms a format splits over several fields, joined in this order. */
|
|
112
|
+
joined: z
|
|
113
|
+
.partialRecord(termName, z.array(bodyPath).min(2).max(4))
|
|
114
|
+
.default({}),
|
|
115
|
+
/** What a mapped term means when the request leaves it out. */
|
|
116
|
+
defaults: z.partialRecord(termName, idSchema).default({}),
|
|
117
|
+
/** Amount, in major units, that a request leaving it out means. */
|
|
118
|
+
amountDefault: z
|
|
119
|
+
.string()
|
|
120
|
+
.regex(/^[0-9]+(\.[0-9]+)?$/)
|
|
121
|
+
.optional(),
|
|
122
|
+
/** A second amount field, which also says what the amount is counted in. */
|
|
123
|
+
alternateAmount: z
|
|
124
|
+
.object({ path: bodyPath, currency: bodyPath })
|
|
125
|
+
.strict()
|
|
126
|
+
.optional(),
|
|
127
|
+
/** Values an amount counts as, such as a stablecoin as its pegged fiat. */
|
|
128
|
+
pegged: z.partialRecord(termName, z.record(idSchema, idSchema)).default({}),
|
|
129
|
+
/** Terms the provider's format does not carry, declared once. */
|
|
130
|
+
fixed: z.partialRecord(termName, idSchema),
|
|
131
|
+
/** Terms sent as a URL, with the path their identifier must sit under. */
|
|
132
|
+
urlFields: z.partialRecord(termName, z.string().min(1).max(64)).default({}),
|
|
133
|
+
/** Arrays that must hold exactly one entry, as only that entry is read. */
|
|
134
|
+
singleEntry: z.array(bodyPath).max(4).default([]),
|
|
135
|
+
amount: z
|
|
136
|
+
.union([
|
|
137
|
+
z.object({ minorDigits: digitsSchema }).strict(),
|
|
138
|
+
z
|
|
139
|
+
.object({
|
|
140
|
+
/** The term naming the asset, whose scale the amount is read at. */
|
|
141
|
+
scaleTerm: termName,
|
|
142
|
+
/** Every supported asset: any other is refused, never assumed. */
|
|
143
|
+
scales: z.record(idSchema, digitsSchema),
|
|
144
|
+
/** The networks each asset may sit on; any other is refused. */
|
|
145
|
+
networks: z.record(idSchema, z.array(idSchema).min(1)).optional(),
|
|
146
|
+
/** Each token's contract by `asset@network`; native has none. */
|
|
147
|
+
contracts: z.record(contractKey, addressSchema).default({}),
|
|
148
|
+
/** Networks whose destinations are EVM addresses. */
|
|
149
|
+
evmNetworks: z.array(idSchema).default([]),
|
|
150
|
+
})
|
|
151
|
+
.strict(),
|
|
152
|
+
])
|
|
153
|
+
.default({ minorDigits: 0 }),
|
|
154
|
+
/** How a repeat of a settled key is answered; it never adds an effect. */
|
|
155
|
+
replay: z.enum(WIRE_REPLAYS).default("same_reply"),
|
|
156
|
+
/** Whether a declined key may be tried again. */
|
|
157
|
+
refusals: z.enum(REFUSAL_REPLAYS).default("retryable"),
|
|
158
|
+
replies: z
|
|
159
|
+
.object({
|
|
160
|
+
paid: replySchema,
|
|
161
|
+
declined: replySchema,
|
|
162
|
+
conflict: replySchema,
|
|
163
|
+
duplicate: replySchema.optional(),
|
|
164
|
+
})
|
|
165
|
+
.strict(),
|
|
166
|
+
/**
|
|
167
|
+
* Stripe Connect's setup and payout calls around a transfer to a
|
|
168
|
+
* connected account; `src/connect.ts` serves them.
|
|
169
|
+
*/
|
|
170
|
+
connect: z
|
|
171
|
+
.object({
|
|
172
|
+
accounts: routeSchema,
|
|
173
|
+
externalAccounts: routeSchema.refine((path) =>
|
|
174
|
+
path.includes(":accountId"),
|
|
175
|
+
),
|
|
176
|
+
payouts: routeSchema,
|
|
177
|
+
})
|
|
178
|
+
.strict()
|
|
179
|
+
.optional(),
|
|
180
|
+
/** What the format's flow is, so each request can be placed against it. */
|
|
181
|
+
financialFlow: financialFlowSchema,
|
|
182
|
+
})
|
|
183
|
+
.strict();
|
|
184
|
+
export type DeclaredWire = z.infer<typeof declaredSchema>;
|
|
185
|
+
export type Terms = Readonly<Record<string, unknown>>;
|
|
186
|
+
|
|
187
|
+
/** Each token as written, with `:number` kept so only the amount can carry it. */
|
|
188
|
+
export function tokensIn(value: unknown): string[] {
|
|
189
|
+
if (typeof value === "string")
|
|
190
|
+
return [...value.matchAll(TOKEN)].map(
|
|
191
|
+
(found) => `${found[1] ?? ""}${found[2] ?? ""}`,
|
|
192
|
+
);
|
|
193
|
+
if (Array.isArray(value)) return value.flatMap(tokensIn);
|
|
194
|
+
if (typeof value === "object" && value !== null)
|
|
195
|
+
return Object.values(value).flatMap(tokensIn);
|
|
196
|
+
return [];
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Every path a declaration reads from the body or the route. */
|
|
200
|
+
function pathsOf(declared: DeclaredWire): string[] {
|
|
201
|
+
return [
|
|
202
|
+
...Object.values(declared.fields),
|
|
203
|
+
...Object.values(declared.joined).flat(),
|
|
204
|
+
...("field" in declared.key ? [declared.key.field] : []),
|
|
205
|
+
...(declared.alternateAmount
|
|
206
|
+
? [declared.alternateAmount.path, declared.alternateAmount.currency]
|
|
207
|
+
: []),
|
|
208
|
+
].filter((path) => path !== undefined);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** An array step outside `singleEntry` would drop the batch's other entries. */
|
|
212
|
+
function requireDeclaredEntries(declared: DeclaredWire): void {
|
|
213
|
+
if (declared.encoding === "form") return;
|
|
214
|
+
for (const path of pathsOf(declared)) {
|
|
215
|
+
const steps = path.split(".");
|
|
216
|
+
steps.forEach((step, index) => {
|
|
217
|
+
const array = steps.slice(0, index).join(".");
|
|
218
|
+
if (ARRAY_STEP.test(step) && !declared.singleEntry.includes(array))
|
|
219
|
+
throw new Error(`${path} reads an undeclared array`);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function requireRouteParameters(declared: DeclaredWire): void {
|
|
225
|
+
const routeSteps = declared.path.split("/");
|
|
226
|
+
for (const path of pathsOf(declared)) {
|
|
227
|
+
if (path.startsWith(ROUTE_PARAMETER) && !routeSteps.includes(path))
|
|
228
|
+
throw new Error(`${path} is not in the route`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function requireReplyTokens(declared: DeclaredWire): void {
|
|
233
|
+
const { paid, duplicate, declined, conflict } = declared.replies;
|
|
234
|
+
const words = (reply: DeclaredReply | undefined) =>
|
|
235
|
+
reply ? tokensIn([reply.body, reply.headers]) : [];
|
|
236
|
+
const unknown = [
|
|
237
|
+
...[paid, duplicate]
|
|
238
|
+
.flatMap(words)
|
|
239
|
+
.filter((name) => !EFFECT_TOKENS.has(name)),
|
|
240
|
+
...[declined, conflict]
|
|
241
|
+
.flatMap(words)
|
|
242
|
+
.filter((name) => !REFUSAL_TOKENS.has(name)),
|
|
243
|
+
];
|
|
244
|
+
if (unknown.length > 0)
|
|
245
|
+
throw new Error(`unknown tokens: ${unknown.join(", ")}`);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Refuses a declaration whose terms or replies could not be honoured. */
|
|
249
|
+
export function validated(declaration: unknown): DeclaredWire {
|
|
250
|
+
const declared = declaredSchema.parse(declaration);
|
|
251
|
+
const unmapped = TERM_NAMES.filter((name) => {
|
|
252
|
+
const sources = [declared.fields, declared.joined, declared.fixed].filter(
|
|
253
|
+
(source) => name in source,
|
|
254
|
+
).length;
|
|
255
|
+
// The payment may have no source: it then takes the key.
|
|
256
|
+
return sources !== 1 && !(sources === 0 && name === "payment");
|
|
257
|
+
});
|
|
258
|
+
if (unmapped.length > 0)
|
|
259
|
+
throw new Error(`each term needs one source: ${unmapped.join(", ")}`);
|
|
260
|
+
if (!("amount" in declared.fields))
|
|
261
|
+
throw new Error("the amount must be read from the request");
|
|
262
|
+
if (Object.keys(declared.defaults).some((name) => !(name in declared.fields)))
|
|
263
|
+
throw new Error("a default needs a mapped field");
|
|
264
|
+
if (declared.replay === "duplicate_reply" && !declared.replies.duplicate)
|
|
265
|
+
throw new Error("duplicate_reply needs a duplicate reply");
|
|
266
|
+
requireDeclaredEntries(declared);
|
|
267
|
+
requireRouteParameters(declared);
|
|
268
|
+
requireReplyTokens(declared);
|
|
269
|
+
return declared;
|
|
270
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { getAddress, isAddress } from "viem";
|
|
2
|
+
import { majorUnits, minorUnits } from "./amount.js";
|
|
3
|
+
import { requireBasicPassword } from "./auth.js";
|
|
4
|
+
import {
|
|
5
|
+
AMOUNT_NUMBER,
|
|
6
|
+
AMOUNT_NUMBER_TOKEN,
|
|
7
|
+
tokensIn,
|
|
8
|
+
TOKEN,
|
|
9
|
+
validated,
|
|
10
|
+
} from "./declaration.js";
|
|
11
|
+
import type {
|
|
12
|
+
DeclaredReply,
|
|
13
|
+
DeclaredWire,
|
|
14
|
+
ReplyValues,
|
|
15
|
+
} from "./declaration.js";
|
|
16
|
+
import { instructionSchema, ProviderError, recordKey } from "./domain.js";
|
|
17
|
+
import type { Instruction } from "./domain.js";
|
|
18
|
+
import {
|
|
19
|
+
keyOf,
|
|
20
|
+
recordedDigits,
|
|
21
|
+
requireShape,
|
|
22
|
+
statedAmount,
|
|
23
|
+
statedTerms,
|
|
24
|
+
} from "./request.js";
|
|
25
|
+
import { connectWire } from "./connect.js";
|
|
26
|
+
import { signedJwtAuthenticator } from "./signature.js";
|
|
27
|
+
import { staticCredential } from "./wire.js";
|
|
28
|
+
import type { PaymentWire, RequestAuthenticator, WireReply } from "./wire.js";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Fills `{{term}}` tokens; a value that is exactly `{{amount:number}}` becomes
|
|
32
|
+
* a number, which `read` has already shown a number can hold.
|
|
33
|
+
*/
|
|
34
|
+
function fill(template: unknown, values: ReplyValues): unknown {
|
|
35
|
+
if (typeof template === "string") {
|
|
36
|
+
if (template === AMOUNT_NUMBER) return Number(values["amount"]);
|
|
37
|
+
return template.replace(
|
|
38
|
+
TOKEN,
|
|
39
|
+
(_token, name: string) => values[name] ?? "",
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
if (Array.isArray(template))
|
|
43
|
+
return template.map((entry: unknown) => fill(entry, values));
|
|
44
|
+
if (typeof template === "object" && template !== null)
|
|
45
|
+
return Object.fromEntries(
|
|
46
|
+
Object.entries(template).map(([name, entry]) => [
|
|
47
|
+
name,
|
|
48
|
+
fill(entry, values),
|
|
49
|
+
]),
|
|
50
|
+
);
|
|
51
|
+
return template;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function requireNetwork(
|
|
55
|
+
amount: DeclaredWire["amount"],
|
|
56
|
+
{ asset, network }: Instruction,
|
|
57
|
+
): void {
|
|
58
|
+
if ("minorDigits" in amount || !amount.networks) return;
|
|
59
|
+
const allowed = Object.hasOwn(amount.networks, asset)
|
|
60
|
+
? amount.networks[asset]
|
|
61
|
+
: undefined;
|
|
62
|
+
if (!allowed?.includes(network))
|
|
63
|
+
throw new ProviderError(400, "unsupported_network");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The checksum form of an EVM destination; other networks keep theirs. */
|
|
67
|
+
function destinationOn(
|
|
68
|
+
amount: DeclaredWire["amount"],
|
|
69
|
+
{ destination, network }: Instruction,
|
|
70
|
+
): string {
|
|
71
|
+
if ("minorDigits" in amount || !amount.evmNetworks.includes(network))
|
|
72
|
+
return destination;
|
|
73
|
+
if (!isAddress(destination))
|
|
74
|
+
throw new ProviderError(400, "invalid_destination");
|
|
75
|
+
return getAddress(destination);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function credentialCheck(
|
|
79
|
+
credential: DeclaredWire["credential"],
|
|
80
|
+
token: string,
|
|
81
|
+
): RequestAuthenticator {
|
|
82
|
+
if ("signedJwt" in credential)
|
|
83
|
+
return signedJwtAuthenticator({
|
|
84
|
+
token,
|
|
85
|
+
maxAgeSeconds: credential.maxAgeSeconds,
|
|
86
|
+
});
|
|
87
|
+
if ("basic" in credential)
|
|
88
|
+
return {
|
|
89
|
+
needsBody: false,
|
|
90
|
+
authenticate: ({ headers }) => {
|
|
91
|
+
requireBasicPassword(headers["authorization"], token);
|
|
92
|
+
},
|
|
93
|
+
reset: () => undefined,
|
|
94
|
+
};
|
|
95
|
+
return staticCredential(credential.header, credential.prefix, token);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Renders each outcome of a declaration; neither can fail once `read` passed. */
|
|
99
|
+
type ReplyWriter = Readonly<{
|
|
100
|
+
replyTerms: (instruction: Instruction, key: string) => ReplyValues;
|
|
101
|
+
answer: (reply: DeclaredReply, values: ReplyValues) => WireReply;
|
|
102
|
+
}>;
|
|
103
|
+
|
|
104
|
+
function replyWriter(declared: DeclaredWire): ReplyWriter {
|
|
105
|
+
const replyTerms = (instruction: Instruction, key: string) => ({
|
|
106
|
+
...instruction,
|
|
107
|
+
key,
|
|
108
|
+
amountMajor: majorUnits(
|
|
109
|
+
instruction.amount,
|
|
110
|
+
recordedDigits(declared, instruction),
|
|
111
|
+
),
|
|
112
|
+
});
|
|
113
|
+
const answer = (reply: DeclaredReply, values: ReplyValues): WireReply => ({
|
|
114
|
+
status: reply.status,
|
|
115
|
+
body: fill(reply.body, values),
|
|
116
|
+
headers: Object.fromEntries(
|
|
117
|
+
Object.entries(reply.headers).map(([name, value]) => [
|
|
118
|
+
name,
|
|
119
|
+
String(fill(value, values)),
|
|
120
|
+
]),
|
|
121
|
+
),
|
|
122
|
+
});
|
|
123
|
+
return { answer, replyTerms };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Builds a wire from a declaration, which is untrusted until validated. */
|
|
127
|
+
export function declaredWire(declaration: unknown, token: string): PaymentWire {
|
|
128
|
+
const declared = validated(declaration);
|
|
129
|
+
const authenticator = credentialCheck(declared.credential, token);
|
|
130
|
+
const { answer, replyTerms } = replyWriter(declared);
|
|
131
|
+
const numericReplies = Object.values(declared.replies).some(
|
|
132
|
+
(reply) =>
|
|
133
|
+
reply !== undefined &&
|
|
134
|
+
tokensIn([reply.body, reply.headers]).includes(AMOUNT_NUMBER_TOKEN),
|
|
135
|
+
);
|
|
136
|
+
const wire: PaymentWire = {
|
|
137
|
+
preparatory: [],
|
|
138
|
+
reset: authenticator.reset,
|
|
139
|
+
path: declared.path,
|
|
140
|
+
financialFlow: declared.financialFlow,
|
|
141
|
+
form: declared.encoding === "form",
|
|
142
|
+
jsonType: declared.jsonType,
|
|
143
|
+
authenticator,
|
|
144
|
+
refusals: declared.refusals,
|
|
145
|
+
read: (headers, body, params) => {
|
|
146
|
+
const request = { declared, body, params };
|
|
147
|
+
requireShape(request);
|
|
148
|
+
const sentKey = keyOf(request, headers);
|
|
149
|
+
const key = recordKey(sentKey);
|
|
150
|
+
const { written, terms, digits } = statedAmount(request, {
|
|
151
|
+
...declared.fixed,
|
|
152
|
+
...statedTerms(request),
|
|
153
|
+
});
|
|
154
|
+
const parsed = instructionSchema.parse({
|
|
155
|
+
payment: key,
|
|
156
|
+
...terms,
|
|
157
|
+
amount: minorUnits(written, digits),
|
|
158
|
+
});
|
|
159
|
+
requireNetwork(declared.amount, parsed);
|
|
160
|
+
const instruction = {
|
|
161
|
+
...parsed,
|
|
162
|
+
destination: destinationOn(declared.amount, parsed),
|
|
163
|
+
};
|
|
164
|
+
if (
|
|
165
|
+
numericReplies &&
|
|
166
|
+
BigInt(instruction.amount) > BigInt(Number.MAX_SAFE_INTEGER)
|
|
167
|
+
)
|
|
168
|
+
throw new ProviderError(400, "invalid_amount");
|
|
169
|
+
return {
|
|
170
|
+
key,
|
|
171
|
+
sentKey,
|
|
172
|
+
paymentFromKey: terms["payment"] === undefined,
|
|
173
|
+
instruction,
|
|
174
|
+
};
|
|
175
|
+
},
|
|
176
|
+
paid: (effect, created, sentKey) => {
|
|
177
|
+
const reply =
|
|
178
|
+
!created && declared.replay === "duplicate_reply"
|
|
179
|
+
? declared.replies.duplicate
|
|
180
|
+
: declared.replies.paid;
|
|
181
|
+
return answer(reply ?? declared.replies.paid, {
|
|
182
|
+
...replyTerms(effect.instruction, sentKey ?? effect.key),
|
|
183
|
+
effectId: effect.effectId,
|
|
184
|
+
});
|
|
185
|
+
},
|
|
186
|
+
declined: ({ instruction, key, sentKey }) =>
|
|
187
|
+
answer(
|
|
188
|
+
declared.replies.declined,
|
|
189
|
+
replyTerms(instruction, sentKey ?? key),
|
|
190
|
+
),
|
|
191
|
+
conflict: ({ instruction, key, sentKey }) =>
|
|
192
|
+
answer(
|
|
193
|
+
declared.replies.conflict,
|
|
194
|
+
replyTerms(instruction, sentKey ?? key),
|
|
195
|
+
),
|
|
196
|
+
};
|
|
197
|
+
return declared.connect ? connectWire(wire, declared.connect) : wire;
|
|
198
|
+
}
|