theokit 0.5.3 → 0.6.0
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/{aws-lambda-SCRGTGF5.js → aws-lambda-WT4HRBNL.js} +3 -3
- package/dist/{build-R74EU6BP.js → build-ZZAQV2ES.js} +7 -7
- package/dist/{bun-FURRCQMS.js → bun-UTDVN6R4.js} +3 -3
- package/dist/{check-NXYPLM6M.js → check-F3UDYSZ4.js} +2 -2
- package/dist/{chunk-KJLECZWQ.js → chunk-3FYJ7R7N.js} +57 -14
- package/dist/chunk-3FYJ7R7N.js.map +1 -0
- package/dist/{chunk-JD7AQNJS.js → chunk-4NLIESWK.js} +18 -12
- package/dist/{chunk-JD7AQNJS.js.map → chunk-4NLIESWK.js.map} +1 -1
- package/dist/{chunk-H4J2LECY.js → chunk-6BUUZ2PK.js} +9 -9
- package/dist/chunk-6BUUZ2PK.js.map +1 -0
- package/dist/{chunk-FGOX37NB.js → chunk-BNGBG2SQ.js} +21 -2
- package/dist/chunk-BNGBG2SQ.js.map +1 -0
- package/dist/{chunk-X32KQH5C.js → chunk-CCVC6P6B.js} +3 -3
- package/dist/chunk-CCVC6P6B.js.map +1 -0
- package/dist/{chunk-S74FECKW.js → chunk-D4SV7JOG.js} +24 -20
- package/dist/chunk-D4SV7JOG.js.map +1 -0
- package/dist/{chunk-DNMSV3R3.js → chunk-D7ZH7DTG.js} +3 -3
- package/dist/chunk-D7ZH7DTG.js.map +1 -0
- package/dist/{chunk-MWYSRZI4.js → chunk-EQV67HZL.js} +2 -2
- package/dist/{chunk-CG563V5M.js → chunk-IEES3CHD.js} +39 -5
- package/dist/chunk-IEES3CHD.js.map +1 -0
- package/dist/{chunk-DUKXQNM7.js → chunk-IHMJV2OK.js} +2 -2
- package/dist/{chunk-WGHJD6I7.js → chunk-JAIKGP3Q.js} +76 -21
- package/dist/chunk-JAIKGP3Q.js.map +1 -0
- package/dist/{chunk-NZXH2LQQ.js → chunk-SJIRP73B.js} +18 -1
- package/dist/chunk-SJIRP73B.js.map +1 -0
- package/dist/{chunk-X3VNROZ7.js → chunk-SVSUUK4H.js} +73 -14
- package/dist/chunk-SVSUUK4H.js.map +1 -0
- package/dist/cli/index.js +25 -10
- package/dist/cli/index.js.map +1 -1
- package/dist/{cloudflare-IZ6VJ2OU.js → cloudflare-U5GYYI47.js} +3 -3
- package/dist/db-ZPDW3UCU.js +78 -0
- package/dist/db-ZPDW3UCU.js.map +1 -0
- package/dist/{deno-deploy-O73NBXIW.js → deno-deploy-3QHJ3AJQ.js} +3 -3
- package/dist/{dev-ZU46C5AZ.js → dev-MHCQ5RD7.js} +16 -8
- package/dist/dev-MHCQ5RD7.js.map +1 -0
- package/dist/{dev-emit-66FCOS7V.js → dev-emit-4WG3B5BM.js} +2 -2
- package/dist/{dev-emit-JBVINGHU.js → dev-emit-6DJUK6DT.js} +76 -21
- package/dist/dev-emit-6DJUK6DT.js.map +1 -0
- package/dist/devtools/entry.js +2 -3
- package/dist/devtools/entry.js.map +1 -1
- package/dist/generate-ODDAYXNR.js +494 -0
- package/dist/generate-ODDAYXNR.js.map +1 -0
- package/dist/index.d.ts +32 -3
- package/dist/index.js +3 -4
- package/dist/index.js.map +1 -1
- package/dist/{info-CORLCPEJ.js → info-CSGWIAXA.js} +5 -5
- package/dist/{netlify-O7G3RLK4.js → netlify-DUB7BZ4E.js} +3 -3
- package/dist/{node-LXPQLMVB.js → node-ELE236WK.js} +3 -3
- package/dist/{openapi-TEOUOIJ2.js → openapi-KSY272CW.js} +5 -5
- package/dist/registry-B7FA6KMI.js +25 -0
- package/dist/{routes-GAXVWJUK.js → routes-NWJA5L5I.js} +4 -4
- package/dist/{scan-NQFI5S7P.js → scan-I5PT6TUX.js} +2 -2
- package/dist/{schema-D3v8VB7o.d.ts → schema-BpH6ivDY.d.ts} +2 -4
- package/dist/{schema-Z5VJ2I76.js → schema-NPI4NJEF.js} +3 -3
- package/dist/server/auth/index.js +3 -5
- package/dist/server/define/index.d.ts +7 -0
- package/dist/server/define/index.js +1 -1
- package/dist/server/http/index.js +1 -2
- package/dist/server/index.d.ts +34 -1
- package/dist/server/index.js +57 -48
- package/dist/server/index.js.map +1 -1
- package/dist/{services-typed-client-ASZL7FQV.js → services-typed-client-24VBMDOF.js} +2 -2
- package/dist/{services-typed-client-KK6RHRDG.js → services-typed-client-IETY2SAK.js} +2 -2
- package/dist/{start-HGUNNF5X.js → start-OAAAQ7Z4.js} +84 -69
- package/dist/start-OAAAQ7Z4.js.map +1 -0
- package/dist/{static-EO73I4C7.js → static-YWF2M6YT.js} +4 -4
- package/dist/{theo-cloud-HBCYEODQ.js → theo-cloud-EUK56I7O.js} +2 -2
- package/dist/{vercel-GSFDMF7K.js → vercel-LGDQWYZD.js} +3 -3
- package/dist/vite-plugin/index.d.ts +1 -1
- package/dist/vite-plugin/index.js +3 -4
- package/dist/{vite-plugin-TX5H4MB6.js → vite-plugin-IF2O6BJV.js} +7 -7
- package/package.json +4 -1
- package/dist/chunk-4HBI7DHP.js +0 -20
- package/dist/chunk-4HBI7DHP.js.map +0 -1
- package/dist/chunk-CG563V5M.js.map +0 -1
- package/dist/chunk-DNMSV3R3.js.map +0 -1
- package/dist/chunk-FGOX37NB.js.map +0 -1
- package/dist/chunk-H4J2LECY.js.map +0 -1
- package/dist/chunk-KJLECZWQ.js.map +0 -1
- package/dist/chunk-NZXH2LQQ.js.map +0 -1
- package/dist/chunk-S74FECKW.js.map +0 -1
- package/dist/chunk-WGHJD6I7.js.map +0 -1
- package/dist/chunk-X32KQH5C.js.map +0 -1
- package/dist/chunk-X3VNROZ7.js.map +0 -1
- package/dist/dev-ZU46C5AZ.js.map +0 -1
- package/dist/dev-emit-JBVINGHU.js.map +0 -1
- package/dist/generate-AZ2K6Z2Z.js +0 -281
- package/dist/generate-AZ2K6Z2Z.js.map +0 -1
- package/dist/registry-KW4F4D2L.js +0 -25
- package/dist/start-HGUNNF5X.js.map +0 -1
- /package/dist/{aws-lambda-SCRGTGF5.js.map → aws-lambda-WT4HRBNL.js.map} +0 -0
- /package/dist/{build-R74EU6BP.js.map → build-ZZAQV2ES.js.map} +0 -0
- /package/dist/{bun-FURRCQMS.js.map → bun-UTDVN6R4.js.map} +0 -0
- /package/dist/{check-NXYPLM6M.js.map → check-F3UDYSZ4.js.map} +0 -0
- /package/dist/{chunk-MWYSRZI4.js.map → chunk-EQV67HZL.js.map} +0 -0
- /package/dist/{chunk-DUKXQNM7.js.map → chunk-IHMJV2OK.js.map} +0 -0
- /package/dist/{cloudflare-IZ6VJ2OU.js.map → cloudflare-U5GYYI47.js.map} +0 -0
- /package/dist/{deno-deploy-O73NBXIW.js.map → deno-deploy-3QHJ3AJQ.js.map} +0 -0
- /package/dist/{dev-emit-66FCOS7V.js.map → dev-emit-4WG3B5BM.js.map} +0 -0
- /package/dist/{info-CORLCPEJ.js.map → info-CSGWIAXA.js.map} +0 -0
- /package/dist/{netlify-O7G3RLK4.js.map → netlify-DUB7BZ4E.js.map} +0 -0
- /package/dist/{node-LXPQLMVB.js.map → node-ELE236WK.js.map} +0 -0
- /package/dist/{openapi-TEOUOIJ2.js.map → openapi-KSY272CW.js.map} +0 -0
- /package/dist/{registry-KW4F4D2L.js.map → registry-B7FA6KMI.js.map} +0 -0
- /package/dist/{routes-GAXVWJUK.js.map → routes-NWJA5L5I.js.map} +0 -0
- /package/dist/{scan-NQFI5S7P.js.map → scan-I5PT6TUX.js.map} +0 -0
- /package/dist/{schema-Z5VJ2I76.js.map → schema-NPI4NJEF.js.map} +0 -0
- /package/dist/{services-typed-client-ASZL7FQV.js.map → services-typed-client-24VBMDOF.js.map} +0 -0
- /package/dist/{services-typed-client-KK6RHRDG.js.map → services-typed-client-IETY2SAK.js.map} +0 -0
- /package/dist/{static-EO73I4C7.js.map → static-YWF2M6YT.js.map} +0 -0
- /package/dist/{theo-cloud-HBCYEODQ.js.map → theo-cloud-EUK56I7O.js.map} +0 -0
- /package/dist/{vercel-GSFDMF7K.js.map → vercel-LGDQWYZD.js.map} +0 -0
- /package/dist/{vite-plugin-TX5H4MB6.js.map → vite-plugin-IF2O6BJV.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/define/define-route.ts","../src/server/define/define-action.ts","../src/server/define/define-middleware.ts","../src/server/define/define-agent-endpoint.ts","../src/server/define/define-agent-tool.ts","../src/server/define/define-websocket.ts","../src/server/define/define-channel.ts","../src/server/define/define-plugin.ts"],"sourcesContent":["import type { z } from 'zod'\n\n// T2.2 (architecture-cleanup) — RouteConfig type moved to core/contracts/\n// (canonical home per ADR-0001 v3). Re-export preserves the public path\n// `import { type RouteConfig } from 'theokit/server'`.\nexport type { RouteConfig } from '../../core/contracts/route-config.js'\n\nimport type { RouteConfig } from '../../core/contracts/route-config.js'\n\n/**\n * Define a typed HTTP route.\n * Identity function — provides type inference for route handlers.\n */\nexport function defineRoute<\n TQuery extends z.ZodType = z.ZodUndefined,\n TBody extends z.ZodType = z.ZodUndefined,\n TParams extends z.ZodType = z.ZodUndefined,\n TCtx = unknown,\n TResponse = unknown,\n>(\n config: RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>,\n): RouteConfig<TQuery, TBody, TParams, TCtx, TResponse> {\n return config\n}\n","import type { z } from 'zod'\n\n/**\n * Action wire-protocol accept mode per plan g3-server-actions-and-useaction\n * v1.2 ADR D1. Default behavior (when omitted) is `'json'`. `'form'` opts the\n * action into FormData multipart parsing for progressive-enhancement forms;\n * the runtime in `server/http/action-execute.ts` will coerce FormData entries\n * against the `input` schema via `formDataToObject` (Astro pattern).\n */\nexport type ActionAccept = 'form' | 'json'\n\nexport interface ActionConfig<TInput extends z.ZodType, TCtx = unknown> {\n /**\n * Zod input schema. Required: every action declares its input contract via\n * Zod (architecture rule: zod-is-SSOT). The shape becomes the handler's\n * typed `input` parameter via `z.infer<TInput>`.\n */\n input: TInput\n /**\n * Wire-protocol accept mode. Defaults to `'json'` when omitted. Setting\n * `'form'` switches the runtime to FormData multipart parsing — the input\n * schema MUST be `z.object(...)` so field-by-field coercion can drive\n * boolean string / number / array coercion (Astro pattern).\n */\n accept?: ActionAccept\n handler: (ctx: { input: z.infer<TInput>; ctx: TCtx }) => unknown\n}\n\n/**\n * Define a typed server action.\n *\n * Identity function — provides type inference for action handlers. The\n * runtime that consumes the config (validation + invocation + serialization)\n * lives in `server/http/action-execute.ts`.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.2: the new\n * `accept?: 'form' | 'json'` field is the only contract change vs the\n * pre-G3 identity. Existing callsites (`defineAction({input, handler})`)\n * continue to compile — `accept` is opt-in.\n */\nexport function defineAction<TInput extends z.ZodType, TCtx = unknown>(\n config: ActionConfig<TInput, TCtx>,\n): ActionConfig<TInput, TCtx> {\n return config\n}\n","export type MiddlewareHandler = (\n request: Request,\n next: (request: Request) => Promise<Response>,\n) => Response | Promise<Response>\n\n/**\n * Define a middleware handler.\n * Identity function — provides type annotation for middleware.\n */\nexport function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler {\n return handler\n}\n","import type { z } from 'zod'\n\nimport type { AgentEvent } from '../agent/agent-types.js'\n\nimport type { RouteConfig } from './define-route.js'\n\n/**\n * T5.1 — defineAgentEndpoint\n *\n * Sugar over defineRoute (ADR D4). Accepts an async generator that yields\n * AgentEvents and produces a RouteConfig whose handler returns a Response\n * streaming Server-Sent Events (SSE).\n *\n * Wire format: `data: <JSON>\\n\\n` per event. Standards-compliant.\n *\n * The generator may throw — the wrapper catches and emits a final\n * `{ type: 'error', message }` event before closing the stream.\n *\n * The wrapper observes `request.signal` (EC-7) — when aborted, the\n * underlying generator is told to `return()` and the stream closes\n * promptly.\n *\n * Note (EC-12, Out of Scope): SSE backpressure (slow consumer) is not\n * handled here. For high-frequency token streaming consider a different\n * transport (WS) or a buffer policy. This MVP enqueues each event\n * immediately.\n */\n\nexport interface AgentEndpointHandlerArgs<TCtx = unknown, TBody = unknown> {\n query: undefined\n body: TBody\n params: undefined\n request: Request\n ctx: TCtx\n /**\n * Mutable headers bag that the wrapper merges into the SSE response BEFORE\n * the stream starts. Used by `createConversationHistory` to issue a\n * conversation-id cookie on first request. Append entries via\n * `cookieHeaders.append('set-cookie', '<cookie-string>')`.\n *\n * Cookies appended AFTER the first yield are NOT applied — the response\n * headers commit when the wrapper constructs the Response, before the\n * async generator runs. This is per HTTP semantics, not a wrapper choice.\n */\n cookieHeaders: Headers\n /**\n * Phase 3 (Production-Readiness #5) — request abort signal.\n *\n * Fires when the SSE client disconnects (browser closes tab, abort fetch,\n * etc.). Thread this to `agent.send(msg, { signal })` so the SDK cancels\n * the in-flight provider call — STOPS TOKENS FROM CHARGING for output\n * the user will never receive.\n *\n * EC-1 (MUST FIX): the signal is derived via duck-type detection\n * (`'aborted' in r.signal && typeof r.signal.addEventListener === 'function'`)\n * to survive cross-realm scenarios (Node 18 polyfills, undici, Edge\n * runtimes with their own AbortSignal globals). `instanceof AbortSignal`\n * would fail in those cases.\n */\n signal: AbortSignal\n}\n\nexport interface AgentEndpointConfig<TCtx = unknown, TBody = unknown> {\n handler: (\n args: AgentEndpointHandlerArgs<TCtx, TBody>,\n ) => AsyncGenerator<AgentEvent, void, unknown>\n}\n\nconst SSE_HEADERS = {\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n} as const\n\nfunction encodeSSE(event: AgentEvent): Uint8Array {\n return new TextEncoder().encode(`data: ${JSON.stringify(event)}\\n\\n`)\n}\n\n/**\n * Resolve an AbortSignal from either a Web `Request` (`.signal`) or a\n * Node `IncomingMessage` (`.aborted` flag + `'close'`/'aborted' events).\n *\n * The framework's `executeRoute` passes IncomingMessage to route handlers\n * today, but `defineAgentEndpoint` was designed for the Web Standards\n * `Request` shape. This helper bridges both — preventing a runtime crash\n * (`Cannot read properties of undefined (reading 'aborted')`) that would\n * otherwise abort the SSE stream silently before the first yield.\n */\nfunction resolveAbortSignal(request: unknown): AbortSignal {\n if (typeof request !== 'object' || request === null) {\n return new AbortController().signal\n }\n const r = request as {\n signal?: unknown\n aborted?: boolean\n on?: (event: string, cb: () => void) => void\n }\n if (\n typeof r.signal === 'object' &&\n r.signal !== null &&\n 'aborted' in r.signal &&\n typeof (r.signal as AbortSignal).addEventListener === 'function'\n ) {\n return r.signal as AbortSignal\n }\n\n const controller = new AbortController()\n if (r.aborted === true) controller.abort()\n if (typeof r.on === 'function') {\n r.on('close', () => {\n if (!controller.signal.aborted) controller.abort()\n })\n r.on('aborted', () => {\n if (!controller.signal.aborted) controller.abort()\n })\n }\n return controller.signal\n}\n\nexport function defineAgentEndpoint<TBody = unknown, TCtx = unknown>(\n config: AgentEndpointConfig<TCtx, TBody>,\n): RouteConfig<z.ZodUndefined, z.ZodUndefined, z.ZodUndefined, TCtx, Response> {\n return {\n handler: async ({ request, ctx, body, query, params }) => {\n const cookieHeaders = new Headers()\n const signal = resolveAbortSignal(request)\n const generator = config.handler({\n request,\n ctx: ctx,\n body: body as TBody,\n query: query,\n params: params,\n cookieHeaders,\n signal,\n })\n\n // Prime the generator to its first yield. This forces the handler's\n // synchronous + async setup (including `createConversationHistory` if\n // used) to run BEFORE the Response headers commit, so any Set-Cookie\n // lines appended to `cookieHeaders` land in the actual response.\n //\n // First-byte latency cost: bounded by the work up to the first yield\n // (typically 100-500ms for an LLM chat with `agent.send`). Acceptable\n // for the use case; alternative (heuristic detection of cookie writes)\n // is brittle.\n let firstResult: IteratorResult<AgentEvent, void>\n let primeError: unknown\n try {\n firstResult = await generator.next()\n } catch (err) {\n primeError = err\n firstResult = { value: undefined, done: true }\n }\n\n // Merge any cookies the handler issued into the response headers.\n const responseHeaders = new Headers(SSE_HEADERS)\n for (const value of cookieHeaders.getSetCookie()) {\n responseHeaders.append('set-cookie', value)\n }\n\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const onAbort = () => {\n void generator.return(undefined)\n }\n\n if (signal.aborted) {\n controller.close()\n return\n }\n signal.addEventListener('abort', onAbort, { once: true })\n\n try {\n // If priming threw, yield a final error event and close.\n if (primeError !== undefined) {\n let message: string\n if (primeError instanceof Error) {\n message = primeError.message\n } else if (typeof primeError === 'string') {\n message = primeError\n } else {\n message = 'agent handler failed during setup'\n }\n controller.enqueue(encodeSSE({ type: 'error', message }))\n return\n }\n // Enqueue the primed first value (if any).\n if (firstResult.done !== true) {\n controller.enqueue(encodeSSE(firstResult.value))\n } else {\n return\n }\n // Continue iterating remaining events.\n for await (const event of generator) {\n // `signal.aborted` can flip true asynchronously via the\n // listener registered above. ESLint's narrowing only sees\n // the false assertion at line 114; the dynamic abort is\n // legitimate and the guard prevents enqueue-after-close.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (signal.aborted) break\n controller.enqueue(encodeSSE(event))\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n controller.enqueue(encodeSSE({ type: 'error', message }))\n } finally {\n signal.removeEventListener('abort', onAbort)\n controller.close()\n }\n },\n cancel() {\n void generator.return(undefined)\n },\n })\n\n return new Response(stream, { headers: responseHeaders })\n },\n }\n}\n","import { z } from 'zod'\n\n/**\n * Item #4 — `defineAgentTool`\n *\n * Sugar over the `@theokit/sdk` `CustomTool` contract. Takes a Zod schema +\n * handler and produces a structurally-compatible `CustomTool` that\n * `Agent.create({ tools: [...] })` accepts.\n *\n * Uses Zod v4's native `z.toJSONSchema()` to convert the input schema to\n * JSON Schema for LLM providers.\n *\n * Handler error propagation:\n * `defineAgentTool` parses the input via the Zod schema BEFORE calling the\n * user handler. Invalid input throws a `ZodError`, which the SDK's tool-\n * dispatcher (or the `streamAgentRun` adapter) sees as a tool failure and\n * surfaces as an `error` AgentEvent on the SSE wire (ADR D3).\n */\n\n/**\n * Local mirror of the SDK's `CustomTool` interface. We don't `import type`\n * from `@theokit/sdk` because the SDK is an optional peer (consumers who\n * never call `defineAgentTool` shouldn't need it installed). The shape is\n * the wire contract; any structurally-matching object is accepted by\n * `Agent.create({ tools })`.\n *\n * @public\n */\nexport interface CustomTool {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n handler: (input: Record<string, unknown>) => string | Promise<string>\n}\n\n/**\n * Spec accepted by {@link defineAgentTool}. `inputSchema` is a Zod 3 schema\n * rooted in `z.object(...)`. The `handler` argument type is inferred via\n * `z.infer<T>`.\n *\n * @public\n */\nexport interface DefineAgentToolSpec<T extends z.ZodType> {\n /** Tool name surfaced to the LLM. Must match `^[a-zA-Z][a-zA-Z0-9_-]{0,63}$`. */\n name: string\n /** Description surfaced to the LLM. Required — drives tool-selection accuracy. */\n description: string\n /** Zod schema describing the input. Must be `z.object(...)` at the root. */\n inputSchema: T\n /** Handler invoked with the parsed input. */\n handler: (input: z.infer<T>) => string | Promise<string>\n}\n\nconst TOOL_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/\n\nfunction isZodObject(schema: z.ZodType): boolean {\n // Zod 3 stores the typeName at `_def.typeName`. ZodObject has 'ZodObject'.\n // Refinements (`.refine`), transforms (`.transform`), and defaults wrap the\n // underlying schema in ZodEffects / ZodDefault / etc. — walk the chain via\n // `_def.schema` / `_def.innerType` until we hit ZodObject (or give up).\n // Avoids importing the ZodObject class to keep the runtime import surface\n // minimal.\n let current: unknown = schema\n for (let depth = 0; depth < 10; depth++) {\n const def = (current as { _def?: { typeName?: string; schema?: unknown; innerType?: unknown } })\n ._def\n if (def?.typeName === 'ZodObject') return true\n if (def?.schema !== undefined) {\n current = def.schema\n continue\n }\n if (def?.innerType !== undefined) {\n current = def.innerType\n continue\n }\n return false\n }\n return false\n}\n\n/**\n * Build a {@link CustomTool} from a Zod 3 schema + handler.\n *\n * Behavior:\n * - Validates `name` matches the LLM tool-name regex.\n * - Requires `inputSchema` to be a `ZodObject` (Anthropic + SDK contract).\n * - Warns (not throws) if `description` is empty — empty descriptions\n * degrade LLM tool selection.\n * - Converts the Zod schema to JSON Schema 7 inline (no `$ref`s — LLMs handle\n * inline schemas more reliably).\n * - Strips the top-level `$schema` field (Anthropic rejects schemas with\n * `$schema` at root in some provider modes).\n * - Wraps the handler to parse the input via the Zod schema BEFORE invoking\n * the user code — bad LLM-supplied input throws `ZodError`, which the SDK\n * converts to `tool_result(isError)`.\n *\n * @public\n */\nexport function defineAgentTool<T extends z.ZodType>(spec: DefineAgentToolSpec<T>): CustomTool {\n if (!TOOL_NAME_REGEX.test(spec.name)) {\n throw new Error(\n `defineAgentTool: name must match ${TOOL_NAME_REGEX.source}. Got: ${JSON.stringify(spec.name)}`,\n )\n }\n if (!isZodObject(spec.inputSchema)) {\n throw new Error('defineAgentTool: inputSchema must be a ZodObject (z.object({...}))')\n }\n if (spec.description.length === 0) {\n console.warn(\n `defineAgentTool(${JSON.stringify(spec.name)}): empty description degrades LLM tool selection — provide a one-sentence summary.`,\n )\n }\n\n // Zod v4 native JSON Schema conversion — replaces zod-to-json-schema dep.\n // Strip $schema (Anthropic + some providers reject it).\n const { $schema: _$schema, ...inputSchema } = z.toJSONSchema(spec.inputSchema) as Record<string, unknown> & {\n $schema?: unknown\n }\n\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (input: Record<string, unknown>): Promise<string> => {\n const parsed = spec.inputSchema.parse(input) as z.infer<T>\n return await spec.handler(parsed)\n },\n }\n}\n","import type { IncomingMessage } from 'node:http'\n\nexport interface WebSocketLike {\n send(data: string | Buffer): void\n close(code?: number, reason?: string): void\n}\n\nexport interface WebSocketHandler {\n onOpen?: (ws: WebSocketLike, req: IncomingMessage) => void\n onMessage?: (ws: WebSocketLike, data: string | Buffer) => void\n onClose?: (ws: WebSocketLike, code: number, reason: Buffer) => void\n onError?: (ws: WebSocketLike, error: Error) => void\n}\n\n/**\n * Define a WebSocket endpoint handler.\n * Identity function — provides type inference for WebSocket handlers.\n */\nexport function defineWebSocket(handler: WebSocketHandler): WebSocketHandler {\n return handler\n}\n\n/**\n * T5a.2 Phase F slice 3/3 — Web-Standards WebSocket endpoint handler.\n *\n * Mirror of `WebSocketHandler` for the Web `Request` shape. `onOpen`\n * receives `request: Request` instead of `req: IncomingMessage`. The\n * rest of the lifecycle (onMessage, onClose, onError) is shape-agnostic\n * (`WebSocketLike` is already Web-standards-compatible per the existing\n * design — `send(string | Buffer)` works on both Node `ws` and Web\n * `WebSocket` instances; CF Workers / Bun / Deno coerce as needed at\n * the adapter boundary).\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase F (closes Phase F).\n *\n * **Architectural note — WebSocket upgrade semantics differ across runtimes:**\n * - Node + `ws`: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —\n * `req` is `IncomingMessage`. Use `WebSocketHandler`.\n * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade\n * handshake IS a Web Request). Use `WebSocketHandlerWeb`.\n * - Bun: `server.upgrade(request, { data })` — same Web Request shape.\n * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.\n *\n * Cross-runtime WebSocket endpoints ship BOTH `WebSocketHandler` +\n * `WebSocketHandlerWeb` exports; the runtime adapter picks the matching\n * one. This is the canonical Hono / Nitric pattern.\n */\nexport interface WebSocketHandlerWeb {\n onOpen?: (ws: WebSocketLike, request: Request) => void\n onMessage?: (ws: WebSocketLike, data: string | Uint8Array) => void\n onClose?: (ws: WebSocketLike, code: number, reason: string) => void\n onError?: (ws: WebSocketLike, error: Error) => void\n}\n\n/**\n * Web-Standards `defineWebSocket` sibling. Identity function — provides\n * type inference for Web WebSocket handlers.\n *\n * **Type difference note vs Node path:**\n * - `onMessage` data is `string | Uint8Array` instead of `string | Buffer`\n * (Web standards have no `Buffer`; Node's Buffer is a Uint8Array\n * subclass so the Node path's Buffer values flow through unchanged\n * when adapters wrap them).\n * - `onClose` reason is `string` instead of `Buffer` (Web `CloseEvent`\n * exposes the reason as a UTF-8 string natively).\n */\nexport function defineWebSocketWeb(handler: WebSocketHandlerWeb): WebSocketHandlerWeb {\n return handler\n}\n","import type { IncomingMessage } from 'node:http'\n\nimport type { WebSocketLike } from './define-websocket.js'\n\nexport interface ChannelHandler<TMessage = unknown> {\n onSubscribe?: (ws: WebSocketLike, room: string, req: IncomingMessage) => void\n onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void\n onUnsubscribe?: (ws: WebSocketLike, room: string) => void\n}\n\n/**\n * Define a channel handler for WebSocket rooms.\n * Identity function — provides type inference for channel handlers.\n */\nexport function defineChannel<TMessage = unknown>(\n handler: ChannelHandler<TMessage>,\n): ChannelHandler<TMessage> {\n return handler\n}\n\n/**\n * T5a.2 Phase F slice 2/3 — Web-Standards channel handler.\n *\n * Mirror of `ChannelHandler<TMessage>` for the Web `Request` shape.\n * `onSubscribe` receives `request: Request` instead of `req: IncomingMessage`\n * — the rest of the surface (onMessage, onUnsubscribe) is shape-agnostic\n * (WebSocketLike is already Web-standards-compatible per `define-websocket.ts`).\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase F.\n *\n * **Architectural note:** WebSocket upgrade semantics differ across\n * runtimes:\n * - Node: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —\n * hands you `req: IncomingMessage` at the upgrade handshake.\n * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade\n * handshake IS a Web Request) — hands you `request: Request`.\n * - Bun: `server.upgrade(request, { data })` — same Web Request shape.\n * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.\n *\n * Channel handlers targeting CF/Bun/Deno use `WebChannelHandler`; legacy\n * Node consumers stay on `ChannelHandler`. Cross-runtime channels ship\n * both shapes.\n */\nexport interface WebChannelHandler<TMessage = unknown> {\n onSubscribe?: (ws: WebSocketLike, room: string, request: Request) => void\n onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void\n onUnsubscribe?: (ws: WebSocketLike, room: string) => void\n}\n\n/**\n * Web-Standards `defineChannel` sibling. Identity function — provides\n * type inference for Web channel handlers.\n */\nexport function defineWebChannel<TMessage = unknown>(\n handler: WebChannelHandler<TMessage>,\n): WebChannelHandler<TMessage> {\n return handler\n}\n","import type { TheoPlugin } from '../plugin-types.js'\n\n/**\n * Identity function for defining a Theo plugin.\n *\n * **Note:** Prefer `definePlugin` (shorter, canonical name per ADR-0008 D6).\n * Both functions are identical — `defineTheoPlugin` is kept as an alias for\n * existing in-tree consumers without forcing a migration sweep.\n */\nexport function defineTheoPlugin(plugin: TheoPlugin): TheoPlugin {\n return plugin\n}\n"],"mappings":";AAaO,SAAS,YAOd,QACsD;AACtD,SAAO;AACT;;;ACiBO,SAAS,aACd,QAC4B;AAC5B,SAAO;AACT;;;ACnCO,SAAS,iBAAiB,SAA+C;AAC9E,SAAO;AACT;;;ACyDA,IAAM,cAAc;AAAA,EAClB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,YAAY;AACd;AAEA,SAAS,UAAU,OAA+B;AAChD,SAAO,IAAI,YAAY,EAAE,OAAO,SAAS,KAAK,UAAU,KAAK,CAAC;AAAA;AAAA,CAAM;AACtE;AAYA,SAAS,mBAAmB,SAA+B;AACzD,MAAI,OAAO,YAAY,YAAY,YAAY,MAAM;AACnD,WAAO,IAAI,gBAAgB,EAAE;AAAA,EAC/B;AACA,QAAM,IAAI;AAKV,MACE,OAAO,EAAE,WAAW,YACpB,EAAE,WAAW,QACb,aAAa,EAAE,UACf,OAAQ,EAAE,OAAuB,qBAAqB,YACtD;AACA,WAAO,EAAE;AAAA,EACX;AAEA,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI,EAAE,YAAY,KAAM,YAAW,MAAM;AACzC,MAAI,OAAO,EAAE,OAAO,YAAY;AAC9B,MAAE,GAAG,SAAS,MAAM;AAClB,UAAI,CAAC,WAAW,OAAO,QAAS,YAAW,MAAM;AAAA,IACnD,CAAC;AACD,MAAE,GAAG,WAAW,MAAM;AACpB,UAAI,CAAC,WAAW,OAAO,QAAS,YAAW,MAAM;AAAA,IACnD,CAAC;AAAA,EACH;AACA,SAAO,WAAW;AACpB;AAEO,SAAS,oBACd,QAC6E;AAC7E,SAAO;AAAA,IACL,SAAS,OAAO,EAAE,SAA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K,WAAW;AAI7E,SAAO;AAAA,IACL,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA,IAClB;AAAA,IACA,SAAS,OAAO,UAAoD;AAClE,YAAM,SAAS,KAAK,YAAY,MAAM,KAAK;AAC3C,aAAO,MAAM,KAAK,QAAQ,MAAM;AAAA,IAClC;AAAA,EACF;AACF;;;AC9GO,SAAS,gBAAgB,SAA6C;AAC3E,SAAO;AACT;AA+CO,SAAS,mBAAmB,SAAmD;AACpF,SAAO;AACT;;;ACvDO,SAAS,cACd,SAC0B;AAC1B,SAAO;AACT;AAoCO,SAAS,iBACd,SAC6B;AAC7B,SAAO;AACT;;;ACjDO,SAAS,iBAAiB,QAAgC;AAC/D,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/contracts/action-protocol.ts","../src/server/http/send-response.ts","../src/server/http/middleware-runner.ts","../src/server/security/csrf-warn-dispatch.ts","../src/server/http/execute-stages.ts","../src/server/http/execute.ts","../src/server/http/form-data-to-object.ts","../src/server/http/handle-request-error.ts","../src/server/http/serialize-action-result.ts","../src/server/http/action-execute.ts","../src/server/http/batch-handler.ts","../src/server/http/cors.ts","../src/server/http/trace-context.ts"],"sourcesContent":["/**\n * Action protocol — cross-boundary contract for `defineAction` + `useAction`.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 0 / T0.1, ADRs D1 (encoding)\n * + D6 (full dot-notation path) + D7 (PII mask) — types and runtime referenced\n * by server (`server/http/action-execute.ts`, `server/define/define-action.ts`)\n * and client (`@theokit/react/useAction`, `vite-plugin/actions-virtual-module`).\n *\n * Lives in `core/contracts/` per architecture.md v3.1 exception — cross-module\n * deep imports ALLOWED for this file. Core depends on NOTHING intra-monorepo;\n * `extractUniversalIssues` is implemented INLINE (NOT imported from `@theokit/sdk`)\n * to honor dep-cruiser `core-depends-on-nothing` invariant (EC-1 absorbed).\n *\n * Field-key convention (D6 + EC-13): dot-notation full path. Nested objects use\n * `'user.address.zip'`; array indices use `'items.0.name'` (NOT bracket\n * `'items[0].name'`). Root-level errors (path = []) use empty string `''`\n * (EC-7). Consumers needing bracket notation can write a small `dotToBracket`\n * helper in userland.\n */\n\nimport type { TheoErrorCode, TheoErrorEnvelope, ValidationFieldsExt } from './error-envelope.js'\n\n/**\n * HTTP-status mapping per IANA HTTP Status Code Registry (subset relevant to\n * action surface). VALIDATION_ERROR → 422 is preferred over Astro's BAD_REQUEST/400\n * (more semantic for input-shape mismatch). PAYLOAD_TOO_LARGE → 413 covers EC-3\n * (response-side size limit; request-side reuses standard 413).\n */\nexport type ActionErrorCode =\n | 'VALIDATION_ERROR'\n | 'BAD_REQUEST'\n | 'UNAUTHORIZED'\n | 'FORBIDDEN'\n | 'NOT_FOUND'\n | 'METHOD_NOT_ALLOWED'\n | 'CONFLICT'\n | 'CONTENT_TOO_LARGE'\n | 'PAYLOAD_TOO_LARGE'\n | 'UNSUPPORTED_MEDIA_TYPE'\n | 'TOO_MANY_REQUESTS'\n | 'INTERNAL_SERVER_ERROR'\n\nconst CODE_TO_STATUS: Record<ActionErrorCode, number> = {\n VALIDATION_ERROR: 422,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n CONFLICT: 409,\n CONTENT_TOO_LARGE: 413,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n TOO_MANY_REQUESTS: 429,\n INTERNAL_SERVER_ERROR: 500,\n}\n\nconst STATUS_TO_CODE: Record<number, ActionErrorCode> = {\n 400: 'BAD_REQUEST',\n 401: 'UNAUTHORIZED',\n 403: 'FORBIDDEN',\n 404: 'NOT_FOUND',\n 405: 'METHOD_NOT_ALLOWED',\n 409: 'CONFLICT',\n 413: 'PAYLOAD_TOO_LARGE',\n 415: 'UNSUPPORTED_MEDIA_TYPE',\n 422: 'VALIDATION_ERROR',\n 429: 'TOO_MANY_REQUESTS',\n 500: 'INTERNAL_SERVER_ERROR',\n}\n\n/**\n * Universal zod issue shape covering BOTH v3 (`z.ZodIssue`) and v4 (`$ZodIssue`).\n * Duck-typed minimum surface: `{path, message}`. Implemented per EC-1 absorbed —\n * consumers chain may ship either zod major; constructor accepts `unknown` and\n * normalizes via `extractUniversalIssues`.\n */\nexport interface UniversalZodIssue {\n readonly path: readonly (string | number)[]\n readonly message: string\n readonly code?: string\n}\n\n/**\n * `ActionError` — general server-side action failure. Discriminator `type` is\n * literal `'TheoActionError'`; used by `ActionError.fromJson` to distinguish\n * from `ActionInputError`.\n */\nexport class ActionError extends Error {\n // Discriminator widened to the full union so subclasses can narrow to their\n // specific literal (TypeScript would otherwise reject the override). Concrete\n // values are still always exact literals at runtime.\n readonly type: 'TheoActionError' | 'TheoActionInputError' = 'TheoActionError'\n readonly code: ActionErrorCode\n readonly status: number\n\n constructor(params: { code: ActionErrorCode; message?: string; stack?: string }) {\n super(params.message ?? params.code)\n this.code = params.code\n this.status = ActionError.codeToStatus(params.code)\n if (params.stack) {\n this.stack = params.stack\n }\n }\n\n /**\n * G5 T2.4 — canonical envelope view of the action error. Maps the G3\n * ActionErrorCode to a canonical TheoErrorCode (VALIDATION_ERROR ↔\n * UNPROCESSABLE_ENTITY, CONTENT_TOO_LARGE ↔ PAYLOAD_TOO_LARGE) so consumer\n * UI / SDK code can switch on the unified envelope.\n *\n * Subclasses override to populate `ext` (see `ActionInputError.envelope`).\n */\n get envelope(): TheoErrorEnvelope {\n return {\n code: ActionError.toTheoErrorCode(this.code),\n message: this.message,\n }\n }\n\n /**\n * Translate G3 ActionErrorCode → canonical TheoErrorCode (blueprint\n * Recommendations § \"G3 ActionError becomes inaugural envelope user\").\n */\n static toTheoErrorCode(code: ActionErrorCode): TheoErrorCode {\n if (code === 'VALIDATION_ERROR') return 'UNPROCESSABLE_ENTITY'\n if (code === 'CONTENT_TOO_LARGE') return 'PAYLOAD_TOO_LARGE'\n // The other ActionErrorCode members (BAD_REQUEST/UNAUTHORIZED/FORBIDDEN/\n // NOT_FOUND/METHOD_NOT_ALLOWED/CONFLICT/PAYLOAD_TOO_LARGE/\n // UNSUPPORTED_MEDIA_TYPE/TOO_MANY_REQUESTS/INTERNAL_SERVER_ERROR) are\n // identical strings in TheoErrorCode. Narrow via a type predicate\n // instead of assertion.\n return code\n }\n\n static codeToStatus(code: ActionErrorCode): number {\n return CODE_TO_STATUS[code]\n }\n\n static statusToCode(status: number): ActionErrorCode {\n return STATUS_TO_CODE[status] ?? 'INTERNAL_SERVER_ERROR'\n }\n\n /**\n * Parse a serialized error JSON back into the typed class hierarchy.\n * Distinguishes `TheoActionInputError` (with `issues` array) from\n * `TheoActionError` via the `type` discriminator. Falls back to\n * `INTERNAL_SERVER_ERROR` for malformed bodies (non-object, missing\n * `type`, unknown `code`).\n */\n static fromJson(body: unknown): ActionError {\n if (typeof body !== 'object' || body === null) {\n return new ActionError({ code: 'INTERNAL_SERVER_ERROR' })\n }\n const obj = body as Record<string, unknown>\n if (obj.type === 'TheoActionInputError' && Array.isArray(obj.issues)) {\n return new ActionInputError(obj.issues as unknown[])\n }\n if (\n obj.type === 'TheoActionError' &&\n typeof obj.code === 'string' &&\n obj.code in CODE_TO_STATUS\n ) {\n return new ActionError({\n code: obj.code as ActionErrorCode,\n message: typeof obj.message === 'string' ? obj.message : undefined,\n })\n }\n return new ActionError({ code: 'INTERNAL_SERVER_ERROR' })\n }\n}\n\n/**\n * `ActionInputError` — validation failure with field-level mapping.\n *\n * `fields` is auto-derived from `issues`: for each issue, key = full\n * dot-notation path (`'user.address.zip'`; root-level `path:[]` → `''`;\n * array indices as numeric segments → `'items.0.name'`). Multiple messages\n * for the same key accumulate; duplicate (path, message) tuples are deduped.\n */\nexport class ActionInputError extends ActionError {\n override readonly type = 'TheoActionInputError' as const\n readonly issues: readonly UniversalZodIssue[]\n readonly fields: Record<string, string[]>\n\n constructor(rawIssues: unknown) {\n super({ code: 'VALIDATION_ERROR', message: 'Validation failed' })\n this.issues = extractUniversalIssues(rawIssues)\n this.fields = buildFieldsMap(this.issues)\n }\n\n /**\n * G5 T2.4 — envelope view with ValidationFieldsExt populated from .fields.\n * UI consumers can `switch (env.code)` on `UNPROCESSABLE_ENTITY` and read\n * `(env.ext as ValidationFieldsExt).fields` for field-level rendering.\n */\n override get envelope(): TheoErrorEnvelope<ValidationFieldsExt> {\n return {\n code: 'UNPROCESSABLE_ENTITY',\n message: this.message,\n ext: { fields: this.fields },\n }\n }\n}\n\nfunction buildFieldsMap(issues: readonly UniversalZodIssue[]): Record<string, string[]> {\n const fields: Record<string, string[]> = {}\n const seen = new Set<string>()\n for (const issue of issues) {\n // EC-7: root path → empty string key. EC-8: numeric segments preserved as strings.\n const key = issue.path.length === 0 ? '' : issue.path.join('.')\n const dedupeKey = `${key}\u0000${issue.message}`\n if (seen.has(dedupeKey)) continue\n seen.add(dedupeKey)\n const bucket = fields[key] ?? []\n bucket.push(issue.message)\n fields[key] = bucket\n }\n return fields\n}\n\n/**\n * Normalize zod v3 (`z.ZodIssue`) and v4 (`$ZodIssue`) raw issues to\n * `UniversalZodIssue[]` (EC-1 absorbed). Duck-typed on `{path, message}` —\n * does NOT import zod types (`core/contracts/` depends on no intra-monorepo\n * + zod is consumer-controlled across the boundary).\n *\n * Silently skips entries missing required fields or shape mismatches; returns\n * empty array on non-array input.\n */\nexport function extractUniversalIssues(raw: unknown): UniversalZodIssue[] {\n if (!Array.isArray(raw)) return []\n const out: UniversalZodIssue[] = []\n for (const entry of raw) {\n if (typeof entry !== 'object' || entry === null) continue\n const obj = entry as Record<string, unknown>\n if (!Array.isArray(obj.path)) continue\n if (typeof obj.message !== 'string') continue\n // Path entries must be string or number\n const path: (string | number)[] = []\n let pathValid = true\n for (const seg of obj.path) {\n if (typeof seg === 'string' || typeof seg === 'number') {\n path.push(seg)\n } else {\n pathValid = false\n break\n }\n }\n if (!pathValid) continue\n out.push({\n path,\n message: obj.message,\n code: typeof obj.code === 'string' ? obj.code : undefined,\n })\n }\n return out\n}\n\n/**\n * Type guard for `ActionError` (and its subclass `ActionInputError`). True\n * iff the value is an instance of `ActionError`. Use `isInputError` to\n * narrow specifically to validation failures.\n */\nexport function isActionError(value: unknown): value is ActionError {\n return value instanceof ActionError\n}\n\n/**\n * Type guard narrowing to `ActionInputError`. Requires `instanceof` check\n * (not duck-typing on `type`) to prevent attacker-controlled JSON from\n * being mistaken for a real error instance.\n */\nexport function isInputError(value: unknown): value is ActionInputError {\n return value instanceof ActionInputError\n}\n\n/**\n * `ActionResult<TData, TError>` — discriminated union returned by client-side\n * action invocation. Either `{data, error: undefined}` (success) or\n * `{data: undefined, error}` (failure). Mirrors Astro `SafeResult` shape.\n */\nexport type ActionResult<TData = unknown, TError extends ActionError = ActionError> =\n | { data: TData; error: undefined }\n | { data: undefined; error: TError }\n\n/**\n * `SerializedActionResult` — wire-shape emitted by `serializeActionResult`\n * in `server/http/serialize-action-result.ts` (T1.3). Discriminator `type`\n * distinguishes data (devalue-encoded), error (JSON), and empty (204) cases.\n */\nexport type SerializedActionResult =\n | {\n type: 'data'\n status: number\n contentType: 'application/json+devalue'\n body: string\n }\n | {\n type: 'error'\n status: number\n contentType: 'application/json'\n body: string\n }\n | { type: 'empty'; status: 204 }\n\n/**\n * `ActionManifestEntry` — per-action metadata emitted by `action-scan.ts`\n * (T1.4) into `.theokit/actions-manifest.json`. Consumed by virtual module\n * `@theo/actions` (T3.1) and G4 devtools \"Actions\" tab (T5.1).\n */\nexport interface ActionManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly urlPath: string\n readonly accept: 'form' | 'json'\n readonly hasInput: boolean\n}\n","import type { ServerResponse } from 'node:http'\n\nimport type { TheoTransformer } from '../transformer.js'\n\n/**\n * Canonical HTTP response helpers (T5.1 extraction).\n *\n * Moved out of execute.ts so request-pipeline stages (execute-stages.ts,\n * handle-request-error.ts, etc.) can depend on these helpers without\n * creating a cycle through execute.ts.\n *\n * Public surface re-exported from execute.ts for backward compat — every\n * existing caller of `sendError` / `sendJson` continues to work via the\n * `theokit/server` barrel.\n */\n\nexport function sendJson(\n res: ServerResponse,\n data: unknown,\n status = 200,\n transformer?: TheoTransformer,\n): void {\n // T1.2 — transformer-aware serialization. Default (no transformer) uses\n // JSON.stringify direct for backward compat.\n const body = transformer ? transformer.serialize(data) : JSON.stringify(data)\n res.writeHead(status, {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(body),\n })\n res.end(body)\n}\n\nexport interface SendErrorOptions {\n custom404Html?: string\n custom500Html?: string\n}\n\n/**\n * Canonical error response.\n *\n * T6.3 (PV-17): the positional 7-param signature is preserved for backward\n * compat. New call sites should use the options-bag form:\n *\n * sendError(res, { code, message, status, issues?, requestId?, options? })\n *\n * Both shapes resolve to the same implementation.\n */\nexport interface SendErrorInput {\n code: string\n message: string\n status: number\n issues?: unknown[]\n requestId?: string\n options?: SendErrorOptions\n}\n\nexport function sendError(res: ServerResponse, input: SendErrorInput): void\n/* eslint-disable-next-line max-params -- T6.3: positional overload preserved\n for backward compat (callers across cli/server still use positional). The\n options-bag overload above is the recommended path. */\nexport function sendError(\n res: ServerResponse,\n code: string,\n message: string,\n status: number,\n issues?: unknown[],\n requestId?: string,\n options?: SendErrorOptions,\n): void\n/* eslint-disable-next-line max-params, complexity -- delegates to two\n surface overloads above; the branch density mirrors the back-compat\n contract, not internal complexity. */\nexport function sendError(\n res: ServerResponse,\n codeOrInput: string | SendErrorInput,\n message?: string,\n status?: number,\n issues?: unknown[],\n requestId?: string,\n options?: SendErrorOptions,\n): void {\n let code: string\n if (typeof codeOrInput === 'string') {\n code = codeOrInput\n message = message ?? ''\n status = status ?? 500\n } else {\n code = codeOrInput.code\n message = codeOrInput.message\n status = codeOrInput.status\n issues = codeOrInput.issues\n requestId = codeOrInput.requestId\n options = codeOrInput.options\n }\n const errorMessage =\n code === 'INTERNAL_ERROR' && process.env.NODE_ENV === 'production'\n ? 'Internal server error'\n : message\n\n if (code === 'INTERNAL_ERROR') {\n console.error(`[${requestId ?? 'no-id'}] ${message}`)\n }\n\n if (status === 404 && options?.custom404Html) {\n const body = options.custom404Html\n res.writeHead(404, {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Length': Buffer.byteLength(body),\n })\n res.end(body)\n return\n }\n if (status === 500 && options?.custom500Html) {\n const body = options.custom500Html\n res.writeHead(500, {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Length': Buffer.byteLength(body),\n })\n res.end(body)\n return\n }\n\n sendJson(\n res,\n {\n error: {\n code,\n message: errorMessage,\n ...(requestId ? { requestId } : {}),\n ...(issues ? { issues } : {}),\n },\n },\n status,\n )\n}\n\n/**\n * T5a.2 Phase G slice 4/N — Web-Standards response helpers.\n *\n * Mirror of `sendJson` + `sendError` for the Web `Request`/`Response`\n * shape. Returns a native `Response` directly instead of mutating a\n * `ServerResponse`.\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase G.\n *\n * **Difference vs IncomingMessage path:**\n * - No `Content-Length` set explicitly — the runtime computes it from\n * the body when needed. CF Workers / Bun / Deno all do this; setting\n * it manually risks conflict if the body is a stream rather than a\n * fixed string.\n * - Custom 404/500 HTML options preserved (same opts shape).\n * - `requestId` flows into the response body's error envelope AND\n * surfaces as `x-request-id` header (parity with handleWebRequestError\n * Phase G slice 3/N).\n */\nexport function buildJsonResponse(\n data: unknown,\n status = 200,\n transformer?: TheoTransformer,\n): Response {\n const body = transformer ? transformer.serialize(data) : JSON.stringify(data)\n return new Response(body, {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\nexport function buildErrorResponse(input: SendErrorInput): Response {\n const { code, message, status, issues, requestId, options } = input\n const errorMessage =\n code === 'INTERNAL_ERROR' && process.env.NODE_ENV === 'production'\n ? 'Internal server error'\n : message\n\n if (code === 'INTERNAL_ERROR') {\n console.error(`[${requestId ?? 'no-id'}] ${message}`)\n }\n\n const headers: Record<string, string> = {}\n if (requestId !== undefined) headers['x-request-id'] = requestId\n\n if (status === 404 && options?.custom404Html !== undefined) {\n headers['content-type'] = 'text/html; charset=utf-8'\n return new Response(options.custom404Html, { status: 404, headers })\n }\n if (status === 500 && options?.custom500Html !== undefined) {\n headers['content-type'] = 'text/html; charset=utf-8'\n return new Response(options.custom500Html, { status: 500, headers })\n }\n\n headers['content-type'] = 'application/json'\n const body = JSON.stringify({\n error: {\n code,\n message: errorMessage,\n ...(requestId ? { requestId } : {}),\n ...(issues ? { issues } : {}),\n },\n })\n return new Response(body, { status, headers })\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Middleware runner. Checks for `serverDir/middleware.ts` + `context.ts`,\n * cached by CR-017. Paths are derived from `serverDir` (cwd-derived). No\n * HTTP input.\n */\nimport { existsSync } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { join } from 'node:path'\n\nimport { scanMiddlewares } from '../scan/middleware-scan.js'\nimport type { LoadModule } from '../scan/module-loader.js'\n\nexport interface MiddlewareResult {\n ctx: unknown\n aborted: boolean\n}\n\n// CR-017 fix: in dev `existsSync` + `scanMiddlewares` ran on EVERY request,\n// turning a constant filesystem read into per-request overhead. We cache\n// the scan result by serverDir. In prod the same scan should be done once\n// at boot — `theo build` already emits a manifest, but the dev path uses\n// this runtime cache as a defense-in-depth. The cache is invalidated by\n// process restart (Vite HMR replaces the module, clearing this map).\ninterface MiddlewareCacheEntry {\n singleFilePath: string\n singleFileExists: boolean\n dirMiddlewares: string[]\n}\nconst middlewareCache = new Map<string, MiddlewareCacheEntry>()\n\nexport function _resetMiddlewareCacheForTests(): void {\n middlewareCache.clear()\n}\n\n// Middleware default-export contract: a function (req, res, next).\ntype MiddlewareFn = (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) => void | Promise<void>\ntype ContextFactory = (args: { request: IncomingMessage; response: ServerResponse }) => unknown // Promise<unknown> is structurally `unknown`; one arm covers both.\n\nfunction getCachedScan(serverDir: string): MiddlewareCacheEntry {\n let cached = middlewareCache.get(serverDir)\n if (!cached) {\n const singleFilePath = join(serverDir, 'middleware.ts')\n cached = {\n singleFilePath,\n singleFileExists: existsSync(singleFilePath),\n dirMiddlewares: scanMiddlewares(serverDir),\n }\n middlewareCache.set(serverDir, cached)\n }\n return cached\n}\n\nasync function runOneMiddleware(\n mw: MiddlewareFn,\n req: IncomingMessage,\n res: ServerResponse,\n): Promise<{ nextCalled: boolean }> {\n // Object-held flag avoids TS narrowing `let nextCalled = false` to the\n // literal `false`, which would make `!nextCalled` an \"always-truthy\"\n // condition under control-flow analysis.\n const state = { nextCalled: false }\n await mw(req, res, () => {\n state.nextCalled = true\n })\n return state\n}\n\nexport async function runMiddlewareAndContext(\n req: IncomingMessage,\n res: ServerResponse,\n loadModule: LoadModule,\n serverDir: string,\n): Promise<MiddlewareResult> {\n const { singleFilePath, singleFileExists, dirMiddlewares } = getCachedScan(serverDir)\n const dirExists = dirMiddlewares.length > 0\n\n // 1. Ambiguity check — both file and directory is a configuration error\n if (singleFileExists && dirExists) {\n throw new Error(\n 'Ambiguous middleware configuration: found both server/middleware.ts and server/middleware/ directory. ' +\n 'Use one or the other, not both.',\n )\n }\n\n // 2. Run middleware chain from directory\n if (dirExists) {\n for (const mwPath of dirMiddlewares) {\n const mod = await loadModule(mwPath)\n const mw = mod.default as MiddlewareFn | undefined\n if (typeof mw !== 'function') continue\n\n const { nextCalled } = await runOneMiddleware(mw, req, res)\n if (!nextCalled || res.writableEnded) {\n return { ctx: {}, aborted: true }\n }\n }\n }\n\n // 3. Run single middleware file (backward compat)\n if (singleFileExists) {\n const mod = await loadModule(singleFilePath)\n const mw = mod.default as MiddlewareFn | undefined\n if (typeof mw === 'function') {\n const { nextCalled } = await runOneMiddleware(mw, req, res)\n if (!nextCalled || res.writableEnded) {\n return { ctx: {}, aborted: true }\n }\n }\n }\n\n // 4. Create context (if exists)\n let ctx: unknown = {}\n const contextPath = join(serverDir, 'context.ts')\n if (existsSync(contextPath)) {\n const mod = await loadModule(contextPath)\n const createContext = mod.createContext as ContextFactory | undefined\n if (typeof createContext === 'function') {\n ctx = await createContext({ request: req, response: res })\n }\n }\n\n return { ctx, aborted: false }\n}\n","/**\n * Canonical CSRF warn dispatcher (T3.3 of architecture-review-remediation-plan).\n *\n * Consolidates the duplicated `warn: (payload) => { warnOnce(...) }` closure\n * that previously appeared in both `http/execute.ts` and\n * `http/action-execute.ts`. Resolves PV-10 (DRY).\n *\n * `warnOnce` dedupes by `event:method:path` so a request loop with 1000 POSTs\n * doesn't flood logs with identical warnings. Apps grep for `event\":\"csrf.warn\"`\n * (stable event shape — see [[enforcement-cutover.md]]).\n */\nimport { warnOnce } from '../observability/logger.js'\n\nexport interface CsrfWarnPayload {\n event: string\n method: string\n path?: string\n reason: string\n code?: string\n docsUrl?: string\n warnOnce?: boolean\n}\n\n/**\n * Build the warn callback that `enforceCsrf` invokes for soft-mode warnings.\n * Returned function is suitable for the `warn` field of `enforceCsrf`'s options.\n */\nexport function dispatchCsrfWarn(payload: CsrfWarnPayload): void {\n const key = `${payload.event}:${payload.method}:${payload.path ?? ''}`\n warnOnce(key, payload as unknown as Record<string, unknown>)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { parseRequestBody } from '../body-parser.js'\n\nimport { sendError } from './send-response.js'\n\n/**\n * T5.1 (partial Pipeline extraction) — request-parsing + Zod-validation\n * stages extracted from the executeRoute monolith.\n *\n * Each stage returns `{ ok: true, ...data }` on success OR `{ ok: false }`\n * on short-circuit (in which case the stage already sent an error response).\n *\n * Per EC-5 (plugin hook ordering) and EC-15 (AsyncLocalStorage), these\n * stages do NOT invoke plugin hooks — the orchestrator (`executeRoute`)\n * keeps that responsibility in one place.\n */\n\nexport type StageResult<T> = { ok: true; data: T } | { ok: false }\n\n/**\n * Parse URL query + request body (multipart/form-data or JSON).\n * On parse failure, sends 400 or 415 (Unsupported Content-Type) + returns\n * `{ ok: false }`. Otherwise returns `{ query, body }`.\n */\nexport async function parseQueryAndBody(\n req: IncomingMessage,\n res: ServerResponse,\n requestId: string | undefined,\n): Promise<StageResult<{ query: Record<string, string>; body: unknown }>> {\n // Query\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`)\n const query: Record<string, string> = Object.fromEntries(url.searchParams)\n\n // Body (JSON + multipart/form-data)\n let body: unknown\n try {\n const parsed = await parseRequestBody(req)\n if (parsed.json !== undefined) {\n body = parsed.json\n } else if (parsed.files.length > 0 || Object.keys(parsed.fields).length > 0) {\n body = { ...parsed.fields, _files: parsed.files }\n } else {\n body = undefined\n }\n } catch (err) {\n const message = (err as Error).message\n const status = message.includes('Unsupported Content-Type') ? 415 : 400\n sendError(res, 'VALIDATION_ERROR', message, status, undefined, requestId)\n return { ok: false }\n }\n\n return { ok: true, data: { query, body } }\n}\n\n/**\n * Validate query, body, params against the route's Zod schemas (when present).\n * On validation failure, sends 400 with Zod issues + returns `{ ok: false }`.\n * On success, returns the (possibly-transformed) values from `schema.safeParse(...).data`.\n */\ninterface ZodLike {\n safeParse: (value: unknown) => {\n success: boolean\n data?: unknown\n error?: { issues: unknown[] }\n }\n}\nconst isZodLike = (value: unknown): value is ZodLike =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === 'function'\n\nexport function runZodValidation(\n routeConfig: Record<string, unknown>,\n res: ServerResponse,\n requestId: string | undefined,\n input: {\n query: Record<string, string>\n body: unknown\n params: Record<string, string>\n },\n): StageResult<{ query: Record<string, string>; body: unknown; params: Record<string, string> }> {\n const { query, params } = input\n let { body } = input\n\n if (isZodLike(routeConfig.query)) {\n const result = routeConfig.query.safeParse(query)\n if (!result.success) {\n sendError(\n res,\n 'VALIDATION_ERROR',\n 'Invalid query parameters',\n 400,\n result.error?.issues,\n requestId,\n )\n return { ok: false }\n }\n Object.assign(query, result.data)\n }\n\n if (isZodLike(routeConfig.body)) {\n const result = routeConfig.body.safeParse(body)\n if (!result.success) {\n sendError(\n res,\n 'VALIDATION_ERROR',\n 'Invalid request body',\n 400,\n result.error?.issues,\n requestId,\n )\n return { ok: false }\n }\n body = result.data\n }\n\n if (isZodLike(routeConfig.params)) {\n const result = routeConfig.params.safeParse(params)\n if (!result.success) {\n sendError(\n res,\n 'VALIDATION_ERROR',\n 'Invalid route parameters',\n 400,\n result.error?.issues,\n requestId,\n )\n return { ok: false }\n }\n Object.assign(params, result.data)\n }\n\n return { ok: true, data: { query, body, params } }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { AuthRequiredError } from '../auth/auth.js'\nimport { DuplicateContextKeyError } from '../jobs/duplicate-context-key-error.js'\nimport { createOutbox } from '../jobs/outbox.js'\nimport { createOutboxDispatcher, createQueueClient } from '../jobs/queue-client.js'\nimport { warnOnce } from '../observability/logger.js'\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\nimport { dispatchCsrfWarn } from '../security/csrf-warn-dispatch.js'\nimport { enforceCsrf } from '../security/csrf.js'\n\nimport type { ExecuteRouteContext } from './execute-context.js'\nimport { parseQueryAndBody, runZodValidation } from './execute-stages.js'\nimport { runMiddlewareAndContext } from './middleware-runner.js'\nimport { sendError, sendJson } from './send-response.js'\n\n// CSRF policy applies to every state-mutating method, including DELETE.\nconst CSRF_PROTECTED_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n// T5.1: sendJson + sendError + SendErrorOptions moved to send-response.ts\n// to break the execute ↔ execute-stages cycle. Re-exported below for\n// backward compat.\nexport { sendJson, sendError } from './send-response.js'\nexport type { SendErrorOptions, SendErrorInput } from './send-response.js'\n// T3.1 — ExecuteRouteContext (ADR-0016)\nexport type { ExecuteRouteContext } from './execute-context.js'\n\ninterface StreamPipeCtx {\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n ctx: Record<string, unknown>\n method: string\n pluginRunner: PluginRunner | undefined\n requestId: string | undefined\n routePath: string\n}\n\n/**\n * Pipe a Web Standard ReadableStream into a Node ServerResponse. Stream\n * errors after headers are sent cannot change the response status, but\n * MUST be logged + reported (CR-004 fix). Extracted from `executeRoute`\n * to keep that function's nesting under the max-depth ceiling.\n */\nasync function pipeWebStreamToResponse(\n body: ReadableStream<Uint8Array>,\n res: ServerResponse,\n ctx: StreamPipeCtx,\n): Promise<void> {\n const reader = body.getReader()\n try {\n let done = false\n while (!done) {\n const chunk = await reader.read()\n done = chunk.done\n if (!done) res.write(chunk.value)\n }\n } catch (streamErr) {\n warnOnce(`stream-error:${ctx.routePath}:${ctx.method}`, {\n event: 'stream.error',\n requestId: ctx.requestId ?? 'no-id',\n route: ctx.routePath,\n method: ctx.method,\n message: streamErr instanceof Error ? streamErr.message : String(streamErr),\n })\n if (ctx.pluginRunner) {\n try {\n await ctx.pluginRunner.runOnError(ctx.buildPluginCtx(ctx.ctx), streamErr)\n } catch {\n // onError plugins must never destabilize the response close.\n }\n }\n } finally {\n try {\n reader.releaseLock()\n } catch {\n /* lock may already be released by abort */\n }\n }\n}\n\n// sendError moved to send-response.ts (T5.1) — re-exported above.\n\n// CR-007/Knip cleanup: `parseBody` (legacy JSON-only parser) was exported\n// but had no remaining consumers — the route pipeline uses\n// `parseRequestBody` (multipart + JSON) directly. Removed to shrink the\n// public surface and remove the duplicated METHODS_WITH_BODY constant.\n\n// eslint-disable-next-line max-lines-per-function, sonarjs/cognitive-complexity, complexity -- `executeRoute` is the framework's central request pipeline; its body length + branch density mirror the actual request lifecycle. T3.1 / ADR-0016 retired `max-params` (context object replaces 12 positional args). Branch complexity remains intentional: the request lifecycle has irreducible state machine arms (CSRF stage → Zod validate → middleware → handler → stream/JSON response). Remaining helpers `runCsrfStage`, `parseQueryAndBody`, `runHandlerStage`, etc. were extracted in earlier waves.\nexport async function executeRoute(ctx: ExecuteRouteContext): Promise<void> {\n // T3.1 — destructure the context with defaults applied\n const {\n route,\n method,\n params,\n req,\n res,\n loadModule,\n serverDir,\n requestId,\n pluginRunner,\n transformer,\n csrfMode = 'strict',\n disallowed,\n jobBackend,\n } = ctx\n const buildPluginCtx = (ctxObj: Record<string, unknown>): PluginContext => ({\n request: req,\n response: res,\n ctx: ctxObj,\n requestId: requestId ?? 'no-id',\n })\n\n // T1.2 — emit x-theo-transformer header when a non-default transformer is in use.\n // 'json' is treated as default (no header); any named transformer emits.\n if (transformer && transformer.name !== 'json') {\n res.setHeader('x-theo-transformer', transformer.name)\n }\n\n try {\n // T4.2 — onRequest hook (runs before middleware)\n let ctx: Record<string, unknown> = {}\n if (pluginRunner) {\n pluginRunner.applyDecorations(ctx)\n const onReqResult = await pluginRunner.runOnRequest(buildPluginCtx(ctx))\n if (onReqResult.shortCircuited) return\n }\n\n // Run middleware + context pipeline\n if (serverDir) {\n const result = await runMiddlewareAndContext(req, res, loadModule, serverDir)\n if (result.aborted) return\n ctx = (result.ctx ?? {}) as Record<string, unknown>\n // Re-apply decorations on top of middleware-produced ctx so plugin\n // decorations win when middleware did not set the same key.\n if (pluginRunner) pluginRunner.applyDecorations(ctx)\n }\n\n // T2.1 — wire ctx.queue + outbox lifecycle when jobBackend is configured.\n // EC-202: throw on collision instead of silent override.\n if (jobBackend) {\n if (ctx.queue !== undefined) {\n throw new DuplicateContextKeyError('queue', {\n reason:\n 'A plugin or middleware already decorated ctx.queue; choose a different key OR remove jobs.backend from theo.config.ts.',\n })\n }\n const outbox = createOutbox()\n const queueClient = createQueueClient(jobBackend, outbox)\n ctx.queue = queueClient\n\n // Discard on abort or 4xx (handler throws cascade to 500 via catch\n // below, where statusCode is already >= 400).\n res.on('close', () => {\n if (!res.writableFinished) outbox.discard()\n })\n // Flush on commit, only when response indicates success.\n res.on('finish', () => {\n if (res.statusCode >= 400) {\n outbox.discard()\n return\n }\n void outbox.flush(createOutboxDispatcher(jobBackend))\n })\n }\n\n const mod = await loadModule(route.filePath)\n const routeConfig = mod[method]\n\n if (!routeConfig) {\n sendError(\n res,\n 'METHOD_NOT_ALLOWED',\n `Method ${method} not allowed`,\n 405,\n undefined,\n requestId,\n )\n return\n }\n\n const handler =\n typeof routeConfig === 'function'\n ? routeConfig\n : (routeConfig as Record<string, unknown>).handler\n if (typeof handler !== 'function') {\n sendError(res, 'INTERNAL_ERROR', 'Route handler is not a function', 500, undefined, requestId)\n return\n }\n\n // Phase 5 — CSRF enforcement (warn-first default; strict in 0.3.0).\n // Skips: safe methods (GET/HEAD/OPTIONS), per-route opt-out (`csrf: false`),\n // and bare function exports (legacy style — no opt-out hook available).\n const routeOptOut =\n typeof routeConfig === 'object' && (routeConfig as { csrf?: unknown }).csrf === false\n if (CSRF_PROTECTED_METHODS.has(method) && !routeOptOut) {\n const decision = enforceCsrf(\n req,\n csrfMode,\n {\n // T3.3 DRY — see security/csrf-warn-dispatch.ts\n warn: dispatchCsrfWarn,\n path: req.url,\n },\n disallowed,\n )\n if (!decision.allow) {\n sendError(\n res,\n 'CSRF_INVALID',\n decision.reason ?? 'CSRF check failed',\n 403,\n undefined,\n requestId,\n )\n return\n }\n }\n\n // T5.1 — extracted stages (parseQueryAndBody + runZodValidation).\n // Each stage either succeeds (returns parsed data) OR short-circuits\n // (sends the error response inline + returns ok:false).\n const rc = routeConfig as Record<string, unknown>\n\n const parseResult = await parseQueryAndBody(req, res, requestId)\n if (!parseResult.ok) return\n const { query } = parseResult.data\n let { body } = parseResult.data\n\n const validationResult = runZodValidation(rc, res, requestId, { query, body, params })\n if (!validationResult.ok) return\n body = validationResult.data.body\n\n // T4.3 — preHandler hook (after Zod validation, before handler)\n if (pluginRunner) {\n const preResult = await pluginRunner.runPreHandler(buildPluginCtx(ctx))\n if (preResult.shortCircuited) return\n }\n\n // Execute handler. `handler` is structurally typed as `unknown` at\n // this point (came out of a duck-typed module). Cast through a narrow\n // type so the call is properly typed.\n type RouteHandlerCallable = (args: {\n query: Record<string, string>\n body: unknown\n params: Record<string, string>\n request: IncomingMessage\n ctx: Record<string, unknown>\n }) => unknown\n const callableHandler = handler as RouteHandlerCallable\n const handlerResult = await callableHandler({ query, body, params, request: req, ctx })\n\n // Handle result\n if (handlerResult === undefined || handlerResult === null) {\n sendJson(res, null, (rc.status as number | undefined) ?? 204, transformer)\n if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx))\n return\n }\n\n if (handlerResult instanceof Response) {\n // `Object.fromEntries(Headers)` collapses multi-valued headers like\n // `Set-Cookie` to a single string. Set Set-Cookie via setHeader array\n // overload BEFORE writeHead (writeHead flushes headers; later setHeader\n // is a no-op or throws). Then writeHead with the remaining singletons.\n const headersBag: Record<string, string> = {}\n for (const [k, v] of handlerResult.headers) {\n if (k.toLowerCase() !== 'set-cookie') headersBag[k] = v\n }\n const setCookies = handlerResult.headers.getSetCookie()\n if (setCookies.length > 0) {\n res.setHeader('Set-Cookie', setCookies)\n }\n res.writeHead(handlerResult.status, headersBag)\n\n if (handlerResult.body) {\n await pipeWebStreamToResponse(handlerResult.body, res, {\n buildPluginCtx,\n ctx,\n method,\n pluginRunner,\n requestId,\n routePath: route.routePath,\n })\n }\n\n res.end()\n if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx))\n return\n }\n\n sendJson(res, handlerResult, (rc.status as number | undefined) ?? 200, transformer)\n if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx))\n } catch (err) {\n // T4.4 — onError hook (runs before default error response)\n if (pluginRunner) {\n // Best-effort: capture a ctx snapshot for plugins. Decorations were\n // applied to local `ctx` above, but if the error came before that, we\n // pass an empty ctx — the request/response are what matters here.\n const errCtxObj: Record<string, unknown> = {}\n pluginRunner.applyDecorations(errCtxObj)\n await pluginRunner.runOnError(buildPluginCtx(errCtxObj), err)\n // EC-9: response may already have been ended by an onError hook\n if (res.writableEnded) {\n // Still run onResponse but mark inErrorPath to prevent recursion\n await pluginRunner.runOnResponse(buildPluginCtx(errCtxObj), { inErrorPath: true })\n return\n }\n }\n // Duck-type the auth error: under Vite dev / vitest the module-loader\n // can produce a duplicate `AuthRequiredError` class identity, so\n // `instanceof` returns false even though the thrown value carries the\n // expected `code` + `status` fields. We fall back to a shape check.\n const isAuthError =\n err instanceof AuthRequiredError ||\n (err !== null &&\n typeof err === 'object' &&\n (err as { code?: unknown }).code === 'AUTH_REQUIRED' &&\n (err as { status?: unknown }).status === 401)\n\n if (isAuthError) {\n const authErr = err as { code: string; message: string; status: number }\n sendError(res, authErr.code, authErr.message, authErr.status, undefined, requestId)\n if (pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n pluginRunner.applyDecorations(errCtxObj)\n await pluginRunner.runOnResponse(buildPluginCtx(errCtxObj), { inErrorPath: true })\n }\n return\n }\n sendError(\n res,\n 'INTERNAL_ERROR',\n err instanceof Error && err.message ? err.message : 'Internal server error',\n 500,\n undefined,\n requestId,\n )\n if (pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n pluginRunner.applyDecorations(errCtxObj)\n await pluginRunner.runOnResponse(buildPluginCtx(errCtxObj), { inErrorPath: true })\n }\n }\n}\n","/**\n * FormData → ZodObject coercion driven by the declared schema.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.3 + Astro\n * runtime/server.ts:323-397 pattern (adapted to zod v3 shape access via\n * `_def.shape()`). FormData entries arrive as strings (or File for binary);\n * we walk the schema field-by-field and coerce to the declared zod type\n * before letting `safeParse` finalize validation.\n *\n * Supports: ZodString, ZodNumber, ZodBoolean, ZodArray (via getAll), nested\n * ZodObject (via dot-notation prefix), ZodOptional / ZodNullable / ZodDefault\n * wrappers. Skips: ZodDiscriminatedUnion + ZodPipe + ZodIntersection (deferred\n * to consumer's safeParse fallback — values returned as-is, zod will validate\n * or coerce).\n */\nimport { z } from 'zod'\n\n/**\n * Walk the declared ZodObject schema and pull values from `formData`,\n * coercing per-field. Returns a plain object suitable for `schema.safeParse`.\n *\n * `prefix` is used for recursive nested-object resolution: a nested field at\n * `user.address.zip` is read from formData key `user.address.zip` (top-level\n * call uses empty prefix).\n */\nexport function formDataToObject(\n formData: FormData,\n schema: z.ZodObject<z.ZodRawShape>,\n prefix = '',\n): Record<string, unknown> {\n const shape = schema._def.shape()\n const out: Record<string, unknown> = {}\n\n for (const [key, rawValidator] of Object.entries(shape)) {\n const fullKey = prefix + key\n const validator = unwrapWrappers(rawValidator)\n\n if (validator instanceof z.ZodObject) {\n // Recurse for nested object types\n const nestedPrefix = `${fullKey}.`\n const hasNestedKeys = [...formData.keys()].some((k) => k.startsWith(nestedPrefix))\n if (hasNestedKeys) {\n out[key] = formDataToObject(formData, validator as z.ZodObject<z.ZodRawShape>, nestedPrefix)\n continue\n }\n // No nested keys present — apply default / nullable / undefined semantics\n out[key] = unwrapMissingDefault(rawValidator)\n continue\n }\n\n if (validator instanceof z.ZodArray) {\n const values = formData.getAll(fullKey)\n out[key] = coerceArrayElements(values, validator as z.ZodArray<z.ZodTypeAny>)\n continue\n }\n\n if (validator instanceof z.ZodBoolean) {\n out[key] = coerceBoolean(formData, fullKey)\n continue\n }\n\n // Scalar (string / number / etc.)\n if (formData.has(fullKey)) {\n const raw = formData.get(fullKey)\n out[key] = coerceScalar(raw, validator)\n } else {\n out[key] = unwrapMissingDefault(rawValidator)\n }\n }\n\n return out\n}\n\n/** Strip ZodOptional / ZodNullable / ZodDefault to reach the inner validator. */\nfunction unwrapWrappers(validator: z.ZodTypeAny): z.ZodTypeAny {\n let inner: z.ZodTypeAny = validator\n while (\n inner instanceof z.ZodOptional ||\n inner instanceof z.ZodNullable ||\n inner instanceof z.ZodDefault\n ) {\n inner = (inner._def as { innerType: z.ZodTypeAny }).innerType\n }\n return inner\n}\n\n/**\n * What to return when a field is missing from FormData:\n * - ZodDefault → the default value (evaluated if function)\n * - ZodNullable → null\n * - ZodOptional → undefined\n * - else → undefined (consumer safeParse will likely error)\n */\nfunction unwrapMissingDefault(validator: z.ZodTypeAny): unknown {\n let cursor: z.ZodTypeAny = validator\n while (\n cursor instanceof z.ZodOptional ||\n cursor instanceof z.ZodNullable ||\n cursor instanceof z.ZodDefault\n ) {\n if (cursor instanceof z.ZodDefault) {\n const def = (cursor._def as { defaultValue: unknown }).defaultValue\n return typeof def === 'function' ? (def as () => unknown)() : def\n }\n if (cursor instanceof z.ZodNullable) return null\n cursor = (cursor._def as { innerType: z.ZodTypeAny }).innerType\n }\n return undefined\n}\n\nfunction coerceScalar(raw: FormDataEntryValue | null, validator: z.ZodTypeAny): unknown {\n if (raw === null) return undefined\n if (validator instanceof z.ZodNumber) {\n return typeof raw === 'string' ? Number(raw) : raw\n }\n // String, File, default — pass through (zod will validate File via .instanceof if used)\n return raw\n}\n\nfunction coerceArrayElements(\n values: FormDataEntryValue[],\n arrayValidator: z.ZodArray<z.ZodTypeAny>,\n): unknown[] {\n const elementType = unwrapWrappers(arrayValidator._def.type)\n if (elementType instanceof z.ZodNumber) {\n return values.map((v) => (typeof v === 'string' ? Number(v) : v))\n }\n if (elementType instanceof z.ZodBoolean) {\n return values.map((v) => {\n if (v === 'true') return true\n if (v === 'false') return false\n return Boolean(v)\n })\n }\n // String / File / unknown — pass through\n return values\n}\n\nfunction coerceBoolean(formData: FormData, key: string): boolean | undefined {\n if (!formData.has(key)) return undefined\n const val = formData.get(key)\n if (val === 'true') return true\n if (val === 'false') return false\n // Presence with truthy non-boolean string (e.g., HTML checkbox \"on\") → true\n return Boolean(val)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { AuthRequiredError } from '../auth/auth.js'\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\n\nimport { sendError } from './send-response.js'\n\n/**\n * Canonical error handler for HTTP request pipelines (T3.4 of\n * architecture-review-remediation-plan, PV-9 DRY).\n *\n * Replaces the duplicated catch-block logic in `executeRoute` (1 site) and\n * `executeAction` (1 site, via `handleActionError`). Both code paths now\n * share this implementation.\n *\n * Behavior contract (preserved from previous inline catches):\n * - Plugin `onError` fires first (swallowed if it throws — never amplify failure).\n * - `AuthRequiredError` is detected via `instanceof` AND a duck-type shape\n * check (`code === 'AUTH_REQUIRED' && status === 401`) — required because\n * under Vite dev / vitest the module-loader can produce a duplicate\n * AuthRequiredError class identity, breaking `instanceof`.\n * - `onResponse({ inErrorPath: true })` always fires at the end (swallowed\n * if it throws — EC-9).\n */\nexport interface HandleRequestErrorCtx {\n req: IncomingMessage\n res: ServerResponse\n requestId: string | undefined\n pluginRunner: PluginRunner | undefined\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n}\n\nexport async function handleRequestError(err: unknown, c: HandleRequestErrorCtx): Promise<void> {\n // 1. onError hook — swallowed on failure (EC-9 — never amplify)\n if (c.pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n c.pluginRunner.applyDecorations(errCtxObj)\n try {\n await c.pluginRunner.runOnError(c.buildPluginCtx(errCtxObj), err)\n } catch {\n // onError handlers must never destabilize the response.\n }\n // EC-9: response may already have been ended by an onError hook\n if (c.res.writableEnded) {\n try {\n await c.pluginRunner.runOnResponse(c.buildPluginCtx(errCtxObj), {\n inErrorPath: true,\n })\n } catch {\n // Containment (same as above).\n }\n return\n }\n }\n\n // 2. Auth error detection (instanceof + duck-type fallback)\n const isAuthError =\n err instanceof AuthRequiredError ||\n (err !== null &&\n typeof err === 'object' &&\n (err as { code?: unknown }).code === 'AUTH_REQUIRED' &&\n (err as { status?: unknown }).status === 401)\n\n if (isAuthError) {\n const authErr = err as { code: string; message: string; status: number }\n sendError(c.res, authErr.code, authErr.message, authErr.status, undefined, c.requestId)\n } else {\n sendError(\n c.res,\n 'INTERNAL_ERROR',\n err instanceof Error ? err.message : 'Internal server error',\n 500,\n undefined,\n c.requestId,\n )\n }\n\n // 3. onResponse(inErrorPath) — swallowed on failure (EC-9)\n if (c.pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n c.pluginRunner.applyDecorations(errCtxObj)\n try {\n await c.pluginRunner.runOnResponse(c.buildPluginCtx(errCtxObj), {\n inErrorPath: true,\n })\n } catch {\n // Containment.\n }\n }\n}\n\n/**\n * T5a.2 Phase G slice 3/N — Web-Standards request error handler.\n *\n * Mirror of `handleRequestError(err, c: HandleRequestErrorCtx)` for the\n * Web `Request` shape. Returns a native `Response` directly instead of\n * mutating `res`. Same behavioral contract:\n *\n * 1. Auth-error detection via `instanceof AuthRequiredError` PLUS a\n * duck-type fallback (`code === 'AUTH_REQUIRED' && status === 401`)\n * — needed because Vite dev / vitest can produce duplicate class\n * identities, breaking `instanceof`.\n * 2. Envelope-shaped JSON body using `serverErrorToEnvelope` (G5 D3\n * boundary translation).\n * 3. Status code derived from envelope.code via `envelopeCodeToStatus`\n * mirror (already implemented inline in web-handler.ts; this slice\n * uses the same mapping table).\n *\n * **Difference vs IncomingMessage path:** the Web path's plugin runner\n * orchestration lives in `executeWebRequest`'s `runWithHooks` /\n * `runErrorHooks` (Phase G slice 1/N) — `handleWebRequestError` is the\n * leaf that builds the error Response WITHOUT touching plugin hooks.\n * Callers compose: `executeWebRequest` (or future Web execute pipeline)\n * catches a throw, calls `handleWebRequestError(err, { requestId })` to\n * build the Response, then routes through onError hooks separately.\n */\nexport interface HandleWebRequestErrorCtx {\n requestId?: string\n}\n\nexport async function handleWebRequestError(\n err: unknown,\n ctx: HandleWebRequestErrorCtx = {},\n): Promise<Response> {\n // Lazy import to avoid pulling the full envelope translator into the\n // bundle for consumers who don't hit the error path. Same dynamic-\n // import pattern as web-handler.ts's parseBodyFull.\n const { serverErrorToEnvelope } = await import('../../core/contracts/server-error-to-envelope.js')\n\n // 1. Auth-error detection (instanceof + duck-type fallback — same as\n // IncomingMessage path for cross-module class-identity safety).\n const isAuthError =\n err instanceof AuthRequiredError ||\n (err !== null &&\n typeof err === 'object' &&\n (err as { code?: unknown }).code === 'AUTH_REQUIRED' &&\n (err as { status?: unknown }).status === 401)\n\n if (isAuthError) {\n const authErr = err as { code?: string; message?: string; status?: number }\n return new Response(\n JSON.stringify({\n code: authErr.code ?? 'AUTH_REQUIRED',\n message: authErr.message ?? 'Authentication required',\n }),\n {\n status: authErr.status ?? 401,\n headers: {\n 'content-type': 'application/json',\n ...(ctx.requestId !== undefined ? { 'x-request-id': ctx.requestId } : {}),\n },\n },\n )\n }\n\n // 2. Envelope translation for everything else (G5 D3 boundary).\n const envelope = serverErrorToEnvelope(err)\n return new Response(JSON.stringify(envelope), {\n status: envelopeCodeToHttpStatus(envelope.code),\n headers: {\n 'content-type': 'application/json',\n ...(ctx.requestId !== undefined ? { 'x-request-id': ctx.requestId } : {}),\n },\n })\n}\n\n/**\n * T5a.2 Phase G slice 3/N — internal HTTP-status mapper for envelope codes.\n * Mirror of the inline `envelopeCodeToStatus` table in web-handler.ts;\n * duplicated to avoid a circular dep between handle-request-error and\n * web-handler. The two tables MUST stay in sync — Phase G slice 4/N may\n * consolidate them into a shared core/contracts module.\n */\nfunction envelopeCodeToHttpStatus(code: string): number {\n switch (code) {\n case 'BAD_REQUEST':\n return 400\n case 'UNAUTHORIZED':\n return 401\n case 'FORBIDDEN':\n return 403\n case 'NOT_FOUND':\n return 404\n case 'METHOD_NOT_ALLOWED':\n return 405\n case 'PAYLOAD_TOO_LARGE':\n return 413\n case 'UNPROCESSABLE_ENTITY':\n return 422\n case 'TOO_MANY_REQUESTS':\n case 'RATE_LIMITED':\n return 429\n case 'BAD_GATEWAY':\n return 502\n case 'SERVICE_UNAVAILABLE':\n return 503\n case 'GATEWAY_TIMEOUT':\n return 504\n case 'INTERNAL_SERVER_ERROR':\n default:\n return 500\n }\n}\n","/**\n * Server-side action result serializer.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.3 + ADR D1.\n * Wraps `devalue.stringify` for success payloads (preserves Date/Set/URL/bigint\n * roundtrip) and JSON-encodes error envelopes for `ActionError` /\n * `ActionInputError`. Returns a `SerializedActionResult` discriminated union\n * consumed by the HTTP send layer (`action-execute.ts`).\n *\n * EC absorbed:\n * - EC-3 (response side): `responseBodySizeLimit` default 5 MB; throws\n * `ActionError({code:'PAYLOAD_TOO_LARGE'})` when the serialized body\n * exceeds the limit. Prevents handler-returns-100MB DoS.\n */\nimport { stringify as devalueStringify } from 'devalue'\n\nimport {\n ActionError,\n ActionInputError,\n type ActionResult,\n type SerializedActionResult,\n} from '../../core/contracts/action-protocol.js'\n\nconst DEFAULT_RESPONSE_BODY_SIZE_LIMIT = 5 * 1024 * 1024 // 5 MB\n\nexport interface SerializeOptions {\n /**\n * Maximum allowed length of the serialized response body in BYTES (UTF-8\n * length of `body` string is checked, not the JS string length). Default\n * 5 MB. Configurable via `defineConfig({security:{responseBodySizeLimit}})`.\n */\n responseBodySizeLimit?: number\n}\n\n/**\n * Serialize an action result for the wire.\n *\n * - Success with data: `application/json+devalue` body via devalue.stringify\n * with a `URL` reviver for round-tripping URL instances.\n * - Success with `undefined` data: status 204 empty.\n * - Error: `application/json` JSON body with type discriminator\n * (`TheoActionError` or `TheoActionInputError`) + code + message\n * (+ fields/issues for input errors).\n *\n * Throws `ActionError({code:'PAYLOAD_TOO_LARGE'})` if the serialized body\n * exceeds the configured size limit (EC-3).\n *\n * Throws on `Response` instance as data (Astro guard — handler must return\n * plain JSON-serializable values, not Web Response objects).\n */\nexport function serializeActionResult(\n result: ActionResult,\n options: SerializeOptions = {},\n): SerializedActionResult {\n const limit = options.responseBodySizeLimit ?? DEFAULT_RESPONSE_BODY_SIZE_LIMIT\n\n if (result.error !== undefined) {\n const body =\n result.error instanceof ActionInputError\n ? JSON.stringify({\n type: result.error.type,\n code: result.error.code,\n message: result.error.message,\n issues: result.error.issues,\n fields: result.error.fields,\n })\n : JSON.stringify({\n type: result.error.type,\n code: result.error.code,\n message: result.error.message,\n })\n if (Buffer.byteLength(body, 'utf8') > limit) {\n throw new ActionError({\n code: 'PAYLOAD_TOO_LARGE',\n message: `Serialized error body exceeds limit (${limit} bytes)`,\n })\n }\n return {\n type: 'error',\n status: result.error.status,\n contentType: 'application/json',\n body,\n }\n }\n\n if (result.data === undefined) {\n return { type: 'empty', status: 204 }\n }\n\n if (result.data instanceof Response) {\n throw new ActionError({\n code: 'INTERNAL_SERVER_ERROR',\n message: 'Action handler cannot serialize Response objects — return plain data instead',\n })\n }\n\n let body: string\n try {\n body = devalueStringify(result.data, {\n URL: (value: unknown) => value instanceof URL && value.href,\n })\n } catch (e) {\n throw new ActionError({\n code: 'INTERNAL_SERVER_ERROR',\n message: `Action data not serializable: ${e instanceof Error ? e.message : String(e)}`,\n })\n }\n\n if (Buffer.byteLength(body, 'utf8') > limit) {\n throw new ActionError({\n code: 'PAYLOAD_TOO_LARGE',\n message: `Serialized response body exceeds limit (${limit} bytes)`,\n })\n }\n\n return {\n type: 'data',\n status: 200,\n contentType: 'application/json+devalue',\n body,\n }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport type { z } from 'zod'\n\nimport {\n ActionError,\n ActionInputError,\n type ActionErrorCode,\n} from '../../core/contracts/action-protocol.js'\nimport { parseRequestBody, type ParsedBody } from '../body-parser.js'\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\nimport type { LoadModule } from '../scan/module-loader.js'\nimport { dispatchCsrfWarn } from '../security/csrf-warn-dispatch.js'\nimport { enforceCsrf, type CsrfMode, type DisallowedConfig } from '../security/csrf.js'\n\nimport { sendError } from './execute.js'\nimport { formDataToObject } from './form-data-to-object.js'\nimport { handleRequestError } from './handle-request-error.js'\nimport { runMiddlewareAndContext } from './middleware-runner.js'\nimport { serializeActionResult } from './serialize-action-result.js'\n\n// Universal dev gate — same IIFE pattern as track-agent-run (EC-11 tree-shake).\n// Both checks are statically replaceable by bundlers in prod build, so the\n// devtools dispatcher import is eliminated from prod bundles entirely.\nconst __IS_DEV = (() => {\n try {\n return (import.meta as { env?: { DEV?: boolean } }).env?.DEV === true\n } catch {\n return process.env.NODE_ENV !== 'production'\n }\n})()\n\n// Minimal Zod-shaped contract — we only need `safeParse`, not the whole API.\ninterface ZodLike {\n safeParse: (value: unknown) => {\n success: boolean\n data?: unknown\n error?: { issues: z.ZodIssue[] }\n }\n}\n\n// Shape of a `defineAction` export. Anchored by structural typing — we do\n// not import the action factory's return type to avoid module cycles, but\n// we do reject inputs that fail the structural test.\ninterface ActionConfig {\n input: ZodLike\n handler: (params: { input: unknown; ctx: unknown }) => unknown\n csrf?: false\n /** T1.3 sub-C: wire-protocol accept mode (defaults to 'json' when omitted). */\n accept?: 'form' | 'json'\n}\n\nfunction isActionConfig(value: unknown): value is ActionConfig {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n if (typeof candidate.handler !== 'function') return false\n const input = candidate.input as ZodLike | undefined\n return typeof input?.safeParse === 'function'\n}\n\nexport interface ExecuteActionOptions {\n filePath: string\n exportName: string\n req: IncomingMessage\n res: ServerResponse\n loadModule: LoadModule\n serverDir?: string\n requestId?: string\n pluginRunner?: PluginRunner\n csrfMode?: CsrfMode\n disallowed?: DisallowedConfig\n}\n\n// Backwards-compatible positional signature; the options-shape is the new\n// preferred entry point and what the framework uses internally.\n// eslint-disable-next-line max-params -- public API surface; existing callers pass positional args\nexport async function executeAction(\n filePath: string,\n exportName: string,\n req: IncomingMessage,\n res: ServerResponse,\n loadModule: LoadModule,\n serverDir?: string,\n requestId?: string,\n pluginRunner?: PluginRunner,\n csrfMode: CsrfMode = 'strict',\n disallowed?: DisallowedConfig,\n): Promise<void> {\n return executeActionWithOptions({\n filePath,\n exportName,\n req,\n res,\n loadModule,\n serverDir,\n requestId,\n pluginRunner,\n csrfMode,\n disallowed,\n })\n}\n\nasync function loadActionConfig(\n loadModule: LoadModule,\n filePath: string,\n exportName: string,\n res: ServerResponse,\n requestId: string | undefined,\n): Promise<ActionConfig | null> {\n const mod = await loadModule(filePath)\n const exportedValue = mod[exportName]\n if (!isActionConfig(exportedValue)) {\n sendError(res, 'NOT_FOUND', `Action \"${exportName}\" not found`, 404, undefined, requestId)\n return null\n }\n return exportedValue\n}\n\ninterface CsrfActionCtx {\n actionConfig: ActionConfig\n csrfMode: CsrfMode\n disallowed: DisallowedConfig | undefined\n requestId: string | undefined\n}\n\nfunction enforceCsrfForAction(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: CsrfActionCtx,\n): boolean {\n if (ctx.actionConfig.csrf === false) return true\n const decision = enforceCsrf(\n req,\n ctx.csrfMode,\n {\n // T3.3 DRY — canonical dispatcher\n warn: dispatchCsrfWarn,\n path: req.url,\n },\n ctx.disallowed,\n )\n if (decision.allow) return true\n sendError(\n res,\n 'CSRF_INVALID',\n decision.reason ?? 'CSRF check failed',\n 403,\n undefined,\n ctx.requestId,\n )\n return false\n}\n\ninterface ActionPipeline {\n ctx: Record<string, unknown>\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n pluginRunner: PluginRunner | undefined\n serverDir: string | undefined\n loadModule: LoadModule\n req: IncomingMessage\n res: ServerResponse\n}\n\nasync function runPreHandlerPipeline(p: ActionPipeline): Promise<boolean> {\n if (p.serverDir) {\n const result = await runMiddlewareAndContext(p.req, p.res, p.loadModule, p.serverDir)\n if (result.aborted) return false\n Object.assign(p.ctx, (result.ctx ?? {}) as Record<string, unknown>)\n p.pluginRunner?.applyDecorations(p.ctx)\n }\n if (p.pluginRunner) {\n const preResult = await p.pluginRunner.runPreHandler(p.buildPluginCtx(p.ctx))\n if (preResult.shortCircuited) return false\n }\n return true\n}\n\nasync function readActionBody(\n req: IncomingMessage,\n res: ServerResponse,\n requestId: string | undefined,\n actionConfig: ActionConfig,\n): Promise<{ ok: true; body: unknown } | { ok: false }> {\n try {\n const parsed = await parseRequestBody(req)\n const accept = actionConfig.accept ?? 'json'\n let body: unknown\n if (accept === 'form') {\n body = formDataToObject(\n synthesizeFormData(parsed),\n actionConfig.input as unknown as z.ZodObject<z.ZodRawShape>,\n )\n } else if (parsed.json !== undefined) {\n body = parsed.json\n } else {\n body = parsed.fields\n }\n return { ok: true, body }\n } catch (err) {\n sendError(res, 'VALIDATION_ERROR', (err as Error).message, 400, undefined, requestId)\n return { ok: false }\n }\n}\n\n/**\n * Build a FormData instance from the body-parser's `ParsedBody`. Fields become\n * string entries; files become Blob entries with the original filename. Used\n * only when `accept === 'form'` to feed `formDataToObject`.\n */\nfunction synthesizeFormData(parsed: ParsedBody): FormData {\n const fd = new FormData()\n for (const [name, value] of Object.entries(parsed.fields)) {\n fd.append(name, value)\n }\n for (const file of parsed.files) {\n const blob = new Blob([file.buffer as unknown as ArrayBuffer], {\n type: file.mimeType,\n })\n fd.append(file.fieldname, blob, file.filename)\n }\n return fd\n}\n\n/**\n * Write a serialized ActionResult to the response. Sets content-type, status,\n * and body. Returns void; caller must not write further after invoking.\n */\nfunction writeSerialized(\n res: ServerResponse,\n serialized: ReturnType<typeof serializeActionResult>,\n): void {\n if (serialized.type === 'empty') {\n res.statusCode = serialized.status\n res.end()\n return\n }\n res.statusCode = serialized.status\n res.setHeader('Content-Type', serialized.contentType)\n res.end(serialized.body)\n}\n\n/**\n * Dev-only telemetry: dispatch ACTION_CALL_ADD so the devtools Actions tab\n * (T5.1) can render this call. Tree-shaken in prod via __IS_DEV guard.\n * Mirrors trackAgentRun pattern. Never throws (swallow + log).\n */\nasync function emitActionCallTelemetry(\n name: string,\n startedAt: number,\n input: unknown,\n outcome: { status: 'success'; output: unknown } | { status: 'error'; error: ActionError },\n): Promise<void> {\n if (!__IS_DEV) return\n try {\n const mod = (await import('../../devtools/bridge/dispatcher.js')) as {\n dispatcher: {\n onActionCall: (r: {\n id: string\n timestamp: number\n name: string\n input: unknown\n output?: unknown\n error?: { code: string; message: string; fields?: Record<string, string[]> }\n durationMs: number\n status: 'success' | 'error'\n }) => void\n }\n }\n mod.dispatcher.onActionCall({\n // eslint-disable-next-line sonarjs/pseudo-random -- non-secret correlation id\n id: `act-${String(Date.now())}-${Math.random().toString(36).slice(2, 8)}`,\n timestamp: startedAt,\n name,\n input,\n output: outcome.status === 'success' ? outcome.output : undefined,\n error:\n outcome.status === 'error'\n ? {\n code: outcome.error.code,\n message: outcome.error.message,\n fields: outcome.error instanceof ActionInputError ? outcome.error.fields : undefined,\n }\n : undefined,\n durationMs: Date.now() - startedAt,\n status: outcome.status,\n })\n } catch {\n // devtools dispatcher missing in some prod-like bundle — silently skip\n }\n}\n\nasync function executeActionWithOptions(opts: ExecuteActionOptions): Promise<void> {\n const {\n filePath,\n exportName,\n req,\n res,\n loadModule,\n serverDir,\n requestId,\n pluginRunner,\n csrfMode = 'strict',\n disallowed,\n } = opts\n\n const buildPluginCtx = (ctxObj: Record<string, unknown>): PluginContext => ({\n request: req,\n response: res,\n ctx: ctxObj,\n requestId: requestId ?? 'no-id',\n })\n\n let ctx: Record<string, unknown> = {}\n\n try {\n // 1. Only POST.\n if ((req.method ?? 'GET').toUpperCase() !== 'POST') {\n sendError(res, 'METHOD_NOT_ALLOWED', 'Actions only accept POST', 405, undefined, requestId)\n return\n }\n\n // 2. Plugin onRequest hook (parity with executeRoute).\n if (pluginRunner) {\n pluginRunner.applyDecorations(ctx)\n const onReqResult = await pluginRunner.runOnRequest(buildPluginCtx(ctx))\n if (onReqResult.shortCircuited) return\n }\n\n // 3. Load module + locate action export.\n const actionConfig = await loadActionConfig(loadModule, filePath, exportName, res, requestId)\n if (!actionConfig) return\n\n // 4. CSRF enforcement\n if (!enforceCsrfForAction(req, res, { actionConfig, csrfMode, disallowed, requestId })) {\n return\n }\n\n // 5+6. Middleware + context pipeline, then plugin preHandler.\n const pipeline: ActionPipeline = {\n ctx,\n buildPluginCtx,\n pluginRunner,\n serverDir,\n loadModule,\n req,\n res,\n }\n if (!(await runPreHandlerPipeline(pipeline))) return\n ctx = pipeline.ctx\n\n // 7. Parse body (supports JSON and multipart/form-data).\n const bodyOutcome = await readActionBody(req, res, requestId, actionConfig)\n if (!bodyOutcome.ok) return\n\n // T1.3 sub-C action name derived from exportName for telemetry.\n const actionName = exportName === 'default' ? deriveActionNameFromPath(filePath) : exportName\n const startedAt = Date.now()\n\n // 8. Validate input with Zod — failure → ActionInputError envelope (T0.1 + ADR D6).\n const result = actionConfig.input.safeParse(bodyOutcome.body)\n if (!result.success) {\n const inputErr = new ActionInputError(result.error?.issues ?? [])\n writeSerialized(res, serializeActionResult({ data: undefined, error: inputErr }))\n await emitActionCallTelemetry(actionName, startedAt, bodyOutcome.body, {\n status: 'error',\n error: inputErr,\n })\n return\n }\n\n await runActionHandler({\n actionConfig,\n actionName,\n startedAt,\n input: result.data,\n ctx,\n res,\n pluginRunner,\n buildPluginCtx,\n })\n } catch (err) {\n await handleActionError(err, { req, res, ctx, requestId, pluginRunner, buildPluginCtx })\n }\n}\n\n/** Derive a stable display name from filePath when handler exported as default. */\nfunction deriveActionNameFromPath(filePath: string): string {\n const base = filePath.split(/[\\\\/]/).pop() ?? 'unknown'\n return base.replace(/\\.[jt]sx?$/, '')\n}\n\n/**\n * Duck-typed guard for ActionError-shaped throws. Necessary because Vite SSR\n * may load multiple module copies of `core/contracts/action-protocol.ts` when\n * the fixture resolves `theokit/server` via a different path than the runtime\n * import — `err instanceof ActionError` then fails even though the user\n * legitimately threw `new ActionError(...)`.\n *\n * Server-only: only invoked on handler-thrown errors (trust boundary already\n * inside the action runtime). Not safe to use on client-parsed JSON — for\n * that path keep `isActionError` (the instanceof guard) from action-protocol.\n */\nfunction isActionErrorLike(err: unknown): err is ActionError {\n if (err === null || typeof err !== 'object') return false\n const obj = err as Record<string, unknown>\n return (\n (obj.type === 'TheoActionError' || obj.type === 'TheoActionInputError') &&\n typeof obj.code === 'string' &&\n typeof obj.status === 'number'\n )\n}\n\ninterface HandlerCtx {\n actionConfig: ActionConfig\n actionName: string\n startedAt: number\n input: unknown\n ctx: Record<string, unknown>\n res: ServerResponse\n pluginRunner: PluginRunner | undefined\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n}\n\nasync function runActionHandler(args: HandlerCtx): Promise<void> {\n try {\n const handlerResult = await args.actionConfig.handler({ input: args.input, ctx: args.ctx })\n // T1.3 sub-C — wire devalue serialization (ADR D1). Undefined → 204; data → 200 + json+devalue.\n writeSerialized(args.res, serializeActionResult({ data: handlerResult, error: undefined }))\n if (args.pluginRunner) {\n await args.pluginRunner.runOnResponse(args.buildPluginCtx(args.ctx))\n }\n await emitActionCallTelemetry(args.actionName, args.startedAt, args.input, {\n status: 'success',\n output: handlerResult,\n })\n } catch (err) {\n // Handler-thrown ActionError → use the typed envelope; other throws bubble\n // up to executeActionWithOptions for handleActionError fallback chain.\n // Duck-type the `type` discriminator (not instanceof): Vite SSR can load\n // multiple module copies of action-protocol.ts when fixture and runtime\n // resolve different paths; `err instanceof ActionError` then fails even\n // when the handler legitimately threw via `new ActionError(...)`.\n if (isActionErrorLike(err)) {\n writeSerialized(args.res, serializeActionResult({ data: undefined, error: err }))\n await emitActionCallTelemetry(args.actionName, args.startedAt, args.input, {\n status: 'error',\n error: err,\n })\n return\n }\n // Wrap unknown throws as INTERNAL_SERVER_ERROR with the original message\n // preserved for telemetry; production error handler still consumes via\n // handleActionError fallback (preserves AuthRequiredError duck-type).\n const wrapped = new ActionError({\n code: 'INTERNAL_SERVER_ERROR' satisfies ActionErrorCode,\n message: err instanceof Error ? err.message : 'Action handler threw',\n })\n await emitActionCallTelemetry(args.actionName, args.startedAt, args.input, {\n status: 'error',\n error: wrapped,\n })\n throw err\n }\n}\n\ninterface ActionErrorCtx {\n req: IncomingMessage\n res: ServerResponse\n ctx: Record<string, unknown>\n requestId: string | undefined\n pluginRunner: PluginRunner | undefined\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n}\n\n// T3.4 (PV-9 DRY): delegate to the shared `handleRequestError` helper.\n// Adds the duck-type AuthRequiredError fallback (latent bug fix — was\n// missing from action-execute, present in execute).\nasync function handleActionError(err: unknown, c: ActionErrorCtx): Promise<void> {\n return handleRequestError(err, {\n req: c.req,\n res: c.res,\n requestId: c.requestId,\n pluginRunner: c.pluginRunner,\n buildPluginCtx: c.buildPluginCtx,\n })\n}\n","/**\n * T1.4 — Server-side batch handler.\n *\n * Receives `{ requests: [...] }` POSTed to `/api/__theo_batch__` and returns\n * `{ results: [...] }` with per-item error isolation. EC-2: items cannot\n * override auth/forwarded headers (would be a session-bypass vector).\n */\n\nimport { z } from 'zod'\n\nexport const STRIPPED_HEADERS = [\n 'authorization',\n 'cookie',\n 'x-forwarded-for',\n 'x-forwarded-host',\n 'x-forwarded-proto',\n 'x-real-ip',\n 'host',\n] as const\n\nexport const BATCH_PATH = '/api/__theo_batch__'\nconst DEFAULT_MAX_BATCH = 32\n\nexport class BatchPathConflictError extends Error {\n constructor(path: string) {\n super(\n `Server route conflicts with reserved batch path ${path}. ` +\n `Rename the route or disable batching in theo.config.ts.`,\n )\n this.name = 'BatchPathConflictError'\n }\n}\n\nconst batchRequestSchema = z.object({\n path: z.string().min(1),\n method: z.string().min(1),\n query: z.record(z.string(), z.unknown()).optional(),\n body: z.unknown().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n})\n\nconst batchPayloadSchema = z.object({\n requests: z.array(batchRequestSchema).min(1),\n})\n\nexport type BatchRequestItem = z.infer<typeof batchRequestSchema>\nexport type BatchPayload = z.infer<typeof batchPayloadSchema>\n\nexport type BatchExecuteFn = (\n req: BatchRequestItem,\n) => Promise<{ data: unknown } | { error: { message: string; code?: string } }>\n\nexport interface HandleBatchOptions {\n execute: BatchExecuteFn\n /** Max number of items per batch. Default 32. */\n max?: number\n /** Outer-request headers that override per-item headers in STRIPPED_HEADERS. */\n outerHeaders?: Record<string, string>\n}\n\nexport type BatchResultItem = { data: unknown } | { error: { message: string; code?: string } }\n\nexport interface BatchResponse {\n results: BatchResultItem[]\n}\n\n/**\n * Sanitize a per-item header object: keys in STRIPPED_HEADERS are removed,\n * then the outer request's values for those keys are layered on top so that\n * downstream middlewares see the real session/auth headers.\n */\nfunction sanitizeItemHeaders(\n itemHeaders: Record<string, string> | undefined,\n outerHeaders: Record<string, string> | undefined,\n): Record<string, string> {\n const out: Record<string, string> = {}\n if (itemHeaders) {\n for (const [k, v] of Object.entries(itemHeaders)) {\n const lower = k.toLowerCase()\n if (!(STRIPPED_HEADERS as readonly string[]).includes(lower)) {\n out[lower] = v\n }\n }\n }\n if (outerHeaders) {\n for (const stripped of STRIPPED_HEADERS) {\n // `Object.hasOwn` defends against missing keys without triggering\n // `no-unnecessary-condition` (TypeScript types `outerHeaders` keys\n // as defined; `hasOwn` keeps the conditional honest at runtime).\n if (Object.hasOwn(outerHeaders, stripped)) {\n out[stripped] = outerHeaders[stripped]\n }\n }\n }\n return out\n}\n\n/**\n * Validate + execute a batch request.\n *\n * CR-028 fix: previously the signature was `payload: BatchPayload`,\n * suggesting the caller had already validated. In reality `api-middleware`\n * passes `JSON.parse(rawBody) as BatchPayload` — an unsafe cast over raw\n * HTTP input. We widen the input type to `unknown` so the type system\n * forces validation, then run Zod once at this single trust boundary.\n */\nexport async function handleBatchRequest(\n payload: unknown,\n options: HandleBatchOptions,\n): Promise<BatchResponse> {\n const parsed = batchPayloadSchema.parse(payload)\n const max = options.max ?? DEFAULT_MAX_BATCH\n if (parsed.requests.length > max) {\n throw new Error(`Batch size ${parsed.requests.length} exceeds max ${max}`)\n }\n\n const results: BatchResultItem[] = []\n for (const item of parsed.requests) {\n const sanitized: BatchRequestItem = {\n ...item,\n headers: sanitizeItemHeaders(item.headers, options.outerHeaders),\n }\n try {\n const r = await options.execute(sanitized)\n results.push(r)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n results.push({ error: { message } })\n }\n }\n return { results }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\n/**\n * T1.2 — CORS middleware.\n *\n * Single global middleware that runs FIRST in the request pipeline:\n * CORS preflight → rate limit → CSRF → security headers → handler\n *\n * Preflight (`OPTIONS` with `Access-Control-Request-Method`) is handled\n * by `handlePreflight`, which short-circuits the response with 204 +\n * Access-Control-* headers.\n *\n * Non-preflight requests pass through; `applyHeaders` adds\n * `Access-Control-Allow-Origin` (echoing the request's Origin),\n * `Access-Control-Expose-Headers`, and `Access-Control-Allow-Credentials`.\n *\n * Per ADR D3: preflight responses are deterministic and only the matched\n * origin is echoed back (never `'*'` when credentials are enabled —\n * required by the CORS spec).\n */\n\n// `'*'` is conceptually distinct from a regular host string (it means\n// \"any origin\"), but TypeScript-wise it is just `string`, so we collapse\n// the union and document the wildcard via the type's name. Callers should\n// still pass the literal `'*'` to mean \"allow anywhere\" for readability.\nexport type CorsOrigin =\n | string\n | RegExp\n | readonly (string | RegExp)[]\n | ((origin: string) => boolean)\n\nexport interface CorsConfig {\n origins: CorsOrigin\n methods?: readonly ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD')[]\n allowedHeaders?: readonly string[]\n exposedHeaders?: readonly string[]\n credentials?: boolean\n maxAge?: number\n}\n\nexport interface CorsHandler {\n handlePreflight(req: IncomingMessage, res: ServerResponse): boolean\n applyHeaders(req: IncomingMessage, res: ServerResponse): void\n}\n\nconst DEFAULT_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'] as const\nconst DEFAULT_ALLOWED_HEADERS = ['Content-Type', 'X-Theo-Action', 'Authorization'] as const\nconst DEFAULT_MAX_AGE = 600\n\n/**\n * Read the request Origin header. Per Node typing, it can be a string,\n * string[] (proxy doubled), or undefined. We take the FIRST non-empty\n * value (consistent with `csrf.ts:121-122`).\n */\nfunction readOrigin(req: IncomingMessage): string | undefined {\n const raw = req.headers.origin\n if (raw === undefined) return undefined\n if (Array.isArray(raw)) {\n return raw.find((v): v is string => typeof v === 'string' && v.length > 0)\n }\n return raw\n}\n\n/**\n * Test whether `origin` is allowed by `allowed`. Pure function — no I/O.\n *\n * EC-8: callback variants that throw are fail-closed (deny). Without\n * this, a transient datastore outage would silently widen CORS during\n * the failure window.\n */\nexport function matchesOrigin(origin: string, allowed: CorsOrigin): boolean {\n if (allowed === '*') return true\n if (typeof allowed === 'string') return origin === allowed\n if (allowed instanceof RegExp) {\n allowed.lastIndex = 0\n return allowed.test(origin)\n }\n if (Array.isArray(allowed)) {\n for (const entry of allowed) {\n if (typeof entry === 'string' && origin === entry) return true\n if (entry instanceof RegExp) {\n entry.lastIndex = 0\n if (entry.test(origin)) return true\n }\n }\n return false\n }\n if (typeof allowed === 'function') {\n // EC-8: fail-closed on any throw\n try {\n return allowed(origin)\n } catch {\n return false\n }\n }\n return false\n}\n\nexport function createCorsHandler(config: CorsConfig): CorsHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflight(req, res) {\n if (req.method !== 'OPTIONS') return false\n const acMethod = req.headers['access-control-request-method']\n if (!acMethod) return false\n const origin = readOrigin(req)\n if (!origin) return false\n\n if (!matchesOrigin(origin, config.origins)) {\n res.statusCode = 403\n res.end()\n return true\n }\n\n // Echo the matched origin (NEVER '*' when credentials are enabled —\n // browsers reject wildcard responses with credentials per CORS spec).\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Access-Control-Allow-Methods', methods.join(', '))\n res.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(', '))\n res.setHeader('Access-Control-Max-Age', maxAge)\n // Mark the response as origin-varying so caches don't poison\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n res.statusCode = 204\n res.end()\n return true\n },\n\n applyHeaders(req, res) {\n const origin = readOrigin(req)\n if (!origin) return\n if (!matchesOrigin(origin, config.origins)) return\n\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders && config.exposedHeaders.length > 0) {\n res.setHeader('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n\n/**\n * T5a.2 Phase B slice 5/6 — Web-Standards CORS handler.\n *\n * Mirror of `createCorsHandler(config): CorsHandler` for the Web `Request`\n * shape. Same `CorsConfig`, same `matchesOrigin` logic (pure helper\n * already), same security guarantees (echo matched origin only — never\n * `'*'` when credentials enabled; EC-8 fail-closed on callback throw).\n *\n * Signature differences vs the IncomingMessage pair:\n * - `handlePreflightRequest(request, config): Response | null` — returns\n * `Response` when this is a CORS preflight; `null` when not. Caller\n * short-circuits accordingly (same control-flow semantic as boolean).\n * - `applyCorsHeaders(request, target, config): void` — mutates a\n * `Headers` instance in place. Caller passes the headers they're\n * building for their Response.\n */\nexport interface CorsWebHandler {\n handlePreflightRequest(request: Request): Response | null\n applyCorsHeaders(request: Request, target: Headers): void\n}\n\nexport function createCorsWebHandler(config: CorsConfig): CorsWebHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflightRequest(request) {\n if (request.method !== 'OPTIONS') return null\n const acMethod = request.headers.get('access-control-request-method')\n if (acMethod === null || acMethod.length === 0) return null\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return null\n\n if (!matchesOrigin(origin, config.origins)) {\n return new Response(null, { status: 403 })\n }\n\n // Echo matched origin only (security: never `'*'` when credentials\n // enabled — browsers reject per CORS spec).\n const headers = new Headers({\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods': methods.join(', '),\n 'Access-Control-Allow-Headers': allowedHeaders.join(', '),\n 'Access-Control-Max-Age': maxAge,\n Vary: 'Origin',\n })\n if (credentials) headers.set('Access-Control-Allow-Credentials', 'true')\n return new Response(null, { status: 204, headers })\n },\n\n applyCorsHeaders(request, target) {\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return\n if (!matchesOrigin(origin, config.origins)) return\n\n target.set('Access-Control-Allow-Origin', origin)\n target.set('Vary', 'Origin')\n if (credentials) target.set('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders !== undefined && config.exposedHeaders.length > 0) {\n target.set('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n","// T5a.1b — Web Crypto migration. randomUUID() moved to globalThis.crypto.\n// IncomingMessage stays as a type-only import (runtime-clean — TS erases at\n// build); full IncomingMessage→Request boundary migration deferred to a\n// later T5a.1c+ slice per ADR-0028 incremental leaf-first sequence.\nimport type { IncomingMessage } from 'node:http'\n\n/**\n * Phase 7 — Observability: traceId propagation (D7).\n *\n * Extract a stable identifier from incoming requests so a single value\n * correlates the client request, every server log line, the response\n * envelope, and any downstream span. Precedence:\n *\n * 1. `traceparent` (W3C Trace Context — `00-{32-hex}-{16-hex}-{flags}`)\n * 2. `x-request-id` (Heroku / GCP / generic proxy header)\n * 3. Generated UUID (fresh per request)\n *\n * UUIDs are accepted as trace identifiers by every major vendor that\n * does not enforce strict 32-hex (Datadog, Honeycomb, Sentry, Logflare,\n * Axiom, etc). We don't need ULIDs to ship this surface.\n */\n\nexport const TRACE_HEADER = 'x-trace-id'\nexport const TRACE_PARENT_HEADER = 'traceparent'\nconst REQUEST_ID_HEADER = 'x-request-id'\n\n// W3C Trace Context: 00-<trace-id 32 hex>-<span-id 16 hex>-<flags 2 hex>\nconst TRACEPARENT_RE = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/\n\n/**\n * Parse a W3C Trace Context `traceparent` header value. Returns the\n * 32-hex trace-id when valid (and not the reserved all-zeros), else\n * `null`.\n */\nexport function parseTraceparent(value: string): string | null {\n if (!value) return null\n const m = TRACEPARENT_RE.exec(value)\n if (!m) return null\n const traceId = m[1]\n // W3C: trace-id of all zeroes is invalid by spec\n if (/^0+$/.test(traceId)) return null\n return traceId\n}\n\n/**\n * Pick the first string value out of an IncomingMessage header. Node\n * collapses repeated headers into arrays; proxies sometimes do this for\n * `x-request-id`. Empty strings count as absent.\n */\nfunction pickHeader(value: string | string[] | undefined): string | null {\n if (Array.isArray(value)) {\n for (const v of value) {\n if (typeof v === 'string' && v.length > 0) return v\n }\n return null\n }\n if (typeof value === 'string' && value.length > 0) return value\n return null\n}\n\n/**\n * T5a.2 Phase C slice 1/2 — pure traceId resolution from pre-extracted\n * header values. Shared between IncomingMessage and Web Request wrappers.\n */\nfunction resolveTraceIdFromHeaders(traceparent: string | null, requestId: string | null): string {\n if (traceparent !== null) {\n const parsed = parseTraceparent(traceparent)\n if (parsed !== null) return parsed\n }\n if (requestId !== null) return requestId\n return globalThis.crypto.randomUUID()\n}\n\n/**\n * Resolve the request's traceId following the precedence above.\n */\nexport function extractTraceId(req: IncomingMessage): string {\n return resolveTraceIdFromHeaders(\n pickHeader(req.headers[TRACE_PARENT_HEADER]),\n pickHeader(req.headers[REQUEST_ID_HEADER]),\n )\n}\n\n/**\n * T5a.2 Phase C slice 1/2 — Web-Standards-shaped traceId resolver.\n *\n * Mirror of `extractTraceId(req: IncomingMessage)` for the Web `Request`\n * shape. Same precedence (`traceparent` → `x-request-id` → generated\n * UUID). Uses `request.headers.get(name)` (native Web `Headers` API)\n * instead of the Node indexer.\n *\n * **Multi-value note:** Web `Headers` collapses repeated headers into a\n * single comma-separated string at parse. The IncomingMessage path's\n * `pickHeader` \"first non-empty value\" semantic is naturally satisfied\n * because there's no array to pick from on the Web side — `.get()`\n * returns the comma-joined value, which for `traceparent` / `x-request-id`\n * is treated as a single string anyway (both headers are conventionally\n * single-valued).\n */\nexport function extractTraceIdFromRequest(request: Request): string {\n return resolveTraceIdFromHeaders(\n request.headers.get(TRACE_PARENT_HEADER),\n request.headers.get(REQUEST_ID_HEADER),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0CA,IAAM,iBAAkD;AAAA,EACtD,kBAAkB;AAAA,EAClB,aAAa;AAAA,EACb,cAAc;AAAA,EACd,WAAW;AAAA,EACX,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,wBAAwB;AAAA,EACxB,mBAAmB;AAAA,EACnB,uBAAuB;AACzB;AAEA,IAAM,iBAAkD;AAAA,EACtD,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AA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AAiB;AAAA,EACvC;AACF;","names":["ctx","body","z"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/auth/crypto.ts","../src/server/auth/session.ts","../src/server/_internal/encoding.ts","../src/server/auth/auth-totp.ts","../src/server/auth/auth-backup-codes.ts","../src/server/auth/auth-throttle.ts","../src/server/auth/oauth-pkce.ts","../src/server/auth/oauth-state.ts","../src/server/auth/oidc-discovery.ts"],"sourcesContent":["// AES-GCM-256 token encryption with cached key derivation.\n//\n// CR-002 fixes:\n// - KDF: HKDF (RFC 5869) over the raw secret, not raw SHA-256.\n// HKDF binds the application context (\"theo-session-v1\") into the\n// derived key so the same secret used elsewhere cannot decrypt these\n// tokens. SHA-256 of the raw secret has neither domain separation nor\n// proper key-stretching guarantees.\n// - Cache: derived `CryptoKey` is memoized per (secret, info) tuple.\n// Pre-fix, every encrypt/decrypt re-ran SHA-256 + importKey, which (a)\n// burned CPU on every authenticated request and (b) made\n// `decryptWithFallback` leak rotation-array position via timing.\n// - Buffer typing: `Uint8Array` flows directly into Web Crypto\n// (`BufferSource`-compatible). The previous `as unknown as ArrayBuffer`\n// double-cast (CR-016) is removed.\n\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\n\nconst HKDF_INFO_DEFAULT = encoder.encode('theo-session-v1')\nconst HKDF_SALT_EMPTY = new Uint8Array(0)\n\n// Memoize derived keys. Bounded by the number of distinct secrets the app\n// ever uses (typically 1 in steady state, 2-5 during rotation). Map-based\n// so distinct secrets do not evict each other.\nconst keyCache = new Map<string, Promise<CryptoKey>>()\n\nasync function deriveKey(secret: string): Promise<CryptoKey> {\n const cached = keyCache.get(secret)\n if (cached) return cached\n\n const derive = (async () => {\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HKDF' },\n false,\n ['deriveKey'],\n )\n return crypto.subtle.deriveKey(\n { name: 'HKDF', hash: 'SHA-256', salt: HKDF_SALT_EMPTY, info: HKDF_INFO_DEFAULT },\n keyMaterial,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt'],\n )\n })()\n\n keyCache.set(secret, derive)\n // If derivation fails (invalid secret), evict so a retry can try fresh.\n derive.catch(() => {\n keyCache.delete(secret)\n })\n return derive\n}\n\nfunction toBase64Url(data: Uint8Array): string {\n return Buffer.from(data).toString('base64url')\n}\n\n/**\n * Decode a base64url string into a `Uint8Array<ArrayBuffer>`. The explicit\n * generic matters: Web Crypto APIs expect `BufferSource`, and TS 5.7+\n * tightened `Uint8Array` to `Uint8Array<ArrayBufferLike>` which includes\n * `SharedArrayBuffer`. Returning the narrower generic lets the value pass\n * `crypto.subtle.decrypt` without `as` casts (CR-016 follow-through).\n */\nfunction fromBase64Url(str: string): Uint8Array<ArrayBuffer> {\n const buf = Buffer.from(str, 'base64url')\n const copy = new Uint8Array(buf.length)\n copy.set(buf)\n return copy\n}\n\n// The `T` generic exists so call sites get type-safe round-tripping\n// (`encrypt<Session>(s, ...)` pairs with `decrypt<Session>(...)`); the\n// runtime body just stringifies `data`, hence T does not appear in the\n// signature beyond the argument.\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T documents the round-trip contract with decrypt<T>\nexport async function encrypt<T>(data: T, secret: string): Promise<string> {\n const key = await deriveKey(secret)\n const iv = crypto.getRandomValues(new Uint8Array(12))\n const plaintext = encoder.encode(JSON.stringify(data))\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext),\n )\n return `${toBase64Url(iv)}:${toBase64Url(ciphertext)}`\n}\n\nexport async function decrypt<T>(token: string, secret: string): Promise<T | null> {\n try {\n const parts = token.split(':')\n if (parts.length !== 2) return null\n\n const iv = fromBase64Url(parts[0])\n const ciphertext = fromBase64Url(parts[1])\n const key = await deriveKey(secret)\n\n const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext)\n return JSON.parse(decoder.decode(plaintext)) as T\n } catch {\n return null\n }\n}\n\n/**\n * Reset the derived-key cache. Test helper — never call from production code.\n * Used by Vitest to guarantee isolation between tests that use distinct\n * secrets and want to confirm the derivation path runs.\n */\nexport function _resetKeyCacheForTests(): void {\n keyCache.clear()\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport {\n getCookie,\n setCookie,\n deleteCookie,\n getCookieFromRequest,\n appendCookieToHeaders,\n appendDeleteCookieToHeaders,\n} from '../http/cookies.js'\n\nimport { encrypt, decrypt } from './crypto.js'\n\nexport interface SessionConfig {\n /**\n * Session secret. Either a single string (legacy) or an array of strings\n * where index 0 is the newest. The array form enables dual-key rotation\n * (T3.1 / ADR D5): encrypt always uses `secrets[0]`, decrypt walks the\n * array, transparent re-encrypt on legacy hits (T3.2).\n *\n * EC-1: array length capped at 5 — enforced via throw at construction.\n */\n secret: string | string[]\n cookieName?: string\n maxAge?: number\n}\n\ninterface SessionEnvelope<T> {\n data: T\n exp: number\n}\n\nexport interface SessionMeta {\n /** Index of the secret that decrypted the session. 0 = newest; > 0 = legacy. */\n secretIndex: number\n /** True when the decrypt used a legacy secret and the cookie should be re-encrypted. */\n needsReencrypt: boolean\n}\n\nexport interface SessionManager<TSession> {\n getSession(req: IncomingMessage): Promise<TSession | null>\n /**\n * T3.2 — Variant of `getSession` that surfaces decrypt metadata.\n * Used by `api-middleware.ts` to wire transparent re-encrypt BEFORE\n * the handler runs (so streaming SSR routes don't miss the Set-Cookie\n * window — EC-4).\n */\n getSessionWithMeta(req: IncomingMessage): Promise<{ data: TSession | null; meta: SessionMeta }>\n createSession(res: ServerResponse, data: TSession): Promise<void>\n destroySession(res: ServerResponse): void\n /**\n * T3.3 — OWASP A07:2021 session fixation mitigation. Re-encrypts the\n * current session with a fresh IV and refreshed expiry. No-op when no\n * session is present.\n */\n rotateSession(req: IncomingMessage, res: ServerResponse): Promise<TSession | null>\n}\n\n/**\n * EC-1 — array length cap. Enforced via throw at construction. Silent\n * truncation would create false sense of rotation; silent acceptance\n * would create unbounded CPU on legacy decrypt walks.\n */\nconst MAX_SECRETS = 5\n\n/**\n * Validate + normalize the secret config into a non-empty array of\n * strings ≥ 32 chars each.\n */\nfunction normalizeSecrets(input: string | string[]): string[] {\n const arr = Array.isArray(input) ? input.slice() : [input]\n if (arr.length === 0) {\n throw new Error('Session secret must be non-empty (received an empty array)')\n }\n if (arr.length > MAX_SECRETS) {\n throw new Error(\n `Session secret array exceeds maximum of ${MAX_SECRETS} entries — drop the oldest before adding a new one (received ${arr.length})`,\n )\n }\n const wasArray = Array.isArray(input)\n for (let i = 0; i < arr.length; i++) {\n const s = arr[i]\n if (typeof s !== 'string' || s.length < 32) {\n const where = wasArray ? ` at index ${i}` : ''\n throw new Error(`Session secret${where} must be at least 32 characters for secure encryption`)\n }\n }\n return arr\n}\n\n/**\n * T5a.2 Phase D slice 3/3 — module-level pure helpers extracted so\n * `createSessionManager` (IncomingMessage path) and\n * `createSessionManagerWeb` (Web path) share the same encryption +\n * dual-key rotation logic without code duplication (sonarjs\n * no-identical-functions). Both wrappers pass `secrets` + `maxAge`\n * captured from their respective factory scope.\n */\nasync function encryptSessionEnvelope(\n data: unknown,\n secrets: string[],\n maxAge: number,\n): Promise<string> {\n const envelope: SessionEnvelope<unknown> = {\n data,\n exp: Date.now() + maxAge * 1000,\n }\n return encrypt(envelope, secrets[0]) // newest\n}\n\n/**\n * CR-002 constant-time: try EVERY rotation entry in parallel, then pick\n * the newest match. Sequential early-exit leaked rotation position via\n * timing (success on entry 0 returned in ~3 ms; success on entry 4 in\n * ~15 ms). Running in parallel binds wall-clock to the slowest single\n * attempt, independent of which entry actually matched. With derived-key\n * cache (CR-002 in crypto.ts), the CPU multiplier per request is ~0\n * after the first request per secret.\n */\nasync function decryptSessionWithFallback<TSession>(\n raw: string,\n secrets: string[],\n): Promise<{ envelope: SessionEnvelope<TSession>; index: number } | null> {\n const results = await Promise.all(\n secrets.map(async (secret, i) => {\n const env = await decrypt<SessionEnvelope<TSession>>(raw, secret)\n return env ? { envelope: env, index: i } : null\n }),\n )\n for (const result of results) {\n if (result) return result\n }\n return null\n}\n\nexport function createSessionManager<TSession>(config: SessionConfig): SessionManager<TSession> {\n const secrets = normalizeSecrets(config.secret)\n const cookieName = config.cookieName ?? 'theo_session'\n const maxAge = config.maxAge ?? 604800 // 7 days\n\n function writeCookie(res: ServerResponse, token: string): void {\n setCookie(res, cookieName, token, {\n httpOnly: true,\n sameSite: 'lax',\n maxAge,\n path: '/',\n })\n }\n\n return {\n async getSession(req) {\n const { data } = await this.getSessionWithMeta(req)\n return data\n },\n\n async getSessionWithMeta(req) {\n const raw = getCookie(req, cookieName)\n if (!raw) return { data: null, meta: { secretIndex: -1, needsReencrypt: false } }\n const decoded = await decryptSessionWithFallback<TSession>(raw, secrets)\n if (!decoded) return { data: null, meta: { secretIndex: -1, needsReencrypt: false } }\n if (decoded.envelope.exp < Date.now()) {\n return { data: null, meta: { secretIndex: decoded.index, needsReencrypt: false } }\n }\n return {\n data: decoded.envelope.data,\n meta: { secretIndex: decoded.index, needsReencrypt: decoded.index > 0 },\n }\n },\n\n async createSession(res, data) {\n const token = await encryptSessionEnvelope(data, secrets, maxAge)\n writeCookie(res, token)\n },\n\n destroySession(res) {\n deleteCookie(res, cookieName)\n },\n\n async rotateSession(req, res) {\n const { data } = await this.getSessionWithMeta(req)\n if (data === null) return null\n // Fresh IV per encrypt call (Web Crypto guarantee — see crypto.ts)\n // + refreshed expiry. Last write wins for the cookie value.\n const token = await encryptSessionEnvelope(data, secrets, maxAge)\n writeCookie(res, token)\n return data\n },\n }\n}\n\n/**\n * T5a.2 Phase D slice 3/3 — Web-Standards session manager.\n *\n * Mirror of `SessionManager<TSession>` for the Web `Request` + `Headers`\n * shape. Same `SessionConfig`, same encryption (`encrypt`/`decrypt` from\n * `./crypto.js`), same dual-key rotation logic (CR-002 constant-time\n * decrypt fallback walk + transparent re-encrypt), same OWASP A07\n * `rotateSession` invariant.\n *\n * **Signature differences vs `SessionManager`:**\n * - Read methods take `Request` (instead of `IncomingMessage`).\n * - Write methods take a `Headers` instance to mutate (instead of\n * `ServerResponse`) — caller passes the headers they're building\n * for their `Response` constructor.\n *\n * Uses `getCookieFromRequest` / `appendCookieToHeaders` /\n * `appendDeleteCookieToHeaders` from Phase B slice 6/6.\n */\nexport interface SessionManagerWeb<TSession> {\n getSession(request: Request): Promise<TSession | null>\n getSessionWithMeta(request: Request): Promise<{ data: TSession | null; meta: SessionMeta }>\n createSession(target: Headers, data: TSession): Promise<void>\n destroySession(target: Headers): void\n rotateSession(request: Request, target: Headers): Promise<TSession | null>\n}\n\nexport function createSessionManagerWeb<TSession>(\n config: SessionConfig,\n): SessionManagerWeb<TSession> {\n const secrets = normalizeSecrets(config.secret)\n const cookieName = config.cookieName ?? 'theo_session'\n const maxAge = config.maxAge ?? 604800 // 7 days\n\n function writeCookieWeb(target: Headers, token: string): void {\n appendCookieToHeaders(target, cookieName, token, {\n httpOnly: true,\n sameSite: 'lax',\n maxAge,\n path: '/',\n })\n }\n\n return {\n async getSession(request) {\n const { data } = await this.getSessionWithMeta(request)\n return data\n },\n\n async getSessionWithMeta(request) {\n const raw = getCookieFromRequest(request, cookieName)\n if (raw === undefined) return { data: null, meta: { secretIndex: -1, needsReencrypt: false } }\n const decoded = await decryptSessionWithFallback<TSession>(raw, secrets)\n if (!decoded) return { data: null, meta: { secretIndex: -1, needsReencrypt: false } }\n if (decoded.envelope.exp < Date.now()) {\n return { data: null, meta: { secretIndex: decoded.index, needsReencrypt: false } }\n }\n return {\n data: decoded.envelope.data,\n meta: { secretIndex: decoded.index, needsReencrypt: decoded.index > 0 },\n }\n },\n\n async createSession(target, data) {\n const token = await encryptSessionEnvelope(data, secrets, maxAge)\n writeCookieWeb(target, token)\n },\n\n destroySession(target) {\n appendDeleteCookieToHeaders(target, cookieName)\n },\n\n async rotateSession(request, target) {\n const { data } = await this.getSessionWithMeta(request)\n if (data === null) return null\n const token = await encryptSessionEnvelope(data, secrets, maxAge)\n writeCookieWeb(target, token)\n return data\n },\n }\n}\n\n/**\n * T5a.2 Phase D slice 3/3 — Web-Standards transparent re-encrypt helper.\n *\n * Mirror of `rotateIfNeeded(sm, req, res)` for the Web Request + Headers\n * shape. Reads session via `getSessionWithMeta`; if the cookie was\n * decrypted with a legacy secret (index > 0), re-issues the cookie with\n * the newest secret via `createSession(target, data)`.\n *\n * **EC-4 honest framing:** unlike the IncomingMessage path where the\n * timing constraint is \"before `res.writeHead` fires\", the Web Request\n * path's constraint is \"before the `Response` object is constructed and\n * returned to the runtime\". Caller MUST invoke `rotateIfNeededWeb`\n * BEFORE building the final `Response(body, { headers: target })` so the\n * re-encrypted Set-Cookie lands on the wire.\n */\nexport async function rotateIfNeededWeb<TSession>(\n sm: SessionManagerWeb<TSession>,\n request: Request,\n target: Headers,\n): Promise<TSession | null> {\n const { data, meta } = await sm.getSessionWithMeta(request)\n if (data !== null && meta.needsReencrypt) {\n await sm.createSession(target, data)\n }\n return data\n}\n\n/**\n * T3.2 — Transparent re-encrypt helper (EC-4 timing-safe wrapper).\n *\n * Call this in your `createContext` (before any rendering / streaming\n * starts). It:\n * 1. Reads the session via `getSessionWithMeta`.\n * 2. If the cookie was decrypted with a legacy secret (index > 0), it\n * immediately re-issues the cookie with `secrets[0]` so the next\n * request lands on the newest key.\n * 3. Returns the session data (or null) for use downstream.\n *\n * EC-4: this MUST run before `renderToPipeableStream` / `res.writeHead`\n * fires. Calling it inside an SSR component or handler body that has\n * already streamed bytes makes the re-encrypt a silent no-op (Set-Cookie\n * is locked once headers commit), trapping users on the legacy secret\n * forever once it's removed from the array.\n */\nexport async function rotateIfNeeded<TSession>(\n sm: SessionManager<TSession>,\n req: IncomingMessage,\n res: ServerResponse,\n): Promise<TSession | null> {\n const { data, meta } = await sm.getSessionWithMeta(req)\n if (data !== null && meta.needsReencrypt) {\n await sm.createSession(res, data)\n }\n return data\n}\n\n/**\n * EC-2 — Production secret guard. Refuses to boot when `NODE_ENV === 'production'`\n * AND the secret is too short (< 32 chars) OR matches a known placeholder.\n *\n * Accepts a single secret OR an array. In array form, each entry is validated\n * independently — a single bad entry refuses boot with an index-qualified message.\n */\nconst PLACEHOLDER_PATTERN = /CHANGE_ME|demo[-_]|placeholder/i\n\nexport function assertProductionSecret(secret: string | string[]): void {\n const arr = Array.isArray(secret) ? secret : [secret]\n const isProd = process.env.NODE_ENV === 'production'\n\n for (let i = 0; i < arr.length; i++) {\n const s = arr[i]\n const isPlaceholder = PLACEHOLDER_PATTERN.test(s)\n const isTooShort = s.length < 32\n const prefix = arr.length > 1 ? `Session secret at index ${i}` : 'Session secret'\n\n if (isProd) {\n if (isTooShort) {\n throw new Error(\n `${prefix} too short for production (${s.length} chars; minimum 32). ` +\n `Set a 32+ random char secret in your env (e.g., \\`openssl rand -hex 32\\`).`,\n )\n }\n if (isPlaceholder) {\n throw new Error(\n `${prefix} looks like a placeholder (\"${s.slice(0, 16)}…\") and NODE_ENV is \"production\". ` +\n `Replace it with a 32+ random char secret (e.g., \\`openssl rand -hex 32\\`) before deploying.`,\n )\n }\n continue\n }\n if (isPlaceholder || isTooShort) {\n console.warn(\n `[theokit] WARNING: ${prefix.toLowerCase()} is a placeholder or too short. ` +\n `This is OK for dev, but the production server will REFUSE to boot until you replace it.`,\n )\n }\n }\n}\n","/**\n * Shared encoding utilities for crypto-adjacent code.\n *\n * CR-020 DRY: `base64urlEncode` was duplicated across `oauth-pkce.ts` and\n * `oauth-state.ts`. Duplication in cryptographic helpers is a bug class —\n * a future RFC-driven tweak (e.g., padding semantics) would diverge across\n * files. Centralizing the single canonical implementation eliminates that\n * vector.\n *\n * Module is intentionally under `_internal/` so it is **not** part of the\n * public API surface. Consumers outside `packages/theo/src/server` must\n * not import from here.\n */\n\n/**\n * RFC 4648 §5 — base64url-encode bytes without padding. Used wherever an\n * RFC requires URL-safe base64 (PKCE per RFC 7636 §4.1, JWT per RFC 7515,\n * etc.). Pure function — does not mutate `bytes`.\n */\nexport function base64urlEncode(bytes: Uint8Array): string {\n let s = ''\n for (const b of bytes) s += String.fromCharCode(b)\n // The `=+$` trailing-padding regex is bounded (at most 2 chars for\n // base64). sonarjs flags the `+` quantifier conservatively, but the\n // input is the output of `btoa()` — a string with at most 2 trailing\n // `=` characters by spec.\n // eslint-disable-next-line sonarjs/slow-regex -- bounded trailing-padding pattern (max 2 chars)\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Constant-time string equality.\n *\n * CR-012: prior implementations early-exited on length mismatch\n * (`if (a.length !== b.length) return false`). That early exit leaks\n * the comparison-target length via wall-clock timing — observable when\n * the secret length is itself sensitive (length-based bucket assignment,\n * variable-length nonces). This implementation always iterates\n * `max(a.length, b.length)` characters, OR-folding mismatches into a\n * single accumulator that is checked once at the end.\n *\n * Returns `false` for empty inputs as a defensive default — never accept\n * \"both empty\" as a match.\n */\nexport function constantTimeEquals(a: string, b: string): boolean {\n if (typeof a !== 'string' || typeof b !== 'string') return false\n if (a.length === 0 || b.length === 0) return false\n\n const maxLen = Math.max(a.length, b.length)\n let diff = a.length ^ b.length\n for (let i = 0; i < maxLen; i++) {\n // charCodeAt returns NaN for out-of-range indices; (NaN ^ x) is x, so we\n // explicitly substitute 0 to keep the OR-fold meaningful.\n const ca = i < a.length ? a.charCodeAt(i) : 0\n const cb = i < b.length ? b.charCodeAt(i) : 0\n diff |= ca ^ cb\n }\n return diff === 0\n}\n","/**\n * T6.2 — RFC 6238 TOTP primitive.\n *\n * Reference: https://datatracker.ietf.org/doc/html/rfc6238\n * HMAC-based one-time password (HOTP) base: https://datatracker.ietf.org/doc/html/rfc4226\n *\n * Pure-function, dependency-free implementation via Web Crypto. Secrets\n * may be passed as Uint8Array (preferred) or base32 string.\n *\n * SECURITY NOTES (documented per EC-13):\n * - TOTP secrets are equivalent to passwords. Encrypt at rest using a\n * separate KMS key from the session secret. If your DB leaks, ALL\n * 2FA codes are compromised — rotate by forcing all users to re-enroll.\n * - Use `verifyTotp` constant-time (we use crypto.timingSafeEqual internally).\n */\n\n// CR-012 fix: use the shared constant-time helper that does not early-exit\n// on length mismatch (the previous local version did, leaking the digit\n// count via timing).\nimport { constantTimeEquals } from '../_internal/encoding.js'\n\n/** Supported HMAC algorithms per RFC 6238 §1.2. Default SHA-1. */\nexport type TotpAlgorithm = 'SHA-1' | 'SHA-256' | 'SHA-512'\n\nexport interface TotpOptions {\n /** Shared secret — bytes (preferred) OR base32 string. */\n secret: Uint8Array | string\n /** Time step in seconds. Default 30 (RFC 6238 §5.2 recommended). */\n step?: number\n /** Code length: 6, 7, or 8 digits. Default 6. */\n digits?: 6 | 7 | 8\n /** HMAC algorithm. Default SHA-1 (RFC default). */\n algorithm?: TotpAlgorithm\n /** Time in ms since epoch. Default Date.now(). */\n time?: number\n}\n\nexport interface VerifyTotpOptions extends TotpOptions {\n /**\n * Drift tolerance in number of steps on each side. Default 1\n * (RFC 6238 §5.2 recommends ±1 step = 90s total window).\n */\n window?: number\n}\n\nconst DEFAULT_STEP = 30\nconst DEFAULT_DIGITS = 6\nconst DEFAULT_ALGORITHM: TotpAlgorithm = 'SHA-1'\n\n/** Decode base32 (RFC 4648, no padding) to bytes. Throws on invalid input. */\nfunction base32Decode(s: string): Uint8Array {\n const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\n // Trailing `=` is bounded by spec to 0..6 chars; `\\s+` collapses runs\n // of whitespace. Input length is the user's TOTP secret (10..50 chars\n // typical), so super-linear backtracking cannot escalate.\n // eslint-disable-next-line sonarjs/slow-regex -- bounded inputs (TOTP secrets are short)\n const clean = s.toUpperCase().replace(/=+$/, '').replace(/\\s+/g, '')\n if (!/^[A-Z2-7]+$/.test(clean)) {\n throw new Error('Invalid base32 secret')\n }\n const bits: number[] = []\n for (const c of clean) {\n const idx = alphabet.indexOf(c)\n for (let i = 4; i >= 0; i--) bits.push((idx >> i) & 1)\n }\n // Trim trailing partial byte\n const fullBytes = Math.floor(bits.length / 8)\n const out = new Uint8Array(fullBytes)\n for (let i = 0; i < fullBytes; i++) {\n let v = 0\n for (let j = 0; j < 8; j++) v = (v << 1) | bits[i * 8 + j]\n out[i] = v\n }\n return out\n}\n\n/** Encode bytes to base32 (RFC 4648, no padding). */\nfunction base32Encode(bytes: Uint8Array): string {\n const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\n let out = ''\n let buffer = 0\n let bits = 0\n for (const b of bytes) {\n buffer = (buffer << 8) | b\n bits += 8\n while (bits >= 5) {\n out += alphabet[(buffer >> (bits - 5)) & 0x1f]\n bits -= 5\n }\n }\n if (bits > 0) out += alphabet[(buffer << (5 - bits)) & 0x1f]\n return out\n}\n\nfunction normalizeSecret(secret: Uint8Array | string): Uint8Array {\n if (typeof secret === 'string') return base32Decode(secret)\n return secret\n}\n\n/** Counter (8-byte big-endian) from time in ms / step in seconds. */\nfunction counterBytes(timeMs: number, stepSec: number): Uint8Array {\n const counter = Math.floor(timeMs / 1000 / stepSec)\n const out = new Uint8Array(8)\n // Two 32-bit halves (Number can safely represent up to 2^53; OK until year 285,000+)\n const hi = Math.floor(counter / 0x100000000)\n const lo = counter >>> 0\n out[0] = (hi >>> 24) & 0xff\n out[1] = (hi >>> 16) & 0xff\n out[2] = (hi >>> 8) & 0xff\n out[3] = hi & 0xff\n out[4] = (lo >>> 24) & 0xff\n out[5] = (lo >>> 16) & 0xff\n out[6] = (lo >>> 8) & 0xff\n out[7] = lo & 0xff\n return out\n}\n\nasync function hmac(\n secret: Uint8Array,\n message: Uint8Array,\n algorithm: TotpAlgorithm,\n): Promise<Uint8Array> {\n const key = await crypto.subtle.importKey(\n 'raw',\n secret as BufferSource,\n { name: 'HMAC', hash: algorithm },\n false,\n ['sign'],\n )\n const sig = await crypto.subtle.sign('HMAC', key, message as BufferSource)\n return new Uint8Array(sig)\n}\n\n/** RFC 4226 §5.3 dynamic truncation. */\nfunction truncate(mac: Uint8Array, digits: number): string {\n const offset = mac[mac.length - 1] & 0x0f\n const code =\n ((mac[offset] & 0x7f) << 24) |\n ((mac[offset + 1] & 0xff) << 16) |\n ((mac[offset + 2] & 0xff) << 8) |\n (mac[offset + 3] & 0xff)\n const mod = 10 ** digits\n return String(code % mod).padStart(digits, '0')\n}\n\n/** Generate a TOTP code for a given time. */\nexport async function generateTotp(opts: TotpOptions): Promise<string> {\n const secret = normalizeSecret(opts.secret)\n const step = opts.step ?? DEFAULT_STEP\n const digits = opts.digits ?? DEFAULT_DIGITS\n const algorithm = opts.algorithm ?? DEFAULT_ALGORITHM\n const time = opts.time ?? Date.now()\n const mac = await hmac(secret, counterBytes(time, step), algorithm)\n return truncate(mac, digits)\n}\n\n/**\n * Verify a TOTP code against the current window ± `window` steps.\n *\n * Returns `false` for malformed tokens (non-digit, wrong length) without\n * throwing — defensive against accidental user-input passthrough.\n */\nexport async function verifyTotp(token: string, opts: VerifyTotpOptions): Promise<boolean> {\n if (typeof token !== 'string') return false\n const digits = opts.digits ?? DEFAULT_DIGITS\n if (!/^\\d+$/.test(token) || token.length !== digits) return false\n\n const step = opts.step ?? DEFAULT_STEP\n const algorithm = opts.algorithm ?? DEFAULT_ALGORITHM\n const time = opts.time ?? Date.now()\n const drift = opts.window ?? 1\n const secret = normalizeSecret(opts.secret)\n\n // Walk the whole drift range constant-time-ish (no early exit).\n let matched = false\n for (let delta = -drift; delta <= drift; delta++) {\n const t = time + delta * step * 1000\n const code = truncate(await hmac(secret, counterBytes(t, step), algorithm), digits)\n if (constantTimeEquals(code, token)) matched = true\n }\n return matched\n}\n\n/** Generate a cryptographically random TOTP secret. Default 20 bytes (RFC minimum). */\nexport function generateTotpSecret(bytes = 20): Uint8Array {\n if (bytes < 16) {\n throw new Error('TOTP secret must be at least 16 bytes (RFC 6238 §3 minimum)')\n }\n const out = new Uint8Array(bytes)\n crypto.getRandomValues(out)\n return out\n}\n\n/**\n * Build an `otpauth://` URI for QR code enrollment. Format follows the\n * de facto Google Authenticator spec adopted by every major TOTP app.\n * otpauth://totp/<issuer>:<account>?secret=<base32>&issuer=<issuer>&algorithm=<alg>&digits=<n>&period=<sec>\n */\nexport interface TotpUriOptions {\n secret: Uint8Array\n issuer: string\n account: string\n algorithm?: TotpAlgorithm\n digits?: 6 | 7 | 8\n step?: number\n}\n\nexport function totpUri(opts: TotpUriOptions): string {\n const label = `${opts.issuer}:${opts.account}`\n const params = new URLSearchParams({\n secret: base32Encode(opts.secret),\n issuer: opts.issuer,\n algorithm: opts.algorithm ?? DEFAULT_ALGORITHM,\n digits: String(opts.digits ?? DEFAULT_DIGITS),\n period: String(opts.step ?? DEFAULT_STEP),\n })\n return `otpauth://totp/${encodeURIComponent(label)}?${params.toString()}`\n}\n","/**\n * T6.3 — Backup codes for 2FA recovery.\n *\n * generateBackupCodes returns N plaintexts (display once to user) + hashes\n * (store in DB). verifyBackupCode constant-time-walks all hashes and\n * returns the matchedHash so caller can delete the used code from storage\n * — replay protection lives at the caller (we can't see their database).\n *\n * SECURITY NOTES:\n * - Codes have ~40 bits entropy (8 chars × 5 bits per char from a\n * 32-char alphabet excluding I/L/O/0/1). Single-use → argon2id\n * overhead is unnecessary; SHA-256 of the normalized code suffices.\n * - The caller MUST atomically delete the matched hash on successful\n * verify. Without that, the code is replayable. We surface\n * matchedHash explicitly so this step is conspicuous.\n * - Pair this with throttleLoginAttempts (T6.1) on the verify endpoint\n * to prevent online brute-force against the 40-bit space.\n */\n\nexport interface BackupCodeOptions {\n /** How many codes to generate. Default 10. */\n count?: number\n /** Length in chars (excluding separator). Default 8. */\n length?: number\n /** Separator inserted at the midpoint. Default '-'; pass null to omit. */\n separator?: '-' | null\n /** Custom alphabet. Default excludes ambiguous chars (I, L, O, 0, 1). */\n alphabet?: string\n}\n\nexport interface BackupCode {\n plaintext: string\n hash: string\n}\n\nconst DEFAULT_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' // no I, O, 0, 1\nconst DEFAULT_COUNT = 10\nconst DEFAULT_LENGTH = 8\n\n/**\n * Generate cryptographically random backup codes + their SHA-256 hashes.\n *\n * Plaintext is uppercase alphanumeric (default alphabet excludes ambiguous\n * chars). Separator inserted at the midpoint (default `-`).\n */\nexport async function generateBackupCodes(opts: BackupCodeOptions = {}): Promise<BackupCode[]> {\n const count = opts.count ?? DEFAULT_COUNT\n const length = opts.length ?? DEFAULT_LENGTH\n const separator = opts.separator === undefined ? '-' : opts.separator\n const alphabet = opts.alphabet ?? DEFAULT_ALPHABET\n\n // CR-022 fix: bound count and length explicitly. Pathological inputs\n // (count=Infinity, length=0) would cause an infinite loop or wasteful\n // resource usage. Bounds are generous (count ≤ 1000, length ∈ [4, 64])\n // — well above any realistic 2FA backup-codes use case.\n if (!Number.isInteger(count) || count <= 0 || count > 1000) {\n throw new RangeError(\n `generateBackupCodes: count must be an integer in [1, 1000] (got ${String(count)})`,\n )\n }\n if (!Number.isInteger(length) || length < 4 || length > 64) {\n throw new RangeError(\n `generateBackupCodes: length must be an integer in [4, 64] (got ${String(length)})`,\n )\n }\n if (alphabet.length < 8) {\n throw new RangeError(\n `generateBackupCodes: alphabet must contain at least 8 distinct chars (got ${alphabet.length})`,\n )\n }\n\n const codes: BackupCode[] = []\n const seen = new Set<string>()\n while (codes.length < count) {\n const raw = randomFromAlphabet(length, alphabet)\n if (seen.has(raw)) continue\n seen.add(raw)\n const plaintext = formatWithSeparator(raw, separator)\n const hash = await sha256Hex(normalizeCode(plaintext))\n codes.push({ plaintext, hash })\n }\n return codes\n}\n\n/**\n * Verify a code against a list of stored hashes. Walks all hashes\n * constant-time (no early exit). Returns `valid:true` + matchedHash on\n * hit; `valid:false` otherwise.\n *\n * `matchedHash` is the EXACT string the caller stored, ready to be passed\n * to a `DELETE FROM backup_codes WHERE hash = ?` query.\n */\nexport async function verifyBackupCode(\n code: string,\n hashes: readonly string[],\n): Promise<{ valid: boolean; matchedHash?: string }> {\n const candidate = await sha256Hex(normalizeCode(code))\n let matchedHash: string | undefined\n // Constant-time iteration over hashes: never short-circuit.\n for (const h of hashes) {\n if (constantTimeEquals(h, candidate)) {\n matchedHash = h\n }\n }\n return matchedHash ? { valid: true, matchedHash } : { valid: false }\n}\n\n/**\n * Normalize a code for hashing: uppercase + strip separator. This way\n * `abcd-efgh` and `ABCDEFGH` produce the same hash. Whitespace is also\n * stripped defensively.\n */\nfunction normalizeCode(input: string): string {\n return input.toUpperCase().replace(/[-\\s]+/g, '')\n}\n\nfunction formatWithSeparator(raw: string, separator: '-' | null): string {\n if (!separator || raw.length < 4) return raw\n const mid = Math.floor(raw.length / 2)\n return raw.slice(0, mid) + separator + raw.slice(mid)\n}\n\nfunction randomFromAlphabet(length: number, alphabet: string): string {\n const random = new Uint8Array(length)\n crypto.getRandomValues(random)\n let out = ''\n for (let i = 0; i < length; i++) {\n out += alphabet[random[i] % alphabet.length]\n }\n return out\n}\n\nasync function sha256Hex(input: string): Promise<string> {\n const bytes = new TextEncoder().encode(input)\n const hash = await crypto.subtle.digest('SHA-256', bytes)\n return Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\nfunction constantTimeEquals(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n","import type { RateLimitStore } from '../rate-limit/rate-limit-store.js'\n\n/**\n * T6.1 — Login throttling primitive.\n *\n * Per-credential failure counter backed by any `RateLimitStore`. After\n * `maxAttempts` failures within `windowMs`, the identifier is locked\n * for `lockoutMs`. Successful login resets the counter.\n *\n * Usage in a login handler:\n *\n * const state = await checkThrottle({ store, identifier: hash(email) })\n * if (!state.allowed) return 429\n * const valid = await verifyPassword(creds)\n * await recordAttempt({ store, identifier: hash(email) }, valid)\n * if (!valid) return 401\n *\n * SECURITY:\n * - NEVER pass raw email/username as `identifier`. Hash or normalize\n * first (e.g. SHA-256 of the lowercased email). This prevents PII\n * from landing in the rate-limit store or audit logs.\n * - Combine with the per-route IP rate limit (T2.2) for layered defense:\n * IP-level limits stop scripted floods; credential-level limits stop\n * distributed brute force.\n */\n\nexport interface ThrottleOptions {\n store: RateLimitStore\n /**\n * Stable identifier per credential. Hash raw emails/usernames before\n * passing in — never leak PII to the rate-limit key space.\n */\n identifier: string\n /** Failures before lockout. Default 5. */\n maxAttempts?: number\n /** Sliding window for counting failures. Default 15 minutes. */\n windowMs?: number\n /** Lockout duration after maxAttempts hit. Default 1 hour. */\n lockoutMs?: number\n}\n\nexport interface ThrottleState {\n allowed: boolean\n remainingAttempts: number\n /** Set when `allowed === false`. Absolute timestamp when the lockout expires. */\n lockedUntil?: Date\n}\n\nconst DEFAULT_MAX_ATTEMPTS = 5\nconst DEFAULT_LOCKOUT_MS = 60 * 60_000\n\n/**\n * Read the current throttle state for an identifier WITHOUT modifying\n * the counter. Call before validating credentials so locked attempts\n * are rejected fast.\n */\nexport async function checkThrottle(opts: ThrottleOptions): Promise<ThrottleState> {\n const maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS\n const state = await opts.store.get(opts.identifier)\n if (!state) {\n return { allowed: true, remainingAttempts: maxAttempts }\n }\n if (state.count >= maxAttempts) {\n return {\n allowed: false,\n remainingAttempts: 0,\n // Lockout expires when the store TTL fires.\n lockedUntil: new Date(state.resetAt),\n }\n }\n return {\n allowed: true,\n remainingAttempts: Math.max(0, maxAttempts - state.count),\n }\n}\n\n/**\n * Record an attempt outcome. On success → reset the counter. On failure\n * → increment within the sliding window. Returns the new throttle state.\n *\n * Storage model: the store entry's TTL is `lockoutMs` (which doubles as\n * the failure-accumulation window). When `lockoutMs` is short — common\n * in tests or for soft lockouts — the entry auto-expires and the next\n * attempt starts fresh.\n */\nexport async function recordAttempt(\n opts: ThrottleOptions,\n success: boolean,\n): Promise<ThrottleState> {\n const maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS\n if (success) {\n await opts.store.reset(opts.identifier)\n return {\n allowed: true,\n remainingAttempts: maxAttempts,\n }\n }\n const lockoutMs = opts.lockoutMs ?? DEFAULT_LOCKOUT_MS\n const state = await opts.store.incr(opts.identifier, lockoutMs)\n\n if (state.count >= maxAttempts) {\n return {\n allowed: false,\n remainingAttempts: 0,\n lockedUntil: new Date(state.resetAt),\n }\n }\n return {\n allowed: true,\n remainingAttempts: Math.max(0, maxAttempts - state.count),\n }\n}\n","/**\n * T7.3 — RFC 7636 PKCE primitive.\n *\n * Reference: https://datatracker.ietf.org/doc/html/rfc7636\n *\n * Pure-function, dependency-free implementation using Web Crypto.\n *\n * Usage in an OAuth authorization-code flow:\n *\n * const { codeVerifier, codeChallenge, codeChallengeMethod } = await generatePkceChallenge()\n * // Store codeVerifier in the user's session\n * // Send codeChallenge + codeChallengeMethod in the /authorize redirect\n * // ... user authenticates with provider ...\n * // On /callback, send codeVerifier with the code → token exchange\n */\n\nexport interface PkceChallenge {\n codeVerifier: string\n codeChallenge: string\n codeChallengeMethod: 'S256'\n}\n\n// CR-020 DRY: single canonical base64url encoder lives in _internal/encoding.\nimport { base64urlEncode } from '../_internal/encoding.js'\n\n/**\n * Compute the code_challenge from a code_verifier per RFC 7636 §4.2.\n * Exported separately to enable RFC 7636 Appendix B vector testing.\n */\nexport async function pkceChallengeFromVerifier(verifier: string): Promise<string> {\n const bytes = new TextEncoder().encode(verifier)\n const hash = await crypto.subtle.digest('SHA-256', bytes)\n return base64urlEncode(new Uint8Array(hash))\n}\n\n/**\n * Generate a fresh PKCE challenge pair.\n *\n * Verifier: 32 cryptographically random bytes → 43-char base64url string.\n * RFC 7636 §4.1 allows 43–128 chars; we ship the minimum-safe default.\n *\n * Method: 'S256' only — no 'plain' fallback. RFC 7636 §7.2 strongly\n * discourages plain and modern providers reject it.\n */\nexport async function generatePkceChallenge(): Promise<PkceChallenge> {\n const random = new Uint8Array(32)\n crypto.getRandomValues(random)\n const codeVerifier = base64urlEncode(random)\n const codeChallenge = await pkceChallengeFromVerifier(codeVerifier)\n return { codeVerifier, codeChallenge, codeChallengeMethod: 'S256' }\n}\n","/**\n * T7.4 — OAuth `state` parameter helpers (RFC 6749 §10.12).\n *\n * `state` is a cryptographically random anti-CSRF token. The client\n * stores it (in session/cookie/db) before redirecting to the\n * authorization endpoint and verifies it on the callback. Without it,\n * an attacker can authorize on the user's account using a captured code.\n */\n\n// CR-020 DRY + CR-012 constant-time: shared helpers in _internal/encoding.\nimport { base64urlEncode, constantTimeEquals } from '../_internal/encoding.js'\n\n/**\n * Generate a cryptographically random state token. Default 32 bytes\n * (~43 base64url chars). Increase for higher entropy if your provider\n * supports it.\n */\nexport function generateOAuthState(opts: { bytes?: number } = {}): string {\n const len = opts.bytes ?? 32\n const buf = new Uint8Array(len)\n crypto.getRandomValues(buf)\n return base64urlEncode(buf)\n}\n\n/**\n * Verify a state token. Constant-time compare. Empty inputs always fail\n * (defensive — never accept empty as \"they match\").\n *\n * CR-012 fix: `constantTimeEquals` does not early-exit on length mismatch,\n * so the comparison time is independent of how the input was forged.\n */\nexport function verifyOAuthState(provided: string, stored: string): boolean {\n return constantTimeEquals(provided, stored)\n}\n","/**\n * T7.4 — OpenID Connect Discovery 1.0 metadata fetcher.\n *\n * Reference: https://openid.net/specs/openid-connect-discovery-1_0.html\n *\n * Caches metadata in module scope. Cache key is the exact issuer string\n * (trailing-slash sensitive per RFC 8414 §3). Failures are NOT cached —\n * subsequent calls retry the fetch.\n *\n * EC-7 — HTTPS enforced. RFC 8414 §3 requires HTTPS for OIDC issuers.\n * Localhost (loopback) is allowed for development.\n */\n\nexport interface OidcMetadata {\n issuer: string\n authorization_endpoint: string\n token_endpoint: string\n jwks_uri?: string\n userinfo_endpoint?: string\n end_session_endpoint?: string\n scopes_supported?: string[]\n response_types_supported?: string[]\n grant_types_supported?: string[]\n id_token_signing_alg_values_supported?: string[]\n [key: string]: unknown // OIDC providers ship many optional fields\n}\n\nconst cache = new Map<string, Promise<OidcMetadata>>()\n\n/** Clear the discovery cache. Used by tests. */\nexport function clearOidcCache(): void {\n cache.clear()\n}\n\nfunction isLoopback(host: string): boolean {\n return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host === '::1'\n}\n\n/**\n * Fetch (or return cached) OIDC provider metadata.\n *\n * Throws when:\n * - Issuer URL is malformed\n * - Issuer is HTTP and not a loopback host (EC-7)\n * - HTTP response is non-OK\n * - Metadata lacks `authorization_endpoint` (sanity check)\n */\nexport async function discoverOidcProvider(issuer: string | URL): Promise<OidcMetadata> {\n const issuerStr = typeof issuer === 'string' ? issuer : issuer.toString()\n // Validate protocol BEFORE checking cache — invalid issuers should never poison.\n const url = new URL(issuerStr)\n if (url.protocol !== 'https:' && !isLoopback(url.hostname)) {\n throw new Error(\n `OIDC issuer must use HTTPS (received \"${url.protocol}//${url.hostname}…\"). ` +\n `RFC 8414 §3 forbids plain HTTP except for loopback hosts.`,\n )\n }\n\n const cached = cache.get(issuerStr)\n if (cached) return cached\n\n const promise = (async () => {\n const wellKnown = new URL(\n '.well-known/openid-configuration',\n issuerStr.endsWith('/') ? issuerStr : issuerStr + '/',\n )\n const res = await fetch(wellKnown)\n if (!res.ok) {\n throw new Error(`OIDC discovery failed: ${res.status} ${res.statusText} at ${wellKnown}`)\n }\n const metadata = (await res.json()) as OidcMetadata\n if (!metadata.authorization_endpoint) {\n throw new Error('OIDC metadata missing authorization_endpoint — provider response is invalid')\n }\n return metadata\n })()\n // Cache the promise; on rejection, remove so the next call retries.\n cache.set(issuerStr, promise)\n promise.catch(() => {\n if (cache.get(issuerStr) === promise) cache.delete(issuerStr)\n })\n return promise\n}\n"],"mappings":";;;;;;;;;;AAgBA,IAAM,UAAU,IAAI,YAAY;AAChC,IAAM,UAAU,IAAI,YAAY;AAEhC,IAAM,oBAAoB,QAAQ,OAAO,iBAAiB;AAC1D,IAAM,kBAAkB,IAAI,WAAW,CAAC;AAKxC,IAAM,WAAW,oBAAI,IAAgC;AAErD,eAAe,UAAU,QAAoC;AAC3D,QAAM,SAAS,SAAS,IAAI,MAAM;AAClC,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU,YAAY;AAC1B,UAAM,cAAc,MAAM,OAAO,OAAO;AAAA,MACtC;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