@ait-co/devtools 0.1.115 → 0.1.116
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli-BLBo0lkP.js +2466 -0
- package/dist/cli-BLBo0lkP.js.map +1 -0
- package/dist/debug-server-DcAKrbnq.js +921 -0
- package/dist/debug-server-DcAKrbnq.js.map +1 -0
- package/dist/debug-server-DlXJARIC.js +8171 -0
- package/dist/debug-server-DlXJARIC.js.map +1 -0
- package/dist/mcp/cli.js +3 -7925
- package/dist/mcp/cli.js.map +1 -1
- package/dist/mcp/server.js +11 -2
- package/dist/mcp/server.js.map +1 -1
- package/dist/panel/index.js +1 -1
- package/dist/{pool-D23t4ibd.d.ts → pool-htlVnEFl.d.ts} +2 -2
- package/dist/{pool-D23t4ibd.d.ts.map → pool-htlVnEFl.d.ts.map} +1 -1
- package/dist/relay-secret-store-BHcOmaNK.js +3 -0
- package/dist/relay-secret-store-CkA7KNUb.js +154 -0
- package/dist/{relay-secret-store-DhzAnnj-.js.map → relay-secret-store-CkA7KNUb.js.map} +1 -1
- package/dist/{relay-secret-store-DhzAnnj-.js → relay-secret-store-CmqchhR5.js} +3 -3
- package/dist/relay-secret-store-CmqchhR5.js.map +1 -0
- package/dist/{relay-url-store-CwKT7i04.js → relay-url-store-C0qukm3R.js} +2 -2
- package/dist/{relay-url-store-CwKT7i04.js.map → relay-url-store-C0qukm3R.js.map} +1 -1
- package/dist/relay-url-store-NDtEcOE-.js +123 -0
- package/dist/relay-url-store-NDtEcOE-.js.map +1 -0
- package/dist/{relay-worker-DERQUao2.d.ts → relay-worker-DWW4vZxU.d.ts} +2 -2
- package/dist/{relay-worker-DERQUao2.d.ts.map → relay-worker-DWW4vZxU.d.ts.map} +1 -1
- package/dist/{runtime-BKMMoeMj.d.ts → runtime-BU-iMHz6.d.ts} +43 -4
- package/dist/runtime-BU-iMHz6.d.ts.map +1 -0
- package/dist/test-runner/cli.d.ts +19 -7
- package/dist/test-runner/cli.d.ts.map +1 -1
- package/dist/test-runner/cli.js +1 -620
- package/dist/test-runner/config.d.ts +1 -1
- package/dist/test-runner/pool.d.ts +1 -1
- package/dist/test-runner/relay-worker.d.ts +1 -1
- package/dist/test-runner/rpc.d.ts +1 -1
- package/dist/test-runner/runtime.d.ts +1 -1
- package/dist/test-runner/runtime.js +111 -3
- package/dist/test-runner/runtime.js.map +1 -1
- package/dist/test-runner/task-graph.d.ts +1 -1
- package/dist/totp-D104cJQN.js +3 -0
- package/dist/{totp-WY6l0ysP.js → totp-D70zD5tJ.js} +1 -1
- package/dist/{totp-WY6l0ysP.js.map → totp-D70zD5tJ.js.map} +1 -1
- package/dist/totp-DvOYkYim.js +212 -0
- package/dist/totp-DvOYkYim.js.map +1 -0
- package/package.json +1 -1
- package/dist/runtime-BKMMoeMj.d.ts.map +0 -1
- package/dist/test-runner/cli.js.map +0 -1
- package/dist/totp-D1pulXLa.js +0 -3
|
@@ -1,9 +1,109 @@
|
|
|
1
1
|
//#region src/test-runner/runtime.ts
|
|
2
2
|
/**
|
|
3
|
+
* Brand property that tags asymmetric matcher markers (`expect.any(String)`,
|
|
4
|
+
* `expect.objectContaining(...)`, etc). A reserved string key is used as the
|
|
5
|
+
* brand so the guard stays a plain own-property check — markers are only ever
|
|
6
|
+
* compared in-process by reference, so no cross-realm Symbol coordination is
|
|
7
|
+
* needed.
|
|
8
|
+
*/
|
|
9
|
+
const ASYMMETRIC_BRAND = "$$asymmetricMatch";
|
|
10
|
+
/** Narrowing guard: is `v` an asymmetric matcher marker? */
|
|
11
|
+
function isAsymmetric(v) {
|
|
12
|
+
return typeof v === "object" && v !== null && v[ASYMMETRIC_BRAND] === true && typeof v.asymmetricMatch === "function";
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* `expect.any(Ctor)` — matches a value by its constructor. Primitive wrappers
|
|
16
|
+
* (`String`/`Number`/`Boolean`) are matched by `typeof` (so the unboxed
|
|
17
|
+
* primitive matches) AND by `instanceof` (so a boxed wrapper instance also
|
|
18
|
+
* matches). `BigInt`/`Symbol` match by `typeof`. `Object` matches any non-null
|
|
19
|
+
* object (NOT functions, matching vitest), `Array` uses `Array.isArray`,
|
|
20
|
+
* `Function` uses `typeof === 'function'`, and any other constructor (user
|
|
21
|
+
* classes) falls back to `instanceof`.
|
|
22
|
+
*/
|
|
23
|
+
function makeAny(ctor) {
|
|
24
|
+
const name = ctor.name ?? String(ctor);
|
|
25
|
+
const ctorAsFn = ctor;
|
|
26
|
+
return {
|
|
27
|
+
[ASYMMETRIC_BRAND]: true,
|
|
28
|
+
toString: () => `Any<${name}>`,
|
|
29
|
+
asymmetricMatch(actual) {
|
|
30
|
+
if (actual === null || actual === void 0) return false;
|
|
31
|
+
switch (ctor) {
|
|
32
|
+
case String: return typeof actual === "string" || actual instanceof String;
|
|
33
|
+
case Number: return typeof actual === "number" || actual instanceof Number;
|
|
34
|
+
case Boolean: return typeof actual === "boolean" || actual instanceof Boolean;
|
|
35
|
+
case BigInt: return typeof actual === "bigint";
|
|
36
|
+
case Symbol: return typeof actual === "symbol";
|
|
37
|
+
case Function: return typeof actual === "function";
|
|
38
|
+
case Object: return typeof actual === "object";
|
|
39
|
+
case Array: return Array.isArray(actual);
|
|
40
|
+
default: return ctorAsFn ? actual instanceof ctorAsFn : false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** `expect.anything()` — matches any value except `null`/`undefined`. */
|
|
46
|
+
function makeAnything() {
|
|
47
|
+
return {
|
|
48
|
+
[ASYMMETRIC_BRAND]: true,
|
|
49
|
+
toString: () => "Anything",
|
|
50
|
+
asymmetricMatch: (actual) => actual !== null && actual !== void 0
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** `expect.objectContaining(obj)` — partial-match every key of `obj` on `actual`. */
|
|
54
|
+
function makeObjectContaining(expected) {
|
|
55
|
+
return {
|
|
56
|
+
[ASYMMETRIC_BRAND]: true,
|
|
57
|
+
toString: () => `ObjectContaining<${safeStringify(expected)}>`,
|
|
58
|
+
asymmetricMatch: (actual) => deepMatchObject(actual, expected)
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** `expect.arrayContaining(arr)` — `actual` is an array containing each element of `arr`. */
|
|
62
|
+
function makeArrayContaining(expected) {
|
|
63
|
+
return {
|
|
64
|
+
[ASYMMETRIC_BRAND]: true,
|
|
65
|
+
toString: () => `ArrayContaining<${safeStringify(expected)}>`,
|
|
66
|
+
asymmetricMatch(actual) {
|
|
67
|
+
if (!Array.isArray(actual)) return false;
|
|
68
|
+
return expected.every((exp) => actual.some((act) => isAsymmetric(exp) ? exp.asymmetricMatch(act) : deepEqual(act, exp)));
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** `expect.stringContaining(sub)` — `actual` is a string containing `sub`. */
|
|
73
|
+
function makeStringContaining(sub) {
|
|
74
|
+
return {
|
|
75
|
+
[ASYMMETRIC_BRAND]: true,
|
|
76
|
+
toString: () => `StringContaining<${sub}>`,
|
|
77
|
+
asymmetricMatch: (actual) => typeof actual === "string" && actual.includes(sub)
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** `expect.stringMatching(re)` — `actual` is a string matching `re` (string or RegExp). */
|
|
81
|
+
function makeStringMatching(re) {
|
|
82
|
+
const pattern = typeof re === "string" ? new RegExp(re) : re;
|
|
83
|
+
return {
|
|
84
|
+
[ASYMMETRIC_BRAND]: true,
|
|
85
|
+
toString: () => `StringMatching<${String(pattern)}>`,
|
|
86
|
+
asymmetricMatch: (actual) => typeof actual === "string" && pattern.test(actual)
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/** JSON.stringify that never throws (cycles/BigInt) — for failure messages. */
|
|
90
|
+
function safeStringify(v) {
|
|
91
|
+
try {
|
|
92
|
+
return JSON.stringify(v, (_k, val) => isAsymmetric(val) ? val.toString() : typeof val === "bigint" ? `${val}n` : val) ?? String(v);
|
|
93
|
+
} catch {
|
|
94
|
+
return String(v);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
3
98
|
* Recursive structural equality — replaces JSON.stringify comparison to
|
|
4
99
|
* handle key-order differences and undefined values correctly.
|
|
100
|
+
*
|
|
101
|
+
* When the `b` (expected) side is an asymmetric marker, its `asymmetricMatch`
|
|
102
|
+
* predicate decides the result instead of structural comparison — markers are
|
|
103
|
+
* placeholders, not plain objects, so deep-comparing them never matches.
|
|
5
104
|
*/
|
|
6
105
|
function deepEqual(a, b) {
|
|
106
|
+
if (isAsymmetric(b)) return b.asymmetricMatch(a);
|
|
7
107
|
if (Object.is(a, b)) return true;
|
|
8
108
|
if (a === null || b === null) return false;
|
|
9
109
|
if (typeof a !== "object" || typeof b !== "object") return false;
|
|
@@ -27,8 +127,12 @@ function deepEqual(a, b) {
|
|
|
27
127
|
/**
|
|
28
128
|
* Partial-match: every key in `expected` must exist in `received` with a
|
|
29
129
|
* recursively matching value. Extra keys in `received` are ignored.
|
|
130
|
+
*
|
|
131
|
+
* As in `deepEqual`, an asymmetric marker on the `expected` side delegates to
|
|
132
|
+
* its `asymmetricMatch` predicate rather than being compared structurally.
|
|
30
133
|
*/
|
|
31
134
|
function deepMatchObject(received, expected) {
|
|
135
|
+
if (isAsymmetric(expected)) return expected.asymmetricMatch(received);
|
|
32
136
|
if (Object.is(received, expected)) return true;
|
|
33
137
|
if (expected === null || received === null) return Object.is(received, expected);
|
|
34
138
|
if (typeof expected !== "object" || typeof received !== "object") return Object.is(received, expected);
|
|
@@ -144,9 +248,13 @@ var Expectation = class Expectation {
|
|
|
144
248
|
}
|
|
145
249
|
};
|
|
146
250
|
/** The `expect` function installed as a global. */
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
251
|
+
const expect = ((received) => new Expectation(received));
|
|
252
|
+
expect.any = makeAny;
|
|
253
|
+
expect.anything = makeAnything;
|
|
254
|
+
expect.objectContaining = makeObjectContaining;
|
|
255
|
+
expect.arrayContaining = makeArrayContaining;
|
|
256
|
+
expect.stringContaining = makeStringContaining;
|
|
257
|
+
expect.stringMatching = makeStringMatching;
|
|
150
258
|
const _pendingTests = [];
|
|
151
259
|
const _suiteStack = [];
|
|
152
260
|
/** Registers a suite scope; calls `fn` synchronously to collect inner tests. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":["#received","#negated","#assert"],"sources":["../../src/test-runner/runtime.ts"],"sourcesContent":["/**\n * Thin test runtime for WebView execution.\n *\n * This file is bundled by `bundle.ts` together with the user's test file\n * into a single IIFE injected into the WebView via `Runtime.evaluate`.\n * It MUST stay browser-compatible — no Node.js APIs allowed.\n *\n * Design: rather than shipping @vitest/runner verbatim into a WebView (where\n * its Node-side internals cause issues), this runtime provides a minimal\n * compatible API surface — describe/it/test/expect globals — collects results\n * into a plain JSON-safe object, and exports `runTestModule` as the entry point.\n *\n * @vitest/runner and @vitest/expect are listed as dependencies so that the\n * package's type contracts are available and so the browser-compatible subsets\n * can be referenced. The Vitest custom pool that drives this runtime through\n * Vitest's `PoolRunnerInitializer` lives in `pool.ts`.\n *\n * NOTE: this file is imported by type from Node-side code (rpc.ts / relay-worker.ts)\n * for the RunReport / TestResult type shapes. The runtime ITSELF is not imported\n * at runtime on the Node side — only the types are used.\n */\n\n/* -------------------------------------------------------------------------- */\n/* Public result types (used by rpc.ts and relay-worker.ts) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Result of a single test case.\n * All fields are JSON-serialisable.\n */\nexport interface TestResult {\n /** Full dot-joined test name including nested suite names. */\n name: string;\n /** `'pass'` or `'fail'`. `'skip'` for skipped tests. */\n status: 'pass' | 'fail' | 'skip';\n /** Duration in milliseconds. */\n duration: number;\n /** Error message (fail only). Does NOT include the expression/secret. */\n error?: string;\n}\n\n/** Aggregate report returned by `runTestModule`. */\nexport interface RunReport {\n /** ISO timestamp of when `runTestModule` was called. */\n startedAt: string;\n /** Total elapsed milliseconds (wall-clock). */\n duration: number;\n passed: number;\n failed: number;\n skipped: number;\n tests: TestResult[];\n}\n\n/* -------------------------------------------------------------------------- */\n/* Deep equality helpers */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Recursive structural equality — replaces JSON.stringify comparison to\n * handle key-order differences and undefined values correctly.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (a === null || b === null) return false;\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (Array.isArray(a) || Array.isArray(b)) return false;\n\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.hasOwn(bObj, key)) return false;\n if (!deepEqual(aObj[key], bObj[key])) return false;\n }\n return true;\n}\n\n/**\n * Partial-match: every key in `expected` must exist in `received` with a\n * recursively matching value. Extra keys in `received` are ignored.\n */\nfunction deepMatchObject(received: unknown, expected: unknown): boolean {\n if (Object.is(received, expected)) return true;\n if (expected === null || received === null) return Object.is(received, expected);\n if (typeof expected !== 'object' || typeof received !== 'object')\n return Object.is(received, expected);\n\n if (Array.isArray(expected) && Array.isArray(received)) {\n if (expected.length !== received.length) return false;\n for (let i = 0; i < expected.length; i++) {\n if (!deepMatchObject(received[i], expected[i])) return false;\n }\n return true;\n }\n if (Array.isArray(expected) || Array.isArray(received)) return false;\n\n const expObj = expected as Record<string, unknown>;\n const recObj = received as Record<string, unknown>;\n for (const key of Object.keys(expObj)) {\n if (!Object.hasOwn(recObj, key)) return false;\n if (!deepMatchObject(recObj[key], expObj[key])) return false;\n }\n return true;\n}\n\n/**\n * Resolves a dot-separated property path on an object.\n * Returns `{ found: true, value }` or `{ found: false }`.\n */\nfunction resolvePath(obj: unknown, dotPath: string): { found: boolean; value?: unknown } {\n const parts = dotPath.split('.');\n let cur: unknown = obj;\n for (const part of parts) {\n if (cur === null || cur === undefined || typeof cur !== 'object') return { found: false };\n const record = cur as Record<string, unknown>;\n if (!Object.hasOwn(record, part)) return { found: false };\n cur = record[part];\n }\n return { found: true, value: cur };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Lightweight expect implementation */\n/* -------------------------------------------------------------------------- */\n\n/** Thrown by expect matchers on failure. */\nclass AssertionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AssertionError';\n }\n}\n\n/** Minimal expect builder compatible with Vitest's jest-style API. */\nclass Expectation {\n #received: unknown;\n #negated = false;\n\n constructor(received: unknown) {\n this.#received = received;\n }\n\n get not(): this {\n const neg = new Expectation(this.#received) as this;\n neg.#negated = true;\n return neg;\n }\n\n #assert(pass: boolean, msg: string): void {\n const actual = this.#negated ? !pass : pass;\n if (!actual) {\n throw new AssertionError(this.#negated ? `Expected NOT: ${msg}` : msg);\n }\n }\n\n toBe(expected: unknown): void {\n this.#assert(\n Object.is(this.#received, expected),\n `Expected ${String(expected)}, received ${String(this.#received)}`,\n );\n }\n\n toEqual(expected: unknown): void {\n this.#assert(\n deepEqual(this.#received, expected),\n `Expected ${JSON.stringify(expected)}, received ${JSON.stringify(this.#received)}`,\n );\n }\n\n toBeTruthy(): void {\n this.#assert(Boolean(this.#received), `Expected truthy, received ${String(this.#received)}`);\n }\n\n toBeFalsy(): void {\n this.#assert(!this.#received, `Expected falsy, received ${String(this.#received)}`);\n }\n\n toBeNull(): void {\n this.#assert(this.#received === null, `Expected null, received ${String(this.#received)}`);\n }\n\n toBeUndefined(): void {\n this.#assert(\n this.#received === undefined,\n `Expected undefined, received ${String(this.#received)}`,\n );\n }\n\n toBeGreaterThan(n: number): void {\n this.#assert(\n typeof this.#received === 'number' && this.#received > n,\n `Expected > ${n}, received ${String(this.#received)}`,\n );\n }\n\n toBeLessThan(n: number): void {\n this.#assert(\n typeof this.#received === 'number' && this.#received < n,\n `Expected < ${n}, received ${String(this.#received)}`,\n );\n }\n\n toContain(sub: string): void {\n this.#assert(\n typeof this.#received === 'string' && this.#received.includes(sub),\n `Expected to contain \"${sub}\", received \"${String(this.#received)}\"`,\n );\n }\n\n toThrow(msgFragment?: string): void {\n if (typeof this.#received !== 'function') {\n throw new AssertionError('toThrow: expected a function');\n }\n let threw = false;\n let errorMsg = '';\n try {\n (this.#received as () => unknown)();\n } catch (e) {\n threw = true;\n errorMsg = e instanceof Error ? e.message : String(e);\n }\n if (msgFragment !== undefined) {\n this.#assert(\n threw && errorMsg.includes(msgFragment),\n `Expected to throw containing \"${msgFragment}\", got \"${errorMsg}\"`,\n );\n } else {\n this.#assert(threw, 'Expected function to throw');\n }\n }\n\n // ---- New matchers (devtools#683) -----------------------------------------\n\n toMatchObject(expected: Record<string, unknown>): void {\n this.#assert(\n deepMatchObject(this.#received, expected),\n `Expected object to match ${JSON.stringify(expected)}, received ${JSON.stringify(this.#received)}`,\n );\n }\n\n toHaveProperty(dotPath: string, ...rest: unknown[]): void {\n const { found, value: actual } = resolvePath(this.#received, dotPath);\n if (rest.length > 0) {\n const value = rest[0];\n this.#assert(\n found && deepEqual(actual, value),\n `Expected property \"${dotPath}\" to equal ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`,\n );\n } else {\n this.#assert(found, `Expected property \"${dotPath}\" to exist`);\n }\n }\n\n // The `abstract new (...args: never) => unknown` signature is the widest\n // constructor type that TypeScript allows without explicit `any`. Real-world\n // constructors like `ErrorConstructor` are assignable to it because `never`\n // in parameter position is contravariant (any arg list satisfies `never[]`).\n toBeInstanceOf(ctor: abstract new (...args: never) => unknown): void {\n this.#assert(\n this.#received instanceof (ctor as new (...args: unknown[]) => unknown),\n `Expected instance of ${(ctor as { name?: string }).name ?? String(ctor)}, received ${String(this.#received)}`,\n );\n }\n\n toBeTypeOf(typeStr: string): void {\n this.#assert(\n typeof this.#received === typeStr,\n `Expected typeof \"${typeStr}\", received \"${typeof this.#received}\"`,\n );\n }\n}\n\n/** The `expect` function installed as a global. */\nfunction expect(received: unknown): Expectation {\n return new Expectation(received);\n}\n\n/* -------------------------------------------------------------------------- */\n/* describe / it / test registry */\n/* -------------------------------------------------------------------------- */\n\ninterface PendingTest {\n suitePath: string[];\n name: string;\n fn: () => void | Promise<void>;\n skip: boolean;\n}\n\nconst _pendingTests: PendingTest[] = [];\nconst _suiteStack: string[] = [];\n\n/** Registers a suite scope; calls `fn` synchronously to collect inner tests. */\nfunction describe(name: string, fn: () => void): void {\n _suiteStack.push(name);\n fn();\n _suiteStack.pop();\n}\n\n/** Registers a test. */\nfunction it(name: string, fn: () => void | Promise<void>): void {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn, skip: false });\n}\n\n/** Alias for `it`. */\nconst test = it;\n\n/** Skipped test — registered but not executed. */\ndescribe.skip = (name: string, _fn: () => void): void => {\n void name;\n};\nit.skip = (name: string, _fn?: () => void | Promise<void>): void => {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn: () => {}, skip: true });\n};\ntest.skip = it.skip;\n\n/**\n * `it.skipIf(cond)(name, fn)` / `it.runIf(cond)(name, fn)` — conditional test\n * registration. `skipIf` skips when `cond` is truthy; `runIf` runs only when\n * `cond` is truthy (skips otherwise). sdk-example uses\n * `it.skipIf(cell.platform === 'mock')(...)` to skip real-SDK-only cases in env1.\n */\ntype ItRegistrar = (name: string, fn: () => void | Promise<void>) => void;\nfunction _conditionalIt(skip: boolean): ItRegistrar {\n return (name, fn) => {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn, skip });\n };\n}\nit.skipIf = (cond: unknown): ItRegistrar => _conditionalIt(Boolean(cond));\nit.runIf = (cond: unknown): ItRegistrar => _conditionalIt(!cond);\ntest.skipIf = it.skipIf;\ntest.runIf = it.runIf;\n\n/**\n * `describe.skipIf(cond)(name, fn)` / `describe.runIf(cond)(name, fn)`.\n * When skipped, the suite body still runs to register its tests but every test\n * inside is marked skipped (collected via a temporary skip flag is overkill —\n * a skipped describe simply does not invoke its body, mirroring `describe.skip`).\n */\ntype DescribeRegistrar = (name: string, fn: () => void) => void;\ndescribe.skipIf = (cond: unknown): DescribeRegistrar =>\n cond ? (name, _fn) => void name : (name, fn) => describe(name, fn);\ndescribe.runIf = (cond: unknown): DescribeRegistrar =>\n cond ? (name, fn) => describe(name, fn) : (name, _fn) => void name;\n\n/* -------------------------------------------------------------------------- */\n/* Lifecycle hooks (devtools#683) */\n/* -------------------------------------------------------------------------- */\n\ntype HookType = 'beforeAll' | 'afterAll' | 'beforeEach' | 'afterEach';\n\ninterface HookEntry {\n /** Suite path at the time of registration ([] = module scope). */\n suitePath: string[];\n type: HookType;\n fn: () => void | Promise<void>;\n}\n\nconst _hooks: HookEntry[] = [];\n\nfunction _registerHook(type: HookType, fn: () => void | Promise<void>): void {\n _hooks.push({ suitePath: [..._suiteStack], type, fn });\n}\n\n/**\n * Returns hooks whose suitePath is a prefix of `testSuitePath`\n * (i.e. the hook's scope contains the test).\n */\nfunction _hooksFor(type: HookType, testSuitePath: string[]): Array<() => void | Promise<void>> {\n return _hooks\n .filter((h) => {\n if (h.type !== type) return false;\n // Hook scope must be a prefix of the test's suite path\n if (h.suitePath.length > testSuitePath.length) return false;\n for (let i = 0; i < h.suitePath.length; i++) {\n if (h.suitePath[i] !== testSuitePath[i]) return false;\n }\n return true;\n })\n .map((h) => h.fn);\n}\n\n/** Runs an array of hook functions in order, awaiting each. */\nasync function _runHooks(fns: Array<() => void | Promise<void>>): Promise<Error | null> {\n for (const fn of fns) {\n try {\n await fn();\n } catch (e) {\n return e instanceof Error ? e : new Error(String(e));\n }\n }\n return null;\n}\n\nfunction beforeAll(fn: () => void | Promise<void>): void {\n _registerHook('beforeAll', fn);\n}\nfunction afterAll(fn: () => void | Promise<void>): void {\n _registerHook('afterAll', fn);\n}\nfunction beforeEach(fn: () => void | Promise<void>): void {\n _registerHook('beforeEach', fn);\n}\nfunction afterEach(fn: () => void | Promise<void>): void {\n _registerHook('afterEach', fn);\n}\n\n/* -------------------------------------------------------------------------- */\n/* vi shim (devtools#683) */\n/* -------------------------------------------------------------------------- */\n\ninterface SpyCall {\n args: unknown[];\n returnValue: unknown;\n}\n\ninterface MockFn<T extends unknown[], R> {\n (...args: T): R;\n mock: { calls: SpyCall[] };\n mockImplementation(fn: (...args: T) => R): this;\n mockReturnValue(value: R): this;\n mockRestore(): void;\n}\n\ninterface SpyRecord {\n obj: Record<string, unknown>;\n method: string;\n original: unknown;\n}\n\nconst _spyRegistry: SpyRecord[] = [];\n\nfunction _createMockFn<T extends unknown[], R>(impl?: (...args: T) => R): MockFn<T, R> {\n let currentImpl: ((...args: T) => R) | undefined = impl;\n const calls: SpyCall[] = [];\n\n const mockFn = ((...args: T): R => {\n const returnValue = currentImpl ? currentImpl(...args) : (undefined as unknown as R);\n calls.push({ args, returnValue });\n return returnValue;\n }) as MockFn<T, R>;\n\n mockFn.mock = { calls };\n\n mockFn.mockImplementation = function (fn: (...args: T) => R): typeof mockFn {\n currentImpl = fn;\n return this;\n };\n\n mockFn.mockReturnValue = function (value: R): typeof mockFn {\n currentImpl = () => value;\n return this;\n };\n\n // No-op restore for standalone fn (only spyOn-created fns have a real restore)\n mockFn.mockRestore = (): void => {};\n\n return mockFn;\n}\n\nconst vi = {\n /** Creates a spy on `obj[method]`, replacing it with a mock function. */\n spyOn<T extends Record<string, unknown>, K extends keyof T>(\n obj: T,\n method: K,\n ): MockFn<unknown[], unknown> {\n const original = obj[method];\n const spy = _createMockFn<unknown[], unknown>(\n typeof original === 'function' ? (original as (...args: unknown[]) => unknown) : undefined,\n );\n\n spy.mockRestore = (): void => {\n obj[method] = original as T[K];\n };\n\n _spyRegistry.push({ obj: obj as Record<string, unknown>, method: method as string, original });\n obj[method] = spy as unknown as T[K];\n return spy;\n },\n\n /** Creates a standalone mock function, optionally wrapping `impl`. */\n fn<T extends unknown[], R>(impl?: (...args: T) => R): MockFn<T, R> {\n return _createMockFn(impl);\n },\n\n /** Restores all spies created via `vi.spyOn` to their original values. */\n restoreAllMocks(): void {\n for (const { obj, method, original } of _spyRegistry) {\n obj[method] = original;\n }\n _spyRegistry.length = 0;\n },\n};\n\n/* -------------------------------------------------------------------------- */\n/* Runtime entry point */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Runtime globals object — exported for direct use in unit tests so that\n * test factories can reference runtime's own `it`/`expect`/`beforeAll`/etc.\n * without depending on `globalThis` injection.\n *\n * In a real WebView bundle these are accessed via globals installed by\n * `runTestModule`; in Node tests, import from here directly.\n */\nexport const runtimeGlobals = {\n describe,\n it,\n test,\n expect,\n beforeAll,\n afterAll,\n beforeEach,\n afterEach,\n vi,\n} as const;\n\n/**\n * Installs describe/it/test/expect/afterAll/afterEach/beforeAll/beforeEach/vi\n * as globals, invokes `moduleFactory` to register the user's tests, then\n * executes them and returns a RunReport.\n *\n * This function is exported as `__testBundle.runTestModule` by the IIFE wrapper\n * that bundle.ts generates. The Node-side rpc.ts calls it via `Runtime.evaluate`.\n *\n * @param moduleFactory - A zero-argument function that contains the user's\n * top-level test code (describe/it/test calls). The bundler wraps the entire\n * test module so that its top-level statements become the body of this factory.\n */\nexport async function runTestModule(\n moduleFactory?: () => void | Promise<void>,\n): Promise<RunReport> {\n // Reset state for re-entrant calls within the same page context.\n _pendingTests.length = 0;\n _suiteStack.length = 0;\n _hooks.length = 0;\n _spyRegistry.length = 0;\n\n // Install globals that user test code expects.\n type G = typeof globalThis & {\n describe: typeof describe;\n it: typeof it;\n test: typeof test;\n expect: typeof expect;\n beforeAll: typeof beforeAll;\n afterAll: typeof afterAll;\n beforeEach: typeof beforeEach;\n afterEach: typeof afterEach;\n vi: typeof vi;\n };\n const g = globalThis as G;\n g.describe = describe;\n g.it = it;\n g.test = test;\n g.expect = expect;\n g.beforeAll = beforeAll;\n g.afterAll = afterAll;\n g.beforeEach = beforeEach;\n g.afterEach = afterEach;\n g.vi = vi;\n\n // Run the factory (which registers describe/it/test blocks via globals).\n if (moduleFactory) {\n await moduleFactory();\n }\n\n const wallStart = Date.now();\n const startedAt = new Date(wallStart).toISOString();\n const results: TestResult[] = [];\n\n // Determine unique suite scopes from registered tests, in discovery order.\n // We need to fire beforeAll/afterAll once per scope (grouped by suitePath).\n //\n // Simplified model: we run beforeAll hooks before the first test in a scope\n // and afterAll hooks after the last test in a scope. Scope identity is the\n // entire suitePath string (e.g. \"Suite A > Suite B\").\n //\n // For module-scope hooks (suitePath=[]), they wrap the entire test run.\n\n // Group tests by their suite key to track beforeAll/afterAll per scope.\n // We keep a Set of scopes for which beforeAll has been fired.\n const firedBeforeAll = new Set<string>();\n // Map from scope key → last index in _pendingTests that belongs to that scope.\n const lastIndexForScope = new Map<string, number>();\n for (let i = 0; i < _pendingTests.length; i++) {\n const key = _pendingTests[i].suitePath.join('\\0');\n lastIndexForScope.set(key, i);\n // Also compute for parent scopes (module scope = '')\n const path = _pendingTests[i].suitePath;\n for (let depth = 0; depth < path.length; depth++) {\n const parentKey = path.slice(0, depth).join('\\0');\n const cur = lastIndexForScope.get(parentKey) ?? -1;\n if (i > cur) lastIndexForScope.set(parentKey, i);\n }\n }\n // Module scope key\n const MODULE_KEY = '';\n if (!lastIndexForScope.has(MODULE_KEY) && _pendingTests.length > 0) {\n lastIndexForScope.set(MODULE_KEY, _pendingTests.length - 1);\n }\n\n // Fire module-scope beforeAll before any tests\n if (_pendingTests.length > 0) {\n const baFns = _hooksFor('beforeAll', []);\n const baErr = await _runHooks(baFns);\n firedBeforeAll.add(MODULE_KEY);\n if (baErr) {\n // If module beforeAll fails, mark all tests as failed.\n for (const pending of _pendingTests) {\n const fullName = [...pending.suitePath, pending.name].join(' > ');\n results.push({\n name: fullName,\n status: 'fail',\n duration: 0,\n error: `beforeAll failed: ${baErr.message}`,\n });\n }\n const duration = Date.now() - wallStart;\n const passed = results.filter((r) => r.status === 'pass').length;\n const failed = results.filter((r) => r.status === 'fail').length;\n const skipped = results.filter((r) => r.status === 'skip').length;\n // Still run module afterAll for cleanup (e.g. flushCapture)\n const aaFns = _hooksFor('afterAll', []);\n await _runHooks(aaFns);\n return { startedAt, duration, passed, failed, skipped, tests: results };\n }\n }\n\n for (let i = 0; i < _pendingTests.length; i++) {\n const pending = _pendingTests[i];\n const fullName = [...pending.suitePath, pending.name].join(' > ');\n\n if (pending.skip) {\n results.push({ name: fullName, status: 'skip', duration: 0 });\n continue;\n }\n\n // Fire suite-scoped beforeAll for any new scopes entered by this test\n for (let depth = 1; depth <= pending.suitePath.length; depth++) {\n const scopePath = pending.suitePath.slice(0, depth);\n const scopeKey = scopePath.join('\\0');\n if (!firedBeforeAll.has(scopeKey)) {\n // Only hooks registered exactly at this scope (not broader/narrower)\n const scopedFns = _hooks\n .filter((h) => h.type === 'beforeAll' && h.suitePath.join('\\0') === scopeKey)\n .map((h) => h.fn);\n const baErr = await _runHooks(scopedFns);\n firedBeforeAll.add(scopeKey);\n if (baErr) {\n // Mark remaining tests in this scope as failed\n results.push({\n name: fullName,\n status: 'fail',\n duration: 0,\n error: `beforeAll failed: ${baErr.message}`,\n });\n }\n }\n }\n\n // beforeEach\n const beFns = _hooksFor('beforeEach', pending.suitePath);\n const beErr = await _runHooks(beFns);\n\n const tStart = Date.now();\n let testErr: string | undefined;\n\n if (beErr) {\n testErr = `beforeEach failed: ${beErr.message}`;\n } else {\n try {\n await pending.fn();\n } catch (e) {\n testErr = e instanceof Error ? e.message : String(e);\n }\n }\n\n // afterEach — always run even if test failed\n const aeFns = _hooksFor('afterEach', pending.suitePath);\n const aeErr = await _runHooks(aeFns);\n if (aeErr && !testErr) testErr = `afterEach failed: ${aeErr.message}`;\n\n if (testErr !== undefined) {\n results.push({\n name: fullName,\n status: 'fail',\n duration: Date.now() - tStart,\n error: testErr,\n });\n } else {\n results.push({ name: fullName, status: 'pass', duration: Date.now() - tStart });\n }\n\n // Fire suite-scoped afterAll when this is the last test in each scope\n for (let depth = pending.suitePath.length; depth >= 1; depth--) {\n const scopePath = pending.suitePath.slice(0, depth);\n const scopeKey = scopePath.join('\\0');\n const lastIdx = lastIndexForScope.get(scopeKey) ?? -1;\n if (lastIdx === i) {\n const scopedFns = _hooks\n .filter((h) => h.type === 'afterAll' && h.suitePath.join('\\0') === scopeKey)\n .map((h) => h.fn);\n await _runHooks(scopedFns);\n }\n }\n }\n\n // Fire module-scope afterAll after all tests — critical for flushCapture\n const moduleAfterAllFns = _hooks\n .filter((h) => h.type === 'afterAll' && h.suitePath.length === 0)\n .map((h) => h.fn);\n await _runHooks(moduleAfterAllFns);\n\n const duration = Date.now() - wallStart;\n const passed = results.filter((r) => r.status === 'pass').length;\n const failed = results.filter((r) => r.status === 'fail').length;\n const skipped = results.filter((r) => r.status === 'skip').length;\n\n return { startedAt, duration, passed, failed, skipped, tests: results };\n}\n"],"mappings":";;;;;AA6DA,SAAS,UAAU,GAAY,GAAqB;AAClD,KAAI,OAAO,GAAG,GAAG,EAAE,CAAE,QAAO;AAC5B,KAAI,MAAM,QAAQ,MAAM,KAAM,QAAO;AACrC,KAAI,OAAO,MAAM,YAAY,OAAO,MAAM,SAAU,QAAO;AAE3D,KAAI,MAAM,QAAQ,EAAE,IAAI,MAAM,QAAQ,EAAE,EAAE;AACxC,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,OAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,IAC5B,KAAI,CAAC,UAAU,EAAE,IAAI,EAAE,GAAG,CAAE,QAAO;AAErC,SAAO;;AAET,KAAI,MAAM,QAAQ,EAAE,IAAI,MAAM,QAAQ,EAAE,CAAE,QAAO;CAEjD,MAAM,OAAO;CACb,MAAM,OAAO;CACb,MAAM,QAAQ,OAAO,KAAK,KAAK;CAC/B,MAAM,QAAQ,OAAO,KAAK,KAAK;AAC/B,KAAI,MAAM,WAAW,MAAM,OAAQ,QAAO;AAC1C,MAAK,MAAM,OAAO,OAAO;AACvB,MAAI,CAAC,OAAO,OAAO,MAAM,IAAI,CAAE,QAAO;AACtC,MAAI,CAAC,UAAU,KAAK,MAAM,KAAK,KAAK,CAAE,Q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QAAQ,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC;EAEJ,OAAO;EAAS"}
|
|
1
|
+
{"version":3,"file":"runtime.js","names":["#received","#negated","#assert"],"sources":["../../src/test-runner/runtime.ts"],"sourcesContent":["/**\n * Thin test runtime for WebView execution.\n *\n * This file is bundled by `bundle.ts` together with the user's test file\n * into a single IIFE injected into the WebView via `Runtime.evaluate`.\n * It MUST stay browser-compatible — no Node.js APIs allowed.\n *\n * Design: rather than shipping @vitest/runner verbatim into a WebView (where\n * its Node-side internals cause issues), this runtime provides a minimal\n * compatible API surface — describe/it/test/expect globals — collects results\n * into a plain JSON-safe object, and exports `runTestModule` as the entry point.\n *\n * @vitest/runner and @vitest/expect are listed as dependencies so that the\n * package's type contracts are available and so the browser-compatible subsets\n * can be referenced. The Vitest custom pool that drives this runtime through\n * Vitest's `PoolRunnerInitializer` lives in `pool.ts`.\n *\n * NOTE: this file is imported by type from Node-side code (rpc.ts / relay-worker.ts)\n * for the RunReport / TestResult type shapes. The runtime ITSELF is not imported\n * at runtime on the Node side — only the types are used.\n */\n\n/* -------------------------------------------------------------------------- */\n/* Public result types (used by rpc.ts and relay-worker.ts) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Result of a single test case.\n * All fields are JSON-serialisable.\n */\nexport interface TestResult {\n /** Full dot-joined test name including nested suite names. */\n name: string;\n /** `'pass'` or `'fail'`. `'skip'` for skipped tests. */\n status: 'pass' | 'fail' | 'skip';\n /** Duration in milliseconds. */\n duration: number;\n /** Error message (fail only). Does NOT include the expression/secret. */\n error?: string;\n}\n\n/** Aggregate report returned by `runTestModule`. */\nexport interface RunReport {\n /** ISO timestamp of when `runTestModule` was called. */\n startedAt: string;\n /** Total elapsed milliseconds (wall-clock). */\n duration: number;\n passed: number;\n failed: number;\n skipped: number;\n tests: TestResult[];\n}\n\n/* -------------------------------------------------------------------------- */\n/* Asymmetric matchers (devtools#692) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Brand property that tags asymmetric matcher markers (`expect.any(String)`,\n * `expect.objectContaining(...)`, etc). A reserved string key is used as the\n * brand so the guard stays a plain own-property check — markers are only ever\n * compared in-process by reference, so no cross-realm Symbol coordination is\n * needed.\n */\nconst ASYMMETRIC_BRAND = '$$asymmetricMatch' as const;\n\n/**\n * An asymmetric matcher: a placeholder that, when found on the `expected` side\n * of a deep comparison, runs its own `asymmetricMatch(actual)` predicate\n * instead of being structurally compared as a plain object. This is what makes\n * `toMatchObject({ hash: expect.any(String) })` match any string `hash`.\n */\ninterface AsymmetricMatcher {\n /** Brand discriminator — present only on asymmetric markers. */\n [ASYMMETRIC_BRAND]: true;\n /** Human-readable label used in failure messages. */\n toString(): string;\n /** Returns true when `actual` satisfies this matcher. */\n asymmetricMatch(actual: unknown): boolean;\n}\n\n/** Narrowing guard: is `v` an asymmetric matcher marker? */\nfunction isAsymmetric(v: unknown): v is AsymmetricMatcher {\n return (\n typeof v === 'object' &&\n v !== null &&\n (v as Record<string, unknown>)[ASYMMETRIC_BRAND] === true &&\n typeof (v as { asymmetricMatch?: unknown }).asymmetricMatch === 'function'\n );\n}\n\n/** The widest constructor type TypeScript allows without `any` (see toBeInstanceOf). */\ntype AnyCtor = abstract new (...args: never) => unknown;\n\n/**\n * `expect.any(Ctor)` — matches a value by its constructor. Primitive wrappers\n * (`String`/`Number`/`Boolean`) are matched by `typeof` (so the unboxed\n * primitive matches) AND by `instanceof` (so a boxed wrapper instance also\n * matches). `BigInt`/`Symbol` match by `typeof`. `Object` matches any non-null\n * object (NOT functions, matching vitest), `Array` uses `Array.isArray`,\n * `Function` uses `typeof === 'function'`, and any other constructor (user\n * classes) falls back to `instanceof`.\n */\nfunction makeAny(ctor: AnyCtor): AsymmetricMatcher {\n const name = (ctor as { name?: string }).name ?? String(ctor);\n const ctorAsFn = ctor as unknown as (new (...args: unknown[]) => unknown) | undefined;\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `Any<${name}>`,\n asymmetricMatch(actual: unknown): boolean {\n if (actual === null || actual === undefined) return false;\n switch (ctor as unknown) {\n case String:\n return typeof actual === 'string' || actual instanceof String;\n case Number:\n return typeof actual === 'number' || actual instanceof Number;\n case Boolean:\n return typeof actual === 'boolean' || actual instanceof Boolean;\n case BigInt:\n return typeof actual === 'bigint';\n case Symbol:\n return typeof actual === 'symbol';\n case Function:\n return typeof actual === 'function';\n case Object:\n // Match vitest: `expect.any(Object)` accepts objects only, NOT\n // functions (vitest checks `typeof other === 'object'`). `null` is\n // already excluded by the guard above.\n return typeof actual === 'object';\n case Array:\n return Array.isArray(actual);\n default:\n return ctorAsFn ? actual instanceof ctorAsFn : false;\n }\n },\n };\n}\n\n/** `expect.anything()` — matches any value except `null`/`undefined`. */\nfunction makeAnything(): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => 'Anything',\n asymmetricMatch: (actual: unknown): boolean => actual !== null && actual !== undefined,\n };\n}\n\n/** `expect.objectContaining(obj)` — partial-match every key of `obj` on `actual`. */\nfunction makeObjectContaining(expected: Record<string, unknown>): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `ObjectContaining<${safeStringify(expected)}>`,\n asymmetricMatch: (actual: unknown): boolean => deepMatchObject(actual, expected),\n };\n}\n\n/** `expect.arrayContaining(arr)` — `actual` is an array containing each element of `arr`. */\nfunction makeArrayContaining(expected: unknown[]): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `ArrayContaining<${safeStringify(expected)}>`,\n asymmetricMatch(actual: unknown): boolean {\n if (!Array.isArray(actual)) return false;\n return expected.every((exp) =>\n actual.some((act) => (isAsymmetric(exp) ? exp.asymmetricMatch(act) : deepEqual(act, exp))),\n );\n },\n };\n}\n\n/** `expect.stringContaining(sub)` — `actual` is a string containing `sub`. */\nfunction makeStringContaining(sub: string): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `StringContaining<${sub}>`,\n asymmetricMatch: (actual: unknown): boolean =>\n typeof actual === 'string' && actual.includes(sub),\n };\n}\n\n/** `expect.stringMatching(re)` — `actual` is a string matching `re` (string or RegExp). */\nfunction makeStringMatching(re: string | RegExp): AsymmetricMatcher {\n const pattern = typeof re === 'string' ? new RegExp(re) : re;\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `StringMatching<${String(pattern)}>`,\n asymmetricMatch: (actual: unknown): boolean =>\n typeof actual === 'string' && pattern.test(actual),\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Deep equality helpers */\n/* -------------------------------------------------------------------------- */\n\n/** JSON.stringify that never throws (cycles/BigInt) — for failure messages. */\nfunction safeStringify(v: unknown): string {\n try {\n return (\n JSON.stringify(v, (_k, val) =>\n isAsymmetric(val) ? val.toString() : typeof val === 'bigint' ? `${val}n` : val,\n ) ?? String(v)\n );\n } catch {\n return String(v);\n }\n}\n\n/**\n * Recursive structural equality — replaces JSON.stringify comparison to\n * handle key-order differences and undefined values correctly.\n *\n * When the `b` (expected) side is an asymmetric marker, its `asymmetricMatch`\n * predicate decides the result instead of structural comparison — markers are\n * placeholders, not plain objects, so deep-comparing them never matches.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (isAsymmetric(b)) return b.asymmetricMatch(a);\n if (Object.is(a, b)) return true;\n if (a === null || b === null) return false;\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (Array.isArray(a) || Array.isArray(b)) return false;\n\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.hasOwn(bObj, key)) return false;\n if (!deepEqual(aObj[key], bObj[key])) return false;\n }\n return true;\n}\n\n/**\n * Partial-match: every key in `expected` must exist in `received` with a\n * recursively matching value. Extra keys in `received` are ignored.\n *\n * As in `deepEqual`, an asymmetric marker on the `expected` side delegates to\n * its `asymmetricMatch` predicate rather than being compared structurally.\n */\nfunction deepMatchObject(received: unknown, expected: unknown): boolean {\n if (isAsymmetric(expected)) return expected.asymmetricMatch(received);\n if (Object.is(received, expected)) return true;\n if (expected === null || received === null) return Object.is(received, expected);\n if (typeof expected !== 'object' || typeof received !== 'object')\n return Object.is(received, expected);\n\n if (Array.isArray(expected) && Array.isArray(received)) {\n if (expected.length !== received.length) return false;\n for (let i = 0; i < expected.length; i++) {\n if (!deepMatchObject(received[i], expected[i])) return false;\n }\n return true;\n }\n if (Array.isArray(expected) || Array.isArray(received)) return false;\n\n const expObj = expected as Record<string, unknown>;\n const recObj = received as Record<string, unknown>;\n for (const key of Object.keys(expObj)) {\n if (!Object.hasOwn(recObj, key)) return false;\n if (!deepMatchObject(recObj[key], expObj[key])) return false;\n }\n return true;\n}\n\n/**\n * Resolves a dot-separated property path on an object.\n * Returns `{ found: true, value }` or `{ found: false }`.\n */\nfunction resolvePath(obj: unknown, dotPath: string): { found: boolean; value?: unknown } {\n const parts = dotPath.split('.');\n let cur: unknown = obj;\n for (const part of parts) {\n if (cur === null || cur === undefined || typeof cur !== 'object') return { found: false };\n const record = cur as Record<string, unknown>;\n if (!Object.hasOwn(record, part)) return { found: false };\n cur = record[part];\n }\n return { found: true, value: cur };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Lightweight expect implementation */\n/* -------------------------------------------------------------------------- */\n\n/** Thrown by expect matchers on failure. */\nclass AssertionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AssertionError';\n }\n}\n\n/** Minimal expect builder compatible with Vitest's jest-style API. */\nclass Expectation {\n #received: unknown;\n #negated = false;\n\n constructor(received: unknown) {\n this.#received = received;\n }\n\n get not(): this {\n const neg = new Expectation(this.#received) as this;\n neg.#negated = true;\n return neg;\n }\n\n #assert(pass: boolean, msg: string): void {\n const actual = this.#negated ? !pass : pass;\n if (!actual) {\n throw new AssertionError(this.#negated ? `Expected NOT: ${msg}` : msg);\n }\n }\n\n toBe(expected: unknown): void {\n this.#assert(\n Object.is(this.#received, expected),\n `Expected ${String(expected)}, received ${String(this.#received)}`,\n );\n }\n\n toEqual(expected: unknown): void {\n this.#assert(\n deepEqual(this.#received, expected),\n `Expected ${JSON.stringify(expected)}, received ${JSON.stringify(this.#received)}`,\n );\n }\n\n toBeTruthy(): void {\n this.#assert(Boolean(this.#received), `Expected truthy, received ${String(this.#received)}`);\n }\n\n toBeFalsy(): void {\n this.#assert(!this.#received, `Expected falsy, received ${String(this.#received)}`);\n }\n\n toBeNull(): void {\n this.#assert(this.#received === null, `Expected null, received ${String(this.#received)}`);\n }\n\n toBeUndefined(): void {\n this.#assert(\n this.#received === undefined,\n `Expected undefined, received ${String(this.#received)}`,\n );\n }\n\n toBeGreaterThan(n: number): void {\n this.#assert(\n typeof this.#received === 'number' && this.#received > n,\n `Expected > ${n}, received ${String(this.#received)}`,\n );\n }\n\n toBeLessThan(n: number): void {\n this.#assert(\n typeof this.#received === 'number' && this.#received < n,\n `Expected < ${n}, received ${String(this.#received)}`,\n );\n }\n\n toContain(sub: string): void {\n this.#assert(\n typeof this.#received === 'string' && this.#received.includes(sub),\n `Expected to contain \"${sub}\", received \"${String(this.#received)}\"`,\n );\n }\n\n toThrow(msgFragment?: string): void {\n if (typeof this.#received !== 'function') {\n throw new AssertionError('toThrow: expected a function');\n }\n let threw = false;\n let errorMsg = '';\n try {\n (this.#received as () => unknown)();\n } catch (e) {\n threw = true;\n errorMsg = e instanceof Error ? e.message : String(e);\n }\n if (msgFragment !== undefined) {\n this.#assert(\n threw && errorMsg.includes(msgFragment),\n `Expected to throw containing \"${msgFragment}\", got \"${errorMsg}\"`,\n );\n } else {\n this.#assert(threw, 'Expected function to throw');\n }\n }\n\n // ---- New matchers (devtools#683) -----------------------------------------\n\n toMatchObject(expected: Record<string, unknown>): void {\n this.#assert(\n deepMatchObject(this.#received, expected),\n `Expected object to match ${JSON.stringify(expected)}, received ${JSON.stringify(this.#received)}`,\n );\n }\n\n toHaveProperty(dotPath: string, ...rest: unknown[]): void {\n const { found, value: actual } = resolvePath(this.#received, dotPath);\n if (rest.length > 0) {\n const value = rest[0];\n this.#assert(\n found && deepEqual(actual, value),\n `Expected property \"${dotPath}\" to equal ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`,\n );\n } else {\n this.#assert(found, `Expected property \"${dotPath}\" to exist`);\n }\n }\n\n // The `abstract new (...args: never) => unknown` signature is the widest\n // constructor type that TypeScript allows without explicit `any`. Real-world\n // constructors like `ErrorConstructor` are assignable to it because `never`\n // in parameter position is contravariant (any arg list satisfies `never[]`).\n toBeInstanceOf(ctor: abstract new (...args: never) => unknown): void {\n this.#assert(\n this.#received instanceof (ctor as new (...args: unknown[]) => unknown),\n `Expected instance of ${(ctor as { name?: string }).name ?? String(ctor)}, received ${String(this.#received)}`,\n );\n }\n\n toBeTypeOf(typeStr: string): void {\n this.#assert(\n typeof this.#received === typeStr,\n `Expected typeof \"${typeStr}\", received \"${typeof this.#received}\"`,\n );\n }\n}\n\n/**\n * The `expect` callable plus its asymmetric-matcher static surface\n * (`expect.any`, `expect.objectContaining`, …). The user file accesses these as\n * `expect.any(String)`; the vitest redirect (`bundle.ts`) re-exports `expect` by\n * reading `globalThis.expect`, so attaching the statics to this function object\n * makes them reachable through the getter (a function's own properties survive\n * the getter that returns the function itself).\n */\ninterface ExpectStatic {\n (received: unknown): Expectation;\n any(ctor: AnyCtor): AsymmetricMatcher;\n anything(): AsymmetricMatcher;\n objectContaining(expected: Record<string, unknown>): AsymmetricMatcher;\n arrayContaining(expected: unknown[]): AsymmetricMatcher;\n stringContaining(sub: string): AsymmetricMatcher;\n stringMatching(re: string | RegExp): AsymmetricMatcher;\n}\n\n/** The `expect` function installed as a global. */\nconst expect: ExpectStatic = ((received: unknown): Expectation =>\n new Expectation(received)) as ExpectStatic;\n\n// Asymmetric matcher statics — vitest-compatible surface (devtools#692).\nexpect.any = makeAny;\nexpect.anything = makeAnything;\nexpect.objectContaining = makeObjectContaining;\nexpect.arrayContaining = makeArrayContaining;\nexpect.stringContaining = makeStringContaining;\nexpect.stringMatching = makeStringMatching;\n\n/* -------------------------------------------------------------------------- */\n/* describe / it / test registry */\n/* -------------------------------------------------------------------------- */\n\ninterface PendingTest {\n suitePath: string[];\n name: string;\n fn: () => void | Promise<void>;\n skip: boolean;\n}\n\nconst _pendingTests: PendingTest[] = [];\nconst _suiteStack: string[] = [];\n\n/** Registers a suite scope; calls `fn` synchronously to collect inner tests. */\nfunction describe(name: string, fn: () => void): void {\n _suiteStack.push(name);\n fn();\n _suiteStack.pop();\n}\n\n/** Registers a test. */\nfunction it(name: string, fn: () => void | Promise<void>): void {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn, skip: false });\n}\n\n/** Alias for `it`. */\nconst test = it;\n\n/** Skipped test — registered but not executed. */\ndescribe.skip = (name: string, _fn: () => void): void => {\n void name;\n};\nit.skip = (name: string, _fn?: () => void | Promise<void>): void => {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn: () => {}, skip: true });\n};\ntest.skip = it.skip;\n\n/**\n * `it.skipIf(cond)(name, fn)` / `it.runIf(cond)(name, fn)` — conditional test\n * registration. `skipIf` skips when `cond` is truthy; `runIf` runs only when\n * `cond` is truthy (skips otherwise). sdk-example uses\n * `it.skipIf(cell.platform === 'mock')(...)` to skip real-SDK-only cases in env1.\n */\ntype ItRegistrar = (name: string, fn: () => void | Promise<void>) => void;\nfunction _conditionalIt(skip: boolean): ItRegistrar {\n return (name, fn) => {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn, skip });\n };\n}\nit.skipIf = (cond: unknown): ItRegistrar => _conditionalIt(Boolean(cond));\nit.runIf = (cond: unknown): ItRegistrar => _conditionalIt(!cond);\ntest.skipIf = it.skipIf;\ntest.runIf = it.runIf;\n\n/**\n * `describe.skipIf(cond)(name, fn)` / `describe.runIf(cond)(name, fn)`.\n * When skipped, the suite body still runs to register its tests but every test\n * inside is marked skipped (collected via a temporary skip flag is overkill —\n * a skipped describe simply does not invoke its body, mirroring `describe.skip`).\n */\ntype DescribeRegistrar = (name: string, fn: () => void) => void;\ndescribe.skipIf = (cond: unknown): DescribeRegistrar =>\n cond ? (name, _fn) => void name : (name, fn) => describe(name, fn);\ndescribe.runIf = (cond: unknown): DescribeRegistrar =>\n cond ? (name, fn) => describe(name, fn) : (name, _fn) => void name;\n\n/* -------------------------------------------------------------------------- */\n/* Lifecycle hooks (devtools#683) */\n/* -------------------------------------------------------------------------- */\n\ntype HookType = 'beforeAll' | 'afterAll' | 'beforeEach' | 'afterEach';\n\ninterface HookEntry {\n /** Suite path at the time of registration ([] = module scope). */\n suitePath: string[];\n type: HookType;\n fn: () => void | Promise<void>;\n}\n\nconst _hooks: HookEntry[] = [];\n\nfunction _registerHook(type: HookType, fn: () => void | Promise<void>): void {\n _hooks.push({ suitePath: [..._suiteStack], type, fn });\n}\n\n/**\n * Returns hooks whose suitePath is a prefix of `testSuitePath`\n * (i.e. the hook's scope contains the test).\n */\nfunction _hooksFor(type: HookType, testSuitePath: string[]): Array<() => void | Promise<void>> {\n return _hooks\n .filter((h) => {\n if (h.type !== type) return false;\n // Hook scope must be a prefix of the test's suite path\n if (h.suitePath.length > testSuitePath.length) return false;\n for (let i = 0; i < h.suitePath.length; i++) {\n if (h.suitePath[i] !== testSuitePath[i]) return false;\n }\n return true;\n })\n .map((h) => h.fn);\n}\n\n/** Runs an array of hook functions in order, awaiting each. */\nasync function _runHooks(fns: Array<() => void | Promise<void>>): Promise<Error | null> {\n for (const fn of fns) {\n try {\n await fn();\n } catch (e) {\n return e instanceof Error ? e : new Error(String(e));\n }\n }\n return null;\n}\n\nfunction beforeAll(fn: () => void | Promise<void>): void {\n _registerHook('beforeAll', fn);\n}\nfunction afterAll(fn: () => void | Promise<void>): void {\n _registerHook('afterAll', fn);\n}\nfunction beforeEach(fn: () => void | Promise<void>): void {\n _registerHook('beforeEach', fn);\n}\nfunction afterEach(fn: () => void | Promise<void>): void {\n _registerHook('afterEach', fn);\n}\n\n/* -------------------------------------------------------------------------- */\n/* vi shim (devtools#683) */\n/* -------------------------------------------------------------------------- */\n\ninterface SpyCall {\n args: unknown[];\n returnValue: unknown;\n}\n\ninterface MockFn<T extends unknown[], R> {\n (...args: T): R;\n mock: { calls: SpyCall[] };\n mockImplementation(fn: (...args: T) => R): this;\n mockReturnValue(value: R): this;\n mockRestore(): void;\n}\n\ninterface SpyRecord {\n obj: Record<string, unknown>;\n method: string;\n original: unknown;\n}\n\nconst _spyRegistry: SpyRecord[] = [];\n\nfunction _createMockFn<T extends unknown[], R>(impl?: (...args: T) => R): MockFn<T, R> {\n let currentImpl: ((...args: T) => R) | undefined = impl;\n const calls: SpyCall[] = [];\n\n const mockFn = ((...args: T): R => {\n const returnValue = currentImpl ? currentImpl(...args) : (undefined as unknown as R);\n calls.push({ args, returnValue });\n return returnValue;\n }) as MockFn<T, R>;\n\n mockFn.mock = { calls };\n\n mockFn.mockImplementation = function (fn: (...args: T) => R): typeof mockFn {\n currentImpl = fn;\n return this;\n };\n\n mockFn.mockReturnValue = function (value: R): typeof mockFn {\n currentImpl = () => value;\n return this;\n };\n\n // No-op restore for standalone fn (only spyOn-created fns have a real restore)\n mockFn.mockRestore = (): void => {};\n\n return mockFn;\n}\n\nconst vi = {\n /** Creates a spy on `obj[method]`, replacing it with a mock function. */\n spyOn<T extends Record<string, unknown>, K extends keyof T>(\n obj: T,\n method: K,\n ): MockFn<unknown[], unknown> {\n const original = obj[method];\n const spy = _createMockFn<unknown[], unknown>(\n typeof original === 'function' ? (original as (...args: unknown[]) => unknown) : undefined,\n );\n\n spy.mockRestore = (): void => {\n obj[method] = original as T[K];\n };\n\n _spyRegistry.push({ obj: obj as Record<string, unknown>, method: method as string, original });\n obj[method] = spy as unknown as T[K];\n return spy;\n },\n\n /** Creates a standalone mock function, optionally wrapping `impl`. */\n fn<T extends unknown[], R>(impl?: (...args: T) => R): MockFn<T, R> {\n return _createMockFn(impl);\n },\n\n /** Restores all spies created via `vi.spyOn` to their original values. */\n restoreAllMocks(): void {\n for (const { obj, method, original } of _spyRegistry) {\n obj[method] = original;\n }\n _spyRegistry.length = 0;\n },\n};\n\n/* -------------------------------------------------------------------------- */\n/* Runtime entry point */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Runtime globals object — exported for direct use in unit tests so that\n * test factories can reference runtime's own `it`/`expect`/`beforeAll`/etc.\n * without depending on `globalThis` injection.\n *\n * In a real WebView bundle these are accessed via globals installed by\n * `runTestModule`; in Node tests, import from here directly.\n */\nexport const runtimeGlobals = {\n describe,\n it,\n test,\n expect,\n beforeAll,\n afterAll,\n beforeEach,\n afterEach,\n vi,\n} as const;\n\n/**\n * Installs describe/it/test/expect/afterAll/afterEach/beforeAll/beforeEach/vi\n * as globals, invokes `moduleFactory` to register the user's tests, then\n * executes them and returns a RunReport.\n *\n * This function is exported as `__testBundle.runTestModule` by the IIFE wrapper\n * that bundle.ts generates. The Node-side rpc.ts calls it via `Runtime.evaluate`.\n *\n * @param moduleFactory - A zero-argument function that contains the user's\n * top-level test code (describe/it/test calls). The bundler wraps the entire\n * test module so that its top-level statements become the body of this factory.\n */\nexport async function runTestModule(\n moduleFactory?: () => void | Promise<void>,\n): Promise<RunReport> {\n // Reset state for re-entrant calls within the same page context.\n _pendingTests.length = 0;\n _suiteStack.length = 0;\n _hooks.length = 0;\n _spyRegistry.length = 0;\n\n // Install globals that user test code expects.\n type G = typeof globalThis & {\n describe: typeof describe;\n it: typeof it;\n test: typeof test;\n expect: typeof expect;\n beforeAll: typeof beforeAll;\n afterAll: typeof afterAll;\n beforeEach: typeof beforeEach;\n afterEach: typeof afterEach;\n vi: typeof vi;\n };\n const g = globalThis as G;\n g.describe = describe;\n g.it = it;\n g.test = test;\n g.expect = expect;\n g.beforeAll = beforeAll;\n g.afterAll = afterAll;\n g.beforeEach = beforeEach;\n g.afterEach = afterEach;\n g.vi = vi;\n\n // Run the factory (which registers describe/it/test blocks via globals).\n if (moduleFactory) {\n await moduleFactory();\n }\n\n const wallStart = Date.now();\n const startedAt = new Date(wallStart).toISOString();\n const results: TestResult[] = [];\n\n // Determine unique suite scopes from registered tests, in discovery order.\n // We need to fire beforeAll/afterAll once per scope (grouped by suitePath).\n //\n // Simplified model: we run beforeAll hooks before the first test in a scope\n // and afterAll hooks after the last test in a scope. Scope identity is the\n // entire suitePath string (e.g. \"Suite A > Suite B\").\n //\n // For module-scope hooks (suitePath=[]), they wrap the entire test run.\n\n // Group tests by their suite key to track beforeAll/afterAll per scope.\n // We keep a Set of scopes for which beforeAll has been fired.\n const firedBeforeAll = new Set<string>();\n // Map from scope key → last index in _pendingTests that belongs to that scope.\n const lastIndexForScope = new Map<string, number>();\n for (let i = 0; i < _pendingTests.length; i++) {\n const key = _pendingTests[i].suitePath.join('\\0');\n lastIndexForScope.set(key, i);\n // Also compute for parent scopes (module scope = '')\n const path = _pendingTests[i].suitePath;\n for (let depth = 0; depth < path.length; depth++) {\n const parentKey = path.slice(0, depth).join('\\0');\n const cur = lastIndexForScope.get(parentKey) ?? -1;\n if (i > cur) lastIndexForScope.set(parentKey, i);\n }\n }\n // Module scope key\n const MODULE_KEY = '';\n if (!lastIndexForScope.has(MODULE_KEY) && _pendingTests.length > 0) {\n lastIndexForScope.set(MODULE_KEY, _pendingTests.length - 1);\n }\n\n // Fire module-scope beforeAll before any tests\n if (_pendingTests.length > 0) {\n const baFns = _hooksFor('beforeAll', []);\n const baErr = await _runHooks(baFns);\n firedBeforeAll.add(MODULE_KEY);\n if (baErr) {\n // If module beforeAll fails, mark all tests as failed.\n for (const pending of _pendingTests) {\n const fullName = [...pending.suitePath, pending.name].join(' > ');\n results.push({\n name: fullName,\n status: 'fail',\n duration: 0,\n error: `beforeAll failed: ${baErr.message}`,\n });\n }\n const duration = Date.now() - wallStart;\n const passed = results.filter((r) => r.status === 'pass').length;\n const failed = results.filter((r) => r.status === 'fail').length;\n const skipped = results.filter((r) => r.status === 'skip').length;\n // Still run module afterAll for cleanup (e.g. flushCapture)\n const aaFns = _hooksFor('afterAll', []);\n await _runHooks(aaFns);\n return { startedAt, duration, passed, failed, skipped, tests: results };\n }\n }\n\n for (let i = 0; i < _pendingTests.length; i++) {\n const pending = _pendingTests[i];\n const fullName = [...pending.suitePath, pending.name].join(' > ');\n\n if (pending.skip) {\n results.push({ name: fullName, status: 'skip', duration: 0 });\n continue;\n }\n\n // Fire suite-scoped beforeAll for any new scopes entered by this test\n for (let depth = 1; depth <= pending.suitePath.length; depth++) {\n const scopePath = pending.suitePath.slice(0, depth);\n const scopeKey = scopePath.join('\\0');\n if (!firedBeforeAll.has(scopeKey)) {\n // Only hooks registered exactly at this scope (not broader/narrower)\n const scopedFns = _hooks\n .filter((h) => h.type === 'beforeAll' && h.suitePath.join('\\0') === scopeKey)\n .map((h) => h.fn);\n const baErr = await _runHooks(scopedFns);\n firedBeforeAll.add(scopeKey);\n if (baErr) {\n // Mark remaining tests in this scope as failed\n results.push({\n name: fullName,\n status: 'fail',\n duration: 0,\n error: `beforeAll failed: ${baErr.message}`,\n });\n }\n }\n }\n\n // beforeEach\n const beFns = _hooksFor('beforeEach', pending.suitePath);\n const beErr = await _runHooks(beFns);\n\n const tStart = Date.now();\n let testErr: string | undefined;\n\n if (beErr) {\n testErr = `beforeEach failed: ${beErr.message}`;\n } else {\n try {\n await pending.fn();\n } catch (e) {\n testErr = e instanceof Error ? e.message : String(e);\n }\n }\n\n // afterEach — always run even if test failed\n const aeFns = _hooksFor('afterEach', pending.suitePath);\n const aeErr = await _runHooks(aeFns);\n if (aeErr && !testErr) testErr = `afterEach failed: ${aeErr.message}`;\n\n if (testErr !== undefined) {\n results.push({\n name: fullName,\n status: 'fail',\n duration: Date.now() - tStart,\n error: testErr,\n });\n } else {\n results.push({ name: fullName, status: 'pass', duration: Date.now() - tStart });\n }\n\n // Fire suite-scoped afterAll when this is the last test in each scope\n for (let depth = pending.suitePath.length; depth >= 1; depth--) {\n const scopePath = pending.suitePath.slice(0, depth);\n const scopeKey = scopePath.join('\\0');\n const lastIdx = lastIndexForScope.get(scopeKey) ?? -1;\n if (lastIdx === i) {\n const scopedFns = _hooks\n .filter((h) => h.type === 'afterAll' && h.suitePath.join('\\0') === scopeKey)\n .map((h) => h.fn);\n await _runHooks(scopedFns);\n }\n }\n }\n\n // Fire module-scope afterAll after all tests — critical for flushCapture\n const moduleAfterAllFns = _hooks\n .filter((h) => h.type === 'afterAll' && h.suitePath.length === 0)\n .map((h) => h.fn);\n await _runHooks(moduleAfterAllFns);\n\n const duration = Date.now() - wallStart;\n const passed = results.filter((r) => r.status === 'pass').length;\n const failed = results.filter((r) => r.status === 'fail').length;\n const skipped = results.filter((r) => r.status === 'skip').length;\n\n return { startedAt, duration, passed, failed, skipped, tests: results };\n}\n"],"mappings":";;;;;;;;AAgEA,MAAM,mBAAmB;;AAkBzB,SAAS,aAAa,GAAoC;AACxD,QACE,OAAO,MAAM,YACb,MAAM,QACL,EAA8B,sBAAsB,QACrD,OAAQ,EAAoC,oBAAoB;;;;;;;;;;;AAgBpE,SAAS,QAAQ,MAAkC;CACjD,MAAM,OAAQ,KAA2B,QAAQ,OAAO,KAAK;CAC7D,MAAM,WAAW;AACjB,QAAO;GACJ,mBAAmB;EACpB,gBAAgB,OAAO,KAAK;EAC5B,gBAAgB,QAA0B;AACxC,OAAI,WAAW,QAAQ,WAAW,KAAA,EAAW,QAAO;AACpD,WAAQ,MAAR;IACE,KAAK,OACH,QAAO,OAAO,WAAW,YAAY,kBAAkB;IACzD,KAAK,OACH,QAAO,OAAO,WAAW,YAAY,kBAAkB;IACzD,KAAK,QACH,QAAO,OAAO,WAAW,aAAa,kBAAkB;IAC1D,KAAK,OACH,QAAO,OAAO,WAAW;IAC3B,KAAK,OACH,QAAO,OAAO,WAAW;IAC3B,KAAK,SACH,QAAO,OAAO,WAAW;IAC3B,KAAK,OAIH,QAAO,OAAO,WAAW;IAC3B,KAAK,MACH,QAAO,MAAM,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Q,IAAI;WACX,GAAG;AACV,aAAU,aAAa,QAAQ,EAAE,UAAU,OAAO,EAAE;;EAMxD,MAAM,QAAQ,MAAM,UADN,UAAU,aAAa,QAAQ,UAAU,CACnB;AACpC,MAAI,SAAS,CAAC,QAAS,WAAU,qBAAqB,MAAM;AAE5D,MAAI,YAAY,KAAA,EACd,SAAQ,KAAK;GACX,MAAM;GACN,QAAQ;GACR,UAAU,KAAK,KAAK,GAAG;GACvB,OAAO;GACR,CAAC;MAEF,SAAQ,KAAK;GAAE,MAAM;GAAU,QAAQ;GAAQ,UAAU,KAAK,KAAK,GAAG;GAAQ,CAAC;AAIjF,OAAK,IAAI,QAAQ,QAAQ,UAAU,QAAQ,SAAS,GAAG,SAAS;GAE9D,MAAM,WADY,QAAQ,UAAU,MAAM,GAAG,MAAM,CACxB,KAAK,KAAK;AAErC,QADgB,kBAAkB,IAAI,SAAS,IAAI,QACnC,EAId,OAAM,UAHY,OACf,QAAQ,MAAM,EAAE,SAAS,cAAc,EAAE,UAAU,KAAK,KAAK,KAAK,SAAS,CAC3E,KAAK,MAAM,EAAE,GAAG,CACO;;;AAShC,OAAM,UAHoB,OACvB,QAAQ,MAAM,EAAE,SAAS,cAAc,EAAE,UAAU,WAAW,EAAE,CAChE,KAAK,MAAM,EAAE,GAAG,CACe;AAOlC,QAAO;EAAE;EAAW,UALH,KAAK,KAAK,GAAG;EAKA,QAJf,QAAQ,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC;EAIpB,QAHvB,QAAQ,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC;EAGZ,SAF9B,QAAQ,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC;EAEJ,OAAO;EAAS"}
|
|
@@ -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-
|
|
190
|
+
//# sourceMappingURL=totp-D70zD5tJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"totp-WY6l0ysP.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,OA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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"}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import "node:module";
|
|
3
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
4
|
+
//#region \0rolldown/runtime.js
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __exportAll = (all, no_symbols) => {
|
|
7
|
+
let target = {};
|
|
8
|
+
for (var name in all) __defProp(target, name, {
|
|
9
|
+
get: all[name],
|
|
10
|
+
enumerable: true
|
|
11
|
+
});
|
|
12
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
13
|
+
return target;
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/mcp/totp.ts
|
|
17
|
+
/**
|
|
18
|
+
* RFC 6238 TOTP implementation (Node.js, node:crypto only).
|
|
19
|
+
*
|
|
20
|
+
* External TOTP libraries (otplib, speakeasy, …) are intentionally NOT used
|
|
21
|
+
* to keep the dependency surface minimal. This hand-roll is ~30 lines and
|
|
22
|
+
* covers exactly what relay-side auth needs.
|
|
23
|
+
*
|
|
24
|
+
* Algorithm summary (RFC 6238 + RFC 4226):
|
|
25
|
+
* T = floor(now / 30) — 30-second time step counter
|
|
26
|
+
* K = Buffer.from(secret, 'hex') — shared secret (raw bytes, hex-encoded)
|
|
27
|
+
* MAC = HMAC-SHA1(K, T as 8-byte big-endian uint64)
|
|
28
|
+
* offset = MAC[19] & 0x0f
|
|
29
|
+
* code = (MAC[offset..offset+4] & 0x7fffffff) % 10^6 — 6 digits
|
|
30
|
+
*
|
|
31
|
+
* Security note (keep this comment accurate):
|
|
32
|
+
* The baked-in secret in a dog-food build is extractable from the bundle by a
|
|
33
|
+
* determined reverse engineer. This mechanism raises the bar from
|
|
34
|
+
* "anyone with the URL" to "URL + bundle extraction + live TOTP calculation".
|
|
35
|
+
* Casual URL leaks (Slack paste, QR screenshot, shoulder-surfing) are
|
|
36
|
+
* blocked; deliberate reverse engineering is not. See threat model in
|
|
37
|
+
* src/mcp/chii-relay.ts and umbrella CLAUDE.md §4.
|
|
38
|
+
*
|
|
39
|
+
* SECRET-HANDLING: secret values and computed codes MUST NOT appear in any
|
|
40
|
+
* log, error message, or string visible outside this module. Only boolean
|
|
41
|
+
* pass/fail and reason enum values are safe to surface.
|
|
42
|
+
*/
|
|
43
|
+
var totp_exports = /* @__PURE__ */ __exportAll({
|
|
44
|
+
RELAY_AUTH_SECRET_MISSING_MESSAGE: () => RELAY_AUTH_SECRET_MISSING_MESSAGE,
|
|
45
|
+
RELAY_VERIFY_SKEW_STEPS: () => 6,
|
|
46
|
+
assertRelayAuthConfigured: () => assertRelayAuthConfigured,
|
|
47
|
+
buildRelayVerifyAuth: () => buildRelayVerifyAuth,
|
|
48
|
+
generateTotp: () => generateTotp,
|
|
49
|
+
isValidRelayAuthSecret: () => isValidRelayAuthSecret,
|
|
50
|
+
verifyTotp: () => verifyTotp
|
|
51
|
+
});
|
|
52
|
+
/** Time step window in seconds (RFC 6238 default). */
|
|
53
|
+
const TIME_STEP = 30;
|
|
54
|
+
/** Number of digits in the generated code. */
|
|
55
|
+
const DIGITS = 6;
|
|
56
|
+
/**
|
|
57
|
+
* Derives a 6-digit TOTP code from a hex-encoded secret at the given wall-
|
|
58
|
+
* clock time.
|
|
59
|
+
*
|
|
60
|
+
* @param secret - The shared secret as a hex string (e.g. 64 hex chars = 32
|
|
61
|
+
* bytes). Must be the output of `generateAttachToken()` or compatible.
|
|
62
|
+
* @param when - Unix timestamp in milliseconds. Defaults to `Date.now()`.
|
|
63
|
+
* @returns A zero-padded 6-digit decimal string, e.g. `"042193"`.
|
|
64
|
+
*/
|
|
65
|
+
function generateTotp(secret, when = Date.now()) {
|
|
66
|
+
const key = Buffer.from(secret, "hex");
|
|
67
|
+
const counter = Math.max(0, Math.floor(when / 1e3 / TIME_STEP));
|
|
68
|
+
const counterBuf = Buffer.alloc(8);
|
|
69
|
+
const hi = Math.floor(counter / 4294967296);
|
|
70
|
+
const lo = counter >>> 0;
|
|
71
|
+
counterBuf.writeUInt32BE(hi, 0);
|
|
72
|
+
counterBuf.writeUInt32BE(lo, 4);
|
|
73
|
+
const mac = createHmac("sha1", key).update(counterBuf).digest();
|
|
74
|
+
const offset = mac[19] & 15;
|
|
75
|
+
return (((mac[offset] & 127) << 24 | (mac[offset + 1] & 255) << 16 | (mac[offset + 2] & 255) << 8 | mac[offset + 3] & 255) % 10 ** DIGITS).toString().padStart(DIGITS, "0");
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Verifies a TOTP code against the secret, accepting ±`skew` time steps to
|
|
79
|
+
* tolerate clock drift between the relay host and the client device.
|
|
80
|
+
*
|
|
81
|
+
* Uses `timingSafeEqual` for constant-time comparison to prevent timing
|
|
82
|
+
* side-channel attacks.
|
|
83
|
+
*
|
|
84
|
+
* @param secret - Hex-encoded shared secret.
|
|
85
|
+
* @param code - The 6-digit code to verify (string or numeric).
|
|
86
|
+
* @param when - Unix timestamp in milliseconds. Defaults to `Date.now()`.
|
|
87
|
+
* @param skew - Number of adjacent steps to accept on either side. Default 1
|
|
88
|
+
* (accepts T-1, T, T+1 — a 90-second acceptance window).
|
|
89
|
+
* @returns `true` if the code matches any accepted step, `false` otherwise.
|
|
90
|
+
*/
|
|
91
|
+
function verifyTotp(secret, code, when = Date.now(), skew = 1) {
|
|
92
|
+
const normalised = String(code).padStart(DIGITS, "0");
|
|
93
|
+
if (normalised.length !== DIGITS || !/^\d{6}$/.test(normalised)) return false;
|
|
94
|
+
const candidateBuf = Buffer.from(normalised, "utf8");
|
|
95
|
+
for (let delta = -skew; delta <= skew; delta++) {
|
|
96
|
+
const expected = generateTotp(secret, when + delta * TIME_STEP * 1e3);
|
|
97
|
+
if (timingSafeEqual(Buffer.from(expected, "utf8"), candidateBuf)) return true;
|
|
98
|
+
}
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Minimum length (in hex characters) accepted for `AIT_DEBUG_TOTP_SECRET`.
|
|
103
|
+
*
|
|
104
|
+
* The secret is hex-encoded (see {@link generateTotp} — `Buffer.from(secret,
|
|
105
|
+
* 'hex')`). 32 hex chars = 16 bytes = 128 bits, the floor for an HMAC-SHA1 key
|
|
106
|
+
* we are willing to gate a public relay behind. `generateAttachToken()` emits
|
|
107
|
+
* 64 hex chars (32 bytes), comfortably above this bar.
|
|
108
|
+
*/
|
|
109
|
+
const MIN_SECRET_HEX_CHARS = 32;
|
|
110
|
+
/** Hex string: one or more hex digits, case-insensitive (RFC 4648 base16). */
|
|
111
|
+
const HEX_RE = /^[0-9a-fA-F]+$/;
|
|
112
|
+
/**
|
|
113
|
+
* Human-facing guidance printed when {@link assertRelayAuthConfigured} fails.
|
|
114
|
+
*
|
|
115
|
+
* SECRET-HANDLING: this message states only the REQUIREMENT (≥32 hex chars) and
|
|
116
|
+
* how to mint one. It NEVER echoes the configured value, its length, or any
|
|
117
|
+
* fragment derived from it — see {@link assertRelayAuthConfigured}.
|
|
118
|
+
*
|
|
119
|
+
* Note on encoding: the secret is hex (base16), not base32 — `generateTotp`
|
|
120
|
+
* decodes it with `Buffer.from(secret, 'hex')`. A base32 string would be
|
|
121
|
+
* silently mis-decoded and every TOTP code would fail to match, so the minting
|
|
122
|
+
* command emits hex.
|
|
123
|
+
*/
|
|
124
|
+
const RELAY_AUTH_SECRET_MISSING_MESSAGE = [
|
|
125
|
+
"[ait-debug] AIT_DEBUG_TOTP_SECRET이 필수입니다. 32자 이상 16진수(hex) 문자열을 설정하세요.",
|
|
126
|
+
"발급: openssl rand -hex 32",
|
|
127
|
+
"데몬은 start_debug의 projectRoot 인자로 받은 디렉토리에서 .ait_relay 파일을 읽어 이 시크릿을 채웁니다.",
|
|
128
|
+
"프로젝트에서 pnpm dev:phone:cdp를 한 번 띄우면 unplugin이 .ait_relay를 자동 생성하니(tunnel.cdp 옵션 필요), projectRoot를 전달하세요.",
|
|
129
|
+
"자세히: https://docs.aitc.dev/guides/relay-auth-totp"
|
|
130
|
+
].join("\n");
|
|
131
|
+
/**
|
|
132
|
+
* Whether `secret` is a well-formed relay-auth TOTP secret: a hex string of at
|
|
133
|
+
* least {@link MIN_SECRET_HEX_CHARS} characters with an even length (an odd
|
|
134
|
+
* length would have its trailing nibble silently dropped by `Buffer.from(...,
|
|
135
|
+
* 'hex')`, weakening the key without warning).
|
|
136
|
+
*
|
|
137
|
+
* Pure predicate so callers can test the validation independently of the
|
|
138
|
+
* fail-fast side effect in {@link assertRelayAuthConfigured}.
|
|
139
|
+
*
|
|
140
|
+
* SECRET-HANDLING: returns only a boolean — the input value is never returned,
|
|
141
|
+
* logged, or echoed.
|
|
142
|
+
*/
|
|
143
|
+
function isValidRelayAuthSecret(secret) {
|
|
144
|
+
if (secret === void 0 || secret === "") return false;
|
|
145
|
+
if (secret.length < MIN_SECRET_HEX_CHARS) return false;
|
|
146
|
+
if (secret.length % 2 !== 0) return false;
|
|
147
|
+
return HEX_RE.test(secret);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Fail-fast guard enforcing that a relay-auth TOTP secret is configured before
|
|
151
|
+
* a public-internet-exposed relay is booted (issue #250).
|
|
152
|
+
*
|
|
153
|
+
* Relay-auth (the §4 Layer C TOTP gate) is the only fail-fast layer that closes
|
|
154
|
+
* the real gap: a leaked `wss://…trycloudflare.com` URL otherwise lets a third
|
|
155
|
+
* party attach a debugger to a dog-food/live mini-app. Without a secret the relay
|
|
156
|
+
* comes up unauthenticated, so this guard is called at every relay-boot site —
|
|
157
|
+
* `bootRelayFamily` (intoss env 3/4) and `bootExternalRelayFamily` (env-2 PWA),
|
|
158
|
+
* both eager and lazy. Local-only sessions never boot a relay and so never reach
|
|
159
|
+
* this guard, matching the issue's exemption for non-relay debugging.
|
|
160
|
+
*
|
|
161
|
+
* Throws when the secret is unset, empty, too short, or not a valid hex string.
|
|
162
|
+
* The thrown message is the bin entry's fatal stderr (see `cli.ts` `main().catch`)
|
|
163
|
+
* — the same fatal model as the missing-`AIT_RELAY_BASE_URL` path.
|
|
164
|
+
*
|
|
165
|
+
* SECRET-HANDLING: the env value is read once, passed ONLY to the boolean
|
|
166
|
+
* predicate, and never logged. The thrown message names the requirement, never
|
|
167
|
+
* the value, its length, or any derived fragment.
|
|
168
|
+
*
|
|
169
|
+
* @param env - Environment to read from. Defaults to `process.env`; injectable
|
|
170
|
+
* for tests so they never mutate the real process environment.
|
|
171
|
+
*/
|
|
172
|
+
function assertRelayAuthConfigured(env = process.env) {
|
|
173
|
+
if (!isValidRelayAuthSecret(env.AIT_DEBUG_TOTP_SECRET)) throw new Error(RELAY_AUTH_SECRET_MISSING_MESSAGE);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Reads `AIT_DEBUG_TOTP_SECRET` from `process.env` at runtime and builds a
|
|
177
|
+
* `verifyAuth` predicate for the Chii relay's WebSocket upgrade gate.
|
|
178
|
+
*
|
|
179
|
+
* The predicate checks the `at` query parameter against the current and
|
|
180
|
+
* adjacent TOTP time steps (±{@link RELAY_VERIFY_SKEW_STEPS} skew) using
|
|
181
|
+
* {@link verifyTotp}. This gives the issued code a minimum validity of ~3
|
|
182
|
+
* minutes, which is enough to cover the QR-scan → launcher-attach flow even
|
|
183
|
+
* when the launcher PWA needs to load or reinstall (#490).
|
|
184
|
+
*
|
|
185
|
+
* Returns `undefined` when the env var is not set — callers treat that as
|
|
186
|
+
* "auth disabled" (no predicate registered on the relay). Note that since
|
|
187
|
+
* issue #250 the secret is MANDATORY at every relay-boot site (enforced by
|
|
188
|
+
* {@link assertRelayAuthConfigured} BEFORE the relay starts), so in production
|
|
189
|
+
* this never returns `undefined` for a relay that actually boots; the
|
|
190
|
+
* `undefined` branch only matters for the no-relay local path and tests.
|
|
191
|
+
*
|
|
192
|
+
* Lives here (not in the MCP server) so the unplugin's env-2 relay can wire the
|
|
193
|
+
* same gate without importing the heavy MCP server module graph. Re-exported
|
|
194
|
+
* from `debug-server.ts` for back-compat.
|
|
195
|
+
*
|
|
196
|
+
* SECRET-HANDLING: The secret value read from env is captured in a closure and
|
|
197
|
+
* is NEVER written to any log, error message, or process output.
|
|
198
|
+
*/
|
|
199
|
+
function buildRelayVerifyAuth(env = process.env) {
|
|
200
|
+
const secret = env.AIT_DEBUG_TOTP_SECRET;
|
|
201
|
+
if (!secret) return void 0;
|
|
202
|
+
return (req) => {
|
|
203
|
+
const rawUrl = req.url ?? "";
|
|
204
|
+
const qIndex = rawUrl.indexOf("?");
|
|
205
|
+
const queryStr = qIndex === -1 ? "" : rawUrl.slice(qIndex + 1);
|
|
206
|
+
return verifyTotp(secret, new URLSearchParams(queryStr).get("at") ?? "", void 0, 6);
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
//#endregion
|
|
210
|
+
export { totp_exports as i, buildRelayVerifyAuth as n, generateTotp as r, assertRelayAuthConfigured as t };
|
|
211
|
+
|
|
212
|
+
//# sourceMappingURL=totp-DvOYkYim.js.map
|