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