@toon-protocol/client 2.1.1 → 3.0.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,143 @@
1
+ import {
2
+ validateSocks5hUrl
3
+ } from "./chunk-32MD3CXE.js";
4
+
5
+ // src/transport/socks.ts
6
+ import { createRequire } from "module";
7
+ var nodeRequire = createRequire(import.meta.url);
8
+ var DEFAULT_HS_CONNECT_TIMEOUT_MS = 12e4;
9
+ async function socksConnect(proxy, destination, timeoutMs) {
10
+ const { SocksClient } = nodeRequire("socks");
11
+ const { socket } = await SocksClient.createConnection({
12
+ proxy: { host: proxy.host, port: proxy.port, type: 5 },
13
+ command: "connect",
14
+ destination,
15
+ timeout: timeoutMs
16
+ });
17
+ return socket;
18
+ }
19
+ function portFor(protocol, port) {
20
+ if (port !== void 0 && port !== null && port !== "" && Number.isFinite(Number(port))) return Number(port);
21
+ return protocol === "https:" || protocol === "wss:" ? 443 : 80;
22
+ }
23
+ function createHiddenServiceTransport(socksProxy, options = {}) {
24
+ const proxy = validateSocks5hUrl(socksProxy);
25
+ const timeoutMs = options.connectTimeoutMs ?? DEFAULT_HS_CONNECT_TIMEOUT_MS;
26
+ const undici = requireOptional("undici", socksProxy);
27
+ requireOptional("socks", socksProxy);
28
+ const tls = nodeRequire("node:tls");
29
+ const dispatcher = new undici.Agent({
30
+ connect(connectOptions, callback) {
31
+ const port = portFor(connectOptions.protocol ?? "http:", connectOptions.port);
32
+ socksConnect(proxy, { host: connectOptions.hostname, port }, timeoutMs).then((socket) => {
33
+ socket.setNoDelay(true);
34
+ if (connectOptions.protocol !== "https:") return callback(null, socket);
35
+ const secure = tls.connect({
36
+ socket,
37
+ servername: connectOptions.servername ?? connectOptions.hostname,
38
+ ALPNProtocols: ["http/1.1"]
39
+ });
40
+ secure.once("secureConnect", () => callback(null, secure));
41
+ secure.once("error", (err) => callback(err, null));
42
+ }, (err) => callback(err, null));
43
+ }
44
+ });
45
+ const proxiedFetch = ((input, init) => globalThis.fetch(input, { ...init, dispatcher }));
46
+ const agents = createWebSocketAgents(proxy, timeoutMs);
47
+ return {
48
+ fetch: proxiedFetch,
49
+ createWebSocket: (url) => {
50
+ const WSClass = loadWebSocketClass();
51
+ const secure = url.startsWith("wss:") || url.startsWith("https:");
52
+ return new WSClass(url, { agent: secure ? agents.https : agents.http });
53
+ },
54
+ dispatcher,
55
+ async close() {
56
+ agents.http.destroy();
57
+ agents.https.destroy();
58
+ await dispatcher.close();
59
+ }
60
+ };
61
+ }
62
+ function createWebSocketAgents(proxy, timeoutMs) {
63
+ const http = nodeRequire("node:http");
64
+ const https = nodeRequire("node:https");
65
+ const tls = nodeRequire("node:tls");
66
+ class SocksHttpAgent extends http.Agent {
67
+ createConnection(opts, callback) {
68
+ socksConnect(proxy, { host: String(opts.host), port: portFor("http:", opts.port) }, timeoutMs).then(
69
+ (socket) => callback?.(null, socket),
70
+ (err) => callback?.(err, void 0)
71
+ );
72
+ return void 0;
73
+ }
74
+ }
75
+ class SocksHttpsAgent extends https.Agent {
76
+ createConnection(opts, callback) {
77
+ const fail = (err) => callback?.(err, void 0);
78
+ socksConnect(proxy, { host: String(opts.host), port: portFor("https:", opts.port) }, timeoutMs).then(
79
+ (socket) => {
80
+ const secure = tls.connect({
81
+ socket,
82
+ servername: opts.servername ?? String(opts.host)
83
+ });
84
+ secure.once("secureConnect", () => callback?.(null, secure));
85
+ secure.once("error", fail);
86
+ },
87
+ fail
88
+ );
89
+ return void 0;
90
+ }
91
+ }
92
+ return {
93
+ http: new SocksHttpAgent({ keepAlive: false }),
94
+ https: new SocksHttpsAgent({ keepAlive: false })
95
+ };
96
+ }
97
+ function loadWebSocketClass() {
98
+ const mod = nodeRequire("ws");
99
+ const candidate = mod;
100
+ const WSClass = typeof candidate === "function" ? candidate : typeof candidate.default === "function" ? candidate.default : typeof candidate.WebSocket === "function" ? candidate.WebSocket : null;
101
+ if (WSClass === null) {
102
+ throw new Error(
103
+ "The BTP carriage over a hidden service needs the `ws` package, and require('ws') did not yield a constructor on .default, .WebSocket, or the module root."
104
+ );
105
+ }
106
+ return WSClass;
107
+ }
108
+ function requireOptional(name, socksProxy) {
109
+ try {
110
+ return nodeRequire(name);
111
+ } catch {
112
+ throw new Error(
113
+ `Reaching a hidden service needs the optional dependency "${name}", which is not installed. Run \`npm install ${name}\`, or drop socksProxy (${socksProxy}) and dial a clearnet connector.`
114
+ );
115
+ }
116
+ }
117
+ async function probeSocks5Proxy(socksProxy, timeoutMs = 2e3) {
118
+ const { host, port } = validateSocks5hUrl(socksProxy);
119
+ const net = nodeRequire("node:net");
120
+ return new Promise((resolve, reject) => {
121
+ const socket = net.createConnection({ host, port }, () => {
122
+ socket.destroy();
123
+ resolve();
124
+ });
125
+ const fail = (why) => {
126
+ socket.destroy();
127
+ reject(
128
+ new Error(
129
+ `No SOCKS5 proxy at ${host}:${port} (${why}). A hidden-service connector is unreachable without one: start the Anyone Protocol \`anon\` daemon, or run \`toon\` which can start one for you.`
130
+ )
131
+ );
132
+ };
133
+ socket.setTimeout(timeoutMs, () => fail(`timed out after ${timeoutMs}ms`));
134
+ socket.on("error", (err) => fail(err.message));
135
+ });
136
+ }
137
+
138
+ export {
139
+ DEFAULT_HS_CONNECT_TIMEOUT_MS,
140
+ createHiddenServiceTransport,
141
+ probeSocks5Proxy
142
+ };
143
+ //# sourceMappingURL=chunk-GOLBDUNV.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 calls the *global* `fetch` and accepts\n * no injected one. Its only opening is `http(url, { fetchOptions })`, so it\n * needs the same dispatcher handed to it as a fetch option (ADR 0002).\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 * `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 * 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/** Options for {@link createHiddenServiceTransport}. */\nexport interface HiddenServiceTransportOptions {\n /** Circuit-build timeout, ms. Default {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}. */\n connectTimeoutMs?: 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 — viem's HTTP transport, in practice\n * (`http(url, { fetchOptions: { dispatcher } })`).\n */\n dispatcher: unknown;\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 },\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: { host: proxy.host, port: proxy.port, type: 5 },\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 = validateSocks5hUrl(socksProxy);\n const timeoutMs = options.connectTimeoutMs ?? DEFAULT_HS_CONNECT_TIMEOUT_MS;\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 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 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);\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 async close(): Promise<void> {\n agents.http.destroy();\n agents.https.destroy();\n await dispatcher.close();\n },\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 },\n timeoutMs: 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 socksConnect(proxy, { host: String(opts.host), port: portFor('http:', opts.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 socksConnect(proxy, { host: String(opts.host), port: portFor('https:', opts.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` 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":";;;;;AA6CA,SAAS,qBAAqB;AAgB9B,IAAM,cAAc,cAAc,YAAY,GAAG;AAS1C,IAAM,gCAAgC;AAiC7C,eAAe,aACb,OACA,aACA,WAC2B;AAC3B,QAAM,EAAE,YAAY,IAAI,YAAY,OAAO;AAC3C,QAAM,EAAE,OAAO,IAAI,MAAM,YAAY,iBAAiB;AAAA,IACpD,OAAO,EAAE,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,EAAE;AAAA,IACrD,SAAS;AAAA,IACT;AAAA,IACA,SAAS;AAAA,EACX,CAAC;AACD,SAAO;AACT;AAGA,SAAS,QAAQ,UAAkB,MAAkD;AACnF,MAAI,SAAS,UAAa,SAAS,QAAQ,SAAS,MAAM,OAAO,SAAS,OAAO,IAAI,CAAC,EAAG,QAAO,OAAO,IAAI;AAC3G,SAAO,aAAa,YAAY,aAAa,SAAS,MAAM;AAC9D;AASO,SAAS,6BACd,YACA,UAAyC,CAAC,GAClB;AACxB,QAAM,QAAQ,mBAAmB,UAAU;AAC3C,QAAM,YAAY,QAAQ,oBAAoB;AAE9C,QAAM,SAAS,gBAAqC,UAAU,UAAU;AACxE,kBAAoC,SAAS,UAAU;AACvD,QAAM,MAAM,YAAY,UAAU;AAMlC,QAAM,aAAa,IAAI,OAAO,MAAM;AAAA,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mB,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
@@ -3,17 +3,18 @@ import {
3
3
  generateKeystore,
4
4
  importKeystore,
5
5
  openKeystore
6
- } from "../chunk-DD7TJKP6.js";
6
+ } from "../chunk-4I3JQ7KA.js";
7
7
  import {
8
8
  DEVNET,
9
9
  deriveFullIdentity,
10
10
  evmDerivationPath,
11
- generateRandomIdentity
12
- } from "../chunk-J6JVCKNV.js";
11
+ generateRandomIdentity,
12
+ isHiddenServiceUrl
13
+ } from "../chunk-7MPONJW5.js";
13
14
 
14
15
  // src/cli/main.ts
15
16
  import { homedir as homedir3 } from "os";
16
- import { readFileSync as readFileSync2 } from "fs";
17
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
17
18
  import { fileURLToPath, pathToFileURL } from "url";
18
19
 
19
20
  // src/cli/args.ts
@@ -74,6 +75,11 @@ var GLOBAL_OPTIONS = {
74
75
  arg: "auto|http|btp",
75
76
  help: "Which carriage to pay over. Default auto."
76
77
  },
78
+ socks: {
79
+ type: "string",
80
+ arg: "URL",
81
+ help: "SOCKS5h proxy for a .anyone connector, e.g. socks5h://127.0.0.1:9050. Env TOON_SOCKS. Default: start a managed anon daemon."
82
+ },
77
83
  json: { type: "boolean", help: "Print one JSON document on stdout and nothing else." },
78
84
  quiet: { type: "boolean", help: "Suppress progress and warnings on stderr." },
79
85
  help: { type: "boolean", short: "h", help: "Show this help." },
@@ -339,7 +345,8 @@ function usage(command) {
339
345
  columns(Object.entries(GLOBAL_OPTIONS).map(([n, s]) => optionLine(n, s))),
340
346
  "",
341
347
  "Environment: TOON_CONNECTOR, TOON_MNEMONIC, TOON_KEYSTORE,",
342
- " TOON_KEYSTORE_PASSWORD, TOON_CHAIN, TOON_RPC_URL, TOON_CHANNEL_STORE.",
348
+ " TOON_KEYSTORE_PASSWORD, TOON_CHAIN, TOON_RPC_URL, TOON_CHANNEL_STORE,",
349
+ " TOON_SOCKS.",
343
350
  "",
344
351
  "Run 'toon help <command>' for one command in detail."
345
352
  ].join("\n");
@@ -420,6 +427,7 @@ var CONNECTOR_ENV = "TOON_CONNECTOR";
420
427
  var CHAIN_ENV = "TOON_CHAIN";
421
428
  var RPC_ENV = "TOON_RPC_URL";
422
429
  var CHANNEL_STORE_ENV = "TOON_CHANNEL_STORE";
430
+ var SOCKS_ENV = "TOON_SOCKS";
423
431
  function defaultChannelStorePath(home = homedir2()) {
424
432
  return join2(home, ".toon", "channels.json");
425
433
  }
@@ -458,6 +466,9 @@ function resolveSettings(values, env, options = {}) {
458
466
  const rpcUrl = stringOption(values, "rpc") ?? env[RPC_ENV];
459
467
  const channelStore = stringOption(values, "store") ?? (env[CHANNEL_STORE_ENV] !== void 0 && env[CHANNEL_STORE_ENV].length > 0 ? env[CHANNEL_STORE_ENV] : defaultChannelStorePath(home));
460
468
  const transport = parseTransport(stringOption(values, "transport"), "--transport");
469
+ const socksFlag = stringOption(values, "socks");
470
+ const socksEnv = env[SOCKS_ENV];
471
+ const socksProxy = socksFlag !== void 0 && socksFlag.length > 0 ? socksFlag : socksEnv !== void 0 && socksEnv.length > 0 ? socksEnv : void 0;
461
472
  const settings = {
462
473
  connector,
463
474
  connectorSource,
@@ -465,6 +476,7 @@ function resolveSettings(values, env, options = {}) {
465
476
  ...rpcUrl !== void 0 && rpcUrl.length > 0 ? { rpcUrl } : {},
466
477
  channelStore,
467
478
  transport,
479
+ ...socksProxy !== void 0 ? { socksProxy } : {},
468
480
  keystorePath: resolveKeystorePath({
469
481
  flag: stringOption(values, "keystore"),
470
482
  env,
@@ -513,6 +525,7 @@ function buildClientConfig(settings, keys) {
513
525
  connector: settings.connector,
514
526
  channelStore: settings.channelStore,
515
527
  transport: settings.transport,
528
+ ...settings.socksProxy !== void 0 ? { socksProxy: settings.socksProxy } : {},
516
529
  // See this module's docs: a command never opens a channel as a side effect.
517
530
  autoOpenChannel: false,
518
531
  ...settings.chain !== void 0 ? { chain: settings.chain } : {},
@@ -529,7 +542,7 @@ function buildClientConfig(settings, keys) {
529
542
  };
530
543
  }
531
544
  async function defaultCreateClient(config) {
532
- const module = await import("../client-ACUZCR5A.js");
545
+ const module = await import("../client-TEP26FMO.js");
533
546
  const factory = module.ToonClient;
534
547
  if (factory === void 0) {
535
548
  throw new Error(
@@ -554,19 +567,48 @@ var Context = class {
554
567
  this.out = init.out;
555
568
  this.deps = init.deps;
556
569
  }
570
+ managedAnon;
557
571
  get openClient() {
558
572
  return this.instance;
559
573
  }
560
574
  async client(options = {}) {
561
575
  if (this.instance !== void 0) return this.instance;
562
- const settings = options.connector === void 0 ? this.settings : { ...this.settings, connector: options.connector, connectorSource: "flag" };
576
+ const base = options.connector === void 0 ? this.settings : { ...this.settings, connector: options.connector, connectorSource: "flag" };
577
+ const settings = await this.withProxy(base);
563
578
  const keys = await resolveKeyMaterial(settings, this.deps, options);
564
579
  const config = buildClientConfig(settings, keys);
565
580
  const create = this.deps.createClient ?? defaultCreateClient;
566
581
  this.instance = await create(config);
567
582
  return this.instance;
568
583
  }
584
+ /**
585
+ * Ensure a hidden-service connector has a proxy to be reached through.
586
+ *
587
+ * The library refuses to start a daemon (ADR 0001); the CLI starts one, and
588
+ * says so. A silent twenty-second pause while a binary downloads and circuits
589
+ * build is indistinguishable from a hang, so every step is announced on
590
+ * stderr — where it cannot corrupt `--json` output.
591
+ */
592
+ async withProxy(settings) {
593
+ if (settings.socksProxy !== void 0) return settings;
594
+ if (!isHiddenServiceUrl(settings.connector)) return settings;
595
+ const log = (message) => this.out.warn(`toon: ${message}`);
596
+ log(`${settings.connector} is a hidden service; starting a local anon daemon`);
597
+ const start = this.deps.startAnon ?? defaultStartAnon;
598
+ this.managedAnon = await start(log);
599
+ log(`proxying through ${this.managedAnon.socksProxy}`);
600
+ return { ...settings, socksProxy: this.managedAnon.socksProxy };
601
+ }
602
+ /** Stop the daemon this context started, if it started one. */
603
+ stopManagedAnon() {
604
+ this.managedAnon?.stop();
605
+ this.managedAnon = void 0;
606
+ }
569
607
  };
608
+ async function defaultStartAnon(log) {
609
+ const { startManagedAnon } = await import("../anon-daemon-ZFBL6EYA.js");
610
+ return startManagedAnon({ log });
611
+ }
570
612
 
571
613
  // src/cli/output.ts
572
614
  import { formatUnits } from "viem";
@@ -1645,23 +1687,33 @@ async function runCli(argv, options = {}) {
1645
1687
  out.warn(`toon: closing the client failed: ${error instanceof Error ? error.message : String(error)}`);
1646
1688
  }
1647
1689
  }
1690
+ context?.stopManagedAnon();
1648
1691
  }
1649
1692
  }
1650
- function isEntryPoint() {
1651
- const entry = process.argv[1];
1693
+ function isEntryPoint(moduleUrl, entry) {
1652
1694
  if (entry === void 0) return false;
1653
1695
  try {
1654
- return fileURLToPath(import.meta.url) === fileURLToPath(pathToFileURL(entry).href);
1696
+ const self = fileURLToPath(moduleUrl);
1697
+ const invoked = fileURLToPath(pathToFileURL(entry).href);
1698
+ return self === invoked || throughLinks(self) === throughLinks(invoked);
1655
1699
  } catch {
1656
1700
  return false;
1657
1701
  }
1658
1702
  }
1659
- if (isEntryPoint()) {
1703
+ function throughLinks(path) {
1704
+ try {
1705
+ return realpathSync(path);
1706
+ } catch {
1707
+ return path;
1708
+ }
1709
+ }
1710
+ if (isEntryPoint(import.meta.url, process.argv[1])) {
1660
1711
  process.exitCode = await runCli(process.argv.slice(2));
1661
1712
  }
1662
1713
  export {
1663
1714
  EXIT,
1664
1715
  exitCodeFor,
1716
+ isEntryPoint,
1665
1717
  packageVersion,
1666
1718
  reportError,
1667
1719
  runCli