@ait-co/debug-console 0.1.1

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/index.cjs ADDED
@@ -0,0 +1,1353 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region ../internal-protocol/src/debug-host.ts
3
+ /**
4
+ * Host allowlist predicates — the one part of the activation gate that BOTH
5
+ * sides of the device↔host protocol evaluate.
6
+ *
7
+ * The device evaluates them inside the runtime gate (`@ait-co/debug-console`'s
8
+ * `gate.ts`, Layer B1). The daemon evaluates the same predicate when it decides
9
+ * whether a CDP target's URL is allowed to be driven (`@ait-co/debugger`'s
10
+ * `debug-server.ts`). Before the split those two call sites shared one module
11
+ * by reaching from the daemon into the in-app tree — a reverse edge that would
12
+ * have dragged the browser bundle into the daemon's graph once the two surfaces
13
+ * became separate packages. Extracting the 5 predicates here removes the edge
14
+ * without duplicating the rule.
15
+ *
16
+ * This module is intentionally dependency-free (no Node, no DOM — only
17
+ * `String#endsWith` and one regex) so it inlines into both bundles. There is no
18
+ * barrel index in this package: each consumer imports the one subpath it needs,
19
+ * and its bundler inlines the handful of statements at build time. Nothing here
20
+ * survives as a runtime cross-package import.
21
+ *
22
+ * SECRET-HANDLING: a hostname is an input, never an output. These functions
23
+ * return booleans only — no predicate may grow to log or return the hostname,
24
+ * a relay URL, or a tunnel host.
25
+ */
26
+ /**
27
+ * The host suffix the Toss app uses to serve dogfood / private mini-apps.
28
+ *
29
+ * A dogfood entry maps to a host such as
30
+ * `example.private-apps.tossmini.com`. A production entry is served from
31
+ * `*.apps.tossmini.com` — the `.private-apps.` segment is absent.
32
+ */
33
+ const PRIVATE_APPS_HOST_SUFFIX = ".private-apps.tossmini.com";
34
+ /**
35
+ * The parent host suffix for the whole mini-app serving family.
36
+ *
37
+ * The 3.0 runtime loader serves mini-app pages from tossmini.com hosts that are
38
+ * NOT `*.private-apps.tossmini.com`, so under 3.0 the hostname no longer
39
+ * distinguishes a dogfood candidate from a production entry. For those hosts
40
+ * the host layer is demoted from a stage discriminator to a "known host family"
41
+ * filter and the effective boundary moves to the opt-in + relay + TOTP layer.
42
+ */
43
+ const TOSSMINI_HOST_SUFFIX = ".tossmini.com";
44
+ /**
45
+ * The host suffix Cloudflare quick-tunnels serve from — the env 2 (PWA) entry.
46
+ */
47
+ const TRYCLOUDFLARE_HOST_SUFFIX = ".trycloudflare.com";
48
+ /**
49
+ * Returns whether `hostname` is a `*.private-apps.tossmini.com` subdomain —
50
+ * the host reserved for dogfood / private mini-app entries.
51
+ *
52
+ * The match is an exact suffix check, not a substring `.includes()`: a
53
+ * substring test would also accept an attacker-controlled host like
54
+ * `private-apps.tossmini.com.evil.example`, which ends in `.example`, not in
55
+ * `.tossmini.com`. Requiring the string to END with the suffix closes that.
56
+ * The leading `.` in the suffix also forces a real subdomain label, so a bare
57
+ * `private-apps.tossmini.com` (no mini-app subdomain) does not match.
58
+ */
59
+ function isPrivateAppsHost(hostname) {
60
+ return hostname.endsWith(PRIVATE_APPS_HOST_SUFFIX);
61
+ }
62
+ /**
63
+ * Returns whether `hostname` is any `*.tossmini.com` subdomain — the host
64
+ * family mini-app pages are served from. Includes the 2.x
65
+ * `*.private-apps.tossmini.com` dogfood hosts and the 3.0 unified serving
66
+ * hosts.
67
+ *
68
+ * Same exact-suffix `endsWith` check as {@link isPrivateAppsHost} — never a
69
+ * substring `.includes()`, which would accept `x.tossmini.com.evil.example`.
70
+ */
71
+ function isTossminiHost(hostname) {
72
+ return hostname.endsWith(TOSSMINI_HOST_SUFFIX);
73
+ }
74
+ /**
75
+ * Returns whether `hostname` is a Cloudflare quick-tunnel host — the env 2
76
+ * (PWA) entry.
77
+ *
78
+ * Env 2 serves the local dev server through a `*.trycloudflare.com` quick
79
+ * tunnel. It has no production runtime: the SDK is the devtools mock and the
80
+ * page is the developer's own dev build. The host safety net (which stops a
81
+ * dogfood build that lands on a production host from attaching) has nothing to
82
+ * protect against here — but the remaining gate layers (opt-in, relay URL,
83
+ * TOTP) still apply, so a leaked tunnel URL is still blocked.
84
+ *
85
+ * Same exact-suffix `endsWith` check as {@link isPrivateAppsHost} — never a
86
+ * substring `.includes()`, which would accept
87
+ * `evil.trycloudflare.com.example.com`.
88
+ */
89
+ function isTrycloudflareHost(hostname) {
90
+ return hostname.endsWith(TRYCLOUDFLARE_HOST_SUFFIX);
91
+ }
92
+ /**
93
+ * Returns true when the hostname is a localhost/loopback address.
94
+ * Allowed: `localhost`, `127.x.x.x` (full RFC 5735 loopback block), `[::1]`,
95
+ * `0.0.0.0`, `*.localhost`.
96
+ *
97
+ * Security note: `hostname.startsWith('127.')` is intentionally NOT used —
98
+ * that pattern would accept `127.evil.com`, which starts with "127." but is an
99
+ * attacker-controlled hostname, not a loopback address. Instead, the 127/8
100
+ * loopback block is matched with a strict numeric-quad regex so only valid
101
+ * dotted-decimal IPv4 in the 127.x.x.x range pass.
102
+ */
103
+ function isLocalhostHost(hostname) {
104
+ if (hostname === "localhost" || hostname === "0.0.0.0") return true;
105
+ if (hostname === "[::1]") return true;
106
+ if (/^127\.\d+\.\d+\.\d+$/.test(hostname)) return true;
107
+ if (hostname.endsWith(".localhost")) return true;
108
+ return false;
109
+ }
110
+ /**
111
+ * Positive-allowlist kill-switch: returns true when the hostname is a known
112
+ * debug-allowed host. The debug surface is ONLY active on:
113
+ * - localhost / loopback (env 1 desktop dev)
114
+ * - `*.trycloudflare.com` (env 2 PWA tunnel)
115
+ * - `*.tossmini.com` (env 3 dog-food — 2.x private-apps hosts AND the 3.0
116
+ * unified serving family)
117
+ *
118
+ * Any other host is silently blocked. Unlisted hosts never had a debug surface
119
+ * regardless, but this function makes it explicit and auditable in one place.
120
+ *
121
+ * The 3.0 loader serves dogfood candidates and production entries from the same
122
+ * host family, so the hostname alone can no longer separate them. The "no naked
123
+ * attach on a production-family host" invariant is preserved one layer down: on
124
+ * tossmini hosts that are not `*.private-apps.*` the TOTP code is mandatory,
125
+ * and production entry URLs carry no debug/relay/at params at all.
126
+ *
127
+ * SECRET-HANDLING: the hostname value MUST NOT be logged or included in any
128
+ * error reason string — only benign labels ('host not in allowlist') are safe.
129
+ */
130
+ function isDebugAllowedHost(hostname) {
131
+ return isLocalhostHost(hostname) || isTrycloudflareHost(hostname) || isTossminiHost(hostname);
132
+ }
133
+ //#endregion
134
+ //#region src/gate.ts
135
+ /**
136
+ * Runtime activation gate for the in-app debug surface.
137
+ *
138
+ * Spec: docs/superpowers/specs/2026-05-18-in-app-debug-mcp.md
139
+ * "3-layer activation gate". This is the pure gate decision; the Chii client,
140
+ * WebSocket transport, MCP server, and CLI that consume it live in src/mcp/.
141
+ *
142
+ * This function evaluates the two RUNTIME layers, B and C. Layer A — the
143
+ * build-time gate — is NOT evaluated here, and deliberately so: it is enforced
144
+ * entirely by the consumer's `if (__DEBUG_BUILD__) { … }` guard around the
145
+ * import site (see sdk-example `src/main.tsx`). `__DEBUG_BUILD__` is a
146
+ * consumer-build-time constant; a release consumer build folds it to `false`
147
+ * and dead-code-eliminates the whole import of `@ait-co/debug-console`, so
148
+ * this code is simply absent from release bundles. A pre-built npm package
149
+ * cannot re-check that flag — it was already baked at devtools' own publish
150
+ * time — so any `isDebugBuild` check inside this function would be permanently
151
+ * `false` and could never pass. Layer A is the consumer guard; B and C are
152
+ * here.
153
+ *
154
+ * Layer B has two parts:
155
+ * B1 — host allowlist: `hostname` must be a `*.private-apps.tossmini.com`
156
+ * subdomain (Toss dogfood entry) OR a `*.trycloudflare.com` host (env 2
157
+ * PWA dev tunnel). The Toss app serves dogfood / private mini-apps from
158
+ * a separate `private-apps` host; a production (`intoss://`) entry is
159
+ * served from `*.apps.tossmini.com` WITHOUT the `private-apps` segment.
160
+ * This is the security gate against a dogfood build that somehow lands
161
+ * on a production entry — see the comment on {@link isPrivateAppsHost}.
162
+ * The env 2 tunnel host is allowed because it has no production runtime
163
+ * (mock SDK, the developer's own dev server) — see {@link
164
+ * isTrycloudflareHost}.
165
+ * B2 — entry query: `_deploymentId` must be present and non-empty. Applies to
166
+ * the Toss path only; the env 2 tunnel has no deployed bundle, so B2 is
167
+ * skipped for `*.trycloudflare.com` hosts.
168
+ *
169
+ * Layer C — opt-in + relay + optional TOTP auth:
170
+ * C1 — opt-in: `debug=1` must be present.
171
+ * C2 — relay URL: `relay=<wss-url>` must be a valid `wss:` URL.
172
+ * C3 — TOTP auth: When `verifyTotpCode` is provided (consumer injected the
173
+ * baked secret at build time via `__DEBUG_TOTP_SECRET__`),
174
+ * `at=<code>` is checked. Invalid or absent code → BLOCKED.
175
+ * When no verifier is provided (TOTP disabled), `at` is
176
+ * ignored (backward compatible).
177
+ *
178
+ * Security note on baked secrets:
179
+ * The TOTP secret baked in via `__DEBUG_TOTP_SECRET__` is present in the
180
+ * dogfood bundle and is extractable by a determined reverse engineer.
181
+ * The practical bar raised is: "URL leak" (Slack paste, QR screenshot) →
182
+ * blocked; "URL + bundle extraction + live TOTP code" → not blocked.
183
+ * This is the intended threat model. Do not overpromise on this guarantee.
184
+ *
185
+ * SECRET-HANDLING: `verifyTotpCode` is a black-box predicate. This module
186
+ * does NOT log the secret, any code value, or pass/fail details beyond the
187
+ * `'auth'` reason enum.
188
+ *
189
+ * Decision matrix (gate only runs in a debug build — Layer A already passed):
190
+ *
191
+ * host | _deploymentId | debug=1 | relay ok | TOTP ok* | result
192
+ * neither | (any) | (any) | (any) | (any) | BLOCKED (host)
193
+ * private-apps| absent | (any) | (any) | (any) | BLOCKED (entry)
194
+ * private-apps| present | absent | (any) | (any) | BLOCKED (opt-in)
195
+ * private-apps| present | present | invalid | (any) | BLOCKED (invalid-relay)
196
+ * private-apps| present | present | valid | fail* | BLOCKED (auth)
197
+ * private-apps| present | present | valid | pass/n/a | ATTACH
198
+ * trycloudflare| (skipped) | absent | (any) | (any) | BLOCKED (opt-in)
199
+ * trycloudflare| (skipped) | present | invalid | (any) | BLOCKED (invalid-relay)
200
+ * trycloudflare| (skipped) | present | valid | fail* | BLOCKED (auth)
201
+ * trycloudflare| (skipped) | present | valid | pass/n/a | ATTACH
202
+ * tossmini(3.0)| (reported) | absent | (any) | (any) | BLOCKED (opt-in)
203
+ * tossmini(3.0)| (reported) | present | invalid | (any) | BLOCKED (invalid-relay)
204
+ * tossmini(3.0)| (reported) | present | valid | at absent| BLOCKED (auth — TOTP mandatory, #760)
205
+ * tossmini(3.0)| (reported) | present | valid | pass/at present | ATTACH
206
+ *
207
+ * * "TOTP ok" column only applies when `verifyTotpCode` is provided.
208
+ * When no verifier is injected, TOTP check is skipped entirely — EXCEPT
209
+ * on tossmini(3.0) hosts (non-private-apps), where a missing `at=` code
210
+ * blocks with 'auth' even without a verifier (devtools#760; the relay
211
+ * side remains the authoritative verifier).
212
+ *
213
+ * tossmini(3.0) = `*.tossmini.com` hosts that are not
214
+ * `*.private-apps.tossmini.com` — the 3.0 unified serving family. The 3.0
215
+ * loader consumes `_deploymentId` natively, so B2 reports it when present
216
+ * but never requires it there (devtools#760).
217
+ * For trycloudflare (env 2 tunnel) hosts B1 is bypassed and B2 is skipped;
218
+ * C1/C2/C3 still apply identically. The ATTACH result carries
219
+ * `deploymentId: ''` for tunnel hosts.
220
+ */
221
+ /**
222
+ * Pure function that evaluates the runtime debug activation layers (B and C).
223
+ *
224
+ * Has no side effects. The input is explicit. Returns a discriminated union
225
+ * so callers can pattern-match on `result.attach`.
226
+ *
227
+ * Layer A (build-time) is intentionally not evaluated here — see the file-level
228
+ * comment. By the time this function runs, the consumer's `if (__DEBUG_BUILD__)`
229
+ * guard has already passed; this function only decides B and C.
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * const result = evaluateDebugGate({
234
+ * hostname: window.location.hostname,
235
+ * searchParams: new URLSearchParams(window.location.search),
236
+ * });
237
+ * if (result.attach) {
238
+ * // Proceed to load Chii client
239
+ * }
240
+ * ```
241
+ */
242
+ function evaluateDebugGate(input) {
243
+ const isTunnel = isTrycloudflareHost(input.hostname);
244
+ const isLocal = isLocalhostHost(input.hostname);
245
+ if (!isDebugAllowedHost(input.hostname)) return {
246
+ attach: false,
247
+ reason: "host"
248
+ };
249
+ let deploymentId = "";
250
+ if (isPrivateAppsHost(input.hostname)) {
251
+ deploymentId = input.searchParams.get("_deploymentId") ?? "";
252
+ if (deploymentId === "") return {
253
+ attach: false,
254
+ reason: "entry"
255
+ };
256
+ } else if (!isTunnel && !isLocal) deploymentId = input.searchParams.get("_deploymentId") ?? "";
257
+ if (input.searchParams.get("debug") !== "1") return {
258
+ attach: false,
259
+ reason: "opt-in"
260
+ };
261
+ const relayRaw = input.searchParams.get("relay") ?? "";
262
+ if (relayRaw === "") return {
263
+ attach: false,
264
+ reason: "invalid-relay"
265
+ };
266
+ let relayUrl;
267
+ try {
268
+ relayUrl = new URL(relayRaw);
269
+ } catch {
270
+ return {
271
+ attach: false,
272
+ reason: "invalid-relay"
273
+ };
274
+ }
275
+ if (relayUrl.protocol !== "wss:") return {
276
+ attach: false,
277
+ reason: "invalid-relay"
278
+ };
279
+ const atCode = input.searchParams.get("at") ?? "";
280
+ if (input.verifyTotpCode !== void 0) {
281
+ if (!input.verifyTotpCode(atCode)) return {
282
+ attach: false,
283
+ reason: "auth"
284
+ };
285
+ } else if (isTossminiHost(input.hostname) && !isPrivateAppsHost(input.hostname) && atCode === "") return {
286
+ attach: false,
287
+ reason: "auth"
288
+ };
289
+ return {
290
+ attach: true,
291
+ relayUrl: relayUrl.href,
292
+ deploymentId
293
+ };
294
+ }
295
+ //#endregion
296
+ //#region ../internal-protocol/src/attach-handshake.ts
297
+ /**
298
+ * Version handshake carried on the attach path.
299
+ *
300
+ * WHY THIS EXISTS — every other clause of the device↔host contract is a
301
+ * value-duplicated string or number with zero compile-time linkage: the
302
+ * `window.__ait_bridge` snapshot and its field names, the `ait:bridge-call` /
303
+ * `ait:relay-ws-state` event names, the `__ait_relay_ws_observed` flag, the
304
+ * `#__ait_debug_indicator` element id, the `/at/<code>/target.js` path
305
+ * convention, `window.__sdk` / `window.__sdkCall`, and close code 4401. When
306
+ * the two sides drift, none of that crashes — it silently misbehaves. The
307
+ * indicator renders empty, a field reads `undefined`, a close frame goes
308
+ * unrecognised. Nothing in the stack says why.
309
+ *
310
+ * Changesets `fixed` keeps `@ait-co/debugger` and `@ait-co/debug-console` on
311
+ * one version number, so "same version" is exactly "mutually tested pair". What
312
+ * `fixed` cannot do is stop a consumer from installing a skewed pair. This
313
+ * handshake turns that skew from a silent misbehaviour into one diagnostic
314
+ * line: the device reports its build-time `__VERSION__` on a fire-and-forget
315
+ * request just before it injects `target.js`, and the daemon compares it with
316
+ * its own.
317
+ *
318
+ * Why a dedicated request rather than a query param on `target.js`: chii's
319
+ * stock `target.js` derives its WebSocket endpoint from its own script `src`
320
+ * via `src.replace('target.js', '')` and then appends `target/<id>`. Any query
321
+ * string on that URL would land in the middle of the derived endpoint and break
322
+ * the dial. The path is therefore separate, and it rides the same
323
+ * `/at/<code>/` prefix so the relay's existing auth gate covers it unchanged.
324
+ *
325
+ * SECRET-HANDLING: the payload is a version string and nothing else. The
326
+ * request carries a TOTP code only in the same path-prefix form the target
327
+ * script already uses; neither side may log the URL, the code, or the relay
328
+ * host. The mismatch diagnostic names two version strings — never a URL.
329
+ */
330
+ /**
331
+ * Relay HTTP path the device pings once, immediately before injecting
332
+ * `target.js`. Served by the daemon's relay; the response body is empty.
333
+ */
334
+ const ATTACH_HANDSHAKE_PATH = "/ait-attach";
335
+ //#endregion
336
+ //#region ../internal-protocol/src/bridge-observer-state.ts
337
+ /**
338
+ * CustomEvent fired (no detail) on every bridge-call start/settle so the
339
+ * indicator badge re-renders promptly. SECRET-HANDLING: carries no detail
340
+ * payload at all — the badge reads the enum-only snapshot on receipt.
341
+ */
342
+ const BRIDGE_CALL_EVENT = "ait:bridge-call";
343
+ /**
344
+ * CustomEvent fired with `{ detail: { state } }` on every relay-WebSocket
345
+ * open/close, so a CDP-injected indicator can follow relay liveness without
346
+ * installing a second Proxy on `window.WebSocket`. `state` is an enum
347
+ * (`'open' | 'closed'`) — never a URL.
348
+ */
349
+ const RELAY_WS_STATE_EVENT = "ait:relay-ws-state";
350
+ //#endregion
351
+ //#region ../internal-protocol/src/relay-auth-close.ts
352
+ /**
353
+ * Shared constants for the relay's named TOTP-auth rejection.
354
+ *
355
+ * Before the accept-then-close fix the relay rejected an unauthenticated
356
+ * WebSocket upgrade with a raw `HTTP/1.1 401` + `socket.destroy()`. A handshake
357
+ * aborted that way is indistinguishable from a network failure on the browser
358
+ * side — the WebSocket only ever sees close code 1006, so the phone (env-2
359
+ * launcher PWA) could not tell "stale TOTP code" apart from "tunnel down" and
360
+ * stayed silent. The fix is accept-then-close: complete the handshake, then
361
+ * close with an application close code that NAMES the rejection.
362
+ *
363
+ * Three parties share this contract:
364
+ * - the relay (`@ait-co/debugger`, Node) sends the close frame / HTTP error body;
365
+ * - the on-device console (`@ait-co/debug-console`, browser) observes
366
+ * relay-bound WebSockets and surfaces the code to the launcher shell;
367
+ * - the daemon's own CDP client (`@ait-co/debugger`, Node) recognises the code
368
+ * as an auth failure on its `/client` dial.
369
+ *
370
+ * This module is intentionally dependency-free (no Node, no DOM) so it is safe
371
+ * to inline into both the browser bundle and the daemon bundle.
372
+ *
373
+ * SECRET-HANDLING: these are fixed enum values. The close reason / error body
374
+ * must never grow to carry a secret, a TOTP code, or a host.
375
+ */
376
+ /**
377
+ * WebSocket close code sent by the relay when TOTP auth is rejected.
378
+ *
379
+ * 4000–4999 is the application-reserved range (RFC 6455 §7.4.2); 4401 mirrors
380
+ * HTTP 401 so it reads as "unauthorized" at a glance.
381
+ */
382
+ const RELAY_AUTH_REJECT_CLOSE_CODE = 4401;
383
+ /**
384
+ * Close reason string accompanying {@link RELAY_AUTH_REJECT_CLOSE_CODE}, and
385
+ * the `error` value of the relay's HTTP 401 JSON body. Enum string only —
386
+ * never interpolated with request data.
387
+ */
388
+ const RELAY_AUTH_REJECT_REASON = "totp-rejected";
389
+ //#endregion
390
+ //#region src/bridge-observer.ts
391
+ /**
392
+ * In-app native-bridge call observer (issue #749).
393
+ *
394
+ * WHY THIS EXISTS — the mock's `observe()` (`src/mock/observe.ts` → `aitState.
395
+ * sdkCallLog`) only wraps the MOCK SDK. In the on-device debug context (env 3,
396
+ * real Toss WebView, run7) the REAL `@apps-in-toss/web-framework` is loaded, so
397
+ * that groundwork sees nothing. The in-app debug surface needs its own
398
+ * observation point at the one place every real async bridge call funnels
399
+ * through, so the on-phone indicator can answer run7's question: is a spinner a
400
+ * pending native call, the app's own UI, or a wedged JS main thread?
401
+ *
402
+ * OBSERVATION POINTS (version-agnostic — both SDK lines route through one of
403
+ * these; picked so a GA flip 2.x↔3.0 does not break the signal):
404
+ *
405
+ * - 3.0 line — `window.__appsInTossNativeBridge.callAsyncMethod(name, params)`
406
+ * is the single async dispatcher; it returns the native Promise. Wrapping
407
+ * it gives the COMPLETE lifecycle (pending on call, settle on resolve/
408
+ * reject) from ONE hook, with no reliance on how native calls back.
409
+ * - 2.x line — there is no single dispatcher method (each async bridge is an
410
+ * independent `createAsyncBridge` closure). The universal START choke point
411
+ * is `window.ReactNativeWebView.postMessage(json)`; the matching SETTLE
412
+ * signal is `window.__GRANITE_NATIVE_EMITTER.emit('<method>/resolve|reject/
413
+ * <eventId>')`. We wrap both.
414
+ *
415
+ * The observer publishes a read-only snapshot on `window.__ait_bridge` (an
416
+ * id→pending map + a last-call record) and fires a payload-less
417
+ * {@link BRIDGE_CALL_EVENT} CustomEvent on every change, so the CDP-injected
418
+ * indicator badge (`buildIndicatorExpression`) can render the pending list +
419
+ * last-call stamp without polling — the same pub/sub decoupling the relay-WS
420
+ * observer uses for `ait:relay-ws-state` (#730).
421
+ *
422
+ * SECRET-HANDLING: this module records API METHOD NAMES + timestamps + a
423
+ * correlation id ONLY. It NEVER reads, stores, or forwards call arguments
424
+ * (`params`/`args`) or results — those may carry tokens, URLs, or user data.
425
+ * The outbound-message parser reads `type`/`name`/`functionName`/`callbackId`/
426
+ * `eventId` and deliberately never touches `params`/`args`.
427
+ *
428
+ * Lives in the in-app graph (reached only via {@link maybeAttach}); a release
429
+ * consumer build DCEs it with the rest of the debug surface (§check:debug-
430
+ * surface-absent). Never throws into the host app — every hook is guarded.
431
+ */
432
+ /**
433
+ * Pending entries older than this are pruned on the next start — a safety net
434
+ * for the fallback path where a settle signal might be missed, so the pending
435
+ * list can never grow unbounded or show a forever-stuck row. Generous enough
436
+ * that a genuinely slow native call (the exact signal we want to surface) still
437
+ * shows while it is plausibly in flight.
438
+ */
439
+ const MAX_PENDING_AGE_MS = 12e4;
440
+ /** Guard so the observer wraps the bridge at most once per page lifecycle. */
441
+ let bridgeObserverInstalled = false;
442
+ /** Monotonic id source for the primary (3.0) path, where native gives us none. */
443
+ let callIdCounter = 0;
444
+ /** Undo hooks that {@link uninstallBridgeObserver} runs to restore originals. */
445
+ let restoreHooks = [];
446
+ /** Drops pending entries older than {@link MAX_PENDING_AGE_MS}. */
447
+ function pruneStale(state, now) {
448
+ for (const id of Object.keys(state.pending)) {
449
+ const entry = state.pending[id];
450
+ if (entry !== void 0 && now - entry.startedAt > MAX_PENDING_AGE_MS) delete state.pending[id];
451
+ }
452
+ }
453
+ /** Fires the payload-less notify event so the badge re-renders. */
454
+ function broadcast() {
455
+ if (typeof window === "undefined") return;
456
+ window.dispatchEvent(new CustomEvent(BRIDGE_CALL_EVENT));
457
+ }
458
+ /** Records a call start: add to pending, set last=pending, notify. */
459
+ function startCall(state, id, method, now) {
460
+ pruneStale(state, now);
461
+ state.pending[id] = {
462
+ method,
463
+ startedAt: now
464
+ };
465
+ state.last = {
466
+ method,
467
+ at: now,
468
+ status: "pending"
469
+ };
470
+ broadcast();
471
+ }
472
+ /** Records a call settle: remove from pending, stamp last, notify. */
473
+ function settleCall(state, id, status, now) {
474
+ const entry = state.pending[id];
475
+ delete state.pending[id];
476
+ state.last = {
477
+ method: entry?.method ?? state.last?.method ?? "unknown",
478
+ at: now,
479
+ status
480
+ };
481
+ broadcast();
482
+ }
483
+ /**
484
+ * Parses an outbound `ReactNativeWebView.postMessage` JSON envelope and records
485
+ * a START for async request/response calls only. Event subscriptions
486
+ * (`addEventListener`/`removeEventListener`/`callEventMethod`), cleanup, and
487
+ * constants are ignored — they are not the "spinner is a pending call" signal.
488
+ *
489
+ * SECRET-HANDLING: reads `type`/`name`/`functionName`/`callbackId`/`eventId`
490
+ * ONLY — never `params`/`args`.
491
+ */
492
+ function observeOutbound(state, message) {
493
+ if (typeof message !== "string") return;
494
+ let parsed;
495
+ try {
496
+ parsed = JSON.parse(message);
497
+ } catch {
498
+ return;
499
+ }
500
+ const now = Date.now();
501
+ if (parsed.type === "callAsyncMethod" && typeof parsed.name === "string" && typeof parsed.callbackId === "string") {
502
+ startCall(state, parsed.callbackId, parsed.name, now);
503
+ return;
504
+ }
505
+ if (parsed.type === "method" && typeof parsed.functionName === "string" && typeof parsed.eventId === "string") startCall(state, parsed.eventId, parsed.functionName, now);
506
+ }
507
+ /**
508
+ * Parses a `__GRANITE_NATIVE_EMITTER.emit` event name and records a SETTLE for
509
+ * 2.x async resolves/rejects (`<method>/resolve/<eventId>` |
510
+ * `<method>/reject/<eventId>`). Event-bridge emits (`.../onEvent/...`) are
511
+ * ignored. SECRET-HANDLING: reads the event NAME only — never the emitted args.
512
+ */
513
+ function observeSettle(state, event) {
514
+ if (typeof event !== "string") return;
515
+ const match = /\/(resolve|reject)\/([^/]+)$/.exec(event);
516
+ if (match === null) return;
517
+ settleCall(state, match[2], match[1] === "resolve" ? "resolved" : "rejected", Date.now());
518
+ }
519
+ /**
520
+ * Installs the native-bridge call observer (#749). Idempotent per page
521
+ * lifecycle. Called by {@link maybeAttach} after the gate passes (debug builds
522
+ * only). Prefers the 3.0 single-dispatcher wrap; falls back to the universal
523
+ * 2.x postMessage-start + emitter-settle pair. A context with no observable
524
+ * bridge (env 2 mock) leaves `window.__ait_bridge` as an empty snapshot — the
525
+ * badge then shows the heartbeat only, which is correct.
526
+ *
527
+ * Never throws into the host app — a wrapped hook that somehow fails is caught
528
+ * and the original behavior is always preserved.
529
+ */
530
+ function installBridgeObserver() {
531
+ if (bridgeObserverInstalled) return;
532
+ if (typeof window === "undefined") return;
533
+ bridgeObserverInstalled = true;
534
+ const state = {
535
+ pending: Object.create(null),
536
+ last: null
537
+ };
538
+ window.__ait_bridge = state;
539
+ const nativeBridge = window.__appsInTossNativeBridge;
540
+ if (nativeBridge !== void 0 && typeof nativeBridge.callAsyncMethod === "function") {
541
+ const original = nativeBridge.callAsyncMethod;
542
+ const wrapped = function(name, params) {
543
+ const id = `c${++callIdCounter}`;
544
+ startCall(state, id, String(name), Date.now());
545
+ let result;
546
+ try {
547
+ result = original.call(this, name, params);
548
+ } catch (err) {
549
+ settleCall(state, id, "rejected", Date.now());
550
+ throw err;
551
+ }
552
+ if (result !== null && typeof result.then === "function") result.then(() => settleCall(state, id, "resolved", Date.now()), () => settleCall(state, id, "rejected", Date.now()));
553
+ else settleCall(state, id, "resolved", Date.now());
554
+ return result;
555
+ };
556
+ nativeBridge.callAsyncMethod = wrapped;
557
+ restoreHooks.push(() => {
558
+ nativeBridge.callAsyncMethod = original;
559
+ });
560
+ return;
561
+ }
562
+ const webView = window.ReactNativeWebView;
563
+ if (webView !== void 0 && typeof webView.postMessage === "function") {
564
+ const originalPost = webView.postMessage;
565
+ webView.postMessage = function(message) {
566
+ try {
567
+ observeOutbound(state, message);
568
+ } catch {}
569
+ originalPost.call(this, message);
570
+ };
571
+ restoreHooks.push(() => {
572
+ webView.postMessage = originalPost;
573
+ });
574
+ }
575
+ const emitter = window.__GRANITE_NATIVE_EMITTER;
576
+ if (emitter !== void 0 && typeof emitter.emit === "function") {
577
+ const originalEmit = emitter.emit;
578
+ emitter.emit = function(event, args) {
579
+ try {
580
+ observeSettle(state, event);
581
+ } catch {}
582
+ originalEmit.call(this, event, args);
583
+ };
584
+ restoreHooks.push(() => {
585
+ emitter.emit = originalEmit;
586
+ });
587
+ }
588
+ }
589
+ /**
590
+ * Restores every wrapped bridge hook and removes `window.__ait_bridge` (#749).
591
+ * Idempotent; safe to call when nothing was installed. Wired into
592
+ * {@link detachDebugSurface} (#748) so no bridge wrap survives a run's end.
593
+ */
594
+ function uninstallBridgeObserver() {
595
+ if (!bridgeObserverInstalled) return;
596
+ bridgeObserverInstalled = false;
597
+ const hooks = restoreHooks;
598
+ restoreHooks = [];
599
+ for (const undo of hooks) try {
600
+ undo();
601
+ } catch {}
602
+ if (typeof window !== "undefined") window.__ait_bridge = void 0;
603
+ }
604
+ //#endregion
605
+ //#region src/eruda-overlay.ts
606
+ /**
607
+ * In-app eruda console overlay for the debug attach flow.
608
+ *
609
+ * Spec: docs/superpowers/specs/2026-05-18-in-app-debug-mcp.md
610
+ *
611
+ * This module mounts the eruda in-page console (https://github.com/liriliri/eruda)
612
+ * on the phone screen when a debug session attaches. It is the mobile-only
613
+ * counterpart to the Chii `target.js` injection in {@link attach.ts}: Chii is a
614
+ * REMOTE CDP transport (phone → relay → PC DevTools frontend), whereas eruda is
615
+ * a LOCAL in-page view — a floating button + console/network/DOM/storage panels
616
+ * rendered directly on the phone, with no relay or second device. The two are
617
+ * orthogonal and coexist (eruda opens no WebSocket, mounts into its own
618
+ * `#eruda` shadow host — it cannot collide with the relay WS or the Chii DOM).
619
+ *
620
+ * Build-time absence (the security contract): this module lives in the
621
+ * `@ait-co/debug-console` graph. A consumer wraps its
622
+ * `import('@ait-co/debug-console')` call site in `if (__DEBUG_BUILD__) { … }`;
623
+ * a release build folds that constant to `false` and dead-code-eliminates the
624
+ * whole module — so eruda (and its dynamic `import('eruda')` chunk) is simply
625
+ * absent from release bundles, exactly like the Chii target.js injection. The
626
+ * `import('eruda')` here is a dynamic import precisely so the bundler emits it
627
+ * as a separate chunk that the dead branch never pulls in.
628
+ *
629
+ * Runtime gate: `mountEruda()` is called only from `maybeAttach()` AFTER the
630
+ * full Layer B/C gate has passed (`gateResult.attach === true`) — host
631
+ * allowlist, `debug=1`, relay URL, and TOTP. So eruda inherits the same
632
+ * four-layer defence as the Chii injection, byte-for-byte, with no eruda-
633
+ * specific gate of its own.
634
+ *
635
+ * SECRET-HANDLING: this module reads no secret, TOTP code, relay URL, or host
636
+ * value, and logs none. eruda observes only the page it is mounted on.
637
+ */
638
+ /** Module-level guard against double mount across repeated `maybeAttach` calls. */
639
+ let erudaMounted = false;
640
+ /**
641
+ * The loaded eruda module, captured on a successful {@link mountEruda} so
642
+ * {@link unmountEruda} can call `.destroy()` on the same instance during
643
+ * graceful detach (#748). `null` when eruda was never mounted.
644
+ */
645
+ let erudaModule = null;
646
+ /**
647
+ * Mounts the eruda in-page console once.
648
+ *
649
+ * Idempotent: repeated calls after a successful mount are no-ops, mirroring the
650
+ * `attached` guard in {@link attach.ts}. Fail-silent: if the dynamic import or
651
+ * `eruda.init()` throws (eruda absent, or a runtime that rejects it), the Chii
652
+ * debug session is unaffected — eruda is an additive convenience, not a
653
+ * dependency of the relay path.
654
+ *
655
+ * `eruda.init()` mounts eruda's own floating entry button on the phone screen;
656
+ * tapping it opens the console. We do not add a separate button.
657
+ */
658
+ async function mountEruda() {
659
+ if (erudaMounted || typeof document === "undefined") return;
660
+ erudaMounted = true;
661
+ try {
662
+ const eruda = (await import("eruda")).default;
663
+ eruda.init();
664
+ erudaModule = eruda;
665
+ } catch (err) {
666
+ erudaMounted = false;
667
+ console.debug("[@ait-co/debug-console] eruda console mount skipped:", err);
668
+ }
669
+ }
670
+ /**
671
+ * Unmounts the eruda in-page console (#748 graceful detach).
672
+ *
673
+ * Calls `eruda.destroy()`, which removes eruda's floating entry button, any
674
+ * open panel, and its `#eruda` shadow host — returning the phone screen to a
675
+ * clean, non-debug state when a debug session ends. After a successful unmount
676
+ * the guard is reset so a later {@link mountEruda} (a fresh attach) can
677
+ * re-mount.
678
+ *
679
+ * Idempotent: a call when eruda was never mounted (or already unmounted) is a
680
+ * no-op. Fail-silent: a `destroy()` throw is swallowed — teardown must never
681
+ * throw into the host app.
682
+ */
683
+ function unmountEruda() {
684
+ if (!erudaMounted || erudaModule === null) return;
685
+ try {
686
+ erudaModule.destroy();
687
+ } catch (err) {
688
+ console.debug("[@ait-co/debug-console] eruda console unmount skipped:", err);
689
+ } finally {
690
+ erudaMounted = false;
691
+ erudaModule = null;
692
+ }
693
+ }
694
+ //#endregion
695
+ //#region src/sdk-probe.ts
696
+ /**
697
+ * Runtime probe for the optional Apps in Toss SDK.
698
+ *
699
+ * WHY A PROBE AND NOT AN IMPORT — this package is the only one in the split
700
+ * that can end up inside a consumer's production bundle, and it ships with
701
+ * `eruda` as its single dependency and no peer dependencies at all. A static
702
+ * `import { setScreenAwakeMode } from '@apps-in-toss/web-framework'` would undo
703
+ * both properties at once: it forces the SDK into the module graph of every
704
+ * consumer that reaches this file, and it pins the package to whichever SDK
705
+ * major exports that symbol. `setScreenAwakeMode` is not part of
706
+ * `@apps-in-toss/web-framework` 2.x's web surface at all — it arrives in the
707
+ * 3.0 line — so a static import does not merely couple us to a version, it
708
+ * breaks 2.x consumers outright.
709
+ *
710
+ * The probe keeps the dependency edge at runtime, where it can be absent
711
+ * without consequence: `import()` inside a `try`, a `typeof === 'function'`
712
+ * check on the export we actually want, and silence when either step fails. The
713
+ * SDK is a devDependency here purely so `tsc` and the unit tests can resolve the
714
+ * specifier; the bundle marks it external so it is never inlined. That makes a
715
+ * 2.x↔3.x GA flip a no-op for this package — the same shape `@ait-co/polyfill`'s
716
+ * `loadTossSdk()` uses.
717
+ *
718
+ * SECRET-HANDLING: nothing here reads or logs a relay URL, a tunnel host, or an
719
+ * auth code. Failures are swallowed; the only thing ever printed is a package-
720
+ * prefixed debug line naming the API that was unavailable.
721
+ */
722
+ /**
723
+ * Resolved SDK namespace, `null` once a probe has established the SDK is
724
+ * absent, `undefined` while no probe has run yet. Module-scoped, so a
725
+ * `vi.resetModules()` in a test gives a fresh probe.
726
+ */
727
+ let sdkCache;
728
+ /**
729
+ * Loads the SDK module if the consumer has it installed, else `null`.
730
+ *
731
+ * Never throws and never rejects. The return type is deliberately a bare
732
+ * property bag rather than `typeof import('@apps-in-toss/web-framework')`:
733
+ * callers must feature-sniff the export they need, which is what keeps this
734
+ * file compiling — and behaving — identically against 2.x and 3.x type
735
+ * surfaces.
736
+ */
737
+ async function loadTossSdk() {
738
+ if (sdkCache !== void 0) return sdkCache;
739
+ try {
740
+ sdkCache = await import("@apps-in-toss/web-framework");
741
+ } catch {
742
+ sdkCache = null;
743
+ }
744
+ return sdkCache;
745
+ }
746
+ /**
747
+ * The SDK namespace if a previous {@link loadTossSdk} already resolved it, else
748
+ * `null`. Never starts a probe of its own.
749
+ *
750
+ * This exists for the unload path. `pagehide` / `beforeunload` handlers are
751
+ * expected to do their work synchronously — a browser tearing the page down is
752
+ * under no obligation to drain the microtask queue first, so a teardown that
753
+ * begins with `await import(...)` can simply never reach its own body and leave
754
+ * the screen held awake. After a successful attach the cache is warm (the same
755
+ * probe already ran to hold the screen), so the release can be dispatched
756
+ * immediately instead.
757
+ */
758
+ function getLoadedTossSdk() {
759
+ return sdkCache ?? null;
760
+ }
761
+ /**
762
+ * Reads a callable export off the SDK namespace, or `null` when it is absent or
763
+ * is not a function. May throw only if the namespace itself is hostile — every
764
+ * caller therefore keeps this inside its own `try`.
765
+ */
766
+ function pickExport(sdk, name) {
767
+ const value = sdk[name];
768
+ return typeof value === "function" ? value : null;
769
+ }
770
+ /**
771
+ * Calls an SDK export by name when it exists, otherwise resolves quietly.
772
+ *
773
+ * @param name - Export to look up on the SDK namespace.
774
+ * @param args - Arguments forwarded verbatim to the export.
775
+ * @returns `true` when the call was dispatched and settled without throwing,
776
+ * `false` when the SDK or the export was unavailable or the call rejected.
777
+ */
778
+ async function callTossSdk(name, ...args) {
779
+ const sdk = await loadTossSdk();
780
+ if (sdk === null) return false;
781
+ try {
782
+ const fn = pickExport(sdk, name);
783
+ if (fn === null) return false;
784
+ await fn(...args);
785
+ return true;
786
+ } catch (err) {
787
+ console.debug(`[@ait-co/debug-console] ${name} failed:`, err);
788
+ return false;
789
+ }
790
+ }
791
+ /**
792
+ * Dispatches an SDK call in the current tick, using only an already-warm cache.
793
+ *
794
+ * Returns `false` without doing anything when no probe has resolved yet — the
795
+ * caller is expected to fall back to {@link callTossSdk}. Unlike that function,
796
+ * `true` here means only "dispatched": a returned promise is left to settle on
797
+ * its own, because the whole point is not to await inside an unload handler.
798
+ *
799
+ * @param name - Export to look up on the SDK namespace.
800
+ * @param args - Arguments forwarded verbatim to the export.
801
+ */
802
+ function callTossSdkNow(name, ...args) {
803
+ const sdk = getLoadedTossSdk();
804
+ if (sdk === null) return false;
805
+ try {
806
+ const fn = pickExport(sdk, name);
807
+ if (fn === null) return false;
808
+ const result = fn(...args);
809
+ if (result instanceof Promise) result.catch((err) => {
810
+ console.debug(`[@ait-co/debug-console] ${name} failed:`, err);
811
+ });
812
+ return true;
813
+ } catch (err) {
814
+ console.debug(`[@ait-co/debug-console] ${name} failed:`, err);
815
+ return false;
816
+ }
817
+ }
818
+ /**
819
+ * Keeps the phone screen awake for the duration of a debug session (or releases
820
+ * it again). No-op when the SDK is absent or does not expose the API.
821
+ *
822
+ * SECRET-HANDLING: only flips a boolean flag — reads nothing from the relay URL
823
+ * or the auth code.
824
+ *
825
+ * @param enabled - `true` to hold the screen awake, `false` to restore normal
826
+ * sleep behaviour.
827
+ */
828
+ async function setScreenAwake(enabled) {
829
+ return callTossSdk("setScreenAwakeMode", { enabled });
830
+ }
831
+ /**
832
+ * Same as {@link setScreenAwake}, but dispatched in the current tick from an
833
+ * already-warm cache; `false` means nothing was dispatched and the caller
834
+ * should fall back to the async form. Used by the teardown path — see
835
+ * {@link getLoadedTossSdk} for why an unload handler cannot await.
836
+ *
837
+ * @param enabled - `true` to hold the screen awake, `false` to restore normal
838
+ * sleep behaviour.
839
+ */
840
+ function setScreenAwakeNow(enabled) {
841
+ return callTossSdkNow("setScreenAwakeMode", { enabled });
842
+ }
843
+ //#endregion
844
+ //#region src/attach.ts
845
+ /**
846
+ * In-app Chii target injection for the debug attach flow.
847
+ *
848
+ * Spec: docs/superpowers/specs/2026-05-18-in-app-debug-mcp.md
849
+ * "MCP attach" topology section — Phase 1 browser-side implementation.
850
+ *
851
+ * This module bridges the 3-layer gate result to a Chii `target.js` script
852
+ * injection. The Chii npm package is the relay SERVER — the in-app side is
853
+ * a plain `<script src="…/target.js">` pointing at the relay host. No chii
854
+ * npm dependency is needed here.
855
+ */
856
+ /**
857
+ * Converts a validated `wss:` relay URL into the Chii `target.js` script URL.
858
+ *
859
+ * Scheme is mapped `wss:` → `https:`. Host and port are preserved.
860
+ * Pathname is set to `/target.js` (or `/at/<code>/target.js` when a TOTP code
861
+ * is given) regardless of the relay path. Query params and hash from the
862
+ * relay URL are dropped — the target script URL is a static asset path on the
863
+ * same host.
864
+ *
865
+ * TOTP path-prefix transport (issue #466): chii's stock `target.js` derives
866
+ * its WS endpoint from the script `src` (`scriptEl.src.replace('target.js',
867
+ * '')`), so embedding the current TOTP code in the script URL *path* is the
868
+ * only way the phone-side WS upgrade can carry it — both the script fetch and
869
+ * the derived `wss://<host>/at/<code>/target/<id>` dial inherit the prefix,
870
+ * and the relay verifies + strips it before chii parses the URL. The
871
+ * `window.ChiiServerUrl` + query alternative does NOT work: chii appends
872
+ * `target/<id>` to the serverUrl string, which would land after a `?`.
873
+ *
874
+ * SECRET-HANDLING: `atCode` rides only inside the returned URL (the intended
875
+ * transport — same exposure grade as the daemon client's `at=` query). It is
876
+ * never logged here.
877
+ *
878
+ * @example
879
+ * deriveTargetScriptUrl('wss://abc.trycloudflare.com/relay')
880
+ * // → 'https://abc.trycloudflare.com/target.js'
881
+ *
882
+ * deriveTargetScriptUrl('wss://h.example.com:9100/', '123456')
883
+ * // → 'https://h.example.com:9100/at/123456/target.js'
884
+ *
885
+ * @param relayUrl - Validated `wss:` relay URL from the gate result.
886
+ * @param atCode - Current TOTP code from the page URL's `at` query param, or
887
+ * `null`/`undefined`/`''` to keep the legacy un-prefixed URL.
888
+ */
889
+ function deriveTargetScriptUrl(relayUrl, atCode) {
890
+ const u = new URL(relayUrl);
891
+ u.protocol = "https:";
892
+ u.pathname = atCode !== void 0 && atCode !== null && atCode !== "" ? `/at/${encodeURIComponent(atCode)}/target.js` : "/target.js";
893
+ u.search = "";
894
+ u.hash = "";
895
+ return u.toString();
896
+ }
897
+ /**
898
+ * Converts a validated `wss:` relay URL into the version-handshake URL.
899
+ *
900
+ * Same scheme/host/TOTP-prefix derivation as {@link deriveTargetScriptUrl},
901
+ * with this package's build-time `__VERSION__` as the single query value. The
902
+ * handshake gets its own path rather than a query on `target.js` because chii's
903
+ * stock `target.js` derives its WebSocket endpoint from its own script `src`
904
+ * (`src.replace('target.js', '')`) and then appends `target/<id>` — a query
905
+ * string there would land in the middle of the derived endpoint.
906
+ *
907
+ * SECRET-HANDLING: `atCode` rides only inside the returned URL (the same
908
+ * transport the target script already uses) and is never logged.
909
+ *
910
+ * @param relayUrl - Validated `wss:` relay URL from the gate result.
911
+ * @param atCode - Current TOTP code from the page URL's `at` query param, or
912
+ * `null`/`undefined`/`''` for the un-prefixed form.
913
+ */
914
+ function deriveHandshakeUrl(relayUrl, atCode) {
915
+ const u = new URL(relayUrl);
916
+ u.protocol = "https:";
917
+ u.pathname = atCode !== void 0 && atCode !== null && atCode !== "" ? `/at/${encodeURIComponent(atCode)}${ATTACH_HANDSHAKE_PATH}` : ATTACH_HANDSHAKE_PATH;
918
+ u.search = `?v=${encodeURIComponent("0.1.1")}`;
919
+ u.hash = "";
920
+ return u.toString();
921
+ }
922
+ /**
923
+ * Reports this package's build-time version to the relay, fire-and-forget.
924
+ *
925
+ * Runs just before `target.js` is injected. Deliberately unawaited and
926
+ * fail-silent: a device↔host version skew is worth a diagnostic on the daemon
927
+ * side, never a reason to hold up or abort an attach. `mode: 'no-cors'` because
928
+ * the relay origin differs from the page origin and we have no use for the
929
+ * response — the daemon is the only party that acts on this.
930
+ *
931
+ * SECRET-HANDLING: the URL (which carries the TOTP code in its path prefix) is
932
+ * never logged, not even on failure.
933
+ */
934
+ function reportProtocolVersion(relayUrl, atCode) {
935
+ if (typeof fetch !== "function") return;
936
+ try {
937
+ fetch(deriveHandshakeUrl(relayUrl, atCode), {
938
+ method: "GET",
939
+ mode: "no-cors",
940
+ cache: "no-store",
941
+ keepalive: true
942
+ }).catch(() => {});
943
+ } catch {}
944
+ }
945
+ /** Module-level guard against double-injection within a page lifecycle. */
946
+ let attached = false;
947
+ /** One-shot guard for the parent notification (both observer + onerror probe). */
948
+ let authExpiredNotified = false;
949
+ /** Set once a relay-bound socket closed with 4401 — flips dials to fail-fast. */
950
+ let relayAuthExpired = false;
951
+ /** Guard against stacking multiple observer wrappers on window.WebSocket. */
952
+ let wsObserverInstalled = false;
953
+ /**
954
+ * Broadcasts relay-socket lifecycle to any in-page listener (#730) — the
955
+ * on-phone debug indicator subscribes to this instead of wrapping
956
+ * `window.WebSocket` a second time.
957
+ *
958
+ * SECRET-HANDLING: the CustomEvent `detail` carries ONLY the enum
959
+ * `'open' | 'close'` — never a close code, host, relay URL, or TOTP value.
960
+ */
961
+ function broadcastRelayWsState(state) {
962
+ if (typeof window === "undefined") return;
963
+ window.dispatchEvent(new CustomEvent(RELAY_WS_STATE_EVENT, { detail: { state } }));
964
+ }
965
+ /**
966
+ * Posts the `auth-expired` block signal to the parent launcher shell, once.
967
+ *
968
+ * Mirrors the existing `reason: 'auth'` postMessage in {@link maybeAttach}.
969
+ * SECRET-HANDLING: the payload carries ONLY the reason enum — never the code,
970
+ * secret, host, or relay URL.
971
+ */
972
+ function notifyAuthExpired() {
973
+ if (authExpiredNotified) return;
974
+ if (typeof window === "undefined" || window.parent === window) return;
975
+ authExpiredNotified = true;
976
+ window.parent.postMessage({
977
+ type: "ait:debug-attach-blocked",
978
+ reason: "auth-expired"
979
+ }, "*");
980
+ }
981
+ /**
982
+ * Normalises a URL into a comparable origin key, mapping the HTTP scheme pair
983
+ * onto the WS pair (`https:`→`wss:`, `http:`→`ws:`) so the `wss:` relay URL
984
+ * from the gate result matches the dials target.js derives from its
985
+ * `https://…/target.js` script src. Returns `null` for unparsable URLs.
986
+ */
987
+ function wsOriginKey(rawUrl) {
988
+ let parsed;
989
+ try {
990
+ parsed = new URL(rawUrl);
991
+ } catch {
992
+ return null;
993
+ }
994
+ return `${parsed.protocol === "https:" ? "wss:" : parsed.protocol === "http:" ? "ws:" : parsed.protocol}//${parsed.host}`;
995
+ }
996
+ /**
997
+ * Builds a dummy WebSocket that never connects and closes immediately
998
+ * (asynchronously, with the 4401 code) — returned for relay-bound dials after
999
+ * auth expiry so chii's internal reconnect loop stops producing real network
1000
+ * traffic. We cannot stop the loop itself (it lives inside stock target.js);
1001
+ * we can only make each iteration free.
1002
+ *
1003
+ * Both `onclose`-style property handlers and `addEventListener` listeners are
1004
+ * fired — stock target.js uses property handlers, but we cannot know every
1005
+ * consumer. (A consumer wiring BOTH would see a double callback; acceptable
1006
+ * for a retry scheduler and irrelevant for chii.)
1007
+ */
1008
+ function createFailFastSocket(url) {
1009
+ const eventTarget = new EventTarget();
1010
+ const sock = {
1011
+ url,
1012
+ readyState: 3,
1013
+ bufferedAmount: 0,
1014
+ extensions: "",
1015
+ protocol: "",
1016
+ binaryType: "blob",
1017
+ onopen: null,
1018
+ onmessage: null,
1019
+ onerror: null,
1020
+ onclose: null,
1021
+ close() {},
1022
+ send() {},
1023
+ addEventListener: eventTarget.addEventListener.bind(eventTarget),
1024
+ removeEventListener: eventTarget.removeEventListener.bind(eventTarget),
1025
+ dispatchEvent: eventTarget.dispatchEvent.bind(eventTarget),
1026
+ CONNECTING: 0,
1027
+ OPEN: 1,
1028
+ CLOSING: 2,
1029
+ CLOSED: 3
1030
+ };
1031
+ setTimeout(() => {
1032
+ const errorEvent = new Event("error");
1033
+ sock.onerror?.(errorEvent);
1034
+ eventTarget.dispatchEvent(errorEvent);
1035
+ let closeEvent;
1036
+ try {
1037
+ closeEvent = new CloseEvent("close", {
1038
+ code: RELAY_AUTH_REJECT_CLOSE_CODE,
1039
+ reason: RELAY_AUTH_REJECT_REASON,
1040
+ wasClean: false
1041
+ });
1042
+ } catch {
1043
+ closeEvent = Object.assign(new Event("close"), {
1044
+ code: RELAY_AUTH_REJECT_CLOSE_CODE,
1045
+ reason: RELAY_AUTH_REJECT_REASON,
1046
+ wasClean: false
1047
+ });
1048
+ }
1049
+ sock.onclose?.(closeEvent);
1050
+ eventTarget.dispatchEvent(closeEvent);
1051
+ }, 0);
1052
+ return sock;
1053
+ }
1054
+ /** Grace window before a non-terminal relay close tears the surface down. */
1055
+ const RECONNECT_GRACE_MS = 5e3;
1056
+ /** One-shot guard so the teardown runs at most once per page lifecycle. */
1057
+ let debugSurfaceDetached = false;
1058
+ /** Pending grace-window timer for a non-terminal close, or `null`. */
1059
+ let pendingDetachTimer = null;
1060
+ /** Cancels a scheduled teardown — called when a relay socket re-opens. */
1061
+ function cancelScheduledDetach() {
1062
+ if (pendingDetachTimer !== null) {
1063
+ clearTimeout(pendingDetachTimer);
1064
+ pendingDetachTimer = null;
1065
+ }
1066
+ }
1067
+ /**
1068
+ * Schedules {@link detachDebugSurface} after {@link RECONNECT_GRACE_MS} unless
1069
+ * a reconnect cancels it first. No-op if teardown already ran or is already
1070
+ * scheduled. Defensive: if `setTimeout` is somehow unavailable, tears down
1071
+ * immediately rather than never.
1072
+ */
1073
+ function scheduleDetach() {
1074
+ if (debugSurfaceDetached || pendingDetachTimer !== null) return;
1075
+ if (typeof setTimeout === "undefined") {
1076
+ detachDebugSurface();
1077
+ return;
1078
+ }
1079
+ pendingDetachTimer = setTimeout(() => {
1080
+ pendingDetachTimer = null;
1081
+ detachDebugSurface();
1082
+ }, RECONNECT_GRACE_MS);
1083
+ }
1084
+ /**
1085
+ * Idempotent, non-throwing teardown of the in-app debug surface (issue #748).
1086
+ *
1087
+ * Removes every debug-surface element WE injected and restores the one side
1088
+ * effect WE applied:
1089
+ * 1. The CDP-injected `#__ait_debug_indicator` badge (the persistent
1090
+ * "Debugger Disconnected" element). Its live heartbeat/pending-call timer
1091
+ * (#749) is stopped first via the badge controller's `stop()` so no 1 Hz
1092
+ * interval leaks past detach; `buildIndicatorExpression` also
1093
+ * self-dismisses the node — this is the in-app hard guarantee, idempotent,
1094
+ * a no-op if it is already gone.
1095
+ * 2. The eruda in-page console (floating button + any open panel).
1096
+ * 3. The native-bridge call observer (#749) — its `callAsyncMethod` /
1097
+ * `postMessage` / emitter wraps are restored and `window.__ait_bridge` is
1098
+ * removed, so nothing we wrapped survives the run's end.
1099
+ * 4. keepAwake — forced on at attach; restored here so a run that ends
1100
+ * WITHOUT a page unload does not leave the screen pinned awake (the
1101
+ * existing `beforeunload` restore only covers the unload path).
1102
+ *
1103
+ * Deliberately NOT touched: the `window.WebSocket` observer proxy (kept so the
1104
+ * #478 post-4401 fail-fast survives; it is non-blocking and never absorbs
1105
+ * input), and any NATIVE overlay (out of our layer — see the block comment
1106
+ * above and issue #748 hypothesis (a)).
1107
+ *
1108
+ * Never throws into the host app — every step is individually guarded.
1109
+ * Exported for unit tests and for a consumer that wants to force a clean detach.
1110
+ */
1111
+ function detachDebugSurface() {
1112
+ if (debugSurfaceDetached) return;
1113
+ debugSurfaceDetached = true;
1114
+ cancelScheduledDetach();
1115
+ try {
1116
+ if (typeof window !== "undefined") window.__ait_indicator?.stop?.();
1117
+ if (typeof document !== "undefined") document.getElementById("__ait_debug_indicator")?.remove();
1118
+ } catch {}
1119
+ try {
1120
+ unmountEruda();
1121
+ } catch {}
1122
+ try {
1123
+ uninstallBridgeObserver();
1124
+ } catch {}
1125
+ try {
1126
+ if (!setScreenAwakeNow(false)) setScreenAwake(false);
1127
+ } catch {}
1128
+ }
1129
+ /**
1130
+ * Wraps `window.WebSocket` with a relay-origin-scoped observer (issue #478).
1131
+ *
1132
+ * - Connections whose URL origin does NOT match the relay origin pass through
1133
+ * to the native constructor untouched — app traffic is never observed.
1134
+ * - Relay-origin connections get a `close` listener: code 4401 (the relay's
1135
+ * named TOTP rejection) flips the module into the expired state and posts
1136
+ * `reason: 'auth-expired'` to the parent launcher shell (once).
1137
+ * - After 4401, further relay-origin dials return a fail-fast dummy socket so
1138
+ * target.js's autonomous reconnect loop stops hitting the network.
1139
+ *
1140
+ * Installed by {@link maybeAttach} BEFORE target.js is injected so the very
1141
+ * first dial is already observed. Idempotent per page lifecycle. Exported for
1142
+ * unit tests.
1143
+ */
1144
+ function installRelayWsObserver(relayUrl) {
1145
+ if (wsObserverInstalled) return;
1146
+ if (typeof window === "undefined" || typeof window.WebSocket !== "function") return;
1147
+ const relayKey = wsOriginKey(relayUrl);
1148
+ if (relayKey === null) return;
1149
+ wsObserverInstalled = true;
1150
+ window.__ait_relay_ws_observed = true;
1151
+ window.addEventListener("pagehide", () => detachDebugSurface(), { once: true });
1152
+ const NativeWebSocket = window.WebSocket;
1153
+ const observed = new Proxy(NativeWebSocket, { construct(target, args) {
1154
+ const url = String(args[0]);
1155
+ if (wsOriginKey(url) !== relayKey) return Reflect.construct(target, args);
1156
+ if (relayAuthExpired) return createFailFastSocket(url);
1157
+ const ws = Reflect.construct(target, args);
1158
+ ws.addEventListener("open", () => {
1159
+ broadcastRelayWsState("open");
1160
+ cancelScheduledDetach();
1161
+ });
1162
+ ws.addEventListener("close", (event) => {
1163
+ broadcastRelayWsState("close");
1164
+ if (event.code === 4401) {
1165
+ relayAuthExpired = true;
1166
+ notifyAuthExpired();
1167
+ detachDebugSurface();
1168
+ } else scheduleDetach();
1169
+ });
1170
+ ws.addEventListener("error", () => {
1171
+ scheduleDetach();
1172
+ });
1173
+ return ws;
1174
+ } });
1175
+ window.WebSocket = observed;
1176
+ }
1177
+ /**
1178
+ * The webViewType self-report postMessage type (#580).
1179
+ *
1180
+ * Canonical definition + the receive-side parser live in
1181
+ * `src/mock/safe-area-bridge.ts` (`WEB_VIEW_TYPE_MESSAGE_TYPE`,
1182
+ * `parseWebViewTypeMessage`). It is re-declared here as a local literal so the
1183
+ * in-app entry does NOT import the mock barrel (which would drag mock internals
1184
+ * — navigation/state — into the dogfood in-app graph). The two literals are
1185
+ * kept in sync by value; if one changes, change both. Same decoupling pattern
1186
+ * the launcher fixture uses for its message-type constants.
1187
+ */
1188
+ const WEB_VIEW_TYPE_MESSAGE_TYPE = "ait:web-view-type";
1189
+ /** Guard so the webViewType self-report is posted at most once per page. */
1190
+ let webViewTypeReported = false;
1191
+ /**
1192
+ * Self-report the mini-app's webViewType to the parent launcher shell, ONCE
1193
+ * (#580).
1194
+ *
1195
+ * The mini-app's type is the build constant `__WEB_VIEW_TYPE__`, injected by
1196
+ * the devtools unplugin from `granite.config.ts`'s `webViewProps.type`. The
1197
+ * launcher (env-2 PWA) is cross-origin and cannot read it directly, so the
1198
+ * framed page posts it to `window.parent`; the launcher switches to game mode
1199
+ * automatically (no manual `?navBarType=game` URL edit).
1200
+ *
1201
+ * Defensive by construction — must NEVER break attach:
1202
+ * - `__WEB_VIEW_TYPE__` is a CONSUMER-build define; it does not exist in
1203
+ * devtools' own build or where the unplugin did not inject it. The `typeof`
1204
+ * guard avoids a ReferenceError; an absent constant is a silent no-op.
1205
+ * - Only posts when inside an iframe (`window.parent !== window`) — a
1206
+ * top-level load has no launcher shell to receive the message.
1207
+ * - The SDK's deprecated `'external'` alias of `partner` (web-framework 2.6.1)
1208
+ * is mapped to `'partner'`; the launcher only emulates `partner` | `game`.
1209
+ * - Wrapped in try/catch so any postMessage/iframe edge case is swallowed.
1210
+ *
1211
+ * SECRET-HANDLING: the payload carries ONLY the webViewType enum — no host,
1212
+ * relay URL, code, or secret.
1213
+ */
1214
+ function reportWebViewType() {
1215
+ if (webViewTypeReported) return;
1216
+ try {
1217
+ if (typeof window === "undefined" || window.parent === window) return;
1218
+ const raw = typeof __WEB_VIEW_TYPE__ !== "undefined" ? __WEB_VIEW_TYPE__ : void 0;
1219
+ if (raw === void 0) return;
1220
+ const value = raw === "game" ? "game" : raw === "partner" || raw === "external" ? "partner" : null;
1221
+ if (value === null) return;
1222
+ webViewTypeReported = true;
1223
+ window.parent.postMessage({
1224
+ type: WEB_VIEW_TYPE_MESSAGE_TYPE,
1225
+ value
1226
+ }, "*");
1227
+ } catch {}
1228
+ }
1229
+ /**
1230
+ * Evaluates the 3-layer debug gate and, if the gate passes, injects the Chii
1231
+ * `target.js` script into `document.head`.
1232
+ *
1233
+ * Idempotent — calling more than once is safe. The second call is a no-op if
1234
+ * a script with the same `src` is already present in the document, and the
1235
+ * module-level `attached` flag prevents redundant DOM queries after the first
1236
+ * successful injection.
1237
+ *
1238
+ * Safe to call even if `document` is somehow unavailable (defensive boundary
1239
+ * guard — in practice this always runs in a real WebView).
1240
+ *
1241
+ * **keepAwake side effect**: on a successful attach, `setScreenAwakeMode({
1242
+ * enabled: true })` is called so the phone screen stays awake during the debug
1243
+ * session. A `beforeunload` handler restores normal sleep on page unload.
1244
+ * Opt out by adding `noKeepAwake=1` to the page URL query string — the check
1245
+ * reads `window.location.search` directly, consistent with other guards in
1246
+ * this file.
1247
+ *
1248
+ * @param gateResult - Optional pre-evaluated gate result for testability.
1249
+ * Defaults to `checkDebugGate()` which reads the current page URL. Passing a
1250
+ * custom value avoids the need to manipulate `window.location` in tests.
1251
+ */
1252
+ function maybeAttach(gateResult = checkDebugGate()) {
1253
+ reportWebViewType();
1254
+ if (!gateResult.attach) {
1255
+ console.debug(`[@ait-co/debug-console] debug attach skipped — gate blocked (reason: ${gateResult.reason})`);
1256
+ if (gateResult.reason === "auth" && typeof window !== "undefined" && window.parent !== window) window.parent.postMessage({
1257
+ type: "ait:debug-attach-blocked",
1258
+ reason: "auth"
1259
+ }, "*");
1260
+ return;
1261
+ }
1262
+ if (attached) return;
1263
+ if (typeof document === "undefined") return;
1264
+ const atCode = typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("at") : null;
1265
+ const src = deriveTargetScriptUrl(gateResult.relayUrl, atCode);
1266
+ reportProtocolVersion(gateResult.relayUrl, atCode);
1267
+ installRelayWsObserver(gateResult.relayUrl);
1268
+ installBridgeObserver();
1269
+ if (document.querySelector(`script[src="${src}"]`) !== null) {
1270
+ attached = true;
1271
+ return;
1272
+ }
1273
+ const script = document.createElement("script");
1274
+ script.src = src;
1275
+ script.async = true;
1276
+ script.onerror = () => {
1277
+ fetch(src).then((res) => {
1278
+ if (res.status === 401) notifyAuthExpired();
1279
+ }).catch(() => {});
1280
+ };
1281
+ (document.head ?? document.documentElement).appendChild(script);
1282
+ attached = true;
1283
+ mountEruda();
1284
+ if (typeof window !== "undefined" && new URLSearchParams(window.location.search).get("noKeepAwake") === "1") return;
1285
+ setScreenAwake(true).then((held) => {
1286
+ if (!held) return;
1287
+ window.addEventListener("beforeunload", () => {
1288
+ if (!setScreenAwakeNow(false)) setScreenAwake(false);
1289
+ }, { once: true });
1290
+ });
1291
+ }
1292
+ //#endregion
1293
+ //#region src/index.ts
1294
+ /**
1295
+ * @ait-co/debug-console entry point.
1296
+ *
1297
+ * Spec: docs/superpowers/specs/2026-05-18-in-app-debug-mcp.md
1298
+ *
1299
+ * Phase 1 — gate + browser-side Chii target injection.
1300
+ * WebSocket relay, QR/paste UI, and AI-host MCP bin are later phases that
1301
+ * require real-device validation and are not included here.
1302
+ *
1303
+ * This thin entry reads `window.location` and calls the pure
1304
+ * {@link evaluateDebugGate} function. All testable logic lives in `./gate.ts`
1305
+ * and `./attach.ts`, not here.
1306
+ *
1307
+ * Layer A of the activation gate (build-time) is NOT enforced in this module.
1308
+ * It is the consumer's responsibility: the consumer wraps its
1309
+ * `import('@ait-co/debug-console')` call site in `if (__DEBUG_BUILD__) { … }`
1310
+ * (see sdk-example `src/main.tsx`), where `__DEBUG_BUILD__` is a
1311
+ * consumer-build-time constant. A release consumer build folds that constant
1312
+ * to `false` and dead-code-eliminates this whole module. This package is
1313
+ * pre-built and ships with `__DEBUG_BUILD__` already resolved at devtools'
1314
+ * publish time, so it could never re-evaluate the consumer's build channel —
1315
+ * which is exactly why Layer A lives at the consumer guard, not here.
1316
+ */
1317
+ /**
1318
+ * Evaluates the runtime debug activation layers (B and C) against the current
1319
+ * page URL.
1320
+ *
1321
+ * Returns the gate result. Callers can check `result.attach` to decide whether
1322
+ * to proceed with debug surface attachment.
1323
+ *
1324
+ * This function reads `window.location` only — both the hostname (Layer B1
1325
+ * host allowlist) and the search params (Layers B2 and C). Layer A
1326
+ * (build-time) is enforced by the consumer's `if (__DEBUG_BUILD__)` guard
1327
+ * around the import site, not here — see the file-level comment. Consumers
1328
+ * call this with no arguments, so the Layer B1 host check is picked up with
1329
+ * no change at the call site.
1330
+ */
1331
+ function checkDebugGate() {
1332
+ return evaluateDebugGate({
1333
+ hostname: window.location.hostname,
1334
+ searchParams: new URLSearchParams(window.location.search)
1335
+ });
1336
+ }
1337
+ //#endregion
1338
+ exports.BRIDGE_CALL_EVENT = BRIDGE_CALL_EVENT;
1339
+ exports.checkDebugGate = checkDebugGate;
1340
+ exports.deriveTargetScriptUrl = deriveTargetScriptUrl;
1341
+ exports.detachDebugSurface = detachDebugSurface;
1342
+ exports.evaluateDebugGate = evaluateDebugGate;
1343
+ exports.installBridgeObserver = installBridgeObserver;
1344
+ exports.isPrivateAppsHost = isPrivateAppsHost;
1345
+ exports.isTossminiHost = isTossminiHost;
1346
+ exports.isTrycloudflareHost = isTrycloudflareHost;
1347
+ exports.maybeAttach = maybeAttach;
1348
+ exports.mountEruda = mountEruda;
1349
+ exports.reportWebViewType = reportWebViewType;
1350
+ exports.uninstallBridgeObserver = uninstallBridgeObserver;
1351
+ exports.unmountEruda = unmountEruda;
1352
+
1353
+ //# sourceMappingURL=index.cjs.map