@toon-protocol/client 5.1.1 → 5.2.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.
@@ -14,6 +14,11 @@ var RPC_SOCKS_USERNAMES = {
14
14
  };
15
15
  var SOCKS_ISOLATION_PASSWORD = "toon";
16
16
  var UNDICI_DEFAULT_KEEP_ALIVE_MS = 4e3;
17
+ var CANARY_HOST = "127.0.0.1";
18
+ var CANARY_PORT = 2;
19
+ function isCanary(host, port) {
20
+ return host === CANARY_HOST && port === CANARY_PORT;
21
+ }
17
22
  async function socksConnect(proxy, destination, timeoutMs) {
18
23
  const { SocksClient } = nodeRequire("socks");
19
24
  const { socket } = await SocksClient.createConnection({
@@ -39,6 +44,7 @@ function createHiddenServiceTransport(socksProxy, options = {}) {
39
44
  ...options.socksUsername !== void 0 ? { username: options.socksUsername } : {}
40
45
  };
41
46
  const timeoutMs = options.connectTimeoutMs ?? DEFAULT_HS_CONNECT_TIMEOUT_MS;
47
+ const canary = { hits: 0 };
42
48
  const undici = requireOptional("undici", socksProxy);
43
49
  requireOptional("socks", socksProxy);
44
50
  const tls = nodeRequire("node:tls");
@@ -51,6 +57,10 @@ function createHiddenServiceTransport(socksProxy, options = {}) {
51
57
  } : {},
52
58
  connect(connectOptions, callback) {
53
59
  const port = portFor(connectOptions.protocol ?? "http:", connectOptions.port);
60
+ if (isCanary(connectOptions.hostname, port)) {
61
+ canary.hits += 1;
62
+ return callback(new Error("proxy canary: dial refused"), null);
63
+ }
54
64
  socksConnect(proxy, { host: connectOptions.hostname, port }, timeoutMs).then((socket) => {
55
65
  socket.setNoDelay(true);
56
66
  if (connectOptions.protocol !== "https:") return callback(null, socket);
@@ -65,7 +75,7 @@ function createHiddenServiceTransport(socksProxy, options = {}) {
65
75
  }
66
76
  });
67
77
  const proxiedFetch = ((input, init) => globalThis.fetch(input, { ...init, dispatcher }));
68
- const agents = createWebSocketAgents(proxy, timeoutMs);
78
+ const agents = createWebSocketAgents(proxy, timeoutMs, canary);
69
79
  return {
70
80
  fetch: proxiedFetch,
71
81
  createWebSocket: (url) => {
@@ -74,6 +84,7 @@ function createHiddenServiceTransport(socksProxy, options = {}) {
74
84
  return new WSClass(url, { agent: secure ? agents.https : agents.http });
75
85
  },
76
86
  dispatcher,
87
+ canaryHits: () => canary.hits,
77
88
  async close() {
78
89
  agents.http.destroy();
79
90
  agents.https.destroy();
@@ -88,13 +99,19 @@ function createChainRpcTransport(socksProxy, chain) {
88
99
  idleTimeoutMs: RPC_POOL_IDLE_TIMEOUT_MS
89
100
  });
90
101
  }
91
- function createWebSocketAgents(proxy, timeoutMs) {
102
+ function createWebSocketAgents(proxy, timeoutMs, canary) {
92
103
  const http = nodeRequire("node:http");
93
104
  const https = nodeRequire("node:https");
94
105
  const tls = nodeRequire("node:tls");
95
106
  class SocksHttpAgent extends http.Agent {
96
107
  createConnection(opts, callback) {
97
- socksConnect(proxy, { host: String(opts.host), port: portFor("http:", opts.port) }, timeoutMs).then(
108
+ const port = portFor("http:", opts.port);
109
+ if (isCanary(String(opts.host), port)) {
110
+ canary.hits += 1;
111
+ callback?.(new Error("proxy canary: dial refused"), void 0);
112
+ return void 0;
113
+ }
114
+ socksConnect(proxy, { host: String(opts.host), port }, timeoutMs).then(
98
115
  (socket) => callback?.(null, socket),
99
116
  (err) => callback?.(err, void 0)
100
117
  );
@@ -104,7 +121,13 @@ function createWebSocketAgents(proxy, timeoutMs) {
104
121
  class SocksHttpsAgent extends https.Agent {
105
122
  createConnection(opts, callback) {
106
123
  const fail = (err) => callback?.(err, void 0);
107
- socksConnect(proxy, { host: String(opts.host), port: portFor("https:", opts.port) }, timeoutMs).then(
124
+ const port = portFor("https:", opts.port);
125
+ if (isCanary(String(opts.host), port)) {
126
+ canary.hits += 1;
127
+ fail(new Error("proxy canary: dial refused"));
128
+ return void 0;
129
+ }
130
+ socksConnect(proxy, { host: String(opts.host), port }, timeoutMs).then(
108
131
  (socket) => {
109
132
  const secure = tls.connect({
110
133
  socket,
@@ -169,8 +192,10 @@ export {
169
192
  DEFAULT_RPC_CONNECT_TIMEOUT_MS,
170
193
  RPC_POOL_IDLE_TIMEOUT_MS,
171
194
  RPC_SOCKS_USERNAMES,
195
+ CANARY_HOST,
196
+ CANARY_PORT,
172
197
  createHiddenServiceTransport,
173
198
  createChainRpcTransport,
174
199
  probeSocks5Proxy
175
200
  };
176
- //# sourceMappingURL=chunk-SIDK54Y5.js.map
201
+ //# sourceMappingURL=chunk-KWUYZQBN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transport/socks.ts"],"sourcesContent":["/**\n * The hidden-service carriage: one SOCKS5h proxy, everything that must ride it.\n *\n * A connector deployed as a hidden service is reachable only through a running\n * `anon` daemon's SOCKS5 port. Three separate things in this client have to go\n * through that port, and — annoyingly — each needs a different object to do it:\n *\n * - **The client edge** (`GET /ilp`, `POST /ilp`) goes through `fetch`, which in\n * Node is undici and takes a **dispatcher**. It does not take an `http.Agent`,\n * which is why the `socks-proxy-agent` this package used to depend on cannot\n * serve this path at all.\n * - **Chain RPC** goes through viem, which takes an injected `fetchFn`\n * (`http(url, { fetchFn })`), so it is handed this transport's proxied `fetch`\n * (ADR 0002, ADR 0005).\n * - **The BTP carriage** goes through `ws`, which is `node:http` underneath and\n * therefore takes an `http.Agent` and nothing else.\n *\n * So this module builds one SOCKS connection primitive and wraps it three ways.\n * The SOCKS5 handshake itself is `socks`'s job; all we supply is the socket.\n *\n * Chain RPC gets a transport of its own per chain ({@link createChainRpcTransport}),\n * authenticating with a fixed SOCKS username so each chain rides one pinned\n * circuit (connector ADR 0073). The same is true whether the connector is a\n * hidden service or a clearnet host that a hidden payer reaches through the\n * proxy (TOON_Network#167).\n *\n * `undici` is an optional dependency for exactly this reason: Node bundles undici\n * internally but exposes it under no specifier (`require('undici')` is\n * `MODULE_NOT_FOUND`, `node:undici` is `ERR_UNKNOWN_BUILTIN_MODULE`), so a\n * dispatcher cannot be constructed without the package. A dispatcher built by the\n * userland copy *is* honoured by Node's global `fetch`, which calls\n * `dispatcher.dispatch(opts, handler)` with a handler its own bundled undici\n * defines — and that is why the dependency is pinned to **undici 7, not 8**.\n * Node's handler changed shape: Node 22 (undici 6.22) passes the old\n * `onConnect`/`onHeaders`/`onData`/`onComplete` handler, Node 26 (undici 8.9)\n * passes the new `onRequestStart`/`onResponseStart` one. undici 7 accepts both —\n * its `UnwrapHandler.unwrap` passes an old-style handler through untouched.\n * undici 8 dropped the old shape, and on Node 22 every request through such a\n * dispatcher dies in `assertRequestHandler` with\n * `InvalidArgumentError: invalid onRequestStart method`. Verified green on both\n * Node 22.21 and Node 26.7 against the fake proxy in `socks.test.ts`; do not\n * widen the range to `^8` without re-running those on the oldest supported Node.\n *\n * NODE ONLY. This module is imported dynamically, never statically, from the\n * paths that need it; every Node built-in is pulled in through an ESM-safe\n * `require` built off `import.meta.url`, because this package builds as ESM with\n * these deps external and esbuild rewrites a bare `require` into a `__require`\n * shim that throws. A browser cannot reach a `.anyone` address by any means, so\n * a browser bundler must never follow an edge into this file.\n */\n\nimport { createRequire } from 'node:module';\nimport { validateSocks5hUrl } from './socks-url.js';\nimport type { ChainKind } from '../channel/types.js';\nimport type * as netModule from 'node:net';\nimport type * as streamModule from 'node:stream';\nimport type * as tlsModule from 'node:tls';\nimport type * as httpModule from 'node:http';\nimport type * as httpsModule from 'node:https';\nimport type * as socksModule from 'socks';\nimport type * as undiciModule from 'undici';\nimport type WSModule from 'ws';\n\n// ESM-safe require: this file builds as ESM with `undici`/`socks`/`ws` external,\n// so a bare `require(...)` would become a throwing `__require` shim in the\n// published bundle. Building a real require off `import.meta.url` keeps the\n// synchronous lookups below working. (The same pattern the deleted `socks5.ts`\n// carried, for the same reason — it was found in production.)\nconst nodeRequire = createRequire(import.meta.url);\n\n/**\n * How long to wait for the proxy to build a circuit to the hidden service.\n *\n * `socks` defaults to 30s, which is too short: an introduction-point circuit to\n * a cold hidden service routinely takes longer, and a too-short connect timeout\n * turns \"slow\" into \"unreachable\".\n */\nexport const DEFAULT_HS_CONNECT_TIMEOUT_MS = 120_000;\n\n/**\n * How long a chain-RPC dial may take through the proxy: the SOCKS handshake, an\n * exit circuit and the TCP connect behind it (connector ADR 0073, decision 4).\n *\n * Far shorter than {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}, because a public RPC\n * is reached over an ordinary exit circuit, not the introduction-point dance a\n * hidden service needs. ADR 0073 measured 3,200 calls through `anon`: the worst\n * one that had to build a fresh circuit took 13s. Twice that, rounded, and a\n * stalled circuit is reported rather than waited on.\n */\nexport const DEFAULT_RPC_CONNECT_TIMEOUT_MS = 20_000;\n\n/**\n * The longest a pooled chain-RPC connection is kept idle (ADR 0073, decision 4).\n *\n * A circuit can die quietly under a kept-alive socket, and the next request on\n * it then hangs until its own timeout. A short idle cap means such a socket is\n * dropped before it is reused. undici keeps a socket for 4s by default but lets a\n * server's `Keep-Alive` header stretch that to ten minutes; this caps the stretch.\n */\nexport const RPC_POOL_IDLE_TIMEOUT_MS = 30_000;\n\n/**\n * The fixed SOCKS5 usernames chain RPC authenticates with, one per chain.\n *\n * `anon` (like Tor) isolates streams by SOCKS credentials (`IsolateSOCKSAuth`,\n * on by default): streams that present the same username share a circuit, and\n * streams with different ones never do. So a fixed username per chain gives each\n * chain one circuit that stays pinned until the daemon's own\n * `MaxCircuitDirtiness` rotates it (connector ADR 0073, decision 3). No exit then\n * sees both chains' RPC, neither shares a circuit with the client edge, and no\n * call pays for a new circuit of its own. They differ from the connector's\n * `toon-settlement-*` names, so a payer and a node on one daemon do not share\n * circuits either.\n */\nexport const RPC_SOCKS_USERNAMES: Readonly<Record<ChainKind, string>> = {\n evm: 'toon-client-rpc-evm',\n solana: 'toon-client-rpc-solana',\n};\n\n/**\n * The password sent beside a {@link HiddenServiceTransportOptions.socksUsername}.\n * `anon` checks nothing; the username alone picks the circuit. RFC 1929 still\n * wants one, so it is a constant.\n */\nconst SOCKS_ISOLATION_PASSWORD = 'toon';\n\n/** undici's own idle keep-alive, which {@link HiddenServiceTransportOptions.idleTimeoutMs} only ever lowers. */\nconst UNDICI_DEFAULT_KEEP_ALIVE_MS = 4_000;\n\n/**\n * Where a canary (ADR 0005) is sent: a closed loopback port. The proxy hooks\n * recognise it, count it and refuse the dial without contacting the proxy; a\n * path that ignores its hook dials it directly and finds nothing listening.\n */\nexport const CANARY_HOST = '127.0.0.1';\n/**\n * Not port 1: the fetch standard blocks it as a \"bad port\" (tcpmux), so a request\n * to it dies before any dial and could never tell a honoured hook from a bypass.\n */\nexport const CANARY_PORT = 2;\n\nfunction isCanary(host: string, port: number): boolean {\n return host === CANARY_HOST && port === CANARY_PORT;\n}\n\n/** Options for {@link createHiddenServiceTransport}. */\nexport interface HiddenServiceTransportOptions {\n /** Circuit-build timeout, ms. Default {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}. */\n connectTimeoutMs?: number;\n /**\n * A fixed SOCKS5 username to authenticate with, which pins every stream this\n * transport opens to one circuit (`IsolateSOCKSAuth`). Unset means no\n * authentication, and the daemon's default circuit.\n */\n socksUsername?: string;\n /**\n * Upper bound on how long an idle pooled connection is kept, ms. Unset keeps\n * undici's own behaviour.\n */\n idleTimeoutMs?: number;\n}\n\n/**\n * The three shapes of one proxy, plus the handle that shuts it down.\n *\n * Spread `fetch` and `createWebSocket` into a {@link ../client/types.js!ToonClientConfig}\n * to route a client by hand; pass `socksProxy` instead to have the client build\n * this itself.\n */\nexport interface HiddenServiceTransport {\n /** `fetch`, bound to the proxy. Returns ordinary global `Response` objects. */\n fetch: typeof fetch;\n /** A `ws` factory bound to the proxy, for the BTP carriage. */\n createWebSocket: (url: string) => unknown;\n /**\n * The undici dispatcher behind `fetch`, for handing to something that insists\n * on calling the global `fetch` itself. The client's own paths, viem's\n * included (`http(url, { fetchFn })`), use `fetch` instead.\n */\n dispatcher: unknown;\n /**\n * How many canary dials this transport's proxy hooks (the dispatcher's\n * `connect`, the websocket agents' `createConnection`) have seen and refused.\n */\n canaryHits(): number;\n /** Close the dispatcher's pool and the websocket agents' sockets. */\n close(): Promise<void>;\n}\n\nexport { validateSocks5hUrl } from './socks-url.js';\n\n/** The one primitive: a TCP socket to `destination`, dialled through the proxy. */\nasync function socksConnect(\n proxy: { host: string; port: number; username?: string },\n destination: { host: string; port: number },\n timeoutMs: number\n): Promise<netModule.Socket> {\n const { SocksClient } = nodeRequire('socks') as typeof socksModule;\n const { socket } = await SocksClient.createConnection({\n proxy: {\n host: proxy.host,\n port: proxy.port,\n type: 5,\n ...(proxy.username !== undefined\n ? { userId: proxy.username, password: SOCKS_ISOLATION_PASSWORD }\n : {}),\n },\n command: 'connect',\n destination,\n timeout: timeoutMs,\n });\n return socket;\n}\n\n/** Default port for a scheme, when the URL does not name one. */\nfunction portFor(protocol: string, port: string | number | null | undefined): number {\n if (port !== undefined && port !== null && port !== '' && Number.isFinite(Number(port))) return Number(port);\n return protocol === 'https:' || protocol === 'wss:' ? 443 : 80;\n}\n\n/**\n * Builds every proxy-bound object this client needs from one `socks5h://` URL.\n *\n * @throws {Error} if the URL is not `socks5h://`, or if `undici`/`socks` are not\n * installed — they are optional dependencies, so a consumer who never touches\n * a hidden service never pays for them.\n */\nexport function createHiddenServiceTransport(\n socksProxy: string,\n options: HiddenServiceTransportOptions = {}\n): HiddenServiceTransport {\n const proxy = {\n ...validateSocks5hUrl(socksProxy),\n ...(options.socksUsername !== undefined ? { username: options.socksUsername } : {}),\n };\n const timeoutMs = options.connectTimeoutMs ?? DEFAULT_HS_CONNECT_TIMEOUT_MS;\n const canary = { hits: 0 };\n\n const undici = requireOptional<typeof undiciModule>('undici', socksProxy);\n requireOptional<typeof socksModule>('socks', socksProxy);\n const tls = nodeRequire('node:tls') as typeof tlsModule;\n\n // The dispatcher. undici hands its `connect` hook the destination it wants a\n // socket to; we dial that through SOCKS instead of `net.connect`, and wrap it\n // in TLS ourselves when the scheme calls for it (undici's default connector\n // would have done that, and we have replaced it).\n const dispatcher = new undici.Agent({\n // A cap, not a new default: undici's own 4s idle stays when it is shorter,\n // and a server's `Keep-Alive` hint can no longer stretch it past the cap.\n ...(options.idleTimeoutMs !== undefined\n ? {\n keepAliveTimeout: Math.min(UNDICI_DEFAULT_KEEP_ALIVE_MS, options.idleTimeoutMs),\n keepAliveMaxTimeout: options.idleTimeoutMs,\n }\n : {}),\n connect(\n connectOptions: { hostname: string; port?: string | number; protocol?: string; servername?: string },\n callback: (err: Error | null, socket: unknown) => void\n ) {\n const port = portFor(connectOptions.protocol ?? 'http:', connectOptions.port);\n if (isCanary(connectOptions.hostname, port)) {\n canary.hits += 1;\n return callback(new Error('proxy canary: dial refused'), null);\n }\n socksConnect(proxy, { host: connectOptions.hostname, port }, timeoutMs).then((socket) => {\n socket.setNoDelay(true);\n if (connectOptions.protocol !== 'https:') return callback(null, socket);\n const secure = tls.connect({\n socket,\n servername: connectOptions.servername ?? connectOptions.hostname,\n ALPNProtocols: ['http/1.1'],\n });\n secure.once('secureConnect', () => callback(null, secure));\n secure.once('error', (err) => callback(err, null));\n }, (err: Error) => callback(err, null));\n },\n } as unknown as undiciModule.Agent.Options);\n\n // Node's global `fetch` honours a dispatcher built by this userland undici —\n // the `connect` hook above fires — and returns ordinary global `Response`\n // objects, which `undici.fetch` would not, and callers do compare those\n // against the global class. See the note on the undici 7 pin at the top of\n // this file: this line is what makes the major version load-bearing.\n // `dispatcher` is not in the standard `RequestInit`, and @types/node carries a\n // second copy of undici's types that does not structurally match the userland\n // one — hence the cast. The runtime behaviour is verified, the types are not\n // able to express it.\n const proxiedFetch = ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) =>\n globalThis.fetch(input, { ...init, dispatcher } as unknown as RequestInit)) as typeof fetch;\n\n const agents = createWebSocketAgents(proxy, timeoutMs, canary);\n\n return {\n fetch: proxiedFetch,\n createWebSocket: (url: string) => {\n const WSClass = loadWebSocketClass();\n const secure = url.startsWith('wss:') || url.startsWith('https:');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new (WSClass as any)(url, { agent: secure ? agents.https : agents.http });\n },\n dispatcher,\n canaryHits: () => canary.hits,\n async close(): Promise<void> {\n agents.http.destroy();\n agents.https.destroy();\n await dispatcher.close();\n },\n };\n}\n\n/**\n * The proxy-bound transport one chain's RPC rides: its own pinned circuit, a\n * connect timeout sized for an exit circuit, and a capped idle pool (connector\n * ADR 0073, decisions 3 and 4).\n *\n * It has no fallback. A proxy that is down fails the call; nothing here, or in\n * the viem and Solana paths that use it, ever dials the RPC directly instead.\n */\nexport function createChainRpcTransport(\n socksProxy: string,\n chain: ChainKind\n): HiddenServiceTransport {\n return createHiddenServiceTransport(socksProxy, {\n connectTimeoutMs: DEFAULT_RPC_CONNECT_TIMEOUT_MS,\n socksUsername: RPC_SOCKS_USERNAMES[chain],\n idleTimeoutMs: RPC_POOL_IDLE_TIMEOUT_MS,\n });\n}\n\n/**\n * `ws` speaks `node:http`, so it wants an `http.Agent` — one per scheme, since\n * an `https.Agent` is what puts TLS on the socket and an `http.Agent` is what\n * must not.\n */\nfunction createWebSocketAgents(\n proxy: { host: string; port: number; username?: string },\n timeoutMs: number,\n canary: { hits: number }\n): { http: httpModule.Agent; https: httpsModule.Agent } {\n const http = nodeRequire('node:http') as typeof httpModule;\n const https = nodeRequire('node:https') as typeof httpsModule;\n const tls = nodeRequire('node:tls') as typeof tlsModule;\n\n // `createConnection` is the whole extension point: everything else about\n // pooling, keep-alive and request framing stays the stock agent's business.\n class SocksHttpAgent extends http.Agent {\n override createConnection(\n opts: httpModule.ClientRequestArgs,\n callback?: (err: Error | null, stream: streamModule.Duplex) => void\n ): streamModule.Duplex | null | undefined {\n const port = portFor('http:', opts.port);\n if (isCanary(String(opts.host), port)) {\n canary.hits += 1;\n callback?.(new Error('proxy canary: dial refused'), undefined as unknown as streamModule.Duplex);\n return undefined;\n }\n socksConnect(proxy, { host: String(opts.host), port }, timeoutMs).then(\n (socket) => callback?.(null, socket),\n (err: Error) => callback?.(err, undefined as unknown as streamModule.Duplex)\n );\n return undefined;\n }\n }\n\n class SocksHttpsAgent extends https.Agent {\n override createConnection(\n opts: httpsModule.RequestOptions,\n callback?: (err: Error | null, stream: streamModule.Duplex) => void\n ): streamModule.Duplex | null | undefined {\n const fail = (err: Error): void => callback?.(err, undefined as unknown as streamModule.Duplex);\n const port = portFor('https:', opts.port);\n if (isCanary(String(opts.host), port)) {\n canary.hits += 1;\n fail(new Error('proxy canary: dial refused'));\n return undefined;\n }\n socksConnect(proxy, { host: String(opts.host), port }, timeoutMs).then(\n (socket) => {\n const secure = tls.connect({\n socket,\n servername: opts.servername ?? String(opts.host),\n });\n secure.once('secureConnect', () => callback?.(null, secure));\n secure.once('error', fail);\n },\n fail\n );\n return undefined;\n }\n }\n\n return {\n http: new SocksHttpAgent({ keepAlive: false }),\n https: new SocksHttpsAgent({ keepAlive: false }),\n };\n}\n\n/**\n * CJS/ESM interop: `require('ws')` yields the class directly, `{ default }`, or\n * `{ WebSocket }` depending on loader and bundler. Walk the ladder rather than\n * accepting a namespace object as a constructor and throwing cryptically later.\n */\nfunction loadWebSocketClass(): unknown {\n const mod = nodeRequire('ws') as typeof WSModule | { default?: unknown; WebSocket?: unknown };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const candidate = mod as any;\n const WSClass =\n typeof candidate === 'function'\n ? candidate\n : typeof candidate.default === 'function'\n ? candidate.default\n : typeof candidate.WebSocket === 'function'\n ? candidate.WebSocket\n : null;\n if (WSClass === null) {\n throw new Error(\n \"The BTP carriage over a hidden service needs the `ws` package, and require('ws') \" +\n 'did not yield a constructor on .default, .WebSocket, or the module root.'\n );\n }\n return WSClass;\n}\n\n/** Loads an optional dependency, or explains what to install and why. */\nfunction requireOptional<T>(name: string, socksProxy: string): T {\n try {\n return nodeRequire(name) as T;\n } catch {\n throw new Error(\n `Reaching a hidden service needs the optional dependency \"${name}\", which is not installed. ` +\n `Run \\`npm install ${name}\\`, or drop socksProxy (${socksProxy}) and dial a clearnet connector.`\n );\n }\n}\n\n/**\n * Probes the proxy with a plain TCP connect. Fail-closed and fail-early: a\n * client configured for a hidden service must not quietly fall back to clearnet,\n * and finding out at packet time costs a signed claim.\n */\nexport async function probeSocks5Proxy(socksProxy: string, timeoutMs = 2000): Promise<void> {\n const { host, port } = validateSocks5hUrl(socksProxy);\n const net = nodeRequire('node:net') as typeof netModule;\n\n return new Promise<void>((resolve, reject) => {\n const socket = net.createConnection({ host, port }, () => {\n socket.destroy();\n resolve();\n });\n const fail = (why: string): void => {\n socket.destroy();\n reject(\n new Error(\n `No SOCKS5 proxy at ${host}:${port} (${why}). A hidden-service connector is ` +\n 'unreachable without one: start the Anyone Protocol `anon` daemon, or run ' +\n '`toon-client` which can start one for you.'\n )\n );\n };\n socket.setTimeout(timeoutMs, () => fail(`timed out after ${timeoutMs}ms`));\n socket.on('error', (err) => fail(err.message));\n });\n}\n"],"mappings":";;;;;AAmDA,SAAS,qBAAqB;AAiB9B,IAAM,cAAc,cAAc,YAAY,GAAG;AAS1C,IAAM,gCAAgC;AAYtC,IAAM,iCAAiC;AAUvC,IAAM,2BAA2B;AAejC,IAAM,sBAA2D;AAAA,EACtE,KAAK;AAAA,EACL,QAAQ;AACV;AAOA,IAAM,2BAA2B;AAGjC,IAAM,+BAA+B;AAO9B,IAAM,cAAc;AAKpB,IAAM,cAAc;AAE3B,SAAS,SAAS,MAAc,MAAuB;AACrD,SAAO,SAAS,eAAe,SAAS;AAC1C;AAiDA,eAAe,aACb,OACA,aACA,WAC2B;AAC3B,QAAM,EAAE,YAAY,IAAI,YAAY,OAAO;AAC3C,QAAM,EAAE,OAAO,IAAI,MAAM,YAAY,iBAAiB;AAAA,IACpD,OAAO;AAAA,MACL,MAAM,MAAM;AAAA,MACZ,MAAM,MAAM;AAAA,MACZ,MAAM;AAAA,MACN,GAAI,MAAM,aAAa,SACnB,EAAE,QAAQ,MAAM,UAAU,UAAU,yBAAyB,IAC7D,CAAC;AAAA,IACP;AAAA,IACA,SAAS;AAAA,IACT;AAAA,IACA,SAAS;AAAA,EACX,CAAC;AACD,SA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c,aAC7B,UAAU,YACV;AACV,MAAI,YAAY,MAAM;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,gBAAmB,MAAc,YAAuB;AAC/D,MAAI;AACF,WAAO,YAAY,IAAI;AAAA,EACzB,QAAQ;AACN,UAAM,IAAI;AAAA,MACR,4DAA4D,IAAI,gDACzC,IAAI,2BAA2B,UAAU;AAAA,IAClE;AAAA,EACF;AACF;AAOA,eAAsB,iBAAiB,YAAoB,YAAY,KAAqB;AAC1F,QAAM,EAAE,MAAM,KAAK,IAAI,mBAAmB,UAAU;AACpD,QAAM,MAAM,YAAY,UAAU;AAElC,SAAO,IAAI,QAAc,CAAC,SAAS,WAAW;AAC5C,UAAM,SAAS,IAAI,iBAAiB,EAAE,MAAM,KAAK,GAAG,MAAM;AACxD,aAAO,QAAQ;AACf,cAAQ;AAAA,IACV,CAAC;AACD,UAAM,OAAO,CAAC,QAAsB;AAClC,aAAO,QAAQ;AACf;AAAA,QACE,IAAI;AAAA,UACF,sBAAsB,IAAI,IAAI,IAAI,KAAK,GAAG;AAAA,QAG5C;AAAA,MACF;AAAA,IACF;AACA,WAAO,WAAW,WAAW,MAAM,KAAK,mBAAmB,SAAS,IAAI,CAAC;AACzE,WAAO,GAAG,SAAS,CAAC,QAAQ,KAAK,IAAI,OAAO,CAAC;AAAA,EAC/C,CAAC;AACH;","names":[]}
package/dist/cli/main.js CHANGED
@@ -75,6 +75,16 @@ var GLOBAL_OPTIONS = {
75
75
  arg: "auto|http|btp",
76
76
  help: "Which carriage to pay over. Default auto."
77
77
  },
78
+ "http-endpoint": {
79
+ type: "string",
80
+ arg: "URL",
81
+ help: "Pay HTTP packets at this URL instead of the httpEndpoint the connector publishes. Env TOON_HTTP_ENDPOINT."
82
+ },
83
+ "btp-endpoint": {
84
+ type: "string",
85
+ arg: "URL",
86
+ help: "Dial BTP at this ws(s):// URL instead of the btpEndpoint the connector publishes. Env TOON_BTP_ENDPOINT."
87
+ },
78
88
  socks: {
79
89
  type: "string",
80
90
  arg: "URL",
@@ -265,6 +275,9 @@ var COMMANDS = {
265
275
  }
266
276
  };
267
277
  var CHANNEL_SUBCOMMANDS = ["open", "deposit", "status", "close", "settle"];
278
+ function isChannelSubcommand(word) {
279
+ return CHANNEL_SUBCOMMANDS.includes(word);
280
+ }
268
281
  function stringOption(values, name) {
269
282
  const v = values[name];
270
283
  if (v === void 0) return void 0;
@@ -308,6 +321,15 @@ function parseCommandLine(argv) {
308
321
  throw new UsageError(`unknown command '${command}'. Run 'toon-client help' for the list.`);
309
322
  }
310
323
  const rest = positionals.slice(1);
324
+ if (rest.length > spec.maxPositionals) {
325
+ throw new UsageError(
326
+ `'${command}' takes at most ${String(spec.maxPositionals)} argument(s); got ${String(rest.length)}`,
327
+ command
328
+ );
329
+ }
330
+ if (command === "channel" && rest[0] !== void 0 && !isChannelSubcommand(rest[0])) {
331
+ throw new UsageError(`channel needs one of: ${CHANNEL_SUBCOMMANDS.join(", ")}`, command);
332
+ }
311
333
  if (!boolOption(values, "help")) {
312
334
  for (const name of Object.keys(values)) {
313
335
  if (values[name] === void 0) continue;
@@ -318,12 +340,6 @@ function parseCommandLine(argv) {
318
340
  if (rest.length < spec.minPositionals) {
319
341
  throw new UsageError(`'${command}' needs more arguments`, command);
320
342
  }
321
- if (rest.length > spec.maxPositionals) {
322
- throw new UsageError(
323
- `'${command}' takes at most ${String(spec.maxPositionals)} argument(s); got ${String(rest.length)}`,
324
- command
325
- );
326
- }
327
343
  }
328
344
  return { command, positionals: rest, values };
329
345
  }
@@ -367,7 +383,8 @@ function usage(command) {
367
383
  "",
368
384
  "Environment: TOON_CONNECTOR, TOON_MNEMONIC, TOON_KEYSTORE,",
369
385
  " TOON_KEYSTORE_PASSWORD, TOON_CHAIN, TOON_RPC_URL, TOON_CHANNEL_STORE,",
370
- " TOON_SOCKS, TOON_FACILITATOR, TOON_DEPOSIT_GAS, TOON_DEPOSIT_METHOD.",
386
+ " TOON_SOCKS, TOON_HTTP_ENDPOINT, TOON_BTP_ENDPOINT, TOON_FACILITATOR,",
387
+ " TOON_DEPOSIT_GAS, TOON_DEPOSIT_METHOD.",
371
388
  "",
372
389
  "Run 'toon-client help <command>' for one command in detail."
373
390
  ].join("\n");
@@ -449,6 +466,8 @@ var CHAIN_ENV = "TOON_CHAIN";
449
466
  var RPC_ENV = "TOON_RPC_URL";
450
467
  var CHANNEL_STORE_ENV = "TOON_CHANNEL_STORE";
451
468
  var SOCKS_ENV = "TOON_SOCKS";
469
+ var HTTP_ENDPOINT_ENV = "TOON_HTTP_ENDPOINT";
470
+ var BTP_ENDPOINT_ENV = "TOON_BTP_ENDPOINT";
452
471
  var FACILITATOR_ENV = "TOON_FACILITATOR";
453
472
  var DEPOSIT_GAS_ENV = "TOON_DEPOSIT_GAS";
454
473
  var DEPOSIT_METHOD_ENV = "TOON_DEPOSIT_METHOD";
@@ -498,6 +517,14 @@ function resolveSettings(values, env, options = {}) {
498
517
  const socksFlag = stringOption(values, "socks");
499
518
  const socksEnv = env[SOCKS_ENV];
500
519
  const socksProxy = socksFlag !== void 0 && socksFlag.length > 0 ? socksFlag : socksEnv !== void 0 && socksEnv.length > 0 ? socksEnv : void 0;
520
+ const nonEmpty = (flag, envName) => {
521
+ const fromFlag = stringOption(values, flag);
522
+ if (fromFlag !== void 0 && fromFlag.length > 0) return fromFlag;
523
+ const fromEnv = env[envName];
524
+ return fromEnv !== void 0 && fromEnv.length > 0 ? fromEnv : void 0;
525
+ };
526
+ const httpEndpoint = nonEmpty("http-endpoint", HTTP_ENDPOINT_ENV);
527
+ const btpEndpoint = nonEmpty("btp-endpoint", BTP_ENDPOINT_ENV);
501
528
  const facilitator = stringOption(values, "facilitator") ?? env[FACILITATOR_ENV];
502
529
  const deposit = stringOption(values, "deposit");
503
530
  const depositGasFlag = stringOption(values, "deposit-gas");
@@ -524,6 +551,8 @@ function resolveSettings(values, env, options = {}) {
524
551
  channelStore,
525
552
  transport,
526
553
  ...socksProxy !== void 0 ? { socksProxy } : {},
554
+ ...httpEndpoint !== void 0 ? { httpEndpoint } : {},
555
+ ...btpEndpoint !== void 0 ? { btpEndpoint } : {},
527
556
  keystorePath: resolveKeystorePath({
528
557
  flag: stringOption(values, "keystore"),
529
558
  env,
@@ -567,12 +596,22 @@ async function resolveKeyMaterial(settings, deps, options = {}) {
567
596
  "Run 'toon-client init' to create one, or set TOON_MNEMONIC."
568
597
  );
569
598
  }
599
+ function carriageEndpointsOf(settings) {
600
+ if (settings.httpEndpoint === void 0 && settings.btpEndpoint === void 0)
601
+ return void 0;
602
+ return {
603
+ ...settings.httpEndpoint !== void 0 ? { http: settings.httpEndpoint } : {},
604
+ ...settings.btpEndpoint !== void 0 ? { btp: settings.btpEndpoint } : {}
605
+ };
606
+ }
570
607
  function buildClientConfig(settings, keys) {
608
+ const carriageEndpoints = carriageEndpointsOf(settings);
571
609
  const base = {
572
610
  connector: settings.connector,
573
611
  channelStore: settings.channelStore,
574
612
  transport: settings.transport,
575
613
  ...settings.socksProxy !== void 0 ? { socksProxy: settings.socksProxy } : {},
614
+ ...carriageEndpoints !== void 0 ? { carriageEndpoints } : {},
576
615
  // See this module's docs: a command never opens a channel as a side effect.
577
616
  autoOpenChannel: false,
578
617
  ...settings.chain !== void 0 ? { chain: settings.chain } : {},
@@ -593,7 +632,7 @@ function buildClientConfig(settings, keys) {
593
632
  };
594
633
  }
595
634
  async function defaultCreateClient(config) {
596
- const module = await import("../client-RO3VITXU.js");
635
+ const module = await import("../client-3KOPQDZG.js");
597
636
  const factory = module.ToonClient;
598
637
  if (factory === void 0) {
599
638
  throw new Error(
@@ -845,7 +884,7 @@ function exitRows(result) {
845
884
  }
846
885
  async function run2(ctx) {
847
886
  const sub = ctx.positionals[0];
848
- if (sub === void 0 || !CHANNEL_SUBCOMMANDS.includes(sub)) {
887
+ if (sub === void 0 || !isChannelSubcommand(sub)) {
849
888
  throw new UsageError(`channel needs one of: ${CHANNEL_SUBCOMMANDS.join(", ")}`, "channel");
850
889
  }
851
890
  const client = await ctx.client();
@@ -967,11 +1006,13 @@ async function run4(ctx) {
967
1006
  });
968
1007
  const description = await client.describe();
969
1008
  const asset = assetFromSettlement(description.batchSettlements[0]);
1009
+ const overrides = carriageEndpointsOf(ctx.settings);
970
1010
  const payload = {
971
1011
  connector: client.connector,
972
1012
  ilpAddresses: description.ilpAddresses,
973
1013
  httpEndpoint: description.httpEndpoint,
974
1014
  btpEndpoint: description.btpEndpoint,
1015
+ ...overrides !== void 0 ? { carriageEndpointOverrides: overrides } : {},
975
1016
  peerCarriages: description.peerCarriages,
976
1017
  edgeIdentity: description.edgeIdentity,
977
1018
  batchSettlements: description.batchSettlements,
@@ -988,6 +1029,12 @@ async function run4(ctx) {
988
1029
  }
989
1030
  if (description.httpEndpoint !== void 0) head.push(["http", description.httpEndpoint]);
990
1031
  if (description.btpEndpoint !== void 0) head.push(["btp", description.btpEndpoint]);
1032
+ if (overrides?.http !== void 0) {
1033
+ head.push(["http override", `${overrides.http} (--http-endpoint; packets go here)`]);
1034
+ }
1035
+ if (overrides?.btp !== void 0) {
1036
+ head.push(["btp override", `${overrides.btp} (--btp-endpoint; packets go here)`]);
1037
+ }
991
1038
  if (description.requiredTransport !== void 0) {
992
1039
  head.push(["requires", `${description.requiredTransport} carriage`]);
993
1040
  }