x402-receipt 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +57 -3
- package/dist/cjs/index.d.ts +3 -0
- package/dist/cjs/index.js +17 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/types.d.ts +58 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/validate.d.ts +8 -0
- package/dist/cjs/validate.js +48 -0
- package/dist/cjs/verify.d.ts +27 -0
- package/dist/cjs/verify.js +189 -0
- package/dist/esm/index.d.ts +3 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/types.d.ts +58 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/validate.d.ts +8 -0
- package/dist/esm/validate.js +40 -0
- package/dist/esm/verify.d.ts +27 -0
- package/dist/esm/verify.js +181 -0
- package/package.json +47 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kopachelli
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,57 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# x402-receipt
|
|
2
|
+
|
|
3
|
+
Verify x402 payment artifacts before you trust them. Decode `PAYMENT-REQUIRED` / `PAYMENT-SIGNATURE` headers, cross-check scheme, network, amount, and payTo; validate EIP-3009 authorization fields; sanity-check facilitator settlement responses. Zero dependencies, edge-safe.
|
|
4
|
+
|
|
5
|
+
Built by someone who runs a paid x402 API fleet — this is the check we wish every client ran before treating a `200` as "paid".
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { verifyPaymentFlow } from 'x402-receipt';
|
|
9
|
+
|
|
10
|
+
const result = verifyPaymentFlow({
|
|
11
|
+
paymentRequiredHeader: req.headers.get('payment-required') ?? undefined,
|
|
12
|
+
paymentSignatureHeader: req.headers.get('payment-signature') ?? undefined,
|
|
13
|
+
settlement: facilitatorResponse, // what the facilitator returned
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
if (!result.ok) {
|
|
17
|
+
// Don't serve the resource. result.payment.checks / result.settlement.checks
|
|
18
|
+
// tell you exactly which invariant broke.
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## What it checks
|
|
23
|
+
|
|
24
|
+
| Check | What it catches |
|
|
25
|
+
|---|---|
|
|
26
|
+
| `requirement-match` | Signature scheme/network isn't in the server's accepts list |
|
|
27
|
+
| `caip2-network` | Malformed network identifier |
|
|
28
|
+
| `payto-valid` / `authorization-to` | Payment directed at the wrong address |
|
|
29
|
+
| `authorization-value` | Atomic value ≠ required amount (catches decimal/atomic confusion) |
|
|
30
|
+
| `authorization-window` | Expired or not-yet-valid EIP-3009 authorization |
|
|
31
|
+
| `evm-signature-shape` | Truncated/malformed 65-byte signature |
|
|
32
|
+
| `settlement-success` + `transaction-present` | Facilitator said no, or returned no tx |
|
|
33
|
+
| `payer-valid`, `network-accepted` | Settlement payer/network inconsistent with requirements |
|
|
34
|
+
|
|
35
|
+
## Honest limits
|
|
36
|
+
|
|
37
|
+
- **Structural verification, not cryptographic.** The EIP-712/EIP-3009 signature itself is verified by the facilitator during settlement — re-verifying it client-side needs secp256k1 recovery, deliberately out of scope for a zero-dep package. Pair `verifyPayment` (before trusting the payload) with `verifySettlement` (after settlement).
|
|
38
|
+
- `exact` scheme on `eip155:*` and `solana:*` is covered; other schemes/networks get generic checks.
|
|
39
|
+
- Known-asset decimals table covers major USDC deployments; pass `decimals` for anything else.
|
|
40
|
+
|
|
41
|
+
## API
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
decodePaymentRequired(header) → { x402Version, accepts[] }
|
|
45
|
+
decodePaymentSignature(header) → { x402Version, scheme, network, payload }
|
|
46
|
+
verifyPayment(required, signature, opts?) → PaymentVerification
|
|
47
|
+
verifySettlement(required|accept, settlement, opts?) → PaymentVerification
|
|
48
|
+
verifyPaymentFlow({ headers..., settlement? }) → { payment?, settlement?, ok }
|
|
49
|
+
decimalToAtomic('0.005', 6) → 5000n
|
|
50
|
+
isEvmAddress / isSolanaAddress / isCaip2 / isValidAddressFor
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Install
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
npm install x402-receipt
|
|
57
|
+
```
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { decodePaymentRequired, decodePaymentSignature, decimalToAtomic, verifyPayment, verifySettlement, verifyPaymentFlow, } from './verify.js';
|
|
2
|
+
export { isEvmAddress, isSolanaAddress, isCaip2, isEvmTxHash, isValidAddressFor, decimalsForAsset, } from './validate.js';
|
|
3
|
+
export type { X402Required, X402Requirement, X402Signature, X402Settlement, Eip3009Authorization, CheckResult, PaymentVerification, VerifyPaymentOptions, } from './types.js';
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.decimalsForAsset = exports.isValidAddressFor = exports.isEvmTxHash = exports.isCaip2 = exports.isSolanaAddress = exports.isEvmAddress = exports.verifyPaymentFlow = exports.verifySettlement = exports.verifyPayment = exports.decimalToAtomic = exports.decodePaymentSignature = exports.decodePaymentRequired = void 0;
|
|
4
|
+
var verify_js_1 = require("./verify.js");
|
|
5
|
+
Object.defineProperty(exports, "decodePaymentRequired", { enumerable: true, get: function () { return verify_js_1.decodePaymentRequired; } });
|
|
6
|
+
Object.defineProperty(exports, "decodePaymentSignature", { enumerable: true, get: function () { return verify_js_1.decodePaymentSignature; } });
|
|
7
|
+
Object.defineProperty(exports, "decimalToAtomic", { enumerable: true, get: function () { return verify_js_1.decimalToAtomic; } });
|
|
8
|
+
Object.defineProperty(exports, "verifyPayment", { enumerable: true, get: function () { return verify_js_1.verifyPayment; } });
|
|
9
|
+
Object.defineProperty(exports, "verifySettlement", { enumerable: true, get: function () { return verify_js_1.verifySettlement; } });
|
|
10
|
+
Object.defineProperty(exports, "verifyPaymentFlow", { enumerable: true, get: function () { return verify_js_1.verifyPaymentFlow; } });
|
|
11
|
+
var validate_js_1 = require("./validate.js");
|
|
12
|
+
Object.defineProperty(exports, "isEvmAddress", { enumerable: true, get: function () { return validate_js_1.isEvmAddress; } });
|
|
13
|
+
Object.defineProperty(exports, "isSolanaAddress", { enumerable: true, get: function () { return validate_js_1.isSolanaAddress; } });
|
|
14
|
+
Object.defineProperty(exports, "isCaip2", { enumerable: true, get: function () { return validate_js_1.isCaip2; } });
|
|
15
|
+
Object.defineProperty(exports, "isEvmTxHash", { enumerable: true, get: function () { return validate_js_1.isEvmTxHash; } });
|
|
16
|
+
Object.defineProperty(exports, "isValidAddressFor", { enumerable: true, get: function () { return validate_js_1.isValidAddressFor; } });
|
|
17
|
+
Object.defineProperty(exports, "decimalsForAsset", { enumerable: true, get: function () { return validate_js_1.decimalsForAsset; } });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Normalized x402 v1 requirement (superset of v2 fields we check). */
|
|
2
|
+
export interface X402Requirement {
|
|
3
|
+
scheme: string;
|
|
4
|
+
network: string;
|
|
5
|
+
/** Decimal amount the server demands, e.g. "0.005". */
|
|
6
|
+
maxAmountRequired: string;
|
|
7
|
+
payTo: string;
|
|
8
|
+
asset?: string;
|
|
9
|
+
resource?: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface X402Required {
|
|
13
|
+
x402Version: number;
|
|
14
|
+
accepts: X402Requirement[];
|
|
15
|
+
}
|
|
16
|
+
export interface X402Signature {
|
|
17
|
+
x402Version: number;
|
|
18
|
+
scheme: string;
|
|
19
|
+
network: string;
|
|
20
|
+
payload: Record<string, unknown>;
|
|
21
|
+
}
|
|
22
|
+
/** Facilitator settlement response (v1 SettleResponse shape). */
|
|
23
|
+
export interface X402Settlement {
|
|
24
|
+
success: boolean;
|
|
25
|
+
errorReason?: string;
|
|
26
|
+
errorMessage?: string;
|
|
27
|
+
payer?: string;
|
|
28
|
+
transaction?: string;
|
|
29
|
+
network?: string;
|
|
30
|
+
}
|
|
31
|
+
/** EIP-3009 authorization carried in exact-scheme EVM payloads. */
|
|
32
|
+
export interface Eip3009Authorization {
|
|
33
|
+
from: string;
|
|
34
|
+
to: string;
|
|
35
|
+
value: string;
|
|
36
|
+
validAfter: string;
|
|
37
|
+
validBefore: string;
|
|
38
|
+
nonce: string;
|
|
39
|
+
}
|
|
40
|
+
export interface CheckResult {
|
|
41
|
+
name: string;
|
|
42
|
+
ok: boolean;
|
|
43
|
+
detail?: string;
|
|
44
|
+
}
|
|
45
|
+
export interface VerifyPaymentOptions {
|
|
46
|
+
/** Expected recipient override; defaults to requirement.payTo. */
|
|
47
|
+
expectedPayTo?: string;
|
|
48
|
+
/** Decimals for the asset; auto-detected for known USDC deployments. */
|
|
49
|
+
decimals?: number;
|
|
50
|
+
/** Current time, epoch seconds. Default Date.now()/1000. */
|
|
51
|
+
now?: () => number;
|
|
52
|
+
}
|
|
53
|
+
export interface PaymentVerification {
|
|
54
|
+
ok: boolean;
|
|
55
|
+
checks: CheckResult[];
|
|
56
|
+
/** The requirement the signature was matched against, if any. */
|
|
57
|
+
matched?: X402Requirement;
|
|
58
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Address/network sanity checks. No crypto — structural validity only. */
|
|
2
|
+
export declare function isEvmAddress(s: string): boolean;
|
|
3
|
+
export declare function isSolanaAddress(s: string): boolean;
|
|
4
|
+
export declare function isCaip2(network: string): boolean;
|
|
5
|
+
export declare function isEvmTxHash(s: string): boolean;
|
|
6
|
+
/** Best-effort address check per CAIP-2 namespace. */
|
|
7
|
+
export declare function isValidAddressFor(network: string, address: string): boolean;
|
|
8
|
+
export declare function decimalsForAsset(asset?: string): number | undefined;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** Address/network sanity checks. No crypto — structural validity only. */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.isEvmAddress = isEvmAddress;
|
|
5
|
+
exports.isSolanaAddress = isSolanaAddress;
|
|
6
|
+
exports.isCaip2 = isCaip2;
|
|
7
|
+
exports.isEvmTxHash = isEvmTxHash;
|
|
8
|
+
exports.isValidAddressFor = isValidAddressFor;
|
|
9
|
+
exports.decimalsForAsset = decimalsForAsset;
|
|
10
|
+
const EVM_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
11
|
+
const CAIP2_RE = /^[a-z0-9-]+:[a-zA-Z0-9._-]+$/; // eip155:8453, solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp
|
|
12
|
+
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
13
|
+
const TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
14
|
+
function isEvmAddress(s) {
|
|
15
|
+
return EVM_RE.test(s);
|
|
16
|
+
}
|
|
17
|
+
function isSolanaAddress(s) {
|
|
18
|
+
return BASE58_RE.test(s);
|
|
19
|
+
}
|
|
20
|
+
function isCaip2(network) {
|
|
21
|
+
return CAIP2_RE.test(network);
|
|
22
|
+
}
|
|
23
|
+
function isEvmTxHash(s) {
|
|
24
|
+
return TX_HASH_RE.test(s);
|
|
25
|
+
}
|
|
26
|
+
/** Best-effort address check per CAIP-2 namespace. */
|
|
27
|
+
function isValidAddressFor(network, address) {
|
|
28
|
+
const ns = network.split(':')[0];
|
|
29
|
+
if (ns === 'eip155')
|
|
30
|
+
return isEvmAddress(address);
|
|
31
|
+
if (ns === 'solana')
|
|
32
|
+
return isSolanaAddress(address);
|
|
33
|
+
// Unknown namespace: require non-empty printable string.
|
|
34
|
+
return address.length > 0 && address.length <= 128 && !/\s/.test(address);
|
|
35
|
+
}
|
|
36
|
+
/** Known token decimals for common x402 assets. */
|
|
37
|
+
const KNOWN_DECIMALS = {
|
|
38
|
+
'0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': 6, // USDC Base
|
|
39
|
+
'0x036cbd53842c5426634e7929541ec2318f3dcf7e': 6, // USDC Base (checksummed variant)
|
|
40
|
+
'0xaf88d065e77c8cc2239327c5edb3a432268e5831': 6, // USDC Arbitrum
|
|
41
|
+
'0x3c499c542cef5e3811e1192ce70d8cc03d5c3359': 6, // USDC Polygon
|
|
42
|
+
'0xusdceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee': 6,
|
|
43
|
+
};
|
|
44
|
+
function decimalsForAsset(asset) {
|
|
45
|
+
if (!asset)
|
|
46
|
+
return undefined;
|
|
47
|
+
return KNOWN_DECIMALS[asset.toLowerCase()] ?? KNOWN_DECIMALS[asset];
|
|
48
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { X402Required, X402Requirement, X402Signature, X402Settlement, PaymentVerification, VerifyPaymentOptions } from './types.js';
|
|
2
|
+
/** Decode a PAYMENT-REQUIRED header (v1 or v2 shape) into normalized form. */
|
|
3
|
+
export declare function decodePaymentRequired(header: string): X402Required;
|
|
4
|
+
/** Decode a PAYMENT-SIGNATURE header into normalized form. */
|
|
5
|
+
export declare function decodePaymentSignature(header: string): X402Signature;
|
|
6
|
+
/** Parse "0.005" decimal string to atomic units as bigint. */
|
|
7
|
+
export declare function decimalToAtomic(amount: string, decimals: number): bigint;
|
|
8
|
+
/**
|
|
9
|
+
* Cross-check a decoded PAYMENT-SIGNATURE against the server's
|
|
10
|
+
* PAYMENT-REQUIRED accepts list. Structural verification only — the
|
|
11
|
+
* EIP-712/EIP-3009 signature itself is verified by the facilitator; pair
|
|
12
|
+
* this with verifySettlement on the facilitator's response.
|
|
13
|
+
*/
|
|
14
|
+
export declare function verifyPayment(required: X402Required, signature: X402Signature, options?: VerifyPaymentOptions): PaymentVerification;
|
|
15
|
+
/** Sanity-check a facilitator settlement response against what was required. */
|
|
16
|
+
export declare function verifySettlement(required: X402Required | X402Requirement | undefined, settlement: X402Settlement, options?: VerifyPaymentOptions): PaymentVerification;
|
|
17
|
+
/** Convenience: verify signature + settlement together from raw headers. */
|
|
18
|
+
export declare function verifyPaymentFlow(input: {
|
|
19
|
+
paymentRequiredHeader?: string;
|
|
20
|
+
paymentSignatureHeader?: string;
|
|
21
|
+
settlement?: X402Settlement;
|
|
22
|
+
options?: VerifyPaymentOptions;
|
|
23
|
+
}): {
|
|
24
|
+
payment?: PaymentVerification;
|
|
25
|
+
settlement?: PaymentVerification;
|
|
26
|
+
ok: boolean;
|
|
27
|
+
};
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.decodePaymentRequired = decodePaymentRequired;
|
|
4
|
+
exports.decodePaymentSignature = decodePaymentSignature;
|
|
5
|
+
exports.decimalToAtomic = decimalToAtomic;
|
|
6
|
+
exports.verifyPayment = verifyPayment;
|
|
7
|
+
exports.verifySettlement = verifySettlement;
|
|
8
|
+
exports.verifyPaymentFlow = verifyPaymentFlow;
|
|
9
|
+
const validate_js_1 = require("./validate.js");
|
|
10
|
+
function b64json(header) {
|
|
11
|
+
// Headers may arrive raw-base64 or already-decoded depending on client.
|
|
12
|
+
const trimmed = header.trim();
|
|
13
|
+
if (trimmed.startsWith('{'))
|
|
14
|
+
return JSON.parse(trimmed);
|
|
15
|
+
const bin = atob(trimmed);
|
|
16
|
+
const bytes = new Uint8Array(bin.length);
|
|
17
|
+
for (let i = 0; i < bin.length; i++)
|
|
18
|
+
bytes[i] = bin.charCodeAt(i);
|
|
19
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
20
|
+
}
|
|
21
|
+
/** Decode a PAYMENT-REQUIRED header (v1 or v2 shape) into normalized form. */
|
|
22
|
+
function decodePaymentRequired(header) {
|
|
23
|
+
const raw = b64json(header);
|
|
24
|
+
const acceptsRaw = raw.accepts ?? (raw.paymentRequirements ? [raw.paymentRequirements] : []);
|
|
25
|
+
const accepts = acceptsRaw.map((a) => ({
|
|
26
|
+
scheme: a.scheme,
|
|
27
|
+
network: a.network,
|
|
28
|
+
maxAmountRequired: String(a.maxAmountRequired ?? a.amount ?? ''),
|
|
29
|
+
payTo: a.payTo ?? a.pay_to ?? '',
|
|
30
|
+
asset: a.asset,
|
|
31
|
+
resource: a.resource,
|
|
32
|
+
description: a.description,
|
|
33
|
+
}));
|
|
34
|
+
return { x402Version: raw.x402Version ?? 2, accepts };
|
|
35
|
+
}
|
|
36
|
+
/** Decode a PAYMENT-SIGNATURE header into normalized form. */
|
|
37
|
+
function decodePaymentSignature(header) {
|
|
38
|
+
const raw = b64json(header);
|
|
39
|
+
// v2 nests under paymentPayload; v1 is flat.
|
|
40
|
+
const p = raw.paymentPayload ?? raw;
|
|
41
|
+
return {
|
|
42
|
+
x402Version: raw.x402Version ?? p.x402Version ?? 1,
|
|
43
|
+
scheme: p.scheme,
|
|
44
|
+
network: p.network,
|
|
45
|
+
payload: p.payload ?? {},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** Parse "0.005" decimal string to atomic units as bigint. */
|
|
49
|
+
function decimalToAtomic(amount, decimals) {
|
|
50
|
+
const m = amount.trim().match(/^(\d+)(?:\.(\d+))?$/);
|
|
51
|
+
if (!m)
|
|
52
|
+
throw new Error(`invalid decimal amount: ${amount}`);
|
|
53
|
+
const intPart = m[1].replace(/^0+/, '') || '0';
|
|
54
|
+
const frac = (m[2] ?? '').padEnd(decimals, '0').slice(0, decimals);
|
|
55
|
+
// Reject precision loss beyond `decimals`.
|
|
56
|
+
if ((m[2] ?? '').length > decimals && /[1-9]/.test((m[2] ?? '').slice(decimals))) {
|
|
57
|
+
throw new Error(`amount ${amount} exceeds ${decimals} decimals`);
|
|
58
|
+
}
|
|
59
|
+
return BigInt(intPart) * 10n ** BigInt(decimals) + BigInt(frac || '0');
|
|
60
|
+
}
|
|
61
|
+
function extractAuthorization(payload) {
|
|
62
|
+
const auth = (payload.authorization ?? payload.auth);
|
|
63
|
+
if (!auth)
|
|
64
|
+
return null;
|
|
65
|
+
const g = (k) => (auth[k] ?? auth[k.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase())] ?? '');
|
|
66
|
+
return {
|
|
67
|
+
from: String(g('from')),
|
|
68
|
+
to: String(g('to')),
|
|
69
|
+
value: String(g('value')),
|
|
70
|
+
validAfter: String(g('validAfter')),
|
|
71
|
+
validBefore: String(g('validBefore')),
|
|
72
|
+
nonce: String(g('nonce')),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Cross-check a decoded PAYMENT-SIGNATURE against the server's
|
|
77
|
+
* PAYMENT-REQUIRED accepts list. Structural verification only — the
|
|
78
|
+
* EIP-712/EIP-3009 signature itself is verified by the facilitator; pair
|
|
79
|
+
* this with verifySettlement on the facilitator's response.
|
|
80
|
+
*/
|
|
81
|
+
function verifyPayment(required, signature, options = {}) {
|
|
82
|
+
const checks = [];
|
|
83
|
+
const push = (name, ok, detail) => checks.push({ name, ok, detail });
|
|
84
|
+
// 1. Find a matching requirement on scheme + network.
|
|
85
|
+
const matched = required.accepts.find((a) => a.scheme === signature.scheme && a.network === signature.network);
|
|
86
|
+
push('requirement-match', !!matched, matched ? `${signature.scheme} on ${signature.network}` : `no accept entry for ${signature.scheme}/${signature.network}`);
|
|
87
|
+
// 2. Network is CAIP-2.
|
|
88
|
+
push('caip2-network', (0, validate_js_1.isCaip2)(signature.network), signature.network);
|
|
89
|
+
// 3. PayTo address is valid for the network.
|
|
90
|
+
if (matched) {
|
|
91
|
+
const payTo = options.expectedPayTo ?? matched.payTo;
|
|
92
|
+
push('payto-valid', (0, validate_js_1.isValidAddressFor)(signature.network, payTo), payTo);
|
|
93
|
+
}
|
|
94
|
+
// 4. Scheme-specific payload checks.
|
|
95
|
+
const decimals = options.decimals ?? (matched?.asset ? (0, validate_js_1.decimalsForAsset)(matched.asset) : undefined);
|
|
96
|
+
const nowSec = Math.floor((options.now ?? Date.now)() / 1000);
|
|
97
|
+
if (signature.scheme === 'exact') {
|
|
98
|
+
const ns = signature.network.split(':')[0];
|
|
99
|
+
if (ns === 'eip155') {
|
|
100
|
+
const sig = signature.payload.signature;
|
|
101
|
+
push('evm-signature-shape', typeof sig === 'string' && /^0x[0-9a-fA-F]{130}$/.test(sig), typeof sig === 'string' ? `${sig.length} chars` : 'missing');
|
|
102
|
+
const auth = extractAuthorization(signature.payload);
|
|
103
|
+
if (auth) {
|
|
104
|
+
push('authorization-to', matched ? auth.to.toLowerCase() === (options.expectedPayTo ?? matched.payTo).toLowerCase() : (0, validate_js_1.isValidAddressFor)(signature.network, auth.to), auth.to);
|
|
105
|
+
push('authorization-from', (0, validate_js_1.isValidAddressFor)(signature.network, auth.from), auth.from);
|
|
106
|
+
if (matched && decimals !== undefined) {
|
|
107
|
+
try {
|
|
108
|
+
const requiredAtomic = decimalToAtomic(matched.maxAmountRequired, decimals);
|
|
109
|
+
const authValue = BigInt(auth.value);
|
|
110
|
+
push('authorization-value', authValue === requiredAtomic, `auth=${auth.value} required=${requiredAtomic} (atomic)`);
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
push('authorization-value', false, String(e?.message ?? e));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const va = Number(auth.validAfter);
|
|
117
|
+
const vb = Number(auth.validBefore);
|
|
118
|
+
push('authorization-window', Number.isFinite(va) && Number.isFinite(vb) && va <= nowSec + 300 && vb > nowSec, `valid ${va}..${vb}, now ${nowSec}`);
|
|
119
|
+
push('authorization-nonce', /^[0-9a-fA-F]{32}$/.test(auth.nonce.replace(/^0x/, '')) || auth.nonce.length >= 32, auth.nonce.slice(0, 18) + '…');
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
push('authorization-present', false, 'no authorization object in payload');
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
else if (ns === 'solana') {
|
|
126
|
+
const txSig = signature.payload.transaction ?? signature.payload.signature;
|
|
127
|
+
push('solana-tx-shape', typeof txSig === 'string' && /^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(txSig), 'base58 signature');
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return { ok: checks.every((c) => c.ok), checks, matched };
|
|
131
|
+
}
|
|
132
|
+
/** Sanity-check a facilitator settlement response against what was required. */
|
|
133
|
+
function verifySettlement(required, settlement, options = {}) {
|
|
134
|
+
const checks = [];
|
|
135
|
+
const push = (name, ok, detail) => checks.push({ name, ok, detail });
|
|
136
|
+
push('settlement-success', settlement.success === true, settlement.success ? 'ok' : `${settlement.errorReason ?? 'failed'}: ${settlement.errorMessage ?? ''}`.slice(0, 120));
|
|
137
|
+
if (!settlement.success)
|
|
138
|
+
return { ok: false, checks };
|
|
139
|
+
push('transaction-present', typeof settlement.transaction === 'string' && settlement.transaction.length > 0, settlement.transaction?.slice(0, 20));
|
|
140
|
+
if (settlement.payer) {
|
|
141
|
+
const network = settlement.network ?? (Array.isArray(required?.accepts) ? required.accepts[0]?.network : required?.network) ?? '';
|
|
142
|
+
push('payer-valid', (0, validate_js_1.isValidAddressFor)(network, settlement.payer), settlement.payer);
|
|
143
|
+
}
|
|
144
|
+
if (settlement.network)
|
|
145
|
+
push('caip2-network', (0, validate_js_1.isCaip2)(settlement.network), settlement.network);
|
|
146
|
+
// If we know the requirement, confirm network appears in accepts.
|
|
147
|
+
const reqs = Array.isArray(required?.accepts)
|
|
148
|
+
? required.accepts
|
|
149
|
+
: required ? [required] : [];
|
|
150
|
+
if (reqs.length && settlement.network) {
|
|
151
|
+
push('network-accepted', reqs.some((r) => r.network === settlement.network), settlement.network);
|
|
152
|
+
}
|
|
153
|
+
return { ok: checks.every((c) => c.ok), checks };
|
|
154
|
+
}
|
|
155
|
+
/** Convenience: verify signature + settlement together from raw headers. */
|
|
156
|
+
function verifyPaymentFlow(input) {
|
|
157
|
+
const out = { ok: true };
|
|
158
|
+
let required;
|
|
159
|
+
let signature;
|
|
160
|
+
try {
|
|
161
|
+
if (input.paymentRequiredHeader)
|
|
162
|
+
required = decodePaymentRequired(input.paymentRequiredHeader);
|
|
163
|
+
}
|
|
164
|
+
catch (e) {
|
|
165
|
+
out.ok = false;
|
|
166
|
+
out.payment = { ok: false, checks: [{ name: 'decode-required', ok: false, detail: String(e?.message ?? e) }] };
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
if (input.paymentSignatureHeader)
|
|
171
|
+
signature = decodePaymentSignature(input.paymentSignatureHeader);
|
|
172
|
+
}
|
|
173
|
+
catch (e) {
|
|
174
|
+
out.ok = false;
|
|
175
|
+
out.payment = { ok: false, checks: [{ name: 'decode-signature', ok: false, detail: String(e?.message ?? e) }] };
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
178
|
+
if (required && signature) {
|
|
179
|
+
out.payment = verifyPayment(required, signature, input.options);
|
|
180
|
+
if (!out.payment.ok)
|
|
181
|
+
out.ok = false;
|
|
182
|
+
}
|
|
183
|
+
if (input.settlement) {
|
|
184
|
+
out.settlement = verifySettlement(required, input.settlement, input.options);
|
|
185
|
+
if (!out.settlement.ok)
|
|
186
|
+
out.ok = false;
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { decodePaymentRequired, decodePaymentSignature, decimalToAtomic, verifyPayment, verifySettlement, verifyPaymentFlow, } from './verify.js';
|
|
2
|
+
export { isEvmAddress, isSolanaAddress, isCaip2, isEvmTxHash, isValidAddressFor, decimalsForAsset, } from './validate.js';
|
|
3
|
+
export type { X402Required, X402Requirement, X402Signature, X402Settlement, Eip3009Authorization, CheckResult, PaymentVerification, VerifyPaymentOptions, } from './types.js';
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Normalized x402 v1 requirement (superset of v2 fields we check). */
|
|
2
|
+
export interface X402Requirement {
|
|
3
|
+
scheme: string;
|
|
4
|
+
network: string;
|
|
5
|
+
/** Decimal amount the server demands, e.g. "0.005". */
|
|
6
|
+
maxAmountRequired: string;
|
|
7
|
+
payTo: string;
|
|
8
|
+
asset?: string;
|
|
9
|
+
resource?: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface X402Required {
|
|
13
|
+
x402Version: number;
|
|
14
|
+
accepts: X402Requirement[];
|
|
15
|
+
}
|
|
16
|
+
export interface X402Signature {
|
|
17
|
+
x402Version: number;
|
|
18
|
+
scheme: string;
|
|
19
|
+
network: string;
|
|
20
|
+
payload: Record<string, unknown>;
|
|
21
|
+
}
|
|
22
|
+
/** Facilitator settlement response (v1 SettleResponse shape). */
|
|
23
|
+
export interface X402Settlement {
|
|
24
|
+
success: boolean;
|
|
25
|
+
errorReason?: string;
|
|
26
|
+
errorMessage?: string;
|
|
27
|
+
payer?: string;
|
|
28
|
+
transaction?: string;
|
|
29
|
+
network?: string;
|
|
30
|
+
}
|
|
31
|
+
/** EIP-3009 authorization carried in exact-scheme EVM payloads. */
|
|
32
|
+
export interface Eip3009Authorization {
|
|
33
|
+
from: string;
|
|
34
|
+
to: string;
|
|
35
|
+
value: string;
|
|
36
|
+
validAfter: string;
|
|
37
|
+
validBefore: string;
|
|
38
|
+
nonce: string;
|
|
39
|
+
}
|
|
40
|
+
export interface CheckResult {
|
|
41
|
+
name: string;
|
|
42
|
+
ok: boolean;
|
|
43
|
+
detail?: string;
|
|
44
|
+
}
|
|
45
|
+
export interface VerifyPaymentOptions {
|
|
46
|
+
/** Expected recipient override; defaults to requirement.payTo. */
|
|
47
|
+
expectedPayTo?: string;
|
|
48
|
+
/** Decimals for the asset; auto-detected for known USDC deployments. */
|
|
49
|
+
decimals?: number;
|
|
50
|
+
/** Current time, epoch seconds. Default Date.now()/1000. */
|
|
51
|
+
now?: () => number;
|
|
52
|
+
}
|
|
53
|
+
export interface PaymentVerification {
|
|
54
|
+
ok: boolean;
|
|
55
|
+
checks: CheckResult[];
|
|
56
|
+
/** The requirement the signature was matched against, if any. */
|
|
57
|
+
matched?: X402Requirement;
|
|
58
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Address/network sanity checks. No crypto — structural validity only. */
|
|
2
|
+
export declare function isEvmAddress(s: string): boolean;
|
|
3
|
+
export declare function isSolanaAddress(s: string): boolean;
|
|
4
|
+
export declare function isCaip2(network: string): boolean;
|
|
5
|
+
export declare function isEvmTxHash(s: string): boolean;
|
|
6
|
+
/** Best-effort address check per CAIP-2 namespace. */
|
|
7
|
+
export declare function isValidAddressFor(network: string, address: string): boolean;
|
|
8
|
+
export declare function decimalsForAsset(asset?: string): number | undefined;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Address/network sanity checks. No crypto — structural validity only. */
|
|
2
|
+
const EVM_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
3
|
+
const CAIP2_RE = /^[a-z0-9-]+:[a-zA-Z0-9._-]+$/; // eip155:8453, solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp
|
|
4
|
+
const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
5
|
+
const TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
6
|
+
export function isEvmAddress(s) {
|
|
7
|
+
return EVM_RE.test(s);
|
|
8
|
+
}
|
|
9
|
+
export function isSolanaAddress(s) {
|
|
10
|
+
return BASE58_RE.test(s);
|
|
11
|
+
}
|
|
12
|
+
export function isCaip2(network) {
|
|
13
|
+
return CAIP2_RE.test(network);
|
|
14
|
+
}
|
|
15
|
+
export function isEvmTxHash(s) {
|
|
16
|
+
return TX_HASH_RE.test(s);
|
|
17
|
+
}
|
|
18
|
+
/** Best-effort address check per CAIP-2 namespace. */
|
|
19
|
+
export function isValidAddressFor(network, address) {
|
|
20
|
+
const ns = network.split(':')[0];
|
|
21
|
+
if (ns === 'eip155')
|
|
22
|
+
return isEvmAddress(address);
|
|
23
|
+
if (ns === 'solana')
|
|
24
|
+
return isSolanaAddress(address);
|
|
25
|
+
// Unknown namespace: require non-empty printable string.
|
|
26
|
+
return address.length > 0 && address.length <= 128 && !/\s/.test(address);
|
|
27
|
+
}
|
|
28
|
+
/** Known token decimals for common x402 assets. */
|
|
29
|
+
const KNOWN_DECIMALS = {
|
|
30
|
+
'0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': 6, // USDC Base
|
|
31
|
+
'0x036cbd53842c5426634e7929541ec2318f3dcf7e': 6, // USDC Base (checksummed variant)
|
|
32
|
+
'0xaf88d065e77c8cc2239327c5edb3a432268e5831': 6, // USDC Arbitrum
|
|
33
|
+
'0x3c499c542cef5e3811e1192ce70d8cc03d5c3359': 6, // USDC Polygon
|
|
34
|
+
'0xusdceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee': 6,
|
|
35
|
+
};
|
|
36
|
+
export function decimalsForAsset(asset) {
|
|
37
|
+
if (!asset)
|
|
38
|
+
return undefined;
|
|
39
|
+
return KNOWN_DECIMALS[asset.toLowerCase()] ?? KNOWN_DECIMALS[asset];
|
|
40
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { X402Required, X402Requirement, X402Signature, X402Settlement, PaymentVerification, VerifyPaymentOptions } from './types.js';
|
|
2
|
+
/** Decode a PAYMENT-REQUIRED header (v1 or v2 shape) into normalized form. */
|
|
3
|
+
export declare function decodePaymentRequired(header: string): X402Required;
|
|
4
|
+
/** Decode a PAYMENT-SIGNATURE header into normalized form. */
|
|
5
|
+
export declare function decodePaymentSignature(header: string): X402Signature;
|
|
6
|
+
/** Parse "0.005" decimal string to atomic units as bigint. */
|
|
7
|
+
export declare function decimalToAtomic(amount: string, decimals: number): bigint;
|
|
8
|
+
/**
|
|
9
|
+
* Cross-check a decoded PAYMENT-SIGNATURE against the server's
|
|
10
|
+
* PAYMENT-REQUIRED accepts list. Structural verification only — the
|
|
11
|
+
* EIP-712/EIP-3009 signature itself is verified by the facilitator; pair
|
|
12
|
+
* this with verifySettlement on the facilitator's response.
|
|
13
|
+
*/
|
|
14
|
+
export declare function verifyPayment(required: X402Required, signature: X402Signature, options?: VerifyPaymentOptions): PaymentVerification;
|
|
15
|
+
/** Sanity-check a facilitator settlement response against what was required. */
|
|
16
|
+
export declare function verifySettlement(required: X402Required | X402Requirement | undefined, settlement: X402Settlement, options?: VerifyPaymentOptions): PaymentVerification;
|
|
17
|
+
/** Convenience: verify signature + settlement together from raw headers. */
|
|
18
|
+
export declare function verifyPaymentFlow(input: {
|
|
19
|
+
paymentRequiredHeader?: string;
|
|
20
|
+
paymentSignatureHeader?: string;
|
|
21
|
+
settlement?: X402Settlement;
|
|
22
|
+
options?: VerifyPaymentOptions;
|
|
23
|
+
}): {
|
|
24
|
+
payment?: PaymentVerification;
|
|
25
|
+
settlement?: PaymentVerification;
|
|
26
|
+
ok: boolean;
|
|
27
|
+
};
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { isCaip2, isValidAddressFor, decimalsForAsset } from './validate.js';
|
|
2
|
+
function b64json(header) {
|
|
3
|
+
// Headers may arrive raw-base64 or already-decoded depending on client.
|
|
4
|
+
const trimmed = header.trim();
|
|
5
|
+
if (trimmed.startsWith('{'))
|
|
6
|
+
return JSON.parse(trimmed);
|
|
7
|
+
const bin = atob(trimmed);
|
|
8
|
+
const bytes = new Uint8Array(bin.length);
|
|
9
|
+
for (let i = 0; i < bin.length; i++)
|
|
10
|
+
bytes[i] = bin.charCodeAt(i);
|
|
11
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
12
|
+
}
|
|
13
|
+
/** Decode a PAYMENT-REQUIRED header (v1 or v2 shape) into normalized form. */
|
|
14
|
+
export function decodePaymentRequired(header) {
|
|
15
|
+
const raw = b64json(header);
|
|
16
|
+
const acceptsRaw = raw.accepts ?? (raw.paymentRequirements ? [raw.paymentRequirements] : []);
|
|
17
|
+
const accepts = acceptsRaw.map((a) => ({
|
|
18
|
+
scheme: a.scheme,
|
|
19
|
+
network: a.network,
|
|
20
|
+
maxAmountRequired: String(a.maxAmountRequired ?? a.amount ?? ''),
|
|
21
|
+
payTo: a.payTo ?? a.pay_to ?? '',
|
|
22
|
+
asset: a.asset,
|
|
23
|
+
resource: a.resource,
|
|
24
|
+
description: a.description,
|
|
25
|
+
}));
|
|
26
|
+
return { x402Version: raw.x402Version ?? 2, accepts };
|
|
27
|
+
}
|
|
28
|
+
/** Decode a PAYMENT-SIGNATURE header into normalized form. */
|
|
29
|
+
export function decodePaymentSignature(header) {
|
|
30
|
+
const raw = b64json(header);
|
|
31
|
+
// v2 nests under paymentPayload; v1 is flat.
|
|
32
|
+
const p = raw.paymentPayload ?? raw;
|
|
33
|
+
return {
|
|
34
|
+
x402Version: raw.x402Version ?? p.x402Version ?? 1,
|
|
35
|
+
scheme: p.scheme,
|
|
36
|
+
network: p.network,
|
|
37
|
+
payload: p.payload ?? {},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** Parse "0.005" decimal string to atomic units as bigint. */
|
|
41
|
+
export function decimalToAtomic(amount, decimals) {
|
|
42
|
+
const m = amount.trim().match(/^(\d+)(?:\.(\d+))?$/);
|
|
43
|
+
if (!m)
|
|
44
|
+
throw new Error(`invalid decimal amount: ${amount}`);
|
|
45
|
+
const intPart = m[1].replace(/^0+/, '') || '0';
|
|
46
|
+
const frac = (m[2] ?? '').padEnd(decimals, '0').slice(0, decimals);
|
|
47
|
+
// Reject precision loss beyond `decimals`.
|
|
48
|
+
if ((m[2] ?? '').length > decimals && /[1-9]/.test((m[2] ?? '').slice(decimals))) {
|
|
49
|
+
throw new Error(`amount ${amount} exceeds ${decimals} decimals`);
|
|
50
|
+
}
|
|
51
|
+
return BigInt(intPart) * 10n ** BigInt(decimals) + BigInt(frac || '0');
|
|
52
|
+
}
|
|
53
|
+
function extractAuthorization(payload) {
|
|
54
|
+
const auth = (payload.authorization ?? payload.auth);
|
|
55
|
+
if (!auth)
|
|
56
|
+
return null;
|
|
57
|
+
const g = (k) => (auth[k] ?? auth[k.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase())] ?? '');
|
|
58
|
+
return {
|
|
59
|
+
from: String(g('from')),
|
|
60
|
+
to: String(g('to')),
|
|
61
|
+
value: String(g('value')),
|
|
62
|
+
validAfter: String(g('validAfter')),
|
|
63
|
+
validBefore: String(g('validBefore')),
|
|
64
|
+
nonce: String(g('nonce')),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Cross-check a decoded PAYMENT-SIGNATURE against the server's
|
|
69
|
+
* PAYMENT-REQUIRED accepts list. Structural verification only — the
|
|
70
|
+
* EIP-712/EIP-3009 signature itself is verified by the facilitator; pair
|
|
71
|
+
* this with verifySettlement on the facilitator's response.
|
|
72
|
+
*/
|
|
73
|
+
export function verifyPayment(required, signature, options = {}) {
|
|
74
|
+
const checks = [];
|
|
75
|
+
const push = (name, ok, detail) => checks.push({ name, ok, detail });
|
|
76
|
+
// 1. Find a matching requirement on scheme + network.
|
|
77
|
+
const matched = required.accepts.find((a) => a.scheme === signature.scheme && a.network === signature.network);
|
|
78
|
+
push('requirement-match', !!matched, matched ? `${signature.scheme} on ${signature.network}` : `no accept entry for ${signature.scheme}/${signature.network}`);
|
|
79
|
+
// 2. Network is CAIP-2.
|
|
80
|
+
push('caip2-network', isCaip2(signature.network), signature.network);
|
|
81
|
+
// 3. PayTo address is valid for the network.
|
|
82
|
+
if (matched) {
|
|
83
|
+
const payTo = options.expectedPayTo ?? matched.payTo;
|
|
84
|
+
push('payto-valid', isValidAddressFor(signature.network, payTo), payTo);
|
|
85
|
+
}
|
|
86
|
+
// 4. Scheme-specific payload checks.
|
|
87
|
+
const decimals = options.decimals ?? (matched?.asset ? decimalsForAsset(matched.asset) : undefined);
|
|
88
|
+
const nowSec = Math.floor((options.now ?? Date.now)() / 1000);
|
|
89
|
+
if (signature.scheme === 'exact') {
|
|
90
|
+
const ns = signature.network.split(':')[0];
|
|
91
|
+
if (ns === 'eip155') {
|
|
92
|
+
const sig = signature.payload.signature;
|
|
93
|
+
push('evm-signature-shape', typeof sig === 'string' && /^0x[0-9a-fA-F]{130}$/.test(sig), typeof sig === 'string' ? `${sig.length} chars` : 'missing');
|
|
94
|
+
const auth = extractAuthorization(signature.payload);
|
|
95
|
+
if (auth) {
|
|
96
|
+
push('authorization-to', matched ? auth.to.toLowerCase() === (options.expectedPayTo ?? matched.payTo).toLowerCase() : isValidAddressFor(signature.network, auth.to), auth.to);
|
|
97
|
+
push('authorization-from', isValidAddressFor(signature.network, auth.from), auth.from);
|
|
98
|
+
if (matched && decimals !== undefined) {
|
|
99
|
+
try {
|
|
100
|
+
const requiredAtomic = decimalToAtomic(matched.maxAmountRequired, decimals);
|
|
101
|
+
const authValue = BigInt(auth.value);
|
|
102
|
+
push('authorization-value', authValue === requiredAtomic, `auth=${auth.value} required=${requiredAtomic} (atomic)`);
|
|
103
|
+
}
|
|
104
|
+
catch (e) {
|
|
105
|
+
push('authorization-value', false, String(e?.message ?? e));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const va = Number(auth.validAfter);
|
|
109
|
+
const vb = Number(auth.validBefore);
|
|
110
|
+
push('authorization-window', Number.isFinite(va) && Number.isFinite(vb) && va <= nowSec + 300 && vb > nowSec, `valid ${va}..${vb}, now ${nowSec}`);
|
|
111
|
+
push('authorization-nonce', /^[0-9a-fA-F]{32}$/.test(auth.nonce.replace(/^0x/, '')) || auth.nonce.length >= 32, auth.nonce.slice(0, 18) + '…');
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
push('authorization-present', false, 'no authorization object in payload');
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
else if (ns === 'solana') {
|
|
118
|
+
const txSig = signature.payload.transaction ?? signature.payload.signature;
|
|
119
|
+
push('solana-tx-shape', typeof txSig === 'string' && /^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(txSig), 'base58 signature');
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return { ok: checks.every((c) => c.ok), checks, matched };
|
|
123
|
+
}
|
|
124
|
+
/** Sanity-check a facilitator settlement response against what was required. */
|
|
125
|
+
export function verifySettlement(required, settlement, options = {}) {
|
|
126
|
+
const checks = [];
|
|
127
|
+
const push = (name, ok, detail) => checks.push({ name, ok, detail });
|
|
128
|
+
push('settlement-success', settlement.success === true, settlement.success ? 'ok' : `${settlement.errorReason ?? 'failed'}: ${settlement.errorMessage ?? ''}`.slice(0, 120));
|
|
129
|
+
if (!settlement.success)
|
|
130
|
+
return { ok: false, checks };
|
|
131
|
+
push('transaction-present', typeof settlement.transaction === 'string' && settlement.transaction.length > 0, settlement.transaction?.slice(0, 20));
|
|
132
|
+
if (settlement.payer) {
|
|
133
|
+
const network = settlement.network ?? (Array.isArray(required?.accepts) ? required.accepts[0]?.network : required?.network) ?? '';
|
|
134
|
+
push('payer-valid', isValidAddressFor(network, settlement.payer), settlement.payer);
|
|
135
|
+
}
|
|
136
|
+
if (settlement.network)
|
|
137
|
+
push('caip2-network', isCaip2(settlement.network), settlement.network);
|
|
138
|
+
// If we know the requirement, confirm network appears in accepts.
|
|
139
|
+
const reqs = Array.isArray(required?.accepts)
|
|
140
|
+
? required.accepts
|
|
141
|
+
: required ? [required] : [];
|
|
142
|
+
if (reqs.length && settlement.network) {
|
|
143
|
+
push('network-accepted', reqs.some((r) => r.network === settlement.network), settlement.network);
|
|
144
|
+
}
|
|
145
|
+
return { ok: checks.every((c) => c.ok), checks };
|
|
146
|
+
}
|
|
147
|
+
/** Convenience: verify signature + settlement together from raw headers. */
|
|
148
|
+
export function verifyPaymentFlow(input) {
|
|
149
|
+
const out = { ok: true };
|
|
150
|
+
let required;
|
|
151
|
+
let signature;
|
|
152
|
+
try {
|
|
153
|
+
if (input.paymentRequiredHeader)
|
|
154
|
+
required = decodePaymentRequired(input.paymentRequiredHeader);
|
|
155
|
+
}
|
|
156
|
+
catch (e) {
|
|
157
|
+
out.ok = false;
|
|
158
|
+
out.payment = { ok: false, checks: [{ name: 'decode-required', ok: false, detail: String(e?.message ?? e) }] };
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
if (input.paymentSignatureHeader)
|
|
163
|
+
signature = decodePaymentSignature(input.paymentSignatureHeader);
|
|
164
|
+
}
|
|
165
|
+
catch (e) {
|
|
166
|
+
out.ok = false;
|
|
167
|
+
out.payment = { ok: false, checks: [{ name: 'decode-signature', ok: false, detail: String(e?.message ?? e) }] };
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
if (required && signature) {
|
|
171
|
+
out.payment = verifyPayment(required, signature, input.options);
|
|
172
|
+
if (!out.payment.ok)
|
|
173
|
+
out.ok = false;
|
|
174
|
+
}
|
|
175
|
+
if (input.settlement) {
|
|
176
|
+
out.settlement = verifySettlement(required, input.settlement, input.options);
|
|
177
|
+
if (!out.settlement.ok)
|
|
178
|
+
out.ok = false;
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "x402-receipt",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "x402-receipt",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Verify x402 payment artifacts before you trust them: decode PAYMENT-REQUIRED/PAYMENT-SIGNATURE headers, cross-check scheme/network/amount/payTo, validate EIP-3009 authorization fields, and sanity-check facilitator settlement responses. Zero dependencies, transport-agnostic.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"x402",
|
|
7
|
+
"payments",
|
|
8
|
+
"verification",
|
|
9
|
+
"usdc",
|
|
10
|
+
"agent-payments",
|
|
11
|
+
"receipt"
|
|
12
|
+
],
|
|
13
|
+
"type": "module",
|
|
14
|
+
"main": "./dist/cjs/index.js",
|
|
15
|
+
"module": "./dist/esm/index.js",
|
|
16
|
+
"types": "./dist/esm/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/esm/index.d.ts",
|
|
20
|
+
"import": "./dist/esm/index.js",
|
|
21
|
+
"require": "./dist/cjs/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=22.13.0"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "npm run build:esm && npm run build:cjs",
|
|
32
|
+
"build:esm": "tsc -p tsconfig.esm.json",
|
|
33
|
+
"build:cjs": "tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json', JSON.stringify({type:'commonjs'}))\"",
|
|
34
|
+
"test": "npm run build && node --test \"test/**/*.test.ts\"",
|
|
35
|
+
"prepublishOnly": "npm run build"
|
|
36
|
+
},
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/Kopachelli/x402-receipt.git"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/node": "^24.19.4",
|
|
44
|
+
"typescript": "^5.9.3"
|
|
45
|
+
},
|
|
46
|
+
"sideEffects": false
|
|
47
|
+
}
|