@dvmkit/dvm-cli 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +14 -0
  2. package/dist/{_esm-M2HUAA3B.js → _esm-MN4BUYV6.js} +56 -54
  3. package/dist/{accounts-S747UW3A.js → accounts-2WZE4N5F.js} +5 -5
  4. package/dist/actions-LR65XILR.js +244 -0
  5. package/dist/{ccip-XZ5F5J6R.js → ccip-JXYJSXTW.js} +3 -3
  6. package/dist/{chains-PINFXYUE.js → chains-LJ7XK6H3.js} +8 -8
  7. package/dist/{chunk-YZUBKHHA.js → chunk-2VVVWBQA.js} +471 -471
  8. package/dist/chunk-3SWX5BQP.js +66 -0
  9. package/dist/chunk-4JXFXP4Y.js +757 -0
  10. package/dist/{chunk-GIDSTROG.js → chunk-4NWEJTAW.js} +160 -158
  11. package/dist/{chunk-UXQCP26E.js → chunk-65EY7CT4.js} +2 -2
  12. package/dist/{chunk-6UGZAFIR.js → chunk-6CC6JGEU.js} +348 -18
  13. package/dist/{chunk-PHZHPRQE.js → chunk-6O27TEXD.js} +173 -173
  14. package/dist/{chunk-HPRIQEJS.js → chunk-7OK7MBT6.js} +19 -19
  15. package/dist/{chunk-7UPZZGC5.js → chunk-BECPI5H5.js} +193 -193
  16. package/dist/chunk-CJTE5TS3.js +1298 -0
  17. package/dist/{chunk-RWBYCM47.js → chunk-ECEM3ZAS.js} +10 -10
  18. package/dist/{chunk-ACNNU5RY.js → chunk-ECK465AY.js} +694 -565
  19. package/dist/{chunk-XGABM4H5.js → chunk-EGY4KDBW.js} +3822 -2012
  20. package/dist/{chunk-SLDVIXCS.js → chunk-EVQERRCP.js} +12 -12
  21. package/dist/{chunk-4AQ4G7L5.js → chunk-EZHT2RLJ.js} +383 -383
  22. package/dist/{chunk-IC6OXFYW.js → chunk-F55NNH2F.js} +63 -63
  23. package/dist/chunk-G5C6E6PJ.js +9063 -0
  24. package/dist/{chunk-6AJ7H2VX.js → chunk-GZWKCIYN.js} +213 -1281
  25. package/dist/{chunk-ZGXCK43G.js → chunk-LH3QPVN6.js} +8499 -8498
  26. package/dist/{chunk-MMJR6N3J.js → chunk-MLDUKBU3.js} +1368 -1368
  27. package/dist/chunk-N3UJT2NJ.js +3 -0
  28. package/dist/chunk-N7MGIK2U.js +61408 -0
  29. package/dist/{chunk-BZNZWRBB.js → chunk-OWJZYYMG.js} +11 -15
  30. package/dist/chunk-ZJYO7OLO.js +514 -0
  31. package/dist/{client-D3XFLWOK.js → client-OWIOFBKS.js} +18 -16
  32. package/dist/{dist-7MMV3EZA.js → dist-2G3QBGID.js} +11 -10
  33. package/dist/dvm.js +27046 -4414
  34. package/dist/esm-RQLHAH2K.js +5183 -0
  35. package/dist/internal-JDG52DJH.js +1230 -0
  36. package/dist/payout-reporter-3UB5WRCV-XTVZFIAO.js +17 -0
  37. package/dist/{pocket-refill-GDYSTECR.js → pocket-refill-QJMMD6QN.js} +29 -30
  38. package/dist/revenue-reporter-JIKUPXOK-TYUBTF4P.js +11 -0
  39. package/dist/{secp256k1-4YWQEMGF.js → secp256k1-JLZEQ2H7.js} +2 -2
  40. package/dist/tempo-lifecycle-SQL3KLEZ-AATA2SKI.js +28 -0
  41. package/dist/{tempo-wallet-5FEOI4CF.js → tempo-wallet-QOLEIPCV-SWCXRBDS.js} +2 -4
  42. package/dist/{x402-VNFA3DBY.js → x402-FTG2GRAQ-UGAUMUL6.js} +13 -24
  43. package/package.json +2 -10
  44. package/skills/dvm/SKILL.md +2 -1
  45. package/dist/channel-store-GOV7TEDN.js +0 -62
  46. package/dist/chunk-3PPOU55E.js +0 -312
  47. package/dist/chunk-3TBULV3F.js +0 -551
  48. package/dist/chunk-5BUV73FO.js +0 -2351
  49. package/dist/chunk-EY5K4BM3.js +0 -1780
  50. package/dist/chunk-G3RLVJF5.js +0 -19
  51. package/dist/chunk-KC4UPK44.js +0 -113
  52. package/dist/chunk-MTBCEXJ6.js +0 -4602
  53. package/dist/chunk-ONQMRWY3.js +0 -83
  54. package/dist/chunk-TO47XRK7.js +0 -24890
  55. package/dist/chunk-U5TNSUYW.js +0 -1757
  56. package/dist/chunk-UU6QMSTQ.js +0 -171
  57. package/dist/chunk-ZELLQI7F.js +0 -248
  58. package/dist/lifecycle-5RLM5JMN.js +0 -29
  59. package/dist/tempo-lifecycle-DHZPQTSB.js +0 -31
  60. package/dist/wallet-G3VOUCL4.js +0 -30
@@ -1,1780 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __dvmCreateRequire } from "node:module";
3
- const require = __dvmCreateRequire(import.meta.url);
4
- import {
5
- authorizeProtectedRemoval,
6
- isValidEvmPrivateKey,
7
- loadConfig,
8
- updateConfig
9
- } from "./chunk-XGABM4H5.js";
10
- import {
11
- assertSupportedX402Network,
12
- x402NetworkByCaip2,
13
- x402NetworkBySlug,
14
- x402SupportedNetworksHint
15
- } from "./chunk-MTBCEXJ6.js";
16
- import {
17
- redactUrl,
18
- redactUrlsInText,
19
- resolveRpcHttpTransportOptions,
20
- resolveRpcOverride
21
- } from "./chunk-ONQMRWY3.js";
22
- import {
23
- withX402ChannelLock
24
- } from "./chunk-3TBULV3F.js";
25
- import {
26
- DvmError
27
- } from "./chunk-U5TNSUYW.js";
28
-
29
- // src/lib/caller-loggers.ts
30
- var callerLoggers = buildNoopLoggers();
31
- function buildNoopLoggers() {
32
- const noopLogger = {
33
- // eslint-disable-next-line @typescript-eslint/no-empty-function -- standalone caller has no exporter
34
- info() {
35
- },
36
- async span(_name, _attrs, fn) {
37
- return fn();
38
- }
39
- };
40
- return {
41
- cashu: noopLogger,
42
- lightning: noopLogger,
43
- x402: noopLogger
44
- };
45
- }
46
-
47
- // src/lib/x402/constants.ts
48
- var X402_DEFAULT_FACILITATOR = "https://x402.org/facilitator";
49
-
50
- // src/lib/x402/facilitator.ts
51
- import { createPrivateKey, randomBytes } from "crypto";
52
-
53
- // node_modules/jose/dist/webapi/lib/buffer_utils.js
54
- var encoder = new TextEncoder();
55
- var decoder = new TextDecoder();
56
- var MAX_INT32 = 2 ** 32;
57
- function concat(...buffers) {
58
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
59
- const buf = new Uint8Array(size);
60
- let i = 0;
61
- for (const buffer of buffers) {
62
- buf.set(buffer, i);
63
- i += buffer.length;
64
- }
65
- return buf;
66
- }
67
- function encode(string) {
68
- const bytes = new Uint8Array(string.length);
69
- for (let i = 0; i < string.length; i++) {
70
- const code = string.charCodeAt(i);
71
- if (code > 127) {
72
- throw new TypeError("non-ASCII string encountered in encode()");
73
- }
74
- bytes[i] = code;
75
- }
76
- return bytes;
77
- }
78
-
79
- // node_modules/jose/dist/webapi/lib/base64.js
80
- function encodeBase64(input) {
81
- if (Uint8Array.prototype.toBase64) {
82
- return input.toBase64();
83
- }
84
- const CHUNK_SIZE = 32768;
85
- const arr = [];
86
- for (let i = 0; i < input.length; i += CHUNK_SIZE) {
87
- arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
88
- }
89
- return btoa(arr.join(""));
90
- }
91
- function decodeBase64(encoded) {
92
- if (Uint8Array.fromBase64) {
93
- return Uint8Array.fromBase64(encoded);
94
- }
95
- const binary = atob(encoded);
96
- const bytes = new Uint8Array(binary.length);
97
- for (let i = 0; i < binary.length; i++) {
98
- bytes[i] = binary.charCodeAt(i);
99
- }
100
- return bytes;
101
- }
102
-
103
- // node_modules/jose/dist/webapi/util/base64url.js
104
- function decode(input) {
105
- if (Uint8Array.fromBase64) {
106
- return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
107
- alphabet: "base64url"
108
- });
109
- }
110
- let encoded = input;
111
- if (encoded instanceof Uint8Array) {
112
- encoded = decoder.decode(encoded);
113
- }
114
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
115
- try {
116
- return decodeBase64(encoded);
117
- } catch {
118
- throw new TypeError("The input to be decoded is not correctly encoded.");
119
- }
120
- }
121
- function encode2(input) {
122
- let unencoded = input;
123
- if (typeof unencoded === "string") {
124
- unencoded = encoder.encode(unencoded);
125
- }
126
- if (Uint8Array.prototype.toBase64) {
127
- return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
128
- }
129
- return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
130
- }
131
-
132
- // node_modules/jose/dist/webapi/lib/crypto_key.js
133
- var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
134
- var isAlgorithm = (algorithm, name) => algorithm.name === name;
135
- function getHashLength(hash) {
136
- return parseInt(hash.name.slice(4), 10);
137
- }
138
- function checkHashLength(algorithm, expected) {
139
- const actual = getHashLength(algorithm.hash);
140
- if (actual !== expected)
141
- throw unusable(`SHA-${expected}`, "algorithm.hash");
142
- }
143
- function getNamedCurve(alg) {
144
- switch (alg) {
145
- case "ES256":
146
- return "P-256";
147
- case "ES384":
148
- return "P-384";
149
- case "ES512":
150
- return "P-521";
151
- default:
152
- throw new Error("unreachable");
153
- }
154
- }
155
- function checkUsage(key, usage) {
156
- if (usage && !key.usages.includes(usage)) {
157
- throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
158
- }
159
- }
160
- function checkSigCryptoKey(key, alg, usage) {
161
- switch (alg) {
162
- case "HS256":
163
- case "HS384":
164
- case "HS512": {
165
- if (!isAlgorithm(key.algorithm, "HMAC"))
166
- throw unusable("HMAC");
167
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
168
- break;
169
- }
170
- case "RS256":
171
- case "RS384":
172
- case "RS512": {
173
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
174
- throw unusable("RSASSA-PKCS1-v1_5");
175
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
176
- break;
177
- }
178
- case "PS256":
179
- case "PS384":
180
- case "PS512": {
181
- if (!isAlgorithm(key.algorithm, "RSA-PSS"))
182
- throw unusable("RSA-PSS");
183
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
184
- break;
185
- }
186
- case "Ed25519":
187
- case "EdDSA": {
188
- if (!isAlgorithm(key.algorithm, "Ed25519"))
189
- throw unusable("Ed25519");
190
- break;
191
- }
192
- case "ML-DSA-44":
193
- case "ML-DSA-65":
194
- case "ML-DSA-87": {
195
- if (!isAlgorithm(key.algorithm, alg))
196
- throw unusable(alg);
197
- break;
198
- }
199
- case "ES256":
200
- case "ES384":
201
- case "ES512": {
202
- if (!isAlgorithm(key.algorithm, "ECDSA"))
203
- throw unusable("ECDSA");
204
- const expected = getNamedCurve(alg);
205
- const actual = key.algorithm.namedCurve;
206
- if (actual !== expected)
207
- throw unusable(expected, "algorithm.namedCurve");
208
- break;
209
- }
210
- default:
211
- throw new TypeError("CryptoKey does not support this operation");
212
- }
213
- checkUsage(key, usage);
214
- }
215
-
216
- // node_modules/jose/dist/webapi/lib/invalid_key_input.js
217
- function message(msg, actual, ...types) {
218
- types = types.filter(Boolean);
219
- if (types.length > 2) {
220
- const last = types.pop();
221
- msg += `one of type ${types.join(", ")}, or ${last}.`;
222
- } else if (types.length === 2) {
223
- msg += `one of type ${types[0]} or ${types[1]}.`;
224
- } else {
225
- msg += `of type ${types[0]}.`;
226
- }
227
- if (actual == null) {
228
- msg += ` Received ${actual}`;
229
- } else if (typeof actual === "function" && actual.name) {
230
- msg += ` Received function ${actual.name}`;
231
- } else if (typeof actual === "object" && actual != null) {
232
- if (actual.constructor?.name) {
233
- msg += ` Received an instance of ${actual.constructor.name}`;
234
- }
235
- }
236
- return msg;
237
- }
238
- var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
239
- var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
240
-
241
- // node_modules/jose/dist/webapi/util/errors.js
242
- var JOSEError = class extends Error {
243
- static code = "ERR_JOSE_GENERIC";
244
- code = "ERR_JOSE_GENERIC";
245
- constructor(message2, options) {
246
- super(message2, options);
247
- this.name = this.constructor.name;
248
- Error.captureStackTrace?.(this, this.constructor);
249
- }
250
- };
251
- var JOSENotSupported = class extends JOSEError {
252
- static code = "ERR_JOSE_NOT_SUPPORTED";
253
- code = "ERR_JOSE_NOT_SUPPORTED";
254
- };
255
- var JWSInvalid = class extends JOSEError {
256
- static code = "ERR_JWS_INVALID";
257
- code = "ERR_JWS_INVALID";
258
- };
259
- var JWTInvalid = class extends JOSEError {
260
- static code = "ERR_JWT_INVALID";
261
- code = "ERR_JWT_INVALID";
262
- };
263
-
264
- // node_modules/jose/dist/webapi/lib/is_key_like.js
265
- var isCryptoKey = (key) => {
266
- if (key?.[Symbol.toStringTag] === "CryptoKey")
267
- return true;
268
- try {
269
- return key instanceof CryptoKey;
270
- } catch {
271
- return false;
272
- }
273
- };
274
- var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
275
- var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
276
-
277
- // node_modules/jose/dist/webapi/lib/helpers.js
278
- function assertNotSet(value, name) {
279
- if (value) {
280
- throw new TypeError(`${name} can only be called once`);
281
- }
282
- }
283
-
284
- // node_modules/jose/dist/webapi/lib/type_checks.js
285
- var isObjectLike = (value) => typeof value === "object" && value !== null;
286
- function isObject(input) {
287
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
288
- return false;
289
- }
290
- if (Object.getPrototypeOf(input) === null) {
291
- return true;
292
- }
293
- let proto = input;
294
- while (Object.getPrototypeOf(proto) !== null) {
295
- proto = Object.getPrototypeOf(proto);
296
- }
297
- return Object.getPrototypeOf(input) === proto;
298
- }
299
- function isDisjoint(...headers) {
300
- const sources = headers.filter(Boolean);
301
- if (sources.length === 0 || sources.length === 1) {
302
- return true;
303
- }
304
- let acc;
305
- for (const header of sources) {
306
- const parameters = Object.keys(header);
307
- if (!acc || acc.size === 0) {
308
- acc = new Set(parameters);
309
- continue;
310
- }
311
- for (const parameter of parameters) {
312
- if (acc.has(parameter)) {
313
- return false;
314
- }
315
- acc.add(parameter);
316
- }
317
- }
318
- return true;
319
- }
320
- var isJWK = (key) => isObject(key) && typeof key.kty === "string";
321
- var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
322
- var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
323
- var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
324
-
325
- // node_modules/jose/dist/webapi/lib/signing.js
326
- function checkKeyLength(alg, key) {
327
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
328
- const { modulusLength } = key.algorithm;
329
- if (typeof modulusLength !== "number" || modulusLength < 2048) {
330
- throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
331
- }
332
- }
333
- }
334
- function subtleAlgorithm(alg, algorithm) {
335
- const hash = `SHA-${alg.slice(-3)}`;
336
- switch (alg) {
337
- case "HS256":
338
- case "HS384":
339
- case "HS512":
340
- return { hash, name: "HMAC" };
341
- case "PS256":
342
- case "PS384":
343
- case "PS512":
344
- return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
345
- case "RS256":
346
- case "RS384":
347
- case "RS512":
348
- return { hash, name: "RSASSA-PKCS1-v1_5" };
349
- case "ES256":
350
- case "ES384":
351
- case "ES512":
352
- return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
353
- case "Ed25519":
354
- case "EdDSA":
355
- return { name: "Ed25519" };
356
- case "ML-DSA-44":
357
- case "ML-DSA-65":
358
- case "ML-DSA-87":
359
- return { name: alg };
360
- default:
361
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
362
- }
363
- }
364
- async function getSigKey(alg, key, usage) {
365
- if (key instanceof Uint8Array) {
366
- if (!alg.startsWith("HS")) {
367
- throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
368
- }
369
- return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
370
- }
371
- checkSigCryptoKey(key, alg, usage);
372
- return key;
373
- }
374
- async function sign(alg, key, data) {
375
- const cryptoKey = await getSigKey(alg, key, "sign");
376
- checkKeyLength(alg, cryptoKey);
377
- const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
378
- return new Uint8Array(signature);
379
- }
380
-
381
- // node_modules/jose/dist/webapi/lib/jwk_to_key.js
382
- var unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value';
383
- function subtleMapping(jwk) {
384
- let algorithm;
385
- let keyUsages;
386
- switch (jwk.kty) {
387
- case "AKP": {
388
- switch (jwk.alg) {
389
- case "ML-DSA-44":
390
- case "ML-DSA-65":
391
- case "ML-DSA-87":
392
- algorithm = { name: jwk.alg };
393
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
394
- break;
395
- default:
396
- throw new JOSENotSupported(unsupportedAlg);
397
- }
398
- break;
399
- }
400
- case "RSA": {
401
- switch (jwk.alg) {
402
- case "PS256":
403
- case "PS384":
404
- case "PS512":
405
- algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
406
- keyUsages = jwk.d ? ["sign"] : ["verify"];
407
- break;
408
- case "RS256":
409
- case "RS384":
410
- case "RS512":
411
- algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
412
- keyUsages = jwk.d ? ["sign"] : ["verify"];
413
- break;
414
- case "RSA-OAEP":
415
- case "RSA-OAEP-256":
416
- case "RSA-OAEP-384":
417
- case "RSA-OAEP-512":
418
- algorithm = {
419
- name: "RSA-OAEP",
420
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
421
- };
422
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
423
- break;
424
- default:
425
- throw new JOSENotSupported(unsupportedAlg);
426
- }
427
- break;
428
- }
429
- case "EC": {
430
- switch (jwk.alg) {
431
- case "ES256":
432
- case "ES384":
433
- case "ES512":
434
- algorithm = {
435
- name: "ECDSA",
436
- namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg]
437
- };
438
- keyUsages = jwk.d ? ["sign"] : ["verify"];
439
- break;
440
- case "ECDH-ES":
441
- case "ECDH-ES+A128KW":
442
- case "ECDH-ES+A192KW":
443
- case "ECDH-ES+A256KW":
444
- algorithm = { name: "ECDH", namedCurve: jwk.crv };
445
- keyUsages = jwk.d ? ["deriveBits"] : [];
446
- break;
447
- default:
448
- throw new JOSENotSupported(unsupportedAlg);
449
- }
450
- break;
451
- }
452
- case "OKP": {
453
- switch (jwk.alg) {
454
- case "Ed25519":
455
- case "EdDSA":
456
- algorithm = { name: "Ed25519" };
457
- keyUsages = jwk.d ? ["sign"] : ["verify"];
458
- break;
459
- case "ECDH-ES":
460
- case "ECDH-ES+A128KW":
461
- case "ECDH-ES+A192KW":
462
- case "ECDH-ES+A256KW":
463
- algorithm = { name: jwk.crv };
464
- keyUsages = jwk.d ? ["deriveBits"] : [];
465
- break;
466
- default:
467
- throw new JOSENotSupported(unsupportedAlg);
468
- }
469
- break;
470
- }
471
- default:
472
- throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
473
- }
474
- return { algorithm, keyUsages };
475
- }
476
- async function jwkToKey(jwk) {
477
- if (!jwk.alg) {
478
- throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
479
- }
480
- const { algorithm, keyUsages } = subtleMapping(jwk);
481
- const keyData = { ...jwk };
482
- if (keyData.kty !== "AKP") {
483
- delete keyData.alg;
484
- }
485
- delete keyData.use;
486
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
487
- }
488
-
489
- // node_modules/jose/dist/webapi/lib/normalize_key.js
490
- var unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
491
- var cache;
492
- var handleJWK = async (key, jwk, alg, freeze = false) => {
493
- cache ||= /* @__PURE__ */ new WeakMap();
494
- let cached = cache.get(key);
495
- if (cached?.[alg]) {
496
- return cached[alg];
497
- }
498
- const cryptoKey = await jwkToKey({ ...jwk, alg });
499
- if (freeze)
500
- Object.freeze(key);
501
- if (!cached) {
502
- cache.set(key, { [alg]: cryptoKey });
503
- } else {
504
- cached[alg] = cryptoKey;
505
- }
506
- return cryptoKey;
507
- };
508
- var handleKeyObject = (keyObject, alg) => {
509
- cache ||= /* @__PURE__ */ new WeakMap();
510
- let cached = cache.get(keyObject);
511
- if (cached?.[alg]) {
512
- return cached[alg];
513
- }
514
- const isPublic = keyObject.type === "public";
515
- const extractable = isPublic ? true : false;
516
- let cryptoKey;
517
- if (keyObject.asymmetricKeyType === "x25519") {
518
- switch (alg) {
519
- case "ECDH-ES":
520
- case "ECDH-ES+A128KW":
521
- case "ECDH-ES+A192KW":
522
- case "ECDH-ES+A256KW":
523
- break;
524
- default:
525
- throw new TypeError(unusableForAlg);
526
- }
527
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
528
- }
529
- if (keyObject.asymmetricKeyType === "ed25519") {
530
- if (alg !== "EdDSA" && alg !== "Ed25519") {
531
- throw new TypeError(unusableForAlg);
532
- }
533
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
534
- isPublic ? "verify" : "sign"
535
- ]);
536
- }
537
- switch (keyObject.asymmetricKeyType) {
538
- case "ml-dsa-44":
539
- case "ml-dsa-65":
540
- case "ml-dsa-87": {
541
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
542
- throw new TypeError(unusableForAlg);
543
- }
544
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
545
- isPublic ? "verify" : "sign"
546
- ]);
547
- }
548
- }
549
- if (keyObject.asymmetricKeyType === "rsa") {
550
- let hash;
551
- switch (alg) {
552
- case "RSA-OAEP":
553
- hash = "SHA-1";
554
- break;
555
- case "RS256":
556
- case "PS256":
557
- case "RSA-OAEP-256":
558
- hash = "SHA-256";
559
- break;
560
- case "RS384":
561
- case "PS384":
562
- case "RSA-OAEP-384":
563
- hash = "SHA-384";
564
- break;
565
- case "RS512":
566
- case "PS512":
567
- case "RSA-OAEP-512":
568
- hash = "SHA-512";
569
- break;
570
- default:
571
- throw new TypeError(unusableForAlg);
572
- }
573
- if (alg.startsWith("RSA-OAEP")) {
574
- return keyObject.toCryptoKey({
575
- name: "RSA-OAEP",
576
- hash
577
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
578
- }
579
- cryptoKey = keyObject.toCryptoKey({
580
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
581
- hash
582
- }, extractable, [isPublic ? "verify" : "sign"]);
583
- }
584
- if (keyObject.asymmetricKeyType === "ec") {
585
- const nist = /* @__PURE__ */ new Map([
586
- ["prime256v1", "P-256"],
587
- ["secp384r1", "P-384"],
588
- ["secp521r1", "P-521"]
589
- ]);
590
- const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
591
- if (!namedCurve) {
592
- throw new TypeError(unusableForAlg);
593
- }
594
- const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" };
595
- if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) {
596
- cryptoKey = keyObject.toCryptoKey({
597
- name: "ECDSA",
598
- namedCurve
599
- }, extractable, [isPublic ? "verify" : "sign"]);
600
- }
601
- if (alg.startsWith("ECDH-ES")) {
602
- cryptoKey = keyObject.toCryptoKey({
603
- name: "ECDH",
604
- namedCurve
605
- }, extractable, isPublic ? [] : ["deriveBits"]);
606
- }
607
- }
608
- if (!cryptoKey) {
609
- throw new TypeError(unusableForAlg);
610
- }
611
- if (!cached) {
612
- cache.set(keyObject, { [alg]: cryptoKey });
613
- } else {
614
- cached[alg] = cryptoKey;
615
- }
616
- return cryptoKey;
617
- };
618
- async function normalizeKey(key, alg) {
619
- if (key instanceof Uint8Array) {
620
- return key;
621
- }
622
- if (isCryptoKey(key)) {
623
- return key;
624
- }
625
- if (isKeyObject(key)) {
626
- if (key.type === "secret") {
627
- return key.export();
628
- }
629
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
630
- try {
631
- return handleKeyObject(key, alg);
632
- } catch (err) {
633
- if (err instanceof TypeError) {
634
- throw err;
635
- }
636
- }
637
- }
638
- let jwk = key.export({ format: "jwk" });
639
- return handleJWK(key, jwk, alg);
640
- }
641
- if (isJWK(key)) {
642
- if (key.k) {
643
- return decode(key.k);
644
- }
645
- return handleJWK(key, key, alg, true);
646
- }
647
- throw new Error("unreachable");
648
- }
649
-
650
- // node_modules/jose/dist/webapi/lib/asn1.js
651
- var bytesEqual = (a, b) => {
652
- if (a.byteLength !== b.length)
653
- return false;
654
- for (let i = 0; i < a.byteLength; i++) {
655
- if (a[i] !== b[i])
656
- return false;
657
- }
658
- return true;
659
- };
660
- var createASN1State = (data) => ({ data, pos: 0 });
661
- var parseLength = (state) => {
662
- const first = state.data[state.pos++];
663
- if (first & 128) {
664
- const lengthOfLen = first & 127;
665
- let length = 0;
666
- for (let i = 0; i < lengthOfLen; i++) {
667
- length = length << 8 | state.data[state.pos++];
668
- }
669
- return length;
670
- }
671
- return first;
672
- };
673
- var expectTag = (state, expectedTag, errorMessage) => {
674
- if (state.data[state.pos++] !== expectedTag) {
675
- throw new Error(errorMessage);
676
- }
677
- };
678
- var getSubarray = (state, length) => {
679
- const result = state.data.subarray(state.pos, state.pos + length);
680
- state.pos += length;
681
- return result;
682
- };
683
- var parseAlgorithmOID = (state) => {
684
- expectTag(state, 6, "Expected algorithm OID");
685
- const oidLen = parseLength(state);
686
- return getSubarray(state, oidLen);
687
- };
688
- function parsePKCS8Header(state) {
689
- expectTag(state, 48, "Invalid PKCS#8 structure");
690
- parseLength(state);
691
- expectTag(state, 2, "Expected version field");
692
- const verLen = parseLength(state);
693
- state.pos += verLen;
694
- expectTag(state, 48, "Expected algorithm identifier");
695
- const algIdLen = parseLength(state);
696
- const algIdStart = state.pos;
697
- return { algIdStart, algIdLength: algIdLen };
698
- }
699
- var parseECAlgorithmIdentifier = (state) => {
700
- const algOid = parseAlgorithmOID(state);
701
- if (bytesEqual(algOid, [43, 101, 110])) {
702
- return "X25519";
703
- }
704
- if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) {
705
- throw new Error("Unsupported key algorithm");
706
- }
707
- expectTag(state, 6, "Expected curve OID");
708
- const curveOidLen = parseLength(state);
709
- const curveOid = getSubarray(state, curveOidLen);
710
- for (const { name, oid } of [
711
- { name: "P-256", oid: [42, 134, 72, 206, 61, 3, 1, 7] },
712
- { name: "P-384", oid: [43, 129, 4, 0, 34] },
713
- { name: "P-521", oid: [43, 129, 4, 0, 35] }
714
- ]) {
715
- if (bytesEqual(curveOid, oid)) {
716
- return name;
717
- }
718
- }
719
- throw new Error("Unsupported named curve");
720
- };
721
- var genericImport = async (keyFormat, keyData, alg, options) => {
722
- let algorithm;
723
- let keyUsages;
724
- const isPublic = keyFormat === "spki";
725
- const getSigUsages = () => isPublic ? ["verify"] : ["sign"];
726
- const getEncUsages = () => isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
727
- switch (alg) {
728
- case "PS256":
729
- case "PS384":
730
- case "PS512":
731
- algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` };
732
- keyUsages = getSigUsages();
733
- break;
734
- case "RS256":
735
- case "RS384":
736
- case "RS512":
737
- algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` };
738
- keyUsages = getSigUsages();
739
- break;
740
- case "RSA-OAEP":
741
- case "RSA-OAEP-256":
742
- case "RSA-OAEP-384":
743
- case "RSA-OAEP-512":
744
- algorithm = {
745
- name: "RSA-OAEP",
746
- hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`
747
- };
748
- keyUsages = getEncUsages();
749
- break;
750
- case "ES256":
751
- case "ES384":
752
- case "ES512": {
753
- const curveMap = { ES256: "P-256", ES384: "P-384", ES512: "P-521" };
754
- algorithm = { name: "ECDSA", namedCurve: curveMap[alg] };
755
- keyUsages = getSigUsages();
756
- break;
757
- }
758
- case "ECDH-ES":
759
- case "ECDH-ES+A128KW":
760
- case "ECDH-ES+A192KW":
761
- case "ECDH-ES+A256KW": {
762
- try {
763
- const namedCurve = options.getNamedCurve(keyData);
764
- algorithm = namedCurve === "X25519" ? { name: "X25519" } : { name: "ECDH", namedCurve };
765
- } catch (cause) {
766
- throw new JOSENotSupported("Invalid or unsupported key format");
767
- }
768
- keyUsages = isPublic ? [] : ["deriveBits"];
769
- break;
770
- }
771
- case "Ed25519":
772
- case "EdDSA":
773
- algorithm = { name: "Ed25519" };
774
- keyUsages = getSigUsages();
775
- break;
776
- case "ML-DSA-44":
777
- case "ML-DSA-65":
778
- case "ML-DSA-87":
779
- algorithm = { name: alg };
780
- keyUsages = getSigUsages();
781
- break;
782
- default:
783
- throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
784
- }
785
- return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
786
- };
787
- var processPEMData = (pem, pattern) => {
788
- return decodeBase64(pem.replace(pattern, ""));
789
- };
790
- var fromPKCS8 = (pem, alg, options) => {
791
- const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
792
- let opts = options;
793
- if (alg?.startsWith?.("ECDH-ES")) {
794
- opts ||= {};
795
- opts.getNamedCurve = (keyData2) => {
796
- const state = createASN1State(keyData2);
797
- parsePKCS8Header(state);
798
- return parseECAlgorithmIdentifier(state);
799
- };
800
- }
801
- return genericImport("pkcs8", keyData, alg, opts);
802
- };
803
-
804
- // node_modules/jose/dist/webapi/key/import.js
805
- async function importPKCS8(pkcs8, alg, options) {
806
- if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
807
- throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
808
- }
809
- return fromPKCS8(pkcs8, alg, options);
810
- }
811
- async function importJWK(jwk, alg, options) {
812
- if (!isObject(jwk)) {
813
- throw new TypeError("JWK must be an object");
814
- }
815
- let ext;
816
- alg ??= jwk.alg;
817
- ext ??= options?.extractable ?? jwk.ext;
818
- switch (jwk.kty) {
819
- case "oct":
820
- if (typeof jwk.k !== "string" || !jwk.k) {
821
- throw new TypeError('missing "k" (Key Value) Parameter value');
822
- }
823
- return decode(jwk.k);
824
- case "RSA":
825
- if ("oth" in jwk && jwk.oth !== void 0) {
826
- throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
827
- }
828
- return jwkToKey({ ...jwk, alg, ext });
829
- case "AKP": {
830
- if (typeof jwk.alg !== "string" || !jwk.alg) {
831
- throw new TypeError('missing "alg" (Algorithm) Parameter value');
832
- }
833
- if (alg !== void 0 && alg !== jwk.alg) {
834
- throw new TypeError("JWK alg and alg option value mismatch");
835
- }
836
- return jwkToKey({ ...jwk, ext });
837
- }
838
- case "EC":
839
- case "OKP":
840
- return jwkToKey({ ...jwk, alg, ext });
841
- default:
842
- throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
843
- }
844
- }
845
-
846
- // node_modules/jose/dist/webapi/lib/validate_crit.js
847
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
848
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
849
- throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
850
- }
851
- if (!protectedHeader || protectedHeader.crit === void 0) {
852
- return /* @__PURE__ */ new Set();
853
- }
854
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
855
- throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
856
- }
857
- let recognized;
858
- if (recognizedOption !== void 0) {
859
- recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
860
- } else {
861
- recognized = recognizedDefault;
862
- }
863
- for (const parameter of protectedHeader.crit) {
864
- if (!recognized.has(parameter)) {
865
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
866
- }
867
- if (joseHeader[parameter] === void 0) {
868
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
869
- }
870
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
871
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
872
- }
873
- }
874
- return new Set(protectedHeader.crit);
875
- }
876
-
877
- // node_modules/jose/dist/webapi/lib/check_key_type.js
878
- var tag = (key) => key?.[Symbol.toStringTag];
879
- var jwkMatchesOp = (alg, key, usage) => {
880
- if (key.use !== void 0) {
881
- let expected;
882
- switch (usage) {
883
- case "sign":
884
- case "verify":
885
- expected = "sig";
886
- break;
887
- case "encrypt":
888
- case "decrypt":
889
- expected = "enc";
890
- break;
891
- }
892
- if (key.use !== expected) {
893
- throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
894
- }
895
- }
896
- if (key.alg !== void 0 && key.alg !== alg) {
897
- throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
898
- }
899
- if (Array.isArray(key.key_ops)) {
900
- let expectedKeyOp;
901
- switch (true) {
902
- case (usage === "sign" || usage === "verify"):
903
- case alg === "dir":
904
- case alg.includes("CBC-HS"):
905
- expectedKeyOp = usage;
906
- break;
907
- case alg.startsWith("PBES2"):
908
- expectedKeyOp = "deriveBits";
909
- break;
910
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
911
- if (!alg.includes("GCM") && alg.endsWith("KW")) {
912
- expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
913
- } else {
914
- expectedKeyOp = usage;
915
- }
916
- break;
917
- case (usage === "encrypt" && alg.startsWith("RSA")):
918
- expectedKeyOp = "wrapKey";
919
- break;
920
- case usage === "decrypt":
921
- expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
922
- break;
923
- }
924
- if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
925
- throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
926
- }
927
- }
928
- return true;
929
- };
930
- var symmetricTypeCheck = (alg, key, usage) => {
931
- if (key instanceof Uint8Array)
932
- return;
933
- if (isJWK(key)) {
934
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
935
- return;
936
- throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
937
- }
938
- if (!isKeyLike(key)) {
939
- throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
940
- }
941
- if (key.type !== "secret") {
942
- throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
943
- }
944
- };
945
- var asymmetricTypeCheck = (alg, key, usage) => {
946
- if (isJWK(key)) {
947
- switch (usage) {
948
- case "decrypt":
949
- case "sign":
950
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
951
- return;
952
- throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
953
- case "encrypt":
954
- case "verify":
955
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
956
- return;
957
- throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
958
- }
959
- }
960
- if (!isKeyLike(key)) {
961
- throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
962
- }
963
- if (key.type === "secret") {
964
- throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
965
- }
966
- if (key.type === "public") {
967
- switch (usage) {
968
- case "sign":
969
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
970
- case "decrypt":
971
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
972
- }
973
- }
974
- if (key.type === "private") {
975
- switch (usage) {
976
- case "verify":
977
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
978
- case "encrypt":
979
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
980
- }
981
- }
982
- };
983
- function checkKeyType(alg, key, usage) {
984
- switch (alg.substring(0, 2)) {
985
- case "A1":
986
- case "A2":
987
- case "di":
988
- case "HS":
989
- case "PB":
990
- symmetricTypeCheck(alg, key, usage);
991
- break;
992
- default:
993
- asymmetricTypeCheck(alg, key, usage);
994
- }
995
- }
996
-
997
- // node_modules/jose/dist/webapi/lib/jwt_claims_set.js
998
- var epoch = (date) => Math.floor(date.getTime() / 1e3);
999
- var minute = 60;
1000
- var hour = minute * 60;
1001
- var day = hour * 24;
1002
- var week = day * 7;
1003
- var year = day * 365.25;
1004
- var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
1005
- function secs(str) {
1006
- const matched = REGEX.exec(str);
1007
- if (!matched || matched[4] && matched[1]) {
1008
- throw new TypeError("Invalid time period format");
1009
- }
1010
- const value = parseFloat(matched[2]);
1011
- const unit = matched[3].toLowerCase();
1012
- let numericDate;
1013
- switch (unit) {
1014
- case "sec":
1015
- case "secs":
1016
- case "second":
1017
- case "seconds":
1018
- case "s":
1019
- numericDate = Math.round(value);
1020
- break;
1021
- case "minute":
1022
- case "minutes":
1023
- case "min":
1024
- case "mins":
1025
- case "m":
1026
- numericDate = Math.round(value * minute);
1027
- break;
1028
- case "hour":
1029
- case "hours":
1030
- case "hr":
1031
- case "hrs":
1032
- case "h":
1033
- numericDate = Math.round(value * hour);
1034
- break;
1035
- case "day":
1036
- case "days":
1037
- case "d":
1038
- numericDate = Math.round(value * day);
1039
- break;
1040
- case "week":
1041
- case "weeks":
1042
- case "w":
1043
- numericDate = Math.round(value * week);
1044
- break;
1045
- default:
1046
- numericDate = Math.round(value * year);
1047
- break;
1048
- }
1049
- if (matched[1] === "-" || matched[4] === "ago") {
1050
- return -numericDate;
1051
- }
1052
- return numericDate;
1053
- }
1054
- function validateInput(label, input) {
1055
- if (!Number.isFinite(input)) {
1056
- throw new TypeError(`Invalid ${label} input`);
1057
- }
1058
- return input;
1059
- }
1060
- var JWTClaimsBuilder = class {
1061
- #payload;
1062
- constructor(payload) {
1063
- if (!isObject(payload)) {
1064
- throw new TypeError("JWT Claims Set MUST be an object");
1065
- }
1066
- this.#payload = structuredClone(payload);
1067
- }
1068
- data() {
1069
- return encoder.encode(JSON.stringify(this.#payload));
1070
- }
1071
- get iss() {
1072
- return this.#payload.iss;
1073
- }
1074
- set iss(value) {
1075
- this.#payload.iss = value;
1076
- }
1077
- get sub() {
1078
- return this.#payload.sub;
1079
- }
1080
- set sub(value) {
1081
- this.#payload.sub = value;
1082
- }
1083
- get aud() {
1084
- return this.#payload.aud;
1085
- }
1086
- set aud(value) {
1087
- this.#payload.aud = value;
1088
- }
1089
- set jti(value) {
1090
- this.#payload.jti = value;
1091
- }
1092
- set nbf(value) {
1093
- if (typeof value === "number") {
1094
- this.#payload.nbf = validateInput("setNotBefore", value);
1095
- } else if (value instanceof Date) {
1096
- this.#payload.nbf = validateInput("setNotBefore", epoch(value));
1097
- } else {
1098
- this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value);
1099
- }
1100
- }
1101
- set exp(value) {
1102
- if (typeof value === "number") {
1103
- this.#payload.exp = validateInput("setExpirationTime", value);
1104
- } else if (value instanceof Date) {
1105
- this.#payload.exp = validateInput("setExpirationTime", epoch(value));
1106
- } else {
1107
- this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value);
1108
- }
1109
- }
1110
- set iat(value) {
1111
- if (value === void 0) {
1112
- this.#payload.iat = epoch(/* @__PURE__ */ new Date());
1113
- } else if (value instanceof Date) {
1114
- this.#payload.iat = validateInput("setIssuedAt", epoch(value));
1115
- } else if (typeof value === "string") {
1116
- this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value));
1117
- } else {
1118
- this.#payload.iat = validateInput("setIssuedAt", value);
1119
- }
1120
- }
1121
- };
1122
-
1123
- // node_modules/jose/dist/webapi/jws/flattened/sign.js
1124
- var FlattenedSign = class {
1125
- #payload;
1126
- #protectedHeader;
1127
- #unprotectedHeader;
1128
- constructor(payload) {
1129
- if (!(payload instanceof Uint8Array)) {
1130
- throw new TypeError("payload must be an instance of Uint8Array");
1131
- }
1132
- this.#payload = payload;
1133
- }
1134
- setProtectedHeader(protectedHeader) {
1135
- assertNotSet(this.#protectedHeader, "setProtectedHeader");
1136
- this.#protectedHeader = protectedHeader;
1137
- return this;
1138
- }
1139
- setUnprotectedHeader(unprotectedHeader) {
1140
- assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
1141
- this.#unprotectedHeader = unprotectedHeader;
1142
- return this;
1143
- }
1144
- async sign(key, options) {
1145
- if (!this.#protectedHeader && !this.#unprotectedHeader) {
1146
- throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
1147
- }
1148
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {
1149
- throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1150
- }
1151
- const joseHeader = {
1152
- ...this.#protectedHeader,
1153
- ...this.#unprotectedHeader
1154
- };
1155
- const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
1156
- let b64 = true;
1157
- if (extensions.has("b64")) {
1158
- b64 = this.#protectedHeader.b64;
1159
- if (typeof b64 !== "boolean") {
1160
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
1161
- }
1162
- }
1163
- const { alg } = joseHeader;
1164
- if (typeof alg !== "string" || !alg) {
1165
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
1166
- }
1167
- checkKeyType(alg, key, "sign");
1168
- let payloadS;
1169
- let payloadB;
1170
- if (b64) {
1171
- payloadS = encode2(this.#payload);
1172
- payloadB = encode(payloadS);
1173
- } else {
1174
- payloadB = this.#payload;
1175
- payloadS = "";
1176
- }
1177
- let protectedHeaderString;
1178
- let protectedHeaderBytes;
1179
- if (this.#protectedHeader) {
1180
- protectedHeaderString = encode2(JSON.stringify(this.#protectedHeader));
1181
- protectedHeaderBytes = encode(protectedHeaderString);
1182
- } else {
1183
- protectedHeaderString = "";
1184
- protectedHeaderBytes = new Uint8Array();
1185
- }
1186
- const data = concat(protectedHeaderBytes, encode("."), payloadB);
1187
- const k = await normalizeKey(key, alg);
1188
- const signature = await sign(alg, k, data);
1189
- const jws = {
1190
- signature: encode2(signature),
1191
- payload: payloadS
1192
- };
1193
- if (this.#unprotectedHeader) {
1194
- jws.header = this.#unprotectedHeader;
1195
- }
1196
- if (this.#protectedHeader) {
1197
- jws.protected = protectedHeaderString;
1198
- }
1199
- return jws;
1200
- }
1201
- };
1202
-
1203
- // node_modules/jose/dist/webapi/jws/compact/sign.js
1204
- var CompactSign = class {
1205
- #flattened;
1206
- constructor(payload) {
1207
- this.#flattened = new FlattenedSign(payload);
1208
- }
1209
- setProtectedHeader(protectedHeader) {
1210
- this.#flattened.setProtectedHeader(protectedHeader);
1211
- return this;
1212
- }
1213
- async sign(key, options) {
1214
- const jws = await this.#flattened.sign(key, options);
1215
- if (jws.payload === void 0) {
1216
- throw new TypeError("use the flattened module for creating JWS with b64: false");
1217
- }
1218
- return `${jws.protected}.${jws.payload}.${jws.signature}`;
1219
- }
1220
- };
1221
-
1222
- // node_modules/jose/dist/webapi/jwt/sign.js
1223
- var SignJWT = class {
1224
- #protectedHeader;
1225
- #jwt;
1226
- constructor(payload = {}) {
1227
- this.#jwt = new JWTClaimsBuilder(payload);
1228
- }
1229
- setIssuer(issuer) {
1230
- this.#jwt.iss = issuer;
1231
- return this;
1232
- }
1233
- setSubject(subject) {
1234
- this.#jwt.sub = subject;
1235
- return this;
1236
- }
1237
- setAudience(audience) {
1238
- this.#jwt.aud = audience;
1239
- return this;
1240
- }
1241
- setJti(jwtId) {
1242
- this.#jwt.jti = jwtId;
1243
- return this;
1244
- }
1245
- setNotBefore(input) {
1246
- this.#jwt.nbf = input;
1247
- return this;
1248
- }
1249
- setExpirationTime(input) {
1250
- this.#jwt.exp = input;
1251
- return this;
1252
- }
1253
- setIssuedAt(input) {
1254
- this.#jwt.iat = input;
1255
- return this;
1256
- }
1257
- setProtectedHeader(protectedHeader) {
1258
- this.#protectedHeader = protectedHeader;
1259
- return this;
1260
- }
1261
- async sign(key, options) {
1262
- const sig = new CompactSign(this.#jwt.data());
1263
- sig.setProtectedHeader(this.#protectedHeader);
1264
- if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) {
1265
- throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1266
- }
1267
- return sig.sign(key, options);
1268
- }
1269
- };
1270
-
1271
- // src/lib/x402/facilitator.ts
1272
- var AUTH_HEADER_TTL_MS = 6e4;
1273
- var AUTH_TOKEN_TTL_SECONDS = 120;
1274
- var FACILITATOR_PATHS = {
1275
- verify: "POST",
1276
- settle: "POST",
1277
- supported: "GET"
1278
- };
1279
- function createX402FacilitatorAuthHeaders(config) {
1280
- const auth = config.facilitatorAuth;
1281
- if (!auth) return void 0;
1282
- const facilitator = new URL(config.facilitator ?? X402_DEFAULT_FACILITATOR);
1283
- const basePath = facilitator.pathname.replace(/\/+$/, "");
1284
- let cached;
1285
- return async () => {
1286
- const nowMs = Date.now();
1287
- if (cached && nowMs < cached.refreshAtMs) return cached.headers;
1288
- const entries = await Promise.all(
1289
- Object.entries(FACILITATOR_PATHS).map(async ([path, method]) => {
1290
- const requestPath = `${basePath}/${path}`;
1291
- const jwt = await generateCdpJwt(
1292
- auth.keyId,
1293
- auth.keySecret,
1294
- `${method} ${facilitator.host}${requestPath}`
1295
- );
1296
- return [path, { Authorization: `Bearer ${jwt}` }];
1297
- })
1298
- );
1299
- const headers = Object.fromEntries(entries);
1300
- cached = { headers, refreshAtMs: nowMs + AUTH_HEADER_TTL_MS };
1301
- return headers;
1302
- };
1303
- }
1304
- async function generateCdpJwt(keyId, keySecret, uri) {
1305
- const now = Math.floor(Date.now() / 1e3);
1306
- const nonce = randomBytes(16).toString("hex");
1307
- const claims = { sub: keyId, iss: "cdp", uris: [uri] };
1308
- try {
1309
- const ecKey = await importPKCS8(normalizeEs256KeySecret(keySecret), "ES256");
1310
- return await new SignJWT(claims).setProtectedHeader({ alg: "ES256", kid: keyId, typ: "JWT", nonce }).setIssuedAt(now).setNotBefore(now).setExpirationTime(now + AUTH_TOKEN_TTL_SECONDS).sign(ecKey);
1311
- } catch {
1312
- }
1313
- const decoded = Buffer.from(keySecret, "base64");
1314
- if (decoded.length !== 64) {
1315
- throw new Error("Invalid CDP key secret: expected an ES256 PEM or base64 Ed25519 key");
1316
- }
1317
- const jwk = {
1318
- kty: "OKP",
1319
- crv: "Ed25519",
1320
- d: decoded.subarray(0, 32).toString("base64url"),
1321
- x: decoded.subarray(32).toString("base64url")
1322
- };
1323
- const edKey = await importJWK(jwk, "EdDSA");
1324
- return new SignJWT(claims).setProtectedHeader({ alg: "EdDSA", kid: keyId, typ: "JWT", nonce }).setIssuedAt(now).setNotBefore(now).setExpirationTime(now + AUTH_TOKEN_TTL_SECONDS).sign(edKey);
1325
- }
1326
- function normalizeEs256KeySecret(keySecret) {
1327
- if (!keySecret.includes("-----BEGIN EC PRIVATE KEY-----")) return keySecret;
1328
- return createPrivateKey(keySecret).export({ format: "pem", type: "pkcs8" });
1329
- }
1330
-
1331
- // src/lib/x402/spec.ts
1332
- var X402_VERSION = 2;
1333
- var X402_V1_VERSION = 1;
1334
- var X402_DEFAULT_NETWORK = "eip155:8453";
1335
- var X402_EXACT_SCHEME = "exact";
1336
- var X402_BATCH_SETTLEMENT_SCHEME = "batch-settlement";
1337
- function buildPaymentRequirements(opts) {
1338
- const { x402Config, requiredUsdcMicro, resource, description, mimeType } = opts;
1339
- const version = opts.version ?? X402_VERSION;
1340
- const network = version === X402_V1_VERSION ? caip2ToX402Network(x402Config.network) : x402Config.network;
1341
- const usdcContract = usdcContractByCaip2(x402Config.network);
1342
- const configuredAsset = x402Config.asset;
1343
- const asset = version === X402_VERSION && configuredAsset?.toUpperCase() === "USDC" ? usdcContract ?? configuredAsset : configuredAsset ?? usdcContract ?? "USDC";
1344
- const extra = paymentRequirementExtra(x402Config.network, asset, usdcContract, version);
1345
- if (version === X402_VERSION) {
1346
- return {
1347
- scheme: "exact",
1348
- network,
1349
- amount: requiredUsdcMicro.toString(),
1350
- payTo: x402Config.payTo,
1351
- asset,
1352
- maxTimeoutSeconds: 60,
1353
- extra
1354
- };
1355
- }
1356
- return {
1357
- scheme: "exact",
1358
- network,
1359
- maxAmountRequired: requiredUsdcMicro.toString(),
1360
- resource,
1361
- description: description ?? x402Config.description ?? "",
1362
- mimeType: mimeType ?? "application/json",
1363
- payTo: x402Config.payTo,
1364
- asset,
1365
- maxTimeoutSeconds: 60,
1366
- ...Object.keys(extra).length > 0 ? { extra } : {}
1367
- };
1368
- }
1369
- function buildPaymentRequiredV2(opts) {
1370
- const description = opts.description ?? opts.x402Config.description ?? "";
1371
- const mimeType = opts.mimeType ?? "application/json";
1372
- return {
1373
- x402Version: X402_VERSION,
1374
- ...opts.error ? { error: opts.error } : {},
1375
- resource: {
1376
- url: opts.resource,
1377
- ...description ? { description } : {},
1378
- ...mimeType ? { mimeType } : {}
1379
- },
1380
- accepts: [buildPaymentRequirements({ ...opts, version: X402_VERSION })],
1381
- extensions: {}
1382
- };
1383
- }
1384
- function paymentRequiredV2FromV1(requirements, error) {
1385
- const first = requirements.at(0);
1386
- if (!first) throw new Error("Cannot build PAYMENT-REQUIRED without requirements");
1387
- return {
1388
- x402Version: X402_VERSION,
1389
- ...error ? { error } : {},
1390
- resource: {
1391
- url: first.resource,
1392
- ...first.description ? { description: first.description } : {},
1393
- ...first.mimeType ? { mimeType: first.mimeType } : {}
1394
- },
1395
- accepts: requirements.map((requirement) => {
1396
- const network = x402NetworkBySlug(requirement.network)?.caip2 ?? requirement.network;
1397
- const usdcContract = usdcContractByCaip2(network);
1398
- const asset = requirement.asset.toUpperCase() === "USDC" ? usdcContract ?? requirement.asset : requirement.asset;
1399
- return {
1400
- scheme: "exact",
1401
- network,
1402
- amount: requirement.maxAmountRequired,
1403
- asset,
1404
- payTo: requirement.payTo,
1405
- maxTimeoutSeconds: requirement.maxTimeoutSeconds,
1406
- extra: {
1407
- ...requirement.extra,
1408
- ...paymentRequirementExtra(network, asset, usdcContract, X402_VERSION),
1409
- assetTransferMethod: "eip3009"
1410
- }
1411
- };
1412
- }),
1413
- extensions: {}
1414
- };
1415
- }
1416
- function caip2ToX402Network(network) {
1417
- return x402NetworkByCaip2(network)?.slug ?? network;
1418
- }
1419
- function x402NetworkToCaip2(network) {
1420
- return x402NetworkBySlug(network)?.caip2 ?? network;
1421
- }
1422
- function chainIdFromCaip2(network) {
1423
- const parts = network.split(":");
1424
- return Number.parseInt(parts[1] ?? "8453", 10);
1425
- }
1426
- function usdcContractFor(networkSlug) {
1427
- return x402NetworkBySlug(networkSlug)?.usdc;
1428
- }
1429
- function usdcContractByCaip2(caip2) {
1430
- return x402NetworkByCaip2(caip2)?.usdc;
1431
- }
1432
- function usdcDomainNameFor(networkSlug) {
1433
- return x402NetworkBySlug(networkSlug)?.domainName;
1434
- }
1435
- function usdcDomainVersionFor(networkSlug) {
1436
- return x402NetworkBySlug(networkSlug)?.domainVersion;
1437
- }
1438
- function decodePayment(header) {
1439
- const decoded = Buffer.from(header, "base64").toString("utf-8");
1440
- const parsed = JSON.parse(decoded);
1441
- if (!parsed || typeof parsed !== "object") throw new Error("Invalid payment header shape");
1442
- const version = parsed.x402Version;
1443
- const scheme = version === X402_V1_VERSION ? parsed.scheme : version === X402_VERSION && isRecord(parsed.accepted) ? parsed.accepted.scheme : void 0;
1444
- if (typeof scheme !== "string") throw new Error("Invalid payment scheme");
1445
- const decoder2 = PAYMENT_SCHEME_DECODERS[scheme];
1446
- if (!decoder2) throw new Error(`Unsupported x402 payment scheme: ${scheme}`);
1447
- return decoder2(parsed);
1448
- }
1449
- function encodePayment(payload) {
1450
- return Buffer.from(JSON.stringify(payload), "utf-8").toString("base64");
1451
- }
1452
- function encodePaymentRequiredHeader(required) {
1453
- return Buffer.from(JSON.stringify(required), "utf-8").toString("base64");
1454
- }
1455
- function decodePaymentRequiredHeader(header) {
1456
- const parsed = JSON.parse(Buffer.from(header, "base64").toString("utf-8"));
1457
- if (!isRecord(parsed) || parsed.x402Version !== X402_VERSION || !isRecord(parsed.resource)) {
1458
- throw new Error("Invalid PAYMENT-REQUIRED header shape");
1459
- }
1460
- if (typeof parsed.resource.url !== "string" || !Array.isArray(parsed.accepts)) {
1461
- throw new Error("Invalid PAYMENT-REQUIRED header shape");
1462
- }
1463
- for (const requirement of parsed.accepts) validateV2Requirements(requirement);
1464
- return parsed;
1465
- }
1466
- function exactEvmAuthorization(payload) {
1467
- return payload.payload.authorization;
1468
- }
1469
- function encodeSettleResponseHeader(response) {
1470
- return Buffer.from(JSON.stringify(response), "utf-8").toString("base64");
1471
- }
1472
- async function verifyWithFacilitator(payload, requirements, config = {}, createAuthHeaders = createX402FacilitatorAuthHeaders(config)) {
1473
- const facilitator = config.facilitator ?? X402_DEFAULT_FACILITATOR;
1474
- const url = facilitator.replace(/\/$/, "") + "/verify";
1475
- return callerLoggers.x402.span(
1476
- "x402.verify_with_facilitator",
1477
- { facilitator_url: url },
1478
- async () => {
1479
- const authHeaders = (await createAuthHeaders?.())?.verify ?? {};
1480
- const res = await fetch(url, {
1481
- method: "POST",
1482
- headers: { "Content-Type": "application/json", ...authHeaders },
1483
- body: JSON.stringify({
1484
- x402Version: payload.x402Version,
1485
- paymentPayload: payload,
1486
- paymentRequirements: requirements
1487
- })
1488
- });
1489
- if (!res.ok) {
1490
- const rejection = await readFacilitatorRejection(res);
1491
- if (rejection?.isValid === false && typeof rejection.invalidReason === "string" && rejection.invalidReason.length > 0) {
1492
- return rejection;
1493
- }
1494
- return { isValid: false, invalidReason: `facilitator_status_${res.status}` };
1495
- }
1496
- const data = await res.json();
1497
- callerLoggers.x402.info("x402.verify_with_facilitator.result", { is_valid: data.isValid });
1498
- return data;
1499
- }
1500
- );
1501
- }
1502
- async function settleWithFacilitator(payload, requirements, config = {}, createAuthHeaders = createX402FacilitatorAuthHeaders(config)) {
1503
- const facilitator = config.facilitator ?? X402_DEFAULT_FACILITATOR;
1504
- const url = facilitator.replace(/\/$/, "") + "/settle";
1505
- return callerLoggers.x402.span(
1506
- "x402.settle_with_facilitator",
1507
- { facilitator_url: url },
1508
- async () => {
1509
- const authHeaders = (await createAuthHeaders?.())?.settle ?? {};
1510
- const res = await fetch(url, {
1511
- method: "POST",
1512
- headers: { "Content-Type": "application/json", ...authHeaders },
1513
- body: JSON.stringify({
1514
- x402Version: payload.x402Version,
1515
- paymentPayload: payload,
1516
- paymentRequirements: requirements
1517
- })
1518
- });
1519
- if (!res.ok) {
1520
- const rejection = await readFacilitatorRejection(res);
1521
- if (rejection?.success === false && typeof rejection.errorReason === "string" && rejection.errorReason.length > 0) {
1522
- return rejection;
1523
- }
1524
- return { success: false, errorReason: `facilitator_status_${res.status}` };
1525
- }
1526
- const data = await res.json();
1527
- callerLoggers.x402.info("x402.settle_with_facilitator.result", {
1528
- success: data.success,
1529
- tx_hash: data.transaction
1530
- });
1531
- return data;
1532
- }
1533
- );
1534
- }
1535
- async function readFacilitatorRejection(res) {
1536
- if (res.status !== 400) return null;
1537
- try {
1538
- const body = await res.json();
1539
- return isRecord(body) ? body : null;
1540
- } catch {
1541
- return null;
1542
- }
1543
- }
1544
- var PAYMENT_SCHEME_DECODERS = {
1545
- exact: decodeExactPayment
1546
- };
1547
- function decodeExactPayment(parsed) {
1548
- validateExactEvmPayload(parsed.payload);
1549
- if (parsed.x402Version === X402_V1_VERSION) {
1550
- if (parsed.scheme !== "exact" || typeof parsed.network !== "string") {
1551
- throw new Error("Invalid x402 v1 exact payload");
1552
- }
1553
- return parsed;
1554
- }
1555
- if (parsed.x402Version === X402_VERSION) {
1556
- validateV2Requirements(parsed.accepted);
1557
- if (parsed.resource !== void 0 && !isResourceInfo(parsed.resource)) {
1558
- throw new Error("Invalid x402 v2 resource");
1559
- }
1560
- if (parsed.extensions !== void 0 && !isRecord(parsed.extensions)) {
1561
- throw new Error("Invalid x402 v2 extensions");
1562
- }
1563
- return parsed;
1564
- }
1565
- throw new Error(`Unsupported x402 version: ${String(parsed.x402Version)}`);
1566
- }
1567
- function validateV2Requirements(value) {
1568
- if (!isRecord(value) || typeof value.scheme !== "string" || typeof value.network !== "string" || typeof value.amount !== "string" || typeof value.asset !== "string" || typeof value.payTo !== "string" || typeof value.maxTimeoutSeconds !== "number" || !isOptionalRecord(value.extra)) {
1569
- throw new Error("Invalid x402 v2 payment requirements");
1570
- }
1571
- }
1572
- function validateExactEvmPayload(value) {
1573
- if (!isRecord(value) || typeof value.signature !== "string" || !isRecord(value.authorization)) {
1574
- throw new Error("Invalid exact EVM payload");
1575
- }
1576
- const authorization = value.authorization;
1577
- for (const field of ["from", "to", "value", "validAfter", "validBefore", "nonce"]) {
1578
- if (typeof authorization[field] !== "string") throw new Error("Invalid exact authorization");
1579
- }
1580
- }
1581
- function paymentRequirementExtra(caip2, asset, usdcContract, version) {
1582
- if (asset.toLowerCase() !== usdcContract?.toLowerCase()) return {};
1583
- const network = x402NetworkByCaip2(caip2);
1584
- if (!network) return {};
1585
- return {
1586
- ...version === X402_VERSION ? { assetTransferMethod: "eip3009" } : {},
1587
- name: network.domainName,
1588
- version: network.domainVersion
1589
- };
1590
- }
1591
- function isResourceInfo(value) {
1592
- return isRecord(value) && typeof value.url === "string";
1593
- }
1594
- function isRecord(value) {
1595
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1596
- }
1597
- function isOptionalRecord(value) {
1598
- return value === void 0 || value === null || isRecord(value);
1599
- }
1600
-
1601
- // src/lib/x402/wallet.ts
1602
- function loadX402Wallet() {
1603
- const config = loadConfig();
1604
- const x402 = config?.x402;
1605
- const privateKey = x402?.privateKey;
1606
- if (!privateKey || !isValidEvmPrivateKey(privateKey)) return null;
1607
- return {
1608
- privateKey,
1609
- address: "",
1610
- network: x402.network ?? X402_DEFAULT_NETWORK
1611
- };
1612
- }
1613
- async function ensureAddress(wallet) {
1614
- if (!isValidEvmPrivateKey(wallet.privateKey)) throw invalidX402PrivateKey();
1615
- if (wallet.address) return wallet;
1616
- const { privateKeyToAccount } = await import("./accounts-S747UW3A.js");
1617
- const account = privateKeyToAccount(wallet.privateKey);
1618
- return { ...wallet, address: account.address };
1619
- }
1620
- async function connectedX402Payer() {
1621
- const wallet = loadX402Wallet();
1622
- if (!wallet) return null;
1623
- return (await ensureAddress(wallet)).address;
1624
- }
1625
- async function generateX402PrivateKey() {
1626
- const { generatePrivateKey } = await import("./accounts-S747UW3A.js");
1627
- return generatePrivateKey();
1628
- }
1629
- async function repinX402WalletNetwork(network) {
1630
- assertSupportedX402Network(network);
1631
- return withX402ChannelLock(async () => {
1632
- const { previous } = await updateConfig({
1633
- reason: "x402_wallet_repin",
1634
- patch: (current) => {
1635
- if (!current) throw new DvmError("no_config", "No config found.", "Run: dvm init");
1636
- const privateKey = current.x402?.privateKey;
1637
- if (privateKey === void 0) throw x402WalletMissingError();
1638
- if (!isValidEvmPrivateKey(privateKey)) throw invalidX402PrivateKey();
1639
- return { set: { x402: { privateKey, network } } };
1640
- }
1641
- });
1642
- const stored = previous?.x402;
1643
- if (stored === void 0) throw x402WalletMissingError();
1644
- if (!isValidEvmPrivateKey(stored.privateKey)) throw invalidX402PrivateKey();
1645
- const { privateKeyToAccount } = await import("./accounts-S747UW3A.js");
1646
- return {
1647
- address: privateKeyToAccount(stored.privateKey).address,
1648
- previousNetwork: stored.network ?? X402_DEFAULT_NETWORK,
1649
- network
1650
- };
1651
- });
1652
- }
1653
- async function saveX402Wallet(privateKey, network) {
1654
- if (network !== void 0) assertSupportedX402Network(network);
1655
- if (!isValidEvmPrivateKey(privateKey)) throw invalidX402PrivateKey();
1656
- const { privateKeyToAccount } = await import("./accounts-S747UW3A.js");
1657
- const account = privateKeyToAccount(privateKey);
1658
- let resolved;
1659
- await updateConfig({
1660
- reason: "x402_wallet_connect",
1661
- patch: (current) => {
1662
- resolved = network ?? current?.x402?.network;
1663
- return {
1664
- set: { x402: resolved === void 0 ? { privateKey } : { privateKey, network: resolved } }
1665
- };
1666
- }
1667
- });
1668
- return { address: account.address, network: resolved ?? X402_DEFAULT_NETWORK };
1669
- }
1670
- async function removeX402Wallet() {
1671
- await updateConfig({
1672
- reason: "x402_wallet_disconnect",
1673
- authorize: authorizeProtectedRemoval("x402"),
1674
- patch: () => ({ unset: ["x402"] })
1675
- });
1676
- }
1677
- function invalidX402PrivateKey() {
1678
- return new DvmError(
1679
- "invalid_key",
1680
- "Invalid secp256k1 private key.",
1681
- "Reconnect with `dvm wallet x402-connect --key-file <path>`, set DVM_X402_KEY, or pipe a valid 0x-prefixed 32-byte secp256k1 private key through stdin."
1682
- );
1683
- }
1684
- function x402WalletMissingError() {
1685
- return new DvmError(
1686
- "x402_wallet_missing",
1687
- "No x402 wallet is connected.",
1688
- "Run 'dvm wallet x402-connect' to create one, or add --key-file <path> to import a key you already hold."
1689
- );
1690
- }
1691
- async function getX402Balance(wallet) {
1692
- const w = await ensureAddress(wallet);
1693
- const spec = x402NetworkByCaip2(w.network);
1694
- if (!spec) {
1695
- throw new DvmError(
1696
- "x402_unsupported_network",
1697
- `The x402 wallet is configured for ${w.network}, a chain this rail can't settle on.`,
1698
- `${x402SupportedNetworksHint()} Re-pin the connected wallet without handling its key: 'dvm wallet x402-network ${X402_DEFAULT_NETWORK}'.`
1699
- );
1700
- }
1701
- const chains = await import("./chains-PINFXYUE.js");
1702
- const { createPublicClient, http, erc20Abi } = await import("./_esm-M2HUAA3B.js");
1703
- const chain = chains[spec.viemChain];
1704
- const { url: rpcUrl, source: rpcSource } = resolveRpcOverride(
1705
- process.env.DVM_X402_RPC_URL,
1706
- chain?.rpcUrls.default.http[0]
1707
- );
1708
- try {
1709
- const transportOptions = resolveRpcHttpTransportOptions(
1710
- rpcSource,
1711
- process.env.DVM_X402_RPC_HEADERS_JSON
1712
- );
1713
- const client = createPublicClient({
1714
- chain,
1715
- transport: transportOptions ? http(rpcUrl, transportOptions) : http(rpcUrl)
1716
- });
1717
- const balance = await client.readContract({
1718
- address: spec.usdc,
1719
- abi: erc20Abi,
1720
- functionName: "balanceOf",
1721
- args: [w.address]
1722
- });
1723
- return {
1724
- address: w.address,
1725
- usdc: Number(balance) / 1e6,
1726
- network: w.network,
1727
- tokenAddress: spec.usdc,
1728
- // an internal review: redacted here rather than at a display surface, so the clear
1729
- // endpoint never leaves this function on the success path either.
1730
- rpcUrlRedacted: rpcUrl ? redactUrl(rpcUrl) : void 0,
1731
- rpcSource
1732
- };
1733
- } catch (err) {
1734
- const cause = redactUrlsInText(err instanceof Error ? err.message : String(err));
1735
- throw new DvmError(
1736
- "x402_rpc_error",
1737
- `x402 USDC balance lookup on ${spec.label} failed: ${cause}`,
1738
- // A caller who set the override doesn't need to be told to set it. Which
1739
- // knob is theirs to turn depends on whose endpoint this was.
1740
- rpcSource === "override" ? `DVM_X402_RPC_URL sent this read to ${redactUrl(rpcUrl)}. Correct it, or unset it to fall back to ${spec.label}'s bundled endpoint.` : `Verify connectivity to ${spec.label}'s bundled endpoint${rpcUrl ? ` (${redactUrl(rpcUrl)})` : ""}, or send the read somewhere else with DVM_X402_RPC_URL.`
1741
- );
1742
- }
1743
- }
1744
-
1745
- export {
1746
- callerLoggers,
1747
- X402_DEFAULT_FACILITATOR,
1748
- createX402FacilitatorAuthHeaders,
1749
- X402_VERSION,
1750
- X402_V1_VERSION,
1751
- X402_DEFAULT_NETWORK,
1752
- X402_EXACT_SCHEME,
1753
- X402_BATCH_SETTLEMENT_SCHEME,
1754
- buildPaymentRequirements,
1755
- buildPaymentRequiredV2,
1756
- paymentRequiredV2FromV1,
1757
- caip2ToX402Network,
1758
- x402NetworkToCaip2,
1759
- chainIdFromCaip2,
1760
- usdcContractFor,
1761
- usdcContractByCaip2,
1762
- usdcDomainNameFor,
1763
- usdcDomainVersionFor,
1764
- decodePayment,
1765
- encodePayment,
1766
- encodePaymentRequiredHeader,
1767
- decodePaymentRequiredHeader,
1768
- exactEvmAuthorization,
1769
- encodeSettleResponseHeader,
1770
- verifyWithFacilitator,
1771
- settleWithFacilitator,
1772
- loadX402Wallet,
1773
- ensureAddress,
1774
- connectedX402Payer,
1775
- generateX402PrivateKey,
1776
- repinX402WalletNetwork,
1777
- saveX402Wallet,
1778
- removeX402Wallet,
1779
- getX402Balance
1780
- };