@craswitch/mcp-server 0.0.0-stage → 2.0.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.
- package/README.md +99 -2
- package/dist/cli.js +8 -0
- package/dist/core/badge.js +156 -0
- package/dist/core/crypto-utils.js +199 -0
- package/dist/core/enisa.js +909 -0
- package/dist/core/evidence.js +350 -0
- package/dist/core/feeds.js +1175 -0
- package/dist/core/guardrails.js +537 -0
- package/dist/core/index.js +16 -0
- package/dist/core/lockfiles.js +1107 -0
- package/dist/core/sbom.js +191 -0
- package/dist/core/types.js +918 -0
- package/dist/core/vex.js +722 -0
- package/dist/core/x402.js +467 -0
- package/dist/crypto.js +214 -0
- package/dist/http-client.js +336 -0
- package/dist/index.js +17 -0
- package/dist/kev-baseline.js +186 -0
- package/dist/server.js +1075 -0
- package/package.json +39 -4
- package/server.json +63 -0
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP 402 (x402) M2M Base USDC attestation challenge & payment verifier.
|
|
3
|
+
* Supports:
|
|
4
|
+
* 1. Live Coinbase CDP / x402 facilitator HTTP verification (`POST /verify`)
|
|
5
|
+
* 2. Deterministic WebCrypto HMAC-SHA256 test/demo mode for offline/local validation
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { SCHEMA_VERSIONS } from './types.js';
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
base64UrlToBytes,
|
|
12
|
+
bytesToBase64Url,
|
|
13
|
+
bytesToUtf8,
|
|
14
|
+
canonicalJson,
|
|
15
|
+
constantTimeEqual,
|
|
16
|
+
sha256Hex,
|
|
17
|
+
utf8ToBytes,
|
|
18
|
+
} from './crypto-utils.js';
|
|
19
|
+
|
|
20
|
+
export const BASE_MAINNET_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' ;
|
|
21
|
+
export const BASE_SEPOLIA_USDC = '0x036CbD53842c5426634e7929541eC2318f3dCF7e' ;
|
|
22
|
+
export const DEFAULT_X402_PRICE_ATOMIC = '30000' ; // $0.03 USDC (6 decimals)
|
|
23
|
+
export const DEFAULT_X402_FACILITATOR_URL = 'https://x402.org/facilitator' ;
|
|
24
|
+
|
|
25
|
+
const EVM_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Validates a 20-byte hex EVM address (`0x` followed by 40 hexadecimal characters).
|
|
29
|
+
*/
|
|
30
|
+
export function isValidEvmAddress(addr ) {
|
|
31
|
+
return typeof addr === 'string' && EVM_ADDRESS_REGEX.test(addr.trim());
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const DEFAULT_X402_BAZAAR_METADATA = {
|
|
35
|
+
discoverable: true,
|
|
36
|
+
category: 'security-compliance',
|
|
37
|
+
tags: ['eu-cra', 'article-14', 'openvex', 'sbom', 'enisa'],
|
|
38
|
+
inputSchema: {
|
|
39
|
+
type: 'object',
|
|
40
|
+
properties: {
|
|
41
|
+
org: { type: 'string', description: 'Repository organization or owner slug' },
|
|
42
|
+
repo: { type: 'string', description: 'Repository name slug' },
|
|
43
|
+
},
|
|
44
|
+
required: ['org', 'repo'],
|
|
45
|
+
},
|
|
46
|
+
outputSchema: {
|
|
47
|
+
type: 'object',
|
|
48
|
+
properties: {
|
|
49
|
+
status: {
|
|
50
|
+
type: 'string',
|
|
51
|
+
description: 'EU CRA Article 14 4-state triage posture (clean, not_affected, triage_required, confirmed_exploited)',
|
|
52
|
+
},
|
|
53
|
+
repo: { type: 'string', description: 'Repository identifier (org/repo)' },
|
|
54
|
+
vex: { type: 'object', description: 'Ed25519-signed OpenVEX v0.2.0 JSON document' },
|
|
55
|
+
receipt: { type: 'object', description: 'Verified Base USDC x402 payment receipt' },
|
|
56
|
+
},
|
|
57
|
+
required: ['status', 'repo', 'vex', 'receipt'],
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async function computeHmacSha256Base64Url(message , secret ) {
|
|
130
|
+
const key = await crypto.subtle.importKey(
|
|
131
|
+
'raw',
|
|
132
|
+
utf8ToBytes(secret),
|
|
133
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
134
|
+
false,
|
|
135
|
+
['sign'],
|
|
136
|
+
);
|
|
137
|
+
const sig = await crypto.subtle.sign('HMAC', key, utf8ToBytes(message));
|
|
138
|
+
return bytesToBase64Url(new Uint8Array(sig));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Builds an HTTP 402 Payment Required x402 challenge payload and standard response headers
|
|
143
|
+
* for Base USDC micropayments.
|
|
144
|
+
*/
|
|
145
|
+
export function buildX402Challenge(input ) {
|
|
146
|
+
const payTo = input.payTo.trim();
|
|
147
|
+
if (!isValidEvmAddress(payTo)) {
|
|
148
|
+
throw new Error(
|
|
149
|
+
`Invalid x402 payTo EVM address: "${input.payTo}" (expected 0x followed by 40 hex chars)`,
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
const network = input.network ?? 'base';
|
|
153
|
+
const asset = (
|
|
154
|
+
input.asset ?? (network === 'base-sepolia' ? BASE_SEPOLIA_USDC : BASE_MAINNET_USDC)
|
|
155
|
+
).trim();
|
|
156
|
+
if (!isValidEvmAddress(asset)) {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`Invalid x402 asset EVM address: "${asset}" (expected 0x followed by 40 hex chars)`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
const maxAmountRequired = input.maxAmountRequired ?? DEFAULT_X402_PRICE_ATOMIC;
|
|
162
|
+
const maxTimeoutSeconds = input.maxTimeoutSeconds ?? 300;
|
|
163
|
+
|
|
164
|
+
const bazaar = {
|
|
165
|
+
discoverable: input.bazaar?.discoverable ?? DEFAULT_X402_BAZAAR_METADATA.discoverable,
|
|
166
|
+
category: input.bazaar?.category ?? DEFAULT_X402_BAZAAR_METADATA.category,
|
|
167
|
+
tags: input.bazaar?.tags ?? [...DEFAULT_X402_BAZAAR_METADATA.tags],
|
|
168
|
+
inputSchema: input.bazaar?.inputSchema ?? DEFAULT_X402_BAZAAR_METADATA.inputSchema,
|
|
169
|
+
outputSchema: input.bazaar?.outputSchema ?? DEFAULT_X402_BAZAAR_METADATA.outputSchema,
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const challenge = {
|
|
173
|
+
x402Version: SCHEMA_VERSIONS.x402,
|
|
174
|
+
scheme: 'exact',
|
|
175
|
+
network,
|
|
176
|
+
maxAmountRequired,
|
|
177
|
+
resource: input.resource,
|
|
178
|
+
description:
|
|
179
|
+
input.description ?? 'CRA-Switch signed EU CRA Article 14 posture & OpenVEX attestation',
|
|
180
|
+
mimeType: 'application/json',
|
|
181
|
+
payTo,
|
|
182
|
+
maxTimeoutSeconds,
|
|
183
|
+
asset,
|
|
184
|
+
extra: {
|
|
185
|
+
name: 'USD Coin',
|
|
186
|
+
version: '2',
|
|
187
|
+
},
|
|
188
|
+
bazaar,
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const headers = {
|
|
192
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
193
|
+
'Cache-Control': 'no-store',
|
|
194
|
+
'X-Payment-Required': 'x402',
|
|
195
|
+
'X-Payment-Version': String(challenge.x402Version),
|
|
196
|
+
'X-Payment-Scheme': challenge.scheme,
|
|
197
|
+
'X-Payment-Network': challenge.network,
|
|
198
|
+
'X-Payment-Asset': challenge.asset,
|
|
199
|
+
'X-Payment-Amount': challenge.maxAmountRequired,
|
|
200
|
+
'X-Payment-PayTo': challenge.payTo,
|
|
201
|
+
'WWW-Authenticate': `x402 scheme="${challenge.scheme}", network="${challenge.network}", asset="${challenge.asset}", amount="${challenge.maxAmountRequired}", payTo="${challenge.payTo}"`,
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
status: 402,
|
|
206
|
+
challenge,
|
|
207
|
+
headers,
|
|
208
|
+
body: {
|
|
209
|
+
x402Version: SCHEMA_VERSIONS.x402,
|
|
210
|
+
error: 'Payment Required',
|
|
211
|
+
accepts: [challenge],
|
|
212
|
+
bazaar,
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Creates a deterministic HMAC-SHA256 signed x402 payment proof for local dev, demos,
|
|
219
|
+
* and offline automated test suites.
|
|
220
|
+
*/
|
|
221
|
+
export async function createTestX402Proof(
|
|
222
|
+
challenge ,
|
|
223
|
+
secret ,
|
|
224
|
+
opts ,
|
|
225
|
+
) {
|
|
226
|
+
if (!secret || secret.trim().length === 0) {
|
|
227
|
+
throw new Error('createTestX402Proof requires a non-empty secret');
|
|
228
|
+
}
|
|
229
|
+
const timestamp = opts?.timestamp ?? Math.floor(Date.now() / 1000);
|
|
230
|
+
const payer = opts?.payer ?? '0x000000000000000000000000000000000000dEaD';
|
|
231
|
+
const amount = opts?.amount ?? challenge.maxAmountRequired;
|
|
232
|
+
const txHash =
|
|
233
|
+
opts?.txHash ??
|
|
234
|
+
`0x${sha256Hex(`${challenge.network}:${challenge.resource}:${challenge.payTo}:${amount}:${payer}:${timestamp}`)}`;
|
|
235
|
+
|
|
236
|
+
const payload = {
|
|
237
|
+
x402Version: 1,
|
|
238
|
+
scheme: 'exact',
|
|
239
|
+
network: challenge.network,
|
|
240
|
+
resource: challenge.resource,
|
|
241
|
+
payTo: challenge.payTo,
|
|
242
|
+
asset: challenge.asset,
|
|
243
|
+
amount,
|
|
244
|
+
payer,
|
|
245
|
+
txHash,
|
|
246
|
+
timestamp,
|
|
247
|
+
mode: 'hmac-test',
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const hmac = await computeHmacSha256Base64Url(canonicalJson(payload), secret);
|
|
251
|
+
const envelope = { payload, hmac };
|
|
252
|
+
return bytesToBase64Url(utf8ToBytes(JSON.stringify(envelope)));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function tryDecodeProofJson(proofHeader ) {
|
|
256
|
+
const trimmed = proofHeader.trim();
|
|
257
|
+
if (!trimmed) return null;
|
|
258
|
+
if (trimmed.startsWith('{')) {
|
|
259
|
+
try {
|
|
260
|
+
const parsed = JSON.parse(trimmed);
|
|
261
|
+
return parsed && typeof parsed === 'object' ? (parsed ) : null;
|
|
262
|
+
} catch {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
const decoded = bytesToUtf8(base64UrlToBytes(trimmed));
|
|
268
|
+
const parsed = JSON.parse(decoded);
|
|
269
|
+
return parsed && typeof parsed === 'object' ? (parsed ) : null;
|
|
270
|
+
} catch {
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Verifies an x402 payment proof header against a challenge.
|
|
277
|
+
* Supports deterministic HMAC test/demo proofs (when `opts.testSecret` is provided)
|
|
278
|
+
* as well as live Coinbase CDP / x402 facilitator HTTP verification.
|
|
279
|
+
*/
|
|
280
|
+
export async function verifyX402Payment(
|
|
281
|
+
proofHeader ,
|
|
282
|
+
challenge ,
|
|
283
|
+
opts ,
|
|
284
|
+
) {
|
|
285
|
+
if (!proofHeader || proofHeader.trim().length === 0) {
|
|
286
|
+
return { valid: false, error: 'Missing X-Payment-Proof header' };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const trimmedProof = proofHeader.trim();
|
|
290
|
+
const decoded = tryDecodeProofJson(trimmedProof);
|
|
291
|
+
|
|
292
|
+
// Path 1: Deterministic HMAC test/demo mode
|
|
293
|
+
if (
|
|
294
|
+
decoded &&
|
|
295
|
+
decoded.payload &&
|
|
296
|
+
typeof decoded.payload === 'object' &&
|
|
297
|
+
(decoded.payload ).mode === 'hmac-test'
|
|
298
|
+
) {
|
|
299
|
+
if (!opts?.testSecret) {
|
|
300
|
+
return { valid: false, error: 'Test HMAC payment proof rejected when testSecret is not configured' };
|
|
301
|
+
}
|
|
302
|
+
const envelope = decoded ;
|
|
303
|
+
const p = envelope.payload;
|
|
304
|
+
if (typeof envelope.hmac !== 'string' || !envelope.hmac) {
|
|
305
|
+
return { valid: false, error: 'Malformed HMAC test proof: missing hmac' };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const expectedHmac = await computeHmacSha256Base64Url(canonicalJson(p), opts.testSecret);
|
|
309
|
+
if (!constantTimeEqual(expectedHmac, envelope.hmac)) {
|
|
310
|
+
return { valid: false, error: 'Invalid HMAC test proof signature' };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (p.network !== challenge.network) {
|
|
314
|
+
return { valid: false, error: `Network mismatch: expected ${challenge.network}, got ${p.network}` };
|
|
315
|
+
}
|
|
316
|
+
if (p.resource !== challenge.resource) {
|
|
317
|
+
return { valid: false, error: 'Resource mismatch in payment proof' };
|
|
318
|
+
}
|
|
319
|
+
if (p.payTo.toLowerCase() !== challenge.payTo.toLowerCase()) {
|
|
320
|
+
return { valid: false, error: 'payTo address mismatch in payment proof' };
|
|
321
|
+
}
|
|
322
|
+
if (p.asset.toLowerCase() !== challenge.asset.toLowerCase()) {
|
|
323
|
+
return { valid: false, error: 'Asset contract mismatch in payment proof' };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
try {
|
|
327
|
+
if (BigInt(p.amount) < BigInt(challenge.maxAmountRequired)) {
|
|
328
|
+
return { valid: false, error: 'Insufficient USDC atomic amount in payment proof' };
|
|
329
|
+
}
|
|
330
|
+
} catch {
|
|
331
|
+
return { valid: false, error: 'Invalid numeric amount in payment proof' };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const nowSec = opts.nowSec ?? Math.floor(Date.now() / 1000);
|
|
335
|
+
if (
|
|
336
|
+
typeof p.timestamp !== 'number' ||
|
|
337
|
+
Math.abs(nowSec - p.timestamp) > challenge.maxTimeoutSeconds
|
|
338
|
+
) {
|
|
339
|
+
return { valid: false, error: 'Payment proof timestamp expired or out of window' };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
return {
|
|
343
|
+
valid: true,
|
|
344
|
+
receipt: {
|
|
345
|
+
txHash: p.txHash,
|
|
346
|
+
payer: p.payer,
|
|
347
|
+
amountUsdcAtomic: p.amount,
|
|
348
|
+
network: p.network,
|
|
349
|
+
verifiedAt: new Date(nowSec * 1000).toISOString(),
|
|
350
|
+
facilitator: 'hmac-test-mode',
|
|
351
|
+
},
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Path 2: Live Coinbase CDP / x402 facilitator HTTP verification + on-chain settlement
|
|
356
|
+
const facilitatorBase = (opts?.facilitatorUrl ?? DEFAULT_X402_FACILITATOR_URL).replace(/\/+$/, '');
|
|
357
|
+
const fetchFn = opts?.fetchImpl ?? globalThis.fetch;
|
|
358
|
+
if (typeof fetchFn !== 'function') {
|
|
359
|
+
return { valid: false, error: 'Fetch API unavailable for facilitator verification' };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const timeoutMs =
|
|
363
|
+
typeof opts?.timeoutMs === 'number' && opts.timeoutMs > 0 ? opts.timeoutMs : 8_000;
|
|
364
|
+
|
|
365
|
+
const postFacilitator = async (endpoint ) => {
|
|
366
|
+
const controller = new AbortController();
|
|
367
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
368
|
+
try {
|
|
369
|
+
return await fetchFn(`${facilitatorBase}${endpoint}`, {
|
|
370
|
+
method: 'POST',
|
|
371
|
+
headers: {
|
|
372
|
+
'Content-Type': 'application/json',
|
|
373
|
+
Accept: 'application/json',
|
|
374
|
+
},
|
|
375
|
+
body: JSON.stringify({
|
|
376
|
+
x402Version: challenge.x402Version,
|
|
377
|
+
paymentHeader: trimmedProof,
|
|
378
|
+
paymentRequirements: challenge,
|
|
379
|
+
}),
|
|
380
|
+
signal: controller.signal,
|
|
381
|
+
});
|
|
382
|
+
} finally {
|
|
383
|
+
clearTimeout(timer);
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
try {
|
|
388
|
+
const verifyRes = await postFacilitator('/verify');
|
|
389
|
+
if (!verifyRes.ok) {
|
|
390
|
+
return {
|
|
391
|
+
valid: false,
|
|
392
|
+
error: `Facilitator rejected payment verification (HTTP ${verifyRes.status})`,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const verifyData = (await verifyRes.json()) ;
|
|
397
|
+
if (verifyData.isValid !== true) {
|
|
398
|
+
const reason =
|
|
399
|
+
typeof verifyData.invalidReason === 'string' && verifyData.invalidReason.length > 0
|
|
400
|
+
? verifyData.invalidReason
|
|
401
|
+
: 'Facilitator marked payment proof invalid';
|
|
402
|
+
return { valid: false, error: reason };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// x402 `/verify` is off-chain only; execute `/settle` to confirm on-chain settlement
|
|
406
|
+
const settleRes = await postFacilitator('/settle');
|
|
407
|
+
if (!settleRes.ok) {
|
|
408
|
+
return {
|
|
409
|
+
valid: false,
|
|
410
|
+
error: `Facilitator failed payment settlement (HTTP ${settleRes.status})`,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const settleData = (await settleRes.json()) ;
|
|
415
|
+
if (settleData.success === false) {
|
|
416
|
+
const reason =
|
|
417
|
+
typeof settleData.errorReason === 'string' && settleData.errorReason.length > 0
|
|
418
|
+
? settleData.errorReason
|
|
419
|
+
: typeof settleData.error === 'string' && settleData.error.length > 0
|
|
420
|
+
? settleData.error
|
|
421
|
+
: 'Facilitator settlement rejected payment';
|
|
422
|
+
return { valid: false, error: reason };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const rawTxHash =
|
|
426
|
+
typeof settleData.txHash === 'string' && settleData.txHash.trim().length > 0
|
|
427
|
+
? settleData.txHash.trim()
|
|
428
|
+
: typeof settleData.transaction === 'string' && settleData.transaction.trim().length > 0
|
|
429
|
+
? settleData.transaction.trim()
|
|
430
|
+
: '';
|
|
431
|
+
if (!rawTxHash) {
|
|
432
|
+
return {
|
|
433
|
+
valid: false,
|
|
434
|
+
error: 'Facilitator settlement did not return an on-chain transaction hash',
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const payer =
|
|
439
|
+
typeof settleData.payer === 'string' && settleData.payer.trim().length > 0
|
|
440
|
+
? settleData.payer.trim()
|
|
441
|
+
: typeof verifyData.payer === 'string' && verifyData.payer.trim().length > 0
|
|
442
|
+
? verifyData.payer.trim()
|
|
443
|
+
: 'verified-payer';
|
|
444
|
+
const nowSec = opts?.nowSec ?? Math.floor(Date.now() / 1000);
|
|
445
|
+
|
|
446
|
+
return {
|
|
447
|
+
valid: true,
|
|
448
|
+
receipt: {
|
|
449
|
+
txHash: rawTxHash,
|
|
450
|
+
payer,
|
|
451
|
+
amountUsdcAtomic: challenge.maxAmountRequired,
|
|
452
|
+
network: challenge.network,
|
|
453
|
+
verifiedAt: new Date(nowSec * 1000).toISOString(),
|
|
454
|
+
facilitator: facilitatorBase,
|
|
455
|
+
},
|
|
456
|
+
};
|
|
457
|
+
} catch (err) {
|
|
458
|
+
const isAbort =
|
|
459
|
+
err instanceof Error && (err.name === 'AbortError' || err.message.includes('aborted'));
|
|
460
|
+
return {
|
|
461
|
+
valid: false,
|
|
462
|
+
error: isAbort
|
|
463
|
+
? `Facilitator request timed out after ${timeoutMs}ms`
|
|
464
|
+
: `Facilitator verification failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
}
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Deterministic canonical JSON (recursive lexicographically sorted keys).
|
|
14
|
+
*/
|
|
15
|
+
export function canonicalizeJson(value ) {
|
|
16
|
+
if (value === null || typeof value !== 'object') {
|
|
17
|
+
return JSON.stringify(value);
|
|
18
|
+
}
|
|
19
|
+
if (Array.isArray(value)) {
|
|
20
|
+
return `[${value.map((item) => canonicalizeJson(item)).join(',')}]`;
|
|
21
|
+
}
|
|
22
|
+
const obj = value ;
|
|
23
|
+
const keys = Object.keys(obj)
|
|
24
|
+
.filter((k) => obj[k] !== undefined)
|
|
25
|
+
.sort();
|
|
26
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalizeJson(obj[k])}`).join(',')}}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function decodeBase64Any(input ) {
|
|
30
|
+
const normalized = input
|
|
31
|
+
.trim()
|
|
32
|
+
.replace(/-/g, '+')
|
|
33
|
+
.replace(/_/g, '/');
|
|
34
|
+
const padLen = (4 - (normalized.length % 4)) % 4;
|
|
35
|
+
const padded = normalized + '='.repeat(padLen);
|
|
36
|
+
const bin = atob(padded);
|
|
37
|
+
const bytes = new Uint8Array(bin.length);
|
|
38
|
+
for (let i = 0; i < bin.length; i++) {
|
|
39
|
+
bytes[i] = bin.charCodeAt(i);
|
|
40
|
+
}
|
|
41
|
+
return bytes;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function encodeBase64Url(bytes ) {
|
|
45
|
+
let bin = '';
|
|
46
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
47
|
+
bin += String.fromCharCode(bytes[i] );
|
|
48
|
+
}
|
|
49
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function importEd25519PublicKey(keyMaterial ) {
|
|
53
|
+
if (typeof keyMaterial === 'object') {
|
|
54
|
+
return crypto.subtle.importKey('jwk', keyMaterial, { name: 'Ed25519' }, false, ['verify']);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const trimmed = keyMaterial.trim();
|
|
58
|
+
if (trimmed.startsWith('{')) {
|
|
59
|
+
const jwk = JSON.parse(trimmed) ;
|
|
60
|
+
return crypto.subtle.importKey('jwk', jwk, { name: 'Ed25519' }, false, ['verify']);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Strip optional `ed25519:` self-verifying keyId prefix and PEM headers if present
|
|
64
|
+
const withoutPrefix = /^ed25519:/i.test(trimmed) ? trimmed.slice('ed25519:'.length) : trimmed;
|
|
65
|
+
const stripped = withoutPrefix
|
|
66
|
+
.replace(/-----BEGIN PUBLIC KEY-----/g, '')
|
|
67
|
+
.replace(/-----END PUBLIC KEY-----/g, '')
|
|
68
|
+
.replace(/\s+/g, '');
|
|
69
|
+
|
|
70
|
+
const raw = decodeBase64Any(stripped);
|
|
71
|
+
// 32-byte raw Ed25519 public key vs SPKI DER (44 bytes)
|
|
72
|
+
if (raw.byteLength === 32) {
|
|
73
|
+
return crypto.subtle.importKey('raw', raw, { name: 'Ed25519' }, false, ['verify']);
|
|
74
|
+
}
|
|
75
|
+
return crypto.subtle.importKey('spki', raw, { name: 'Ed25519' }, false, ['verify']);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function extractEmbeddedPublicKey(
|
|
79
|
+
doc ,
|
|
80
|
+
explicitKey ,
|
|
81
|
+
) {
|
|
82
|
+
if (explicitKey) return explicitKey;
|
|
83
|
+
|
|
84
|
+
const sigAny = doc.signature ;
|
|
85
|
+
const docAny = doc ;
|
|
86
|
+
|
|
87
|
+
if (sigAny) {
|
|
88
|
+
if (typeof sigAny.publicKey === 'string' && sigAny.publicKey.length > 0) {
|
|
89
|
+
return sigAny.publicKey;
|
|
90
|
+
}
|
|
91
|
+
if (sigAny.publicKeyJwk && typeof sigAny.publicKeyJwk === 'object') {
|
|
92
|
+
return sigAny.publicKeyJwk ;
|
|
93
|
+
}
|
|
94
|
+
if (typeof sigAny.publicKeyJwk === 'string' && sigAny.publicKeyJwk.length > 0) {
|
|
95
|
+
return sigAny.publicKeyJwk;
|
|
96
|
+
}
|
|
97
|
+
if (typeof sigAny.spki === 'string' && sigAny.spki.length > 0) {
|
|
98
|
+
return sigAny.spki;
|
|
99
|
+
}
|
|
100
|
+
// Support did:key or keyId carrying an inline SPKI/raw key suffix like "ed25519:<base64>"
|
|
101
|
+
if (typeof sigAny.keyId === 'string' && sigAny.keyId.startsWith('ed25519:')) {
|
|
102
|
+
const candidate = sigAny.keyId.slice('ed25519:'.length);
|
|
103
|
+
if (candidate.length >= 40) return candidate;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (typeof docAny.publicKey === 'string' && docAny.publicKey.length > 0) {
|
|
108
|
+
return docAny.publicKey;
|
|
109
|
+
}
|
|
110
|
+
if (docAny.publicKeyJwk && typeof docAny.publicKeyJwk === 'object') {
|
|
111
|
+
return docAny.publicKeyJwk ;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Verifies an Ed25519-signed OpenVEX document via WebCrypto `crypto.subtle`.
|
|
119
|
+
* Strips top-level `signature` before computing canonical sorted JSON payload.
|
|
120
|
+
*/
|
|
121
|
+
export async function verifyEd25519VexDocument(
|
|
122
|
+
doc ,
|
|
123
|
+
publicKey ,
|
|
124
|
+
) {
|
|
125
|
+
const statementCount = Array.isArray(doc.statements) ? doc.statements.length : 0;
|
|
126
|
+
|
|
127
|
+
if (!doc.signature) {
|
|
128
|
+
return {
|
|
129
|
+
valid: false,
|
|
130
|
+
reason: 'OpenVEX document is missing a signature block.',
|
|
131
|
+
statementCount,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (doc.signature.algorithm !== 'Ed25519') {
|
|
136
|
+
return {
|
|
137
|
+
valid: false,
|
|
138
|
+
reason: `Unsupported signature algorithm: ${String(doc.signature.algorithm)}`,
|
|
139
|
+
algorithm: String(doc.signature.algorithm),
|
|
140
|
+
keyId: doc.signature.keyId,
|
|
141
|
+
signedAt: doc.signature.signedAt,
|
|
142
|
+
statementCount,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const keyMaterial = extractEmbeddedPublicKey(doc, publicKey);
|
|
147
|
+
if (!keyMaterial) {
|
|
148
|
+
return {
|
|
149
|
+
valid: false,
|
|
150
|
+
reason: 'No Ed25519 public key available in document, response headers, or tool input.',
|
|
151
|
+
algorithm: doc.signature.algorithm,
|
|
152
|
+
keyId: doc.signature.keyId,
|
|
153
|
+
signedAt: doc.signature.signedAt,
|
|
154
|
+
statementCount,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let cryptoKey ;
|
|
159
|
+
try {
|
|
160
|
+
cryptoKey = await importEd25519PublicKey(keyMaterial);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
return {
|
|
163
|
+
valid: false,
|
|
164
|
+
reason: `Failed to import Ed25519 public key: ${err instanceof Error ? err.message : String(err)}`,
|
|
165
|
+
algorithm: doc.signature.algorithm,
|
|
166
|
+
keyId: doc.signature.keyId,
|
|
167
|
+
signedAt: doc.signature.signedAt,
|
|
168
|
+
statementCount,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
let sigBytes ;
|
|
173
|
+
try {
|
|
174
|
+
sigBytes = decodeBase64Any(doc.signature.value);
|
|
175
|
+
} catch (err) {
|
|
176
|
+
return {
|
|
177
|
+
valid: false,
|
|
178
|
+
reason: `Malformed signature encoding: ${err instanceof Error ? err.message : String(err)}`,
|
|
179
|
+
algorithm: doc.signature.algorithm,
|
|
180
|
+
keyId: doc.signature.keyId,
|
|
181
|
+
signedAt: doc.signature.signedAt,
|
|
182
|
+
statementCount,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const unsignedCopy = { ...(doc ) };
|
|
187
|
+
delete unsignedCopy.signature;
|
|
188
|
+
|
|
189
|
+
const canonical = canonicalizeJson(unsignedCopy);
|
|
190
|
+
const payloadBytes = new TextEncoder().encode(canonical);
|
|
191
|
+
|
|
192
|
+
let verified = false;
|
|
193
|
+
try {
|
|
194
|
+
verified = await crypto.subtle.verify({ name: 'Ed25519' }, cryptoKey, sigBytes, payloadBytes);
|
|
195
|
+
} catch (err) {
|
|
196
|
+
return {
|
|
197
|
+
valid: false,
|
|
198
|
+
reason: `WebCrypto verification error: ${err instanceof Error ? err.message : String(err)}`,
|
|
199
|
+
algorithm: doc.signature.algorithm,
|
|
200
|
+
keyId: doc.signature.keyId,
|
|
201
|
+
signedAt: doc.signature.signedAt,
|
|
202
|
+
statementCount,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
valid: verified,
|
|
208
|
+
reason: verified ? undefined : 'Ed25519 signature does not match canonical OpenVEX payload.',
|
|
209
|
+
algorithm: doc.signature.algorithm,
|
|
210
|
+
keyId: doc.signature.keyId,
|
|
211
|
+
signedAt: doc.signature.signedAt,
|
|
212
|
+
statementCount,
|
|
213
|
+
};
|
|
214
|
+
}
|