@integraledger/profile-facilitator 0.2.0 → 0.3.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/dist/http.js CHANGED
@@ -6,19 +6,31 @@ const UNSENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH"
6
6
  function isObject(v) {
7
7
  return typeof v === "object" && v !== null;
8
8
  }
9
- /** Why a node call gave no answer. `sent` is false only when the request cannot have reached the node. */
9
+ /**
10
+ * Why a node call gave no answer. `sent` is false only when the request cannot have reached the node. `spent` is a call
11
+ * whose deadline left it no time: it is not sent.
12
+ */
10
13
  export class NodeError extends Error {
11
14
  code;
12
15
  sent;
13
- constructor(code, sent, detail) {
14
- super(`${code}: ${detail}`);
16
+ constructor(code, sent, detail, options) {
17
+ super(`${code}: ${detail}`, options);
15
18
  this.code = code;
16
19
  this.sent = sent;
17
20
  }
18
21
  }
19
- /** POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and `maxBytes` (4 MiB unless given). */
22
+ /** True for a node call that was not sent because its deadline left it no time. */
23
+ export function isSpent(e) {
24
+ return e instanceof NodeError && e.code === "spent";
25
+ }
26
+ /**
27
+ * POSTs a JSON body and reads a JSON answer within the timeout (at most 5 s) and `maxBytes` (4 MiB unless given). A
28
+ * timeout that leaves no time sends nothing: the call fails as `spent`.
29
+ */
20
30
  export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS, maxBytes = NODE_MAX_BYTES) {
21
- const ms = Number.isFinite(timeoutMs) ? Math.max(1, Math.ceil(Math.min(timeoutMs, NODE_TIMEOUT_MS))) : NODE_TIMEOUT_MS;
31
+ if (timeoutMs <= 0)
32
+ throw new NodeError("spent", false, url);
33
+ const ms = Number.isFinite(timeoutMs) ? Math.ceil(Math.min(timeoutMs, NODE_TIMEOUT_MS)) : NODE_TIMEOUT_MS;
22
34
  const signal = AbortSignal.timeout(ms);
23
35
  let res;
24
36
  try {
@@ -31,10 +43,10 @@ export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS, maxBytes
31
43
  }
32
44
  catch (e) {
33
45
  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));
46
+ throw new NodeError("timeout", true, url, { cause: e });
47
+ const code = e instanceof Error && isObject(e.cause) ? e.cause["code"] : undefined;
48
+ const unsent = typeof code === "string" && UNSENT.has(code);
49
+ throw new NodeError("transport", !unsent, e instanceof Error ? e.message : String(e), { cause: e });
38
50
  }
39
51
  const bytes = await readBounded(res, signal, maxBytes);
40
52
  if (res.status < 200 || res.status > 299)
@@ -42,8 +54,8 @@ export async function postJson(url, body, timeoutMs = NODE_TIMEOUT_MS, maxBytes
42
54
  try {
43
55
  return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
44
56
  }
45
- catch {
46
- throw new NodeError("malformed", true, "the answer is not JSON");
57
+ catch (e) {
58
+ throw new NodeError("malformed", true, "the answer is not JSON", { cause: e });
47
59
  }
48
60
  }
49
61
  async function readBounded(res, signal, maxBytes) {
@@ -74,8 +86,8 @@ async function readBounded(res, signal, maxBytes) {
74
86
  if (e instanceof NodeError)
75
87
  throw e;
76
88
  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));
89
+ throw new NodeError("timeout", true, "reading the answer", { cause: e });
90
+ throw new NodeError("transport", true, e instanceof Error ? e.message : String(e), { cause: e });
79
91
  }
80
92
  const out = new Uint8Array(total);
81
93
  let at = 0;
@@ -85,24 +97,33 @@ async function readBounded(res, signal, maxBytes) {
85
97
  }
86
98
  return out;
87
99
  }
88
- /** Reads a request body of at most 64 KiB as JSON; undefined when it is larger or is not JSON. */
100
+ /**
101
+ * Reads a request body of at most 64 KiB as JSON: `tooLarge` when it is larger, `left` when the request ends before
102
+ * its body does (the client left), and undefined when it is not JSON.
103
+ */
89
104
  export async function readRequestJson(req) {
90
105
  const declared = Number(req.headers["content-length"]);
91
106
  if (Number.isFinite(declared) && declared > REQUEST_MAX_BYTES)
92
107
  return { tooLarge: true };
93
108
  const parts = [];
94
109
  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);
110
+ try {
111
+ for await (const chunk of req) {
112
+ const b = chunk;
113
+ total += b.byteLength;
114
+ if (total > REQUEST_MAX_BYTES)
115
+ return { tooLarge: true };
116
+ parts.push(b);
117
+ }
118
+ }
119
+ catch {
120
+ return { left: true };
101
121
  }
102
122
  try {
103
123
  return { json: JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(parts))) };
104
124
  }
105
125
  catch {
126
+ // The client's own body is not JSON: refused `invalid_payload` to that client.
106
127
  return undefined;
107
128
  }
108
129
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { type PolkadotNetwork } from "@integraledger/lcp/polkadot";
2
- export type { SettleAnswer, VerifyAnswer } from "./answers.js";
3
2
  export interface ProfileFacilitatorConfig {
4
3
  /** "host:port" */
5
4
  listen: string;
@@ -19,6 +18,21 @@ export interface ProfileFacilitatorConfig {
19
18
  };
20
19
  /** How long `/settle` waits for inclusion before answering `settlement_pending`; default 30 000. */
21
20
  settleWaitMs: number;
21
+ /**
22
+ * Receives every entry for the operator: what the facilitator saw that its answer does not carry, with `network`,
23
+ * `payer` and `transaction` naming the payment where they are known. `cause` is the error that caused the entry,
24
+ * when there is one; the answer to the client is the same either way, and carries nothing from it. Called once per
25
+ * entry; what it throws, or a promise it returns that rejects, goes to the default with an `operator-log-failed`
26
+ * entry. Default: one JSON line per entry on standard error, the cause as its `cause` (name, message, stack and its
27
+ * own `cause` chain).
28
+ */
29
+ operatorLog?: (entry: {
30
+ event: string;
31
+ network?: string;
32
+ payer?: string;
33
+ transaction?: string;
34
+ [field: string]: unknown;
35
+ }, cause?: unknown) => void;
22
36
  }
23
37
  export declare function serveProfileFacilitator(c: ProfileFacilitatorConfig): Promise<{
24
38
  close(): Promise<void>;
package/dist/index.js CHANGED
@@ -7,12 +7,19 @@
7
7
  import { createServer } from "node:http";
8
8
  import { LCP_ASSETS_REMARK } from "@integraledger/lcp/polkadot";
9
9
  import { LCP_TRC20_MEMO } from "@integraledger/lcp/tron";
10
- import { failed, readRequest } from "./answers.js";
10
+ import { failed, guarded, invalid, isObject, operatorLine, readRequest, } from "./answers.js";
11
11
  import { readRequestJson, sendJson } from "./http.js";
12
12
  import { createPolkadot } from "./polkadot.js";
13
13
  import { openStore } from "./store.js";
14
14
  import { createTron } from "./tron.js";
15
+ import { unexpectedSettle, unexpectedVerify } from "./unexpected.js";
15
16
  const DEFAULT_SETTLE_WAIT_MS = 30_000;
17
+ /** The body's `paymentRequirements.network` when it is a string, else "". */
18
+ function networkOf(body) {
19
+ const requirements = isObject(body) ? body["paymentRequirements"] : undefined;
20
+ const network = isObject(requirements) ? requirements["network"] : undefined;
21
+ return typeof network === "string" ? network : "";
22
+ }
16
23
  function hostPort(listen) {
17
24
  const m = /^\[?([^\]]*)\]?:(\d{1,5})$/.exec(listen);
18
25
  const port = m === null ? NaN : Number(m[2]);
@@ -26,115 +33,133 @@ function trimmed(url) {
26
33
  export async function serveProfileFacilitator(c) {
27
34
  const { host, port } = hostPort(c.listen);
28
35
  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);
36
+ const log = guarded(c.operatorLog ?? operatorLine);
37
+ const store = await openStore(c.store.url, log);
38
+ // If the facilitator does not start, what it opened is closed before its error goes to the caller unchanged: the
39
+ // store's pool and sweep, and the Polkadot rail, which opens a node's client only on that node's first request.
40
+ let closeNodes = async () => { };
41
+ try {
42
+ const tron = createTron((c.tron ?? []).map((n) => ({ ...n, fullNode: trimmed(n.fullNode), solidityNode: trimmed(n.solidityNode) })), store, settleWaitMs, log);
43
+ const polkadot = createPolkadot((c.polkadot ?? []).map((n) => ({ ...n, rpc: trimmed(n.rpc) })), store, settleWaitMs, log);
44
+ closeNodes = () => polkadot.close();
45
+ const supported = {
46
+ kinds: [
47
+ ...tron.networks.map((network) => ({
48
+ x402Version: 2,
49
+ scheme: "exact",
50
+ network,
51
+ extra: { assetTransferMethod: LCP_TRC20_MEMO },
52
+ })),
53
+ ...polkadot.networks.map((network) => ({
54
+ x402Version: 2,
55
+ scheme: "exact",
56
+ network,
57
+ extra: { assetTransferMethod: LCP_ASSETS_REMARK },
58
+ })),
59
+ ],
60
+ extensions: [],
61
+ signers: {},
62
+ };
63
+ function railOf(r) {
64
+ const n = r.paymentRequirements.network;
65
+ if (tron.networks.includes(n))
66
+ return tron;
67
+ if (polkadot.networks.includes(n))
68
+ return polkadot;
69
+ return undefined;
67
70
  }
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);
71
+ async function verify(body) {
72
+ const r = readRequest(body);
73
+ if (typeof r === "string")
74
+ return { isValid: false, invalidReason: r };
75
+ const rail = railOf(r);
76
+ if (rail === undefined)
77
+ return { isValid: false, invalidReason: "invalid_network" };
78
+ try {
79
+ return await rail.verify(r);
80
+ }
81
+ catch (e) {
82
+ return invalid(unexpectedVerify(log, { event: "verify-error", network: r.paymentRequirements.network }, e));
83
+ }
82
84
  }
83
- catch {
84
- return failed("unexpected_settle_error", "", network);
85
+ async function settle(body) {
86
+ const r = readRequest(body);
87
+ if (typeof r === "string")
88
+ return failed(r, "", networkOf(body));
89
+ const network = r.paymentRequirements.network;
90
+ const rail = railOf(r);
91
+ if (rail === undefined)
92
+ return failed("invalid_network", "", network);
93
+ try {
94
+ return await rail.settle(r);
95
+ }
96
+ catch (e) {
97
+ return unexpectedSettle(log, { event: "settle-error", network }, e);
98
+ }
85
99
  }
86
- }
87
- async function handle(req, res) {
88
- const path = (req.url ?? "").split("?")[0];
89
- if (path === "/supported") {
90
- if (req.method !== "GET")
100
+ async function handle(req, res) {
101
+ const path = (req.url ?? "").split("?")[0];
102
+ if (path === "/supported") {
103
+ if (req.method !== "GET")
104
+ return sendJson(res, 405, { error: "method not allowed" });
105
+ return sendJson(res, 200, supported);
106
+ }
107
+ if (path !== "/verify" && path !== "/settle")
108
+ return sendJson(res, 404, { error: "not found" });
109
+ if (req.method !== "POST")
91
110
  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") {
111
+ const read = await readRequestJson(req);
112
+ if (read !== undefined && "tooLarge" in read) {
113
+ res.setHeader("connection", "close");
114
+ sendJson(res, 413, { error: "the body is larger than 64 KiB" });
115
+ req.destroy();
116
+ return;
117
+ }
118
+ if (read !== undefined && "left" in read) {
119
+ // The client left before its body was complete: there is no one to answer, and nothing failed here to log.
120
+ res.destroy();
121
+ return;
122
+ }
123
+ if (path === "/verify") {
124
+ if (read === undefined)
125
+ return sendJson(res, 400, { isValid: false, invalidReason: "invalid_payload" });
126
+ return sendJson(res, 200, await verify(read.json));
127
+ }
106
128
  if (read === undefined)
107
- return sendJson(res, 400, { isValid: false, invalidReason: "invalid_payload" });
108
- return sendJson(res, 200, await verify(read.json));
129
+ return sendJson(res, 400, failed("invalid_payload", "", ""));
130
+ return sendJson(res, 200, await settle(read.json));
109
131
  }
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();
132
+ const server = createServer((req, res) => {
133
+ handle(req, res).catch((e) => {
134
+ log({ event: "request-error", path: (req.url ?? "").split("?")[0] }, e);
135
+ if (!res.headersSent)
136
+ sendJson(res, 500, { error: "internal error" });
137
+ else
138
+ res.destroy();
139
+ });
128
140
  });
129
- });
130
- return {
131
- async close() {
132
- await new Promise((resolve) => {
133
- server.close(() => resolve());
134
- server.closeAllConnections();
141
+ server.requestTimeout = settleWaitMs + 60_000;
142
+ await new Promise((resolve, reject) => {
143
+ server.once("error", reject);
144
+ server.listen(port, host, () => {
145
+ server.off("error", reject);
146
+ resolve();
135
147
  });
136
- await polkadot.close();
137
- await store.close();
138
- },
139
- };
148
+ });
149
+ return {
150
+ async close() {
151
+ await new Promise((resolve) => {
152
+ server.close(() => resolve());
153
+ server.closeAllConnections();
154
+ });
155
+ await polkadot.close();
156
+ await store.close();
157
+ },
158
+ };
159
+ }
160
+ catch (e) {
161
+ await closeNodes();
162
+ await store.close();
163
+ throw e;
164
+ }
140
165
  }
@@ -1,5 +1,5 @@
1
1
  import { type PolkadotNetwork } from "@integraledger/lcp/polkadot";
2
- import { type FacilitatorRequest, type SettleAnswer, type VerifyAnswer } from "./answers.js";
2
+ import { type FacilitatorRequest, type OperatorLog, type SettleAnswer, type VerifyAnswer } from "./answers.js";
3
3
  import { Slots } from "./http.js";
4
4
  import { type SettlementStore } from "./store.js";
5
5
  export interface PolkadotNode {
@@ -13,7 +13,7 @@ export interface PolkadotNode {
13
13
  export declare const BLOCK_READS = 4;
14
14
  /** The slots of `BLOCK_READS`, shared by every network and every scan in this process. */
15
15
  export declare const blockReads: Slots;
16
- export declare function createPolkadot(nodes: readonly PolkadotNode[], s: SettlementStore, settleWaitMs: number): {
16
+ export declare function createPolkadot(nodes: readonly PolkadotNode[], s: SettlementStore, settleWaitMs: number, log: OperatorLog): {
17
17
  verify: (r: FacilitatorRequest) => Promise<VerifyAnswer>;
18
18
  settle: (r: FacilitatorRequest) => Promise<SettleAnswer>;
19
19
  close: () => Promise<void>;