@integraledger/profile-facilitator 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.
@@ -0,0 +1,44 @@
1
+ /** The x402 facilitator API's bodies, as this facilitator reads and writes them. */
2
+ export function invalid(invalidReason, payer) {
3
+ return payer === undefined ? { isValid: false, invalidReason } : { isValid: false, invalidReason, payer };
4
+ }
5
+ /** x402 requires a non-empty `transaction` on `settlement_pending`. */
6
+ export function pending(transaction, network) {
7
+ return { success: false, errorReason: "settlement_pending", transaction, network };
8
+ }
9
+ export function failed(errorReason, transaction, network) {
10
+ return { success: false, errorReason, transaction, network };
11
+ }
12
+ export function isPending(a) {
13
+ return !a.success && a.errorReason === "settlement_pending";
14
+ }
15
+ /** One JSON line on standard error, for the operator: what the node reported that the answer does not carry. */
16
+ export function operatorLog(entry) {
17
+ process.stderr.write(`${JSON.stringify(entry)}\n`);
18
+ }
19
+ export function isObject(v) {
20
+ return typeof v === "object" && v !== null && !Array.isArray(v);
21
+ }
22
+ /**
23
+ * The shared shape checks of a request: the versions, the scheme, and the objects the rails read. Returns the typed
24
+ * request, or the reason it is refused.
25
+ */
26
+ export function readRequest(body) {
27
+ if (!isObject(body))
28
+ return "invalid_payload";
29
+ if (body["x402Version"] !== 2)
30
+ return "invalid_x402_version";
31
+ const p = body["paymentPayload"];
32
+ const r = body["paymentRequirements"];
33
+ if (!isObject(p) || !isObject(r))
34
+ return "invalid_payload";
35
+ if (p["x402Version"] !== 2)
36
+ return "invalid_x402_version";
37
+ if (!isObject(p["payload"]))
38
+ return "invalid_payload";
39
+ if (r["scheme"] !== "exact")
40
+ return "unsupported_scheme";
41
+ if (typeof r["network"] !== "string")
42
+ return "invalid_network";
43
+ return body;
44
+ }
@@ -0,0 +1 @@
1
+ export declare function base58check(payload: Uint8Array): string;
@@ -0,0 +1,25 @@
1
+ /** Base58check encoding (Bitcoin's alphabet, a four-byte double-SHA-256 checksum), as Tron writes addresses. */
2
+ import { createHash } from "node:crypto";
3
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
4
+ function sha256(b) {
5
+ return createHash("sha256").update(b).digest();
6
+ }
7
+ export function base58check(payload) {
8
+ const bytes = new Uint8Array(payload.length + 4);
9
+ bytes.set(payload, 0);
10
+ bytes.set(sha256(sha256(payload)).subarray(0, 4), payload.length);
11
+ let n = 0n;
12
+ for (const b of bytes)
13
+ n = (n << 8n) | BigInt(b);
14
+ let out = "";
15
+ while (n > 0n) {
16
+ out = ALPHABET[Number(n % 58n)] + out;
17
+ n /= 58n;
18
+ }
19
+ for (const b of bytes) {
20
+ if (b !== 0)
21
+ break;
22
+ out = "1" + out;
23
+ }
24
+ return out;
25
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ /** Bounded JSON over HTTP: outbound node calls, and reading and writing the facilitator's own requests. */
2
+ import type { IncomingMessage, ServerResponse } from "node:http";
3
+ export declare const NODE_TIMEOUT_MS = 5000;
4
+ export declare const NODE_MAX_BYTES: number;
5
+ export declare const REQUEST_MAX_BYTES: number;
6
+ /** Why a node call gave no answer. `sent` is false only when the request cannot have reached the node. */
7
+ export declare class NodeError extends Error {
8
+ readonly code: "timeout" | "transport" | "http-status" | "too-large" | "malformed";
9
+ readonly sent: boolean;
10
+ constructor(code: "timeout" | "transport" | "http-status" | "too-large" | "malformed", sent: boolean, detail: string);
11
+ }
12
+ /** POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and the size bound. */
13
+ export declare function postJson(url: string, body: unknown, timeoutMs?: number): Promise<unknown>;
14
+ /** Reads a request body of at most 64 KiB as JSON; undefined when it is larger or is not JSON. */
15
+ export declare function readRequestJson(req: IncomingMessage): Promise<{
16
+ json: unknown;
17
+ } | {
18
+ tooLarge: true;
19
+ } | undefined>;
20
+ export declare function sendJson(res: ServerResponse, status: number, body: unknown): void;
21
+ export declare function sleep(ms: number): Promise<void>;
22
+ /** `p`'s outcome, or a `timeout` NodeError once `ms` has passed first. */
23
+ export declare function within<T>(p: Promise<T>, ms: number): Promise<T>;
package/dist/http.js ADDED
@@ -0,0 +1,131 @@
1
+ export const NODE_TIMEOUT_MS = 5_000;
2
+ export const NODE_MAX_BYTES = 4 * 1024 * 1024;
3
+ export const REQUEST_MAX_BYTES = 64 * 1024;
4
+ /** Connection errors after which no byte of the request can have reached the node. */
5
+ const UNSENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH"]);
6
+ function isObject(v) {
7
+ return typeof v === "object" && v !== null;
8
+ }
9
+ /** Why a node call gave no answer. `sent` is false only when the request cannot have reached the node. */
10
+ export class NodeError extends Error {
11
+ code;
12
+ sent;
13
+ constructor(code, sent, detail) {
14
+ super(`${code}: ${detail}`);
15
+ this.code = code;
16
+ this.sent = sent;
17
+ }
18
+ }
19
+ /** POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and the size bound. */
20
+ export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS) {
21
+ const ms = Number.isFinite(timeoutMs) ? Math.max(1, Math.ceil(Math.min(timeoutMs, NODE_TIMEOUT_MS))) : NODE_TIMEOUT_MS;
22
+ const signal = AbortSignal.timeout(ms);
23
+ let res;
24
+ try {
25
+ res = await fetch(url, {
26
+ method: "POST",
27
+ headers: { "content-type": "application/json", accept: "application/json" },
28
+ body: JSON.stringify(body),
29
+ signal,
30
+ });
31
+ }
32
+ catch (e) {
33
+ if (signal.aborted)
34
+ throw new NodeError("timeout", true, url);
35
+ const cause = e instanceof Error && isObject(e.cause) ? e.cause["code"] : undefined;
36
+ const unsent = typeof cause === "string" && UNSENT.has(cause);
37
+ throw new NodeError("transport", !unsent, e instanceof Error ? e.message : String(e));
38
+ }
39
+ const bytes = await readBounded(res, signal);
40
+ if (res.status < 200 || res.status > 299)
41
+ throw new NodeError("http-status", true, `status ${res.status}`);
42
+ try {
43
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
44
+ }
45
+ catch {
46
+ throw new NodeError("malformed", true, "the answer is not JSON");
47
+ }
48
+ }
49
+ async function readBounded(res, signal) {
50
+ const declared = Number(res.headers.get("content-length"));
51
+ if (Number.isFinite(declared) && declared > NODE_MAX_BYTES) {
52
+ await res.body?.cancel();
53
+ throw new NodeError("too-large", true, `content-length ${declared}`);
54
+ }
55
+ if (res.body === null)
56
+ return new Uint8Array(0);
57
+ const reader = res.body.getReader();
58
+ const parts = [];
59
+ let total = 0;
60
+ try {
61
+ for (;;) {
62
+ const { done, value } = await reader.read();
63
+ if (done)
64
+ break;
65
+ total += value.byteLength;
66
+ if (total > NODE_MAX_BYTES) {
67
+ await reader.cancel();
68
+ throw new NodeError("too-large", true, `more than ${NODE_MAX_BYTES} bytes`);
69
+ }
70
+ parts.push(value);
71
+ }
72
+ }
73
+ catch (e) {
74
+ if (e instanceof NodeError)
75
+ throw e;
76
+ if (signal.aborted)
77
+ throw new NodeError("timeout", true, "reading the answer");
78
+ throw new NodeError("transport", true, e instanceof Error ? e.message : String(e));
79
+ }
80
+ const out = new Uint8Array(total);
81
+ let at = 0;
82
+ for (const p of parts) {
83
+ out.set(p, at);
84
+ at += p.byteLength;
85
+ }
86
+ return out;
87
+ }
88
+ /** Reads a request body of at most 64 KiB as JSON; undefined when it is larger or is not JSON. */
89
+ export async function readRequestJson(req) {
90
+ const declared = Number(req.headers["content-length"]);
91
+ if (Number.isFinite(declared) && declared > REQUEST_MAX_BYTES)
92
+ return { tooLarge: true };
93
+ const parts = [];
94
+ let total = 0;
95
+ for await (const chunk of req) {
96
+ const b = chunk;
97
+ total += b.byteLength;
98
+ if (total > REQUEST_MAX_BYTES)
99
+ return { tooLarge: true };
100
+ parts.push(b);
101
+ }
102
+ try {
103
+ return { json: JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(parts))) };
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ }
109
+ export function sendJson(res, status, body) {
110
+ const text = JSON.stringify(body);
111
+ res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(text) });
112
+ res.end(text);
113
+ }
114
+ export function sleep(ms) {
115
+ return new Promise((resolve) => setTimeout(resolve, ms));
116
+ }
117
+ /** `p`'s outcome, or a `timeout` NodeError once `ms` has passed first. */
118
+ export async function within(p, ms) {
119
+ let timer;
120
+ try {
121
+ return await Promise.race([
122
+ p,
123
+ new Promise((_, reject) => {
124
+ timer = setTimeout(() => reject(new NodeError("timeout", true, `no answer within ${ms} ms`)), Math.max(0, ms));
125
+ }),
126
+ ]);
127
+ }
128
+ finally {
129
+ clearTimeout(timer);
130
+ }
131
+ }
@@ -0,0 +1,25 @@
1
+ import { type PolkadotNetwork } from "@integraledger/lcp/polkadot";
2
+ export type { SettleAnswer, VerifyAnswer } from "./answers.js";
3
+ export interface ProfileFacilitatorConfig {
4
+ /** "host:port" */
5
+ listen: string;
6
+ tron?: {
7
+ network: `tron:${number}`;
8
+ fullNode: string;
9
+ solidityNode: string;
10
+ }[];
11
+ /** An RPC node that serves `state_call` and `author_submitExtrinsic`. */
12
+ polkadot?: {
13
+ network: PolkadotNetwork;
14
+ rpc: string;
15
+ }[];
16
+ /** Postgres, for deduplication only. */
17
+ store: {
18
+ url: string;
19
+ };
20
+ /** How long `/settle` waits for inclusion before answering `settlement_pending`; default 30 000. */
21
+ settleWaitMs: number;
22
+ }
23
+ export declare function serveProfileFacilitator(c: ProfileFacilitatorConfig): Promise<{
24
+ close(): Promise<void>;
25
+ }>;
package/dist/index.js ADDED
@@ -0,0 +1,140 @@
1
+ /**
2
+ * A reference x402 facilitator for two LCP profiles, `x402/exact/tron/lcp-trc20-memo` and
3
+ * `x402/exact/polkadot/lcp-assets-remark`: `GET /supported`, `POST /verify` and `POST /settle` over `node:http`. It
4
+ * holds no key and pays no fee; it checks, submits what the payer signed, deduplicates, and reports what the network
5
+ * shows.
6
+ */
7
+ import { createServer } from "node:http";
8
+ import { LCP_ASSETS_REMARK } from "@integraledger/lcp/polkadot";
9
+ import { LCP_TRC20_MEMO } from "@integraledger/lcp/tron";
10
+ import { failed, readRequest } from "./answers.js";
11
+ import { readRequestJson, sendJson } from "./http.js";
12
+ import { createPolkadot } from "./polkadot.js";
13
+ import { openStore } from "./store.js";
14
+ import { createTron } from "./tron.js";
15
+ const DEFAULT_SETTLE_WAIT_MS = 30_000;
16
+ function hostPort(listen) {
17
+ const m = /^\[?([^\]]*)\]?:(\d{1,5})$/.exec(listen);
18
+ const port = m === null ? NaN : Number(m[2]);
19
+ if (m === null || !(port >= 0 && port <= 65_535))
20
+ throw new TypeError(`listen must be "host:port": ${listen}`);
21
+ return { host: m[1], port };
22
+ }
23
+ function trimmed(url) {
24
+ return url.replace(/\/+$/, "");
25
+ }
26
+ export async function serveProfileFacilitator(c) {
27
+ const { host, port } = hostPort(c.listen);
28
+ const settleWaitMs = Number.isFinite(c.settleWaitMs) && c.settleWaitMs > 0 ? c.settleWaitMs : DEFAULT_SETTLE_WAIT_MS;
29
+ const store = await openStore(c.store.url);
30
+ const tron = createTron((c.tron ?? []).map((n) => ({ ...n, fullNode: trimmed(n.fullNode), solidityNode: trimmed(n.solidityNode) })), store, settleWaitMs);
31
+ const polkadot = createPolkadot((c.polkadot ?? []).map((n) => ({ ...n, rpc: trimmed(n.rpc) })), store, settleWaitMs);
32
+ const supported = {
33
+ kinds: [
34
+ ...tron.networks.map((network) => ({
35
+ x402Version: 2,
36
+ scheme: "exact",
37
+ network,
38
+ extra: { assetTransferMethod: LCP_TRC20_MEMO },
39
+ })),
40
+ ...polkadot.networks.map((network) => ({
41
+ x402Version: 2,
42
+ scheme: "exact",
43
+ network,
44
+ extra: { assetTransferMethod: LCP_ASSETS_REMARK },
45
+ })),
46
+ ],
47
+ extensions: [],
48
+ signers: {},
49
+ };
50
+ function railOf(r) {
51
+ const n = r.paymentRequirements.network;
52
+ if (tron.networks.includes(n))
53
+ return tron;
54
+ if (polkadot.networks.includes(n))
55
+ return polkadot;
56
+ return undefined;
57
+ }
58
+ async function verify(body) {
59
+ const r = readRequest(body);
60
+ if (typeof r === "string")
61
+ return { isValid: false, invalidReason: r };
62
+ const rail = railOf(r);
63
+ if (rail === undefined)
64
+ return { isValid: false, invalidReason: "invalid_network" };
65
+ try {
66
+ return await rail.verify(r);
67
+ }
68
+ catch {
69
+ return { isValid: false, invalidReason: "unexpected_verify_error" };
70
+ }
71
+ }
72
+ async function settle(body) {
73
+ const r = readRequest(body);
74
+ const network = typeof r === "string" ? "" : r.paymentRequirements.network;
75
+ if (typeof r === "string")
76
+ return failed(r, "", network);
77
+ const rail = railOf(r);
78
+ if (rail === undefined)
79
+ return failed("invalid_network", "", network);
80
+ try {
81
+ return await rail.settle(r);
82
+ }
83
+ catch {
84
+ return failed("unexpected_settle_error", "", network);
85
+ }
86
+ }
87
+ async function handle(req, res) {
88
+ const path = (req.url ?? "").split("?")[0];
89
+ if (path === "/supported") {
90
+ if (req.method !== "GET")
91
+ return sendJson(res, 405, { error: "method not allowed" });
92
+ return sendJson(res, 200, supported);
93
+ }
94
+ if (path !== "/verify" && path !== "/settle")
95
+ return sendJson(res, 404, { error: "not found" });
96
+ if (req.method !== "POST")
97
+ return sendJson(res, 405, { error: "method not allowed" });
98
+ const read = await readRequestJson(req);
99
+ if (read !== undefined && "tooLarge" in read) {
100
+ res.setHeader("connection", "close");
101
+ sendJson(res, 413, { error: "the body is larger than 64 KiB" });
102
+ req.destroy();
103
+ return;
104
+ }
105
+ if (path === "/verify") {
106
+ if (read === undefined)
107
+ return sendJson(res, 400, { isValid: false, invalidReason: "invalid_payload" });
108
+ return sendJson(res, 200, await verify(read.json));
109
+ }
110
+ if (read === undefined)
111
+ return sendJson(res, 400, failed("invalid_payload", "", ""));
112
+ return sendJson(res, 200, await settle(read.json));
113
+ }
114
+ const server = createServer((req, res) => {
115
+ handle(req, res).catch(() => {
116
+ if (!res.headersSent)
117
+ sendJson(res, 500, { error: "internal error" });
118
+ else
119
+ res.destroy();
120
+ });
121
+ });
122
+ server.requestTimeout = settleWaitMs + 60_000;
123
+ await new Promise((resolve, reject) => {
124
+ server.once("error", reject);
125
+ server.listen(port, host, () => {
126
+ server.off("error", reject);
127
+ resolve();
128
+ });
129
+ });
130
+ return {
131
+ async close() {
132
+ await new Promise((resolve) => {
133
+ server.close(() => resolve());
134
+ server.closeAllConnections();
135
+ });
136
+ await polkadot.close();
137
+ await store.close();
138
+ },
139
+ };
140
+ }
@@ -0,0 +1,13 @@
1
+ import { type PolkadotNetwork } from "@integraledger/lcp/polkadot";
2
+ import { type FacilitatorRequest, type SettleAnswer, type VerifyAnswer } from "./answers.js";
3
+ import { type SettlementStore } from "./store.js";
4
+ export interface PolkadotNode {
5
+ network: PolkadotNetwork;
6
+ rpc: string;
7
+ }
8
+ export declare function createPolkadot(nodes: readonly PolkadotNode[], s: SettlementStore, settleWaitMs: number): {
9
+ verify: (r: FacilitatorRequest) => Promise<VerifyAnswer>;
10
+ settle: (r: FacilitatorRequest) => Promise<SettleAnswer>;
11
+ close: () => Promise<void>;
12
+ networks: string[];
13
+ };