overmux 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/auth/.vite/manifest.json +2 -2
  3. package/dist/auth/assets/{index-Bx8JhwVi.css → index-BM9gETvx.css} +1 -1
  4. package/dist/auth/assets/{index-CHIE7qYj.js → index-DabAfcs1.js} +1 -1
  5. package/dist/auth/index.html +2 -2
  6. package/dist/bin.js +430 -18
  7. package/dist/bin.js.map +1 -1
  8. package/dist/docs/200-getting-started/100-install-and-run-overmux.md +1 -2
  9. package/dist/docs/300-fundamentals/100-project-structure.md +20 -0
  10. package/dist/docs/300-fundamentals/300-theming.md +51 -0
  11. package/dist/docs/400-reference/100-configuration.md +20 -0
  12. package/dist/docs/400-reference/200-server-api.md +18 -0
  13. package/dist/docs/400-reference/300-client-api.md +36 -0
  14. package/dist/docs/400-reference/400-cli/050-init.md +17 -0
  15. package/dist/docs/400-reference/400-cli/350-instance.md +24 -0
  16. package/dist/exports/client.d.ts +33 -3
  17. package/dist/exports/client.d.ts.map +1 -1
  18. package/dist/exports/client.js +123 -14
  19. package/dist/exports/client.js.map +1 -1
  20. package/dist/exports/{index-D3_Dpy_T.d.ts → index-DS70rKzo.d.ts} +14 -2
  21. package/dist/exports/index-DS70rKzo.d.ts.map +1 -0
  22. package/dist/exports/index.d.ts +2 -2
  23. package/dist/exports/index.js +1 -1
  24. package/dist/exports/index.js.map +1 -1
  25. package/dist/exports/{notifications-kDp16bU_.js → notifications-av0FK0yZ.js} +7 -2
  26. package/dist/exports/{notifications-kDp16bU_.js.map → notifications-av0FK0yZ.js.map} +1 -1
  27. package/dist/exports/server.d.ts.map +1 -1
  28. package/dist/exports/server.js +52 -10
  29. package/dist/exports/server.js.map +1 -1
  30. package/dist/internal/server/coordinator/server-child.js +110 -46
  31. package/dist/internal/server/coordinator/server-child.js.map +1 -1
  32. package/docs/200-getting-started/100-install-and-run-overmux.md +1 -2
  33. package/docs/300-fundamentals/100-project-structure.md +20 -0
  34. package/docs/300-fundamentals/300-theming.md +51 -0
  35. package/docs/400-reference/100-configuration.md +20 -0
  36. package/docs/400-reference/200-server-api.md +18 -0
  37. package/docs/400-reference/300-client-api.md +36 -0
  38. package/docs/400-reference/400-cli/050-init.md +17 -0
  39. package/docs/400-reference/400-cli/350-instance.md +24 -0
  40. package/package.json +2 -2
  41. package/src/internal/cli/app.ts +7 -1
  42. package/src/internal/cli/commands/init-template.ts +146 -0
  43. package/src/internal/cli/commands/init.ts +267 -0
  44. package/src/internal/cli/commands/instance.ts +58 -0
  45. package/src/internal/cli/commands/integration.ts +15 -0
  46. package/src/internal/cli/commands/zellij-install.ts +96 -0
  47. package/src/internal/cli/parse-port.ts +2 -1
  48. package/src/internal/client/auth/auth-shell.css +17 -1
  49. package/src/internal/client/auth/auth-shell.tsx +2 -11
  50. package/src/internal/client/auth/login-code-input.tsx +140 -0
  51. package/src/internal/client/browser-api.ts +17 -3
  52. package/src/internal/client/clipboard.ts +22 -0
  53. package/src/internal/client/host/desktop-host.ts +15 -0
  54. package/src/internal/client/host/environment.ts +67 -0
  55. package/src/internal/client/host/instance-forwarding.ts +21 -0
  56. package/src/internal/client/host/notification-forwarding.ts +1 -10
  57. package/src/internal/client/host/overmux-host.tsx +8 -0
  58. package/src/internal/client/overmux-react.ts +24 -2
  59. package/src/internal/client/websocket.ts +48 -20
  60. package/src/internal/server/auth/instance-control.ts +24 -3
  61. package/src/internal/server/runtime/create-runtime.ts +12 -1
  62. package/src/internal/server/runtime/runtime-instance.ts +46 -0
  63. package/src/internal/server/runtime/runtime-resources.ts +3 -0
  64. package/src/internal/server/server-startup-options.ts +9 -4
  65. package/src/internal/server/start-application-server.ts +20 -12
  66. package/src/internal/server/websocket-server.ts +7 -0
  67. package/src/internal/shared/index.ts +2 -0
  68. package/src/internal/shared/protocol.ts +10 -1
  69. package/src/public/client.ts +5 -0
  70. package/src/public/config.ts +7 -0
  71. package/src/public/index.ts +2 -0
  72. package/dist/exports/index-D3_Dpy_T.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"server-child.js","names":["durationPattern","millisecondsByUnit","durationToMilliseconds","isLoopbackHostname","loginGrantSchema","parseCookie","errorDetails","errorDetails","send","diagnosticErrorDetails","diagnosticErrorDetails","diagnosticErrorDetails","errorDetails","errorDetails","errorDetails"],"sources":["../../../../../shared/dist/node/index.js","../../../../../lib/dist/index.js","../../../../src/internal/server/notifications/private-json-file.ts","../../../../src/internal/server/auth/auth-service.ts","../../../../src/internal/server/rate-limiter.ts","../../../../src/internal/server/auth/auth-shell-http.ts","../../../../src/internal/server/auth/auth-http.ts","../../../../src/internal/server/auth/instance-control.ts","../../../../src/internal/shared/background-notifications.ts","../../../../../shared/dist/index.js","../../../../src/internal/shared/protocol.ts","../../../../src/internal/server/http/background-notification-handlers.ts","../../../../src/internal/server/server-logger.ts","../../../../src/internal/server/http/development-web-backend.ts","../../../../src/internal/server/http/control-handlers.ts","../../../../src/internal/server/runtime/runtime-operations.ts","../../../../src/internal/server/http/operation-handler.ts","../../../../src/internal/server/http/request-logging.ts","../../../../src/internal/server/http/runtime-manifest-handler.ts","../../../../src/internal/shared/routes.ts","../../../../src/internal/server/http/routes.ts","../../../../src/internal/server/http/create-http-app.ts","../../../../src/internal/server/websocket-limits.ts","../../../../src/internal/server/websocket-connection.ts","../../../../src/internal/server/vite-websocket-proxy.ts","../../../../src/internal/server/websocket-server.ts","../../../../src/internal/server/notifications/background-notification-payload.ts","../../../../src/internal/server/notifications/background-notification-service.ts","../../../../src/internal/server/notifications/background-notification-store.ts","../../../../src/public/ai-context.ts","../../../../src/public/contracts.ts","../../../../src/internal/server/notifications/notification-service.ts","../../../../src/internal/server/runtime/runtime-lifecycle.ts","../../../../src/internal/server/runtime/resource-dependency-graph.ts","../../../../src/internal/server/runtime/runtime-resources.ts","../../../../src/internal/server/runtime/runtime-streams.ts","../../../../src/internal/server/runtime/create-runtime.ts","../../../../src/internal/server/server-startup-options.ts","../../../../src/internal/server/start-application-server.ts","../../../../src/internal/server/coordinator/ipc-protocol.ts","../../../../src/internal/server/coordinator/server-child.ts"],"sourcesContent":["import { realpath } from \"node:fs/promises\";\nimport { isIP } from \"node:net\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { createJiti } from \"jiti\";\nimport { z } from \"zod\";\nimport { homedir } from \"node:os\";\n//#region ../lib/dist/index.js\nconst durationPattern = /^([1-9]\\d*)(ms|s|m|h|d)$/;\nconst millisecondsByUnit = {\n\td: 1440 * 60 * 1e3,\n\th: 3600 * 1e3,\n\tm: 60 * 1e3,\n\tms: 1,\n\ts: 1e3\n};\nconst durationToMilliseconds = (duration) => {\n\tconst match = durationPattern.exec(duration);\n\tif (!match) return;\n\tconst unit = match[2];\n\tconst milliseconds = Number(match[1]) * millisecondsByUnit[unit];\n\treturn Number.isSafeInteger(milliseconds) ? milliseconds : void 0;\n};\nconst aiContextSnippets = [\"package-source\", \"tech-stack-recommendations\"];\n//#endregion\n//#region src/node/config.ts\nconst zodTypeSchema = z.custom((value) => value instanceof z.ZodType, \"Expected a Zod schema\");\nconst functionSchema = z.custom((value) => typeof value === \"function\", \"Expected a function\");\nconst contractRuntimeSchema = z.object({\n\tinput: zodTypeSchema,\n\toutput: zodTypeSchema\n});\nconst operationRuntimeSchema = z.object({\n\thandle: functionSchema,\n\tinput: zodTypeSchema,\n\toutput: zodTypeSchema\n});\nconst streamHandlerRuntimeSchema = z.object({\n\tcontract: z.object({\n\t\tclientMessage: zodTypeSchema,\n\t\tinput: zodTypeSchema,\n\t\tserverMessage: zodTypeSchema\n\t}),\n\topen: functionSchema\n});\nconst resourceDefinitionRuntimeSchema = z.discriminatedUnion(\"kind\", [\n\tz.object({\n\t\tcontract: contractRuntimeSchema,\n\t\tkind: z.literal(\"query\"),\n\t\tread: functionSchema\n\t}),\n\tz.object({\n\t\tcontract: contractRuntimeSchema,\n\t\tkind: z.literal(\"subscription\"),\n\t\tread: functionSchema,\n\t\tsubscribe: functionSchema\n\t}),\n\tz.object({\n\t\tcombine: functionSchema,\n\t\tcontract: contractRuntimeSchema,\n\t\tdependencies: z.record(z.string(), z.string()),\n\t\tkind: z.literal(\"derived\")\n\t})\n]);\nconst authDurationSchema = z.string().regex(/^[1-9]\\d*[mhd]$/, \"Expected a positive duration such as 30d\").refine((value) => durationToMilliseconds(value) !== void 0, \"Duration is too large\");\nconst isLoopbackHostname = (hostname) => hostname === \"localhost\" || hostname === \"[::1]\" || /^127(?:\\.\\d{1,3}){3}$/.test(hostname);\nconst exactOriginSchema = z.url().refine((value) => new URL(value).origin === value, \"Expected an origin\").refine((value) => {\n\tconst url = new URL(value);\n\treturn url.protocol === \"https:\" || url.protocol === \"http:\" && isLoopbackHostname(url.hostname);\n}, \"Non-loopback Overmux origins must use HTTPS\");\nconst loopbackPeerSchema = z.string().refine((value) => isIP(value) !== 0 && (value === \"::1\" || value.startsWith(\"127.\")), \"Expected a loopback IP address\");\nconst authConfigRuntimeSchema = z.object({\n\tmode: z.literal(\"cli-login\"),\n\torigins: z.array(exactOriginSchema).min(1).refine((origins) => new Set(origins).size === origins.length, \"Expected unique origins\").optional(),\n\tsessionLifetime: z.union([z.literal(\"never\"), authDurationSchema]).default(\"never\"),\n\ttrustedProxyPeer: loopbackPeerSchema.optional()\n}).strict();\nconst serverConfigRuntimeSchema = z.object({\n\thost: z.string().min(1).optional(),\n\tlogFile: z.string().min(1).optional(),\n\tport: z.number().int().min(1).max(65535).optional(),\n\tproductionWebAssetsDir: z.string().min(1).optional(),\n\twatch: z.boolean().optional()\n});\nconst serverDefinitionRuntimeSchema = z.object({\n\toperations: z.record(z.string(), operationRuntimeSchema).optional(),\n\tresources: z.record(z.string(), resourceDefinitionRuntimeSchema),\n\tstreams: z.record(z.string(), streamHandlerRuntimeSchema).optional()\n});\nconst configDefinitionRuntimeSchema = serverConfigRuntimeSchema.extend({\n\taiContextSnippets: z.array(z.enum(aiContextSnippets)).optional(),\n\tauth: authConfigRuntimeSchema,\n\tdebug: z.boolean().optional(),\n\tserver: serverDefinitionRuntimeSchema,\n\tvite: z.string().min(1).optional()\n});\nconst resolveLogicalPath = async (path) => {\n\tconst logicalPath = resolve(path);\n\treturn {\n\t\tlogicalPath,\n\t\trealPath: await realpath(logicalPath)\n\t};\n};\nconst resolveOvermuxConfigPaths = async (configPath) => {\n\tconst { logicalPath, realPath } = await resolveLogicalPath(configPath);\n\treturn {\n\t\tlogicalApplicationRoot: dirname(logicalPath),\n\t\tlogicalConfigPath: logicalPath,\n\t\trealApplicationRoot: dirname(realPath),\n\t\trealConfigPath: realPath\n\t};\n};\nconst unwrapDefaultExport = (module) => {\n\tif (typeof module === \"object\" && module !== null && \"default\" in module) return module.default;\n\treturn module;\n};\nconst loadOvermuxConfig = async ({ aliases = {}, configPath }) => {\n\tconst paths = await resolveOvermuxConfigPaths(configPath);\n\tconst module = await createJiti(paths.logicalConfigPath, {\n\t\talias: aliases,\n\t\tfsCache: true,\n\t\tjsx: {\n\t\t\timportSource: \"react\",\n\t\t\truntime: \"automatic\"\n\t\t},\n\t\tmoduleCache: false,\n\t\tsourceMaps: true,\n\t\ttsconfigPaths: true\n\t}).import(paths.logicalConfigPath);\n\treturn {\n\t\tconfig: configDefinitionRuntimeSchema.parse(unwrapDefaultExport(module)),\n\t\tpaths\n\t};\n};\n//#endregion\n//#region src/node/paths.ts\nconst xdgDirectory = (configured, fallback) => configured && isAbsolute(configured) ? configured : fallback;\nconst overmuxDirectory = (root) => join(root, \"overmux\");\nconst getOvermuxPaths = ({ environment = process.env, homeDir = homedir(), xdgCacheHome = environment.XDG_CACHE_HOME, xdgConfigHome = environment.XDG_CONFIG_HOME, xdgDataHome = environment.XDG_DATA_HOME, xdgRuntimeDir = environment.XDG_RUNTIME_DIR, xdgStateHome = environment.XDG_STATE_HOME } = {}) => {\n\tif (!isAbsolute(homeDir)) throw new TypeError(\"The home directory must be absolute.\");\n\tconst runtimeDir = xdgRuntimeDir && isAbsolute(xdgRuntimeDir) ? overmuxDirectory(xdgRuntimeDir) : void 0;\n\treturn {\n\t\tcacheDir: overmuxDirectory(xdgDirectory(xdgCacheHome, join(homeDir, \".cache\"))),\n\t\tconfigDir: overmuxDirectory(xdgDirectory(xdgConfigHome, join(homeDir, \".config\"))),\n\t\tdataDir: overmuxDirectory(xdgDirectory(xdgDataHome, join(homeDir, \".local\", \"share\"))),\n\t\t...runtimeDir ? { runtimeDir } : {},\n\t\tstateDir: overmuxDirectory(xdgDirectory(xdgStateHome, join(homeDir, \".local\", \"state\")))\n\t};\n};\n//#endregion\nexport { authConfigRuntimeSchema, authDurationSchema, configDefinitionRuntimeSchema, getOvermuxPaths, loadOvermuxConfig, resolveLogicalPath, resolveOvermuxConfigPaths, serverConfigRuntimeSchema, serverDefinitionRuntimeSchema };\n\n//# sourceMappingURL=index.js.map","//#region src/delay.ts\nconst delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));\n//#endregion\n//#region src/duration.ts\nconst durationPattern = /^([1-9]\\d*)(ms|s|m|h|d)$/;\nconst millisecondsByUnit = {\n\td: 1440 * 60 * 1e3,\n\th: 3600 * 1e3,\n\tm: 60 * 1e3,\n\tms: 1,\n\ts: 1e3\n};\nconst durationToMilliseconds = (duration) => {\n\tconst match = durationPattern.exec(duration);\n\tif (!match) return;\n\tconst unit = match[2];\n\tconst milliseconds = Number(match[1]) * millisecondsByUnit[unit];\n\treturn Number.isSafeInteger(milliseconds) ? milliseconds : void 0;\n};\n//#endregion\nexport { delay, durationToMilliseconds };\n\n//# sourceMappingURL=index.js.map","/*\n * Provides private, schema-validated JSON files with atomic persistence: directories and files\n * use owner-only modes; writes fsync a temporary file before rename replacement or hard-link\n * exclusive publication so concurrent first creation safely converges.\n */\nimport { randomUUID } from \"node:crypto\";\nimport {\n chmod,\n link,\n mkdir,\n open,\n readFile,\n rename,\n rm,\n} from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { z } from \"zod\";\n\nconst missingFile = (cause: unknown) =>\n (cause as NodeJS.ErrnoException).code === \"ENOENT\";\n\nconst preparePrivateDirectory = async (path: string) => {\n await mkdir(path, { mode: 0o700, recursive: true });\n await chmod(path, 0o700);\n};\n\nconst writeTemporaryPrivateJson = async (path: string, value: unknown) => {\n await preparePrivateDirectory(dirname(path));\n const temporaryPath = `${path}.${process.pid}.${randomUUID()}`;\n try {\n const handle = await open(temporaryPath, \"wx\", 0o600);\n try {\n await handle.writeFile(`${JSON.stringify(value)}\\n`);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return temporaryPath;\n } catch (cause) {\n await rm(temporaryPath, { force: true });\n throw cause;\n }\n};\n\nexport const readPrivateJson = async <TSchema extends z.ZodType>(\n path: string,\n schema: TSchema,\n): Promise<z.output<TSchema> | undefined> => {\n try {\n const contents = await readFile(path, \"utf8\");\n await chmod(path, 0o600);\n return schema.parse(JSON.parse(contents));\n } catch (cause) {\n if (missingFile(cause)) {\n return undefined;\n }\n throw cause;\n }\n};\n\nexport const replacePrivateJsonAtomically = async (\n path: string,\n value: unknown,\n) => {\n const temporaryPath = await writeTemporaryPrivateJson(path, value);\n try {\n await rename(temporaryPath, path);\n } catch (cause) {\n await rm(temporaryPath, { force: true });\n throw cause;\n }\n};\n\nexport const createPrivateJsonExclusively = async (\n path: string,\n value: unknown,\n) => {\n const temporaryPath = await writeTemporaryPrivateJson(path, value);\n try {\n await link(temporaryPath, path);\n } finally {\n await rm(temporaryPath, { force: true });\n }\n};\n","import {\n createHash,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from \"node:crypto\";\nimport { chmod, mkdir, open, rm, stat } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { durationToMilliseconds } from \"@overmux/lib\";\nimport { authDurationSchema } from \"@overmux/shared/node\";\nimport { z } from \"zod\";\n\nimport type { AuthConfigDefinition } from \"../../../public/config\";\nimport {\n createPrivateJsonExclusively,\n readPrivateJson,\n replacePrivateJsonAtomically,\n} from \"../notifications/private-json-file\";\nimport { getOvermuxPaths } from \"../paths\";\n\n// Login grants are brief, single-use browser bootstrap credentials. Local\n// bearers last only long enough for a CLI request because the owner-only control\n// socket can cheaply issue another without interactive authentication.\nconst loginGrantLifetimeMs = 10 * 60_000;\nconst localBearerLifetimeMs = 60_000;\nconst maxCodeAttempts = 8;\nconst lastSeenWriteIntervalMs = 60_000;\nconst codeAlphabet = \"23456789ABCDEFGHJKLMNPQRSTUVWXYZ\";\n\nconst loginGrantSchema = z.object({\n codeHash: z.string(),\n codeLookupHash: z.string(),\n consumedAt: z.string().optional(),\n createdAt: z.string(),\n expiresAt: z.string(),\n failedCodeAttempts: z.number().int().nonnegative(),\n id: z.string(),\n linkTokenHash: z.string(),\n});\n\nconst authSessionSchema = z.object({\n createdAt: z.string(),\n expiresAt: z.string().optional(),\n id: z.string(),\n kind: z.enum([\"browser\", \"local\"]),\n lastSeenAt: z.string(),\n origin: z.string().optional(),\n revokedAt: z.string().optional(),\n tokenHash: z.string(),\n});\n\nconst authStoreSchema = z.object({\n grants: z.array(loginGrantSchema),\n installationId: z.string(),\n sessions: z.array(authSessionSchema),\n version: z.literal(1),\n});\n\ntype AuthStore = z.infer<typeof authStoreSchema>;\ntype StoredSession = z.infer<typeof authSessionSchema>;\n\nexport type AuthSession = Omit<StoredSession, \"kind\" | \"tokenHash\">;\nexport type LoginGrant = {\n code: string;\n expiresAt: string;\n id: string;\n urls: string[];\n};\nexport type LoginResult =\n | { status: \"expired\" | \"invalid\" | \"rate-limited\" }\n | { session: AuthSession; status: \"authenticated\"; token: string };\nexport type AuthenticatedSession = {\n expiresAt?: string;\n id: string;\n kind: \"browser\" | \"local\";\n origin?: string;\n token: string;\n};\n// AuthService is transport-neutral and persists grants and sessions across\n// server replacement. Opaque credentials are returned once; only their hashes\n// and non-secret lifecycle metadata are stored. Every session represents\n// authority delegated by the OS user; there are no application users or roles.\nexport type AuthService = {\n authenticateToken: (\n token: string,\n origin?: string,\n ) => Promise<AuthenticatedSession | undefined>;\n consumeLoginGrant: (input: {\n code?: string;\n origin: string;\n ticket?: string;\n }) => Promise<LoginResult>;\n createLoginGrant: () => Promise<LoginGrant>;\n issueLocalBearer: () => Promise<{ expiresAt: string; token: string }>;\n isSessionActive: (id: string) => Promise<boolean>;\n listSessions: () => Promise<AuthSession[]>;\n onSessionsRevoked: (\n listener: (ids: ReadonlySet<string>) => void,\n ) => () => void;\n revokeAllSessions: () => Promise<number>;\n revokeSession: (id: string) => Promise<boolean>;\n setOrigins: (origins: string[]) => void;\n};\n\nconst tokenHash = (token: string) =>\n createHash(\"sha256\").update(token, \"utf8\").digest(\"hex\");\n\nconst hashesEqual = (left: string, right: string) => {\n const leftBytes = Buffer.from(left, \"hex\");\n const rightBytes = Buffer.from(right, \"hex\");\n return (\n leftBytes.length === rightBytes.length &&\n timingSafeEqual(leftBytes, rightBytes)\n );\n};\n\nconst randomToken = () => randomBytes(32).toString(\"base64url\");\n\nconst randomCode = () => {\n const bytes = randomBytes(8);\n const characters = Array.from(\n bytes,\n (byte) => codeAlphabet[byte % codeAlphabet.length],\n );\n return `${characters.slice(0, 4).join(\"\")}-${characters.slice(4).join(\"\")}`;\n};\n\nconst durationMilliseconds = (\n duration: Exclude<\n AuthConfigDefinition[\"sessionLifetime\"],\n \"never\" | undefined\n >,\n) => {\n const milliseconds = durationToMilliseconds(\n authDurationSchema.parse(duration),\n );\n if (milliseconds === undefined) {\n throw new Error(\"Expected a validated authentication duration\");\n }\n return milliseconds;\n};\n\n// Old and replacement server processes may overlap, so every read-modify-write\n// transaction takes a filesystem lock. This is what makes grant consumption and\n// revocation atomic across processes, not only within one AuthService instance.\nconst acquireStoreLock = async (\n path: string,\n deadline = Date.now() + 5_000,\n): Promise<() => Promise<void>> => {\n await mkdir(dirname(path), { mode: 0o700, recursive: true });\n await chmod(dirname(path), 0o700);\n try {\n const handle = await open(path, \"wx\", 0o600);\n await handle.close();\n return () => rm(path, { force: true });\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw cause;\n }\n let lockAge: number;\n try {\n lockAge = Date.now() - (await stat(path)).mtimeMs;\n } catch (statCause) {\n if ((statCause as NodeJS.ErrnoException).code === \"ENOENT\") {\n return acquireStoreLock(path, deadline);\n }\n throw statCause;\n }\n if (lockAge > 30_000) {\n await rm(path, { force: true });\n return acquireStoreLock(path, deadline);\n }\n if (Date.now() >= deadline) {\n throw new Error(\"Timed out waiting for the authentication store lock\");\n }\n await new Promise((resolve) => setTimeout(resolve, 10));\n return acquireStoreLock(path, deadline);\n }\n};\n\nconst dataDirectory = ({\n environment,\n homeDirectory,\n}: {\n environment: NodeJS.ProcessEnv;\n homeDirectory: string;\n}) =>\n join(\n getOvermuxPaths({ environment, homeDir: homeDirectory }).dataDir,\n \"auth\",\n );\n\nconst publicSession = ({\n kind: _kind,\n tokenHash: _tokenHash,\n ...session\n}: StoredSession): AuthSession => session;\nconst activeSession = (session: StoredSession, now: number) =>\n !session.revokedAt &&\n (session.kind === \"local\" || Boolean(session.origin)) &&\n (!session.expiresAt || Date.parse(session.expiresAt) > now);\n\nconst revokeExpired = (store: AuthStore, currentTime: number) => {\n const expiredIds: string[] = [];\n const sessions = store.sessions.map((session) => {\n if (\n !session.revokedAt &&\n session.expiresAt &&\n Date.parse(session.expiresAt) <= currentTime\n ) {\n expiredIds.push(session.id);\n return { ...session, revokedAt: new Date(currentTime).toISOString() };\n }\n return session;\n });\n return { expiredIds, sessions };\n};\n\nconst authenticateStoredToken = ({\n currentTime,\n store,\n origin,\n token,\n}: {\n currentTime: number;\n origin?: string;\n store: AuthStore;\n token: string;\n}) => {\n const { expiredIds, sessions } = revokeExpired(store, currentTime);\n const expectedHash = tokenHash(token);\n const session = sessions.find((candidate) =>\n hashesEqual(candidate.tokenHash, expectedHash),\n );\n const authenticated =\n session &&\n activeSession(session, currentTime) &&\n (session.kind === \"local\" || session.origin === origin)\n ? {\n ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),\n id: session.id,\n kind: session.kind,\n ...(session.origin ? { origin: session.origin } : {}),\n token,\n }\n : undefined;\n const updateLastSeen = Boolean(\n session &&\n authenticated &&\n currentTime - Date.parse(session.lastSeenAt) >= lastSeenWriteIntervalMs,\n );\n const nextSessions = updateLastSeen\n ? sessions.map((candidate) =>\n candidate.id === session?.id\n ? { ...candidate, lastSeenAt: new Date(currentTime).toISOString() }\n : candidate,\n )\n : sessions;\n return { authenticated, expiredIds, nextSessions, updateLastSeen };\n};\n\nexport const createAuthService = ({\n config,\n environment = process.env,\n homeDirectory = homedir(),\n now = Date.now,\n}: {\n config: AuthConfigDefinition;\n environment?: NodeJS.ProcessEnv;\n homeDirectory?: string;\n now?: () => number;\n}): AuthService => {\n const directory = dataDirectory({ environment, homeDirectory });\n const storePath = join(directory, \"auth.json\");\n const lockPath = join(directory, \"auth.lock\");\n const listeners = new Set<(ids: ReadonlySet<string>) => void>();\n let origins = config.origins;\n let pendingWrite = Promise.resolve();\n\n const readStore = async (): Promise<AuthStore> => {\n const existing = await readPrivateJson(storePath, authStoreSchema);\n if (existing) {\n return existing;\n }\n const initial: AuthStore = {\n grants: [],\n installationId: randomUUID(),\n sessions: [],\n version: 1,\n };\n try {\n await createPrivateJsonExclusively(storePath, initial);\n return initial;\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw cause;\n }\n const concurrentlyCreated = await readPrivateJson(\n storePath,\n authStoreSchema,\n );\n if (!concurrentlyCreated) {\n throw cause;\n }\n return concurrentlyCreated;\n }\n };\n\n const updateStore = <T>(\n update: (store: AuthStore) => {\n result: T;\n revokedIds?: string[];\n store?: AuthStore;\n },\n ) => {\n const operation = pendingWrite.then(async () => {\n const release = await acquireStoreLock(lockPath);\n try {\n const current = await readStore();\n const updated = update(current);\n if (updated.store) {\n await replacePrivateJsonAtomically(storePath, updated.store);\n }\n emitRevoked(updated.revokedIds ?? []);\n return updated.result;\n } finally {\n await release();\n }\n });\n pendingWrite = operation.then(\n () => undefined,\n () => undefined,\n );\n return operation;\n };\n\n // Revocation is the shared lifecycle signal for closing WebSockets and\n // removing session-owned background notification subscriptions.\n const emitRevoked = (ids: string[]) => {\n if (ids.length === 0) {\n return;\n }\n const revoked = new Set(ids);\n listeners.forEach((listener) => listener(revoked));\n };\n\n const createSession = ({\n kind,\n lifetimeMs,\n origin,\n }: {\n kind: StoredSession[\"kind\"];\n lifetimeMs?: number;\n origin?: string;\n }) => {\n const token = randomToken();\n const createdAt = new Date(now()).toISOString();\n const configuredLifetime =\n config.sessionLifetime && config.sessionLifetime !== \"never\"\n ? durationMilliseconds(config.sessionLifetime)\n : undefined;\n const expiresIn = lifetimeMs ?? configuredLifetime;\n const stored: StoredSession = {\n createdAt,\n ...(expiresIn\n ? { expiresAt: new Date(now() + expiresIn).toISOString() }\n : {}),\n id: randomUUID(),\n kind,\n lastSeenAt: createdAt,\n ...(origin ? { origin } : {}),\n tokenHash: tokenHash(token),\n };\n return { stored, token };\n };\n\n const authenticateToken = async (token: string, origin?: string) => {\n await pendingWrite;\n const currentTime = now();\n const inspected = authenticateStoredToken({\n currentTime,\n origin,\n store: await readStore(),\n token,\n });\n if (inspected.expiredIds.length === 0 && !inspected.updateLastSeen) {\n return inspected.authenticated;\n }\n return updateStore((store) => {\n const current = authenticateStoredToken({\n currentTime: now(),\n origin,\n store,\n token,\n });\n return {\n result: current.authenticated,\n revokedIds: current.expiredIds,\n store: { ...store, sessions: current.nextSessions },\n };\n });\n };\n\n return {\n authenticateToken,\n consumeLoginGrant: (input) =>\n updateStore<LoginResult>((store) => {\n const currentTime = now();\n const presented = input.code?.trim().toUpperCase() ?? input.ticket;\n if (!presented || Boolean(input.code) === Boolean(input.ticket)) {\n return { result: { status: \"invalid\" } as const };\n }\n const expectedHash = tokenHash(presented);\n const codeLookupHash = input.code\n ? tokenHash(presented.split(\"-\", 1)[0] ?? \"\")\n : undefined;\n const exactCodeIndex = store.grants.findIndex((grant) =>\n hashesEqual(grant.codeHash, expectedHash),\n );\n const codeIndex =\n exactCodeIndex >= 0\n ? exactCodeIndex\n : store.grants.findIndex((grant) =>\n hashesEqual(grant.codeLookupHash, codeLookupHash ?? \"\"),\n );\n const index = input.code\n ? codeIndex\n : store.grants.findIndex((grant) =>\n hashesEqual(grant.linkTokenHash, expectedHash),\n );\n if (index < 0) {\n return { result: { status: \"invalid\" } as const };\n }\n const grant = store.grants[index]!;\n if (grant.consumedAt) {\n return { result: { status: \"invalid\" } as const };\n }\n if (Date.parse(grant.expiresAt) <= currentTime) {\n return { result: { status: \"expired\" } as const };\n }\n if (input.code && grant.failedCodeAttempts >= maxCodeAttempts) {\n return { result: { status: \"rate-limited\" } as const };\n }\n if (input.code && !hashesEqual(grant.codeHash, expectedHash)) {\n const grants = store.grants.map((candidate, grantIndex) =>\n grantIndex === index\n ? {\n ...candidate,\n failedCodeAttempts: candidate.failedCodeAttempts + 1,\n }\n : candidate,\n );\n return {\n result: { status: \"invalid\" } as const,\n store: { ...store, grants },\n };\n }\n const { stored, token } = createSession({\n kind: \"browser\",\n origin: input.origin,\n });\n const grants = store.grants.map((candidate, grantIndex) =>\n grantIndex === index\n ? { ...candidate, consumedAt: new Date(currentTime).toISOString() }\n : candidate,\n );\n return {\n result: {\n session: publicSession(stored),\n status: \"authenticated\",\n token,\n } as const,\n store: {\n ...store,\n grants,\n sessions: [\n ...store.sessions.filter((session) =>\n activeSession(session, currentTime),\n ),\n stored,\n ],\n },\n };\n }),\n createLoginGrant: () =>\n updateStore((store) => {\n if (!origins) {\n throw new Error(\"The server has not established its browser origins\");\n }\n const code = randomCode();\n const ticket = randomToken();\n const createdAt = new Date(now()).toISOString();\n const expiresAt = new Date(now() + loginGrantLifetimeMs).toISOString();\n const id = randomUUID();\n const grant = {\n codeHash: tokenHash(code),\n codeLookupHash: tokenHash(code.split(\"-\", 1)[0]!),\n createdAt,\n expiresAt,\n failedCodeAttempts: 0,\n id,\n linkTokenHash: tokenHash(ticket),\n };\n return {\n result: {\n code,\n expiresAt,\n id,\n urls: origins.map(\n (origin) =>\n `${origin}/login#ticket=${encodeURIComponent(ticket)}`,\n ),\n },\n store: {\n ...store,\n grants: [\n ...store.grants.filter(\n (candidate) =>\n Date.parse(candidate.expiresAt) > now() &&\n !candidate.consumedAt,\n ),\n grant,\n ],\n },\n };\n }),\n issueLocalBearer: () =>\n updateStore((store) => {\n const currentTime = now();\n const { stored, token } = createSession({\n kind: \"local\",\n lifetimeMs: localBearerLifetimeMs,\n });\n return {\n result: { expiresAt: stored.expiresAt!, token },\n store: {\n ...store,\n sessions: [\n ...store.sessions.filter((session) =>\n activeSession(session, currentTime),\n ),\n stored,\n ],\n },\n };\n }),\n isSessionActive: (id) =>\n updateStore((store) => {\n const currentTime = now();\n const { expiredIds, sessions } = revokeExpired(store, currentTime);\n return {\n result: Boolean(\n sessions.find(\n (session) =>\n session.id === id && activeSession(session, currentTime),\n ),\n ),\n revokedIds: expiredIds,\n ...(expiredIds.length > 0 ? { store: { ...store, sessions } } : {}),\n };\n }),\n listSessions: () =>\n updateStore((store) => {\n const currentTime = now();\n const { expiredIds, sessions } = revokeExpired(store, currentTime);\n return {\n result: sessions\n .filter(\n (session) =>\n session.kind === \"browser\" &&\n activeSession(session, currentTime),\n )\n .map(publicSession),\n revokedIds: expiredIds,\n ...(expiredIds.length > 0 ? { store: { ...store, sessions } } : {}),\n };\n }),\n onSessionsRevoked: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n revokeAllSessions: () =>\n updateStore((store) => {\n const currentTime = now();\n const expired = revokeExpired(store, currentTime);\n const ids = expired.sessions\n .filter(\n (session) =>\n session.kind === \"browser\" && activeSession(session, currentTime),\n )\n .map((session) => session.id);\n const revoked = new Set(ids);\n const revokedAt = new Date(currentTime).toISOString();\n const sessions = expired.sessions.map((session) =>\n revoked.has(session.id) ? { ...session, revokedAt } : session,\n );\n const revokedIds = [...expired.expiredIds, ...ids];\n return {\n result: ids.length,\n revokedIds,\n ...(revokedIds.length > 0 ? { store: { ...store, sessions } } : {}),\n };\n }),\n revokeSession: (id) =>\n updateStore((store) => {\n const session = store.sessions.find(\n (candidate) => candidate.id === id && !candidate.revokedAt,\n );\n if (!session) {\n return { result: false };\n }\n const revokedAt = new Date(now()).toISOString();\n const sessions = store.sessions.map((candidate) =>\n candidate.id === id ? { ...candidate, revokedAt } : candidate,\n );\n return {\n result: true,\n revokedIds: [id],\n store: { ...store, sessions },\n };\n }),\n setOrigins: (nextOrigins) => {\n origins = nextOrigins.map((origin) => new URL(origin).origin);\n },\n };\n};\n","export type RateLimiter = {\n attemptsByKey: Map<string, number[]>;\n globalAttempts: number[];\n maxAttemptsPerKey: number;\n maxGlobalAttempts: number;\n maxTrackedKeys: number;\n windowMs: number;\n};\n\nexport const createRateLimiter = ({\n maxAttemptsPerKey,\n maxGlobalAttempts,\n maxTrackedKeys,\n windowMs,\n}: {\n maxAttemptsPerKey: number;\n maxGlobalAttempts: number;\n maxTrackedKeys: number;\n windowMs: number;\n}): RateLimiter => ({\n attemptsByKey: new Map(),\n globalAttempts: [],\n maxAttemptsPerKey,\n maxGlobalAttempts,\n maxTrackedKeys,\n windowMs,\n});\n\nexport const hasRateLimitCapacity = ({\n currentTime = Date.now(),\n key,\n limiter,\n}: {\n currentTime?: number;\n key: string;\n limiter: RateLimiter;\n}) => {\n const threshold = currentTime - limiter.windowMs;\n const recent = (limiter.attemptsByKey.get(key) ?? []).filter(\n (attempt) => attempt > threshold,\n );\n limiter.globalAttempts = limiter.globalAttempts.filter(\n (attempt) => attempt > threshold,\n );\n if (\n recent.length >= limiter.maxAttemptsPerKey ||\n limiter.globalAttempts.length >= limiter.maxGlobalAttempts\n ) {\n limiter.attemptsByKey.set(key, recent);\n return false;\n }\n limiter.attemptsByKey.set(key, [...recent, currentTime]);\n limiter.globalAttempts.push(currentTime);\n if (limiter.attemptsByKey.size > limiter.maxTrackedKeys) {\n limiter.attemptsByKey.clear();\n }\n return true;\n};\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Context } from \"hono\";\n\nconst authAssetPrefix = \"/_overmux/auth-shell/\";\nconst authEntry = \"index.html\";\nconst fingerprintedAssetPattern =\n /^assets\\/[A-Za-z0-9_.-]+-[A-Za-z0-9_-]{8}\\.(?:css|js)$/;\n\ntype AuthManifest = Record<string, { css?: string[]; file?: string }>;\ntype AuthAsset = { body: ArrayBuffer; contentType: string };\n\nexport type AuthShell = {\n files: Map<string, AuthAsset>;\n html: string;\n};\n\nconst defaultAuthAssetsDirectory = () =>\n fileURLToPath(new URL(\"../auth/\", import.meta.resolve(\"overmux\")));\n\nexport const loadAuthShell = (\n directory = defaultAuthAssetsDirectory(),\n): AuthShell => {\n const manifest = JSON.parse(\n readFileSync(`${directory}/.vite/manifest.json`, \"utf8\"),\n ) as AuthManifest;\n const entry = manifest[authEntry];\n if (!entry?.file || !entry.css?.length) {\n throw new Error(\n \"The packaged Overmux authentication assets are incomplete\",\n );\n }\n const paths = new Set(\n Object.values(manifest).flatMap(({ css = [], file }) =>\n file ? [file, ...css] : css,\n ),\n );\n const invalidPath = [...paths].find(\n (path) => !fingerprintedAssetPattern.test(path),\n );\n if (invalidPath) {\n throw new Error(\n `Invalid Overmux authentication asset path: ${invalidPath}`,\n );\n }\n const files = new Map(\n [...paths].map((path) => [\n path,\n {\n body: Uint8Array.from(readFileSync(`${directory}/${path}`)).buffer,\n contentType: path.endsWith(\".css\")\n ? \"text/css; charset=UTF-8\"\n : \"text/javascript; charset=UTF-8\",\n },\n ]),\n );\n return { files, html: readFileSync(`${directory}/index.html`, \"utf8\") };\n};\n\nexport const serveAuthShellAsset = (context: Context, shell: AuthShell) => {\n const asset = shell.files.get(context.req.path.slice(authAssetPrefix.length));\n if (!asset) {\n return context.body(null, 404);\n }\n context.header(\"Cache-Control\", \"public, max-age=31536000, immutable\");\n context.header(\"Content-Type\", asset.contentType);\n context.header(\"Cross-Origin-Resource-Policy\", \"same-origin\");\n context.header(\"X-Content-Type-Options\", \"nosniff\");\n return context.body(asset.body);\n};\n\nexport const renderAuthShell = (\n context: Context,\n shell: AuthShell,\n status: 200 | 401 = 200,\n) => {\n context.header(\"Cache-Control\", \"no-store\");\n context.header(\n \"Content-Security-Policy\",\n \"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'\",\n );\n context.header(\"Cross-Origin-Resource-Policy\", \"same-origin\");\n context.header(\"Referrer-Policy\", \"no-referrer\");\n context.header(\"X-Content-Type-Options\", \"nosniff\");\n return context.html(shell.html, status);\n};\n\nexport const isBrowserNavigation = (request: Request) =>\n request.headers.get(\"Sec-Fetch-Dest\") === \"document\" ||\n request.headers.get(\"Accept\")?.includes(\"text/html\");\n","import type { HttpBindings } from \"@hono/node-server\";\nimport type { Context, Handler, MiddlewareHandler } from \"hono\";\nimport { generateCookie } from \"hono/cookie\";\nimport { bodyLimit } from \"hono/body-limit\";\nimport { parse as parseCookie } from \"hono/utils/cookie\";\nimport { z } from \"zod\";\n\nimport { createRateLimiter, hasRateLimitCapacity } from \"../rate-limiter\";\nimport type { AuthService, AuthenticatedSession } from \"./auth-service\";\nimport {\n isBrowserNavigation,\n loadAuthShell,\n renderAuthShell,\n serveAuthShellAsset,\n} from \"./auth-shell-http\";\n\nconst maxLoginBodyBytes = 4_096;\n// Login limits use a rolling window covering the preceding 60 seconds.\nconst loginWindowMs = 60_000;\nconst maxLoginRequestsPerWindow = 12;\nconst maxGlobalLoginRequestsPerWindow = 120;\nconst maxTrackedLoginAddresses = 10_000;\n// Browser cookies cap non-expiring and longer sessions at 400 days.\nconst neverCookieLifetimeSeconds = 400 * 24 * 60 * 60;\nconst sessionCookieName = \"overmux_session\";\n\n// Session kind records the intended client, while credential records how the\n// request presented it. Only local + bearer and browser + cookie are accepted.\n// This prevents a copied browser token from bypassing browser origin policy.\nexport type RequestSession = AuthenticatedSession & {\n credential: \"bearer\" | \"cookie\";\n};\n\nexport type AuthEnvironment = {\n Variables: { session: RequestSession };\n};\n\nexport type RequestAuthentication = {\n authenticate: (\n request: Request,\n origin?: string,\n ) => Promise<RequestSession | undefined>;\n clearCookieHeader: (origin: string) => string;\n cookieHeader: (origin: string, token: string, expiresAt?: string) => string;\n};\n\nexport type RequestOriginInput = {\n remoteAddress?: string;\n request: Request;\n};\n\n// Groups the transport-neutral session service with the HTTP-specific policy\n// needed to authenticate requests against the configured browser origins.\nexport type AuthBoundary = {\n // Owns login grants, persisted sessions, token validation, and revocation.\n service: AuthService;\n // Resolves lazily because an ephemeral listening port is unknown until startup.\n resolveOrigin: (input: RequestOriginInput) => string | undefined;\n // Parses request credentials and creates or clears browser session cookies.\n requests: RequestAuthentication;\n};\n\nconst bearerToken = (header: string | null) =>\n /^Bearer ([A-Za-z0-9_-]+)$/.exec(header ?? \"\")?.[1];\n\nconst isLoopbackHostname = (hostname: string) =>\n hostname === \"localhost\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n /^127(?:\\.\\d{1,3}){3}$/.test(hostname);\n\nexport const validateAuthOrigin = (origin: string) => {\n const url = new URL(origin);\n if (url.origin !== origin) {\n throw new Error(\"auth.origins must contain exact origins without paths\");\n }\n if (\n url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && isLoopbackHostname(url.hostname))\n ) {\n throw new Error(\"Non-loopback Overmux origins must use HTTPS\");\n }\n return origin;\n};\n\n// Proxy chains commonly represent multiple previous values as a comma-separated list.\n// Authentication accepts only one exact value with no surrounding whitespace.\nconst exactForwardedValue = (value: string | null) =>\n value !== null && value === value.trim() && !value.includes(\",\")\n ? value\n : undefined;\n\n// Resolve the browser-facing origin and return it only when explicitly configured.\nexport const resolveRequestOrigin = ({\n origins,\n remoteAddress,\n request,\n trustedProxyPeer,\n}: RequestOriginInput & {\n origins: string[];\n trustedProxyPeer?: string;\n}) => {\n const requestUrl = new URL(request.url);\n\n // A reverse proxy accepts the browser request, then opens a new backend request to Overmux.\n // These headers report the browser-facing host, optional port, and protocol lost on that hop.\n // They are ordinary spoofable headers until the immediate sender matches trustedProxyPeer.\n const forwardedHost = request.headers.get(\"X-Forwarded-Host\");\n const forwardedProto = request.headers.get(\"X-Forwarded-Proto\");\n\n // If the trusted proxy supplies either header, require a complete valid pair.\n // Invalid proxy metadata rejects the request instead of falling back to its direct origin.\n if (\n trustedProxyPeer !== undefined &&\n remoteAddress === trustedProxyPeer &&\n (forwardedHost !== null || forwardedProto !== null)\n ) {\n const host = exactForwardedValue(forwardedHost);\n const proto = exactForwardedValue(forwardedProto);\n\n // The supported proxy setup accepts external HTTPS, forwards over HTTP, and preserves Host.\n // Requiring these values to agree rejects partial or contradictory origin descriptions.\n if (\n proto !== \"https\" ||\n !host ||\n requestUrl.protocol !== \"http:\" ||\n requestUrl.host !== host\n ) {\n return;\n }\n\n // The proxy may describe the request only as one of the explicitly configured origins.\n const forwardedOrigin = new URL(`https://${host}`).origin;\n return origins.includes(forwardedOrigin) ? forwardedOrigin : undefined;\n }\n\n // Other requests use their direct URL; any untrusted forwarded headers are ignored.\n return origins.includes(requestUrl.origin) ? requestUrl.origin : undefined;\n};\n\nconst cookieMaxAge = (expiresAt?: string) =>\n Math.min(\n neverCookieLifetimeSeconds,\n expiresAt\n ? Math.max(0, Math.floor((Date.parse(expiresAt) - Date.now()) / 1_000))\n : neverCookieLifetimeSeconds,\n );\n\nconst generateSessionCookie = ({\n origin,\n token,\n maxAge,\n}: {\n origin: string;\n token: string;\n maxAge: number;\n}) =>\n generateCookie(sessionCookieName, token, {\n httpOnly: true,\n maxAge,\n path: \"/\",\n sameSite: \"Strict\",\n ...(new URL(origin).protocol === \"https:\"\n ? { prefix: \"host\" as const }\n : {}),\n });\n\nconst createRequestAuthentication = ({\n service,\n}: {\n service: AuthService;\n}): RequestAuthentication => {\n // Browser sessions use HttpOnly, SameSite=Strict cookies. On HTTPS the\n // browser-enforced __Host- prefix also requires Secure, Path=/, and no Domain,\n // making the cookie host-only and resistant to subdomain replacement.\n const cookieName = (origin: string) =>\n new URL(origin).protocol === \"https:\"\n ? `__Host-${sessionCookieName}`\n : sessionCookieName;\n const cookieHeader = (origin: string, token: string, expiresAt?: string) =>\n generateSessionCookie({\n maxAge: cookieMaxAge(expiresAt),\n origin,\n token,\n });\n return {\n authenticate: async (request, origin) => {\n // Authorization is authoritative: an invalid header must not silently\n // fall back to a valid ambient browser cookie.\n const authorizationHeader = request.headers.get(\"Authorization\");\n if (authorizationHeader !== null) {\n const token = bearerToken(authorizationHeader);\n const authenticatedSession = token\n ? await service.authenticateToken(token)\n : undefined;\n return authenticatedSession?.kind === \"local\"\n ? { ...authenticatedSession, credential: \"bearer\" }\n : undefined;\n }\n if (!origin) {\n return;\n }\n const name = cookieName(origin);\n const token = parseCookie(request.headers.get(\"Cookie\") ?? \"\", name)[\n name\n ];\n const authenticatedSession = token\n ? await service.authenticateToken(token, origin)\n : undefined;\n return authenticatedSession?.kind === \"browser\"\n ? { ...authenticatedSession, credential: \"cookie\" }\n : undefined;\n },\n clearCookieHeader: (origin) =>\n generateSessionCookie({ maxAge: 0, origin, token: \"\" }),\n cookieHeader,\n };\n};\n\nexport const createAuthBoundary = ({\n origins,\n service,\n trustedProxyPeer,\n}: {\n origins: () => string[];\n service: AuthService;\n trustedProxyPeer?: string;\n}): AuthBoundary => ({\n requests: createRequestAuthentication({ service }),\n resolveOrigin: (input) =>\n resolveRequestOrigin({\n ...input,\n origins: origins(),\n trustedProxyPeer,\n }),\n service,\n});\n\nconst loginInputSchema = z.union([\n z.object({ code: z.string() }).strict(),\n z.object({ ticket: z.string() }).strict(),\n]);\n\nconst parseLoginBody = async (request: Request) => {\n if (\n request.headers.get(\"Content-Type\")?.split(\";\", 1)[0]?.toLowerCase() !==\n \"application/json\"\n ) {\n return;\n }\n try {\n return loginInputSchema.safeParse(await request.json()).data;\n } catch {\n return;\n }\n};\n\nconst hasTrustedBrowserHeaders = (request: Request, origin: string) =>\n request.headers.get(\"Origin\") === origin &&\n request.headers.get(\"Sec-Fetch-Site\") === \"same-origin\";\n\nconst changesState = (request: Request) =>\n ![\"GET\", \"HEAD\", \"OPTIONS\"].includes(request.method);\n\nconst requestOrigin = (auth: AuthBoundary, context: Context<AuthEnvironment>) =>\n auth.resolveOrigin({\n remoteAddress: (context.env as Partial<HttpBindings> | undefined)?.incoming\n ?.socket.remoteAddress,\n request: context.req.raw,\n });\n\ntype HttpAuthenticationHandlers = {\n asset: Handler<AuthEnvironment>;\n authenticate: MiddlewareHandler<AuthEnvironment>;\n login: Handler<AuthEnvironment>;\n loginBodyLimitMiddleware: MiddlewareHandler<AuthEnvironment>;\n loginPage: Handler<AuthEnvironment>;\n logout: Handler<AuthEnvironment>;\n state: Handler<AuthEnvironment>;\n};\n\n// Browser login and cookie-authenticated mutations require the effective\n// configured Origin plus same-origin Fetch Metadata. Bearer credentials are explicit rather\n// than ambient browser credentials, so they do not use the browser CSRF check.\nexport const createHttpAuthenticationHandlers = ({\n auth,\n authAssetsDirectory,\n}: {\n auth: AuthBoundary;\n authAssetsDirectory?: string;\n}): HttpAuthenticationHandlers => {\n const authShell = loadAuthShell(authAssetsDirectory);\n const loginRateLimiter = createRateLimiter({\n maxAttemptsPerKey: maxLoginRequestsPerWindow,\n maxGlobalAttempts: maxGlobalLoginRequestsPerWindow,\n maxTrackedKeys: maxTrackedLoginAddresses,\n windowMs: loginWindowMs,\n });\n\n return {\n asset: (context) => serveAuthShellAsset(context, authShell),\n state: async (context) => {\n context.header(\"Cache-Control\", \"no-store\");\n const origin = requestOrigin(auth, context);\n const session = await auth.requests.authenticate(context.req.raw, origin);\n if (session?.credential === \"cookie\" && origin) {\n context.header(\n \"Set-Cookie\",\n auth.requests.cookieHeader(origin, session.token, session.expiresAt),\n );\n }\n return context.json({ authenticated: Boolean(session) });\n },\n loginBodyLimitMiddleware: bodyLimit({\n maxSize: maxLoginBodyBytes,\n onError: (context) =>\n context.json({ error: \"Login request is too large\" }, 413),\n }),\n login: async (context) => {\n context.header(\"Cache-Control\", \"no-store\");\n const origin = requestOrigin(auth, context);\n if (!origin || !hasTrustedBrowserHeaders(context.req.raw, origin)) {\n return context.json(\n { error: \"Login request origin was rejected\" },\n 403,\n );\n }\n const address =\n (context.env as Partial<HttpBindings> | undefined)?.incoming?.socket\n .remoteAddress ?? \"unknown\";\n if (!hasRateLimitCapacity({ key: address, limiter: loginRateLimiter })) {\n return context.json({ status: \"rate-limited\" }, 429);\n }\n const input = await parseLoginBody(context.req.raw);\n if (!input) {\n return context.json({ error: \"Invalid login request\" }, 400);\n }\n const result = await auth.service.consumeLoginGrant({ ...input, origin });\n if (result.status !== \"authenticated\") {\n return context.json(\n { status: result.status },\n result.status === \"rate-limited\" ? 429 : 401,\n );\n }\n context.header(\n \"Set-Cookie\",\n auth.requests.cookieHeader(\n origin,\n result.token,\n result.session.expiresAt,\n ),\n );\n return context.json({ authenticated: true });\n },\n loginPage: async (context) => {\n const origin = requestOrigin(auth, context);\n const session = await auth.requests.authenticate(context.req.raw, origin);\n if (session) {\n return context.redirect(\"/\");\n }\n return renderAuthShell(context, authShell);\n },\n authenticate: async (context, next) => {\n const origin = requestOrigin(auth, context);\n let session: RequestSession | undefined;\n try {\n session = await auth.requests.authenticate(context.req.raw, origin);\n } catch {\n context.header(\"Cache-Control\", \"no-store\");\n return context.json(\n { error: \"Authentication service unavailable\" },\n 503,\n );\n }\n if (!session) {\n if (\n !context.req.path.startsWith(\"/api/\") &&\n isBrowserNavigation(context.req.raw)\n ) {\n return renderAuthShell(context, authShell, 401);\n }\n context.header(\"Cache-Control\", \"no-store\");\n return context.json({ error: \"Authentication required\" }, 401);\n }\n context.set(\"session\", session);\n context.header(\"Cache-Control\", \"private, no-store\");\n if (session.credential === \"cookie\") {\n if (\n !origin ||\n (changesState(context.req.raw) &&\n !hasTrustedBrowserHeaders(context.req.raw, origin))\n ) {\n return context.json({ error: \"Request origin was rejected\" }, 403);\n }\n context.header(\n \"Set-Cookie\",\n auth.requests.cookieHeader(origin, session.token, session.expiresAt),\n );\n }\n await next();\n },\n logout: async (context) => {\n const session = context.get(\"session\");\n await auth.service.revokeSession(session.id);\n if (session.origin) {\n context.header(\n \"Set-Cookie\",\n auth.requests.clearCookieHeader(session.origin),\n );\n }\n return context.json({ authenticated: false });\n },\n };\n};\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { chmod, mkdir, readdir, rm } from \"node:fs/promises\";\nimport { createConnection, createServer, type Socket } from \"node:net\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\n\nimport { getOvermuxPaths } from \"../paths\";\nimport {\n readPrivateJson,\n replacePrivateJsonAtomically,\n} from \"../notifications/private-json-file\";\nimport type { AuthService } from \"./auth-service\";\n\nconst maxControlMessageBytes = 16_384;\n\nconst controlRequestSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"ping\") }).strict(),\n z.object({ type: z.literal(\"create-login\") }).strict(),\n z.object({ type: z.literal(\"issue-bearer\") }).strict(),\n z.object({ type: z.literal(\"list-sessions\") }).strict(),\n z.object({ id: z.string(), type: z.literal(\"revoke-session\") }).strict(),\n z.object({ type: z.literal(\"revoke-all\") }).strict(),\n]);\n\nconst loginGrantSchema = z\n .object({\n code: z.string(),\n expiresAt: z.string(),\n id: z.string(),\n urls: z.array(z.string()),\n })\n .strict();\n\nconst sessionSchema = z\n .object({\n createdAt: z.string(),\n expiresAt: z.string().optional(),\n id: z.string(),\n lastSeenAt: z.string(),\n origin: z.string().optional(),\n revokedAt: z.string().optional(),\n })\n .strict();\n\nconst controlResponseSchemas = {\n \"create-login\": z\n .object({ login: loginGrantSchema, ok: z.literal(true) })\n .strict(),\n \"issue-bearer\": z\n .object({\n bearer: z.object({ expiresAt: z.string(), token: z.string() }).strict(),\n ok: z.literal(true),\n })\n .strict(),\n \"list-sessions\": z\n .object({ ok: z.literal(true), sessions: z.array(sessionSchema) })\n .strict(),\n ping: z.object({ ok: z.literal(true) }).strict(),\n \"revoke-all\": z\n .object({ count: z.number().int().nonnegative(), ok: z.literal(true) })\n .strict(),\n \"revoke-session\": z\n .object({ ok: z.literal(true), revoked: z.boolean() })\n .strict(),\n};\n\nconst controlResponseEnvelopeSchema = z\n .object({ error: z.unknown().optional(), ok: z.unknown() })\n .passthrough();\n\nconst registrationSchema = z.object({\n apiUrl: z.string().url(),\n controlSocket: z.string(),\n id: z.string(),\n pid: z.number().int().positive(),\n port: z.number().int().min(1).max(65_535),\n url: z.string().url(),\n});\n\nexport type InstanceRegistration = z.infer<typeof registrationSchema>;\nexport type ControlRequest = z.infer<typeof controlRequestSchema>;\nexport type InstanceControl = { close: () => Promise<void> };\n\ntype ControlResponseByType = {\n [Type in keyof typeof controlResponseSchemas]: z.infer<\n (typeof controlResponseSchemas)[Type]\n >;\n};\n\nconst runtimeDirectory = () => {\n const paths = getOvermuxPaths();\n const preferred = paths.runtimeDir ?? join(paths.stateDir, \"runtime\");\n if (Buffer.byteLength(preferred) <= 80) {\n return preferred;\n }\n const suffix = createHash(\"sha256\")\n .update(preferred)\n .digest(\"hex\")\n .slice(0, 12);\n return join(tmpdir(), `overmux-${process.getuid?.() ?? \"user\"}-${suffix}`);\n};\n\nconst readNewlineFrame = ({\n maximumBytes,\n socket,\n timeout,\n}: {\n maximumBytes: number;\n socket: Socket;\n timeout?: number;\n}): Promise<Buffer> =>\n new Promise((resolve, reject) => {\n let buffer = Buffer.alloc(0);\n let timer: NodeJS.Timeout | undefined;\n\n const cleanup = () => {\n socket.off(\"data\", onData);\n socket.off(\"end\", onEnd);\n socket.off(\"error\", onError);\n if (timer) {\n clearTimeout(timer);\n }\n };\n const fail = (cause: Error) => {\n cleanup();\n reject(cause);\n };\n const onData = (chunk: Buffer) => {\n buffer = Buffer.concat([buffer, chunk]);\n if (buffer.length > maximumBytes) {\n fail(new Error(\"Control message is too large\"));\n return;\n }\n const newline = buffer.indexOf(0x0a);\n if (newline < 0) {\n return;\n }\n cleanup();\n resolve(buffer.subarray(0, newline));\n };\n const onEnd = () =>\n fail(new Error(\"Control socket ended before a complete frame\"));\n const onError = (cause: Error) => fail(cause);\n\n if (socket.errored) {\n fail(socket.errored);\n } else if (socket.readableEnded || socket.destroyed) {\n fail(new Error(\"Control socket is already closed\"));\n } else {\n socket.on(\"data\", onData);\n socket.once(\"end\", onEnd);\n socket.once(\"error\", onError);\n if (timeout !== undefined) {\n timer = setTimeout(() => {\n socket.destroy();\n fail(new Error(\"Control request timed out\"));\n }, timeout);\n }\n }\n });\n\nconst writeResponse = (socket: Socket, response: unknown) => {\n socket.end(`${JSON.stringify(response)}\\n`);\n};\n\nconst handleRequest = async (auth: AuthService, request: ControlRequest) => {\n if (request.type === \"ping\") {\n return { ok: true };\n }\n if (request.type === \"create-login\") {\n return { login: await auth.createLoginGrant(), ok: true };\n }\n if (request.type === \"issue-bearer\") {\n return { bearer: await auth.issueLocalBearer(), ok: true };\n }\n if (request.type === \"list-sessions\") {\n return { ok: true, sessions: await auth.listSessions() };\n }\n if (request.type === \"revoke-session\") {\n return { ok: true, revoked: await auth.revokeSession(request.id) };\n }\n return { count: await auth.revokeAllSessions(), ok: true };\n};\n\nconst handleConnection = async ({\n auth,\n socket,\n}: {\n auth: AuthService;\n socket: Socket;\n}) => {\n try {\n const frame = await readNewlineFrame({\n maximumBytes: maxControlMessageBytes,\n socket,\n });\n const request = controlRequestSchema.parse(JSON.parse(frame.toString()));\n writeResponse(socket, await handleRequest(auth, request));\n } catch (cause) {\n writeResponse(socket, {\n error: cause instanceof Error ? cause.message : \"Invalid control request\",\n ok: false,\n });\n }\n};\n\n// Instance control is the private, same-user administration channel for a running\n// server. It bootstraps browser login grants and short-lived CLI bearers without\n// exposing those privileged operations over HTTP. The owner-only runtime\n// directory, registration file, and Unix socket make OS permissions the root of\n// trust. This boundary intentionally does not defend against another process\n// already running as the same OS user.\nexport const startInstanceControl = async ({\n auth,\n apiUrl,\n port,\n url,\n}: {\n auth: AuthService;\n apiUrl: string;\n port: number;\n url: string;\n}): Promise<InstanceControl> => {\n const directory = runtimeDirectory();\n await mkdir(directory, { mode: 0o700, recursive: true });\n await chmod(directory, 0o700);\n const id = randomBytes(8).toString(\"hex\");\n const socketPath = join(directory, `${id}.sock`);\n const registrationPath = join(directory, `${id}.json`);\n const sockets = new Set<Socket>();\n const server = createServer((socket) => {\n sockets.add(socket);\n socket.once(\"close\", () => sockets.delete(socket));\n void handleConnection({ auth, socket });\n });\n const close = async () => {\n sockets.forEach((socket) => socket.destroy());\n try {\n await new Promise<void>((resolve, reject) =>\n server.close((cause) => (cause ? reject(cause) : resolve())),\n );\n } finally {\n await Promise.all([\n rm(socketPath, { force: true }),\n rm(registrationPath, { force: true }),\n ]);\n }\n };\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(socketPath, () => {\n server.off(\"error\", reject);\n resolve();\n });\n });\n try {\n await chmod(socketPath, 0o600);\n await replacePrivateJsonAtomically(registrationPath, {\n apiUrl,\n controlSocket: socketPath,\n id,\n pid: process.pid,\n port,\n url,\n });\n } catch (cause) {\n await close().catch(() => undefined);\n throw cause;\n }\n\n return { close };\n};\n\nconst processIsLive = (pid: number) => {\n try {\n process.kill(pid, 0);\n return true;\n } catch (cause) {\n return (cause as NodeJS.ErrnoException).code === \"EPERM\";\n }\n};\n\n// Finds the sole responsive local server, optionally filtered by port.\nexport const discoverInstance = async (\n port?: number,\n): Promise<InstanceRegistration> => {\n const directory = runtimeDirectory();\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new Error(\"No running Overmux server was found\");\n }\n throw cause;\n }\n const candidates = (\n await Promise.all(\n names\n .filter((name) => name.endsWith(\".json\"))\n .map((name) =>\n readPrivateJson(join(directory, name), registrationSchema).catch(\n () => undefined,\n ),\n ),\n )\n ).filter((registration): registration is InstanceRegistration =>\n Boolean(\n registration &&\n processIsLive(registration.pid) &&\n (port === undefined || registration.port === port),\n ),\n );\n const registrations = (\n await Promise.all(\n candidates.map(async (registration) => {\n try {\n await sendControlRequest(registration, { type: \"ping\" });\n return registration;\n } catch {\n return undefined;\n }\n }),\n )\n ).filter(\n (registration): registration is InstanceRegistration =>\n registration !== undefined,\n );\n if (registrations.length === 0) {\n throw new Error(\n port === undefined\n ? \"No running Overmux server was found\"\n : `No running Overmux server was found on port ${port}`,\n );\n }\n if (registrations.length > 1) {\n throw new Error(\n \"Multiple Overmux servers are running; use --port to select one\",\n );\n }\n return registrations[0]!;\n};\n\nexport const sendControlRequest = async <Request extends ControlRequest>(\n registration: InstanceRegistration,\n request: Request,\n): Promise<ControlResponseByType[Request[\"type\"]]> => {\n const socket = createConnection(registration.controlSocket);\n let frame: Buffer;\n try {\n const response = readNewlineFrame({\n maximumBytes: maxControlMessageBytes,\n socket,\n timeout: 1_000,\n });\n socket.once(\"connect\", () => socket.write(`${JSON.stringify(request)}\\n`));\n frame = await response;\n } finally {\n socket.destroy();\n }\n const parsed = controlResponseEnvelopeSchema.safeParse(\n JSON.parse(frame.toString()),\n );\n if (!parsed.success) {\n throw new Error(\"Invalid control response\");\n }\n if (parsed.data.ok !== true) {\n throw new Error(\n typeof parsed.data.error === \"string\"\n ? parsed.data.error\n : \"Control request failed\",\n );\n }\n const response = controlResponseSchemas[request.type].safeParse(parsed.data);\n if (!response.success) {\n throw new Error(\"Invalid control response\");\n }\n return response.data as ControlResponseByType[Request[\"type\"]];\n};\n","// Validates browser subscription data exchanged by background-notification delivery.\n// Browser-standard key and endpoint details stay behind this internal boundary.\nimport { z } from \"zod\";\n\nconst deliveryKeySchema = z\n .string()\n .min(1)\n .max(1_024)\n .regex(/^[\\w-]+$/u);\n\nexport const backgroundNotificationSubscriptionSchema = z\n .object({\n endpoint: z\n .url()\n .max(4_096)\n .refine((endpoint) => {\n const url = new URL(endpoint);\n return url.protocol === \"https:\" && !url.username && !url.password;\n }),\n expirationTime: z.number().int().nonnegative().nullable(),\n keys: z\n .object({ auth: deliveryKeySchema, p256dh: deliveryKeySchema })\n .strict(),\n })\n .strict();\n\nexport const backgroundNotificationPublicKeyResponseSchema = z\n .object({ publicKey: deliveryKeySchema })\n .strict();\n\nexport const backgroundNotificationDisableRequestSchema = z\n .object({ endpoint: backgroundNotificationSubscriptionSchema.shape.endpoint })\n .strict();\n\nexport type BackgroundNotificationSubscription = z.infer<\n typeof backgroundNotificationSubscriptionSchema\n>;\n","import { z } from \"zod\";\n//#region src/ai-context.ts\nconst packageSourceSnippet = \"package-source\";\nconst techStackRecommendationsSnippet = \"tech-stack-recommendations\";\nconst aiContextSnippets = [packageSourceSnippet, techStackRecommendationsSnippet];\n//#endregion\n//#region src/hosted-routes.ts\nconst overmuxSettingsPath = \"/_overmux/settings\";\nconst overmuxLogoutPath = \"/_overmux/logout\";\nconst reservedPathPrefixes = [\n\t\"/_overmux\",\n\t\"/api\",\n\t\"/login\"\n];\nconst returnToBase = \"https://overmux.invalid\";\nconst isReservedPath = (pathname) => reservedPathPrefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));\nconst resolveOvermuxReturnTo = (candidate) => {\n\tif (!candidate?.startsWith(\"/\") || candidate.startsWith(\"//\")) return \"/\";\n\ttry {\n\t\tconst url = new URL(candidate, returnToBase);\n\t\tconst decodedPathname = decodeURIComponent(url.pathname);\n\t\tif (url.origin !== returnToBase || isReservedPath(decodedPathname)) return \"/\";\n\t\treturn `${url.pathname}${url.search}${url.hash}`;\n\t} catch {\n\t\treturn \"/\";\n\t}\n};\nconst createOvermuxSettingsPath = (returnTo) => {\n\tconst safeReturnTo = resolveOvermuxReturnTo(returnTo);\n\tif (safeReturnTo === \"/\") return overmuxSettingsPath;\n\tconst search = new URLSearchParams({ returnTo: safeReturnTo });\n\treturn `${overmuxSettingsPath}?${search.toString()}`;\n};\n//#endregion\n//#region src/notifications.ts\nconst safeRelativeNotificationLink = (link) => {\n\tlet decoded;\n\ttry {\n\t\tdecoded = decodeURIComponent(link);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn !decoded.startsWith(\"//\") && !decoded.includes(\"\\\\\") && ![...decoded].some((character) => {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\treturn codePoint < 32 || codePoint === 127;\n\t});\n};\nconst notificationLinkSchema = z.union([z.string().max(4096).startsWith(\"/\").refine(safeRelativeNotificationLink), z.string().max(4096).url().refine((link) => {\n\tif (!URL.canParse(link)) return false;\n\tconst url = new URL(link);\n\treturn [\"http:\", \"https:\"].includes(url.protocol) && !url.username && !url.password;\n})]);\nconst notificationSchema = z.object({\n\tbody: z.string().max(4096).optional(),\n\topen: z.object({ link: notificationLinkSchema }).strict().optional(),\n\ttitle: z.string().min(1).max(4096)\n}).strict();\n//#endregion\nexport { aiContextSnippets, createOvermuxSettingsPath, notificationLinkSchema, notificationSchema, overmuxLogoutPath, overmuxSettingsPath, packageSourceSnippet, resolveOvermuxReturnTo, techStackRecommendationsSnippet };\n\n//# sourceMappingURL=index.js.map","import { z } from \"zod\";\n\nimport { notificationSchema } from \"../../public/notifications\";\n\n// Compatibility gate, not negotiation: open tabs may still run older client assets.\n// The exact version rejects incompatible runtime manifest and wire formats before later traffic.\nexport const protocolVersion = 9 as const;\n\n// Application-defined WebSocket close codes shared by server and browser transports.\nexport const webSocketCloseCode = {\n authenticationRevoked: 4001,\n authenticationUnavailable: 4002,\n} as const;\n\nexport const runtimeManifestSchema = z.object({\n debug: z.boolean(),\n operations: z.array(z.string().min(1)),\n protocolVersion: z.literal(protocolVersion),\n resources: z.array(z.string().min(1)),\n streams: z.array(z.string().min(1)),\n});\n\nexport const updateAvailableEventSchema = z.object({\n type: z.literal(\"update-available\"),\n});\n\nexport const restartingEventSchema = z.object({\n type: z.literal(\"restarting\"),\n});\n\nexport const serverLifecycleEventSchema = z.discriminatedUnion(\"type\", [\n updateAvailableEventSchema,\n restartingEventSchema,\n]);\n\nexport const notificationEventSchema = z\n .object({\n notification: notificationSchema,\n type: z.literal(\"notification\"),\n })\n .strict();\n\nconst operationIdSchema = z.string().min(1).max(256);\nconst registrationNameSchema = z.string().min(1).max(256);\n\nexport const resourceReadMessageSchema = z.object({\n input: z.unknown().optional(),\n operationId: operationIdSchema,\n resourceName: registrationNameSchema,\n type: z.literal(\"resource-read\"),\n});\n\nexport const resourceSubscribeMessageSchema = z.object({\n input: z.unknown().optional(),\n operationId: operationIdSchema,\n resourceName: registrationNameSchema,\n subscriptionId: operationIdSchema,\n type: z.literal(\"resource-subscribe\"),\n});\n\nexport const resourceUnsubscribeMessageSchema = z.object({\n subscriptionId: operationIdSchema,\n type: z.literal(\"resource-unsubscribe\"),\n});\n\nexport const streamOpenMessageSchema = z.object({\n input: z.unknown().optional(),\n operationId: operationIdSchema,\n streamId: operationIdSchema,\n streamName: registrationNameSchema,\n type: z.literal(\"stream-open\"),\n});\n\nexport const streamMessageSchema = z.object({\n message: z.unknown(),\n streamId: operationIdSchema,\n type: z.literal(\"stream-message\"),\n});\n\nexport const streamCloseMessageSchema = z.object({\n streamId: operationIdSchema,\n type: z.literal(\"stream-close\"),\n});\n\nexport const clientDiagnosticEventSchema = z.object({\n arguments: z.string().max(16_100),\n level: z.enum([\"log\", \"info\", \"warn\", \"error\", \"debug\"]),\n message: z.string().max(4_100),\n stack: z.string().max(8_100).optional(),\n timestamp: z.iso.datetime(),\n type: z.literal(\"client-diagnostic\"),\n url: z.string().max(2_100).optional(),\n});\n\nexport const clientProtocolMessageSchema = z.discriminatedUnion(\"type\", [\n resourceReadMessageSchema,\n resourceSubscribeMessageSchema,\n resourceUnsubscribeMessageSchema,\n streamOpenMessageSchema,\n streamMessageSchema,\n streamCloseMessageSchema,\n clientDiagnosticEventSchema,\n]);\n\nexport const resourceResultMessageSchema = z.object({\n operationId: operationIdSchema,\n output: z.unknown(),\n type: z.literal(\"resource-result\"),\n});\n\nexport const resourceInvalidatedMessageSchema = z.object({\n subscriptionId: operationIdSchema,\n type: z.literal(\"resource-invalidated\"),\n});\n\nexport const streamOpenedMessageSchema = z.object({\n operationId: operationIdSchema,\n streamId: operationIdSchema,\n type: z.literal(\"stream-opened\"),\n});\n\nexport const streamOutputMessageSchema = z.object({\n message: z.unknown(),\n streamId: operationIdSchema,\n type: z.literal(\"stream-output\"),\n});\n\nexport const streamClosedMessageSchema = z.object({\n streamId: operationIdSchema,\n type: z.literal(\"stream-closed\"),\n});\n\nexport const protocolErrorMessageSchema = z.object({\n code: z.enum([\"bad-request\", \"conflict\", \"internal\", \"not-found\"]),\n message: z.string(),\n operationId: operationIdSchema.optional(),\n streamId: operationIdSchema.optional(),\n subscriptionId: operationIdSchema.optional(),\n type: z.literal(\"error\"),\n});\n\nexport const serverProtocolMessageSchema = z.discriminatedUnion(\"type\", [\n resourceResultMessageSchema,\n resourceInvalidatedMessageSchema,\n streamOpenedMessageSchema,\n streamOutputMessageSchema,\n streamClosedMessageSchema,\n protocolErrorMessageSchema,\n updateAvailableEventSchema,\n restartingEventSchema,\n notificationEventSchema,\n]);\n\nconst byteMarker = \"$overmuxBytes\";\n\ntype EncodedBytes = { [byteMarker]: number[] };\n\nconst encodeValue = (value: unknown): unknown => {\n if (value instanceof Uint8Array) {\n return { [byteMarker]: Array.from(value) } satisfies EncodedBytes;\n }\n if (Array.isArray(value)) {\n return value.map(encodeValue);\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [key, encodeValue(item)]),\n );\n }\n return value;\n};\n\nconst decodeValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map(decodeValue);\n }\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n const record = value as Record<string, unknown>;\n if (\n Object.keys(record).length === 1 &&\n Array.isArray(record[byteMarker]) &&\n record[byteMarker].every(\n (item) => Number.isInteger(item) && item >= 0 && item <= 255,\n )\n ) {\n return Uint8Array.from(record[byteMarker] as number[]);\n }\n return Object.fromEntries(\n Object.entries(record).map(([key, item]) => [key, decodeValue(item)]),\n );\n};\n\nconst binaryMarker = \"$overmuxBinary\";\nconst binaryMagic = 0x4f4d5801;\n\ntype EncodedBinary = { [binaryMarker]: [number, number] };\n\nconst encodeBinaryValue = (\n value: unknown,\n payloads: Uint8Array[],\n offset: { value: number },\n): unknown => {\n if (value instanceof Uint8Array) {\n const marker = {\n [binaryMarker]: [offset.value, value.byteLength],\n } satisfies EncodedBinary;\n payloads.push(value);\n offset.value += value.byteLength;\n return marker;\n }\n if (Array.isArray(value)) {\n return value.map((item) => encodeBinaryValue(item, payloads, offset));\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [\n key,\n encodeBinaryValue(item, payloads, offset),\n ]),\n );\n }\n return value;\n};\n\nconst decodeBinaryValue = (value: unknown, payload: Uint8Array): unknown => {\n if (Array.isArray(value)) {\n return value.map((item) => decodeBinaryValue(item, payload));\n }\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n const record = value as Record<string, unknown>;\n const marker = record[binaryMarker];\n if (\n Object.keys(record).length === 1 &&\n Array.isArray(marker) &&\n marker.length === 2 &&\n marker.every((item) => Number.isInteger(item) && item >= 0)\n ) {\n const [offset, length] = marker as [number, number];\n if (offset + length > payload.byteLength) {\n throw new Error(\"Invalid Overmux binary payload range\");\n }\n return payload.slice(offset, offset + length);\n }\n return Object.fromEntries(\n Object.entries(record).map(([key, item]) => [\n key,\n decodeBinaryValue(item, payload),\n ]),\n );\n};\n\nexport const encodeProtocolMessage = (message: unknown): string =>\n JSON.stringify(encodeValue(message));\n\nexport const decodeProtocolMessage = (message: string): unknown =>\n decodeValue(JSON.parse(message));\n\nexport const encodeProtocolFrame = (message: unknown): string | Uint8Array => {\n const payloads: Uint8Array[] = [];\n const encoded = encodeBinaryValue(message, payloads, { value: 0 });\n if (!payloads.length) {\n return JSON.stringify(encoded);\n }\n const header = new TextEncoder().encode(JSON.stringify(encoded));\n const payloadLength = payloads.reduce(\n (total, payload) => total + payload.byteLength,\n 0,\n );\n const frame = new Uint8Array(8 + header.byteLength + payloadLength);\n const view = new DataView(frame.buffer);\n view.setUint32(0, binaryMagic);\n view.setUint32(4, header.byteLength);\n frame.set(header, 8);\n let offset = 8 + header.byteLength;\n payloads.forEach((payload) => {\n frame.set(payload, offset);\n offset += payload.byteLength;\n });\n return frame;\n};\n\nexport const decodeProtocolFrame = (\n frame: string | ArrayBuffer | Uint8Array,\n): unknown => {\n if (typeof frame === \"string\") {\n return decodeProtocolMessage(frame);\n }\n const bytes =\n frame instanceof Uint8Array\n ? frame\n : new Uint8Array(frame, 0, frame.byteLength);\n if (bytes.byteLength < 8) {\n throw new Error(\"Invalid Overmux binary frame\");\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n if (view.getUint32(0) !== binaryMagic) {\n throw new Error(\"Invalid Overmux binary frame magic\");\n }\n const headerLength = view.getUint32(4);\n if (8 + headerLength > bytes.byteLength) {\n throw new Error(\"Invalid Overmux binary frame header\");\n }\n const header = JSON.parse(\n new TextDecoder().decode(bytes.subarray(8, 8 + headerLength)),\n ) as unknown;\n return decodeBinaryValue(header, bytes.subarray(8 + headerLength));\n};\n\nexport type RuntimeManifest = z.infer<typeof runtimeManifestSchema>;\nexport type ClientDiagnosticEvent = z.infer<typeof clientDiagnosticEventSchema>;\nexport type ClientProtocolMessage = z.infer<typeof clientProtocolMessageSchema>;\nexport type ServerLifecycleEvent = z.infer<typeof serverLifecycleEventSchema>;\nexport type ServerProtocolMessage = z.infer<typeof serverProtocolMessageSchema>;\n","// Exposes browser controls for enabling and disabling background notifications.\n// Subscription details pass directly to the background-delivery boundary.\nimport {\n backgroundNotificationDisableRequestSchema,\n backgroundNotificationSubscriptionSchema,\n} from \"../../shared/index\";\nimport type { Handler } from \"hono\";\nimport type { z } from \"zod\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\nimport type { BackgroundNotificationService } from \"../notifications/background-notification-service\";\n\nconst requestLimit = 16_384;\n\nconst parseJson = async <TSchema extends z.ZodType>(\n request: Request,\n schema: TSchema,\n): Promise<z.output<TSchema> | undefined> => {\n if (\n request.headers.get(\"Content-Type\")?.split(\";\", 1)[0]?.toLowerCase() !==\n \"application/json\"\n ) {\n return undefined;\n }\n const contentLength = Number(request.headers.get(\"Content-Length\") ?? 0);\n if (contentLength > requestLimit) {\n return undefined;\n }\n try {\n const bytes = await request.arrayBuffer();\n if (bytes.byteLength > requestLimit) {\n return undefined;\n }\n const parsed = schema.safeParse(\n JSON.parse(new TextDecoder().decode(bytes)),\n );\n return parsed.success ? parsed.data : undefined;\n } catch {\n return undefined;\n }\n};\n\nexport const createBackgroundNotificationHandlers = ({\n backgroundNotifications,\n}: {\n backgroundNotifications: BackgroundNotificationService;\n}): {\n disable: Handler<AuthEnvironment>;\n enable: Handler<AuthEnvironment>;\n publicKey: Handler<AuthEnvironment>;\n} => ({\n publicKey: async (context) => {\n context.header(\"Cache-Control\", \"no-store\");\n return context.json({\n publicKey: await backgroundNotifications.publicKey(),\n });\n },\n enable: async (context) => {\n const subscription = await parseJson(\n context.req.raw,\n backgroundNotificationSubscriptionSchema,\n );\n if (!subscription) {\n return context.json({ error: \"Invalid background subscription\" }, 400);\n }\n await backgroundNotifications.enable(\n context.get(\"session\").id,\n subscription,\n );\n return context.json({ ok: true });\n },\n disable: async (context) => {\n const input = await parseJson(\n context.req.raw,\n backgroundNotificationDisableRequestSchema,\n );\n if (!input) {\n return context.json({ error: \"Invalid background subscription\" }, 400);\n }\n await backgroundNotifications.disable(input.endpoint);\n return context.json({ ok: true });\n },\n});\n","import { appendFileSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { getOvermuxPaths } from \"./paths\";\n\nexport type ServerLogLevel = \"debug\" | \"error\" | \"info\" | \"warn\";\n\nexport type ServerLogEntry = {\n // Groups related request, connection, and operation logs for diagnostics.\n correlationId?: string;\n details?: Record<string, unknown>;\n durationMs?: number;\n event: string;\n level?: ServerLogLevel;\n message?: string;\n source?: \"browser\" | \"server\";\n timestamp?: string;\n};\n\nexport type ServerLogger = {\n enabled: boolean;\n id: () => string;\n log: (entry: ServerLogEntry) => void;\n};\n\ntype ConfigurableServerLogger = ServerLogger & {\n setEnabled: (enabled: boolean) => void;\n setLogFile: (logFile: string) => void;\n};\n\nconst lifecycleEvents = new Set([\n \"server-start\",\n \"server-stop\",\n \"websocket-close\",\n \"websocket-close-event\",\n \"websocket-connect\",\n \"websocket-open\",\n]);\n\nexport const getDefaultServerLogFile = ({\n homeDir,\n xdgStateHome,\n}: {\n homeDir?: string;\n xdgStateHome?: string;\n} = {}) =>\n join(getOvermuxPaths({ homeDir, xdgStateHome }).stateDir, \"overmux.log\");\n\nconst safeJson = (value: unknown) => {\n try {\n return JSON.stringify(value);\n } catch {\n return JSON.stringify({\n event: \"log-serialization-error\",\n level: \"error\",\n source: \"server\",\n timestamp: new Date().toISOString(),\n });\n }\n};\n\nexport const createServerLogger = ({\n enabled,\n logFile = getDefaultServerLogFile(),\n}: {\n enabled: boolean;\n logFile?: string;\n}): ConfigurableServerLogger => {\n let activeLogFile = logFile;\n let debugEnabled = enabled;\n return {\n get enabled() {\n return debugEnabled;\n },\n id: randomUUID,\n log: (entry) => {\n if (\n !debugEnabled &&\n entry.level !== \"error\" &&\n !lifecycleEvents.has(entry.event)\n ) {\n return;\n }\n const record = safeJson({\n timestamp: entry.timestamp ?? new Date().toISOString(),\n level: entry.level ?? \"info\",\n source: entry.source ?? \"server\",\n ...entry,\n });\n mkdirSync(dirname(activeLogFile), { recursive: true });\n appendFileSync(activeLogFile, `${record}\\n`, \"utf8\");\n process.stderr.write(`[overmux:debug] ${record}\\n`);\n },\n setEnabled: (nextEnabled) => {\n debugEnabled = nextEnabled;\n },\n setLogFile: (nextLogFile) => {\n activeLogFile = nextLogFile;\n },\n };\n};\n\nexport const errorMessage = (cause: unknown) =>\n cause instanceof Error ? cause.message : String(cause);\n\nexport const errorDetails = (cause: unknown) => ({\n message: errorMessage(cause),\n ...(cause instanceof Error && cause.stack ? { stack: cause.stack } : {}),\n});\n","import type { HttpBindings } from \"@hono/node-server\";\nimport { proxyFetch } from \"httpxy\";\nimport type { Handler } from \"hono\";\n\nimport type { AuthBoundary, AuthEnvironment } from \"../auth/auth-http\";\nimport { errorDetails, type ServerLogger } from \"../server-logger\";\n\nconst createForwardingHeaders = ({\n origin,\n remoteAddress,\n request,\n}: {\n origin: string;\n remoteAddress?: string;\n request: Request;\n}) => {\n const headers = new Headers(request.headers);\n [...headers.keys()].forEach((name) => {\n if (\n name === \"authorization\" ||\n name === \"cookie\" ||\n name === \"forwarded\" ||\n name.startsWith(\"x-forwarded-\")\n ) {\n headers.delete(name);\n }\n });\n const publicUrl = new URL(origin);\n if (remoteAddress) {\n headers.set(\"x-forwarded-for\", remoteAddress);\n }\n headers.set(\"x-forwarded-host\", publicUrl.host);\n headers.set(\n \"x-forwarded-port\",\n publicUrl.port || (publicUrl.protocol === \"https:\" ? \"443\" : \"80\"),\n );\n headers.set(\"x-forwarded-proto\", publicUrl.protocol.slice(0, -1));\n return headers;\n};\n\nexport const createDevelopmentWebHandler =\n ({\n auth,\n serverLogger,\n target,\n }: {\n auth: AuthBoundary;\n serverLogger?: ServerLogger;\n target: string;\n }): Handler<AuthEnvironment> =>\n async (context) => {\n const incoming = (context.env as Partial<HttpBindings> | undefined)\n ?.incoming;\n const origin = auth.resolveOrigin({\n remoteAddress: incoming?.socket.remoteAddress,\n request: context.req.raw,\n });\n if (!origin) {\n return context.text(\"Request origin was rejected\", 403);\n }\n const headers = createForwardingHeaders({\n origin,\n remoteAddress: incoming?.socket.remoteAddress,\n request: context.req.raw,\n });\n try {\n return await proxyFetch(\n target,\n new Request(context.req.raw, { headers }),\n undefined,\n { changeOrigin: true, xfwd: false },\n );\n } catch (cause) {\n serverLogger?.log({\n details: errorDetails(cause),\n event: \"vite-http-proxy-failure\",\n level: \"error\",\n });\n return context.text(\"Overmux development server is unavailable\", 503, {\n \"Cache-Control\": \"no-store\",\n });\n }\n };\n","// Provides server health and acknowledged restart control endpoints.\n// Shutdown state is shared with the HTTP app composition root.\nimport type { HttpBindings } from \"@hono/node-server\";\nimport type { Handler } from \"hono\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\n\nexport type ShutdownState = { requested: boolean };\n\nexport const createHealthHandler =\n ({ shutdown }: { shutdown: ShutdownState }): Handler<AuthEnvironment> =>\n (context) =>\n shutdown.requested\n ? context.json({ status: \"stopping\" }, 503)\n : context.json({ status: \"ok\" });\n\nexport const createRestartHandler =\n ({\n onRestartRequested,\n shutdown,\n }: {\n onRestartRequested?: () => void;\n shutdown: ShutdownState;\n }): Handler<AuthEnvironment> =>\n (context) => {\n const response = context.json({ status: \"restarting\" }, 202);\n if (!onRestartRequested) {\n return response;\n }\n const beginRestart = () => {\n shutdown.requested = true;\n onRestartRequested();\n };\n const nodeResponse = (context.env as Partial<HttpBindings> | undefined)\n ?.outgoing;\n if (nodeResponse) {\n // Flush the restart acknowledgement before replacing the server.\n nodeResponse.once(\"finish\", beginRestart);\n } else {\n // In-memory Hono requests have no Node response, so defer past the handler.\n setImmediate(beginRestart);\n }\n return response;\n };\n","// Registers named operations with validated input, output, and notification context.\n// Lookup metadata stays aligned with the names published in the runtime manifest.\n\nimport type {\n HandlerContext,\n OperationDefinition,\n} from \"../../../public/index\";\nimport type { Notifications } from \"../../../public/index\";\nimport { z } from \"zod\";\n\nexport class OperationValidationError extends Error {\n constructor(\n readonly phase: \"input\" | \"output\",\n cause: z.ZodError,\n ) {\n super(cause.message, { cause });\n }\n}\n\nexport type RuntimeOperation = {\n execute: (input: unknown, signal?: AbortSignal) => Promise<unknown>;\n returnsVoid: boolean;\n};\n\nexport type RuntimeOperations = {\n get: (name: string) => RuntimeOperation | undefined;\n names: readonly string[];\n};\n\ntype AnyOperation = OperationDefinition<z.ZodTypeAny, z.ZodTypeAny>;\n\nexport type RuntimeOperationDefinitions = Readonly<\n Record<string, AnyOperation>\n>;\n\ntype CreateRuntimeOperationsOptions = {\n context: (signal?: AbortSignal) => HandlerContext;\n definitions: RuntimeOperationDefinitions;\n notifications: Notifications;\n};\n\nexport const createRuntimeOperations = ({\n context,\n definitions,\n notifications,\n}: CreateRuntimeOperationsOptions): RuntimeOperations => {\n const operations = new Map<string, RuntimeOperation>();\n Object.entries(definitions).forEach(([name, definition]) => {\n if (!name) {\n throw new Error(\"Operation names must not be empty\");\n }\n operations.set(name, {\n execute: async (rawInput, signal) => {\n const operationContext = context(signal);\n operationContext.signal.throwIfAborted();\n const input = definition.input.safeParse(rawInput);\n if (!input.success) {\n throw new OperationValidationError(\"input\", input.error);\n }\n const rawOutput = await definition.handle(input.data, {\n ...operationContext,\n notifications,\n });\n operationContext.signal.throwIfAborted();\n const output = definition.output.safeParse(rawOutput);\n if (!output.success) {\n throw new OperationValidationError(\"output\", output.error);\n }\n return output.data;\n },\n returnsVoid: definition.output instanceof z.ZodVoid,\n });\n });\n return {\n get: (name) => operations.get(name),\n names: [...operations.keys()],\n };\n};\n","// Handles operation request validation, execution, cancellation, and lifecycle logs.\n// Operation payloads are limited to 1 MiB before JSON parsing.\nimport type { Handler } from \"hono\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\nimport type { ServerLogger } from \"../server-logger\";\nimport type { Runtime } from \"../runtime/create-runtime\";\nimport { OperationValidationError } from \"../runtime/runtime-operations\";\n\nconst maxOperationRequestBytes = 1_048_576;\n\nconst parseOperationRequest = async (request: Request) => {\n const contentType = request.headers.get(\"Content-Type\")?.split(\";\", 1)[0];\n if (contentType?.toLowerCase() !== \"application/json\") {\n return {\n error: \"Content-Type must be application/json\",\n status: 415,\n } as const;\n }\n const contentLength = Number(request.headers.get(\"Content-Length\") ?? 0);\n if (contentLength > maxOperationRequestBytes) {\n return { error: \"Request body is too large\", status: 413 } as const;\n }\n try {\n const body = await request.arrayBuffer();\n if (body.byteLength > maxOperationRequestBytes) {\n return { error: \"Request body is too large\", status: 413 } as const;\n }\n const text = new TextDecoder().decode(body);\n return { input: text ? (JSON.parse(text) as unknown) : undefined };\n } catch {\n return { error: \"Invalid JSON request body\", status: 400 } as const;\n }\n};\n\nexport const createOperationHandler =\n ({\n runtime,\n serverLogger,\n }: {\n runtime: Runtime;\n serverLogger?: ServerLogger;\n }): Handler<AuthEnvironment, \"/api/operations/:name\"> =>\n async (context) => {\n const operation = runtime.getOperation(context.req.param(\"name\"));\n if (!operation) {\n return context.json({ error: \"Operation not found\" }, 404);\n }\n const parsed = await parseOperationRequest(context.req.raw);\n if (\"error\" in parsed) {\n return context.json({ error: parsed.error }, parsed.status);\n }\n const correlationId =\n context.res.headers.get(\"X-Overmux-Correlation-Id\") ?? serverLogger?.id();\n const startedAt = Date.now();\n serverLogger?.log({\n correlationId,\n details: { registeredName: context.req.param(\"name\") },\n event: \"operation-start\",\n });\n try {\n const output = await operation.execute(\n parsed.input,\n context.req.raw.signal,\n );\n serverLogger?.log({\n correlationId,\n details: { registeredName: context.req.param(\"name\") },\n durationMs: Date.now() - startedAt,\n event: \"operation-complete\",\n });\n return operation.returnsVoid\n ? new Response(undefined, { status: 204 })\n : context.json(output);\n } catch (cause) {\n const message =\n cause instanceof Error ? cause.message : \"Operation failed\";\n serverLogger?.log({\n correlationId,\n details: { registeredName: context.req.param(\"name\") },\n durationMs: Date.now() - startedAt,\n event: \"operation-error\",\n level: \"error\",\n message,\n });\n return context.json(\n { error: message },\n cause instanceof OperationValidationError && cause.phase === \"input\"\n ? 400\n : 500,\n );\n }\n };\n","// Adds request correlation IDs and emits the final HTTP request log entry.\n// Logging runs after the matched middleware and route handler complete.\nimport type { MiddlewareHandler } from \"hono\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\nimport type { ServerLogger } from \"../server-logger\";\n\nexport const createRequestLoggingMiddleware =\n ({\n serverLogger,\n }: {\n serverLogger?: ServerLogger;\n }): MiddlewareHandler<AuthEnvironment> =>\n async (context, next) => {\n const correlationId = serverLogger?.id();\n const startedAt = Date.now();\n if (correlationId) {\n context.header(\"X-Overmux-Correlation-Id\", correlationId);\n }\n await next();\n const failed = context.res.status >= 400 || Boolean(context.error);\n serverLogger?.log({\n correlationId,\n details: {\n method: context.req.method,\n path: context.req.path,\n status: context.res.status,\n },\n durationMs: Date.now() - startedAt,\n event: failed ? \"http-request-failure\" : \"http-request\",\n level: failed ? \"error\" : undefined,\n message: context.error?.message,\n });\n };\n","// Runtime manifest responses must not be stored by client caches.\nimport type { Handler } from \"hono\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\nimport type { Runtime } from \"../runtime/create-runtime\";\n\nexport const createRuntimeManifestHandler =\n ({ runtime }: { runtime: Runtime }): Handler<AuthEnvironment> =>\n (context) => {\n context.header(\"Cache-Control\", \"no-store\");\n return context.json(runtime.manifest);\n };\n","export const runtimeWebSocketPath = \"/api/socket\";\nexport const viteHmrPath = \"/_overmux/vite/hmr\";\nexport const viteInfrastructurePath = \"/_overmux/vite/*\";\n","import { serveStatic } from \"@hono/node-server/serve-static\";\nimport type { Handler, Hono, MiddlewareHandler } from \"hono\";\nimport { join } from \"node:path\";\n\nimport {\n createHttpAuthenticationHandlers,\n type AuthBoundary,\n type AuthEnvironment,\n} from \"../auth/auth-http\";\nimport type { BackgroundNotificationService } from \"../notifications/background-notification-service\";\nimport type { Runtime } from \"../runtime/create-runtime\";\nimport type { ServerLogger } from \"../server-logger\";\nimport { createBackgroundNotificationHandlers } from \"./background-notification-handlers\";\nimport { createDevelopmentWebHandler } from \"./development-web-backend\";\nimport {\n createHealthHandler,\n createRestartHandler,\n type ShutdownState,\n} from \"./control-handlers\";\nimport { createOperationHandler } from \"./operation-handler\";\nimport { createRequestLoggingMiddleware } from \"./request-logging\";\nimport { createRuntimeManifestHandler } from \"./runtime-manifest-handler\";\nimport { overmuxLogoutPath, overmuxSettingsPath } from \"@overmux/shared\";\nimport { viteInfrastructurePath } from \"../../shared/routes\";\n\n// Registration order is the public/protected boundary. Authentication state,\n// login, and health are registered before the session gate; runtime APIs and\n// static assets are registered after it. Keep every Hono route visible in this\n// file for review.\ntype RouteDescriptor =\n | {\n method: \"USE\";\n path: string;\n handler: MiddlewareHandler<AuthEnvironment>;\n }\n | {\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"ALL\";\n path: string;\n handler: Handler<AuthEnvironment> | MiddlewareHandler<AuthEnvironment>;\n middleware?: MiddlewareHandler<AuthEnvironment>;\n };\n\ntype RegisterHttpRoutesOptions = {\n app: Hono<AuthEnvironment>;\n auth: AuthBoundary;\n authAssetsDirectory?: string;\n backgroundNotifications?: BackgroundNotificationService;\n developmentWebTarget?: string;\n onRestartRequested?: () => void;\n runtime: Runtime;\n serverLogger?: ServerLogger;\n shutdown: ShutdownState;\n webAssetsDir?: string;\n};\n\nconst applyDescriptor = (\n app: Hono<AuthEnvironment>,\n route: RouteDescriptor,\n) => {\n if (route.method === \"USE\") {\n app.use(route.path, route.handler);\n return;\n }\n if (route.middleware) {\n app.on(route.method, route.path, route.middleware, route.handler);\n return;\n }\n app.on(route.method, route.path, route.handler);\n};\n\nexport const registerHttpRoutes = ({\n app,\n auth,\n authAssetsDirectory,\n backgroundNotifications,\n developmentWebTarget,\n onRestartRequested,\n runtime,\n serverLogger,\n shutdown,\n webAssetsDir,\n}: RegisterHttpRoutesOptions) => {\n const authentication = createHttpAuthenticationHandlers({\n auth,\n authAssetsDirectory,\n });\n const notificationHandlers = backgroundNotifications\n ? createBackgroundNotificationHandlers({ backgroundNotifications })\n : undefined;\n const developmentWebHandler = developmentWebTarget\n ? createDevelopmentWebHandler({\n auth,\n serverLogger,\n target: developmentWebTarget,\n })\n : undefined;\n const productionWebHandler = webAssetsDir\n ? serveStatic({ path: join(webAssetsDir, \"index.html\") })\n : undefined;\n const hostedWebHandler = developmentWebHandler ?? productionWebHandler;\n const routes: RouteDescriptor[] = [\n {\n method: \"USE\",\n path: \"*\",\n handler: createRequestLoggingMiddleware({ serverLogger }),\n },\n // BEGIN: UNAUTHENTICATED\n {\n method: \"GET\",\n path: \"/_overmux/auth-shell/*\",\n handler: authentication.asset,\n },\n {\n method: \"GET\",\n path: \"/api/auth/state\",\n handler: authentication.state,\n },\n {\n method: \"POST\",\n path: \"/api/auth/login\",\n middleware: authentication.loginBodyLimitMiddleware,\n handler: authentication.login,\n },\n {\n method: \"GET\",\n path: \"/login\",\n handler: authentication.loginPage,\n },\n {\n method: \"GET\",\n path: \"/api/health\",\n handler: createHealthHandler({ shutdown }),\n },\n // END: UNAUTHENTICATED\n {\n method: \"USE\",\n path: \"*\",\n handler: authentication.authenticate,\n },\n // BEGIN: AUTHENTICATED\n {\n method: \"POST\",\n path: \"/api/auth/logout\",\n handler: authentication.logout,\n },\n {\n method: \"POST\",\n path: \"/api/operations/:name\",\n handler: createOperationHandler({ runtime, serverLogger }),\n },\n {\n method: \"POST\",\n path: \"/api/restart\",\n handler: createRestartHandler({ onRestartRequested, shutdown }),\n },\n {\n method: \"GET\",\n path: \"/api/runtime-manifest\",\n handler: createRuntimeManifestHandler({ runtime }),\n },\n ...(notificationHandlers\n ? [\n {\n method: \"GET\" as const,\n path: \"/api/background-notifications/public-key\",\n handler: notificationHandlers.publicKey,\n },\n {\n method: \"PUT\" as const,\n path: \"/api/background-notifications/subscription\",\n handler: notificationHandlers.enable,\n },\n {\n method: \"DELETE\" as const,\n path: \"/api/background-notifications/subscription\",\n handler: notificationHandlers.disable,\n },\n ]\n : []),\n {\n method: \"ALL\",\n path: \"/api/*\",\n handler: (context) => context.notFound(),\n },\n ...(developmentWebHandler\n ? [\n {\n method: \"ALL\" as const,\n path: viteInfrastructurePath,\n handler: developmentWebHandler,\n },\n ]\n : []),\n ...(hostedWebHandler\n ? [\n {\n method: \"GET\" as const,\n path: overmuxSettingsPath,\n handler: hostedWebHandler,\n },\n {\n method: \"GET\" as const,\n path: overmuxLogoutPath,\n handler: hostedWebHandler,\n },\n ]\n : []),\n {\n method: \"ALL\",\n path: \"/_overmux/*\",\n handler: (context) => context.notFound(),\n },\n ...(developmentWebHandler\n ? [\n {\n method: \"ALL\" as const,\n path: \"*\",\n handler: developmentWebHandler,\n },\n ]\n : []),\n ...(webAssetsDir\n ? [\n {\n method: \"USE\" as const,\n path: \"*\",\n handler: serveStatic({ root: webAssetsDir }),\n },\n // Serve the SPA shell for client-side routes that do not match a static asset.\n {\n method: \"GET\" as const,\n path: \"*\",\n handler: serveStatic({ path: join(webAssetsDir, \"index.html\") }),\n },\n ]\n : []),\n // END: AUTHENTICATED\n ];\n\n routes.forEach((route) => applyDescriptor(app, route));\n};\n","import { Hono } from \"hono\";\n\nimport type { AuthBoundary, AuthEnvironment } from \"../auth/auth-http\";\nimport type { BackgroundNotificationService } from \"../notifications/background-notification-service\";\nimport type { ServerLogger } from \"../server-logger\";\nimport type { Runtime } from \"../runtime/create-runtime\";\nimport { registerHttpRoutes } from \"./routes\";\n\nexport type HttpAppOptions = {\n auth: AuthBoundary;\n authAssetsDirectory?: string;\n backgroundNotifications?: BackgroundNotificationService;\n developmentWebTarget?: string;\n onRestartRequested?: () => void;\n serverLogger?: ServerLogger;\n runtime: Runtime;\n webAssetsDir?: string;\n};\n\nexport const createHttpApp = ({\n auth,\n authAssetsDirectory,\n backgroundNotifications,\n developmentWebTarget,\n onRestartRequested,\n serverLogger,\n runtime,\n webAssetsDir,\n}: HttpAppOptions) => {\n const app = new Hono<AuthEnvironment>();\n const shutdown = { requested: false };\n\n registerHttpRoutes({\n app,\n auth,\n authAssetsDirectory,\n backgroundNotifications,\n developmentWebTarget,\n onRestartRequested,\n runtime,\n serverLogger,\n shutdown,\n webAssetsDir,\n });\n\n return Object.assign(app, {\n beginShutdown: () => {\n shutdown.requested = true;\n },\n });\n};\n\nexport type OvermuxHttpApp = ReturnType<typeof createHttpApp>;\n","// Shares the server's outbound WebSocket backpressure policy.\nexport const maxWebSocketBufferedBytes = 1_048_576;\n","// Owns protocol and lifecycle state for one WebSocket connection.\n// Independent resource, stream, notification, diagnostics, and lifecycle traffic shares it.\nimport {\n clientProtocolMessageSchema,\n decodeProtocolFrame,\n encodeProtocolFrame,\n serverProtocolMessageSchema,\n type ClientProtocolMessage,\n type ServerProtocolMessage,\n} from \"../shared/index\";\nimport { WebSocket, type RawData } from \"ws\";\nimport { ZodError } from \"zod\";\n\nimport {\n errorDetails as diagnosticErrorDetails,\n type ServerLogger,\n} from \"./server-logger\";\nimport type { Runtime } from \"./runtime/create-runtime\";\nimport type { RuntimeStreamSession } from \"./runtime/runtime-streams\";\nimport { maxWebSocketBufferedBytes } from \"./websocket-limits\";\n\nconst maxPendingStreamOutputBytes = 1_048_576;\n\ntype ErrorCode = \"bad-request\" | \"conflict\" | \"internal\" | \"not-found\";\n\ntype SubscriptionEntry = {\n controller: AbortController;\n dispose?: () => Promise<void> | void;\n};\n\ntype OperationIdentity = {\n operationId: string;\n operationType: string;\n requestedName?: string;\n};\n\ntype StreamEntry = {\n controller: AbortController;\n identity: OperationIdentity;\n session?: RuntimeStreamSession;\n};\n\ntype ConnectionState = {\n closed: boolean;\n connectionId?: string;\n operations: Map<string, AbortController>;\n runtime: Runtime;\n serverLogger?: ServerLogger;\n socket: WebSocket;\n streams: Map<string, StreamEntry>;\n subscriptions: Map<string, SubscriptionEntry>;\n};\n\nclass OperationError extends Error {\n constructor(\n readonly code: ErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\nconst bytesOf = (data: RawData) => {\n if (Array.isArray(data)) {\n return Buffer.concat(data);\n }\n if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n};\n\nconst textOf = (data: RawData) => Buffer.from(bytesOf(data)).toString(\"utf8\");\n\nconst frameLength = (message: unknown) => {\n const frame = encodeProtocolFrame(message);\n return typeof frame === \"string\"\n ? Buffer.byteLength(frame, \"utf8\")\n : frame.byteLength;\n};\n\nconst operationIdOf = (value: unknown) => {\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n const operationId = (value as Record<string, unknown>).operationId;\n return typeof operationId === \"string\" && operationId.length <= 256\n ? operationId\n : undefined;\n};\n\nconst errorDetails = (cause: unknown): { code: ErrorCode; message: string } => {\n if (cause instanceof OperationError) {\n return { code: cause.code, message: cause.message };\n }\n if (cause instanceof ZodError || cause instanceof SyntaxError) {\n return {\n code: \"bad-request\",\n message:\n cause instanceof ZodError\n ? cause.issues\n .map(\n (issue) =>\n `${issue.path.join(\".\") || \"value\"}: ${issue.message}`,\n )\n .join(\"; \")\n : cause.message,\n };\n }\n return {\n code: \"internal\",\n message: cause instanceof Error ? cause.message : String(cause),\n };\n};\n\nconst send = (state: ConnectionState, message: ServerProtocolMessage) => {\n if (state.closed || state.socket.readyState !== WebSocket.OPEN) {\n return false;\n }\n // Apply outbound backpressure before queued messages consume unbounded memory.\n if (state.socket.bufferedAmount > maxWebSocketBufferedBytes) {\n state.socket.close(1013, \"client could not keep up\");\n return false;\n }\n state.socket.send(\n encodeProtocolFrame(serverProtocolMessageSchema.parse(message)),\n );\n return true;\n};\n\nconst sendError = (\n state: ConnectionState,\n cause: unknown,\n operationId?: string,\n identity?: OperationIdentity,\n) => {\n const error = errorDetails(cause);\n state.serverLogger?.log({\n correlationId: identity?.operationId ?? operationId ?? state.connectionId,\n details: {\n code: error.code,\n ...identity,\n ...diagnosticErrorDetails(cause),\n },\n event: \"protocol-handler-error\",\n level: \"error\",\n });\n send(state, { ...error, operationId, type: \"error\" });\n};\n\nconst disposeSubscription = async (\n state: ConnectionState,\n subscriptionId: string,\n) => {\n const entry = state.subscriptions.get(subscriptionId);\n if (!entry) {\n return;\n }\n state.subscriptions.delete(subscriptionId);\n entry.controller.abort(new Error(\"Resource subscription closed\"));\n await entry.dispose?.();\n};\n\nconst disposeStream = async (\n state: ConnectionState,\n streamId: string,\n notify = true,\n) => {\n const entry = state.streams.get(streamId);\n if (!entry) {\n if (notify) {\n send(state, { streamId, type: \"stream-closed\" });\n }\n return;\n }\n state.streams.delete(streamId);\n entry.controller.abort(new Error(\"Stream closed\"));\n await entry.session?.dispose();\n if (notify) {\n send(state, { streamId, type: \"stream-closed\" });\n }\n};\n\nconst disposeConnectionOperations = async (\n state: ConnectionState,\n notify: boolean,\n) => {\n const operationControllers = [...state.operations.values()];\n state.operations.clear();\n operationControllers.forEach((controller) =>\n controller.abort(new Error(\"WebSocket connection closed\")),\n );\n const subscriptionIds = [...state.subscriptions.keys()];\n const streamIds = [...state.streams.keys()];\n await Promise.allSettled([\n ...subscriptionIds.map((subscriptionId) =>\n disposeSubscription(state, subscriptionId),\n ),\n ...streamIds.map((streamId) => disposeStream(state, streamId, notify)),\n ]);\n};\n\nconst runOperation = (\n state: ConnectionState,\n identity: OperationIdentity,\n operation: (signal: AbortSignal) => Promise<void>,\n) => {\n if (state.operations.has(identity.operationId)) {\n sendError(\n state,\n new OperationError(\"conflict\", \"Operation ID is already active\"),\n identity.operationId,\n identity,\n );\n return;\n }\n const controller = new AbortController();\n const startedAt = Date.now();\n state.operations.set(identity.operationId, controller);\n state.serverLogger?.log({\n correlationId: identity.operationId,\n details: identity,\n event: \"operation-start\",\n });\n void operation(controller.signal)\n .then(() => {\n state.serverLogger?.log({\n correlationId: identity.operationId,\n details: identity,\n durationMs: Date.now() - startedAt,\n event: \"operation-complete\",\n });\n })\n .catch((cause: unknown) => {\n if (!controller.signal.aborted && !state.closed) {\n state.serverLogger?.log({\n correlationId: identity.operationId,\n details: { ...identity, ...diagnosticErrorDetails(cause) },\n durationMs: Date.now() - startedAt,\n event: \"operation-error\",\n level: \"error\",\n });\n sendError(state, cause, identity.operationId, identity);\n }\n })\n .finally(() => {\n if (state.operations.get(identity.operationId) === controller) {\n state.operations.delete(identity.operationId);\n }\n });\n};\n\nconst readResource = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"resource-read\" }>,\n) => {\n const resource = state.runtime.getResource(message.resourceName);\n const identity: OperationIdentity = {\n operationId: message.operationId,\n operationType: message.type,\n requestedName: message.resourceName,\n };\n runOperation(state, identity, async (signal) => {\n if (!resource) {\n throw new OperationError(\"not-found\", \"Resource not found\");\n }\n const output = await resource.read(message.input, signal);\n send(state, {\n operationId: message.operationId,\n output,\n type: \"resource-result\",\n });\n });\n};\n\nconst subscribeResource = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"resource-subscribe\" }>,\n) => {\n const resource = state.runtime.getResource(message.resourceName);\n const identity: OperationIdentity = {\n operationId: message.operationId,\n operationType: message.type,\n requestedName: message.resourceName,\n };\n if (state.subscriptions.has(message.subscriptionId)) {\n sendError(\n state,\n new OperationError(\"conflict\", \"Subscription ID is already active\"),\n message.operationId,\n identity,\n );\n return;\n }\n runOperation(state, identity, async (operationSignal) => {\n if (!resource) {\n throw new OperationError(\"not-found\", \"Resource not found\");\n }\n const controller = new AbortController();\n const entry: SubscriptionEntry = { controller };\n state.subscriptions.set(message.subscriptionId, entry);\n const signal = AbortSignal.any([operationSignal, controller.signal]);\n try {\n entry.dispose = resource.subscribe(\n message.input,\n () =>\n void send(state, {\n subscriptionId: message.subscriptionId,\n type: \"resource-invalidated\",\n }),\n signal,\n );\n } catch (cause) {\n await disposeSubscription(state, message.subscriptionId);\n throw cause;\n }\n });\n};\n\nconst openStream = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"stream-open\" }>,\n) => {\n const stream = state.runtime.getStream(message.streamName);\n const identity: OperationIdentity = {\n operationId: message.operationId,\n operationType: message.type,\n requestedName: message.streamName,\n };\n if (state.streams.has(message.streamId)) {\n sendError(\n state,\n new OperationError(\"conflict\", \"Stream ID is already active\"),\n message.operationId,\n identity,\n );\n return;\n }\n runOperation(state, identity, async (operationSignal) => {\n if (!stream) {\n throw new OperationError(\"not-found\", \"Stream not found\");\n }\n const controller = new AbortController();\n const entry: StreamEntry = { controller, identity };\n state.streams.set(message.streamId, entry);\n const pending: unknown[] = [];\n let pendingBytes = 0;\n let opened = false;\n try {\n entry.session = await stream.open(\n message.input,\n (output) => {\n if (opened) {\n const sent = send(state, {\n message: output,\n streamId: message.streamId,\n type: \"stream-output\",\n });\n if (!sent) {\n throw new Error(\"Stream output could not be delivered\");\n }\n return;\n }\n pendingBytes += frameLength(output);\n if (pendingBytes > maxPendingStreamOutputBytes) {\n throw new Error(\"Stream produced too much output while opening\");\n }\n pending.push(output);\n },\n AbortSignal.any([operationSignal, controller.signal]),\n (cause) => {\n sendError(state, cause, message.streamId, identity);\n void disposeStream(state, message.streamId).catch(\n (disposeCause: unknown) => {\n sendError(state, disposeCause, message.streamId, identity);\n },\n );\n },\n );\n send(state, {\n operationId: message.operationId,\n streamId: message.streamId,\n type: \"stream-opened\",\n });\n opened = true;\n for (const output of pending) {\n if (\n !send(state, {\n message: output,\n streamId: message.streamId,\n type: \"stream-output\",\n })\n ) {\n throw new Error(\"Stream output could not be delivered\");\n }\n }\n } catch (cause) {\n await disposeStream(state, message.streamId, false);\n throw cause;\n }\n });\n};\n\nconst sendStreamMessage = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"stream-message\" }>,\n) => {\n const entry = state.streams.get(message.streamId);\n const identity: OperationIdentity = {\n ...entry?.identity,\n operationId: message.streamId,\n operationType: message.type,\n };\n if (!entry?.session) {\n sendError(\n state,\n new OperationError(\"not-found\", \"Stream not found\"),\n message.streamId,\n identity,\n );\n return;\n }\n void entry.session.send(message.message).catch((cause: unknown) => {\n sendError(state, cause, message.streamId, identity);\n void disposeStream(state, message.streamId).catch(\n (disposeCause: unknown) => {\n sendError(state, disposeCause, message.streamId, identity);\n },\n );\n });\n};\n\nconst logClientDiagnostic = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"client-diagnostic\" }>,\n) => {\n if (!state.serverLogger?.enabled) {\n return;\n }\n state.serverLogger.log({\n details: {\n arguments: message.arguments,\n ...(message.stack ? { stack: message.stack } : {}),\n ...(message.url ? { url: message.url } : {}),\n },\n event: \"browser-console\",\n level: message.level === \"log\" ? \"info\" : message.level,\n message: message.message,\n source: \"browser\",\n timestamp: message.timestamp,\n });\n};\n\nconst handleMessage = (\n state: ConnectionState,\n message: ClientProtocolMessage,\n) => {\n if (message.type === \"client-diagnostic\") {\n logClientDiagnostic(state, message);\n return;\n }\n if (message.type === \"resource-read\") {\n readResource(state, message);\n return;\n }\n if (message.type === \"resource-subscribe\") {\n subscribeResource(state, message);\n return;\n }\n if (message.type === \"resource-unsubscribe\") {\n void disposeSubscription(state, message.subscriptionId).catch(\n (cause: unknown) => {\n sendError(state, cause, message.subscriptionId);\n },\n );\n return;\n }\n if (message.type === \"stream-open\") {\n openStream(state, message);\n return;\n }\n if (message.type === \"stream-close\") {\n void disposeStream(state, message.streamId).catch((cause: unknown) => {\n sendError(state, cause, message.streamId);\n });\n return;\n }\n sendStreamMessage(state, message);\n};\n\nconst handleFrame = (\n state: ConnectionState,\n data: RawData,\n isBinary: boolean,\n) => {\n let raw: unknown;\n try {\n raw = decodeProtocolFrame(isBinary ? bytesOf(data) : textOf(data));\n const result = clientProtocolMessageSchema.safeParse(raw);\n if (!result.success) {\n state.serverLogger?.log({\n correlationId: state.connectionId,\n details: diagnosticErrorDetails(result.error),\n event: \"protocol-parse-error\",\n level: \"error\",\n });\n sendError(state, result.error, operationIdOf(raw));\n return;\n }\n handleMessage(state, result.data);\n } catch (cause) {\n state.serverLogger?.log({\n correlationId: state.connectionId,\n details: diagnosticErrorDetails(cause),\n event: \"protocol-parse-error\",\n level: \"error\",\n });\n sendError(state, cause, operationIdOf(raw));\n }\n};\n\nconst disposeConnection = async (state: ConnectionState) => {\n if (state.closed) {\n return;\n }\n state.closed = true;\n state.serverLogger?.log({\n correlationId: state.connectionId,\n event: \"websocket-close\",\n });\n await disposeConnectionOperations(state, false);\n};\n\nconst createConnectionState = ({\n runtime,\n serverLogger,\n socket,\n}: {\n runtime: Runtime;\n serverLogger?: ServerLogger;\n socket: WebSocket;\n}): ConnectionState => ({\n closed: false,\n connectionId: serverLogger?.id(),\n operations: new Map(),\n runtime,\n serverLogger,\n socket,\n streams: new Map(),\n subscriptions: new Map(),\n});\n\nexport const attachWebSocketConnection = ({\n runtime,\n serverLogger,\n socket,\n}: {\n runtime: Runtime;\n serverLogger?: ServerLogger;\n socket: WebSocket;\n}) => {\n const state = createConnectionState({ runtime, serverLogger, socket });\n serverLogger?.log({\n correlationId: state.connectionId,\n event: \"websocket-open\",\n });\n socket.on(\"message\", (data, isBinary) => handleFrame(state, data, isBinary));\n socket.once(\"close\", (code, reason) => {\n serverLogger?.log({\n correlationId: state.connectionId,\n details: { code, reason: reason?.toString() ?? \"\" },\n event: \"websocket-close-event\",\n });\n void disposeConnection(state);\n });\n socket.once(\"error\", (cause) => {\n serverLogger?.log({\n correlationId: state.connectionId,\n details: diagnosticErrorDetails(cause),\n event: \"websocket-error\",\n level: \"error\",\n });\n void disposeConnection(state);\n });\n return () => disposeConnection(state);\n};\n","import type { IncomingMessage } from \"node:http\";\nimport type { Socket } from \"node:net\";\nimport type { Duplex } from \"node:stream\";\nimport { proxyUpgrade } from \"httpxy\";\n\nimport { webSocketCloseCode } from \"../shared/index\";\nimport type { AuthBoundary, RequestSession } from \"./auth/auth-http\";\nimport {\n errorDetails as diagnosticErrorDetails,\n type ServerLogger,\n} from \"./server-logger\";\n\ntype ProxiedSocket = {\n client: Duplex;\n closed: boolean;\n sessionId: string;\n timer: NodeJS.Timeout;\n upstream?: Socket;\n};\n\nconst setTrustedForwardingHeaders = (\n request: IncomingMessage,\n origin: string,\n) => {\n Object.keys(request.headers).forEach((name) => {\n if (\n name === \"authorization\" ||\n name === \"cookie\" ||\n name === \"forwarded\" ||\n name.startsWith(\"x-forwarded-\")\n ) {\n Reflect.deleteProperty(request.headers, name);\n }\n });\n const publicUrl = new URL(origin);\n request.headers[\"x-forwarded-for\"] = request.socket.remoteAddress;\n request.headers[\"x-forwarded-host\"] = publicUrl.host;\n request.headers[\"x-forwarded-port\"] =\n publicUrl.port || (publicUrl.protocol === \"https:\" ? \"443\" : \"80\");\n request.headers[\"x-forwarded-proto\"] = publicUrl.protocol.slice(0, -1);\n};\n\n// httpxy preserves an established WebSocket as a raw tunnel, so gateway-owned\n// revocation writes the server close frame before ending both sides.\nconst closeFrame = (code: number, reason: string) => {\n const payload = Buffer.allocUnsafe(2 + Buffer.byteLength(reason));\n payload.writeUInt16BE(code);\n payload.write(reason, 2);\n return Buffer.concat([Buffer.from([0x88, payload.length]), payload]);\n};\n\nconst closeSocket = (socket: ProxiedSocket, code: number, reason: string) => {\n if (socket.closed) {\n return;\n }\n socket.closed = true;\n clearInterval(socket.timer);\n if (!socket.client.destroyed) {\n socket.client.end(closeFrame(code, reason));\n }\n socket.upstream?.destroy();\n};\n\nconst revalidateSocket = async ({\n auth,\n serverLogger,\n origin,\n socket,\n token,\n}: {\n auth: AuthBoundary;\n origin: string;\n serverLogger?: ServerLogger;\n socket: ProxiedSocket;\n token: string;\n}) => {\n try {\n if (!(await auth.service.authenticateToken(token, origin))) {\n closeSocket(\n socket,\n webSocketCloseCode.authenticationRevoked,\n \"authentication revoked\",\n );\n }\n } catch (cause) {\n serverLogger?.log({\n details: diagnosticErrorDetails(cause),\n event: \"vite-websocket-session-revalidation-failure\",\n level: \"error\",\n });\n closeSocket(\n socket,\n webSocketCloseCode.authenticationUnavailable,\n \"authentication unavailable\",\n );\n }\n};\n\nexport const createViteWebSocketProxy = ({\n auth,\n serverLogger,\n target,\n}: {\n auth: AuthBoundary;\n serverLogger?: ServerLogger;\n target: string;\n}) => {\n const sockets = new Map<Duplex, ProxiedSocket>();\n\n const connect = ({\n correlationId,\n head,\n origin,\n request,\n session,\n socket,\n }: {\n correlationId?: string;\n head: Buffer;\n origin: string;\n request: IncomingMessage;\n session: RequestSession;\n socket: Duplex;\n }) => {\n let revalidationPending = false;\n const proxied: ProxiedSocket = {\n client: socket,\n closed: false,\n sessionId: session.id,\n timer: setInterval(() => {\n if (revalidationPending) {\n return;\n }\n revalidationPending = true;\n void revalidateSocket({\n auth,\n origin,\n serverLogger,\n socket: proxied,\n token: session.token,\n }).finally(() => {\n revalidationPending = false;\n });\n }, 1_000),\n };\n sockets.set(socket, proxied);\n socket.once(\"close\", () => {\n clearInterval(proxied.timer);\n sockets.delete(socket);\n });\n setTrustedForwardingHeaders(request, origin);\n void proxyUpgrade(target, request, socket, head, {\n changeOrigin: true,\n xfwd: false,\n }).then(\n (upstream) => {\n // Revocation can win while httpxy is opening the private side.\n if (proxied.closed) {\n upstream.destroy();\n return;\n }\n proxied.upstream = upstream;\n },\n (cause: unknown) => {\n clearInterval(proxied.timer);\n sockets.delete(socket);\n if (proxied.closed) {\n return;\n }\n proxied.closed = true;\n serverLogger?.log({\n correlationId,\n details: diagnosticErrorDetails(cause),\n event: \"vite-websocket-proxy-failure\",\n level: \"error\",\n });\n },\n );\n };\n\n return {\n close: () => {\n sockets.forEach((socket) =>\n closeSocket(socket, 1001, \"server shutting down\"),\n );\n sockets.clear();\n },\n connect,\n revoke: (ids: ReadonlySet<string>) => {\n sockets.forEach((socket) => {\n if (ids.has(socket.sessionId)) {\n closeSocket(\n socket,\n webSocketCloseCode.authenticationRevoked,\n \"authentication revoked\",\n );\n }\n });\n },\n };\n};\n","import type { ServerType as NodeServer } from \"@hono/node-server\";\nimport {\n encodeProtocolFrame,\n notificationEventSchema,\n serverProtocolMessageSchema,\n webSocketCloseCode,\n type ServerProtocolMessage,\n} from \"../shared/index\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { Duplex } from \"node:stream\";\nimport { WebSocket, WebSocketServer } from \"ws\";\n\nimport { runtimeWebSocketPath, viteHmrPath } from \"../shared/routes\";\nimport { attachWebSocketConnection } from \"./websocket-connection\";\nimport type { AuthBoundary, RequestSession } from \"./auth/auth-http\";\nimport {\n errorDetails as diagnosticErrorDetails,\n type ServerLogger,\n} from \"./server-logger\";\nimport type { Runtime } from \"./runtime/create-runtime\";\nimport { createViteWebSocketProxy } from \"./vite-websocket-proxy\";\nimport { maxWebSocketBufferedBytes } from \"./websocket-limits\";\n\nconst maxWebSocketPayloadBytes = 1_048_576;\n\n// Upgrade requests bypass Hono routing, so rejected paths need a raw HTTP response.\nconst rejectUpgrade = (socket: Duplex, status: number, message: string) => {\n socket.end(\n `HTTP/1.1 ${status} ${message}\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n`,\n );\n};\n\nconst requestPath = (request: IncomingMessage) => {\n try {\n return new URL(request.url ?? \"\", \"http://localhost\").pathname;\n } catch {\n return undefined;\n }\n};\n\nconst requestAuthenticationInput = (request: IncomingMessage) => {\n const host = request.headers.host;\n if (!host) {\n return;\n }\n const headers = new Headers();\n Object.entries(request.headers).forEach(([name, value]) => {\n if (Array.isArray(value)) {\n value.forEach((entry) => headers.append(name, entry));\n } else if (value !== undefined) {\n headers.set(name, value);\n }\n });\n const encrypted = Boolean(\n (request.socket as typeof request.socket & { encrypted?: boolean })\n .encrypted,\n );\n try {\n return new Request(\n `${encrypted ? \"https\" : \"http\"}://${host}${request.url ?? \"/\"}`,\n { headers },\n );\n } catch {\n return;\n }\n};\n\n// Tie a WebSocket to its session, periodically revalidating it and cleaning up\n// the session mapping when the connection closes.\nexport const attachSessionLifecycle = ({\n auth,\n serverLogger,\n session,\n sessionSockets,\n socket,\n}: {\n auth: AuthBoundary;\n serverLogger?: ServerLogger;\n session: RequestSession;\n sessionSockets: Map<WebSocket, string>;\n socket: WebSocket;\n}) => {\n sessionSockets.set(socket, session.id);\n let revalidationPending = false;\n const revalidationTimer = setInterval(() => {\n if (revalidationPending) {\n return;\n }\n revalidationPending = true;\n void auth.service\n .authenticateToken(session.token, session.origin)\n .then(\n (authenticated) => {\n if (!authenticated) {\n socket.close(\n webSocketCloseCode.authenticationRevoked,\n \"authentication revoked\",\n );\n }\n },\n (cause: unknown) => {\n serverLogger?.log({\n details: diagnosticErrorDetails(cause),\n event: \"websocket-session-revalidation-failure\",\n level: \"error\",\n });\n socket.close(\n webSocketCloseCode.authenticationUnavailable,\n \"authentication unavailable\",\n );\n },\n )\n .finally(() => {\n revalidationPending = false;\n });\n }, 1_000);\n socket.once(\"close\", () => {\n clearInterval(revalidationTimer);\n sessionSockets.delete(socket);\n });\n};\n\n// WebSocket upgrades bypass Hono but share its credential parser. Browser\n// sessions additionally require the exact canonical Origin; local bearer clients\n// are not browser-origin credentials. Each socket remains tied to its session so\n// explicit revocation closes it immediately, while periodic revalidation covers\n// expiration and changes made by another server process.\nexport const createWebSocketServer = ({\n auth,\n developmentWebTarget,\n runtime,\n server,\n serverLogger,\n}: {\n auth: AuthBoundary;\n developmentWebTarget?: string;\n runtime: Runtime;\n server: NodeServer;\n serverLogger?: ServerLogger;\n}) => {\n const webSocketServer = new WebSocketServer({\n maxPayload: maxWebSocketPayloadBytes,\n noServer: true,\n });\n let updateAvailable = false;\n const sessionSockets = new Map<WebSocket, string>();\n const viteProxy = developmentWebTarget\n ? createViteWebSocketProxy({\n auth,\n serverLogger,\n target: developmentWebTarget,\n })\n : undefined;\n const removeRevocationListener = auth.service.onSessionsRevoked((ids) => {\n sessionSockets.forEach((sessionId, socket) => {\n if (ids.has(sessionId)) {\n socket.close(\n webSocketCloseCode.authenticationRevoked,\n \"authentication revoked\",\n );\n }\n });\n viteProxy?.revoke(ids);\n });\n const onUpgrade = async (\n request: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n ) => {\n const correlationId = serverLogger?.id();\n serverLogger?.log({ correlationId, event: \"websocket-connect\" });\n const path = requestPath(request);\n const isRuntimeSocket = path === runtimeWebSocketPath;\n const isViteSocket =\n path === viteHmrPath && developmentWebTarget !== undefined;\n if (!isRuntimeSocket && !isViteSocket) {\n serverLogger?.log({\n correlationId,\n details: { status: 404 },\n event: \"websocket-connect-rejected\",\n level: \"warn\",\n });\n rejectUpgrade(socket, 404, \"Not Found\");\n return;\n }\n const authenticationInput = requestAuthenticationInput(request);\n if (!authenticationInput) {\n rejectUpgrade(socket, 400, \"Bad Request\");\n return;\n }\n const origin = auth.resolveOrigin({\n remoteAddress: request.socket.remoteAddress,\n request: authenticationInput,\n });\n let session: RequestSession | undefined;\n try {\n session = await auth.requests.authenticate(authenticationInput, origin);\n } catch (cause) {\n serverLogger?.log({\n correlationId,\n details: diagnosticErrorDetails(cause),\n event: \"websocket-authentication-failure\",\n level: \"error\",\n });\n rejectUpgrade(socket, 503, \"Service Unavailable\");\n return;\n }\n if (!session) {\n rejectUpgrade(socket, 401, \"Unauthorized\");\n return;\n }\n if (\n session.kind === \"browser\" &&\n (!origin || request.headers.origin !== origin)\n ) {\n rejectUpgrade(socket, 403, \"Forbidden\");\n return;\n }\n if (isViteSocket) {\n if (\n session.kind !== \"browser\" ||\n session.credential !== \"cookie\" ||\n !origin\n ) {\n rejectUpgrade(socket, 401, \"Unauthorized\");\n return;\n }\n if (!viteProxy) {\n rejectUpgrade(socket, 503, \"Service Unavailable\");\n return;\n }\n viteProxy.connect({\n correlationId,\n head,\n origin,\n request,\n session,\n socket,\n });\n return;\n }\n webSocketServer.handleUpgrade(request, socket, head, (webSocket) => {\n attachSessionLifecycle({\n auth,\n serverLogger,\n session,\n sessionSockets,\n socket: webSocket,\n });\n webSocketServer.emit(\"connection\", webSocket, request);\n attachWebSocketConnection({ runtime, serverLogger, socket: webSocket });\n if (updateAvailable) {\n webSocket.send(encodeProtocolFrame({ type: \"update-available\" }));\n }\n });\n };\n server.on(\"upgrade\", onUpgrade);\n\n const broadcast = (message: ServerProtocolMessage) => {\n const frame = encodeProtocolFrame(\n serverProtocolMessageSchema.parse(message),\n );\n let delivered = 0;\n webSocketServer.clients.forEach((socket) => {\n if (socket.readyState !== WebSocket.OPEN) {\n return;\n }\n // Apply outbound backpressure by dropping slow clients before queued broadcasts consume unbounded memory.\n if (socket.bufferedAmount > maxWebSocketBufferedBytes) {\n socket.close(1013, \"client could not keep up\");\n return;\n }\n try {\n socket.send(frame);\n delivered += 1;\n } catch (cause) {\n socket.terminate();\n serverLogger?.log({\n details: diagnosticErrorDetails(cause),\n event: \"websocket-broadcast-failure\",\n level: \"error\",\n });\n }\n });\n return delivered;\n };\n\n return {\n announceRestarting: () => broadcast({ type: \"restarting\" }),\n announceUpdateAvailable: () => {\n updateAvailable = true;\n return broadcast({ type: \"update-available\" });\n },\n broadcastNotification: (notification: unknown) =>\n broadcast(\n notificationEventSchema.parse({\n notification,\n type: \"notification\",\n }),\n ),\n close: async () => {\n server.off(\"upgrade\", onUpgrade);\n removeRevocationListener();\n viteProxy?.close();\n webSocketServer.clients.forEach((socket) => socket.terminate());\n await new Promise<void>((resolve) =>\n webSocketServer.close(() => resolve()),\n );\n },\n };\n};\n","// Fits background notification payloads within the Web Push provider limit.\n// Input is validated by the notification service before this internal boundary.\nimport type { Notification } from \"../../../public/index\";\n\nconst maxPayloadBytes = 3_800;\n\nconst payloadBytes = (payload: unknown) =>\n new TextEncoder().encode(JSON.stringify(payload)).byteLength;\n\nconst largestFittingPrefix = (\n characters: string[],\n accepts: (prefix: string) => boolean,\n low = 0,\n high = characters.length,\n): string => {\n if (low >= high) {\n return characters.slice(0, low).join(\"\");\n }\n const middle = Math.ceil((low + high) / 2);\n return accepts(characters.slice(0, middle).join(\"\"))\n ? largestFittingPrefix(characters, accepts, middle, high)\n : largestFittingPrefix(characters, accepts, low, middle - 1);\n};\n\nconst notificationPayload = (notification: Notification) => ({\n notification,\n type: \"notification\" as const,\n});\n\nexport const createBackgroundNotificationPayload = (\n notification: Notification,\n) => {\n const original = notificationPayload(notification);\n if (payloadBytes(original) <= maxPayloadBytes) {\n return JSON.stringify(original);\n }\n\n const withoutBody = { ...notification, body: undefined };\n const body = largestFittingPrefix(\n [...(notification.body ?? \"\")],\n (prefix) =>\n payloadBytes(\n notificationPayload({\n ...withoutBody,\n ...(prefix ? { body: prefix } : {}),\n }),\n ) <= maxPayloadBytes,\n );\n const bodyTruncated = notificationPayload({\n ...withoutBody,\n ...(body ? { body } : {}),\n });\n if (payloadBytes(bodyTruncated) <= maxPayloadBytes) {\n return JSON.stringify(bodyTruncated);\n }\n\n const title = largestFittingPrefix(\n [...notification.title],\n (prefix) =>\n Boolean(prefix) &&\n payloadBytes(notificationPayload({ ...withoutBody, title: prefix })) <=\n maxPayloadBytes,\n );\n if (title) {\n return JSON.stringify(notificationPayload({ ...withoutBody, title }));\n }\n const safeTitle = largestFittingPrefix(\n [...notification.title],\n (prefix) =>\n Boolean(prefix) &&\n payloadBytes(notificationPayload({ title: prefix })) <= maxPayloadBytes,\n );\n return JSON.stringify(notificationPayload({ title: safeTitle || \"Overmux\" }));\n};\n","// Delivers background notifications through the browser Web Push standard.\n// Provider payload, VAPID signing, and expired endpoints remain inside this boundary.\nimport type { BackgroundNotificationSubscription } from \"../../shared/index\";\nimport type { Notification } from \"../../../public/index\";\nimport webPush from \"web-push\";\n\nimport { errorDetails, type ServerLogger } from \"../server-logger\";\nimport type { BackgroundNotificationStore } from \"./background-notification-store\";\nimport { createBackgroundNotificationPayload } from \"./background-notification-payload\";\n\nconst vapidSubject = \"https://github.com/richardgill/overmux\";\n\nconst webPushStatus = (cause: unknown) => {\n if (\n typeof cause === \"object\" &&\n cause !== null &&\n \"statusCode\" in cause &&\n typeof cause.statusCode === \"number\"\n ) {\n return cause.statusCode;\n }\n return undefined;\n};\n\nconst deliverToSubscription = async ({\n keys,\n logger,\n payload,\n sendWebPush,\n store,\n subscription,\n}: {\n keys: Awaited<ReturnType<BackgroundNotificationStore[\"getOrCreateKeys\"]>>;\n logger?: ServerLogger;\n payload: string;\n sendWebPush: typeof webPush.sendNotification;\n store: BackgroundNotificationStore;\n subscription: BackgroundNotificationSubscription;\n}) => {\n try {\n await sendWebPush(subscription, payload, {\n TTL: 60,\n vapidDetails: {\n privateKey: keys.privateKey,\n publicKey: keys.publicKey,\n subject: vapidSubject,\n },\n });\n } catch (cause) {\n const status = webPushStatus(cause);\n if (status === 404 || status === 410) {\n await store.removeSubscription(subscription.endpoint);\n }\n logger?.log({\n details: {\n ...errorDetails(cause),\n ...(status ? { status } : {}),\n },\n event: \"background-notification-delivery-failure\",\n level: \"warn\",\n });\n }\n};\n\nexport type BackgroundNotificationService = {\n disable: (endpoint: string) => Promise<void>;\n disableSessions: (sessionIds: ReadonlySet<string>) => Promise<void>;\n enable: (\n sessionId: string,\n subscription: BackgroundNotificationSubscription,\n ) => Promise<void>;\n publicKey: () => Promise<string>;\n send: (notification: Notification) => Promise<void>;\n};\n\nexport const createBackgroundNotificationService = ({\n isSessionActive = async () => true,\n logger,\n sendWebPush = webPush.sendNotification,\n store,\n}: {\n isSessionActive?: (sessionId: string) => Promise<boolean>;\n logger?: ServerLogger;\n sendWebPush?: typeof webPush.sendNotification;\n store: BackgroundNotificationStore;\n}): BackgroundNotificationService => {\n let keysPromise:\n | ReturnType<BackgroundNotificationStore[\"getOrCreateKeys\"]>\n | undefined;\n const getKeys = () => {\n if (!keysPromise) {\n keysPromise = store\n .getOrCreateKeys(webPush.generateVAPIDKeys)\n .catch((cause: unknown) => {\n keysPromise = undefined;\n throw cause;\n });\n }\n return keysPromise;\n };\n\n return {\n disable: (endpoint) => store.removeSubscription(endpoint),\n disableSessions: (sessionIds) =>\n store.removeSessionSubscriptions(sessionIds),\n enable: (sessionId, subscription) =>\n store.upsertSubscription(sessionId, subscription),\n publicKey: async () => (await getKeys()).publicKey,\n send: async (notification) => {\n const storedSubscriptions = await store.listSubscriptions();\n const active = await Promise.all(\n storedSubscriptions.map(async (entry) => ({\n active: await isSessionActive(entry.sessionId),\n entry,\n })),\n );\n const subscriptions = active.flatMap(\n ({ active: sessionActive, entry }) => (sessionActive ? [entry] : []),\n );\n if (!subscriptions.length) {\n return;\n }\n const keys = await getKeys();\n const payload = createBackgroundNotificationPayload(notification);\n await Promise.all(\n subscriptions.map((entry) =>\n deliverToSubscription({\n keys,\n logger,\n payload,\n sendWebPush,\n store,\n subscription: entry.subscription,\n }),\n ),\n );\n },\n };\n};\n","// Defines replaceable persistence for background-notification keys and subscriptions.\n// The file implementation owns the required XDG data location and atomic updates.\nimport {\n backgroundNotificationSubscriptionSchema,\n type BackgroundNotificationSubscription,\n} from \"../../shared/index\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\n\nimport { getOvermuxPaths } from \"../paths\";\nimport {\n createPrivateJsonExclusively,\n readPrivateJson,\n replacePrivateJsonAtomically,\n} from \"./private-json-file\";\n\nconst vapidKeysSchema = z\n .object({ privateKey: z.string().min(1), publicKey: z.string().min(1) })\n .strict();\nconst storedSubscriptionSchema = z.object({\n sessionId: z.string(),\n subscription: backgroundNotificationSubscriptionSchema,\n});\nconst subscriptionsSchema = z.array(storedSubscriptionSchema);\n\ntype VapidKeys = z.infer<typeof vapidKeysSchema>;\nexport type StoredBackgroundNotificationSubscription = z.infer<\n typeof storedSubscriptionSchema\n>;\n\nexport type BackgroundNotificationStore = {\n getOrCreateKeys: (generate: () => VapidKeys) => Promise<VapidKeys>;\n listSubscriptions: () => Promise<\n readonly StoredBackgroundNotificationSubscription[]\n >;\n removeSessionSubscriptions: (\n sessionIds: ReadonlySet<string>,\n ) => Promise<void>;\n removeSubscription: (endpoint: string) => Promise<void>;\n upsertSubscription: (\n sessionId: string,\n subscription: BackgroundNotificationSubscription,\n ) => Promise<void>;\n};\n\nconst backgroundNotificationDataDirectory = ({\n environment,\n homeDirectory,\n}: {\n environment: NodeJS.ProcessEnv;\n homeDirectory: string;\n}) =>\n join(\n getOvermuxPaths({ environment, homeDir: homeDirectory }).dataDir,\n \"background-notifications\",\n );\n\nexport const createFileBackgroundNotificationStore = ({\n environment = process.env,\n homeDirectory = homedir(),\n}: {\n environment?: NodeJS.ProcessEnv;\n homeDirectory?: string;\n} = {}): BackgroundNotificationStore => {\n const directory = backgroundNotificationDataDirectory({\n environment,\n homeDirectory,\n });\n const keysPath = join(directory, \"vapid.json\");\n const subscriptionsPath = join(directory, \"subscriptions.json\");\n let pendingSubscriptionWrite = Promise.resolve();\n\n const readSubscriptions = async () =>\n (await readPrivateJson(subscriptionsPath, subscriptionsSchema)) ?? [];\n\n const updateSubscriptions = (\n update: (\n subscriptions: StoredBackgroundNotificationSubscription[],\n ) => StoredBackgroundNotificationSubscription[] | undefined,\n ) => {\n const operation = pendingSubscriptionWrite.then(async () => {\n const subscriptions = await readSubscriptions();\n const updated = update(subscriptions);\n if (updated) {\n await replacePrivateJsonAtomically(subscriptionsPath, updated);\n }\n });\n pendingSubscriptionWrite = operation.catch(() => undefined);\n return operation;\n };\n\n return {\n getOrCreateKeys: async (generate) => {\n const existing = await readPrivateJson(keysPath, vapidKeysSchema);\n if (existing) {\n return existing;\n }\n const generated = vapidKeysSchema.parse(generate());\n try {\n await createPrivateJsonExclusively(keysPath, generated);\n return generated;\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw cause;\n }\n const concurrentlyCreated = await readPrivateJson(\n keysPath,\n vapidKeysSchema,\n );\n if (!concurrentlyCreated) {\n throw cause;\n }\n return concurrentlyCreated;\n }\n },\n listSubscriptions: async () => {\n await pendingSubscriptionWrite;\n return readSubscriptions();\n },\n removeSubscription: (endpoint) =>\n updateSubscriptions((subscriptions) => {\n if (\n !subscriptions.some(\n (entry) => entry.subscription.endpoint === endpoint,\n )\n ) {\n return undefined;\n }\n return subscriptions.filter(\n (entry) => entry.subscription.endpoint !== endpoint,\n );\n }),\n removeSessionSubscriptions: (sessionIds) =>\n updateSubscriptions((subscriptions) => {\n const updated = subscriptions.filter(\n (entry) => !sessionIds.has(entry.sessionId),\n );\n return updated.length === subscriptions.length ? undefined : updated;\n }),\n upsertSubscription: (sessionId, subscription) => {\n const parsed =\n backgroundNotificationSubscriptionSchema.parse(subscription);\n return updateSubscriptions((subscriptions) => {\n const entry = { sessionId, subscription: parsed };\n const existing = subscriptions.find(\n (candidate) => candidate.subscription.endpoint === parsed.endpoint,\n );\n if (isDeepStrictEqual(existing, entry)) {\n return undefined;\n }\n return [\n ...subscriptions.filter(\n (candidate) => candidate.subscription.endpoint !== parsed.endpoint,\n ),\n entry,\n ];\n });\n },\n };\n};\n","import {\n packageSourceSnippet,\n techStackRecommendationsSnippet,\n type AiContextSnippet,\n} from \"@overmux/shared\";\n\nexport {\n packageSourceSnippet,\n techStackRecommendationsSnippet,\n type AiContextSnippet,\n};\nexport type AiContextSnippetDefinition = readonly AiContextSnippet[];\n\nexport const coreAiContextSnippets = [\n packageSourceSnippet,\n] as const satisfies AiContextSnippetDefinition;\nexport const defaultAiContextSnippets = [\n ...coreAiContextSnippets,\n techStackRecommendationsSnippet,\n] as const satisfies AiContextSnippetDefinition;\n\nconst packageSourceSnippetContent = `Overmux ships with documentation and TypeScript source.\n\nRun \\`overmux docs\\` to find the installed documentation and source for the overmux cli.\n\nE.g. \\`node_modules/overmux\\` and \\`node_modules/@overmux/xterm\\`.\n\nInspect these files so guidance matches the versions used by the application.`;\n\nconst techStackRecommendationsSnippetContent = `Prefer pnpm as the package manager, TanStack Router for routing, shadcn/ui for UI components, and Zod for schemas and runtime validation. Follow the application's established stack when it already differs.`;\n\nconst aiContextContentBySnippet: Record<AiContextSnippet, string> = {\n [packageSourceSnippet]: packageSourceSnippetContent,\n [techStackRecommendationsSnippet]: techStackRecommendationsSnippetContent,\n};\n\nexport const composeAiContext = (snippets: AiContextSnippetDefinition) =>\n snippets.length === 0\n ? \"\"\n : `${snippets\n .map(\n (snippet) => `## ${snippet}\\n\\n${aiContextContentBySnippet[snippet]}`,\n )\n .join(\"\\n\\n\")}\\n`;\n","import { z } from \"zod\";\n\nexport const noInputSchema = z.void();\n\nexport const jsonValueSchema: z.ZodType<unknown> = z.lazy(() =>\n z.union([\n z.string(),\n z.number().finite(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(z.string(), jsonValueSchema),\n ]),\n);\n\nexport const parseJsonValue = <T>(value: T): T =>\n jsonValueSchema.parse(value) as T;\n\nexport type ContractInputArguments<TInput extends z.ZodType> =\n undefined extends z.input<TInput>\n ? [input?: Exclude<z.input<TInput>, undefined>]\n : [input: z.input<TInput>];\n\nexport type ResourceContract<\n TInput extends z.ZodType = z.ZodType,\n TOutput extends z.ZodType = z.ZodType,\n> = {\n input: TInput;\n output: TOutput;\n};\n\nexport const defineResourceContract = <\n TInput extends z.ZodType,\n TOutput extends z.ZodType,\n>(\n contract: ResourceContract<TInput, TOutput>,\n): ResourceContract<TInput, TOutput> => contract;\n\nexport type StreamContract<\n TInput extends z.ZodType = z.ZodType,\n TClientMessage extends z.ZodType = z.ZodType,\n TServerMessage extends z.ZodType = z.ZodType,\n> = {\n clientMessage: TClientMessage;\n input: TInput;\n serverMessage: TServerMessage;\n};\n\nexport const defineStreamContract = <\n TInput extends z.ZodType,\n TClientMessage extends z.ZodType,\n TServerMessage extends z.ZodType,\n>(\n contract: StreamContract<TInput, TClientMessage, TServerMessage>,\n): StreamContract<TInput, TClientMessage, TServerMessage> => contract;\n","// Orchestrates operation notifications across live and background delivery.\n// Provider-specific details stay behind the background-notification service.\nimport {\n notificationSchema,\n type Notification,\n type Notifications,\n} from \"../../../public/index\";\n\nimport { errorDetails, type ServerLogger } from \"../server-logger\";\nimport type { BackgroundNotificationService } from \"./background-notification-service\";\n\ntype NotificationService = Notifications & {\n attachLiveDelivery: (deliver: (notification: Notification) => void) => void;\n};\n\nconst deliverSafely = async ({\n deliver,\n event,\n logger,\n}: {\n deliver: () => void | Promise<void>;\n event: string;\n logger?: ServerLogger;\n}) => {\n try {\n await deliver();\n } catch (cause) {\n logger?.log({\n details: errorDetails(cause),\n event,\n level: \"error\",\n });\n }\n};\n\nexport const createNotificationService = ({\n backgroundNotifications,\n logger,\n}: {\n backgroundNotifications: BackgroundNotificationService;\n logger?: ServerLogger;\n}): NotificationService => {\n let liveDeliveryAttached = false;\n let deliverLive: (notification: Notification) => void = () => undefined;\n\n return {\n send: async (input) => {\n const notification = notificationSchema.parse(input);\n await Promise.all([\n deliverSafely({\n deliver: () => deliverLive(notification),\n event: \"live-notification-dispatch-failure\",\n logger,\n }),\n deliverSafely({\n deliver: () => backgroundNotifications.send(notification),\n event: \"background-notification-dispatch-failure\",\n logger,\n }),\n ]);\n },\n attachLiveDelivery: (deliver) => {\n if (liveDeliveryAttached) {\n throw new Error(\"Live delivery is already attached\");\n }\n liveDeliveryAttached = true;\n deliverLive = deliver;\n },\n };\n};\n","// Composes runtime and request cancellation while owning asynchronous cleanup.\n// Tracked disposers run exactly once, and aggregate shutdown reports every failure.\n\nimport type { RuntimeDisposer } from \"../../../public/index\";\n\nexport type RuntimeLifecycle = {\n completePreparation: () => void;\n dispose: (reason?: unknown) => Promise<void>;\n disposeAll: (disposers: Iterable<RuntimeDisposer>) => Promise<void>;\n requestSignal: (signal?: AbortSignal) => AbortSignal;\n signal: AbortSignal;\n track: (dispose: RuntimeDisposer, signal?: AbortSignal) => RuntimeDisposer;\n};\n\nconst asError = (cause: unknown) =>\n cause instanceof Error ? cause : new Error(String(cause));\n\nconst disposeAll = async (disposers: Iterable<RuntimeDisposer>) => {\n const results = await Promise.allSettled(\n [...disposers].map(async (dispose) => dispose()),\n );\n const errors = results.flatMap((result) =>\n result.status === \"rejected\" ? [asError(result.reason)] : [],\n );\n if (errors.length) {\n throw new AggregateError(errors, \"Runtime disposal failed\");\n }\n};\n\nexport const createRuntimeLifecycle = (\n preparationSignal?: AbortSignal,\n): RuntimeLifecycle => {\n const controller = new AbortController();\n const activeDisposers = new Set<RuntimeDisposer>();\n let disposal: Promise<void> | undefined;\n const abortPreparation = () => controller.abort(preparationSignal?.reason);\n preparationSignal?.addEventListener(\"abort\", abortPreparation, {\n once: true,\n });\n if (preparationSignal?.aborted) {\n abortPreparation();\n }\n\n const completePreparation = () => {\n preparationSignal?.removeEventListener(\"abort\", abortPreparation);\n };\n const requestSignal = (signal?: AbortSignal) =>\n signal ? AbortSignal.any([controller.signal, signal]) : controller.signal;\n const track = (\n dispose: RuntimeDisposer,\n signal?: AbortSignal,\n ): RuntimeDisposer => {\n let pending: Promise<void> | undefined;\n const disposeOnce = () => {\n if (pending) {\n return pending;\n }\n controller.signal.removeEventListener(\"abort\", onAbort);\n signal?.removeEventListener(\"abort\", onAbort);\n activeDisposers.delete(disposeOnce);\n pending = Promise.resolve().then(dispose);\n return pending;\n };\n const onAbort = () => {\n void disposeOnce().catch(() => undefined);\n };\n activeDisposers.add(disposeOnce);\n controller.signal.addEventListener(\"abort\", onAbort, { once: true });\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (controller.signal.aborted || signal?.aborted) {\n onAbort();\n }\n return disposeOnce;\n };\n const dispose = (reason: unknown = new Error(\"Runtime disposed\")) => {\n if (disposal) {\n return disposal;\n }\n completePreparation();\n const pending = [...activeDisposers];\n activeDisposers.clear();\n controller.abort(reason);\n disposal = disposeAll(pending);\n return disposal;\n };\n\n return {\n completePreparation,\n dispose,\n disposeAll,\n requestSignal,\n signal: controller.signal,\n track,\n };\n};\n","// Resource invalidation follows relationships among configured resources.\n// This model owns those relationships and their invariants before runtime work begins.\n\nimport type { ResourceDefinition } from \"../../../public/index\";\n\n// A dependency supplies a derived resource's value; a dependant consumes that value.\n// Keeping both directions makes reads follow dependencies while invalidation follows dependants.\nexport type ResourceDependencyGraph = Readonly<{\n dependencies: ReadonlyMap<string, ReadonlySet<string>>;\n dependants: ReadonlyMap<string, ReadonlySet<string>>;\n}>;\n\ntype MutableResourceGraph = Map<string, Set<string>>;\n\nconst emptyGraphFor = (resourceIds: readonly string[]): MutableResourceGraph =>\n new Map(resourceIds.map((resourceId) => [resourceId, new Set<string>()]));\n\nconst visitDependencies = ({\n dependencies,\n path,\n resourceId,\n visited,\n visiting,\n}: {\n dependencies: ReadonlyMap<string, ReadonlySet<string>>;\n path: readonly string[];\n resourceId: string;\n visited: Set<string>;\n visiting: Set<string>;\n}) => {\n if (visiting.has(resourceId)) {\n throw new Error(\n `Resource dependency cycle: ${[...path, resourceId].join(\" -> \")}`,\n );\n }\n if (visited.has(resourceId)) {\n return;\n }\n visiting.add(resourceId);\n dependencies.get(resourceId)?.forEach((dependencyId) => {\n visitDependencies({\n dependencies,\n path: [...path, resourceId],\n resourceId: dependencyId,\n visited,\n visiting,\n });\n });\n visiting.delete(resourceId);\n visited.add(resourceId);\n};\n\nconst assertAcyclic = (\n dependencies: ReadonlyMap<string, ReadonlySet<string>>,\n) => {\n // Derived reads recurse through dependencies, so a cycle could never produce a value or finish activation.\n const visited = new Set<string>();\n const visiting = new Set<string>();\n dependencies.forEach((_, resourceId) => {\n visitDependencies({\n dependencies,\n path: [],\n resourceId,\n visited,\n visiting,\n });\n });\n};\n\nexport const createResourceDependencyGraph = (\n resources: Readonly<Record<string, ResourceDefinition>>,\n): ResourceDependencyGraph => {\n const resourceIds = Object.keys(resources);\n if (resourceIds.some((resourceId) => !resourceId)) {\n throw new Error(\"Resource IDs must not be empty\");\n }\n const dependencies = emptyGraphFor(resourceIds);\n const dependants = emptyGraphFor(resourceIds);\n\n Object.entries(resources).forEach(([resourceId, resource]) => {\n if (resource.kind !== \"derived\") {\n return;\n }\n Object.entries(\n resource.dependencies as Readonly<Record<string, string>>,\n ).forEach(([dependencyName, dependencyId]) => {\n if (!dependencyName) {\n throw new Error(`Resource ${resourceId} has an empty dependency name`);\n }\n if (!dependencyId) {\n throw new Error(`Resource ${resourceId} has an empty dependency ID`);\n }\n if (!dependencies.has(dependencyId)) {\n throw new Error(`Unknown resource dependency: ${dependencyId}`);\n }\n dependencies.get(resourceId)?.add(dependencyId);\n dependants.get(dependencyId)?.add(resourceId);\n });\n });\n\n assertAcyclic(dependencies);\n return Object.freeze({ dependencies, dependants });\n};\n\nconst collectInvalidatedResourceIds = (\n graph: ResourceDependencyGraph,\n resourceId: string,\n invalidated: Set<string>,\n) => {\n if (invalidated.has(resourceId)) {\n return;\n }\n invalidated.add(resourceId);\n graph.dependants.get(resourceId)?.forEach((dependantId) => {\n collectInvalidatedResourceIds(graph, dependantId, invalidated);\n });\n};\n\nexport const getInvalidatedResourceIds = (\n graph: ResourceDependencyGraph,\n resourceId: string,\n): ReadonlySet<string> => {\n // A changed value invalidates itself and the full reverse-edge closure, not just immediate consumers.\n // Set membership is essential for diamonds: a shared dependant must notify once despite multiple paths.\n const invalidated = new Set<string>();\n collectInvalidatedResourceIds(graph, resourceId, invalidated);\n return invalidated;\n};\n","// Owns named runtime resource lookup, validated reads, dependency watchers, and invalidation.\n\nimport {\n type HandlerContext,\n type ResourceDefinition,\n type RuntimeDisposer,\n} from \"../../../public/index\";\nimport type { ResourceContract } from \"../../../public/index\";\nimport { isDeepStrictEqual } from \"node:util\";\n\nimport {\n createResourceDependencyGraph,\n getInvalidatedResourceIds,\n} from \"./resource-dependency-graph\";\nimport type { RuntimeLifecycle } from \"./runtime-lifecycle\";\n\nexport type RuntimeResource = {\n read: (input: unknown, signal?: AbortSignal) => Promise<unknown>;\n subscribe: (\n input: unknown,\n listener: () => void,\n signal?: AbortSignal,\n ) => RuntimeDisposer;\n};\n\nexport type RuntimeResourceDefinitions = Readonly<\n Record<string, ResourceDefinition>\n>;\n\nexport type RuntimeResources = {\n context: (signal?: AbortSignal) => HandlerContext;\n get: (name: string) => RuntimeResource | undefined;\n invalidate: (contract: ResourceContract, input?: unknown) => void;\n names: readonly string[];\n};\n\ntype InvalidationListener = {\n input: unknown;\n listener: () => void;\n resourceId: string;\n};\n\ntype CreateRuntimeResourcesOptions = {\n definitions: RuntimeResourceDefinitions;\n lifecycle: RuntimeLifecycle;\n};\n\nexport const createRuntimeResources = ({\n definitions,\n lifecycle,\n}: CreateRuntimeResourcesOptions): RuntimeResources => {\n const graph = createResourceDependencyGraph(definitions);\n const invalidationListeners = new Set<InvalidationListener>();\n const contracts = new Map<ResourceContract, string[]>();\n const resources = new Map<string, RuntimeResource>();\n\n Object.entries(definitions).forEach(([id, definition]) => {\n contracts.set(definition.contract, [\n ...(contracts.get(definition.contract) ?? []),\n id,\n ]);\n });\n\n const invalidateResource = (\n id: string,\n input: unknown,\n allInputs = false,\n ) => {\n if (lifecycle.signal.aborted) {\n return;\n }\n const ids = getInvalidatedResourceIds(graph, id);\n invalidationListeners.forEach((entry) => {\n if (\n ids.has(entry.resourceId) &&\n (allInputs || isDeepStrictEqual(entry.input, input))\n ) {\n entry.listener();\n }\n });\n };\n\n const invalidate = (contract: ResourceContract, input?: unknown) => {\n const ids =\n contracts.get(contract) ??\n Object.entries(definitions)\n .filter(\n ([, definition]) =>\n definition.contract.input === contract.input &&\n definition.contract.output === contract.output,\n )\n .map(([id]) => id);\n if (!ids.length) {\n throw new Error(\"Cannot invalidate a resource outside this runtime\");\n }\n ids.forEach((id) => {\n const definition = definitions[id]!;\n const parsedInput =\n input === undefined\n ? undefined\n : definition.contract.input.parse(input);\n invalidateResource(id, parsedInput, input === undefined);\n });\n };\n\n const context = (signal?: AbortSignal): HandlerContext => ({\n invalidate,\n signal: lifecycle.requestSignal(signal),\n });\n\n const read = async (\n id: string,\n rawInput: unknown,\n signal?: AbortSignal,\n ): Promise<unknown> => {\n const definition = definitions[id]!;\n const operationSignal = lifecycle.requestSignal(signal);\n operationSignal.throwIfAborted();\n const input = definition.contract.input.parse(rawInput);\n const rawOutput =\n definition.kind === \"derived\"\n ? definition.combine(\n Object.fromEntries(\n await Promise.all(\n Object.entries(\n definition.dependencies as Readonly<Record<string, string>>,\n ).map(async ([name, dependencyId]) => [\n name,\n await read(dependencyId, rawInput, signal),\n ]),\n ),\n ),\n )\n : await definition.read(input, context(signal));\n operationSignal.throwIfAborted();\n return definition.contract.output.parse(rawOutput);\n };\n\n const activateWatchers = (\n id: string,\n rawInput: unknown,\n signal: AbortSignal | undefined,\n activated: Set<string>,\n disposers: RuntimeDisposer[],\n ) => {\n if (activated.has(id)) {\n return;\n }\n activated.add(id);\n const definition = definitions[id]!;\n const input = definition.contract.input.parse(rawInput);\n if (definition.kind === \"subscription\") {\n const dispose = definition.subscribe(\n input,\n () => invalidateResource(id, input),\n context(signal),\n );\n if (typeof dispose !== \"function\") {\n throw new Error(`Resource ${id} subscribe must return a disposer`);\n }\n disposers.push(dispose);\n return;\n }\n if (definition.kind === \"derived\") {\n graph.dependencies.get(id)?.forEach((dependencyId) => {\n activateWatchers(dependencyId, rawInput, signal, activated, disposers);\n });\n }\n };\n\n Object.keys(definitions).forEach((name) => {\n resources.set(name, {\n read: (input, signal) => read(name, input, signal),\n subscribe: (rawInput, listener, signal) => {\n lifecycle.requestSignal(signal).throwIfAborted();\n const input = definitions[name]!.contract.input.parse(rawInput);\n const entry = { input, listener, resourceId: name };\n const watcherDisposers: RuntimeDisposer[] = [];\n invalidationListeners.add(entry);\n try {\n activateWatchers(name, rawInput, signal, new Set(), watcherDisposers);\n } catch (cause) {\n invalidationListeners.delete(entry);\n void lifecycle.disposeAll(watcherDisposers).catch(() => undefined);\n throw cause;\n }\n return lifecycle.track(async () => {\n invalidationListeners.delete(entry);\n await lifecycle.disposeAll(watcherDisposers);\n }, signal);\n },\n });\n });\n\n return {\n context,\n get: (name) => resources.get(name),\n invalidate,\n names: [...resources.keys()],\n };\n};\n","// Owns named stream registration and ordered, validated session messaging.\n// Session abort, failure, and disposal remain exactly-once across every close path.\n\nimport type {\n HandlerContext,\n StreamHandlerDefinition,\n} from \"../../../public/index\";\nimport { z } from \"zod\";\n\nimport type { RuntimeLifecycle } from \"./runtime-lifecycle\";\n\nexport type RuntimeStreamSession = {\n dispose: () => Promise<void>;\n send: (message: unknown) => Promise<void>;\n};\n\nexport type RuntimeStream = {\n open: (\n input: unknown,\n emit: (message: unknown) => void,\n signal?: AbortSignal,\n onError?: (cause: unknown) => void,\n ) => Promise<RuntimeStreamSession>;\n};\n\nexport type RuntimeStreams = {\n get: (name: string) => RuntimeStream | undefined;\n names: readonly string[];\n};\n\ntype AnyStream = StreamHandlerDefinition<\n z.ZodTypeAny,\n z.ZodTypeAny,\n z.ZodTypeAny\n>;\n\nexport type RuntimeStreamDefinitions = Readonly<Record<string, AnyStream>>;\n\ntype CreateRuntimeStreamsOptions = {\n context: (signal?: AbortSignal) => HandlerContext;\n definitions: RuntimeStreamDefinitions;\n lifecycle: RuntimeLifecycle;\n};\n\nexport const createRuntimeStreams = ({\n context,\n definitions,\n lifecycle,\n}: CreateRuntimeStreamsOptions): RuntimeStreams => {\n const streams = new Map<string, RuntimeStream>();\n Object.entries(definitions).forEach(([name, definition]) => {\n if (!name) {\n throw new Error(\"Stream names must not be empty\");\n }\n streams.set(name, {\n open: async (rawInput, emit, requestSignal, onError) => {\n const sessionController = new AbortController();\n const sessionSignal = requestSignal\n ? AbortSignal.any([requestSignal, sessionController.signal])\n : sessionController.signal;\n const operationSignal = lifecycle.requestSignal(sessionSignal);\n operationSignal.throwIfAborted();\n const input = definition.contract.input.parse(rawInput);\n let acceptingMessages = true;\n let failed = false;\n let failure: unknown;\n let opened = false;\n const fail = (cause: unknown) => {\n if (failed || operationSignal.aborted) {\n return;\n }\n failed = true;\n failure = cause;\n acceptingMessages = false;\n sessionController.abort(cause);\n if (opened) {\n onError?.(cause);\n }\n };\n const session = await definition.open(input, {\n ...context(sessionSignal),\n emit: (message) => {\n if (operationSignal.aborted) {\n return;\n }\n try {\n emit(definition.contract.serverMessage.parse(message));\n } catch (cause) {\n fail(cause);\n }\n },\n fail,\n signal: operationSignal,\n });\n opened = true;\n if (failed || operationSignal.aborted) {\n await session.dispose?.();\n operationSignal.throwIfAborted();\n throw failure;\n }\n let messages = Promise.resolve();\n const dispose = lifecycle.track(async () => {\n acceptingMessages = false;\n sessionController.abort(new Error(\"Stream session disposed\"));\n await messages.catch(() => undefined);\n await session.dispose?.();\n }, requestSignal);\n return {\n dispose: async () => dispose(),\n send: async (rawMessage) => {\n if (!acceptingMessages) {\n throw new Error(\"Stream session is closed\");\n }\n const message = definition.contract.clientMessage.parse(rawMessage);\n messages = messages.then(async () => {\n operationSignal.throwIfAborted();\n await session.onMessage?.(message);\n operationSignal.throwIfAborted();\n });\n return messages;\n },\n };\n },\n });\n });\n return {\n get: (name) => streams.get(name),\n names: [...streams.keys()],\n };\n};\n","// Composes one process-lifetime runtime from cohesive lifecycle and protocol components.\n\nimport type { RuntimeConfigDefinition } from \"@overmux/shared/node\";\n\nimport type { Notifications } from \"../../../public/index\";\nimport { protocolVersion, type RuntimeManifest } from \"../../shared/index\";\n\nimport { createRuntimeLifecycle } from \"./runtime-lifecycle\";\nimport {\n createRuntimeOperations,\n type RuntimeOperation,\n type RuntimeOperationDefinitions,\n} from \"./runtime-operations\";\nimport {\n createRuntimeResources,\n type RuntimeResource,\n type RuntimeResourceDefinitions,\n} from \"./runtime-resources\";\nimport {\n createRuntimeStreams,\n type RuntimeStream,\n type RuntimeStreamDefinitions,\n} from \"./runtime-streams\";\n\nexport type Runtime = {\n manifest: RuntimeManifest;\n dispose: () => Promise<void>;\n getOperation: (name: string) => RuntimeOperation | undefined;\n getResource: (name: string) => RuntimeResource | undefined;\n getStream: (name: string) => RuntimeStream | undefined;\n};\n\ntype CreateRuntimeOptions = {\n config: RuntimeConfigDefinition;\n debug?: boolean;\n notifications?: Notifications;\n signal?: AbortSignal;\n};\n\nexport const createRuntime = async ({\n config,\n debug = false,\n notifications = { send: async () => undefined },\n signal,\n}: CreateRuntimeOptions): Promise<Runtime> => {\n const lifecycle = createRuntimeLifecycle(signal);\n try {\n const resources = createRuntimeResources({\n definitions: (config.server.resources ??\n {}) as RuntimeResourceDefinitions,\n lifecycle,\n });\n const context = resources.context;\n const operations = createRuntimeOperations({\n context,\n definitions: (config.server.operations ??\n {}) as RuntimeOperationDefinitions,\n notifications,\n });\n const streams = createRuntimeStreams({\n context,\n definitions: (config.server.streams ?? {}) as RuntimeStreamDefinitions,\n lifecycle,\n });\n\n lifecycle.signal.throwIfAborted();\n lifecycle.completePreparation();\n\n const manifest: RuntimeManifest = {\n debug,\n operations: [...operations.names],\n protocolVersion,\n resources: [...resources.names],\n streams: [...streams.names],\n };\n return {\n manifest,\n dispose: lifecycle.dispose,\n getOperation: operations.get,\n getResource: resources.get,\n getStream: streams.get,\n };\n } catch (cause) {\n await lifecycle.dispose(cause).catch(() => undefined);\n throw cause;\n }\n};\n","import {\n serverConfigRuntimeSchema,\n type RuntimeConfigDefinition,\n} from \"@overmux/shared/node\";\nimport { dirname, resolve } from \"node:path\";\nimport { z } from \"zod\";\n\nimport type { ServerConfigDefinition } from \"../../public/index\";\n\nexport type ResolvedServerStartupOptions = {\n host: string;\n logFile?: string;\n port: number;\n productionWebAssetsDir?: string;\n watch: boolean;\n};\n\nexport const resolveServerStartupOptions = ({\n config,\n configPath,\n overrides = {},\n}: {\n config: RuntimeConfigDefinition;\n configPath: string;\n overrides?: ServerConfigDefinition;\n}): ResolvedServerStartupOptions => {\n const validatedOverrides = serverConfigRuntimeSchema\n .omit({ port: true })\n .extend({ port: z.number().int().min(0).max(65_535).optional() })\n .parse(overrides);\n const configuredLogFile = config.logFile\n ? resolve(dirname(configPath), config.logFile)\n : undefined;\n const logFile = validatedOverrides.logFile\n ? resolve(validatedOverrides.logFile)\n : configuredLogFile;\n const configuredWebAssetsDir = config.productionWebAssetsDir\n ? resolve(dirname(configPath), config.productionWebAssetsDir)\n : undefined;\n const productionWebAssetsDir = validatedOverrides.productionWebAssetsDir\n ? resolve(validatedOverrides.productionWebAssetsDir)\n : configuredWebAssetsDir;\n\n return {\n host: validatedOverrides.host ?? config.host ?? \"localhost\",\n ...(logFile === undefined ? {} : { logFile }),\n port: validatedOverrides.port ?? config.port ?? 4200,\n ...(productionWebAssetsDir === undefined ? {} : { productionWebAssetsDir }),\n watch: validatedOverrides.watch ?? config.watch ?? true,\n };\n};\n","// Starts one immutable application runtime inside the supervised child process.\n// It owns config loading, transport, and the listening socket.\n\nimport { serve, type ServerType as NodeServer } from \"@hono/node-server\";\nimport {\n loadOvermuxConfig,\n type RuntimeConfigDefinition,\n} from \"@overmux/shared/node\";\nimport { once } from \"node:events\";\nimport type { AddressInfo } from \"node:net\";\nimport { resolve } from \"node:path\";\n\nimport { createAuthService, type AuthService } from \"./auth/auth-service\";\nimport {\n createAuthBoundary,\n validateAuthOrigin,\n type AuthBoundary,\n} from \"./auth/auth-http\";\nimport { startInstanceControl } from \"./auth/instance-control\";\nimport { createHttpApp } from \"./http/create-http-app\";\nimport { createWebSocketServer } from \"./websocket-server\";\nimport {\n createBackgroundNotificationService,\n type BackgroundNotificationService,\n} from \"./notifications/background-notification-service\";\nimport { createFileBackgroundNotificationStore } from \"./notifications/background-notification-store\";\nimport { createNotificationService } from \"./notifications/notification-service\";\nimport { createRuntime, type Runtime } from \"./runtime/create-runtime\";\nimport {\n createServerLogger,\n errorDetails,\n type ServerLogger,\n} from \"./server-logger\";\nimport {\n resolveServerStartupOptions,\n type ResolvedServerStartupOptions,\n} from \"./server-startup-options\";\nimport type { OvermuxServerOptions } from \"./start-overmux-server\";\n\ntype ResourceCleanup = () => void | Promise<void>;\ntype ServerResources = ReturnType<typeof createResources>;\ntype NotificationService = ReturnType<typeof createNotificationService>;\ntype ApplicationLogger = ReturnType<typeof createServerLogger>;\ntype StartApplicationServerOptions = {\n onRestartRequested: () => void;\n options: OvermuxServerOptions;\n};\n\nexport type ApplicationServer = {\n announceUpdateAvailable: () => void;\n close: () => Promise<void>;\n host: string;\n port: number;\n url: string;\n watch: boolean;\n};\n\nconst cleanupResources = async (cleanups: ResourceCleanup[]) => {\n const errors: unknown[] = [];\n for (const cleanup of [...cleanups].reverse()) {\n try {\n await cleanup();\n } catch (cause) {\n errors.push(cause);\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Failed to clean up server resources\");\n }\n};\n\nconst createResources = () => {\n const cleanups: ResourceCleanup[] = [];\n let closePromise: Promise<void> | undefined;\n return {\n add: (cleanup: ResourceCleanup) => cleanups.push(cleanup),\n close: () => {\n const next = closePromise ?? cleanupResources(cleanups);\n closePromise = next;\n return next;\n },\n };\n};\n\nconst closeNodeServer = (\n server: NodeServer,\n cancelActiveWork: () => Promise<void>,\n): Promise<void> => {\n const closed = new Promise<void>((resolveClose, reject) => {\n server.close((error) => {\n if (\n error &&\n (error as NodeJS.ErrnoException).code !== \"ERR_SERVER_NOT_RUNNING\"\n ) {\n reject(error);\n return;\n }\n resolveClose();\n });\n });\n const cancellation = cancelActiveWork();\n if (\"closeAllConnections\" in server) {\n server.closeAllConnections();\n }\n return Promise.all([closed, cancellation]).then(() => undefined);\n};\n\nconst getServerAddress = async (server: NodeServer): Promise<AddressInfo> => {\n if (!server.address()) {\n await once(server, \"listening\");\n }\n const address = server.address();\n if (!address || typeof address === \"string\") {\n throw new Error(\"Overmux server did not bind a TCP address\");\n }\n return address;\n};\n\nconst registerProcessErrorLogging = (logger: ServerLogger) => {\n const onUncaughtException = (\n cause: Error,\n origin: \"uncaughtException\" | \"unhandledRejection\",\n ) =>\n logger.log({\n details: errorDetails(cause),\n event:\n origin === \"unhandledRejection\"\n ? \"unhandled-rejection\"\n : \"uncaught-exception\",\n level: \"error\",\n });\n process.on(\"uncaughtExceptionMonitor\", onUncaughtException);\n return () => {\n process.off(\"uncaughtExceptionMonitor\", onUncaughtException);\n };\n};\n\nconst loadServerSettings = async ({\n configPath,\n options,\n}: {\n configPath: string;\n options: OvermuxServerOptions;\n}) => {\n const { config } = await loadOvermuxConfig({\n aliases: options.configAliases,\n configPath,\n });\n const startup = resolveServerStartupOptions({\n config,\n configPath,\n overrides: options,\n });\n return { config, startup };\n};\n\nconst createAuthOrigins = ({\n configuredOrigins,\n startup,\n}: {\n configuredOrigins?: string[];\n startup: ResolvedServerStartupOptions;\n}) => {\n const urlHost = startup.host.includes(\":\")\n ? `[${startup.host}]`\n : startup.host;\n let values = (configuredOrigins ?? [`http://${urlHost}:${startup.port}`]).map(\n validateAuthOrigin,\n );\n return {\n establish: (localUrl: string) => {\n values = (configuredOrigins ?? [localUrl]).map(validateAuthOrigin);\n return values;\n },\n get: () => values,\n };\n};\n\nconst createApplicationServices = async ({\n config,\n logger,\n resources,\n startup,\n}: {\n config: RuntimeConfigDefinition;\n logger: ServerLogger;\n resources: ServerResources;\n startup: ResolvedServerStartupOptions;\n}) => {\n // Browser origins are fixed from trusted startup data, never discovered from\n // requests. Ephemeral listener ports are finalized after binding.\n const authOrigins = createAuthOrigins({\n configuredOrigins: config.auth.origins,\n startup,\n });\n const authService = createAuthService({ config: config.auth });\n const auth = createAuthBoundary({\n origins: authOrigins.get,\n service: authService,\n trustedProxyPeer: config.auth.trustedProxyPeer,\n });\n const backgroundNotifications = createBackgroundNotificationService({\n isSessionActive: authService.isSessionActive,\n logger,\n store: createFileBackgroundNotificationStore(),\n });\n // Background subscriptions belong to browser sessions, so revocation also\n // removes delivery credentials owned by those sessions.\n resources.add(\n authService.onSessionsRevoked((sessionIds) => {\n void backgroundNotifications\n .disableSessions(sessionIds)\n .catch((cause: unknown) => {\n logger.log({\n details: errorDetails(cause),\n event: \"background-notification-session-cleanup-failed\",\n level: \"error\",\n });\n });\n }),\n );\n const notifications = createNotificationService({\n backgroundNotifications,\n logger,\n });\n const runtime = await createRuntime({\n config,\n debug: logger.enabled,\n notifications,\n });\n resources.add(runtime.dispose);\n return {\n auth,\n authOrigins,\n authService,\n backgroundNotifications,\n notifications,\n runtime,\n };\n};\n\nconst startApplicationTransport = async ({\n auth,\n authOrigins,\n authService,\n backgroundNotifications,\n developmentWebTarget,\n logger,\n notifications,\n onRestartRequested,\n resources,\n runtime,\n startup,\n}: {\n auth: AuthBoundary;\n authOrigins: ReturnType<typeof createAuthOrigins>;\n authService: AuthService;\n backgroundNotifications: BackgroundNotificationService;\n developmentWebTarget?: string;\n logger: ServerLogger;\n notifications: NotificationService;\n onRestartRequested: () => void;\n resources: ServerResources;\n runtime: Runtime;\n startup: ResolvedServerStartupOptions;\n}) => {\n let announceRestarting: () => void = () => undefined;\n const app = createHttpApp({\n auth,\n backgroundNotifications,\n developmentWebTarget,\n onRestartRequested: () => {\n announceRestarting();\n onRestartRequested();\n },\n runtime,\n serverLogger: logger,\n webAssetsDir: developmentWebTarget\n ? undefined\n : startup.productionWebAssetsDir,\n });\n const server = serve({\n fetch: app.fetch,\n hostname: startup.host,\n port: startup.port,\n });\n resources.add(() => closeNodeServer(server, runtime.dispose));\n const webSockets = createWebSocketServer({\n auth,\n developmentWebTarget,\n runtime,\n server,\n serverLogger: logger,\n });\n resources.add(webSockets.close);\n announceRestarting = webSockets.announceRestarting;\n notifications.attachLiveDelivery(webSockets.broadcastNotification);\n\n const address = await getServerAddress(server);\n const urlHost = startup.host.includes(\":\")\n ? `[${startup.host}]`\n : startup.host;\n const localUrl = `http://${urlHost}:${address.port}`;\n const controlApiHost =\n startup.host === \"0.0.0.0\"\n ? \"127.0.0.1\"\n : startup.host === \"::\"\n ? \"[::1]\"\n : urlHost;\n const origins = authOrigins.establish(localUrl);\n authService.setOrigins(origins);\n const instanceControl = await startInstanceControl({\n auth: authService,\n apiUrl: `http://${controlApiHost}:${address.port}`,\n port: address.port,\n url: origins[0]!,\n });\n resources.add(instanceControl.close);\n return { address, app, localUrl, webSockets };\n};\n\nconst closeApplicationServer = async ({\n app,\n logger,\n resources,\n}: {\n app: ReturnType<typeof createHttpApp>;\n logger: ServerLogger;\n resources: ServerResources;\n}) => {\n logger.log({ event: \"server-stop\" });\n app.beginShutdown();\n await resources.close();\n};\n\nconst failApplicationServerStartup = async (\n cause: unknown,\n resources: ServerResources,\n): Promise<never> => {\n try {\n await resources.close();\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Server startup and cleanup failed\",\n );\n }\n throw cause;\n};\n\nexport const startApplicationServer = async ({\n onRestartRequested,\n options,\n}: StartApplicationServerOptions): Promise<ApplicationServer> => {\n const logger = createServerLogger({\n enabled: options.debug ?? false,\n logFile: options.logFile ? resolve(options.logFile) : undefined,\n });\n const resources = createResources();\n resources.add(registerProcessErrorLogging(logger));\n\n try {\n const configPath = resolve(options.configPath);\n logger.log({ details: { configPath }, event: \"server-start\" });\n const { config, startup } = await loadServerSettings({\n configPath,\n options,\n });\n logger.setEnabled(Boolean(options.debug || config.debug));\n if (startup.logFile) {\n logger.setLogFile(startup.logFile);\n }\n const {\n auth,\n authOrigins,\n authService,\n backgroundNotifications,\n notifications,\n runtime,\n } = await createApplicationServices({\n config,\n logger,\n resources,\n startup,\n });\n const { address, app, localUrl, webSockets } =\n await startApplicationTransport({\n auth,\n authOrigins,\n authService,\n backgroundNotifications,\n developmentWebTarget: options.developmentWebTarget,\n logger,\n notifications,\n onRestartRequested,\n resources,\n runtime,\n startup,\n });\n\n return {\n announceUpdateAvailable: webSockets.announceUpdateAvailable,\n close: () => closeApplicationServer({ app, logger, resources }),\n host: startup.host,\n port: address.port,\n url: localUrl,\n watch: startup.watch,\n };\n } catch (cause) {\n return failApplicationServerStartup(cause, resources);\n }\n};\n","// Defines the complete validated IPC boundary between coordinator and child.\n// Application traffic never crosses this process boundary.\n\nimport { z } from \"zod\";\n\nconst childOptionsSchema = z.object({\n configAliases: z.record(z.string(), z.string()).optional(),\n configPath: z.string(),\n debug: z.boolean().optional(),\n developmentWebTarget: z.url().optional(),\n host: z.string().optional(),\n logFile: z.string().optional(),\n port: z.number().int().min(0).max(65_535).optional(),\n productionWebAssetsDir: z.string().optional(),\n watch: z.boolean().optional(),\n});\n\nconst parentMessageSchema = z.discriminatedUnion(\"type\", [\n z.object({ options: childOptionsSchema, type: z.literal(\"start\") }),\n z.object({ type: z.literal(\"update-available\") }),\n z.object({ type: z.literal(\"stop\") }),\n]);\n\nconst childMessageSchema = z.discriminatedUnion(\"type\", [\n z.object({\n host: z.string(),\n port: z.number().int().min(1).max(65_535),\n type: z.literal(\"ready\"),\n url: z.string(),\n watch: z.boolean(),\n }),\n z.object({ type: z.literal(\"restart-requested\") }),\n z.object({ message: z.string(), type: z.literal(\"startup-failed\") }),\n]);\n\nexport type ChildServerOptions = z.infer<typeof childOptionsSchema>;\nexport type ParentToChildMessage = z.infer<typeof parentMessageSchema>;\nexport type ChildToParentMessage = z.infer<typeof childMessageSchema>;\n\nexport const parseParentMessage = (value: unknown): ParentToChildMessage =>\n parentMessageSchema.parse(value);\n\nexport const parseChildMessage = (value: unknown): ChildToParentMessage =>\n childMessageSchema.parse(value);\n","// Executable entry for one fresh application-server child process.\n// It translates lifecycle IPC only and never retains state across restarts.\n\nimport { startApplicationServer } from \"../start-application-server\";\nimport { errorMessage } from \"../server-logger\";\nimport { parseParentMessage, type ChildToParentMessage } from \"./ipc-protocol\";\n\nconst send = (message: ChildToParentMessage) => {\n if (!process.connected) {\n return;\n }\n try {\n process.send?.(message, () => undefined);\n } catch {}\n};\n\nconst disconnect = () => {\n if (!process.connected) {\n return;\n }\n try {\n process.disconnect();\n } catch {}\n};\n\nconst runServerChild = () => {\n let serverPromise: ReturnType<typeof startApplicationServer> | undefined;\n let closing: Promise<void> | undefined;\n\n const close = () => {\n if (closing) {\n return closing;\n }\n closing =\n serverPromise?.then(\n (server) => server.close(),\n () => undefined,\n ) ?? Promise.resolve();\n return closing;\n };\n\n process.on(\"message\", (raw) => {\n let message;\n try {\n message = parseParentMessage(raw);\n } catch (cause) {\n send({ message: errorMessage(cause), type: \"startup-failed\" });\n return;\n }\n if (message.type === \"update-available\") {\n if (!closing) {\n void serverPromise?.then(\n (server) => server.announceUpdateAvailable(),\n () => undefined,\n );\n }\n return;\n }\n if (message.type === \"stop\") {\n void close()\n .catch((cause: unknown) => {\n process.stderr.write(\n `[overmux] child shutdown failed: ${errorMessage(cause)}\\n`,\n );\n })\n .finally(disconnect);\n return;\n }\n if (serverPromise || closing) {\n send({\n message: \"Server child received more than one start request\",\n type: \"startup-failed\",\n });\n return;\n }\n serverPromise = startApplicationServer({\n onRestartRequested: () => send({ type: \"restart-requested\" }),\n options: message.options,\n });\n void serverPromise\n .then((server) => {\n if (closing) {\n return;\n }\n send({\n host: server.host,\n port: server.port,\n type: \"ready\",\n url: server.url,\n watch: server.watch,\n });\n })\n .catch((cause: unknown) => {\n send({ message: errorMessage(cause), type: \"startup-failed\" });\n disconnect();\n });\n });\n\n process.once(\"disconnect\", () => {\n void close().catch((cause: unknown) => {\n process.stderr.write(\n `[overmux] disconnected child shutdown failed: ${errorMessage(cause)}\\n`,\n );\n });\n });\n};\n\nrunServerChild();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAOA,MAAMA,oBAAkB;AACxB,MAAMC,uBAAqB;CAC1B,GAAG,OAAO,KAAK;CACf,GAAG,OAAO;CACV,GAAG,KAAK;CACR,IAAI;CACJ,GAAG;AACJ;AACA,MAAMC,4BAA0B,aAAa;CAC5C,MAAM,QAAQF,kBAAgB,KAAK,QAAQ;CAC3C,IAAI,CAAC,OAAO;CACZ,MAAM,OAAO,MAAM;CACnB,MAAM,eAAe,OAAO,MAAM,EAAE,IAAIC,qBAAmB;CAC3D,OAAO,OAAO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ACd,KAAK;IAAE,SAAS,aAAa,KAAK;IAAG,MAAM;GAAiB,CAAC;GAC7D;EACF;EACA,IAAI,QAAQ,SAAS,oBAAoB;GACvC,IAAI,CAAC,SACH,eAAoB,MACjB,WAAW,OAAO,wBAAwB,SACrC,KAAA,CACR;GAEF;EACF;EACA,IAAI,QAAQ,SAAS,QAAQ;GAC3B,MAAW,CAAC,CACT,OAAO,UAAmB;IACzB,QAAQ,OAAO,MACb,oCAAoC,aAAa,KAAK,EAAE,GAC1D;GACF,CAAC,CAAC,CACD,QAAQ,UAAU;GACrB;EACF;EACA,IAAI,iBAAiB,SAAS;GAC5B,KAAK;IACH,SAAS;IACT,MAAM;GACR,CAAC;GACD;EACF;EACA,gBAAgB,uBAAuB;GACrC,0BAA0B,KAAK,EAAE,MAAM,oBAAoB,CAAC;GAC5D,SAAS,QAAQ;EACnB,CAAC;EACD,cACG,MAAM,WAAW;GAChB,IAAI,SACF;GAEF,KAAK;IACH,MAAM,OAAO;IACb,MAAM,OAAO;IACb,MAAM;IACN,KAAK,OAAO;IACZ,OAAO,OAAO;GAChB,CAAC;EACH,CAAC,CAAC,CACD,OAAO,UAAmB;GACzB,KAAK;IAAE,SAAS,aAAa,KAAK;IAAG,MAAM;GAAiB,CAAC;GAC7D,WAAW;EACb,CAAC;CACL,CAAC;CAED,QAAQ,KAAK,oBAAoB;EAC/B,MAAW,CAAC,CAAC,OAAO,UAAmB;GACrC,QAAQ,OAAO,MACb,iDAAiD,aAAa,KAAK,EAAE,GACvE;EACF,CAAC;CACH,CAAC;AACH;AAEA,eAAe"}
1
+ {"version":3,"file":"server-child.js","names":["durationPattern","millisecondsByUnit","durationToMilliseconds","instanceIdSchema","isLoopbackHostname","loginGrantSchema","parseCookie","errorDetails","errorDetails","send","diagnosticErrorDetails","diagnosticErrorDetails","diagnosticErrorDetails","errorDetails","errorDetails","errorDetails"],"sources":["../../../../../shared/dist/node/index.js","../../../../../lib/dist/index.js","../../../../src/internal/server/notifications/private-json-file.ts","../../../../src/internal/server/auth/auth-service.ts","../../../../src/internal/server/rate-limiter.ts","../../../../src/internal/server/auth/auth-shell-http.ts","../../../../src/internal/server/auth/auth-http.ts","../../../../../shared/dist/index.js","../../../../src/internal/server/auth/instance-control.ts","../../../../src/internal/shared/background-notifications.ts","../../../../src/internal/shared/protocol.ts","../../../../src/internal/server/http/background-notification-handlers.ts","../../../../src/internal/server/server-logger.ts","../../../../src/internal/server/http/development-web-backend.ts","../../../../src/internal/server/http/control-handlers.ts","../../../../src/internal/server/runtime/runtime-operations.ts","../../../../src/internal/server/http/operation-handler.ts","../../../../src/internal/server/http/request-logging.ts","../../../../src/internal/server/http/runtime-manifest-handler.ts","../../../../src/internal/shared/routes.ts","../../../../src/internal/server/http/routes.ts","../../../../src/internal/server/http/create-http-app.ts","../../../../src/internal/server/websocket-limits.ts","../../../../src/internal/server/websocket-connection.ts","../../../../src/internal/server/vite-websocket-proxy.ts","../../../../src/internal/server/websocket-server.ts","../../../../src/internal/server/notifications/background-notification-payload.ts","../../../../src/internal/server/notifications/background-notification-service.ts","../../../../src/internal/server/notifications/background-notification-store.ts","../../../../src/public/ai-context.ts","../../../../src/public/contracts.ts","../../../../src/internal/server/notifications/notification-service.ts","../../../../src/internal/server/runtime/runtime-instance.ts","../../../../src/internal/server/runtime/runtime-lifecycle.ts","../../../../src/internal/server/runtime/resource-dependency-graph.ts","../../../../src/internal/server/runtime/runtime-resources.ts","../../../../src/internal/server/runtime/runtime-streams.ts","../../../../src/internal/server/runtime/create-runtime.ts","../../../../src/internal/server/server-startup-options.ts","../../../../src/internal/server/start-application-server.ts","../../../../src/internal/server/coordinator/ipc-protocol.ts","../../../../src/internal/server/coordinator/server-child.ts"],"sourcesContent":["import { realpath } from \"node:fs/promises\";\nimport { isIP } from \"node:net\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { createJiti } from \"jiti\";\nimport { z } from \"zod\";\nimport { homedir } from \"node:os\";\n//#region ../lib/dist/index.js\nconst durationPattern = /^([1-9]\\d*)(ms|s|m|h|d)$/;\nconst millisecondsByUnit = {\n\td: 1440 * 60 * 1e3,\n\th: 3600 * 1e3,\n\tm: 60 * 1e3,\n\tms: 1,\n\ts: 1e3\n};\nconst durationToMilliseconds = (duration) => {\n\tconst match = durationPattern.exec(duration);\n\tif (!match) return;\n\tconst unit = match[2];\n\tconst milliseconds = Number(match[1]) * millisecondsByUnit[unit];\n\treturn Number.isSafeInteger(milliseconds) ? milliseconds : void 0;\n};\nconst aiContextSnippets = [\"package-source\", \"tech-stack-recommendations\"];\n//#endregion\n//#region src/instance.ts\nconst instanceIdSchema = z.string().max(253).regex(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?![\\s\\S])/, \"Expected a lowercase instance ID with only ASCII letters, digits, internal dots and hyphens\");\n//#endregion\n//#region src/node/config.ts\nconst zodTypeSchema = z.custom((value) => value instanceof z.ZodType, \"Expected a Zod schema\");\nconst functionSchema = z.custom((value) => typeof value === \"function\", \"Expected a function\");\nconst contractRuntimeSchema = z.object({\n\tinput: zodTypeSchema,\n\toutput: zodTypeSchema\n});\nconst operationRuntimeSchema = z.object({\n\thandle: functionSchema,\n\tinput: zodTypeSchema,\n\toutput: zodTypeSchema\n});\nconst streamHandlerRuntimeSchema = z.object({\n\tcontract: z.object({\n\t\tclientMessage: zodTypeSchema,\n\t\tinput: zodTypeSchema,\n\t\tserverMessage: zodTypeSchema\n\t}),\n\topen: functionSchema\n});\nconst resourceDefinitionRuntimeSchema = z.discriminatedUnion(\"kind\", [\n\tz.object({\n\t\tcontract: contractRuntimeSchema,\n\t\tkind: z.literal(\"query\"),\n\t\tread: functionSchema\n\t}),\n\tz.object({\n\t\tcontract: contractRuntimeSchema,\n\t\tkind: z.literal(\"subscription\"),\n\t\tread: functionSchema,\n\t\tsubscribe: functionSchema\n\t}),\n\tz.object({\n\t\tcombine: functionSchema,\n\t\tcontract: contractRuntimeSchema,\n\t\tdependencies: z.record(z.string(), z.string()),\n\t\tkind: z.literal(\"derived\")\n\t})\n]);\nconst authDurationSchema = z.string().regex(/^[1-9]\\d*[mhd]$/, \"Expected a positive duration such as 30d\").refine((value) => durationToMilliseconds(value) !== void 0, \"Duration is too large\");\nconst isLoopbackHostname = (hostname) => hostname === \"localhost\" || hostname === \"[::1]\" || /^127(?:\\.\\d{1,3}){3}$/.test(hostname);\nconst exactOriginSchema = z.url().refine((value) => new URL(value).origin === value, \"Expected an origin\").refine((value) => {\n\tconst url = new URL(value);\n\treturn url.protocol === \"https:\" || url.protocol === \"http:\" && isLoopbackHostname(url.hostname);\n}, \"Non-loopback Overmux origins must use HTTPS\");\nconst loopbackPeerSchema = z.string().refine((value) => isIP(value) !== 0 && (value === \"::1\" || value.startsWith(\"127.\")), \"Expected a loopback IP address\");\nconst authConfigRuntimeSchema = z.object({\n\tmode: z.literal(\"cli-login\"),\n\torigins: z.array(exactOriginSchema).min(1).refine((origins) => new Set(origins).size === origins.length, \"Expected unique origins\").optional(),\n\tsessionLifetime: z.union([z.literal(\"never\"), authDurationSchema]).default(\"never\"),\n\ttrustedProxyPeer: loopbackPeerSchema.optional()\n}).strict();\nconst serverConfigRuntimeSchema = z.object({\n\thost: z.string().min(1).optional(),\n\tlogFile: z.string().min(1).optional(),\n\tport: z.number().int().min(1).max(65535).optional(),\n\tproductionWebAssetsDir: z.string().min(1).optional(),\n\twatch: z.boolean().optional()\n});\nconst serverDefinitionRuntimeSchema = z.object({\n\toperations: z.record(z.string(), operationRuntimeSchema).optional(),\n\tresources: z.record(z.string(), resourceDefinitionRuntimeSchema),\n\tstreams: z.record(z.string(), streamHandlerRuntimeSchema).optional()\n});\nconst configDefinitionRuntimeSchema = serverConfigRuntimeSchema.extend({\n\taiContextSnippets: z.array(z.enum(aiContextSnippets)).optional(),\n\tauth: authConfigRuntimeSchema,\n\tdebug: z.boolean().optional(),\n\tinstanceId: z.union([instanceIdSchema, z.custom((value) => typeof value === \"function\", \"Expected an instance ID or a function of the bound port\")]).optional(),\n\tserver: serverDefinitionRuntimeSchema,\n\tvite: z.string().min(1).optional()\n});\nconst resolveLogicalPath = async (path) => {\n\tconst logicalPath = resolve(path);\n\treturn {\n\t\tlogicalPath,\n\t\trealPath: await realpath(logicalPath)\n\t};\n};\nconst resolveOvermuxConfigPaths = async (configPath) => {\n\tconst { logicalPath, realPath } = await resolveLogicalPath(configPath);\n\treturn {\n\t\tlogicalApplicationRoot: dirname(logicalPath),\n\t\tlogicalConfigPath: logicalPath,\n\t\trealApplicationRoot: dirname(realPath),\n\t\trealConfigPath: realPath\n\t};\n};\nconst unwrapDefaultExport = (module) => {\n\tif (typeof module === \"object\" && module !== null && \"default\" in module) return module.default;\n\treturn module;\n};\nconst loadOvermuxConfig = async ({ aliases = {}, configPath }) => {\n\tconst paths = await resolveOvermuxConfigPaths(configPath);\n\tconst module = await createJiti(paths.logicalConfigPath, {\n\t\talias: aliases,\n\t\tfsCache: true,\n\t\tjsx: {\n\t\t\timportSource: \"react\",\n\t\t\truntime: \"automatic\"\n\t\t},\n\t\tmoduleCache: false,\n\t\tsourceMaps: true,\n\t\ttsconfigPaths: true\n\t}).import(paths.logicalConfigPath);\n\treturn {\n\t\tconfig: configDefinitionRuntimeSchema.parse(unwrapDefaultExport(module)),\n\t\tpaths\n\t};\n};\n//#endregion\n//#region src/node/paths.ts\nconst xdgDirectory = (configured, fallback) => configured && isAbsolute(configured) ? configured : fallback;\nconst overmuxDirectory = (root) => join(root, \"overmux\");\nconst getOvermuxPaths = ({ environment = process.env, homeDir = homedir(), xdgCacheHome = environment.XDG_CACHE_HOME, xdgConfigHome = environment.XDG_CONFIG_HOME, xdgDataHome = environment.XDG_DATA_HOME, xdgRuntimeDir = environment.XDG_RUNTIME_DIR, xdgStateHome = environment.XDG_STATE_HOME } = {}) => {\n\tif (!isAbsolute(homeDir)) throw new TypeError(\"The home directory must be absolute.\");\n\tconst runtimeDir = xdgRuntimeDir && isAbsolute(xdgRuntimeDir) ? overmuxDirectory(xdgRuntimeDir) : void 0;\n\treturn {\n\t\tcacheDir: overmuxDirectory(xdgDirectory(xdgCacheHome, join(homeDir, \".cache\"))),\n\t\tconfigDir: overmuxDirectory(xdgDirectory(xdgConfigHome, join(homeDir, \".config\"))),\n\t\tdataDir: overmuxDirectory(xdgDirectory(xdgDataHome, join(homeDir, \".local\", \"share\"))),\n\t\t...runtimeDir ? { runtimeDir } : {},\n\t\tstateDir: overmuxDirectory(xdgDirectory(xdgStateHome, join(homeDir, \".local\", \"state\")))\n\t};\n};\n//#endregion\nexport { authConfigRuntimeSchema, authDurationSchema, configDefinitionRuntimeSchema, getOvermuxPaths, loadOvermuxConfig, resolveLogicalPath, resolveOvermuxConfigPaths, serverConfigRuntimeSchema, serverDefinitionRuntimeSchema };\n\n//# sourceMappingURL=index.js.map","//#region src/delay.ts\nconst delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));\n//#endregion\n//#region src/duration.ts\nconst durationPattern = /^([1-9]\\d*)(ms|s|m|h|d)$/;\nconst millisecondsByUnit = {\n\td: 1440 * 60 * 1e3,\n\th: 3600 * 1e3,\n\tm: 60 * 1e3,\n\tms: 1,\n\ts: 1e3\n};\nconst durationToMilliseconds = (duration) => {\n\tconst match = durationPattern.exec(duration);\n\tif (!match) return;\n\tconst unit = match[2];\n\tconst milliseconds = Number(match[1]) * millisecondsByUnit[unit];\n\treturn Number.isSafeInteger(milliseconds) ? milliseconds : void 0;\n};\n//#endregion\nexport { delay, durationToMilliseconds };\n\n//# sourceMappingURL=index.js.map","/*\n * Provides private, schema-validated JSON files with atomic persistence: directories and files\n * use owner-only modes; writes fsync a temporary file before rename replacement or hard-link\n * exclusive publication so concurrent first creation safely converges.\n */\nimport { randomUUID } from \"node:crypto\";\nimport {\n chmod,\n link,\n mkdir,\n open,\n readFile,\n rename,\n rm,\n} from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { z } from \"zod\";\n\nconst missingFile = (cause: unknown) =>\n (cause as NodeJS.ErrnoException).code === \"ENOENT\";\n\nconst preparePrivateDirectory = async (path: string) => {\n await mkdir(path, { mode: 0o700, recursive: true });\n await chmod(path, 0o700);\n};\n\nconst writeTemporaryPrivateJson = async (path: string, value: unknown) => {\n await preparePrivateDirectory(dirname(path));\n const temporaryPath = `${path}.${process.pid}.${randomUUID()}`;\n try {\n const handle = await open(temporaryPath, \"wx\", 0o600);\n try {\n await handle.writeFile(`${JSON.stringify(value)}\\n`);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return temporaryPath;\n } catch (cause) {\n await rm(temporaryPath, { force: true });\n throw cause;\n }\n};\n\nexport const readPrivateJson = async <TSchema extends z.ZodType>(\n path: string,\n schema: TSchema,\n): Promise<z.output<TSchema> | undefined> => {\n try {\n const contents = await readFile(path, \"utf8\");\n await chmod(path, 0o600);\n return schema.parse(JSON.parse(contents));\n } catch (cause) {\n if (missingFile(cause)) {\n return undefined;\n }\n throw cause;\n }\n};\n\nexport const replacePrivateJsonAtomically = async (\n path: string,\n value: unknown,\n) => {\n const temporaryPath = await writeTemporaryPrivateJson(path, value);\n try {\n await rename(temporaryPath, path);\n } catch (cause) {\n await rm(temporaryPath, { force: true });\n throw cause;\n }\n};\n\nexport const createPrivateJsonExclusively = async (\n path: string,\n value: unknown,\n) => {\n const temporaryPath = await writeTemporaryPrivateJson(path, value);\n try {\n await link(temporaryPath, path);\n } finally {\n await rm(temporaryPath, { force: true });\n }\n};\n","import {\n createHash,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from \"node:crypto\";\nimport { chmod, mkdir, open, rm, stat } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { durationToMilliseconds } from \"@overmux/lib\";\nimport { authDurationSchema } from \"@overmux/shared/node\";\nimport { z } from \"zod\";\n\nimport type { AuthConfigDefinition } from \"../../../public/config\";\nimport {\n createPrivateJsonExclusively,\n readPrivateJson,\n replacePrivateJsonAtomically,\n} from \"../notifications/private-json-file\";\nimport { getOvermuxPaths } from \"../paths\";\n\n// Login grants are brief, single-use browser bootstrap credentials. Local\n// bearers last only long enough for a CLI request because the owner-only control\n// socket can cheaply issue another without interactive authentication.\nconst loginGrantLifetimeMs = 10 * 60_000;\nconst localBearerLifetimeMs = 60_000;\nconst maxCodeAttempts = 8;\nconst lastSeenWriteIntervalMs = 60_000;\nconst codeAlphabet = \"23456789ABCDEFGHJKLMNPQRSTUVWXYZ\";\n\nconst loginGrantSchema = z.object({\n codeHash: z.string(),\n codeLookupHash: z.string(),\n consumedAt: z.string().optional(),\n createdAt: z.string(),\n expiresAt: z.string(),\n failedCodeAttempts: z.number().int().nonnegative(),\n id: z.string(),\n linkTokenHash: z.string(),\n});\n\nconst authSessionSchema = z.object({\n createdAt: z.string(),\n expiresAt: z.string().optional(),\n id: z.string(),\n kind: z.enum([\"browser\", \"local\"]),\n lastSeenAt: z.string(),\n origin: z.string().optional(),\n revokedAt: z.string().optional(),\n tokenHash: z.string(),\n});\n\nconst authStoreSchema = z.object({\n grants: z.array(loginGrantSchema),\n installationId: z.string(),\n sessions: z.array(authSessionSchema),\n version: z.literal(1),\n});\n\ntype AuthStore = z.infer<typeof authStoreSchema>;\ntype StoredSession = z.infer<typeof authSessionSchema>;\n\nexport type AuthSession = Omit<StoredSession, \"kind\" | \"tokenHash\">;\nexport type LoginGrant = {\n code: string;\n expiresAt: string;\n id: string;\n urls: string[];\n};\nexport type LoginResult =\n | { status: \"expired\" | \"invalid\" | \"rate-limited\" }\n | { session: AuthSession; status: \"authenticated\"; token: string };\nexport type AuthenticatedSession = {\n expiresAt?: string;\n id: string;\n kind: \"browser\" | \"local\";\n origin?: string;\n token: string;\n};\n// AuthService is transport-neutral and persists grants and sessions across\n// server replacement. Opaque credentials are returned once; only their hashes\n// and non-secret lifecycle metadata are stored. Every session represents\n// authority delegated by the OS user; there are no application users or roles.\nexport type AuthService = {\n authenticateToken: (\n token: string,\n origin?: string,\n ) => Promise<AuthenticatedSession | undefined>;\n consumeLoginGrant: (input: {\n code?: string;\n origin: string;\n ticket?: string;\n }) => Promise<LoginResult>;\n createLoginGrant: () => Promise<LoginGrant>;\n issueLocalBearer: () => Promise<{ expiresAt: string; token: string }>;\n isSessionActive: (id: string) => Promise<boolean>;\n listSessions: () => Promise<AuthSession[]>;\n onSessionsRevoked: (\n listener: (ids: ReadonlySet<string>) => void,\n ) => () => void;\n revokeAllSessions: () => Promise<number>;\n revokeSession: (id: string) => Promise<boolean>;\n setOrigins: (origins: string[]) => void;\n};\n\nconst tokenHash = (token: string) =>\n createHash(\"sha256\").update(token, \"utf8\").digest(\"hex\");\n\nconst hashesEqual = (left: string, right: string) => {\n const leftBytes = Buffer.from(left, \"hex\");\n const rightBytes = Buffer.from(right, \"hex\");\n return (\n leftBytes.length === rightBytes.length &&\n timingSafeEqual(leftBytes, rightBytes)\n );\n};\n\nconst randomToken = () => randomBytes(32).toString(\"base64url\");\n\nconst randomCode = () => {\n const bytes = randomBytes(8);\n const characters = Array.from(\n bytes,\n (byte) => codeAlphabet[byte % codeAlphabet.length],\n );\n return `${characters.slice(0, 4).join(\"\")}-${characters.slice(4).join(\"\")}`;\n};\n\nconst durationMilliseconds = (\n duration: Exclude<\n AuthConfigDefinition[\"sessionLifetime\"],\n \"never\" | undefined\n >,\n) => {\n const milliseconds = durationToMilliseconds(\n authDurationSchema.parse(duration),\n );\n if (milliseconds === undefined) {\n throw new Error(\"Expected a validated authentication duration\");\n }\n return milliseconds;\n};\n\n// Old and replacement server processes may overlap, so every read-modify-write\n// transaction takes a filesystem lock. This is what makes grant consumption and\n// revocation atomic across processes, not only within one AuthService instance.\nconst acquireStoreLock = async (\n path: string,\n deadline = Date.now() + 5_000,\n): Promise<() => Promise<void>> => {\n await mkdir(dirname(path), { mode: 0o700, recursive: true });\n await chmod(dirname(path), 0o700);\n try {\n const handle = await open(path, \"wx\", 0o600);\n await handle.close();\n return () => rm(path, { force: true });\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw cause;\n }\n let lockAge: number;\n try {\n lockAge = Date.now() - (await stat(path)).mtimeMs;\n } catch (statCause) {\n if ((statCause as NodeJS.ErrnoException).code === \"ENOENT\") {\n return acquireStoreLock(path, deadline);\n }\n throw statCause;\n }\n if (lockAge > 30_000) {\n await rm(path, { force: true });\n return acquireStoreLock(path, deadline);\n }\n if (Date.now() >= deadline) {\n throw new Error(\"Timed out waiting for the authentication store lock\");\n }\n await new Promise((resolve) => setTimeout(resolve, 10));\n return acquireStoreLock(path, deadline);\n }\n};\n\nconst dataDirectory = ({\n environment,\n homeDirectory,\n}: {\n environment: NodeJS.ProcessEnv;\n homeDirectory: string;\n}) =>\n join(\n getOvermuxPaths({ environment, homeDir: homeDirectory }).dataDir,\n \"auth\",\n );\n\nconst publicSession = ({\n kind: _kind,\n tokenHash: _tokenHash,\n ...session\n}: StoredSession): AuthSession => session;\nconst activeSession = (session: StoredSession, now: number) =>\n !session.revokedAt &&\n (session.kind === \"local\" || Boolean(session.origin)) &&\n (!session.expiresAt || Date.parse(session.expiresAt) > now);\n\nconst revokeExpired = (store: AuthStore, currentTime: number) => {\n const expiredIds: string[] = [];\n const sessions = store.sessions.map((session) => {\n if (\n !session.revokedAt &&\n session.expiresAt &&\n Date.parse(session.expiresAt) <= currentTime\n ) {\n expiredIds.push(session.id);\n return { ...session, revokedAt: new Date(currentTime).toISOString() };\n }\n return session;\n });\n return { expiredIds, sessions };\n};\n\nconst authenticateStoredToken = ({\n currentTime,\n store,\n origin,\n token,\n}: {\n currentTime: number;\n origin?: string;\n store: AuthStore;\n token: string;\n}) => {\n const { expiredIds, sessions } = revokeExpired(store, currentTime);\n const expectedHash = tokenHash(token);\n const session = sessions.find((candidate) =>\n hashesEqual(candidate.tokenHash, expectedHash),\n );\n const authenticated =\n session &&\n activeSession(session, currentTime) &&\n (session.kind === \"local\" || session.origin === origin)\n ? {\n ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),\n id: session.id,\n kind: session.kind,\n ...(session.origin ? { origin: session.origin } : {}),\n token,\n }\n : undefined;\n const updateLastSeen = Boolean(\n session &&\n authenticated &&\n currentTime - Date.parse(session.lastSeenAt) >= lastSeenWriteIntervalMs,\n );\n const nextSessions = updateLastSeen\n ? sessions.map((candidate) =>\n candidate.id === session?.id\n ? { ...candidate, lastSeenAt: new Date(currentTime).toISOString() }\n : candidate,\n )\n : sessions;\n return { authenticated, expiredIds, nextSessions, updateLastSeen };\n};\n\nexport const createAuthService = ({\n config,\n environment = process.env,\n homeDirectory = homedir(),\n now = Date.now,\n}: {\n config: AuthConfigDefinition;\n environment?: NodeJS.ProcessEnv;\n homeDirectory?: string;\n now?: () => number;\n}): AuthService => {\n const directory = dataDirectory({ environment, homeDirectory });\n const storePath = join(directory, \"auth.json\");\n const lockPath = join(directory, \"auth.lock\");\n const listeners = new Set<(ids: ReadonlySet<string>) => void>();\n let origins = config.origins;\n let pendingWrite = Promise.resolve();\n\n const readStore = async (): Promise<AuthStore> => {\n const existing = await readPrivateJson(storePath, authStoreSchema);\n if (existing) {\n return existing;\n }\n const initial: AuthStore = {\n grants: [],\n installationId: randomUUID(),\n sessions: [],\n version: 1,\n };\n try {\n await createPrivateJsonExclusively(storePath, initial);\n return initial;\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw cause;\n }\n const concurrentlyCreated = await readPrivateJson(\n storePath,\n authStoreSchema,\n );\n if (!concurrentlyCreated) {\n throw cause;\n }\n return concurrentlyCreated;\n }\n };\n\n const updateStore = <T>(\n update: (store: AuthStore) => {\n result: T;\n revokedIds?: string[];\n store?: AuthStore;\n },\n ) => {\n const operation = pendingWrite.then(async () => {\n const release = await acquireStoreLock(lockPath);\n try {\n const current = await readStore();\n const updated = update(current);\n if (updated.store) {\n await replacePrivateJsonAtomically(storePath, updated.store);\n }\n emitRevoked(updated.revokedIds ?? []);\n return updated.result;\n } finally {\n await release();\n }\n });\n pendingWrite = operation.then(\n () => undefined,\n () => undefined,\n );\n return operation;\n };\n\n // Revocation is the shared lifecycle signal for closing WebSockets and\n // removing session-owned background notification subscriptions.\n const emitRevoked = (ids: string[]) => {\n if (ids.length === 0) {\n return;\n }\n const revoked = new Set(ids);\n listeners.forEach((listener) => listener(revoked));\n };\n\n const createSession = ({\n kind,\n lifetimeMs,\n origin,\n }: {\n kind: StoredSession[\"kind\"];\n lifetimeMs?: number;\n origin?: string;\n }) => {\n const token = randomToken();\n const createdAt = new Date(now()).toISOString();\n const configuredLifetime =\n config.sessionLifetime && config.sessionLifetime !== \"never\"\n ? durationMilliseconds(config.sessionLifetime)\n : undefined;\n const expiresIn = lifetimeMs ?? configuredLifetime;\n const stored: StoredSession = {\n createdAt,\n ...(expiresIn\n ? { expiresAt: new Date(now() + expiresIn).toISOString() }\n : {}),\n id: randomUUID(),\n kind,\n lastSeenAt: createdAt,\n ...(origin ? { origin } : {}),\n tokenHash: tokenHash(token),\n };\n return { stored, token };\n };\n\n const authenticateToken = async (token: string, origin?: string) => {\n await pendingWrite;\n const currentTime = now();\n const inspected = authenticateStoredToken({\n currentTime,\n origin,\n store: await readStore(),\n token,\n });\n if (inspected.expiredIds.length === 0 && !inspected.updateLastSeen) {\n return inspected.authenticated;\n }\n return updateStore((store) => {\n const current = authenticateStoredToken({\n currentTime: now(),\n origin,\n store,\n token,\n });\n return {\n result: current.authenticated,\n revokedIds: current.expiredIds,\n store: { ...store, sessions: current.nextSessions },\n };\n });\n };\n\n return {\n authenticateToken,\n consumeLoginGrant: (input) =>\n updateStore<LoginResult>((store) => {\n const currentTime = now();\n const presented = input.code?.trim().toUpperCase() ?? input.ticket;\n if (!presented || Boolean(input.code) === Boolean(input.ticket)) {\n return { result: { status: \"invalid\" } as const };\n }\n const expectedHash = tokenHash(presented);\n const codeLookupHash = input.code\n ? tokenHash(presented.split(\"-\", 1)[0] ?? \"\")\n : undefined;\n const exactCodeIndex = store.grants.findIndex((grant) =>\n hashesEqual(grant.codeHash, expectedHash),\n );\n const codeIndex =\n exactCodeIndex >= 0\n ? exactCodeIndex\n : store.grants.findIndex((grant) =>\n hashesEqual(grant.codeLookupHash, codeLookupHash ?? \"\"),\n );\n const index = input.code\n ? codeIndex\n : store.grants.findIndex((grant) =>\n hashesEqual(grant.linkTokenHash, expectedHash),\n );\n if (index < 0) {\n return { result: { status: \"invalid\" } as const };\n }\n const grant = store.grants[index]!;\n if (grant.consumedAt) {\n return { result: { status: \"invalid\" } as const };\n }\n if (Date.parse(grant.expiresAt) <= currentTime) {\n return { result: { status: \"expired\" } as const };\n }\n if (input.code && grant.failedCodeAttempts >= maxCodeAttempts) {\n return { result: { status: \"rate-limited\" } as const };\n }\n if (input.code && !hashesEqual(grant.codeHash, expectedHash)) {\n const grants = store.grants.map((candidate, grantIndex) =>\n grantIndex === index\n ? {\n ...candidate,\n failedCodeAttempts: candidate.failedCodeAttempts + 1,\n }\n : candidate,\n );\n return {\n result: { status: \"invalid\" } as const,\n store: { ...store, grants },\n };\n }\n const { stored, token } = createSession({\n kind: \"browser\",\n origin: input.origin,\n });\n const grants = store.grants.map((candidate, grantIndex) =>\n grantIndex === index\n ? { ...candidate, consumedAt: new Date(currentTime).toISOString() }\n : candidate,\n );\n return {\n result: {\n session: publicSession(stored),\n status: \"authenticated\",\n token,\n } as const,\n store: {\n ...store,\n grants,\n sessions: [\n ...store.sessions.filter((session) =>\n activeSession(session, currentTime),\n ),\n stored,\n ],\n },\n };\n }),\n createLoginGrant: () =>\n updateStore((store) => {\n if (!origins) {\n throw new Error(\"The server has not established its browser origins\");\n }\n const code = randomCode();\n const ticket = randomToken();\n const createdAt = new Date(now()).toISOString();\n const expiresAt = new Date(now() + loginGrantLifetimeMs).toISOString();\n const id = randomUUID();\n const grant = {\n codeHash: tokenHash(code),\n codeLookupHash: tokenHash(code.split(\"-\", 1)[0]!),\n createdAt,\n expiresAt,\n failedCodeAttempts: 0,\n id,\n linkTokenHash: tokenHash(ticket),\n };\n return {\n result: {\n code,\n expiresAt,\n id,\n urls: origins.map(\n (origin) =>\n `${origin}/login#ticket=${encodeURIComponent(ticket)}`,\n ),\n },\n store: {\n ...store,\n grants: [\n ...store.grants.filter(\n (candidate) =>\n Date.parse(candidate.expiresAt) > now() &&\n !candidate.consumedAt,\n ),\n grant,\n ],\n },\n };\n }),\n issueLocalBearer: () =>\n updateStore((store) => {\n const currentTime = now();\n const { stored, token } = createSession({\n kind: \"local\",\n lifetimeMs: localBearerLifetimeMs,\n });\n return {\n result: { expiresAt: stored.expiresAt!, token },\n store: {\n ...store,\n sessions: [\n ...store.sessions.filter((session) =>\n activeSession(session, currentTime),\n ),\n stored,\n ],\n },\n };\n }),\n isSessionActive: (id) =>\n updateStore((store) => {\n const currentTime = now();\n const { expiredIds, sessions } = revokeExpired(store, currentTime);\n return {\n result: Boolean(\n sessions.find(\n (session) =>\n session.id === id && activeSession(session, currentTime),\n ),\n ),\n revokedIds: expiredIds,\n ...(expiredIds.length > 0 ? { store: { ...store, sessions } } : {}),\n };\n }),\n listSessions: () =>\n updateStore((store) => {\n const currentTime = now();\n const { expiredIds, sessions } = revokeExpired(store, currentTime);\n return {\n result: sessions\n .filter(\n (session) =>\n session.kind === \"browser\" &&\n activeSession(session, currentTime),\n )\n .map(publicSession),\n revokedIds: expiredIds,\n ...(expiredIds.length > 0 ? { store: { ...store, sessions } } : {}),\n };\n }),\n onSessionsRevoked: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n revokeAllSessions: () =>\n updateStore((store) => {\n const currentTime = now();\n const expired = revokeExpired(store, currentTime);\n const ids = expired.sessions\n .filter(\n (session) =>\n session.kind === \"browser\" && activeSession(session, currentTime),\n )\n .map((session) => session.id);\n const revoked = new Set(ids);\n const revokedAt = new Date(currentTime).toISOString();\n const sessions = expired.sessions.map((session) =>\n revoked.has(session.id) ? { ...session, revokedAt } : session,\n );\n const revokedIds = [...expired.expiredIds, ...ids];\n return {\n result: ids.length,\n revokedIds,\n ...(revokedIds.length > 0 ? { store: { ...store, sessions } } : {}),\n };\n }),\n revokeSession: (id) =>\n updateStore((store) => {\n const session = store.sessions.find(\n (candidate) => candidate.id === id && !candidate.revokedAt,\n );\n if (!session) {\n return { result: false };\n }\n const revokedAt = new Date(now()).toISOString();\n const sessions = store.sessions.map((candidate) =>\n candidate.id === id ? { ...candidate, revokedAt } : candidate,\n );\n return {\n result: true,\n revokedIds: [id],\n store: { ...store, sessions },\n };\n }),\n setOrigins: (nextOrigins) => {\n origins = nextOrigins.map((origin) => new URL(origin).origin);\n },\n };\n};\n","export type RateLimiter = {\n attemptsByKey: Map<string, number[]>;\n globalAttempts: number[];\n maxAttemptsPerKey: number;\n maxGlobalAttempts: number;\n maxTrackedKeys: number;\n windowMs: number;\n};\n\nexport const createRateLimiter = ({\n maxAttemptsPerKey,\n maxGlobalAttempts,\n maxTrackedKeys,\n windowMs,\n}: {\n maxAttemptsPerKey: number;\n maxGlobalAttempts: number;\n maxTrackedKeys: number;\n windowMs: number;\n}): RateLimiter => ({\n attemptsByKey: new Map(),\n globalAttempts: [],\n maxAttemptsPerKey,\n maxGlobalAttempts,\n maxTrackedKeys,\n windowMs,\n});\n\nexport const hasRateLimitCapacity = ({\n currentTime = Date.now(),\n key,\n limiter,\n}: {\n currentTime?: number;\n key: string;\n limiter: RateLimiter;\n}) => {\n const threshold = currentTime - limiter.windowMs;\n const recent = (limiter.attemptsByKey.get(key) ?? []).filter(\n (attempt) => attempt > threshold,\n );\n limiter.globalAttempts = limiter.globalAttempts.filter(\n (attempt) => attempt > threshold,\n );\n if (\n recent.length >= limiter.maxAttemptsPerKey ||\n limiter.globalAttempts.length >= limiter.maxGlobalAttempts\n ) {\n limiter.attemptsByKey.set(key, recent);\n return false;\n }\n limiter.attemptsByKey.set(key, [...recent, currentTime]);\n limiter.globalAttempts.push(currentTime);\n if (limiter.attemptsByKey.size > limiter.maxTrackedKeys) {\n limiter.attemptsByKey.clear();\n }\n return true;\n};\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Context } from \"hono\";\n\nconst authAssetPrefix = \"/_overmux/auth-shell/\";\nconst authEntry = \"index.html\";\nconst fingerprintedAssetPattern =\n /^assets\\/[A-Za-z0-9_.-]+-[A-Za-z0-9_-]{8}\\.(?:css|js)$/;\n\ntype AuthManifest = Record<string, { css?: string[]; file?: string }>;\ntype AuthAsset = { body: ArrayBuffer; contentType: string };\n\nexport type AuthShell = {\n files: Map<string, AuthAsset>;\n html: string;\n};\n\nconst defaultAuthAssetsDirectory = () =>\n fileURLToPath(new URL(\"../auth/\", import.meta.resolve(\"overmux\")));\n\nexport const loadAuthShell = (\n directory = defaultAuthAssetsDirectory(),\n): AuthShell => {\n const manifest = JSON.parse(\n readFileSync(`${directory}/.vite/manifest.json`, \"utf8\"),\n ) as AuthManifest;\n const entry = manifest[authEntry];\n if (!entry?.file || !entry.css?.length) {\n throw new Error(\n \"The packaged Overmux authentication assets are incomplete\",\n );\n }\n const paths = new Set(\n Object.values(manifest).flatMap(({ css = [], file }) =>\n file ? [file, ...css] : css,\n ),\n );\n const invalidPath = [...paths].find(\n (path) => !fingerprintedAssetPattern.test(path),\n );\n if (invalidPath) {\n throw new Error(\n `Invalid Overmux authentication asset path: ${invalidPath}`,\n );\n }\n const files = new Map(\n [...paths].map((path) => [\n path,\n {\n body: Uint8Array.from(readFileSync(`${directory}/${path}`)).buffer,\n contentType: path.endsWith(\".css\")\n ? \"text/css; charset=UTF-8\"\n : \"text/javascript; charset=UTF-8\",\n },\n ]),\n );\n return { files, html: readFileSync(`${directory}/index.html`, \"utf8\") };\n};\n\nexport const serveAuthShellAsset = (context: Context, shell: AuthShell) => {\n const asset = shell.files.get(context.req.path.slice(authAssetPrefix.length));\n if (!asset) {\n return context.body(null, 404);\n }\n context.header(\"Cache-Control\", \"public, max-age=31536000, immutable\");\n context.header(\"Content-Type\", asset.contentType);\n context.header(\"Cross-Origin-Resource-Policy\", \"same-origin\");\n context.header(\"X-Content-Type-Options\", \"nosniff\");\n return context.body(asset.body);\n};\n\nexport const renderAuthShell = (\n context: Context,\n shell: AuthShell,\n status: 200 | 401 = 200,\n) => {\n context.header(\"Cache-Control\", \"no-store\");\n context.header(\n \"Content-Security-Policy\",\n \"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'\",\n );\n context.header(\"Cross-Origin-Resource-Policy\", \"same-origin\");\n context.header(\"Referrer-Policy\", \"no-referrer\");\n context.header(\"X-Content-Type-Options\", \"nosniff\");\n return context.html(shell.html, status);\n};\n\nexport const isBrowserNavigation = (request: Request) =>\n request.headers.get(\"Sec-Fetch-Dest\") === \"document\" ||\n request.headers.get(\"Accept\")?.includes(\"text/html\");\n","import type { HttpBindings } from \"@hono/node-server\";\nimport type { Context, Handler, MiddlewareHandler } from \"hono\";\nimport { generateCookie } from \"hono/cookie\";\nimport { bodyLimit } from \"hono/body-limit\";\nimport { parse as parseCookie } from \"hono/utils/cookie\";\nimport { z } from \"zod\";\n\nimport { createRateLimiter, hasRateLimitCapacity } from \"../rate-limiter\";\nimport type { AuthService, AuthenticatedSession } from \"./auth-service\";\nimport {\n isBrowserNavigation,\n loadAuthShell,\n renderAuthShell,\n serveAuthShellAsset,\n} from \"./auth-shell-http\";\n\nconst maxLoginBodyBytes = 4_096;\n// Login limits use a rolling window covering the preceding 60 seconds.\nconst loginWindowMs = 60_000;\nconst maxLoginRequestsPerWindow = 12;\nconst maxGlobalLoginRequestsPerWindow = 120;\nconst maxTrackedLoginAddresses = 10_000;\n// Browser cookies cap non-expiring and longer sessions at 400 days.\nconst neverCookieLifetimeSeconds = 400 * 24 * 60 * 60;\nconst sessionCookieName = \"overmux_session\";\n\n// Session kind records the intended client, while credential records how the\n// request presented it. Only local + bearer and browser + cookie are accepted.\n// This prevents a copied browser token from bypassing browser origin policy.\nexport type RequestSession = AuthenticatedSession & {\n credential: \"bearer\" | \"cookie\";\n};\n\nexport type AuthEnvironment = {\n Variables: { session: RequestSession };\n};\n\nexport type RequestAuthentication = {\n authenticate: (\n request: Request,\n origin?: string,\n ) => Promise<RequestSession | undefined>;\n clearCookieHeader: (origin: string) => string;\n cookieHeader: (origin: string, token: string, expiresAt?: string) => string;\n};\n\nexport type RequestOriginInput = {\n remoteAddress?: string;\n request: Request;\n};\n\n// Groups the transport-neutral session service with the HTTP-specific policy\n// needed to authenticate requests against the configured browser origins.\nexport type AuthBoundary = {\n // Owns login grants, persisted sessions, token validation, and revocation.\n service: AuthService;\n // Resolves lazily because an ephemeral listening port is unknown until startup.\n resolveOrigin: (input: RequestOriginInput) => string | undefined;\n // Parses request credentials and creates or clears browser session cookies.\n requests: RequestAuthentication;\n};\n\nconst bearerToken = (header: string | null) =>\n /^Bearer ([A-Za-z0-9_-]+)$/.exec(header ?? \"\")?.[1];\n\nconst isLoopbackHostname = (hostname: string) =>\n hostname === \"localhost\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n /^127(?:\\.\\d{1,3}){3}$/.test(hostname);\n\nexport const validateAuthOrigin = (origin: string) => {\n const url = new URL(origin);\n if (url.origin !== origin) {\n throw new Error(\"auth.origins must contain exact origins without paths\");\n }\n if (\n url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && isLoopbackHostname(url.hostname))\n ) {\n throw new Error(\"Non-loopback Overmux origins must use HTTPS\");\n }\n return origin;\n};\n\n// Proxy chains commonly represent multiple previous values as a comma-separated list.\n// Authentication accepts only one exact value with no surrounding whitespace.\nconst exactForwardedValue = (value: string | null) =>\n value !== null && value === value.trim() && !value.includes(\",\")\n ? value\n : undefined;\n\n// Resolve the browser-facing origin and return it only when explicitly configured.\nexport const resolveRequestOrigin = ({\n origins,\n remoteAddress,\n request,\n trustedProxyPeer,\n}: RequestOriginInput & {\n origins: string[];\n trustedProxyPeer?: string;\n}) => {\n const requestUrl = new URL(request.url);\n\n // A reverse proxy accepts the browser request, then opens a new backend request to Overmux.\n // These headers report the browser-facing host, optional port, and protocol lost on that hop.\n // They are ordinary spoofable headers until the immediate sender matches trustedProxyPeer.\n const forwardedHost = request.headers.get(\"X-Forwarded-Host\");\n const forwardedProto = request.headers.get(\"X-Forwarded-Proto\");\n\n // If the trusted proxy supplies either header, require a complete valid pair.\n // Invalid proxy metadata rejects the request instead of falling back to its direct origin.\n if (\n trustedProxyPeer !== undefined &&\n remoteAddress === trustedProxyPeer &&\n (forwardedHost !== null || forwardedProto !== null)\n ) {\n const host = exactForwardedValue(forwardedHost);\n const proto = exactForwardedValue(forwardedProto);\n\n // The supported proxy setup accepts external HTTPS, forwards over HTTP, and preserves Host.\n // Requiring these values to agree rejects partial or contradictory origin descriptions.\n if (\n proto !== \"https\" ||\n !host ||\n requestUrl.protocol !== \"http:\" ||\n requestUrl.host !== host\n ) {\n return;\n }\n\n // The proxy may describe the request only as one of the explicitly configured origins.\n const forwardedOrigin = new URL(`https://${host}`).origin;\n return origins.includes(forwardedOrigin) ? forwardedOrigin : undefined;\n }\n\n // Other requests use their direct URL; any untrusted forwarded headers are ignored.\n return origins.includes(requestUrl.origin) ? requestUrl.origin : undefined;\n};\n\nconst cookieMaxAge = (expiresAt?: string) =>\n Math.min(\n neverCookieLifetimeSeconds,\n expiresAt\n ? Math.max(0, Math.floor((Date.parse(expiresAt) - Date.now()) / 1_000))\n : neverCookieLifetimeSeconds,\n );\n\nconst generateSessionCookie = ({\n origin,\n token,\n maxAge,\n}: {\n origin: string;\n token: string;\n maxAge: number;\n}) =>\n generateCookie(sessionCookieName, token, {\n httpOnly: true,\n maxAge,\n path: \"/\",\n sameSite: \"Strict\",\n ...(new URL(origin).protocol === \"https:\"\n ? { prefix: \"host\" as const }\n : {}),\n });\n\nconst createRequestAuthentication = ({\n service,\n}: {\n service: AuthService;\n}): RequestAuthentication => {\n // Browser sessions use HttpOnly, SameSite=Strict cookies. On HTTPS the\n // browser-enforced __Host- prefix also requires Secure, Path=/, and no Domain,\n // making the cookie host-only and resistant to subdomain replacement.\n const cookieName = (origin: string) =>\n new URL(origin).protocol === \"https:\"\n ? `__Host-${sessionCookieName}`\n : sessionCookieName;\n const cookieHeader = (origin: string, token: string, expiresAt?: string) =>\n generateSessionCookie({\n maxAge: cookieMaxAge(expiresAt),\n origin,\n token,\n });\n return {\n authenticate: async (request, origin) => {\n // Authorization is authoritative: an invalid header must not silently\n // fall back to a valid ambient browser cookie.\n const authorizationHeader = request.headers.get(\"Authorization\");\n if (authorizationHeader !== null) {\n const token = bearerToken(authorizationHeader);\n const authenticatedSession = token\n ? await service.authenticateToken(token)\n : undefined;\n return authenticatedSession?.kind === \"local\"\n ? { ...authenticatedSession, credential: \"bearer\" }\n : undefined;\n }\n if (!origin) {\n return;\n }\n const name = cookieName(origin);\n const token = parseCookie(request.headers.get(\"Cookie\") ?? \"\", name)[\n name\n ];\n const authenticatedSession = token\n ? await service.authenticateToken(token, origin)\n : undefined;\n return authenticatedSession?.kind === \"browser\"\n ? { ...authenticatedSession, credential: \"cookie\" }\n : undefined;\n },\n clearCookieHeader: (origin) =>\n generateSessionCookie({ maxAge: 0, origin, token: \"\" }),\n cookieHeader,\n };\n};\n\nexport const createAuthBoundary = ({\n origins,\n service,\n trustedProxyPeer,\n}: {\n origins: () => string[];\n service: AuthService;\n trustedProxyPeer?: string;\n}): AuthBoundary => ({\n requests: createRequestAuthentication({ service }),\n resolveOrigin: (input) =>\n resolveRequestOrigin({\n ...input,\n origins: origins(),\n trustedProxyPeer,\n }),\n service,\n});\n\nconst loginInputSchema = z.union([\n z.object({ code: z.string() }).strict(),\n z.object({ ticket: z.string() }).strict(),\n]);\n\nconst parseLoginBody = async (request: Request) => {\n if (\n request.headers.get(\"Content-Type\")?.split(\";\", 1)[0]?.toLowerCase() !==\n \"application/json\"\n ) {\n return;\n }\n try {\n return loginInputSchema.safeParse(await request.json()).data;\n } catch {\n return;\n }\n};\n\nconst hasTrustedBrowserHeaders = (request: Request, origin: string) =>\n request.headers.get(\"Origin\") === origin &&\n request.headers.get(\"Sec-Fetch-Site\") === \"same-origin\";\n\nconst changesState = (request: Request) =>\n ![\"GET\", \"HEAD\", \"OPTIONS\"].includes(request.method);\n\nconst requestOrigin = (auth: AuthBoundary, context: Context<AuthEnvironment>) =>\n auth.resolveOrigin({\n remoteAddress: (context.env as Partial<HttpBindings> | undefined)?.incoming\n ?.socket.remoteAddress,\n request: context.req.raw,\n });\n\ntype HttpAuthenticationHandlers = {\n asset: Handler<AuthEnvironment>;\n authenticate: MiddlewareHandler<AuthEnvironment>;\n login: Handler<AuthEnvironment>;\n loginBodyLimitMiddleware: MiddlewareHandler<AuthEnvironment>;\n loginPage: Handler<AuthEnvironment>;\n logout: Handler<AuthEnvironment>;\n state: Handler<AuthEnvironment>;\n};\n\n// Browser login and cookie-authenticated mutations require the effective\n// configured Origin plus same-origin Fetch Metadata. Bearer credentials are explicit rather\n// than ambient browser credentials, so they do not use the browser CSRF check.\nexport const createHttpAuthenticationHandlers = ({\n auth,\n authAssetsDirectory,\n}: {\n auth: AuthBoundary;\n authAssetsDirectory?: string;\n}): HttpAuthenticationHandlers => {\n const authShell = loadAuthShell(authAssetsDirectory);\n const loginRateLimiter = createRateLimiter({\n maxAttemptsPerKey: maxLoginRequestsPerWindow,\n maxGlobalAttempts: maxGlobalLoginRequestsPerWindow,\n maxTrackedKeys: maxTrackedLoginAddresses,\n windowMs: loginWindowMs,\n });\n\n return {\n asset: (context) => serveAuthShellAsset(context, authShell),\n state: async (context) => {\n context.header(\"Cache-Control\", \"no-store\");\n const origin = requestOrigin(auth, context);\n const session = await auth.requests.authenticate(context.req.raw, origin);\n if (session?.credential === \"cookie\" && origin) {\n context.header(\n \"Set-Cookie\",\n auth.requests.cookieHeader(origin, session.token, session.expiresAt),\n );\n }\n return context.json({ authenticated: Boolean(session) });\n },\n loginBodyLimitMiddleware: bodyLimit({\n maxSize: maxLoginBodyBytes,\n onError: (context) =>\n context.json({ error: \"Login request is too large\" }, 413),\n }),\n login: async (context) => {\n context.header(\"Cache-Control\", \"no-store\");\n const origin = requestOrigin(auth, context);\n if (!origin || !hasTrustedBrowserHeaders(context.req.raw, origin)) {\n return context.json(\n { error: \"Login request origin was rejected\" },\n 403,\n );\n }\n const address =\n (context.env as Partial<HttpBindings> | undefined)?.incoming?.socket\n .remoteAddress ?? \"unknown\";\n if (!hasRateLimitCapacity({ key: address, limiter: loginRateLimiter })) {\n return context.json({ status: \"rate-limited\" }, 429);\n }\n const input = await parseLoginBody(context.req.raw);\n if (!input) {\n return context.json({ error: \"Invalid login request\" }, 400);\n }\n const result = await auth.service.consumeLoginGrant({ ...input, origin });\n if (result.status !== \"authenticated\") {\n return context.json(\n { status: result.status },\n result.status === \"rate-limited\" ? 429 : 401,\n );\n }\n context.header(\n \"Set-Cookie\",\n auth.requests.cookieHeader(\n origin,\n result.token,\n result.session.expiresAt,\n ),\n );\n return context.json({ authenticated: true });\n },\n loginPage: async (context) => {\n const origin = requestOrigin(auth, context);\n const session = await auth.requests.authenticate(context.req.raw, origin);\n if (session) {\n return context.redirect(\"/\");\n }\n return renderAuthShell(context, authShell);\n },\n authenticate: async (context, next) => {\n const origin = requestOrigin(auth, context);\n let session: RequestSession | undefined;\n try {\n session = await auth.requests.authenticate(context.req.raw, origin);\n } catch {\n context.header(\"Cache-Control\", \"no-store\");\n return context.json(\n { error: \"Authentication service unavailable\" },\n 503,\n );\n }\n if (!session) {\n if (\n !context.req.path.startsWith(\"/api/\") &&\n isBrowserNavigation(context.req.raw)\n ) {\n return renderAuthShell(context, authShell, 401);\n }\n context.header(\"Cache-Control\", \"no-store\");\n return context.json({ error: \"Authentication required\" }, 401);\n }\n context.set(\"session\", session);\n context.header(\"Cache-Control\", \"private, no-store\");\n if (session.credential === \"cookie\") {\n if (\n !origin ||\n (changesState(context.req.raw) &&\n !hasTrustedBrowserHeaders(context.req.raw, origin))\n ) {\n return context.json({ error: \"Request origin was rejected\" }, 403);\n }\n context.header(\n \"Set-Cookie\",\n auth.requests.cookieHeader(origin, session.token, session.expiresAt),\n );\n }\n await next();\n },\n logout: async (context) => {\n const session = context.get(\"session\");\n await auth.service.revokeSession(session.id);\n if (session.origin) {\n context.header(\n \"Set-Cookie\",\n auth.requests.clearCookieHeader(session.origin),\n );\n }\n return context.json({ authenticated: false });\n },\n };\n};\n","import { z } from \"zod\";\n//#region src/ai-context.ts\nconst packageSourceSnippet = \"package-source\";\nconst techStackRecommendationsSnippet = \"tech-stack-recommendations\";\nconst aiContextSnippets = [packageSourceSnippet, techStackRecommendationsSnippet];\n//#endregion\n//#region src/hosted-routes.ts\nconst overmuxSettingsPath = \"/_overmux/settings\";\nconst overmuxLogoutPath = \"/_overmux/logout\";\nconst reservedPathPrefixes = [\n\t\"/_overmux\",\n\t\"/api\",\n\t\"/login\"\n];\nconst returnToBase = \"https://overmux.invalid\";\nconst isReservedPath = (pathname) => reservedPathPrefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));\nconst resolveOvermuxReturnTo = (candidate) => {\n\tif (!candidate?.startsWith(\"/\") || candidate.startsWith(\"//\")) return \"/\";\n\ttry {\n\t\tconst url = new URL(candidate, returnToBase);\n\t\tconst decodedPathname = decodeURIComponent(url.pathname);\n\t\tif (url.origin !== returnToBase || isReservedPath(decodedPathname)) return \"/\";\n\t\treturn `${url.pathname}${url.search}${url.hash}`;\n\t} catch {\n\t\treturn \"/\";\n\t}\n};\nconst createOvermuxSettingsPath = (returnTo) => {\n\tconst safeReturnTo = resolveOvermuxReturnTo(returnTo);\n\tif (safeReturnTo === \"/\") return overmuxSettingsPath;\n\tconst search = new URLSearchParams({ returnTo: safeReturnTo });\n\treturn `${overmuxSettingsPath}?${search.toString()}`;\n};\n//#endregion\n//#region src/notifications.ts\nconst safeRelativeNotificationLink = (link) => {\n\tlet decoded;\n\ttry {\n\t\tdecoded = decodeURIComponent(link);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn !decoded.startsWith(\"//\") && !decoded.includes(\"\\\\\") && ![...decoded].some((character) => {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\treturn codePoint < 32 || codePoint === 127;\n\t});\n};\nconst notificationLinkSchema = z.union([z.string().max(4096).startsWith(\"/\").refine(safeRelativeNotificationLink), z.string().max(4096).url().refine((link) => {\n\tif (!URL.canParse(link)) return false;\n\tconst url = new URL(link);\n\treturn [\"http:\", \"https:\"].includes(url.protocol) && !url.username && !url.password;\n})]);\nconst notificationSchema = z.object({\n\tbody: z.string().max(4096).optional(),\n\topen: z.object({ link: notificationLinkSchema }).strict().optional(),\n\ttitle: z.string().min(1).max(4096)\n}).strict();\n//#endregion\n//#region src/instance.ts\nconst instanceIdSchema = z.string().max(253).regex(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?![\\s\\S])/, \"Expected a lowercase instance ID with only ASCII letters, digits, internal dots and hyphens\");\nconst createInstanceIdentity = (instanceId) => ({\n\tinstanceId: instanceIdSchema.parse(instanceId),\n\tdeepLinkPrefix: `overmux://${instanceId}`\n});\n//#endregion\nexport { aiContextSnippets, createInstanceIdentity, createOvermuxSettingsPath, instanceIdSchema, notificationLinkSchema, notificationSchema, overmuxLogoutPath, overmuxSettingsPath, packageSourceSnippet, resolveOvermuxReturnTo, techStackRecommendationsSnippet };\n\n//# sourceMappingURL=index.js.map","import { createHash, randomBytes } from \"node:crypto\";\nimport { chmod, mkdir, readdir, rm } from \"node:fs/promises\";\nimport { createConnection, createServer, type Socket } from \"node:net\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\n\nimport { instanceIdSchema } from \"@overmux/shared\";\n\nimport { getOvermuxPaths } from \"../paths\";\nimport {\n readPrivateJson,\n replacePrivateJsonAtomically,\n} from \"../notifications/private-json-file\";\nimport type { AuthService } from \"./auth-service\";\n\nconst maxControlMessageBytes = 16_384;\n\nconst controlRequestSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"get-instance\") }).strict(),\n z.object({ type: z.literal(\"ping\") }).strict(),\n z.object({ type: z.literal(\"create-login\") }).strict(),\n z.object({ type: z.literal(\"issue-bearer\") }).strict(),\n z.object({ type: z.literal(\"list-sessions\") }).strict(),\n z.object({ id: z.string(), type: z.literal(\"revoke-session\") }).strict(),\n z.object({ type: z.literal(\"revoke-all\") }).strict(),\n]);\n\nconst loginGrantSchema = z\n .object({\n code: z.string(),\n expiresAt: z.string(),\n id: z.string(),\n urls: z.array(z.string()),\n })\n .strict();\n\nconst sessionSchema = z\n .object({\n createdAt: z.string(),\n expiresAt: z.string().optional(),\n id: z.string(),\n lastSeenAt: z.string(),\n origin: z.string().optional(),\n revokedAt: z.string().optional(),\n })\n .strict();\n\nconst controlResponseSchemas = {\n \"get-instance\": z\n .object({ instanceId: instanceIdSchema, ok: z.literal(true) })\n .strict(),\n \"create-login\": z\n .object({ login: loginGrantSchema, ok: z.literal(true) })\n .strict(),\n \"issue-bearer\": z\n .object({\n bearer: z.object({ expiresAt: z.string(), token: z.string() }).strict(),\n ok: z.literal(true),\n })\n .strict(),\n \"list-sessions\": z\n .object({ ok: z.literal(true), sessions: z.array(sessionSchema) })\n .strict(),\n ping: z.object({ ok: z.literal(true) }).strict(),\n \"revoke-all\": z\n .object({ count: z.number().int().nonnegative(), ok: z.literal(true) })\n .strict(),\n \"revoke-session\": z\n .object({ ok: z.literal(true), revoked: z.boolean() })\n .strict(),\n};\n\nconst controlResponseEnvelopeSchema = z\n .object({ error: z.unknown().optional(), ok: z.unknown() })\n .passthrough();\n\nconst registrationSchema = z.object({\n apiUrl: z.string().url(),\n controlSocket: z.string(),\n id: z.string(),\n pid: z.number().int().positive(),\n port: z.number().int().min(1).max(65_535),\n url: z.string().url(),\n});\n\nexport type InstanceRegistration = z.infer<typeof registrationSchema>;\nexport type ControlRequest = z.infer<typeof controlRequestSchema>;\nexport type InstanceControl = { close: () => Promise<void> };\n\ntype ControlResponseByType = {\n [Type in keyof typeof controlResponseSchemas]: z.infer<\n (typeof controlResponseSchemas)[Type]\n >;\n};\n\nconst runtimeDirectory = () => {\n const paths = getOvermuxPaths();\n const preferred = paths.runtimeDir ?? join(paths.stateDir, \"runtime\");\n if (Buffer.byteLength(preferred) <= 80) {\n return preferred;\n }\n const suffix = createHash(\"sha256\")\n .update(preferred)\n .digest(\"hex\")\n .slice(0, 12);\n return join(tmpdir(), `overmux-${process.getuid?.() ?? \"user\"}-${suffix}`);\n};\n\nconst readNewlineFrame = ({\n maximumBytes,\n socket,\n timeout,\n}: {\n maximumBytes: number;\n socket: Socket;\n timeout?: number;\n}): Promise<Buffer> =>\n new Promise((resolve, reject) => {\n let buffer = Buffer.alloc(0);\n let timer: NodeJS.Timeout | undefined;\n\n const cleanup = () => {\n socket.off(\"data\", onData);\n socket.off(\"end\", onEnd);\n socket.off(\"error\", onError);\n if (timer) {\n clearTimeout(timer);\n }\n };\n const fail = (cause: Error) => {\n cleanup();\n reject(cause);\n };\n const onData = (chunk: Buffer) => {\n buffer = Buffer.concat([buffer, chunk]);\n if (buffer.length > maximumBytes) {\n fail(new Error(\"Control message is too large\"));\n return;\n }\n const newline = buffer.indexOf(0x0a);\n if (newline < 0) {\n return;\n }\n cleanup();\n resolve(buffer.subarray(0, newline));\n };\n const onEnd = () =>\n fail(new Error(\"Control socket ended before a complete frame\"));\n const onError = (cause: Error) => fail(cause);\n\n if (socket.errored) {\n fail(socket.errored);\n } else if (socket.readableEnded || socket.destroyed) {\n fail(new Error(\"Control socket is already closed\"));\n } else {\n socket.on(\"data\", onData);\n socket.once(\"end\", onEnd);\n socket.once(\"error\", onError);\n if (timeout !== undefined) {\n timer = setTimeout(() => {\n socket.destroy();\n fail(new Error(\"Control request timed out\"));\n }, timeout);\n }\n }\n });\n\nconst writeResponse = (socket: Socket, response: unknown) => {\n socket.end(`${JSON.stringify(response)}\\n`);\n};\n\nconst handleRequest = async ({\n auth,\n instanceId,\n request,\n}: {\n auth: AuthService;\n instanceId: string;\n request: ControlRequest;\n}) => {\n if (request.type === \"get-instance\") {\n return { instanceId, ok: true };\n }\n if (request.type === \"ping\") {\n return { ok: true };\n }\n if (request.type === \"create-login\") {\n return { login: await auth.createLoginGrant(), ok: true };\n }\n if (request.type === \"issue-bearer\") {\n return { bearer: await auth.issueLocalBearer(), ok: true };\n }\n if (request.type === \"list-sessions\") {\n return { ok: true, sessions: await auth.listSessions() };\n }\n if (request.type === \"revoke-session\") {\n return { ok: true, revoked: await auth.revokeSession(request.id) };\n }\n return { count: await auth.revokeAllSessions(), ok: true };\n};\n\nconst handleConnection = async ({\n auth,\n instanceId,\n socket,\n}: {\n auth: AuthService;\n instanceId: string;\n socket: Socket;\n}) => {\n try {\n const frame = await readNewlineFrame({\n maximumBytes: maxControlMessageBytes,\n socket,\n });\n const request = controlRequestSchema.parse(JSON.parse(frame.toString()));\n writeResponse(socket, await handleRequest({ auth, instanceId, request }));\n } catch (cause) {\n writeResponse(socket, {\n error: cause instanceof Error ? cause.message : \"Invalid control request\",\n ok: false,\n });\n }\n};\n\n// Instance control is the private, same-user administration channel for a running\n// server. It bootstraps browser login grants and short-lived CLI bearers without\n// exposing those privileged operations over HTTP. The owner-only runtime\n// directory, registration file, and Unix socket make OS permissions the root of\n// trust. This boundary intentionally does not defend against another process\n// already running as the same OS user.\nexport const startInstanceControl = async ({\n auth,\n apiUrl,\n instanceId,\n port,\n url,\n}: {\n auth: AuthService;\n apiUrl: string;\n instanceId: string;\n port: number;\n url: string;\n}): Promise<InstanceControl> => {\n const directory = runtimeDirectory();\n await mkdir(directory, { mode: 0o700, recursive: true });\n await chmod(directory, 0o700);\n const id = randomBytes(8).toString(\"hex\");\n const socketPath = join(directory, `${id}.sock`);\n const registrationPath = join(directory, `${id}.json`);\n const sockets = new Set<Socket>();\n const server = createServer((socket) => {\n sockets.add(socket);\n socket.once(\"close\", () => sockets.delete(socket));\n void handleConnection({ auth, instanceId, socket });\n });\n const close = async () => {\n sockets.forEach((socket) => socket.destroy());\n try {\n await new Promise<void>((resolve, reject) =>\n server.close((cause) => (cause ? reject(cause) : resolve())),\n );\n } finally {\n await Promise.all([\n rm(socketPath, { force: true }),\n rm(registrationPath, { force: true }),\n ]);\n }\n };\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(socketPath, () => {\n server.off(\"error\", reject);\n resolve();\n });\n });\n try {\n await chmod(socketPath, 0o600);\n await replacePrivateJsonAtomically(registrationPath, {\n apiUrl,\n controlSocket: socketPath,\n id,\n pid: process.pid,\n port,\n url,\n });\n } catch (cause) {\n await close().catch(() => undefined);\n throw cause;\n }\n\n return { close };\n};\n\nconst processIsLive = (pid: number) => {\n try {\n process.kill(pid, 0);\n return true;\n } catch (cause) {\n return (cause as NodeJS.ErrnoException).code === \"EPERM\";\n }\n};\n\n// Finds the sole responsive local server, optionally filtered by port.\nexport const discoverInstance = async (\n port?: number,\n): Promise<InstanceRegistration> => {\n const directory = runtimeDirectory();\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new Error(\"No running Overmux server was found\");\n }\n throw cause;\n }\n const candidates = (\n await Promise.all(\n names\n .filter((name) => name.endsWith(\".json\"))\n .map((name) =>\n readPrivateJson(join(directory, name), registrationSchema).catch(\n () => undefined,\n ),\n ),\n )\n ).filter((registration): registration is InstanceRegistration =>\n Boolean(\n registration &&\n processIsLive(registration.pid) &&\n (port === undefined || registration.port === port),\n ),\n );\n const registrations = (\n await Promise.all(\n candidates.map(async (registration) => {\n try {\n await sendControlRequest(registration, { type: \"ping\" });\n return registration;\n } catch {\n return undefined;\n }\n }),\n )\n ).filter(\n (registration): registration is InstanceRegistration =>\n registration !== undefined,\n );\n if (registrations.length === 0) {\n throw new Error(\n port === undefined\n ? \"No running Overmux server was found\"\n : `No running Overmux server was found on port ${port}`,\n );\n }\n if (registrations.length > 1) {\n throw new Error(\n \"Multiple Overmux servers are running; use --port to select one\",\n );\n }\n return registrations[0]!;\n};\n\nexport const sendControlRequest = async <Request extends ControlRequest>(\n registration: InstanceRegistration,\n request: Request,\n): Promise<ControlResponseByType[Request[\"type\"]]> => {\n const socket = createConnection(registration.controlSocket);\n let frame: Buffer;\n try {\n const response = readNewlineFrame({\n maximumBytes: maxControlMessageBytes,\n socket,\n timeout: 1_000,\n });\n socket.once(\"connect\", () => socket.write(`${JSON.stringify(request)}\\n`));\n frame = await response;\n } finally {\n socket.destroy();\n }\n const parsed = controlResponseEnvelopeSchema.safeParse(\n JSON.parse(frame.toString()),\n );\n if (!parsed.success) {\n throw new Error(\"Invalid control response\");\n }\n if (parsed.data.ok !== true) {\n throw new Error(\n typeof parsed.data.error === \"string\"\n ? parsed.data.error\n : \"Control request failed\",\n );\n }\n const response = controlResponseSchemas[request.type].safeParse(parsed.data);\n if (!response.success) {\n throw new Error(\"Invalid control response\");\n }\n return response.data as ControlResponseByType[Request[\"type\"]];\n};\n","// Validates browser subscription data exchanged by background-notification delivery.\n// Browser-standard key and endpoint details stay behind this internal boundary.\nimport { z } from \"zod\";\n\nconst deliveryKeySchema = z\n .string()\n .min(1)\n .max(1_024)\n .regex(/^[\\w-]+$/u);\n\nexport const backgroundNotificationSubscriptionSchema = z\n .object({\n endpoint: z\n .url()\n .max(4_096)\n .refine((endpoint) => {\n const url = new URL(endpoint);\n return url.protocol === \"https:\" && !url.username && !url.password;\n }),\n expirationTime: z.number().int().nonnegative().nullable(),\n keys: z\n .object({ auth: deliveryKeySchema, p256dh: deliveryKeySchema })\n .strict(),\n })\n .strict();\n\nexport const backgroundNotificationPublicKeyResponseSchema = z\n .object({ publicKey: deliveryKeySchema })\n .strict();\n\nexport const backgroundNotificationDisableRequestSchema = z\n .object({ endpoint: backgroundNotificationSubscriptionSchema.shape.endpoint })\n .strict();\n\nexport type BackgroundNotificationSubscription = z.infer<\n typeof backgroundNotificationSubscriptionSchema\n>;\n","import { z } from \"zod\";\nimport { instanceIdSchema } from \"@overmux/shared\";\n\nimport { notificationSchema } from \"../../public/notifications\";\n\n// Compatibility gate, not negotiation: open tabs may still run older client assets.\n// The exact version rejects incompatible runtime manifest and wire formats before later traffic.\nexport const protocolVersion = 10 as const;\n\n// Application-defined WebSocket close codes shared by server and browser transports.\nexport const webSocketCloseCode = {\n authenticationRevoked: 4001,\n authenticationUnavailable: 4002,\n} as const;\n\nexport const runtimeManifestSchema = z.object({\n debug: z.boolean(),\n operations: z.array(z.string().min(1)),\n protocolVersion: z.literal(protocolVersion),\n resources: z.array(z.string().min(1)),\n streams: z.array(z.string().min(1)),\n});\n\nexport const updateAvailableEventSchema = z.object({\n type: z.literal(\"update-available\"),\n});\n\nexport const restartingEventSchema = z.object({\n type: z.literal(\"restarting\"),\n});\n\nexport const serverLifecycleEventSchema = z.discriminatedUnion(\"type\", [\n updateAvailableEventSchema,\n restartingEventSchema,\n]);\n\nexport const notificationEventSchema = z\n .object({\n notification: notificationSchema,\n type: z.literal(\"notification\"),\n })\n .strict();\n\nconst operationIdSchema = z.string().min(1).max(256);\nconst registrationNameSchema = z.string().min(1).max(256);\n\nexport const resourceReadMessageSchema = z.object({\n input: z.unknown().optional(),\n operationId: operationIdSchema,\n resourceName: registrationNameSchema,\n type: z.literal(\"resource-read\"),\n});\n\nexport const resourceSubscribeMessageSchema = z.object({\n input: z.unknown().optional(),\n operationId: operationIdSchema,\n resourceName: registrationNameSchema,\n subscriptionId: operationIdSchema,\n type: z.literal(\"resource-subscribe\"),\n});\n\nexport const resourceUnsubscribeMessageSchema = z.object({\n subscriptionId: operationIdSchema,\n type: z.literal(\"resource-unsubscribe\"),\n});\n\nexport const streamOpenMessageSchema = z.object({\n input: z.unknown().optional(),\n operationId: operationIdSchema,\n streamId: operationIdSchema,\n streamName: registrationNameSchema,\n type: z.literal(\"stream-open\"),\n});\n\nexport const streamMessageSchema = z.object({\n message: z.unknown(),\n streamId: operationIdSchema,\n type: z.literal(\"stream-message\"),\n});\n\nexport const streamCloseMessageSchema = z.object({\n streamId: operationIdSchema,\n type: z.literal(\"stream-close\"),\n});\n\nexport const clientDiagnosticEventSchema = z.object({\n arguments: z.string().max(16_100),\n level: z.enum([\"log\", \"info\", \"warn\", \"error\", \"debug\"]),\n message: z.string().max(4_100),\n stack: z.string().max(8_100).optional(),\n timestamp: z.iso.datetime(),\n type: z.literal(\"client-diagnostic\"),\n url: z.string().max(2_100).optional(),\n});\n\nexport const clientProtocolMessageSchema = z.discriminatedUnion(\"type\", [\n resourceReadMessageSchema,\n resourceSubscribeMessageSchema,\n resourceUnsubscribeMessageSchema,\n streamOpenMessageSchema,\n streamMessageSchema,\n streamCloseMessageSchema,\n clientDiagnosticEventSchema,\n]);\n\nexport const resourceResultMessageSchema = z.object({\n operationId: operationIdSchema,\n output: z.unknown(),\n type: z.literal(\"resource-result\"),\n});\n\nexport const resourceInvalidatedMessageSchema = z.object({\n subscriptionId: operationIdSchema,\n type: z.literal(\"resource-invalidated\"),\n});\n\nexport const streamOpenedMessageSchema = z.object({\n operationId: operationIdSchema,\n streamId: operationIdSchema,\n type: z.literal(\"stream-opened\"),\n});\n\nexport const streamOutputMessageSchema = z.object({\n message: z.unknown(),\n streamId: operationIdSchema,\n type: z.literal(\"stream-output\"),\n});\n\nexport const streamClosedMessageSchema = z.object({\n streamId: operationIdSchema,\n type: z.literal(\"stream-closed\"),\n});\n\nexport const protocolErrorMessageSchema = z.object({\n code: z.enum([\"bad-request\", \"conflict\", \"internal\", \"not-found\"]),\n message: z.string(),\n operationId: operationIdSchema.optional(),\n streamId: operationIdSchema.optional(),\n subscriptionId: operationIdSchema.optional(),\n type: z.literal(\"error\"),\n});\n\nexport const serverInfoMessageSchema = z\n .object({\n type: z.literal(\"server-info\"),\n instanceId: instanceIdSchema,\n })\n .strict();\n\nexport const serverProtocolMessageSchema = z.discriminatedUnion(\"type\", [\n serverInfoMessageSchema,\n resourceResultMessageSchema,\n resourceInvalidatedMessageSchema,\n streamOpenedMessageSchema,\n streamOutputMessageSchema,\n streamClosedMessageSchema,\n protocolErrorMessageSchema,\n updateAvailableEventSchema,\n restartingEventSchema,\n notificationEventSchema,\n]);\n\nconst byteMarker = \"$overmuxBytes\";\n\ntype EncodedBytes = { [byteMarker]: number[] };\n\nconst encodeValue = (value: unknown): unknown => {\n if (value instanceof Uint8Array) {\n return { [byteMarker]: Array.from(value) } satisfies EncodedBytes;\n }\n if (Array.isArray(value)) {\n return value.map(encodeValue);\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [key, encodeValue(item)]),\n );\n }\n return value;\n};\n\nconst decodeValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map(decodeValue);\n }\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n const record = value as Record<string, unknown>;\n if (\n Object.keys(record).length === 1 &&\n Array.isArray(record[byteMarker]) &&\n record[byteMarker].every(\n (item) => Number.isInteger(item) && item >= 0 && item <= 255,\n )\n ) {\n return Uint8Array.from(record[byteMarker] as number[]);\n }\n return Object.fromEntries(\n Object.entries(record).map(([key, item]) => [key, decodeValue(item)]),\n );\n};\n\nconst binaryMarker = \"$overmuxBinary\";\nconst binaryMagic = 0x4f4d5801;\n\ntype EncodedBinary = { [binaryMarker]: [number, number] };\n\nconst encodeBinaryValue = (\n value: unknown,\n payloads: Uint8Array[],\n offset: { value: number },\n): unknown => {\n if (value instanceof Uint8Array) {\n const marker = {\n [binaryMarker]: [offset.value, value.byteLength],\n } satisfies EncodedBinary;\n payloads.push(value);\n offset.value += value.byteLength;\n return marker;\n }\n if (Array.isArray(value)) {\n return value.map((item) => encodeBinaryValue(item, payloads, offset));\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, item]) => [\n key,\n encodeBinaryValue(item, payloads, offset),\n ]),\n );\n }\n return value;\n};\n\nconst decodeBinaryValue = (value: unknown, payload: Uint8Array): unknown => {\n if (Array.isArray(value)) {\n return value.map((item) => decodeBinaryValue(item, payload));\n }\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n const record = value as Record<string, unknown>;\n const marker = record[binaryMarker];\n if (\n Object.keys(record).length === 1 &&\n Array.isArray(marker) &&\n marker.length === 2 &&\n marker.every((item) => Number.isInteger(item) && item >= 0)\n ) {\n const [offset, length] = marker as [number, number];\n if (offset + length > payload.byteLength) {\n throw new Error(\"Invalid Overmux binary payload range\");\n }\n return payload.slice(offset, offset + length);\n }\n return Object.fromEntries(\n Object.entries(record).map(([key, item]) => [\n key,\n decodeBinaryValue(item, payload),\n ]),\n );\n};\n\nexport const encodeProtocolMessage = (message: unknown): string =>\n JSON.stringify(encodeValue(message));\n\nexport const decodeProtocolMessage = (message: string): unknown =>\n decodeValue(JSON.parse(message));\n\nexport const encodeProtocolFrame = (message: unknown): string | Uint8Array => {\n const payloads: Uint8Array[] = [];\n const encoded = encodeBinaryValue(message, payloads, { value: 0 });\n if (!payloads.length) {\n return JSON.stringify(encoded);\n }\n const header = new TextEncoder().encode(JSON.stringify(encoded));\n const payloadLength = payloads.reduce(\n (total, payload) => total + payload.byteLength,\n 0,\n );\n const frame = new Uint8Array(8 + header.byteLength + payloadLength);\n const view = new DataView(frame.buffer);\n view.setUint32(0, binaryMagic);\n view.setUint32(4, header.byteLength);\n frame.set(header, 8);\n let offset = 8 + header.byteLength;\n payloads.forEach((payload) => {\n frame.set(payload, offset);\n offset += payload.byteLength;\n });\n return frame;\n};\n\nexport const decodeProtocolFrame = (\n frame: string | ArrayBuffer | Uint8Array,\n): unknown => {\n if (typeof frame === \"string\") {\n return decodeProtocolMessage(frame);\n }\n const bytes =\n frame instanceof Uint8Array\n ? frame\n : new Uint8Array(frame, 0, frame.byteLength);\n if (bytes.byteLength < 8) {\n throw new Error(\"Invalid Overmux binary frame\");\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n if (view.getUint32(0) !== binaryMagic) {\n throw new Error(\"Invalid Overmux binary frame magic\");\n }\n const headerLength = view.getUint32(4);\n if (8 + headerLength > bytes.byteLength) {\n throw new Error(\"Invalid Overmux binary frame header\");\n }\n const header = JSON.parse(\n new TextDecoder().decode(bytes.subarray(8, 8 + headerLength)),\n ) as unknown;\n return decodeBinaryValue(header, bytes.subarray(8 + headerLength));\n};\n\nexport type RuntimeManifest = z.infer<typeof runtimeManifestSchema>;\nexport type ClientDiagnosticEvent = z.infer<typeof clientDiagnosticEventSchema>;\nexport type ClientProtocolMessage = z.infer<typeof clientProtocolMessageSchema>;\nexport type ServerLifecycleEvent = z.infer<typeof serverLifecycleEventSchema>;\nexport type ServerProtocolMessage = z.infer<typeof serverProtocolMessageSchema>;\n","// Exposes browser controls for enabling and disabling background notifications.\n// Subscription details pass directly to the background-delivery boundary.\nimport {\n backgroundNotificationDisableRequestSchema,\n backgroundNotificationSubscriptionSchema,\n} from \"../../shared/index\";\nimport type { Handler } from \"hono\";\nimport type { z } from \"zod\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\nimport type { BackgroundNotificationService } from \"../notifications/background-notification-service\";\n\nconst requestLimit = 16_384;\n\nconst parseJson = async <TSchema extends z.ZodType>(\n request: Request,\n schema: TSchema,\n): Promise<z.output<TSchema> | undefined> => {\n if (\n request.headers.get(\"Content-Type\")?.split(\";\", 1)[0]?.toLowerCase() !==\n \"application/json\"\n ) {\n return undefined;\n }\n const contentLength = Number(request.headers.get(\"Content-Length\") ?? 0);\n if (contentLength > requestLimit) {\n return undefined;\n }\n try {\n const bytes = await request.arrayBuffer();\n if (bytes.byteLength > requestLimit) {\n return undefined;\n }\n const parsed = schema.safeParse(\n JSON.parse(new TextDecoder().decode(bytes)),\n );\n return parsed.success ? parsed.data : undefined;\n } catch {\n return undefined;\n }\n};\n\nexport const createBackgroundNotificationHandlers = ({\n backgroundNotifications,\n}: {\n backgroundNotifications: BackgroundNotificationService;\n}): {\n disable: Handler<AuthEnvironment>;\n enable: Handler<AuthEnvironment>;\n publicKey: Handler<AuthEnvironment>;\n} => ({\n publicKey: async (context) => {\n context.header(\"Cache-Control\", \"no-store\");\n return context.json({\n publicKey: await backgroundNotifications.publicKey(),\n });\n },\n enable: async (context) => {\n const subscription = await parseJson(\n context.req.raw,\n backgroundNotificationSubscriptionSchema,\n );\n if (!subscription) {\n return context.json({ error: \"Invalid background subscription\" }, 400);\n }\n await backgroundNotifications.enable(\n context.get(\"session\").id,\n subscription,\n );\n return context.json({ ok: true });\n },\n disable: async (context) => {\n const input = await parseJson(\n context.req.raw,\n backgroundNotificationDisableRequestSchema,\n );\n if (!input) {\n return context.json({ error: \"Invalid background subscription\" }, 400);\n }\n await backgroundNotifications.disable(input.endpoint);\n return context.json({ ok: true });\n },\n});\n","import { appendFileSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { getOvermuxPaths } from \"./paths\";\n\nexport type ServerLogLevel = \"debug\" | \"error\" | \"info\" | \"warn\";\n\nexport type ServerLogEntry = {\n // Groups related request, connection, and operation logs for diagnostics.\n correlationId?: string;\n details?: Record<string, unknown>;\n durationMs?: number;\n event: string;\n level?: ServerLogLevel;\n message?: string;\n source?: \"browser\" | \"server\";\n timestamp?: string;\n};\n\nexport type ServerLogger = {\n enabled: boolean;\n id: () => string;\n log: (entry: ServerLogEntry) => void;\n};\n\ntype ConfigurableServerLogger = ServerLogger & {\n setEnabled: (enabled: boolean) => void;\n setLogFile: (logFile: string) => void;\n};\n\nconst lifecycleEvents = new Set([\n \"server-start\",\n \"server-stop\",\n \"websocket-close\",\n \"websocket-close-event\",\n \"websocket-connect\",\n \"websocket-open\",\n]);\n\nexport const getDefaultServerLogFile = ({\n homeDir,\n xdgStateHome,\n}: {\n homeDir?: string;\n xdgStateHome?: string;\n} = {}) =>\n join(getOvermuxPaths({ homeDir, xdgStateHome }).stateDir, \"overmux.log\");\n\nconst safeJson = (value: unknown) => {\n try {\n return JSON.stringify(value);\n } catch {\n return JSON.stringify({\n event: \"log-serialization-error\",\n level: \"error\",\n source: \"server\",\n timestamp: new Date().toISOString(),\n });\n }\n};\n\nexport const createServerLogger = ({\n enabled,\n logFile = getDefaultServerLogFile(),\n}: {\n enabled: boolean;\n logFile?: string;\n}): ConfigurableServerLogger => {\n let activeLogFile = logFile;\n let debugEnabled = enabled;\n return {\n get enabled() {\n return debugEnabled;\n },\n id: randomUUID,\n log: (entry) => {\n if (\n !debugEnabled &&\n entry.level !== \"error\" &&\n !lifecycleEvents.has(entry.event)\n ) {\n return;\n }\n const record = safeJson({\n timestamp: entry.timestamp ?? new Date().toISOString(),\n level: entry.level ?? \"info\",\n source: entry.source ?? \"server\",\n ...entry,\n });\n mkdirSync(dirname(activeLogFile), { recursive: true });\n appendFileSync(activeLogFile, `${record}\\n`, \"utf8\");\n process.stderr.write(`[overmux:debug] ${record}\\n`);\n },\n setEnabled: (nextEnabled) => {\n debugEnabled = nextEnabled;\n },\n setLogFile: (nextLogFile) => {\n activeLogFile = nextLogFile;\n },\n };\n};\n\nexport const errorMessage = (cause: unknown) =>\n cause instanceof Error ? cause.message : String(cause);\n\nexport const errorDetails = (cause: unknown) => ({\n message: errorMessage(cause),\n ...(cause instanceof Error && cause.stack ? { stack: cause.stack } : {}),\n});\n","import type { HttpBindings } from \"@hono/node-server\";\nimport { proxyFetch } from \"httpxy\";\nimport type { Handler } from \"hono\";\n\nimport type { AuthBoundary, AuthEnvironment } from \"../auth/auth-http\";\nimport { errorDetails, type ServerLogger } from \"../server-logger\";\n\nconst createForwardingHeaders = ({\n origin,\n remoteAddress,\n request,\n}: {\n origin: string;\n remoteAddress?: string;\n request: Request;\n}) => {\n const headers = new Headers(request.headers);\n [...headers.keys()].forEach((name) => {\n if (\n name === \"authorization\" ||\n name === \"cookie\" ||\n name === \"forwarded\" ||\n name.startsWith(\"x-forwarded-\")\n ) {\n headers.delete(name);\n }\n });\n const publicUrl = new URL(origin);\n if (remoteAddress) {\n headers.set(\"x-forwarded-for\", remoteAddress);\n }\n headers.set(\"x-forwarded-host\", publicUrl.host);\n headers.set(\n \"x-forwarded-port\",\n publicUrl.port || (publicUrl.protocol === \"https:\" ? \"443\" : \"80\"),\n );\n headers.set(\"x-forwarded-proto\", publicUrl.protocol.slice(0, -1));\n return headers;\n};\n\nexport const createDevelopmentWebHandler =\n ({\n auth,\n serverLogger,\n target,\n }: {\n auth: AuthBoundary;\n serverLogger?: ServerLogger;\n target: string;\n }): Handler<AuthEnvironment> =>\n async (context) => {\n const incoming = (context.env as Partial<HttpBindings> | undefined)\n ?.incoming;\n const origin = auth.resolveOrigin({\n remoteAddress: incoming?.socket.remoteAddress,\n request: context.req.raw,\n });\n if (!origin) {\n return context.text(\"Request origin was rejected\", 403);\n }\n const headers = createForwardingHeaders({\n origin,\n remoteAddress: incoming?.socket.remoteAddress,\n request: context.req.raw,\n });\n try {\n return await proxyFetch(\n target,\n new Request(context.req.raw, { headers }),\n undefined,\n { changeOrigin: true, xfwd: false },\n );\n } catch (cause) {\n serverLogger?.log({\n details: errorDetails(cause),\n event: \"vite-http-proxy-failure\",\n level: \"error\",\n });\n return context.text(\"Overmux development server is unavailable\", 503, {\n \"Cache-Control\": \"no-store\",\n });\n }\n };\n","// Provides server health and acknowledged restart control endpoints.\n// Shutdown state is shared with the HTTP app composition root.\nimport type { HttpBindings } from \"@hono/node-server\";\nimport type { Handler } from \"hono\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\n\nexport type ShutdownState = { requested: boolean };\n\nexport const createHealthHandler =\n ({ shutdown }: { shutdown: ShutdownState }): Handler<AuthEnvironment> =>\n (context) =>\n shutdown.requested\n ? context.json({ status: \"stopping\" }, 503)\n : context.json({ status: \"ok\" });\n\nexport const createRestartHandler =\n ({\n onRestartRequested,\n shutdown,\n }: {\n onRestartRequested?: () => void;\n shutdown: ShutdownState;\n }): Handler<AuthEnvironment> =>\n (context) => {\n const response = context.json({ status: \"restarting\" }, 202);\n if (!onRestartRequested) {\n return response;\n }\n const beginRestart = () => {\n shutdown.requested = true;\n onRestartRequested();\n };\n const nodeResponse = (context.env as Partial<HttpBindings> | undefined)\n ?.outgoing;\n if (nodeResponse) {\n // Flush the restart acknowledgement before replacing the server.\n nodeResponse.once(\"finish\", beginRestart);\n } else {\n // In-memory Hono requests have no Node response, so defer past the handler.\n setImmediate(beginRestart);\n }\n return response;\n };\n","// Registers named operations with validated input, output, and notification context.\n// Lookup metadata stays aligned with the names published in the runtime manifest.\n\nimport type {\n HandlerContext,\n OperationDefinition,\n} from \"../../../public/index\";\nimport type { Notifications } from \"../../../public/index\";\nimport { z } from \"zod\";\n\nexport class OperationValidationError extends Error {\n constructor(\n readonly phase: \"input\" | \"output\",\n cause: z.ZodError,\n ) {\n super(cause.message, { cause });\n }\n}\n\nexport type RuntimeOperation = {\n execute: (input: unknown, signal?: AbortSignal) => Promise<unknown>;\n returnsVoid: boolean;\n};\n\nexport type RuntimeOperations = {\n get: (name: string) => RuntimeOperation | undefined;\n names: readonly string[];\n};\n\ntype AnyOperation = OperationDefinition<z.ZodTypeAny, z.ZodTypeAny>;\n\nexport type RuntimeOperationDefinitions = Readonly<\n Record<string, AnyOperation>\n>;\n\ntype CreateRuntimeOperationsOptions = {\n context: (signal?: AbortSignal) => HandlerContext;\n definitions: RuntimeOperationDefinitions;\n notifications: Notifications;\n};\n\nexport const createRuntimeOperations = ({\n context,\n definitions,\n notifications,\n}: CreateRuntimeOperationsOptions): RuntimeOperations => {\n const operations = new Map<string, RuntimeOperation>();\n Object.entries(definitions).forEach(([name, definition]) => {\n if (!name) {\n throw new Error(\"Operation names must not be empty\");\n }\n operations.set(name, {\n execute: async (rawInput, signal) => {\n const operationContext = context(signal);\n operationContext.signal.throwIfAborted();\n const input = definition.input.safeParse(rawInput);\n if (!input.success) {\n throw new OperationValidationError(\"input\", input.error);\n }\n const rawOutput = await definition.handle(input.data, {\n ...operationContext,\n notifications,\n });\n operationContext.signal.throwIfAborted();\n const output = definition.output.safeParse(rawOutput);\n if (!output.success) {\n throw new OperationValidationError(\"output\", output.error);\n }\n return output.data;\n },\n returnsVoid: definition.output instanceof z.ZodVoid,\n });\n });\n return {\n get: (name) => operations.get(name),\n names: [...operations.keys()],\n };\n};\n","// Handles operation request validation, execution, cancellation, and lifecycle logs.\n// Operation payloads are limited to 1 MiB before JSON parsing.\nimport type { Handler } from \"hono\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\nimport type { ServerLogger } from \"../server-logger\";\nimport type { Runtime } from \"../runtime/create-runtime\";\nimport { OperationValidationError } from \"../runtime/runtime-operations\";\n\nconst maxOperationRequestBytes = 1_048_576;\n\nconst parseOperationRequest = async (request: Request) => {\n const contentType = request.headers.get(\"Content-Type\")?.split(\";\", 1)[0];\n if (contentType?.toLowerCase() !== \"application/json\") {\n return {\n error: \"Content-Type must be application/json\",\n status: 415,\n } as const;\n }\n const contentLength = Number(request.headers.get(\"Content-Length\") ?? 0);\n if (contentLength > maxOperationRequestBytes) {\n return { error: \"Request body is too large\", status: 413 } as const;\n }\n try {\n const body = await request.arrayBuffer();\n if (body.byteLength > maxOperationRequestBytes) {\n return { error: \"Request body is too large\", status: 413 } as const;\n }\n const text = new TextDecoder().decode(body);\n return { input: text ? (JSON.parse(text) as unknown) : undefined };\n } catch {\n return { error: \"Invalid JSON request body\", status: 400 } as const;\n }\n};\n\nexport const createOperationHandler =\n ({\n runtime,\n serverLogger,\n }: {\n runtime: Runtime;\n serverLogger?: ServerLogger;\n }): Handler<AuthEnvironment, \"/api/operations/:name\"> =>\n async (context) => {\n const operation = runtime.getOperation(context.req.param(\"name\"));\n if (!operation) {\n return context.json({ error: \"Operation not found\" }, 404);\n }\n const parsed = await parseOperationRequest(context.req.raw);\n if (\"error\" in parsed) {\n return context.json({ error: parsed.error }, parsed.status);\n }\n const correlationId =\n context.res.headers.get(\"X-Overmux-Correlation-Id\") ?? serverLogger?.id();\n const startedAt = Date.now();\n serverLogger?.log({\n correlationId,\n details: { registeredName: context.req.param(\"name\") },\n event: \"operation-start\",\n });\n try {\n const output = await operation.execute(\n parsed.input,\n context.req.raw.signal,\n );\n serverLogger?.log({\n correlationId,\n details: { registeredName: context.req.param(\"name\") },\n durationMs: Date.now() - startedAt,\n event: \"operation-complete\",\n });\n return operation.returnsVoid\n ? new Response(undefined, { status: 204 })\n : context.json(output);\n } catch (cause) {\n const message =\n cause instanceof Error ? cause.message : \"Operation failed\";\n serverLogger?.log({\n correlationId,\n details: { registeredName: context.req.param(\"name\") },\n durationMs: Date.now() - startedAt,\n event: \"operation-error\",\n level: \"error\",\n message,\n });\n return context.json(\n { error: message },\n cause instanceof OperationValidationError && cause.phase === \"input\"\n ? 400\n : 500,\n );\n }\n };\n","// Adds request correlation IDs and emits the final HTTP request log entry.\n// Logging runs after the matched middleware and route handler complete.\nimport type { MiddlewareHandler } from \"hono\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\nimport type { ServerLogger } from \"../server-logger\";\n\nexport const createRequestLoggingMiddleware =\n ({\n serverLogger,\n }: {\n serverLogger?: ServerLogger;\n }): MiddlewareHandler<AuthEnvironment> =>\n async (context, next) => {\n const correlationId = serverLogger?.id();\n const startedAt = Date.now();\n if (correlationId) {\n context.header(\"X-Overmux-Correlation-Id\", correlationId);\n }\n await next();\n const failed = context.res.status >= 400 || Boolean(context.error);\n serverLogger?.log({\n correlationId,\n details: {\n method: context.req.method,\n path: context.req.path,\n status: context.res.status,\n },\n durationMs: Date.now() - startedAt,\n event: failed ? \"http-request-failure\" : \"http-request\",\n level: failed ? \"error\" : undefined,\n message: context.error?.message,\n });\n };\n","// Runtime manifest responses must not be stored by client caches.\nimport type { Handler } from \"hono\";\n\nimport type { AuthEnvironment } from \"../auth/auth-http\";\nimport type { Runtime } from \"../runtime/create-runtime\";\n\nexport const createRuntimeManifestHandler =\n ({ runtime }: { runtime: Runtime }): Handler<AuthEnvironment> =>\n (context) => {\n context.header(\"Cache-Control\", \"no-store\");\n return context.json(runtime.manifest);\n };\n","export const runtimeWebSocketPath = \"/api/socket\";\nexport const viteHmrPath = \"/_overmux/vite/hmr\";\nexport const viteInfrastructurePath = \"/_overmux/vite/*\";\n","import { serveStatic } from \"@hono/node-server/serve-static\";\nimport type { Handler, Hono, MiddlewareHandler } from \"hono\";\nimport { join } from \"node:path\";\n\nimport {\n createHttpAuthenticationHandlers,\n type AuthBoundary,\n type AuthEnvironment,\n} from \"../auth/auth-http\";\nimport type { BackgroundNotificationService } from \"../notifications/background-notification-service\";\nimport type { Runtime } from \"../runtime/create-runtime\";\nimport type { ServerLogger } from \"../server-logger\";\nimport { createBackgroundNotificationHandlers } from \"./background-notification-handlers\";\nimport { createDevelopmentWebHandler } from \"./development-web-backend\";\nimport {\n createHealthHandler,\n createRestartHandler,\n type ShutdownState,\n} from \"./control-handlers\";\nimport { createOperationHandler } from \"./operation-handler\";\nimport { createRequestLoggingMiddleware } from \"./request-logging\";\nimport { createRuntimeManifestHandler } from \"./runtime-manifest-handler\";\nimport { overmuxLogoutPath, overmuxSettingsPath } from \"@overmux/shared\";\nimport { viteInfrastructurePath } from \"../../shared/routes\";\n\n// Registration order is the public/protected boundary. Authentication state,\n// login, and health are registered before the session gate; runtime APIs and\n// static assets are registered after it. Keep every Hono route visible in this\n// file for review.\ntype RouteDescriptor =\n | {\n method: \"USE\";\n path: string;\n handler: MiddlewareHandler<AuthEnvironment>;\n }\n | {\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"ALL\";\n path: string;\n handler: Handler<AuthEnvironment> | MiddlewareHandler<AuthEnvironment>;\n middleware?: MiddlewareHandler<AuthEnvironment>;\n };\n\ntype RegisterHttpRoutesOptions = {\n app: Hono<AuthEnvironment>;\n auth: AuthBoundary;\n authAssetsDirectory?: string;\n backgroundNotifications?: BackgroundNotificationService;\n developmentWebTarget?: string;\n onRestartRequested?: () => void;\n runtime: Runtime;\n serverLogger?: ServerLogger;\n shutdown: ShutdownState;\n webAssetsDir?: string;\n};\n\nconst applyDescriptor = (\n app: Hono<AuthEnvironment>,\n route: RouteDescriptor,\n) => {\n if (route.method === \"USE\") {\n app.use(route.path, route.handler);\n return;\n }\n if (route.middleware) {\n app.on(route.method, route.path, route.middleware, route.handler);\n return;\n }\n app.on(route.method, route.path, route.handler);\n};\n\nexport const registerHttpRoutes = ({\n app,\n auth,\n authAssetsDirectory,\n backgroundNotifications,\n developmentWebTarget,\n onRestartRequested,\n runtime,\n serverLogger,\n shutdown,\n webAssetsDir,\n}: RegisterHttpRoutesOptions) => {\n const authentication = createHttpAuthenticationHandlers({\n auth,\n authAssetsDirectory,\n });\n const notificationHandlers = backgroundNotifications\n ? createBackgroundNotificationHandlers({ backgroundNotifications })\n : undefined;\n const developmentWebHandler = developmentWebTarget\n ? createDevelopmentWebHandler({\n auth,\n serverLogger,\n target: developmentWebTarget,\n })\n : undefined;\n const productionWebHandler = webAssetsDir\n ? serveStatic({ path: join(webAssetsDir, \"index.html\") })\n : undefined;\n const hostedWebHandler = developmentWebHandler ?? productionWebHandler;\n const routes: RouteDescriptor[] = [\n {\n method: \"USE\",\n path: \"*\",\n handler: createRequestLoggingMiddleware({ serverLogger }),\n },\n // BEGIN: UNAUTHENTICATED\n {\n method: \"GET\",\n path: \"/_overmux/auth-shell/*\",\n handler: authentication.asset,\n },\n {\n method: \"GET\",\n path: \"/api/auth/state\",\n handler: authentication.state,\n },\n {\n method: \"POST\",\n path: \"/api/auth/login\",\n middleware: authentication.loginBodyLimitMiddleware,\n handler: authentication.login,\n },\n {\n method: \"GET\",\n path: \"/login\",\n handler: authentication.loginPage,\n },\n {\n method: \"GET\",\n path: \"/api/health\",\n handler: createHealthHandler({ shutdown }),\n },\n // END: UNAUTHENTICATED\n {\n method: \"USE\",\n path: \"*\",\n handler: authentication.authenticate,\n },\n // BEGIN: AUTHENTICATED\n {\n method: \"POST\",\n path: \"/api/auth/logout\",\n handler: authentication.logout,\n },\n {\n method: \"POST\",\n path: \"/api/operations/:name\",\n handler: createOperationHandler({ runtime, serverLogger }),\n },\n {\n method: \"POST\",\n path: \"/api/restart\",\n handler: createRestartHandler({ onRestartRequested, shutdown }),\n },\n {\n method: \"GET\",\n path: \"/api/runtime-manifest\",\n handler: createRuntimeManifestHandler({ runtime }),\n },\n ...(notificationHandlers\n ? [\n {\n method: \"GET\" as const,\n path: \"/api/background-notifications/public-key\",\n handler: notificationHandlers.publicKey,\n },\n {\n method: \"PUT\" as const,\n path: \"/api/background-notifications/subscription\",\n handler: notificationHandlers.enable,\n },\n {\n method: \"DELETE\" as const,\n path: \"/api/background-notifications/subscription\",\n handler: notificationHandlers.disable,\n },\n ]\n : []),\n {\n method: \"ALL\",\n path: \"/api/*\",\n handler: (context) => context.notFound(),\n },\n ...(developmentWebHandler\n ? [\n {\n method: \"ALL\" as const,\n path: viteInfrastructurePath,\n handler: developmentWebHandler,\n },\n ]\n : []),\n ...(hostedWebHandler\n ? [\n {\n method: \"GET\" as const,\n path: overmuxSettingsPath,\n handler: hostedWebHandler,\n },\n {\n method: \"GET\" as const,\n path: overmuxLogoutPath,\n handler: hostedWebHandler,\n },\n ]\n : []),\n {\n method: \"ALL\",\n path: \"/_overmux/*\",\n handler: (context) => context.notFound(),\n },\n ...(developmentWebHandler\n ? [\n {\n method: \"ALL\" as const,\n path: \"*\",\n handler: developmentWebHandler,\n },\n ]\n : []),\n ...(webAssetsDir\n ? [\n {\n method: \"USE\" as const,\n path: \"*\",\n handler: serveStatic({ root: webAssetsDir }),\n },\n // Serve the SPA shell for client-side routes that do not match a static asset.\n {\n method: \"GET\" as const,\n path: \"*\",\n handler: serveStatic({ path: join(webAssetsDir, \"index.html\") }),\n },\n ]\n : []),\n // END: AUTHENTICATED\n ];\n\n routes.forEach((route) => applyDescriptor(app, route));\n};\n","import { Hono } from \"hono\";\n\nimport type { AuthBoundary, AuthEnvironment } from \"../auth/auth-http\";\nimport type { BackgroundNotificationService } from \"../notifications/background-notification-service\";\nimport type { ServerLogger } from \"../server-logger\";\nimport type { Runtime } from \"../runtime/create-runtime\";\nimport { registerHttpRoutes } from \"./routes\";\n\nexport type HttpAppOptions = {\n auth: AuthBoundary;\n authAssetsDirectory?: string;\n backgroundNotifications?: BackgroundNotificationService;\n developmentWebTarget?: string;\n onRestartRequested?: () => void;\n serverLogger?: ServerLogger;\n runtime: Runtime;\n webAssetsDir?: string;\n};\n\nexport const createHttpApp = ({\n auth,\n authAssetsDirectory,\n backgroundNotifications,\n developmentWebTarget,\n onRestartRequested,\n serverLogger,\n runtime,\n webAssetsDir,\n}: HttpAppOptions) => {\n const app = new Hono<AuthEnvironment>();\n const shutdown = { requested: false };\n\n registerHttpRoutes({\n app,\n auth,\n authAssetsDirectory,\n backgroundNotifications,\n developmentWebTarget,\n onRestartRequested,\n runtime,\n serverLogger,\n shutdown,\n webAssetsDir,\n });\n\n return Object.assign(app, {\n beginShutdown: () => {\n shutdown.requested = true;\n },\n });\n};\n\nexport type OvermuxHttpApp = ReturnType<typeof createHttpApp>;\n","// Shares the server's outbound WebSocket backpressure policy.\nexport const maxWebSocketBufferedBytes = 1_048_576;\n","// Owns protocol and lifecycle state for one WebSocket connection.\n// Independent resource, stream, notification, diagnostics, and lifecycle traffic shares it.\nimport {\n clientProtocolMessageSchema,\n decodeProtocolFrame,\n encodeProtocolFrame,\n serverProtocolMessageSchema,\n type ClientProtocolMessage,\n type ServerProtocolMessage,\n} from \"../shared/index\";\nimport { WebSocket, type RawData } from \"ws\";\nimport { ZodError } from \"zod\";\n\nimport {\n errorDetails as diagnosticErrorDetails,\n type ServerLogger,\n} from \"./server-logger\";\nimport type { Runtime } from \"./runtime/create-runtime\";\nimport type { RuntimeStreamSession } from \"./runtime/runtime-streams\";\nimport { maxWebSocketBufferedBytes } from \"./websocket-limits\";\n\nconst maxPendingStreamOutputBytes = 1_048_576;\n\ntype ErrorCode = \"bad-request\" | \"conflict\" | \"internal\" | \"not-found\";\n\ntype SubscriptionEntry = {\n controller: AbortController;\n dispose?: () => Promise<void> | void;\n};\n\ntype OperationIdentity = {\n operationId: string;\n operationType: string;\n requestedName?: string;\n};\n\ntype StreamEntry = {\n controller: AbortController;\n identity: OperationIdentity;\n session?: RuntimeStreamSession;\n};\n\ntype ConnectionState = {\n closed: boolean;\n connectionId?: string;\n operations: Map<string, AbortController>;\n runtime: Runtime;\n serverLogger?: ServerLogger;\n socket: WebSocket;\n streams: Map<string, StreamEntry>;\n subscriptions: Map<string, SubscriptionEntry>;\n};\n\nclass OperationError extends Error {\n constructor(\n readonly code: ErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\nconst bytesOf = (data: RawData) => {\n if (Array.isArray(data)) {\n return Buffer.concat(data);\n }\n if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n};\n\nconst textOf = (data: RawData) => Buffer.from(bytesOf(data)).toString(\"utf8\");\n\nconst frameLength = (message: unknown) => {\n const frame = encodeProtocolFrame(message);\n return typeof frame === \"string\"\n ? Buffer.byteLength(frame, \"utf8\")\n : frame.byteLength;\n};\n\nconst operationIdOf = (value: unknown) => {\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n const operationId = (value as Record<string, unknown>).operationId;\n return typeof operationId === \"string\" && operationId.length <= 256\n ? operationId\n : undefined;\n};\n\nconst errorDetails = (cause: unknown): { code: ErrorCode; message: string } => {\n if (cause instanceof OperationError) {\n return { code: cause.code, message: cause.message };\n }\n if (cause instanceof ZodError || cause instanceof SyntaxError) {\n return {\n code: \"bad-request\",\n message:\n cause instanceof ZodError\n ? cause.issues\n .map(\n (issue) =>\n `${issue.path.join(\".\") || \"value\"}: ${issue.message}`,\n )\n .join(\"; \")\n : cause.message,\n };\n }\n return {\n code: \"internal\",\n message: cause instanceof Error ? cause.message : String(cause),\n };\n};\n\nconst send = (state: ConnectionState, message: ServerProtocolMessage) => {\n if (state.closed || state.socket.readyState !== WebSocket.OPEN) {\n return false;\n }\n // Apply outbound backpressure before queued messages consume unbounded memory.\n if (state.socket.bufferedAmount > maxWebSocketBufferedBytes) {\n state.socket.close(1013, \"client could not keep up\");\n return false;\n }\n state.socket.send(\n encodeProtocolFrame(serverProtocolMessageSchema.parse(message)),\n );\n return true;\n};\n\nconst sendError = (\n state: ConnectionState,\n cause: unknown,\n operationId?: string,\n identity?: OperationIdentity,\n) => {\n const error = errorDetails(cause);\n state.serverLogger?.log({\n correlationId: identity?.operationId ?? operationId ?? state.connectionId,\n details: {\n code: error.code,\n ...identity,\n ...diagnosticErrorDetails(cause),\n },\n event: \"protocol-handler-error\",\n level: \"error\",\n });\n send(state, { ...error, operationId, type: \"error\" });\n};\n\nconst disposeSubscription = async (\n state: ConnectionState,\n subscriptionId: string,\n) => {\n const entry = state.subscriptions.get(subscriptionId);\n if (!entry) {\n return;\n }\n state.subscriptions.delete(subscriptionId);\n entry.controller.abort(new Error(\"Resource subscription closed\"));\n await entry.dispose?.();\n};\n\nconst disposeStream = async (\n state: ConnectionState,\n streamId: string,\n notify = true,\n) => {\n const entry = state.streams.get(streamId);\n if (!entry) {\n if (notify) {\n send(state, { streamId, type: \"stream-closed\" });\n }\n return;\n }\n state.streams.delete(streamId);\n entry.controller.abort(new Error(\"Stream closed\"));\n await entry.session?.dispose();\n if (notify) {\n send(state, { streamId, type: \"stream-closed\" });\n }\n};\n\nconst disposeConnectionOperations = async (\n state: ConnectionState,\n notify: boolean,\n) => {\n const operationControllers = [...state.operations.values()];\n state.operations.clear();\n operationControllers.forEach((controller) =>\n controller.abort(new Error(\"WebSocket connection closed\")),\n );\n const subscriptionIds = [...state.subscriptions.keys()];\n const streamIds = [...state.streams.keys()];\n await Promise.allSettled([\n ...subscriptionIds.map((subscriptionId) =>\n disposeSubscription(state, subscriptionId),\n ),\n ...streamIds.map((streamId) => disposeStream(state, streamId, notify)),\n ]);\n};\n\nconst runOperation = (\n state: ConnectionState,\n identity: OperationIdentity,\n operation: (signal: AbortSignal) => Promise<void>,\n) => {\n if (state.operations.has(identity.operationId)) {\n sendError(\n state,\n new OperationError(\"conflict\", \"Operation ID is already active\"),\n identity.operationId,\n identity,\n );\n return;\n }\n const controller = new AbortController();\n const startedAt = Date.now();\n state.operations.set(identity.operationId, controller);\n state.serverLogger?.log({\n correlationId: identity.operationId,\n details: identity,\n event: \"operation-start\",\n });\n void operation(controller.signal)\n .then(() => {\n state.serverLogger?.log({\n correlationId: identity.operationId,\n details: identity,\n durationMs: Date.now() - startedAt,\n event: \"operation-complete\",\n });\n })\n .catch((cause: unknown) => {\n if (!controller.signal.aborted && !state.closed) {\n state.serverLogger?.log({\n correlationId: identity.operationId,\n details: { ...identity, ...diagnosticErrorDetails(cause) },\n durationMs: Date.now() - startedAt,\n event: \"operation-error\",\n level: \"error\",\n });\n sendError(state, cause, identity.operationId, identity);\n }\n })\n .finally(() => {\n if (state.operations.get(identity.operationId) === controller) {\n state.operations.delete(identity.operationId);\n }\n });\n};\n\nconst readResource = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"resource-read\" }>,\n) => {\n const resource = state.runtime.getResource(message.resourceName);\n const identity: OperationIdentity = {\n operationId: message.operationId,\n operationType: message.type,\n requestedName: message.resourceName,\n };\n runOperation(state, identity, async (signal) => {\n if (!resource) {\n throw new OperationError(\"not-found\", \"Resource not found\");\n }\n const output = await resource.read(message.input, signal);\n send(state, {\n operationId: message.operationId,\n output,\n type: \"resource-result\",\n });\n });\n};\n\nconst subscribeResource = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"resource-subscribe\" }>,\n) => {\n const resource = state.runtime.getResource(message.resourceName);\n const identity: OperationIdentity = {\n operationId: message.operationId,\n operationType: message.type,\n requestedName: message.resourceName,\n };\n if (state.subscriptions.has(message.subscriptionId)) {\n sendError(\n state,\n new OperationError(\"conflict\", \"Subscription ID is already active\"),\n message.operationId,\n identity,\n );\n return;\n }\n runOperation(state, identity, async (operationSignal) => {\n if (!resource) {\n throw new OperationError(\"not-found\", \"Resource not found\");\n }\n const controller = new AbortController();\n const entry: SubscriptionEntry = { controller };\n state.subscriptions.set(message.subscriptionId, entry);\n const signal = AbortSignal.any([operationSignal, controller.signal]);\n try {\n entry.dispose = resource.subscribe(\n message.input,\n () =>\n void send(state, {\n subscriptionId: message.subscriptionId,\n type: \"resource-invalidated\",\n }),\n signal,\n );\n } catch (cause) {\n await disposeSubscription(state, message.subscriptionId);\n throw cause;\n }\n });\n};\n\nconst openStream = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"stream-open\" }>,\n) => {\n const stream = state.runtime.getStream(message.streamName);\n const identity: OperationIdentity = {\n operationId: message.operationId,\n operationType: message.type,\n requestedName: message.streamName,\n };\n if (state.streams.has(message.streamId)) {\n sendError(\n state,\n new OperationError(\"conflict\", \"Stream ID is already active\"),\n message.operationId,\n identity,\n );\n return;\n }\n runOperation(state, identity, async (operationSignal) => {\n if (!stream) {\n throw new OperationError(\"not-found\", \"Stream not found\");\n }\n const controller = new AbortController();\n const entry: StreamEntry = { controller, identity };\n state.streams.set(message.streamId, entry);\n const pending: unknown[] = [];\n let pendingBytes = 0;\n let opened = false;\n try {\n entry.session = await stream.open(\n message.input,\n (output) => {\n if (opened) {\n const sent = send(state, {\n message: output,\n streamId: message.streamId,\n type: \"stream-output\",\n });\n if (!sent) {\n throw new Error(\"Stream output could not be delivered\");\n }\n return;\n }\n pendingBytes += frameLength(output);\n if (pendingBytes > maxPendingStreamOutputBytes) {\n throw new Error(\"Stream produced too much output while opening\");\n }\n pending.push(output);\n },\n AbortSignal.any([operationSignal, controller.signal]),\n (cause) => {\n sendError(state, cause, message.streamId, identity);\n void disposeStream(state, message.streamId).catch(\n (disposeCause: unknown) => {\n sendError(state, disposeCause, message.streamId, identity);\n },\n );\n },\n );\n send(state, {\n operationId: message.operationId,\n streamId: message.streamId,\n type: \"stream-opened\",\n });\n opened = true;\n for (const output of pending) {\n if (\n !send(state, {\n message: output,\n streamId: message.streamId,\n type: \"stream-output\",\n })\n ) {\n throw new Error(\"Stream output could not be delivered\");\n }\n }\n } catch (cause) {\n await disposeStream(state, message.streamId, false);\n throw cause;\n }\n });\n};\n\nconst sendStreamMessage = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"stream-message\" }>,\n) => {\n const entry = state.streams.get(message.streamId);\n const identity: OperationIdentity = {\n ...entry?.identity,\n operationId: message.streamId,\n operationType: message.type,\n };\n if (!entry?.session) {\n sendError(\n state,\n new OperationError(\"not-found\", \"Stream not found\"),\n message.streamId,\n identity,\n );\n return;\n }\n void entry.session.send(message.message).catch((cause: unknown) => {\n sendError(state, cause, message.streamId, identity);\n void disposeStream(state, message.streamId).catch(\n (disposeCause: unknown) => {\n sendError(state, disposeCause, message.streamId, identity);\n },\n );\n });\n};\n\nconst logClientDiagnostic = (\n state: ConnectionState,\n message: Extract<ClientProtocolMessage, { type: \"client-diagnostic\" }>,\n) => {\n if (!state.serverLogger?.enabled) {\n return;\n }\n state.serverLogger.log({\n details: {\n arguments: message.arguments,\n ...(message.stack ? { stack: message.stack } : {}),\n ...(message.url ? { url: message.url } : {}),\n },\n event: \"browser-console\",\n level: message.level === \"log\" ? \"info\" : message.level,\n message: message.message,\n source: \"browser\",\n timestamp: message.timestamp,\n });\n};\n\nconst handleMessage = (\n state: ConnectionState,\n message: ClientProtocolMessage,\n) => {\n if (message.type === \"client-diagnostic\") {\n logClientDiagnostic(state, message);\n return;\n }\n if (message.type === \"resource-read\") {\n readResource(state, message);\n return;\n }\n if (message.type === \"resource-subscribe\") {\n subscribeResource(state, message);\n return;\n }\n if (message.type === \"resource-unsubscribe\") {\n void disposeSubscription(state, message.subscriptionId).catch(\n (cause: unknown) => {\n sendError(state, cause, message.subscriptionId);\n },\n );\n return;\n }\n if (message.type === \"stream-open\") {\n openStream(state, message);\n return;\n }\n if (message.type === \"stream-close\") {\n void disposeStream(state, message.streamId).catch((cause: unknown) => {\n sendError(state, cause, message.streamId);\n });\n return;\n }\n sendStreamMessage(state, message);\n};\n\nconst handleFrame = (\n state: ConnectionState,\n data: RawData,\n isBinary: boolean,\n) => {\n let raw: unknown;\n try {\n raw = decodeProtocolFrame(isBinary ? bytesOf(data) : textOf(data));\n const result = clientProtocolMessageSchema.safeParse(raw);\n if (!result.success) {\n state.serverLogger?.log({\n correlationId: state.connectionId,\n details: diagnosticErrorDetails(result.error),\n event: \"protocol-parse-error\",\n level: \"error\",\n });\n sendError(state, result.error, operationIdOf(raw));\n return;\n }\n handleMessage(state, result.data);\n } catch (cause) {\n state.serverLogger?.log({\n correlationId: state.connectionId,\n details: diagnosticErrorDetails(cause),\n event: \"protocol-parse-error\",\n level: \"error\",\n });\n sendError(state, cause, operationIdOf(raw));\n }\n};\n\nconst disposeConnection = async (state: ConnectionState) => {\n if (state.closed) {\n return;\n }\n state.closed = true;\n state.serverLogger?.log({\n correlationId: state.connectionId,\n event: \"websocket-close\",\n });\n await disposeConnectionOperations(state, false);\n};\n\nconst createConnectionState = ({\n runtime,\n serverLogger,\n socket,\n}: {\n runtime: Runtime;\n serverLogger?: ServerLogger;\n socket: WebSocket;\n}): ConnectionState => ({\n closed: false,\n connectionId: serverLogger?.id(),\n operations: new Map(),\n runtime,\n serverLogger,\n socket,\n streams: new Map(),\n subscriptions: new Map(),\n});\n\nexport const attachWebSocketConnection = ({\n runtime,\n serverLogger,\n socket,\n}: {\n runtime: Runtime;\n serverLogger?: ServerLogger;\n socket: WebSocket;\n}) => {\n const state = createConnectionState({ runtime, serverLogger, socket });\n serverLogger?.log({\n correlationId: state.connectionId,\n event: \"websocket-open\",\n });\n socket.on(\"message\", (data, isBinary) => handleFrame(state, data, isBinary));\n socket.once(\"close\", (code, reason) => {\n serverLogger?.log({\n correlationId: state.connectionId,\n details: { code, reason: reason?.toString() ?? \"\" },\n event: \"websocket-close-event\",\n });\n void disposeConnection(state);\n });\n socket.once(\"error\", (cause) => {\n serverLogger?.log({\n correlationId: state.connectionId,\n details: diagnosticErrorDetails(cause),\n event: \"websocket-error\",\n level: \"error\",\n });\n void disposeConnection(state);\n });\n return () => disposeConnection(state);\n};\n","import type { IncomingMessage } from \"node:http\";\nimport type { Socket } from \"node:net\";\nimport type { Duplex } from \"node:stream\";\nimport { proxyUpgrade } from \"httpxy\";\n\nimport { webSocketCloseCode } from \"../shared/index\";\nimport type { AuthBoundary, RequestSession } from \"./auth/auth-http\";\nimport {\n errorDetails as diagnosticErrorDetails,\n type ServerLogger,\n} from \"./server-logger\";\n\ntype ProxiedSocket = {\n client: Duplex;\n closed: boolean;\n sessionId: string;\n timer: NodeJS.Timeout;\n upstream?: Socket;\n};\n\nconst setTrustedForwardingHeaders = (\n request: IncomingMessage,\n origin: string,\n) => {\n Object.keys(request.headers).forEach((name) => {\n if (\n name === \"authorization\" ||\n name === \"cookie\" ||\n name === \"forwarded\" ||\n name.startsWith(\"x-forwarded-\")\n ) {\n Reflect.deleteProperty(request.headers, name);\n }\n });\n const publicUrl = new URL(origin);\n request.headers[\"x-forwarded-for\"] = request.socket.remoteAddress;\n request.headers[\"x-forwarded-host\"] = publicUrl.host;\n request.headers[\"x-forwarded-port\"] =\n publicUrl.port || (publicUrl.protocol === \"https:\" ? \"443\" : \"80\");\n request.headers[\"x-forwarded-proto\"] = publicUrl.protocol.slice(0, -1);\n};\n\n// httpxy preserves an established WebSocket as a raw tunnel, so gateway-owned\n// revocation writes the server close frame before ending both sides.\nconst closeFrame = (code: number, reason: string) => {\n const payload = Buffer.allocUnsafe(2 + Buffer.byteLength(reason));\n payload.writeUInt16BE(code);\n payload.write(reason, 2);\n return Buffer.concat([Buffer.from([0x88, payload.length]), payload]);\n};\n\nconst closeSocket = (socket: ProxiedSocket, code: number, reason: string) => {\n if (socket.closed) {\n return;\n }\n socket.closed = true;\n clearInterval(socket.timer);\n if (!socket.client.destroyed) {\n socket.client.end(closeFrame(code, reason));\n }\n socket.upstream?.destroy();\n};\n\nconst revalidateSocket = async ({\n auth,\n serverLogger,\n origin,\n socket,\n token,\n}: {\n auth: AuthBoundary;\n origin: string;\n serverLogger?: ServerLogger;\n socket: ProxiedSocket;\n token: string;\n}) => {\n try {\n if (!(await auth.service.authenticateToken(token, origin))) {\n closeSocket(\n socket,\n webSocketCloseCode.authenticationRevoked,\n \"authentication revoked\",\n );\n }\n } catch (cause) {\n serverLogger?.log({\n details: diagnosticErrorDetails(cause),\n event: \"vite-websocket-session-revalidation-failure\",\n level: \"error\",\n });\n closeSocket(\n socket,\n webSocketCloseCode.authenticationUnavailable,\n \"authentication unavailable\",\n );\n }\n};\n\nexport const createViteWebSocketProxy = ({\n auth,\n serverLogger,\n target,\n}: {\n auth: AuthBoundary;\n serverLogger?: ServerLogger;\n target: string;\n}) => {\n const sockets = new Map<Duplex, ProxiedSocket>();\n\n const connect = ({\n correlationId,\n head,\n origin,\n request,\n session,\n socket,\n }: {\n correlationId?: string;\n head: Buffer;\n origin: string;\n request: IncomingMessage;\n session: RequestSession;\n socket: Duplex;\n }) => {\n let revalidationPending = false;\n const proxied: ProxiedSocket = {\n client: socket,\n closed: false,\n sessionId: session.id,\n timer: setInterval(() => {\n if (revalidationPending) {\n return;\n }\n revalidationPending = true;\n void revalidateSocket({\n auth,\n origin,\n serverLogger,\n socket: proxied,\n token: session.token,\n }).finally(() => {\n revalidationPending = false;\n });\n }, 1_000),\n };\n sockets.set(socket, proxied);\n socket.once(\"close\", () => {\n clearInterval(proxied.timer);\n sockets.delete(socket);\n });\n setTrustedForwardingHeaders(request, origin);\n void proxyUpgrade(target, request, socket, head, {\n changeOrigin: true,\n xfwd: false,\n }).then(\n (upstream) => {\n // Revocation can win while httpxy is opening the private side.\n if (proxied.closed) {\n upstream.destroy();\n return;\n }\n proxied.upstream = upstream;\n },\n (cause: unknown) => {\n clearInterval(proxied.timer);\n sockets.delete(socket);\n if (proxied.closed) {\n return;\n }\n proxied.closed = true;\n serverLogger?.log({\n correlationId,\n details: diagnosticErrorDetails(cause),\n event: \"vite-websocket-proxy-failure\",\n level: \"error\",\n });\n },\n );\n };\n\n return {\n close: () => {\n sockets.forEach((socket) =>\n closeSocket(socket, 1001, \"server shutting down\"),\n );\n sockets.clear();\n },\n connect,\n revoke: (ids: ReadonlySet<string>) => {\n sockets.forEach((socket) => {\n if (ids.has(socket.sessionId)) {\n closeSocket(\n socket,\n webSocketCloseCode.authenticationRevoked,\n \"authentication revoked\",\n );\n }\n });\n },\n };\n};\n","import type { ServerType as NodeServer } from \"@hono/node-server\";\nimport {\n encodeProtocolFrame,\n notificationEventSchema,\n serverProtocolMessageSchema,\n webSocketCloseCode,\n type ServerProtocolMessage,\n} from \"../shared/index\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { Duplex } from \"node:stream\";\nimport { WebSocket, WebSocketServer } from \"ws\";\n\nimport { runtimeWebSocketPath, viteHmrPath } from \"../shared/routes\";\nimport { attachWebSocketConnection } from \"./websocket-connection\";\nimport type { AuthBoundary, RequestSession } from \"./auth/auth-http\";\nimport {\n errorDetails as diagnosticErrorDetails,\n type ServerLogger,\n} from \"./server-logger\";\nimport type { Runtime } from \"./runtime/create-runtime\";\nimport { createViteWebSocketProxy } from \"./vite-websocket-proxy\";\nimport { maxWebSocketBufferedBytes } from \"./websocket-limits\";\n\nconst maxWebSocketPayloadBytes = 1_048_576;\n\n// Upgrade requests bypass Hono routing, so rejected paths need a raw HTTP response.\nconst rejectUpgrade = (socket: Duplex, status: number, message: string) => {\n socket.end(\n `HTTP/1.1 ${status} ${message}\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n`,\n );\n};\n\nconst requestPath = (request: IncomingMessage) => {\n try {\n return new URL(request.url ?? \"\", \"http://localhost\").pathname;\n } catch {\n return undefined;\n }\n};\n\nconst requestAuthenticationInput = (request: IncomingMessage) => {\n const host = request.headers.host;\n if (!host) {\n return;\n }\n const headers = new Headers();\n Object.entries(request.headers).forEach(([name, value]) => {\n if (Array.isArray(value)) {\n value.forEach((entry) => headers.append(name, entry));\n } else if (value !== undefined) {\n headers.set(name, value);\n }\n });\n const encrypted = Boolean(\n (request.socket as typeof request.socket & { encrypted?: boolean })\n .encrypted,\n );\n try {\n return new Request(\n `${encrypted ? \"https\" : \"http\"}://${host}${request.url ?? \"/\"}`,\n { headers },\n );\n } catch {\n return;\n }\n};\n\n// Tie a WebSocket to its session, periodically revalidating it and cleaning up\n// the session mapping when the connection closes.\nexport const attachSessionLifecycle = ({\n auth,\n serverLogger,\n session,\n sessionSockets,\n socket,\n}: {\n auth: AuthBoundary;\n serverLogger?: ServerLogger;\n session: RequestSession;\n sessionSockets: Map<WebSocket, string>;\n socket: WebSocket;\n}) => {\n sessionSockets.set(socket, session.id);\n let revalidationPending = false;\n const revalidationTimer = setInterval(() => {\n if (revalidationPending) {\n return;\n }\n revalidationPending = true;\n void auth.service\n .authenticateToken(session.token, session.origin)\n .then(\n (authenticated) => {\n if (!authenticated) {\n socket.close(\n webSocketCloseCode.authenticationRevoked,\n \"authentication revoked\",\n );\n }\n },\n (cause: unknown) => {\n serverLogger?.log({\n details: diagnosticErrorDetails(cause),\n event: \"websocket-session-revalidation-failure\",\n level: \"error\",\n });\n socket.close(\n webSocketCloseCode.authenticationUnavailable,\n \"authentication unavailable\",\n );\n },\n )\n .finally(() => {\n revalidationPending = false;\n });\n }, 1_000);\n socket.once(\"close\", () => {\n clearInterval(revalidationTimer);\n sessionSockets.delete(socket);\n });\n};\n\n// WebSocket upgrades bypass Hono but share its credential parser. Browser\n// sessions additionally require the exact canonical Origin; local bearer clients\n// are not browser-origin credentials. Each socket remains tied to its session so\n// explicit revocation closes it immediately, while periodic revalidation covers\n// expiration and changes made by another server process.\nexport const createWebSocketServer = ({\n auth,\n developmentWebTarget,\n runtime,\n server,\n serverLogger,\n}: {\n auth: AuthBoundary;\n developmentWebTarget?: string;\n runtime: Runtime;\n server: NodeServer;\n serverLogger?: ServerLogger;\n}) => {\n const webSocketServer = new WebSocketServer({\n maxPayload: maxWebSocketPayloadBytes,\n noServer: true,\n });\n let updateAvailable = false;\n const sessionSockets = new Map<WebSocket, string>();\n const viteProxy = developmentWebTarget\n ? createViteWebSocketProxy({\n auth,\n serverLogger,\n target: developmentWebTarget,\n })\n : undefined;\n const removeRevocationListener = auth.service.onSessionsRevoked((ids) => {\n sessionSockets.forEach((sessionId, socket) => {\n if (ids.has(sessionId)) {\n socket.close(\n webSocketCloseCode.authenticationRevoked,\n \"authentication revoked\",\n );\n }\n });\n viteProxy?.revoke(ids);\n });\n const onUpgrade = async (\n request: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n ) => {\n const correlationId = serverLogger?.id();\n serverLogger?.log({ correlationId, event: \"websocket-connect\" });\n const path = requestPath(request);\n const isRuntimeSocket = path === runtimeWebSocketPath;\n const isViteSocket =\n path === viteHmrPath && developmentWebTarget !== undefined;\n if (!isRuntimeSocket && !isViteSocket) {\n serverLogger?.log({\n correlationId,\n details: { status: 404 },\n event: \"websocket-connect-rejected\",\n level: \"warn\",\n });\n rejectUpgrade(socket, 404, \"Not Found\");\n return;\n }\n const authenticationInput = requestAuthenticationInput(request);\n if (!authenticationInput) {\n rejectUpgrade(socket, 400, \"Bad Request\");\n return;\n }\n const origin = auth.resolveOrigin({\n remoteAddress: request.socket.remoteAddress,\n request: authenticationInput,\n });\n let session: RequestSession | undefined;\n try {\n session = await auth.requests.authenticate(authenticationInput, origin);\n } catch (cause) {\n serverLogger?.log({\n correlationId,\n details: diagnosticErrorDetails(cause),\n event: \"websocket-authentication-failure\",\n level: \"error\",\n });\n rejectUpgrade(socket, 503, \"Service Unavailable\");\n return;\n }\n if (!session) {\n rejectUpgrade(socket, 401, \"Unauthorized\");\n return;\n }\n if (\n session.kind === \"browser\" &&\n (!origin || request.headers.origin !== origin)\n ) {\n rejectUpgrade(socket, 403, \"Forbidden\");\n return;\n }\n if (isViteSocket) {\n if (\n session.kind !== \"browser\" ||\n session.credential !== \"cookie\" ||\n !origin\n ) {\n rejectUpgrade(socket, 401, \"Unauthorized\");\n return;\n }\n if (!viteProxy) {\n rejectUpgrade(socket, 503, \"Service Unavailable\");\n return;\n }\n viteProxy.connect({\n correlationId,\n head,\n origin,\n request,\n session,\n socket,\n });\n return;\n }\n webSocketServer.handleUpgrade(request, socket, head, (webSocket) => {\n attachSessionLifecycle({\n auth,\n serverLogger,\n session,\n sessionSockets,\n socket: webSocket,\n });\n // Discovery precedes all connection traffic, including sticky announcements.\n webSocket.send(\n encodeProtocolFrame({\n type: \"server-info\",\n instanceId: runtime.instance.getInstanceId(),\n }),\n );\n webSocketServer.emit(\"connection\", webSocket, request);\n attachWebSocketConnection({ runtime, serverLogger, socket: webSocket });\n if (updateAvailable) {\n webSocket.send(encodeProtocolFrame({ type: \"update-available\" }));\n }\n });\n };\n server.on(\"upgrade\", onUpgrade);\n\n const broadcast = (message: ServerProtocolMessage) => {\n const frame = encodeProtocolFrame(\n serverProtocolMessageSchema.parse(message),\n );\n let delivered = 0;\n webSocketServer.clients.forEach((socket) => {\n if (socket.readyState !== WebSocket.OPEN) {\n return;\n }\n // Apply outbound backpressure by dropping slow clients before queued broadcasts consume unbounded memory.\n if (socket.bufferedAmount > maxWebSocketBufferedBytes) {\n socket.close(1013, \"client could not keep up\");\n return;\n }\n try {\n socket.send(frame);\n delivered += 1;\n } catch (cause) {\n socket.terminate();\n serverLogger?.log({\n details: diagnosticErrorDetails(cause),\n event: \"websocket-broadcast-failure\",\n level: \"error\",\n });\n }\n });\n return delivered;\n };\n\n return {\n announceRestarting: () => broadcast({ type: \"restarting\" }),\n announceUpdateAvailable: () => {\n updateAvailable = true;\n return broadcast({ type: \"update-available\" });\n },\n broadcastNotification: (notification: unknown) =>\n broadcast(\n notificationEventSchema.parse({\n notification,\n type: \"notification\",\n }),\n ),\n close: async () => {\n server.off(\"upgrade\", onUpgrade);\n removeRevocationListener();\n viteProxy?.close();\n webSocketServer.clients.forEach((socket) => socket.terminate());\n await new Promise<void>((resolve) =>\n webSocketServer.close(() => resolve()),\n );\n },\n };\n};\n","// Fits background notification payloads within the Web Push provider limit.\n// Input is validated by the notification service before this internal boundary.\nimport type { Notification } from \"../../../public/index\";\n\nconst maxPayloadBytes = 3_800;\n\nconst payloadBytes = (payload: unknown) =>\n new TextEncoder().encode(JSON.stringify(payload)).byteLength;\n\nconst largestFittingPrefix = (\n characters: string[],\n accepts: (prefix: string) => boolean,\n low = 0,\n high = characters.length,\n): string => {\n if (low >= high) {\n return characters.slice(0, low).join(\"\");\n }\n const middle = Math.ceil((low + high) / 2);\n return accepts(characters.slice(0, middle).join(\"\"))\n ? largestFittingPrefix(characters, accepts, middle, high)\n : largestFittingPrefix(characters, accepts, low, middle - 1);\n};\n\nconst notificationPayload = (notification: Notification) => ({\n notification,\n type: \"notification\" as const,\n});\n\nexport const createBackgroundNotificationPayload = (\n notification: Notification,\n) => {\n const original = notificationPayload(notification);\n if (payloadBytes(original) <= maxPayloadBytes) {\n return JSON.stringify(original);\n }\n\n const withoutBody = { ...notification, body: undefined };\n const body = largestFittingPrefix(\n [...(notification.body ?? \"\")],\n (prefix) =>\n payloadBytes(\n notificationPayload({\n ...withoutBody,\n ...(prefix ? { body: prefix } : {}),\n }),\n ) <= maxPayloadBytes,\n );\n const bodyTruncated = notificationPayload({\n ...withoutBody,\n ...(body ? { body } : {}),\n });\n if (payloadBytes(bodyTruncated) <= maxPayloadBytes) {\n return JSON.stringify(bodyTruncated);\n }\n\n const title = largestFittingPrefix(\n [...notification.title],\n (prefix) =>\n Boolean(prefix) &&\n payloadBytes(notificationPayload({ ...withoutBody, title: prefix })) <=\n maxPayloadBytes,\n );\n if (title) {\n return JSON.stringify(notificationPayload({ ...withoutBody, title }));\n }\n const safeTitle = largestFittingPrefix(\n [...notification.title],\n (prefix) =>\n Boolean(prefix) &&\n payloadBytes(notificationPayload({ title: prefix })) <= maxPayloadBytes,\n );\n return JSON.stringify(notificationPayload({ title: safeTitle || \"Overmux\" }));\n};\n","// Delivers background notifications through the browser Web Push standard.\n// Provider payload, VAPID signing, and expired endpoints remain inside this boundary.\nimport type { BackgroundNotificationSubscription } from \"../../shared/index\";\nimport type { Notification } from \"../../../public/index\";\nimport webPush from \"web-push\";\n\nimport { errorDetails, type ServerLogger } from \"../server-logger\";\nimport type { BackgroundNotificationStore } from \"./background-notification-store\";\nimport { createBackgroundNotificationPayload } from \"./background-notification-payload\";\n\nconst vapidSubject = \"https://github.com/richardgill/overmux\";\n\nconst webPushStatus = (cause: unknown) => {\n if (\n typeof cause === \"object\" &&\n cause !== null &&\n \"statusCode\" in cause &&\n typeof cause.statusCode === \"number\"\n ) {\n return cause.statusCode;\n }\n return undefined;\n};\n\nconst deliverToSubscription = async ({\n keys,\n logger,\n payload,\n sendWebPush,\n store,\n subscription,\n}: {\n keys: Awaited<ReturnType<BackgroundNotificationStore[\"getOrCreateKeys\"]>>;\n logger?: ServerLogger;\n payload: string;\n sendWebPush: typeof webPush.sendNotification;\n store: BackgroundNotificationStore;\n subscription: BackgroundNotificationSubscription;\n}) => {\n try {\n await sendWebPush(subscription, payload, {\n TTL: 60,\n vapidDetails: {\n privateKey: keys.privateKey,\n publicKey: keys.publicKey,\n subject: vapidSubject,\n },\n });\n } catch (cause) {\n const status = webPushStatus(cause);\n if (status === 404 || status === 410) {\n await store.removeSubscription(subscription.endpoint);\n }\n logger?.log({\n details: {\n ...errorDetails(cause),\n ...(status ? { status } : {}),\n },\n event: \"background-notification-delivery-failure\",\n level: \"warn\",\n });\n }\n};\n\nexport type BackgroundNotificationService = {\n disable: (endpoint: string) => Promise<void>;\n disableSessions: (sessionIds: ReadonlySet<string>) => Promise<void>;\n enable: (\n sessionId: string,\n subscription: BackgroundNotificationSubscription,\n ) => Promise<void>;\n publicKey: () => Promise<string>;\n send: (notification: Notification) => Promise<void>;\n};\n\nexport const createBackgroundNotificationService = ({\n isSessionActive = async () => true,\n logger,\n sendWebPush = webPush.sendNotification,\n store,\n}: {\n isSessionActive?: (sessionId: string) => Promise<boolean>;\n logger?: ServerLogger;\n sendWebPush?: typeof webPush.sendNotification;\n store: BackgroundNotificationStore;\n}): BackgroundNotificationService => {\n let keysPromise:\n | ReturnType<BackgroundNotificationStore[\"getOrCreateKeys\"]>\n | undefined;\n const getKeys = () => {\n if (!keysPromise) {\n keysPromise = store\n .getOrCreateKeys(webPush.generateVAPIDKeys)\n .catch((cause: unknown) => {\n keysPromise = undefined;\n throw cause;\n });\n }\n return keysPromise;\n };\n\n return {\n disable: (endpoint) => store.removeSubscription(endpoint),\n disableSessions: (sessionIds) =>\n store.removeSessionSubscriptions(sessionIds),\n enable: (sessionId, subscription) =>\n store.upsertSubscription(sessionId, subscription),\n publicKey: async () => (await getKeys()).publicKey,\n send: async (notification) => {\n const storedSubscriptions = await store.listSubscriptions();\n const active = await Promise.all(\n storedSubscriptions.map(async (entry) => ({\n active: await isSessionActive(entry.sessionId),\n entry,\n })),\n );\n const subscriptions = active.flatMap(\n ({ active: sessionActive, entry }) => (sessionActive ? [entry] : []),\n );\n if (!subscriptions.length) {\n return;\n }\n const keys = await getKeys();\n const payload = createBackgroundNotificationPayload(notification);\n await Promise.all(\n subscriptions.map((entry) =>\n deliverToSubscription({\n keys,\n logger,\n payload,\n sendWebPush,\n store,\n subscription: entry.subscription,\n }),\n ),\n );\n },\n };\n};\n","// Defines replaceable persistence for background-notification keys and subscriptions.\n// The file implementation owns the required XDG data location and atomic updates.\nimport {\n backgroundNotificationSubscriptionSchema,\n type BackgroundNotificationSubscription,\n} from \"../../shared/index\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\n\nimport { getOvermuxPaths } from \"../paths\";\nimport {\n createPrivateJsonExclusively,\n readPrivateJson,\n replacePrivateJsonAtomically,\n} from \"./private-json-file\";\n\nconst vapidKeysSchema = z\n .object({ privateKey: z.string().min(1), publicKey: z.string().min(1) })\n .strict();\nconst storedSubscriptionSchema = z.object({\n sessionId: z.string(),\n subscription: backgroundNotificationSubscriptionSchema,\n});\nconst subscriptionsSchema = z.array(storedSubscriptionSchema);\n\ntype VapidKeys = z.infer<typeof vapidKeysSchema>;\nexport type StoredBackgroundNotificationSubscription = z.infer<\n typeof storedSubscriptionSchema\n>;\n\nexport type BackgroundNotificationStore = {\n getOrCreateKeys: (generate: () => VapidKeys) => Promise<VapidKeys>;\n listSubscriptions: () => Promise<\n readonly StoredBackgroundNotificationSubscription[]\n >;\n removeSessionSubscriptions: (\n sessionIds: ReadonlySet<string>,\n ) => Promise<void>;\n removeSubscription: (endpoint: string) => Promise<void>;\n upsertSubscription: (\n sessionId: string,\n subscription: BackgroundNotificationSubscription,\n ) => Promise<void>;\n};\n\nconst backgroundNotificationDataDirectory = ({\n environment,\n homeDirectory,\n}: {\n environment: NodeJS.ProcessEnv;\n homeDirectory: string;\n}) =>\n join(\n getOvermuxPaths({ environment, homeDir: homeDirectory }).dataDir,\n \"background-notifications\",\n );\n\nexport const createFileBackgroundNotificationStore = ({\n environment = process.env,\n homeDirectory = homedir(),\n}: {\n environment?: NodeJS.ProcessEnv;\n homeDirectory?: string;\n} = {}): BackgroundNotificationStore => {\n const directory = backgroundNotificationDataDirectory({\n environment,\n homeDirectory,\n });\n const keysPath = join(directory, \"vapid.json\");\n const subscriptionsPath = join(directory, \"subscriptions.json\");\n let pendingSubscriptionWrite = Promise.resolve();\n\n const readSubscriptions = async () =>\n (await readPrivateJson(subscriptionsPath, subscriptionsSchema)) ?? [];\n\n const updateSubscriptions = (\n update: (\n subscriptions: StoredBackgroundNotificationSubscription[],\n ) => StoredBackgroundNotificationSubscription[] | undefined,\n ) => {\n const operation = pendingSubscriptionWrite.then(async () => {\n const subscriptions = await readSubscriptions();\n const updated = update(subscriptions);\n if (updated) {\n await replacePrivateJsonAtomically(subscriptionsPath, updated);\n }\n });\n pendingSubscriptionWrite = operation.catch(() => undefined);\n return operation;\n };\n\n return {\n getOrCreateKeys: async (generate) => {\n const existing = await readPrivateJson(keysPath, vapidKeysSchema);\n if (existing) {\n return existing;\n }\n const generated = vapidKeysSchema.parse(generate());\n try {\n await createPrivateJsonExclusively(keysPath, generated);\n return generated;\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw cause;\n }\n const concurrentlyCreated = await readPrivateJson(\n keysPath,\n vapidKeysSchema,\n );\n if (!concurrentlyCreated) {\n throw cause;\n }\n return concurrentlyCreated;\n }\n },\n listSubscriptions: async () => {\n await pendingSubscriptionWrite;\n return readSubscriptions();\n },\n removeSubscription: (endpoint) =>\n updateSubscriptions((subscriptions) => {\n if (\n !subscriptions.some(\n (entry) => entry.subscription.endpoint === endpoint,\n )\n ) {\n return undefined;\n }\n return subscriptions.filter(\n (entry) => entry.subscription.endpoint !== endpoint,\n );\n }),\n removeSessionSubscriptions: (sessionIds) =>\n updateSubscriptions((subscriptions) => {\n const updated = subscriptions.filter(\n (entry) => !sessionIds.has(entry.sessionId),\n );\n return updated.length === subscriptions.length ? undefined : updated;\n }),\n upsertSubscription: (sessionId, subscription) => {\n const parsed =\n backgroundNotificationSubscriptionSchema.parse(subscription);\n return updateSubscriptions((subscriptions) => {\n const entry = { sessionId, subscription: parsed };\n const existing = subscriptions.find(\n (candidate) => candidate.subscription.endpoint === parsed.endpoint,\n );\n if (isDeepStrictEqual(existing, entry)) {\n return undefined;\n }\n return [\n ...subscriptions.filter(\n (candidate) => candidate.subscription.endpoint !== parsed.endpoint,\n ),\n entry,\n ];\n });\n },\n };\n};\n","import {\n packageSourceSnippet,\n techStackRecommendationsSnippet,\n type AiContextSnippet,\n} from \"@overmux/shared\";\n\nexport {\n packageSourceSnippet,\n techStackRecommendationsSnippet,\n type AiContextSnippet,\n};\nexport type AiContextSnippetDefinition = readonly AiContextSnippet[];\n\nexport const coreAiContextSnippets = [\n packageSourceSnippet,\n] as const satisfies AiContextSnippetDefinition;\nexport const defaultAiContextSnippets = [\n ...coreAiContextSnippets,\n techStackRecommendationsSnippet,\n] as const satisfies AiContextSnippetDefinition;\n\nconst packageSourceSnippetContent = `Overmux ships with documentation and TypeScript source.\n\nRun \\`overmux docs\\` to find the installed documentation and source for the overmux cli.\n\nE.g. \\`node_modules/overmux\\` and \\`node_modules/@overmux/xterm\\`.\n\nInspect these files so guidance matches the versions used by the application.`;\n\nconst techStackRecommendationsSnippetContent = `Prefer pnpm as the package manager, TanStack Router for routing, shadcn/ui for UI components, and Zod for schemas and runtime validation. Follow the application's established stack when it already differs.`;\n\nconst aiContextContentBySnippet: Record<AiContextSnippet, string> = {\n [packageSourceSnippet]: packageSourceSnippetContent,\n [techStackRecommendationsSnippet]: techStackRecommendationsSnippetContent,\n};\n\nexport const composeAiContext = (snippets: AiContextSnippetDefinition) =>\n snippets.length === 0\n ? \"\"\n : `${snippets\n .map(\n (snippet) => `## ${snippet}\\n\\n${aiContextContentBySnippet[snippet]}`,\n )\n .join(\"\\n\\n\")}\\n`;\n","import { z } from \"zod\";\n\nexport const noInputSchema = z.void();\n\nexport const jsonValueSchema: z.ZodType<unknown> = z.lazy(() =>\n z.union([\n z.string(),\n z.number().finite(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(z.string(), jsonValueSchema),\n ]),\n);\n\nexport const parseJsonValue = <T>(value: T): T =>\n jsonValueSchema.parse(value) as T;\n\nexport type ContractInputArguments<TInput extends z.ZodType> =\n undefined extends z.input<TInput>\n ? [input?: Exclude<z.input<TInput>, undefined>]\n : [input: z.input<TInput>];\n\nexport type ResourceContract<\n TInput extends z.ZodType = z.ZodType,\n TOutput extends z.ZodType = z.ZodType,\n> = {\n input: TInput;\n output: TOutput;\n};\n\nexport const defineResourceContract = <\n TInput extends z.ZodType,\n TOutput extends z.ZodType,\n>(\n contract: ResourceContract<TInput, TOutput>,\n): ResourceContract<TInput, TOutput> => contract;\n\nexport type StreamContract<\n TInput extends z.ZodType = z.ZodType,\n TClientMessage extends z.ZodType = z.ZodType,\n TServerMessage extends z.ZodType = z.ZodType,\n> = {\n clientMessage: TClientMessage;\n input: TInput;\n serverMessage: TServerMessage;\n};\n\nexport const defineStreamContract = <\n TInput extends z.ZodType,\n TClientMessage extends z.ZodType,\n TServerMessage extends z.ZodType,\n>(\n contract: StreamContract<TInput, TClientMessage, TServerMessage>,\n): StreamContract<TInput, TClientMessage, TServerMessage> => contract;\n","// Orchestrates operation notifications across live and background delivery.\n// Provider-specific details stay behind the background-notification service.\nimport {\n notificationSchema,\n type Notification,\n type Notifications,\n} from \"../../../public/index\";\n\nimport { errorDetails, type ServerLogger } from \"../server-logger\";\nimport type { BackgroundNotificationService } from \"./background-notification-service\";\n\ntype NotificationService = Notifications & {\n attachLiveDelivery: (deliver: (notification: Notification) => void) => void;\n};\n\nconst deliverSafely = async ({\n deliver,\n event,\n logger,\n}: {\n deliver: () => void | Promise<void>;\n event: string;\n logger?: ServerLogger;\n}) => {\n try {\n await deliver();\n } catch (cause) {\n logger?.log({\n details: errorDetails(cause),\n event,\n level: \"error\",\n });\n }\n};\n\nexport const createNotificationService = ({\n backgroundNotifications,\n logger,\n}: {\n backgroundNotifications: BackgroundNotificationService;\n logger?: ServerLogger;\n}): NotificationService => {\n let liveDeliveryAttached = false;\n let deliverLive: (notification: Notification) => void = () => undefined;\n\n return {\n send: async (input) => {\n const notification = notificationSchema.parse(input);\n await Promise.all([\n deliverSafely({\n deliver: () => deliverLive(notification),\n event: \"live-notification-dispatch-failure\",\n logger,\n }),\n deliverSafely({\n deliver: () => backgroundNotifications.send(notification),\n event: \"background-notification-dispatch-failure\",\n logger,\n }),\n ]);\n },\n attachLiveDelivery: (deliver) => {\n if (liveDeliveryAttached) {\n throw new Error(\"Live delivery is already attached\");\n }\n liveDeliveryAttached = true;\n deliverLive = deliver;\n },\n };\n};\n","import { hostname } from \"node:os\";\nimport type { RuntimeConfigDefinition } from \"@overmux/shared/node\";\nimport {\n createInstanceIdentity,\n type InstanceIdentity,\n} from \"../../shared/index\";\nimport type { InstanceContext } from \"../../../public/config\";\n\n// The scope exists during preparation, but identity is immutable once the listener\n// binds. No handler or connection may observe it before establishment.\nexport const createRuntimeInstance = (\n configured: RuntimeConfigDefinition[\"instanceId\"],\n) => {\n let identity: InstanceIdentity | undefined;\n const get = () => {\n if (!identity) {\n throw new Error(\"Overmux instance identity is not ready\");\n }\n return identity;\n };\n const context: InstanceContext = {\n getInstanceId: () => get().instanceId,\n getDeepLinkPrefix: () => get().deepLinkPrefix,\n };\n return {\n context,\n establish: (port: number) => {\n if (identity) {\n throw new Error(\"Overmux instance identity is already established\");\n }\n try {\n identity = createInstanceIdentity(\n typeof configured === \"function\"\n ? configured({ port })\n : (configured ?? `${hostname()}-${port}`),\n );\n } catch (cause) {\n throw new Error(\n \"Invalid Overmux instance ID; configure instanceId with a canonical lowercase ID\",\n { cause },\n );\n }\n return identity;\n },\n };\n};\n","// Composes runtime and request cancellation while owning asynchronous cleanup.\n// Tracked disposers run exactly once, and aggregate shutdown reports every failure.\n\nimport type { RuntimeDisposer } from \"../../../public/index\";\n\nexport type RuntimeLifecycle = {\n completePreparation: () => void;\n dispose: (reason?: unknown) => Promise<void>;\n disposeAll: (disposers: Iterable<RuntimeDisposer>) => Promise<void>;\n requestSignal: (signal?: AbortSignal) => AbortSignal;\n signal: AbortSignal;\n track: (dispose: RuntimeDisposer, signal?: AbortSignal) => RuntimeDisposer;\n};\n\nconst asError = (cause: unknown) =>\n cause instanceof Error ? cause : new Error(String(cause));\n\nconst disposeAll = async (disposers: Iterable<RuntimeDisposer>) => {\n const results = await Promise.allSettled(\n [...disposers].map(async (dispose) => dispose()),\n );\n const errors = results.flatMap((result) =>\n result.status === \"rejected\" ? [asError(result.reason)] : [],\n );\n if (errors.length) {\n throw new AggregateError(errors, \"Runtime disposal failed\");\n }\n};\n\nexport const createRuntimeLifecycle = (\n preparationSignal?: AbortSignal,\n): RuntimeLifecycle => {\n const controller = new AbortController();\n const activeDisposers = new Set<RuntimeDisposer>();\n let disposal: Promise<void> | undefined;\n const abortPreparation = () => controller.abort(preparationSignal?.reason);\n preparationSignal?.addEventListener(\"abort\", abortPreparation, {\n once: true,\n });\n if (preparationSignal?.aborted) {\n abortPreparation();\n }\n\n const completePreparation = () => {\n preparationSignal?.removeEventListener(\"abort\", abortPreparation);\n };\n const requestSignal = (signal?: AbortSignal) =>\n signal ? AbortSignal.any([controller.signal, signal]) : controller.signal;\n const track = (\n dispose: RuntimeDisposer,\n signal?: AbortSignal,\n ): RuntimeDisposer => {\n let pending: Promise<void> | undefined;\n const disposeOnce = () => {\n if (pending) {\n return pending;\n }\n controller.signal.removeEventListener(\"abort\", onAbort);\n signal?.removeEventListener(\"abort\", onAbort);\n activeDisposers.delete(disposeOnce);\n pending = Promise.resolve().then(dispose);\n return pending;\n };\n const onAbort = () => {\n void disposeOnce().catch(() => undefined);\n };\n activeDisposers.add(disposeOnce);\n controller.signal.addEventListener(\"abort\", onAbort, { once: true });\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (controller.signal.aborted || signal?.aborted) {\n onAbort();\n }\n return disposeOnce;\n };\n const dispose = (reason: unknown = new Error(\"Runtime disposed\")) => {\n if (disposal) {\n return disposal;\n }\n completePreparation();\n const pending = [...activeDisposers];\n activeDisposers.clear();\n controller.abort(reason);\n disposal = disposeAll(pending);\n return disposal;\n };\n\n return {\n completePreparation,\n dispose,\n disposeAll,\n requestSignal,\n signal: controller.signal,\n track,\n };\n};\n","// Resource invalidation follows relationships among configured resources.\n// This model owns those relationships and their invariants before runtime work begins.\n\nimport type { ResourceDefinition } from \"../../../public/index\";\n\n// A dependency supplies a derived resource's value; a dependant consumes that value.\n// Keeping both directions makes reads follow dependencies while invalidation follows dependants.\nexport type ResourceDependencyGraph = Readonly<{\n dependencies: ReadonlyMap<string, ReadonlySet<string>>;\n dependants: ReadonlyMap<string, ReadonlySet<string>>;\n}>;\n\ntype MutableResourceGraph = Map<string, Set<string>>;\n\nconst emptyGraphFor = (resourceIds: readonly string[]): MutableResourceGraph =>\n new Map(resourceIds.map((resourceId) => [resourceId, new Set<string>()]));\n\nconst visitDependencies = ({\n dependencies,\n path,\n resourceId,\n visited,\n visiting,\n}: {\n dependencies: ReadonlyMap<string, ReadonlySet<string>>;\n path: readonly string[];\n resourceId: string;\n visited: Set<string>;\n visiting: Set<string>;\n}) => {\n if (visiting.has(resourceId)) {\n throw new Error(\n `Resource dependency cycle: ${[...path, resourceId].join(\" -> \")}`,\n );\n }\n if (visited.has(resourceId)) {\n return;\n }\n visiting.add(resourceId);\n dependencies.get(resourceId)?.forEach((dependencyId) => {\n visitDependencies({\n dependencies,\n path: [...path, resourceId],\n resourceId: dependencyId,\n visited,\n visiting,\n });\n });\n visiting.delete(resourceId);\n visited.add(resourceId);\n};\n\nconst assertAcyclic = (\n dependencies: ReadonlyMap<string, ReadonlySet<string>>,\n) => {\n // Derived reads recurse through dependencies, so a cycle could never produce a value or finish activation.\n const visited = new Set<string>();\n const visiting = new Set<string>();\n dependencies.forEach((_, resourceId) => {\n visitDependencies({\n dependencies,\n path: [],\n resourceId,\n visited,\n visiting,\n });\n });\n};\n\nexport const createResourceDependencyGraph = (\n resources: Readonly<Record<string, ResourceDefinition>>,\n): ResourceDependencyGraph => {\n const resourceIds = Object.keys(resources);\n if (resourceIds.some((resourceId) => !resourceId)) {\n throw new Error(\"Resource IDs must not be empty\");\n }\n const dependencies = emptyGraphFor(resourceIds);\n const dependants = emptyGraphFor(resourceIds);\n\n Object.entries(resources).forEach(([resourceId, resource]) => {\n if (resource.kind !== \"derived\") {\n return;\n }\n Object.entries(\n resource.dependencies as Readonly<Record<string, string>>,\n ).forEach(([dependencyName, dependencyId]) => {\n if (!dependencyName) {\n throw new Error(`Resource ${resourceId} has an empty dependency name`);\n }\n if (!dependencyId) {\n throw new Error(`Resource ${resourceId} has an empty dependency ID`);\n }\n if (!dependencies.has(dependencyId)) {\n throw new Error(`Unknown resource dependency: ${dependencyId}`);\n }\n dependencies.get(resourceId)?.add(dependencyId);\n dependants.get(dependencyId)?.add(resourceId);\n });\n });\n\n assertAcyclic(dependencies);\n return Object.freeze({ dependencies, dependants });\n};\n\nconst collectInvalidatedResourceIds = (\n graph: ResourceDependencyGraph,\n resourceId: string,\n invalidated: Set<string>,\n) => {\n if (invalidated.has(resourceId)) {\n return;\n }\n invalidated.add(resourceId);\n graph.dependants.get(resourceId)?.forEach((dependantId) => {\n collectInvalidatedResourceIds(graph, dependantId, invalidated);\n });\n};\n\nexport const getInvalidatedResourceIds = (\n graph: ResourceDependencyGraph,\n resourceId: string,\n): ReadonlySet<string> => {\n // A changed value invalidates itself and the full reverse-edge closure, not just immediate consumers.\n // Set membership is essential for diamonds: a shared dependant must notify once despite multiple paths.\n const invalidated = new Set<string>();\n collectInvalidatedResourceIds(graph, resourceId, invalidated);\n return invalidated;\n};\n","// Owns named runtime resource lookup, validated reads, dependency watchers, and invalidation.\n\nimport {\n type HandlerContext,\n type ResourceDefinition,\n type RuntimeDisposer,\n} from \"../../../public/index\";\nimport type { ResourceContract } from \"../../../public/index\";\nimport { isDeepStrictEqual } from \"node:util\";\n\nimport {\n createResourceDependencyGraph,\n getInvalidatedResourceIds,\n} from \"./resource-dependency-graph\";\nimport type { RuntimeLifecycle } from \"./runtime-lifecycle\";\n\nexport type RuntimeResource = {\n read: (input: unknown, signal?: AbortSignal) => Promise<unknown>;\n subscribe: (\n input: unknown,\n listener: () => void,\n signal?: AbortSignal,\n ) => RuntimeDisposer;\n};\n\nexport type RuntimeResourceDefinitions = Readonly<\n Record<string, ResourceDefinition>\n>;\n\nexport type RuntimeResources = {\n context: (signal?: AbortSignal) => HandlerContext;\n get: (name: string) => RuntimeResource | undefined;\n invalidate: (contract: ResourceContract, input?: unknown) => void;\n names: readonly string[];\n};\n\ntype InvalidationListener = {\n input: unknown;\n listener: () => void;\n resourceId: string;\n};\n\ntype CreateRuntimeResourcesOptions = {\n definitions: RuntimeResourceDefinitions;\n instance: HandlerContext[\"instance\"];\n lifecycle: RuntimeLifecycle;\n};\n\nexport const createRuntimeResources = ({\n definitions,\n instance,\n lifecycle,\n}: CreateRuntimeResourcesOptions): RuntimeResources => {\n const graph = createResourceDependencyGraph(definitions);\n const invalidationListeners = new Set<InvalidationListener>();\n const contracts = new Map<ResourceContract, string[]>();\n const resources = new Map<string, RuntimeResource>();\n\n Object.entries(definitions).forEach(([id, definition]) => {\n contracts.set(definition.contract, [\n ...(contracts.get(definition.contract) ?? []),\n id,\n ]);\n });\n\n const invalidateResource = (\n id: string,\n input: unknown,\n allInputs = false,\n ) => {\n if (lifecycle.signal.aborted) {\n return;\n }\n const ids = getInvalidatedResourceIds(graph, id);\n invalidationListeners.forEach((entry) => {\n if (\n ids.has(entry.resourceId) &&\n (allInputs || isDeepStrictEqual(entry.input, input))\n ) {\n entry.listener();\n }\n });\n };\n\n const invalidate = (contract: ResourceContract, input?: unknown) => {\n const ids =\n contracts.get(contract) ??\n Object.entries(definitions)\n .filter(\n ([, definition]) =>\n definition.contract.input === contract.input &&\n definition.contract.output === contract.output,\n )\n .map(([id]) => id);\n if (!ids.length) {\n throw new Error(\"Cannot invalidate a resource outside this runtime\");\n }\n ids.forEach((id) => {\n const definition = definitions[id]!;\n const parsedInput =\n input === undefined\n ? undefined\n : definition.contract.input.parse(input);\n invalidateResource(id, parsedInput, input === undefined);\n });\n };\n\n const context = (signal?: AbortSignal): HandlerContext => ({\n instance,\n invalidate,\n signal: lifecycle.requestSignal(signal),\n });\n\n const read = async (\n id: string,\n rawInput: unknown,\n signal?: AbortSignal,\n ): Promise<unknown> => {\n const definition = definitions[id]!;\n const operationSignal = lifecycle.requestSignal(signal);\n operationSignal.throwIfAborted();\n const input = definition.contract.input.parse(rawInput);\n const rawOutput =\n definition.kind === \"derived\"\n ? definition.combine(\n Object.fromEntries(\n await Promise.all(\n Object.entries(\n definition.dependencies as Readonly<Record<string, string>>,\n ).map(async ([name, dependencyId]) => [\n name,\n await read(dependencyId, rawInput, signal),\n ]),\n ),\n ),\n )\n : await definition.read(input, context(signal));\n operationSignal.throwIfAborted();\n return definition.contract.output.parse(rawOutput);\n };\n\n const activateWatchers = (\n id: string,\n rawInput: unknown,\n signal: AbortSignal | undefined,\n activated: Set<string>,\n disposers: RuntimeDisposer[],\n ) => {\n if (activated.has(id)) {\n return;\n }\n activated.add(id);\n const definition = definitions[id]!;\n const input = definition.contract.input.parse(rawInput);\n if (definition.kind === \"subscription\") {\n const dispose = definition.subscribe(\n input,\n () => invalidateResource(id, input),\n context(signal),\n );\n if (typeof dispose !== \"function\") {\n throw new Error(`Resource ${id} subscribe must return a disposer`);\n }\n disposers.push(dispose);\n return;\n }\n if (definition.kind === \"derived\") {\n graph.dependencies.get(id)?.forEach((dependencyId) => {\n activateWatchers(dependencyId, rawInput, signal, activated, disposers);\n });\n }\n };\n\n Object.keys(definitions).forEach((name) => {\n resources.set(name, {\n read: (input, signal) => read(name, input, signal),\n subscribe: (rawInput, listener, signal) => {\n lifecycle.requestSignal(signal).throwIfAborted();\n const input = definitions[name]!.contract.input.parse(rawInput);\n const entry = { input, listener, resourceId: name };\n const watcherDisposers: RuntimeDisposer[] = [];\n invalidationListeners.add(entry);\n try {\n activateWatchers(name, rawInput, signal, new Set(), watcherDisposers);\n } catch (cause) {\n invalidationListeners.delete(entry);\n void lifecycle.disposeAll(watcherDisposers).catch(() => undefined);\n throw cause;\n }\n return lifecycle.track(async () => {\n invalidationListeners.delete(entry);\n await lifecycle.disposeAll(watcherDisposers);\n }, signal);\n },\n });\n });\n\n return {\n context,\n get: (name) => resources.get(name),\n invalidate,\n names: [...resources.keys()],\n };\n};\n","// Owns named stream registration and ordered, validated session messaging.\n// Session abort, failure, and disposal remain exactly-once across every close path.\n\nimport type {\n HandlerContext,\n StreamHandlerDefinition,\n} from \"../../../public/index\";\nimport { z } from \"zod\";\n\nimport type { RuntimeLifecycle } from \"./runtime-lifecycle\";\n\nexport type RuntimeStreamSession = {\n dispose: () => Promise<void>;\n send: (message: unknown) => Promise<void>;\n};\n\nexport type RuntimeStream = {\n open: (\n input: unknown,\n emit: (message: unknown) => void,\n signal?: AbortSignal,\n onError?: (cause: unknown) => void,\n ) => Promise<RuntimeStreamSession>;\n};\n\nexport type RuntimeStreams = {\n get: (name: string) => RuntimeStream | undefined;\n names: readonly string[];\n};\n\ntype AnyStream = StreamHandlerDefinition<\n z.ZodTypeAny,\n z.ZodTypeAny,\n z.ZodTypeAny\n>;\n\nexport type RuntimeStreamDefinitions = Readonly<Record<string, AnyStream>>;\n\ntype CreateRuntimeStreamsOptions = {\n context: (signal?: AbortSignal) => HandlerContext;\n definitions: RuntimeStreamDefinitions;\n lifecycle: RuntimeLifecycle;\n};\n\nexport const createRuntimeStreams = ({\n context,\n definitions,\n lifecycle,\n}: CreateRuntimeStreamsOptions): RuntimeStreams => {\n const streams = new Map<string, RuntimeStream>();\n Object.entries(definitions).forEach(([name, definition]) => {\n if (!name) {\n throw new Error(\"Stream names must not be empty\");\n }\n streams.set(name, {\n open: async (rawInput, emit, requestSignal, onError) => {\n const sessionController = new AbortController();\n const sessionSignal = requestSignal\n ? AbortSignal.any([requestSignal, sessionController.signal])\n : sessionController.signal;\n const operationSignal = lifecycle.requestSignal(sessionSignal);\n operationSignal.throwIfAborted();\n const input = definition.contract.input.parse(rawInput);\n let acceptingMessages = true;\n let failed = false;\n let failure: unknown;\n let opened = false;\n const fail = (cause: unknown) => {\n if (failed || operationSignal.aborted) {\n return;\n }\n failed = true;\n failure = cause;\n acceptingMessages = false;\n sessionController.abort(cause);\n if (opened) {\n onError?.(cause);\n }\n };\n const session = await definition.open(input, {\n ...context(sessionSignal),\n emit: (message) => {\n if (operationSignal.aborted) {\n return;\n }\n try {\n emit(definition.contract.serverMessage.parse(message));\n } catch (cause) {\n fail(cause);\n }\n },\n fail,\n signal: operationSignal,\n });\n opened = true;\n if (failed || operationSignal.aborted) {\n await session.dispose?.();\n operationSignal.throwIfAborted();\n throw failure;\n }\n let messages = Promise.resolve();\n const dispose = lifecycle.track(async () => {\n acceptingMessages = false;\n sessionController.abort(new Error(\"Stream session disposed\"));\n await messages.catch(() => undefined);\n await session.dispose?.();\n }, requestSignal);\n return {\n dispose: async () => dispose(),\n send: async (rawMessage) => {\n if (!acceptingMessages) {\n throw new Error(\"Stream session is closed\");\n }\n const message = definition.contract.clientMessage.parse(rawMessage);\n messages = messages.then(async () => {\n operationSignal.throwIfAborted();\n await session.onMessage?.(message);\n operationSignal.throwIfAborted();\n });\n return messages;\n },\n };\n },\n });\n });\n return {\n get: (name) => streams.get(name),\n names: [...streams.keys()],\n };\n};\n","// Composes one process-lifetime runtime from cohesive lifecycle and protocol components.\n\nimport type { RuntimeConfigDefinition } from \"@overmux/shared/node\";\n\nimport type {\n InstanceContext,\n InstanceIdentity,\n Notifications,\n} from \"../../../public/index\";\nimport { createRuntimeInstance } from \"./runtime-instance\";\nimport { protocolVersion, type RuntimeManifest } from \"../../shared/index\";\n\nimport { createRuntimeLifecycle } from \"./runtime-lifecycle\";\nimport {\n createRuntimeOperations,\n type RuntimeOperation,\n type RuntimeOperationDefinitions,\n} from \"./runtime-operations\";\nimport {\n createRuntimeResources,\n type RuntimeResource,\n type RuntimeResourceDefinitions,\n} from \"./runtime-resources\";\nimport {\n createRuntimeStreams,\n type RuntimeStream,\n type RuntimeStreamDefinitions,\n} from \"./runtime-streams\";\n\nexport type Runtime = {\n instance: InstanceContext;\n establishInstance: (port: number) => InstanceIdentity;\n manifest: RuntimeManifest;\n dispose: () => Promise<void>;\n getOperation: (name: string) => RuntimeOperation | undefined;\n getResource: (name: string) => RuntimeResource | undefined;\n getStream: (name: string) => RuntimeStream | undefined;\n};\n\ntype CreateRuntimeOptions = {\n config: RuntimeConfigDefinition;\n debug?: boolean;\n notifications?: Notifications;\n signal?: AbortSignal;\n};\n\nexport const createRuntime = async ({\n config,\n debug = false,\n notifications = { send: async () => undefined },\n signal,\n}: CreateRuntimeOptions): Promise<Runtime> => {\n const lifecycle = createRuntimeLifecycle(signal);\n const instance = createRuntimeInstance(config.instanceId);\n try {\n const resources = createRuntimeResources({\n definitions: (config.server.resources ??\n {}) as RuntimeResourceDefinitions,\n instance: instance.context,\n lifecycle,\n });\n const context = resources.context;\n const operations = createRuntimeOperations({\n context,\n definitions: (config.server.operations ??\n {}) as RuntimeOperationDefinitions,\n notifications,\n });\n const streams = createRuntimeStreams({\n context,\n definitions: (config.server.streams ?? {}) as RuntimeStreamDefinitions,\n lifecycle,\n });\n\n lifecycle.signal.throwIfAborted();\n lifecycle.completePreparation();\n\n const manifest: RuntimeManifest = {\n debug,\n operations: [...operations.names],\n protocolVersion,\n resources: [...resources.names],\n streams: [...streams.names],\n };\n return {\n instance: instance.context,\n establishInstance: instance.establish,\n manifest,\n dispose: lifecycle.dispose,\n getOperation: operations.get,\n getResource: resources.get,\n getStream: streams.get,\n };\n } catch (cause) {\n await lifecycle.dispose(cause).catch(() => undefined);\n throw cause;\n }\n};\n","import {\n serverConfigRuntimeSchema,\n type RuntimeConfigDefinition,\n} from \"@overmux/shared/node\";\nimport { dirname, resolve } from \"node:path\";\nimport { z } from \"zod\";\n\nimport type { ServerConfigDefinition } from \"../../public/index\";\n\nconst serverStartupOverridesRuntimeSchema = serverConfigRuntimeSchema\n .omit({ port: true })\n .extend({\n // Port 0 asks the OS for a free port for internal listeners and tests; it must not leak into user config.\n port: z.number().int().min(0).max(65_535).optional(),\n });\n\nexport type ResolvedServerStartupOptions = {\n host: string;\n logFile?: string;\n port: number;\n productionWebAssetsDir?: string;\n watch: boolean;\n};\n\nexport const resolveServerStartupOptions = ({\n config,\n configPath,\n overrides = {},\n}: {\n config: RuntimeConfigDefinition;\n configPath: string;\n overrides?: ServerConfigDefinition;\n}): ResolvedServerStartupOptions => {\n const validatedOverrides =\n serverStartupOverridesRuntimeSchema.parse(overrides);\n const configuredLogFile = config.logFile\n ? resolve(dirname(configPath), config.logFile)\n : undefined;\n const logFile = validatedOverrides.logFile\n ? resolve(validatedOverrides.logFile)\n : configuredLogFile;\n const configuredWebAssetsDir = config.productionWebAssetsDir\n ? resolve(dirname(configPath), config.productionWebAssetsDir)\n : undefined;\n const productionWebAssetsDir = validatedOverrides.productionWebAssetsDir\n ? resolve(validatedOverrides.productionWebAssetsDir)\n : configuredWebAssetsDir;\n\n return {\n host: validatedOverrides.host ?? config.host ?? \"localhost\",\n ...(logFile === undefined ? {} : { logFile }),\n port: validatedOverrides.port ?? config.port ?? 4200,\n ...(productionWebAssetsDir === undefined ? {} : { productionWebAssetsDir }),\n watch: validatedOverrides.watch ?? config.watch ?? true,\n };\n};\n","// Starts one immutable application runtime inside the supervised child process.\n// It owns config loading, transport, and the listening socket.\n\nimport { serve, type ServerType as NodeServer } from \"@hono/node-server\";\nimport {\n loadOvermuxConfig,\n type RuntimeConfigDefinition,\n} from \"@overmux/shared/node\";\nimport { once } from \"node:events\";\nimport type { AddressInfo } from \"node:net\";\nimport { resolve } from \"node:path\";\n\nimport { createAuthService, type AuthService } from \"./auth/auth-service\";\nimport {\n createAuthBoundary,\n validateAuthOrigin,\n type AuthBoundary,\n} from \"./auth/auth-http\";\nimport { startInstanceControl } from \"./auth/instance-control\";\nimport { createHttpApp } from \"./http/create-http-app\";\nimport { createWebSocketServer } from \"./websocket-server\";\nimport {\n createBackgroundNotificationService,\n type BackgroundNotificationService,\n} from \"./notifications/background-notification-service\";\nimport { createFileBackgroundNotificationStore } from \"./notifications/background-notification-store\";\nimport { createNotificationService } from \"./notifications/notification-service\";\nimport { createRuntime, type Runtime } from \"./runtime/create-runtime\";\nimport {\n createServerLogger,\n errorDetails,\n type ServerLogger,\n} from \"./server-logger\";\nimport {\n resolveServerStartupOptions,\n type ResolvedServerStartupOptions,\n} from \"./server-startup-options\";\nimport type { OvermuxServerOptions } from \"./start-overmux-server\";\n\ntype ResourceCleanup = () => void | Promise<void>;\ntype ServerResources = ReturnType<typeof createResources>;\ntype NotificationService = ReturnType<typeof createNotificationService>;\ntype ApplicationLogger = ReturnType<typeof createServerLogger>;\ntype StartApplicationServerOptions = {\n onRestartRequested: () => void;\n options: OvermuxServerOptions;\n};\n\nexport type ApplicationServer = {\n announceUpdateAvailable: () => void;\n close: () => Promise<void>;\n host: string;\n port: number;\n url: string;\n watch: boolean;\n};\n\nconst cleanupResources = async (cleanups: ResourceCleanup[]) => {\n const errors: unknown[] = [];\n for (const cleanup of [...cleanups].reverse()) {\n try {\n await cleanup();\n } catch (cause) {\n errors.push(cause);\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Failed to clean up server resources\");\n }\n};\n\nconst createResources = () => {\n const cleanups: ResourceCleanup[] = [];\n let closePromise: Promise<void> | undefined;\n return {\n add: (cleanup: ResourceCleanup) => cleanups.push(cleanup),\n close: () => {\n const next = closePromise ?? cleanupResources(cleanups);\n closePromise = next;\n return next;\n },\n };\n};\n\nconst closeNodeServer = (\n server: NodeServer,\n cancelActiveWork: () => Promise<void>,\n): Promise<void> => {\n const closed = new Promise<void>((resolveClose, reject) => {\n server.close((error) => {\n if (\n error &&\n (error as NodeJS.ErrnoException).code !== \"ERR_SERVER_NOT_RUNNING\"\n ) {\n reject(error);\n return;\n }\n resolveClose();\n });\n });\n const cancellation = cancelActiveWork();\n if (\"closeAllConnections\" in server) {\n server.closeAllConnections();\n }\n return Promise.all([closed, cancellation]).then(() => undefined);\n};\n\nconst getServerAddress = async (server: NodeServer): Promise<AddressInfo> => {\n if (!server.address()) {\n await once(server, \"listening\");\n }\n const address = server.address();\n if (!address || typeof address === \"string\") {\n throw new Error(\"Overmux server did not bind a TCP address\");\n }\n return address;\n};\n\nconst registerProcessErrorLogging = (logger: ServerLogger) => {\n const onUncaughtException = (\n cause: Error,\n origin: \"uncaughtException\" | \"unhandledRejection\",\n ) =>\n logger.log({\n details: errorDetails(cause),\n event:\n origin === \"unhandledRejection\"\n ? \"unhandled-rejection\"\n : \"uncaught-exception\",\n level: \"error\",\n });\n process.on(\"uncaughtExceptionMonitor\", onUncaughtException);\n return () => {\n process.off(\"uncaughtExceptionMonitor\", onUncaughtException);\n };\n};\n\nconst loadServerSettings = async ({\n configPath,\n options,\n}: {\n configPath: string;\n options: OvermuxServerOptions;\n}) => {\n const { config } = await loadOvermuxConfig({\n aliases: options.configAliases,\n configPath,\n });\n const startup = resolveServerStartupOptions({\n config,\n configPath,\n overrides: options,\n });\n return { config, startup };\n};\n\nconst createAuthOrigins = ({\n configuredOrigins,\n startup,\n}: {\n configuredOrigins?: string[];\n startup: ResolvedServerStartupOptions;\n}) => {\n const urlHost = startup.host.includes(\":\")\n ? `[${startup.host}]`\n : startup.host;\n let values = (configuredOrigins ?? [`http://${urlHost}:${startup.port}`]).map(\n validateAuthOrigin,\n );\n return {\n establish: (localUrl: string) => {\n values = (configuredOrigins ?? [localUrl]).map(validateAuthOrigin);\n return values;\n },\n get: () => values,\n };\n};\n\nconst createApplicationServices = async ({\n config,\n logger,\n resources,\n startup,\n}: {\n config: RuntimeConfigDefinition;\n logger: ServerLogger;\n resources: ServerResources;\n startup: ResolvedServerStartupOptions;\n}) => {\n // Browser origins are fixed from trusted startup data, never discovered from\n // requests. Ephemeral listener ports are finalized after binding.\n const authOrigins = createAuthOrigins({\n configuredOrigins: config.auth.origins,\n startup,\n });\n const authService = createAuthService({ config: config.auth });\n const auth = createAuthBoundary({\n origins: authOrigins.get,\n service: authService,\n trustedProxyPeer: config.auth.trustedProxyPeer,\n });\n const backgroundNotifications = createBackgroundNotificationService({\n isSessionActive: authService.isSessionActive,\n logger,\n store: createFileBackgroundNotificationStore(),\n });\n // Background subscriptions belong to browser sessions, so revocation also\n // removes delivery credentials owned by those sessions.\n resources.add(\n authService.onSessionsRevoked((sessionIds) => {\n void backgroundNotifications\n .disableSessions(sessionIds)\n .catch((cause: unknown) => {\n logger.log({\n details: errorDetails(cause),\n event: \"background-notification-session-cleanup-failed\",\n level: \"error\",\n });\n });\n }),\n );\n const notifications = createNotificationService({\n backgroundNotifications,\n logger,\n });\n const runtime = await createRuntime({\n config,\n debug: logger.enabled,\n notifications,\n });\n resources.add(runtime.dispose);\n return {\n auth,\n authOrigins,\n authService,\n backgroundNotifications,\n notifications,\n runtime,\n };\n};\n\nconst startApplicationTransport = async ({\n auth,\n authOrigins,\n authService,\n backgroundNotifications,\n developmentWebTarget,\n logger,\n notifications,\n onRestartRequested,\n resources,\n runtime,\n startup,\n}: {\n auth: AuthBoundary;\n authOrigins: ReturnType<typeof createAuthOrigins>;\n authService: AuthService;\n backgroundNotifications: BackgroundNotificationService;\n developmentWebTarget?: string;\n logger: ServerLogger;\n notifications: NotificationService;\n onRestartRequested: () => void;\n resources: ServerResources;\n runtime: Runtime;\n startup: ResolvedServerStartupOptions;\n}) => {\n let announceRestarting: () => void = () => undefined;\n const app = createHttpApp({\n auth,\n backgroundNotifications,\n developmentWebTarget,\n onRestartRequested: () => {\n announceRestarting();\n onRestartRequested();\n },\n runtime,\n serverLogger: logger,\n webAssetsDir: developmentWebTarget\n ? undefined\n : startup.productionWebAssetsDir,\n });\n // Binding allocates the actual port. Reject early HTTP traffic until identity\n // and trusted origins are established; WebSocket upgrades attach only after that.\n let ready = false;\n const server = serve({\n fetch: (request, env) =>\n ready\n ? app.fetch(request, env)\n : new Response(\"Starting\", { status: 503 }),\n hostname: startup.host,\n port: startup.port,\n });\n resources.add(() => closeNodeServer(server, runtime.dispose));\n const address = await getServerAddress(server);\n runtime.establishInstance(address.port);\n const urlHost = startup.host.includes(\":\")\n ? `[${startup.host}]`\n : startup.host;\n const localUrl = `http://${urlHost}:${address.port}`;\n const controlApiHost =\n startup.host === \"0.0.0.0\"\n ? \"127.0.0.1\"\n : startup.host === \"::\"\n ? \"[::1]\"\n : urlHost;\n const origins = authOrigins.establish(localUrl);\n authService.setOrigins(origins);\n const webSockets = createWebSocketServer({\n auth,\n developmentWebTarget,\n runtime,\n server,\n serverLogger: logger,\n });\n resources.add(webSockets.close);\n announceRestarting = webSockets.announceRestarting;\n notifications.attachLiveDelivery(webSockets.broadcastNotification);\n ready = true;\n const instanceControl = await startInstanceControl({\n auth: authService,\n apiUrl: `http://${controlApiHost}:${address.port}`,\n instanceId: runtime.instance.getInstanceId(),\n port: address.port,\n url: origins[0]!,\n });\n resources.add(instanceControl.close);\n return { address, app, localUrl, webSockets };\n};\n\nconst closeApplicationServer = async ({\n app,\n logger,\n resources,\n}: {\n app: ReturnType<typeof createHttpApp>;\n logger: ServerLogger;\n resources: ServerResources;\n}) => {\n logger.log({ event: \"server-stop\" });\n app.beginShutdown();\n await resources.close();\n};\n\nconst failApplicationServerStartup = async (\n cause: unknown,\n resources: ServerResources,\n): Promise<never> => {\n try {\n await resources.close();\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Server startup and cleanup failed\",\n );\n }\n throw cause;\n};\n\nexport const startApplicationServer = async ({\n onRestartRequested,\n options,\n}: StartApplicationServerOptions): Promise<ApplicationServer> => {\n const logger = createServerLogger({\n enabled: options.debug ?? false,\n logFile: options.logFile ? resolve(options.logFile) : undefined,\n });\n const resources = createResources();\n resources.add(registerProcessErrorLogging(logger));\n\n try {\n const configPath = resolve(options.configPath);\n logger.log({ details: { configPath }, event: \"server-start\" });\n const { config, startup } = await loadServerSettings({\n configPath,\n options,\n });\n logger.setEnabled(Boolean(options.debug || config.debug));\n if (startup.logFile) {\n logger.setLogFile(startup.logFile);\n }\n const {\n auth,\n authOrigins,\n authService,\n backgroundNotifications,\n notifications,\n runtime,\n } = await createApplicationServices({\n config,\n logger,\n resources,\n startup,\n });\n const { address, app, localUrl, webSockets } =\n await startApplicationTransport({\n auth,\n authOrigins,\n authService,\n backgroundNotifications,\n developmentWebTarget: options.developmentWebTarget,\n logger,\n notifications,\n onRestartRequested,\n resources,\n runtime,\n startup,\n });\n\n return {\n announceUpdateAvailable: webSockets.announceUpdateAvailable,\n close: () => closeApplicationServer({ app, logger, resources }),\n host: startup.host,\n port: address.port,\n url: localUrl,\n watch: startup.watch,\n };\n } catch (cause) {\n return failApplicationServerStartup(cause, resources);\n }\n};\n","// Defines the complete validated IPC boundary between coordinator and child.\n// Application traffic never crosses this process boundary.\n\nimport { z } from \"zod\";\n\nconst childOptionsSchema = z.object({\n configAliases: z.record(z.string(), z.string()).optional(),\n configPath: z.string(),\n debug: z.boolean().optional(),\n developmentWebTarget: z.url().optional(),\n host: z.string().optional(),\n logFile: z.string().optional(),\n port: z.number().int().min(0).max(65_535).optional(),\n productionWebAssetsDir: z.string().optional(),\n watch: z.boolean().optional(),\n});\n\nconst parentMessageSchema = z.discriminatedUnion(\"type\", [\n z.object({ options: childOptionsSchema, type: z.literal(\"start\") }),\n z.object({ type: z.literal(\"update-available\") }),\n z.object({ type: z.literal(\"stop\") }),\n]);\n\nconst childMessageSchema = z.discriminatedUnion(\"type\", [\n z.object({\n host: z.string(),\n port: z.number().int().min(1).max(65_535),\n type: z.literal(\"ready\"),\n url: z.string(),\n watch: z.boolean(),\n }),\n z.object({ type: z.literal(\"restart-requested\") }),\n z.object({ message: z.string(), type: z.literal(\"startup-failed\") }),\n]);\n\nexport type ChildServerOptions = z.infer<typeof childOptionsSchema>;\nexport type ParentToChildMessage = z.infer<typeof parentMessageSchema>;\nexport type ChildToParentMessage = z.infer<typeof childMessageSchema>;\n\nexport const parseParentMessage = (value: unknown): ParentToChildMessage =>\n parentMessageSchema.parse(value);\n\nexport const parseChildMessage = (value: unknown): ChildToParentMessage =>\n childMessageSchema.parse(value);\n","// Executable entry for one fresh application-server child process.\n// It translates lifecycle IPC only and never retains state across restarts.\n\nimport { startApplicationServer } from \"../start-application-server\";\nimport { errorMessage } from \"../server-logger\";\nimport { parseParentMessage, type ChildToParentMessage } from \"./ipc-protocol\";\n\nconst send = (message: ChildToParentMessage) => {\n if (!process.connected) {\n return;\n }\n try {\n process.send?.(message, () => undefined);\n } catch {}\n};\n\nconst disconnect = () => {\n if (!process.connected) {\n return;\n }\n try {\n process.disconnect();\n } catch {}\n};\n\nconst runServerChild = () => {\n let serverPromise: ReturnType<typeof startApplicationServer> | undefined;\n let closing: Promise<void> | undefined;\n\n const close = () => {\n if (closing) {\n return closing;\n }\n closing =\n serverPromise?.then(\n (server) => server.close(),\n () => undefined,\n ) ?? Promise.resolve();\n return closing;\n };\n\n process.on(\"message\", (raw) => {\n let message;\n try {\n message = parseParentMessage(raw);\n } catch (cause) {\n send({ message: errorMessage(cause), type: \"startup-failed\" });\n return;\n }\n if (message.type === \"update-available\") {\n if (!closing) {\n void serverPromise?.then(\n (server) => server.announceUpdateAvailable(),\n () => undefined,\n );\n }\n return;\n }\n if (message.type === \"stop\") {\n void close()\n .catch((cause: unknown) => {\n process.stderr.write(\n `[overmux] child shutdown failed: ${errorMessage(cause)}\\n`,\n );\n })\n .finally(disconnect);\n return;\n }\n if (serverPromise || closing) {\n send({\n message: \"Server child received more than one start request\",\n type: \"startup-failed\",\n });\n return;\n }\n serverPromise = startApplicationServer({\n onRestartRequested: () => send({ type: \"restart-requested\" }),\n options: message.options,\n });\n void serverPromise\n .then((server) => {\n if (closing) {\n return;\n }\n send({\n host: server.host,\n port: server.port,\n type: \"ready\",\n url: server.url,\n watch: server.watch,\n });\n })\n .catch((cause: unknown) => {\n send({ message: errorMessage(cause), type: \"startup-failed\" });\n disconnect();\n });\n });\n\n process.once(\"disconnect\", () => {\n void close().catch((cause: unknown) => {\n process.stderr.write(\n `[overmux] disconnected child shutdown failed: ${errorMessage(cause)}\\n`,\n );\n });\n });\n};\n\nrunServerChild();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAOA,MAAMA,oBAAkB;AACxB,MAAMC,uBAAqB;CAC1B,GAAG,OAAO,KAAK;CACf,GAAG,OAAO;CACV,GAAG,KAAK;CACR,IAAI;CACJ,GAAG;AACJ;AACA,MAAMC,4BAA0B,aAAa;CAC5C,MAAM,QAAQF,kBAAgB,KAAK,QAAQ;CAC3C,IAAI,CAAC,OAAO;CACZ,MAAM,OAAO,MAAM;CACnB,MAAM,eAAe,OAAO,MAAM,EAAE,IAAIC,qBAAmB;CAC3D,OAAO,OAAO,cAAc,YAAY,IAAI,eAAe,KAAK;AACjE;AACA,MAAM,oBAAoB,CAAC,kBAAkB,4BAA4B;AAGzE,MAAME,qBAAmB,EAAE,OAAO,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,MAAM,+CAA+C,6FAA6F;AAG/L,MAAM,gBAAgB,EAAE,QAAQ,UAAU,iBAAiB,EAAE,SAAS,uBAAuB;AAC7F,MAAM,iBAAiB,EAAE,QAAQ,UAAU,OAAO,UAAU,YAAY,qBAAqB;AAC7F,MAAM,wBAAwB,EAAE,OAAO;CACtC,OAAO;CACP,QAAQ;AACT,CAAC;AACD,MAAM,yBAAyB,EAAE,OAAO;CACvC,QAAQ;CACR,OAAO;CACP,QAAQ;AACT,CAAC;AACD,MAAM,6BAA6B,EAAE,OAAO;CAC3C,UAAU,EAAE,OAAO;EAClB,eAAe;EACf,OAAO;EACP,eAAe;CAChB,CAAC;CACD,MAAM;AACP,CAAC;AACD,MAAM,kCAAkC,EAAE,mBAAmB,QAAQ;CACpE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