dsh-auth-remote 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/CHANGELOG.zh-CN.md +16 -0
  3. package/CONTRIBUTING.md +23 -0
  4. package/CONTRIBUTING.zh-CN.md +23 -0
  5. package/LICENSE +21 -0
  6. package/README.md +65 -0
  7. package/README.zh-CN.md +65 -0
  8. package/cordis.patch.yml +45 -0
  9. package/dist/cli.js +1858 -0
  10. package/dist/cli.js.map +7 -0
  11. package/dist/client.js +3076 -0
  12. package/dist/client.js.map +7 -0
  13. package/dist/index.js +2473 -0
  14. package/dist/index.js.map +7 -0
  15. package/dist/login.css +230 -0
  16. package/dist/login.css.map +7 -0
  17. package/dist/login.js +2865 -0
  18. package/dist/login.js.map +7 -0
  19. package/dist/types/adapters/dsh/browser-auth.d.ts +8 -0
  20. package/dist/types/adapters/dsh/browser-auth.d.ts.map +1 -0
  21. package/dist/types/adapters/dsh/browser-capability.d.ts +8 -0
  22. package/dist/types/adapters/dsh/browser-capability.d.ts.map +1 -0
  23. package/dist/types/adapters/dsh/compatibility.d.ts +7 -0
  24. package/dist/types/adapters/dsh/compatibility.d.ts.map +1 -0
  25. package/dist/types/adapters/dsh/readiness.d.ts +22 -0
  26. package/dist/types/adapters/dsh/readiness.d.ts.map +1 -0
  27. package/dist/types/adapters/dsh/startup-urls.d.ts +4 -0
  28. package/dist/types/adapters/dsh/startup-urls.d.ts.map +1 -0
  29. package/dist/types/adapters/dsh/webserver.d.ts +36 -0
  30. package/dist/types/adapters/dsh/webserver.d.ts.map +1 -0
  31. package/dist/types/auth/password.d.ts +12 -0
  32. package/dist/types/auth/password.d.ts.map +1 -0
  33. package/dist/types/auth/service.d.ts +90 -0
  34. package/dist/types/auth/service.d.ts.map +1 -0
  35. package/dist/types/auth/sessions.d.ts +8 -0
  36. package/dist/types/auth/sessions.d.ts.map +1 -0
  37. package/dist/types/auth/totp.d.ts +10 -0
  38. package/dist/types/auth/totp.d.ts.map +1 -0
  39. package/dist/types/cli/index.d.ts +3 -0
  40. package/dist/types/cli/index.d.ts.map +1 -0
  41. package/dist/types/cli/ipc-client.d.ts +18 -0
  42. package/dist/types/cli/ipc-client.d.ts.map +1 -0
  43. package/dist/types/cli/language.d.ts +14 -0
  44. package/dist/types/cli/language.d.ts.map +1 -0
  45. package/dist/types/cli/profile.d.ts +10 -0
  46. package/dist/types/cli/profile.d.ts.map +1 -0
  47. package/dist/types/cli/prompt.d.ts +20 -0
  48. package/dist/types/cli/prompt.d.ts.map +1 -0
  49. package/dist/types/config.d.ts +27 -0
  50. package/dist/types/config.d.ts.map +1 -0
  51. package/dist/types/http/admin-socket.d.ts +18 -0
  52. package/dist/types/http/admin-socket.d.ts.map +1 -0
  53. package/dist/types/http/connections.d.ts +21 -0
  54. package/dist/types/http/connections.d.ts.map +1 -0
  55. package/dist/types/http/gate.d.ts +24 -0
  56. package/dist/types/http/gate.d.ts.map +1 -0
  57. package/dist/types/http/origin-policy.d.ts +35 -0
  58. package/dist/types/http/origin-policy.d.ts.map +1 -0
  59. package/dist/types/http/origin.d.ts +5 -0
  60. package/dist/types/http/origin.d.ts.map +1 -0
  61. package/dist/types/http/request-context.d.ts +5 -0
  62. package/dist/types/http/request-context.d.ts.map +1 -0
  63. package/dist/types/http/routes.d.ts +15 -0
  64. package/dist/types/http/routes.d.ts.map +1 -0
  65. package/dist/types/index.d.ts +33 -0
  66. package/dist/types/index.d.ts.map +1 -0
  67. package/dist/types/shared/admin-contract.d.ts +40 -0
  68. package/dist/types/shared/admin-contract.d.ts.map +1 -0
  69. package/dist/types/shared/auth-contract.d.ts +33 -0
  70. package/dist/types/shared/auth-contract.d.ts.map +1 -0
  71. package/dist/types/shared/i18n.d.ts +323 -0
  72. package/dist/types/shared/i18n.d.ts.map +1 -0
  73. package/dist/types/shared/locales/en.d.ts +151 -0
  74. package/dist/types/shared/locales/en.d.ts.map +1 -0
  75. package/dist/types/shared/locales/zh.d.ts +150 -0
  76. package/dist/types/shared/locales/zh.d.ts.map +1 -0
  77. package/dist/types/storage/lock.d.ts +17 -0
  78. package/dist/types/storage/lock.d.ts.map +1 -0
  79. package/dist/types/storage/state.d.ts +34 -0
  80. package/dist/types/storage/state.d.ts.map +1 -0
  81. package/dist/types/storage/store.d.ts +30 -0
  82. package/dist/types/storage/store.d.ts.map +1 -0
  83. package/docs/deployment.md +89 -0
  84. package/docs/deployment.zh-CN.md +89 -0
  85. package/docs/development.md +43 -0
  86. package/docs/development.zh-CN.md +43 -0
  87. package/docs/releasing.md +44 -0
  88. package/docs/releasing.zh-CN.md +44 -0
  89. package/docs/reverse-proxy.md +27 -0
  90. package/docs/reverse-proxy.zh-CN.md +27 -0
  91. package/examples/nginx.conf +27 -0
  92. package/examples/traefik-dsh.yml +20 -0
  93. package/examples/web-profile-auth-remote.patch.yml +14 -0
  94. package/package.json +112 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/adapters/dsh/compatibility.ts", "../src/adapters/dsh/browser-capability.ts", "../src/adapters/dsh/browser-auth.ts", "../src/adapters/dsh/readiness.ts", "../src/adapters/dsh/startup-urls.ts", "../src/adapters/dsh/webserver.ts", "../src/http/origin-policy.ts", "../src/auth/service.ts", "../src/storage/store.ts", "../src/storage/lock.ts", "../src/storage/state.ts", "../src/auth/password.ts", "../src/auth/sessions.ts", "../src/auth/totp.ts", "../src/config.ts", "../src/http/connections.ts", "../src/http/admin-socket.ts", "../src/shared/admin-contract.ts", "../src/shared/auth-contract.ts", "../src/http/origin.ts", "../src/http/request-context.ts", "../src/http/routes.ts", "../src/http/gate.ts"],
4
+ "sourcesContent": ["/** Host entry: storage is preflighted before the guarded listener opens. */\nimport { Service, type Context } from '@deepseek-ai/cordis'\nimport { basename } from 'node:path'\nimport { assertWebServerCompatibility } from './adapters/dsh/compatibility.js'\nimport { installAuthenticatedHostCapability } from './adapters/dsh/browser-capability.js'\nimport { DshReadiness, watchConnection } from './adapters/dsh/readiness.js'\nimport { startupLines } from './adapters/dsh/startup-urls.js'\nimport { DenyGate, GuardedWebServer, SwitchGate } from './adapters/dsh/webserver.js'\nimport { AuthService } from './auth/service.js'\nimport {\n resolveAuthConfig,\n Config,\n DEFAULT_WEB_HOST,\n DEFAULT_WEB_PORT,\n type AuthConfig,\n type ResolvedAuthConfig,\n} from './config.js'\nimport { AuthConnections } from './http/connections.js'\nimport { AdminSocket } from './http/admin-socket.js'\nimport { AuthGate } from './http/gate.js'\nimport { AuthRoutes } from './http/routes.js'\nimport { AuthStateStore } from './storage/store.js'\n\nexport type { AuthConfig } from './config.js'\nexport { Config, DEFAULT_REQUIRE_TOTP, DEFAULT_SESSION_HOURS } from './config.js'\nexport { resolveAuthConfig } from './config.js'\nexport { installAuthenticatedHostCapability } from './adapters/dsh/browser-capability.js'\nexport { GuardedWebServer, READY_PATH, READY_PROTOCOL_VERSION } from './adapters/dsh/webserver.js'\nexport { DshReadiness, watchConnection } from './adapters/dsh/readiness.js'\nexport { AuthService, AuthError } from './auth/service.js'\nexport type { AuthPolicy, AuthErrorCode, LoginResult } from './auth/service.js'\nexport { AuthStateStore } from './storage/store.js'\nexport { AuthGate } from './http/gate.js'\nexport { AuthConnections } from './http/connections.js'\n\nexport const name = 'auth-remote'\n\nexport class AuthRemoteWebServer extends GuardedWebServer {\n static override Config = Config as unknown as typeof GuardedWebServer.Config\n private stateStore: AuthStateStore | undefined\n private authService: AuthService | undefined\n private readonly resolved: ResolvedAuthConfig\n private readonly switchGate: SwitchGate\n\n constructor(ctx: Context, input: AuthConfig) {\n const startup = ctx.get('webStartup') as { host?: string; port?: number } | undefined\n if (!startup) throw new Error('auth-remote: webStartup service is required')\n const config = resolveAuthConfig(input, {\n host: startup.host ?? DEFAULT_WEB_HOST,\n port: startup.port ?? DEFAULT_WEB_PORT,\n compression: 'none',\n })\n assertWebServerCompatibility(ctx)\n const gate = new SwitchGate()\n super(ctx, config, gate)\n this.resolved = config\n this.switchGate = gate\n installAuthenticatedHostCapability(ctx)\n }\n\n override async [Service.init](): Promise<void> {\n const profile = this.ctx.get('profileContext') as { dir?: string; name?: string } | undefined\n if (!profile?.dir) throw new Error('dsh-auth-remote: profileContext is required for storage')\n const profileName = profile.name ?? basename(profile.dir)\n let readiness: DshReadiness | undefined\n let connections: AuthConnections | undefined\n let admin: AdminSocket | undefined\n const store = await AuthStateStore.open(profile.dir, {\n onUnavailable: () => {\n this.switchGate.set(new DenyGate())\n readiness?.detach()\n if (connections) void connections.closeAll()\n },\n })\n try {\n const auth = new AuthService(store, {\n requireTotp: this.resolved.requireTotp,\n sessionHours: this.resolved.sessionHours,\n })\n await auth.enforceCurrentPolicy()\n this.stateStore = store\n this.authService = auth\n connections = new AuthConnections(store, auth)\n readiness = new DshReadiness(this, this.resolved, () => {\n if (connections) void connections.closeAll()\n })\n this.switchGate.set(\n new AuthGate(() => this.port, this.resolved, store, auth, readiness, connections),\n )\n new AuthRoutes(auth, profileName).install(this)\n admin = new AdminSocket(\n profile.dir,\n auth,\n () => this.switchGate.ready(),\n () => {\n this.switchGate.set(new DenyGate())\n readiness?.detach()\n if (connections) void connections.closeAll()\n },\n )\n await admin.start()\n const activeConnections = connections\n const activeReadiness = readiness\n const activeAdmin = admin\n this.ctx.effect(\n () => async () => {\n this.switchGate.set(new DenyGate())\n activeReadiness.detach()\n await activeAdmin.dispose()\n await activeConnections.dispose()\n auth.dispose()\n await store.close()\n },\n 'auth-remote.storage-and-gate',\n )\n await super[Service.init]()\n let announced = false\n watchConnection(this.ctx, readiness, () => {\n const loader = this.ctx.get('loader') as { await(): Promise<unknown> } | undefined\n const settled = loader?.await() ?? Promise.resolve()\n void settled\n .then(() => {\n if (announced || !activeReadiness.ready()) return\n announced = true\n console.log(startupLines(profileName, this.resolved, this.port).join('\\n'))\n })\n .catch(() => {})\n })\n } catch (error) {\n this.switchGate.set(new DenyGate())\n await admin?.dispose()\n await connections?.dispose()\n this.authService?.dispose()\n await store.close()\n throw error\n }\n }\n\n get storage(): AuthStateStore {\n if (!this.stateStore) throw new Error('dsh-auth-remote: storage is not initialized')\n return this.stateStore\n }\n\n get authentication(): AuthService {\n if (!this.authService) throw new Error('dsh-auth-remote: authentication is not initialized')\n return this.authService\n }\n\n /** Public authorities needed by native Connection for preserved routes. */\n get connectionTrustedHosts(): readonly string[] {\n if (this.resolved.preserveOriginPaths.length === 0) return []\n return this.resolved.originPolicy.registeredOrigins.map((entry) => entry.host)\n }\n}\n\nexport default AuthRemoteWebServer\n", "import { readFileSync, realpathSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport type { Context } from '@deepseek-ai/cordis'\nimport WebServer from '@deepseek-ai/dsh-host-webserver'\nimport type { HostConnectionHandle } from '@deepseek-ai/dsh-client-connection'\nimport semver from 'semver'\n\nconst WEB_SERVER_PACKAGE = '@deepseek-ai/dsh-host-webserver'\nconst CONNECTION_PACKAGE = '@deepseek-ai/dsh-client-connection'\nconst SUPPORTED_DSH_RANGE = '>=0.1.7-rc.1 <0.2.0-0'\n\ninterface PackageManifest {\n name: string\n version: string\n}\n\nfunction packageManifest(\n packageName: string,\n anchor: string,\n): { path: string; manifest: PackageManifest } {\n const path = realpathSync(createRequire(anchor).resolve(`${packageName}/package.json`))\n const manifest = JSON.parse(readFileSync(path, 'utf8')) as PackageManifest\n if (\n manifest.name !== packageName ||\n !semver.satisfies(manifest.version, SUPPORTED_DSH_RANGE, { includePrerelease: true })\n ) {\n throw new Error(`auth-remote: unsupported ${packageName} version ${manifest.version}`)\n }\n return { path, manifest }\n}\n\n/** Verify the loaded module and the profile's host resolve to one DSH copy. */\nexport function assertWebServerCompatibility(ctx: Context): string {\n const own = packageManifest(WEB_SERVER_PACKAGE, import.meta.url)\n const profile = ctx.get('profileContext') as { installAnchor?: string } | undefined\n if (profile?.installAnchor !== undefined) {\n const host = packageManifest(WEB_SERVER_PACKAGE, profile.installAnchor)\n if (own.path !== host.path) {\n throw new Error(\n `auth-remote: duplicate WebServer package copies: ${own.path} and ${host.path}`,\n )\n }\n }\n for (const method of [\n 'register',\n 'registerUpgrade',\n 'registerFallback',\n 'renderIndex',\n ] as const) {\n if (typeof WebServer.prototype[method] !== 'function') {\n throw new Error(`auth-remote: WebServer lacks ${method}`)\n }\n }\n return own.manifest.version\n}\n\n/** Check Connection after it appears; readiness must be withdrawn on its loss. */\nexport function assertConnectionCompatibility(\n connection: HostConnectionHandle,\n anchor?: string,\n): string {\n const own = packageManifest(CONNECTION_PACKAGE, import.meta.url)\n if (anchor !== undefined) {\n const host = packageManifest(CONNECTION_PACKAGE, anchor)\n if (own.path !== host.path) {\n throw new Error(\n `auth-remote: duplicate Connection package copies: ${own.path} and ${host.path}`,\n )\n }\n }\n for (const method of ['authenticatedUrl', 'authorizeIndex', 'requestRejection'] as const) {\n if (typeof connection[method] !== 'function') {\n throw new Error(`auth-remote: Connection lacks ${method}`)\n }\n }\n return own.manifest.version\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type { IndexInjection } from '@deepseek-ai/dsh-host-webserver'\n\n/**\n * A fully authenticated administrator may use the Host settings surface from\n * the public origin. Install the fact before the index boots Connection and\n * Remote; neither service can be repaired after its constructor caches it.\n */\nexport function installAuthenticatedHostCapability(ctx: Context): void {\n ctx.on('webserver/index-inject', (table: IndexInjection[]) => {\n table.push({ kind: 'global', name: '__DSH_TRANSPORT__', value: { ownsHost: true } })\n })\n}\n", "import type { HostConnectionHandle } from '@deepseek-ai/dsh-client-connection'\n\ninterface NativeCookie {\n readonly pair: string\n readonly expiresAt: number\n}\n\n/** Host-only bridge to the public Connection token exchange. */\nexport class NativeBrowserAuth {\n private readonly cookies = new WeakMap<HostConnectionHandle, Map<string, NativeCookie>>()\n\n cookieFor(\n connection: HostConnectionHandle,\n authority: string,\n origin: string,\n now = Date.now(),\n ): string {\n let byAuthority = this.cookies.get(connection)\n if (byAuthority === undefined) {\n byAuthority = new Map()\n this.cookies.set(connection, byAuthority)\n }\n let cookie = byAuthority.get(authority)\n if (cookie === undefined || now >= cookie.expiresAt - 60_000) {\n cookie = exchange(connection, authority, now)\n byAuthority.set(authority, cookie)\n }\n const rejection = connection.requestRejection({\n headers: { host: authority, origin, cookie: cookie.pair },\n })\n if (rejection !== undefined) {\n byAuthority.delete(authority)\n throw new Error(\n `auth-remote: native Connection rejected ${authority} with ${String(rejection)}`,\n )\n }\n return cookie.pair\n }\n\n clear(connection: HostConnectionHandle): void {\n this.cookies.delete(connection)\n }\n}\n\nfunction exchange(connection: HostConnectionHandle, authority: string, now: number): NativeCookie {\n const tokenUrl = new URL(connection.authenticatedUrl(`http://${authority}/`))\n const normalizedAuthority = new URL(`http://${authority}/`).host\n if (\n tokenUrl.host !== normalizedAuthority ||\n tokenUrl.pathname !== '/' ||\n tokenUrl.searchParams.getAll('token').length !== 1\n ) {\n throw new Error('auth-remote: native Connection returned an invalid token URL')\n }\n let status: number | undefined\n let responseHeaders: Readonly<Record<string, string>> | undefined\n let ended = false\n const admitted = connection.authorizeIndex(\n { method: 'GET', url: tokenUrl.pathname + tokenUrl.search, headers: { host: authority } },\n {\n writeHead(code, headers) {\n status = code\n responseHeaders = headers\n },\n end() {\n ended = true\n },\n },\n )\n // The target version returns false after a successful 303 exchange.\n const setCookie = responseHeaders?.['set-cookie']\n if (\n admitted ||\n !ended ||\n status !== 303 ||\n setCookie === undefined ||\n responseHeaders?.location !== './'\n ) {\n throw new Error('auth-remote: native Connection token exchange failed')\n }\n const [pair, ...attributes] = setCookie.split(';').map((part) => part.trim())\n if (pair === undefined || !/^[^=;\\s]+=([^;\\s]*)$/u.test(pair)) {\n throw new Error('auth-remote: native Connection returned an invalid Cookie')\n }\n const maxAge = attributes\n .find((attribute) => /^max-age=/iu.test(attribute))\n ?.slice('max-age='.length)\n const seconds = maxAge === undefined ? NaN : Number(maxAge)\n const expiresAt = now + seconds * 1000\n if (!Number.isSafeInteger(seconds) || seconds <= 0 || !Number.isSafeInteger(expiresAt)) {\n throw new Error('auth-remote: native Connection returned an invalid Cookie lifetime')\n }\n return { pair, expiresAt }\n}\n", "import type { Context } from '@deepseek-ai/cordis'\nimport type { HostConnectionHandle } from '@deepseek-ai/dsh-client-connection'\nimport type { ResolvedAuthConfig } from '../../config.js'\nimport { NativeBrowserAuth } from './browser-auth.js'\nimport { assertConnectionCompatibility } from './compatibility.js'\nimport type { GuardedWebServer } from './webserver.js'\n\n/** Connection availability and the native authorities used by the bridge. */\nexport class DshReadiness {\n private readonly native = new NativeBrowserAuth()\n private connection: HostConnectionHandle | undefined\n private isReady = false\n\n constructor(\n private readonly server: GuardedWebServer,\n private readonly config: ResolvedAuthConfig,\n private readonly onUnavailable: () => void = () => {},\n ) {}\n\n ready(): boolean {\n return this.isReady\n }\n\n currentConnection(): HostConnectionHandle | undefined {\n return this.connection\n }\n\n attach(connection: HostConnectionHandle, profileAnchor?: string): void {\n this.detach()\n assertConnectionCompatibility(connection, profileAnchor)\n const localAuthority = `127.0.0.1:${String(this.server.port)}`\n try {\n this.native.cookieFor(connection, localAuthority, `http://${localAuthority}`)\n if (this.config.preserveOriginPaths.length > 0)\n for (const entry of this.config.originPolicy.registeredOrigins)\n this.native.cookieFor(connection, entry.host, entry.origin)\n } catch (error) {\n this.native.clear(connection)\n throw error\n }\n this.connection = connection\n this.isReady = true\n }\n\n nativeCookie(authority: string, origin: string): string {\n if (!this.isReady || this.connection === undefined)\n throw new Error('auth-remote: Connection is not ready')\n return this.native.cookieFor(this.connection, authority, origin)\n }\n\n detach(connection?: HostConnectionHandle): void {\n if (connection !== undefined && this.connection !== connection) return\n const old = this.connection\n this.connection = undefined\n if (this.isReady) {\n this.isReady = false\n this.onUnavailable()\n }\n if (old !== undefined) this.native.clear(old)\n }\n}\n\n/** Dynamic injection avoids waiting for Connection before supplying WebServer. */\nexport function watchConnection(\n ctx: Context,\n readiness: DshReadiness,\n onReady: () => void = () => {},\n): void {\n ctx.inject(['connection'], (connectionCtx) => {\n const connection = connectionCtx.get('connection') as HostConnectionHandle\n const profile = ctx.get('profileContext') as { installAnchor?: string } | undefined\n connectionCtx.effect(() => {\n readiness.attach(connection, profile?.installAnchor)\n onReady()\n return () => {\n readiness.detach(connection)\n }\n }, 'auth-remote: native Connection readiness')\n })\n}\n", "import type { ResolvedAuthConfig } from '../../config.js'\n\n/** Startup URLs for the listener and configured public browser entries. */\nexport function startupLines(profile: string, config: ResolvedAuthConfig, port: number): string[] {\n const lines = [`dsh ${profile} start at`, ` http://${config.host}:${String(port)}`]\n if (config.allowedOrigins.length > 0) {\n lines.push('', 'public access at')\n for (const origin of config.allowedOrigins) lines.push(` ${origin}`)\n }\n return lines\n}\n", "import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { Context } from '@deepseek-ai/cordis'\nimport WebServer, {\n type Config as WebServerConfig,\n type WebRoute,\n type WebUpgradeRoute,\n} from '@deepseek-ai/dsh-host-webserver'\nimport type { ResolvedAuthConfig } from '../../config.js'\nimport { evaluateRequestOrigin } from '../../http/origin-policy.js'\n\nexport const READY_PATH = '/auth-remote/ready'\nexport const READY_PROTOCOL_VERSION = 1\n\n/** A gate owns admission and then calls the official route exactly once. */\nexport interface WebGate {\n ready(): boolean\n http(req: IncomingMessage, res: ServerResponse, next: () => Promise<void>): Promise<void>\n upgrade(\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n next: () => Promise<void>,\n ): Promise<void>\n}\n\n/** Safe production baseline until the account and HTTP gate are installed. */\nexport class DenyGate implements WebGate {\n ready(): boolean {\n return false\n }\n\n async http(_req: IncomingMessage, res: ServerResponse): Promise<void> {\n res.writeHead(503, { 'cache-control': 'no-store' })\n res.end()\n }\n\n async upgrade(_req: IncomingMessage, socket: Duplex): Promise<void> {\n socket.end('HTTP/1.1 503 Service Unavailable\\r\\nConnection: close\\r\\n\\r\\n')\n }\n}\n\n/** Keeps the public listener closed while asynchronous preflight completes. */\nexport class SwitchGate implements WebGate {\n private delegate: WebGate = new DenyGate()\n\n set(delegate: WebGate): void {\n this.delegate = delegate\n }\n\n ready(): boolean {\n return this.delegate.ready()\n }\n\n http(req: IncomingMessage, res: ServerResponse, next: () => Promise<void>): Promise<void> {\n return this.delegate.http(req, res, next)\n }\n\n upgrade(\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n next: () => Promise<void>,\n ): Promise<void> {\n return this.delegate.upgrade(req, socket, head, next)\n }\n}\n\n/** Wrap only public WebServer registration methods; its routing and IO stay official. */\nexport class GuardedWebServer extends WebServer {\n constructor(\n ctx: Context,\n config: ResolvedAuthConfig,\n private readonly gate: WebGate = new DenyGate(),\n ) {\n // The native runtime passes host directly to server.listen(); its public\n // config type lists only two literals. The auth plugin validates IPv4 first.\n super(ctx, config as WebServerConfig)\n super.register({\n kind: 'exact',\n path: READY_PATH,\n handler: (req, res) => {\n if (\n !evaluateRequestOrigin(config.originPolicy, {\n rawHeaders: req.rawHeaders,\n method: req.method,\n target: req.url,\n })\n ) {\n res.writeHead(403, { 'cache-control': 'no-store' })\n res.end()\n return\n }\n if (req.method !== 'GET') {\n res.writeHead(405, { 'cache-control': 'no-store', allow: 'GET' })\n res.end()\n return\n }\n const ready = this.gate.ready()\n res.writeHead(ready ? 200 : 503, {\n 'cache-control': 'no-store',\n 'content-type': 'application/json; charset=utf-8',\n })\n res.end(\n JSON.stringify({\n plugin: 'dsh-auth-remote',\n protocolVersion: READY_PROTOCOL_VERSION,\n ready,\n }),\n )\n },\n })\n }\n\n override register(route: WebRoute): () => void {\n return super.register({\n ...route,\n handler: (req, res) =>\n this.gate.http(req, res, () => Promise.resolve(route.handler(req, res))),\n })\n }\n\n override registerFallback(handler: WebRoute['handler']): () => void {\n return super.registerFallback((req, res) =>\n this.gate.http(req, res, () => Promise.resolve(handler(req, res))),\n )\n }\n\n override registerUpgrade(route: WebUpgradeRoute): () => void {\n return super.registerUpgrade({\n ...route,\n handler: (req, socket, head) =>\n this.gate.upgrade(req, socket, head, () =>\n Promise.resolve(route.handler(req, socket, head)),\n ),\n })\n }\n}\n", "export type OriginProtocol = 'http:' | 'https:'\n\nexport interface RegisteredOrigin {\n readonly origin: string\n readonly protocol: OriginProtocol\n readonly host: string\n readonly hostname: string\n readonly port: number\n readonly authorities: readonly string[]\n}\n\nexport interface OriginPolicy {\n readonly registeredOrigins: readonly RegisteredOrigin[]\n matchAuthority(host: string): RegisteredOrigin | undefined\n}\n\nexport interface RawRequestHead {\n readonly rawHeaders: readonly string[]\n readonly method: string | undefined\n readonly target: string | undefined\n readonly upgrade?: boolean\n}\n\nexport interface RequestOriginContext {\n readonly origin: string\n readonly protocol: OriginProtocol\n readonly authority: string\n readonly downstreamAuthority: string\n readonly hostname: string\n readonly pathname: string\n readonly returnPath: string\n readonly registered: boolean\n readonly mayWriteCookie: boolean\n}\n\ninterface Authority {\n readonly host: string\n readonly hostname: string\n readonly explicitPort: number | undefined\n readonly kind: 'ipv4' | 'ipv6' | 'name'\n}\n\nfunction defaultPort(protocol: OriginProtocol): number {\n return protocol === 'https:' ? 443 : 80\n}\n\nfunction parseAuthority(value: string): Authority | null {\n const ipv6 = /^(\\[[0-9a-fA-F:.]+\\])(?::([0-9]+))?$/u.exec(value)\n const plain = /^([A-Za-z0-9.-]+)(?::([0-9]+))?$/u.exec(value)\n const hostname = (ipv6?.[1] ?? plain?.[1])?.toLowerCase()\n const portText = ipv6?.[2] ?? plain?.[2]\n if (!hostname) return null\n if (portText !== undefined && (!/^[1-9][0-9]*$/u.test(portText) || Number(portText) > 65535))\n return null\n let parsed: URL\n try {\n parsed = new URL(`http://${hostname}`)\n } catch {\n return null\n }\n if (parsed.hostname !== hostname || parsed.username || parsed.password) return null\n let kind: Authority['kind']\n if (ipv6) {\n kind = 'ipv6'\n } else if (/^(?:[0-9]+\\.){3}[0-9]+$/u.test(hostname)) {\n const octets = hostname.split('.')\n if (octets.some((octet) => Number(octet) > 255 || String(Number(octet)) !== octet)) return null\n kind = 'ipv4'\n } else {\n if (hostname.length > 253 || hostname.endsWith('.')) return null\n if (hostname.split('.').some((label) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(label)))\n return null\n kind = 'name'\n }\n const explicitPort = portText === undefined ? undefined : Number(portText)\n return {\n host: `${hostname}${explicitPort === undefined ? '' : `:${explicitPort}`}`,\n hostname,\n explicitPort,\n kind,\n }\n}\n\nfunction parseOrigin(value: string): RegisteredOrigin | null {\n const match = /^(https?):\\/\\/([^/?#]+)$/iu.exec(value)\n if (!match?.[1] || !match[2]) return null\n const authority = parseAuthority(match[2])\n if (!authority) return null\n const protocol = `${match[1].toLowerCase()}:` as OriginProtocol\n let url: URL\n try {\n url = new URL(`${protocol}//${authority.host}`)\n } catch {\n return null\n }\n if (url.hostname !== authority.hostname) return null\n const port = authority.explicitPort ?? defaultPort(protocol)\n const authorities = [url.host]\n if (url.port === '') authorities.push(`${url.hostname}:${defaultPort(protocol)}`)\n return Object.freeze({\n origin: url.origin,\n protocol,\n host: url.host,\n hostname: url.hostname,\n port,\n authorities: Object.freeze(authorities),\n })\n}\n\n/** Resolve an exact authority to a single configured protocol. No DNS or proxy headers are used. */\nexport function createOriginPolicy(origins: readonly string[]): OriginPolicy {\n if (!Array.isArray(origins)) throw new Error('auth-remote: allowedOrigins must be an array')\n const indexed = new Map<string, RegisteredOrigin>()\n const registeredOrigins: RegisteredOrigin[] = []\n const seen = new Set<string>()\n for (const value of origins) {\n const entry = typeof value === 'string' ? parseOrigin(value) : null\n if (!entry) {\n throw new Error(`auth-remote: invalid allowedOrigins entry ${JSON.stringify(value)}`)\n }\n if (seen.has(entry.origin)) {\n throw new Error(`auth-remote: duplicate allowedOrigins entry ${JSON.stringify(value)}`)\n }\n seen.add(entry.origin)\n for (const alias of entry.authorities) {\n const previous = indexed.get(alias)\n if (previous) {\n throw new Error(\n `auth-remote: ambiguous allowedOrigins authority ${alias} (${previous.protocol} and ${entry.protocol})`,\n )\n }\n indexed.set(alias, entry)\n }\n registeredOrigins.push(entry)\n }\n return Object.freeze({\n registeredOrigins: Object.freeze(registeredOrigins),\n matchAuthority(host: string) {\n const authority = parseAuthority(host)\n return authority ? indexed.get(authority.host) : undefined\n },\n })\n}\n\nfunction headerValues(rawHeaders: readonly string[], name: string): string[] | null {\n if (rawHeaders.length % 2 !== 0) return null\n const values: string[] = []\n for (let i = 0; i < rawHeaders.length; i += 2) {\n const key = rawHeaders[i]\n const value = rawHeaders[i + 1]\n if (typeof key !== 'string' || typeof value !== 'string') return null\n if (key.toLowerCase() === name) values.push(value)\n }\n return values\n}\n\nfunction parseTarget(target: string): { pathname: string; returnPath: string } | null {\n if (\n !target.startsWith('/') ||\n target.startsWith('//') ||\n /[\\\\\\u0000-\\u001f\\u007f\\s#]/u.test(target) ||\n /%(?![0-9a-fA-F]{2})/u.test(target)\n )\n return null\n const rawPath = target.split('?', 1)[0]!\n for (const segment of rawPath.split('/')) {\n let decoded: string\n try {\n decoded = decodeURIComponent(segment)\n } catch {\n return null\n }\n if (decoded === '.' || decoded === '..' || /[/\\\\\\u0000-\\u001f\\u007f]/u.test(decoded))\n return null\n }\n let parsed: URL\n try {\n parsed = new URL(target, 'http://auth-remote.invalid')\n } catch {\n return null\n }\n if (parsed.origin !== 'http://auth-remote.invalid') return null\n if (parsed.pathname === '/') parsed.searchParams.delete('token')\n return { pathname: parsed.pathname, returnPath: parsed.pathname + parsed.search }\n}\n\nfunction isImplicitLoopback(authority: Authority): boolean {\n if (authority.hostname === 'localhost' || authority.hostname === '[::1]') return true\n if (authority.kind !== 'ipv4') return false\n return authority.hostname.startsWith('127.')\n}\n\n/** Validate the original request head before any Host, Origin or Cookie rewrite. */\nexport function evaluateRequestOrigin(\n policy: OriginPolicy,\n request: RawRequestHead,\n): RequestOriginContext | null {\n const hosts = headerValues(request.rawHeaders, 'host')\n const origins = headerValues(request.rawHeaders, 'origin')\n const fetchSites = headerValues(request.rawHeaders, 'sec-fetch-site')\n if (\n !hosts ||\n !origins ||\n !fetchSites ||\n hosts.length !== 1 ||\n origins.length > 1 ||\n fetchSites.length > 1\n )\n return null\n const authority = parseAuthority(hosts[0]!)\n const target = request.target ? parseTarget(request.target) : null\n const method = request.method\n if (!authority || !target || !method || !/^[A-Z!#$%&'*+.^_`|~-]+$/u.test(method)) return null\n const needsOrigin = request.upgrade === true || method !== 'GET'\n if (needsOrigin && origins.length !== 1) return null\n const site = fetchSites[0]?.toLowerCase()\n if (\n site !== undefined &&\n (needsOrigin ? site !== 'same-origin' : !['same-origin', 'none'].includes(site))\n )\n return null\n const suppliedOrigin = origins.length === 1 ? parseOrigin(origins[0]!) : null\n if (origins.length === 1 && !suppliedOrigin) return null\n const registered = policy.matchAuthority(authority.host)\n let origin: string\n let protocol: OriginProtocol\n if (registered) {\n if (suppliedOrigin && suppliedOrigin.origin !== registered.origin) return null\n origin = registered.origin\n protocol = registered.protocol\n } else {\n if (!isImplicitLoopback(authority)) return null\n protocol = suppliedOrigin?.protocol ?? 'http:'\n const hostPort = authority.explicitPort ?? defaultPort(protocol)\n if (\n suppliedOrigin &&\n (suppliedOrigin.hostname !== authority.hostname || suppliedOrigin.port !== hostPort)\n )\n return null\n origin = suppliedOrigin?.origin ?? new URL(`${protocol}//${authority.host}`).origin\n }\n return Object.freeze({\n origin,\n protocol,\n authority: authority.host,\n downstreamAuthority: new URL(origin).host,\n hostname: authority.hostname,\n pathname: target.pathname,\n returnPath: target.returnPath,\n registered: registered !== undefined,\n mayWriteCookie: registered !== undefined || suppliedOrigin !== null,\n })\n}\n", "import { randomBytes } from 'node:crypto'\nimport type { AuthState, AccountRecord, SessionRecord } from '../storage/state.js'\nimport { AuthStateStore } from '../storage/store.js'\nimport {\n DUMMY_PASSWORD_RECORD,\n hashPassword,\n validatePassword,\n verifyPassword,\n} from './password.js'\nimport { issueSession, sessionFor, sessionHash } from './sessions.js'\nimport { backupCodeHash, generateBackupCodes, generateTotpSecret, matchedTotpStep } from './totp.js'\n\nexport interface AuthPolicy {\n requireTotp: boolean\n sessionHours: number\n}\n\nexport type AuthErrorCode =\n | 'invalid_input'\n | 'uninitialized'\n | 'already_initialized'\n | 'invalid_credentials'\n | 'invalid_factor'\n | 'invalid_challenge'\n | 'challenge_expired'\n | 'unauthorized'\n | 'rate_limited'\n | 'busy'\n | 'conflict'\n | 'totp_required'\n\nexport class AuthError extends Error {\n constructor(\n readonly code: AuthErrorCode,\n readonly retryAfter?: number,\n ) {\n super(`auth-remote: ${code}`)\n }\n}\n\ninterface BaseChallenge {\n id: string\n accountId: string\n securityVersion: number\n expiresAt: number\n failures: number\n busy: boolean\n}\n\ninterface MfaChallenge extends BaseChallenge {\n kind: 'mfa'\n}\n\ninterface BindingChallenge extends BaseChallenge {\n kind: 'binding'\n secret: string\n originSessionHash: string | null\n}\n\ntype Challenge = MfaChallenge | BindingChallenge\n\nexport type LoginResult =\n | { kind: 'session'; token: string; expiresAt: number }\n | { kind: 'mfa'; challenge: string; expiresAt: number }\n | { kind: 'binding'; challenge: string; secret: string; expiresAt: number }\n\nexport interface AuthServiceOptions {\n now?: () => number\n}\n\nconst LOGIN_CHALLENGE_MS = 5 * 60_000\nconst BINDING_CHALLENGE_MS = 10 * 60_000\nconst RATE_WINDOW_MS = 60_000\nconst MAX_ATTEMPTS = 10\nconst MAX_CHALLENGES = 32\n\nfunction validatePolicy(policy: AuthPolicy, now: number): void {\n if (\n typeof policy.requireTotp !== 'boolean' ||\n !Number.isSafeInteger(policy.sessionHours) ||\n policy.sessionHours < 1 ||\n !Number.isSafeInteger(now + policy.sessionHours * 3_600_000)\n )\n throw new AuthError('invalid_input')\n}\n\nfunction validUsername(username: unknown): username is string {\n return (\n typeof username === 'string' &&\n username.length > 0 &&\n [...username].length <= 64 &&\n !/[\\u0000-\\u001f\\u007f]/u.test(username)\n )\n}\n\nexport class AuthService {\n private readonly now: () => number\n private readonly challenges = new Map<string, Challenge>()\n private readonly attempts: number[] = []\n private activeDerivations = 0\n private policyChanging = false\n private readonly unsubscribe: () => void\n\n constructor(\n private readonly store: AuthStateStore,\n private policy: AuthPolicy,\n options: AuthServiceOptions = {},\n ) {\n this.now = options.now ?? Date.now\n validatePolicy(policy, this.now())\n this.unsubscribe = store.subscribe((previous, current) => {\n if (previous.account?.securityVersion !== current.account?.securityVersion) {\n this.challenges.clear()\n return\n }\n for (const [id, challenge] of this.challenges) {\n if (\n challenge.kind === 'binding' &&\n challenge.originSessionHash &&\n previous.sessions[challenge.originSessionHash] &&\n !current.sessions[challenge.originSessionHash]\n )\n this.challenges.delete(id)\n }\n })\n }\n\n dispose(): void {\n this.unsubscribe()\n this.challenges.clear()\n }\n\n status(): { initialized: boolean; totpEnabled: boolean; activeSessions: number } {\n const state = this.store.current()\n return {\n initialized: state.account !== null,\n totpEnabled: state.account?.totp !== null && state.account?.totp !== undefined,\n activeSessions: Object.values(state.sessions).filter(\n (session) =>\n state.account &&\n session.accountId === state.account.id &&\n session.securityVersion === state.account.securityVersion &&\n session.expiresAt > this.now() &&\n (!this.policy.requireTotp || state.account.totp),\n ).length,\n }\n }\n\n session(token: string): SessionRecord | null {\n return sessionFor(this.store.current(), token, this.now(), this.policy.requireTotp)\n }\n\n policySnapshot(): AuthPolicy {\n return { ...this.policy }\n }\n\n me(token: string): { username: string; totpEnabled: boolean; expiresAt: number } {\n const state = this.store.current()\n const session = sessionFor(state, token, this.now(), this.policy.requireTotp)\n if (!session || !state.account) throw new AuthError('unauthorized')\n return {\n username: state.account.username,\n totpEnabled: state.account.totp !== null,\n expiresAt: session.expiresAt,\n }\n }\n\n bindingDetails(id: string): { secret: string; expiresAt: number } {\n const challenge = this.challenges.get(id)\n if (!challenge || challenge.kind !== 'binding') throw new AuthError('invalid_challenge')\n if (challenge.expiresAt <= this.now()) {\n this.challenges.delete(id)\n throw new AuthError('challenge_expired')\n }\n const state = this.store.current()\n this.sameAccount(state, challenge.accountId, challenge.securityVersion)\n if (challenge.originSessionHash) {\n const session = state.sessions[challenge.originSessionHash]\n if (!session || session.expiresAt <= this.now()) throw new AuthError('unauthorized')\n }\n return { secret: challenge.secret, expiresAt: challenge.expiresAt }\n }\n\n pendingChallenges(): number {\n this.expireChallenges()\n return this.challenges.size\n }\n\n private occupyAttempt(): void {\n const now = this.now()\n while (this.attempts.length > 0 && this.attempts[0]! <= now - RATE_WINDOW_MS)\n this.attempts.shift()\n if (this.attempts.length >= MAX_ATTEMPTS)\n throw new AuthError(\n 'rate_limited',\n Math.ceil((this.attempts[0]! + RATE_WINDOW_MS - now) / 1000),\n )\n this.attempts.push(now)\n }\n\n private async derive<T>(run: () => Promise<T>): Promise<T> {\n if (this.activeDerivations >= 2) throw new AuthError('busy')\n this.activeDerivations++\n try {\n return await run()\n } finally {\n this.activeDerivations--\n }\n }\n\n private expireChallenges(): void {\n const now = this.now()\n for (const [id, challenge] of this.challenges)\n if (challenge.expiresAt <= now) this.challenges.delete(id)\n }\n\n private createChallenge(\n kind: 'mfa' | 'binding',\n account: AccountRecord,\n originSessionHash: string | null = null,\n ): LoginResult {\n this.expireChallenges()\n if (this.challenges.size >= MAX_CHALLENGES) throw new AuthError('busy')\n const id = randomBytes(32).toString('base64url')\n const expiresAt = this.now() + (kind === 'mfa' ? LOGIN_CHALLENGE_MS : BINDING_CHALLENGE_MS)\n const base = {\n id,\n accountId: account.id,\n securityVersion: account.securityVersion,\n expiresAt,\n failures: 0,\n busy: false,\n }\n if (kind === 'mfa') {\n this.challenges.set(id, { ...base, kind })\n return { kind, challenge: id, expiresAt }\n }\n const secret = generateTotpSecret()\n this.challenges.set(id, { ...base, kind, secret, originSessionHash })\n return { kind, challenge: id, secret, expiresAt }\n }\n\n private claim(id: string, kind: Challenge['kind']): Challenge {\n const challenge = this.challenges.get(id)\n if (!challenge || challenge.kind !== kind) throw new AuthError('invalid_challenge')\n if (challenge.expiresAt <= this.now()) {\n this.challenges.delete(id)\n throw new AuthError('challenge_expired')\n }\n if (challenge.busy || challenge.failures >= 5) throw new AuthError('invalid_challenge')\n challenge.busy = true\n return challenge\n }\n\n private failedChallenge(challenge: Challenge): void {\n challenge.failures++\n if (challenge.failures >= 5) this.challenges.delete(challenge.id)\n }\n\n private sameAccount(state: AuthState, accountId: string, securityVersion: number): AccountRecord {\n const account = state.account\n if (!account || account.id !== accountId || account.securityVersion !== securityVersion)\n throw new AuthError('conflict')\n return account\n }\n\n private requireSession(state: AuthState, token: string): AccountRecord {\n if (!sessionFor(state, token, this.now(), this.policy.requireTotp))\n throw new AuthError('unauthorized')\n return state.account!\n }\n\n private verifyFactor(account: AccountRecord, code: string | undefined): boolean {\n const factor = account.totp\n if (!factor) return true\n if (!code) return false\n const step = matchedTotpStep(factor.secret, code, this.now(), factor.lastUsedStep)\n if (step !== null) {\n factor.lastUsedStep = step\n return true\n }\n const hash = backupCodeHash(code)\n if (!hash) return false\n const index = factor.backupCodeHashes.indexOf(hash)\n if (index < 0) return false\n factor.backupCodeHashes.splice(index, 1)\n return true\n }\n\n async initialize(username: string, password: string): Promise<void> {\n if (!validUsername(username)) throw new AuthError('invalid_input')\n validatePassword(password)\n if (this.store.current().account) throw new AuthError('already_initialized')\n const record = await this.derive(() => hashPassword(password))\n await this.store.transact((draft) => {\n if (draft.account) throw new AuthError('already_initialized')\n draft.account = {\n id: randomBytes(16).toString('hex'),\n username,\n password: record,\n totp: null,\n securityVersion: 1,\n }\n })\n }\n\n async login(username: string, password: string): Promise<LoginResult> {\n this.occupyAttempt()\n if (!validUsername(username) || typeof password !== 'string' || password.length > 1024)\n throw new AuthError('invalid_credentials')\n const snapshot = this.store.current()\n const account = snapshot.account\n if (!account) throw new AuthError('uninitialized')\n const match = await this.derive(() =>\n verifyPassword(\n password,\n username === account.username ? account.password : DUMMY_PASSWORD_RECORD,\n ),\n )\n if (!match || username !== account.username) throw new AuthError('invalid_credentials')\n const current = this.store.current()\n const latest = this.sameAccount(current, account.id, account.securityVersion)\n if (latest.totp) return this.createChallenge('mfa', latest)\n if (this.policy.requireTotp) return this.createChallenge('binding', latest)\n const issued = await this.store.transact((draft) => {\n this.sameAccount(draft, account.id, account.securityVersion)\n if (draft.account!.totp || this.policy.requireTotp) throw new AuthError('conflict')\n return issueSession(draft, this.now(), this.policy.sessionHours)\n })\n return { kind: 'session', ...issued }\n }\n\n async verifyMfa(id: string, code: string): Promise<{ token: string; expiresAt: number }> {\n this.occupyAttempt()\n const challenge = this.claim(id, 'mfa') as MfaChallenge\n try {\n const issued = await this.store.transact((draft) => {\n if (challenge.expiresAt <= this.now()) throw new AuthError('challenge_expired')\n const account = this.sameAccount(draft, challenge.accountId, challenge.securityVersion)\n if (!account.totp || !this.verifyFactor(account, code))\n throw new AuthError('invalid_factor')\n return issueSession(draft, this.now(), this.policy.sessionHours)\n })\n this.challenges.delete(id)\n return issued\n } catch (error) {\n if (error instanceof AuthError && error.code === 'invalid_factor')\n this.failedChallenge(challenge)\n throw error\n } finally {\n challenge.busy = false\n }\n }\n\n async startBinding(\n token: string,\n password: string,\n currentCode?: string,\n ): Promise<Extract<LoginResult, { kind: 'binding' }>> {\n this.occupyAttempt()\n const snapshot = this.store.current()\n const account = this.requireSession(snapshot, token)\n if (typeof password !== 'string' || password.length > 1024)\n throw new AuthError('invalid_credentials')\n const match = await this.derive(() => verifyPassword(password, account.password))\n if (!match) throw new AuthError('invalid_credentials')\n if (account.totp) {\n await this.store.transact((draft) => {\n this.requireSession(draft, token)\n this.sameAccount(draft, account.id, account.securityVersion)\n if (!this.verifyFactor(draft.account!, currentCode)) throw new AuthError('invalid_factor')\n })\n } else {\n const latest = this.store.current()\n this.requireSession(latest, token)\n this.sameAccount(latest, account.id, account.securityVersion)\n }\n return this.createChallenge('binding', account, sessionHash(token)) as Extract<\n LoginResult,\n { kind: 'binding' }\n >\n }\n\n async confirmBinding(id: string, code: string): Promise<{ backupCodes: string[] }> {\n this.occupyAttempt()\n const challenge = this.claim(id, 'binding') as BindingChallenge\n try {\n const step = matchedTotpStep(challenge.secret, code, this.now(), null)\n if (step === null) {\n this.failedChallenge(challenge)\n throw new AuthError('invalid_factor')\n }\n const backups = generateBackupCodes()\n await this.store.transact((draft) => {\n if (challenge.expiresAt <= this.now()) throw new AuthError('challenge_expired')\n const account = this.sameAccount(draft, challenge.accountId, challenge.securityVersion)\n const originSession = challenge.originSessionHash\n ? draft.sessions[challenge.originSessionHash]\n : null\n if (\n challenge.originSessionHash &&\n (!originSession || originSession.expiresAt <= this.now())\n )\n throw new AuthError('unauthorized')\n account.totp = {\n secret: challenge.secret,\n lastUsedStep: step,\n backupCodeHashes: backups.hashes,\n }\n account.securityVersion++\n draft.sessions = {}\n })\n this.challenges.clear()\n return { backupCodes: backups.codes }\n } finally {\n challenge.busy = false\n }\n }\n\n async changePassword(\n token: string,\n currentPassword: string,\n currentCode: string | undefined,\n newPassword: string,\n ): Promise<void> {\n this.occupyAttempt()\n validatePassword(newPassword)\n if (typeof currentPassword !== 'string' || currentPassword.length > 1024)\n throw new AuthError('invalid_credentials')\n const snapshot = this.store.current()\n const account = this.requireSession(snapshot, token)\n const match = await this.derive(() => verifyPassword(currentPassword, account.password))\n if (!match) throw new AuthError('invalid_credentials')\n const replacement = await this.derive(() => hashPassword(newPassword))\n await this.store.transact((draft) => {\n this.requireSession(draft, token)\n const current = this.sameAccount(draft, account.id, account.securityVersion)\n if (!this.verifyFactor(current, currentCode)) throw new AuthError('invalid_factor')\n current.password = replacement\n current.securityVersion++\n draft.sessions = {}\n })\n }\n\n async disableTotp(token: string, password: string, currentCode: string): Promise<void> {\n this.occupyAttempt()\n if (this.policy.requireTotp) throw new AuthError('totp_required')\n if (typeof password !== 'string' || password.length > 1024)\n throw new AuthError('invalid_credentials')\n const snapshot = this.store.current()\n const account = this.requireSession(snapshot, token)\n const match = await this.derive(() => verifyPassword(password, account.password))\n if (!match) throw new AuthError('invalid_credentials')\n await this.store.transact((draft) => {\n this.requireSession(draft, token)\n const current = this.sameAccount(draft, account.id, account.securityVersion)\n if (!current.totp || !this.verifyFactor(current, currentCode))\n throw new AuthError('invalid_factor')\n current.totp = null\n current.securityVersion++\n draft.sessions = {}\n })\n }\n\n async revokeWithCredentials(\n token: string,\n password: string,\n currentCode?: string,\n ): Promise<void> {\n this.occupyAttempt()\n if (typeof password !== 'string' || password.length > 1024)\n throw new AuthError('invalid_credentials')\n const snapshot = this.store.current()\n const account = this.requireSession(snapshot, token)\n const match = await this.derive(() => verifyPassword(password, account.password))\n if (!match) throw new AuthError('invalid_credentials')\n await this.store.transact((draft) => {\n this.requireSession(draft, token)\n const current = this.sameAccount(draft, account.id, account.securityVersion)\n if (!this.verifyFactor(current, currentCode)) throw new AuthError('invalid_factor')\n current.securityVersion++\n draft.sessions = {}\n })\n }\n\n async logout(token: string): Promise<void> {\n if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/u.test(token)) return\n const hash = sessionHash(token)\n if (!this.store.current().sessions[hash]) return\n await this.store.transact((draft) => {\n delete draft.sessions[hash]\n })\n }\n\n async resetPassword(newPassword: string): Promise<void> {\n validatePassword(newPassword)\n const replacement = await this.derive(() => hashPassword(newPassword))\n await this.store.transact((draft) => {\n if (!draft.account) throw new AuthError('uninitialized')\n draft.account.password = replacement\n draft.account.securityVersion++\n draft.sessions = {}\n })\n }\n\n async resetTotp(): Promise<void> {\n await this.store.transact((draft) => {\n if (!draft.account) throw new AuthError('uninitialized')\n draft.account.totp = null\n draft.account.securityVersion++\n draft.sessions = {}\n })\n }\n\n async revokeAll(): Promise<void> {\n await this.store.transact((draft) => {\n if (!draft.account) throw new AuthError('uninitialized')\n draft.account.securityVersion++\n draft.sessions = {}\n })\n }\n\n async applyPolicy(next: AuthPolicy): Promise<void> {\n validatePolicy(next, this.now())\n if (this.policyChanging) throw new AuthError('busy')\n if (\n next.requireTotp === this.policy.requireTotp &&\n next.sessionHours === this.policy.sessionHours\n )\n return\n this.policyChanging = true\n const previous = this.policy\n this.policy = next // fail closed while the policy commit is pending\n try {\n await this.store.transact((draft) => {\n if (next.requireTotp && !previous.requireTotp && draft.account && !draft.account.totp) {\n draft.account.securityVersion++\n draft.sessions = {}\n }\n if (next.sessionHours < previous.sessionHours) {\n for (const session of Object.values(draft.sessions))\n session.expiresAt = Math.min(\n session.expiresAt,\n session.createdAt + next.sessionHours * 3_600_000,\n )\n }\n })\n this.challenges.clear()\n } catch (error) {\n if (this.store.healthy()) this.policy = previous\n throw error\n } finally {\n this.policyChanging = false\n }\n }\n\n /** Startup/re-activation must persist tightening before the guarded listener opens. */\n async enforceCurrentPolicy(): Promise<void> {\n const state = this.store.current()\n const revokeUnbound =\n this.policy.requireTotp && !state.account?.totp && Object.keys(state.sessions).length > 0\n const shorten = Object.values(state.sessions).some(\n (session) => session.expiresAt > session.createdAt + this.policy.sessionHours * 3_600_000,\n )\n if (!revokeUnbound && !shorten) return\n await this.store.transact((draft) => {\n if (this.policy.requireTotp && draft.account && !draft.account.totp) {\n draft.account.securityVersion++\n draft.sessions = {}\n }\n for (const session of Object.values(draft.sessions))\n session.expiresAt = Math.min(\n session.expiresAt,\n session.createdAt + this.policy.sessionHours * 3_600_000,\n )\n })\n }\n}\n", "import { randomUUID } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport { lstat, open, readFile, rename, unlink } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { assertPrivateStateFile, STATE_FILE, StateLock } from './lock.js'\nimport { emptyState, validateState, type AuthState } from './state.js'\n\nexport type CommitStage =\n | 'afterTempWrite'\n | 'afterFileSync'\n | 'beforeRename'\n | 'afterRename'\n | 'afterDirSync'\n | 'beforeSuccess'\n\nexport interface StoreOptions {\n /** A failed notification makes the store unavailable before a caller can report success. */\n onCommitted?: (previous: AuthState, current: AuthState) => void | Promise<void>\n onUnavailable?: (reason: Error) => void\n /** Fault injection for isolated tests only. */\n onStage?: (stage: CommitStage) => void | Promise<void>\n}\n\nfunction errno(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && error.code === code\n}\n\n/** One process owns the lock; every mutation serializes through this instance. */\nexport class AuthStateStore {\n readonly path: string\n private state: AuthState\n private queue: Promise<void> = Promise.resolve()\n private unavailableReason: Error | null = null\n private closed = false\n private readonly listeners = new Set<\n (previous: AuthState, current: AuthState) => void | Promise<void>\n >()\n\n private constructor(\n private readonly lock: StateLock,\n state: AuthState,\n private readonly options: StoreOptions,\n ) {\n this.path = join(lock.dir, STATE_FILE)\n this.state = state\n }\n\n static async open(profileDir: string, options: StoreOptions = {}): Promise<AuthStateStore> {\n const lock = await StateLock.acquire(profileDir)\n try {\n const path = join(lock.dir, STATE_FILE)\n let state = emptyState()\n try {\n await assertPrivateStateFile(path)\n const info = await lstat(path)\n if (info.size > 16 * 1024 * 1024)\n throw new Error('auth-remote: state file exceeds the supported size')\n state = validateState(JSON.parse(await readFile(path, 'utf8')))\n } catch (error) {\n if (!errno(error, 'ENOENT')) throw error\n }\n return new AuthStateStore(lock, state, options)\n } catch (error) {\n await lock.release()\n throw error\n }\n }\n\n healthy(): boolean {\n return !this.closed && this.unavailableReason === null\n }\n\n current(): AuthState {\n if (!this.healthy()) throw this.unavailableReason ?? new Error('auth-remote: store is closed')\n return structuredClone(this.state)\n }\n\n /** Notifications finish before transact reports success; a failed listener closes admission. */\n subscribe(\n listener: (previous: AuthState, current: AuthState) => void | Promise<void>,\n ): () => void {\n if (!this.healthy()) throw this.unavailableReason ?? new Error('auth-remote: store is closed')\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n async transact<T>(mutate: (draft: AuthState) => T | Promise<T>): Promise<T> {\n const run = async (): Promise<T> => {\n if (!this.healthy()) throw this.unavailableReason ?? new Error('auth-remote: store is closed')\n const draft = structuredClone(this.state)\n const result = await mutate(draft)\n if (this.state.revision >= Number.MAX_SAFE_INTEGER)\n throw new Error('auth-remote: state revision exhausted')\n draft.revision = this.state.revision + 1\n const next = validateState(draft)\n await this.persist(next)\n return result\n }\n const operation = this.queue.then(run)\n this.queue = operation.then(\n () => undefined,\n () => undefined,\n )\n return operation\n }\n\n private async persist(next: AuthState): Promise<void> {\n const temp = `${this.path}.tmp-${process.pid}-${randomUUID()}`\n const bytes = Buffer.from(`${JSON.stringify(next)}\\n`, 'utf8')\n if (bytes.length > 16 * 1024 * 1024)\n throw new Error('auth-remote: state file exceeds the supported size')\n let renamed = false\n let file: Awaited<ReturnType<typeof open>> | undefined\n try {\n file = await open(\n temp,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,\n 0o600,\n )\n await file.writeFile(bytes)\n await this.options.onStage?.('afterTempWrite')\n await file.sync()\n await this.options.onStage?.('afterFileSync')\n await file.close()\n file = undefined\n await this.options.onStage?.('beforeRename')\n await rename(temp, this.path)\n renamed = true\n await this.options.onStage?.('afterRename')\n const parent = await open(this.lock.dir, constants.O_RDONLY | constants.O_DIRECTORY)\n try {\n await parent.sync()\n } finally {\n await parent.close()\n }\n await this.options.onStage?.('afterDirSync')\n const previous = this.state\n this.state = next\n await this.options.onCommitted?.(structuredClone(previous), structuredClone(next))\n for (const listener of this.listeners)\n await listener(structuredClone(previous), structuredClone(next))\n await this.options.onStage?.('beforeSuccess')\n } catch (error) {\n if (renamed) {\n this.unavailableReason = new Error('auth-remote: state commit outcome is uncertain', {\n cause: error,\n })\n this.options.onUnavailable?.(this.unavailableReason)\n }\n throw error\n } finally {\n await file?.close().catch(() => undefined)\n if (!renamed) await unlink(temp).catch(() => undefined)\n }\n }\n\n async close(): Promise<void> {\n if (this.closed) return\n this.closed = true\n await this.queue\n await this.lock.release()\n }\n}\n", "import { randomUUID } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport { lstat, mkdir, open, readFile, rmdir, unlink } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nexport const STATE_DIR = 'auth-remote'\nexport const STATE_FILE = 'auth-state.json'\nexport const LOCK_FILE = 'auth-state.lock'\n\ninterface Owner {\n pid: number\n bootId: string\n startTicks: string\n nonce: string\n}\n\nfunction errno(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && error.code === code\n}\n\nasync function processStartTicks(pid: number): Promise<string | null> {\n let raw: string\n try {\n raw = await readFile(`/proc/${pid}/stat`, 'utf8')\n } catch (error) {\n if (errno(error, 'ENOENT')) return null\n throw error\n }\n const tail = raw\n .slice(raw.lastIndexOf(')') + 1)\n .trim()\n .split(/\\s+/u)\n const ticks = tail[19]\n if (!ticks || !/^\\d+$/u.test(ticks)) throw new Error('auth-remote: cannot verify lock owner')\n return ticks\n}\n\nasync function localOwner(): Promise<Owner> {\n const [bootId, startTicks] = await Promise.all([\n readFile('/proc/sys/kernel/random/boot_id', 'utf8'),\n processStartTicks(process.pid),\n ])\n if (!startTicks) throw new Error('auth-remote: cannot verify own process identity')\n return { pid: process.pid, bootId: bootId.trim(), startTicks, nonce: randomUUID() }\n}\n\nfunction parseOwner(raw: string): Owner {\n let value: unknown\n try {\n value = JSON.parse(raw)\n } catch {\n throw new Error('auth-remote: lock owner is unreadable; manual recovery required')\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value))\n throw new Error('auth-remote: lock owner is invalid; manual recovery required')\n const owner = value as Record<string, unknown>\n if (\n !Number.isSafeInteger(owner.pid) ||\n (owner.pid as number) <= 0 ||\n typeof owner.bootId !== 'string' ||\n !/^[0-9a-f-]{36}$/u.test(owner.bootId) ||\n typeof owner.startTicks !== 'string' ||\n !/^\\d+$/u.test(owner.startTicks) ||\n typeof owner.nonce !== 'string' ||\n !/^[0-9a-f-]{36}$/u.test(owner.nonce)\n )\n throw new Error('auth-remote: lock owner is invalid; manual recovery required')\n return owner as unknown as Owner\n}\n\nasync function isDead(owner: Owner, currentBootId: string): Promise<boolean> {\n if (owner.bootId !== currentBootId) return true\n const ticks = await processStartTicks(owner.pid)\n return ticks === null || ticks !== owner.startTicks\n}\n\nasync function assertPrivate(path: string, kind: 'directory' | 'file'): Promise<void> {\n const info = await lstat(path)\n if (\n (kind === 'directory' ? !info.isDirectory() : !info.isFile()) ||\n info.uid !== process.getuid?.() ||\n (info.mode & 0o777) !== (kind === 'directory' ? 0o700 : 0o600)\n )\n throw new Error(`auth-remote: unsafe ${kind} permissions or owner: ${path}`)\n}\n\nexport async function ensureStateDirectory(profileDir: string): Promise<string> {\n if (process.platform !== 'linux') throw new Error('auth-remote: storage requires Linux /proc')\n const dir = join(profileDir, STATE_DIR)\n let created = false\n try {\n await mkdir(dir, { mode: 0o700 })\n created = true\n } catch (error) {\n if (!errno(error, 'EEXIST')) throw error\n }\n await assertPrivate(dir, 'directory')\n if (created) {\n const parent = await open(profileDir, constants.O_RDONLY | constants.O_DIRECTORY)\n try {\n await parent.sync()\n } finally {\n await parent.close()\n }\n }\n return dir\n}\n\n/** Lock recovery uses a second exclusive directory, so reclaimers cannot erase one another's new lock. */\nexport class StateLock {\n private released = false\n\n private constructor(\n readonly dir: string,\n readonly path: string,\n private readonly owner: Owner,\n ) {}\n\n static async acquire(profileDir: string): Promise<StateLock> {\n const dir = await ensureStateDirectory(profileDir)\n const path = join(dir, LOCK_FILE)\n const owner = await localOwner()\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n const file = await open(\n path,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,\n 0o600,\n )\n try {\n await file.writeFile(JSON.stringify(owner))\n await file.sync()\n } catch (error) {\n await file.close()\n await unlink(path).catch(() => undefined)\n throw error\n }\n await file.close()\n return new StateLock(dir, path, owner)\n } catch (error) {\n if (!errno(error, 'EEXIST')) throw error\n if (attempt === 1) throw new Error('auth-remote: state lock is held or contested')\n await this.recoverStale(dir, path, owner.bootId)\n }\n }\n throw new Error('auth-remote: state lock acquisition failed')\n }\n\n private static async recoverStale(\n dir: string,\n path: string,\n currentBootId: string,\n ): Promise<void> {\n const recovery = `${path}.recovery`\n try {\n await mkdir(recovery, { mode: 0o700 })\n } catch (error) {\n if (errno(error, 'EEXIST'))\n throw new Error(\n 'auth-remote: lock recovery is already active or abandoned; manual review required',\n )\n throw error\n }\n try {\n let info\n try {\n info = await lstat(path)\n } catch (error) {\n if (errno(error, 'ENOENT')) return\n throw error\n }\n await assertPrivate(path, 'file')\n const old = parseOwner(await readFile(path, 'utf8'))\n if (!(await isDead(old, currentBootId)))\n throw new Error(`auth-remote: state lock held by live process ${old.pid}`)\n const latest = await lstat(path)\n if (latest.ino !== info.ino || latest.dev !== info.dev)\n throw new Error('auth-remote: state lock changed during recovery')\n await unlink(path)\n const parent = await open(dir, constants.O_RDONLY | constants.O_DIRECTORY)\n try {\n await parent.sync()\n } finally {\n await parent.close()\n }\n } finally {\n await rmdir(recovery)\n }\n }\n\n async release(): Promise<void> {\n if (this.released) return\n const current = parseOwner(await readFile(this.path, 'utf8'))\n if (current.nonce !== this.owner.nonce)\n throw new Error('auth-remote: state lock ownership changed before release')\n await unlink(this.path)\n this.released = true\n }\n}\n\nexport async function assertPrivateStateFile(path: string): Promise<void> {\n await assertPrivate(path, 'file')\n}\n", "/** The only persisted representation of account and full-session state. */\nexport const STATE_SCHEMA_VERSION = 1\n\nexport interface PasswordRecord {\n salt: string\n hash: string\n}\n\nexport interface TotpRecord {\n secret: string\n lastUsedStep: number | null\n backupCodeHashes: string[]\n}\n\nexport interface AccountRecord {\n id: string\n username: string\n password: PasswordRecord\n totp: TotpRecord | null\n securityVersion: number\n}\n\nexport interface SessionRecord {\n accountId: string\n securityVersion: number\n createdAt: number\n expiresAt: number\n}\n\nexport interface AuthState {\n schemaVersion: typeof STATE_SCHEMA_VERSION\n revision: number\n account: AccountRecord | null\n /** Keys are SHA-256 token hashes, never bearer tokens. */\n sessions: Record<string, SessionRecord>\n}\n\nexport function emptyState(): AuthState {\n return { schemaVersion: STATE_SCHEMA_VERSION, revision: 0, account: null, sessions: {} }\n}\n\nfunction record(value: unknown, keys: string[], label: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value))\n throw new Error(`auth-remote: invalid ${label}`)\n const entries = Object.keys(value)\n if (entries.length !== keys.length || entries.some((key) => !keys.includes(key)))\n throw new Error(`auth-remote: invalid ${label} fields`)\n return value as Record<string, unknown>\n}\n\nfunction integer(value: unknown, label: string, min = 0): number {\n if (!Number.isSafeInteger(value) || (value as number) < min)\n throw new Error(`auth-remote: invalid ${label}`)\n return value as number\n}\n\nfunction nonempty(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.length === 0)\n throw new Error(`auth-remote: invalid ${label}`)\n return value\n}\n\nfunction hex(value: unknown, bytes: number, label: string): string {\n if (typeof value !== 'string' || !new RegExp(`^[a-f0-9]{${bytes * 2}}$`, 'u').test(value))\n throw new Error(`auth-remote: invalid ${label}`)\n return value\n}\n\nfunction digest(value: unknown, label: string): string {\n if (typeof value !== 'string' || !/^[a-f0-9]{64}$/u.test(value))\n throw new Error(`auth-remote: invalid ${label}`)\n return value\n}\n\nexport function validateState(value: unknown): AuthState {\n const state = record(value, ['schemaVersion', 'revision', 'account', 'sessions'], 'state')\n if (state.schemaVersion !== STATE_SCHEMA_VERSION)\n throw new Error(`auth-remote: unsupported state schema version ${String(state.schemaVersion)}`)\n const revision = integer(state.revision, 'revision')\n let account: AccountRecord | null = null\n if (state.account !== null) {\n const entry = record(\n state.account,\n ['id', 'username', 'password', 'totp', 'securityVersion'],\n 'account',\n )\n const password = record(entry.password, ['salt', 'hash'], 'password record')\n let totp: TotpRecord | null = null\n if (entry.totp !== null) {\n const factor = record(\n entry.totp,\n ['secret', 'lastUsedStep', 'backupCodeHashes'],\n 'TOTP record',\n )\n if (!Array.isArray(factor.backupCodeHashes) || factor.backupCodeHashes.length > 10)\n throw new Error('auth-remote: invalid backup code hashes')\n if (typeof factor.secret !== 'string' || !/^[A-Z2-7]{32}$/u.test(factor.secret))\n throw new Error('auth-remote: invalid TOTP secret')\n totp = {\n secret: factor.secret,\n lastUsedStep:\n factor.lastUsedStep === null ? null : integer(factor.lastUsedStep, 'TOTP step'),\n backupCodeHashes: factor.backupCodeHashes.map((hash) => digest(hash, 'backup code hash')),\n }\n if (new Set(totp.backupCodeHashes).size !== totp.backupCodeHashes.length)\n throw new Error('auth-remote: duplicate backup code hash')\n }\n const username = nonempty(entry.username, 'username')\n if ([...username].length > 64 || /[\\u0000-\\u001f\\u007f]/u.test(username))\n throw new Error('auth-remote: invalid username')\n account = {\n id: hex(entry.id, 16, 'account id'),\n username,\n password: {\n salt: hex(password.salt, 32, 'password salt'),\n hash: hex(password.hash, 64, 'password hash'),\n },\n totp,\n securityVersion: integer(entry.securityVersion, 'security version', 1),\n }\n }\n const sessions = state.sessions\n if (typeof sessions !== 'object' || sessions === null || Array.isArray(sessions))\n throw new Error('auth-remote: invalid sessions')\n const validatedSessions: Record<string, SessionRecord> = Object.create(null)\n for (const [hash, value] of Object.entries(sessions)) {\n digest(hash, 'session token hash')\n const session = record(\n value,\n ['accountId', 'securityVersion', 'createdAt', 'expiresAt'],\n 'session',\n )\n const createdAt = integer(session.createdAt, 'session creation')\n const expiresAt = integer(session.expiresAt, 'session expiry')\n if (!account || session.accountId !== account.id || expiresAt <= createdAt)\n throw new Error('auth-remote: invalid session account or lifetime')\n validatedSessions[hash] = {\n accountId: account.id,\n securityVersion: integer(session.securityVersion, 'session security version', 1),\n createdAt,\n expiresAt,\n }\n }\n return { schemaVersion: STATE_SCHEMA_VERSION, revision, account, sessions: validatedSessions }\n}\n", "import { randomBytes, scrypt as scryptCallback, timingSafeEqual } from 'node:crypto'\nimport type { PasswordRecord } from '../storage/state.js'\n\nexport const PASSWORD_MIN_CHARACTERS = 12\nexport const PASSWORD_MAX_CHARACTERS = 256\n\nexport class PasswordValidationError extends Error {\n constructor() {\n super('auth-remote: password must contain 12\u2013256 Unicode characters')\n }\n}\n\nexport function validatePassword(password: unknown): asserts password is string {\n if (\n typeof password !== 'string' ||\n [...password].length < PASSWORD_MIN_CHARACTERS ||\n [...password].length > PASSWORD_MAX_CHARACTERS\n )\n throw new PasswordValidationError()\n}\n\nasync function derive(password: string, salt: string): Promise<Buffer> {\n return new Promise<Buffer>((resolve, reject) => {\n scryptCallback(\n password,\n Buffer.from(salt, 'hex'),\n 64,\n { N: 16_384, r: 8, p: 1, maxmem: 32 * 1024 * 1024 },\n (error, key) => (error ? reject(error) : resolve(key)),\n )\n })\n}\n\nexport async function hashPassword(password: string): Promise<PasswordRecord> {\n validatePassword(password)\n const salt = randomBytes(32).toString('hex')\n return { salt, hash: (await derive(password, salt)).toString('hex') }\n}\n\nexport async function verifyPassword(password: string, record: PasswordRecord): Promise<boolean> {\n const derived = await derive(password, record.salt)\n return timingSafeEqual(derived, Buffer.from(record.hash, 'hex'))\n}\n\n/** Wrong usernames still perform a comparable derivation. */\nexport const DUMMY_PASSWORD_RECORD: PasswordRecord = {\n salt: '0'.repeat(64),\n hash: '0'.repeat(128),\n}\n", "import { createHash, randomBytes } from 'node:crypto'\nimport type { AuthState, SessionRecord } from '../storage/state.js'\n\nexport function sessionHash(token: string): string {\n return createHash('sha256').update(token).digest('hex')\n}\n\nexport function issueSession(\n draft: AuthState,\n now: number,\n sessionHours: number,\n): { token: string; expiresAt: number } {\n const account = draft.account\n if (!account) throw new Error('auth-remote: cannot issue a session without an account')\n const expiresAt = now + sessionHours * 3_600_000\n if (!Number.isSafeInteger(expiresAt)) throw new Error('auth-remote: session expiry overflow')\n const token = randomBytes(32).toString('base64url')\n draft.sessions[sessionHash(token)] = {\n accountId: account.id,\n securityVersion: account.securityVersion,\n createdAt: now,\n expiresAt,\n }\n return { token, expiresAt }\n}\n\nexport function sessionFor(\n state: AuthState,\n token: string,\n now: number,\n requireTotp: boolean,\n): SessionRecord | null {\n if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/u.test(token)) return null\n const session = state.sessions[sessionHash(token)]\n const account = state.account\n if (\n !session ||\n !account ||\n session.accountId !== account.id ||\n session.securityVersion !== account.securityVersion ||\n session.expiresAt <= now ||\n (requireTotp && !account.totp)\n )\n return null\n return session\n}\n", "import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\n\nconst alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nexport const TOTP_PERIOD_MS = 30_000\n\nfunction base32(bytes: Buffer): string {\n let bits = 0\n let value = 0\n let output = ''\n for (const byte of bytes) {\n value = (value << 8) | byte\n bits += 8\n while (bits >= 5) {\n output += alphabet[(value >>> (bits - 5)) & 31]\n bits -= 5\n }\n }\n if (bits > 0) output += alphabet[(value << (5 - bits)) & 31]\n return output\n}\n\nfunction fromBase32(value: string): Buffer {\n let bits = 0\n let accum = 0\n const output: number[] = []\n for (const char of value) {\n const digit = alphabet.indexOf(char)\n if (digit < 0) throw new Error('auth-remote: invalid TOTP secret')\n accum = (accum << 5) | digit\n bits += 5\n if (bits >= 8) {\n output.push((accum >>> (bits - 8)) & 255)\n bits -= 8\n }\n }\n return Buffer.from(output)\n}\n\nexport function generateTotpSecret(): string {\n return base32(randomBytes(20))\n}\n\nexport function totpCode(secret: string, step: number): string {\n if (!Number.isSafeInteger(step) || step < 0) throw new Error('auth-remote: invalid TOTP step')\n const counter = Buffer.alloc(8)\n counter.writeBigUInt64BE(BigInt(step))\n const mac = createHmac('sha1', fromBase32(secret)).update(counter).digest()\n const offset = mac[mac.length - 1]! & 15\n const value = (mac.readUInt32BE(offset) & 0x7fff_ffff) % 1_000_000\n return String(value).padStart(6, '0')\n}\n\nexport function matchedTotpStep(\n secret: string,\n code: string,\n timestamp: number,\n lastUsedStep: number | null,\n): number | null {\n if (typeof code !== 'string' || !/^\\d{6}$/u.test(code)) return null\n const current = Math.floor(timestamp / TOTP_PERIOD_MS)\n for (const step of [current - 1, current, current + 1]) {\n if (step < 0 || (lastUsedStep !== null && step <= lastUsedStep)) continue\n if (timingSafeEqual(Buffer.from(totpCode(secret, step)), Buffer.from(code))) return step\n }\n return null\n}\n\nexport function backupCodeHash(code: string): string | null {\n if (typeof code !== 'string') return null\n const canonical = code.replaceAll('-', '').toUpperCase()\n if (!/^[A-Z2-7]{20}$/u.test(canonical)) return null\n return createHash('sha256').update(`auth-remote-backup:${canonical}`).digest('hex')\n}\n\nexport function generateBackupCodes(): { codes: string[]; hashes: string[] } {\n const codes = Array.from({ length: 10 }, () =>\n base32(randomBytes(12))\n .match(/.{1,5}/gu)!\n .join('-'),\n )\n return { codes, hashes: codes.map((code) => backupCodeHash(code)!) }\n}\n", "import type { Config as WebServerConfig } from '@deepseek-ai/dsh-host-webserver'\nimport z from '@deepseek-ai/schemastery'\nimport { isIP } from 'node:net'\nimport { createOriginPolicy, type OriginPolicy } from './http/origin-policy.js'\n\nexport interface AuthConfig {\n allowedOrigins?: string[]\n requireTotp?: boolean\n sessionHours?: number\n preserveOriginPaths?: string[]\n}\n\nexport interface ResolvedAuthConfig extends Omit<WebServerConfig, 'host'> {\n host: string\n allowedOrigins: readonly string[]\n originPolicy: OriginPolicy\n requireTotp: boolean\n sessionHours: number\n preserveOriginPaths: readonly string[]\n}\n\nexport const DEFAULT_REQUIRE_TOTP = true\nexport const DEFAULT_SESSION_HOURS = 168\nexport const DEFAULT_WEB_HOST = '127.0.0.1'\nexport const DEFAULT_WEB_PORT = 3080\nconst AUTH_CONFIG_KEYS = new Set([\n 'allowedOrigins',\n 'requireTotp',\n 'sessionHours',\n 'preserveOriginPaths',\n])\n\nexport interface WebListenerConfig extends Omit<WebServerConfig, 'host'> {\n host: string\n}\n\n// The Loader resolves defaults before apply(). Programmatic activation is\n// checked here as well because it need not pass through the Loader.\nexport const Config: z<AuthConfig> = z.object({\n allowedOrigins: z.array(z.string()).default([]),\n requireTotp: z.boolean().default(DEFAULT_REQUIRE_TOTP),\n sessionHours: z.number().step(1).min(1).default(DEFAULT_SESSION_HOURS),\n preserveOriginPaths: z.array(z.string()).default([]),\n})\n\nexport function resolveAuthConfig(\n input: AuthConfig,\n listener: WebListenerConfig,\n): ResolvedAuthConfig {\n if (typeof input !== 'object' || input === null)\n throw new Error('auth-remote: config is required')\n for (const key of Object.keys(input))\n if (!AUTH_CONFIG_KEYS.has(key))\n throw new Error(`auth-remote: unknown config key ${JSON.stringify(key)}`)\n const config = Config(input)\n if (isIP(listener.host) !== 4) throw new Error('auth-remote: DSH web startup host must be IPv4')\n if (listener.host === '0.0.0.0')\n throw new Error('auth-remote: DSH does not support --host 0.0.0.0')\n if (!Number.isInteger(listener.port) || listener.port < 0 || listener.port > 65535)\n throw new Error('auth-remote: invalid DSH web startup port')\n const originPolicy = createOriginPolicy(config.allowedOrigins ?? [])\n const sessionHours = config.sessionHours ?? DEFAULT_SESSION_HOURS\n if (\n !Number.isSafeInteger(sessionHours) ||\n !Number.isSafeInteger(Date.now() + sessionHours * 3_600_000)\n ) {\n throw new Error('auth-remote: sessionHours exceeds the safe timestamp range')\n }\n const paths = config.preserveOriginPaths ?? []\n const seen = new Set<string>()\n for (const path of paths) {\n if (!isCanonicalPathPrefix(path)) {\n throw new Error(`auth-remote: invalid preserveOriginPaths entry ${JSON.stringify(path)}`)\n }\n if (seen.has(path))\n throw new Error(`auth-remote: duplicate preserveOriginPaths entry ${JSON.stringify(path)}`)\n seen.add(path)\n }\n return {\n host: listener.host,\n port: listener.port,\n compression: listener.compression ?? 'none',\n compressionLevel: listener.compressionLevel ?? 1,\n compressionThresholdBytes: listener.compressionThresholdBytes ?? 1024,\n allowedOrigins: Object.freeze(originPolicy.registeredOrigins.map((entry) => entry.origin)),\n originPolicy,\n requireTotp: config.requireTotp ?? DEFAULT_REQUIRE_TOTP,\n sessionHours,\n preserveOriginPaths: paths,\n }\n}\n\nfunction isCanonicalPathPrefix(path: string): boolean {\n if (!path.startsWith('/') || (path.length > 1 && path.endsWith('/'))) return false\n if (/[?#*\\\\]/u.test(path)) return false\n let url: URL\n try {\n url = new URL(path, 'http://auth-remote.invalid')\n } catch {\n return false\n }\n if (url.pathname !== path || url.search !== '' || url.hash !== '') return false\n for (const segment of path.slice(1).split('/')) {\n if (segment === '' && path !== '/') return false\n let decoded: string\n try {\n decoded = decodeURIComponent(segment)\n } catch {\n return false\n }\n if (decoded === '.' || decoded === '..' || /[/\\\\\\u0000-\\u001f\\u007f]/u.test(decoded))\n return false\n }\n return true\n}\n", "import type { ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { AuthState, SessionRecord } from '../storage/state.js'\nimport { AuthStateStore } from '../storage/store.js'\nimport { AuthService } from '../auth/service.js'\n\ninterface Tracked {\n hash: string\n expiresAt: number\n timer: NodeJS.Timeout | undefined\n close(): Promise<void>\n}\n\n/** Long responses and upgraded sockets close before revocation commits report success. */\nexport class AuthConnections {\n private readonly active = new Set<Tracked>()\n private readonly unsubscribe: () => void\n\n constructor(\n store: AuthStateStore,\n private readonly auth: AuthService,\n ) {\n this.unsubscribe = store.subscribe((_previous, current) => this.reconcile(current))\n }\n\n trackResponse(hash: string, session: SessionRecord, response: ServerResponse): void {\n const entry = this.makeEntry(\n hash,\n session.expiresAt,\n () =>\n new Promise<void>((resolve) => {\n if (response.destroyed || response.writableEnded) return resolve()\n response.once('close', () => resolve())\n response.destroy()\n }),\n )\n response.once('close', () => this.remove(entry))\n response.once('finish', () => this.remove(entry))\n }\n\n trackSocket(hash: string, session: SessionRecord, socket: Duplex): void {\n const entry = this.makeEntry(\n hash,\n session.expiresAt,\n () =>\n new Promise<void>((resolve) => {\n if (socket.destroyed) return resolve()\n socket.once('close', () => resolve())\n socket.destroy()\n }),\n )\n socket.once('close', () => this.remove(entry))\n }\n\n private makeEntry(hash: string, expiresAt: number, close: () => Promise<void>): Tracked {\n let closing: Promise<void> | undefined\n const entry: Tracked = {\n hash,\n expiresAt,\n timer: undefined,\n close: () => (closing ??= close()),\n }\n this.active.add(entry)\n this.schedule(entry)\n return entry\n }\n\n private schedule(entry: Tracked): void {\n if (entry.timer) clearTimeout(entry.timer)\n const remaining = entry.expiresAt - Date.now()\n entry.timer = setTimeout(\n () => {\n if (entry.expiresAt <= Date.now()) void entry.close()\n else this.schedule(entry)\n },\n Math.max(1, Math.min(remaining, 2_147_483_647)),\n )\n entry.timer.unref()\n }\n\n private remove(entry: Tracked): void {\n if (!this.active.delete(entry)) return\n if (entry.timer) clearTimeout(entry.timer)\n }\n\n async reconcile(state: AuthState): Promise<void> {\n const closing: Promise<void>[] = []\n for (const entry of this.active) {\n const session = state.sessions[entry.hash]\n const account = state.account\n if (\n !session ||\n !account ||\n session.accountId !== account.id ||\n session.securityVersion !== account.securityVersion ||\n session.expiresAt <= Date.now() ||\n (this.auth.policySnapshot().requireTotp && !account.totp)\n ) {\n closing.push(entry.close())\n } else if (entry.expiresAt !== session.expiresAt) {\n entry.expiresAt = session.expiresAt\n this.schedule(entry)\n }\n }\n await Promise.all(closing)\n }\n\n async closeAll(): Promise<void> {\n await Promise.all([...this.active].map((entry) => entry.close()))\n }\n\n async dispose(): Promise<void> {\n this.unsubscribe()\n await this.closeAll()\n }\n}\n", "import { createServer, type Server, type Socket } from 'node:net'\nimport { chmod, lstat, unlink } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { PasswordValidationError } from '../auth/password.js'\nimport { AuthError, AuthService } from '../auth/service.js'\nimport {\n ADMIN_MAX_BYTES,\n ADMIN_PROTOCOL_VERSION,\n type AdminRequest,\n type AdminResponse,\n type AdminStatus,\n} from '../shared/admin-contract.js'\nimport { STATE_DIR } from '../storage/lock.js'\n\nfunction errno(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && error.code === code\n}\n\nfunction validRequest(value: unknown): AdminRequest | null {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null\n const row = value as Record<string, unknown>\n if (row.version !== ADMIN_PROTOCOL_VERSION || typeof row.command !== 'string') return null\n const allowed: Record<string, readonly string[]> = {\n status: ['version', 'command'],\n init: ['version', 'command', 'username', 'password'],\n 'reset-password': ['version', 'command', 'password'],\n 'reset-totp': ['version', 'command'],\n 'revoke-sessions': ['version', 'command'],\n }\n const fields = allowed[row.command]\n if (\n !fields ||\n Object.keys(row).length !== fields.length ||\n Object.keys(row).some((key) => !fields.includes(key))\n )\n return null\n if (\n row.command === 'init' &&\n (typeof row.username !== 'string' || typeof row.password !== 'string')\n )\n return null\n if (row.command === 'reset-password' && typeof row.password !== 'string') return null\n return row as AdminRequest\n}\n\nfunction failure(error: unknown): AdminResponse {\n return {\n version: ADMIN_PROTOCOL_VERSION,\n ok: false,\n error:\n error instanceof PasswordValidationError\n ? 'invalid_input'\n : error instanceof AuthError\n ? error.code\n : 'service_unavailable',\n }\n}\n\n/** Single-request local protocol. The state lock must already be held before start(). */\nexport class AdminSocket {\n readonly path: string\n private server: Server | undefined\n private inode: bigint | undefined\n private readonly sockets = new Set<Socket>()\n private readonly operations = new Set<Promise<void>>()\n\n constructor(\n profileDir: string,\n private readonly auth: AuthService,\n private readonly ready: () => boolean,\n private readonly onUnavailable: () => void,\n ) {\n this.path = join(profileDir, STATE_DIR, 'admin.sock')\n }\n\n async start(): Promise<void> {\n try {\n const stale = await lstat(this.path, { bigint: true })\n if (\n !stale.isSocket() ||\n stale.uid !== BigInt(process.getuid?.() ?? -1) ||\n (stale.mode & 0o777n) !== 0o600n\n )\n throw new Error('auth-remote: unsafe admin socket path; manual review required')\n await unlink(this.path)\n } catch (error) {\n if (!errno(error, 'ENOENT')) throw error\n }\n const server = createServer((socket) => this.accept(socket))\n server.on('error', () => this.onUnavailable())\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(this.path, () => {\n server.off('error', reject)\n resolve()\n })\n })\n this.server = server\n await chmod(this.path, 0o600)\n const info = await lstat(this.path, { bigint: true })\n if (\n !info.isSocket() ||\n info.uid !== BigInt(process.getuid?.() ?? -1) ||\n (info.mode & 0o777n) !== 0o600n\n )\n throw new Error('auth-remote: unsafe admin socket permissions')\n this.inode = info.ino\n }\n\n private accept(socket: Socket): void {\n this.sockets.add(socket)\n socket.on('error', () => undefined)\n socket.once('close', () => this.sockets.delete(socket))\n socket.setTimeout(10_000, () => socket.destroy())\n let chunks: Buffer[] = []\n let bytes = 0\n let received = false\n socket.on('data', (chunk: Buffer) => {\n if (received) return\n bytes += chunk.length\n if (bytes > ADMIN_MAX_BYTES) {\n received = true\n socket.end(JSON.stringify({ version: 1, ok: false, error: 'request_too_large' }) + '\\n')\n return\n }\n chunks.push(chunk)\n const all = Buffer.concat(chunks)\n const newline = all.indexOf(10)\n if (newline < 0) return\n received = true\n socket.setTimeout(0)\n if (newline !== all.length - 1) {\n socket.end(JSON.stringify({ version: 1, ok: false, error: 'invalid_request' }) + '\\n')\n return\n }\n chunks = []\n let request: AdminRequest | null\n try {\n request = validRequest(JSON.parse(all.subarray(0, newline).toString('utf8')))\n } catch {\n request = null\n }\n if (!request) {\n socket.end(JSON.stringify({ version: 1, ok: false, error: 'invalid_request' }) + '\\n')\n return\n }\n const operation = this.respond(socket, request)\n this.operations.add(operation)\n void operation.finally(() => this.operations.delete(operation))\n })\n }\n\n private async respond(socket: Socket, request: AdminRequest): Promise<void> {\n let response: AdminResponse\n try {\n switch (request.command) {\n case 'status': {\n const status: AdminStatus = { ...this.auth.status(), online: true, ready: this.ready() }\n response = { version: 1, ok: true, result: status }\n break\n }\n case 'init':\n await this.auth.initialize(request.username, request.password)\n response = { version: 1, ok: true, result: { ok: true } }\n break\n case 'reset-password':\n await this.auth.resetPassword(request.password)\n response = { version: 1, ok: true, result: { ok: true } }\n break\n case 'reset-totp':\n await this.auth.resetTotp()\n response = { version: 1, ok: true, result: { ok: true } }\n break\n case 'revoke-sessions':\n await this.auth.revokeAll()\n response = { version: 1, ok: true, result: { ok: true } }\n }\n } catch (error) {\n response = failure(error)\n }\n if (!socket.destroyed) socket.end(`${JSON.stringify(response)}\\n`)\n }\n\n async dispose(): Promise<void> {\n const server = this.server\n this.server = undefined\n if (server) {\n const closed = new Promise<void>((resolve) => server.close(() => resolve()))\n for (const socket of this.sockets) socket.destroy()\n await Promise.allSettled(this.operations)\n await closed\n }\n if (this.inode !== undefined) {\n try {\n const current = await lstat(this.path, { bigint: true })\n if (current.isSocket() && current.ino === this.inode) await unlink(this.path)\n } catch (error) {\n if (!errno(error, 'ENOENT')) throw error\n }\n this.inode = undefined\n }\n }\n}\n", "export const ADMIN_PROTOCOL_VERSION = 1\nexport const ADMIN_MAX_BYTES = 16 * 1024\n\nexport type AdminRequest =\n | { version: 1; command: 'status' }\n | { version: 1; command: 'init'; username: string; password: string }\n | { version: 1; command: 'reset-password'; password: string }\n | { version: 1; command: 'reset-totp' }\n | { version: 1; command: 'revoke-sessions' }\n\nexport interface AdminStatus {\n initialized: boolean\n totpEnabled: boolean\n activeSessions: number\n online: boolean\n ready: boolean\n}\n\nexport type AdminResponse =\n | { version: 1; ok: true; result: AdminStatus | { ok: true } }\n | { version: 1; ok: false; error: string }\n", "export const AUTH_BASE = '/auth-remote'\nexport const AUTH_COOKIE = 'dsh_auth_remote'\n\nexport interface PublicStateResponse {\n initialized: boolean\n requireTotp: boolean\n profileName: string\n}\n\nexport interface MeResponse {\n username: string\n totpEnabled: boolean\n requireTotp: boolean\n expiresAt: number\n}\n\nexport interface AuthErrorResponse {\n error: string\n retryAfter?: number\n}\n\nexport type LoginResponse =\n | { kind: 'session'; expiresAt: number }\n | { kind: 'mfa'; challenge: string; expiresAt: number }\n | { kind: 'binding'; challenge: string; expiresAt: number }\n\nexport interface BindingResponse {\n backupCodes: string[]\n}\n", "import type { IncomingMessage } from 'node:http'\n\nexport function preservePublicOrigin(pathname: string, prefixes: readonly string[]): boolean {\n return prefixes.some(\n (prefix) => prefix === '/' || pathname === prefix || pathname.startsWith(`${prefix}/`),\n )\n}\n\n/** Remove only the official launch token on the root index entry. */\nexport function stripRootToken(req: IncomingMessage): void {\n if (!req.url) return\n const url = new URL(req.url, 'http://auth-remote.invalid')\n if (url.pathname !== '/' || !url.searchParams.has('token')) return\n url.searchParams.delete('token')\n req.url = url.pathname + url.search + url.hash\n}\n", "import type { IncomingMessage } from 'node:http'\nimport type { RequestOriginContext } from './origin-policy.js'\n\nconst contexts = new WeakMap<IncomingMessage, RequestOriginContext>()\n\nexport function setRequestContext(req: IncomingMessage, context: RequestOriginContext): void {\n if (contexts.has(req)) throw new Error('auth-remote: request context already set')\n contexts.set(req, context)\n}\n\nexport function requireRequestContext(req: IncomingMessage): RequestOriginContext {\n const context = contexts.get(req)\n if (!context) throw new Error('auth-remote: missing validated request context')\n return context\n}\n", "import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { readFileSync } from 'node:fs'\nimport type { GuardedWebServer } from '../adapters/dsh/webserver.js'\nimport { PasswordValidationError } from '../auth/password.js'\nimport { AuthError, AuthService } from '../auth/service.js'\nimport { requireRequestContext } from './request-context.js'\nimport {\n AUTH_BASE,\n AUTH_COOKIE,\n type AuthErrorResponse,\n type LoginResponse,\n type MeResponse,\n type PublicStateResponse,\n} from '../shared/auth-contract.js'\n\nexport type RoutePermission = 'public' | 'session' | 'logout' | null\n\nconst policies: Readonly<Record<string, RoutePermission>> = {\n [`GET ${AUTH_BASE}/state`]: 'public',\n [`GET ${AUTH_BASE}/login`]: 'public',\n [`GET ${AUTH_BASE}/login.js`]: 'public',\n [`GET ${AUTH_BASE}/login.css`]: 'public',\n [`POST ${AUTH_BASE}/login`]: 'public',\n [`POST ${AUTH_BASE}/mfa/verify`]: 'public',\n [`POST ${AUTH_BASE}/totp/start`]: 'public',\n [`POST ${AUTH_BASE}/totp/confirm`]: 'public',\n [`GET ${AUTH_BASE}/me`]: 'session',\n [`POST ${AUTH_BASE}/password`]: 'session',\n [`POST ${AUTH_BASE}/totp/disable`]: 'session',\n [`POST ${AUTH_BASE}/revoke-sessions`]: 'session',\n [`POST ${AUTH_BASE}/logout`]: 'logout',\n}\n\nexport function routePermission(method: string | undefined, pathname: string): RoutePermission {\n return policies[`${method ?? ''} ${pathname}`] ?? null\n}\n\nclass HttpFailure extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n ) {\n super(code)\n }\n}\n\nfunction stringField(body: Record<string, unknown>, field: string): string {\n const value = body[field]\n if (typeof value !== 'string') throw new HttpFailure(400, 'invalid_input')\n return value\n}\n\nfunction optionalStringField(body: Record<string, unknown>, field: string): string | undefined {\n const value = body[field]\n if (value === undefined) return undefined\n if (typeof value !== 'string') throw new HttpFailure(400, 'invalid_input')\n return value\n}\n\nasync function readJsonBody(req: IncomingMessage): Promise<Record<string, unknown>> {\n const declared = Number(req.headers['content-length'])\n if (Number.isFinite(declared) && declared > 16 * 1024)\n throw new HttpFailure(413, 'body_too_large')\n if (!/^application\\/json(?:\\s*;|$)/iu.test(String(req.headers['content-type'] ?? '')))\n throw new HttpFailure(415, 'unsupported_media_type')\n return new Promise((resolve, reject) => {\n let done = false\n let bytes = 0\n const chunks: Buffer[] = []\n const cleanup = () => {\n clearTimeout(timer)\n req.off('data', onData)\n req.off('end', onEnd)\n req.off('error', onError)\n req.off('aborted', onAbort)\n }\n const fail = (error: Error) => {\n if (done) return\n done = true\n req.pause()\n cleanup()\n reject(error)\n }\n const onData = (chunk: Buffer) => {\n bytes += chunk.length\n if (bytes > 16 * 1024) fail(new HttpFailure(413, 'body_too_large'))\n else chunks.push(chunk)\n }\n const onEnd = () => {\n if (done) return\n done = true\n cleanup()\n try {\n const body: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))\n if (typeof body !== 'object' || body === null || Array.isArray(body))\n throw new HttpFailure(400, 'invalid_input')\n resolve(body as Record<string, unknown>)\n } catch {\n reject(new HttpFailure(400, 'invalid_json'))\n }\n }\n const onError = (error: Error) => fail(error)\n const onAbort = () => fail(new HttpFailure(408, 'request_aborted'))\n const timer = setTimeout(() => fail(new HttpFailure(408, 'request_timeout')), 10_000)\n req.on('data', onData)\n req.once('end', onEnd)\n req.once('error', onError)\n req.once('aborted', onAbort)\n })\n}\n\nfunction sendJson(\n res: ServerResponse,\n status: number,\n body: unknown,\n headers: Record<string, string> = {},\n): void {\n res.writeHead(status, {\n 'cache-control': 'no-store',\n 'content-type': 'application/json; charset=utf-8',\n ...headers,\n })\n res.end(JSON.stringify(body))\n}\n\nfunction cookieToken(req: IncomingMessage): string | null {\n const header = req.headers.cookie\n if (typeof header !== 'string') return null\n const values = header\n .split(';')\n .map((part) => part.trim())\n .filter((part) => part.startsWith(`${AUTH_COOKIE}=`))\n if (values.length !== 1) return null\n return values[0]!.slice(AUTH_COOKIE.length + 1)\n}\n\nexport function currentSessionToken(req: IncomingMessage): string | null {\n return cookieToken(req)\n}\n\nfunction cookieHeader(token: string, expiresAt: number, secure: boolean): string {\n const maxAge = Math.max(0, Math.floor((expiresAt - Date.now()) / 1000))\n return `${AUTH_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? '; Secure' : ''}`\n}\n\nfunction clearCookieHeader(secure: boolean): string {\n return `${AUTH_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure ? '; Secure' : ''}`\n}\n\nfunction cookieResponse(mayWriteCookie: boolean, value: string): Record<string, string> {\n if (!mayWriteCookie) throw new HttpFailure(403, 'invalid_origin')\n return { 'set-cookie': value }\n}\n\nfunction loginAsset(name: 'login.js' | 'login.css'): string {\n const source = import.meta.url.endsWith('/src/http/routes.ts')\n const base = new URL(source ? '../../dist/' : './', import.meta.url)\n return readFileSync(new URL(name, base), 'utf8')\n}\n\nfunction errorStatus(error: unknown): {\n status: number\n body: AuthErrorResponse\n retryAfter?: string\n} {\n if (error instanceof HttpFailure) return { status: error.status, body: { error: error.code } }\n if (error instanceof PasswordValidationError)\n return { status: 400, body: { error: 'invalid_input' } }\n if (error instanceof AuthError) {\n const retryAfter = error.retryAfter ?? (error.code === 'busy' ? 1 : undefined)\n const status: Record<string, number> = {\n invalid_input: 400,\n uninitialized: 409,\n already_initialized: 409,\n invalid_credentials: 401,\n invalid_factor: 401,\n invalid_challenge: 400,\n challenge_expired: 410,\n unauthorized: 401,\n rate_limited: 429,\n busy: 429,\n conflict: 409,\n totp_required: 403,\n }\n return {\n status: status[error.code] ?? 500,\n body: { error: error.code, ...(retryAfter ? { retryAfter } : {}) },\n ...(retryAfter ? { retryAfter: String(retryAfter) } : {}),\n }\n }\n return { status: 503, body: { error: 'service_unavailable' } }\n}\n\n/** Explicit path/method registry; no prefix grants anonymous access. */\nexport class AuthRoutes {\n constructor(\n private readonly auth: AuthService,\n private readonly profileName: string,\n ) {}\n\n install(server: GuardedWebServer): void {\n const paths = new Set(Object.keys(policies).map((row) => row.slice(row.indexOf(' ') + 1)))\n for (const path of paths)\n server.register({\n kind: 'exact',\n path,\n handler: (req, res) => this.handle(req, res, path),\n })\n }\n\n private async handle(req: IncomingMessage, res: ServerResponse, path: string): Promise<void> {\n const route = `${req.method ?? ''} ${path}`\n try {\n const context = requireRequestContext(req)\n const secure = context.protocol === 'https:'\n switch (route) {\n case `GET ${AUTH_BASE}/state`: {\n const status = this.auth.status()\n const body: PublicStateResponse = {\n initialized: status.initialized,\n requireTotp: this.auth.policySnapshot().requireTotp,\n profileName: this.profileName,\n }\n sendJson(res, 200, body)\n return\n }\n case `GET ${AUTH_BASE}/login`: {\n res.writeHead(200, {\n 'cache-control': 'no-store',\n 'content-type': 'text/html; charset=utf-8',\n 'content-security-policy':\n \"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'\",\n 'x-content-type-options': 'nosniff',\n 'referrer-policy': 'no-referrer',\n })\n res.end(\n '<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>Sign in to DSH</title><link rel=\"stylesheet\" href=\"/auth-remote/login.css\"><script defer src=\"/auth-remote/login.js\"></script></head><body><main id=\"login-root\" aria-live=\"polite\">Checking sign-in status\u2026</main></body></html>',\n )\n return\n }\n case `GET ${AUTH_BASE}/login.js`:\n case `GET ${AUTH_BASE}/login.css`: {\n const asset = loginAsset(route.endsWith('.css') ? 'login.css' : 'login.js')\n res.writeHead(200, {\n 'cache-control': 'no-store',\n 'content-type': route.endsWith('.css')\n ? 'text/css; charset=utf-8'\n : 'text/javascript; charset=utf-8',\n 'x-content-type-options': 'nosniff',\n })\n res.end(asset)\n return\n }\n case `POST ${AUTH_BASE}/login`: {\n const body = await readJsonBody(req)\n const result = await this.auth.login(\n stringField(body, 'username'),\n stringField(body, 'password'),\n )\n if (result.kind === 'session') {\n const response: LoginResponse = { kind: 'session', expiresAt: result.expiresAt }\n sendJson(res, 200, response, {\n ...cookieResponse(\n context.mayWriteCookie,\n cookieHeader(result.token, result.expiresAt, secure),\n ),\n })\n } else if (result.kind === 'binding') {\n const response: LoginResponse = {\n kind: 'binding',\n challenge: result.challenge,\n expiresAt: result.expiresAt,\n }\n sendJson(res, 200, response)\n } else sendJson(res, 200, result satisfies LoginResponse)\n return\n }\n case `POST ${AUTH_BASE}/mfa/verify`: {\n const body = await readJsonBody(req)\n const result = await this.auth.verifyMfa(\n stringField(body, 'challenge'),\n stringField(body, 'code'),\n )\n sendJson(\n res,\n 200,\n { kind: 'session', expiresAt: result.expiresAt } satisfies LoginResponse,\n {\n ...cookieResponse(\n context.mayWriteCookie,\n cookieHeader(result.token, result.expiresAt, secure),\n ),\n },\n )\n return\n }\n case `POST ${AUTH_BASE}/totp/start`: {\n const body = await readJsonBody(req)\n if (typeof body.challenge === 'string') {\n sendJson(res, 200, this.auth.bindingDetails(body.challenge))\n } else {\n const token = cookieToken(req)\n if (!token) throw new AuthError('unauthorized')\n const result = await this.auth.startBinding(\n token,\n stringField(body, 'password'),\n optionalStringField(body, 'currentCode'),\n )\n sendJson(res, 200, result)\n }\n return\n }\n case `POST ${AUTH_BASE}/totp/confirm`: {\n const body = await readJsonBody(req)\n sendJson(\n res,\n 200,\n await this.auth.confirmBinding(\n stringField(body, 'challenge'),\n stringField(body, 'code'),\n ),\n cookieResponse(context.mayWriteCookie, clearCookieHeader(secure)),\n )\n return\n }\n case `GET ${AUTH_BASE}/me`: {\n const token = cookieToken(req)\n if (!token) throw new AuthError('unauthorized')\n const me = this.auth.me(token)\n const body: MeResponse = { ...me, requireTotp: this.auth.policySnapshot().requireTotp }\n sendJson(res, 200, body)\n return\n }\n case `POST ${AUTH_BASE}/password`: {\n const body = await readJsonBody(req)\n const token = cookieToken(req)\n if (!token) throw new AuthError('unauthorized')\n await this.auth.changePassword(\n token,\n stringField(body, 'currentPassword'),\n optionalStringField(body, 'currentCode'),\n stringField(body, 'newPassword'),\n )\n sendJson(\n res,\n 200,\n { ok: true },\n cookieResponse(context.mayWriteCookie, clearCookieHeader(secure)),\n )\n return\n }\n case `POST ${AUTH_BASE}/totp/disable`: {\n const body = await readJsonBody(req)\n const token = cookieToken(req)\n if (!token) throw new AuthError('unauthorized')\n await this.auth.disableTotp(\n token,\n stringField(body, 'password'),\n stringField(body, 'currentCode'),\n )\n sendJson(\n res,\n 200,\n { ok: true },\n cookieResponse(context.mayWriteCookie, clearCookieHeader(secure)),\n )\n return\n }\n case `POST ${AUTH_BASE}/revoke-sessions`: {\n const body = await readJsonBody(req)\n const token = cookieToken(req)\n if (!token) throw new AuthError('unauthorized')\n await this.auth.revokeWithCredentials(\n token,\n stringField(body, 'password'),\n optionalStringField(body, 'currentCode'),\n )\n sendJson(\n res,\n 200,\n { ok: true },\n cookieResponse(context.mayWriteCookie, clearCookieHeader(secure)),\n )\n return\n }\n case `POST ${AUTH_BASE}/logout`:\n if (req.headers['transfer-encoding'] || Number(req.headers['content-length'] ?? 0) > 0)\n await readJsonBody(req)\n await this.auth.logout(cookieToken(req) ?? '')\n sendJson(\n res,\n 200,\n { ok: true },\n cookieResponse(context.mayWriteCookie, clearCookieHeader(secure)),\n )\n return\n default:\n sendJson(res, 405, { error: 'method_not_allowed' })\n }\n } catch (error) {\n if (res.headersSent) {\n res.destroy()\n return\n }\n const failure = errorStatus(error)\n const terminateBody =\n failure.status === 413 || failure.status === 408 || failure.status === 415\n sendJson(res, failure.status, failure.body, {\n ...(failure.retryAfter ? { 'retry-after': failure.retryAfter } : {}),\n ...(terminateBody ? { connection: 'close' } : {}),\n })\n if (terminateBody)\n res.once('finish', () => {\n req.resume()\n req.socket.end()\n })\n }\n }\n}\n", "import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { DshReadiness } from '../adapters/dsh/readiness.js'\nimport type { WebGate } from '../adapters/dsh/webserver.js'\nimport { AuthService } from '../auth/service.js'\nimport { sessionHash } from '../auth/sessions.js'\nimport type { ResolvedAuthConfig } from '../config.js'\nimport { AUTH_BASE, AUTH_COOKIE } from '../shared/auth-contract.js'\nimport { AuthStateStore } from '../storage/store.js'\nimport { AuthConnections } from './connections.js'\nimport { preservePublicOrigin, stripRootToken } from './origin.js'\nimport { evaluateRequestOrigin, type RequestOriginContext } from './origin-policy.js'\nimport { setRequestContext } from './request-context.js'\nimport { currentSessionToken, routePermission } from './routes.js'\n\nfunction rejectHttp(res: ServerResponse, status: number, code: string): void {\n res.writeHead(status, {\n 'cache-control': 'no-store',\n 'content-type': 'application/json; charset=utf-8',\n })\n res.end(JSON.stringify({ error: code }))\n}\n\nfunction rejectUpgrade(socket: Duplex, status: number, reason: string): void {\n socket.end(`HTTP/1.1 ${status} ${reason}\\r\\nConnection: close\\r\\n\\r\\n`)\n}\n\nfunction downstreamCookie(original: string | undefined, native: string): string {\n const name = native.slice(0, native.indexOf('='))\n const unrelated = (original ?? '')\n .split(';')\n .map((part) => part.trim())\n .filter((part) => {\n if (!part) return false\n const split = part.indexOf('=')\n const key = (split < 0 ? part : part.slice(0, split)).trim()\n return key !== name && key !== AUTH_COOKIE\n })\n return [...unrelated, native].join('; ')\n}\n\n/** Validates the public request before rewriting only the admitted business carrier. */\nexport class AuthGate implements WebGate {\n constructor(\n private readonly serverPort: () => number,\n private readonly config: ResolvedAuthConfig,\n private readonly store: AuthStateStore,\n private readonly auth: AuthService,\n private readonly readiness: DshReadiness,\n private readonly connections: AuthConnections,\n ) {}\n\n ready(): boolean {\n return this.store.healthy() && this.readiness.ready()\n }\n\n async http(req: IncomingMessage, res: ServerResponse, next: () => Promise<void>): Promise<void> {\n const raw = evaluateRequestOrigin(this.config.originPolicy, {\n rawHeaders: req.rawHeaders,\n method: req.method,\n target: req.url,\n })\n if (!raw) return rejectHttp(res, 403, 'invalid_origin')\n if (!this.ready()) return rejectHttp(res, 503, 'service_unavailable')\n setRequestContext(req, raw)\n const permission = routePermission(req.method, raw.pathname)\n if (permission === 'public' || permission === 'logout') return next()\n const token = currentSessionToken(req)\n const session = token ? this.auth.session(token) : null\n if (!session) {\n const accept = String(req.headers.accept ?? '')\n const navigation =\n req.method === 'GET' &&\n !raw.pathname.startsWith('/api') &&\n !raw.pathname.startsWith(AUTH_BASE) &&\n (accept.includes('text/html') || req.headers['sec-fetch-mode'] === 'navigate')\n if (navigation) {\n const location = new URL(`${AUTH_BASE}/login`, raw.origin)\n location.searchParams.set('return', raw.returnPath)\n res.writeHead(302, {\n 'cache-control': 'no-store',\n location: location.pathname + location.search,\n })\n res.end()\n return\n }\n return rejectHttp(res, 401, 'unauthorized')\n }\n if (permission === 'session') return next()\n try {\n this.bridge(req, raw)\n } catch {\n this.readiness.detach()\n return rejectHttp(res, 503, 'service_unavailable')\n }\n stripRootToken(req)\n this.connections.trackResponse(\n // The token has already been checked by AuthService.\n this.hash(token!),\n session,\n res,\n )\n await next()\n }\n\n async upgrade(\n req: IncomingMessage,\n socket: Duplex,\n _head: Buffer,\n next: () => Promise<void>,\n ): Promise<void> {\n const raw = evaluateRequestOrigin(this.config.originPolicy, {\n rawHeaders: req.rawHeaders,\n method: req.method,\n target: req.url,\n upgrade: true,\n })\n if (!raw) return rejectUpgrade(socket, 403, 'Forbidden')\n if (!this.ready()) return rejectUpgrade(socket, 503, 'Service Unavailable')\n setRequestContext(req, raw)\n const token = currentSessionToken(req)\n const session = token ? this.auth.session(token) : null\n if (!session) return rejectUpgrade(socket, 401, 'Unauthorized')\n try {\n this.bridge(req, raw)\n } catch {\n this.readiness.detach()\n return rejectUpgrade(socket, 503, 'Service Unavailable')\n }\n this.connections.trackSocket(this.hash(token!), session, socket)\n await next()\n }\n\n private hash(token: string): string {\n // Kept in one place so a raw bearer token is never retained by connection tracking.\n return sessionHash(token)\n }\n\n private bridge(req: IncomingMessage, context: RequestOriginContext): void {\n const preserve = preservePublicOrigin(context.pathname, this.config.preserveOriginPaths)\n const authority = preserve\n ? context.downstreamAuthority\n : `127.0.0.1:${String(this.serverPort())}`\n const origin = preserve ? context.origin : `http://${authority}`\n const native = this.readiness.nativeCookie(authority, origin)\n req.headers.cookie = downstreamCookie(req.headers.cookie, native)\n req.headers.host = auth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M,MAAM;AAClB,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,IAAI,UAA0B;AAC5B,QAAI,CAAC,KAAK,WAAY,OAAM,IAAI,MAAM,6CAA6C;AACnF,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,iBAA8B;AAChC,QAAI,CAAC,KAAK,YAAa,OAAM,IAAI,MAAM,oDAAoD;AAC3F,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,IAAI,yBAA4C;AAC9C,QAAI,KAAK,SAAS,oBAAoB,WAAW,EAAG,QAAO,CAAC;AAC5D,WAAO,KAAK,SAAS,aAAa,kBAAkB,IAAI,CAAC,UAAU,MAAM,IAAI;AAAA,EAC/E;AACF;AAEA,IAAO,cAAQ;",
6
+ "names": ["WebServer", "name", "WebServer", "randomBytes", "randomUUID", "constants", "lstat", "open", "readFile", "unlink", "join", "value", "errno", "join", "lstat", "readFile", "randomUUID", "open", "constants", "unlink", "record", "randomBytes", "createHash", "randomBytes", "timingSafeEqual", "randomBytes", "record", "lstat", "unlink", "join", "errno", "join", "lstat", "unlink", "readFileSync", "name", "readFileSync", "failure", "name"]
7
+ }