@ait-co/devtools 0.1.128 → 0.1.131

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.
Files changed (113) hide show
  1. package/dist/{attach-orchestrator-CPMQWkGV.js → attach-orchestrator-BiaYiNOr.js} +34 -107
  2. package/dist/attach-orchestrator-BiaYiNOr.js.map +1 -0
  3. package/dist/{attach-orchestrator-RhOdO3DS.js → attach-orchestrator-Cjdhir2U.js} +31 -13
  4. package/dist/{attach-orchestrator-RhOdO3DS.js.map → attach-orchestrator-Cjdhir2U.js.map} +1 -1
  5. package/dist/{attach-orchestrator-CpE0dMew.js → attach-orchestrator-ca34r46y.js} +33 -106
  6. package/dist/attach-orchestrator-ca34r46y.js.map +1 -0
  7. package/dist/{bundle-Cb3GFuw6.d.ts → bundle-BKqyhEK9.d.ts} +1 -1
  8. package/dist/{bundle-Cb3GFuw6.d.ts.map → bundle-BKqyhEK9.d.ts.map} +1 -1
  9. package/dist/{capture-B1zfGyTo.d.ts → capture-ltuV0gZa.d.ts} +1 -1
  10. package/dist/{capture-B1zfGyTo.d.ts.map → capture-ltuV0gZa.d.ts.map} +1 -1
  11. package/dist/{cdp-connection-Dxw_EY8s.d.ts → cdp-connection-D7AYQck2.d.ts} +1 -1
  12. package/dist/{cdp-connection-Dxw_EY8s.d.ts.map → cdp-connection-D7AYQck2.d.ts.map} +1 -1
  13. package/dist/{cell-D0dJSGHi.js → cell-Bi8MAPA8.js} +11 -7
  14. package/dist/cell-Bi8MAPA8.js.map +1 -0
  15. package/dist/{cell-Ba9lCI3B.js → cell-Cw4fVOl2.js} +11 -7
  16. package/dist/cell-Cw4fVOl2.js.map +1 -0
  17. package/dist/{cell-CX92lDI0.js → cell-rr6gL9AT.js} +11 -7
  18. package/dist/cell-rr6gL9AT.js.map +1 -0
  19. package/dist/debug-server-BSbfnFR5.js +436 -0
  20. package/dist/debug-server-BSbfnFR5.js.map +1 -0
  21. package/dist/debug-server-CD4zYBq4.js +379 -0
  22. package/dist/{debug-server-BzzNkETg.js.map → debug-server-CD4zYBq4.js.map} +1 -1
  23. package/dist/{debug-server-Dctc9GAh.js → debug-server-qRSRG7YZ.js} +68 -65
  24. package/dist/debug-server-qRSRG7YZ.js.map +1 -0
  25. package/dist/in-app/auto.js +15 -0
  26. package/dist/in-app/auto.js.map +1 -1
  27. package/dist/in-app/index.d.ts +27 -0
  28. package/dist/in-app/index.d.ts.map +1 -1
  29. package/dist/in-app/index.js +15 -0
  30. package/dist/in-app/index.js.map +1 -1
  31. package/dist/log-CUik_tHp.js +95 -0
  32. package/dist/log-CUik_tHp.js.map +1 -0
  33. package/dist/mcp/cli.js +1272 -1111
  34. package/dist/mcp/cli.js.map +1 -1
  35. package/dist/mcp/server.js +1 -1
  36. package/dist/panel/index.js +11 -1
  37. package/dist/panel/index.js.map +1 -1
  38. package/dist/{pool-DBLKNeRC.d.ts → pool-BaSCZALv.d.ts} +12 -4
  39. package/dist/{pool-DBLKNeRC.d.ts.map → pool-BaSCZALv.d.ts.map} +1 -1
  40. package/dist/{qr-http-server-Bo8LMOJQ.js → qr-http-server-BdNGPRoL.js} +76 -6
  41. package/dist/qr-http-server-BdNGPRoL.js.map +1 -0
  42. package/dist/{qr-http-server-CrGohOwC.js → qr-http-server-Bq9zR7-z.js} +76 -6
  43. package/dist/qr-http-server-Bq9zR7-z.js.map +1 -0
  44. package/dist/{qr-http-server-Bt_RAxFn.cjs → qr-http-server-BxoRp2w7.cjs} +76 -6
  45. package/dist/qr-http-server-BxoRp2w7.cjs.map +1 -0
  46. package/dist/{qr-http-server-DM2R25jP.cjs → qr-http-server-CV6TA9ZN.cjs} +76 -6
  47. package/dist/qr-http-server-CV6TA9ZN.cjs.map +1 -0
  48. package/dist/{qr-http-server-s1iW_5VQ.js → qr-http-server-DCbjORFa.js} +76 -6
  49. package/dist/qr-http-server-DCbjORFa.js.map +1 -0
  50. package/dist/{qr-http-server-BH0UFeUn.js → qr-http-server-cKbciY5k.js} +76 -6
  51. package/dist/qr-http-server-cKbciY5k.js.map +1 -0
  52. package/dist/{relay-factory-Dug7W6Ao.js → relay-factory-Cloog1jb.js} +34 -14
  53. package/dist/relay-factory-Cloog1jb.js.map +1 -0
  54. package/dist/{relay-secret-store-DKxs7zwq.js → relay-secret-store-DzxDsK6S.js} +1 -1
  55. package/dist/{relay-secret-store-DKxs7zwq.js.map → relay-secret-store-DzxDsK6S.js.map} +1 -1
  56. package/dist/{relay-url-store-xmUuTjXA.js → relay-url-store-D3rY-GJJ.js} +2 -2
  57. package/dist/{relay-url-store-xmUuTjXA.js.map → relay-url-store-D3rY-GJJ.js.map} +1 -1
  58. package/dist/{debug-server-BzzNkETg.js → relay-worker-CCAHLC4a.js} +220 -350
  59. package/dist/relay-worker-CCAHLC4a.js.map +1 -0
  60. package/dist/{relay-worker-TReZtzGl.d.ts → relay-worker-o0M2ndyJ.d.ts} +7 -7
  61. package/dist/relay-worker-o0M2ndyJ.d.ts.map +1 -0
  62. package/dist/{runtime-ozyPnRbU.d.ts → runtime-9xhN9pr8.d.ts} +1 -1
  63. package/dist/{runtime-ozyPnRbU.d.ts.map → runtime-9xhN9pr8.d.ts.map} +1 -1
  64. package/dist/test-runner/bin.js +744 -25
  65. package/dist/test-runner/bin.js.map +1 -1
  66. package/dist/test-runner/bundle.d.ts +1 -1
  67. package/dist/test-runner/capture.d.ts +1 -1
  68. package/dist/test-runner/config.d.ts +15 -9
  69. package/dist/test-runner/config.d.ts.map +1 -1
  70. package/dist/test-runner/config.js +1 -1
  71. package/dist/test-runner/pool.d.ts +1 -1
  72. package/dist/test-runner/pool.js +1 -1
  73. package/dist/test-runner/pool.js.map +1 -1
  74. package/dist/test-runner/relay-factory.d.ts +23 -9
  75. package/dist/test-runner/relay-factory.d.ts.map +1 -1
  76. package/dist/test-runner/relay-factory.js +32 -12
  77. package/dist/test-runner/relay-factory.js.map +1 -1
  78. package/dist/test-runner/relay-worker.d.ts +1 -1
  79. package/dist/test-runner/relay-worker.js +1 -187
  80. package/dist/test-runner/report.d.ts +3 -3
  81. package/dist/test-runner/rpc.d.ts +2 -2
  82. package/dist/test-runner/runtime.d.ts +1 -1
  83. package/dist/test-runner/task-graph.d.ts +1 -1
  84. package/dist/{tunnel-DyEV6WwL.cjs → tunnel-B2UCKAc7.cjs} +4 -3
  85. package/dist/{tunnel-DyEV6WwL.cjs.map → tunnel-B2UCKAc7.cjs.map} +1 -1
  86. package/dist/{tunnel-BFwOSwT4.js → tunnel-C-rQ34dM.js} +4 -3
  87. package/dist/{tunnel-BFwOSwT4.js.map → tunnel-C-rQ34dM.js.map} +1 -1
  88. package/dist/unplugin/index.cjs +1 -1
  89. package/dist/unplugin/index.js +1 -1
  90. package/dist/unplugin/tunnel.cjs +3 -2
  91. package/dist/unplugin/tunnel.cjs.map +1 -1
  92. package/dist/unplugin/tunnel.d.cts.map +1 -1
  93. package/dist/unplugin/tunnel.d.ts.map +1 -1
  94. package/dist/unplugin/tunnel.js +3 -2
  95. package/dist/unplugin/tunnel.js.map +1 -1
  96. package/package.json +1 -1
  97. package/dist/attach-orchestrator-CPMQWkGV.js.map +0 -1
  98. package/dist/attach-orchestrator-CpE0dMew.js.map +0 -1
  99. package/dist/cell-Ba9lCI3B.js.map +0 -1
  100. package/dist/cell-CX92lDI0.js.map +0 -1
  101. package/dist/cell-D0dJSGHi.js.map +0 -1
  102. package/dist/debug-server-1dhDA3aw.js +0 -980
  103. package/dist/debug-server-1dhDA3aw.js.map +0 -1
  104. package/dist/debug-server-Dctc9GAh.js.map +0 -1
  105. package/dist/qr-http-server-BH0UFeUn.js.map +0 -1
  106. package/dist/qr-http-server-Bo8LMOJQ.js.map +0 -1
  107. package/dist/qr-http-server-Bt_RAxFn.cjs.map +0 -1
  108. package/dist/qr-http-server-CrGohOwC.js.map +0 -1
  109. package/dist/qr-http-server-DM2R25jP.cjs.map +0 -1
  110. package/dist/qr-http-server-s1iW_5VQ.js.map +0 -1
  111. package/dist/relay-factory-Dug7W6Ao.js.map +0 -1
  112. package/dist/relay-worker-TReZtzGl.d.ts.map +0 -1
  113. package/dist/test-runner/relay-worker.js.map +0 -1
@@ -0,0 +1,379 @@
1
+ #!/usr/bin/env node
2
+ import { n as buildRelayVerifyAuth, t as assertRelayAuthConfigured } from "./totp-DvOYkYim.js";
3
+ import { a as RELAY_AUTH_REJECT_REASON, i as RELAY_AUTH_REJECT_CLOSE_CODE, n as logError, r as logInfo, t as ChiiCdpConnection } from "./test-runner/bin.js";
4
+ import { a as startTunnelHealthProbe, i as startQuickTunnel, n as makeTunnelStatus, r as printAttachBanner, t as generateAttachToken } from "./attach-orchestrator-ca34r46y.js";
5
+ import "./cell-rr6gL9AT.js";
6
+ import "./qr-http-server-DCbjORFa.js";
7
+ import "./relay-secret-store-CFc9n0OA.js";
8
+ import { createRequire } from "node:module";
9
+ import "node:events";
10
+ import { WebSocketServer } from "ws";
11
+ import "@modelcontextprotocol/sdk/server/index.js";
12
+ import "@modelcontextprotocol/sdk/server/stdio.js";
13
+ import "@modelcontextprotocol/sdk/types.js";
14
+ import { createServer } from "node:http";
15
+ //#region src/mcp/chii-relay.ts
16
+ /**
17
+ * Boots the local Chii relay server.
18
+ *
19
+ * Chii (liriliri/chii) is a chobitsu-based CDP relay that lets non-Chrome
20
+ * WebViews (iOS WKWebView / Android WebView — i.e. the Toss app) expose CDP.
21
+ * The relay accepts a `target` websocket from the phone's injected `target.js`
22
+ * and `client` websockets from CDP frontends (our MCP connection).
23
+ *
24
+ * Node-only: `chii` pulls in Koa + ws. Never bundled into the browser/in-app
25
+ * entries.
26
+ *
27
+ * TOTP auth (relay-side, authoritative gate):
28
+ * When `verifyAuth` is provided, this module gates both inbound surfaces:
29
+ *
30
+ * - HTTP 'request': a listener registered BEFORE `chii.start({server})`.
31
+ * Node's `http.Server` calls listeners in registration order; the first
32
+ * to call `res.end()` wins. Invalid auth → 401 + CORS header + a tiny
33
+ * JSON body (`{"error":"totp-rejected"}`) so a cross-origin script
34
+ * `fetch()` probe can READ the status (issue #478). Valid auth → return
35
+ * without side-effect (chii's Koa handler serves it).
36
+ *
37
+ * - WS 'upgrade': after `chii.start()` has registered chii's own upgrade
38
+ * listener, we take over the upgrade chain (remove chii's listeners,
39
+ * re-dispatch manually). Invalid auth → accept-then-close: complete the
40
+ * handshake via a `noServer` WebSocketServer, then immediately close
41
+ * with code 4401 reason 'totp-rejected' (issue #478). A raw 401 +
42
+ * `socket.destroy()` only ever surfaced as close code 1006 in the
43
+ * browser — indistinguishable from a tunnel failure, which left the
44
+ * env-2 phone UI silent. The explicit dispatch (not listener ordering)
45
+ * is what keeps chii away from rejected sockets: accept-then-close
46
+ * leaves the socket alive, so an order-based early-return would let
47
+ * chii's later listener complete a SECOND handshake on the same socket
48
+ * — an auth bypass. Valid auth → forward to chii's captured listeners.
49
+ *
50
+ * TOTP code transports (issue #466) — two equivalent ways to carry the code:
51
+ * 1. Query param `at=<code>` — used by the daemon-side `/client` connection
52
+ * (`chii-connection.ts` appends it; it holds the secret).
53
+ * 2. Path prefix `/at/<code>/…` — used by the phone-side target. Chii's
54
+ * stock `target.js` derives its WS endpoint from the script `src`
55
+ * (`scriptEl.src.replace('target.js','')`), so the only way for the
56
+ * phone to carry a code is to embed it in the script URL path. The
57
+ * in-app attach injects `https://<host>/at/<code>/target.js`; both the
58
+ * script fetch and the derived `wss://<host>/at/<code>/target/<id>` WS
59
+ * dial then carry the prefix. The listeners below rewrite the prefix
60
+ * into the query form (`rewriteAtPathPrefix`) and MUTATE `req.url`
61
+ * before chii's own handlers (registered later) parse it — chii only
62
+ * ever sees the stripped URL.
63
+ *
64
+ * Threat model: "URL leak" — someone obtains the tunnel URL (Slack paste, QR
65
+ * screenshot, shoulder-surfing) but does not have the shared TOTP secret.
66
+ * Rotating 6-digit code makes the URL stale after 30 s.
67
+ * A determined attacker who extracts the secret from the dogfood bundle can
68
+ * still compute valid codes; that is out of scope (see umbrella CLAUDE.md §4).
69
+ *
70
+ * SECRET-HANDLING: The secret value and computed TOTP codes MUST NOT appear
71
+ * in any log, error message, or process output. `verifyAuth` is a black-box
72
+ * predicate from the caller's perspective; this module only forwards pass/fail.
73
+ */
74
+ const require = createRequire(import.meta.url);
75
+ /**
76
+ * WS keepalive ping interval (ms).
77
+ *
78
+ * Cloudflare proxied connections are dropped after ~100 s of no traffic.
79
+ * 45 s comfortably fits inside that window and lets both the phone-target leg
80
+ * and the daemon-client leg survive idle CDP sessions.
81
+ */
82
+ const DEFAULT_KEEPALIVE_INTERVAL_MS = 45e3;
83
+ /**
84
+ * Loads chii's internal WebSocketServer class and returns it together with a
85
+ * flag indicating whether the real class was found.
86
+ *
87
+ * Returns `null` if the internal path is not resolvable (future chii release
88
+ * changes the layout) — callers skip keepalive gracefully.
89
+ */
90
+ function tryLoadChiiWssClass() {
91
+ try {
92
+ const mod = require("chii/server/lib/WebSocketServer");
93
+ if (typeof mod === "function") return mod;
94
+ } catch {}
95
+ return null;
96
+ }
97
+ /**
98
+ * Calls `chii.start()` and returns the chii `WebSocketServer` instance that
99
+ * was constructed during the call.
100
+ *
101
+ * How: `chii/server/index.js`'s `start()` creates `new WebSocketServer()`
102
+ * where `WebSocketServer` is captured from `require('./lib/WebSocketServer')`
103
+ * at module load time. The class reference is stable, so we can temporarily
104
+ * patch `ChiiWssClass.prototype.start` — which runs *on the instance* —
105
+ * to record `this` before the original `start` runs.
106
+ *
107
+ * The patch is installed before `chii.start()` and removed (via `finally`)
108
+ * immediately after, so concurrent `startChiiRelay` calls nest correctly: each
109
+ * call's patch overrides the previous in the prototype chain for the duration
110
+ * of its own `chii.start()` call, restoring the prior descriptor on exit.
111
+ *
112
+ * If `ChiiWssClass` is null (internal path changed in a future chii release),
113
+ * `chii.start()` runs unpatched and the function returns null — callers skip
114
+ * keepalive gracefully without affecting relay correctness.
115
+ */
116
+ async function startChiiWithCapture(chii, startOptions, ChiiWssClass) {
117
+ if (ChiiWssClass === null) {
118
+ await chii.start(startOptions);
119
+ return null;
120
+ }
121
+ let captured = null;
122
+ const proto = ChiiWssClass.prototype;
123
+ const originalStart = proto.start;
124
+ proto.start = function(server) {
125
+ captured = this;
126
+ return originalStart.call(this, server);
127
+ };
128
+ try {
129
+ await chii.start(startOptions);
130
+ } finally {
131
+ proto.start = originalStart;
132
+ }
133
+ return captured;
134
+ }
135
+ function loadChiiServer() {
136
+ const mod = require("chii");
137
+ if (typeof mod === "object" && mod !== null && "start" in mod && typeof mod.start === "function") return mod;
138
+ throw new Error("chii server module did not expose start()");
139
+ }
140
+ /**
141
+ * Rewrites a `/at/<code>/…` path-prefixed request URL into the equivalent
142
+ * query-based form, e.g.:
143
+ *
144
+ * `/at/123456/target.js` → `/target.js?at=123456`
145
+ * `/at/123456/target/x?url=u` → `/target/x?url=u&at=123456`
146
+ * `/at/123456/` → `/?at=123456`
147
+ *
148
+ * Returns `null` when the URL does not carry the prefix (including an empty
149
+ * code segment) — callers fall back to the unmodified URL and the existing
150
+ * query-based auth path.
151
+ *
152
+ * Pure string surgery — this function knows nothing about secrets or code
153
+ * validity; verification stays inside the caller-provided `verifyAuth`
154
+ * predicate (which parses the query). The raw path segment is appended
155
+ * verbatim to the query: both path segments and query values are
156
+ * percent-decoded exactly once by their consumers, so no re-encoding is
157
+ * needed (TOTP codes are 6 digits and never percent-encoded in practice).
158
+ */
159
+ function rewriteAtPathPrefix(rawUrl) {
160
+ const match = /^\/at\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(rawUrl);
161
+ if (match === null) return null;
162
+ const code = match[1];
163
+ const path = match[2] === void 0 || match[2] === "" ? "/" : match[2];
164
+ const query = match[3] ?? "";
165
+ return `${path}${query}${query === "" ? "?" : "&"}at=${code}`;
166
+ }
167
+ /**
168
+ * Starts the Chii relay and resolves once listening.
169
+ *
170
+ * Default port is 0 (OS-assigned). With port 0 the OS picks a free ephemeral
171
+ * port on every start, so a stale cloudflared orphan holding any particular
172
+ * port cannot cause EADDRINUSE. The resolved `ChiiRelay.port` and `baseUrl`
173
+ * always reflect the actual bound port.
174
+ *
175
+ * chii.start() is called with `server` (our pre-created httpServer) BEFORE
176
+ * httpServer.listen(). This is intentional: chii attaches its Koa handler and
177
+ * WS upgrade listener to the server object, but the actual TCP bind is
178
+ * performed by our httpServer.listen() call below. The `port`/`domain` values
179
+ * passed to chii.start() are used for display/banner purposes inside chii and
180
+ * do not affect which port the server binds. The connection path (clients
181
+ * connecting to `relay.baseUrl`) always uses the post-listen confirmed port.
182
+ */
183
+ async function startChiiRelay(options = {}) {
184
+ const requestedPort = options.port ?? 0;
185
+ const host = options.host ?? "127.0.0.1";
186
+ const { verifyAuth, onAuthReject } = options;
187
+ const keepaliveIntervalMs = options.keepaliveIntervalMs !== void 0 ? options.keepaliveIntervalMs : DEFAULT_KEEPALIVE_INTERVAL_MS;
188
+ const httpServer = createServer();
189
+ const notifyAuthReject = (kind) => {
190
+ if (onAuthReject === void 0) return;
191
+ try {
192
+ onAuthReject({ kind });
193
+ } catch {}
194
+ };
195
+ if (verifyAuth) httpServer.on("request", (req, res) => {
196
+ const rewritten = rewriteAtPathPrefix(req.url ?? "");
197
+ if (rewritten !== null) {
198
+ req.url = rewritten;
199
+ if (!verifyAuth(req)) {
200
+ res.statusCode = 401;
201
+ res.setHeader("Access-Control-Allow-Origin", "*");
202
+ res.setHeader("Content-Type", "application/json");
203
+ res.end(JSON.stringify({ error: RELAY_AUTH_REJECT_REASON }));
204
+ notifyAuthReject("http-request");
205
+ }
206
+ return;
207
+ }
208
+ const pathname = (req.url ?? "").split("?")[0];
209
+ if (pathname === "/targets" || pathname === "/targets/") {
210
+ if (!verifyAuth(req)) {
211
+ res.statusCode = 401;
212
+ res.setHeader("Access-Control-Allow-Origin", "*");
213
+ res.setHeader("Content-Type", "application/json");
214
+ res.end(JSON.stringify({ error: RELAY_AUTH_REJECT_REASON }));
215
+ notifyAuthReject("http-request");
216
+ return;
217
+ }
218
+ return;
219
+ }
220
+ });
221
+ const chiiWssClass = keepaliveIntervalMs > 0 ? tryLoadChiiWssClass() : null;
222
+ const capturedChiiWss = await startChiiWithCapture(loadChiiServer(), {
223
+ server: httpServer,
224
+ domain: `${host}:${requestedPort}`,
225
+ port: requestedPort
226
+ }, chiiWssClass);
227
+ if (verifyAuth) {
228
+ const chiiUpgradeListeners = httpServer.listeners("upgrade");
229
+ httpServer.removeAllListeners("upgrade");
230
+ const rejectWss = new WebSocketServer({ noServer: true });
231
+ httpServer.on("upgrade", (req, socket, head) => {
232
+ const rewritten = rewriteAtPathPrefix(req.url ?? "");
233
+ if (rewritten !== null) req.url = rewritten;
234
+ if (!verifyAuth(req)) {
235
+ rejectWss.handleUpgrade(req, socket, head, (ws) => {
236
+ ws.close(RELAY_AUTH_REJECT_CLOSE_CODE, RELAY_AUTH_REJECT_REASON);
237
+ });
238
+ notifyAuthReject("ws-upgrade");
239
+ return;
240
+ }
241
+ for (const listener of chiiUpgradeListeners) listener(req, socket, head);
242
+ });
243
+ }
244
+ const actualPort = await new Promise((resolve, reject) => {
245
+ httpServer.once("error", reject);
246
+ httpServer.listen(requestedPort, host, () => {
247
+ httpServer.off("error", reject);
248
+ resolve(httpServer.address().port);
249
+ });
250
+ });
251
+ let keepaliveHandle = null;
252
+ if (keepaliveIntervalMs > 0 && capturedChiiWss !== null) {
253
+ const chiiWss = capturedChiiWss;
254
+ keepaliveHandle = setInterval(() => {
255
+ for (const client of chiiWss._wss.clients) if (client.readyState === 1) client.ping();
256
+ }, keepaliveIntervalMs);
257
+ }
258
+ return {
259
+ port: actualPort,
260
+ baseUrl: `http://${host}:${actualPort}`,
261
+ close: () => new Promise((resolve) => {
262
+ if (keepaliveHandle !== null) {
263
+ clearInterval(keepaliveHandle);
264
+ keepaliveHandle = null;
265
+ }
266
+ httpServer.close(() => resolve());
267
+ })
268
+ };
269
+ }
270
+ //#endregion
271
+ //#region src/mcp/debug-server.ts
272
+ /**
273
+ * Factory that constructs a `ChiiCdpConnection` for the given relay base URL.
274
+ *
275
+ * Introduced as a named seam so PR-2 (dual-connection, #348) can defer
276
+ * construction to first-activation time by moving or replacing this call. Since
277
+ * #396 every family (relay included) is constructed lazily on its first
278
+ * `start_debug`, so this is always called from the lazy boot path.
279
+ *
280
+ * The relay base URL is only available after `startChiiRelay()` resolves, so
281
+ * the factory is called right after that point (same as before this refactor).
282
+ */
283
+ function createRelayConnection(relayBaseUrl) {
284
+ return new ChiiCdpConnection({
285
+ relayBaseUrl,
286
+ totpSecret: process.env.AIT_DEBUG_TOTP_SECRET
287
+ });
288
+ }
289
+ /**
290
+ * Boots the relay family (issues #348, #356): starts the Chii relay on an
291
+ * OS-assigned port (with optional TOTP gate), opens a cloudflared quick tunnel
292
+ * to the relay's confirmed port in the background, prints the attach banner,
293
+ * and arms the tunnel health probe. Returns a {@link BootedFamily} whose
294
+ * `getTunnelStatus()` reflects the live tunnel (it flips up once the background
295
+ * tunnel resolves and follows reissues).
296
+ *
297
+ * Booted lazily via the dual router's `bootLazyFor('relay-intoss')` callback
298
+ * (symmetry with {@link bootLocalFamily}), at most once on the first
299
+ * `start_debug({ mode: 'relay-staging' })` (all-lazy, #396 — every relay boot now
300
+ * flows through `switchMode` after the project-local secret load). `relay-live`
301
+ * removed (#665).
302
+ *
303
+ * The relay base URL is only known after `startChiiRelay()` resolves, so the
304
+ * `ChiiCdpConnection` (via {@link createRelayConnection}) is constructed inside
305
+ * this function, after the relay port is confirmed.
306
+ *
307
+ * SECRET-HANDLING: the TOTP secret rides only inside `verifyAuth`; the wssUrl
308
+ * (relay host) is never logged here directly.
309
+ */
310
+ async function bootRelayFamily(options = {}) {
311
+ assertRelayAuthConfigured();
312
+ const relayPort = options.relayPort ?? 0;
313
+ const totpEnabled = options.verifyAuth !== void 0;
314
+ const relay = await startChiiRelay({
315
+ port: relayPort,
316
+ verifyAuth: options.verifyAuth,
317
+ onAuthReject: options.onAuthReject
318
+ });
319
+ logInfo("server.start", {
320
+ port: relay.port,
321
+ totpEnabled
322
+ });
323
+ let tunnel = null;
324
+ let tunnelStatus = makeTunnelStatus(false, null);
325
+ let tunnelProbe = null;
326
+ generateAttachToken();
327
+ startQuickTunnel(relay.port).then((t) => {
328
+ tunnel = t;
329
+ tunnelStatus = makeTunnelStatus(true, t.wssUrl);
330
+ options.onWssUrl?.(t.wssUrl);
331
+ if (t.childPid !== void 0) options.onTunnelChildPid?.(t.childPid);
332
+ logInfo("tunnel.up", { totpEnabled });
333
+ tunnelProbe = startTunnelHealthProbe(t, relay.port, {
334
+ onReissue: (newTunnel) => {
335
+ tunnel = newTunnel;
336
+ tunnelStatus = makeTunnelStatus(true, newTunnel.wssUrl, null, 0);
337
+ options.onWssUrl?.(newTunnel.wssUrl);
338
+ if (newTunnel.childPid !== void 0) options.onTunnelChildPid?.(newTunnel.childPid);
339
+ printAttachBanner({
340
+ wssUrl: newTunnel.wssUrl,
341
+ totpEnabled
342
+ }).then(() => {
343
+ logInfo("tunnel.up", {
344
+ totpEnabled,
345
+ reissued: true
346
+ });
347
+ });
348
+ },
349
+ onPermanentDrop: (droppedAt) => {
350
+ tunnelStatus = makeTunnelStatus(false, null, droppedAt, 3);
351
+ logError("tunnel.down", { msg: `tunnel permanently dropped (${droppedAt}). Restart: npx @ait-co/devtools devtools-mcp` });
352
+ options.onTunnelDown?.();
353
+ }
354
+ });
355
+ return printAttachBanner({
356
+ wssUrl: t.wssUrl,
357
+ totpEnabled
358
+ });
359
+ }, (err) => {
360
+ logError("tunnel.down", { msg: `Failed to open cloudflared quick tunnel: ${err instanceof Error ? err.message : String(err)}. The relay is up locally; attach over the public URL is unavailable until the tunnel starts.` });
361
+ });
362
+ const connection = createRelayConnection(relay.baseUrl);
363
+ return {
364
+ connection,
365
+ relayOrigin: "intoss-webview",
366
+ relayHttpUrl: relay.baseUrl,
367
+ getTunnelStatus: () => tunnelStatus,
368
+ stop() {
369
+ tunnelProbe?.stop();
370
+ tunnel?.stop();
371
+ connection.close();
372
+ relay.close();
373
+ }
374
+ };
375
+ }
376
+ //#endregion
377
+ export { bootRelayFamily, buildRelayVerifyAuth };
378
+
379
+ //# sourceMappingURL=debug-server-CD4zYBq4.js.map