shinjuku-shield 0.3.221 → 0.3.223

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,12 +5,12 @@ web services and AI answers from your private balance, so the payment does
5
5
  not show who paid. It works inside your AI app (Claude, Cursor, Codex) and in
6
6
  a terminal. Only you hold the keys: they never leave your computer.
7
7
 
8
- This is version 0.3.221. The command is `shinjuku`.
8
+ This is version 0.3.223. The command is `shinjuku`.
9
9
 
10
10
  ## Set up
11
11
 
12
12
  ```sh
13
- npx -y shinjuku@0.3.221 setup
13
+ npx -y shinjuku@0.3.223 setup
14
14
  ```
15
15
 
16
16
  Setup does every step for you:
@@ -100,7 +100,7 @@ Add it yourself. The name of the wallet in your app is `shinjuku`.
100
100
  Claude Code:
101
101
 
102
102
  ```sh
103
- claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.221 mcp
103
+ claude mcp add --scope user shinjuku -- npx -y --no-audit --no-fund shinjuku-shield@0.3.223 mcp
104
104
  ```
105
105
 
106
106
  ## For builders: check what you install
@@ -116,7 +116,7 @@ with the Releases table in
116
116
  Versions are published from GitHub Actions with npm provenance.
117
117
 
118
118
  `shinjuku-shield` is the package that holds the wallet. `shinjuku-shielded`
119
- 0.3.221, its older name, runs this package at the same version, so wallets
119
+ 0.3.223, its older name, runs this package at the same version, so wallets
120
120
  installed under that name keep updating. New installs use `shinjuku`.
121
121
 
122
122
  The full guide is
package/manifest.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schema": "carbon-shielded-wallet/bundle-manifest/v1",
3
3
  "file": "shinjuku-wallet.mjs",
4
- "sha256": "52c863352dfca86ebd1266a905c55445c48cadc8b53b77d349725fd5062a2a62",
5
- "bytes": 10298934,
6
- "sourceCommit": "7411e830aea9ee9b7143b5c895a054606cfecaf8",
4
+ "sha256": "91d53b343519d56d1c1dc52e5418d8647f07822009ba8e42db9e3f1007660353",
5
+ "bytes": 10306995,
6
+ "sourceCommit": "69056ae8c7924fa78e539f36092963f2c2a7a606",
7
7
  "sourceDirty": false,
8
8
  "installRecordMatchesLockfile": true,
9
9
  "releaseRule": "valid only when two fresh npm ci --ignore-scripts builds on different OSes give the same sha256; installRecordMatchesLockfile true means every entry npm installed equals its package-lock.json entry and every entry not marked optional, devOptional included, is installed: an optional entry (a package for another platform) may be absent",
@@ -1075,8 +1075,8 @@
1075
1075
  ],
1076
1076
  "seller": {
1077
1077
  "file": "shinjuku-seller.mjs",
1078
- "sha256": "3fbd12397c06f6b157b183fafd86d9f0d72e708c0c97887833ead480da1aabe6",
1079
- "bytes": 4182433,
1078
+ "sha256": "f23a0db92725b1a8f4cbbd65089f08c32b82cf7e31fec14ef0ec08685aaf41e1",
1079
+ "bytes": 4187011,
1080
1080
  "entry": "wallet/src/seller/exact/index.mjs",
1081
1081
  "external": [
1082
1082
  "@x402/core/http",
@@ -1968,5 +1968,5 @@
1968
1968
  }
1969
1969
  ]
1970
1970
  },
1971
- "publishedAt": "2026-11-12T16:14:06.249Z"
1971
+ "publishedAt": "2026-11-12T17:36:48.817Z"
1972
1972
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "shinjuku-shield",
3
- "version": "0.3.221",
3
+ "version": "0.3.223",
4
4
  "mcpName": "io.github.ShinjukuStaition/shinjuku-shield",
5
5
  "description": "Shinjuku Shield, private x402 payments on Solana: the self-custody wallet CLI and its MCP server. Shield, pay, and unshield USDC from any MCP agent, under caps you set.",
6
- "shinjukuRelease": "52c86335",
7
- "shinjukuSha256": "52c863352dfca86ebd1266a905c55445c48cadc8b53b77d349725fd5062a2a62",
6
+ "shinjukuRelease": "91d53b34",
7
+ "shinjukuSha256": "91d53b343519d56d1c1dc52e5418d8647f07822009ba8e42db9e3f1007660353",
8
8
  "license": "SEE LICENSE IN LICENSE.txt",
9
9
  "author": "Shinjuku Shield",
10
10
  "homepage": "https://github.com/ShinjukuStaition/shinjuku-shield#readme",
@@ -34889,9 +34889,11 @@ function tunnelClient(Dispatcher, proxyPort, proxyHost) {
34889
34889
  async connect(params) {
34890
34890
  const target = String(params?.path ?? "");
34891
34891
  if (optimisticTarget(target)) return optimisticConnect(params, { proxyHost, proxyPort, closedInRow });
34892
+ const startedAt = Date.now();
34892
34893
  try {
34893
34894
  const answer = await direct.connect(params);
34894
34895
  closedInRow.delete(target);
34896
+ if (answer?.socket && typeof answer.socket === "object") tunnelConnectMs.set(answer.socket, Date.now() - startedAt);
34895
34897
  return answer;
34896
34898
  } catch (error) {
34897
34899
  if (error?.code !== "UND_ERR_SOCKET") throw error;
@@ -35142,13 +35144,15 @@ ${Object.entries(params.headers ?? {}).filter(([name, value2]) => value2 !== voi
35142
35144
  throw error;
35143
35145
  });
35144
35146
  }
35145
- var circuitProbe, RUN_MARK, TUNNEL_CLOSED_TRIES, REPLAY_LIMIT;
35147
+ var circuitProbe, RUN_MARK, tunnelConnectMs, tunnelConnectMsOf, TUNNEL_CLOSED_TRIES, REPLAY_LIMIT;
35146
35148
  var init_tunnelGuard = __esm({
35147
35149
  "wallet/src/net/tunnelGuard.mjs"() {
35148
35150
  "use strict";
35149
35151
  init_keepAlive();
35150
35152
  init_phaseTiming();
35151
35153
  RUN_MARK = "SHINJUKU_WALLET_PROXIED";
35154
+ tunnelConnectMs = /* @__PURE__ */ new WeakMap();
35155
+ tunnelConnectMsOf = (socket) => socket && typeof socket === "object" ? tunnelConnectMs.get(socket) : void 0;
35152
35156
  TUNNEL_CLOSED_TRIES = 3;
35153
35157
  REPLAY_LIMIT = 8 * 1024;
35154
35158
  }
@@ -35247,7 +35251,7 @@ function untilAborted(promise, signal) {
35247
35251
  promise.then(resolve18, reject).finally(() => signal.removeEventListener("abort", onAbort));
35248
35252
  });
35249
35253
  }
35250
- var SITE_ONIONS, SITE_SPARE_ONIONS, PINNED_FACILITATOR_ONIONS, PINNED_SPARE_ONIONS, HISTORY_ONIONS, HISTORY_SPARE_ONIONS, PINNED_HISTORY_ONIONS, PINNED_HISTORY_SPARE_ONIONS, KEPT_ANSWER_BYTES, streamScope, requestStreams, socketRequests, guarded, STREAM_CHANNELS, SPARE_CAUSE, routedOrigins, routedGroupOf, answeredOn, onionDispatchers, ownTag, ownTagDispatchers, onOwnTagNow, ownTagInit;
35254
+ var SITE_ONIONS, SITE_SPARE_ONIONS, PINNED_FACILITATOR_ONIONS, PINNED_SPARE_ONIONS, HISTORY_ONIONS, HISTORY_SPARE_ONIONS, PINNED_HISTORY_ONIONS, PINNED_HISTORY_SPARE_ONIONS, KEPT_ANSWER_BYTES, streamScope, requestStreams, socketRequests, guarded, STREAM_CHANNELS, SPARE_CAUSE, routedOrigins, routedGroupOf, answeredOn, tagRoutes, isKey, noteRoute, TAG_LETTERS, onionDispatchers, ownTag, ownTagDispatchers, onOwnTagNow, ownTagInit;
35251
35255
  var init_facilitatorOnion = __esm({
35252
35256
  "wallet/src/net/facilitatorOnion.mjs"() {
35253
35257
  "use strict";
@@ -35306,12 +35310,27 @@ var init_facilitatorOnion = __esm({
35306
35310
  if (!stream || stream.request !== request || stream.sentAt !== void 0) return;
35307
35311
  stream.sentAt = Date.now();
35308
35312
  stream.kind = !known ? "unknown" : sent === 1 ? "new" : "reused";
35313
+ if (stream.kind === "new") stream.connectMs = tunnelConnectMsOf(socket);
35314
+ if (known && Number.isInteger(socket.localPort)) stream.localPort = socket.localPort;
35315
+ if (stream.route) noteRoute(stream.route.dispatcher, stream.route.onion);
35309
35316
  })
35310
35317
  });
35311
35318
  SPARE_CAUSE = Object.freeze({ silent: "no pinned onion answered", failed: "every pinned probe failed", wait: "a request's route wait ended" });
35312
35319
  routedOrigins = /* @__PURE__ */ new Map();
35313
35320
  routedGroupOf = /* @__PURE__ */ new Map();
35314
35321
  answeredOn = /* @__PURE__ */ new WeakMap();
35322
+ tagRoutes = /* @__PURE__ */ new WeakMap();
35323
+ isKey = (value2) => value2 !== null && (typeof value2 === "object" || typeof value2 === "function");
35324
+ noteRoute = (dispatcher, onion) => {
35325
+ try {
35326
+ if (!isKey(dispatcher) || typeof onion !== "string") return;
35327
+ let onions = tagRoutes.get(dispatcher);
35328
+ if (!onions) tagRoutes.set(dispatcher, onions = /* @__PURE__ */ new Set());
35329
+ onions.add(onion);
35330
+ } catch {
35331
+ }
35332
+ };
35333
+ TAG_LETTERS = Object.freeze({ run: "r", own: "o", given: "g", none: "n" });
35315
35334
  onionDispatchers = /* @__PURE__ */ new Map();
35316
35335
  ownTag = new AsyncLocalStorage2();
35317
35336
  ownTagDispatchers = /* @__PURE__ */ new Set();
@@ -79437,7 +79456,7 @@ init_timing();
79437
79456
  import { spawn as spawn3, spawnSync as spawnSync3 } from "node:child_process";
79438
79457
  import { createHash as createHash27, createHmac as createHmac12, randomBytes as randomBytes17, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
79439
79458
  import net3 from "node:net";
79440
- import { basename as basename6, dirname as dirname20, join as join24 } from "node:path";
79459
+ import { basename as basename6, dirname as dirname20, join as join24, sep as sep3 } from "node:path";
79441
79460
  import { Readable } from "node:stream";
79442
79461
  import { pipeline } from "node:stream/promises";
79443
79462
  var ownTorPlatform = (platform = process.platform, arch = process.arch) => platform === "win32" || platform === "darwin" || platform === "linux" && arch === "x64";
@@ -79827,7 +79846,7 @@ AUTHCHALLENGE SAFECOOKIE ${clientNonce.toString("hex")}\r
79827
79846
  }
79828
79847
  if (step === 2 && typeof events === "function") {
79829
79848
  step = 6;
79830
- socket.write("SETEVENTS HS_DESC CIRC\r\n");
79849
+ socket.write("SETEVENTS HS_DESC CIRC STREAM\r\n");
79831
79850
  continue;
79832
79851
  }
79833
79852
  if (step === 6) {
@@ -80355,16 +80374,77 @@ async function ownTorReady(home, state2, { wait = true, deadline } = {}) {
80355
80374
  }
80356
80375
  return tunnelOf(state2.port);
80357
80376
  }
80358
- function ownPortOf(home) {
80359
- const state2 = managedTorState(home);
80360
- if (state2) return state2.port;
80361
- if (!bundleComplete(home) && !existsSync(join24(managedTorDir(home), "torrc"))) return void 0;
80377
+ var NOTICE_READ_MAX = 2 * 1024 * 1024;
80378
+ var TUNNEL_LISTENER_LINE = /^[A-Z][a-z]{2} [ 0-9]?[0-9] [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3} \[notice\] Opened HTTP tunnel listener (?:connection \(ready\) )?on 127\.0\.0\.1:([0-9]{1,5})\r?$/gm;
80379
+ function readHomeFileTail(home, path, max) {
80362
80380
  try {
80363
- return Number(new URL(readSetupConfig(home)?.torTunnel ?? "").port) || void 0;
80381
+ const kind = lstatSync(path);
80382
+ if (!kind.isFile()) return void 0;
80383
+ if (!realpathSync(path).startsWith(`${realpathSync(home)}${sep3}`)) return void 0;
80384
+ const length = Math.min(kind.size, max);
80385
+ const bytes2 = Buffer.alloc(length);
80386
+ const fd = openSync(path, "r");
80387
+ try {
80388
+ readSync(fd, bytes2, 0, length, kind.size - length);
80389
+ } finally {
80390
+ closeSync(fd);
80391
+ }
80392
+ return bytes2.toString("utf8");
80364
80393
  } catch {
80365
80394
  return void 0;
80366
80395
  }
80367
80396
  }
80397
+ function loggedTunnelPorts(home) {
80398
+ const ports = /* @__PURE__ */ new Set();
80399
+ const text2 = readHomeFileTail(home, logFile(home), NOTICE_READ_MAX);
80400
+ if (text2 === void 0) return ports;
80401
+ for (const match of text2.matchAll(TUNNEL_LISTENER_LINE)) {
80402
+ const port = Number(match[1]);
80403
+ if (port > 0 && port < 65536) ports.add(port);
80404
+ }
80405
+ return ports;
80406
+ }
80407
+ var ownPortsFile = (home) => join24(managedTorDir(home), "own-ports.json");
80408
+ var OWN_PORTS_MAX = 256;
80409
+ var OWN_PORTS_READ_MAX = 16 * 1024;
80410
+ function recordedOwnPorts(home) {
80411
+ const text2 = readHomeFileTail(home, ownPortsFile(home), OWN_PORTS_READ_MAX + 1);
80412
+ if (text2 === void 0 || text2.length > OWN_PORTS_READ_MAX) return void 0;
80413
+ let parsed;
80414
+ try {
80415
+ parsed = JSON.parse(text2);
80416
+ } catch {
80417
+ return void 0;
80418
+ }
80419
+ if (!Array.isArray(parsed?.ports) || !parsed.ports.every((port) => Number.isInteger(port) && port > 0 && port < 65536)) return void 0;
80420
+ return parsed.ports;
80421
+ }
80422
+ function recordOwnPort(home, port) {
80423
+ try {
80424
+ const path = ownPortsFile(home);
80425
+ const known = recordedOwnPorts(home);
80426
+ if (known === void 0 && existsSync(path) && !lstatSync(path).isFile()) return;
80427
+ if (known?.includes(port)) return;
80428
+ writeAtomic(path, `${JSON.stringify({ ports: [...known ?? [], port].slice(-OWN_PORTS_MAX) })}
80429
+ `);
80430
+ } catch {
80431
+ }
80432
+ }
80433
+ function ownTunnelPort(home, tunnel) {
80434
+ let url;
80435
+ try {
80436
+ url = new URL(tunnel);
80437
+ } catch {
80438
+ return void 0;
80439
+ }
80440
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1") return void 0;
80441
+ const port = Number(url.port);
80442
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) return void 0;
80443
+ const state2 = managedTorState(home);
80444
+ if (state2) return state2.port === port ? port : void 0;
80445
+ if (recordedOwnPorts(home)?.includes(port)) return port;
80446
+ return loggedTunnelPorts(home).has(port) ? port : void 0;
80447
+ }
80368
80448
  async function ensureWalletTor(proxy, { env = process.env, platform = process.platform, explicit = false, say = () => {
80369
80449
  } } = {}) {
80370
80450
  if (!ownTorPlatform(platform)) return proxy;
@@ -80375,14 +80455,15 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
80375
80455
  return proxy;
80376
80456
  }
80377
80457
  const home = setupHome(env);
80378
- const ownPort = ownPortOf(home);
80379
- if (explicit && Number(url.port) !== ownPort) return proxy;
80458
+ const ownPort = explicit ? ownTunnelPort(home, proxy) : void 0;
80459
+ if (explicit && ownPort === void 0) return proxy;
80380
80460
  let deadline = Date.now() + BOOTSTRAP_MAX_MS;
80381
80461
  const timeLeft = () => deadline - Date.now();
80382
80462
  try {
80383
80463
  const known = managedTorState(home);
80384
80464
  const ready = await ownTorReady(home, known, { wait: false });
80385
80465
  if (ready && await processLockFree(lockName(home)) && pidAlive3(known.pid)) {
80466
+ recordOwnPort(home, known.port);
80386
80467
  await recordTunnel(home, ready, deadline);
80387
80468
  return ready;
80388
80469
  }
@@ -80397,6 +80478,7 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
80397
80478
  if (!(error?.stalled === true && timeLeft() >= RESTART_MIN_MS)) throw error;
80398
80479
  }
80399
80480
  if (again) {
80481
+ recordOwnPort(home, state2.port);
80400
80482
  await recordTunnel(home, again, deadline);
80401
80483
  return again;
80402
80484
  }
@@ -80427,6 +80509,7 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
80427
80509
  if (timeLeft() < RESTART_MIN_MS) throw noTimeLeft();
80428
80510
  try {
80429
80511
  await startTor(home, port, say, assertHeld, deadline);
80512
+ recordOwnPort(home, port);
80430
80513
  await recordTunnel(home, tunnelOf(port), deadline);
80431
80514
  return tunnelOf(port);
80432
80515
  } catch (error) {
@@ -80452,15 +80535,13 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
80452
80535
  setTunnelCircuitProbe(async ({ proxyHost, proxyPort } = {}) => {
80453
80536
  if (String(proxyHost) !== "127.0.0.1") return void 0;
80454
80537
  const home = setupHome(process.env);
80455
- const port = ownPortOf(home);
80456
- if (!Number.isInteger(port) || Number(proxyPort) !== port) return void 0;
80457
80538
  const state2 = managedTorState(home);
80458
- if (!state2 || state2.port !== port) return void 0;
80539
+ if (!state2 || Number(proxyPort) !== state2.port) return void 0;
80459
80540
  const answer = await controlCheck(home, state2, { circuits: true, unref: true });
80460
80541
  return answer && answer.tunnelPort === Number(proxyPort) ? answer.circuits : void 0;
80461
80542
  });
80462
80543
  var EVENT_LINE_MAX = 4096;
80463
- var TOR_TIMING_MAX = 200;
80544
+ var TOR_TIMING_MAX = 800;
80464
80545
  var HS_DESC_ACTIONS = /* @__PURE__ */ new Set(["REQUESTED", "RECEIVED", "FAILED"]);
80465
80546
  var HS_DESC_REASONS = /* @__PURE__ */ new Set([
80466
80547
  "BAD_DESC",
@@ -80500,6 +80581,7 @@ var CIRC_REASONS = /* @__PURE__ */ new Set([
80500
80581
  "MEASUREMENT_EXPIRED",
80501
80582
  "IP_NOW_REDUNDANT"
80502
80583
  ]);
80584
+ var STREAM_STATUSES = /* @__PURE__ */ new Set(["NEW", "SENTCONNECT", "SUCCEEDED", "FAILED", "CLOSED", "DETACHED"]);
80503
80585
  function ownOnionPrefixes() {
80504
80586
  const all = [
80505
80587
  ...FACILITATOR_SITE_ONIONS,
@@ -80523,6 +80605,13 @@ function torTimingMark(line, ours) {
80523
80605
  if (!prefix2 || !HS_DESC_ACTIONS.has(desc[1]) || reason2 !== void 0 && !HS_DESC_REASONS.has(reason2)) return void 0;
80524
80606
  return { phase: `hs-desc-${desc[1].toLowerCase()}`, outcome: `onion_${prefix2}${reason2 ? `_${reason2.toLowerCase()}` : ""}` };
80525
80607
  }
80608
+ const stream = /^650 STREAM (\d{1,20}) ([A-Z_]+) (\d{1,10}) ([a-z2-7]{56})\.onion:\d{1,5}(?: |$)/.exec(line);
80609
+ if (stream) {
80610
+ const prefix2 = ours.get(stream[4]);
80611
+ if (!prefix2 || !STREAM_STATUSES.has(stream[2])) return void 0;
80612
+ const port = stream[2] === "NEW" ? /(?:^| )SOURCE_ADDR=127\.0\.0\.1:(\d{1,5})(?: |$)/.exec(line)?.[1] : void 0;
80613
+ return { phase: `stream-${stream[2].toLowerCase()}`, outcome: `onion_${prefix2}_s${stream[1]}_c${stream[3]}${port ? `_lp${port}` : ""}` };
80614
+ }
80526
80615
  const circ = /^650 CIRC (\d{1,10}) ([A-Z_]+) /.exec(`${line} `);
80527
80616
  if (!circ || !CIRC_STATUSES.has(circ[2])) return void 0;
80528
80617
  const rend = /(?:^| )REND_QUERY=([a-z2-7]{56})(?: |$)/.exec(line)?.[1];
@@ -80535,7 +80624,7 @@ function torTimingMark(line, ours) {
80535
80624
  }
80536
80625
  function startTorTimingMarks() {
80537
80626
  const run2 = String(process.env.SHINJUKU_WALLET_PROXIED ?? "");
80538
- if (!run2.startsWith("tor ") || !process.argv.includes("--verbose")) return;
80627
+ if (!run2.startsWith("tor ") || !(process.argv.includes("--verbose") || process.argv[2] === "mcp")) return;
80539
80628
  setImmediate(async () => {
80540
80629
  try {
80541
80630
  const home = setupHome(process.env);
@@ -80551,17 +80640,34 @@ function startTorTimingMarks() {
80551
80640
  const ours = ownOnionPrefixes();
80552
80641
  const mark = createTimingLog(join24(home, pool2, "wallet.json.timing.log"), { component: "tor" }).start({ startedAt: Date.now() - performance.now() });
80553
80642
  let marks = 0;
80643
+ let session;
80644
+ let spent = false;
80645
+ const closeSession = () => {
80646
+ try {
80647
+ session?.close();
80648
+ } catch {
80649
+ }
80650
+ };
80554
80651
  const once2 = (phase, outcome) => {
80555
80652
  if (marks >= TOR_TIMING_MAX) return;
80556
80653
  marks += 1;
80557
80654
  mark(phase, outcome);
80655
+ if (marks >= TOR_TIMING_MAX) {
80656
+ spent = true;
80657
+ closeSession();
80658
+ }
80558
80659
  };
80559
- const session = await controlCheck(home, state2, { unref: true, events: (line) => {
80660
+ session = await controlCheck(home, state2, { unref: true, events: (line) => {
80661
+ if (spent) return;
80560
80662
  const one = torTimingMark(line, ours);
80561
80663
  if (one) once2(one.phase, one.outcome);
80562
80664
  } });
80563
80665
  if (!session) return;
80564
- process.once("exit", () => session.close());
80666
+ if (spent) {
80667
+ closeSession();
80668
+ return;
80669
+ }
80670
+ process.once("exit", closeSession);
80565
80671
  once2("events-on");
80566
80672
  } catch {
80567
80673
  }
@@ -80648,11 +80754,12 @@ function proxyDispatcherClass() {
80648
80754
  async function sellerTor(recorded, home) {
80649
80755
  let tunnel = recorded;
80650
80756
  if (home) {
80651
- const current = readSetupConfig(home)?.torTunnel ?? recorded;
80757
+ const walletRecorded = readSetupConfig(home)?.torTunnel;
80758
+ const current = walletRecorded ?? recorded;
80652
80759
  try {
80653
80760
  tunnel = await ensureWalletTor(current, {
80654
80761
  env: { ...process.env, SHIELDED_WALLET_HOME: home },
80655
- explicit: true,
80762
+ explicit: walletRecorded !== void 0,
80656
80763
  say: (line) => process.stderr.write(`${line}
80657
80764
  `)
80658
80765
  });
@@ -43797,9 +43797,11 @@ function tunnelClient(Dispatcher, proxyPort, proxyHost) {
43797
43797
  async connect(params) {
43798
43798
  const target = String(params?.path ?? "");
43799
43799
  if (optimisticTarget(target)) return optimisticConnect(params, { proxyHost, proxyPort, closedInRow });
43800
+ const startedAt = Date.now();
43800
43801
  try {
43801
43802
  const answer = await direct.connect(params);
43802
43803
  closedInRow.delete(target);
43804
+ if (answer?.socket && typeof answer.socket === "object") tunnelConnectMs.set(answer.socket, Date.now() - startedAt);
43803
43805
  return answer;
43804
43806
  } catch (error) {
43805
43807
  if (error?.code !== "UND_ERR_SOCKET") throw error;
@@ -44050,13 +44052,15 @@ ${Object.entries(params.headers ?? {}).filter(([name, value2]) => value2 !== voi
44050
44052
  throw error;
44051
44053
  });
44052
44054
  }
44053
- var circuitProbe, RUN_MARK, TUNNEL_CLOSED_TRIES, REPLAY_LIMIT;
44055
+ var circuitProbe, RUN_MARK, tunnelConnectMs, tunnelConnectMsOf, TUNNEL_CLOSED_TRIES, REPLAY_LIMIT;
44054
44056
  var init_tunnelGuard = __esm({
44055
44057
  "wallet/src/net/tunnelGuard.mjs"() {
44056
44058
  "use strict";
44057
44059
  init_keepAlive();
44058
44060
  init_phaseTiming();
44059
44061
  RUN_MARK = "SHINJUKU_WALLET_PROXIED";
44062
+ tunnelConnectMs = /* @__PURE__ */ new WeakMap();
44063
+ tunnelConnectMsOf = (socket) => socket && typeof socket === "object" ? tunnelConnectMs.get(socket) : void 0;
44060
44064
  TUNNEL_CLOSED_TRIES = 3;
44061
44065
  REPLAY_LIMIT = 8 * 1024;
44062
44066
  }
@@ -44156,6 +44160,19 @@ function unsubscribeStreamChannels() {
44156
44160
  }
44157
44161
  }
44158
44162
  }
44163
+ function tagOf(init, routedInit) {
44164
+ try {
44165
+ let base = init?.dispatcher;
44166
+ if (base && typeof base.tagDispatcher === "function") base = base.tagDispatcher() ?? base;
44167
+ const dispatcher = base ?? routedInit?.dispatcher;
44168
+ if (!isKey(dispatcher)) return { dispatcher: void 0, tag: "none" };
44169
+ if (ownTagDispatchers.has(dispatcher)) return { dispatcher, tag: "own" };
44170
+ for (const kept3 of onionDispatchers.values()) if (kept3 === dispatcher) return { dispatcher, tag: "run" };
44171
+ return { dispatcher, tag: "given" };
44172
+ } catch {
44173
+ return { dispatcher: void 0, tag: "none" };
44174
+ }
44175
+ }
44159
44176
  function onionRouteCold(url, sentAtMs2 = Date.now()) {
44160
44177
  let origin;
44161
44178
  try {
@@ -44185,6 +44202,7 @@ function markFirstOnionRaces(timingLog) {
44185
44202
  firstRacesMarked = true;
44186
44203
  moveTimingLog = timingLog;
44187
44204
  for (const move of moveRecords.splice(0)) writeMove(move);
44205
+ for (const record of requestRecords.splice(0)) writeRequest(record);
44188
44206
  for (const record of firstRaceRecords) {
44189
44207
  record.then((race) => {
44190
44208
  const mark = timingLog.start({ startedAt: race.startedAt });
@@ -44562,6 +44580,7 @@ async function routeOverOnions(argv2, {
44562
44580
  });
44563
44581
  group.pending = raced.winner.then((onion) => {
44564
44582
  if (!unanswered2 && !raced.stopped) noteAnswered(group, raceDispatcher);
44583
+ if (!unanswered2 && !raced.stopped) noteRoute(raceDispatcher, onion);
44565
44584
  const answer = raced.answer();
44566
44585
  group.answer = answer && !raced.stopped ? { ...answer, path: SITE_PROBE_PATH, atMs: Date.now() } : void 0;
44567
44586
  if (first) Object.assign(first, { endedAt: Date.now(), answered: !unanswered2 });
@@ -44603,7 +44622,7 @@ async function routeOverOnions(argv2, {
44603
44622
  } } : {}
44604
44623
  }).startSpares;
44605
44624
  }
44606
- const moveOn = (group, onion, why, { request, ageMs }) => {
44625
+ const moveOn = (group, onion, why, { request, ageMs, tag: tag2 }) => {
44607
44626
  if (stopped || group.winner !== onion || group.pending) return;
44608
44627
  endHedge(group, onion);
44609
44628
  group.moves = (group.moves ?? 0) + 1;
@@ -44619,7 +44638,7 @@ async function routeOverOnions(argv2, {
44619
44638
  group.live = group.onions.length;
44620
44639
  group.winner = void 0;
44621
44640
  const role = roleOf(group, onion);
44622
- const move = { at: Date.now(), role, request, cause: why === "the stream failed" ? "stream_failed" : "timeout", ageMs };
44641
+ const move = { at: Date.now(), role, request, cause: why === "the stream failed" ? "stream_failed" : "timeout", ageMs, tag: tag2 };
44623
44642
  if (moveTimingLog) writeMove(move);
44624
44643
  else moveRecords.push(move);
44625
44644
  err(`tor: the onion ${hostOf(onion)} of ${group.label} gave no answer (${why}); its requests move to the first of ${others.map(hostOf).join(", ")} to answer (move ${group.moves} of ${max}; the request was ${request} to ${role}, sent ${(ageMs / 1e3).toFixed(1)} s before)
@@ -44664,6 +44683,8 @@ async function routeOverOnions(argv2, {
44664
44683
  hedgeAborts.add(hedge.abort);
44665
44684
  const role = roleOf(group, onion);
44666
44685
  const streamNow = streamWords(stream);
44686
+ const tagNow = tagWords(stream);
44687
+ const hedgeDispatcher = onionInit({}).dispatcher;
44667
44688
  err(`tor: the onion ${hostOf(onion)} of ${group.label} has not started its answer in ${HEDGE_MS / 1e3} s (the request was ${request} to ${role}, on ${streamText(stream)}); the other onions race for the next requests, and that request keeps waiting
44668
44689
  `);
44669
44690
  raced.winner.then((won) => {
@@ -44673,6 +44694,7 @@ async function routeOverOnions(argv2, {
44673
44694
  hedge.waiters = [];
44674
44695
  if (hedge.ended || !answered2 || stopped || group.winner !== onion || group.pending) return;
44675
44696
  group.winner = won;
44697
+ noteRoute(hedgeDispatcher, won);
44676
44698
  (group.hedgedFrom ??= /* @__PURE__ */ new Set()).add(onion);
44677
44699
  const move = {
44678
44700
  at: Date.now(),
@@ -44681,7 +44703,8 @@ async function routeOverOnions(argv2, {
44681
44703
  request,
44682
44704
  cause: `to_${roleOf(group, won).replaceAll("-", "_")}`,
44683
44705
  ageMs: ageMs + (Date.now() - hedge.startedAt),
44684
- stream: streamNow
44706
+ stream: streamNow,
44707
+ tag: tagNow
44685
44708
  };
44686
44709
  if (moveTimingLog) writeMove(move);
44687
44710
  else moveRecords.push(move);
@@ -44737,12 +44760,18 @@ async function routeOverOnions(argv2, {
44737
44760
  return original(input instanceof Request ? new Request(target, input) : target, routedInit);
44738
44761
  };
44739
44762
  const sentAt = Date.now();
44740
- const stream = {};
44763
+ const tagged = tagOf(init, routedInit);
44764
+ const stream = streamRecord(tagged, onion);
44741
44765
  const sent = streamScope.run(stream, () => sendTo(onion));
44742
44766
  sent.then(() => noteAnswered(group, routedInit.dispatcher), () => {
44743
44767
  });
44744
- if (group.onions.length < 2) return sent;
44745
44768
  const request = requestLabel(group, method, url);
44769
+ const markSend = (promise, to, record, phase) => promise.then(
44770
+ () => noteRequest({ at: Date.now(), role: roleOf(group, to), request, stream: record, phase }),
44771
+ () => noteRequest({ at: Date.now(), role: roleOf(group, to), request, stream: record, phase, failed: true })
44772
+ );
44773
+ markSend(sent, onion, stream, "onion:request");
44774
+ if (group.onions.length < 2) return sent;
44746
44775
  const hedgeable = group.kind !== "history" && !init?.ownLane && onion === group.winner && !CHAIN_WAIT_LABELS.has(request);
44747
44776
  let headTimer;
44748
44777
  const clearHead = () => {
@@ -44762,7 +44791,7 @@ async function routeOverOnions(argv2, {
44762
44791
  }, (error) => {
44763
44792
  clearHead();
44764
44793
  const why = noAnswer(error, signal);
44765
- if (why && !init?.ownLane) moveOn(group, onion, why, { request, ageMs: Date.now() - sentAt });
44794
+ if (why && !init?.ownLane) moveOn(group, onion, why, { request, ageMs: Date.now() - sentAt, tag: tagWords(stream) });
44766
44795
  throw error;
44767
44796
  });
44768
44797
  if (!hedgeable) return tracked;
@@ -44789,7 +44818,10 @@ async function routeOverOnions(argv2, {
44789
44818
  onSwitch = (won) => {
44790
44819
  if (done || signal?.aborted || runEnded()) return;
44791
44820
  open5 += 1;
44792
- sendTo(won).then(win, lose);
44821
+ const resendStream = streamRecord(tagged, won);
44822
+ const resent = streamScope.run(resendStream, () => sendTo(won));
44823
+ markSend(resent, won, resendStream, "onion:resend");
44824
+ resent.then(win, lose);
44793
44825
  };
44794
44826
  });
44795
44827
  headTimer = setTimeout(() => {
@@ -44823,7 +44855,7 @@ async function routeOverOnions(argv2, {
44823
44855
  }
44824
44856
  };
44825
44857
  }
44826
- var SITE_ONIONS, SITE_SPARE_ONIONS, PINNED_FACILITATOR_ONIONS, PINNED_SPARE_ONIONS, HISTORY_ONIONS, HISTORY_SPARE_ONIONS, PINNED_HISTORY_ONIONS, PINNED_HISTORY_SPARE_ONIONS, HISTORY_PROBE_PATH, SITE_PROBE_PATH, SITE_PROBE_ANSWERS, KEPT_ANSWER_MS, KEPT_ANSWER_BYTES, KEPT_BODY_MS, FACILITATOR_FLAGS, V3_ONION, DISCOVERY_TIMEOUT_MS, WARM_TIMEOUT_MS, RACE_TIMEOUT_MS, ROUTE_WAIT_MS, SPARE_AFTER_MS, HISTORY_SPARE_AFTER_MS, HEDGE_MS, streamScope, requestStreams, socketRequests, guarded, STREAM_CHANNELS, streamSubscribers, streamWords, streamText, RESEND_LABELS, CHAIN_WAIT_LABELS, SPARE_CAUSE, routedGroups, liveOnions, hostOf, noAnswer, routedOnions, routedOrigins, onionsOfOrigin, routesOverOnion, routedGroupOf, answeredOn, noteAnswered, firstRaces, firstRaceRecords, firstRacesMarked, roleOf, ROUTE_LABELS, requestLabel, moveRecords, moveTimingLog, writeMove, firstOnionRace, onionDispatchers, ownTag, ownTagDispatchers, onOwnTagNow, ownTagInit;
44858
+ var SITE_ONIONS, SITE_SPARE_ONIONS, PINNED_FACILITATOR_ONIONS, PINNED_SPARE_ONIONS, HISTORY_ONIONS, HISTORY_SPARE_ONIONS, PINNED_HISTORY_ONIONS, PINNED_HISTORY_SPARE_ONIONS, HISTORY_PROBE_PATH, SITE_PROBE_PATH, SITE_PROBE_ANSWERS, KEPT_ANSWER_MS, KEPT_ANSWER_BYTES, KEPT_BODY_MS, FACILITATOR_FLAGS, V3_ONION, DISCOVERY_TIMEOUT_MS, WARM_TIMEOUT_MS, RACE_TIMEOUT_MS, ROUTE_WAIT_MS, SPARE_AFTER_MS, HISTORY_SPARE_AFTER_MS, HEDGE_MS, streamScope, requestStreams, socketRequests, guarded, STREAM_CHANNELS, streamSubscribers, streamWords, streamText, RESEND_LABELS, CHAIN_WAIT_LABELS, SPARE_CAUSE, routedGroups, liveOnions, hostOf, noAnswer, routedOnions, routedOrigins, onionsOfOrigin, routesOverOnion, routedGroupOf, answeredOn, tagRoutes, isKey, tagHasRoute, noteRoute, streamRecord, TAG_LETTERS, tagWords, OUTCOME_MAX, noteAnswered, firstRaces, firstRaceRecords, firstRacesMarked, roleOf, ROUTE_LABELS, requestLabel, moveRecords, moveTimingLog, writeMove, REQUEST_RECORDS_MAX, requestRecords, requestOutcome, writeRequest, REQUEST_MARK_FAST_MS, noteRequest, firstOnionRace, onionDispatchers, ownTag, ownTagDispatchers, onOwnTagNow, ownTagInit;
44827
44859
  var init_facilitatorOnion = __esm({
44828
44860
  "wallet/src/net/facilitatorOnion.mjs"() {
44829
44861
  "use strict";
@@ -44896,6 +44928,9 @@ var init_facilitatorOnion = __esm({
44896
44928
  if (!stream || stream.request !== request || stream.sentAt !== void 0) return;
44897
44929
  stream.sentAt = Date.now();
44898
44930
  stream.kind = !known ? "unknown" : sent === 1 ? "new" : "reused";
44931
+ if (stream.kind === "new") stream.connectMs = tunnelConnectMsOf(socket);
44932
+ if (known && Number.isInteger(socket.localPort)) stream.localPort = socket.localPort;
44933
+ if (stream.route) noteRoute(stream.route.dispatcher, stream.route.onion);
44899
44934
  })
44900
44935
  });
44901
44936
  streamSubscribers = 0;
@@ -44932,6 +44967,31 @@ var init_facilitatorOnion = __esm({
44932
44967
  routesOverOnion = (origin) => routedOrigins.has(origin);
44933
44968
  routedGroupOf = /* @__PURE__ */ new Map();
44934
44969
  answeredOn = /* @__PURE__ */ new WeakMap();
44970
+ tagRoutes = /* @__PURE__ */ new WeakMap();
44971
+ isKey = (value2) => value2 !== null && (typeof value2 === "object" || typeof value2 === "function");
44972
+ tagHasRoute = (dispatcher, onion) => {
44973
+ try {
44974
+ return isKey(dispatcher) && typeof onion === "string" ? tagRoutes.get(dispatcher)?.has(onion) === true : void 0;
44975
+ } catch {
44976
+ return void 0;
44977
+ }
44978
+ };
44979
+ noteRoute = (dispatcher, onion) => {
44980
+ try {
44981
+ if (!isKey(dispatcher) || typeof onion !== "string") return;
44982
+ let onions = tagRoutes.get(dispatcher);
44983
+ if (!onions) tagRoutes.set(dispatcher, onions = /* @__PURE__ */ new Set());
44984
+ onions.add(onion);
44985
+ } catch {
44986
+ }
44987
+ };
44988
+ streamRecord = (tagged, onion) => {
44989
+ const known = tagHasRoute(tagged.dispatcher, onion);
44990
+ return { startedAt: Date.now(), tag: tagged.tag, first: known === void 0 ? void 0 : !known, route: { dispatcher: tagged.dispatcher, onion } };
44991
+ };
44992
+ TAG_LETTERS = Object.freeze({ run: "r", own: "o", given: "g", none: "n" });
44993
+ tagWords = (stream) => `t${TAG_LETTERS[stream?.tag] ?? "x"}${stream?.first === true ? "f" : stream?.first === false ? "l" : "x"}`;
44994
+ OUTCOME_MAX = 96;
44935
44995
  noteAnswered = (group, dispatcher) => {
44936
44996
  if (!dispatcher) return;
44937
44997
  let seen = answeredOn.get(group);
@@ -44978,11 +45038,30 @@ var init_facilitatorOnion = __esm({
44978
45038
  moveRecords = [];
44979
45039
  writeMove = (move) => {
44980
45040
  try {
44981
- const outcome = `${move.role.replaceAll("-", "_")}_${move.request}_${move.cause}_age_${move.ageMs}${move.stream ? `_${move.stream}` : ""}`;
45041
+ let outcome = `${move.role.replaceAll("-", "_")}_${move.request}_${move.cause}_age_${move.ageMs}${move.stream ? `_${move.stream}` : ""}${move.tag ? `_${move.tag}` : ""}`;
45042
+ if (outcome.length > OUTCOME_MAX) outcome = outcome.slice(0, OUTCOME_MAX);
44982
45043
  moveTimingLog?.start({ startedAt: move.at - move.ageMs })(move.phase ?? "onion:move", outcome, move.at);
44983
45044
  } catch {
44984
45045
  }
44985
45046
  };
45047
+ REQUEST_RECORDS_MAX = 256;
45048
+ requestRecords = [];
45049
+ requestOutcome = ({ role, request, stream, failed }) => {
45050
+ const ms = (value2) => Number.isFinite(value2) && value2 >= 0 ? String(Math.round(value2)) : "na";
45051
+ return `${role.replaceAll("-", "_")}_${request}_${tagWords(stream)}_${streamWords(stream)}_connect_${ms(stream.connectMs)}_sent_${ms(stream.sentAt - stream.startedAt)}_lp${ms(stream.localPort)}${failed ? "_failed" : ""}`.slice(0, OUTCOME_MAX);
45052
+ };
45053
+ writeRequest = (record) => {
45054
+ try {
45055
+ moveTimingLog?.start({ startedAt: record.stream.startedAt })(record.phase ?? "onion:request", requestOutcome(record), record.at);
45056
+ } catch {
45057
+ }
45058
+ };
45059
+ REQUEST_MARK_FAST_MS = 1e3;
45060
+ noteRequest = (record) => {
45061
+ if (!record.failed && record.stream.kind === "reused" && record.at - record.stream.startedAt < REQUEST_MARK_FAST_MS) return;
45062
+ if (moveTimingLog) writeRequest(record);
45063
+ else if (requestRecords.length < REQUEST_RECORDS_MAX) requestRecords.push(record);
45064
+ };
44986
45065
  firstOnionRace = (origin) => {
44987
45066
  const race = firstRaces.get(origin);
44988
45067
  return race === void 0 ? void 0 : { ...race };
@@ -106614,7 +106693,10 @@ function sellerWaitMs(record) {
106614
106693
  function sellerAnswerInit(url, init, ms) {
106615
106694
  const target = () => init.dispatcher ?? routeDispatcherOf(url) ?? activeGlobalDispatcher();
106616
106695
  if (target() === void 0) return init;
106617
- return { ...init, dispatcher: { dispatch: (options, handler) => target().dispatch({ ...options, headersTimeout: ms, bodyTimeout: ms }, handler) } };
106696
+ return { ...init, dispatcher: {
106697
+ dispatch: (options, handler) => target().dispatch({ ...options, headersTimeout: ms, bodyTimeout: ms }, handler),
106698
+ tagDispatcher: target
106699
+ } };
106618
106700
  }
106619
106701
  async function sendWatchingStall(fetchImpl, url, init, waitMs, {
106620
106702
  mark = () => {
@@ -139030,7 +139112,7 @@ function cloudPlace(place, { platform = process.platform, env = process.env, hom
139030
139112
  const text3 = String(place ?? "").trim();
139031
139113
  if (!text3) return void 0;
139032
139114
  const fold = platform === "win32" || platform === "darwin";
139033
- const sep6 = platform === "win32" ? "\\" : "/";
139115
+ const sep7 = platform === "win32" ? "\\" : "/";
139034
139116
  const norm = (path) => {
139035
139117
  const full = (platform === "win32" ? resolve26(localForm(path, platform)) : posix.resolve(path)).replace(/[\\/]+$/, "");
139036
139118
  return fold ? full.toLowerCase() : full;
@@ -139038,7 +139120,7 @@ function cloudPlace(place, { platform = process.platform, env = process.env, hom
139038
139120
  const at = norm(text3);
139039
139121
  for (const root of (roots ?? (() => cloudRoots({ platform, env, home })))()) {
139040
139122
  const base = norm(root.path);
139041
- if (base && (at === base || at.startsWith(`${base}${sep6}`))) return root.service;
139123
+ if (base && (at === base || at.startsWith(`${base}${sep7}`))) return root.service;
139042
139124
  }
139043
139125
  for (const part of text3.split(/[\\/]+/).map((name) => name.trim().toLowerCase())) {
139044
139126
  if (part === "onedrive" || part.startsWith("onedrive - ") || part.startsWith("onedrive-")) return "OneDrive";
@@ -161740,7 +161822,7 @@ ${words2}`;
161740
161822
  import { spawn as spawn11, spawnSync as spawnSync9 } from "node:child_process";
161741
161823
  import { createHash as createHash43, createHmac as createHmac15, randomBytes as randomBytes44, timingSafeEqual as timingSafeEqual6 } from "node:crypto";
161742
161824
  import net3 from "node:net";
161743
- import { basename as basename12, dirname as dirname42, join as join51 } from "node:path";
161825
+ import { basename as basename12, dirname as dirname42, join as join51, sep as sep6 } from "node:path";
161744
161826
  import { Readable } from "node:stream";
161745
161827
  import { pipeline } from "node:stream/promises";
161746
161828
  function bootstrapProgress(text3) {
@@ -162019,7 +162101,7 @@ AUTHCHALLENGE SAFECOOKIE ${clientNonce.toString("hex")}\r
162019
162101
  }
162020
162102
  if (step === 2 && typeof events === "function") {
162021
162103
  step = 6;
162022
- socket.write("SETEVENTS HS_DESC CIRC\r\n");
162104
+ socket.write("SETEVENTS HS_DESC CIRC STREAM\r\n");
162023
162105
  continue;
162024
162106
  }
162025
162107
  if (step === 6) {
@@ -162540,25 +162622,75 @@ async function ownTorReady(home, state2, { wait: wait2 = true, deadline } = {})
162540
162622
  }
162541
162623
  return tunnelOf(state2.port);
162542
162624
  }
162543
- function ownPortOf(home) {
162544
- const state2 = managedTorState(home);
162545
- if (state2) return state2.port;
162546
- if (!bundleComplete(home) && !existsSync(join51(managedTorDir(home), "torrc"))) return void 0;
162625
+ function readHomeFileTail(home, path, max) {
162547
162626
  try {
162548
- return Number(new URL(readSetupConfig(home)?.torTunnel ?? "").port) || void 0;
162627
+ const kind = lstatSync(path);
162628
+ if (!kind.isFile()) return void 0;
162629
+ if (!realpathSync(path).startsWith(`${realpathSync(home)}${sep6}`)) return void 0;
162630
+ const length = Math.min(kind.size, max);
162631
+ const bytes2 = Buffer.alloc(length);
162632
+ const fd = openSync(path, "r");
162633
+ try {
162634
+ readSync(fd, bytes2, 0, length, kind.size - length);
162635
+ } finally {
162636
+ closeSync(fd);
162637
+ }
162638
+ return bytes2.toString("utf8");
162549
162639
  } catch {
162550
162640
  return void 0;
162551
162641
  }
162552
162642
  }
162553
- function isWalletOwnTunnel(home, tunnel) {
162554
- const state2 = managedTorState(home);
162555
- if (!state2) return false;
162643
+ function loggedTunnelPorts(home) {
162644
+ const ports = /* @__PURE__ */ new Set();
162645
+ const text3 = readHomeFileTail(home, logFile(home), NOTICE_READ_MAX);
162646
+ if (text3 === void 0) return ports;
162647
+ for (const match of text3.matchAll(TUNNEL_LISTENER_LINE)) {
162648
+ const port = Number(match[1]);
162649
+ if (port > 0 && port < 65536) ports.add(port);
162650
+ }
162651
+ return ports;
162652
+ }
162653
+ function recordedOwnPorts(home) {
162654
+ const text3 = readHomeFileTail(home, ownPortsFile(home), OWN_PORTS_READ_MAX + 1);
162655
+ if (text3 === void 0 || text3.length > OWN_PORTS_READ_MAX) return void 0;
162656
+ let parsed2;
162556
162657
  try {
162557
- return new URL(tunnel).origin === new URL(tunnelOf(state2.port)).origin;
162658
+ parsed2 = JSON.parse(text3);
162659
+ } catch {
162660
+ return void 0;
162661
+ }
162662
+ if (!Array.isArray(parsed2?.ports) || !parsed2.ports.every((port) => Number.isInteger(port) && port > 0 && port < 65536)) return void 0;
162663
+ return parsed2.ports;
162664
+ }
162665
+ function recordOwnPort(home, port) {
162666
+ try {
162667
+ const path = ownPortsFile(home);
162668
+ const known = recordedOwnPorts(home);
162669
+ if (known === void 0 && existsSync(path) && !lstatSync(path).isFile()) return;
162670
+ if (known?.includes(port)) return;
162671
+ writeAtomic5(path, `${JSON.stringify({ ports: [...known ?? [], port].slice(-OWN_PORTS_MAX) })}
162672
+ `);
162558
162673
  } catch {
162559
- return false;
162560
162674
  }
162561
162675
  }
162676
+ function ownTunnelPort(home, tunnel) {
162677
+ let url;
162678
+ try {
162679
+ url = new URL(tunnel);
162680
+ } catch {
162681
+ return void 0;
162682
+ }
162683
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1") return void 0;
162684
+ const port = Number(url.port);
162685
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) return void 0;
162686
+ const state2 = managedTorState(home);
162687
+ if (state2) return state2.port === port ? port : void 0;
162688
+ if (recordedOwnPorts(home)?.includes(port)) return port;
162689
+ return loggedTunnelPorts(home).has(port) ? port : void 0;
162690
+ }
162691
+ function isWalletOwnTunnel(home, tunnel) {
162692
+ return ownTunnelPort(home, tunnel) !== void 0;
162693
+ }
162562
162694
  async function setWalletTor(home, on, { say: say2 = () => {
162563
162695
  }, platform = process.platform } = {}) {
162564
162696
  let config;
@@ -162573,13 +162705,7 @@ async function setWalletTor(home, on, { say: say2 = () => {
162573
162705
  return { tor: false, agentAppRestart: true };
162574
162706
  }
162575
162707
  const recorded = config.torTunnel;
162576
- let recordedPort;
162577
- try {
162578
- recordedPort = recorded ? Number(new URL(recorded).port) : void 0;
162579
- } catch {
162580
- recordedPort = void 0;
162581
- }
162582
- const explicit = recorded !== void 0 && recordedPort !== ownPortOf(home);
162708
+ const explicit = recorded !== void 0 && ownTunnelPort(home, recorded) === void 0;
162583
162709
  const tunnel = await ensureWalletTor(recorded ?? TOR_HTTP_TUNNEL, { env: { ...process.env, SHIELDED_WALLET_HOME: home }, platform, explicit, say: say2 });
162584
162710
  if (!ownTorPlatform(platform) || explicit) {
162585
162711
  let now;
@@ -162603,14 +162729,15 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
162603
162729
  return proxy;
162604
162730
  }
162605
162731
  const home = setupHome(env);
162606
- const ownPort = ownPortOf(home);
162607
- if (explicit && Number(url.port) !== ownPort) return proxy;
162732
+ const ownPort = explicit ? ownTunnelPort(home, proxy) : void 0;
162733
+ if (explicit && ownPort === void 0) return proxy;
162608
162734
  let deadline = Date.now() + BOOTSTRAP_MAX_MS;
162609
162735
  const timeLeft = () => deadline - Date.now();
162610
162736
  try {
162611
162737
  const known = managedTorState(home);
162612
162738
  const ready = await ownTorReady(home, known, { wait: false });
162613
162739
  if (ready && await processLockFree(lockName(home)) && pidAlive5(known.pid)) {
162740
+ recordOwnPort(home, known.port);
162614
162741
  await recordTunnel(home, ready, deadline);
162615
162742
  return ready;
162616
162743
  }
@@ -162625,6 +162752,7 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
162625
162752
  if (!(error?.stalled === true && timeLeft() >= RESTART_MIN_MS)) throw error;
162626
162753
  }
162627
162754
  if (again) {
162755
+ recordOwnPort(home, state2.port);
162628
162756
  await recordTunnel(home, again, deadline);
162629
162757
  return again;
162630
162758
  }
@@ -162655,6 +162783,7 @@ async function ensureWalletTor(proxy, { env = process.env, platform = process.pl
162655
162783
  if (timeLeft() < RESTART_MIN_MS) throw noTimeLeft();
162656
162784
  try {
162657
162785
  await startTor(home, port, say2, assertHeld, deadline);
162786
+ recordOwnPort(home, port);
162658
162787
  await recordTunnel(home, tunnelOf(port), deadline);
162659
162788
  return tunnelOf(port);
162660
162789
  } catch (error) {
@@ -162700,6 +162829,13 @@ function torTimingMark(line, ours) {
162700
162829
  if (!prefix2 || !HS_DESC_ACTIONS.has(desc[1]) || reason2 !== void 0 && !HS_DESC_REASONS.has(reason2)) return void 0;
162701
162830
  return { phase: `hs-desc-${desc[1].toLowerCase()}`, outcome: `onion_${prefix2}${reason2 ? `_${reason2.toLowerCase()}` : ""}` };
162702
162831
  }
162832
+ const stream = /^650 STREAM (\d{1,20}) ([A-Z_]+) (\d{1,10}) ([a-z2-7]{56})\.onion:\d{1,5}(?: |$)/.exec(line);
162833
+ if (stream) {
162834
+ const prefix2 = ours.get(stream[4]);
162835
+ if (!prefix2 || !STREAM_STATUSES.has(stream[2])) return void 0;
162836
+ const port = stream[2] === "NEW" ? /(?:^| )SOURCE_ADDR=127\.0\.0\.1:(\d{1,5})(?: |$)/.exec(line)?.[1] : void 0;
162837
+ return { phase: `stream-${stream[2].toLowerCase()}`, outcome: `onion_${prefix2}_s${stream[1]}_c${stream[3]}${port ? `_lp${port}` : ""}` };
162838
+ }
162703
162839
  const circ = /^650 CIRC (\d{1,10}) ([A-Z_]+) /.exec(`${line} `);
162704
162840
  if (!circ || !CIRC_STATUSES.has(circ[2])) return void 0;
162705
162841
  const rend = /(?:^| )REND_QUERY=([a-z2-7]{56})(?: |$)/.exec(line)?.[1];
@@ -162712,7 +162848,7 @@ function torTimingMark(line, ours) {
162712
162848
  }
162713
162849
  function startTorTimingMarks() {
162714
162850
  const run2 = String(process.env.SHINJUKU_WALLET_PROXIED ?? "");
162715
- if (!run2.startsWith("tor ") || !process.argv.includes("--verbose")) return;
162851
+ if (!run2.startsWith("tor ") || !(process.argv.includes("--verbose") || process.argv[2] === "mcp")) return;
162716
162852
  setImmediate(async () => {
162717
162853
  try {
162718
162854
  const home = setupHome(process.env);
@@ -162728,23 +162864,40 @@ function startTorTimingMarks() {
162728
162864
  const ours = ownOnionPrefixes();
162729
162865
  const mark = createTimingLog(join51(home, pool2, "wallet.json.timing.log"), { component: "tor" }).start({ startedAt: Date.now() - performance.now() });
162730
162866
  let marks = 0;
162867
+ let session;
162868
+ let spent = false;
162869
+ const closeSession = () => {
162870
+ try {
162871
+ session?.close();
162872
+ } catch {
162873
+ }
162874
+ };
162731
162875
  const once2 = (phase, outcome) => {
162732
162876
  if (marks >= TOR_TIMING_MAX) return;
162733
162877
  marks += 1;
162734
162878
  mark(phase, outcome);
162879
+ if (marks >= TOR_TIMING_MAX) {
162880
+ spent = true;
162881
+ closeSession();
162882
+ }
162735
162883
  };
162736
- const session = await controlCheck(home, state2, { unref: true, events: (line) => {
162884
+ session = await controlCheck(home, state2, { unref: true, events: (line) => {
162885
+ if (spent) return;
162737
162886
  const one = torTimingMark(line, ours);
162738
162887
  if (one) once2(one.phase, one.outcome);
162739
162888
  } });
162740
162889
  if (!session) return;
162741
- process.once("exit", () => session.close());
162890
+ if (spent) {
162891
+ closeSession();
162892
+ return;
162893
+ }
162894
+ process.once("exit", closeSession);
162742
162895
  once2("events-on");
162743
162896
  } catch {
162744
162897
  }
162745
162898
  });
162746
162899
  }
162747
- var ownTorPlatform, MAC, LINUX, SYSTEM2, bundle, managedTorDir, stateFile, bundleDir, torExe, MAC_SIGNED, COMPLETE, LINUX_TOR, BUNDLE_FILES, logFile, BOOTSTRAP_STALL_MS, BOOTSTRAP_MAX_MS, STALL_RESTART_PERCENT, RESTART_MIN_MS, REACHED_RELAY_PERCENT, phaseWords, DOWNLOAD_TIMEOUT_MS, BIND_TRIES, POLL_MS2, pidAlive5, WIN_OWN_TOR, STOP_WAIT_MS, cookieFile, CONTROL_TIMEOUT_MS, SERVER_KEY, CLIENT_KEY, failure2, sleep4, tunnelOf, bundleComplete, LINUX_HASHES, fileSha256, startErrorsFile, EVENT_LINE_MAX, TOR_TIMING_MAX, HS_DESC_ACTIONS, HS_DESC_REASONS, CIRC_STATUSES, CIRC_PURPOSES, CIRC_HS_STATES, CIRC_REASONS;
162900
+ var ownTorPlatform, MAC, LINUX, SYSTEM2, bundle, managedTorDir, stateFile, bundleDir, torExe, MAC_SIGNED, COMPLETE, LINUX_TOR, BUNDLE_FILES, logFile, BOOTSTRAP_STALL_MS, BOOTSTRAP_MAX_MS, STALL_RESTART_PERCENT, RESTART_MIN_MS, REACHED_RELAY_PERCENT, phaseWords, DOWNLOAD_TIMEOUT_MS, BIND_TRIES, POLL_MS2, pidAlive5, WIN_OWN_TOR, STOP_WAIT_MS, cookieFile, CONTROL_TIMEOUT_MS, SERVER_KEY, CLIENT_KEY, failure2, sleep4, tunnelOf, bundleComplete, LINUX_HASHES, fileSha256, startErrorsFile, NOTICE_READ_MAX, TUNNEL_LISTENER_LINE, ownPortsFile, OWN_PORTS_MAX, OWN_PORTS_READ_MAX, EVENT_LINE_MAX, TOR_TIMING_MAX, HS_DESC_ACTIONS, HS_DESC_REASONS, CIRC_STATUSES, CIRC_PURPOSES, CIRC_HS_STATES, CIRC_REASONS, STREAM_STATUSES;
162748
162901
  var init_managedTor = __esm({
162749
162902
  "wallet/src/net/managedTor.mjs"() {
162750
162903
  "use strict";
@@ -162875,18 +163028,21 @@ public static class ShinjukuOwnTor {
162875
163028
  LINUX_HASHES = ".hashes.json";
162876
163029
  fileSha256 = (path) => createHash43("sha256").update(readFileSync(path)).digest("hex");
162877
163030
  startErrorsFile = (home) => join51(managedTorDir(home), "start-errors.log");
163031
+ NOTICE_READ_MAX = 2 * 1024 * 1024;
163032
+ TUNNEL_LISTENER_LINE = /^[A-Z][a-z]{2} [ 0-9]?[0-9] [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3} \[notice\] Opened HTTP tunnel listener (?:connection \(ready\) )?on 127\.0\.0\.1:([0-9]{1,5})\r?$/gm;
163033
+ ownPortsFile = (home) => join51(managedTorDir(home), "own-ports.json");
163034
+ OWN_PORTS_MAX = 256;
163035
+ OWN_PORTS_READ_MAX = 16 * 1024;
162878
163036
  setTunnelCircuitProbe(async ({ proxyHost, proxyPort } = {}) => {
162879
163037
  if (String(proxyHost) !== "127.0.0.1") return void 0;
162880
163038
  const home = setupHome(process.env);
162881
- const port = ownPortOf(home);
162882
- if (!Number.isInteger(port) || Number(proxyPort) !== port) return void 0;
162883
163039
  const state2 = managedTorState(home);
162884
- if (!state2 || state2.port !== port) return void 0;
163040
+ if (!state2 || Number(proxyPort) !== state2.port) return void 0;
162885
163041
  const answer = await controlCheck(home, state2, { circuits: true, unref: true });
162886
163042
  return answer && answer.tunnelPort === Number(proxyPort) ? answer.circuits : void 0;
162887
163043
  });
162888
163044
  EVENT_LINE_MAX = 4096;
162889
- TOR_TIMING_MAX = 200;
163045
+ TOR_TIMING_MAX = 800;
162890
163046
  HS_DESC_ACTIONS = /* @__PURE__ */ new Set(["REQUESTED", "RECEIVED", "FAILED"]);
162891
163047
  HS_DESC_REASONS = /* @__PURE__ */ new Set([
162892
163048
  "BAD_DESC",
@@ -162926,6 +163082,7 @@ public static class ShinjukuOwnTor {
162926
163082
  "MEASUREMENT_EXPIRED",
162927
163083
  "IP_NOW_REDUNDANT"
162928
163084
  ]);
163085
+ STREAM_STATUSES = /* @__PURE__ */ new Set(["NEW", "SENTCONNECT", "SUCCEEDED", "FAILED", "CLOSED", "DETACHED"]);
162929
163086
  startTorTimingMarks();
162930
163087
  }
162931
163088
  });
@@ -163127,11 +163284,12 @@ function proxyDispatcherClass() {
163127
163284
  async function sellerTor(recorded, home) {
163128
163285
  let tunnel = recorded;
163129
163286
  if (home) {
163130
- const current = readSetupConfig(home)?.torTunnel ?? recorded;
163287
+ const walletRecorded = readSetupConfig(home)?.torTunnel;
163288
+ const current = walletRecorded ?? recorded;
163131
163289
  try {
163132
163290
  tunnel = await ensureWalletTor(current, {
163133
163291
  env: { ...process.env, SHIELDED_WALLET_HOME: home },
163134
- explicit: true,
163292
+ explicit: walletRecorded !== void 0,
163135
163293
  say: (line) => process.stderr.write(`${line}
163136
163294
  `)
163137
163295
  });
@@ -172517,8 +172675,9 @@ function mcpSetupAdapter(values, home, deps) {
172517
172675
  // A "Use Tor?" yes: run() starts the wallet's own Tor first (mcpSetupBehindTor -> torTunnelReady -> ensureWalletTor)
172518
172676
  // when it applies, so the setup box probes no tunnel then (a live check on npm 0.3.219, a fresh computer, 2026-11-12 15:23:32 UTC: a
172519
172677
  // fresh home with nothing at 127.0.0.1:9080 stopped at tor_not_running with a terminal step before that start). The
172520
- // rule: an own-Tor platform, and no recorded torTunnel, or the recorded one is the tunnel managed.json names (the Tor
172521
- // this wallet started here; isWalletOwnTunnel). Any other recorded tunnel is the user's, and the box probes it.
172678
+ // rule: an own-Tor platform, and no recorded torTunnel, or the recorded one is this home's own Tor tunnel by the rule
172679
+ // every Tor run uses (isWalletOwnTunnel: managed.json, else tor\own-ports.json, else tor\notice.log; never config.json).
172680
+ // Any other recorded tunnel is the user's, and the box probes it.
172522
172681
  // torTunnel: the tunnel the probe checks otherwise (a Tor the user set, recorded in config.json; else the default).
172523
172682
  ownTor: () => {
172524
172683
  const recorded = configOrNull(home)?.torTunnel;
@@ -173403,7 +173562,7 @@ async function hostCheckProxy(home, deps, noTor) {
173403
173562
  if (proxy.tor) {
173404
173563
  if (!inProxiedRun(deps.env)) {
173405
173564
  try {
173406
- proxy = { ...proxy, url: await torTunnelReady(proxy.url, { explicit: proxy.url !== TOR_HTTP_TUNNEL }) };
173565
+ proxy = { ...proxy, url: await torTunnelReady(proxy.url, { explicit: proxy.explicit === true }) };
173407
173566
  } catch {
173408
173567
  return { down: true };
173409
173568
  }
@@ -173596,8 +173755,8 @@ Setup stopped. Run the same setup line again to finish it; files already downloa
173596
173755
  }
173597
173756
  function installProxy(deps, behindTor, tunnel) {
173598
173757
  const run2 = childRunProxy(deps.env).args;
173599
- if (run2[0] === "--tor") return { url: run2[2] ?? TOR_HTTP_TUNNEL, tor: true };
173600
- return behindTor ? { url: tunnel ?? TOR_HTTP_TUNNEL, tor: true } : void 0;
173758
+ if (run2[0] === "--tor") return { url: run2[2] ?? TOR_HTTP_TUNNEL, tor: true, explicit: run2[2] !== void 0 };
173759
+ return behindTor ? { url: tunnel ?? TOR_HTTP_TUNNEL, tor: true, explicit: tunnel !== void 0 } : void 0;
173601
173760
  }
173602
173761
  var COMMAND_NOT_INSTALLED = "The shinjuku command could not be installed on this computer; the longer command below works the same.";
173603
173762
  async function installCommand(deps, {
@@ -173621,7 +173780,7 @@ async function installCommand(deps, {
173621
173780
  tunnelOf2(proxy.url);
173622
173781
  if (!inProxiedRun(deps.env)) {
173623
173782
  try {
173624
- proxy = { ...proxy, url: await torTunnelReady(proxy.url, { explicit: proxy.url !== TOR_HTTP_TUNNEL }) };
173783
+ proxy = { ...proxy, url: await torTunnelReady(proxy.url, { explicit: proxy.explicit === true }) };
173625
173784
  } catch {
173626
173785
  return "tor-down";
173627
173786
  }