@absol-labs/agent 0.10.0 → 0.12.0-rc.1
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 +106 -30
- package/dist/capability/invocation-capability.d.ts +20 -8
- package/dist/capability/invocation-capability.d.ts.map +1 -1
- package/dist/capability/invocation-capability.js.map +1 -1
- package/dist/capability/probe-capability.d.ts +225 -0
- package/dist/capability/probe-capability.d.ts.map +1 -0
- package/dist/capability/probe-capability.js +248 -0
- package/dist/capability/probe-capability.js.map +1 -0
- package/dist/cli/args.d.ts +11 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +23 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/commands/claim.d.ts.map +1 -1
- package/dist/cli/commands/claim.js +21 -5
- package/dist/cli/commands/claim.js.map +1 -1
- package/dist/cli/commands/close.d.ts.map +1 -1
- package/dist/cli/commands/close.js +51 -7
- package/dist/cli/commands/close.js.map +1 -1
- package/dist/cli/commands/invoke.d.ts +2 -0
- package/dist/cli/commands/invoke.d.ts.map +1 -1
- package/dist/cli/commands/invoke.js +3 -2
- package/dist/cli/commands/invoke.js.map +1 -1
- package/dist/cli/commands/mcp.d.ts.map +1 -1
- package/dist/cli/commands/mcp.js +15 -2
- package/dist/cli/commands/mcp.js.map +1 -1
- package/dist/cli/commands/open.d.ts.map +1 -1
- package/dist/cli/commands/open.js +121 -15
- package/dist/cli/commands/open.js.map +1 -1
- package/dist/cli/commands/pay.d.ts +19 -0
- package/dist/cli/commands/pay.d.ts.map +1 -0
- package/dist/cli/commands/pay.js +355 -0
- package/dist/cli/commands/pay.js.map +1 -0
- package/dist/cli/commands/reclaim-unverified.d.ts.map +1 -1
- package/dist/cli/commands/reclaim-unverified.js +15 -6
- package/dist/cli/commands/reclaim-unverified.js.map +1 -1
- package/dist/cli/commands/reclaim.d.ts +23 -2
- package/dist/cli/commands/reclaim.d.ts.map +1 -1
- package/dist/cli/commands/reclaim.js +200 -21
- package/dist/cli/commands/reclaim.js.map +1 -1
- package/dist/cli/commands/refund.d.ts +13 -0
- package/dist/cli/commands/refund.d.ts.map +1 -0
- package/dist/cli/commands/refund.js +224 -0
- package/dist/cli/commands/refund.js.map +1 -0
- package/dist/cli/commands/status.d.ts.map +1 -1
- package/dist/cli/commands/status.js +10 -1
- package/dist/cli/commands/status.js.map +1 -1
- package/dist/cli/commands/streams.js +9 -13
- package/dist/cli/commands/streams.js.map +1 -1
- package/dist/cli/commands/watch.d.ts.map +1 -1
- package/dist/cli/commands/watch.js +2 -1
- package/dist/cli/commands/watch.js.map +1 -1
- package/dist/cli/config.d.ts +44 -26
- package/dist/cli/config.d.ts.map +1 -1
- package/dist/cli/config.js +88 -38
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/deps.d.ts +86 -7
- package/dist/cli/deps.d.ts.map +1 -1
- package/dist/cli/deps.js +102 -16
- package/dist/cli/deps.js.map +1 -1
- package/dist/cli/errors.d.ts.map +1 -1
- package/dist/cli/errors.js +21 -1
- package/dist/cli/errors.js.map +1 -1
- package/dist/cli/escape-hatch.d.ts +6 -4
- package/dist/cli/escape-hatch.d.ts.map +1 -1
- package/dist/cli/escape-hatch.js +6 -2
- package/dist/cli/escape-hatch.js.map +1 -1
- package/dist/cli/listings.d.ts +18 -0
- package/dist/cli/listings.d.ts.map +1 -1
- package/dist/cli/listings.js +22 -12
- package/dist/cli/listings.js.map +1 -1
- package/dist/cli/preflight.d.ts +20 -14
- package/dist/cli/preflight.d.ts.map +1 -1
- package/dist/cli/preflight.js +34 -20
- package/dist/cli/preflight.js.map +1 -1
- package/dist/cli/privy.d.ts +83 -0
- package/dist/cli/privy.d.ts.map +1 -0
- package/dist/cli/privy.js +232 -0
- package/dist/cli/privy.js.map +1 -0
- package/dist/cli/reclaimability.d.ts +82 -0
- package/dist/cli/reclaimability.d.ts.map +1 -0
- package/dist/cli/reclaimability.js +80 -0
- package/dist/cli/reclaimability.js.map +1 -0
- package/dist/cli/run.d.ts +2 -1
- package/dist/cli/run.d.ts.map +1 -1
- package/dist/cli/run.js +40 -11
- package/dist/cli/run.js.map +1 -1
- package/dist/cli/scan-range.d.ts +2 -2
- package/dist/cli/scan-range.js +2 -2
- package/dist/cli/spend-policy.d.ts +60 -0
- package/dist/cli/spend-policy.d.ts.map +1 -0
- package/dist/cli/spend-policy.js +65 -0
- package/dist/cli/spend-policy.js.map +1 -0
- package/dist/cli/status.d.ts +3 -1
- package/dist/cli/status.d.ts.map +1 -1
- package/dist/cli/status.js +15 -3
- package/dist/cli/status.js.map +1 -1
- package/dist/cli/wallet.d.ts +109 -40
- package/dist/cli/wallet.d.ts.map +1 -1
- package/dist/cli/wallet.js +109 -44
- package/dist/cli/wallet.js.map +1 -1
- package/dist/discovery/rate-band.d.ts +74 -0
- package/dist/discovery/rate-band.d.ts.map +1 -0
- package/dist/discovery/rate-band.js +114 -0
- package/dist/discovery/rate-band.js.map +1 -0
- package/dist/escrow-generation.d.ts +81 -0
- package/dist/escrow-generation.d.ts.map +1 -0
- package/dist/escrow-generation.js +76 -0
- package/dist/escrow-generation.js.map +1 -0
- package/dist/frameworks/agentkit.d.ts +8 -4
- package/dist/frameworks/agentkit.d.ts.map +1 -1
- package/dist/frameworks/agentkit.js +27 -10
- package/dist/frameworks/agentkit.js.map +1 -1
- package/dist/frameworks/eliza.d.ts +3 -3
- package/dist/frameworks/eliza.d.ts.map +1 -1
- package/dist/frameworks/eliza.js +15 -6
- package/dist/frameworks/eliza.js.map +1 -1
- package/dist/frameworks/langchain.d.ts.map +1 -1
- package/dist/frameworks/langchain.js +8 -0
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/gateway/caller-auth-gateway.d.ts +91 -4
- package/dist/gateway/caller-auth-gateway.d.ts.map +1 -1
- package/dist/gateway/caller-auth-gateway.js +184 -7
- package/dist/gateway/caller-auth-gateway.js.map +1 -1
- package/dist/gateway/http-server.d.ts +121 -1
- package/dist/gateway/http-server.d.ts.map +1 -1
- package/dist/gateway/http-server.js +474 -5
- package/dist/gateway/http-server.js.map +1 -1
- package/dist/gateway/probe-auth.d.ts +112 -0
- package/dist/gateway/probe-auth.d.ts.map +1 -0
- package/dist/gateway/probe-auth.js +127 -0
- package/dist/gateway/probe-auth.js.map +1 -0
- package/dist/gateway/signed-rate-bounds.d.ts +51 -0
- package/dist/gateway/signed-rate-bounds.d.ts.map +1 -0
- package/dist/gateway/signed-rate-bounds.js +94 -0
- package/dist/gateway/signed-rate-bounds.js.map +1 -0
- package/dist/gateway/x402-opener-mode.d.ts +215 -0
- package/dist/gateway/x402-opener-mode.d.ts.map +1 -0
- package/dist/gateway/x402-opener-mode.js +639 -0
- package/dist/gateway/x402-opener-mode.js.map +1 -0
- package/dist/index.d.ts +11 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -5
- package/dist/index.js.map +1 -1
- package/dist/mandates/env.d.ts +3 -2
- package/dist/mandates/env.d.ts.map +1 -1
- package/dist/mandates/env.js +3 -2
- package/dist/mandates/env.js.map +1 -1
- package/dist/mcp/server.d.ts +100 -0
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +719 -39
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/service-invoker.d.ts +97 -0
- package/dist/mcp/service-invoker.d.ts.map +1 -0
- package/dist/mcp/service-invoker.js +167 -0
- package/dist/mcp/service-invoker.js.map +1 -0
- package/dist/mcp/x402-tools.d.ts +104 -0
- package/dist/mcp/x402-tools.d.ts.map +1 -0
- package/dist/mcp/x402-tools.js +434 -0
- package/dist/mcp/x402-tools.js.map +1 -0
- package/dist/network.d.ts +119 -0
- package/dist/network.d.ts.map +1 -0
- package/dist/network.js +199 -0
- package/dist/network.js.map +1 -0
- package/dist/sdk/invoke.d.ts +23 -4
- package/dist/sdk/invoke.d.ts.map +1 -1
- package/dist/sdk/invoke.js +71 -10
- package/dist/sdk/invoke.js.map +1 -1
- package/dist/wallet/autonomous-wallet-broker.d.ts +3 -0
- package/dist/wallet/autonomous-wallet-broker.d.ts.map +1 -1
- package/dist/wallet/autonomous-wallet-broker.js +27 -23
- package/dist/wallet/autonomous-wallet-broker.js.map +1 -1
- package/dist/wallet/autonomous-wallet-protocol.d.ts +8 -2
- package/dist/wallet/autonomous-wallet-protocol.d.ts.map +1 -1
- package/dist/wallet/autonomous-wallet-protocol.js +9 -2
- package/dist/wallet/autonomous-wallet-protocol.js.map +1 -1
- package/dist/wallet/autonomous-wallet.d.ts.map +1 -1
- package/dist/wallet/autonomous-wallet.js +3 -2
- package/dist/wallet/autonomous-wallet.js.map +1 -1
- package/dist/wallet/broker-escrows.d.ts +222 -0
- package/dist/wallet/broker-escrows.d.ts.map +1 -0
- package/dist/wallet/broker-escrows.js +36 -0
- package/dist/wallet/broker-escrows.js.map +1 -0
- package/dist/wallet/lifecycle.d.ts +21 -5
- package/dist/wallet/lifecycle.d.ts.map +1 -1
- package/dist/wallet/lifecycle.js +32 -12
- package/dist/wallet/lifecycle.js.map +1 -1
- package/dist/wallet/privy-broker-server.d.ts.map +1 -1
- package/dist/wallet/privy-broker-server.js +31 -26
- package/dist/wallet/privy-broker-server.js.map +1 -1
- package/dist/wallet/privy-session-broker.d.ts +14 -5
- package/dist/wallet/privy-session-broker.d.ts.map +1 -1
- package/dist/wallet/privy-session-broker.js +29 -17
- package/dist/wallet/privy-session-broker.js.map +1 -1
- package/dist/wallet/privy-session-provider.d.ts +3 -1
- package/dist/wallet/privy-session-provider.d.ts.map +1 -1
- package/dist/wallet/privy-session-provider.js +5 -3
- package/dist/wallet/privy-session-provider.js.map +1 -1
- package/dist/wallet/provider.d.ts.map +1 -1
- package/dist/wallet/provider.js +15 -8
- package/dist/wallet/provider.js.map +1 -1
- package/dist/x402/facilitator.d.ts +42 -17
- package/dist/x402/facilitator.d.ts.map +1 -1
- package/dist/x402/facilitator.js +49 -33
- package/dist/x402/facilitator.js.map +1 -1
- package/dist/x402-buyer/guarded-fetch.d.ts +51 -0
- package/dist/x402-buyer/guarded-fetch.d.ts.map +1 -0
- package/dist/x402-buyer/guarded-fetch.js +147 -0
- package/dist/x402-buyer/guarded-fetch.js.map +1 -0
- package/dist/x402-buyer/index.d.ts +10 -0
- package/dist/x402-buyer/index.d.ts.map +1 -0
- package/dist/x402-buyer/index.js +10 -0
- package/dist/x402-buyer/index.js.map +1 -0
- package/dist/x402-buyer/pay.d.ts +135 -0
- package/dist/x402-buyer/pay.d.ts.map +1 -0
- package/dist/x402-buyer/pay.js +336 -0
- package/dist/x402-buyer/pay.js.map +1 -0
- package/dist/x402-opener/abi.d.ts +684 -0
- package/dist/x402-opener/abi.d.ts.map +1 -0
- package/dist/x402-opener/abi.js +880 -0
- package/dist/x402-opener/abi.js.map +1 -0
- package/dist/x402-opener/facilitator-entry.d.ts +3 -0
- package/dist/x402-opener/facilitator-entry.d.ts.map +1 -0
- package/dist/x402-opener/facilitator-entry.js +37 -0
- package/dist/x402-opener/facilitator-entry.js.map +1 -0
- package/dist/x402-opener/facilitator-server.d.ts +180 -0
- package/dist/x402-opener/facilitator-server.d.ts.map +1 -0
- package/dist/x402-opener/facilitator-server.js +696 -0
- package/dist/x402-opener/facilitator-server.js.map +1 -0
- package/dist/x402-opener/index.d.ts +14 -0
- package/dist/x402-opener/index.d.ts.map +1 -0
- package/dist/x402-opener/index.js +14 -0
- package/dist/x402-opener/index.js.map +1 -0
- package/dist/x402-opener/listing-resolver.d.ts +55 -0
- package/dist/x402-opener/listing-resolver.d.ts.map +1 -0
- package/dist/x402-opener/listing-resolver.js +125 -0
- package/dist/x402-opener/listing-resolver.js.map +1 -0
- package/dist/x402-opener/refund-relay.d.ts +240 -0
- package/dist/x402-opener/refund-relay.d.ts.map +1 -0
- package/dist/x402-opener/refund-relay.js +1240 -0
- package/dist/x402-opener/refund-relay.js.map +1 -0
- package/dist/x402-opener/relayer-queue.d.ts +14 -0
- package/dist/x402-opener/relayer-queue.d.ts.map +1 -0
- package/dist/x402-opener/relayer-queue.js +18 -0
- package/dist/x402-opener/relayer-queue.js.map +1 -0
- package/dist/x402-opener/scheme.d.ts +217 -0
- package/dist/x402-opener/scheme.d.ts.map +1 -0
- package/dist/x402-opener/scheme.js +749 -0
- package/dist/x402-opener/scheme.js.map +1 -0
- package/dist/x402-opener/terms.d.ts +105 -0
- package/dist/x402-opener/terms.d.ts.map +1 -0
- package/dist/x402-opener/terms.js +212 -0
- package/dist/x402-opener/terms.js.map +1 -0
- package/dist/zktls/reclaim.d.ts +2 -2
- package/docs/agent-layer.md +13 -8
- package/docs/autonomous-privy-wallet.md +188 -0
- package/docs/cli.md +342 -53
- package/docs/langchain.md +5 -0
- package/docs/mcp-hosted.md +4 -3
- package/docs/mcp-reference.md +245 -0
- package/docs/probe-capability.md +191 -0
- package/docs/quickstart.md +54 -5
- package/docs/threat-model.md +24 -3
- package/docs/x402.md +681 -0
- package/package.json +19 -6
- package/src/capability/invocation-capability.ts +17 -1
- package/src/capability/probe-capability.ts +355 -0
- package/src/cli/args.ts +29 -0
- package/src/cli/commands/claim.ts +31 -5
- package/src/cli/commands/close.ts +56 -7
- package/src/cli/commands/invoke.ts +6 -2
- package/src/cli/commands/mcp.ts +18 -2
- package/src/cli/commands/open.ts +151 -14
- package/src/cli/commands/pay.ts +442 -0
- package/src/cli/commands/reclaim-unverified.ts +24 -6
- package/src/cli/commands/reclaim.ts +274 -19
- package/src/cli/commands/refund.ts +277 -0
- package/src/cli/commands/status.ts +17 -1
- package/src/cli/commands/streams.ts +11 -15
- package/src/cli/commands/watch.ts +7 -1
- package/src/cli/config.ts +139 -52
- package/src/cli/deps.ts +189 -25
- package/src/cli/errors.ts +24 -1
- package/src/cli/escape-hatch.ts +19 -5
- package/src/cli/listings.ts +43 -10
- package/src/cli/preflight.ts +36 -21
- package/src/cli/privy.ts +398 -0
- package/src/cli/reclaimability.ts +154 -0
- package/src/cli/run.ts +54 -11
- package/src/cli/scan-range.ts +2 -2
- package/src/cli/spend-policy.ts +139 -0
- package/src/cli/status.ts +14 -1
- package/src/cli/wallet.ts +189 -58
- package/src/discovery/rate-band.ts +172 -0
- package/src/escrow-generation.ts +135 -0
- package/src/frameworks/agentkit.ts +45 -11
- package/src/frameworks/eliza.ts +27 -5
- package/src/frameworks/langchain.ts +14 -0
- package/src/gateway/caller-auth-gateway.ts +336 -13
- package/src/gateway/http-server.ts +690 -7
- package/src/gateway/probe-auth.ts +191 -0
- package/src/gateway/signed-rate-bounds.ts +164 -0
- package/src/gateway/x402-opener-mode.ts +974 -0
- package/src/index.ts +112 -14
- package/src/mandates/env.ts +3 -2
- package/src/mcp/server.ts +973 -44
- package/src/mcp/service-invoker.ts +285 -0
- package/src/mcp/x402-tools.ts +621 -0
- package/src/network.ts +302 -0
- package/src/sdk/invoke.ts +96 -17
- package/src/wallet/autonomous-wallet-broker.ts +46 -20
- package/src/wallet/autonomous-wallet-protocol.ts +11 -2
- package/src/wallet/autonomous-wallet.ts +4 -2
- package/src/wallet/broker-escrows.ts +66 -0
- package/src/wallet/lifecycle.ts +53 -18
- package/src/wallet/privy-broker-server.ts +35 -25
- package/src/wallet/privy-session-broker.ts +58 -25
- package/src/wallet/privy-session-provider.ts +7 -3
- package/src/wallet/provider.ts +20 -15
- package/src/x402/facilitator.ts +85 -46
- package/src/x402-buyer/guarded-fetch.ts +213 -0
- package/src/x402-buyer/index.ts +9 -0
- package/src/x402-buyer/pay.ts +517 -0
- package/src/x402-opener/abi.ts +881 -0
- package/src/x402-opener/facilitator-entry.ts +45 -0
- package/src/x402-opener/facilitator-server.ts +1014 -0
- package/src/x402-opener/index.ts +13 -0
- package/src/x402-opener/listing-resolver.ts +202 -0
- package/src/x402-opener/refund-relay.ts +1743 -0
- package/src/x402-opener/relayer-queue.ts +18 -0
- package/src/x402-opener/scheme.ts +1133 -0
- package/src/x402-opener/terms.ts +300 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { lookup as dnsLookup } from "node:dns/promises";
|
|
2
|
+
import { isIP } from "node:net";
|
|
3
|
+
/** A request the guard refused; nothing was sent. */
|
|
4
|
+
export class OutboundRequestRefusedError extends Error {
|
|
5
|
+
constructor(reason) {
|
|
6
|
+
super(`outbound request refused: ${reason}`);
|
|
7
|
+
this.name = "OutboundRequestRefusedError";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const defaultLookup = async (hostname) => await dnsLookup(hostname, { all: true, verbatim: true });
|
|
11
|
+
function ipv4ToInt(address) {
|
|
12
|
+
return address.split(".").reduce((acc, part) => acc * 256 + Number(part), 0);
|
|
13
|
+
}
|
|
14
|
+
const BLOCKED_V4 = [
|
|
15
|
+
["0.0.0.0", 8],
|
|
16
|
+
["10.0.0.0", 8],
|
|
17
|
+
["100.64.0.0", 10],
|
|
18
|
+
["127.0.0.0", 8],
|
|
19
|
+
["169.254.0.0", 16],
|
|
20
|
+
["172.16.0.0", 12],
|
|
21
|
+
["192.0.0.0", 24],
|
|
22
|
+
["192.0.2.0", 24],
|
|
23
|
+
["192.168.0.0", 16],
|
|
24
|
+
["198.18.0.0", 15],
|
|
25
|
+
["198.51.100.0", 24],
|
|
26
|
+
["203.0.113.0", 24],
|
|
27
|
+
["224.0.0.0", 4],
|
|
28
|
+
["240.0.0.0", 4],
|
|
29
|
+
];
|
|
30
|
+
function blockedV4(address) {
|
|
31
|
+
const value = ipv4ToInt(address);
|
|
32
|
+
return BLOCKED_V4.some(([base, bits]) => {
|
|
33
|
+
const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
|
|
34
|
+
return (value & mask) >>> 0 === (ipv4ToInt(base) & mask) >>> 0;
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function blockedV6(raw) {
|
|
38
|
+
const address = raw.toLowerCase().replace(/^\[|\]$/g, "");
|
|
39
|
+
if (address === "::" || address === "::1")
|
|
40
|
+
return true;
|
|
41
|
+
// IPv4-mapped / -compatible: judge the embedded IPv4 address.
|
|
42
|
+
const mapped = /^(?:::ffff:|::)(\d+\.\d+\.\d+\.\d+)$/.exec(address);
|
|
43
|
+
if (mapped?.[1] !== undefined)
|
|
44
|
+
return blockedV4(mapped[1]);
|
|
45
|
+
const hexMapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address);
|
|
46
|
+
if (hexMapped?.[1] !== undefined && hexMapped[2] !== undefined) {
|
|
47
|
+
const hi = parseInt(hexMapped[1], 16);
|
|
48
|
+
const lo = parseInt(hexMapped[2], 16);
|
|
49
|
+
return blockedV4(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
|
|
50
|
+
}
|
|
51
|
+
const first = parseInt(address.split(":")[0] || "0", 16);
|
|
52
|
+
return ((first & 0xfe00) === 0xfc00 || // fc00::/7 unique local
|
|
53
|
+
(first & 0xffc0) === 0xfe80 || // fe80::/10 link-local
|
|
54
|
+
(first & 0xffc0) === 0xfec0 || // fec0::/10 site-local (deprecated)
|
|
55
|
+
(first & 0xff00) === 0xff00 || // ff00::/8 multicast
|
|
56
|
+
address.startsWith("64:ff9b:") || // NAT64 (embeds IPv4)
|
|
57
|
+
address.startsWith("2001:db8:") // documentation
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
/** Whether an IP literal is in a range an outbound x402 request must not reach. */
|
|
61
|
+
export function isBlockedAddress(address) {
|
|
62
|
+
const bare = address.replace(/^\[|\]$/g, "");
|
|
63
|
+
const family = isIP(bare);
|
|
64
|
+
if (family === 4)
|
|
65
|
+
return blockedV4(bare);
|
|
66
|
+
if (family === 6)
|
|
67
|
+
return blockedV6(bare);
|
|
68
|
+
return true; // not an IP: never "safe" by default
|
|
69
|
+
}
|
|
70
|
+
function hostAllowed(hostname, allowed) {
|
|
71
|
+
const host = hostname.toLowerCase();
|
|
72
|
+
return allowed.some((entry) => {
|
|
73
|
+
const rule = entry.trim().toLowerCase();
|
|
74
|
+
if (rule.startsWith("*."))
|
|
75
|
+
return host.endsWith(rule.slice(1));
|
|
76
|
+
return host === rule;
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/** Validate one URL against the guard; throws {@link OutboundRequestRefusedError}. */
|
|
80
|
+
export async function assertOutboundUrlAllowed(raw, options = {}) {
|
|
81
|
+
let url;
|
|
82
|
+
try {
|
|
83
|
+
url = new URL(String(raw));
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
throw new OutboundRequestRefusedError(`"${String(raw)}" is not a URL`);
|
|
87
|
+
}
|
|
88
|
+
const allowPrivate = options.allowPrivateNetworks === true;
|
|
89
|
+
if (url.protocol !== "https:" &&
|
|
90
|
+
!(url.protocol === "http:" && allowPrivate)) {
|
|
91
|
+
throw new OutboundRequestRefusedError(`${url.protocol} is not allowed (https only)`);
|
|
92
|
+
}
|
|
93
|
+
if (url.username !== "" || url.password !== "") {
|
|
94
|
+
throw new OutboundRequestRefusedError("credentials in the URL");
|
|
95
|
+
}
|
|
96
|
+
const hostname = url.hostname.replace(/^\[|\]$/g, "");
|
|
97
|
+
if (options.allowedHosts !== undefined &&
|
|
98
|
+
options.allowedHosts.length > 0 &&
|
|
99
|
+
!hostAllowed(hostname, options.allowedHosts)) {
|
|
100
|
+
throw new OutboundRequestRefusedError(`${hostname} is not in METRIK_AGENT_X402_ALLOWED_HOSTS`);
|
|
101
|
+
}
|
|
102
|
+
if (allowPrivate)
|
|
103
|
+
return url;
|
|
104
|
+
if (isIP(hostname) !== 0) {
|
|
105
|
+
if (isBlockedAddress(hostname)) {
|
|
106
|
+
throw new OutboundRequestRefusedError(`${hostname} is a loopback, private, link-local or reserved address`);
|
|
107
|
+
}
|
|
108
|
+
return url;
|
|
109
|
+
}
|
|
110
|
+
if (hostname === "localhost" || hostname.endsWith(".localhost")) {
|
|
111
|
+
throw new OutboundRequestRefusedError(`${hostname} is loopback`);
|
|
112
|
+
}
|
|
113
|
+
let addresses;
|
|
114
|
+
try {
|
|
115
|
+
addresses = await (options.lookup ?? defaultLookup)(hostname);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
throw new OutboundRequestRefusedError(`${hostname} did not resolve`);
|
|
119
|
+
}
|
|
120
|
+
if (addresses.length === 0) {
|
|
121
|
+
throw new OutboundRequestRefusedError(`${hostname} did not resolve`);
|
|
122
|
+
}
|
|
123
|
+
const blocked = addresses.find((entry) => isBlockedAddress(entry.address));
|
|
124
|
+
if (blocked !== undefined) {
|
|
125
|
+
throw new OutboundRequestRefusedError(`${hostname} resolves to ${blocked.address}, a loopback, private, link-local or reserved address`);
|
|
126
|
+
}
|
|
127
|
+
return url;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* A `fetch` that applies {@link assertOutboundUrlAllowed} to every request and
|
|
131
|
+
* never follows a redirect.
|
|
132
|
+
*/
|
|
133
|
+
export function createGuardedFetch(options = {}) {
|
|
134
|
+
const base = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
135
|
+
const guarded = async (input, init) => {
|
|
136
|
+
const target = input instanceof Request ? input.url : input;
|
|
137
|
+
await assertOutboundUrlAllowed(target, options);
|
|
138
|
+
const response = await base(input, { ...init, redirect: "manual" });
|
|
139
|
+
if (response.type === "opaqueredirect" ||
|
|
140
|
+
(response.status >= 300 && response.status < 400)) {
|
|
141
|
+
throw new OutboundRequestRefusedError(`${new URL(String(target)).host} answered with a redirect (${response.status}), which is never followed`);
|
|
142
|
+
}
|
|
143
|
+
return response;
|
|
144
|
+
};
|
|
145
|
+
return guarded;
|
|
146
|
+
}
|
|
147
|
+
//# sourceMappingURL=guarded-fetch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guarded-fetch.js","sourceRoot":"","sources":["../../src/x402-buyer/guarded-fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAyChC,qDAAqD;AACrD,MAAM,OAAO,2BAA4B,SAAQ,KAAK;IACpD,YAAY,MAAc;QACxB,KAAK,CAAC,6BAA6B,MAAM,EAAE,CAAC,CAAC;QAC7C,IAA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,MAAM,MAAM,GAAG,KAAK,YAAY,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC;QAC5D,MAAM,wBAAwB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAChD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAC;QACpE,IACE,QAAQ,CAAC,IAAI,KAAK,gBAAgB;YAClC,CAAC,QAAQ,CAAC,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC,EACjD,CAAC;YACD,MAAM,IAAI,2BAA2B,CACnC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,8BAA8B,QAAQ,CAAC,MAAM,4BAA4B,CACzG,CAAC;QACJ,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC;IACF,OAAO,OAAuB,CAAC;AACjC,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@absol-labs/agent/x402-buyer` — the BUYER side of Metrik x402: pay an x402
|
|
3
|
+
* v2 endpoint through `@absol-labs/sdk/x402`'s `payWithX402` with every SDK
|
|
4
|
+
* protection intact, gated by a spend mandate (`checkMandate()`) before
|
|
5
|
+
* anything is signed. Kept out of the root barrel so consumers that never use
|
|
6
|
+
* x402 do not load `@x402/*`. See docs/x402.md.
|
|
7
|
+
*/
|
|
8
|
+
export * from "./pay.js";
|
|
9
|
+
export * from "./guarded-fetch.js";
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/x402-buyer/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,cAAc,UAAU,CAAC;AACzB,cAAc,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@absol-labs/agent/x402-buyer` — the BUYER side of Metrik x402: pay an x402
|
|
3
|
+
* v2 endpoint through `@absol-labs/sdk/x402`'s `payWithX402` with every SDK
|
|
4
|
+
* protection intact, gated by a spend mandate (`checkMandate()`) before
|
|
5
|
+
* anything is signed. Kept out of the root barrel so consumers that never use
|
|
6
|
+
* x402 do not load `@x402/*`. See docs/x402.md.
|
|
7
|
+
*/
|
|
8
|
+
export * from "./pay.js";
|
|
9
|
+
export * from "./guarded-fetch.js";
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/x402-buyer/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,cAAc,UAAU,CAAC;AACzB,cAAc,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { MetrikNetwork } from "@absol-labs/sdk";
|
|
2
|
+
import { payWithX402, type PayWithX402Options, type PayWithX402Result, type SignedTransferAuthorization, type X402PayerSigner, type X402QuoteSummary } from "@absol-labs/sdk/x402";
|
|
3
|
+
import { type PublicClient } from "viem";
|
|
4
|
+
import { type HireRequest, type MandateDecision, type SignedSpendMandate } from "../mandates/mandate.js";
|
|
5
|
+
/**
|
|
6
|
+
* Buyer-side x402 payments under a spend mandate (metrik-agent#121).
|
|
7
|
+
*
|
|
8
|
+
* The golden rule of this package — no spend without a mandate — applies to an
|
|
9
|
+
* x402 payment exactly as it applies to `metrik open`, because a Metrik x402
|
|
10
|
+
* payment IS a stream open: the opener facilitator settles the payer's EIP-3009
|
|
11
|
+
* authorization with `factory.deployAndSettle`, which opens a `StreamEscrowV2`
|
|
12
|
+
* stream with `deposit = price`. So the payment is mapped onto the SAME
|
|
13
|
+
* {@link HireRequest} a stream open is checked as, from the quote's opener terms
|
|
14
|
+
* (which the SDK has already proven on-chain: `payTo == factory.predict(terms)`):
|
|
15
|
+
*
|
|
16
|
+
* | Mandate field | x402 quote field |
|
|
17
|
+
* | ---------------------- | ------------------------------------------------ |
|
|
18
|
+
* | `maxPerStreamUsdc` | `amount` (the deposit; the price of the call) |
|
|
19
|
+
* | `maxTotalUsdc` | `spentSoFar + amount` |
|
|
20
|
+
* | `maxRatePerSecondUsdc` | `ratePerSecond` (how fast the seller can earn) |
|
|
21
|
+
* | `maxDurationSeconds` | `maxDuration` (the stream's window) |
|
|
22
|
+
* | `allowedOperators` | `operator` (who the stream pays) |
|
|
23
|
+
*
|
|
24
|
+
* The check runs inside the SDK's `onQuote` hook — after every SDK protection
|
|
25
|
+
* (scheme, network, USDC domain, EIP-3009 only, registered factory, on-chain
|
|
26
|
+
* `predict`, authorization lifetime) and BEFORE anything is signed — so a
|
|
27
|
+
* denied payment never produces a signature. It is enforced twice: the mandate's
|
|
28
|
+
* caps are also handed to the SDK as `maxAmount` / `maxRatePerSecond`. A quote
|
|
29
|
+
* that is not a Metrik opener payment (no operator/rate/duration terms) is
|
|
30
|
+
* refused: there would be no stream to bound and nothing to recover.
|
|
31
|
+
*
|
|
32
|
+
* The mandate itself (signature, expiry, revocation) is verified FIRST, before
|
|
33
|
+
* any request reaches the seller.
|
|
34
|
+
*/
|
|
35
|
+
/** A payment refused by the spend mandate. Nothing was signed. */
|
|
36
|
+
export declare class X402MandateDeniedError extends Error {
|
|
37
|
+
readonly reason: NonNullable<MandateDecision["reason"]> | "not-an-opener-quote";
|
|
38
|
+
readonly quote: X402QuoteSummary | null;
|
|
39
|
+
constructor(reason: X402MandateDeniedError["reason"], quote: X402QuoteSummary | null, detail?: string);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The stream-open request an x402 quote would create, or a refusal reason when
|
|
43
|
+
* the quote does not carry Metrik opener terms.
|
|
44
|
+
*/
|
|
45
|
+
export declare function x402QuoteToHireRequest(quote: X402QuoteSummary): HireRequest | {
|
|
46
|
+
readonly refused: string;
|
|
47
|
+
};
|
|
48
|
+
export interface PayX402WithMandateInput {
|
|
49
|
+
readonly url: string | URL;
|
|
50
|
+
readonly init?: RequestInit;
|
|
51
|
+
/** The payer: signs the EIP-3009 authorization. Needs USDC, no gas. */
|
|
52
|
+
readonly signer: X402PayerSigner;
|
|
53
|
+
readonly network: MetrikNetwork;
|
|
54
|
+
readonly signedMandate: SignedSpendMandate;
|
|
55
|
+
/** USDC already spent under this mandate (the cumulative-cap input). */
|
|
56
|
+
readonly spentSoFarUsdc: bigint;
|
|
57
|
+
readonly nowSeconds: number;
|
|
58
|
+
readonly revokedMandateIds?: Iterable<`0x${string}`>;
|
|
59
|
+
/** An explicit price ceiling, tighter than the mandate (never looser). */
|
|
60
|
+
readonly maxAmount?: bigint;
|
|
61
|
+
/** An explicit rate ceiling, tighter than the mandate (never looser). */
|
|
62
|
+
readonly maxRatePerSecond?: bigint;
|
|
63
|
+
/** Refuse a quote the seller can fully earn in fewer verified seconds. */
|
|
64
|
+
readonly minDurationSeconds?: number;
|
|
65
|
+
/** Passed through to the SDK (transport, fetch, publicClient, ...). */
|
|
66
|
+
readonly sdkOptions?: Pick<PayWithX402Options, "publicClient" | "transport" | "fetch" | "allowInsecureHttp" | "maxAuthorizationSeconds" | "allowLegacyFactory">;
|
|
67
|
+
/** Test seam: the SDK payer. Default `payWithX402`. */
|
|
68
|
+
readonly payImpl?: typeof payWithX402;
|
|
69
|
+
/**
|
|
70
|
+
* Called once the mandate APPROVES a quote, BEFORE the SDK signs it. A
|
|
71
|
+
* caller that tracks cumulative spend reserves the payment here, so a
|
|
72
|
+
* failure after the signature is handed out can never leave it uncounted.
|
|
73
|
+
* Throwing refuses the quote (nothing is signed).
|
|
74
|
+
*/
|
|
75
|
+
readonly onApproved?: (approval: {
|
|
76
|
+
readonly request: HireRequest;
|
|
77
|
+
readonly quote: X402QuoteSummary;
|
|
78
|
+
}) => void | Promise<void>;
|
|
79
|
+
/**
|
|
80
|
+
* Chain reads used after a post-signature failure (USDC
|
|
81
|
+
* `authorizationState`, the opener's `StreamOpenedFor` log). Default: the
|
|
82
|
+
* SDK options' `publicClient`, else a client over their `transport`, else
|
|
83
|
+
* the network's first RPC.
|
|
84
|
+
*/
|
|
85
|
+
readonly chainReader?: Pick<PublicClient, "readContract" | "getLogs" | "getBlockNumber">;
|
|
86
|
+
}
|
|
87
|
+
/** What is known about a payment whose signature was handed out but that did not complete cleanly. */
|
|
88
|
+
export type X402PostSignatureState =
|
|
89
|
+
/** The authorization was used: the money left the payer. */
|
|
90
|
+
"used"
|
|
91
|
+
/** It could not be established either way. Treat as used. */
|
|
92
|
+
| "possibly-used"
|
|
93
|
+
/** Not used yet, but still valid until `validBefore`: a holder can still submit it. */
|
|
94
|
+
| "unused-but-valid"
|
|
95
|
+
/** Not used and past `validBefore`: it can never move funds. */
|
|
96
|
+
| "unused-expired";
|
|
97
|
+
/**
|
|
98
|
+
* The payment was APPROVED and its authorization signed and handed to the
|
|
99
|
+
* seller, then something failed (a malformed or missing PAYMENT-RESPONSE, a
|
|
100
|
+
* settlement the SDK could not confirm, a dropped connection). The money may
|
|
101
|
+
* have moved: {@link X402PostSignatureError.state} says what is known, and
|
|
102
|
+
* {@link X402PostSignatureError.releasable} is `true` only when the
|
|
103
|
+
* authorization provably can never be used. A spend reservation must be kept
|
|
104
|
+
* otherwise.
|
|
105
|
+
*/
|
|
106
|
+
export declare class X402PostSignatureError extends Error {
|
|
107
|
+
readonly state: X402PostSignatureState;
|
|
108
|
+
readonly approved: HireRequest;
|
|
109
|
+
readonly quote: X402QuoteSummary;
|
|
110
|
+
readonly authorization: SignedTransferAuthorization | null;
|
|
111
|
+
/** The stream the payment opened, when it could be identified. */
|
|
112
|
+
readonly streamId: `0x${string}` | null;
|
|
113
|
+
readonly opener: `0x${string}`;
|
|
114
|
+
constructor(context: {
|
|
115
|
+
readonly state: X402PostSignatureState;
|
|
116
|
+
readonly approved: HireRequest;
|
|
117
|
+
readonly quote: X402QuoteSummary;
|
|
118
|
+
readonly authorization: SignedTransferAuthorization | null;
|
|
119
|
+
readonly streamId: `0x${string}` | null;
|
|
120
|
+
readonly cause: unknown;
|
|
121
|
+
});
|
|
122
|
+
/** Only an authorization that provably can never move funds frees its reservation. */
|
|
123
|
+
get releasable(): boolean;
|
|
124
|
+
}
|
|
125
|
+
export interface PayX402WithMandateResult extends PayWithX402Result {
|
|
126
|
+
/** The stream-open request the mandate approved (null if nothing was paid). */
|
|
127
|
+
readonly approved: HireRequest | null;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Pay an x402 v2 endpoint through the SDK's `payWithX402`, gated by
|
|
131
|
+
* `checkMandate()`. Fail closed: a mandate that does not verify, a quote it
|
|
132
|
+
* denies, or a quote without opener terms is a hard stop with nothing signed.
|
|
133
|
+
*/
|
|
134
|
+
export declare function payX402WithMandate(input: PayX402WithMandateInput): Promise<PayX402WithMandateResult>;
|
|
135
|
+
//# sourceMappingURL=pay.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pay.d.ts","sourceRoot":"","sources":["../../src/x402-buyer/pay.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAEL,WAAW,EAEX,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,2BAA2B,EAChC,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACtB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAwC,KAAK,YAAY,EAAE,MAAM,MAAM,CAAC;AAE/E,OAAO,EAGL,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACxB,MAAM,wBAAwB,CAAC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,kEAAkE;AAClE,qBAAa,sBAAuB,SAAQ,KAAK;IAC/C,QAAQ,CAAC,MAAM,EACX,WAAW,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC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;IAsBD,sFAAsF;IACtF,IAAI,UAAU,IAAI,OAAO,CAExB;CACF;AA2CD,MAAM,WAAW,wBAAyB,SAAQ,iBAAiB;IACjE,+EAA+E;IAC/E,QAAQ,CAAC,QAAQ,EAAE,WAAW,GAAG,IAAI,CAAC;CACvC;AAMD;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,KAAK,EAAE,uBAAuB,GAC7B,OAAO,CAAC,wBAAwB,CAAC,CA6InC"}
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { findStreamForAuthorization, payWithX402, X402PaymentRefusedError, } from "@absol-labs/sdk/x402";
|
|
2
|
+
import { decodePaymentSignatureHeader } from "@x402/core/http";
|
|
3
|
+
import { createPublicClient, getAddress, http } from "viem";
|
|
4
|
+
import { checkMandate, verifySignedMandate, } from "../mandates/mandate.js";
|
|
5
|
+
/**
|
|
6
|
+
* Buyer-side x402 payments under a spend mandate (metrik-agent#121).
|
|
7
|
+
*
|
|
8
|
+
* The golden rule of this package — no spend without a mandate — applies to an
|
|
9
|
+
* x402 payment exactly as it applies to `metrik open`, because a Metrik x402
|
|
10
|
+
* payment IS a stream open: the opener facilitator settles the payer's EIP-3009
|
|
11
|
+
* authorization with `factory.deployAndSettle`, which opens a `StreamEscrowV2`
|
|
12
|
+
* stream with `deposit = price`. So the payment is mapped onto the SAME
|
|
13
|
+
* {@link HireRequest} a stream open is checked as, from the quote's opener terms
|
|
14
|
+
* (which the SDK has already proven on-chain: `payTo == factory.predict(terms)`):
|
|
15
|
+
*
|
|
16
|
+
* | Mandate field | x402 quote field |
|
|
17
|
+
* | ---------------------- | ------------------------------------------------ |
|
|
18
|
+
* | `maxPerStreamUsdc` | `amount` (the deposit; the price of the call) |
|
|
19
|
+
* | `maxTotalUsdc` | `spentSoFar + amount` |
|
|
20
|
+
* | `maxRatePerSecondUsdc` | `ratePerSecond` (how fast the seller can earn) |
|
|
21
|
+
* | `maxDurationSeconds` | `maxDuration` (the stream's window) |
|
|
22
|
+
* | `allowedOperators` | `operator` (who the stream pays) |
|
|
23
|
+
*
|
|
24
|
+
* The check runs inside the SDK's `onQuote` hook — after every SDK protection
|
|
25
|
+
* (scheme, network, USDC domain, EIP-3009 only, registered factory, on-chain
|
|
26
|
+
* `predict`, authorization lifetime) and BEFORE anything is signed — so a
|
|
27
|
+
* denied payment never produces a signature. It is enforced twice: the mandate's
|
|
28
|
+
* caps are also handed to the SDK as `maxAmount` / `maxRatePerSecond`. A quote
|
|
29
|
+
* that is not a Metrik opener payment (no operator/rate/duration terms) is
|
|
30
|
+
* refused: there would be no stream to bound and nothing to recover.
|
|
31
|
+
*
|
|
32
|
+
* The mandate itself (signature, expiry, revocation) is verified FIRST, before
|
|
33
|
+
* any request reaches the seller.
|
|
34
|
+
*/
|
|
35
|
+
/** A payment refused by the spend mandate. Nothing was signed. */
|
|
36
|
+
export class X402MandateDeniedError extends Error {
|
|
37
|
+
reason;
|
|
38
|
+
quote;
|
|
39
|
+
constructor(reason, quote, detail) {
|
|
40
|
+
super(`x402 payment refused by the spend mandate: ${reason}${detail === undefined ? "" : ` (${detail})`}. Nothing was signed.`);
|
|
41
|
+
this.name = "X402MandateDeniedError";
|
|
42
|
+
this.reason = reason;
|
|
43
|
+
this.quote = quote;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The stream-open request an x402 quote would create, or a refusal reason when
|
|
48
|
+
* the quote does not carry Metrik opener terms.
|
|
49
|
+
*/
|
|
50
|
+
export function x402QuoteToHireRequest(quote) {
|
|
51
|
+
if (quote.operator === null ||
|
|
52
|
+
quote.ratePerSecond === null ||
|
|
53
|
+
quote.maxDuration === null) {
|
|
54
|
+
return {
|
|
55
|
+
refused: "the quote carries no Metrik opener terms (operator, ratePerSecond, maxDuration), so it would not open a recoverable stream",
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
if (quote.maxDuration > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
59
|
+
return { refused: `maxDuration ${quote.maxDuration} is out of range` };
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
operator: quote.operator,
|
|
63
|
+
budgetUsdc: quote.amount,
|
|
64
|
+
ratePerSecondUsdc: quote.ratePerSecond,
|
|
65
|
+
maxDurationSeconds: Number(quote.maxDuration),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The payment was APPROVED and its authorization signed and handed to the
|
|
70
|
+
* seller, then something failed (a malformed or missing PAYMENT-RESPONSE, a
|
|
71
|
+
* settlement the SDK could not confirm, a dropped connection). The money may
|
|
72
|
+
* have moved: {@link X402PostSignatureError.state} says what is known, and
|
|
73
|
+
* {@link X402PostSignatureError.releasable} is `true` only when the
|
|
74
|
+
* authorization provably can never be used. A spend reservation must be kept
|
|
75
|
+
* otherwise.
|
|
76
|
+
*/
|
|
77
|
+
export class X402PostSignatureError extends Error {
|
|
78
|
+
state;
|
|
79
|
+
approved;
|
|
80
|
+
quote;
|
|
81
|
+
authorization;
|
|
82
|
+
/** The stream the payment opened, when it could be identified. */
|
|
83
|
+
streamId;
|
|
84
|
+
opener;
|
|
85
|
+
constructor(context) {
|
|
86
|
+
const what = context.state === "used"
|
|
87
|
+
? `the payment SETTLED (the authorization was used)${context.streamId === null ? ", but its stream could not be identified" : ` into stream ${context.streamId}`}`
|
|
88
|
+
: context.state === "possibly-used"
|
|
89
|
+
? "the payment MAY HAVE SETTLED: whether the authorization was used could not be established, so treat it as spent"
|
|
90
|
+
: context.state === "unused-but-valid"
|
|
91
|
+
? `the authorization has not been used, but it stays valid until ${context.authorization?.validBefore.toString() ?? "its validBefore"} and the seller still holds it — treat it as spent until then, or cancel it on USDC (cancelAuthorization)`
|
|
92
|
+
: "the authorization was never used and has expired: nothing moved";
|
|
93
|
+
super(`x402 payment of ${context.approved.budgetUsdc.toString()} USDC base units to ${context.quote.payTo} did not complete cleanly: ${what}. Cause: ${context.cause instanceof Error ? context.cause.message : String(context.cause)}`, { cause: context.cause });
|
|
94
|
+
this.name = "X402PostSignatureError";
|
|
95
|
+
this.state = context.state;
|
|
96
|
+
this.approved = context.approved;
|
|
97
|
+
this.quote = context.quote;
|
|
98
|
+
this.authorization = context.authorization;
|
|
99
|
+
this.streamId = context.streamId;
|
|
100
|
+
this.opener = getAddress(context.quote.payTo);
|
|
101
|
+
}
|
|
102
|
+
/** Only an authorization that provably can never move funds frees its reservation. */
|
|
103
|
+
get releasable() {
|
|
104
|
+
return this.state === "unused-expired";
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function headerValue(headers, name) {
|
|
108
|
+
if (headers === undefined)
|
|
109
|
+
return null;
|
|
110
|
+
if (headers instanceof Headers)
|
|
111
|
+
return headers.get(name);
|
|
112
|
+
if (Array.isArray(headers)) {
|
|
113
|
+
const hit = headers.find((pair) => pair[0]?.toLowerCase() === name);
|
|
114
|
+
return hit?.[1] ?? null;
|
|
115
|
+
}
|
|
116
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
117
|
+
if (key.toLowerCase() === name) {
|
|
118
|
+
return typeof value === "string" ? value : (value[0] ?? null);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
/** The EIP-3009 authorization inside an x402 v2 PAYMENT-SIGNATURE header, if decodable. */
|
|
124
|
+
function authorizationFromHeader(header) {
|
|
125
|
+
try {
|
|
126
|
+
const payload = decodePaymentSignatureHeader(header);
|
|
127
|
+
const auth = payload.payload?.authorization;
|
|
128
|
+
if (auth === undefined)
|
|
129
|
+
return null;
|
|
130
|
+
return {
|
|
131
|
+
from: getAddress(auth.from),
|
|
132
|
+
to: getAddress(auth.to),
|
|
133
|
+
value: BigInt(auth.value),
|
|
134
|
+
validAfter: BigInt(auth.validAfter),
|
|
135
|
+
validBefore: BigInt(auth.validBefore),
|
|
136
|
+
nonce: auth.nonce,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function smaller(a, b) {
|
|
144
|
+
return b !== undefined && b < a ? b : a;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Pay an x402 v2 endpoint through the SDK's `payWithX402`, gated by
|
|
148
|
+
* `checkMandate()`. Fail closed: a mandate that does not verify, a quote it
|
|
149
|
+
* denies, or a quote without opener terms is a hard stop with nothing signed.
|
|
150
|
+
*/
|
|
151
|
+
export async function payX402WithMandate(input) {
|
|
152
|
+
const mandate = input.signedMandate.mandate;
|
|
153
|
+
// 1. The mandate itself, before the seller is even contacted.
|
|
154
|
+
const verdict = await verifySignedMandate(input.signedMandate, {
|
|
155
|
+
nowSeconds: input.nowSeconds,
|
|
156
|
+
...(input.revokedMandateIds === undefined
|
|
157
|
+
? {}
|
|
158
|
+
: { revokedMandateIds: input.revokedMandateIds }),
|
|
159
|
+
});
|
|
160
|
+
if (!verdict.allowed) {
|
|
161
|
+
throw new X402MandateDeniedError(verdict.reason ?? "invalid-signature", null);
|
|
162
|
+
}
|
|
163
|
+
if (input.signedMandate.owner.toLowerCase() !==
|
|
164
|
+
input.signer.address.toLowerCase()) {
|
|
165
|
+
throw new X402MandateDeniedError("invalid-signature", null, `the mandate is owned by ${input.signedMandate.owner}, not the payer ${input.signer.address}`);
|
|
166
|
+
}
|
|
167
|
+
if (input.signedMandate.chainId !== input.network.chain.id) {
|
|
168
|
+
throw new X402MandateDeniedError("invalid-signature", null, `the mandate is for chain ${input.signedMandate.chainId}, not ${input.network.name} (${input.network.chain.id})`);
|
|
169
|
+
}
|
|
170
|
+
// 2. The SDK's own ceilings, never looser than the mandate.
|
|
171
|
+
const remaining = mandate.maxTotalUsdc - input.spentSoFarUsdc;
|
|
172
|
+
if (remaining <= 0n) {
|
|
173
|
+
throw new X402MandateDeniedError("exceeds-total-cap", null, "the mandate's total cap is already spent");
|
|
174
|
+
}
|
|
175
|
+
const maxAmount = smaller(smaller(mandate.maxPerStreamUsdc, remaining), input.maxAmount);
|
|
176
|
+
const maxRatePerSecond = smaller(mandate.maxRatePerSecondUsdc, input.maxRatePerSecond);
|
|
177
|
+
// 3. The per-quote mandate check, before signing.
|
|
178
|
+
let denial = null;
|
|
179
|
+
let approved = null;
|
|
180
|
+
let approvedQuote = null;
|
|
181
|
+
// The authorization exactly as it left this process, read from the
|
|
182
|
+
// PAYMENT-SIGNATURE header on the way out — so a post-signature failure can
|
|
183
|
+
// still be traced on-chain even when the SDK error does not carry it.
|
|
184
|
+
let sentAuthorization = null;
|
|
185
|
+
const baseFetch = input.sdkOptions?.fetch ?? globalThis.fetch.bind(globalThis);
|
|
186
|
+
const capturingFetch = (async (resource, init) => {
|
|
187
|
+
const header = headerValue(init?.headers, "payment-signature") ??
|
|
188
|
+
(resource instanceof Request
|
|
189
|
+
? resource.headers.get("payment-signature")
|
|
190
|
+
: null);
|
|
191
|
+
if (header !== null) {
|
|
192
|
+
sentAuthorization = authorizationFromHeader(header) ?? sentAuthorization;
|
|
193
|
+
}
|
|
194
|
+
return await baseFetch(resource, init);
|
|
195
|
+
});
|
|
196
|
+
const pay = input.payImpl ?? payWithX402;
|
|
197
|
+
let result;
|
|
198
|
+
try {
|
|
199
|
+
result = await pay(input.url, input.init, {
|
|
200
|
+
...input.sdkOptions,
|
|
201
|
+
fetch: capturingFetch,
|
|
202
|
+
signer: input.signer,
|
|
203
|
+
network: input.network,
|
|
204
|
+
maxAmount,
|
|
205
|
+
maxRatePerSecond,
|
|
206
|
+
...(input.minDurationSeconds === undefined
|
|
207
|
+
? {}
|
|
208
|
+
: { minDurationSeconds: input.minDurationSeconds }),
|
|
209
|
+
onQuote: async (quote) => {
|
|
210
|
+
const request = x402QuoteToHireRequest(quote);
|
|
211
|
+
if ("refused" in request) {
|
|
212
|
+
denial = new X402MandateDeniedError("not-an-opener-quote", quote, request.refused);
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
const decision = await checkMandate(input.signedMandate, request, input.spentSoFarUsdc, {
|
|
216
|
+
nowSeconds: input.nowSeconds,
|
|
217
|
+
...(input.revokedMandateIds === undefined
|
|
218
|
+
? {}
|
|
219
|
+
: { revokedMandateIds: input.revokedMandateIds }),
|
|
220
|
+
});
|
|
221
|
+
if (!decision.allowed) {
|
|
222
|
+
denial = new X402MandateDeniedError(decision.reason ?? "invalid-signature", quote);
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
// Reserve BEFORE the SDK signs: from here on the money can move.
|
|
226
|
+
// A reservation hook that fails refuses the quote.
|
|
227
|
+
await input.onApproved?.({ request, quote });
|
|
228
|
+
approved = request;
|
|
229
|
+
approvedQuote = quote;
|
|
230
|
+
denial = null;
|
|
231
|
+
return true;
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
if (error instanceof X402PaymentRefusedError) {
|
|
237
|
+
// The SDK's own statement: nothing was signed or sent. A reservation
|
|
238
|
+
// made in onApproved can be released by the caller.
|
|
239
|
+
if (denial !== null)
|
|
240
|
+
throw denial;
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
if (approved === null || approvedQuote === null)
|
|
244
|
+
throw error;
|
|
245
|
+
throw await classifyPostSignatureFailure(input, {
|
|
246
|
+
error,
|
|
247
|
+
approved,
|
|
248
|
+
quote: approvedQuote,
|
|
249
|
+
sentAuthorization,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
return { ...result, approved: result.paid ? approved : null };
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* After a failure past the point of signing, establish what happened from the
|
|
256
|
+
* CHAIN, never from the seller: USDC `authorizationState(from, nonce)` and the
|
|
257
|
+
* opener's `StreamOpenedFor(streamId, payer, authorizationNonce, …)` log.
|
|
258
|
+
*/
|
|
259
|
+
async function classifyPostSignatureFailure(input, context) {
|
|
260
|
+
const sdkError = context.error;
|
|
261
|
+
const authorization = sdkError.authorization ?? context.sentAuthorization ?? null;
|
|
262
|
+
let used = typeof sdkError.authorizationUsed === "boolean"
|
|
263
|
+
? sdkError.authorizationUsed
|
|
264
|
+
: null;
|
|
265
|
+
let streamId = typeof sdkError.streamId === "string" &&
|
|
266
|
+
/^0x[0-9a-fA-F]{64}$/.test(sdkError.streamId)
|
|
267
|
+
? sdkError.streamId
|
|
268
|
+
: null;
|
|
269
|
+
const reader = input.chainReader ??
|
|
270
|
+
input.sdkOptions?.publicClient ??
|
|
271
|
+
createPublicClient({
|
|
272
|
+
transport: input.sdkOptions?.transport ?? http(input.network.rpcUrls[0]),
|
|
273
|
+
});
|
|
274
|
+
if (authorization !== null) {
|
|
275
|
+
if (used === null) {
|
|
276
|
+
try {
|
|
277
|
+
used = await reader.readContract({
|
|
278
|
+
address: input.network.usdc.address,
|
|
279
|
+
abi: authorizationStateAbi,
|
|
280
|
+
functionName: "authorizationState",
|
|
281
|
+
args: [authorization.from, authorization.nonce],
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
used = null;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (streamId === null && used !== false) {
|
|
289
|
+
// The SDK's recovery: only a registered factory's opener
|
|
290
|
+
// (factory.isOpener read on-chain) can prove a stream for this nonce.
|
|
291
|
+
try {
|
|
292
|
+
const recovery = await findStreamForAuthorization({
|
|
293
|
+
authorization,
|
|
294
|
+
network: input.network,
|
|
295
|
+
factory: context.quote.factory ?? null,
|
|
296
|
+
publicClient: reader,
|
|
297
|
+
});
|
|
298
|
+
streamId = recovery.streamId;
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
streamId = null;
|
|
302
|
+
}
|
|
303
|
+
if (streamId !== null)
|
|
304
|
+
used = true;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const nowSeconds = BigInt(Math.floor(Date.now() / 1000));
|
|
308
|
+
const state = streamId !== null || used === true
|
|
309
|
+
? "used"
|
|
310
|
+
: used === false && authorization !== null
|
|
311
|
+
? authorization.validBefore <= nowSeconds
|
|
312
|
+
? "unused-expired"
|
|
313
|
+
: "unused-but-valid"
|
|
314
|
+
: "possibly-used";
|
|
315
|
+
return new X402PostSignatureError({
|
|
316
|
+
state,
|
|
317
|
+
approved: context.approved,
|
|
318
|
+
quote: context.quote,
|
|
319
|
+
authorization,
|
|
320
|
+
streamId,
|
|
321
|
+
cause: context.error,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
const authorizationStateAbi = [
|
|
325
|
+
{
|
|
326
|
+
type: "function",
|
|
327
|
+
name: "authorizationState",
|
|
328
|
+
stateMutability: "view",
|
|
329
|
+
inputs: [
|
|
330
|
+
{ name: "authorizer", type: "address" },
|
|
331
|
+
{ name: "nonce", type: "bytes32" },
|
|
332
|
+
],
|
|
333
|
+
outputs: [{ name: "", type: "bool" }],
|
|
334
|
+
},
|
|
335
|
+
];
|
|
336
|
+
//# sourceMappingURL=pay.js.map
|