@ait-co/devtools 0.1.117 → 0.1.119

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/attach-orchestrator-CFotueL3.js +1749 -0
  2. package/dist/attach-orchestrator-CFotueL3.js.map +1 -0
  3. package/dist/attach-orchestrator-CII9Gl5m.js +2797 -0
  4. package/dist/attach-orchestrator-CII9Gl5m.js.map +1 -0
  5. package/dist/attach-orchestrator-C_6xb_L5.js +3 -0
  6. package/dist/attach-orchestrator-DEJfLm7V.js +1749 -0
  7. package/dist/attach-orchestrator-DEJfLm7V.js.map +1 -0
  8. package/dist/{cli-CvUNQKqw.js → attach-orchestrator-qFEMBUwb.js} +3 -805
  9. package/dist/attach-orchestrator-qFEMBUwb.js.map +1 -0
  10. package/dist/{bundle-KFs4t-wc.d.ts → bundle-CA1TCXED.d.ts} +1 -1
  11. package/dist/bundle-CA1TCXED.d.ts.map +1 -0
  12. package/dist/capture-BmK_cBqQ.d.ts +58 -0
  13. package/dist/capture-BmK_cBqQ.d.ts.map +1 -0
  14. package/dist/{cdp-connection-C0AP0tH2.d.ts → cdp-connection-DB2zgthr.d.ts} +1 -1
  15. package/dist/{cdp-connection-C0AP0tH2.d.ts.map → cdp-connection-DB2zgthr.d.ts.map} +1 -1
  16. package/dist/cell-BJiaGlVu.js +3 -0
  17. package/dist/cell-BPWZUm_X.js +85 -0
  18. package/dist/cell-BPWZUm_X.js.map +1 -0
  19. package/dist/cell-Cv3e_qwn.js +84 -0
  20. package/dist/cell-Cv3e_qwn.js.map +1 -0
  21. package/dist/cell-bLwQ4gTq.js +85 -0
  22. package/dist/cell-bLwQ4gTq.js.map +1 -0
  23. package/dist/cell-nrWFeqvG.js +84 -0
  24. package/dist/cell-nrWFeqvG.js.map +1 -0
  25. package/dist/cli-RhzASQef.js +1057 -0
  26. package/dist/cli-RhzASQef.js.map +1 -0
  27. package/dist/debug-server-BhHVy3XT.js +1191 -0
  28. package/dist/debug-server-BhHVy3XT.js.map +1 -0
  29. package/dist/{debug-server-jrI9U_f4.js → debug-server-Bi6jLuY6.js} +467 -2989
  30. package/dist/debug-server-Bi6jLuY6.js.map +1 -0
  31. package/dist/debug-server-Buc8yoa7.js +1909 -0
  32. package/dist/debug-server-Buc8yoa7.js.map +1 -0
  33. package/dist/{debug-server-BvrESnaV.js → debug-server-C_5ag9jj.js} +5 -3
  34. package/dist/debug-server-C_5ag9jj.js.map +1 -0
  35. package/dist/mcp/cli.js +3 -2
  36. package/dist/mcp/cli.js.map +1 -1
  37. package/dist/mcp/server.js +1 -1
  38. package/dist/panel/index.js +1 -1
  39. package/dist/{pool-htlVnEFl.d.ts → pool-U9FrxEuR.d.ts} +5 -5
  40. package/dist/{pool-htlVnEFl.d.ts.map → pool-U9FrxEuR.d.ts.map} +1 -1
  41. package/dist/relay-factory-DVI7TrX4.js +69 -0
  42. package/dist/relay-factory-DVI7TrX4.js.map +1 -0
  43. package/dist/relay-secret-store-BcVrWwTq.js +153 -0
  44. package/dist/relay-secret-store-BcVrWwTq.js.map +1 -0
  45. package/dist/{relay-secret-store-BHcOmaNK.js → relay-secret-store-BlFEhqwb.js} +1 -1
  46. package/dist/{relay-secret-store-CmqchhR5.js → relay-secret-store-CFc9n0OA.js} +1 -1
  47. package/dist/{relay-secret-store-CmqchhR5.js.map → relay-secret-store-CFc9n0OA.js.map} +1 -1
  48. package/dist/{relay-secret-store-CkA7KNUb.js → relay-secret-store-CmDDfZMh.js} +2 -2
  49. package/dist/{relay-secret-store-CkA7KNUb.js.map → relay-secret-store-CmDDfZMh.js.map} +1 -1
  50. package/dist/relay-secret-store-DNPJKHNs.js +153 -0
  51. package/dist/relay-secret-store-DNPJKHNs.js.map +1 -0
  52. package/dist/relay-url-store-CdA58fgw.js +122 -0
  53. package/dist/relay-url-store-CdA58fgw.js.map +1 -0
  54. package/dist/{relay-url-store-C0qukm3R.js → relay-url-store-CnL2zwbH.js} +2 -2
  55. package/dist/{relay-url-store-C0qukm3R.js.map → relay-url-store-CnL2zwbH.js.map} +1 -1
  56. package/dist/{relay-url-store-NDtEcOE-.js → relay-url-store-DGQ-HPQC.js} +2 -2
  57. package/dist/{relay-url-store-NDtEcOE-.js.map → relay-url-store-DGQ-HPQC.js.map} +1 -1
  58. package/dist/relay-url-store-Dv5HSzwb.js +122 -0
  59. package/dist/relay-url-store-Dv5HSzwb.js.map +1 -0
  60. package/dist/{relay-worker-DWW4vZxU.d.ts → relay-worker-D-3aAyDO.d.ts} +28 -4
  61. package/dist/relay-worker-D-3aAyDO.d.ts.map +1 -0
  62. package/dist/{runtime-BU-iMHz6.d.ts → runtime-D57Rtnsd.d.ts} +1 -1
  63. package/dist/{runtime-BU-iMHz6.d.ts.map → runtime-D57Rtnsd.d.ts.map} +1 -1
  64. package/dist/test-runner/bundle.d.ts +1 -1
  65. package/dist/test-runner/bundle.js +45 -27
  66. package/dist/test-runner/bundle.js.map +1 -1
  67. package/dist/test-runner/capture.d.ts +2 -0
  68. package/dist/test-runner/capture.js +44 -0
  69. package/dist/test-runner/capture.js.map +1 -0
  70. package/dist/test-runner/cli.d.ts +85 -12
  71. package/dist/test-runner/cli.d.ts.map +1 -1
  72. package/dist/test-runner/cli.js +2 -2
  73. package/dist/test-runner/config.d.ts +76 -2
  74. package/dist/test-runner/config.d.ts.map +1 -1
  75. package/dist/test-runner/config.js +4 -2
  76. package/dist/test-runner/config.js.map +1 -1
  77. package/dist/test-runner/pool.d.ts +1 -1
  78. package/dist/test-runner/relay-factory.d.ts +11136 -0
  79. package/dist/test-runner/relay-factory.d.ts.map +1 -0
  80. package/dist/test-runner/relay-factory.js +69 -0
  81. package/dist/test-runner/relay-factory.js.map +1 -0
  82. package/dist/test-runner/relay-worker.d.ts +1 -1
  83. package/dist/test-runner/relay-worker.js +66 -20
  84. package/dist/test-runner/relay-worker.js.map +1 -1
  85. package/dist/test-runner/report.d.ts +106 -0
  86. package/dist/test-runner/report.d.ts.map +1 -0
  87. package/dist/test-runner/report.js +139 -0
  88. package/dist/test-runner/report.js.map +1 -0
  89. package/dist/test-runner/rpc.d.ts +2 -2
  90. package/dist/test-runner/runtime.d.ts +1 -1
  91. package/dist/test-runner/task-graph.d.ts +1 -1
  92. package/dist/{totp-D70zD5tJ.js → totp-0bvlo9Yb.js} +1 -1
  93. package/dist/{totp-D70zD5tJ.js.map → totp-0bvlo9Yb.js.map} +1 -1
  94. package/dist/totp-DfekTBk3.js +211 -0
  95. package/dist/totp-DfekTBk3.js.map +1 -0
  96. package/dist/totp-zGIlDsZS.js +3 -0
  97. package/package.json +1 -1
  98. package/dist/bundle-KFs4t-wc.d.ts.map +0 -1
  99. package/dist/cli-CvUNQKqw.js.map +0 -1
  100. package/dist/debug-server-BvrESnaV.js.map +0 -1
  101. package/dist/debug-server-jrI9U_f4.js.map +0 -1
  102. package/dist/relay-worker-DWW4vZxU.d.ts.map +0 -1
  103. package/dist/totp-D104cJQN.js +0 -3
@@ -0,0 +1,69 @@
1
+ //#region src/test-runner/relay-factory.ts
2
+ /**
3
+ * Builds a {@link RelayConnectionFactory} that opens a standalone env3 relay
4
+ * connection.
5
+ *
6
+ * `open()` performs the full attach lifecycle and BLOCKS for tens of seconds (up
7
+ * to `timeoutMs`) while a human scans the rendered QR with their phone — there
8
+ * is no way around the manual scan for env3. It resolves with the live
9
+ * `CdpConnection` once a matching page attaches; `close()` tears the relay
10
+ * family down.
11
+ *
12
+ * The factory holds the booted relay family in a closure so `close()` can stop
13
+ * it. A second `open()` on the same factory boots a fresh family (the previous
14
+ * one should have been `close()`d first).
15
+ */
16
+ function createRelayConnectionFactory(opts) {
17
+ const projectRoot = opts.projectRoot ?? process.cwd();
18
+ const timeoutMs = opts.timeoutMs ?? 6e5;
19
+ const headless = opts.headless === true;
20
+ let family;
21
+ return {
22
+ async open() {
23
+ const { prepareAttach, renderAndMaybeWait } = await import("../attach-orchestrator-DEJfLm7V.js");
24
+ const { injectDebugIndicator, injectGlobals } = await import("../cell-Cv3e_qwn.js");
25
+ const { loadRelaySecretReadOnly } = await import("../relay-secret-store-DNPJKHNs.js");
26
+ const { bootRelayFamily, buildRelayVerifyAuth } = await import("../debug-server-Buc8yoa7.js");
27
+ await loadRelaySecretReadOnly({ projectRoot });
28
+ const booted = await bootRelayFamily({ verifyAuth: buildRelayVerifyAuth() });
29
+ family = booted;
30
+ const attachDeps = {
31
+ getTunnelStatus: booted.getTunnelStatus ?? (() => ({
32
+ up: false,
33
+ wssUrl: null
34
+ })),
35
+ getTotpSecret: () => process.env.AIT_DEBUG_TOTP_SECRET,
36
+ qrHttpServer: void 0,
37
+ onAttachUrlBuilt: void 0,
38
+ canOpenBrowser: () => !headless
39
+ };
40
+ const prep = await prepareAttach(attachDeps, "relay-dev", { scheme_url: opts.schemeUrl }, booted.connection);
41
+ if (!prep.ok) {
42
+ booted.stop();
43
+ family = void 0;
44
+ throw new Error("createRelayConnectionFactory: attach preparation failed — check the scheme_url and that the relay tunnel is up");
45
+ }
46
+ const waitResult = await renderAndMaybeWait(attachDeps, prep, true, timeoutMs, booted.connection);
47
+ if (waitResult.isError) {
48
+ booted.stop();
49
+ family = void 0;
50
+ const timeoutSec = Math.round(timeoutMs / 1e3);
51
+ throw new Error(`createRelayConnectionFactory: attach timed out after ${timeoutSec}s — phone did not scan the QR within the timeout`);
52
+ }
53
+ const qrChunks = waitResult.content.filter((c) => c.type === "text").map((c) => c.text);
54
+ opts.onQrContent(qrChunks);
55
+ await injectDebugIndicator(booted.connection);
56
+ if (opts.cell !== void 0) await injectGlobals(booted.connection, { __AIT_CELL__: opts.cell });
57
+ await booted.connection.enableDomains();
58
+ return booted.connection;
59
+ },
60
+ async close(_connection) {
61
+ family?.stop();
62
+ family = void 0;
63
+ }
64
+ };
65
+ }
66
+ //#endregion
67
+ export { createRelayConnectionFactory };
68
+
69
+ //# sourceMappingURL=relay-factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay-factory.js","names":[],"sources":["../../src/test-runner/relay-factory.ts"],"sourcesContent":["/**\n * Relay connection factory for the Vitest custom pool (devtools#696).\n *\n * The Vitest pool (`pool.ts`) takes a {@link RelayConnectionFactory} that knows\n * how to `open()` a live CDP relay connection (boot relay → QR → phone scan →\n * cell inject → enableDomains) and `close()` it. Before this module that exact\n * assembly lived only inside the `devtools-test` CLI's `main()`; the standalone\n * CLI and the Vitest pool would otherwise each hand-roll it and drift.\n *\n * This is the single source of that assembly. `cli.ts` is refactored to call\n * `createRelayConnectionFactory(...).open()`, and `definePhoneVitestConfig`\n * (config.ts) exposes it so a downstream `vitest.config.ts` can wire the pool:\n *\n * import { createRelayConnectionFactory } from '@ait-co/devtools/test-runner';\n * const connection = createRelayConnectionFactory({\n * schemeUrl,\n * cell,\n * // REQUIRED — own the stdout decision (the chunks carry the relay wss +\n * // TOTP code). Suppress on non-interactive stdout; print otherwise.\n * onQrContent: (chunks) => {\n * if (!process.stdout.isTTY) return;\n * for (const c of chunks) process.stdout.write(`${c}\\n`);\n * },\n * });\n * export default defineConfig({ test: definePhoneVitestConfig({ connection }) });\n *\n * The heavy boot graph (chii relay, cloudflared, ws, debug-server) is pulled via\n * DYNAMIC import inside `open()` — so merely importing this module (or the\n * `@ait-co/devtools/test-runner` barrel) does NOT statically drag that graph in.\n *\n * SECRET-HANDLING: relay wss URLs, scheme URLs, and the TOTP secret/code are\n * never logged. `open()` reads the project-local `.ait_relay` secret read-only\n * (never mints) and the minted TOTP code rides only inside the QR `at=` param.\n *\n * Node-only. react-free (CdpConnection + lazily-imported MCP boot helpers only).\n */\n\nimport type { AttachDeps } from '../mcp/attach-orchestrator.js';\nimport type { CdpConnection } from '../mcp/cdp-connection.js';\nimport type { RelayConnectionFactory } from './pool.js';\n\n// NOTE: every value import below is a DYNAMIC import inside `open()`. This module\n// keeps ONLY type-level static imports so that re-exporting it from the\n// `@ait-co/devtools/test-runner` barrel (config.ts) does NOT statically drag the\n// heavy MCP graph (cell.ts → attach-orchestrator.ts → tools.ts → server-lock,\n// plus chii/cloudflared via debug-server) onto that Node-config entry.\n\n/** Options for {@link createRelayConnectionFactory}. */\nexport interface RelayConnectionFactoryOptions {\n /**\n * intoss-private:// scheme URL from `ait deploy --scheme-only` (env3). The\n * phone cold-loads the candidate bundle this URL points at. SECRET-HANDLING:\n * never logged.\n */\n schemeUrl: string;\n /**\n * Project root for the `.ait_relay` secret lookup (read-only). Defaults to\n * `process.cwd()`.\n */\n projectRoot?: string;\n /**\n * Attach wait timeout in ms — how long `open()` waits for the phone to scan\n * the QR and attach. Defaults to 600 000 (10 min) to give time for a manual\n * scan. (The per-file evaluate timeout is separate, passed via the pool's\n * `run` options.)\n */\n timeoutMs?: number;\n /** Disable browser auto-open of the QR dashboard (text QR only). */\n headless?: boolean;\n /**\n * Cell axes injected as `__AIT_CELL__` before the first test bundle runs, so\n * sdk-example's capture picks up the correct sdkLine/platform. Optional — when\n * omitted no cell is injected. The values are not secrets.\n */\n cell?: { sdkLine: string; platform: string };\n /**\n * Receives the QR/attach render content (text chunks) from\n * `renderAndMaybeWait`, so the caller decides whether to print them — e.g.\n * suppress on non-interactive stdout.\n *\n * REQUIRED (not optional) on purpose: these chunks contain the QR payload\n * (which encodes the relay wss + TOTP `at=` code) and the attach JSON block.\n * Making the hook mandatory means the factory never falls back to printing\n * them itself — a downstream `vitest.config.ts` consumer that wires this via\n * the `@ait-co/devtools/test-runner` barrel is forced to make an explicit\n * stdout decision rather than silently leaking the secret-bearing block.\n *\n * SECRET-HANDLING: when a non-interactive caller is detected the hook MUST\n * suppress the WHOLE chunk (not just `attachUrl`), since `relayUrl` rides in\n * the same block.\n */\n onQrContent: (textChunks: string[]) => void;\n}\n\n/**\n * Builds a {@link RelayConnectionFactory} that opens a standalone env3 relay\n * connection.\n *\n * `open()` performs the full attach lifecycle and BLOCKS for tens of seconds (up\n * to `timeoutMs`) while a human scans the rendered QR with their phone — there\n * is no way around the manual scan for env3. It resolves with the live\n * `CdpConnection` once a matching page attaches; `close()` tears the relay\n * family down.\n *\n * The factory holds the booted relay family in a closure so `close()` can stop\n * it. A second `open()` on the same factory boots a fresh family (the previous\n * one should have been `close()`d first).\n */\nexport function createRelayConnectionFactory(\n opts: RelayConnectionFactoryOptions,\n): RelayConnectionFactory {\n const projectRoot = opts.projectRoot ?? process.cwd();\n const timeoutMs = opts.timeoutMs ?? 600_000;\n const headless = opts.headless === true;\n\n // Captured so close() can stop the family that open() booted.\n let family: { connection: CdpConnection; stop(): void } | undefined;\n\n return {\n async open(): Promise<CdpConnection> {\n // Dynamic imports: keep the chii/cloudflared/debug-server graph OFF the\n // static import graph of this module (and the test-runner config barrel).\n const { prepareAttach, renderAndMaybeWait } = await import('../mcp/attach-orchestrator.js');\n const { injectDebugIndicator, injectGlobals } = await import('./cell.js');\n const { loadRelaySecretReadOnly } = await import('../mcp/relay-secret-store.js');\n const { bootRelayFamily, buildRelayVerifyAuth } = await import('../mcp/debug-server.js');\n\n // Load the project-local .ait_relay secret into AIT_DEBUG_TOTP_SECRET\n // BEFORE booting the relay so assertRelayAuthConfigured()/buildRelayVerifyAuth()\n // at the boot site see it. Read-only — never mints. SECRET-HANDLING: the\n // value is never logged here.\n await loadRelaySecretReadOnly({ projectRoot });\n\n const booted = await bootRelayFamily({ verifyAuth: buildRelayVerifyAuth() });\n family = booted;\n\n // Assemble AttachDeps with no dashboard/SSE (CLI/pool is not the daemon).\n const attachDeps: AttachDeps = {\n getTunnelStatus: booted.getTunnelStatus ?? (() => ({ up: false, wssUrl: null })),\n getTotpSecret: () => process.env.AIT_DEBUG_TOTP_SECRET,\n qrHttpServer: undefined,\n onAttachUrlBuilt: undefined,\n canOpenBrowser: () => !headless,\n };\n\n const prep = await prepareAttach(\n attachDeps,\n 'relay-dev',\n { scheme_url: opts.schemeUrl },\n booted.connection,\n );\n if (!prep.ok) {\n booted.stop();\n family = undefined;\n // SECRET-HANDLING: do NOT surface `prep.error.content` in the thrown\n // message. Some prep error paths build their text from attach\n // components, and the CLI catch writes `e.message` to stderr — embedding\n // that text risks leaking the scheme/relay wss URL. The detailed\n // diagnostic is the daemon/dashboard's job; the factory throws a\n // secret-free message only.\n throw new Error(\n 'createRelayConnectionFactory: attach preparation failed — check the scheme_url and that the relay tunnel is up',\n );\n }\n\n // Render the QR + wait for the phone to attach. SECRET-HANDLING: this\n // function never logs scheme/wss/TOTP values.\n const waitResult = await renderAndMaybeWait(\n attachDeps,\n prep,\n true,\n timeoutMs,\n booted.connection,\n );\n if (waitResult.isError) {\n booted.stop();\n family = undefined;\n // SECRET-HANDLING (BLOCKER fix): `waitResult.content` is the timeout\n // result built from `buildTimeoutError(baseText, ...)`, and `baseText`\n // is `JSON.stringify({ attachUrl, relayUrl, ... })` — `attachUrl` carries\n // the TOTP `at=` code and `relayUrl` is the relay `wss://` URL. The CLI\n // catch writes `e.message` to stderr, so extracting that text here would\n // leak the relay wss + TOTP code on every timeout. Throw a secret-free\n // message with only the timeout duration.\n const timeoutSec = Math.round(timeoutMs / 1000);\n throw new Error(\n `createRelayConnectionFactory: attach timed out after ${timeoutSec}s — phone did not scan the QR within the timeout`,\n );\n }\n\n // Surface the QR/attach render content to the caller, which owns the\n // stdout decision (suppress on non-interactive stdout). There is no\n // fallback that prints here itself: `onQrContent` is a required option so\n // the secret-bearing block (attachUrl TOTP + relayUrl wss) can never be\n // emitted without an explicit caller decision. SECRET-HANDLING.\n const qrChunks = waitResult.content\n .filter((c): c is { type: 'text'; text: string } => c.type === 'text')\n .map((c) => c.text);\n opts.onQrContent(qrChunks);\n\n // Debugger attached — show the on-phone \"Debugger Connected\" badge.\n await injectDebugIndicator(booted.connection);\n\n // Inject the cell globals before any test bundle runs (session-global).\n if (opts.cell !== undefined) {\n await injectGlobals(booted.connection, { __AIT_CELL__: opts.cell });\n }\n\n // Open the CDP client websocket + enable domains so the first run's\n // Runtime.evaluate and console stream are live. enableDomains is\n // idempotent; runTestFilesOverRelay also calls it defensively.\n await booted.connection.enableDomains();\n\n return booted.connection;\n },\n\n async close(_connection: CdpConnection): Promise<void> {\n // family.stop() is synchronous best-effort: closes the CDP connection and\n // shuts down the relay + cloudflared child.\n family?.stop();\n family = undefined;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4GA,SAAgB,6BACd,MACwB;CACxB,MAAM,cAAc,KAAK,eAAe,QAAQ,KAAK;CACrD,MAAM,YAAY,KAAK,aAAa;CACpC,MAAM,WAAW,KAAK,aAAa;CAGnC,IAAI;AAEJ,QAAO;EACL,MAAM,OAA+B;GAGnC,MAAM,EAAE,eAAe,uBAAuB,MAAM,OAAO;GAC3D,MAAM,EAAE,sBAAsB,kBAAkB,MAAM,OAAO;GAC7D,MAAM,EAAE,4BAA4B,MAAM,OAAO;GACjD,MAAM,EAAE,iBAAiB,yBAAyB,MAAM,OAAO;AAM/D,SAAM,wBAAwB,EAAE,aAAa,CAAC;GAE9C,MAAM,SAAS,MAAM,gBAAgB,EAAE,YAAY,sBAAsB,EAAE,CAAC;AAC5E,YAAS;GAGT,MAAM,aAAyB;IAC7B,iBAAiB,OAAO,2BAA2B;KAAE,IAAI;KAAO,QAAQ;KAAM;IAC9E,qBAAqB,QAAQ,IAAI;IACjC,cAAc,KAAA;IACd,kBAAkB,KAAA;IAClB,sBAAsB,CAAC;IACxB;GAED,MAAM,OAAO,MAAM,cACjB,YACA,aACA,EAAE,YAAY,KAAK,WAAW,EAC9B,OAAO,WACR;AACD,OAAI,CAAC,KAAK,IAAI;AACZ,WAAO,MAAM;AACb,aAAS,KAAA;AAOT,UAAM,IAAI,MACR,iHACD;;GAKH,MAAM,aAAa,MAAM,mBACvB,YACA,MACA,MACA,WACA,OAAO,WACR;AACD,OAAI,WAAW,SAAS;AACtB,WAAO,MAAM;AACb,aAAS,KAAA;IAQT,MAAM,aAAa,KAAK,MAAM,YAAY,IAAK;AAC/C,UAAM,IAAI,MACR,wDAAwD,WAAW,kDACpE;;GAQH,MAAM,WAAW,WAAW,QACzB,QAAQ,MAA2C,EAAE,SAAS,OAAO,CACrE,KAAK,MAAM,EAAE,KAAK;AACrB,QAAK,YAAY,SAAS;AAG1B,SAAM,qBAAqB,OAAO,WAAW;AAG7C,OAAI,KAAK,SAAS,KAAA,EAChB,OAAM,cAAc,OAAO,YAAY,EAAE,cAAc,KAAK,MAAM,CAAC;AAMrE,SAAM,OAAO,WAAW,eAAe;AAEvC,UAAO,OAAO;;EAGhB,MAAM,MAAM,aAA2C;AAGrD,WAAQ,MAAM;AACd,YAAS,KAAA;;EAEZ"}
@@ -1,2 +1,2 @@
1
- import { a as runTestFilesOverRelay, i as flattenResults, n as RelayRunOptions, r as RelayRunReport, t as FileResult } from "../relay-worker-DWW4vZxU.js";
1
+ import { a as runTestFilesOverRelay, i as flattenResults, n as RelayRunOptions, r as RelayRunReport, t as FileResult } from "../relay-worker-D-3aAyDO.js";
2
2
  export { FileResult, RelayRunOptions, RelayRunReport, flattenResults, runTestFilesOverRelay };
@@ -1,4 +1,5 @@
1
1
  import { bundleTestFile } from "./bundle.js";
2
+ import { parseCaptureLines } from "./capture.js";
2
3
  import { injectAndRunBundle } from "./rpc.js";
3
4
  //#region src/test-runner/relay-worker.ts
4
5
  /**
@@ -26,27 +27,45 @@ async function runTestFilesOverRelay(connection, files, opts) {
26
27
  const wallStart = Date.now();
27
28
  const startedAt = new Date(wallStart).toISOString();
28
29
  const fileResults = [];
29
- for (const file of files) {
30
- let fileEntry;
31
- try {
32
- const { code } = await bundleTestFile(file, opts?.bundleOptions);
33
- const rpcResult = await injectAndRunBundle(connection, code, opts?.timeoutMs);
34
- if (rpcResult.ok) fileEntry = {
35
- file,
36
- result: rpcResult.report
37
- };
38
- else fileEntry = {
39
- file,
40
- result: { error: rpcResult.error }
41
- };
42
- } catch (e) {
43
- fileEntry = {
44
- file,
45
- result: { error: e instanceof Error ? e.message : String(e) }
46
- };
30
+ let domainsEnabled = false;
31
+ try {
32
+ await connection.enableDomains();
33
+ domainsEnabled = true;
34
+ } catch (e) {
35
+ process.stderr.write(`relay-worker: enableDomains() failed before run — console capture may be empty (${e instanceof Error ? e.message : String(e)})\n`);
36
+ }
37
+ const collectCaptures = opts?.collectCaptures === true;
38
+ const liveConsole = [];
39
+ let unsubscribeConsole;
40
+ if (collectCaptures && domainsEnabled) unsubscribeConsole = connection.on("Runtime.consoleAPICalled", (event) => {
41
+ liveConsole.push(event);
42
+ });
43
+ try {
44
+ for (const file of files) {
45
+ let fileEntry;
46
+ try {
47
+ const { code } = await bundleTestFile(file, opts?.bundleOptions);
48
+ const rpcResult = await injectAndRunBundle(connection, code, opts?.timeoutMs);
49
+ if (rpcResult.ok) fileEntry = {
50
+ file,
51
+ result: rpcResult.report
52
+ };
53
+ else fileEntry = {
54
+ file,
55
+ result: { error: rpcResult.error }
56
+ };
57
+ } catch (e) {
58
+ fileEntry = {
59
+ file,
60
+ result: { error: e instanceof Error ? e.message : String(e) }
61
+ };
62
+ }
63
+ fileResults.push(fileEntry);
47
64
  }
48
- fileResults.push(fileEntry);
65
+ } finally {
66
+ unsubscribeConsole?.();
49
67
  }
68
+ const captures = collectCaptures ? parseCaptureLines(liveConsole.map((e) => ({ text: renderConsoleLineText(e) }))) : [];
50
69
  const totals = fileResults.reduce((acc, { result }) => {
51
70
  if ("error" in result) {
52
71
  acc.failed += 1;
@@ -68,10 +87,37 @@ async function runTestFilesOverRelay(connection, files, opts) {
68
87
  startedAt,
69
88
  duration: Date.now() - wallStart,
70
89
  files: fileResults,
71
- totals
90
+ totals,
91
+ captures
72
92
  };
73
93
  }
74
94
  /**
95
+ * Renders one `Runtime.consoleAPICalled` event to a single line of text, the
96
+ * same way `tools.ts#normalizeConsoleMessage` does (args rendered + space-
97
+ * joined). Inlined here (≈8 lines) so this module avoids importing `tools.ts`,
98
+ * which would drag the heavy MCP/Node graph (server-lock, parent-watcher, …)
99
+ * onto the test-runner entry.
100
+ *
101
+ * SECRET-HANDLING: this only stringifies console args; the caller's
102
+ * allowlist-prefix parser then discards everything that is not a genuine
103
+ * `__AIT_CAPTURE__` line.
104
+ */
105
+ function renderConsoleLineText(event) {
106
+ return event.args.map((arg) => {
107
+ if (arg.value !== void 0) {
108
+ if (typeof arg.value === "string") return arg.value;
109
+ try {
110
+ return JSON.stringify(arg.value);
111
+ } catch {
112
+ return String(arg.value);
113
+ }
114
+ }
115
+ if (arg.description !== void 0) return arg.description;
116
+ if (arg.className !== void 0) return arg.className;
117
+ return arg.subtype ?? arg.type;
118
+ }).join(" ");
119
+ }
120
+ /**
75
121
  * Flattens all test results from a `RelayRunReport` into a single array.
76
122
  * Files that errored during bundle/inject produce a synthetic failed entry.
77
123
  */
@@ -1 +1 @@
1
- {"version":3,"file":"relay-worker.js","names":[],"sources":["../../src/test-runner/relay-worker.ts"],"sourcesContent":["/**\n * Orchestrator: runs a list of test files sequentially over a CDP relay.\n *\n * Each file goes through: bundle → inject → run → collect.\n * This is the transport layer: it does NOT integrate with Vitest's pool or the\n * MCP surface. The Vitest custom pool (`pool.ts`) and the `run_tests` MCP tool\n * are separate callers that build on this orchestrator.\n *\n * Single-attach constraint: only one page is active at a time. Files run\n * sequentially; parallel execution across targets is out of scope.\n *\n * The 30-second per-file timeout is inherited from `injectAndRunBundle`.\n * For suites that exceed it, split the file into smaller pieces.\n *\n * SECRET-HANDLING: file paths are surfaced in reports; relay URLs are not.\n */\n\nimport type { CdpConnection } from '../mcp/cdp-connection.js';\nimport { type BundleOptions, bundleTestFile } from './bundle.js';\nimport { injectAndRunBundle } from './rpc.js';\nimport type { RunReport, TestResult } from './runtime.js';\n\n/** Per-file result in the aggregate `RunReport`. */\nexport interface FileResult {\n /** Absolute or relative path to the test file. */\n file: string;\n /** Full run report for this file, or an error if bundling/injection failed. */\n result: RunReport | { error: string };\n}\n\n/** Aggregate report returned by `runTestFilesOverRelay`. */\nexport interface RelayRunReport {\n /** ISO timestamp of when the run started. */\n startedAt: string;\n /** Total elapsed wall-clock milliseconds. */\n duration: number;\n /** Per-file results in execution order. */\n files: FileResult[];\n /** Flattened totals across all files. */\n totals: {\n passed: number;\n failed: number;\n skipped: number;\n total: number;\n };\n}\n\n/** Options for `runTestFilesOverRelay`. */\nexport interface RelayRunOptions {\n /**\n * Options forwarded to `bundleTestFile` for each file.\n */\n bundleOptions?: BundleOptions;\n /**\n * Per-file evaluate timeout in milliseconds. Defaults to 30 000.\n * Increase for long-running suites or split the file.\n */\n timeoutMs?: number;\n}\n\n/**\n * Runs all `files` sequentially over the given CDP `connection`.\n *\n * For each file:\n * 1. Bundle with esbuild (includes SDK shim + runtime).\n * 2. Inject into the attached page via `Runtime.evaluate`.\n * 3. Await the `RunReport` JSON response.\n * 4. Accumulate results.\n *\n * Returns a `RelayRunReport` with per-file results and flattened totals.\n *\n * This function does NOT open or manage the relay connection — the caller\n * is responsible for attaching and closing it.\n *\n * TODO (#645): implement the Vitest `PoolRunnerInitializer` interface here\n * so that `runTestFilesOverRelay` can be used as a Vitest pool entry.\n *\n * @param connection - Active CDP connection (relay or local kind).\n * @param files - Absolute paths to test files, run in order.\n * @param opts - Optional per-run overrides.\n */\nexport async function runTestFilesOverRelay(\n connection: CdpConnection,\n files: string[],\n opts?: RelayRunOptions,\n): Promise<RelayRunReport> {\n const wallStart = Date.now();\n const startedAt = new Date(wallStart).toISOString();\n const fileResults: FileResult[] = [];\n\n for (const file of files) {\n let fileEntry: FileResult;\n try {\n const { code } = await bundleTestFile(file, opts?.bundleOptions);\n const rpcResult = await injectAndRunBundle(connection, code, opts?.timeoutMs);\n if (rpcResult.ok) {\n fileEntry = { file, result: rpcResult.report };\n } else {\n fileEntry = { file, result: { error: rpcResult.error } };\n }\n } catch (e) {\n // Capture bundle/inject errors per-file so subsequent files still run.\n fileEntry = {\n file,\n result: {\n error: e instanceof Error ? e.message : String(e),\n },\n };\n }\n fileResults.push(fileEntry);\n }\n\n const totals = fileResults.reduce(\n (acc, { result }) => {\n if ('error' in result) {\n // Treat whole-file errors as a single failure.\n acc.failed += 1;\n acc.total += 1;\n } else {\n acc.passed += result.passed;\n acc.failed += result.failed;\n acc.skipped += result.skipped;\n acc.total += result.passed + result.failed + result.skipped;\n }\n return acc;\n },\n { passed: 0, failed: 0, skipped: 0, total: 0 },\n );\n\n return {\n startedAt,\n duration: Date.now() - wallStart,\n files: fileResults,\n totals,\n };\n}\n\n/**\n * Flattens all test results from a `RelayRunReport` into a single array.\n * Files that errored during bundle/inject produce a synthetic failed entry.\n */\nexport function flattenResults(report: RelayRunReport): Array<TestResult & { file: string }> {\n const out: Array<TestResult & { file: string }> = [];\n for (const { file, result } of report.files) {\n if ('error' in result) {\n out.push({\n file,\n name: `<bundle/inject error>`,\n status: 'fail',\n duration: 0,\n error: result.error,\n });\n } else {\n for (const t of result.tests) {\n out.push({ ...t, file });\n }\n }\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiFA,eAAsB,sBACpB,YACA,OACA,MACyB;CACzB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,YAAY,IAAI,KAAK,UAAU,CAAC,aAAa;CACnD,MAAM,cAA4B,EAAE;AAEpC,MAAK,MAAM,QAAQ,OAAO;EACxB,IAAI;AACJ,MAAI;GACF,MAAM,EAAE,SAAS,MAAM,eAAe,MAAM,MAAM,cAAc;GAChE,MAAM,YAAY,MAAM,mBAAmB,YAAY,MAAM,MAAM,UAAU;AAC7E,OAAI,UAAU,GACZ,aAAY;IAAE;IAAM,QAAQ,UAAU;IAAQ;OAE9C,aAAY;IAAE;IAAM,QAAQ,EAAE,OAAO,UAAU,OAAO;IAAE;WAEnD,GAAG;AAEV,eAAY;IACV;IACA,QAAQ,EACN,OAAO,aAAa,QAAQ,EAAE,UAAU,OAAO,EAAE,EAClD;IACF;;AAEH,cAAY,KAAK,UAAU;;CAG7B,MAAM,SAAS,YAAY,QACxB,KAAK,EAAE,aAAa;AACnB,MAAI,WAAW,QAAQ;AAErB,OAAI,UAAU;AACd,OAAI,SAAS;SACR;AACL,OAAI,UAAU,OAAO;AACrB,OAAI,UAAU,OAAO;AACrB,OAAI,WAAW,OAAO;AACtB,OAAI,SAAS,OAAO,SAAS,OAAO,SAAS,OAAO;;AAEtD,SAAO;IAET;EAAE,QAAQ;EAAG,QAAQ;EAAG,SAAS;EAAG,OAAO;EAAG,CAC/C;AAED,QAAO;EACL;EACA,UAAU,KAAK,KAAK,GAAG;EACvB,OAAO;EACP;EACD;;;;;;AAOH,SAAgB,eAAe,QAA8D;CAC3F,MAAM,MAA4C,EAAE;AACpD,MAAK,MAAM,EAAE,MAAM,YAAY,OAAO,MACpC,KAAI,WAAW,OACb,KAAI,KAAK;EACP;EACA,MAAM;EACN,QAAQ;EACR,UAAU;EACV,OAAO,OAAO;EACf,CAAC;KAEF,MAAK,MAAM,KAAK,OAAO,MACrB,KAAI,KAAK;EAAE,GAAG;EAAG;EAAM,CAAC;AAI9B,QAAO"}
1
+ {"version":3,"file":"relay-worker.js","names":[],"sources":["../../src/test-runner/relay-worker.ts"],"sourcesContent":["/**\n * Orchestrator: runs a list of test files sequentially over a CDP relay.\n *\n * Each file goes through: bundle → inject → run → collect.\n * This is the transport layer: it does NOT integrate with Vitest's pool or the\n * MCP surface. The Vitest custom pool (`pool.ts`) and the `run_tests` MCP tool\n * are separate callers that build on this orchestrator.\n *\n * Single-attach constraint: only one page is active at a time. Files run\n * sequentially; parallel execution across targets is out of scope.\n *\n * The 30-second per-file timeout is inherited from `injectAndRunBundle`.\n * For suites that exceed it, split the file into smaller pieces.\n *\n * SECRET-HANDLING: file paths are surfaced in reports; relay URLs are not.\n */\n\nimport type { CdpConnection, ConsoleApiCalledEvent } from '../mcp/cdp-connection.js';\nimport { type BundleOptions, bundleTestFile } from './bundle.js';\nimport { type AitCaptureLine, parseCaptureLines } from './capture.js';\nimport { injectAndRunBundle } from './rpc.js';\nimport type { RunReport, TestResult } from './runtime.js';\n\n/** Per-file result in the aggregate `RunReport`. */\nexport interface FileResult {\n /** Absolute or relative path to the test file. */\n file: string;\n /** Full run report for this file, or an error if bundling/injection failed. */\n result: RunReport | { error: string };\n}\n\n/** Aggregate report returned by `runTestFilesOverRelay`. */\nexport interface RelayRunReport {\n /** ISO timestamp of when the run started. */\n startedAt: string;\n /** Total elapsed wall-clock milliseconds. */\n duration: number;\n /** Per-file results in execution order. */\n files: FileResult[];\n /** Flattened totals across all files. */\n totals: {\n passed: number;\n failed: number;\n skipped: number;\n total: number;\n };\n /**\n * `__AIT_CAPTURE__` lines harvested from the page console during the run\n * (additive field, devtools#696). Empty unless `collectCaptures` was set.\n * Each entry is opaque (`{ category, json }`) — devtools does not interpret\n * the record shape, only forwards it for downstream 2.x↔3.0 diffing.\n *\n * SECRET-HANDLING: only lines matching the `__AIT_CAPTURE__ ` allowlist\n * prefix reach here; relay/wss/scheme noise lines are dropped in\n * `parseCaptureLines`.\n */\n captures: AitCaptureLine[];\n}\n\n/** Options for `runTestFilesOverRelay`. */\nexport interface RelayRunOptions {\n /**\n * Options forwarded to `bundleTestFile` for each file.\n */\n bundleOptions?: BundleOptions;\n /**\n * Per-file evaluate timeout in milliseconds. Defaults to 30 000.\n * Increase for long-running suites or split the file.\n */\n timeoutMs?: number;\n /**\n * When `true`, registers a live `Runtime.consoleAPICalled` listener for the\n * duration of the run and harvests `__AIT_CAPTURE__` lines into\n * `RelayRunReport.captures`. Defaults to **false** so the build-only\n * eval/e2e path (and the Vitest pool) pay no listener/state overhead —\n * `captures` is then an empty array.\n *\n * The listener is registered just BEFORE the first file runs and removed in a\n * `finally` so it never accumulates across runs (no ring-buffer drain — the\n * default 500-entry buffer would silently drop lines via `shift`).\n */\n collectCaptures?: boolean;\n}\n\n/**\n * Runs all `files` sequentially over the given CDP `connection`.\n *\n * For each file:\n * 1. Bundle with esbuild (includes SDK shim + runtime).\n * 2. Inject into the attached page via `Runtime.evaluate`.\n * 3. Await the `RunReport` JSON response.\n * 4. Accumulate results.\n *\n * Returns a `RelayRunReport` with per-file results and flattened totals.\n *\n * This function does NOT open or manage the relay connection — the caller\n * is responsible for attaching and closing it.\n *\n * TODO (#645): implement the Vitest `PoolRunnerInitializer` interface here\n * so that `runTestFilesOverRelay` can be used as a Vitest pool entry.\n *\n * @param connection - Active CDP connection (relay or local kind).\n * @param files - Absolute paths to test files, run in order.\n * @param opts - Optional per-run overrides.\n */\nexport async function runTestFilesOverRelay(\n connection: CdpConnection,\n files: string[],\n opts?: RelayRunOptions,\n): Promise<RelayRunReport> {\n const wallStart = Date.now();\n const startedAt = new Date(wallStart).toISOString();\n const fileResults: FileResult[] = [];\n\n // Enable CDP domains ONCE up front. Without this the relay connection has not\n // opened its client websocket, so the very first `Runtime.evaluate` (in\n // `injectAndRunBundle`) explodes AND `Runtime.consoleAPICalled` never streams\n // — the console capture harvest would be structurally 0. `enableDomains()` is\n // idempotent (see chii-connection: early-returns when the ws is already OPEN,\n // and shares an in-flight promise), so calling it here is safe even when a\n // caller (the MCP `run_tests` path) already enabled it.\n //\n // Failure here (e.g. no target attached yet) must NOT throw the whole run: the\n // per-file inject below produces a structured error result instead. We warn on\n // stderr (secret-free) and continue. SECRET-HANDLING: the message names the\n // failure only — no relay/wss URL.\n let domainsEnabled = false;\n try {\n await connection.enableDomains();\n domainsEnabled = true;\n } catch (e) {\n process.stderr.write(\n `relay-worker: enableDomains() failed before run — console capture may be empty (${\n e instanceof Error ? e.message : String(e)\n })\\n`,\n );\n }\n\n // Live console capture (#696): when requested, accumulate every\n // `Runtime.consoleAPICalled` event into a local array via a LIVE listener\n // registered just before the run. We deliberately do NOT drain\n // `getBufferedEvents` after the fact — that ring buffer caps at 500 and\n // `shift()`s older entries, so a chatty run would silently lose capture lines.\n // The listener is removed in `finally` so it never bleeds into the next run.\n //\n // Gate the listener on `domainsEnabled`: if enableDomains() soft-failed, the\n // client ws never opened so `Runtime.consoleAPICalled` cannot stream —\n // registering would only add a dead listener that never fires. (The `finally`\n // unsubscribe is an undefined no-op in that case, so this stays safe.)\n const collectCaptures = opts?.collectCaptures === true;\n const liveConsole: ConsoleApiCalledEvent[] = [];\n let unsubscribeConsole: (() => void) | undefined;\n if (collectCaptures && domainsEnabled) {\n unsubscribeConsole = connection.on('Runtime.consoleAPICalled', (event) => {\n liveConsole.push(event);\n });\n }\n\n try {\n for (const file of files) {\n let fileEntry: FileResult;\n try {\n const { code } = await bundleTestFile(file, opts?.bundleOptions);\n const rpcResult = await injectAndRunBundle(connection, code, opts?.timeoutMs);\n if (rpcResult.ok) {\n fileEntry = { file, result: rpcResult.report };\n } else {\n fileEntry = { file, result: { error: rpcResult.error } };\n }\n } catch (e) {\n // Capture bundle/inject errors per-file so subsequent files still run.\n fileEntry = {\n file,\n result: {\n error: e instanceof Error ? e.message : String(e),\n },\n };\n }\n fileResults.push(fileEntry);\n }\n } finally {\n // Always remove the live listener — leaking it would accumulate across runs\n // on a reused connection (the Vitest pool keeps one connection for the whole\n // run; the MCP daemon keeps one for the session).\n unsubscribeConsole?.();\n }\n\n // Convert the accumulated console events to `__AIT_CAPTURE__` lines. Each\n // event's args are rendered to a single line text (inlined console rendering —\n // no tools.ts import, to keep this module off the heavy MCP graph), then the\n // allowlist-prefix parser keeps only genuine capture lines.\n const captures = collectCaptures\n ? parseCaptureLines(liveConsole.map((e) => ({ text: renderConsoleLineText(e) })))\n : [];\n\n const totals = fileResults.reduce(\n (acc, { result }) => {\n if ('error' in result) {\n // Treat whole-file errors as a single failure.\n acc.failed += 1;\n acc.total += 1;\n } else {\n acc.passed += result.passed;\n acc.failed += result.failed;\n acc.skipped += result.skipped;\n acc.total += result.passed + result.failed + result.skipped;\n }\n return acc;\n },\n { passed: 0, failed: 0, skipped: 0, total: 0 },\n );\n\n return {\n startedAt,\n duration: Date.now() - wallStart,\n files: fileResults,\n totals,\n captures,\n };\n}\n\n/**\n * Renders one `Runtime.consoleAPICalled` event to a single line of text, the\n * same way `tools.ts#normalizeConsoleMessage` does (args rendered + space-\n * joined). Inlined here (≈8 lines) so this module avoids importing `tools.ts`,\n * which would drag the heavy MCP/Node graph (server-lock, parent-watcher, …)\n * onto the test-runner entry.\n *\n * SECRET-HANDLING: this only stringifies console args; the caller's\n * allowlist-prefix parser then discards everything that is not a genuine\n * `__AIT_CAPTURE__` line.\n */\nfunction renderConsoleLineText(event: ConsoleApiCalledEvent): string {\n return event.args\n .map((arg) => {\n if (arg.value !== undefined) {\n if (typeof arg.value === 'string') return arg.value;\n try {\n return JSON.stringify(arg.value);\n } catch {\n return String(arg.value);\n }\n }\n if (arg.description !== undefined) return arg.description;\n if (arg.className !== undefined) return arg.className;\n return arg.subtype ?? arg.type;\n })\n .join(' ');\n}\n\n/**\n * Flattens all test results from a `RelayRunReport` into a single array.\n * Files that errored during bundle/inject produce a synthetic failed entry.\n */\nexport function flattenResults(report: RelayRunReport): Array<TestResult & { file: string }> {\n const out: Array<TestResult & { file: string }> = [];\n for (const { file, result } of report.files) {\n if ('error' in result) {\n out.push({\n file,\n name: `<bundle/inject error>`,\n status: 'fail',\n duration: 0,\n error: result.error,\n });\n } else {\n for (const t of result.tests) {\n out.push({ ...t, file });\n }\n }\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyGA,eAAsB,sBACpB,YACA,OACA,MACyB;CACzB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,YAAY,IAAI,KAAK,UAAU,CAAC,aAAa;CACnD,MAAM,cAA4B,EAAE;CAcpC,IAAI,iBAAiB;AACrB,KAAI;AACF,QAAM,WAAW,eAAe;AAChC,mBAAiB;UACV,GAAG;AACV,UAAQ,OAAO,MACb,mFACE,aAAa,QAAQ,EAAE,UAAU,OAAO,EAAE,CAC3C,KACF;;CAcH,MAAM,kBAAkB,MAAM,oBAAoB;CAClD,MAAM,cAAuC,EAAE;CAC/C,IAAI;AACJ,KAAI,mBAAmB,eACrB,sBAAqB,WAAW,GAAG,6BAA6B,UAAU;AACxE,cAAY,KAAK,MAAM;GACvB;AAGJ,KAAI;AACF,OAAK,MAAM,QAAQ,OAAO;GACxB,IAAI;AACJ,OAAI;IACF,MAAM,EAAE,SAAS,MAAM,eAAe,MAAM,MAAM,cAAc;IAChE,MAAM,YAAY,MAAM,mBAAmB,YAAY,MAAM,MAAM,UAAU;AAC7E,QAAI,UAAU,GACZ,aAAY;KAAE;KAAM,QAAQ,UAAU;KAAQ;QAE9C,aAAY;KAAE;KAAM,QAAQ,EAAE,OAAO,UAAU,OAAO;KAAE;YAEnD,GAAG;AAEV,gBAAY;KACV;KACA,QAAQ,EACN,OAAO,aAAa,QAAQ,EAAE,UAAU,OAAO,EAAE,EAClD;KACF;;AAEH,eAAY,KAAK,UAAU;;WAErB;AAIR,wBAAsB;;CAOxB,MAAM,WAAW,kBACb,kBAAkB,YAAY,KAAK,OAAO,EAAE,MAAM,sBAAsB,EAAE,EAAE,EAAE,CAAC,GAC/E,EAAE;CAEN,MAAM,SAAS,YAAY,QACxB,KAAK,EAAE,aAAa;AACnB,MAAI,WAAW,QAAQ;AAErB,OAAI,UAAU;AACd,OAAI,SAAS;SACR;AACL,OAAI,UAAU,OAAO;AACrB,OAAI,UAAU,OAAO;AACrB,OAAI,WAAW,OAAO;AACtB,OAAI,SAAS,OAAO,SAAS,OAAO,SAAS,OAAO;;AAEtD,SAAO;IAET;EAAE,QAAQ;EAAG,QAAQ;EAAG,SAAS;EAAG,OAAO;EAAG,CAC/C;AAED,QAAO;EACL;EACA,UAAU,KAAK,KAAK,GAAG;EACvB,OAAO;EACP;EACA;EACD;;;;;;;;;;;;;AAcH,SAAS,sBAAsB,OAAsC;AACnE,QAAO,MAAM,KACV,KAAK,QAAQ;AACZ,MAAI,IAAI,UAAU,KAAA,GAAW;AAC3B,OAAI,OAAO,IAAI,UAAU,SAAU,QAAO,IAAI;AAC9C,OAAI;AACF,WAAO,KAAK,UAAU,IAAI,MAAM;WAC1B;AACN,WAAO,OAAO,IAAI,MAAM;;;AAG5B,MAAI,IAAI,gBAAgB,KAAA,EAAW,QAAO,IAAI;AAC9C,MAAI,IAAI,cAAc,KAAA,EAAW,QAAO,IAAI;AAC5C,SAAO,IAAI,WAAW,IAAI;GAC1B,CACD,KAAK,IAAI;;;;;;AAOd,SAAgB,eAAe,QAA8D;CAC3F,MAAM,MAA4C,EAAE;AACpD,MAAK,MAAM,EAAE,MAAM,YAAY,OAAO,MACpC,KAAI,WAAW,OACb,KAAI,KAAK;EACP;EACA,MAAM;EACN,QAAQ;EACR,UAAU;EACV,OAAO,OAAO;EACf,CAAC;KAEF,MAAK,MAAM,KAAK,OAAO,MACrB,KAAI,KAAK;EAAE,GAAG;EAAG;EAAM,CAAC;AAI9B,QAAO"}
@@ -0,0 +1,106 @@
1
+ import { t as AitCaptureLine } from "../capture-BmK_cBqQ.js";
2
+ import { n as TestResult } from "../runtime-D57Rtnsd.js";
3
+ import { r as RelayRunReport } from "../relay-worker-D-3aAyDO.js";
4
+
5
+ //#region src/test-runner/report.d.ts
6
+ /** The cell axes a report is stamped with — the test-matrix coordinates. */
7
+ interface ReportCellMeta {
8
+ /** SDK line under test (e.g. `'2.x'` / `'3.x'`). */
9
+ sdkLine: string;
10
+ /** Platform under test (e.g. `'ios'` / `'android'` / `'mock'`). */
11
+ platform: string;
12
+ /**
13
+ * Project root the run was launched from. Used ONLY to relativise file paths
14
+ * out of the serialised report — never stored in the output. SECRET-HANDLING:
15
+ * absolute project paths must not leak into artifacts.
16
+ */
17
+ projectRoot: string;
18
+ }
19
+ /** Per-file slice of a {@link RunnerAgnosticReport}. */
20
+ interface RunnerAgnosticFileReport {
21
+ /**
22
+ * Test file path, RELATIVE to `projectRoot`. Never absolute — `path.relative`
23
+ * strips the machine-specific prefix so the artifact is portable and leaks no
24
+ * local filesystem layout.
25
+ */
26
+ file: string;
27
+ /** Whole-file bundle/inject error (matcher message only), when the file failed. */
28
+ error?: string;
29
+ /** In-page run duration (ms) for this file, when it ran. */
30
+ duration?: number;
31
+ passed?: number;
32
+ failed?: number;
33
+ skipped?: number;
34
+ /** Per-test results, when the file ran. Error strings are matcher messages only. */
35
+ tests?: TestResult[];
36
+ }
37
+ /**
38
+ * The runner-neutral, secret-free report written to disk. There are
39
+ * intentionally NO wss/scheme/TOTP/relayUrl fields on this type — the absence is
40
+ * load-bearing (SECRET-HANDLING) and must not be "completed" by a future edit.
41
+ */
42
+ interface RunnerAgnosticReport {
43
+ /** Cell axes this run belongs to — baked into the body for portability. */
44
+ cell: {
45
+ sdkLine: string;
46
+ platform: string;
47
+ };
48
+ /** ISO timestamp of when the run started (from the core report). */
49
+ startedAt: string;
50
+ /** Total wall-clock ms (bundling + sequential injection). */
51
+ duration: number;
52
+ /** Flattened totals across all files. */
53
+ totals: RelayRunReport['totals'];
54
+ /** Per-file results with projectRoot-relative paths. */
55
+ files: RunnerAgnosticFileReport[];
56
+ }
57
+ /**
58
+ * Serialises a {@link RelayRunReport} into the runner-agnostic, secret-free
59
+ * on-disk shape. Pure — no IO; testable with a plain report + meta.
60
+ *
61
+ * @param report - The core relay run report.
62
+ * @param meta - Cell axes + projectRoot (projectRoot is consumed, not stored).
63
+ */
64
+ declare function serializeRelayReport(report: RelayRunReport, meta: ReportCellMeta): RunnerAgnosticReport;
65
+ /**
66
+ * Writes the serialised report to `<dir>/<sdkLine>.<platform>.json`, creating
67
+ * `dir` if needed. Returns the absolute path written.
68
+ *
69
+ * The cell-suffixed filename keeps 2.x and 3.0 (and per-platform) runs as
70
+ * distinct artifacts in the same directory; the same cell metadata is also baked
71
+ * into the body so a renamed/moved file still carries its provenance.
72
+ *
73
+ * SECRET-HANDLING: the written body contains no relay/secret fields (the schema
74
+ * has none). `dir`/`projectRoot` are local filesystem paths, never logged here.
75
+ *
76
+ * @param report - The core relay run report.
77
+ * @param dir - Output directory (created recursively if missing).
78
+ * @param meta - Cell axes + projectRoot.
79
+ * @returns The absolute path of the written file.
80
+ */
81
+ declare function writeReportArtifact(report: RelayRunReport, dir: string, meta: ReportCellMeta): Promise<string>;
82
+ /**
83
+ * Writes harvested `__AIT_CAPTURE__` lines to per-category files under `dir`,
84
+ * named `<category>.<sdkLine>.<platform>.json` — the SAME convention
85
+ * sdk-example's env1 `flushCapture` uses on the filesystem, so env1 and env3
86
+ * capture artifacts line up for diffing.
87
+ *
88
+ * Each line's `json` payload is an opaque JSON array of capture records. Lines
89
+ * sharing a category are concatenated into one array, in harvest order.
90
+ *
91
+ * SECRET-HANDLING: only allowlist-prefixed capture lines reach here (the parser
92
+ * dropped wss/scheme noise); the `json` payload is written verbatim but is a
93
+ * capture record array, not a relay/secret.
94
+ *
95
+ * @param captures - Parsed capture lines (from `RelayRunReport.captures`).
96
+ * @param dir - Output directory (created recursively if missing).
97
+ * @param cell - Cell axes for the filename suffix.
98
+ * @returns The absolute paths written (one per category), in category order.
99
+ */
100
+ declare function writeCaptureArtifacts(captures: ReadonlyArray<AitCaptureLine>, dir: string, cell: {
101
+ sdkLine: string;
102
+ platform: string;
103
+ }): Promise<string[]>;
104
+ //#endregion
105
+ export { ReportCellMeta, RunnerAgnosticFileReport, RunnerAgnosticReport, serializeRelayReport, writeCaptureArtifacts, writeReportArtifact };
106
+ //# sourceMappingURL=report.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"report.d.ts","names":[],"sources":["../../src/test-runner/report.ts"],"mappings":";;;;;;UA+BiB,cAAA;EAqCA;EAnCf,OAAA;;EAEA,QAAA;EAmCA;;;;;EA7BA,WAAA;AAAA;;UAIe,wBAAA;EAiCgB;;AA4BjC;;;EAvDE,IAAA;EAyDM;EAvDN,KAAA;EAwDqB;EAtDrB,QAAA;EACA,MAAA;EACA,MAAA;EACA,OAAA;EAkDA;EAhDA,KAAA,GAAQ,UAAA;AAAA;;AA0FV;;;;UAlFiB,oBAAA;EAsFd;EApFD,IAAA;IAAQ,OAAA;IAAiB,QAAA;EAAA;EAkFzB;EAhFA,SAAA;EAiFA;EA/EA,QAAA;EAgFQ;EA9ER,MAAA,EAAQ,cAAA;EAwGY;EAtGpB,KAAA,EAAO,wBAAA;AAAA;;;;;;;;iBA4BO,oBAAA,CACd,MAAA,EAAQ,cAAA,EACR,IAAA,EAAM,cAAA,GACL,oBAAA;;;;;;;;;;;;;;;;;iBAyCmB,mBAAA,CACpB,MAAA,EAAQ,cAAA,EACR,GAAA,UACA,IAAA,EAAM,cAAA,GACL,OAAA;;;;;;;;;;;;;;;;;;;iBA0BmB,qBAAA,CACpB,QAAA,EAAU,aAAA,CAAc,cAAA,GACxB,GAAA,UACA,IAAA;EAAQ,OAAA;EAAiB,QAAA;AAAA,IACxB,OAAA"}
@@ -0,0 +1,139 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ //#region src/test-runner/report.ts
4
+ /**
5
+ * Runner-agnostic report serialisation for env3 test runs (devtools#696).
6
+ *
7
+ * Both env3 execution paths — the Vitest custom pool (`pool.ts`) and the
8
+ * standalone `devtools-test` CLI (`cli.ts`) — call the same core
9
+ * `runTestFilesOverRelay` and so produce the same {@link RelayRunReport}. This
10
+ * module is the single, runner-neutral place that turns that in-memory report
11
+ * into a stable on-disk artifact so a 2.x run and a 3.0 run can be diffed
12
+ * cell-by-cell after the fact.
13
+ *
14
+ * The serialised schema is deliberately MINIMAL and secret-free:
15
+ *
16
+ * - file paths are stored RELATIVE to `projectRoot` (no absolute `/Users/...`
17
+ * leakage — see {@link RunnerAgnosticReport.files});
18
+ * - the cell metadata (sdkLine/platform) is baked INTO the body, not only the
19
+ * filename, so a moved artifact never loses its provenance;
20
+ * - NO relay wss / scheme / TOTP / relayUrl fields exist in the schema at all
21
+ * (enforced by the type + this comment) — error strings are the matcher
22
+ * message only, inherited from rpc.ts which already strips expression/value.
23
+ *
24
+ * react-free — depends only on the type-level `RelayRunReport` and `node:fs` /
25
+ * `node:path`. Safe to bundle without pulling the chii/cloudflared graph.
26
+ */
27
+ /**
28
+ * Converts an absolute (or already-relative) file path to a projectRoot-relative
29
+ * one. `path.relative` returns `''` when the paths are equal — guard that to the
30
+ * basename so the field is never empty.
31
+ *
32
+ * SECRET-HANDLING: this is the single choke point that strips absolute project
33
+ * paths from the artifact.
34
+ */
35
+ function relativise(projectRoot, file) {
36
+ const rel = path.relative(projectRoot, file);
37
+ if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) return path.basename(file);
38
+ return rel;
39
+ }
40
+ /**
41
+ * Serialises a {@link RelayRunReport} into the runner-agnostic, secret-free
42
+ * on-disk shape. Pure — no IO; testable with a plain report + meta.
43
+ *
44
+ * @param report - The core relay run report.
45
+ * @param meta - Cell axes + projectRoot (projectRoot is consumed, not stored).
46
+ */
47
+ function serializeRelayReport(report, meta) {
48
+ return {
49
+ cell: {
50
+ sdkLine: meta.sdkLine,
51
+ platform: meta.platform
52
+ },
53
+ startedAt: report.startedAt,
54
+ duration: report.duration,
55
+ totals: report.totals,
56
+ files: report.files.map((f) => {
57
+ const file = relativise(meta.projectRoot, f.file);
58
+ if ("error" in f.result) return {
59
+ file,
60
+ error: f.result.error
61
+ };
62
+ return {
63
+ file,
64
+ duration: f.result.duration,
65
+ passed: f.result.passed,
66
+ failed: f.result.failed,
67
+ skipped: f.result.skipped,
68
+ tests: f.result.tests
69
+ };
70
+ })
71
+ };
72
+ }
73
+ /**
74
+ * Writes the serialised report to `<dir>/<sdkLine>.<platform>.json`, creating
75
+ * `dir` if needed. Returns the absolute path written.
76
+ *
77
+ * The cell-suffixed filename keeps 2.x and 3.0 (and per-platform) runs as
78
+ * distinct artifacts in the same directory; the same cell metadata is also baked
79
+ * into the body so a renamed/moved file still carries its provenance.
80
+ *
81
+ * SECRET-HANDLING: the written body contains no relay/secret fields (the schema
82
+ * has none). `dir`/`projectRoot` are local filesystem paths, never logged here.
83
+ *
84
+ * @param report - The core relay run report.
85
+ * @param dir - Output directory (created recursively if missing).
86
+ * @param meta - Cell axes + projectRoot.
87
+ * @returns The absolute path of the written file.
88
+ */
89
+ async function writeReportArtifact(report, dir, meta) {
90
+ const serialised = serializeRelayReport(report, meta);
91
+ await mkdir(dir, { recursive: true });
92
+ const outFile = path.join(dir, `${meta.sdkLine}.${meta.platform}.json`);
93
+ await writeFile(outFile, `${JSON.stringify(serialised, null, 2)}\n`, "utf8");
94
+ return outFile;
95
+ }
96
+ /**
97
+ * Writes harvested `__AIT_CAPTURE__` lines to per-category files under `dir`,
98
+ * named `<category>.<sdkLine>.<platform>.json` — the SAME convention
99
+ * sdk-example's env1 `flushCapture` uses on the filesystem, so env1 and env3
100
+ * capture artifacts line up for diffing.
101
+ *
102
+ * Each line's `json` payload is an opaque JSON array of capture records. Lines
103
+ * sharing a category are concatenated into one array, in harvest order.
104
+ *
105
+ * SECRET-HANDLING: only allowlist-prefixed capture lines reach here (the parser
106
+ * dropped wss/scheme noise); the `json` payload is written verbatim but is a
107
+ * capture record array, not a relay/secret.
108
+ *
109
+ * @param captures - Parsed capture lines (from `RelayRunReport.captures`).
110
+ * @param dir - Output directory (created recursively if missing).
111
+ * @param cell - Cell axes for the filename suffix.
112
+ * @returns The absolute paths written (one per category), in category order.
113
+ */
114
+ async function writeCaptureArtifacts(captures, dir, cell) {
115
+ if (captures.length === 0) return [];
116
+ const byCategory = /* @__PURE__ */ new Map();
117
+ for (const { category, json } of captures) {
118
+ let merged = byCategory.get(category);
119
+ if (!merged) {
120
+ merged = [];
121
+ byCategory.set(category, merged);
122
+ }
123
+ const parsed = JSON.parse(json);
124
+ if (Array.isArray(parsed)) merged.push(...parsed);
125
+ else merged.push(parsed);
126
+ }
127
+ await mkdir(dir, { recursive: true });
128
+ const written = [];
129
+ for (const [category, records] of byCategory) {
130
+ const outFile = path.join(dir, `${category}.${cell.sdkLine}.${cell.platform}.json`);
131
+ await writeFile(outFile, `${JSON.stringify(records, null, 2)}\n`, "utf8");
132
+ written.push(outFile);
133
+ }
134
+ return written;
135
+ }
136
+ //#endregion
137
+ export { serializeRelayReport, writeCaptureArtifacts, writeReportArtifact };
138
+
139
+ //# sourceMappingURL=report.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"report.js","names":[],"sources":["../../src/test-runner/report.ts"],"sourcesContent":["/**\n * Runner-agnostic report serialisation for env3 test runs (devtools#696).\n *\n * Both env3 execution paths — the Vitest custom pool (`pool.ts`) and the\n * standalone `devtools-test` CLI (`cli.ts`) — call the same core\n * `runTestFilesOverRelay` and so produce the same {@link RelayRunReport}. This\n * module is the single, runner-neutral place that turns that in-memory report\n * into a stable on-disk artifact so a 2.x run and a 3.0 run can be diffed\n * cell-by-cell after the fact.\n *\n * The serialised schema is deliberately MINIMAL and secret-free:\n *\n * - file paths are stored RELATIVE to `projectRoot` (no absolute `/Users/...`\n * leakage — see {@link RunnerAgnosticReport.files});\n * - the cell metadata (sdkLine/platform) is baked INTO the body, not only the\n * filename, so a moved artifact never loses its provenance;\n * - NO relay wss / scheme / TOTP / relayUrl fields exist in the schema at all\n * (enforced by the type + this comment) — error strings are the matcher\n * message only, inherited from rpc.ts which already strips expression/value.\n *\n * react-free — depends only on the type-level `RelayRunReport` and `node:fs` /\n * `node:path`. Safe to bundle without pulling the chii/cloudflared graph.\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport type { AitCaptureLine } from './capture.js';\nimport type { RelayRunReport } from './relay-worker.js';\nimport type { TestResult } from './runtime.js';\n\n/** The cell axes a report is stamped with — the test-matrix coordinates. */\nexport interface ReportCellMeta {\n /** SDK line under test (e.g. `'2.x'` / `'3.x'`). */\n sdkLine: string;\n /** Platform under test (e.g. `'ios'` / `'android'` / `'mock'`). */\n platform: string;\n /**\n * Project root the run was launched from. Used ONLY to relativise file paths\n * out of the serialised report — never stored in the output. SECRET-HANDLING:\n * absolute project paths must not leak into artifacts.\n */\n projectRoot: string;\n}\n\n/** Per-file slice of a {@link RunnerAgnosticReport}. */\nexport interface RunnerAgnosticFileReport {\n /**\n * Test file path, RELATIVE to `projectRoot`. Never absolute — `path.relative`\n * strips the machine-specific prefix so the artifact is portable and leaks no\n * local filesystem layout.\n */\n file: string;\n /** Whole-file bundle/inject error (matcher message only), when the file failed. */\n error?: string;\n /** In-page run duration (ms) for this file, when it ran. */\n duration?: number;\n passed?: number;\n failed?: number;\n skipped?: number;\n /** Per-test results, when the file ran. Error strings are matcher messages only. */\n tests?: TestResult[];\n}\n\n/**\n * The runner-neutral, secret-free report written to disk. There are\n * intentionally NO wss/scheme/TOTP/relayUrl fields on this type — the absence is\n * load-bearing (SECRET-HANDLING) and must not be \"completed\" by a future edit.\n */\nexport interface RunnerAgnosticReport {\n /** Cell axes this run belongs to — baked into the body for portability. */\n cell: { sdkLine: string; platform: string };\n /** ISO timestamp of when the run started (from the core report). */\n startedAt: string;\n /** Total wall-clock ms (bundling + sequential injection). */\n duration: number;\n /** Flattened totals across all files. */\n totals: RelayRunReport['totals'];\n /** Per-file results with projectRoot-relative paths. */\n files: RunnerAgnosticFileReport[];\n}\n\n/**\n * Converts an absolute (or already-relative) file path to a projectRoot-relative\n * one. `path.relative` returns `''` when the paths are equal — guard that to the\n * basename so the field is never empty.\n *\n * SECRET-HANDLING: this is the single choke point that strips absolute project\n * paths from the artifact.\n */\nfunction relativise(projectRoot: string, file: string): string {\n const rel = path.relative(projectRoot, file);\n if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {\n // Outside the project root (or equal) — fall back to the basename rather\n // than emitting an absolute or `../../..` traversal path.\n return path.basename(file);\n }\n return rel;\n}\n\n/**\n * Serialises a {@link RelayRunReport} into the runner-agnostic, secret-free\n * on-disk shape. Pure — no IO; testable with a plain report + meta.\n *\n * @param report - The core relay run report.\n * @param meta - Cell axes + projectRoot (projectRoot is consumed, not stored).\n */\nexport function serializeRelayReport(\n report: RelayRunReport,\n meta: ReportCellMeta,\n): RunnerAgnosticReport {\n return {\n cell: { sdkLine: meta.sdkLine, platform: meta.platform },\n startedAt: report.startedAt,\n duration: report.duration,\n totals: report.totals,\n files: report.files.map((f): RunnerAgnosticFileReport => {\n const file = relativise(meta.projectRoot, f.file);\n if ('error' in f.result) {\n // Matcher/inject error message only — rpc.ts already stripped the\n // expression/value upstream.\n return { file, error: f.result.error };\n }\n return {\n file,\n duration: f.result.duration,\n passed: f.result.passed,\n failed: f.result.failed,\n skipped: f.result.skipped,\n tests: f.result.tests,\n };\n }),\n };\n}\n\n/**\n * Writes the serialised report to `<dir>/<sdkLine>.<platform>.json`, creating\n * `dir` if needed. Returns the absolute path written.\n *\n * The cell-suffixed filename keeps 2.x and 3.0 (and per-platform) runs as\n * distinct artifacts in the same directory; the same cell metadata is also baked\n * into the body so a renamed/moved file still carries its provenance.\n *\n * SECRET-HANDLING: the written body contains no relay/secret fields (the schema\n * has none). `dir`/`projectRoot` are local filesystem paths, never logged here.\n *\n * @param report - The core relay run report.\n * @param dir - Output directory (created recursively if missing).\n * @param meta - Cell axes + projectRoot.\n * @returns The absolute path of the written file.\n */\nexport async function writeReportArtifact(\n report: RelayRunReport,\n dir: string,\n meta: ReportCellMeta,\n): Promise<string> {\n const serialised = serializeRelayReport(report, meta);\n await mkdir(dir, { recursive: true });\n const outFile = path.join(dir, `${meta.sdkLine}.${meta.platform}.json`);\n await writeFile(outFile, `${JSON.stringify(serialised, null, 2)}\\n`, 'utf8');\n return outFile;\n}\n\n/**\n * Writes harvested `__AIT_CAPTURE__` lines to per-category files under `dir`,\n * named `<category>.<sdkLine>.<platform>.json` — the SAME convention\n * sdk-example's env1 `flushCapture` uses on the filesystem, so env1 and env3\n * capture artifacts line up for diffing.\n *\n * Each line's `json` payload is an opaque JSON array of capture records. Lines\n * sharing a category are concatenated into one array, in harvest order.\n *\n * SECRET-HANDLING: only allowlist-prefixed capture lines reach here (the parser\n * dropped wss/scheme noise); the `json` payload is written verbatim but is a\n * capture record array, not a relay/secret.\n *\n * @param captures - Parsed capture lines (from `RelayRunReport.captures`).\n * @param dir - Output directory (created recursively if missing).\n * @param cell - Cell axes for the filename suffix.\n * @returns The absolute paths written (one per category), in category order.\n */\nexport async function writeCaptureArtifacts(\n captures: ReadonlyArray<AitCaptureLine>,\n dir: string,\n cell: { sdkLine: string; platform: string },\n): Promise<string[]> {\n if (captures.length === 0) return [];\n\n // Group payloads by category, preserving harvest order. Each payload is an\n // opaque JSON array string; concatenate parsed arrays under the same category.\n const byCategory = new Map<string, unknown[]>();\n for (const { category, json } of captures) {\n let merged = byCategory.get(category);\n if (!merged) {\n merged = [];\n byCategory.set(category, merged);\n }\n // The parser already validated `json` parses; an array payload is expected.\n const parsed = JSON.parse(json) as unknown;\n if (Array.isArray(parsed)) {\n merged.push(...parsed);\n } else {\n merged.push(parsed);\n }\n }\n\n await mkdir(dir, { recursive: true });\n const written: string[] = [];\n for (const [category, records] of byCategory) {\n const outFile = path.join(dir, `${category}.${cell.sdkLine}.${cell.platform}.json`);\n await writeFile(outFile, `${JSON.stringify(records, null, 2)}\\n`, 'utf8');\n written.push(outFile);\n }\n return written;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,SAAS,WAAW,aAAqB,MAAsB;CAC7D,MAAM,MAAM,KAAK,SAAS,aAAa,KAAK;AAC5C,KAAI,QAAQ,MAAM,IAAI,WAAW,KAAK,IAAI,KAAK,WAAW,IAAI,CAG5D,QAAO,KAAK,SAAS,KAAK;AAE5B,QAAO;;;;;;;;;AAUT,SAAgB,qBACd,QACA,MACsB;AACtB,QAAO;EACL,MAAM;GAAE,SAAS,KAAK;GAAS,UAAU,KAAK;GAAU;EACxD,WAAW,OAAO;EAClB,UAAU,OAAO;EACjB,QAAQ,OAAO;EACf,OAAO,OAAO,MAAM,KAAK,MAAgC;GACvD,MAAM,OAAO,WAAW,KAAK,aAAa,EAAE,KAAK;AACjD,OAAI,WAAW,EAAE,OAGf,QAAO;IAAE;IAAM,OAAO,EAAE,OAAO;IAAO;AAExC,UAAO;IACL;IACA,UAAU,EAAE,OAAO;IACnB,QAAQ,EAAE,OAAO;IACjB,QAAQ,EAAE,OAAO;IACjB,SAAS,EAAE,OAAO;IAClB,OAAO,EAAE,OAAO;IACjB;IACD;EACH;;;;;;;;;;;;;;;;;;AAmBH,eAAsB,oBACpB,QACA,KACA,MACiB;CACjB,MAAM,aAAa,qBAAqB,QAAQ,KAAK;AACrD,OAAM,MAAM,KAAK,EAAE,WAAW,MAAM,CAAC;CACrC,MAAM,UAAU,KAAK,KAAK,KAAK,GAAG,KAAK,QAAQ,GAAG,KAAK,SAAS,OAAO;AACvE,OAAM,UAAU,SAAS,GAAG,KAAK,UAAU,YAAY,MAAM,EAAE,CAAC,KAAK,OAAO;AAC5E,QAAO;;;;;;;;;;;;;;;;;;;;AAqBT,eAAsB,sBACpB,UACA,KACA,MACmB;AACnB,KAAI,SAAS,WAAW,EAAG,QAAO,EAAE;CAIpC,MAAM,6BAAa,IAAI,KAAwB;AAC/C,MAAK,MAAM,EAAE,UAAU,UAAU,UAAU;EACzC,IAAI,SAAS,WAAW,IAAI,SAAS;AACrC,MAAI,CAAC,QAAQ;AACX,YAAS,EAAE;AACX,cAAW,IAAI,UAAU,OAAO;;EAGlC,MAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,MAAI,MAAM,QAAQ,OAAO,CACvB,QAAO,KAAK,GAAG,OAAO;MAEtB,QAAO,KAAK,OAAO;;AAIvB,OAAM,MAAM,KAAK,EAAE,WAAW,MAAM,CAAC;CACrC,MAAM,UAAoB,EAAE;AAC5B,MAAK,MAAM,CAAC,UAAU,YAAY,YAAY;EAC5C,MAAM,UAAU,KAAK,KAAK,KAAK,GAAG,SAAS,GAAG,KAAK,QAAQ,GAAG,KAAK,SAAS,OAAO;AACnF,QAAM,UAAU,SAAS,GAAG,KAAK,UAAU,SAAS,MAAM,EAAE,CAAC,KAAK,OAAO;AACzE,UAAQ,KAAK,QAAQ;;AAEvB,QAAO"}
@@ -1,5 +1,5 @@
1
- import { t as CdpConnection } from "../cdp-connection-C0AP0tH2.js";
2
- import { t as RunReport } from "../runtime-BU-iMHz6.js";
1
+ import { t as CdpConnection } from "../cdp-connection-DB2zgthr.js";
2
+ import { t as RunReport } from "../runtime-D57Rtnsd.js";
3
3
 
4
4
  //#region src/test-runner/rpc.d.ts
5
5
  /**
@@ -1,2 +1,2 @@
1
- import { i as runtimeGlobals, n as TestResult, r as runTestModule, t as RunReport } from "../runtime-BU-iMHz6.js";
1
+ import { i as runtimeGlobals, n as TestResult, r as runTestModule, t as RunReport } from "../runtime-D57Rtnsd.js";
2
2
  export { RunReport, TestResult, runTestModule, runtimeGlobals };
@@ -1,4 +1,4 @@
1
- import { t as RunReport } from "../runtime-BU-iMHz6.js";
1
+ import { t as RunReport } from "../runtime-D57Rtnsd.js";
2
2
  import { File, TaskEventPack, TaskResultPack } from "@vitest/runner";
3
3
 
4
4
  //#region src/test-runner/task-graph.d.ts
@@ -187,4 +187,4 @@ function buildRelayVerifyAuth(env = process.env) {
187
187
  //#endregion
188
188
  export { isValidRelayAuthSecret as a, generateTotp as i, assertRelayAuthConfigured as n, verifyTotp as o, buildRelayVerifyAuth as r, RELAY_AUTH_SECRET_MISSING_MESSAGE as t };
189
189
 
190
- //# sourceMappingURL=totp-D70zD5tJ.js.map
190
+ //# sourceMappingURL=totp-0bvlo9Yb.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"totp-D70zD5tJ.js","names":[],"sources":["../src/mcp/totp.ts"],"sourcesContent":["/**\n * RFC 6238 TOTP implementation (Node.js, node:crypto only).\n *\n * External TOTP libraries (otplib, speakeasy, …) are intentionally NOT used\n * to keep the dependency surface minimal. This hand-roll is ~30 lines and\n * covers exactly what relay-side auth needs.\n *\n * Algorithm summary (RFC 6238 + RFC 4226):\n * T = floor(now / 30) — 30-second time step counter\n * K = Buffer.from(secret, 'hex') — shared secret (raw bytes, hex-encoded)\n * MAC = HMAC-SHA1(K, T as 8-byte big-endian uint64)\n * offset = MAC[19] & 0x0f\n * code = (MAC[offset..offset+4] & 0x7fffffff) % 10^6 — 6 digits\n *\n * Security note (keep this comment accurate):\n * The baked-in secret in a dog-food build is extractable from the bundle by a\n * determined reverse engineer. This mechanism raises the bar from\n * \"anyone with the URL\" to \"URL + bundle extraction + live TOTP calculation\".\n * Casual URL leaks (Slack paste, QR screenshot, shoulder-surfing) are\n * blocked; deliberate reverse engineering is not. See threat model in\n * src/mcp/chii-relay.ts and umbrella CLAUDE.md §4.\n *\n * SECRET-HANDLING: secret values and computed codes MUST NOT appear in any\n * log, error message, or string visible outside this module. Only boolean\n * pass/fail and reason enum values are safe to surface.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/** Time step window in seconds (RFC 6238 default). */\nconst TIME_STEP = 30;\n\n/** Number of digits in the generated code. */\nconst DIGITS = 6;\n\n/**\n * Derives a 6-digit TOTP code from a hex-encoded secret at the given wall-\n * clock time.\n *\n * @param secret - The shared secret as a hex string (e.g. 64 hex chars = 32\n * bytes). Must be the output of `generateAttachToken()` or compatible.\n * @param when - Unix timestamp in milliseconds. Defaults to `Date.now()`.\n * @returns A zero-padded 6-digit decimal string, e.g. `\"042193\"`.\n */\nexport function generateTotp(secret: string, when: number = Date.now()): string {\n const key = Buffer.from(secret, 'hex');\n // Clamp to 0 so negative timestamps (e.g. in ±skew checks near epoch) do not\n // produce a negative counter, which would cause writeUInt32BE to throw.\n const counter = Math.max(0, Math.floor(when / 1000 / TIME_STEP));\n\n // Encode counter as 8-byte big-endian unsigned integer.\n const counterBuf = Buffer.alloc(8);\n // JavaScript numbers are safe integers up to 2^53; counter is ~7.5×10^10 at\n // year 9999 — well within safe range so standard bitwise ops are fine.\n const hi = Math.floor(counter / 0x100000000);\n const lo = counter >>> 0;\n counterBuf.writeUInt32BE(hi, 0);\n counterBuf.writeUInt32BE(lo, 4);\n\n const mac = createHmac('sha1', key).update(counterBuf).digest();\n\n // Dynamic truncation (RFC 4226 §5.4).\n const offset = mac[19] & 0x0f;\n const binCode =\n ((mac[offset] & 0x7f) << 24) |\n ((mac[offset + 1] & 0xff) << 16) |\n ((mac[offset + 2] & 0xff) << 8) |\n (mac[offset + 3] & 0xff);\n\n const otp = binCode % 10 ** DIGITS;\n return otp.toString().padStart(DIGITS, '0');\n}\n\n/**\n * Verifies a TOTP code against the secret, accepting ±`skew` time steps to\n * tolerate clock drift between the relay host and the client device.\n *\n * Uses `timingSafeEqual` for constant-time comparison to prevent timing\n * side-channel attacks.\n *\n * @param secret - Hex-encoded shared secret.\n * @param code - The 6-digit code to verify (string or numeric).\n * @param when - Unix timestamp in milliseconds. Defaults to `Date.now()`.\n * @param skew - Number of adjacent steps to accept on either side. Default 1\n * (accepts T-1, T, T+1 — a 90-second acceptance window).\n * @returns `true` if the code matches any accepted step, `false` otherwise.\n */\nexport function verifyTotp(\n secret: string,\n code: string,\n when: number = Date.now(),\n skew: number = 1,\n): boolean {\n const normalised = String(code).padStart(DIGITS, '0');\n if (normalised.length !== DIGITS || !/^\\d{6}$/.test(normalised)) {\n return false;\n }\n\n const candidateBuf = Buffer.from(normalised, 'utf8');\n\n for (let delta = -skew; delta <= skew; delta++) {\n const stepWhen = when + delta * TIME_STEP * 1000;\n const expected = generateTotp(secret, stepWhen);\n const expectedBuf = Buffer.from(expected, 'utf8');\n if (timingSafeEqual(expectedBuf, candidateBuf)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Minimum length (in hex characters) accepted for `AIT_DEBUG_TOTP_SECRET`.\n *\n * The secret is hex-encoded (see {@link generateTotp} — `Buffer.from(secret,\n * 'hex')`). 32 hex chars = 16 bytes = 128 bits, the floor for an HMAC-SHA1 key\n * we are willing to gate a public relay behind. `generateAttachToken()` emits\n * 64 hex chars (32 bytes), comfortably above this bar.\n */\nconst MIN_SECRET_HEX_CHARS = 32;\n\n/** Hex string: one or more hex digits, case-insensitive (RFC 4648 base16). */\nconst HEX_RE = /^[0-9a-fA-F]+$/;\n\n/**\n * Human-facing guidance printed when {@link assertRelayAuthConfigured} fails.\n *\n * SECRET-HANDLING: this message states only the REQUIREMENT (≥32 hex chars) and\n * how to mint one. It NEVER echoes the configured value, its length, or any\n * fragment derived from it — see {@link assertRelayAuthConfigured}.\n *\n * Note on encoding: the secret is hex (base16), not base32 — `generateTotp`\n * decodes it with `Buffer.from(secret, 'hex')`. A base32 string would be\n * silently mis-decoded and every TOTP code would fail to match, so the minting\n * command emits hex.\n */\nexport const RELAY_AUTH_SECRET_MISSING_MESSAGE = [\n '[ait-debug] AIT_DEBUG_TOTP_SECRET이 필수입니다. 32자 이상 16진수(hex) 문자열을 설정하세요.',\n '발급: openssl rand -hex 32',\n '데몬은 start_debug의 projectRoot 인자로 받은 디렉토리에서 .ait_relay 파일을 읽어 이 시크릿을 채웁니다.',\n '프로젝트에서 pnpm dev:phone:cdp를 한 번 띄우면 unplugin이 .ait_relay를 자동 생성하니(tunnel.cdp 옵션 필요), projectRoot를 전달하세요.',\n '자세히: https://docs.aitc.dev/guides/relay-auth-totp',\n].join('\\n');\n\n/**\n * Whether `secret` is a well-formed relay-auth TOTP secret: a hex string of at\n * least {@link MIN_SECRET_HEX_CHARS} characters with an even length (an odd\n * length would have its trailing nibble silently dropped by `Buffer.from(...,\n * 'hex')`, weakening the key without warning).\n *\n * Pure predicate so callers can test the validation independently of the\n * fail-fast side effect in {@link assertRelayAuthConfigured}.\n *\n * SECRET-HANDLING: returns only a boolean — the input value is never returned,\n * logged, or echoed.\n */\nexport function isValidRelayAuthSecret(secret: string | undefined): secret is string {\n if (secret === undefined || secret === '') return false;\n if (secret.length < MIN_SECRET_HEX_CHARS) return false;\n if (secret.length % 2 !== 0) return false;\n return HEX_RE.test(secret);\n}\n\n/**\n * Fail-fast guard enforcing that a relay-auth TOTP secret is configured before\n * a public-internet-exposed relay is booted (issue #250).\n *\n * Relay-auth (the §4 Layer C TOTP gate) is the only fail-fast layer that closes\n * the real gap: a leaked `wss://…trycloudflare.com` URL otherwise lets a third\n * party attach a debugger to a dog-food/live mini-app. Without a secret the relay\n * comes up unauthenticated, so this guard is called at every relay-boot site —\n * `bootRelayFamily` (intoss env 3/4) and `bootExternalRelayFamily` (env-2 PWA),\n * both eager and lazy. Local-only sessions never boot a relay and so never reach\n * this guard, matching the issue's exemption for non-relay debugging.\n *\n * Throws when the secret is unset, empty, too short, or not a valid hex string.\n * The thrown message is the bin entry's fatal stderr (see `cli.ts` `main().catch`)\n * — the same fatal model as the missing-`AIT_RELAY_BASE_URL` path.\n *\n * SECRET-HANDLING: the env value is read once, passed ONLY to the boolean\n * predicate, and never logged. The thrown message names the requirement, never\n * the value, its length, or any derived fragment.\n *\n * @param env - Environment to read from. Defaults to `process.env`; injectable\n * for tests so they never mutate the real process environment.\n */\nexport function assertRelayAuthConfigured(env: NodeJS.ProcessEnv = process.env): void {\n if (!isValidRelayAuthSecret(env.AIT_DEBUG_TOTP_SECRET)) {\n throw new Error(RELAY_AUTH_SECRET_MISSING_MESSAGE);\n }\n}\n\n/**\n * Gate-specific skew for the relay WebSocket upgrade TOTP check.\n *\n * Rationale (why 6, not the RFC default of 1):\n * - Each step is 30 s, so ±6 steps = past 6 steps accepted = 180–210 s of\n * backwards acceptance. This means a code generated at issuance time is\n * guaranteed valid for at least 3 minutes (180 s) after it was minted.\n * - The real-world attach flow (QR issued on desktop → developer picks up\n * phone → camera scan → launcher PWA loads → attach) routinely exceeds\n * the 90 s window of the RFC default (skew=1), especially when the launcher\n * PWA needs to reinstall or when the phone is not immediately at hand.\n * - Expanding to ~3.5 min reachability is acceptable under the §4 threat\n * model: the adversary we guard against is \"someone who got the URL but\n * does NOT have the secret\". Without the secret they cannot compute a TOTP\n * code regardless of the window size — security theater is explicitly\n * forbidden by the project principle. An attacker WITH the secret (bundle\n * extractor) is out of scope per CLAUDE.md §4.\n *\n * `verifyTotp`'s own default (skew=1) is deliberately left unchanged — it is\n * the RFC primitive. Only this relay-gate call site is widened.\n */\nexport const RELAY_VERIFY_SKEW_STEPS = 6;\n\n/**\n * Reads `AIT_DEBUG_TOTP_SECRET` from `process.env` at runtime and builds a\n * `verifyAuth` predicate for the Chii relay's WebSocket upgrade gate.\n *\n * The predicate checks the `at` query parameter against the current and\n * adjacent TOTP time steps (±{@link RELAY_VERIFY_SKEW_STEPS} skew) using\n * {@link verifyTotp}. This gives the issued code a minimum validity of ~3\n * minutes, which is enough to cover the QR-scan → launcher-attach flow even\n * when the launcher PWA needs to load or reinstall (#490).\n *\n * Returns `undefined` when the env var is not set — callers treat that as\n * \"auth disabled\" (no predicate registered on the relay). Note that since\n * issue #250 the secret is MANDATORY at every relay-boot site (enforced by\n * {@link assertRelayAuthConfigured} BEFORE the relay starts), so in production\n * this never returns `undefined` for a relay that actually boots; the\n * `undefined` branch only matters for the no-relay local path and tests.\n *\n * Lives here (not in the MCP server) so the unplugin's env-2 relay can wire the\n * same gate without importing the heavy MCP server module graph. Re-exported\n * from `debug-server.ts` for back-compat.\n *\n * SECRET-HANDLING: The secret value read from env is captured in a closure and\n * is NEVER written to any log, error message, or process output.\n */\nexport function buildRelayVerifyAuth(\n env: NodeJS.ProcessEnv = process.env,\n): ((req: import('node:http').IncomingMessage) => boolean) | undefined {\n const secret = env.AIT_DEBUG_TOTP_SECRET;\n if (!secret) return undefined;\n\n return (req) => {\n // Parse the `at` query param from the upgrade request URL.\n // req.url is the raw request path + query, e.g. `/client/id?target=…&at=123456`\n const rawUrl = req.url ?? '';\n const qIndex = rawUrl.indexOf('?');\n const queryStr = qIndex === -1 ? '' : rawUrl.slice(qIndex + 1);\n const params = new URLSearchParams(queryStr);\n const code = params.get('at') ?? '';\n\n // Do NOT log `code`, `secret`, or any derived value here.\n // Use RELAY_VERIFY_SKEW_STEPS (±6) for a ~3-minute acceptance window (#490).\n // verifyTotp's own default (skew=1) is unchanged — only this call site is widened.\n return verifyTotp(secret, code, undefined, RELAY_VERIFY_SKEW_STEPS);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,YAAY;;AAGlB,MAAM,SAAS;;;;;;;;;;AAWf,SAAgB,aAAa,QAAgB,OAAe,KAAK,KAAK,EAAU;CAC9E,MAAM,MAAM,OAAO,KAAK,QAAQ,MAAM;CAGtC,MAAM,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,OAAO,MAAO,UAAU,CAAC;CAGhE,MAAM,aAAa,OAAO,MAAM,EAAE;CAGlC,MAAM,KAAK,KAAK,MAAM,UAAU,WAAY;CAC5C,MAAM,KAAK,YAAY;AACvB,YAAW,cAAc,IAAI,EAAE;AAC/B,YAAW,cAAc,IAAI,EAAE;CAE/B,MAAM,MAAM,WAAW,QAAQ,IAAI,CAAC,OAAO,WAAW,CAAC,QAAQ;CAG/D,MAAM,SAAS,IAAI,MAAM;AAQzB,WANI,IAAI,UAAU,QAAS,MACvB,IAAI,SAAS,KAAK,QAAS,MAC3B,IAAI,SAAS,KAAK,QAAS,IAC5B,IAAI,SAAS,KAAK,OAEC,MAAM,QACjB,UAAU,CAAC,SAAS,QAAQ,IAAI;;;;;;;;;;;;;;;;AAiB7C,SAAgB,WACd,QACA,MACA,OAAe,KAAK,KAAK,EACzB,OAAe,GACN;CACT,MAAM,aAAa,OAAO,KAAK,CAAC,SAAS,QAAQ,IAAI;AACrD,KAAI,WAAW,WAAW,UAAU,CAAC,UAAU,KAAK,WAAW,CAC7D,QAAO;CAGT,MAAM,eAAe,OAAO,KAAK,YAAY,OAAO;AAEpD,MAAK,IAAI,QAAQ,CAAC,MAAM,SAAS,MAAM,SAAS;EAE9C,MAAM,WAAW,aAAa,QADb,OAAO,QAAQ,YAAY,IACG;AAE/C,MAAI,gBADgB,OAAO,KAAK,UAAU,OAAO,EAChB,aAAa,CAC5C,QAAO;;AAIX,QAAO;;;;;;;;;;AAWT,MAAM,uBAAuB;;AAG7B,MAAM,SAAS;;;;;;;;;;;;;AAcf,MAAa,oCAAoC;CAC/C;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;;;;;;;;;;;;;AAcZ,SAAgB,uBAAuB,QAA8C;AACnF,KAAI,WAAW,KAAA,KAAa,WAAW,GAAI,QAAO;AAClD,KAAI,OAAO,SAAS,qBAAsB,QAAO;AACjD,KAAI,OAAO,SAAS,MAAM,EAAG,QAAO;AACpC,QAAO,OAAO,KAAK,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;AA0B5B,SAAgB,0BAA0B,MAAyB,QAAQ,KAAW;AACpF,KAAI,CAAC,uBAAuB,IAAI,sBAAsB,CACpD,OAAM,IAAI,MAAM,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDtD,SAAgB,qBACd,MAAyB,QAAQ,KACoC;CACrE,MAAM,SAAS,IAAI;AACnB,KAAI,CAAC,OAAQ,QAAO,KAAA;AAEpB,SAAQ,QAAQ;EAGd,MAAM,SAAS,IAAI,OAAO;EAC1B,MAAM,SAAS,OAAO,QAAQ,IAAI;EAClC,MAAM,WAAW,WAAW,KAAK,KAAK,OAAO,MAAM,SAAS,EAAE;AAO9D,SAAO,WAAW,QANH,IAAI,gBAAgB,SAAS,CACxB,IAAI,KAAK,IAAI,IAKD,KAAA,GAAA,EAAmC"}
1
+ {"version":3,"file":"totp-0bvlo9Yb.js","names":[],"sources":["../src/mcp/totp.ts"],"sourcesContent":["/**\n * RFC 6238 TOTP implementation (Node.js, node:crypto only).\n *\n * External TOTP libraries (otplib, speakeasy, …) are intentionally NOT used\n * to keep the dependency surface minimal. This hand-roll is ~30 lines and\n * covers exactly what relay-side auth needs.\n *\n * Algorithm summary (RFC 6238 + RFC 4226):\n * T = floor(now / 30) — 30-second time step counter\n * K = Buffer.from(secret, 'hex') — shared secret (raw bytes, hex-encoded)\n * MAC = HMAC-SHA1(K, T as 8-byte big-endian uint64)\n * offset = MAC[19] & 0x0f\n * code = (MAC[offset..offset+4] & 0x7fffffff) % 10^6 — 6 digits\n *\n * Security note (keep this comment accurate):\n * The baked-in secret in a dog-food build is extractable from the bundle by a\n * determined reverse engineer. This mechanism raises the bar from\n * \"anyone with the URL\" to \"URL + bundle extraction + live TOTP calculation\".\n * Casual URL leaks (Slack paste, QR screenshot, shoulder-surfing) are\n * blocked; deliberate reverse engineering is not. See threat model in\n * src/mcp/chii-relay.ts and umbrella CLAUDE.md §4.\n *\n * SECRET-HANDLING: secret values and computed codes MUST NOT appear in any\n * log, error message, or string visible outside this module. Only boolean\n * pass/fail and reason enum values are safe to surface.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/** Time step window in seconds (RFC 6238 default). */\nconst TIME_STEP = 30;\n\n/** Number of digits in the generated code. */\nconst DIGITS = 6;\n\n/**\n * Derives a 6-digit TOTP code from a hex-encoded secret at the given wall-\n * clock time.\n *\n * @param secret - The shared secret as a hex string (e.g. 64 hex chars = 32\n * bytes). Must be the output of `generateAttachToken()` or compatible.\n * @param when - Unix timestamp in milliseconds. Defaults to `Date.now()`.\n * @returns A zero-padded 6-digit decimal string, e.g. `\"042193\"`.\n */\nexport function generateTotp(secret: string, when: number = Date.now()): string {\n const key = Buffer.from(secret, 'hex');\n // Clamp to 0 so negative timestamps (e.g. in ±skew checks near epoch) do not\n // produce a negative counter, which would cause writeUInt32BE to throw.\n const counter = Math.max(0, Math.floor(when / 1000 / TIME_STEP));\n\n // Encode counter as 8-byte big-endian unsigned integer.\n const counterBuf = Buffer.alloc(8);\n // JavaScript numbers are safe integers up to 2^53; counter is ~7.5×10^10 at\n // year 9999 — well within safe range so standard bitwise ops are fine.\n const hi = Math.floor(counter / 0x100000000);\n const lo = counter >>> 0;\n counterBuf.writeUInt32BE(hi, 0);\n counterBuf.writeUInt32BE(lo, 4);\n\n const mac = createHmac('sha1', key).update(counterBuf).digest();\n\n // Dynamic truncation (RFC 4226 §5.4).\n const offset = mac[19] & 0x0f;\n const binCode =\n ((mac[offset] & 0x7f) << 24) |\n ((mac[offset + 1] & 0xff) << 16) |\n ((mac[offset + 2] & 0xff) << 8) |\n (mac[offset + 3] & 0xff);\n\n const otp = binCode % 10 ** DIGITS;\n return otp.toString().padStart(DIGITS, '0');\n}\n\n/**\n * Verifies a TOTP code against the secret, accepting ±`skew` time steps to\n * tolerate clock drift between the relay host and the client device.\n *\n * Uses `timingSafeEqual` for constant-time comparison to prevent timing\n * side-channel attacks.\n *\n * @param secret - Hex-encoded shared secret.\n * @param code - The 6-digit code to verify (string or numeric).\n * @param when - Unix timestamp in milliseconds. Defaults to `Date.now()`.\n * @param skew - Number of adjacent steps to accept on either side. Default 1\n * (accepts T-1, T, T+1 — a 90-second acceptance window).\n * @returns `true` if the code matches any accepted step, `false` otherwise.\n */\nexport function verifyTotp(\n secret: string,\n code: string,\n when: number = Date.now(),\n skew: number = 1,\n): boolean {\n const normalised = String(code).padStart(DIGITS, '0');\n if (normalised.length !== DIGITS || !/^\\d{6}$/.test(normalised)) {\n return false;\n }\n\n const candidateBuf = Buffer.from(normalised, 'utf8');\n\n for (let delta = -skew; delta <= skew; delta++) {\n const stepWhen = when + delta * TIME_STEP * 1000;\n const expected = generateTotp(secret, stepWhen);\n const expectedBuf = Buffer.from(expected, 'utf8');\n if (timingSafeEqual(expectedBuf, candidateBuf)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Minimum length (in hex characters) accepted for `AIT_DEBUG_TOTP_SECRET`.\n *\n * The secret is hex-encoded (see {@link generateTotp} — `Buffer.from(secret,\n * 'hex')`). 32 hex chars = 16 bytes = 128 bits, the floor for an HMAC-SHA1 key\n * we are willing to gate a public relay behind. `generateAttachToken()` emits\n * 64 hex chars (32 bytes), comfortably above this bar.\n */\nconst MIN_SECRET_HEX_CHARS = 32;\n\n/** Hex string: one or more hex digits, case-insensitive (RFC 4648 base16). */\nconst HEX_RE = /^[0-9a-fA-F]+$/;\n\n/**\n * Human-facing guidance printed when {@link assertRelayAuthConfigured} fails.\n *\n * SECRET-HANDLING: this message states only the REQUIREMENT (≥32 hex chars) and\n * how to mint one. It NEVER echoes the configured value, its length, or any\n * fragment derived from it — see {@link assertRelayAuthConfigured}.\n *\n * Note on encoding: the secret is hex (base16), not base32 — `generateTotp`\n * decodes it with `Buffer.from(secret, 'hex')`. A base32 string would be\n * silently mis-decoded and every TOTP code would fail to match, so the minting\n * command emits hex.\n */\nexport const RELAY_AUTH_SECRET_MISSING_MESSAGE = [\n '[ait-debug] AIT_DEBUG_TOTP_SECRET이 필수입니다. 32자 이상 16진수(hex) 문자열을 설정하세요.',\n '발급: openssl rand -hex 32',\n '데몬은 start_debug의 projectRoot 인자로 받은 디렉토리에서 .ait_relay 파일을 읽어 이 시크릿을 채웁니다.',\n '프로젝트에서 pnpm dev:phone:cdp를 한 번 띄우면 unplugin이 .ait_relay를 자동 생성하니(tunnel.cdp 옵션 필요), projectRoot를 전달하세요.',\n '자세히: https://docs.aitc.dev/guides/relay-auth-totp',\n].join('\\n');\n\n/**\n * Whether `secret` is a well-formed relay-auth TOTP secret: a hex string of at\n * least {@link MIN_SECRET_HEX_CHARS} characters with an even length (an odd\n * length would have its trailing nibble silently dropped by `Buffer.from(...,\n * 'hex')`, weakening the key without warning).\n *\n * Pure predicate so callers can test the validation independently of the\n * fail-fast side effect in {@link assertRelayAuthConfigured}.\n *\n * SECRET-HANDLING: returns only a boolean — the input value is never returned,\n * logged, or echoed.\n */\nexport function isValidRelayAuthSecret(secret: string | undefined): secret is string {\n if (secret === undefined || secret === '') return false;\n if (secret.length < MIN_SECRET_HEX_CHARS) return false;\n if (secret.length % 2 !== 0) return false;\n return HEX_RE.test(secret);\n}\n\n/**\n * Fail-fast guard enforcing that a relay-auth TOTP secret is configured before\n * a public-internet-exposed relay is booted (issue #250).\n *\n * Relay-auth (the §4 Layer C TOTP gate) is the only fail-fast layer that closes\n * the real gap: a leaked `wss://…trycloudflare.com` URL otherwise lets a third\n * party attach a debugger to a dog-food/live mini-app. Without a secret the relay\n * comes up unauthenticated, so this guard is called at every relay-boot site —\n * `bootRelayFamily` (intoss env 3/4) and `bootExternalRelayFamily` (env-2 PWA),\n * both eager and lazy. Local-only sessions never boot a relay and so never reach\n * this guard, matching the issue's exemption for non-relay debugging.\n *\n * Throws when the secret is unset, empty, too short, or not a valid hex string.\n * The thrown message is the bin entry's fatal stderr (see `cli.ts` `main().catch`)\n * — the same fatal model as the missing-`AIT_RELAY_BASE_URL` path.\n *\n * SECRET-HANDLING: the env value is read once, passed ONLY to the boolean\n * predicate, and never logged. The thrown message names the requirement, never\n * the value, its length, or any derived fragment.\n *\n * @param env - Environment to read from. Defaults to `process.env`; injectable\n * for tests so they never mutate the real process environment.\n */\nexport function assertRelayAuthConfigured(env: NodeJS.ProcessEnv = process.env): void {\n if (!isValidRelayAuthSecret(env.AIT_DEBUG_TOTP_SECRET)) {\n throw new Error(RELAY_AUTH_SECRET_MISSING_MESSAGE);\n }\n}\n\n/**\n * Gate-specific skew for the relay WebSocket upgrade TOTP check.\n *\n * Rationale (why 6, not the RFC default of 1):\n * - Each step is 30 s, so ±6 steps = past 6 steps accepted = 180–210 s of\n * backwards acceptance. This means a code generated at issuance time is\n * guaranteed valid for at least 3 minutes (180 s) after it was minted.\n * - The real-world attach flow (QR issued on desktop → developer picks up\n * phone → camera scan → launcher PWA loads → attach) routinely exceeds\n * the 90 s window of the RFC default (skew=1), especially when the launcher\n * PWA needs to reinstall or when the phone is not immediately at hand.\n * - Expanding to ~3.5 min reachability is acceptable under the §4 threat\n * model: the adversary we guard against is \"someone who got the URL but\n * does NOT have the secret\". Without the secret they cannot compute a TOTP\n * code regardless of the window size — security theater is explicitly\n * forbidden by the project principle. An attacker WITH the secret (bundle\n * extractor) is out of scope per CLAUDE.md §4.\n *\n * `verifyTotp`'s own default (skew=1) is deliberately left unchanged — it is\n * the RFC primitive. Only this relay-gate call site is widened.\n */\nexport const RELAY_VERIFY_SKEW_STEPS = 6;\n\n/**\n * Reads `AIT_DEBUG_TOTP_SECRET` from `process.env` at runtime and builds a\n * `verifyAuth` predicate for the Chii relay's WebSocket upgrade gate.\n *\n * The predicate checks the `at` query parameter against the current and\n * adjacent TOTP time steps (±{@link RELAY_VERIFY_SKEW_STEPS} skew) using\n * {@link verifyTotp}. This gives the issued code a minimum validity of ~3\n * minutes, which is enough to cover the QR-scan → launcher-attach flow even\n * when the launcher PWA needs to load or reinstall (#490).\n *\n * Returns `undefined` when the env var is not set — callers treat that as\n * \"auth disabled\" (no predicate registered on the relay). Note that since\n * issue #250 the secret is MANDATORY at every relay-boot site (enforced by\n * {@link assertRelayAuthConfigured} BEFORE the relay starts), so in production\n * this never returns `undefined` for a relay that actually boots; the\n * `undefined` branch only matters for the no-relay local path and tests.\n *\n * Lives here (not in the MCP server) so the unplugin's env-2 relay can wire the\n * same gate without importing the heavy MCP server module graph. Re-exported\n * from `debug-server.ts` for back-compat.\n *\n * SECRET-HANDLING: The secret value read from env is captured in a closure and\n * is NEVER written to any log, error message, or process output.\n */\nexport function buildRelayVerifyAuth(\n env: NodeJS.ProcessEnv = process.env,\n): ((req: import('node:http').IncomingMessage) => boolean) | undefined {\n const secret = env.AIT_DEBUG_TOTP_SECRET;\n if (!secret) return undefined;\n\n return (req) => {\n // Parse the `at` query param from the upgrade request URL.\n // req.url is the raw request path + query, e.g. `/client/id?target=…&at=123456`\n const rawUrl = req.url ?? '';\n const qIndex = rawUrl.indexOf('?');\n const queryStr = qIndex === -1 ? '' : rawUrl.slice(qIndex + 1);\n const params = new URLSearchParams(queryStr);\n const code = params.get('at') ?? '';\n\n // Do NOT log `code`, `secret`, or any derived value here.\n // Use RELAY_VERIFY_SKEW_STEPS (±6) for a ~3-minute acceptance window (#490).\n // verifyTotp's own default (skew=1) is unchanged — only this call site is widened.\n return verifyTotp(secret, code, undefined, RELAY_VERIFY_SKEW_STEPS);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,YAAY;;AAGlB,MAAM,SAAS;;;;;;;;;;AAWf,SAAgB,aAAa,QAAgB,OAAe,KAAK,KAAK,EAAU;CAC9E,MAAM,MAAM,OAAO,KAAK,QAAQ,MAAM;CAGtC,MAAM,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,OAAO,MAAO,UAAU,CAAC;CAGhE,MAAM,aAAa,OAAO,MAAM,EAAE;CAGlC,MAAM,KAAK,KAAK,MAAM,UAAU,WAAY;CAC5C,MAAM,KAAK,YAAY;AACvB,YAAW,cAAc,IAAI,EAAE;AAC/B,YAAW,cAAc,IAAI,EAAE;CAE/B,MAAM,MAAM,WAAW,QAAQ,IAAI,CAAC,OAAO,WAAW,CAAC,QAAQ;CAG/D,MAAM,SAAS,IAAI,MAAM;AAQzB,WANI,IAAI,UAAU,QAAS,MACvB,IAAI,SAAS,KAAK,QAAS,MAC3B,IAAI,SAAS,KAAK,QAAS,IAC5B,IAAI,SAAS,KAAK,OAEC,MAAM,QACjB,UAAU,CAAC,SAAS,QAAQ,IAAI;;;;;;;;;;;;;;;;AAiB7C,SAAgB,WACd,QACA,MACA,OAAe,KAAK,KAAK,EACzB,OAAe,GACN;CACT,MAAM,aAAa,OAAO,KAAK,CAAC,SAAS,QAAQ,IAAI;AACrD,KAAI,WAAW,WAAW,UAAU,CAAC,UAAU,KAAK,WAAW,CAC7D,QAAO;CAGT,MAAM,eAAe,OAAO,KAAK,YAAY,OAAO;AAEpD,MAAK,IAAI,QAAQ,CAAC,MAAM,SAAS,MAAM,SAAS;EAE9C,MAAM,WAAW,aAAa,QADb,OAAO,QAAQ,YAAY,IACG;AAE/C,MAAI,gBADgB,OAAO,KAAK,UAAU,OAAO,EAChB,aAAa,CAC5C,QAAO;;AAIX,QAAO;;;;;;;;;;AAWT,MAAM,uBAAuB;;AAG7B,MAAM,SAAS;;;;;;;;;;;;;AAcf,MAAa,oCAAoC;CAC/C;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;;;;;;;;;;;;;AAcZ,SAAgB,uBAAuB,QAA8C;AACnF,KAAI,WAAW,KAAA,KAAa,WAAW,GAAI,QAAO;AAClD,KAAI,OAAO,SAAS,qBAAsB,QAAO;AACjD,KAAI,OAAO,SAAS,MAAM,EAAG,QAAO;AACpC,QAAO,OAAO,KAAK,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;AA0B5B,SAAgB,0BAA0B,MAAyB,QAAQ,KAAW;AACpF,KAAI,CAAC,uBAAuB,IAAI,sBAAsB,CACpD,OAAM,IAAI,MAAM,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDtD,SAAgB,qBACd,MAAyB,QAAQ,KACoC;CACrE,MAAM,SAAS,IAAI;AACnB,KAAI,CAAC,OAAQ,QAAO,KAAA;AAEpB,SAAQ,QAAQ;EAGd,MAAM,SAAS,IAAI,OAAO;EAC1B,MAAM,SAAS,OAAO,QAAQ,IAAI;EAClC,MAAM,WAAW,WAAW,KAAK,KAAK,OAAO,MAAM,SAAS,EAAE;AAO9D,SAAO,WAAW,QANH,IAAI,gBAAgB,SAAS,CACxB,IAAI,KAAK,IAAI,IAKD,KAAA,GAAA,EAAmC"}