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
package/dist/index.js ADDED
@@ -0,0 +1,2473 @@
1
+ // src/index.ts
2
+ import { Service } from "@deepseek-ai/cordis";
3
+ import { basename } from "node:path";
4
+
5
+ // src/adapters/dsh/compatibility.ts
6
+ import { readFileSync, realpathSync } from "node:fs";
7
+ import { createRequire } from "node:module";
8
+ import WebServer from "@deepseek-ai/dsh-host-webserver";
9
+ import semver from "semver";
10
+ var WEB_SERVER_PACKAGE = "@deepseek-ai/dsh-host-webserver";
11
+ var CONNECTION_PACKAGE = "@deepseek-ai/dsh-client-connection";
12
+ var SUPPORTED_DSH_RANGE = ">=0.1.7-rc.1 <0.2.0-0";
13
+ function packageManifest(packageName, anchor) {
14
+ const path = realpathSync(createRequire(anchor).resolve(`${packageName}/package.json`));
15
+ const manifest = JSON.parse(readFileSync(path, "utf8"));
16
+ if (manifest.name !== packageName || !semver.satisfies(manifest.version, SUPPORTED_DSH_RANGE, { includePrerelease: true })) {
17
+ throw new Error(`auth-remote: unsupported ${packageName} version ${manifest.version}`);
18
+ }
19
+ return { path, manifest };
20
+ }
21
+ function assertWebServerCompatibility(ctx) {
22
+ const own = packageManifest(WEB_SERVER_PACKAGE, import.meta.url);
23
+ const profile = ctx.get("profileContext");
24
+ if (profile?.installAnchor !== void 0) {
25
+ const host = packageManifest(WEB_SERVER_PACKAGE, profile.installAnchor);
26
+ if (own.path !== host.path) {
27
+ throw new Error(
28
+ `auth-remote: duplicate WebServer package copies: ${own.path} and ${host.path}`
29
+ );
30
+ }
31
+ }
32
+ for (const method of [
33
+ "register",
34
+ "registerUpgrade",
35
+ "registerFallback",
36
+ "renderIndex"
37
+ ]) {
38
+ if (typeof WebServer.prototype[method] !== "function") {
39
+ throw new Error(`auth-remote: WebServer lacks ${method}`);
40
+ }
41
+ }
42
+ return own.manifest.version;
43
+ }
44
+ function assertConnectionCompatibility(connection, anchor) {
45
+ const own = packageManifest(CONNECTION_PACKAGE, import.meta.url);
46
+ if (anchor !== void 0) {
47
+ const host = packageManifest(CONNECTION_PACKAGE, anchor);
48
+ if (own.path !== host.path) {
49
+ throw new Error(
50
+ `auth-remote: duplicate Connection package copies: ${own.path} and ${host.path}`
51
+ );
52
+ }
53
+ }
54
+ for (const method of ["authenticatedUrl", "authorizeIndex", "requestRejection"]) {
55
+ if (typeof connection[method] !== "function") {
56
+ throw new Error(`auth-remote: Connection lacks ${method}`);
57
+ }
58
+ }
59
+ return own.manifest.version;
60
+ }
61
+
62
+ // src/adapters/dsh/browser-capability.ts
63
+ function installAuthenticatedHostCapability(ctx) {
64
+ ctx.on("webserver/index-inject", (table) => {
65
+ table.push({ kind: "global", name: "__DSH_TRANSPORT__", value: { ownsHost: true } });
66
+ });
67
+ }
68
+
69
+ // src/adapters/dsh/browser-auth.ts
70
+ var NativeBrowserAuth = class {
71
+ cookies = /* @__PURE__ */ new WeakMap();
72
+ cookieFor(connection, authority, origin, now = Date.now()) {
73
+ let byAuthority = this.cookies.get(connection);
74
+ if (byAuthority === void 0) {
75
+ byAuthority = /* @__PURE__ */ new Map();
76
+ this.cookies.set(connection, byAuthority);
77
+ }
78
+ let cookie = byAuthority.get(authority);
79
+ if (cookie === void 0 || now >= cookie.expiresAt - 6e4) {
80
+ cookie = exchange(connection, authority, now);
81
+ byAuthority.set(authority, cookie);
82
+ }
83
+ const rejection = connection.requestRejection({
84
+ headers: { host: authority, origin, cookie: cookie.pair }
85
+ });
86
+ if (rejection !== void 0) {
87
+ byAuthority.delete(authority);
88
+ throw new Error(
89
+ `auth-remote: native Connection rejected ${authority} with ${String(rejection)}`
90
+ );
91
+ }
92
+ return cookie.pair;
93
+ }
94
+ clear(connection) {
95
+ this.cookies.delete(connection);
96
+ }
97
+ };
98
+ function exchange(connection, authority, now) {
99
+ const tokenUrl = new URL(connection.authenticatedUrl(`http://${authority}/`));
100
+ const normalizedAuthority = new URL(`http://${authority}/`).host;
101
+ if (tokenUrl.host !== normalizedAuthority || tokenUrl.pathname !== "/" || tokenUrl.searchParams.getAll("token").length !== 1) {
102
+ throw new Error("auth-remote: native Connection returned an invalid token URL");
103
+ }
104
+ let status;
105
+ let responseHeaders;
106
+ let ended = false;
107
+ const admitted = connection.authorizeIndex(
108
+ { method: "GET", url: tokenUrl.pathname + tokenUrl.search, headers: { host: authority } },
109
+ {
110
+ writeHead(code, headers) {
111
+ status = code;
112
+ responseHeaders = headers;
113
+ },
114
+ end() {
115
+ ended = true;
116
+ }
117
+ }
118
+ );
119
+ const setCookie = responseHeaders?.["set-cookie"];
120
+ if (admitted || !ended || status !== 303 || setCookie === void 0 || responseHeaders?.location !== "./") {
121
+ throw new Error("auth-remote: native Connection token exchange failed");
122
+ }
123
+ const [pair, ...attributes] = setCookie.split(";").map((part) => part.trim());
124
+ if (pair === void 0 || !/^[^=;\s]+=([^;\s]*)$/u.test(pair)) {
125
+ throw new Error("auth-remote: native Connection returned an invalid Cookie");
126
+ }
127
+ const maxAge = attributes.find((attribute) => /^max-age=/iu.test(attribute))?.slice("max-age=".length);
128
+ const seconds = maxAge === void 0 ? NaN : Number(maxAge);
129
+ const expiresAt = now + seconds * 1e3;
130
+ if (!Number.isSafeInteger(seconds) || seconds <= 0 || !Number.isSafeInteger(expiresAt)) {
131
+ throw new Error("auth-remote: native Connection returned an invalid Cookie lifetime");
132
+ }
133
+ return { pair, expiresAt };
134
+ }
135
+
136
+ // src/adapters/dsh/readiness.ts
137
+ var DshReadiness = class {
138
+ constructor(server, config, onUnavailable = () => {
139
+ }) {
140
+ this.server = server;
141
+ this.config = config;
142
+ this.onUnavailable = onUnavailable;
143
+ }
144
+ server;
145
+ config;
146
+ onUnavailable;
147
+ native = new NativeBrowserAuth();
148
+ connection;
149
+ isReady = false;
150
+ ready() {
151
+ return this.isReady;
152
+ }
153
+ currentConnection() {
154
+ return this.connection;
155
+ }
156
+ attach(connection, profileAnchor) {
157
+ this.detach();
158
+ assertConnectionCompatibility(connection, profileAnchor);
159
+ const localAuthority = `127.0.0.1:${String(this.server.port)}`;
160
+ try {
161
+ this.native.cookieFor(connection, localAuthority, `http://${localAuthority}`);
162
+ if (this.config.preserveOriginPaths.length > 0)
163
+ for (const entry of this.config.originPolicy.registeredOrigins)
164
+ this.native.cookieFor(connection, entry.host, entry.origin);
165
+ } catch (error) {
166
+ this.native.clear(connection);
167
+ throw error;
168
+ }
169
+ this.connection = connection;
170
+ this.isReady = true;
171
+ }
172
+ nativeCookie(authority, origin) {
173
+ if (!this.isReady || this.connection === void 0)
174
+ throw new Error("auth-remote: Connection is not ready");
175
+ return this.native.cookieFor(this.connection, authority, origin);
176
+ }
177
+ detach(connection) {
178
+ if (connection !== void 0 && this.connection !== connection) return;
179
+ const old = this.connection;
180
+ this.connection = void 0;
181
+ if (this.isReady) {
182
+ this.isReady = false;
183
+ this.onUnavailable();
184
+ }
185
+ if (old !== void 0) this.native.clear(old);
186
+ }
187
+ };
188
+ function watchConnection(ctx, readiness, onReady = () => {
189
+ }) {
190
+ ctx.inject(["connection"], (connectionCtx) => {
191
+ const connection = connectionCtx.get("connection");
192
+ const profile = ctx.get("profileContext");
193
+ connectionCtx.effect(() => {
194
+ readiness.attach(connection, profile?.installAnchor);
195
+ onReady();
196
+ return () => {
197
+ readiness.detach(connection);
198
+ };
199
+ }, "auth-remote: native Connection readiness");
200
+ });
201
+ }
202
+
203
+ // src/adapters/dsh/startup-urls.ts
204
+ function startupLines(profile, config, port) {
205
+ const lines = [`dsh ${profile} start at`, ` http://${config.host}:${String(port)}`];
206
+ if (config.allowedOrigins.length > 0) {
207
+ lines.push("", "public access at");
208
+ for (const origin of config.allowedOrigins) lines.push(` ${origin}`);
209
+ }
210
+ return lines;
211
+ }
212
+
213
+ // src/adapters/dsh/webserver.ts
214
+ import WebServer2 from "@deepseek-ai/dsh-host-webserver";
215
+
216
+ // src/http/origin-policy.ts
217
+ function defaultPort(protocol) {
218
+ return protocol === "https:" ? 443 : 80;
219
+ }
220
+ function parseAuthority(value) {
221
+ const ipv6 = /^(\[[0-9a-fA-F:.]+\])(?::([0-9]+))?$/u.exec(value);
222
+ const plain = /^([A-Za-z0-9.-]+)(?::([0-9]+))?$/u.exec(value);
223
+ const hostname = (ipv6?.[1] ?? plain?.[1])?.toLowerCase();
224
+ const portText = ipv6?.[2] ?? plain?.[2];
225
+ if (!hostname) return null;
226
+ if (portText !== void 0 && (!/^[1-9][0-9]*$/u.test(portText) || Number(portText) > 65535))
227
+ return null;
228
+ let parsed;
229
+ try {
230
+ parsed = new URL(`http://${hostname}`);
231
+ } catch {
232
+ return null;
233
+ }
234
+ if (parsed.hostname !== hostname || parsed.username || parsed.password) return null;
235
+ let kind;
236
+ if (ipv6) {
237
+ kind = "ipv6";
238
+ } else if (/^(?:[0-9]+\.){3}[0-9]+$/u.test(hostname)) {
239
+ const octets = hostname.split(".");
240
+ if (octets.some((octet) => Number(octet) > 255 || String(Number(octet)) !== octet)) return null;
241
+ kind = "ipv4";
242
+ } else {
243
+ if (hostname.length > 253 || hostname.endsWith(".")) return null;
244
+ if (hostname.split(".").some((label) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(label)))
245
+ return null;
246
+ kind = "name";
247
+ }
248
+ const explicitPort = portText === void 0 ? void 0 : Number(portText);
249
+ return {
250
+ host: `${hostname}${explicitPort === void 0 ? "" : `:${explicitPort}`}`,
251
+ hostname,
252
+ explicitPort,
253
+ kind
254
+ };
255
+ }
256
+ function parseOrigin(value) {
257
+ const match = /^(https?):\/\/([^/?#]+)$/iu.exec(value);
258
+ if (!match?.[1] || !match[2]) return null;
259
+ const authority = parseAuthority(match[2]);
260
+ if (!authority) return null;
261
+ const protocol = `${match[1].toLowerCase()}:`;
262
+ let url;
263
+ try {
264
+ url = new URL(`${protocol}//${authority.host}`);
265
+ } catch {
266
+ return null;
267
+ }
268
+ if (url.hostname !== authority.hostname) return null;
269
+ const port = authority.explicitPort ?? defaultPort(protocol);
270
+ const authorities = [url.host];
271
+ if (url.port === "") authorities.push(`${url.hostname}:${defaultPort(protocol)}`);
272
+ return Object.freeze({
273
+ origin: url.origin,
274
+ protocol,
275
+ host: url.host,
276
+ hostname: url.hostname,
277
+ port,
278
+ authorities: Object.freeze(authorities)
279
+ });
280
+ }
281
+ function createOriginPolicy(origins) {
282
+ if (!Array.isArray(origins)) throw new Error("auth-remote: allowedOrigins must be an array");
283
+ const indexed = /* @__PURE__ */ new Map();
284
+ const registeredOrigins = [];
285
+ const seen = /* @__PURE__ */ new Set();
286
+ for (const value of origins) {
287
+ const entry = typeof value === "string" ? parseOrigin(value) : null;
288
+ if (!entry) {
289
+ throw new Error(`auth-remote: invalid allowedOrigins entry ${JSON.stringify(value)}`);
290
+ }
291
+ if (seen.has(entry.origin)) {
292
+ throw new Error(`auth-remote: duplicate allowedOrigins entry ${JSON.stringify(value)}`);
293
+ }
294
+ seen.add(entry.origin);
295
+ for (const alias of entry.authorities) {
296
+ const previous = indexed.get(alias);
297
+ if (previous) {
298
+ throw new Error(
299
+ `auth-remote: ambiguous allowedOrigins authority ${alias} (${previous.protocol} and ${entry.protocol})`
300
+ );
301
+ }
302
+ indexed.set(alias, entry);
303
+ }
304
+ registeredOrigins.push(entry);
305
+ }
306
+ return Object.freeze({
307
+ registeredOrigins: Object.freeze(registeredOrigins),
308
+ matchAuthority(host) {
309
+ const authority = parseAuthority(host);
310
+ return authority ? indexed.get(authority.host) : void 0;
311
+ }
312
+ });
313
+ }
314
+ function headerValues(rawHeaders, name2) {
315
+ if (rawHeaders.length % 2 !== 0) return null;
316
+ const values = [];
317
+ for (let i = 0; i < rawHeaders.length; i += 2) {
318
+ const key = rawHeaders[i];
319
+ const value = rawHeaders[i + 1];
320
+ if (typeof key !== "string" || typeof value !== "string") return null;
321
+ if (key.toLowerCase() === name2) values.push(value);
322
+ }
323
+ return values;
324
+ }
325
+ function parseTarget(target) {
326
+ if (!target.startsWith("/") || target.startsWith("//") || /[\\\u0000-\u001f\u007f\s#]/u.test(target) || /%(?![0-9a-fA-F]{2})/u.test(target))
327
+ return null;
328
+ const rawPath = target.split("?", 1)[0];
329
+ for (const segment of rawPath.split("/")) {
330
+ let decoded;
331
+ try {
332
+ decoded = decodeURIComponent(segment);
333
+ } catch {
334
+ return null;
335
+ }
336
+ if (decoded === "." || decoded === ".." || /[/\\\u0000-\u001f\u007f]/u.test(decoded))
337
+ return null;
338
+ }
339
+ let parsed;
340
+ try {
341
+ parsed = new URL(target, "http://auth-remote.invalid");
342
+ } catch {
343
+ return null;
344
+ }
345
+ if (parsed.origin !== "http://auth-remote.invalid") return null;
346
+ if (parsed.pathname === "/") parsed.searchParams.delete("token");
347
+ return { pathname: parsed.pathname, returnPath: parsed.pathname + parsed.search };
348
+ }
349
+ function isImplicitLoopback(authority) {
350
+ if (authority.hostname === "localhost" || authority.hostname === "[::1]") return true;
351
+ if (authority.kind !== "ipv4") return false;
352
+ return authority.hostname.startsWith("127.");
353
+ }
354
+ function evaluateRequestOrigin(policy, request) {
355
+ const hosts = headerValues(request.rawHeaders, "host");
356
+ const origins = headerValues(request.rawHeaders, "origin");
357
+ const fetchSites = headerValues(request.rawHeaders, "sec-fetch-site");
358
+ if (!hosts || !origins || !fetchSites || hosts.length !== 1 || origins.length > 1 || fetchSites.length > 1)
359
+ return null;
360
+ const authority = parseAuthority(hosts[0]);
361
+ const target = request.target ? parseTarget(request.target) : null;
362
+ const method = request.method;
363
+ if (!authority || !target || !method || !/^[A-Z!#$%&'*+.^_`|~-]+$/u.test(method)) return null;
364
+ const needsOrigin = request.upgrade === true || method !== "GET";
365
+ if (needsOrigin && origins.length !== 1) return null;
366
+ const site = fetchSites[0]?.toLowerCase();
367
+ if (site !== void 0 && (needsOrigin ? site !== "same-origin" : !["same-origin", "none"].includes(site)))
368
+ return null;
369
+ const suppliedOrigin = origins.length === 1 ? parseOrigin(origins[0]) : null;
370
+ if (origins.length === 1 && !suppliedOrigin) return null;
371
+ const registered = policy.matchAuthority(authority.host);
372
+ let origin;
373
+ let protocol;
374
+ if (registered) {
375
+ if (suppliedOrigin && suppliedOrigin.origin !== registered.origin) return null;
376
+ origin = registered.origin;
377
+ protocol = registered.protocol;
378
+ } else {
379
+ if (!isImplicitLoopback(authority)) return null;
380
+ protocol = suppliedOrigin?.protocol ?? "http:";
381
+ const hostPort = authority.explicitPort ?? defaultPort(protocol);
382
+ if (suppliedOrigin && (suppliedOrigin.hostname !== authority.hostname || suppliedOrigin.port !== hostPort))
383
+ return null;
384
+ origin = suppliedOrigin?.origin ?? new URL(`${protocol}//${authority.host}`).origin;
385
+ }
386
+ return Object.freeze({
387
+ origin,
388
+ protocol,
389
+ authority: authority.host,
390
+ downstreamAuthority: new URL(origin).host,
391
+ hostname: authority.hostname,
392
+ pathname: target.pathname,
393
+ returnPath: target.returnPath,
394
+ registered: registered !== void 0,
395
+ mayWriteCookie: registered !== void 0 || suppliedOrigin !== null
396
+ });
397
+ }
398
+
399
+ // src/adapters/dsh/webserver.ts
400
+ var READY_PATH = "/auth-remote/ready";
401
+ var READY_PROTOCOL_VERSION = 1;
402
+ var DenyGate = class {
403
+ ready() {
404
+ return false;
405
+ }
406
+ async http(_req, res) {
407
+ res.writeHead(503, { "cache-control": "no-store" });
408
+ res.end();
409
+ }
410
+ async upgrade(_req, socket) {
411
+ socket.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n");
412
+ }
413
+ };
414
+ var SwitchGate = class {
415
+ delegate = new DenyGate();
416
+ set(delegate) {
417
+ this.delegate = delegate;
418
+ }
419
+ ready() {
420
+ return this.delegate.ready();
421
+ }
422
+ http(req, res, next) {
423
+ return this.delegate.http(req, res, next);
424
+ }
425
+ upgrade(req, socket, head, next) {
426
+ return this.delegate.upgrade(req, socket, head, next);
427
+ }
428
+ };
429
+ var GuardedWebServer = class extends WebServer2 {
430
+ constructor(ctx, config, gate = new DenyGate()) {
431
+ super(ctx, config);
432
+ this.gate = gate;
433
+ super.register({
434
+ kind: "exact",
435
+ path: READY_PATH,
436
+ handler: (req, res) => {
437
+ if (!evaluateRequestOrigin(config.originPolicy, {
438
+ rawHeaders: req.rawHeaders,
439
+ method: req.method,
440
+ target: req.url
441
+ })) {
442
+ res.writeHead(403, { "cache-control": "no-store" });
443
+ res.end();
444
+ return;
445
+ }
446
+ if (req.method !== "GET") {
447
+ res.writeHead(405, { "cache-control": "no-store", allow: "GET" });
448
+ res.end();
449
+ return;
450
+ }
451
+ const ready = this.gate.ready();
452
+ res.writeHead(ready ? 200 : 503, {
453
+ "cache-control": "no-store",
454
+ "content-type": "application/json; charset=utf-8"
455
+ });
456
+ res.end(
457
+ JSON.stringify({
458
+ plugin: "dsh-auth-remote",
459
+ protocolVersion: READY_PROTOCOL_VERSION,
460
+ ready
461
+ })
462
+ );
463
+ }
464
+ });
465
+ }
466
+ gate;
467
+ register(route) {
468
+ return super.register({
469
+ ...route,
470
+ handler: (req, res) => this.gate.http(req, res, () => Promise.resolve(route.handler(req, res)))
471
+ });
472
+ }
473
+ registerFallback(handler) {
474
+ return super.registerFallback(
475
+ (req, res) => this.gate.http(req, res, () => Promise.resolve(handler(req, res)))
476
+ );
477
+ }
478
+ registerUpgrade(route) {
479
+ return super.registerUpgrade({
480
+ ...route,
481
+ handler: (req, socket, head) => this.gate.upgrade(
482
+ req,
483
+ socket,
484
+ head,
485
+ () => Promise.resolve(route.handler(req, socket, head))
486
+ )
487
+ });
488
+ }
489
+ };
490
+
491
+ // src/auth/service.ts
492
+ import { randomBytes as randomBytes4 } from "node:crypto";
493
+
494
+ // src/storage/store.ts
495
+ import { randomUUID as randomUUID2 } from "node:crypto";
496
+ import { constants as constants2 } from "node:fs";
497
+ import { lstat as lstat2, open as open2, readFile as readFile2, rename, unlink as unlink2 } from "node:fs/promises";
498
+ import { join as join2 } from "node:path";
499
+
500
+ // src/storage/lock.ts
501
+ import { randomUUID } from "node:crypto";
502
+ import { constants } from "node:fs";
503
+ import { lstat, mkdir, open, readFile, rmdir, unlink } from "node:fs/promises";
504
+ import { join } from "node:path";
505
+ var STATE_DIR = "auth-remote";
506
+ var STATE_FILE = "auth-state.json";
507
+ var LOCK_FILE = "auth-state.lock";
508
+ function errno(error, code) {
509
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
510
+ }
511
+ async function processStartTicks(pid) {
512
+ let raw;
513
+ try {
514
+ raw = await readFile(`/proc/${pid}/stat`, "utf8");
515
+ } catch (error) {
516
+ if (errno(error, "ENOENT")) return null;
517
+ throw error;
518
+ }
519
+ const tail = raw.slice(raw.lastIndexOf(")") + 1).trim().split(/\s+/u);
520
+ const ticks = tail[19];
521
+ if (!ticks || !/^\d+$/u.test(ticks)) throw new Error("auth-remote: cannot verify lock owner");
522
+ return ticks;
523
+ }
524
+ async function localOwner() {
525
+ const [bootId, startTicks] = await Promise.all([
526
+ readFile("/proc/sys/kernel/random/boot_id", "utf8"),
527
+ processStartTicks(process.pid)
528
+ ]);
529
+ if (!startTicks) throw new Error("auth-remote: cannot verify own process identity");
530
+ return { pid: process.pid, bootId: bootId.trim(), startTicks, nonce: randomUUID() };
531
+ }
532
+ function parseOwner(raw) {
533
+ let value;
534
+ try {
535
+ value = JSON.parse(raw);
536
+ } catch {
537
+ throw new Error("auth-remote: lock owner is unreadable; manual recovery required");
538
+ }
539
+ if (typeof value !== "object" || value === null || Array.isArray(value))
540
+ throw new Error("auth-remote: lock owner is invalid; manual recovery required");
541
+ const owner = value;
542
+ if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0 || typeof owner.bootId !== "string" || !/^[0-9a-f-]{36}$/u.test(owner.bootId) || typeof owner.startTicks !== "string" || !/^\d+$/u.test(owner.startTicks) || typeof owner.nonce !== "string" || !/^[0-9a-f-]{36}$/u.test(owner.nonce))
543
+ throw new Error("auth-remote: lock owner is invalid; manual recovery required");
544
+ return owner;
545
+ }
546
+ async function isDead(owner, currentBootId) {
547
+ if (owner.bootId !== currentBootId) return true;
548
+ const ticks = await processStartTicks(owner.pid);
549
+ return ticks === null || ticks !== owner.startTicks;
550
+ }
551
+ async function assertPrivate(path, kind) {
552
+ const info = await lstat(path);
553
+ if ((kind === "directory" ? !info.isDirectory() : !info.isFile()) || info.uid !== process.getuid?.() || (info.mode & 511) !== (kind === "directory" ? 448 : 384))
554
+ throw new Error(`auth-remote: unsafe ${kind} permissions or owner: ${path}`);
555
+ }
556
+ async function ensureStateDirectory(profileDir) {
557
+ if (process.platform !== "linux") throw new Error("auth-remote: storage requires Linux /proc");
558
+ const dir = join(profileDir, STATE_DIR);
559
+ let created = false;
560
+ try {
561
+ await mkdir(dir, { mode: 448 });
562
+ created = true;
563
+ } catch (error) {
564
+ if (!errno(error, "EEXIST")) throw error;
565
+ }
566
+ await assertPrivate(dir, "directory");
567
+ if (created) {
568
+ const parent = await open(profileDir, constants.O_RDONLY | constants.O_DIRECTORY);
569
+ try {
570
+ await parent.sync();
571
+ } finally {
572
+ await parent.close();
573
+ }
574
+ }
575
+ return dir;
576
+ }
577
+ var StateLock = class _StateLock {
578
+ constructor(dir, path, owner) {
579
+ this.dir = dir;
580
+ this.path = path;
581
+ this.owner = owner;
582
+ }
583
+ dir;
584
+ path;
585
+ owner;
586
+ released = false;
587
+ static async acquire(profileDir) {
588
+ const dir = await ensureStateDirectory(profileDir);
589
+ const path = join(dir, LOCK_FILE);
590
+ const owner = await localOwner();
591
+ for (let attempt = 0; attempt < 2; attempt++) {
592
+ try {
593
+ const file = await open(
594
+ path,
595
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
596
+ 384
597
+ );
598
+ try {
599
+ await file.writeFile(JSON.stringify(owner));
600
+ await file.sync();
601
+ } catch (error) {
602
+ await file.close();
603
+ await unlink(path).catch(() => void 0);
604
+ throw error;
605
+ }
606
+ await file.close();
607
+ return new _StateLock(dir, path, owner);
608
+ } catch (error) {
609
+ if (!errno(error, "EEXIST")) throw error;
610
+ if (attempt === 1) throw new Error("auth-remote: state lock is held or contested");
611
+ await this.recoverStale(dir, path, owner.bootId);
612
+ }
613
+ }
614
+ throw new Error("auth-remote: state lock acquisition failed");
615
+ }
616
+ static async recoverStale(dir, path, currentBootId) {
617
+ const recovery = `${path}.recovery`;
618
+ try {
619
+ await mkdir(recovery, { mode: 448 });
620
+ } catch (error) {
621
+ if (errno(error, "EEXIST"))
622
+ throw new Error(
623
+ "auth-remote: lock recovery is already active or abandoned; manual review required"
624
+ );
625
+ throw error;
626
+ }
627
+ try {
628
+ let info;
629
+ try {
630
+ info = await lstat(path);
631
+ } catch (error) {
632
+ if (errno(error, "ENOENT")) return;
633
+ throw error;
634
+ }
635
+ await assertPrivate(path, "file");
636
+ const old = parseOwner(await readFile(path, "utf8"));
637
+ if (!await isDead(old, currentBootId))
638
+ throw new Error(`auth-remote: state lock held by live process ${old.pid}`);
639
+ const latest = await lstat(path);
640
+ if (latest.ino !== info.ino || latest.dev !== info.dev)
641
+ throw new Error("auth-remote: state lock changed during recovery");
642
+ await unlink(path);
643
+ const parent = await open(dir, constants.O_RDONLY | constants.O_DIRECTORY);
644
+ try {
645
+ await parent.sync();
646
+ } finally {
647
+ await parent.close();
648
+ }
649
+ } finally {
650
+ await rmdir(recovery);
651
+ }
652
+ }
653
+ async release() {
654
+ if (this.released) return;
655
+ const current = parseOwner(await readFile(this.path, "utf8"));
656
+ if (current.nonce !== this.owner.nonce)
657
+ throw new Error("auth-remote: state lock ownership changed before release");
658
+ await unlink(this.path);
659
+ this.released = true;
660
+ }
661
+ };
662
+ async function assertPrivateStateFile(path) {
663
+ await assertPrivate(path, "file");
664
+ }
665
+
666
+ // src/storage/state.ts
667
+ var STATE_SCHEMA_VERSION = 1;
668
+ function emptyState() {
669
+ return { schemaVersion: STATE_SCHEMA_VERSION, revision: 0, account: null, sessions: {} };
670
+ }
671
+ function record(value, keys, label) {
672
+ if (typeof value !== "object" || value === null || Array.isArray(value))
673
+ throw new Error(`auth-remote: invalid ${label}`);
674
+ const entries = Object.keys(value);
675
+ if (entries.length !== keys.length || entries.some((key) => !keys.includes(key)))
676
+ throw new Error(`auth-remote: invalid ${label} fields`);
677
+ return value;
678
+ }
679
+ function integer(value, label, min = 0) {
680
+ if (!Number.isSafeInteger(value) || value < min)
681
+ throw new Error(`auth-remote: invalid ${label}`);
682
+ return value;
683
+ }
684
+ function nonempty(value, label) {
685
+ if (typeof value !== "string" || value.length === 0)
686
+ throw new Error(`auth-remote: invalid ${label}`);
687
+ return value;
688
+ }
689
+ function hex(value, bytes, label) {
690
+ if (typeof value !== "string" || !new RegExp(`^[a-f0-9]{${bytes * 2}}$`, "u").test(value))
691
+ throw new Error(`auth-remote: invalid ${label}`);
692
+ return value;
693
+ }
694
+ function digest(value, label) {
695
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/u.test(value))
696
+ throw new Error(`auth-remote: invalid ${label}`);
697
+ return value;
698
+ }
699
+ function validateState(value) {
700
+ const state = record(value, ["schemaVersion", "revision", "account", "sessions"], "state");
701
+ if (state.schemaVersion !== STATE_SCHEMA_VERSION)
702
+ throw new Error(`auth-remote: unsupported state schema version ${String(state.schemaVersion)}`);
703
+ const revision = integer(state.revision, "revision");
704
+ let account = null;
705
+ if (state.account !== null) {
706
+ const entry = record(
707
+ state.account,
708
+ ["id", "username", "password", "totp", "securityVersion"],
709
+ "account"
710
+ );
711
+ const password = record(entry.password, ["salt", "hash"], "password record");
712
+ let totp = null;
713
+ if (entry.totp !== null) {
714
+ const factor = record(
715
+ entry.totp,
716
+ ["secret", "lastUsedStep", "backupCodeHashes"],
717
+ "TOTP record"
718
+ );
719
+ if (!Array.isArray(factor.backupCodeHashes) || factor.backupCodeHashes.length > 10)
720
+ throw new Error("auth-remote: invalid backup code hashes");
721
+ if (typeof factor.secret !== "string" || !/^[A-Z2-7]{32}$/u.test(factor.secret))
722
+ throw new Error("auth-remote: invalid TOTP secret");
723
+ totp = {
724
+ secret: factor.secret,
725
+ lastUsedStep: factor.lastUsedStep === null ? null : integer(factor.lastUsedStep, "TOTP step"),
726
+ backupCodeHashes: factor.backupCodeHashes.map((hash) => digest(hash, "backup code hash"))
727
+ };
728
+ if (new Set(totp.backupCodeHashes).size !== totp.backupCodeHashes.length)
729
+ throw new Error("auth-remote: duplicate backup code hash");
730
+ }
731
+ const username = nonempty(entry.username, "username");
732
+ if ([...username].length > 64 || /[\u0000-\u001f\u007f]/u.test(username))
733
+ throw new Error("auth-remote: invalid username");
734
+ account = {
735
+ id: hex(entry.id, 16, "account id"),
736
+ username,
737
+ password: {
738
+ salt: hex(password.salt, 32, "password salt"),
739
+ hash: hex(password.hash, 64, "password hash")
740
+ },
741
+ totp,
742
+ securityVersion: integer(entry.securityVersion, "security version", 1)
743
+ };
744
+ }
745
+ const sessions = state.sessions;
746
+ if (typeof sessions !== "object" || sessions === null || Array.isArray(sessions))
747
+ throw new Error("auth-remote: invalid sessions");
748
+ const validatedSessions = /* @__PURE__ */ Object.create(null);
749
+ for (const [hash, value2] of Object.entries(sessions)) {
750
+ digest(hash, "session token hash");
751
+ const session = record(
752
+ value2,
753
+ ["accountId", "securityVersion", "createdAt", "expiresAt"],
754
+ "session"
755
+ );
756
+ const createdAt = integer(session.createdAt, "session creation");
757
+ const expiresAt = integer(session.expiresAt, "session expiry");
758
+ if (!account || session.accountId !== account.id || expiresAt <= createdAt)
759
+ throw new Error("auth-remote: invalid session account or lifetime");
760
+ validatedSessions[hash] = {
761
+ accountId: account.id,
762
+ securityVersion: integer(session.securityVersion, "session security version", 1),
763
+ createdAt,
764
+ expiresAt
765
+ };
766
+ }
767
+ return { schemaVersion: STATE_SCHEMA_VERSION, revision, account, sessions: validatedSessions };
768
+ }
769
+
770
+ // src/storage/store.ts
771
+ function errno2(error, code) {
772
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
773
+ }
774
+ var AuthStateStore = class _AuthStateStore {
775
+ constructor(lock, state, options) {
776
+ this.lock = lock;
777
+ this.options = options;
778
+ this.path = join2(lock.dir, STATE_FILE);
779
+ this.state = state;
780
+ }
781
+ lock;
782
+ options;
783
+ path;
784
+ state;
785
+ queue = Promise.resolve();
786
+ unavailableReason = null;
787
+ closed = false;
788
+ listeners = /* @__PURE__ */ new Set();
789
+ static async open(profileDir, options = {}) {
790
+ const lock = await StateLock.acquire(profileDir);
791
+ try {
792
+ const path = join2(lock.dir, STATE_FILE);
793
+ let state = emptyState();
794
+ try {
795
+ await assertPrivateStateFile(path);
796
+ const info = await lstat2(path);
797
+ if (info.size > 16 * 1024 * 1024)
798
+ throw new Error("auth-remote: state file exceeds the supported size");
799
+ state = validateState(JSON.parse(await readFile2(path, "utf8")));
800
+ } catch (error) {
801
+ if (!errno2(error, "ENOENT")) throw error;
802
+ }
803
+ return new _AuthStateStore(lock, state, options);
804
+ } catch (error) {
805
+ await lock.release();
806
+ throw error;
807
+ }
808
+ }
809
+ healthy() {
810
+ return !this.closed && this.unavailableReason === null;
811
+ }
812
+ current() {
813
+ if (!this.healthy()) throw this.unavailableReason ?? new Error("auth-remote: store is closed");
814
+ return structuredClone(this.state);
815
+ }
816
+ /** Notifications finish before transact reports success; a failed listener closes admission. */
817
+ subscribe(listener) {
818
+ if (!this.healthy()) throw this.unavailableReason ?? new Error("auth-remote: store is closed");
819
+ this.listeners.add(listener);
820
+ return () => this.listeners.delete(listener);
821
+ }
822
+ async transact(mutate) {
823
+ const run = async () => {
824
+ if (!this.healthy()) throw this.unavailableReason ?? new Error("auth-remote: store is closed");
825
+ const draft = structuredClone(this.state);
826
+ const result = await mutate(draft);
827
+ if (this.state.revision >= Number.MAX_SAFE_INTEGER)
828
+ throw new Error("auth-remote: state revision exhausted");
829
+ draft.revision = this.state.revision + 1;
830
+ const next = validateState(draft);
831
+ await this.persist(next);
832
+ return result;
833
+ };
834
+ const operation = this.queue.then(run);
835
+ this.queue = operation.then(
836
+ () => void 0,
837
+ () => void 0
838
+ );
839
+ return operation;
840
+ }
841
+ async persist(next) {
842
+ const temp = `${this.path}.tmp-${process.pid}-${randomUUID2()}`;
843
+ const bytes = Buffer.from(`${JSON.stringify(next)}
844
+ `, "utf8");
845
+ if (bytes.length > 16 * 1024 * 1024)
846
+ throw new Error("auth-remote: state file exceeds the supported size");
847
+ let renamed = false;
848
+ let file;
849
+ try {
850
+ file = await open2(
851
+ temp,
852
+ constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY | constants2.O_NOFOLLOW,
853
+ 384
854
+ );
855
+ await file.writeFile(bytes);
856
+ await this.options.onStage?.("afterTempWrite");
857
+ await file.sync();
858
+ await this.options.onStage?.("afterFileSync");
859
+ await file.close();
860
+ file = void 0;
861
+ await this.options.onStage?.("beforeRename");
862
+ await rename(temp, this.path);
863
+ renamed = true;
864
+ await this.options.onStage?.("afterRename");
865
+ const parent = await open2(this.lock.dir, constants2.O_RDONLY | constants2.O_DIRECTORY);
866
+ try {
867
+ await parent.sync();
868
+ } finally {
869
+ await parent.close();
870
+ }
871
+ await this.options.onStage?.("afterDirSync");
872
+ const previous = this.state;
873
+ this.state = next;
874
+ await this.options.onCommitted?.(structuredClone(previous), structuredClone(next));
875
+ for (const listener of this.listeners)
876
+ await listener(structuredClone(previous), structuredClone(next));
877
+ await this.options.onStage?.("beforeSuccess");
878
+ } catch (error) {
879
+ if (renamed) {
880
+ this.unavailableReason = new Error("auth-remote: state commit outcome is uncertain", {
881
+ cause: error
882
+ });
883
+ this.options.onUnavailable?.(this.unavailableReason);
884
+ }
885
+ throw error;
886
+ } finally {
887
+ await file?.close().catch(() => void 0);
888
+ if (!renamed) await unlink2(temp).catch(() => void 0);
889
+ }
890
+ }
891
+ async close() {
892
+ if (this.closed) return;
893
+ this.closed = true;
894
+ await this.queue;
895
+ await this.lock.release();
896
+ }
897
+ };
898
+
899
+ // src/auth/password.ts
900
+ import { randomBytes, scrypt as scryptCallback, timingSafeEqual } from "node:crypto";
901
+ var PASSWORD_MIN_CHARACTERS = 12;
902
+ var PASSWORD_MAX_CHARACTERS = 256;
903
+ var PasswordValidationError = class extends Error {
904
+ constructor() {
905
+ super("auth-remote: password must contain 12\u2013256 Unicode characters");
906
+ }
907
+ };
908
+ function validatePassword(password) {
909
+ if (typeof password !== "string" || [...password].length < PASSWORD_MIN_CHARACTERS || [...password].length > PASSWORD_MAX_CHARACTERS)
910
+ throw new PasswordValidationError();
911
+ }
912
+ async function derive(password, salt) {
913
+ return new Promise((resolve, reject) => {
914
+ scryptCallback(
915
+ password,
916
+ Buffer.from(salt, "hex"),
917
+ 64,
918
+ { N: 16384, r: 8, p: 1, maxmem: 32 * 1024 * 1024 },
919
+ (error, key) => error ? reject(error) : resolve(key)
920
+ );
921
+ });
922
+ }
923
+ async function hashPassword(password) {
924
+ validatePassword(password);
925
+ const salt = randomBytes(32).toString("hex");
926
+ return { salt, hash: (await derive(password, salt)).toString("hex") };
927
+ }
928
+ async function verifyPassword(password, record2) {
929
+ const derived = await derive(password, record2.salt);
930
+ return timingSafeEqual(derived, Buffer.from(record2.hash, "hex"));
931
+ }
932
+ var DUMMY_PASSWORD_RECORD = {
933
+ salt: "0".repeat(64),
934
+ hash: "0".repeat(128)
935
+ };
936
+
937
+ // src/auth/sessions.ts
938
+ import { createHash, randomBytes as randomBytes2 } from "node:crypto";
939
+ function sessionHash(token) {
940
+ return createHash("sha256").update(token).digest("hex");
941
+ }
942
+ function issueSession(draft, now, sessionHours) {
943
+ const account = draft.account;
944
+ if (!account) throw new Error("auth-remote: cannot issue a session without an account");
945
+ const expiresAt = now + sessionHours * 36e5;
946
+ if (!Number.isSafeInteger(expiresAt)) throw new Error("auth-remote: session expiry overflow");
947
+ const token = randomBytes2(32).toString("base64url");
948
+ draft.sessions[sessionHash(token)] = {
949
+ accountId: account.id,
950
+ securityVersion: account.securityVersion,
951
+ createdAt: now,
952
+ expiresAt
953
+ };
954
+ return { token, expiresAt };
955
+ }
956
+ function sessionFor(state, token, now, requireTotp) {
957
+ if (typeof token !== "string" || !/^[A-Za-z0-9_-]{43}$/u.test(token)) return null;
958
+ const session = state.sessions[sessionHash(token)];
959
+ const account = state.account;
960
+ if (!session || !account || session.accountId !== account.id || session.securityVersion !== account.securityVersion || session.expiresAt <= now || requireTotp && !account.totp)
961
+ return null;
962
+ return session;
963
+ }
964
+
965
+ // src/auth/totp.ts
966
+ import { createHash as createHash2, createHmac, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
967
+ var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
968
+ var TOTP_PERIOD_MS = 3e4;
969
+ function base32(bytes) {
970
+ let bits = 0;
971
+ let value = 0;
972
+ let output = "";
973
+ for (const byte of bytes) {
974
+ value = value << 8 | byte;
975
+ bits += 8;
976
+ while (bits >= 5) {
977
+ output += alphabet[value >>> bits - 5 & 31];
978
+ bits -= 5;
979
+ }
980
+ }
981
+ if (bits > 0) output += alphabet[value << 5 - bits & 31];
982
+ return output;
983
+ }
984
+ function fromBase32(value) {
985
+ let bits = 0;
986
+ let accum = 0;
987
+ const output = [];
988
+ for (const char of value) {
989
+ const digit = alphabet.indexOf(char);
990
+ if (digit < 0) throw new Error("auth-remote: invalid TOTP secret");
991
+ accum = accum << 5 | digit;
992
+ bits += 5;
993
+ if (bits >= 8) {
994
+ output.push(accum >>> bits - 8 & 255);
995
+ bits -= 8;
996
+ }
997
+ }
998
+ return Buffer.from(output);
999
+ }
1000
+ function generateTotpSecret() {
1001
+ return base32(randomBytes3(20));
1002
+ }
1003
+ function totpCode(secret, step) {
1004
+ if (!Number.isSafeInteger(step) || step < 0) throw new Error("auth-remote: invalid TOTP step");
1005
+ const counter = Buffer.alloc(8);
1006
+ counter.writeBigUInt64BE(BigInt(step));
1007
+ const mac = createHmac("sha1", fromBase32(secret)).update(counter).digest();
1008
+ const offset = mac[mac.length - 1] & 15;
1009
+ const value = (mac.readUInt32BE(offset) & 2147483647) % 1e6;
1010
+ return String(value).padStart(6, "0");
1011
+ }
1012
+ function matchedTotpStep(secret, code, timestamp, lastUsedStep) {
1013
+ if (typeof code !== "string" || !/^\d{6}$/u.test(code)) return null;
1014
+ const current = Math.floor(timestamp / TOTP_PERIOD_MS);
1015
+ for (const step of [current - 1, current, current + 1]) {
1016
+ if (step < 0 || lastUsedStep !== null && step <= lastUsedStep) continue;
1017
+ if (timingSafeEqual2(Buffer.from(totpCode(secret, step)), Buffer.from(code))) return step;
1018
+ }
1019
+ return null;
1020
+ }
1021
+ function backupCodeHash(code) {
1022
+ if (typeof code !== "string") return null;
1023
+ const canonical = code.replaceAll("-", "").toUpperCase();
1024
+ if (!/^[A-Z2-7]{20}$/u.test(canonical)) return null;
1025
+ return createHash2("sha256").update(`auth-remote-backup:${canonical}`).digest("hex");
1026
+ }
1027
+ function generateBackupCodes() {
1028
+ const codes = Array.from(
1029
+ { length: 10 },
1030
+ () => base32(randomBytes3(12)).match(/.{1,5}/gu).join("-")
1031
+ );
1032
+ return { codes, hashes: codes.map((code) => backupCodeHash(code)) };
1033
+ }
1034
+
1035
+ // src/auth/service.ts
1036
+ var AuthError = class extends Error {
1037
+ constructor(code, retryAfter) {
1038
+ super(`auth-remote: ${code}`);
1039
+ this.code = code;
1040
+ this.retryAfter = retryAfter;
1041
+ }
1042
+ code;
1043
+ retryAfter;
1044
+ };
1045
+ var LOGIN_CHALLENGE_MS = 5 * 6e4;
1046
+ var BINDING_CHALLENGE_MS = 10 * 6e4;
1047
+ var RATE_WINDOW_MS = 6e4;
1048
+ var MAX_ATTEMPTS = 10;
1049
+ var MAX_CHALLENGES = 32;
1050
+ function validatePolicy(policy, now) {
1051
+ if (typeof policy.requireTotp !== "boolean" || !Number.isSafeInteger(policy.sessionHours) || policy.sessionHours < 1 || !Number.isSafeInteger(now + policy.sessionHours * 36e5))
1052
+ throw new AuthError("invalid_input");
1053
+ }
1054
+ function validUsername(username) {
1055
+ return typeof username === "string" && username.length > 0 && [...username].length <= 64 && !/[\u0000-\u001f\u007f]/u.test(username);
1056
+ }
1057
+ var AuthService = class {
1058
+ constructor(store, policy, options = {}) {
1059
+ this.store = store;
1060
+ this.policy = policy;
1061
+ this.now = options.now ?? Date.now;
1062
+ validatePolicy(policy, this.now());
1063
+ this.unsubscribe = store.subscribe((previous, current) => {
1064
+ if (previous.account?.securityVersion !== current.account?.securityVersion) {
1065
+ this.challenges.clear();
1066
+ return;
1067
+ }
1068
+ for (const [id, challenge] of this.challenges) {
1069
+ if (challenge.kind === "binding" && challenge.originSessionHash && previous.sessions[challenge.originSessionHash] && !current.sessions[challenge.originSessionHash])
1070
+ this.challenges.delete(id);
1071
+ }
1072
+ });
1073
+ }
1074
+ store;
1075
+ policy;
1076
+ now;
1077
+ challenges = /* @__PURE__ */ new Map();
1078
+ attempts = [];
1079
+ activeDerivations = 0;
1080
+ policyChanging = false;
1081
+ unsubscribe;
1082
+ dispose() {
1083
+ this.unsubscribe();
1084
+ this.challenges.clear();
1085
+ }
1086
+ status() {
1087
+ const state = this.store.current();
1088
+ return {
1089
+ initialized: state.account !== null,
1090
+ totpEnabled: state.account?.totp !== null && state.account?.totp !== void 0,
1091
+ activeSessions: Object.values(state.sessions).filter(
1092
+ (session) => state.account && session.accountId === state.account.id && session.securityVersion === state.account.securityVersion && session.expiresAt > this.now() && (!this.policy.requireTotp || state.account.totp)
1093
+ ).length
1094
+ };
1095
+ }
1096
+ session(token) {
1097
+ return sessionFor(this.store.current(), token, this.now(), this.policy.requireTotp);
1098
+ }
1099
+ policySnapshot() {
1100
+ return { ...this.policy };
1101
+ }
1102
+ me(token) {
1103
+ const state = this.store.current();
1104
+ const session = sessionFor(state, token, this.now(), this.policy.requireTotp);
1105
+ if (!session || !state.account) throw new AuthError("unauthorized");
1106
+ return {
1107
+ username: state.account.username,
1108
+ totpEnabled: state.account.totp !== null,
1109
+ expiresAt: session.expiresAt
1110
+ };
1111
+ }
1112
+ bindingDetails(id) {
1113
+ const challenge = this.challenges.get(id);
1114
+ if (!challenge || challenge.kind !== "binding") throw new AuthError("invalid_challenge");
1115
+ if (challenge.expiresAt <= this.now()) {
1116
+ this.challenges.delete(id);
1117
+ throw new AuthError("challenge_expired");
1118
+ }
1119
+ const state = this.store.current();
1120
+ this.sameAccount(state, challenge.accountId, challenge.securityVersion);
1121
+ if (challenge.originSessionHash) {
1122
+ const session = state.sessions[challenge.originSessionHash];
1123
+ if (!session || session.expiresAt <= this.now()) throw new AuthError("unauthorized");
1124
+ }
1125
+ return { secret: challenge.secret, expiresAt: challenge.expiresAt };
1126
+ }
1127
+ pendingChallenges() {
1128
+ this.expireChallenges();
1129
+ return this.challenges.size;
1130
+ }
1131
+ occupyAttempt() {
1132
+ const now = this.now();
1133
+ while (this.attempts.length > 0 && this.attempts[0] <= now - RATE_WINDOW_MS)
1134
+ this.attempts.shift();
1135
+ if (this.attempts.length >= MAX_ATTEMPTS)
1136
+ throw new AuthError(
1137
+ "rate_limited",
1138
+ Math.ceil((this.attempts[0] + RATE_WINDOW_MS - now) / 1e3)
1139
+ );
1140
+ this.attempts.push(now);
1141
+ }
1142
+ async derive(run) {
1143
+ if (this.activeDerivations >= 2) throw new AuthError("busy");
1144
+ this.activeDerivations++;
1145
+ try {
1146
+ return await run();
1147
+ } finally {
1148
+ this.activeDerivations--;
1149
+ }
1150
+ }
1151
+ expireChallenges() {
1152
+ const now = this.now();
1153
+ for (const [id, challenge] of this.challenges)
1154
+ if (challenge.expiresAt <= now) this.challenges.delete(id);
1155
+ }
1156
+ createChallenge(kind, account, originSessionHash = null) {
1157
+ this.expireChallenges();
1158
+ if (this.challenges.size >= MAX_CHALLENGES) throw new AuthError("busy");
1159
+ const id = randomBytes4(32).toString("base64url");
1160
+ const expiresAt = this.now() + (kind === "mfa" ? LOGIN_CHALLENGE_MS : BINDING_CHALLENGE_MS);
1161
+ const base = {
1162
+ id,
1163
+ accountId: account.id,
1164
+ securityVersion: account.securityVersion,
1165
+ expiresAt,
1166
+ failures: 0,
1167
+ busy: false
1168
+ };
1169
+ if (kind === "mfa") {
1170
+ this.challenges.set(id, { ...base, kind });
1171
+ return { kind, challenge: id, expiresAt };
1172
+ }
1173
+ const secret = generateTotpSecret();
1174
+ this.challenges.set(id, { ...base, kind, secret, originSessionHash });
1175
+ return { kind, challenge: id, secret, expiresAt };
1176
+ }
1177
+ claim(id, kind) {
1178
+ const challenge = this.challenges.get(id);
1179
+ if (!challenge || challenge.kind !== kind) throw new AuthError("invalid_challenge");
1180
+ if (challenge.expiresAt <= this.now()) {
1181
+ this.challenges.delete(id);
1182
+ throw new AuthError("challenge_expired");
1183
+ }
1184
+ if (challenge.busy || challenge.failures >= 5) throw new AuthError("invalid_challenge");
1185
+ challenge.busy = true;
1186
+ return challenge;
1187
+ }
1188
+ failedChallenge(challenge) {
1189
+ challenge.failures++;
1190
+ if (challenge.failures >= 5) this.challenges.delete(challenge.id);
1191
+ }
1192
+ sameAccount(state, accountId, securityVersion) {
1193
+ const account = state.account;
1194
+ if (!account || account.id !== accountId || account.securityVersion !== securityVersion)
1195
+ throw new AuthError("conflict");
1196
+ return account;
1197
+ }
1198
+ requireSession(state, token) {
1199
+ if (!sessionFor(state, token, this.now(), this.policy.requireTotp))
1200
+ throw new AuthError("unauthorized");
1201
+ return state.account;
1202
+ }
1203
+ verifyFactor(account, code) {
1204
+ const factor = account.totp;
1205
+ if (!factor) return true;
1206
+ if (!code) return false;
1207
+ const step = matchedTotpStep(factor.secret, code, this.now(), factor.lastUsedStep);
1208
+ if (step !== null) {
1209
+ factor.lastUsedStep = step;
1210
+ return true;
1211
+ }
1212
+ const hash = backupCodeHash(code);
1213
+ if (!hash) return false;
1214
+ const index = factor.backupCodeHashes.indexOf(hash);
1215
+ if (index < 0) return false;
1216
+ factor.backupCodeHashes.splice(index, 1);
1217
+ return true;
1218
+ }
1219
+ async initialize(username, password) {
1220
+ if (!validUsername(username)) throw new AuthError("invalid_input");
1221
+ validatePassword(password);
1222
+ if (this.store.current().account) throw new AuthError("already_initialized");
1223
+ const record2 = await this.derive(() => hashPassword(password));
1224
+ await this.store.transact((draft) => {
1225
+ if (draft.account) throw new AuthError("already_initialized");
1226
+ draft.account = {
1227
+ id: randomBytes4(16).toString("hex"),
1228
+ username,
1229
+ password: record2,
1230
+ totp: null,
1231
+ securityVersion: 1
1232
+ };
1233
+ });
1234
+ }
1235
+ async login(username, password) {
1236
+ this.occupyAttempt();
1237
+ if (!validUsername(username) || typeof password !== "string" || password.length > 1024)
1238
+ throw new AuthError("invalid_credentials");
1239
+ const snapshot = this.store.current();
1240
+ const account = snapshot.account;
1241
+ if (!account) throw new AuthError("uninitialized");
1242
+ const match = await this.derive(
1243
+ () => verifyPassword(
1244
+ password,
1245
+ username === account.username ? account.password : DUMMY_PASSWORD_RECORD
1246
+ )
1247
+ );
1248
+ if (!match || username !== account.username) throw new AuthError("invalid_credentials");
1249
+ const current = this.store.current();
1250
+ const latest = this.sameAccount(current, account.id, account.securityVersion);
1251
+ if (latest.totp) return this.createChallenge("mfa", latest);
1252
+ if (this.policy.requireTotp) return this.createChallenge("binding", latest);
1253
+ const issued = await this.store.transact((draft) => {
1254
+ this.sameAccount(draft, account.id, account.securityVersion);
1255
+ if (draft.account.totp || this.policy.requireTotp) throw new AuthError("conflict");
1256
+ return issueSession(draft, this.now(), this.policy.sessionHours);
1257
+ });
1258
+ return { kind: "session", ...issued };
1259
+ }
1260
+ async verifyMfa(id, code) {
1261
+ this.occupyAttempt();
1262
+ const challenge = this.claim(id, "mfa");
1263
+ try {
1264
+ const issued = await this.store.transact((draft) => {
1265
+ if (challenge.expiresAt <= this.now()) throw new AuthError("challenge_expired");
1266
+ const account = this.sameAccount(draft, challenge.accountId, challenge.securityVersion);
1267
+ if (!account.totp || !this.verifyFactor(account, code))
1268
+ throw new AuthError("invalid_factor");
1269
+ return issueSession(draft, this.now(), this.policy.sessionHours);
1270
+ });
1271
+ this.challenges.delete(id);
1272
+ return issued;
1273
+ } catch (error) {
1274
+ if (error instanceof AuthError && error.code === "invalid_factor")
1275
+ this.failedChallenge(challenge);
1276
+ throw error;
1277
+ } finally {
1278
+ challenge.busy = false;
1279
+ }
1280
+ }
1281
+ async startBinding(token, password, currentCode) {
1282
+ this.occupyAttempt();
1283
+ const snapshot = this.store.current();
1284
+ const account = this.requireSession(snapshot, token);
1285
+ if (typeof password !== "string" || password.length > 1024)
1286
+ throw new AuthError("invalid_credentials");
1287
+ const match = await this.derive(() => verifyPassword(password, account.password));
1288
+ if (!match) throw new AuthError("invalid_credentials");
1289
+ if (account.totp) {
1290
+ await this.store.transact((draft) => {
1291
+ this.requireSession(draft, token);
1292
+ this.sameAccount(draft, account.id, account.securityVersion);
1293
+ if (!this.verifyFactor(draft.account, currentCode)) throw new AuthError("invalid_factor");
1294
+ });
1295
+ } else {
1296
+ const latest = this.store.current();
1297
+ this.requireSession(latest, token);
1298
+ this.sameAccount(latest, account.id, account.securityVersion);
1299
+ }
1300
+ return this.createChallenge("binding", account, sessionHash(token));
1301
+ }
1302
+ async confirmBinding(id, code) {
1303
+ this.occupyAttempt();
1304
+ const challenge = this.claim(id, "binding");
1305
+ try {
1306
+ const step = matchedTotpStep(challenge.secret, code, this.now(), null);
1307
+ if (step === null) {
1308
+ this.failedChallenge(challenge);
1309
+ throw new AuthError("invalid_factor");
1310
+ }
1311
+ const backups = generateBackupCodes();
1312
+ await this.store.transact((draft) => {
1313
+ if (challenge.expiresAt <= this.now()) throw new AuthError("challenge_expired");
1314
+ const account = this.sameAccount(draft, challenge.accountId, challenge.securityVersion);
1315
+ const originSession = challenge.originSessionHash ? draft.sessions[challenge.originSessionHash] : null;
1316
+ if (challenge.originSessionHash && (!originSession || originSession.expiresAt <= this.now()))
1317
+ throw new AuthError("unauthorized");
1318
+ account.totp = {
1319
+ secret: challenge.secret,
1320
+ lastUsedStep: step,
1321
+ backupCodeHashes: backups.hashes
1322
+ };
1323
+ account.securityVersion++;
1324
+ draft.sessions = {};
1325
+ });
1326
+ this.challenges.clear();
1327
+ return { backupCodes: backups.codes };
1328
+ } finally {
1329
+ challenge.busy = false;
1330
+ }
1331
+ }
1332
+ async changePassword(token, currentPassword, currentCode, newPassword) {
1333
+ this.occupyAttempt();
1334
+ validatePassword(newPassword);
1335
+ if (typeof currentPassword !== "string" || currentPassword.length > 1024)
1336
+ throw new AuthError("invalid_credentials");
1337
+ const snapshot = this.store.current();
1338
+ const account = this.requireSession(snapshot, token);
1339
+ const match = await this.derive(() => verifyPassword(currentPassword, account.password));
1340
+ if (!match) throw new AuthError("invalid_credentials");
1341
+ const replacement = await this.derive(() => hashPassword(newPassword));
1342
+ await this.store.transact((draft) => {
1343
+ this.requireSession(draft, token);
1344
+ const current = this.sameAccount(draft, account.id, account.securityVersion);
1345
+ if (!this.verifyFactor(current, currentCode)) throw new AuthError("invalid_factor");
1346
+ current.password = replacement;
1347
+ current.securityVersion++;
1348
+ draft.sessions = {};
1349
+ });
1350
+ }
1351
+ async disableTotp(token, password, currentCode) {
1352
+ this.occupyAttempt();
1353
+ if (this.policy.requireTotp) throw new AuthError("totp_required");
1354
+ if (typeof password !== "string" || password.length > 1024)
1355
+ throw new AuthError("invalid_credentials");
1356
+ const snapshot = this.store.current();
1357
+ const account = this.requireSession(snapshot, token);
1358
+ const match = await this.derive(() => verifyPassword(password, account.password));
1359
+ if (!match) throw new AuthError("invalid_credentials");
1360
+ await this.store.transact((draft) => {
1361
+ this.requireSession(draft, token);
1362
+ const current = this.sameAccount(draft, account.id, account.securityVersion);
1363
+ if (!current.totp || !this.verifyFactor(current, currentCode))
1364
+ throw new AuthError("invalid_factor");
1365
+ current.totp = null;
1366
+ current.securityVersion++;
1367
+ draft.sessions = {};
1368
+ });
1369
+ }
1370
+ async revokeWithCredentials(token, password, currentCode) {
1371
+ this.occupyAttempt();
1372
+ if (typeof password !== "string" || password.length > 1024)
1373
+ throw new AuthError("invalid_credentials");
1374
+ const snapshot = this.store.current();
1375
+ const account = this.requireSession(snapshot, token);
1376
+ const match = await this.derive(() => verifyPassword(password, account.password));
1377
+ if (!match) throw new AuthError("invalid_credentials");
1378
+ await this.store.transact((draft) => {
1379
+ this.requireSession(draft, token);
1380
+ const current = this.sameAccount(draft, account.id, account.securityVersion);
1381
+ if (!this.verifyFactor(current, currentCode)) throw new AuthError("invalid_factor");
1382
+ current.securityVersion++;
1383
+ draft.sessions = {};
1384
+ });
1385
+ }
1386
+ async logout(token) {
1387
+ if (typeof token !== "string" || !/^[A-Za-z0-9_-]{43}$/u.test(token)) return;
1388
+ const hash = sessionHash(token);
1389
+ if (!this.store.current().sessions[hash]) return;
1390
+ await this.store.transact((draft) => {
1391
+ delete draft.sessions[hash];
1392
+ });
1393
+ }
1394
+ async resetPassword(newPassword) {
1395
+ validatePassword(newPassword);
1396
+ const replacement = await this.derive(() => hashPassword(newPassword));
1397
+ await this.store.transact((draft) => {
1398
+ if (!draft.account) throw new AuthError("uninitialized");
1399
+ draft.account.password = replacement;
1400
+ draft.account.securityVersion++;
1401
+ draft.sessions = {};
1402
+ });
1403
+ }
1404
+ async resetTotp() {
1405
+ await this.store.transact((draft) => {
1406
+ if (!draft.account) throw new AuthError("uninitialized");
1407
+ draft.account.totp = null;
1408
+ draft.account.securityVersion++;
1409
+ draft.sessions = {};
1410
+ });
1411
+ }
1412
+ async revokeAll() {
1413
+ await this.store.transact((draft) => {
1414
+ if (!draft.account) throw new AuthError("uninitialized");
1415
+ draft.account.securityVersion++;
1416
+ draft.sessions = {};
1417
+ });
1418
+ }
1419
+ async applyPolicy(next) {
1420
+ validatePolicy(next, this.now());
1421
+ if (this.policyChanging) throw new AuthError("busy");
1422
+ if (next.requireTotp === this.policy.requireTotp && next.sessionHours === this.policy.sessionHours)
1423
+ return;
1424
+ this.policyChanging = true;
1425
+ const previous = this.policy;
1426
+ this.policy = next;
1427
+ try {
1428
+ await this.store.transact((draft) => {
1429
+ if (next.requireTotp && !previous.requireTotp && draft.account && !draft.account.totp) {
1430
+ draft.account.securityVersion++;
1431
+ draft.sessions = {};
1432
+ }
1433
+ if (next.sessionHours < previous.sessionHours) {
1434
+ for (const session of Object.values(draft.sessions))
1435
+ session.expiresAt = Math.min(
1436
+ session.expiresAt,
1437
+ session.createdAt + next.sessionHours * 36e5
1438
+ );
1439
+ }
1440
+ });
1441
+ this.challenges.clear();
1442
+ } catch (error) {
1443
+ if (this.store.healthy()) this.policy = previous;
1444
+ throw error;
1445
+ } finally {
1446
+ this.policyChanging = false;
1447
+ }
1448
+ }
1449
+ /** Startup/re-activation must persist tightening before the guarded listener opens. */
1450
+ async enforceCurrentPolicy() {
1451
+ const state = this.store.current();
1452
+ const revokeUnbound = this.policy.requireTotp && !state.account?.totp && Object.keys(state.sessions).length > 0;
1453
+ const shorten = Object.values(state.sessions).some(
1454
+ (session) => session.expiresAt > session.createdAt + this.policy.sessionHours * 36e5
1455
+ );
1456
+ if (!revokeUnbound && !shorten) return;
1457
+ await this.store.transact((draft) => {
1458
+ if (this.policy.requireTotp && draft.account && !draft.account.totp) {
1459
+ draft.account.securityVersion++;
1460
+ draft.sessions = {};
1461
+ }
1462
+ for (const session of Object.values(draft.sessions))
1463
+ session.expiresAt = Math.min(
1464
+ session.expiresAt,
1465
+ session.createdAt + this.policy.sessionHours * 36e5
1466
+ );
1467
+ });
1468
+ }
1469
+ };
1470
+
1471
+ // src/config.ts
1472
+ import z from "@deepseek-ai/schemastery";
1473
+ import { isIP } from "node:net";
1474
+ var DEFAULT_REQUIRE_TOTP = true;
1475
+ var DEFAULT_SESSION_HOURS = 168;
1476
+ var DEFAULT_WEB_HOST = "127.0.0.1";
1477
+ var DEFAULT_WEB_PORT = 3080;
1478
+ var AUTH_CONFIG_KEYS = /* @__PURE__ */ new Set([
1479
+ "allowedOrigins",
1480
+ "requireTotp",
1481
+ "sessionHours",
1482
+ "preserveOriginPaths"
1483
+ ]);
1484
+ var Config = z.object({
1485
+ allowedOrigins: z.array(z.string()).default([]),
1486
+ requireTotp: z.boolean().default(DEFAULT_REQUIRE_TOTP),
1487
+ sessionHours: z.number().step(1).min(1).default(DEFAULT_SESSION_HOURS),
1488
+ preserveOriginPaths: z.array(z.string()).default([])
1489
+ });
1490
+ function resolveAuthConfig(input, listener) {
1491
+ if (typeof input !== "object" || input === null)
1492
+ throw new Error("auth-remote: config is required");
1493
+ for (const key of Object.keys(input))
1494
+ if (!AUTH_CONFIG_KEYS.has(key))
1495
+ throw new Error(`auth-remote: unknown config key ${JSON.stringify(key)}`);
1496
+ const config = Config(input);
1497
+ if (isIP(listener.host) !== 4) throw new Error("auth-remote: DSH web startup host must be IPv4");
1498
+ if (listener.host === "0.0.0.0")
1499
+ throw new Error("auth-remote: DSH does not support --host 0.0.0.0");
1500
+ if (!Number.isInteger(listener.port) || listener.port < 0 || listener.port > 65535)
1501
+ throw new Error("auth-remote: invalid DSH web startup port");
1502
+ const originPolicy = createOriginPolicy(config.allowedOrigins ?? []);
1503
+ const sessionHours = config.sessionHours ?? DEFAULT_SESSION_HOURS;
1504
+ if (!Number.isSafeInteger(sessionHours) || !Number.isSafeInteger(Date.now() + sessionHours * 36e5)) {
1505
+ throw new Error("auth-remote: sessionHours exceeds the safe timestamp range");
1506
+ }
1507
+ const paths = config.preserveOriginPaths ?? [];
1508
+ const seen = /* @__PURE__ */ new Set();
1509
+ for (const path of paths) {
1510
+ if (!isCanonicalPathPrefix(path)) {
1511
+ throw new Error(`auth-remote: invalid preserveOriginPaths entry ${JSON.stringify(path)}`);
1512
+ }
1513
+ if (seen.has(path))
1514
+ throw new Error(`auth-remote: duplicate preserveOriginPaths entry ${JSON.stringify(path)}`);
1515
+ seen.add(path);
1516
+ }
1517
+ return {
1518
+ host: listener.host,
1519
+ port: listener.port,
1520
+ compression: listener.compression ?? "none",
1521
+ compressionLevel: listener.compressionLevel ?? 1,
1522
+ compressionThresholdBytes: listener.compressionThresholdBytes ?? 1024,
1523
+ allowedOrigins: Object.freeze(originPolicy.registeredOrigins.map((entry) => entry.origin)),
1524
+ originPolicy,
1525
+ requireTotp: config.requireTotp ?? DEFAULT_REQUIRE_TOTP,
1526
+ sessionHours,
1527
+ preserveOriginPaths: paths
1528
+ };
1529
+ }
1530
+ function isCanonicalPathPrefix(path) {
1531
+ if (!path.startsWith("/") || path.length > 1 && path.endsWith("/")) return false;
1532
+ if (/[?#*\\]/u.test(path)) return false;
1533
+ let url;
1534
+ try {
1535
+ url = new URL(path, "http://auth-remote.invalid");
1536
+ } catch {
1537
+ return false;
1538
+ }
1539
+ if (url.pathname !== path || url.search !== "" || url.hash !== "") return false;
1540
+ for (const segment of path.slice(1).split("/")) {
1541
+ if (segment === "" && path !== "/") return false;
1542
+ let decoded;
1543
+ try {
1544
+ decoded = decodeURIComponent(segment);
1545
+ } catch {
1546
+ return false;
1547
+ }
1548
+ if (decoded === "." || decoded === ".." || /[/\\\u0000-\u001f\u007f]/u.test(decoded))
1549
+ return false;
1550
+ }
1551
+ return true;
1552
+ }
1553
+
1554
+ // src/http/connections.ts
1555
+ var AuthConnections = class {
1556
+ constructor(store, auth) {
1557
+ this.auth = auth;
1558
+ this.unsubscribe = store.subscribe((_previous, current) => this.reconcile(current));
1559
+ }
1560
+ auth;
1561
+ active = /* @__PURE__ */ new Set();
1562
+ unsubscribe;
1563
+ trackResponse(hash, session, response) {
1564
+ const entry = this.makeEntry(
1565
+ hash,
1566
+ session.expiresAt,
1567
+ () => new Promise((resolve) => {
1568
+ if (response.destroyed || response.writableEnded) return resolve();
1569
+ response.once("close", () => resolve());
1570
+ response.destroy();
1571
+ })
1572
+ );
1573
+ response.once("close", () => this.remove(entry));
1574
+ response.once("finish", () => this.remove(entry));
1575
+ }
1576
+ trackSocket(hash, session, socket) {
1577
+ const entry = this.makeEntry(
1578
+ hash,
1579
+ session.expiresAt,
1580
+ () => new Promise((resolve) => {
1581
+ if (socket.destroyed) return resolve();
1582
+ socket.once("close", () => resolve());
1583
+ socket.destroy();
1584
+ })
1585
+ );
1586
+ socket.once("close", () => this.remove(entry));
1587
+ }
1588
+ makeEntry(hash, expiresAt, close) {
1589
+ let closing;
1590
+ const entry = {
1591
+ hash,
1592
+ expiresAt,
1593
+ timer: void 0,
1594
+ close: () => closing ??= close()
1595
+ };
1596
+ this.active.add(entry);
1597
+ this.schedule(entry);
1598
+ return entry;
1599
+ }
1600
+ schedule(entry) {
1601
+ if (entry.timer) clearTimeout(entry.timer);
1602
+ const remaining = entry.expiresAt - Date.now();
1603
+ entry.timer = setTimeout(
1604
+ () => {
1605
+ if (entry.expiresAt <= Date.now()) void entry.close();
1606
+ else this.schedule(entry);
1607
+ },
1608
+ Math.max(1, Math.min(remaining, 2147483647))
1609
+ );
1610
+ entry.timer.unref();
1611
+ }
1612
+ remove(entry) {
1613
+ if (!this.active.delete(entry)) return;
1614
+ if (entry.timer) clearTimeout(entry.timer);
1615
+ }
1616
+ async reconcile(state) {
1617
+ const closing = [];
1618
+ for (const entry of this.active) {
1619
+ const session = state.sessions[entry.hash];
1620
+ const account = state.account;
1621
+ if (!session || !account || session.accountId !== account.id || session.securityVersion !== account.securityVersion || session.expiresAt <= Date.now() || this.auth.policySnapshot().requireTotp && !account.totp) {
1622
+ closing.push(entry.close());
1623
+ } else if (entry.expiresAt !== session.expiresAt) {
1624
+ entry.expiresAt = session.expiresAt;
1625
+ this.schedule(entry);
1626
+ }
1627
+ }
1628
+ await Promise.all(closing);
1629
+ }
1630
+ async closeAll() {
1631
+ await Promise.all([...this.active].map((entry) => entry.close()));
1632
+ }
1633
+ async dispose() {
1634
+ this.unsubscribe();
1635
+ await this.closeAll();
1636
+ }
1637
+ };
1638
+
1639
+ // src/http/admin-socket.ts
1640
+ import { createServer } from "node:net";
1641
+ import { chmod, lstat as lstat3, unlink as unlink3 } from "node:fs/promises";
1642
+ import { join as join3 } from "node:path";
1643
+
1644
+ // src/shared/admin-contract.ts
1645
+ var ADMIN_PROTOCOL_VERSION = 1;
1646
+ var ADMIN_MAX_BYTES = 16 * 1024;
1647
+
1648
+ // src/http/admin-socket.ts
1649
+ function errno3(error, code) {
1650
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
1651
+ }
1652
+ function validRequest(value) {
1653
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
1654
+ const row = value;
1655
+ if (row.version !== ADMIN_PROTOCOL_VERSION || typeof row.command !== "string") return null;
1656
+ const allowed = {
1657
+ status: ["version", "command"],
1658
+ init: ["version", "command", "username", "password"],
1659
+ "reset-password": ["version", "command", "password"],
1660
+ "reset-totp": ["version", "command"],
1661
+ "revoke-sessions": ["version", "command"]
1662
+ };
1663
+ const fields = allowed[row.command];
1664
+ if (!fields || Object.keys(row).length !== fields.length || Object.keys(row).some((key) => !fields.includes(key)))
1665
+ return null;
1666
+ if (row.command === "init" && (typeof row.username !== "string" || typeof row.password !== "string"))
1667
+ return null;
1668
+ if (row.command === "reset-password" && typeof row.password !== "string") return null;
1669
+ return row;
1670
+ }
1671
+ function failure(error) {
1672
+ return {
1673
+ version: ADMIN_PROTOCOL_VERSION,
1674
+ ok: false,
1675
+ error: error instanceof PasswordValidationError ? "invalid_input" : error instanceof AuthError ? error.code : "service_unavailable"
1676
+ };
1677
+ }
1678
+ var AdminSocket = class {
1679
+ constructor(profileDir, auth, ready, onUnavailable) {
1680
+ this.auth = auth;
1681
+ this.ready = ready;
1682
+ this.onUnavailable = onUnavailable;
1683
+ this.path = join3(profileDir, STATE_DIR, "admin.sock");
1684
+ }
1685
+ auth;
1686
+ ready;
1687
+ onUnavailable;
1688
+ path;
1689
+ server;
1690
+ inode;
1691
+ sockets = /* @__PURE__ */ new Set();
1692
+ operations = /* @__PURE__ */ new Set();
1693
+ async start() {
1694
+ try {
1695
+ const stale = await lstat3(this.path, { bigint: true });
1696
+ if (!stale.isSocket() || stale.uid !== BigInt(process.getuid?.() ?? -1) || (stale.mode & 0o777n) !== 0o600n)
1697
+ throw new Error("auth-remote: unsafe admin socket path; manual review required");
1698
+ await unlink3(this.path);
1699
+ } catch (error) {
1700
+ if (!errno3(error, "ENOENT")) throw error;
1701
+ }
1702
+ const server = createServer((socket) => this.accept(socket));
1703
+ server.on("error", () => this.onUnavailable());
1704
+ await new Promise((resolve, reject) => {
1705
+ server.once("error", reject);
1706
+ server.listen(this.path, () => {
1707
+ server.off("error", reject);
1708
+ resolve();
1709
+ });
1710
+ });
1711
+ this.server = server;
1712
+ await chmod(this.path, 384);
1713
+ const info = await lstat3(this.path, { bigint: true });
1714
+ if (!info.isSocket() || info.uid !== BigInt(process.getuid?.() ?? -1) || (info.mode & 0o777n) !== 0o600n)
1715
+ throw new Error("auth-remote: unsafe admin socket permissions");
1716
+ this.inode = info.ino;
1717
+ }
1718
+ accept(socket) {
1719
+ this.sockets.add(socket);
1720
+ socket.on("error", () => void 0);
1721
+ socket.once("close", () => this.sockets.delete(socket));
1722
+ socket.setTimeout(1e4, () => socket.destroy());
1723
+ let chunks = [];
1724
+ let bytes = 0;
1725
+ let received = false;
1726
+ socket.on("data", (chunk) => {
1727
+ if (received) return;
1728
+ bytes += chunk.length;
1729
+ if (bytes > ADMIN_MAX_BYTES) {
1730
+ received = true;
1731
+ socket.end(JSON.stringify({ version: 1, ok: false, error: "request_too_large" }) + "\n");
1732
+ return;
1733
+ }
1734
+ chunks.push(chunk);
1735
+ const all = Buffer.concat(chunks);
1736
+ const newline = all.indexOf(10);
1737
+ if (newline < 0) return;
1738
+ received = true;
1739
+ socket.setTimeout(0);
1740
+ if (newline !== all.length - 1) {
1741
+ socket.end(JSON.stringify({ version: 1, ok: false, error: "invalid_request" }) + "\n");
1742
+ return;
1743
+ }
1744
+ chunks = [];
1745
+ let request;
1746
+ try {
1747
+ request = validRequest(JSON.parse(all.subarray(0, newline).toString("utf8")));
1748
+ } catch {
1749
+ request = null;
1750
+ }
1751
+ if (!request) {
1752
+ socket.end(JSON.stringify({ version: 1, ok: false, error: "invalid_request" }) + "\n");
1753
+ return;
1754
+ }
1755
+ const operation = this.respond(socket, request);
1756
+ this.operations.add(operation);
1757
+ void operation.finally(() => this.operations.delete(operation));
1758
+ });
1759
+ }
1760
+ async respond(socket, request) {
1761
+ let response;
1762
+ try {
1763
+ switch (request.command) {
1764
+ case "status": {
1765
+ const status = { ...this.auth.status(), online: true, ready: this.ready() };
1766
+ response = { version: 1, ok: true, result: status };
1767
+ break;
1768
+ }
1769
+ case "init":
1770
+ await this.auth.initialize(request.username, request.password);
1771
+ response = { version: 1, ok: true, result: { ok: true } };
1772
+ break;
1773
+ case "reset-password":
1774
+ await this.auth.resetPassword(request.password);
1775
+ response = { version: 1, ok: true, result: { ok: true } };
1776
+ break;
1777
+ case "reset-totp":
1778
+ await this.auth.resetTotp();
1779
+ response = { version: 1, ok: true, result: { ok: true } };
1780
+ break;
1781
+ case "revoke-sessions":
1782
+ await this.auth.revokeAll();
1783
+ response = { version: 1, ok: true, result: { ok: true } };
1784
+ }
1785
+ } catch (error) {
1786
+ response = failure(error);
1787
+ }
1788
+ if (!socket.destroyed) socket.end(`${JSON.stringify(response)}
1789
+ `);
1790
+ }
1791
+ async dispose() {
1792
+ const server = this.server;
1793
+ this.server = void 0;
1794
+ if (server) {
1795
+ const closed = new Promise((resolve) => server.close(() => resolve()));
1796
+ for (const socket of this.sockets) socket.destroy();
1797
+ await Promise.allSettled(this.operations);
1798
+ await closed;
1799
+ }
1800
+ if (this.inode !== void 0) {
1801
+ try {
1802
+ const current = await lstat3(this.path, { bigint: true });
1803
+ if (current.isSocket() && current.ino === this.inode) await unlink3(this.path);
1804
+ } catch (error) {
1805
+ if (!errno3(error, "ENOENT")) throw error;
1806
+ }
1807
+ this.inode = void 0;
1808
+ }
1809
+ }
1810
+ };
1811
+
1812
+ // src/shared/auth-contract.ts
1813
+ var AUTH_BASE = "/auth-remote";
1814
+ var AUTH_COOKIE = "dsh_auth_remote";
1815
+
1816
+ // src/http/origin.ts
1817
+ function preservePublicOrigin(pathname, prefixes) {
1818
+ return prefixes.some(
1819
+ (prefix) => prefix === "/" || pathname === prefix || pathname.startsWith(`${prefix}/`)
1820
+ );
1821
+ }
1822
+ function stripRootToken(req) {
1823
+ if (!req.url) return;
1824
+ const url = new URL(req.url, "http://auth-remote.invalid");
1825
+ if (url.pathname !== "/" || !url.searchParams.has("token")) return;
1826
+ url.searchParams.delete("token");
1827
+ req.url = url.pathname + url.search + url.hash;
1828
+ }
1829
+
1830
+ // src/http/request-context.ts
1831
+ var contexts = /* @__PURE__ */ new WeakMap();
1832
+ function setRequestContext(req, context) {
1833
+ if (contexts.has(req)) throw new Error("auth-remote: request context already set");
1834
+ contexts.set(req, context);
1835
+ }
1836
+ function requireRequestContext(req) {
1837
+ const context = contexts.get(req);
1838
+ if (!context) throw new Error("auth-remote: missing validated request context");
1839
+ return context;
1840
+ }
1841
+
1842
+ // src/http/routes.ts
1843
+ import { readFileSync as readFileSync2 } from "node:fs";
1844
+ var policies = {
1845
+ [`GET ${AUTH_BASE}/state`]: "public",
1846
+ [`GET ${AUTH_BASE}/login`]: "public",
1847
+ [`GET ${AUTH_BASE}/login.js`]: "public",
1848
+ [`GET ${AUTH_BASE}/login.css`]: "public",
1849
+ [`POST ${AUTH_BASE}/login`]: "public",
1850
+ [`POST ${AUTH_BASE}/mfa/verify`]: "public",
1851
+ [`POST ${AUTH_BASE}/totp/start`]: "public",
1852
+ [`POST ${AUTH_BASE}/totp/confirm`]: "public",
1853
+ [`GET ${AUTH_BASE}/me`]: "session",
1854
+ [`POST ${AUTH_BASE}/password`]: "session",
1855
+ [`POST ${AUTH_BASE}/totp/disable`]: "session",
1856
+ [`POST ${AUTH_BASE}/revoke-sessions`]: "session",
1857
+ [`POST ${AUTH_BASE}/logout`]: "logout"
1858
+ };
1859
+ function routePermission(method, pathname) {
1860
+ return policies[`${method ?? ""} ${pathname}`] ?? null;
1861
+ }
1862
+ var HttpFailure = class extends Error {
1863
+ constructor(status, code) {
1864
+ super(code);
1865
+ this.status = status;
1866
+ this.code = code;
1867
+ }
1868
+ status;
1869
+ code;
1870
+ };
1871
+ function stringField(body, field) {
1872
+ const value = body[field];
1873
+ if (typeof value !== "string") throw new HttpFailure(400, "invalid_input");
1874
+ return value;
1875
+ }
1876
+ function optionalStringField(body, field) {
1877
+ const value = body[field];
1878
+ if (value === void 0) return void 0;
1879
+ if (typeof value !== "string") throw new HttpFailure(400, "invalid_input");
1880
+ return value;
1881
+ }
1882
+ async function readJsonBody(req) {
1883
+ const declared = Number(req.headers["content-length"]);
1884
+ if (Number.isFinite(declared) && declared > 16 * 1024)
1885
+ throw new HttpFailure(413, "body_too_large");
1886
+ if (!/^application\/json(?:\s*;|$)/iu.test(String(req.headers["content-type"] ?? "")))
1887
+ throw new HttpFailure(415, "unsupported_media_type");
1888
+ return new Promise((resolve, reject) => {
1889
+ let done = false;
1890
+ let bytes = 0;
1891
+ const chunks = [];
1892
+ const cleanup = () => {
1893
+ clearTimeout(timer);
1894
+ req.off("data", onData);
1895
+ req.off("end", onEnd);
1896
+ req.off("error", onError);
1897
+ req.off("aborted", onAbort);
1898
+ };
1899
+ const fail = (error) => {
1900
+ if (done) return;
1901
+ done = true;
1902
+ req.pause();
1903
+ cleanup();
1904
+ reject(error);
1905
+ };
1906
+ const onData = (chunk) => {
1907
+ bytes += chunk.length;
1908
+ if (bytes > 16 * 1024) fail(new HttpFailure(413, "body_too_large"));
1909
+ else chunks.push(chunk);
1910
+ };
1911
+ const onEnd = () => {
1912
+ if (done) return;
1913
+ done = true;
1914
+ cleanup();
1915
+ try {
1916
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
1917
+ if (typeof body !== "object" || body === null || Array.isArray(body))
1918
+ throw new HttpFailure(400, "invalid_input");
1919
+ resolve(body);
1920
+ } catch {
1921
+ reject(new HttpFailure(400, "invalid_json"));
1922
+ }
1923
+ };
1924
+ const onError = (error) => fail(error);
1925
+ const onAbort = () => fail(new HttpFailure(408, "request_aborted"));
1926
+ const timer = setTimeout(() => fail(new HttpFailure(408, "request_timeout")), 1e4);
1927
+ req.on("data", onData);
1928
+ req.once("end", onEnd);
1929
+ req.once("error", onError);
1930
+ req.once("aborted", onAbort);
1931
+ });
1932
+ }
1933
+ function sendJson(res, status, body, headers = {}) {
1934
+ res.writeHead(status, {
1935
+ "cache-control": "no-store",
1936
+ "content-type": "application/json; charset=utf-8",
1937
+ ...headers
1938
+ });
1939
+ res.end(JSON.stringify(body));
1940
+ }
1941
+ function cookieToken(req) {
1942
+ const header = req.headers.cookie;
1943
+ if (typeof header !== "string") return null;
1944
+ const values = header.split(";").map((part) => part.trim()).filter((part) => part.startsWith(`${AUTH_COOKIE}=`));
1945
+ if (values.length !== 1) return null;
1946
+ return values[0].slice(AUTH_COOKIE.length + 1);
1947
+ }
1948
+ function currentSessionToken(req) {
1949
+ return cookieToken(req);
1950
+ }
1951
+ function cookieHeader(token, expiresAt, secure) {
1952
+ const maxAge = Math.max(0, Math.floor((expiresAt - Date.now()) / 1e3));
1953
+ return `${AUTH_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
1954
+ }
1955
+ function clearCookieHeader(secure) {
1956
+ return `${AUTH_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure ? "; Secure" : ""}`;
1957
+ }
1958
+ function cookieResponse(mayWriteCookie, value) {
1959
+ if (!mayWriteCookie) throw new HttpFailure(403, "invalid_origin");
1960
+ return { "set-cookie": value };
1961
+ }
1962
+ function loginAsset(name2) {
1963
+ const source = import.meta.url.endsWith("/src/http/routes.ts");
1964
+ const base = new URL(source ? "../../dist/" : "./", import.meta.url);
1965
+ return readFileSync2(new URL(name2, base), "utf8");
1966
+ }
1967
+ function errorStatus(error) {
1968
+ if (error instanceof HttpFailure) return { status: error.status, body: { error: error.code } };
1969
+ if (error instanceof PasswordValidationError)
1970
+ return { status: 400, body: { error: "invalid_input" } };
1971
+ if (error instanceof AuthError) {
1972
+ const retryAfter = error.retryAfter ?? (error.code === "busy" ? 1 : void 0);
1973
+ const status = {
1974
+ invalid_input: 400,
1975
+ uninitialized: 409,
1976
+ already_initialized: 409,
1977
+ invalid_credentials: 401,
1978
+ invalid_factor: 401,
1979
+ invalid_challenge: 400,
1980
+ challenge_expired: 410,
1981
+ unauthorized: 401,
1982
+ rate_limited: 429,
1983
+ busy: 429,
1984
+ conflict: 409,
1985
+ totp_required: 403
1986
+ };
1987
+ return {
1988
+ status: status[error.code] ?? 500,
1989
+ body: { error: error.code, ...retryAfter ? { retryAfter } : {} },
1990
+ ...retryAfter ? { retryAfter: String(retryAfter) } : {}
1991
+ };
1992
+ }
1993
+ return { status: 503, body: { error: "service_unavailable" } };
1994
+ }
1995
+ var AuthRoutes = class {
1996
+ constructor(auth, profileName) {
1997
+ this.auth = auth;
1998
+ this.profileName = profileName;
1999
+ }
2000
+ auth;
2001
+ profileName;
2002
+ install(server) {
2003
+ const paths = new Set(Object.keys(policies).map((row) => row.slice(row.indexOf(" ") + 1)));
2004
+ for (const path of paths)
2005
+ server.register({
2006
+ kind: "exact",
2007
+ path,
2008
+ handler: (req, res) => this.handle(req, res, path)
2009
+ });
2010
+ }
2011
+ async handle(req, res, path) {
2012
+ const route = `${req.method ?? ""} ${path}`;
2013
+ try {
2014
+ const context = requireRequestContext(req);
2015
+ const secure = context.protocol === "https:";
2016
+ switch (route) {
2017
+ case `GET ${AUTH_BASE}/state`: {
2018
+ const status = this.auth.status();
2019
+ const body = {
2020
+ initialized: status.initialized,
2021
+ requireTotp: this.auth.policySnapshot().requireTotp,
2022
+ profileName: this.profileName
2023
+ };
2024
+ sendJson(res, 200, body);
2025
+ return;
2026
+ }
2027
+ case `GET ${AUTH_BASE}/login`: {
2028
+ res.writeHead(200, {
2029
+ "cache-control": "no-store",
2030
+ "content-type": "text/html; charset=utf-8",
2031
+ "content-security-policy": "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'",
2032
+ "x-content-type-options": "nosniff",
2033
+ "referrer-policy": "no-referrer"
2034
+ });
2035
+ res.end(
2036
+ '<!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>'
2037
+ );
2038
+ return;
2039
+ }
2040
+ case `GET ${AUTH_BASE}/login.js`:
2041
+ case `GET ${AUTH_BASE}/login.css`: {
2042
+ const asset = loginAsset(route.endsWith(".css") ? "login.css" : "login.js");
2043
+ res.writeHead(200, {
2044
+ "cache-control": "no-store",
2045
+ "content-type": route.endsWith(".css") ? "text/css; charset=utf-8" : "text/javascript; charset=utf-8",
2046
+ "x-content-type-options": "nosniff"
2047
+ });
2048
+ res.end(asset);
2049
+ return;
2050
+ }
2051
+ case `POST ${AUTH_BASE}/login`: {
2052
+ const body = await readJsonBody(req);
2053
+ const result = await this.auth.login(
2054
+ stringField(body, "username"),
2055
+ stringField(body, "password")
2056
+ );
2057
+ if (result.kind === "session") {
2058
+ const response = { kind: "session", expiresAt: result.expiresAt };
2059
+ sendJson(res, 200, response, {
2060
+ ...cookieResponse(
2061
+ context.mayWriteCookie,
2062
+ cookieHeader(result.token, result.expiresAt, secure)
2063
+ )
2064
+ });
2065
+ } else if (result.kind === "binding") {
2066
+ const response = {
2067
+ kind: "binding",
2068
+ challenge: result.challenge,
2069
+ expiresAt: result.expiresAt
2070
+ };
2071
+ sendJson(res, 200, response);
2072
+ } else sendJson(res, 200, result);
2073
+ return;
2074
+ }
2075
+ case `POST ${AUTH_BASE}/mfa/verify`: {
2076
+ const body = await readJsonBody(req);
2077
+ const result = await this.auth.verifyMfa(
2078
+ stringField(body, "challenge"),
2079
+ stringField(body, "code")
2080
+ );
2081
+ sendJson(
2082
+ res,
2083
+ 200,
2084
+ { kind: "session", expiresAt: result.expiresAt },
2085
+ {
2086
+ ...cookieResponse(
2087
+ context.mayWriteCookie,
2088
+ cookieHeader(result.token, result.expiresAt, secure)
2089
+ )
2090
+ }
2091
+ );
2092
+ return;
2093
+ }
2094
+ case `POST ${AUTH_BASE}/totp/start`: {
2095
+ const body = await readJsonBody(req);
2096
+ if (typeof body.challenge === "string") {
2097
+ sendJson(res, 200, this.auth.bindingDetails(body.challenge));
2098
+ } else {
2099
+ const token = cookieToken(req);
2100
+ if (!token) throw new AuthError("unauthorized");
2101
+ const result = await this.auth.startBinding(
2102
+ token,
2103
+ stringField(body, "password"),
2104
+ optionalStringField(body, "currentCode")
2105
+ );
2106
+ sendJson(res, 200, result);
2107
+ }
2108
+ return;
2109
+ }
2110
+ case `POST ${AUTH_BASE}/totp/confirm`: {
2111
+ const body = await readJsonBody(req);
2112
+ sendJson(
2113
+ res,
2114
+ 200,
2115
+ await this.auth.confirmBinding(
2116
+ stringField(body, "challenge"),
2117
+ stringField(body, "code")
2118
+ ),
2119
+ cookieResponse(context.mayWriteCookie, clearCookieHeader(secure))
2120
+ );
2121
+ return;
2122
+ }
2123
+ case `GET ${AUTH_BASE}/me`: {
2124
+ const token = cookieToken(req);
2125
+ if (!token) throw new AuthError("unauthorized");
2126
+ const me = this.auth.me(token);
2127
+ const body = { ...me, requireTotp: this.auth.policySnapshot().requireTotp };
2128
+ sendJson(res, 200, body);
2129
+ return;
2130
+ }
2131
+ case `POST ${AUTH_BASE}/password`: {
2132
+ const body = await readJsonBody(req);
2133
+ const token = cookieToken(req);
2134
+ if (!token) throw new AuthError("unauthorized");
2135
+ await this.auth.changePassword(
2136
+ token,
2137
+ stringField(body, "currentPassword"),
2138
+ optionalStringField(body, "currentCode"),
2139
+ stringField(body, "newPassword")
2140
+ );
2141
+ sendJson(
2142
+ res,
2143
+ 200,
2144
+ { ok: true },
2145
+ cookieResponse(context.mayWriteCookie, clearCookieHeader(secure))
2146
+ );
2147
+ return;
2148
+ }
2149
+ case `POST ${AUTH_BASE}/totp/disable`: {
2150
+ const body = await readJsonBody(req);
2151
+ const token = cookieToken(req);
2152
+ if (!token) throw new AuthError("unauthorized");
2153
+ await this.auth.disableTotp(
2154
+ token,
2155
+ stringField(body, "password"),
2156
+ stringField(body, "currentCode")
2157
+ );
2158
+ sendJson(
2159
+ res,
2160
+ 200,
2161
+ { ok: true },
2162
+ cookieResponse(context.mayWriteCookie, clearCookieHeader(secure))
2163
+ );
2164
+ return;
2165
+ }
2166
+ case `POST ${AUTH_BASE}/revoke-sessions`: {
2167
+ const body = await readJsonBody(req);
2168
+ const token = cookieToken(req);
2169
+ if (!token) throw new AuthError("unauthorized");
2170
+ await this.auth.revokeWithCredentials(
2171
+ token,
2172
+ stringField(body, "password"),
2173
+ optionalStringField(body, "currentCode")
2174
+ );
2175
+ sendJson(
2176
+ res,
2177
+ 200,
2178
+ { ok: true },
2179
+ cookieResponse(context.mayWriteCookie, clearCookieHeader(secure))
2180
+ );
2181
+ return;
2182
+ }
2183
+ case `POST ${AUTH_BASE}/logout`:
2184
+ if (req.headers["transfer-encoding"] || Number(req.headers["content-length"] ?? 0) > 0)
2185
+ await readJsonBody(req);
2186
+ await this.auth.logout(cookieToken(req) ?? "");
2187
+ sendJson(
2188
+ res,
2189
+ 200,
2190
+ { ok: true },
2191
+ cookieResponse(context.mayWriteCookie, clearCookieHeader(secure))
2192
+ );
2193
+ return;
2194
+ default:
2195
+ sendJson(res, 405, { error: "method_not_allowed" });
2196
+ }
2197
+ } catch (error) {
2198
+ if (res.headersSent) {
2199
+ res.destroy();
2200
+ return;
2201
+ }
2202
+ const failure2 = errorStatus(error);
2203
+ const terminateBody = failure2.status === 413 || failure2.status === 408 || failure2.status === 415;
2204
+ sendJson(res, failure2.status, failure2.body, {
2205
+ ...failure2.retryAfter ? { "retry-after": failure2.retryAfter } : {},
2206
+ ...terminateBody ? { connection: "close" } : {}
2207
+ });
2208
+ if (terminateBody)
2209
+ res.once("finish", () => {
2210
+ req.resume();
2211
+ req.socket.end();
2212
+ });
2213
+ }
2214
+ }
2215
+ };
2216
+
2217
+ // src/http/gate.ts
2218
+ function rejectHttp(res, status, code) {
2219
+ res.writeHead(status, {
2220
+ "cache-control": "no-store",
2221
+ "content-type": "application/json; charset=utf-8"
2222
+ });
2223
+ res.end(JSON.stringify({ error: code }));
2224
+ }
2225
+ function rejectUpgrade(socket, status, reason) {
2226
+ socket.end(`HTTP/1.1 ${status} ${reason}\r
2227
+ Connection: close\r
2228
+ \r
2229
+ `);
2230
+ }
2231
+ function downstreamCookie(original, native) {
2232
+ const name2 = native.slice(0, native.indexOf("="));
2233
+ const unrelated = (original ?? "").split(";").map((part) => part.trim()).filter((part) => {
2234
+ if (!part) return false;
2235
+ const split = part.indexOf("=");
2236
+ const key = (split < 0 ? part : part.slice(0, split)).trim();
2237
+ return key !== name2 && key !== AUTH_COOKIE;
2238
+ });
2239
+ return [...unrelated, native].join("; ");
2240
+ }
2241
+ var AuthGate = class {
2242
+ constructor(serverPort, config, store, auth, readiness, connections) {
2243
+ this.serverPort = serverPort;
2244
+ this.config = config;
2245
+ this.store = store;
2246
+ this.auth = auth;
2247
+ this.readiness = readiness;
2248
+ this.connections = connections;
2249
+ }
2250
+ serverPort;
2251
+ config;
2252
+ store;
2253
+ auth;
2254
+ readiness;
2255
+ connections;
2256
+ ready() {
2257
+ return this.store.healthy() && this.readiness.ready();
2258
+ }
2259
+ async http(req, res, next) {
2260
+ const raw = evaluateRequestOrigin(this.config.originPolicy, {
2261
+ rawHeaders: req.rawHeaders,
2262
+ method: req.method,
2263
+ target: req.url
2264
+ });
2265
+ if (!raw) return rejectHttp(res, 403, "invalid_origin");
2266
+ if (!this.ready()) return rejectHttp(res, 503, "service_unavailable");
2267
+ setRequestContext(req, raw);
2268
+ const permission = routePermission(req.method, raw.pathname);
2269
+ if (permission === "public" || permission === "logout") return next();
2270
+ const token = currentSessionToken(req);
2271
+ const session = token ? this.auth.session(token) : null;
2272
+ if (!session) {
2273
+ const accept = String(req.headers.accept ?? "");
2274
+ const navigation = req.method === "GET" && !raw.pathname.startsWith("/api") && !raw.pathname.startsWith(AUTH_BASE) && (accept.includes("text/html") || req.headers["sec-fetch-mode"] === "navigate");
2275
+ if (navigation) {
2276
+ const location = new URL(`${AUTH_BASE}/login`, raw.origin);
2277
+ location.searchParams.set("return", raw.returnPath);
2278
+ res.writeHead(302, {
2279
+ "cache-control": "no-store",
2280
+ location: location.pathname + location.search
2281
+ });
2282
+ res.end();
2283
+ return;
2284
+ }
2285
+ return rejectHttp(res, 401, "unauthorized");
2286
+ }
2287
+ if (permission === "session") return next();
2288
+ try {
2289
+ this.bridge(req, raw);
2290
+ } catch {
2291
+ this.readiness.detach();
2292
+ return rejectHttp(res, 503, "service_unavailable");
2293
+ }
2294
+ stripRootToken(req);
2295
+ this.connections.trackResponse(
2296
+ // The token has already been checked by AuthService.
2297
+ this.hash(token),
2298
+ session,
2299
+ res
2300
+ );
2301
+ await next();
2302
+ }
2303
+ async upgrade(req, socket, _head, next) {
2304
+ const raw = evaluateRequestOrigin(this.config.originPolicy, {
2305
+ rawHeaders: req.rawHeaders,
2306
+ method: req.method,
2307
+ target: req.url,
2308
+ upgrade: true
2309
+ });
2310
+ if (!raw) return rejectUpgrade(socket, 403, "Forbidden");
2311
+ if (!this.ready()) return rejectUpgrade(socket, 503, "Service Unavailable");
2312
+ setRequestContext(req, raw);
2313
+ const token = currentSessionToken(req);
2314
+ const session = token ? this.auth.session(token) : null;
2315
+ if (!session) return rejectUpgrade(socket, 401, "Unauthorized");
2316
+ try {
2317
+ this.bridge(req, raw);
2318
+ } catch {
2319
+ this.readiness.detach();
2320
+ return rejectUpgrade(socket, 503, "Service Unavailable");
2321
+ }
2322
+ this.connections.trackSocket(this.hash(token), session, socket);
2323
+ await next();
2324
+ }
2325
+ hash(token) {
2326
+ return sessionHash(token);
2327
+ }
2328
+ bridge(req, context) {
2329
+ const preserve = preservePublicOrigin(context.pathname, this.config.preserveOriginPaths);
2330
+ const authority = preserve ? context.downstreamAuthority : `127.0.0.1:${String(this.serverPort())}`;
2331
+ const origin = preserve ? context.origin : `http://${authority}`;
2332
+ const native = this.readiness.nativeCookie(authority, origin);
2333
+ req.headers.cookie = downstreamCookie(req.headers.cookie, native);
2334
+ req.headers.host = authority;
2335
+ if (req.headers.origin !== void 0) req.headers.origin = origin;
2336
+ }
2337
+ };
2338
+
2339
+ // src/index.ts
2340
+ var name = "auth-remote";
2341
+ var AuthRemoteWebServer = class extends GuardedWebServer {
2342
+ static Config = Config;
2343
+ stateStore;
2344
+ authService;
2345
+ resolved;
2346
+ switchGate;
2347
+ constructor(ctx, input) {
2348
+ const startup = ctx.get("webStartup");
2349
+ if (!startup) throw new Error("auth-remote: webStartup service is required");
2350
+ const config = resolveAuthConfig(input, {
2351
+ host: startup.host ?? DEFAULT_WEB_HOST,
2352
+ port: startup.port ?? DEFAULT_WEB_PORT,
2353
+ compression: "none"
2354
+ });
2355
+ assertWebServerCompatibility(ctx);
2356
+ const gate = new SwitchGate();
2357
+ super(ctx, config, gate);
2358
+ this.resolved = config;
2359
+ this.switchGate = gate;
2360
+ installAuthenticatedHostCapability(ctx);
2361
+ }
2362
+ async [Service.init]() {
2363
+ const profile = this.ctx.get("profileContext");
2364
+ if (!profile?.dir) throw new Error("dsh-auth-remote: profileContext is required for storage");
2365
+ const profileName = profile.name ?? basename(profile.dir);
2366
+ let readiness;
2367
+ let connections;
2368
+ let admin;
2369
+ const store = await AuthStateStore.open(profile.dir, {
2370
+ onUnavailable: () => {
2371
+ this.switchGate.set(new DenyGate());
2372
+ readiness?.detach();
2373
+ if (connections) void connections.closeAll();
2374
+ }
2375
+ });
2376
+ try {
2377
+ const auth = new AuthService(store, {
2378
+ requireTotp: this.resolved.requireTotp,
2379
+ sessionHours: this.resolved.sessionHours
2380
+ });
2381
+ await auth.enforceCurrentPolicy();
2382
+ this.stateStore = store;
2383
+ this.authService = auth;
2384
+ connections = new AuthConnections(store, auth);
2385
+ readiness = new DshReadiness(this, this.resolved, () => {
2386
+ if (connections) void connections.closeAll();
2387
+ });
2388
+ this.switchGate.set(
2389
+ new AuthGate(() => this.port, this.resolved, store, auth, readiness, connections)
2390
+ );
2391
+ new AuthRoutes(auth, profileName).install(this);
2392
+ admin = new AdminSocket(
2393
+ profile.dir,
2394
+ auth,
2395
+ () => this.switchGate.ready(),
2396
+ () => {
2397
+ this.switchGate.set(new DenyGate());
2398
+ readiness?.detach();
2399
+ if (connections) void connections.closeAll();
2400
+ }
2401
+ );
2402
+ await admin.start();
2403
+ const activeConnections = connections;
2404
+ const activeReadiness = readiness;
2405
+ const activeAdmin = admin;
2406
+ this.ctx.effect(
2407
+ () => async () => {
2408
+ this.switchGate.set(new DenyGate());
2409
+ activeReadiness.detach();
2410
+ await activeAdmin.dispose();
2411
+ await activeConnections.dispose();
2412
+ auth.dispose();
2413
+ await store.close();
2414
+ },
2415
+ "auth-remote.storage-and-gate"
2416
+ );
2417
+ await super[Service.init]();
2418
+ let announced = false;
2419
+ watchConnection(this.ctx, readiness, () => {
2420
+ const loader = this.ctx.get("loader");
2421
+ const settled = loader?.await() ?? Promise.resolve();
2422
+ void settled.then(() => {
2423
+ if (announced || !activeReadiness.ready()) return;
2424
+ announced = true;
2425
+ console.log(startupLines(profileName, this.resolved, this.port).join("\n"));
2426
+ }).catch(() => {
2427
+ });
2428
+ });
2429
+ } catch (error) {
2430
+ this.switchGate.set(new DenyGate());
2431
+ await admin?.dispose();
2432
+ await connections?.dispose();
2433
+ this.authService?.dispose();
2434
+ await store.close();
2435
+ throw error;
2436
+ }
2437
+ }
2438
+ get storage() {
2439
+ if (!this.stateStore) throw new Error("dsh-auth-remote: storage is not initialized");
2440
+ return this.stateStore;
2441
+ }
2442
+ get authentication() {
2443
+ if (!this.authService) throw new Error("dsh-auth-remote: authentication is not initialized");
2444
+ return this.authService;
2445
+ }
2446
+ /** Public authorities needed by native Connection for preserved routes. */
2447
+ get connectionTrustedHosts() {
2448
+ if (this.resolved.preserveOriginPaths.length === 0) return [];
2449
+ return this.resolved.originPolicy.registeredOrigins.map((entry) => entry.host);
2450
+ }
2451
+ };
2452
+ var src_default = AuthRemoteWebServer;
2453
+ export {
2454
+ AuthConnections,
2455
+ AuthError,
2456
+ AuthGate,
2457
+ AuthRemoteWebServer,
2458
+ AuthService,
2459
+ AuthStateStore,
2460
+ Config,
2461
+ DEFAULT_REQUIRE_TOTP,
2462
+ DEFAULT_SESSION_HOURS,
2463
+ DshReadiness,
2464
+ GuardedWebServer,
2465
+ READY_PATH,
2466
+ READY_PROTOCOL_VERSION,
2467
+ src_default as default,
2468
+ installAuthenticatedHostCapability,
2469
+ name,
2470
+ resolveAuthConfig,
2471
+ watchConnection
2472
+ };
2473
+ //# sourceMappingURL=index.js.map