@ocap/mpc-hsm 1.33.6 → 1.33.7
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/esm/bip39-english-wordlist.d.mts +11 -0
- package/esm/bip39-english-wordlist.mjs +31 -0
- package/esm/constants.d.mts +66 -2
- package/esm/constants.mjs +65 -1
- package/esm/dkg.mjs +2 -2
- package/esm/index.d.mts +11 -3
- package/esm/index.mjs +11 -3
- package/esm/ocap-clear-signing.d.mts +125 -0
- package/esm/ocap-clear-signing.mjs +1170 -0
- package/esm/offline-ceremony.d.mts +127 -0
- package/esm/offline-ceremony.mjs +481 -0
- package/esm/ot.d.mts +7 -1
- package/esm/ot.mjs +149 -16
- package/esm/personal-vault.d.mts +1292 -0
- package/esm/personal-vault.mjs +3615 -0
- package/esm/personal.d.mts +10 -0
- package/esm/personal.mjs +11 -0
- package/esm/presign.mjs +1 -1
- package/esm/rlp-eip1559.d.mts +75 -0
- package/esm/rlp-eip1559.mjs +293 -0
- package/esm/secp256k1-scalar.d.mts +1 -1
- package/esm/secp256k1-scalar.mjs +14 -5
- package/esm/steel-mnemonic.d.mts +55 -0
- package/esm/steel-mnemonic.mjs +247 -0
- package/esm/ves-backup.d.mts +296 -0
- package/esm/ves-backup.mjs +1025 -0
- package/esm/x402-agent-guard.d.mts +111 -0
- package/esm/x402-agent-guard.mjs +780 -0
- package/lib/bip39-english-wordlist.cjs +33 -0
- package/lib/bip39-english-wordlist.d.cts +11 -0
- package/lib/constants.cjs +128 -0
- package/lib/constants.d.cts +66 -2
- package/lib/dkg.cjs +2 -2
- package/lib/index.cjs +249 -0
- package/lib/index.d.cts +11 -3
- package/lib/ocap-clear-signing.cjs +1176 -0
- package/lib/ocap-clear-signing.d.cts +125 -0
- package/lib/offline-ceremony.cjs +487 -0
- package/lib/offline-ceremony.d.cts +127 -0
- package/lib/ot.cjs +150 -15
- package/lib/ot.d.cts +7 -1
- package/lib/personal-vault.cjs +3725 -0
- package/lib/personal-vault.d.cts +1292 -0
- package/lib/personal.cjs +338 -0
- package/lib/personal.d.cts +10 -0
- package/lib/presign.cjs +1 -1
- package/lib/rlp-eip1559.cjs +303 -0
- package/lib/rlp-eip1559.d.cts +75 -0
- package/lib/secp256k1-scalar.cjs +14 -5
- package/lib/steel-mnemonic.cjs +253 -0
- package/lib/steel-mnemonic.d.cts +55 -0
- package/lib/ves-backup.cjs +1053 -0
- package/lib/ves-backup.d.cts +296 -0
- package/lib/x402-agent-guard.cjs +788 -0
- package/lib/x402-agent-guard.d.cts +111 -0
- package/package.json +6 -1
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
const require_constants = require('./constants.cjs');
|
|
2
|
+
const require_secp256k1_scalar = require('./secp256k1-scalar.cjs');
|
|
3
|
+
const require_tweak = require('./tweak.cjs');
|
|
4
|
+
const require_rlp_eip1559 = require('./rlp-eip1559.cjs');
|
|
5
|
+
const require_personal_vault = require('./personal-vault.cjs');
|
|
6
|
+
|
|
7
|
+
//#region src/x402-agent-guard.ts
|
|
8
|
+
const MAX_X402_CHALLENGE_BYTES = 16384;
|
|
9
|
+
const MAX_X402_ACCEPTS_ENTRIES = 16;
|
|
10
|
+
const MAX_X402_RETRIES = 1;
|
|
11
|
+
const X402_PROTOCOL_VERSION = 1;
|
|
12
|
+
const X402_EXACT_EVM_TX_SCHEME = "exact-evm-tx";
|
|
13
|
+
const MAX_UINT64 = (1n << 64n) - 1n;
|
|
14
|
+
const MAX_UINT256 = (1n << 256n) - 1n;
|
|
15
|
+
const MAX_X402_TEXT_FIELD_CHARS = 2048;
|
|
16
|
+
const strictUtf8Decoder = new TextDecoder("utf-8", { fatal: true });
|
|
17
|
+
const FORBIDDEN_PROTOTYPE_KEYS = new Set([
|
|
18
|
+
"__proto__",
|
|
19
|
+
"constructor",
|
|
20
|
+
"prototype"
|
|
21
|
+
]);
|
|
22
|
+
const ALLOWED_X402_SCHEMES = new Set([
|
|
23
|
+
"exact",
|
|
24
|
+
"exact-evm",
|
|
25
|
+
"exact-evm-tx"
|
|
26
|
+
]);
|
|
27
|
+
const KNOWN_X402_NETWORK_CHAIN_IDS = {
|
|
28
|
+
ethereum: 1n,
|
|
29
|
+
"ethereum-mainnet": 1n,
|
|
30
|
+
mainnet: 1n,
|
|
31
|
+
sepolia: 11155111n,
|
|
32
|
+
"ethereum-sepolia": 11155111n,
|
|
33
|
+
base: 8453n,
|
|
34
|
+
"base-mainnet": 8453n,
|
|
35
|
+
"base-sepolia": 84532n,
|
|
36
|
+
optimism: 10n,
|
|
37
|
+
"optimism-mainnet": 10n,
|
|
38
|
+
arbitrum: 42161n,
|
|
39
|
+
"arbitrum-one": 42161n,
|
|
40
|
+
polygon: 137n,
|
|
41
|
+
"polygon-mainnet": 137n
|
|
42
|
+
};
|
|
43
|
+
function decodeStrictUtf8(bytes) {
|
|
44
|
+
try {
|
|
45
|
+
return strictUtf8Decoder.decode(bytes);
|
|
46
|
+
} catch {
|
|
47
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid UTF-8 byte sequence in x402 challenge");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const STD_BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
51
|
+
const URL_BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
52
|
+
function buildAlphabetLookup(alphabet) {
|
|
53
|
+
const table = new Int16Array(128).fill(-1);
|
|
54
|
+
for (let i = 0; i < alphabet.length; i++) table[alphabet.charCodeAt(i)] = i;
|
|
55
|
+
return table;
|
|
56
|
+
}
|
|
57
|
+
const STD_B64_LOOKUP = buildAlphabetLookup(STD_BASE64_ALPHABET);
|
|
58
|
+
const URL_B64_LOOKUP = buildAlphabetLookup(URL_BASE64_ALPHABET);
|
|
59
|
+
function decodeStrictBase64OrBase64UrlBytes(encoded) {
|
|
60
|
+
if (typeof encoded !== "string" || encoded.length === 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Empty x402 base64 header");
|
|
61
|
+
const hasStdChars = encoded.includes("+") || encoded.includes("/");
|
|
62
|
+
const hasUrlChars = encoded.includes("-") || encoded.includes("_");
|
|
63
|
+
if (hasStdChars && hasUrlChars) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Mixed base64 and base64url alphabet in x402 header");
|
|
64
|
+
let padCount = 0;
|
|
65
|
+
if (encoded.endsWith("==")) padCount = 2;
|
|
66
|
+
else if (encoded.endsWith("=")) padCount = 1;
|
|
67
|
+
if (padCount > 0 && encoded.length % 4 !== 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid base64 padding length in x402 header");
|
|
68
|
+
const body = padCount > 0 ? encoded.slice(0, encoded.length - padCount) : encoded;
|
|
69
|
+
const len = body.length;
|
|
70
|
+
if (len === 0 || len % 4 === 1) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Malformed base64 length in x402 header");
|
|
71
|
+
if (hasStdChars && padCount === 0 && len % 4 !== 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Unpadded standard base64 length invalid in x402 header");
|
|
72
|
+
const lookup = hasUrlChars ? URL_B64_LOOKUP : STD_B64_LOOKUP;
|
|
73
|
+
const vals = new Uint8Array(len);
|
|
74
|
+
for (let i$1 = 0; i$1 < len; i$1++) {
|
|
75
|
+
const code = body.charCodeAt(i$1);
|
|
76
|
+
const sextet = code < 128 ? lookup[code] : -1;
|
|
77
|
+
if (sextet < 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid base64 character in x402 header");
|
|
78
|
+
vals[i$1] = sextet;
|
|
79
|
+
}
|
|
80
|
+
const rem = len % 4;
|
|
81
|
+
if (padCount === 1 && rem !== 3) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Mismatched single \"=\" padding in x402 header");
|
|
82
|
+
if (padCount === 2 && rem !== 2) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Mismatched double \"==\" padding in x402 header");
|
|
83
|
+
if (rem === 2 && (vals[len - 1] & 15) !== 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Non-canonical trailing bits in x402 base64 header");
|
|
84
|
+
if (rem === 3 && (vals[len - 1] & 3) !== 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Non-canonical trailing bits in x402 base64 header");
|
|
85
|
+
const outLen = Math.floor(len * 3 / 4);
|
|
86
|
+
if (outLen === 0 || outLen > MAX_X402_CHALLENGE_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Decoded x402 header length (${outLen}B) out of bounds 1..${MAX_X402_CHALLENGE_BYTES}B`);
|
|
87
|
+
const out = new Uint8Array(outLen);
|
|
88
|
+
let outIdx = 0;
|
|
89
|
+
let i = 0;
|
|
90
|
+
for (; i + 3 < len; i += 4) {
|
|
91
|
+
const n = vals[i] << 18 | vals[i + 1] << 12 | vals[i + 2] << 6 | vals[i + 3];
|
|
92
|
+
out[outIdx++] = n >>> 16 & 255;
|
|
93
|
+
out[outIdx++] = n >>> 8 & 255;
|
|
94
|
+
out[outIdx++] = n & 255;
|
|
95
|
+
}
|
|
96
|
+
if (rem === 2) out[outIdx++] = (vals[i] << 2 | vals[i + 1] >>> 4) & 255;
|
|
97
|
+
else if (rem === 3) {
|
|
98
|
+
const n = vals[i] << 10 | vals[i + 1] << 4 | vals[i + 2] >>> 2;
|
|
99
|
+
out[outIdx++] = n >>> 8 & 255;
|
|
100
|
+
out[outIdx++] = n & 255;
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
function assertBoundedJsonNestingDepth(jsonText, maxDepth) {
|
|
105
|
+
let depth = 0;
|
|
106
|
+
let inString = false;
|
|
107
|
+
let escaped = false;
|
|
108
|
+
for (let i = 0; i < jsonText.length; i++) {
|
|
109
|
+
const ch = jsonText.charCodeAt(i);
|
|
110
|
+
if (inString) {
|
|
111
|
+
if (escaped) escaped = false;
|
|
112
|
+
else if (ch === 92) escaped = true;
|
|
113
|
+
else if (ch === 34) inString = false;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (ch === 34) inString = true;
|
|
117
|
+
else if (ch === 123 || ch === 91) {
|
|
118
|
+
depth += 1;
|
|
119
|
+
if (depth > maxDepth) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 JSON nesting depth exceeds MAX_PERSONAL_JSON_DEPTH (${maxDepth})`);
|
|
120
|
+
} else if (ch === 125 || ch === 93) {
|
|
121
|
+
depth -= 1;
|
|
122
|
+
if (depth < 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Malformed bracket nesting in x402 JSON");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function sanitizeJsonValueNoProto(value) {
|
|
127
|
+
if (value === null || typeof value !== "object") return value;
|
|
128
|
+
if (Array.isArray(value)) return value.map((item) => sanitizeJsonValueNoProto(item));
|
|
129
|
+
const ownNames = Object.getOwnPropertyNames(value);
|
|
130
|
+
const cleanObj = Object.create(null);
|
|
131
|
+
for (const key of ownNames) {
|
|
132
|
+
if (FORBIDDEN_PROTOTYPE_KEYS.has(key)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Forbidden prototype-pollution property "${key}" in x402 JSON`);
|
|
133
|
+
cleanObj[key] = sanitizeJsonValueNoProto(value[key]);
|
|
134
|
+
}
|
|
135
|
+
return cleanObj;
|
|
136
|
+
}
|
|
137
|
+
function parseSafeBoundedJsonObject(jsonText, maxBytes = MAX_X402_CHALLENGE_BYTES) {
|
|
138
|
+
const rawBytes = require_secp256k1_scalar.utf8Bytes(jsonText);
|
|
139
|
+
if (rawBytes.length === 0 || rawBytes.length > maxBytes) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 payload length (${rawBytes.length}B) out of bounds 1..${maxBytes}B`);
|
|
140
|
+
assertBoundedJsonNestingDepth(jsonText, require_constants.MAX_PERSONAL_JSON_DEPTH);
|
|
141
|
+
let parsed;
|
|
142
|
+
try {
|
|
143
|
+
parsed = JSON.parse(jsonText, (key, val) => {
|
|
144
|
+
if (FORBIDDEN_PROTOTYPE_KEYS.has(key)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Forbidden prototype-pollution key "${key}" in x402 JSON`);
|
|
145
|
+
return val;
|
|
146
|
+
});
|
|
147
|
+
} catch (err) {
|
|
148
|
+
if (err instanceof require_constants.MpcProtocolError) throw err;
|
|
149
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid JSON in x402 payment challenge");
|
|
150
|
+
}
|
|
151
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 payment challenge must be a JSON object");
|
|
152
|
+
return sanitizeJsonValueNoProto(parsed);
|
|
153
|
+
}
|
|
154
|
+
function parsePositiveBigIntStrict(val, max, label) {
|
|
155
|
+
let out;
|
|
156
|
+
if (typeof val === "bigint") out = val;
|
|
157
|
+
else if (typeof val === "number") {
|
|
158
|
+
if (!Number.isSafeInteger(val) || val < 1) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} must be a positive integer`);
|
|
159
|
+
out = BigInt(val);
|
|
160
|
+
} else if (typeof val === "string" && /^[1-9][0-9]*$/.test(val)) out = BigInt(val);
|
|
161
|
+
else throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} must be a positive canonical integer`);
|
|
162
|
+
if (out < 1n || out > max) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} exceeds valid positive range`);
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
function parseChainIdFlexible(val, label) {
|
|
166
|
+
if (typeof val === "bigint") {
|
|
167
|
+
if (val < 1n || val > MAX_UINT64) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} out of uint64 range`);
|
|
168
|
+
return val;
|
|
169
|
+
}
|
|
170
|
+
if (typeof val === "number") {
|
|
171
|
+
if (!Number.isSafeInteger(val) || val < 1) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid ${label}`);
|
|
172
|
+
return BigInt(val);
|
|
173
|
+
}
|
|
174
|
+
if (typeof val === "string") {
|
|
175
|
+
if (/^[1-9][0-9]*$/.test(val)) {
|
|
176
|
+
const parsed = BigInt(val);
|
|
177
|
+
if (parsed < 1n || parsed > MAX_UINT64) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} out of uint64 range`);
|
|
178
|
+
return parsed;
|
|
179
|
+
}
|
|
180
|
+
if (/^0x[1-9a-fA-F][0-9a-fA-F]*$/.test(val)) {
|
|
181
|
+
const parsed = BigInt(val);
|
|
182
|
+
if (parsed < 1n || parsed > MAX_UINT64) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} out of uint64 range`);
|
|
183
|
+
return parsed;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid ${label}: ${String(val)}`);
|
|
187
|
+
}
|
|
188
|
+
function parseNetworkIdentifierToChainId(networkRaw) {
|
|
189
|
+
const trimmed = networkRaw.trim();
|
|
190
|
+
if (trimmed.length === 0 || trimmed.length > 64) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid x402 network identifier");
|
|
191
|
+
const lower = trimmed.toLowerCase();
|
|
192
|
+
if (lower.startsWith("eip155:")) {
|
|
193
|
+
const suffix = lower.slice(7);
|
|
194
|
+
if (!/^[1-9][0-9]*$/.test(suffix)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid CAIP-2 network "${trimmed}"`);
|
|
195
|
+
const cid = BigInt(suffix);
|
|
196
|
+
if (cid < 1n || cid > MAX_UINT64) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `CAIP-2 chainId out of range in "${trimmed}"`);
|
|
197
|
+
return cid;
|
|
198
|
+
}
|
|
199
|
+
if (/^[1-9][0-9]*$/.test(lower)) {
|
|
200
|
+
const cid = BigInt(lower);
|
|
201
|
+
if (cid < 1n || cid > MAX_UINT64) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `ChainId out of range in "${trimmed}"`);
|
|
202
|
+
return cid;
|
|
203
|
+
}
|
|
204
|
+
const known = KNOWN_X402_NETWORK_CHAIN_IDS[lower];
|
|
205
|
+
if (known !== void 0) return known;
|
|
206
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Unsupported x402 network "${trimmed}"`);
|
|
207
|
+
}
|
|
208
|
+
function validateOptionalCleanString(val, label) {
|
|
209
|
+
if (val === void 0 || val === null) return;
|
|
210
|
+
if (typeof val !== "string" || val.length > MAX_X402_TEXT_FIELD_CHARS) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid or oversized x402 ${label}`);
|
|
211
|
+
for (let i = 0; i < val.length; i++) {
|
|
212
|
+
const c = val.charCodeAt(i);
|
|
213
|
+
if (c < 32 && c !== 9 && c !== 10) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Control character forbidden in x402 ${label}`);
|
|
214
|
+
}
|
|
215
|
+
return val;
|
|
216
|
+
}
|
|
217
|
+
function assertNoEip7702OrApproveTricks(entry, root) {
|
|
218
|
+
for (const obj of [root, entry]) {
|
|
219
|
+
if (obj.authorizationList !== void 0 || obj.eip7702 !== void 0 || obj.setCode !== void 0 || obj.txType === 4 || obj.txType === "0x4" || obj.txType === "0x04" || obj.type === 4 || obj.type === "0x4" || obj.type === "0x04") throw new require_constants.MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", "EIP-7702 fields are forbidden in x402 challenges");
|
|
220
|
+
for (const rawField of [
|
|
221
|
+
obj.rawTx,
|
|
222
|
+
obj.txBytes,
|
|
223
|
+
obj.payload,
|
|
224
|
+
obj.unsignedTx,
|
|
225
|
+
obj.data,
|
|
226
|
+
obj.calldata,
|
|
227
|
+
obj.callData
|
|
228
|
+
]) {
|
|
229
|
+
if (typeof rawField === "string" && rawField.length > 0 && rawField !== "0x") {
|
|
230
|
+
const normalized = rawField.startsWith("0x") ? rawField.slice(2).toLowerCase() : rawField.toLowerCase();
|
|
231
|
+
if (normalized.startsWith("04") || normalized.startsWith("05")) throw new require_constants.MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", "EIP-7702 0x04/0x05 payload prefix forbidden in x402 challenge");
|
|
232
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Arbitrary calldata / approve payloads are forbidden in x402 challenges");
|
|
233
|
+
}
|
|
234
|
+
if (rawField !== void 0 && rawField !== "0x" && rawField !== "") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Arbitrary calldata fields are forbidden in x402 challenges");
|
|
235
|
+
}
|
|
236
|
+
if (obj.spender !== void 0 || obj.allowance !== void 0 || obj.approve !== void 0 || obj.permit !== void 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "ERC-20 approve/allowance/permit tricks are forbidden in x402 challenges");
|
|
237
|
+
for (const methodField of [
|
|
238
|
+
obj.method,
|
|
239
|
+
obj.function,
|
|
240
|
+
obj.action,
|
|
241
|
+
obj.callKind,
|
|
242
|
+
obj.selector
|
|
243
|
+
]) if (typeof methodField === "string") {
|
|
244
|
+
const lower = methodField.toLowerCase();
|
|
245
|
+
if (lower.includes("approve") || lower.includes("permit") || lower.includes("transferfrom") || lower.includes("multicall") || lower.includes("execute") || lower === "0x095ea7b3" || lower === "0x23b872dd" || lower === "0xac9650d8") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Forbidden method/selector "${methodField}" in x402 challenge`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function parseSingleX402Requirement(entryRaw, rootObj) {
|
|
250
|
+
if (!entryRaw || typeof entryRaw !== "object" || Array.isArray(entryRaw)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Each x402 accepts item must be an object");
|
|
251
|
+
const entry = entryRaw;
|
|
252
|
+
assertNoEip7702OrApproveTricks(entry, rootObj);
|
|
253
|
+
const schemeRaw = entry.scheme ?? "exact";
|
|
254
|
+
if (typeof schemeRaw !== "string" || schemeRaw.trim() === "") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid x402 payment scheme");
|
|
255
|
+
const scheme = schemeRaw.trim().toLowerCase();
|
|
256
|
+
if (scheme.includes("7702") || scheme === "0x04" || scheme === "setcode") throw new require_constants.MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", `Forbidden EIP-7702 scheme "${schemeRaw}" in x402`);
|
|
257
|
+
if (!ALLOWED_X402_SCHEMES.has(scheme)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Unsupported or unsafe x402 scheme "${schemeRaw}"`);
|
|
258
|
+
let chainIdFromNetwork;
|
|
259
|
+
let networkLabel;
|
|
260
|
+
if (entry.network !== void 0) {
|
|
261
|
+
if (typeof entry.network !== "string") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 network must be a string");
|
|
262
|
+
networkLabel = entry.network.trim();
|
|
263
|
+
chainIdFromNetwork = parseNetworkIdentifierToChainId(networkLabel);
|
|
264
|
+
}
|
|
265
|
+
let chainIdFromField;
|
|
266
|
+
if (entry.chainId !== void 0) chainIdFromField = parseChainIdFlexible(entry.chainId, "x402.chainId");
|
|
267
|
+
if (chainIdFromNetwork === void 0 && chainIdFromField === void 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 requirement must specify network or chainId");
|
|
268
|
+
if (chainIdFromNetwork !== void 0 && chainIdFromField !== void 0 && chainIdFromNetwork !== chainIdFromField) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Conflicting x402 network (${chainIdFromNetwork}) vs chainId (${chainIdFromField})`);
|
|
269
|
+
const chainId = chainIdFromField ?? chainIdFromNetwork;
|
|
270
|
+
const network = networkLabel ?? `eip155:${chainId.toString(10)}`;
|
|
271
|
+
const hasMaxAmount = entry.maxAmountRequired !== void 0;
|
|
272
|
+
const hasAmount = entry.amount !== void 0;
|
|
273
|
+
if (!hasMaxAmount && !hasAmount) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 requirement missing maxAmountRequired / amount");
|
|
274
|
+
const parsedMaxAmount = hasMaxAmount ? parsePositiveBigIntStrict(entry.maxAmountRequired, MAX_UINT256, "maxAmountRequired") : void 0;
|
|
275
|
+
const parsedAmount = hasAmount ? parsePositiveBigIntStrict(entry.amount, MAX_UINT256, "amount") : void 0;
|
|
276
|
+
if (parsedMaxAmount !== void 0 && parsedAmount !== void 0 && parsedMaxAmount !== parsedAmount) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Conflicting maxAmountRequired and amount in x402 requirement");
|
|
277
|
+
const amount = parsedMaxAmount ?? parsedAmount;
|
|
278
|
+
if (typeof entry.payTo !== "string") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 requirement missing payTo address");
|
|
279
|
+
const parsedPayTo = require_tweak.parseStrictEthAddress(entry.payTo);
|
|
280
|
+
const rawAsset = entry.asset;
|
|
281
|
+
const rawTokenAddr = entry.tokenAddress;
|
|
282
|
+
if (rawAsset !== void 0 && typeof rawAsset !== "string") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 asset must be a string");
|
|
283
|
+
if (rawTokenAddr !== void 0 && typeof rawTokenAddr !== "string") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 tokenAddress must be a string");
|
|
284
|
+
const isNativeString = (s) => {
|
|
285
|
+
const trimmed = s.trim().toLowerCase();
|
|
286
|
+
return trimmed === "native" || trimmed === "eth";
|
|
287
|
+
};
|
|
288
|
+
let assetKind;
|
|
289
|
+
let asset;
|
|
290
|
+
let tokenChecksumAddress;
|
|
291
|
+
if (rawTokenAddr !== void 0 && !isNativeString(rawTokenAddr)) {
|
|
292
|
+
const parsedToken = require_tweak.parseStrictEthAddress(rawTokenAddr);
|
|
293
|
+
if (rawAsset !== void 0 && !isNativeString(rawAsset)) {
|
|
294
|
+
if (require_tweak.parseStrictEthAddress(rawAsset).checksumAddress !== parsedToken.checksumAddress) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Conflicting asset and tokenAddress in x402");
|
|
295
|
+
} else if (rawAsset !== void 0 && isNativeString(rawAsset)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Conflicting native asset and ERC-20 tokenAddress");
|
|
296
|
+
assetKind = "erc20";
|
|
297
|
+
asset = parsedToken.lowercaseAddress;
|
|
298
|
+
tokenChecksumAddress = parsedToken.checksumAddress;
|
|
299
|
+
} else if (rawAsset === void 0 || isNativeString(rawAsset)) {
|
|
300
|
+
assetKind = "native";
|
|
301
|
+
asset = "native";
|
|
302
|
+
} else {
|
|
303
|
+
const parsedToken = require_tweak.parseStrictEthAddress(rawAsset);
|
|
304
|
+
assetKind = "erc20";
|
|
305
|
+
asset = parsedToken.lowercaseAddress;
|
|
306
|
+
tokenChecksumAddress = parsedToken.checksumAddress;
|
|
307
|
+
}
|
|
308
|
+
if (tokenChecksumAddress && tokenChecksumAddress === parsedPayTo.checksumAddress) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 ERC-20 payTo cannot equal the token contract address itself");
|
|
309
|
+
const resource = validateOptionalCleanString(entry.resource, "resource");
|
|
310
|
+
const description = validateOptionalCleanString(entry.description, "description");
|
|
311
|
+
return {
|
|
312
|
+
scheme,
|
|
313
|
+
chainId,
|
|
314
|
+
network,
|
|
315
|
+
amount,
|
|
316
|
+
assetKind,
|
|
317
|
+
asset,
|
|
318
|
+
...tokenChecksumAddress ? { tokenChecksumAddress } : {},
|
|
319
|
+
payToChecksumAddress: parsedPayTo.checksumAddress,
|
|
320
|
+
...resource !== void 0 ? { resource } : {},
|
|
321
|
+
...description !== void 0 ? { description } : {}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
function parseX402JsonObject(rootObj, source) {
|
|
325
|
+
const ver = rootObj.x402Version;
|
|
326
|
+
if (ver !== 1 && ver !== "1") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Unsupported x402Version: ${String(ver)}`);
|
|
327
|
+
if (!Array.isArray(rootObj.accepts) || rootObj.accepts.length === 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 accepts list must be a non-empty array");
|
|
328
|
+
if (rootObj.accepts.length > MAX_X402_ACCEPTS_ENTRIES) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 accepts list exceeds maximum length (${MAX_X402_ACCEPTS_ENTRIES})`);
|
|
329
|
+
return {
|
|
330
|
+
x402Version: 1,
|
|
331
|
+
accepts: rootObj.accepts.map((item) => parseSingleX402Requirement(item, rootObj)),
|
|
332
|
+
source
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
function decodeHeaderOrBodyTextToObject(rawText, allowBase64, source) {
|
|
336
|
+
const rawUtf8 = require_secp256k1_scalar.utf8Bytes(rawText);
|
|
337
|
+
if (rawUtf8.length === 0 || rawUtf8.length > MAX_X402_CHALLENGE_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 ${source} length (${rawUtf8.length}B) out of bounds 1..${MAX_X402_CHALLENGE_BYTES}B`);
|
|
338
|
+
const trimmed = rawText.trim();
|
|
339
|
+
if (trimmed.length === 0) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Empty x402 ${source}`);
|
|
340
|
+
if (trimmed.startsWith("{")) return parseX402JsonObject(parseSafeBoundedJsonObject(trimmed, MAX_X402_CHALLENGE_BYTES), source);
|
|
341
|
+
if (!allowBase64) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "x402 402 response body must be a JSON object");
|
|
342
|
+
const decodedJson = decodeStrictUtf8(decodeStrictBase64OrBase64UrlBytes(trimmed)).trim();
|
|
343
|
+
if (!decodedJson.startsWith("{")) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Decoded x402 base64 header must be a JSON object");
|
|
344
|
+
return parseX402JsonObject(parseSafeBoundedJsonObject(decodedJson, MAX_X402_CHALLENGE_BYTES), source);
|
|
345
|
+
}
|
|
346
|
+
function extractPaymentRequiredHeaderValue(headers) {
|
|
347
|
+
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
348
|
+
const xVal = headers.get("x-payment-required");
|
|
349
|
+
const pVal = headers.get("payment-required");
|
|
350
|
+
if (xVal !== null && pVal !== null && xVal.trim() !== pVal.trim()) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Conflicting X-Payment-Required and Payment-Required headers");
|
|
351
|
+
return xVal ?? pVal;
|
|
352
|
+
}
|
|
353
|
+
let xHeader;
|
|
354
|
+
let pHeader;
|
|
355
|
+
for (const key of Object.getOwnPropertyNames(headers)) {
|
|
356
|
+
if (FORBIDDEN_PROTOTYPE_KEYS.has(key)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Forbidden header key "${key}"`);
|
|
357
|
+
const lower = key.toLowerCase();
|
|
358
|
+
if (lower !== "x-payment-required" && lower !== "payment-required") continue;
|
|
359
|
+
const rawVal = headers[key];
|
|
360
|
+
if (rawVal === void 0) continue;
|
|
361
|
+
const strVal = Array.isArray(rawVal) ? rawVal.length === 1 && typeof rawVal[0] === "string" ? rawVal[0] : (() => {
|
|
362
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Duplicate ${key} header values forbidden`);
|
|
363
|
+
})() : typeof rawVal === "string" ? rawVal : (() => {
|
|
364
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid ${key} header value`);
|
|
365
|
+
})();
|
|
366
|
+
if (lower === "x-payment-required") xHeader = strVal;
|
|
367
|
+
else pHeader = strVal;
|
|
368
|
+
}
|
|
369
|
+
if (xHeader !== void 0 && pHeader !== void 0 && xHeader.trim() !== pHeader.trim()) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Conflicting X-Payment-Required and Payment-Required headers");
|
|
370
|
+
return xHeader ?? pHeader ?? null;
|
|
371
|
+
}
|
|
372
|
+
async function readBoundedFetchResponseText(response, maxBytes) {
|
|
373
|
+
const contentLen = response.headers.get("content-length");
|
|
374
|
+
if (contentLen !== null && /^[0-9]+$/.test(contentLen.trim())) {
|
|
375
|
+
if (Number(contentLen.trim()) > maxBytes) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 402 response Content-Length exceeds ${maxBytes}B limit`);
|
|
376
|
+
}
|
|
377
|
+
if (!response.body || typeof response.body.getReader !== "function") {
|
|
378
|
+
const text = await response.text();
|
|
379
|
+
if (require_secp256k1_scalar.utf8Bytes(text).length > maxBytes) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 402 response body exceeds ${maxBytes}B limit`);
|
|
380
|
+
return text;
|
|
381
|
+
}
|
|
382
|
+
const reader = response.body.getReader();
|
|
383
|
+
const chunks = [];
|
|
384
|
+
let total = 0;
|
|
385
|
+
try {
|
|
386
|
+
for (;;) {
|
|
387
|
+
const { done, value } = await reader.read();
|
|
388
|
+
if (done) break;
|
|
389
|
+
if (value) {
|
|
390
|
+
total += value.byteLength;
|
|
391
|
+
if (total > maxBytes) {
|
|
392
|
+
await reader.cancel().catch(() => {});
|
|
393
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 402 response body exceeds ${maxBytes}B limit`);
|
|
394
|
+
}
|
|
395
|
+
chunks.push(value);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
} finally {
|
|
399
|
+
reader.releaseLock();
|
|
400
|
+
}
|
|
401
|
+
const merged = new Uint8Array(total);
|
|
402
|
+
let offset = 0;
|
|
403
|
+
for (const chunk of chunks) {
|
|
404
|
+
merged.set(chunk, offset);
|
|
405
|
+
offset += chunk.byteLength;
|
|
406
|
+
}
|
|
407
|
+
return decodeStrictUtf8(merged);
|
|
408
|
+
}
|
|
409
|
+
function isFetchResponseInstance(val) {
|
|
410
|
+
return typeof val === "object" && val !== null && typeof val.status === "number" && typeof val.headers?.get === "function" && typeof val.text === "function";
|
|
411
|
+
}
|
|
412
|
+
function parseSyncChallengeInput(input) {
|
|
413
|
+
if (typeof input === "string") return decodeHeaderOrBodyTextToObject(input, true, "header");
|
|
414
|
+
if (input instanceof Uint8Array) {
|
|
415
|
+
if (input.length === 0 || input.length > MAX_X402_CHALLENGE_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 byte payload (${input.length}B) out of bounds 1..${MAX_X402_CHALLENGE_BYTES}B`);
|
|
416
|
+
return decodeHeaderOrBodyTextToObject(decodeStrictUtf8(input), true, "header");
|
|
417
|
+
}
|
|
418
|
+
if (typeof Headers !== "undefined" && input instanceof Headers) {
|
|
419
|
+
const hdr = extractPaymentRequiredHeaderValue(input);
|
|
420
|
+
if (hdr === null) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Missing X-Payment-Required / Payment-Required header");
|
|
421
|
+
return decodeHeaderOrBodyTextToObject(hdr, true, "header");
|
|
422
|
+
}
|
|
423
|
+
if (typeof input === "object" && input !== null) {
|
|
424
|
+
const maybeSnap = input;
|
|
425
|
+
if ("status" in maybeSnap || "headers" in maybeSnap || "body" in maybeSnap) {
|
|
426
|
+
if (maybeSnap.status !== void 0 && maybeSnap.status !== 402) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Expected HTTP 402 status for x402 challenge, got ${maybeSnap.status}`);
|
|
427
|
+
if (maybeSnap.headers) {
|
|
428
|
+
const hdr$1 = extractPaymentRequiredHeaderValue(maybeSnap.headers);
|
|
429
|
+
if (hdr$1 !== null) return decodeHeaderOrBodyTextToObject(hdr$1, true, "header");
|
|
430
|
+
}
|
|
431
|
+
if (maybeSnap.body !== void 0) return decodeHeaderOrBodyTextToObject(typeof maybeSnap.body === "string" ? maybeSnap.body : maybeSnap.body instanceof Uint8Array ? (() => {
|
|
432
|
+
if (maybeSnap.body.length > MAX_X402_CHALLENGE_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 402 body exceeds ${MAX_X402_CHALLENGE_BYTES}B`);
|
|
433
|
+
return decodeStrictUtf8(maybeSnap.body);
|
|
434
|
+
})() : (() => {
|
|
435
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid x402 response body type");
|
|
436
|
+
})(), false, "body");
|
|
437
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "HTTP 402 snapshot missing payment challenge");
|
|
438
|
+
}
|
|
439
|
+
const hdr = extractPaymentRequiredHeaderValue(input);
|
|
440
|
+
if (hdr === null) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Missing X-Payment-Required / Payment-Required header");
|
|
441
|
+
return decodeHeaderOrBodyTextToObject(hdr, true, "header");
|
|
442
|
+
}
|
|
443
|
+
throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Unsupported x402 challenge input");
|
|
444
|
+
}
|
|
445
|
+
function parseX402PaymentChallenge(responseOrHeader) {
|
|
446
|
+
if (isFetchResponseInstance(responseOrHeader)) return (async () => {
|
|
447
|
+
if (responseOrHeader.status !== 402) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Expected HTTP 402 response for x402 challenge, got ${responseOrHeader.status}`);
|
|
448
|
+
const hdr = extractPaymentRequiredHeaderValue(responseOrHeader.headers);
|
|
449
|
+
if (hdr !== null) return decodeHeaderOrBodyTextToObject(hdr, true, "header");
|
|
450
|
+
return decodeHeaderOrBodyTextToObject(await readBoundedFetchResponseText(responseOrHeader, MAX_X402_CHALLENGE_BYTES), false, "body");
|
|
451
|
+
})();
|
|
452
|
+
return parseSyncChallengeInput(responseOrHeader);
|
|
453
|
+
}
|
|
454
|
+
function encodeX402PaymentHeader(payload) {
|
|
455
|
+
return require_personal_vault.base64UrlEncodeBytes(require_secp256k1_scalar.utf8Bytes(JSON.stringify({
|
|
456
|
+
x402Version: 1,
|
|
457
|
+
scheme: X402_EXACT_EVM_TX_SCHEME,
|
|
458
|
+
chainId: payload.chainId,
|
|
459
|
+
signedRawTxHex: payload.signedRawTxHex,
|
|
460
|
+
txHashHex: payload.txHashHex,
|
|
461
|
+
payer: payload.payer
|
|
462
|
+
})));
|
|
463
|
+
}
|
|
464
|
+
function decodeX402PaymentHeader(encodedHeader) {
|
|
465
|
+
const rawBytes = require_personal_vault.base64UrlDecodeBytes(encodedHeader, "PERSONAL_POLICY_VIOLATION");
|
|
466
|
+
if (rawBytes.length === 0 || rawBytes.length > MAX_X402_CHALLENGE_BYTES) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Decoded X-Payment header out of bounds");
|
|
467
|
+
const obj = parseSafeBoundedJsonObject(decodeStrictUtf8(rawBytes), MAX_X402_CHALLENGE_BYTES);
|
|
468
|
+
if (obj.x402Version !== 1 || obj.scheme !== X402_EXACT_EVM_TX_SCHEME) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid X-Payment version or scheme");
|
|
469
|
+
const chainIdVal = parseChainIdFlexible(obj.chainId, "X-Payment.chainId");
|
|
470
|
+
const chainIdOut = chainIdVal <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(chainIdVal) : chainIdVal.toString(10);
|
|
471
|
+
if (typeof obj.signedRawTxHex !== "string" || !/^0x02[0-9a-fA-F]+$/.test(obj.signedRawTxHex)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "X-Payment signedRawTxHex must be Type-2 0x02 hex");
|
|
472
|
+
if (typeof obj.txHashHex !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(obj.txHashHex)) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid X-Payment txHashHex");
|
|
473
|
+
if (typeof obj.payer !== "string") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Missing X-Payment payer");
|
|
474
|
+
const payer = require_tweak.parseStrictEthAddress(obj.payer).checksumAddress;
|
|
475
|
+
return {
|
|
476
|
+
x402Version: 1,
|
|
477
|
+
scheme: X402_EXACT_EVM_TX_SCHEME,
|
|
478
|
+
chainId: chainIdOut,
|
|
479
|
+
signedRawTxHex: obj.signedRawTxHex,
|
|
480
|
+
txHashHex: obj.txHashHex,
|
|
481
|
+
payer
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
function normalizeCeilingMap(ceiling, label) {
|
|
485
|
+
if (ceiling === void 0) return null;
|
|
486
|
+
if (typeof ceiling === "bigint") {
|
|
487
|
+
if (ceiling < 0n) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `${label} cannot be negative`);
|
|
488
|
+
return () => ceiling;
|
|
489
|
+
}
|
|
490
|
+
if (typeof ceiling === "object" && ceiling !== null && !Array.isArray(ceiling)) {
|
|
491
|
+
const map = /* @__PURE__ */ new Map();
|
|
492
|
+
for (const [k, v] of Object.entries(ceiling)) {
|
|
493
|
+
if (typeof v !== "bigint" || v < 0n) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `${label}["${k}"] must be a non-negative bigint`);
|
|
494
|
+
const normKey = k === "native" || k.toLowerCase() === "eth" ? "native" : require_tweak.parseStrictEthAddress(k).lowercaseAddress;
|
|
495
|
+
map.set(normKey, v);
|
|
496
|
+
}
|
|
497
|
+
return (asset) => map.get(asset);
|
|
498
|
+
}
|
|
499
|
+
throw new require_constants.MpcProtocolError("INVALID_PARAMETER", `Invalid ${label}`);
|
|
500
|
+
}
|
|
501
|
+
function verifyClientSideAnnounceTicketFields(params) {
|
|
502
|
+
const { ticket } = params;
|
|
503
|
+
if (!ticket || ticket.kind !== "announce-ticket" || ticket.vaultId !== params.vaultId) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Invalid SignedAnnounceTicket");
|
|
504
|
+
if (typeof ticket.ticketKid !== "string" || ticket.ticketKid.length === 0 || ticket.ticketKid.length > 32) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed SignedAnnounceTicket ticketKid");
|
|
505
|
+
let policyEpoch;
|
|
506
|
+
let announcedAtSec;
|
|
507
|
+
let executableAfterSec;
|
|
508
|
+
let expiresAtSec;
|
|
509
|
+
let ticketPreview32;
|
|
510
|
+
let ticketDigest32;
|
|
511
|
+
try {
|
|
512
|
+
if (typeof ticket.policyEpoch !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(ticket.policyEpoch) || typeof ticket.vetoEpoch !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(ticket.vetoEpoch) || typeof ticket.announcedAtSec !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(ticket.announcedAtSec) || typeof ticket.executableAfterSec !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(ticket.executableAfterSec) || typeof ticket.expiresAtSec !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(ticket.expiresAtSec)) throw new Error("non-canonical uint64");
|
|
513
|
+
policyEpoch = BigInt(ticket.policyEpoch);
|
|
514
|
+
const vetoEpoch = BigInt(ticket.vetoEpoch);
|
|
515
|
+
announcedAtSec = BigInt(ticket.announcedAtSec);
|
|
516
|
+
executableAfterSec = BigInt(ticket.executableAfterSec);
|
|
517
|
+
expiresAtSec = BigInt(ticket.expiresAtSec);
|
|
518
|
+
if (policyEpoch > MAX_UINT64 || vetoEpoch > MAX_UINT64 || announcedAtSec > MAX_UINT64 || executableAfterSec > MAX_UINT64 || expiresAtSec > MAX_UINT64) throw new Error("uint64 overflow");
|
|
519
|
+
require_secp256k1_scalar.normalizeHexBytes(ticket.macHex, 32);
|
|
520
|
+
ticketPreview32 = require_secp256k1_scalar.normalizeHexBytes(ticket.clearSigningPreviewHashHex, 32);
|
|
521
|
+
ticketDigest32 = require_secp256k1_scalar.normalizeHexBytes(ticket.signingDigestHex, 32);
|
|
522
|
+
} catch {
|
|
523
|
+
throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed SignedAnnounceTicket fields");
|
|
524
|
+
}
|
|
525
|
+
if (policyEpoch !== params.policyEpoch || !require_secp256k1_scalar.constantTimeEqual(ticketPreview32, params.clearSigningPreviewHash32) || !require_secp256k1_scalar.constantTimeEqual(ticketDigest32, params.signingDigest32)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket transaction binding mismatch");
|
|
526
|
+
if (executableAfterSec < announcedAtSec || executableAfterSec - announcedAtSec < BigInt(params.minTimelockDelaySec)) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket delay shorter than policy timelockDelaySec");
|
|
527
|
+
if (params.nowSec < executableAfterSec) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket timelock has not matured yet");
|
|
528
|
+
if (params.nowSec > expiresAtSec) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket has expired");
|
|
529
|
+
}
|
|
530
|
+
function tierToEscalationKind(tier) {
|
|
531
|
+
if (tier === "L1") return "announce-timelock";
|
|
532
|
+
if (tier === "L2") return "role-quorum";
|
|
533
|
+
return "quorum-and-timelock";
|
|
534
|
+
}
|
|
535
|
+
function buildCanonicalX402UnsignedTx(requirement, txParams) {
|
|
536
|
+
if (typeof txParams.nonce !== "bigint" || txParams.nonce < 0n) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "txParams.nonce must be a non-negative bigint");
|
|
537
|
+
if (typeof txParams.maxPriorityFeePerGasWei !== "bigint" || txParams.maxPriorityFeePerGasWei < 0n) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "txParams.maxPriorityFeePerGasWei must be >= 0n");
|
|
538
|
+
if (typeof txParams.maxFeePerGasWei !== "bigint" || txParams.maxFeePerGasWei < txParams.maxPriorityFeePerGasWei) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "txParams.maxFeePerGasWei must be >= maxPriorityFeePerGasWei");
|
|
539
|
+
if (txParams.gasLimit !== void 0 && (typeof txParams.gasLimit !== "bigint" || txParams.gasLimit < 21000n)) throw new require_constants.MpcProtocolError("RLP_INVALID_TRANSACTION", "txParams.gasLimit must be >= 21_000n");
|
|
540
|
+
if (requirement.assetKind === "native") return {
|
|
541
|
+
chainId: requirement.chainId,
|
|
542
|
+
nonce: txParams.nonce,
|
|
543
|
+
maxPriorityFeePerGasWei: txParams.maxPriorityFeePerGasWei,
|
|
544
|
+
maxFeePerGasWei: txParams.maxFeePerGasWei,
|
|
545
|
+
gasLimit: txParams.gasLimit ?? 21000n,
|
|
546
|
+
to: requirement.payToChecksumAddress,
|
|
547
|
+
valueWei: requirement.amount,
|
|
548
|
+
data: "0x"
|
|
549
|
+
};
|
|
550
|
+
const calldata = require_rlp_eip1559.encodeErc20TransferCalldata(requirement.payToChecksumAddress, requirement.amount);
|
|
551
|
+
return {
|
|
552
|
+
chainId: requirement.chainId,
|
|
553
|
+
nonce: txParams.nonce,
|
|
554
|
+
maxPriorityFeePerGasWei: txParams.maxPriorityFeePerGasWei,
|
|
555
|
+
maxFeePerGasWei: txParams.maxFeePerGasWei,
|
|
556
|
+
gasLimit: txParams.gasLimit ?? 65000n,
|
|
557
|
+
to: requirement.tokenChecksumAddress,
|
|
558
|
+
valueWei: 0n,
|
|
559
|
+
data: calldata
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
function evaluateRequirementEligibility(params) {
|
|
563
|
+
const { requirement, canonicalPolicy } = params;
|
|
564
|
+
const chainStr = requirement.chainId.toString(10);
|
|
565
|
+
if (!canonicalPolicy.allowedChainIds.includes(chainStr)) return `ChainId ${chainStr} is not allowlisted by PersonalVaultPolicy`;
|
|
566
|
+
if (params.clientAllowedChainIds && !params.clientAllowedChainIds.has(chainStr)) return `ChainId ${chainStr} is not in x402 client allowedChainIds`;
|
|
567
|
+
if (params.clientAllowedPayees && !params.clientAllowedPayees.has(requirement.payToChecksumAddress)) return `Payee ${requirement.payToChecksumAddress} is not in x402 client allowedPayees`;
|
|
568
|
+
if (canonicalPolicy.allowedPayees.length > 0 && canonicalPolicy.enforcePayeeAllowlistInL0 && !canonicalPolicy.allowedPayees.includes(requirement.payToChecksumAddress) && Object.keys(canonicalPolicy.roleRosters).length === 0 && !canonicalPolicy.guardianRoster) {}
|
|
569
|
+
if (params.getMaxPerRequest) {
|
|
570
|
+
const cap = params.getMaxPerRequest(requirement.asset);
|
|
571
|
+
if (cap !== void 0 && requirement.amount > cap) return `x402 payment amount (${requirement.amount}) exceeds maxPerRequestAmount (${cap})`;
|
|
572
|
+
}
|
|
573
|
+
if (params.getMaxSessionTotal) {
|
|
574
|
+
const cap = params.getMaxSessionTotal(requirement.asset);
|
|
575
|
+
if (cap !== void 0) {
|
|
576
|
+
const prior = params.sessionSpentByAssetKey.get(`${chainStr}:${requirement.asset}`) ?? 0n;
|
|
577
|
+
if (prior + requirement.amount > cap) return `x402 cumulative session spend (${prior + requirement.amount}) exceeds maxSessionTotalAmount (${cap})`;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Wraps Web `fetch` with deterministic `x402` (`HTTP 402 Payment Required`) AI Agent Treasury governance:
|
|
584
|
+
* - Constructs ONLY canonical `native-transfer` or `erc20-transfer` Type-2 EIP-1559 transactions.
|
|
585
|
+
* - Auto-signs in `L0` within `PersonalVaultPolicy` + optional client-side ceilings, attaches base64url
|
|
586
|
+
* `X-Payment`, and retries at most once (`MAX_X402_RETRIES = 1`, failing closed on a second `402`).
|
|
587
|
+
* - Escalates `L1`..`L3` requirements through `onEscalationRequired` to collect a `PolicyProofBundle`
|
|
588
|
+
* before co-signing; fails closed with `PERSONAL_POLICY_VIOLATION` if unconfigured or denied.
|
|
589
|
+
*/
|
|
590
|
+
function createX402AgentPaymentFetch(options) {
|
|
591
|
+
if (!options?.signer || !options.policy || typeof options.txParamsProvider !== "function") throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "createX402AgentPaymentFetch requires signer, policy, and txParamsProvider");
|
|
592
|
+
const baseFetch = options.fetchImpl ?? globalThis.fetch;
|
|
593
|
+
if (typeof baseFetch !== "function") throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Global fetch is unavailable; supply options.fetchImpl");
|
|
594
|
+
const { canonicalPolicy, policyHash32 } = require_personal_vault.canonicalizePersonalVaultPolicy(options.policy);
|
|
595
|
+
const clientAllowedPayees = options.allowedPayees !== void 0 ? new Set(options.allowedPayees.map((addr) => require_tweak.parseStrictEthAddress(addr).checksumAddress)) : null;
|
|
596
|
+
const clientAllowedChainIds = options.allowedChainIds !== void 0 ? new Set(options.allowedChainIds.map((cid) => parseChainIdFlexible(cid, "allowedChainIds").toString(10))) : null;
|
|
597
|
+
const getMaxPerRequest = normalizeCeilingMap(options.maxPerRequestAmount, "maxPerRequestAmount");
|
|
598
|
+
const getMaxSessionTotal = normalizeCeilingMap(options.maxSessionTotalAmount, "maxSessionTotalAmount");
|
|
599
|
+
const sessionSpentByAssetKey = /* @__PURE__ */ new Map();
|
|
600
|
+
return async function x402GuardedFetch(input, init) {
|
|
601
|
+
const clonedRetryRequest = typeof Request !== "undefined" && input instanceof Request ? input.clone() : null;
|
|
602
|
+
const initialResponse = await baseFetch(input, init);
|
|
603
|
+
if (initialResponse.status !== 402) return initialResponse;
|
|
604
|
+
const challenge = await parseX402PaymentChallenge(initialResponse);
|
|
605
|
+
let selectedRequirement = null;
|
|
606
|
+
let firstRejectionReason = null;
|
|
607
|
+
for (const candidate of challenge.accepts) {
|
|
608
|
+
const rejectReason = evaluateRequirementEligibility({
|
|
609
|
+
requirement: candidate,
|
|
610
|
+
canonicalPolicy,
|
|
611
|
+
clientAllowedChainIds,
|
|
612
|
+
clientAllowedPayees,
|
|
613
|
+
getMaxPerRequest,
|
|
614
|
+
getMaxSessionTotal,
|
|
615
|
+
sessionSpentByAssetKey
|
|
616
|
+
});
|
|
617
|
+
if (rejectReason === null) {
|
|
618
|
+
selectedRequirement = candidate;
|
|
619
|
+
break;
|
|
620
|
+
}
|
|
621
|
+
if (firstRejectionReason === null) firstRejectionReason = rejectReason;
|
|
622
|
+
}
|
|
623
|
+
if (!selectedRequirement) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", firstRejectionReason ?? "No x402 payment option satisfied policy and client guardrails");
|
|
624
|
+
const assetVelocityKey = `${selectedRequirement.chainId.toString(10)}:${selectedRequirement.asset}`;
|
|
625
|
+
const currentSpent = sessionSpentByAssetKey.get(assetVelocityKey) ?? 0n;
|
|
626
|
+
const nextSpent = currentSpent + selectedRequirement.amount;
|
|
627
|
+
if (getMaxSessionTotal) {
|
|
628
|
+
const cap = getMaxSessionTotal(selectedRequirement.asset);
|
|
629
|
+
if (cap !== void 0 && nextSpent > cap) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 cumulative session spend (${nextSpent}) exceeds maxSessionTotalAmount (${cap})`);
|
|
630
|
+
}
|
|
631
|
+
sessionSpentByAssetKey.set(assetVelocityKey, nextSpent);
|
|
632
|
+
let xPaymentHeader;
|
|
633
|
+
try {
|
|
634
|
+
const txParams = await options.txParamsProvider({
|
|
635
|
+
requirement: selectedRequirement,
|
|
636
|
+
payerAddress: options.signer.address
|
|
637
|
+
});
|
|
638
|
+
const unsignedTx = buildCanonicalX402UnsignedTx(selectedRequirement, txParams);
|
|
639
|
+
const verifiedTx = require_personal_vault.decodeAndVerifyPersonalEip1559Tx({
|
|
640
|
+
txOrRawBytes: unsignedTx,
|
|
641
|
+
policy: canonicalPolicy
|
|
642
|
+
});
|
|
643
|
+
if (verifiedTx.callKind !== "native-transfer" && verifiedTx.callKind !== "erc20-transfer") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 only permits canonical native-transfer or erc20-transfer, got ${verifiedTx.callKind}`);
|
|
644
|
+
const nativeVelocityKey = `${selectedRequirement.chainId.toString(10)}:native`;
|
|
645
|
+
const externalRolling = options.getRolling24hSpendAmount ? await options.getRolling24hSpendAmount({
|
|
646
|
+
chainId: selectedRequirement.chainId,
|
|
647
|
+
asset: selectedRequirement.asset
|
|
648
|
+
}) : currentSpent;
|
|
649
|
+
const { requiredTier } = require_personal_vault.resolveRequiredPolicyTier({
|
|
650
|
+
policy: canonicalPolicy,
|
|
651
|
+
verifiedTx,
|
|
652
|
+
currentRolling24hSpendAmount: externalRolling,
|
|
653
|
+
currentNativeRolling24hSpendAmount: selectedRequirement.asset === "native" ? externalRolling : options.getRolling24hSpendAmount ? await options.getRolling24hSpendAmount({
|
|
654
|
+
chainId: selectedRequirement.chainId,
|
|
655
|
+
asset: "native"
|
|
656
|
+
}) : sessionSpentByAssetKey.get(nativeVelocityKey) ?? 0n
|
|
657
|
+
});
|
|
658
|
+
const preview = require_personal_vault.buildPersonalClearSigningPreview({
|
|
659
|
+
fromAddress: options.signer.address,
|
|
660
|
+
verifiedTx
|
|
661
|
+
});
|
|
662
|
+
const previewHash32 = require_personal_vault.computePersonalClearSigningPreviewHash32(preview);
|
|
663
|
+
let policyProof;
|
|
664
|
+
if (requiredTier !== "L0") {
|
|
665
|
+
if (!options.onEscalationRequired) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 payment requires ${requiredTier} (${tierToEscalationKind(requiredTier)}) escalation, but no onEscalationRequired handler is configured`);
|
|
666
|
+
const resolvedProof = await options.onEscalationRequired({
|
|
667
|
+
challenge,
|
|
668
|
+
requirement: selectedRequirement,
|
|
669
|
+
unsignedTx,
|
|
670
|
+
verifiedTx,
|
|
671
|
+
preview,
|
|
672
|
+
previewHash32,
|
|
673
|
+
signingDigest32: verifiedTx.signingDigest32,
|
|
674
|
+
requiredTier,
|
|
675
|
+
escalationKind: tierToEscalationKind(requiredTier)
|
|
676
|
+
});
|
|
677
|
+
if (!resolvedProof) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `x402 ${requiredTier} escalation was denied or returned no PolicyProofBundle`);
|
|
678
|
+
if (resolvedProof.tier === "L0" || requiredTier === "L3" && resolvedProof.tier !== "L3" || requiredTier === "L2" && resolvedProof.tier === "L1" || requiredTier === "L1" && resolvedProof.tier === "L2") throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Supplied PolicyProofBundle tier ${resolvedProof.tier} does not satisfy required tier ${requiredTier}`);
|
|
679
|
+
const nowSec = options.nowSec ? options.nowSec() : BigInt(Math.floor(Date.now() / 1e3));
|
|
680
|
+
if (resolvedProof.tier === "L2") require_personal_vault.verifyPersonalPolicyProofBundle({
|
|
681
|
+
requiredTier,
|
|
682
|
+
proofBundle: resolvedProof,
|
|
683
|
+
policy: canonicalPolicy,
|
|
684
|
+
vaultId: canonicalPolicy.vaultId,
|
|
685
|
+
policyEpoch: options.signer.cluster.keyEpoch,
|
|
686
|
+
policyHash32,
|
|
687
|
+
currentVetoEpoch: 0n,
|
|
688
|
+
clearSigningPreviewHash32: previewHash32,
|
|
689
|
+
signingDigest32: verifiedTx.signingDigest32,
|
|
690
|
+
nowSec
|
|
691
|
+
});
|
|
692
|
+
else if (resolvedProof.tier === "L1") verifyClientSideAnnounceTicketFields({
|
|
693
|
+
ticket: resolvedProof.announceTicket,
|
|
694
|
+
vaultId: canonicalPolicy.vaultId,
|
|
695
|
+
policyEpoch: options.signer.cluster.keyEpoch,
|
|
696
|
+
minTimelockDelaySec: canonicalPolicy.timelockDelaySec,
|
|
697
|
+
clearSigningPreviewHash32: previewHash32,
|
|
698
|
+
signingDigest32: verifiedTx.signingDigest32,
|
|
699
|
+
nowSec
|
|
700
|
+
});
|
|
701
|
+
else if (resolvedProof.tier === "L3") {
|
|
702
|
+
verifyClientSideAnnounceTicketFields({
|
|
703
|
+
ticket: resolvedProof.announceTicket,
|
|
704
|
+
vaultId: canonicalPolicy.vaultId,
|
|
705
|
+
policyEpoch: options.signer.cluster.keyEpoch,
|
|
706
|
+
minTimelockDelaySec: canonicalPolicy.timelockDelaySec,
|
|
707
|
+
clearSigningPreviewHash32: previewHash32,
|
|
708
|
+
signingDigest32: verifiedTx.signingDigest32,
|
|
709
|
+
nowSec
|
|
710
|
+
});
|
|
711
|
+
if (canonicalPolicy.guardianRoster !== void 0) {
|
|
712
|
+
if (!resolvedProof.quorumProof || resolvedProof.quorumProof.kind !== "guardian-quorum") throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "L3 requires guardian-quorum when guardianRoster is configured in policy");
|
|
713
|
+
require_personal_vault.verifyGuardianQuorumProof({
|
|
714
|
+
proof: resolvedProof.quorumProof,
|
|
715
|
+
policy: canonicalPolicy,
|
|
716
|
+
vaultId: canonicalPolicy.vaultId,
|
|
717
|
+
policyEpoch: options.signer.cluster.keyEpoch,
|
|
718
|
+
policyHash32,
|
|
719
|
+
clearSigningPreviewHash32: previewHash32,
|
|
720
|
+
signingDigest32: verifiedTx.signingDigest32,
|
|
721
|
+
nowSec
|
|
722
|
+
});
|
|
723
|
+
} else {
|
|
724
|
+
if (!resolvedProof.quorumProof || resolvedProof.quorumProof.kind !== "role-quorum") throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", "L3 requires role-quorum when policy has no guardianRoster");
|
|
725
|
+
const requiredL3Role = canonicalPolicy.defaultRoleForL3 ?? canonicalPolicy.defaultRoleForL2;
|
|
726
|
+
if (requiredL3Role !== void 0 && resolvedProof.quorumProof.role !== requiredL3Role) throw new require_constants.MpcProtocolError("PERSONAL_PROOF_INVALID", `L3 RoleQuorumProof role "${resolvedProof.quorumProof.role}" does not match required role "${requiredL3Role}"`);
|
|
727
|
+
require_personal_vault.verifyRoleQuorumProof({
|
|
728
|
+
proof: resolvedProof.quorumProof,
|
|
729
|
+
policy: canonicalPolicy,
|
|
730
|
+
vaultId: canonicalPolicy.vaultId,
|
|
731
|
+
policyEpoch: options.signer.cluster.keyEpoch,
|
|
732
|
+
policyHash32,
|
|
733
|
+
clearSigningPreviewHash32: previewHash32,
|
|
734
|
+
signingDigest32: verifiedTx.signingDigest32,
|
|
735
|
+
nowSec
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
policyProof = resolvedProof;
|
|
740
|
+
}
|
|
741
|
+
const signed = await options.signer.signTransaction(unsignedTx, {
|
|
742
|
+
policyProof,
|
|
743
|
+
entitlementTicket: options.entitlementTicket
|
|
744
|
+
});
|
|
745
|
+
if (verifiedTx.maxGasFeeWei > 0n) sessionSpentByAssetKey.set(nativeVelocityKey, (sessionSpentByAssetKey.get(nativeVelocityKey) ?? 0n) + verifiedTx.maxGasFeeWei);
|
|
746
|
+
xPaymentHeader = encodeX402PaymentHeader({
|
|
747
|
+
x402Version: 1,
|
|
748
|
+
scheme: X402_EXACT_EVM_TX_SCHEME,
|
|
749
|
+
chainId: selectedRequirement.chainId <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(selectedRequirement.chainId) : selectedRequirement.chainId.toString(10),
|
|
750
|
+
signedRawTxHex: signed.rawSignedTxHex,
|
|
751
|
+
txHashHex: signed.txHashHex,
|
|
752
|
+
payer: signed.signerAddress
|
|
753
|
+
});
|
|
754
|
+
} catch (err) {
|
|
755
|
+
const latest = sessionSpentByAssetKey.get(assetVelocityKey) ?? 0n;
|
|
756
|
+
const restored = latest > selectedRequirement.amount ? latest - selectedRequirement.amount : 0n;
|
|
757
|
+
if (restored === 0n) sessionSpentByAssetKey.delete(assetVelocityKey);
|
|
758
|
+
else sessionSpentByAssetKey.set(assetVelocityKey, restored);
|
|
759
|
+
throw err;
|
|
760
|
+
}
|
|
761
|
+
const mergedHeaders = new Headers(init?.headers ?? (clonedRetryRequest ? clonedRetryRequest.headers : void 0));
|
|
762
|
+
mergedHeaders.set("X-Payment", xPaymentHeader);
|
|
763
|
+
let retryResponse;
|
|
764
|
+
if (clonedRetryRequest) retryResponse = await baseFetch(new Request(clonedRetryRequest, {
|
|
765
|
+
...init,
|
|
766
|
+
headers: mergedHeaders,
|
|
767
|
+
redirect: "error"
|
|
768
|
+
}));
|
|
769
|
+
else retryResponse = await baseFetch(input, {
|
|
770
|
+
...init,
|
|
771
|
+
headers: mergedHeaders,
|
|
772
|
+
redirect: "error"
|
|
773
|
+
});
|
|
774
|
+
if (retryResponse.status === 402) throw new require_constants.MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Upstream returned HTTP 402 again after X-Payment retry (MAX_X402_RETRIES = ${MAX_X402_RETRIES})`);
|
|
775
|
+
return retryResponse;
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
//#endregion
|
|
780
|
+
exports.MAX_X402_ACCEPTS_ENTRIES = MAX_X402_ACCEPTS_ENTRIES;
|
|
781
|
+
exports.MAX_X402_CHALLENGE_BYTES = MAX_X402_CHALLENGE_BYTES;
|
|
782
|
+
exports.MAX_X402_RETRIES = MAX_X402_RETRIES;
|
|
783
|
+
exports.X402_EXACT_EVM_TX_SCHEME = X402_EXACT_EVM_TX_SCHEME;
|
|
784
|
+
exports.X402_PROTOCOL_VERSION = X402_PROTOCOL_VERSION;
|
|
785
|
+
exports.createX402AgentPaymentFetch = createX402AgentPaymentFetch;
|
|
786
|
+
exports.decodeX402PaymentHeader = decodeX402PaymentHeader;
|
|
787
|
+
exports.encodeX402PaymentHeader = encodeX402PaymentHeader;
|
|
788
|
+
exports.parseX402PaymentChallenge = parseX402PaymentChallenge;
|