-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathx402.mjs
More file actions
756 lines (678 loc) · 25.8 KB
/
Copy pathx402.mjs
File metadata and controls
756 lines (678 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
import crypto from "node:crypto";
export const X402_PROTOCOL = "x402-v2";
export const X402_HEADERS = Object.freeze({
paymentRequired: "PAYMENT-REQUIRED",
paymentSignature: "PAYMENT-SIGNATURE",
paymentResponse: "PAYMENT-RESPONSE",
});
export const PRIVATE_X402_INTENT_SCHEMA = "dark-null-private-x402-intent-v1";
export const PRIVATE_X402_REQUEST_BINDING_SCHEMA = "dark-null-private-x402-request-binding-v1";
export const PRIVATE_X402_RECEIPT_SCHEMA = "dark-null-private-x402-receipt-v1";
export const DNA_X402_PRIVATE_RECEIPT_SCHEMA = "dark-null-dna-x402-private-receipt-v1";
export const EMPTY_BODY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
const HASH_RE = /^[0-9a-f]{64}$/;
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,96}$/;
const COMMIT_RE = /^[0-9a-f]{40}$/;
const BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
const SAFE_NONCE_RE = /^[A-Za-z0-9_-]{16,128}$/;
const SAFE_RESOURCE_RE = /^[a-z0-9][a-z0-9:._/-]{1,127}$/;
const SAFE_IDENTIFIER_RE = /^[A-Za-z0-9:._+/@-]{1,160}$/;
const SUPPORTED_STATUS = new Set(["settled", "rejected"]);
const SUPPORTED_CONFIRMATION = new Set(["processed", "confirmed", "finalized"]);
const SUPPORTED_CLUSTER = new Set(["devnet", "localnet", "mainnet-beta"]);
const CURRENT_WITHDRAW_V2_PUBLIC_INPUTS = [
"commitment",
"nullifier",
"root",
"amount",
"receiver_token_part_0",
"receiver_token_part_1",
"mint_part_0",
"mint_part_1",
];
const SENSITIVE_PATTERNS = [
{ label: "email address", regex: /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i },
{ label: "phone number", regex: /\b(?:\+?\d[\d\s().-]{7,}\d)\b/ },
{ label: "query string", regex: /[?#][A-Za-z0-9_.~=&%+-]+/ },
{ label: "bearer token", regex: /\bbearer\s+[A-Za-z0-9._~+/=-]{16,}/i },
{ label: "api key", regex: /\b(?:api[_-]?key|secret|token)[=:][A-Za-z0-9._~+/=-]{8,}/i },
{ label: "private key", regex: /BEGIN [A-Z ]*PRIVATE KEY/ },
];
function fail(message) {
throw new Error(message);
}
function assertObject(value, label) {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
fail(`${label} must be an object`);
}
}
function canonicalValue(value) {
if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return value;
}
if (typeof value === "bigint") {
return value.toString();
}
if (Array.isArray(value)) {
return value.map((entry) => canonicalValue(entry));
}
if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value)
.filter(([, entry]) => entry !== undefined)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, entry]) => [key, canonicalValue(entry)]),
);
}
fail("canonical JSON cannot encode undefined, functions, or symbols");
}
export function canonicalJsonString(value) {
return JSON.stringify(canonicalValue(value));
}
export function sha256Hex(value) {
const bytes = Buffer.isBuffer(value)
? value
: typeof value === "string"
? Buffer.from(value, "utf8")
: Buffer.from(canonicalJsonString(value), "utf8");
return crypto.createHash("sha256").update(bytes).digest("hex");
}
export function encodeBase64Json(value) {
return Buffer.from(canonicalJsonString(value), "utf8").toString("base64");
}
export function decodeBase64Json(value) {
if (typeof value !== "string" || value.length === 0 || value.length % 4 !== 0 || !BASE64_RE.test(value)) {
fail("x402 header must be a non-empty Base64 JSON string");
}
const decoded = Buffer.from(value, "base64").toString("utf8");
try {
return JSON.parse(decoded);
} catch {
fail("x402 header does not contain valid JSON");
}
}
function normalizeHash(value, label) {
if (typeof value !== "string" || !HASH_RE.test(value)) {
fail(`${label} must be a lowercase sha256 hex digest`);
}
return value;
}
function normalizeCommit(value) {
if (typeof value !== "string" || !COMMIT_RE.test(value)) {
fail("repository.commit must be a full 40-character lowercase git commit hash");
}
return value;
}
function normalizeAtomicAmount(value, label = "amount") {
const parsed =
typeof value === "bigint"
? value
: typeof value === "number" && Number.isSafeInteger(value)
? BigInt(value)
: typeof value === "string" && /^\d+$/.test(value)
? BigInt(value)
: null;
if (parsed === null || parsed <= 0n) {
fail(`${label} must be a positive atomic-unit integer`);
}
return parsed.toString();
}
function normalizeMethod(value) {
const method = String(value ?? "GET").toUpperCase();
if (!/^[A-Z]{3,12}$/.test(method)) {
fail("method must be an uppercase HTTP method");
}
return method;
}
function assertNoSensitiveMetadata(value, label) {
for (const pattern of SENSITIVE_PATTERNS) {
if (pattern.regex.test(value)) {
fail(`${label} contains ${pattern.label}; use an opaque alias and hash the raw value outside the receipt`);
}
}
}
function normalizeResourceAlias(value) {
if (typeof value !== "string" || !SAFE_RESOURCE_RE.test(value)) {
fail("resource must be an opaque lowercase alias, not a raw URL or user-specific string");
}
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
fail("resource must not be a raw URL");
}
assertNoSensitiveMetadata(value, "resource");
return value;
}
function normalizeDescription(value) {
const description = String(value ?? "dark-null-private-x402-payment");
if (description.length < 3 || description.length > 120) {
fail("description must be 3-120 characters");
}
assertNoSensitiveMetadata(description, "description");
return description;
}
function normalizeIdentifier(value, label) {
if (typeof value !== "string" || !SAFE_IDENTIFIER_RE.test(value)) {
fail(`${label} must be a stable protocol identifier`);
}
return value;
}
function normalizeOptionalHash(value, label) {
return value === undefined ? undefined : normalizeHash(value, label);
}
function normalizeDnaSignedReceipt(receipt) {
assertObject(receipt, "dnaReceipt");
assertObject(receipt.payload, "dnaReceipt.payload");
const payload = receipt.payload;
const normalized = {
payload,
prevHash: normalizeHash(receipt.prevHash, "dnaReceipt.prevHash"),
receiptHash: normalizeHash(receipt.receiptHash, "dnaReceipt.receiptHash"),
signerPublicKey: normalizeIdentifier(receipt.signerPublicKey, "dnaReceipt.signerPublicKey"),
signature: normalizeIdentifier(receipt.signature, "dnaReceipt.signature"),
};
normalizeIdentifier(payload.receiptId, "dnaReceipt.payload.receiptId");
normalizeIdentifier(payload.quoteId, "dnaReceipt.payload.quoteId");
normalizeIdentifier(payload.commitId, "dnaReceipt.payload.commitId");
normalizeHash(payload.requestDigest, "dnaReceipt.payload.requestDigest");
normalizeHash(payload.responseDigest, "dnaReceipt.payload.responseDigest");
normalizeAtomicAmount(payload.totalAtomic, "dnaReceipt.payload.totalAtomic");
normalizeIdentifier(payload.recipient, "dnaReceipt.payload.recipient");
normalizeIdentifier(payload.mint, "dnaReceipt.payload.mint");
normalizeIdentifier(payload.settlement, "dnaReceipt.payload.settlement");
return normalized;
}
function defaultProofEncodingHash() {
return sha256Hex({
field: "bn254-fr",
publicInputs: CURRENT_WITHDRAW_V2_PUBLIC_INPUTS,
});
}
function normalizeDnaSettlement(input, payload) {
const settlement = input.settlement ?? {
cluster: input.cluster,
programId: input.programId,
signature: payload.txSignature,
slot: input.slot,
confirmationStatus: input.confirmationStatus ?? "finalized",
};
return normalizeReceiptSettlement(settlement, "settled");
}
function normalizeNonce(value) {
if (typeof value !== "string" || !SAFE_NONCE_RE.test(value)) {
fail("nonce must be a 16-128 character URL-safe nonce");
}
return value;
}
function normalizeIsoDate(value, label) {
if (typeof value !== "string" || Number.isNaN(Date.parse(value)) || new Date(value).toISOString() !== value) {
fail(`${label} must be an ISO-8601 UTC timestamp`);
}
return value;
}
function normalizeSettlementProfile(settlement) {
assertObject(settlement, "settlement");
const cluster = normalizeIdentifier(settlement.cluster, "settlement.cluster");
if (!SUPPORTED_CLUSTER.has(cluster)) {
fail("settlement.cluster must be devnet, localnet, or mainnet-beta");
}
const normalized = {
mode: normalizeIdentifier(settlement.mode ?? "dark-null-withdraw-v2", "settlement.mode"),
cluster,
programId: normalizeIdentifier(settlement.programId, "settlement.programId"),
manifestLabel: normalizeIdentifier(settlement.manifestLabel, "settlement.manifestLabel"),
};
if (settlement.amountLamports !== undefined) {
normalized.amountLamports = normalizeAtomicAmount(settlement.amountLamports, "settlement.amountLamports");
}
for (const field of ["receiverTokenAccountHash", "mintHash", "proofEncodingHash"]) {
if (settlement[field] !== undefined) {
normalized[field] = normalizeHash(settlement[field], `settlement.${field}`);
}
}
return normalized;
}
export function createPrivateX402Intent(input) {
assertObject(input, "input");
const resource = normalizeResourceAlias(input.resource);
const settlement = normalizeSettlementProfile(input.settlement);
const base = {
schema: PRIVATE_X402_INTENT_SCHEMA,
protocol: X402_PROTOCOL,
scheme: "exact",
method: normalizeMethod(input.method),
resource,
resourceHash: sha256Hex(resource),
description: normalizeDescription(input.description),
nonce: normalizeNonce(input.nonce),
expiresAt: normalizeIsoDate(input.expiresAt, "expiresAt"),
payment: {
maxAmountRequired: normalizeAtomicAmount(input.maxAmountRequired, "maxAmountRequired"),
asset: normalizeIdentifier(input.asset, "asset"),
network: normalizeIdentifier(input.network, "network"),
payTo: normalizeIdentifier(input.payTo, "payTo"),
},
settlement,
privacy: {
rawBuyerMetadataAllowed: false,
rawBuyerMetadataStored: false,
resourceIsOpaqueAlias: true,
paymentHeadersStored: false,
},
};
return {
...base,
intentHash: sha256Hex(base),
};
}
export function createPaymentRequiredHeader(intent) {
assertObject(intent, "intent");
if (intent.schema !== PRIVATE_X402_INTENT_SCHEMA || !intent.intentHash) {
fail("intent must be created by createPrivateX402Intent");
}
const payload = {
x402Version: 2,
accepts: [
{
scheme: "exact",
network: intent.payment.network,
maxAmountRequired: intent.payment.maxAmountRequired,
resource: intent.resource,
description: intent.description,
payTo: intent.payment.payTo,
asset: intent.payment.asset,
extra: {
darkNull: {
schema: PRIVATE_X402_INTENT_SCHEMA,
protocol: X402_PROTOCOL,
intentHash: intent.intentHash,
resourceHash: intent.resourceHash,
receiptSchema: PRIVATE_X402_RECEIPT_SCHEMA,
cluster: intent.settlement.cluster,
programId: intent.settlement.programId,
manifestLabel: intent.settlement.manifestLabel,
rawBuyerMetadataAllowed: false,
},
},
},
],
};
return {
name: X402_HEADERS.paymentRequired,
value: encodeBase64Json(payload),
payload,
};
}
export function createPrivateX402ReceiptFromDna(input) {
assertObject(input, "input");
const dnaReceipt = normalizeDnaSignedReceipt(input.dnaReceipt);
const payload = dnaReceipt.payload;
const proofEncodingHash = normalizeHash(
input.proof?.proofEncodingHash ?? input.proofEncodingHash ?? defaultProofEncodingHash(),
"proofEncodingHash",
);
const resourceHash = sha256Hex(payload.resource ?? payload.requestDigest);
const recipientHash = sha256Hex(payload.recipient);
const mintHash = sha256Hex(payload.mint);
const signatureHash = sha256Hex(dnaReceipt.signature);
const dnaReceiptPayloadHash = sha256Hex(payload);
const privateResourceAlias = input.resourceAlias ?? `dna:receipt:${dnaReceipt.receiptHash.slice(0, 32)}`;
const intent = createPrivateX402Intent({
method: input.method ?? "POST",
resource: privateResourceAlias,
description: input.description ?? "dna-x402-dark-null-private-receipt",
nonce: input.nonce ?? `dna_${dnaReceipt.receiptHash.slice(0, 32)}`,
expiresAt: input.expiresAt,
maxAmountRequired: payload.totalAtomic,
asset: input.asset ?? "solana-usdc",
network: input.network ?? `solana-${input.cluster ?? input.settlement?.cluster ?? "devnet"}`,
payTo: input.payTo ?? payload.recipient,
settlement: {
mode: input.settlementMode ?? "dark-null-withdraw-v2",
cluster: input.cluster ?? input.settlement?.cluster,
programId: input.programId ?? input.settlement?.programId,
manifestLabel: input.manifestLabel,
amountLamports: input.amountLamports ?? payload.totalAtomic,
receiverTokenAccountHash: input.receiverTokenAccountHash ?? recipientHash,
mintHash: input.mintHash ?? mintHash,
proofEncodingHash,
},
});
const paymentRequiredHeader = input.paymentRequiredHeader ?? createPaymentRequiredHeader(intent).value;
const paymentSignatureHeader = input.paymentSignatureHeader ?? encodeBase64Json({
schema: "dna-x402-signed-receipt-lock-v1",
receiptHash: dnaReceipt.receiptHash,
signerPublicKey: dnaReceipt.signerPublicKey,
signatureHash,
});
const paymentResponseHeader = input.paymentResponseHeader ?? encodeBase64Json({
status: "settled",
dnaReceiptHash: dnaReceipt.receiptHash,
});
const requestBinding = createPrivateX402RequestBinding({
intent,
method: input.method ?? "POST",
resourceHash,
bodyHash: payload.requestDigest,
paymentRequiredHeader,
paymentSignatureHeader,
});
const proof = {
proofBundleHash: normalizeOptionalHash(input.proof?.proofBundleHash, "proof.proofBundleHash")
?? normalizeOptionalHash(input.proofBundleHash, "proofBundleHash")
?? sha256Hex({
source: "dna-x402",
receiptHash: dnaReceipt.receiptHash,
receiptSignatureHash: signatureHash,
splitPaymentProofs: payload.splitPaymentProofs ?? null,
}),
publicInputHash: normalizeOptionalHash(input.proof?.publicInputHash, "proof.publicInputHash")
?? normalizeOptionalHash(input.publicInputHash, "publicInputHash")
?? sha256Hex({
source: "dna-x402",
amount: payload.totalAtomic,
recipientHash,
mintHash,
receiptHash: dnaReceipt.receiptHash,
}),
proofEncodingHash,
};
const receipt = createPrivateX402Receipt({
requestBinding,
paymentResponseHeader,
observedAt: input.observedAt,
response: {
statusCode: input.responseStatusCode ?? 200,
bodyHash: payload.responseDigest,
},
settlement: normalizeDnaSettlement(input, payload),
proof,
repository: input.repository,
previousReceiptHash: input.previousReceiptHash,
});
return {
schema: DNA_X402_PRIVATE_RECEIPT_SCHEMA,
source: "dna-x402",
privacyPath: "dark-null",
normalPath: "dna-x402",
dnaReceiptHash: dnaReceipt.receiptHash,
dnaReceiptPayloadHash,
dnaReceiptSignatureHash: signatureHash,
resourceHash,
requestDigest: payload.requestDigest,
responseDigest: payload.responseDigest,
amountHash: sha256Hex(payload.totalAtomic),
recipientHash,
mintHash,
intent,
requestBinding,
receipt,
receiptHash: receipt.lock.receiptHash,
privacy: {
rawDnaReceiptStored: false,
rawResourceStored: false,
rawPaymentHeadersStored: false,
darkNullOptionalPath: true,
normalDnaPathStillSupported: true,
},
};
}
function hashHeader(value, label) {
if (typeof value !== "string" || value.length === 0) {
fail(`${label} must be a non-empty header value`);
}
return sha256Hex(value);
}
export function createPrivateX402RequestBinding(input) {
assertObject(input, "input");
const intentHash = normalizeHash(input.intentHash ?? input.intent?.intentHash, "intentHash");
const paymentRequiredHash = hashHeader(input.paymentRequiredHeader, X402_HEADERS.paymentRequired);
const paymentSignatureHash = hashHeader(input.paymentSignatureHeader, X402_HEADERS.paymentSignature);
const bodyHash = normalizeHash(input.bodyHash ?? EMPTY_BODY_SHA256, "bodyHash");
const resource = normalizeResourceAlias(input.resource ?? input.intent?.resource);
const base = {
schema: PRIVATE_X402_REQUEST_BINDING_SCHEMA,
protocol: X402_PROTOCOL,
intentHash,
method: normalizeMethod(input.method ?? input.intent?.method),
resourceHash: sha256Hex(resource),
bodyHash,
paymentRequiredHash,
paymentSignatureHash,
};
return {
...base,
replayKey: sha256Hex(base),
};
}
function normalizeReceiptSettlement(settlement, status) {
assertObject(settlement, "settlement");
const normalized = {
cluster: normalizeIdentifier(settlement.cluster, "settlement.cluster"),
programId: normalizeIdentifier(settlement.programId, "settlement.programId"),
};
if (!SUPPORTED_CLUSTER.has(normalized.cluster)) {
fail("settlement.cluster must be devnet, localnet, or mainnet-beta");
}
if (status === "settled") {
if (typeof settlement.signature !== "string" || !BASE58_RE.test(settlement.signature)) {
fail("settled receipt requires a Solana transaction signature");
}
if (!Number.isSafeInteger(settlement.slot) || settlement.slot <= 0) {
fail("settled receipt requires a positive slot");
}
if (!SUPPORTED_CONFIRMATION.has(settlement.confirmationStatus)) {
fail("settled receipt requires a Solana confirmation status");
}
normalized.signature = settlement.signature;
normalized.slot = settlement.slot;
normalized.confirmationStatus = settlement.confirmationStatus;
}
if (settlement.explorerUrl !== undefined) {
normalized.explorerUrl = normalizeIdentifier(settlement.explorerUrl, "settlement.explorerUrl");
}
return normalized;
}
function normalizeProofLock(proof) {
assertObject(proof, "proof");
return {
proofBundleHash: normalizeHash(proof.proofBundleHash, "proof.proofBundleHash"),
publicInputHash: normalizeHash(proof.publicInputHash, "proof.publicInputHash"),
proofEncodingHash: normalizeHash(proof.proofEncodingHash, "proof.proofEncodingHash"),
};
}
function normalizeRepositoryLock(repository) {
assertObject(repository, "repository");
const normalized = {
commit: normalizeCommit(repository.commit),
manifestSha256: normalizeHash(repository.manifestSha256, "repository.manifestSha256"),
};
if (repository.releaseChecksumsSha256 !== undefined) {
normalized.releaseChecksumsSha256 = normalizeHash(
repository.releaseChecksumsSha256,
"repository.releaseChecksumsSha256",
);
}
return normalized;
}
export function createPrivateX402Receipt(input) {
assertObject(input, "input");
const status = input.status ?? "settled";
if (!SUPPORTED_STATUS.has(status)) {
fail("status must be settled or rejected");
}
const requestBinding = input.requestBinding;
assertObject(requestBinding, "requestBinding");
const base = {
schema: PRIVATE_X402_RECEIPT_SCHEMA,
protocol: X402_PROTOCOL,
status,
observedAt: normalizeIsoDate(input.observedAt, "observedAt"),
intentHash: normalizeHash(input.intentHash ?? requestBinding.intentHash, "intentHash"),
replayKey: normalizeHash(requestBinding.replayKey, "requestBinding.replayKey"),
x402: {
paymentRequiredHash: normalizeHash(requestBinding.paymentRequiredHash, "requestBinding.paymentRequiredHash"),
paymentSignatureHash: normalizeHash(requestBinding.paymentSignatureHash, "requestBinding.paymentSignatureHash"),
paymentResponseHash: hashHeader(input.paymentResponseHeader, X402_HEADERS.paymentResponse),
rawHeadersStored: false,
requiredHeaders: [
X402_HEADERS.paymentRequired,
X402_HEADERS.paymentSignature,
X402_HEADERS.paymentResponse,
],
},
request: {
method: normalizeMethod(requestBinding.method),
resourceHash: normalizeHash(requestBinding.resourceHash, "requestBinding.resourceHash"),
bodyHash: normalizeHash(requestBinding.bodyHash, "requestBinding.bodyHash"),
},
response: {
statusCode: Number.isInteger(input.response?.statusCode) ? input.response.statusCode : 200,
bodyHash: normalizeHash(input.response?.bodyHash ?? EMPTY_BODY_SHA256, "response.bodyHash"),
},
privacy: {
rawBuyerMetadataStored: false,
rawPaymentHeadersStored: false,
resourceIsHashed: true,
},
settlement: normalizeReceiptSettlement(input.settlement, status),
proof: normalizeProofLock(input.proof),
repository: normalizeRepositoryLock(input.repository),
lock: {
previousReceiptHash: input.previousReceiptHash === null || input.previousReceiptHash === undefined
? null
: normalizeHash(input.previousReceiptHash, "previousReceiptHash"),
},
};
return {
...base,
lock: {
...base.lock,
receiptHash: sha256Hex(base),
},
};
}
function receiptWithoutHash(receipt) {
const clone = canonicalValue(receipt);
if (!clone.lock || typeof clone.lock !== "object") {
return clone;
}
const { receiptHash, ...lockWithoutHash } = clone.lock;
return {
...clone,
lock: lockWithoutHash,
};
}
export function verifyPrivateX402Receipt(receipt, options = {}) {
const failures = [];
try {
assertObject(receipt, "receipt");
if (receipt.schema !== PRIVATE_X402_RECEIPT_SCHEMA) {
failures.push(`schema must be ${PRIVATE_X402_RECEIPT_SCHEMA}`);
}
if (receipt.protocol !== X402_PROTOCOL) {
failures.push(`protocol must be ${X402_PROTOCOL}`);
}
if (!SUPPORTED_STATUS.has(receipt.status)) {
failures.push("status must be settled or rejected");
}
if (receipt.privacy?.rawBuyerMetadataStored !== false) {
failures.push("privacy.rawBuyerMetadataStored must be false");
}
if (receipt.privacy?.rawPaymentHeadersStored !== false) {
failures.push("privacy.rawPaymentHeadersStored must be false");
}
if (receipt.x402?.rawHeadersStored !== false) {
failures.push("x402.rawHeadersStored must be false");
}
const expectedReceiptHash = sha256Hex(receiptWithoutHash(receipt));
if (receipt.lock?.receiptHash !== expectedReceiptHash) {
failures.push("receipt hash does not match canonical receipt body");
}
if (
options.expectedPreviousReceiptHash !== undefined &&
receipt.lock?.previousReceiptHash !== options.expectedPreviousReceiptHash
) {
failures.push("previous receipt hash mismatch");
}
if (receipt.status === "settled") {
if (!receipt.settlement?.signature || !BASE58_RE.test(receipt.settlement.signature)) {
failures.push("settled receipt must include a Solana transaction signature");
}
if (!Number.isSafeInteger(receipt.settlement?.slot) || receipt.settlement.slot <= 0) {
failures.push("settled receipt must include a positive Solana slot");
}
if (!SUPPORTED_CONFIRMATION.has(receipt.settlement?.confirmationStatus)) {
failures.push("settled receipt must include a supported confirmation status");
}
}
for (const [label, value] of [
["intentHash", receipt.intentHash],
["replayKey", receipt.replayKey],
["x402.paymentRequiredHash", receipt.x402?.paymentRequiredHash],
["x402.paymentSignatureHash", receipt.x402?.paymentSignatureHash],
["x402.paymentResponseHash", receipt.x402?.paymentResponseHash],
["request.bodyHash", receipt.request?.bodyHash],
["request.resourceHash", receipt.request?.resourceHash],
["response.bodyHash", receipt.response?.bodyHash],
["proof.proofBundleHash", receipt.proof?.proofBundleHash],
["proof.publicInputHash", receipt.proof?.publicInputHash],
["proof.proofEncodingHash", receipt.proof?.proofEncodingHash],
["repository.manifestSha256", receipt.repository?.manifestSha256],
]) {
if (typeof value !== "string" || !HASH_RE.test(value)) {
failures.push(`${label} must be a lowercase sha256 hex digest`);
}
}
if (typeof receipt.repository?.commit !== "string" || !COMMIT_RE.test(receipt.repository.commit)) {
failures.push("repository.commit must be a full 40-character lowercase git commit hash");
}
return {
ok: failures.length === 0,
failures,
expectedReceiptHash,
receiptHash: receipt.lock?.receiptHash ?? null,
};
} catch (error) {
return {
ok: false,
failures: [error.message],
expectedReceiptHash: null,
receiptHash: receipt?.lock?.receiptHash ?? null,
};
}
}
export async function verifyPrivateX402ReceiptOnSolana(receipt, connection, options = {}) {
const local = verifyPrivateX402Receipt(receipt, options);
const failures = [...local.failures];
if (!connection || typeof connection.getSignatureStatuses !== "function") {
failures.push("connection must expose getSignatureStatuses");
return { ok: false, failures, signatureStatus: null };
}
if (receipt.status !== "settled") {
return { ok: failures.length === 0, failures, signatureStatus: null };
}
const response = await connection.getSignatureStatuses([receipt.settlement.signature], {
searchTransactionHistory: true,
});
const signatureStatus = response?.value?.[0] ?? null;
if (!signatureStatus) {
failures.push("Solana signature was not found");
} else {
if (signatureStatus.err !== null) {
failures.push("Solana transaction has an error status");
}
if (signatureStatus.slot !== receipt.settlement.slot) {
failures.push(`Solana slot mismatch: expected ${receipt.settlement.slot}, got ${signatureStatus.slot}`);
}
if (
options.minConfirmationStatus === "finalized" &&
signatureStatus.confirmationStatus !== "finalized"
) {
failures.push("Solana transaction is not finalized");
}
}
return {
ok: failures.length === 0,
failures,
signatureStatus,
};
}