@ait-co/devtools 0.1.127 → 0.1.129
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attach-orchestrator-CpE0dMew.js → attach-orchestrator-Bdt5Zdo9.js} +3 -94
- package/dist/attach-orchestrator-Bdt5Zdo9.js.map +1 -0
- package/dist/{attach-orchestrator-CPMQWkGV.js → attach-orchestrator-DvrgUIx7.js} +4 -95
- package/dist/attach-orchestrator-DvrgUIx7.js.map +1 -0
- package/dist/{bundle-Cb3GFuw6.d.ts → bundle-BKqyhEK9.d.ts} +1 -1
- package/dist/{bundle-Cb3GFuw6.d.ts.map → bundle-BKqyhEK9.d.ts.map} +1 -1
- package/dist/{capture-B1zfGyTo.d.ts → capture-ltuV0gZa.d.ts} +1 -1
- package/dist/{capture-B1zfGyTo.d.ts.map → capture-ltuV0gZa.d.ts.map} +1 -1
- package/dist/{cdp-connection-Dxw_EY8s.d.ts → cdp-connection-D7AYQck2.d.ts} +1 -1
- package/dist/{cdp-connection-Dxw_EY8s.d.ts.map → cdp-connection-D7AYQck2.d.ts.map} +1 -1
- package/dist/{cell-D0dJSGHi.js → cell-DA_lcpDI.js} +2 -2
- package/dist/{cell-D0dJSGHi.js.map → cell-DA_lcpDI.js.map} +1 -1
- package/dist/{cell-CX92lDI0.js → cell-DLRv4iG6.js} +2 -2
- package/dist/{cell-CX92lDI0.js.map → cell-DLRv4iG6.js.map} +1 -1
- package/dist/{debug-server-Dctc9GAh.js → debug-server--Y0QZVJS.js} +57 -58
- package/dist/debug-server--Y0QZVJS.js.map +1 -0
- package/dist/debug-server-Bu3pCG9c.js +436 -0
- package/dist/debug-server-Bu3pCG9c.js.map +1 -0
- package/dist/debug-server-e1qPe0ZB.js +379 -0
- package/dist/{debug-server-BzzNkETg.js.map → debug-server-e1qPe0ZB.js.map} +1 -1
- package/dist/log-CUik_tHp.js +95 -0
- package/dist/log-CUik_tHp.js.map +1 -0
- package/dist/mcp/cli.js +1296 -1230
- package/dist/mcp/cli.js.map +1 -1
- package/dist/mcp/server.js +1 -1
- package/dist/panel/index.js +1 -1
- package/dist/{pool-DBLKNeRC.d.ts → pool-C0pc7T2p.d.ts} +4 -4
- package/dist/{pool-DBLKNeRC.d.ts.map → pool-C0pc7T2p.d.ts.map} +1 -1
- package/dist/{qr-http-server-Bo8LMOJQ.js → qr-http-server-HANhOFwI.js} +1 -1
- package/dist/{qr-http-server-Bo8LMOJQ.js.map → qr-http-server-HANhOFwI.js.map} +1 -1
- package/dist/{relay-factory-Dug7W6Ao.js → relay-factory-Ck3vBonr.js} +6 -6
- package/dist/{relay-factory-Dug7W6Ao.js.map → relay-factory-Ck3vBonr.js.map} +1 -1
- package/dist/{relay-secret-store-DKxs7zwq.js → relay-secret-store-DzxDsK6S.js} +1 -1
- package/dist/{relay-secret-store-DKxs7zwq.js.map → relay-secret-store-DzxDsK6S.js.map} +1 -1
- package/dist/{relay-url-store-xmUuTjXA.js → relay-url-store-D3rY-GJJ.js} +2 -2
- package/dist/{relay-url-store-xmUuTjXA.js.map → relay-url-store-D3rY-GJJ.js.map} +1 -1
- package/dist/{debug-server-BzzNkETg.js → relay-worker-Bt0QYKQH.js} +212 -346
- package/dist/relay-worker-Bt0QYKQH.js.map +1 -0
- package/dist/{relay-worker-TReZtzGl.d.ts → relay-worker-o0M2ndyJ.d.ts} +7 -7
- package/dist/relay-worker-o0M2ndyJ.d.ts.map +1 -0
- package/dist/{runtime-ozyPnRbU.d.ts → runtime-9xhN9pr8.d.ts} +1 -1
- package/dist/{runtime-ozyPnRbU.d.ts.map → runtime-9xhN9pr8.d.ts.map} +1 -1
- package/dist/test-runner/bin.js +721 -15
- package/dist/test-runner/bin.js.map +1 -1
- package/dist/test-runner/bundle.d.ts +1 -1
- package/dist/test-runner/capture.d.ts +1 -1
- package/dist/test-runner/config.d.ts +1 -1
- package/dist/test-runner/config.js +1 -1
- package/dist/test-runner/pool.d.ts +1 -1
- package/dist/test-runner/pool.js +1 -1
- package/dist/test-runner/relay-factory.d.ts +1 -1
- package/dist/test-runner/relay-factory.js +1 -1
- package/dist/test-runner/relay-worker.d.ts +1 -1
- package/dist/test-runner/relay-worker.js +1 -183
- package/dist/test-runner/report.d.ts +3 -3
- package/dist/test-runner/rpc.d.ts +2 -2
- package/dist/test-runner/rpc.js +12 -3
- package/dist/test-runner/rpc.js.map +1 -1
- package/dist/test-runner/runtime.d.ts +1 -1
- package/dist/test-runner/task-graph.d.ts +1 -1
- package/package.json +1 -1
- package/dist/attach-orchestrator-CPMQWkGV.js.map +0 -1
- package/dist/attach-orchestrator-CpE0dMew.js.map +0 -1
- package/dist/debug-server-1dhDA3aw.js +0 -980
- package/dist/debug-server-1dhDA3aw.js.map +0 -1
- package/dist/debug-server-Dctc9GAh.js.map +0 -1
- package/dist/relay-worker-TReZtzGl.d.ts.map +0 -1
- package/dist/test-runner/relay-worker.js.map +0 -1
|
@@ -1,980 +0,0 @@
|
|
|
1
|
-
import { n as buildRelayVerifyAuth, r as generateTotp, t as assertRelayAuthConfigured } from "./totp-DfekTBk3.js";
|
|
2
|
-
import "./test-runner/relay-worker.js";
|
|
3
|
-
import "./relay-factory-Dug7W6Ao.js";
|
|
4
|
-
import { a as startTunnelHealthProbe, i as startQuickTunnel, n as makeTunnelStatus, o as logError, r as printAttachBanner, s as logInfo, t as generateAttachToken } from "./attach-orchestrator-CPMQWkGV.js";
|
|
5
|
-
import "./cell-D0dJSGHi.js";
|
|
6
|
-
import "./qr-http-server-Bo8LMOJQ.js";
|
|
7
|
-
import "./relay-secret-store-DKxs7zwq.js";
|
|
8
|
-
import { createRequire } from "node:module";
|
|
9
|
-
import "@modelcontextprotocol/sdk/server/index.js";
|
|
10
|
-
import "@modelcontextprotocol/sdk/server/stdio.js";
|
|
11
|
-
import "@modelcontextprotocol/sdk/types.js";
|
|
12
|
-
import { EventEmitter } from "node:events";
|
|
13
|
-
import { WebSocket, WebSocketServer } from "ws";
|
|
14
|
-
import { createServer } from "node:http";
|
|
15
|
-
`
|
|
16
|
-
devtools-test — run mini-app tests on a real device WebView over the CDP relay
|
|
17
|
-
|
|
18
|
-
USAGE
|
|
19
|
-
devtools-test <glob> [<glob> ...] [options]
|
|
20
|
-
|
|
21
|
-
OPTIONS
|
|
22
|
-
--scheme-url <url> intoss-private:// URL from \`ait deploy --scheme-only\`
|
|
23
|
-
(required for standalone relay attach / env3)
|
|
24
|
-
--timeout <ms> Per-file evaluate timeout in ms (default: 30000).
|
|
25
|
-
Controls how long a single test file is allowed to run
|
|
26
|
-
before it is considered hung. Does NOT affect how long
|
|
27
|
-
the CLI waits for a human to scan the QR code — use
|
|
28
|
-
--attach-timeout for that.
|
|
29
|
-
--attach-timeout <ms> How long to wait for a human to scan the QR code with
|
|
30
|
-
their phone (default: 600000 — 10 minutes). Omit to
|
|
31
|
-
use the relay factory's generous default. Decrease for
|
|
32
|
-
CI environments where a scan should arrive quickly.
|
|
33
|
-
--cell-sdk-line <line> SDK line to inject as __AIT_CELL__.sdkLine (2.x|3.x)
|
|
34
|
-
--cell-platform <plat> Platform to inject as __AIT_CELL__.platform
|
|
35
|
-
(mock|ios|android, default: AIT_CELL_PLATFORM env)
|
|
36
|
-
--report-dir <dir> Persist a runner-agnostic report + captures to <dir>
|
|
37
|
-
(report: <sdkLine>.<platform>.json; captures:
|
|
38
|
-
<dir>/.ait-capture/<category>.<sdkLine>.<platform>.json).
|
|
39
|
-
Omitted = nothing saved. Enables console capture.
|
|
40
|
-
--no-qr-stdout Suppress the QR/attach block on stdout (auto-on for
|
|
41
|
-
non-interactive stdout / CI / AIT_NO_QR_STDOUT)
|
|
42
|
-
--headless Disable browser auto-open (text QR only)
|
|
43
|
-
--project-root <dir> Project root for .ait_relay secret lookup
|
|
44
|
-
(default: current working directory)
|
|
45
|
-
--help, -h Show this help message
|
|
46
|
-
|
|
47
|
-
DESCRIPTION
|
|
48
|
-
Boots a Chii relay + cloudflared tunnel, renders a QR code, waits for a real
|
|
49
|
-
device to scan and attach, injects the cell globals (__AIT_CELL__), bundles
|
|
50
|
-
each matched test file with esbuild (SDK imports redirected to window.__sdk),
|
|
51
|
-
injects the bundle into the attached WebView via Runtime.evaluate, and prints
|
|
52
|
-
a summary.
|
|
53
|
-
|
|
54
|
-
With --report-dir, also harvests __AIT_CAPTURE__ console lines and writes a
|
|
55
|
-
runner-agnostic report + per-category capture files so 2.x↔3.0 runs can be
|
|
56
|
-
compared offline.
|
|
57
|
-
|
|
58
|
-
The test files run against the live relay connection started by this process;
|
|
59
|
-
no separate MCP daemon is required.
|
|
60
|
-
|
|
61
|
-
EXAMPLE
|
|
62
|
-
devtools-test 'src/**/*.ait.test.ts' \\
|
|
63
|
-
--scheme-url "intoss-private://..." \\
|
|
64
|
-
--cell-sdk-line 3.x \\
|
|
65
|
-
--cell-platform ios \\
|
|
66
|
-
--report-dir .ait-report \\
|
|
67
|
-
--timeout 60000
|
|
68
|
-
|
|
69
|
-
`.trimStart();
|
|
70
|
-
//#endregion
|
|
71
|
-
//#region src/shared/relay-auth-close.ts
|
|
72
|
-
/**
|
|
73
|
-
* Shared constants for the relay's named TOTP-auth rejection (issue #478).
|
|
74
|
-
*
|
|
75
|
-
* Before #478 the relay rejected an unauthenticated WebSocket upgrade with a
|
|
76
|
-
* raw `HTTP/1.1 401` + `socket.destroy()`. A handshake aborted that way is
|
|
77
|
-
* indistinguishable from a network failure on the browser side — the
|
|
78
|
-
* WebSocket only ever sees close code 1006, so the phone (env-2 launcher PWA)
|
|
79
|
-
* could not tell "stale TOTP code" apart from "tunnel down" and stayed
|
|
80
|
-
* silent. The fix is accept-then-close: complete the handshake, then close
|
|
81
|
-
* with an application close code that NAMES the rejection.
|
|
82
|
-
*
|
|
83
|
-
* Three parties share this contract:
|
|
84
|
-
* - `src/mcp/chii-relay.ts` (Node) sends the close frame / HTTP error body;
|
|
85
|
-
* - `src/in-app/attach.ts` (browser) observes relay-bound WebSockets and
|
|
86
|
-
* surfaces the code to the launcher shell;
|
|
87
|
-
* - `src/mcp/chii-connection.ts` (Node daemon client) recognises the code
|
|
88
|
-
* as an auth failure on its own `/client` dial (defensive — #439's fresh
|
|
89
|
-
* code mint means it should not normally hit this).
|
|
90
|
-
*
|
|
91
|
-
* This module is intentionally dependency-free (no Node, no DOM) so it is
|
|
92
|
-
* safe to import from both the browser in-app bundle and the MCP daemon
|
|
93
|
-
* bundle.
|
|
94
|
-
*
|
|
95
|
-
* SECRET-HANDLING: these are fixed enum values. The close reason / error body
|
|
96
|
-
* must never grow to carry a secret, a TOTP code, or a host.
|
|
97
|
-
*/
|
|
98
|
-
/**
|
|
99
|
-
* WebSocket close code sent by the relay when TOTP auth is rejected.
|
|
100
|
-
*
|
|
101
|
-
* 4000–4999 is the application-reserved range (RFC 6455 §7.4.2); 4401 mirrors
|
|
102
|
-
* HTTP 401 so it reads as "unauthorized" at a glance.
|
|
103
|
-
*/
|
|
104
|
-
const RELAY_AUTH_REJECT_CLOSE_CODE = 4401;
|
|
105
|
-
/**
|
|
106
|
-
* Close reason string accompanying {@link RELAY_AUTH_REJECT_CLOSE_CODE}, and
|
|
107
|
-
* the `error` value of the relay's HTTP 401 JSON body. Enum string only —
|
|
108
|
-
* never interpolated with request data.
|
|
109
|
-
*/
|
|
110
|
-
const RELAY_AUTH_REJECT_REASON = "totp-rejected";
|
|
111
|
-
//#endregion
|
|
112
|
-
//#region src/mcp/chii-connection.ts
|
|
113
|
-
/**
|
|
114
|
-
* Production `CdpConnection` backed by the local Chii relay.
|
|
115
|
-
*
|
|
116
|
-
* Topology (debug mode):
|
|
117
|
-
* phone target.js --WS--> Chii relay :9100 <--WS-- this connection
|
|
118
|
-
*
|
|
119
|
-
* The phone connects to the relay as a `target`; this module connects as a
|
|
120
|
-
* `client` (the role a CDP frontend would take) so CDP events the page emits
|
|
121
|
-
* (`Runtime.consoleAPICalled`, `Network.*`) flow back here. We buffer recent
|
|
122
|
-
* events in ring buffers the tool layer reads via `getBufferedEvents`.
|
|
123
|
-
*
|
|
124
|
-
* Node-only: imports `ws`. Never bundled into the browser/in-app entries.
|
|
125
|
-
*
|
|
126
|
-
* Attach reliability (#281):
|
|
127
|
-
* `refreshTargets()` emits an internal 'target:attached' event whenever a
|
|
128
|
-
* new target is added to the relay. `waitForFirstTarget()` awaits that event
|
|
129
|
-
* (with a polling-interval fallback) so `start_attach`'s attach wait
|
|
130
|
-
* resolves deterministically rather than racing between polling rounds.
|
|
131
|
-
*/
|
|
132
|
-
/** Max events retained per domain ring buffer. */
|
|
133
|
-
const DEFAULT_BUFFER_SIZE = 500;
|
|
134
|
-
function isObject(value) {
|
|
135
|
-
return typeof value === "object" && value !== null;
|
|
136
|
-
}
|
|
137
|
-
function parseInbound(raw) {
|
|
138
|
-
let parsed;
|
|
139
|
-
try {
|
|
140
|
-
parsed = JSON.parse(raw);
|
|
141
|
-
} catch {
|
|
142
|
-
return null;
|
|
143
|
-
}
|
|
144
|
-
if (!isObject(parsed)) return null;
|
|
145
|
-
const message = {};
|
|
146
|
-
if (typeof parsed.id === "number") message.id = parsed.id;
|
|
147
|
-
if (typeof parsed.method === "string") message.method = parsed.method;
|
|
148
|
-
if ("params" in parsed) message.params = parsed.params;
|
|
149
|
-
if ("result" in parsed) message.result = parsed.result;
|
|
150
|
-
if (isObject(parsed.error) && typeof parsed.error.message === "string") message.error = { message: parsed.error.message };
|
|
151
|
-
return message;
|
|
152
|
-
}
|
|
153
|
-
const PHASE_1_EVENTS = [
|
|
154
|
-
"Runtime.consoleAPICalled",
|
|
155
|
-
"Network.requestWillBeSent",
|
|
156
|
-
"Network.responseReceived"
|
|
157
|
-
];
|
|
158
|
-
/**
|
|
159
|
-
* Ring buffer size for `Runtime.exceptionThrown`.
|
|
160
|
-
*
|
|
161
|
-
* Exceptions are rarer than console messages but each is heavier (stack
|
|
162
|
-
* trace). 50 is generous enough to cover a crash scenario while keeping
|
|
163
|
-
* memory bounded.
|
|
164
|
-
*
|
|
165
|
-
* **Lifecycle note**: the exception buffer intentionally survives `replaced` /
|
|
166
|
-
* `crashed` / `destroyed` lifecycle events — it is NOT cleared on target
|
|
167
|
-
* transitions. Rationale: an exception fired just before a crash is exactly
|
|
168
|
-
* the signal we want to preserve for root-cause analysis. The buffer
|
|
169
|
-
* represents "exceptions seen in this MCP session", not "exceptions in the
|
|
170
|
-
* current page".
|
|
171
|
-
*/
|
|
172
|
-
const EXCEPTION_BUFFER_SIZE = 50;
|
|
173
|
-
/** Default per-command timeout if neither option nor env var is set. */
|
|
174
|
-
const DEFAULT_COMMAND_TIMEOUT_MS = 3e4;
|
|
175
|
-
/**
|
|
176
|
-
* Production CDP connection. Polls the relay for the first attached target,
|
|
177
|
-
* opens a client websocket to it, enables Phase 1 domains, and buffers events.
|
|
178
|
-
*/
|
|
179
|
-
var ChiiCdpConnection = class {
|
|
180
|
-
/** Authoritative connection kind (issue #348) — relay-backed. */
|
|
181
|
-
kind = "relay";
|
|
182
|
-
relayBaseUrl;
|
|
183
|
-
bufferSize;
|
|
184
|
-
commandTimeoutMs;
|
|
185
|
-
totpSecret;
|
|
186
|
-
emitter = new EventEmitter();
|
|
187
|
-
buffers = /* @__PURE__ */ new Map();
|
|
188
|
-
targets = /* @__PURE__ */ new Map();
|
|
189
|
-
ws = null;
|
|
190
|
-
connectionState = "idle";
|
|
191
|
-
nextCommandId = 1;
|
|
192
|
-
/**
|
|
193
|
-
* The single active target id under the single-attach model.
|
|
194
|
-
* Updated by `refreshTargets()` whenever a non-null target is present.
|
|
195
|
-
* Used to detect a new (different) target attach and evict the previous one.
|
|
196
|
-
*/
|
|
197
|
-
activeTargetId = null;
|
|
198
|
-
/** In-flight enableDomains() promise — concurrent callers share it. */
|
|
199
|
-
enablingPromise = null;
|
|
200
|
-
/** Pending request→response commands keyed by CDP message id. */
|
|
201
|
-
pending = /* @__PURE__ */ new Map();
|
|
202
|
-
/**
|
|
203
|
-
* Timestamp (ms since epoch) of the most recent crash/destroy/detach event,
|
|
204
|
-
* or `null` if no crash has been detected since the last `enableDomains()`.
|
|
205
|
-
*/
|
|
206
|
-
lastCrashDetectedAt = null;
|
|
207
|
-
/**
|
|
208
|
-
* Per-target last-seen timestamp (ms since epoch). Updated on any inbound
|
|
209
|
-
* CDP message carrying data from a target. Keyed by target id.
|
|
210
|
-
*/
|
|
211
|
-
targetLastSeenAt = /* @__PURE__ */ new Map();
|
|
212
|
-
/** Active heartbeat interval handle (only when `AIT_CDP_HEARTBEAT_MS` is set). */
|
|
213
|
-
heartbeatHandle = null;
|
|
214
|
-
/** Lifecycle event listeners (crash / destroyed / detached). */
|
|
215
|
-
lifecycleListeners = [];
|
|
216
|
-
constructor(options) {
|
|
217
|
-
this.relayBaseUrl = options.relayBaseUrl.replace(/\/$/, "");
|
|
218
|
-
this.bufferSize = options.bufferSize ?? DEFAULT_BUFFER_SIZE;
|
|
219
|
-
this.totpSecret = options.totpSecret;
|
|
220
|
-
const envMs = process.env.AIT_CDP_COMMAND_TIMEOUT_MS ? Number(process.env.AIT_CDP_COMMAND_TIMEOUT_MS) : void 0;
|
|
221
|
-
this.commandTimeoutMs = (envMs !== void 0 && Number.isFinite(envMs) && envMs > 0 ? envMs : void 0) ?? options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
|
|
222
|
-
for (const event of PHASE_1_EVENTS) this.buffers.set(event, []);
|
|
223
|
-
this.buffers.set("Runtime.exceptionThrown", []);
|
|
224
|
-
this.emitter.setMaxListeners(0);
|
|
225
|
-
}
|
|
226
|
-
/** Refresh the attached-target list from the relay's `GET /targets`. */
|
|
227
|
-
async refreshTargets() {
|
|
228
|
-
let targetsUrl = `${this.relayBaseUrl}/targets`;
|
|
229
|
-
if (this.totpSecret) {
|
|
230
|
-
const code = generateTotp(this.totpSecret);
|
|
231
|
-
targetsUrl += `?at=${encodeURIComponent(code)}`;
|
|
232
|
-
}
|
|
233
|
-
const res = await fetch(targetsUrl);
|
|
234
|
-
if (!res.ok) throw new Error(`Chii relay /targets returned HTTP ${res.status} ${res.statusText}`);
|
|
235
|
-
const body = await res.json();
|
|
236
|
-
const list = isObject(body) && Array.isArray(body.targets) ? body.targets : [];
|
|
237
|
-
let newestTargetId = null;
|
|
238
|
-
for (const item of list) {
|
|
239
|
-
if (!isObject(item) || typeof item.id !== "string") continue;
|
|
240
|
-
newestTargetId = item.id;
|
|
241
|
-
}
|
|
242
|
-
if (newestTargetId !== null && this.activeTargetId !== null && newestTargetId !== this.activeTargetId) {
|
|
243
|
-
const prevId = this.activeTargetId;
|
|
244
|
-
logInfo("page.detached", { prevTargetId: prevId });
|
|
245
|
-
this.evictTarget(prevId);
|
|
246
|
-
}
|
|
247
|
-
this.targets.clear();
|
|
248
|
-
for (const item of list) {
|
|
249
|
-
if (!isObject(item) || typeof item.id !== "string") continue;
|
|
250
|
-
if (item.id !== newestTargetId) continue;
|
|
251
|
-
this.targets.set(item.id, {
|
|
252
|
-
id: item.id,
|
|
253
|
-
title: typeof item.title === "string" ? item.title : "",
|
|
254
|
-
url: typeof item.url === "string" ? item.url : ""
|
|
255
|
-
});
|
|
256
|
-
}
|
|
257
|
-
if (newestTargetId !== null) this.activeTargetId = newestTargetId;
|
|
258
|
-
else this.activeTargetId = null;
|
|
259
|
-
const result = [...this.targets.values()];
|
|
260
|
-
if (newestTargetId !== null) this.emitter.emit("target:attached", result);
|
|
261
|
-
return result;
|
|
262
|
-
}
|
|
263
|
-
listTargets() {
|
|
264
|
-
return [...this.targets.values()];
|
|
265
|
-
}
|
|
266
|
-
/**
|
|
267
|
-
* Waits until at least one target matching `filterFn` is attached, then
|
|
268
|
-
* resolves with the full target list at that moment.
|
|
269
|
-
*
|
|
270
|
-
* Resolution happens on whichever comes first:
|
|
271
|
-
* (a) a `'target:attached'` event from `refreshTargets()` (triggered by
|
|
272
|
-
* the /targets poll finding a new target), OR
|
|
273
|
-
* (b) a `'target:attached'` event from `handleMessage()` (triggered by
|
|
274
|
-
* the first inbound CDP message from a target — confirms the relay
|
|
275
|
-
* websocket has data from the phone, not just a target entry in the map).
|
|
276
|
-
*
|
|
277
|
-
* This dual-signal approach eliminates the polling race that previously
|
|
278
|
-
* caused `wait_for_attach` to resolve before the first CDP message arrived.
|
|
279
|
-
*
|
|
280
|
-
* Falls back to checking `listTargets()` every `pollIntervalMs` in case the
|
|
281
|
-
* EventEmitter is missed (defensive belt-and-suspenders).
|
|
282
|
-
*
|
|
283
|
-
* @param filterFn - Predicate that the returned targets must satisfy.
|
|
284
|
-
* @param timeoutMs - Reject after this many ms (default 90 000).
|
|
285
|
-
* @param pollIntervalMs - Fallback poll interval (default 500ms).
|
|
286
|
-
*/
|
|
287
|
-
waitForFirstTarget(filterFn, timeoutMs = 9e4, pollIntervalMs = 500) {
|
|
288
|
-
const current = this.listTargets();
|
|
289
|
-
if (filterFn(current)) return Promise.resolve(current);
|
|
290
|
-
return new Promise((resolve, reject) => {
|
|
291
|
-
let settled = false;
|
|
292
|
-
let pollHandle = null;
|
|
293
|
-
const settle = (targets) => {
|
|
294
|
-
if (settled) return;
|
|
295
|
-
settled = true;
|
|
296
|
-
clearTimeout(timeoutHandle);
|
|
297
|
-
if (pollHandle !== null) {
|
|
298
|
-
clearInterval(pollHandle);
|
|
299
|
-
pollHandle = null;
|
|
300
|
-
}
|
|
301
|
-
this.emitter.off("target:attached", onAttach);
|
|
302
|
-
resolve(targets);
|
|
303
|
-
};
|
|
304
|
-
const onAttach = (targets) => {
|
|
305
|
-
if (filterFn(targets)) settle(targets);
|
|
306
|
-
};
|
|
307
|
-
const timeoutHandle = setTimeout(() => {
|
|
308
|
-
if (settled) return;
|
|
309
|
-
settled = true;
|
|
310
|
-
if (pollHandle !== null) {
|
|
311
|
-
clearInterval(pollHandle);
|
|
312
|
-
pollHandle = null;
|
|
313
|
-
}
|
|
314
|
-
this.emitter.off("target:attached", onAttach);
|
|
315
|
-
reject(/* @__PURE__ */ new Error(`waitForFirstTarget: 타임아웃 (${timeoutMs}ms) — 폰이 relay에 attach되지 않았습니다.`));
|
|
316
|
-
}, timeoutMs);
|
|
317
|
-
this.emitter.on("target:attached", onAttach);
|
|
318
|
-
pollHandle = setInterval(() => {
|
|
319
|
-
this.refreshTargets().then((targets) => {
|
|
320
|
-
if (filterFn(targets)) settle(targets);
|
|
321
|
-
}, () => {});
|
|
322
|
-
}, pollIntervalMs);
|
|
323
|
-
});
|
|
324
|
-
}
|
|
325
|
-
/**
|
|
326
|
-
* Timestamp (ms since epoch) of the most recent crash/destroy/detach event
|
|
327
|
-
* detected since the last `enableDomains()` call, or `null` if none.
|
|
328
|
-
*/
|
|
329
|
-
getLastCrashDetectedAt() {
|
|
330
|
-
return this.lastCrashDetectedAt;
|
|
331
|
-
}
|
|
332
|
-
/**
|
|
333
|
-
* Last-seen timestamp (ms since epoch) for a given target id, or `null` if
|
|
334
|
-
* the target is unknown / no message has been received from it yet.
|
|
335
|
-
*/
|
|
336
|
-
getTargetLastSeenAt(targetId) {
|
|
337
|
-
return this.targetLastSeenAt.get(targetId) ?? null;
|
|
338
|
-
}
|
|
339
|
-
/** Subscribe to target lifecycle events (crash / destroyed / detached). */
|
|
340
|
-
onLifecycle(listener) {
|
|
341
|
-
this.lifecycleListeners.push(listener);
|
|
342
|
-
return () => {
|
|
343
|
-
const idx = this.lifecycleListeners.indexOf(listener);
|
|
344
|
-
if (idx !== -1) this.lifecycleListeners.splice(idx, 1);
|
|
345
|
-
};
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* Connect a client websocket to the first attached target and enable Phase 1
|
|
349
|
-
* domains. Resolves once the socket is open and enable commands are sent.
|
|
350
|
-
*/
|
|
351
|
-
async enableDomains() {
|
|
352
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
|
|
353
|
-
if (this.enablingPromise) return this.enablingPromise;
|
|
354
|
-
this.enablingPromise = this._doEnableDomains().finally(() => {
|
|
355
|
-
this.enablingPromise = null;
|
|
356
|
-
});
|
|
357
|
-
return this.enablingPromise;
|
|
358
|
-
}
|
|
359
|
-
async _doEnableDomains() {
|
|
360
|
-
const target = (await this.refreshTargets())[0];
|
|
361
|
-
if (!target) throw new Error("No mini-app page attached to the Chii relay yet.");
|
|
362
|
-
let clientUrl = `${this.relayBaseUrl.replace(/^http/, "ws")}/client/${`devtools-mcp-${Date.now()}`}?target=${encodeURIComponent(target.id)}`;
|
|
363
|
-
if (this.totpSecret) {
|
|
364
|
-
const code = generateTotp(this.totpSecret);
|
|
365
|
-
clientUrl += `&at=${encodeURIComponent(code)}`;
|
|
366
|
-
}
|
|
367
|
-
const ws = new WebSocket(clientUrl);
|
|
368
|
-
this.ws = ws;
|
|
369
|
-
await new Promise((resolve, reject) => {
|
|
370
|
-
ws.once("open", () => resolve());
|
|
371
|
-
ws.once("error", (err) => reject(err));
|
|
372
|
-
ws.once("close", (code) => {
|
|
373
|
-
if (code === 4401) reject(/* @__PURE__ */ new Error("relay 인증(TOTP)이 거부됐습니다 (close 4401). 코드가 만료됐을 수 있습니다 — 재연결 시 새 코드가 발급됩니다."));
|
|
374
|
-
});
|
|
375
|
-
});
|
|
376
|
-
this.lastCrashDetectedAt = null;
|
|
377
|
-
this.targetLastSeenAt.clear();
|
|
378
|
-
this.connectionState = "connected";
|
|
379
|
-
ws.on("message", (data) => this.handleMessage(data.toString()));
|
|
380
|
-
ws.on("close", (code) => this.handleDisconnect(code === 4401 ? "relay 인증(TOTP)이 거부돼 연결이 종료됐습니다 (close 4401)" : "relay WebSocket 연결이 끊겼습니다"));
|
|
381
|
-
ws.on("error", (err) => this.handleDisconnect(`relay WebSocket 오류: ${err.message}`));
|
|
382
|
-
this.sendFireAndForget("Runtime.enable");
|
|
383
|
-
this.sendFireAndForget("Network.enable");
|
|
384
|
-
this.sendFireAndForget("DOM.enable");
|
|
385
|
-
this.sendFireAndForget("Page.enable");
|
|
386
|
-
this.sendFireAndForget("Inspector.enable");
|
|
387
|
-
this.sendFireAndForget("Target.setDiscoverTargets", { discover: true });
|
|
388
|
-
this.startHeartbeat(target.id);
|
|
389
|
-
}
|
|
390
|
-
/** Fire-and-forget CDP message (used for `*.enable`, no result awaited). */
|
|
391
|
-
sendFireAndForget(method, params = {}) {
|
|
392
|
-
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
|
|
393
|
-
const id = this.nextCommandId++;
|
|
394
|
-
this.ws.send(JSON.stringify({
|
|
395
|
-
id,
|
|
396
|
-
method,
|
|
397
|
-
params
|
|
398
|
-
}));
|
|
399
|
-
}
|
|
400
|
-
/**
|
|
401
|
-
* Issue a CDP command and resolve with its result (Phase 2). Rejects on a CDP
|
|
402
|
-
* error frame or when no websocket is open (no page attached yet).
|
|
403
|
-
*/
|
|
404
|
-
send(method, params) {
|
|
405
|
-
return this.sendCommand(method, params ?? {});
|
|
406
|
-
}
|
|
407
|
-
/**
|
|
408
|
-
* Issue an arbitrary request→response command over the relay and resolve with
|
|
409
|
-
* its raw result. Both the typed CDP {@link send} and the AIT domain (Phase 3
|
|
410
|
-
* `AIT.*` methods, forwarded over the same Chii channel) build on this.
|
|
411
|
-
*
|
|
412
|
-
* Rejects immediately if the connection is disconnected (fail-fast — no
|
|
413
|
-
* auto-reconnect). Caller should re-run `list_pages` or `enableDomains` to
|
|
414
|
-
* reattach.
|
|
415
|
-
*
|
|
416
|
-
* Times out after `commandTimeoutMs` (default 30s, env
|
|
417
|
-
* `AIT_CDP_COMMAND_TIMEOUT_MS`). On timeout the pending entry is cleaned up
|
|
418
|
-
* and the promise rejects with a descriptive Korean error.
|
|
419
|
-
*/
|
|
420
|
-
sendCommand(method, params = {}) {
|
|
421
|
-
if (this.connectionState === "disconnected") return Promise.reject(/* @__PURE__ */ new Error(`relay에 연결되어 있지 않습니다 (${method}). list_pages로 attach 상태를 확인하고 enableDomains()로 재연결하세요.`));
|
|
422
|
-
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return Promise.reject(/* @__PURE__ */ new Error("No mini-app page attached to the Chii relay yet. Call enableDomains() first."));
|
|
423
|
-
const id = this.nextCommandId++;
|
|
424
|
-
const ws = this.ws;
|
|
425
|
-
const timeoutMs = this.commandTimeoutMs;
|
|
426
|
-
return new Promise((resolve, reject) => {
|
|
427
|
-
const handle = setTimeout(() => {
|
|
428
|
-
this.pending.delete(id);
|
|
429
|
-
reject(/* @__PURE__ */ new Error(`CDP 명령이 타임아웃됐습니다 (${method}, ${timeoutMs}ms). 폰 측 토스 앱이 백그라운드로 내려갔거나 미니앱이 unload됐을 수 있습니다. list_pages로 attach 상태를 확인하세요.`));
|
|
430
|
-
}, timeoutMs);
|
|
431
|
-
this.pending.set(id, {
|
|
432
|
-
resolve: (v) => {
|
|
433
|
-
clearTimeout(handle);
|
|
434
|
-
resolve(v);
|
|
435
|
-
},
|
|
436
|
-
reject: (e) => {
|
|
437
|
-
clearTimeout(handle);
|
|
438
|
-
reject(e);
|
|
439
|
-
}
|
|
440
|
-
});
|
|
441
|
-
ws.send(JSON.stringify({
|
|
442
|
-
id,
|
|
443
|
-
method,
|
|
444
|
-
params
|
|
445
|
-
}));
|
|
446
|
-
});
|
|
447
|
-
}
|
|
448
|
-
/**
|
|
449
|
-
* Called on WebSocket `close` or `error` after a successful connection.
|
|
450
|
-
* Rejects all pending commands and marks the connection as disconnected so
|
|
451
|
-
* subsequent `sendCommand` calls fail fast (no auto-reconnect).
|
|
452
|
-
*/
|
|
453
|
-
handleDisconnect(reason) {
|
|
454
|
-
if (this.connectionState === "disconnected") return;
|
|
455
|
-
this.connectionState = "disconnected";
|
|
456
|
-
this.ws = null;
|
|
457
|
-
this.stopHeartbeat();
|
|
458
|
-
const err = /* @__PURE__ */ new Error(`${reason}. list_pages로 attach 상태를 확인하고 enableDomains()로 재연결하세요.`);
|
|
459
|
-
for (const waiter of this.pending.values()) waiter.reject(err);
|
|
460
|
-
this.pending.clear();
|
|
461
|
-
}
|
|
462
|
-
/**
|
|
463
|
-
* Evict a previously active target under the single-attach model.
|
|
464
|
-
* Rejects pending commands with a 'replaced-by-new-attach' reason and emits
|
|
465
|
-
* a 'replaced' lifecycle event. Does NOT clear all targets — only the specific
|
|
466
|
-
* targetId. The caller is responsible for rebuilding the targets map afterwards.
|
|
467
|
-
*
|
|
468
|
-
* The error message uses 'replaced-by-new-attach' so test assertions can match it.
|
|
469
|
-
*/
|
|
470
|
-
evictTarget(targetId) {
|
|
471
|
-
const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
472
|
-
this.targets.delete(targetId);
|
|
473
|
-
this.targetLastSeenAt.delete(targetId);
|
|
474
|
-
const err = /* @__PURE__ */ new Error(`[ait-debug] replaced-by-new-attach — 이전 page 세션이 새 attach로 교체됐습니다 (targetId=${targetId}). list_pages로 현재 attach 상태를 확인하세요.`);
|
|
475
|
-
for (const waiter of this.pending.values()) waiter.reject(err);
|
|
476
|
-
this.pending.clear();
|
|
477
|
-
const event = {
|
|
478
|
-
kind: "replaced",
|
|
479
|
-
targetId,
|
|
480
|
-
detectedAt
|
|
481
|
-
};
|
|
482
|
-
for (const listener of this.lifecycleListeners) try {
|
|
483
|
-
listener(event);
|
|
484
|
-
} catch {}
|
|
485
|
-
}
|
|
486
|
-
/**
|
|
487
|
-
* Handle a page-level crash or target destruction event.
|
|
488
|
-
* Removes the target from the in-memory map, rejects all pending commands,
|
|
489
|
-
* and emits a lifecycle event.
|
|
490
|
-
*
|
|
491
|
-
* @param kind - Event kind: 'crashed' | 'destroyed' | 'detached'
|
|
492
|
-
* @param targetId - The target ID from the event params (may be null for
|
|
493
|
-
* Inspector.targetCrashed which has no targetId in the params).
|
|
494
|
-
*/
|
|
495
|
-
handleTargetGone(kind, targetId) {
|
|
496
|
-
const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
497
|
-
this.lastCrashDetectedAt = Date.now();
|
|
498
|
-
if (targetId !== null) {
|
|
499
|
-
this.targets.delete(targetId);
|
|
500
|
-
this.targetLastSeenAt.delete(targetId);
|
|
501
|
-
if (this.activeTargetId === targetId) this.activeTargetId = null;
|
|
502
|
-
} else {
|
|
503
|
-
this.targets.clear();
|
|
504
|
-
this.targetLastSeenAt.clear();
|
|
505
|
-
this.activeTargetId = null;
|
|
506
|
-
}
|
|
507
|
-
const err = /* @__PURE__ */ new Error(`[ait-debug] ${kind === "crashed" ? "page crash (Inspector.targetCrashed)" : kind === "destroyed" ? "target 종료 (Target.targetDestroyed)" : "target detach (Target.detachedFromTarget)"} 감지됨 — relay에서 제거됐습니다. 새 attach가 필요합니다 (list_pages로 확인 → enableDomains()로 재연결).`);
|
|
508
|
-
for (const waiter of this.pending.values()) waiter.reject(err);
|
|
509
|
-
this.pending.clear();
|
|
510
|
-
const event = {
|
|
511
|
-
kind,
|
|
512
|
-
targetId,
|
|
513
|
-
detectedAt
|
|
514
|
-
};
|
|
515
|
-
for (const listener of this.lifecycleListeners) try {
|
|
516
|
-
listener(event);
|
|
517
|
-
} catch {}
|
|
518
|
-
}
|
|
519
|
-
/**
|
|
520
|
-
* Start the optional CDP heartbeat loop.
|
|
521
|
-
*
|
|
522
|
-
* When `AIT_CDP_HEARTBEAT_MS` is set to a positive integer, every interval
|
|
523
|
-
* we send `Runtime.evaluate({expression: '1'})` to each active target. If
|
|
524
|
-
* the command times out (2 s hard deadline) or errors, we treat the target
|
|
525
|
-
* as dead and call `handleTargetGone`.
|
|
526
|
-
*
|
|
527
|
-
* This is a zombie-detector fallback: cloudflared keeps-alive the tunnel ws
|
|
528
|
-
* even when the phone app has crashed, so the ws-level disconnect (#252) won't
|
|
529
|
-
* fire. The heartbeat catches this gap.
|
|
530
|
-
*
|
|
531
|
-
* Default: OFF. Only activates when `AIT_CDP_HEARTBEAT_MS` is set.
|
|
532
|
-
*/
|
|
533
|
-
startHeartbeat(initialTargetId) {
|
|
534
|
-
this.stopHeartbeat();
|
|
535
|
-
const envMs = process.env.AIT_CDP_HEARTBEAT_MS ? Number(process.env.AIT_CDP_HEARTBEAT_MS) : void 0;
|
|
536
|
-
if (envMs === void 0 || !Number.isFinite(envMs) || envMs <= 0) return;
|
|
537
|
-
const PING_TIMEOUT_MS = 2e3;
|
|
538
|
-
this.heartbeatHandle = setInterval(() => {
|
|
539
|
-
const targetIds = this.targets.size > 0 ? [...this.targets.keys()] : [initialTargetId];
|
|
540
|
-
for (const targetId of targetIds) {
|
|
541
|
-
const pingPromise = this.sendCommand("Runtime.evaluate", {
|
|
542
|
-
expression: "1",
|
|
543
|
-
returnByValue: true,
|
|
544
|
-
timeout: PING_TIMEOUT_MS
|
|
545
|
-
});
|
|
546
|
-
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("heartbeat timeout")), PING_TIMEOUT_MS + 500));
|
|
547
|
-
Promise.race([pingPromise, timeoutPromise]).catch(() => {
|
|
548
|
-
if (this.targets.has(targetId)) this.handleTargetGone("destroyed", targetId);
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
}, envMs);
|
|
552
|
-
}
|
|
553
|
-
stopHeartbeat() {
|
|
554
|
-
if (this.heartbeatHandle !== null) {
|
|
555
|
-
clearInterval(this.heartbeatHandle);
|
|
556
|
-
this.heartbeatHandle = null;
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
handleMessage(raw) {
|
|
560
|
-
const message = parseInbound(raw);
|
|
561
|
-
if (!message) return;
|
|
562
|
-
if (typeof message.id === "number" && this.pending.has(message.id)) {
|
|
563
|
-
const waiter = this.pending.get(message.id);
|
|
564
|
-
this.pending.delete(message.id);
|
|
565
|
-
if (waiter) if (message.error) waiter.reject(new Error(message.error.message));
|
|
566
|
-
else waiter.resolve(message.result);
|
|
567
|
-
return;
|
|
568
|
-
}
|
|
569
|
-
const now = Date.now();
|
|
570
|
-
let firstMessageSeen = false;
|
|
571
|
-
for (const targetId of this.targets.keys()) {
|
|
572
|
-
if (!this.targetLastSeenAt.has(targetId)) firstMessageSeen = true;
|
|
573
|
-
this.targetLastSeenAt.set(targetId, now);
|
|
574
|
-
}
|
|
575
|
-
if (firstMessageSeen && this.targets.size > 0) this.emitter.emit("target:attached", [...this.targets.values()]);
|
|
576
|
-
if (typeof message.method !== "string") return;
|
|
577
|
-
if (message.method === "Inspector.targetCrashed") {
|
|
578
|
-
this.handleTargetGone("crashed", null);
|
|
579
|
-
return;
|
|
580
|
-
}
|
|
581
|
-
if (message.method === "Target.targetDestroyed") {
|
|
582
|
-
const targetId = isObject(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
|
|
583
|
-
this.handleTargetGone("destroyed", targetId);
|
|
584
|
-
return;
|
|
585
|
-
}
|
|
586
|
-
if (message.method === "Target.detachedFromTarget") {
|
|
587
|
-
const targetId = isObject(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
|
|
588
|
-
this.handleTargetGone("detached", targetId);
|
|
589
|
-
return;
|
|
590
|
-
}
|
|
591
|
-
if (!this.buffers.has(message.method)) return;
|
|
592
|
-
const event = message.method;
|
|
593
|
-
const buffer = this.buffers.get(event);
|
|
594
|
-
if (!buffer) return;
|
|
595
|
-
buffer.push(message.params);
|
|
596
|
-
const cap = event === "Runtime.exceptionThrown" ? EXCEPTION_BUFFER_SIZE : this.bufferSize;
|
|
597
|
-
if (buffer.length > cap) buffer.shift();
|
|
598
|
-
this.emitter.emit(event, message.params);
|
|
599
|
-
}
|
|
600
|
-
getBufferedEvents(event) {
|
|
601
|
-
return this.buffers.get(event) ?? [];
|
|
602
|
-
}
|
|
603
|
-
on(event, listener) {
|
|
604
|
-
this.emitter.on(event, listener);
|
|
605
|
-
return () => this.emitter.off(event, listener);
|
|
606
|
-
}
|
|
607
|
-
/** Close the relay client websocket and reject any in-flight commands. */
|
|
608
|
-
close() {
|
|
609
|
-
const ws = this.ws;
|
|
610
|
-
this.stopHeartbeat();
|
|
611
|
-
this.handleDisconnect("Chii relay connection closed");
|
|
612
|
-
ws?.close();
|
|
613
|
-
}
|
|
614
|
-
};
|
|
615
|
-
//#endregion
|
|
616
|
-
//#region src/mcp/chii-relay.ts
|
|
617
|
-
/**
|
|
618
|
-
* Boots the local Chii relay server.
|
|
619
|
-
*
|
|
620
|
-
* Chii (liriliri/chii) is a chobitsu-based CDP relay that lets non-Chrome
|
|
621
|
-
* WebViews (iOS WKWebView / Android WebView — i.e. the Toss app) expose CDP.
|
|
622
|
-
* The relay accepts a `target` websocket from the phone's injected `target.js`
|
|
623
|
-
* and `client` websockets from CDP frontends (our MCP connection).
|
|
624
|
-
*
|
|
625
|
-
* Node-only: `chii` pulls in Koa + ws. Never bundled into the browser/in-app
|
|
626
|
-
* entries.
|
|
627
|
-
*
|
|
628
|
-
* TOTP auth (relay-side, authoritative gate):
|
|
629
|
-
* When `verifyAuth` is provided, this module gates both inbound surfaces:
|
|
630
|
-
*
|
|
631
|
-
* - HTTP 'request': a listener registered BEFORE `chii.start({server})`.
|
|
632
|
-
* Node's `http.Server` calls listeners in registration order; the first
|
|
633
|
-
* to call `res.end()` wins. Invalid auth → 401 + CORS header + a tiny
|
|
634
|
-
* JSON body (`{"error":"totp-rejected"}`) so a cross-origin script
|
|
635
|
-
* `fetch()` probe can READ the status (issue #478). Valid auth → return
|
|
636
|
-
* without side-effect (chii's Koa handler serves it).
|
|
637
|
-
*
|
|
638
|
-
* - WS 'upgrade': after `chii.start()` has registered chii's own upgrade
|
|
639
|
-
* listener, we take over the upgrade chain (remove chii's listeners,
|
|
640
|
-
* re-dispatch manually). Invalid auth → accept-then-close: complete the
|
|
641
|
-
* handshake via a `noServer` WebSocketServer, then immediately close
|
|
642
|
-
* with code 4401 reason 'totp-rejected' (issue #478). A raw 401 +
|
|
643
|
-
* `socket.destroy()` only ever surfaced as close code 1006 in the
|
|
644
|
-
* browser — indistinguishable from a tunnel failure, which left the
|
|
645
|
-
* env-2 phone UI silent. The explicit dispatch (not listener ordering)
|
|
646
|
-
* is what keeps chii away from rejected sockets: accept-then-close
|
|
647
|
-
* leaves the socket alive, so an order-based early-return would let
|
|
648
|
-
* chii's later listener complete a SECOND handshake on the same socket
|
|
649
|
-
* — an auth bypass. Valid auth → forward to chii's captured listeners.
|
|
650
|
-
*
|
|
651
|
-
* TOTP code transports (issue #466) — two equivalent ways to carry the code:
|
|
652
|
-
* 1. Query param `at=<code>` — used by the daemon-side `/client` connection
|
|
653
|
-
* (`chii-connection.ts` appends it; it holds the secret).
|
|
654
|
-
* 2. Path prefix `/at/<code>/…` — used by the phone-side target. Chii's
|
|
655
|
-
* stock `target.js` derives its WS endpoint from the script `src`
|
|
656
|
-
* (`scriptEl.src.replace('target.js','')`), so the only way for the
|
|
657
|
-
* phone to carry a code is to embed it in the script URL path. The
|
|
658
|
-
* in-app attach injects `https://<host>/at/<code>/target.js`; both the
|
|
659
|
-
* script fetch and the derived `wss://<host>/at/<code>/target/<id>` WS
|
|
660
|
-
* dial then carry the prefix. The listeners below rewrite the prefix
|
|
661
|
-
* into the query form (`rewriteAtPathPrefix`) and MUTATE `req.url`
|
|
662
|
-
* before chii's own handlers (registered later) parse it — chii only
|
|
663
|
-
* ever sees the stripped URL.
|
|
664
|
-
*
|
|
665
|
-
* Threat model: "URL leak" — someone obtains the tunnel URL (Slack paste, QR
|
|
666
|
-
* screenshot, shoulder-surfing) but does not have the shared TOTP secret.
|
|
667
|
-
* Rotating 6-digit code makes the URL stale after 30 s.
|
|
668
|
-
* A determined attacker who extracts the secret from the dogfood bundle can
|
|
669
|
-
* still compute valid codes; that is out of scope (see umbrella CLAUDE.md §4).
|
|
670
|
-
*
|
|
671
|
-
* SECRET-HANDLING: The secret value and computed TOTP codes MUST NOT appear
|
|
672
|
-
* in any log, error message, or process output. `verifyAuth` is a black-box
|
|
673
|
-
* predicate from the caller's perspective; this module only forwards pass/fail.
|
|
674
|
-
*/
|
|
675
|
-
const require = createRequire(import.meta.url);
|
|
676
|
-
/**
|
|
677
|
-
* WS keepalive ping interval (ms).
|
|
678
|
-
*
|
|
679
|
-
* Cloudflare proxied connections are dropped after ~100 s of no traffic.
|
|
680
|
-
* 45 s comfortably fits inside that window and lets both the phone-target leg
|
|
681
|
-
* and the daemon-client leg survive idle CDP sessions.
|
|
682
|
-
*/
|
|
683
|
-
const DEFAULT_KEEPALIVE_INTERVAL_MS = 45e3;
|
|
684
|
-
/**
|
|
685
|
-
* Loads chii's internal WebSocketServer class and returns it together with a
|
|
686
|
-
* flag indicating whether the real class was found.
|
|
687
|
-
*
|
|
688
|
-
* Returns `null` if the internal path is not resolvable (future chii release
|
|
689
|
-
* changes the layout) — callers skip keepalive gracefully.
|
|
690
|
-
*/
|
|
691
|
-
function tryLoadChiiWssClass() {
|
|
692
|
-
try {
|
|
693
|
-
const mod = require("chii/server/lib/WebSocketServer");
|
|
694
|
-
if (typeof mod === "function") return mod;
|
|
695
|
-
} catch {}
|
|
696
|
-
return null;
|
|
697
|
-
}
|
|
698
|
-
/**
|
|
699
|
-
* Calls `chii.start()` and returns the chii `WebSocketServer` instance that
|
|
700
|
-
* was constructed during the call.
|
|
701
|
-
*
|
|
702
|
-
* How: `chii/server/index.js`'s `start()` creates `new WebSocketServer()`
|
|
703
|
-
* where `WebSocketServer` is captured from `require('./lib/WebSocketServer')`
|
|
704
|
-
* at module load time. The class reference is stable, so we can temporarily
|
|
705
|
-
* patch `ChiiWssClass.prototype.start` — which runs *on the instance* —
|
|
706
|
-
* to record `this` before the original `start` runs.
|
|
707
|
-
*
|
|
708
|
-
* The patch is installed before `chii.start()` and removed (via `finally`)
|
|
709
|
-
* immediately after, so concurrent `startChiiRelay` calls nest correctly: each
|
|
710
|
-
* call's patch overrides the previous in the prototype chain for the duration
|
|
711
|
-
* of its own `chii.start()` call, restoring the prior descriptor on exit.
|
|
712
|
-
*
|
|
713
|
-
* If `ChiiWssClass` is null (internal path changed in a future chii release),
|
|
714
|
-
* `chii.start()` runs unpatched and the function returns null — callers skip
|
|
715
|
-
* keepalive gracefully without affecting relay correctness.
|
|
716
|
-
*/
|
|
717
|
-
async function startChiiWithCapture(chii, startOptions, ChiiWssClass) {
|
|
718
|
-
if (ChiiWssClass === null) {
|
|
719
|
-
await chii.start(startOptions);
|
|
720
|
-
return null;
|
|
721
|
-
}
|
|
722
|
-
let captured = null;
|
|
723
|
-
const proto = ChiiWssClass.prototype;
|
|
724
|
-
const originalStart = proto.start;
|
|
725
|
-
proto.start = function(server) {
|
|
726
|
-
captured = this;
|
|
727
|
-
return originalStart.call(this, server);
|
|
728
|
-
};
|
|
729
|
-
try {
|
|
730
|
-
await chii.start(startOptions);
|
|
731
|
-
} finally {
|
|
732
|
-
proto.start = originalStart;
|
|
733
|
-
}
|
|
734
|
-
return captured;
|
|
735
|
-
}
|
|
736
|
-
function loadChiiServer() {
|
|
737
|
-
const mod = require("chii");
|
|
738
|
-
if (typeof mod === "object" && mod !== null && "start" in mod && typeof mod.start === "function") return mod;
|
|
739
|
-
throw new Error("chii server module did not expose start()");
|
|
740
|
-
}
|
|
741
|
-
/**
|
|
742
|
-
* Rewrites a `/at/<code>/…` path-prefixed request URL into the equivalent
|
|
743
|
-
* query-based form, e.g.:
|
|
744
|
-
*
|
|
745
|
-
* `/at/123456/target.js` → `/target.js?at=123456`
|
|
746
|
-
* `/at/123456/target/x?url=u` → `/target/x?url=u&at=123456`
|
|
747
|
-
* `/at/123456/` → `/?at=123456`
|
|
748
|
-
*
|
|
749
|
-
* Returns `null` when the URL does not carry the prefix (including an empty
|
|
750
|
-
* code segment) — callers fall back to the unmodified URL and the existing
|
|
751
|
-
* query-based auth path.
|
|
752
|
-
*
|
|
753
|
-
* Pure string surgery — this function knows nothing about secrets or code
|
|
754
|
-
* validity; verification stays inside the caller-provided `verifyAuth`
|
|
755
|
-
* predicate (which parses the query). The raw path segment is appended
|
|
756
|
-
* verbatim to the query: both path segments and query values are
|
|
757
|
-
* percent-decoded exactly once by their consumers, so no re-encoding is
|
|
758
|
-
* needed (TOTP codes are 6 digits and never percent-encoded in practice).
|
|
759
|
-
*/
|
|
760
|
-
function rewriteAtPathPrefix(rawUrl) {
|
|
761
|
-
const match = /^\/at\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(rawUrl);
|
|
762
|
-
if (match === null) return null;
|
|
763
|
-
const code = match[1];
|
|
764
|
-
const path = match[2] === void 0 || match[2] === "" ? "/" : match[2];
|
|
765
|
-
const query = match[3] ?? "";
|
|
766
|
-
return `${path}${query}${query === "" ? "?" : "&"}at=${code}`;
|
|
767
|
-
}
|
|
768
|
-
/**
|
|
769
|
-
* Starts the Chii relay and resolves once listening.
|
|
770
|
-
*
|
|
771
|
-
* Default port is 0 (OS-assigned). With port 0 the OS picks a free ephemeral
|
|
772
|
-
* port on every start, so a stale cloudflared orphan holding any particular
|
|
773
|
-
* port cannot cause EADDRINUSE. The resolved `ChiiRelay.port` and `baseUrl`
|
|
774
|
-
* always reflect the actual bound port.
|
|
775
|
-
*
|
|
776
|
-
* chii.start() is called with `server` (our pre-created httpServer) BEFORE
|
|
777
|
-
* httpServer.listen(). This is intentional: chii attaches its Koa handler and
|
|
778
|
-
* WS upgrade listener to the server object, but the actual TCP bind is
|
|
779
|
-
* performed by our httpServer.listen() call below. The `port`/`domain` values
|
|
780
|
-
* passed to chii.start() are used for display/banner purposes inside chii and
|
|
781
|
-
* do not affect which port the server binds. The connection path (clients
|
|
782
|
-
* connecting to `relay.baseUrl`) always uses the post-listen confirmed port.
|
|
783
|
-
*/
|
|
784
|
-
async function startChiiRelay(options = {}) {
|
|
785
|
-
const requestedPort = options.port ?? 0;
|
|
786
|
-
const host = options.host ?? "127.0.0.1";
|
|
787
|
-
const { verifyAuth, onAuthReject } = options;
|
|
788
|
-
const keepaliveIntervalMs = options.keepaliveIntervalMs !== void 0 ? options.keepaliveIntervalMs : DEFAULT_KEEPALIVE_INTERVAL_MS;
|
|
789
|
-
const httpServer = createServer();
|
|
790
|
-
const notifyAuthReject = (kind) => {
|
|
791
|
-
if (onAuthReject === void 0) return;
|
|
792
|
-
try {
|
|
793
|
-
onAuthReject({ kind });
|
|
794
|
-
} catch {}
|
|
795
|
-
};
|
|
796
|
-
if (verifyAuth) httpServer.on("request", (req, res) => {
|
|
797
|
-
const rewritten = rewriteAtPathPrefix(req.url ?? "");
|
|
798
|
-
if (rewritten !== null) {
|
|
799
|
-
req.url = rewritten;
|
|
800
|
-
if (!verifyAuth(req)) {
|
|
801
|
-
res.statusCode = 401;
|
|
802
|
-
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
803
|
-
res.setHeader("Content-Type", "application/json");
|
|
804
|
-
res.end(JSON.stringify({ error: RELAY_AUTH_REJECT_REASON }));
|
|
805
|
-
notifyAuthReject("http-request");
|
|
806
|
-
}
|
|
807
|
-
return;
|
|
808
|
-
}
|
|
809
|
-
const pathname = (req.url ?? "").split("?")[0];
|
|
810
|
-
if (pathname === "/targets" || pathname === "/targets/") {
|
|
811
|
-
if (!verifyAuth(req)) {
|
|
812
|
-
res.statusCode = 401;
|
|
813
|
-
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
814
|
-
res.setHeader("Content-Type", "application/json");
|
|
815
|
-
res.end(JSON.stringify({ error: RELAY_AUTH_REJECT_REASON }));
|
|
816
|
-
notifyAuthReject("http-request");
|
|
817
|
-
return;
|
|
818
|
-
}
|
|
819
|
-
return;
|
|
820
|
-
}
|
|
821
|
-
});
|
|
822
|
-
const chiiWssClass = keepaliveIntervalMs > 0 ? tryLoadChiiWssClass() : null;
|
|
823
|
-
const capturedChiiWss = await startChiiWithCapture(loadChiiServer(), {
|
|
824
|
-
server: httpServer,
|
|
825
|
-
domain: `${host}:${requestedPort}`,
|
|
826
|
-
port: requestedPort
|
|
827
|
-
}, chiiWssClass);
|
|
828
|
-
if (verifyAuth) {
|
|
829
|
-
const chiiUpgradeListeners = httpServer.listeners("upgrade");
|
|
830
|
-
httpServer.removeAllListeners("upgrade");
|
|
831
|
-
const rejectWss = new WebSocketServer({ noServer: true });
|
|
832
|
-
httpServer.on("upgrade", (req, socket, head) => {
|
|
833
|
-
const rewritten = rewriteAtPathPrefix(req.url ?? "");
|
|
834
|
-
if (rewritten !== null) req.url = rewritten;
|
|
835
|
-
if (!verifyAuth(req)) {
|
|
836
|
-
rejectWss.handleUpgrade(req, socket, head, (ws) => {
|
|
837
|
-
ws.close(RELAY_AUTH_REJECT_CLOSE_CODE, RELAY_AUTH_REJECT_REASON);
|
|
838
|
-
});
|
|
839
|
-
notifyAuthReject("ws-upgrade");
|
|
840
|
-
return;
|
|
841
|
-
}
|
|
842
|
-
for (const listener of chiiUpgradeListeners) listener(req, socket, head);
|
|
843
|
-
});
|
|
844
|
-
}
|
|
845
|
-
const actualPort = await new Promise((resolve, reject) => {
|
|
846
|
-
httpServer.once("error", reject);
|
|
847
|
-
httpServer.listen(requestedPort, host, () => {
|
|
848
|
-
httpServer.off("error", reject);
|
|
849
|
-
resolve(httpServer.address().port);
|
|
850
|
-
});
|
|
851
|
-
});
|
|
852
|
-
let keepaliveHandle = null;
|
|
853
|
-
if (keepaliveIntervalMs > 0 && capturedChiiWss !== null) {
|
|
854
|
-
const chiiWss = capturedChiiWss;
|
|
855
|
-
keepaliveHandle = setInterval(() => {
|
|
856
|
-
for (const client of chiiWss._wss.clients) if (client.readyState === 1) client.ping();
|
|
857
|
-
}, keepaliveIntervalMs);
|
|
858
|
-
}
|
|
859
|
-
return {
|
|
860
|
-
port: actualPort,
|
|
861
|
-
baseUrl: `http://${host}:${actualPort}`,
|
|
862
|
-
close: () => new Promise((resolve) => {
|
|
863
|
-
if (keepaliveHandle !== null) {
|
|
864
|
-
clearInterval(keepaliveHandle);
|
|
865
|
-
keepaliveHandle = null;
|
|
866
|
-
}
|
|
867
|
-
httpServer.close(() => resolve());
|
|
868
|
-
})
|
|
869
|
-
};
|
|
870
|
-
}
|
|
871
|
-
//#endregion
|
|
872
|
-
//#region src/mcp/debug-server.ts
|
|
873
|
-
/**
|
|
874
|
-
* Factory that constructs a `ChiiCdpConnection` for the given relay base URL.
|
|
875
|
-
*
|
|
876
|
-
* Introduced as a named seam so PR-2 (dual-connection, #348) can defer
|
|
877
|
-
* construction to first-activation time by moving or replacing this call. Since
|
|
878
|
-
* #396 every family (relay included) is constructed lazily on its first
|
|
879
|
-
* `start_debug`, so this is always called from the lazy boot path.
|
|
880
|
-
*
|
|
881
|
-
* The relay base URL is only available after `startChiiRelay()` resolves, so
|
|
882
|
-
* the factory is called right after that point (same as before this refactor).
|
|
883
|
-
*/
|
|
884
|
-
function createRelayConnection(relayBaseUrl) {
|
|
885
|
-
return new ChiiCdpConnection({
|
|
886
|
-
relayBaseUrl,
|
|
887
|
-
totpSecret: process.env.AIT_DEBUG_TOTP_SECRET
|
|
888
|
-
});
|
|
889
|
-
}
|
|
890
|
-
/**
|
|
891
|
-
* Boots the relay family (issues #348, #356): starts the Chii relay on an
|
|
892
|
-
* OS-assigned port (with optional TOTP gate), opens a cloudflared quick tunnel
|
|
893
|
-
* to the relay's confirmed port in the background, prints the attach banner,
|
|
894
|
-
* and arms the tunnel health probe. Returns a {@link BootedFamily} whose
|
|
895
|
-
* `getTunnelStatus()` reflects the live tunnel (it flips up once the background
|
|
896
|
-
* tunnel resolves and follows reissues).
|
|
897
|
-
*
|
|
898
|
-
* Booted lazily via the dual router's `bootLazyFor('relay-intoss')` callback
|
|
899
|
-
* (symmetry with {@link bootLocalFamily}), at most once on the first
|
|
900
|
-
* `start_debug({ mode: 'relay-staging' })` (all-lazy, #396 — every relay boot now
|
|
901
|
-
* flows through `switchMode` after the project-local secret load). `relay-live`
|
|
902
|
-
* removed (#665).
|
|
903
|
-
*
|
|
904
|
-
* The relay base URL is only known after `startChiiRelay()` resolves, so the
|
|
905
|
-
* `ChiiCdpConnection` (via {@link createRelayConnection}) is constructed inside
|
|
906
|
-
* this function, after the relay port is confirmed.
|
|
907
|
-
*
|
|
908
|
-
* SECRET-HANDLING: the TOTP secret rides only inside `verifyAuth`; the wssUrl
|
|
909
|
-
* (relay host) is never logged here directly.
|
|
910
|
-
*/
|
|
911
|
-
async function bootRelayFamily(options = {}) {
|
|
912
|
-
assertRelayAuthConfigured();
|
|
913
|
-
const relayPort = options.relayPort ?? 0;
|
|
914
|
-
const totpEnabled = options.verifyAuth !== void 0;
|
|
915
|
-
const relay = await startChiiRelay({
|
|
916
|
-
port: relayPort,
|
|
917
|
-
verifyAuth: options.verifyAuth,
|
|
918
|
-
onAuthReject: options.onAuthReject
|
|
919
|
-
});
|
|
920
|
-
logInfo("server.start", {
|
|
921
|
-
port: relay.port,
|
|
922
|
-
totpEnabled
|
|
923
|
-
});
|
|
924
|
-
let tunnel = null;
|
|
925
|
-
let tunnelStatus = makeTunnelStatus(false, null);
|
|
926
|
-
let tunnelProbe = null;
|
|
927
|
-
generateAttachToken();
|
|
928
|
-
startQuickTunnel(relay.port).then((t) => {
|
|
929
|
-
tunnel = t;
|
|
930
|
-
tunnelStatus = makeTunnelStatus(true, t.wssUrl);
|
|
931
|
-
options.onWssUrl?.(t.wssUrl);
|
|
932
|
-
if (t.childPid !== void 0) options.onTunnelChildPid?.(t.childPid);
|
|
933
|
-
logInfo("tunnel.up", { totpEnabled });
|
|
934
|
-
tunnelProbe = startTunnelHealthProbe(t, relay.port, {
|
|
935
|
-
onReissue: (newTunnel) => {
|
|
936
|
-
tunnel = newTunnel;
|
|
937
|
-
tunnelStatus = makeTunnelStatus(true, newTunnel.wssUrl, null, 0);
|
|
938
|
-
options.onWssUrl?.(newTunnel.wssUrl);
|
|
939
|
-
if (newTunnel.childPid !== void 0) options.onTunnelChildPid?.(newTunnel.childPid);
|
|
940
|
-
printAttachBanner({
|
|
941
|
-
wssUrl: newTunnel.wssUrl,
|
|
942
|
-
totpEnabled
|
|
943
|
-
}).then(() => {
|
|
944
|
-
logInfo("tunnel.up", {
|
|
945
|
-
totpEnabled,
|
|
946
|
-
reissued: true
|
|
947
|
-
});
|
|
948
|
-
});
|
|
949
|
-
},
|
|
950
|
-
onPermanentDrop: (droppedAt) => {
|
|
951
|
-
tunnelStatus = makeTunnelStatus(false, null, droppedAt, 3);
|
|
952
|
-
logError("tunnel.down", { msg: `tunnel permanently dropped (${droppedAt}). Restart: npx @ait-co/devtools devtools-mcp` });
|
|
953
|
-
options.onTunnelDown?.();
|
|
954
|
-
}
|
|
955
|
-
});
|
|
956
|
-
return printAttachBanner({
|
|
957
|
-
wssUrl: t.wssUrl,
|
|
958
|
-
totpEnabled
|
|
959
|
-
});
|
|
960
|
-
}, (err) => {
|
|
961
|
-
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.` });
|
|
962
|
-
});
|
|
963
|
-
const connection = createRelayConnection(relay.baseUrl);
|
|
964
|
-
return {
|
|
965
|
-
connection,
|
|
966
|
-
relayOrigin: "intoss-webview",
|
|
967
|
-
relayHttpUrl: relay.baseUrl,
|
|
968
|
-
getTunnelStatus: () => tunnelStatus,
|
|
969
|
-
stop() {
|
|
970
|
-
tunnelProbe?.stop();
|
|
971
|
-
tunnel?.stop();
|
|
972
|
-
connection.close();
|
|
973
|
-
relay.close();
|
|
974
|
-
}
|
|
975
|
-
};
|
|
976
|
-
}
|
|
977
|
-
//#endregion
|
|
978
|
-
export { bootRelayFamily, buildRelayVerifyAuth };
|
|
979
|
-
|
|
980
|
-
//# sourceMappingURL=debug-server-1dhDA3aw.js.map
|