dsh-auth-remote 0.1.3 → 0.1.6

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 (40) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CHANGELOG.zh-CN.md +14 -0
  3. package/CONTRIBUTING.md +2 -0
  4. package/CONTRIBUTING.zh-CN.md +2 -0
  5. package/README.md +16 -10
  6. package/README.zh-CN.md +16 -10
  7. package/cordis.patch.yml +4 -5
  8. package/dist/client.js +2 -2
  9. package/dist/client.js.map +2 -2
  10. package/dist/index.js +280 -87
  11. package/dist/index.js.map +4 -4
  12. package/dist/types/adapters/dsh/browser-auth.d.ts +3 -0
  13. package/dist/types/adapters/dsh/browser-auth.d.ts.map +1 -1
  14. package/dist/types/adapters/dsh/public-url.d.ts +10 -0
  15. package/dist/types/adapters/dsh/public-url.d.ts.map +1 -0
  16. package/dist/types/adapters/dsh/readiness.d.ts +2 -3
  17. package/dist/types/adapters/dsh/readiness.d.ts.map +1 -1
  18. package/dist/types/adapters/dsh/runtime-capabilities.d.ts +46 -0
  19. package/dist/types/adapters/dsh/runtime-capabilities.d.ts.map +1 -0
  20. package/dist/types/adapters/dsh/startup-urls.d.ts +2 -2
  21. package/dist/types/adapters/dsh/startup-urls.d.ts.map +1 -1
  22. package/dist/types/adapters/dsh/webserver.d.ts +8 -2
  23. package/dist/types/adapters/dsh/webserver.d.ts.map +1 -1
  24. package/dist/types/config.d.ts +48 -14
  25. package/dist/types/config.d.ts.map +1 -1
  26. package/dist/types/http/gate.d.ts +1 -2
  27. package/dist/types/http/gate.d.ts.map +1 -1
  28. package/dist/types/index.d.ts +6 -2
  29. package/dist/types/index.d.ts.map +1 -1
  30. package/docs/deployment.md +83 -38
  31. package/docs/deployment.zh-CN.md +84 -39
  32. package/docs/development.md +11 -5
  33. package/docs/development.zh-CN.md +11 -5
  34. package/docs/legacy-compatibility.md +115 -0
  35. package/docs/releasing.md +7 -5
  36. package/docs/releasing.zh-CN.md +7 -5
  37. package/docs/reverse-proxy.md +7 -5
  38. package/docs/reverse-proxy.zh-CN.md +7 -5
  39. package/examples/web-profile-auth-remote.patch.yml +7 -3
  40. package/package.json +19 -10
package/dist/index.js CHANGED
@@ -68,6 +68,10 @@ function installAuthenticatedHostCapability(ctx) {
68
68
 
69
69
  // src/adapters/dsh/browser-auth.ts
70
70
  var NativeBrowserAuth = class {
71
+ constructor(protocol = "http:") {
72
+ this.protocol = protocol;
73
+ }
74
+ protocol;
71
75
  cookies = /* @__PURE__ */ new WeakMap();
72
76
  cookieFor(connection, authority, origin, now = Date.now()) {
73
77
  let byAuthority = this.cookies.get(connection);
@@ -77,7 +81,7 @@ var NativeBrowserAuth = class {
77
81
  }
78
82
  let cookie = byAuthority.get(authority);
79
83
  if (cookie === void 0 || now >= cookie.expiresAt - 6e4) {
80
- cookie = exchange(connection, authority, now);
84
+ cookie = exchange(connection, authority, this.protocol, now);
81
85
  byAuthority.set(authority, cookie);
82
86
  }
83
87
  const rejection = connection.requestRejection({
@@ -95,10 +99,11 @@ var NativeBrowserAuth = class {
95
99
  this.cookies.delete(connection);
96
100
  }
97
101
  };
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
+ function exchange(connection, authority, protocol, now) {
103
+ const baseUrl = new URL(`${protocol}//${authority}/`);
104
+ const tokenUrl = new URL(connection.authenticatedUrl(baseUrl.href));
105
+ const normalizedAuthority = baseUrl.host;
106
+ if (tokenUrl.protocol !== protocol || tokenUrl.host !== normalizedAuthority || tokenUrl.pathname !== "/" || tokenUrl.searchParams.getAll("token").length !== 1) {
102
107
  throw new Error("auth-remote: native Connection returned an invalid token URL");
103
108
  }
104
109
  let status;
@@ -121,6 +126,8 @@ function exchange(connection, authority, now) {
121
126
  throw new Error("auth-remote: native Connection token exchange failed");
122
127
  }
123
128
  const [pair, ...attributes] = setCookie.split(";").map((part) => part.trim());
129
+ if (attributes.some((attribute) => /^secure$/iu.test(attribute)) !== (protocol === "https:"))
130
+ throw new Error("auth-remote: native Connection returned a Cookie for the wrong protocol");
124
131
  if (pair === void 0 || !/^[^=;\s]+=([^;\s]*)$/u.test(pair)) {
125
132
  throw new Error("auth-remote: native Connection returned an invalid Cookie");
126
133
  }
@@ -135,16 +142,15 @@ function exchange(connection, authority, now) {
135
142
 
136
143
  // src/adapters/dsh/readiness.ts
137
144
  var DshReadiness = class {
138
- constructor(server, config, onUnavailable = () => {
145
+ constructor(_server, config, onUnavailable = () => {
139
146
  }) {
140
- this.server = server;
141
147
  this.config = config;
142
148
  this.onUnavailable = onUnavailable;
149
+ this.native = new NativeBrowserAuth(config.protocol);
143
150
  }
144
- server;
145
151
  config;
146
152
  onUnavailable;
147
- native = new NativeBrowserAuth();
153
+ native;
148
154
  connection;
149
155
  isReady = false;
150
156
  ready() {
@@ -156,9 +162,8 @@ var DshReadiness = class {
156
162
  attach(connection, profileAnchor) {
157
163
  this.detach();
158
164
  assertConnectionCompatibility(connection, profileAnchor);
159
- const localAuthority = `127.0.0.1:${String(this.server.port)}`;
160
165
  try {
161
- this.native.cookieFor(connection, localAuthority, `http://${localAuthority}`);
166
+ this.native.cookieFor(connection, this.config.nativeAuthority, this.config.nativeOrigin);
162
167
  if (this.config.preserveOriginPaths.length > 0)
163
168
  for (const entry of this.config.originPolicy.registeredOrigins)
164
169
  this.native.cookieFor(connection, entry.host, entry.origin);
@@ -186,12 +191,18 @@ var DshReadiness = class {
186
191
  }
187
192
  };
188
193
  function watchConnection(ctx, readiness, onReady = () => {
194
+ }, onFailure = async () => {
189
195
  }) {
190
196
  ctx.inject(["connection"], (connectionCtx) => {
191
197
  const connection = connectionCtx.get("connection");
192
198
  const profile = ctx.get("profileContext");
193
199
  connectionCtx.effect(() => {
194
- readiness.attach(connection, profile?.installAnchor);
200
+ try {
201
+ readiness.attach(connection, profile?.installAnchor);
202
+ } catch (error) {
203
+ void onFailure(error).catch((reason) => connectionCtx.logger.error(reason));
204
+ throw error;
205
+ }
195
206
  onReady();
196
207
  return () => {
197
208
  readiness.detach(connection);
@@ -201,17 +212,20 @@ function watchConnection(ctx, readiness, onReady = () => {
201
212
  }
202
213
 
203
214
  // 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
- }
215
+ function startupLines(profile, config) {
216
+ const lines = [`dsh ${profile} start at`, ` ${config.listenerUrl.replace(/\/$/u, "")}`];
217
+ if (config.publicUrl !== config.listenerUrl)
218
+ lines.push("", "public access at", ` ${config.publicUrl.replace(/\/$/u, "")}`);
210
219
  return lines;
211
220
  }
212
221
 
213
- // src/adapters/dsh/webserver.ts
214
- import WebServer2 from "@deepseek-ai/dsh-host-webserver";
222
+ // src/adapters/dsh/runtime-capabilities.ts
223
+ import * as NativeWebServer from "@deepseek-ai/dsh-host-webserver";
224
+ import { isIP as isIP2 } from "node:net";
225
+ import semver2 from "semver";
226
+
227
+ // src/adapters/dsh/public-url.ts
228
+ import { isIP } from "node:net";
215
229
 
216
230
  // src/http/origin-policy.ts
217
231
  function defaultPort(protocol) {
@@ -396,7 +410,83 @@ function evaluateRequestOrigin(policy, request) {
396
410
  });
397
411
  }
398
412
 
413
+ // src/adapters/dsh/public-url.ts
414
+ function parsePublicUrl(value) {
415
+ if (typeof value !== "string" || !/^https?:\/\/[^/?#]+\/?$/iu.test(value) || /[\\\s\u0000-\u001f\u007f]/u.test(value))
416
+ throw new Error("auth-remote: publicUrl must be an absolute HTTP(S) root URL");
417
+ const originInput = value.endsWith("/") ? value.slice(0, -1) : value;
418
+ try {
419
+ const policy = createOriginPolicy([originInput]);
420
+ const origin = policy.registeredOrigins[0].origin;
421
+ return Object.freeze({ url: new URL(origin).href, origin });
422
+ } catch {
423
+ throw new Error("auth-remote: invalid publicUrl authority");
424
+ }
425
+ }
426
+ function listenerPublicUrl(host, port, protocol) {
427
+ if (isIP(host) === 0 || host.includes("%") || !Number.isInteger(port) || port < 1 || port > 65535)
428
+ throw new Error("auth-remote: listener cannot form a root URL; configure explicit publicUrl");
429
+ const authority = isIP(host) === 6 ? `[${host}]` : host;
430
+ const url = new URL(`${protocol}//${authority}:${port}/`);
431
+ if (["0.0.0.0", "[::]", "[::ffff:0:0]"].includes(url.hostname))
432
+ throw new Error("auth-remote: wildcard listener cannot form a publicUrl");
433
+ return url.href;
434
+ }
435
+
436
+ // src/adapters/dsh/runtime-capabilities.ts
437
+ function getRuntimeCapabilities(version) {
438
+ if (!semver2.satisfies(version, SUPPORTED_DSH_RANGE, { includePrerelease: true }))
439
+ throw new Error(`auth-remote: unsupported DSH version ${version}`);
440
+ return Object.freeze({
441
+ version,
442
+ publicUrl: semver2.gte(version, "0.2.1-alpha.1"),
443
+ nativeTransport: semver2.gte(version, "0.2.1-alpha.2")
444
+ });
445
+ }
446
+ function validateListenerConfig(capabilities, config, native = NativeWebServer) {
447
+ if (!Number.isInteger(config.port) || config.port < 0 || config.port > 65535)
448
+ throw new Error("auth-remote: invalid web listener port");
449
+ if (!capabilities.nativeTransport) {
450
+ if (config.tls) throw new Error("auth-remote: this DSH version does not support TLS");
451
+ if (isIP2(config.host) !== 4)
452
+ throw new Error("auth-remote: this DSH version supports only concrete IPv4, not IPv6");
453
+ if (config.host === "0.0.0.0") throw new Error("auth-remote: wildcard binding is not supported");
454
+ return { ...config, compression: config.compression ?? "none" };
455
+ }
456
+ if (typeof native.default.Config !== "function" || typeof Object.getOwnPropertyDescriptor(native.default.prototype, "protocol")?.get !== "function" || typeof native.isLoopbackHost !== "function" || typeof native.isWildcardHost !== "function" || typeof native.normalizeBindAddress !== "function")
457
+ throw new Error("auth-remote: DSH lacks native transport capabilities");
458
+ return native.default.Config({
459
+ ...config,
460
+ compression: config.compression ?? "none"
461
+ });
462
+ }
463
+ function listenerProtocol(server, capabilities) {
464
+ if (!capabilities.nativeTransport) return "http:";
465
+ if (server.protocol !== "http:" && server.protocol !== "https:")
466
+ throw new Error("auth-remote: DSH listener lacks a valid native protocol");
467
+ return server.protocol;
468
+ }
469
+ function listenerTransport(actual, capabilities) {
470
+ const loopback = capabilities.nativeTransport ? NativeWebServer.isLoopbackHost(actual.host) : isIP2(actual.host) === 4 && actual.host.startsWith("127.");
471
+ const host = capabilities.nativeTransport ? loopback ? NativeWebServer.normalizeBindAddress(actual.host) : (
472
+ // Connection compares the bind literal through WHATWG URL, retaining mapped IPv6.
473
+ // A zone selects an interface and is excluded by its authority comparison.
474
+ actual.host.split("%", 1)[0]
475
+ ) : (
476
+ // Older Connection cannot recognize a concrete non-loopback bind authority.
477
+ // Preserve its existing server-side loopback bridge without changing the listener.
478
+ "127.0.0.1"
479
+ );
480
+ const url = new URL(listenerPublicUrl(host, actual.port, actual.protocol));
481
+ return {
482
+ authority: url.host,
483
+ origin: url.origin,
484
+ loopback
485
+ };
486
+ }
487
+
399
488
  // src/adapters/dsh/webserver.ts
489
+ import WebServer2 from "@deepseek-ai/dsh-host-webserver";
400
490
  var READY_PATH = "/auth-remote/ready";
401
491
  var READY_PROTOCOL_VERSION = 1;
402
492
  var DenyGate = class {
@@ -430,11 +520,17 @@ var GuardedWebServer = class extends WebServer2 {
430
520
  constructor(ctx, config, gate = new DenyGate()) {
431
521
  super(ctx, config);
432
522
  this.gate = gate;
523
+ this.originPolicy = config.originPolicy;
433
524
  super.register({
434
525
  kind: "exact",
435
526
  path: READY_PATH,
436
527
  handler: (req, res) => {
437
- if (!evaluateRequestOrigin(config.originPolicy, {
528
+ if (!this.originPolicy) {
529
+ res.writeHead(503, { "cache-control": "no-store" });
530
+ res.end();
531
+ return;
532
+ }
533
+ if (!evaluateRequestOrigin(this.originPolicy, {
438
534
  rawHeaders: req.rawHeaders,
439
535
  method: req.method,
440
536
  target: req.url
@@ -464,6 +560,11 @@ var GuardedWebServer = class extends WebServer2 {
464
560
  });
465
561
  }
466
562
  gate;
563
+ originPolicy;
564
+ /** Ready and the authenticated gate consume the same listener-finalized policy. */
565
+ setOriginPolicy(policy) {
566
+ this.originPolicy = policy;
567
+ }
467
568
  register(route) {
468
569
  return super.register({
469
570
  ...route,
@@ -910,13 +1011,13 @@ function validatePassword(password) {
910
1011
  throw new PasswordValidationError();
911
1012
  }
912
1013
  async function derive(password, salt) {
913
- return new Promise((resolve, reject) => {
1014
+ return new Promise((resolve2, reject) => {
914
1015
  scryptCallback(
915
1016
  password,
916
1017
  Buffer.from(salt, "hex"),
917
1018
  64,
918
1019
  { N: 16384, r: 8, p: 1, maxmem: 32 * 1024 * 1024 },
919
- (error, key) => error ? reject(error) : resolve(key)
1020
+ (error, key) => error ? reject(error) : resolve2(key)
920
1021
  );
921
1022
  });
922
1023
  }
@@ -1470,7 +1571,8 @@ var AuthService = class {
1470
1571
 
1471
1572
  // src/config.ts
1472
1573
  import z from "@deepseek-ai/schemastery";
1473
- import { isIP } from "node:net";
1574
+ import { isIP as isIP3 } from "node:net";
1575
+ import { resolve } from "node:path";
1474
1576
  var DEFAULT_REQUIRE_TOTP = true;
1475
1577
  var DEFAULT_SESSION_HOURS = 168;
1476
1578
  var DEFAULT_WEB_HOST = "127.0.0.1";
@@ -1482,51 +1584,118 @@ var AUTH_CONFIG_KEYS = /* @__PURE__ */ new Set([
1482
1584
  "preserveOriginPaths"
1483
1585
  ]);
1484
1586
  var Config = z.object({
1485
- allowedOrigins: z.array(z.string()).default([]),
1587
+ publicUrl: z.string(),
1588
+ host: z.string(),
1589
+ port: z.number().step(1).min(0).max(65535),
1590
+ tlsCert: z.string(),
1591
+ tlsKey: z.string(),
1592
+ allowedOrigins: z.union([z.array(z.string()), z.const(void 0)]).default(void 0),
1486
1593
  requireTotp: z.boolean().default(DEFAULT_REQUIRE_TOTP),
1487
1594
  sessionHours: z.number().step(1).min(1).default(DEFAULT_SESSION_HOURS),
1488
1595
  preserveOriginPaths: z.array(z.string()).default([])
1489
1596
  });
1490
- function resolveAuthConfig(input, listener) {
1491
- if (typeof input !== "object" || input === null)
1597
+ function resolveStartupConfig(input, startup, context) {
1598
+ if (typeof input !== "object" || input === null || Array.isArray(input))
1492
1599
  throw new Error("auth-remote: config is required");
1600
+ const keys = /* @__PURE__ */ new Set([...AUTH_CONFIG_KEYS, "publicUrl", "host", "port", "tlsCert", "tlsKey"]);
1493
1601
  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)}`);
1602
+ if (!keys.has(key)) throw new Error(`auth-remote: unknown config key ${JSON.stringify(key)}`);
1603
+ const legacyWarning = Object.hasOwn(input, "allowedOrigins");
1604
+ const explicitUrl = startup.publicUrl !== void 0 || Object.hasOwn(input, "publicUrl");
1605
+ if (legacyWarning && explicitUrl)
1606
+ throw new Error("auth-remote: publicUrl and allowedOrigins cannot be supplied together");
1496
1607
  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 ?? []);
1608
+ const capabilities = getRuntimeCapabilities(context.version);
1609
+ let publicUrl;
1610
+ let publicUrlSource = "derived";
1611
+ if (explicitUrl) {
1612
+ publicUrlSource = startup.publicUrl !== void 0 ? "cli" : "file";
1613
+ publicUrl = parsePublicUrl(startup.publicUrl ?? config.publicUrl);
1614
+ } else if (legacyWarning) {
1615
+ const origins = config.allowedOrigins;
1616
+ if (!Array.isArray(origins)) throw new Error("auth-remote: allowedOrigins must be an array");
1617
+ if (origins.length > 1)
1618
+ throw new Error("auth-remote: allowedOrigins must select one unique publicUrl");
1619
+ if (origins.length === 1) {
1620
+ publicUrlSource = "legacy";
1621
+ publicUrl = parsePublicUrl(origins[0]);
1622
+ }
1623
+ }
1624
+ let tls;
1625
+ let tlsSource;
1626
+ if (startup.tls !== void 0) {
1627
+ const { certFile, keyFile } = startup.tls;
1628
+ if (!certFile || !keyFile)
1629
+ throw new Error("auth-remote: --tls-cert and --tls-key must be supplied together");
1630
+ tlsSource = "cli";
1631
+ tls = { certFile: resolve(context.cwd, certFile), keyFile: resolve(context.cwd, keyFile) };
1632
+ } else if (Object.hasOwn(input, "tlsCert") || Object.hasOwn(input, "tlsKey")) {
1633
+ if (!config.tlsCert || !config.tlsKey)
1634
+ throw new Error("auth-remote: TLS requires both tlsCert and tlsKey");
1635
+ tlsSource = "file";
1636
+ tls = {
1637
+ certFile: resolve(context.profileDir, config.tlsCert),
1638
+ keyFile: resolve(context.profileDir, config.tlsKey)
1639
+ };
1640
+ }
1641
+ const listener = validateListenerConfig(capabilities, {
1642
+ host: startup.host ?? (Object.hasOwn(input, "host") ? config.host : DEFAULT_WEB_HOST),
1643
+ port: startup.port ?? (Object.hasOwn(input, "port") ? config.port : DEFAULT_WEB_PORT),
1644
+ ...tls ? { tls } : {},
1645
+ compression: "none"
1646
+ });
1503
1647
  const sessionHours = config.sessionHours ?? DEFAULT_SESSION_HOURS;
1504
- if (!Number.isSafeInteger(sessionHours) || !Number.isSafeInteger(Date.now() + sessionHours * 36e5)) {
1648
+ if (!Number.isSafeInteger(sessionHours) || !Number.isSafeInteger(Date.now() + sessionHours * 36e5))
1505
1649
  throw new Error("auth-remote: sessionHours exceeds the safe timestamp range");
1506
- }
1507
1650
  const paths = config.preserveOriginPaths ?? [];
1508
1651
  const seen = /* @__PURE__ */ new Set();
1509
1652
  for (const path of paths) {
1510
- if (!isCanonicalPathPrefix(path)) {
1653
+ if (!isCanonicalPathPrefix(path))
1511
1654
  throw new Error(`auth-remote: invalid preserveOriginPaths entry ${JSON.stringify(path)}`);
1512
- }
1513
1655
  if (seen.has(path))
1514
1656
  throw new Error(`auth-remote: duplicate preserveOriginPaths entry ${JSON.stringify(path)}`);
1515
1657
  seen.add(path);
1516
1658
  }
1517
1659
  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,
1660
+ ...listener,
1661
+ capabilities,
1662
+ publicUrl,
1663
+ publicUrlSource,
1664
+ tlsSource,
1665
+ legacyWarning,
1525
1666
  requireTotp: config.requireTotp ?? DEFAULT_REQUIRE_TOTP,
1526
1667
  sessionHours,
1527
- preserveOriginPaths: paths
1668
+ preserveOriginPaths: Object.freeze([...paths])
1528
1669
  };
1529
1670
  }
1671
+ function finalizeAuthConfig(pending, actual) {
1672
+ if (!Number.isInteger(actual.port) || actual.port < 1 || actual.port > 65535 || isIP3(actual.host) === 0)
1673
+ throw new Error("auth-remote: invalid actual listener host or port");
1674
+ const transport = listenerTransport(actual, pending.capabilities);
1675
+ let listenerUrl;
1676
+ if (actual.host.includes("%")) {
1677
+ if (transport.loopback) listenerUrl = `${transport.origin}/`;
1678
+ else {
1679
+ if (!pending.publicUrl)
1680
+ throw new Error("auth-remote: scoped listener requires explicit publicUrl");
1681
+ listenerUrl = `${actual.protocol}//[${actual.host}]:${actual.port}/`;
1682
+ }
1683
+ } else listenerUrl = listenerPublicUrl(actual.host, actual.port, actual.protocol);
1684
+ const publicUrl = pending.publicUrl ?? parsePublicUrl(listenerUrl);
1685
+ const originPolicy = createOriginPolicy([publicUrl.origin]);
1686
+ return Object.freeze({
1687
+ ...pending,
1688
+ host: actual.host,
1689
+ port: actual.port,
1690
+ protocol: actual.protocol,
1691
+ nativeAuthority: transport.authority,
1692
+ nativeOrigin: transport.origin,
1693
+ publicUrl: publicUrl.url,
1694
+ listenerUrl,
1695
+ originPolicy,
1696
+ allowedOrigins: Object.freeze([publicUrl.origin])
1697
+ });
1698
+ }
1530
1699
  function isCanonicalPathPrefix(path) {
1531
1700
  if (!path.startsWith("/") || path.length > 1 && path.endsWith("/")) return false;
1532
1701
  if (/[?#*\\]/u.test(path)) return false;
@@ -1564,9 +1733,9 @@ var AuthConnections = class {
1564
1733
  const entry = this.makeEntry(
1565
1734
  hash,
1566
1735
  session.expiresAt,
1567
- () => new Promise((resolve) => {
1568
- if (response.destroyed || response.writableEnded) return resolve();
1569
- response.once("close", () => resolve());
1736
+ () => new Promise((resolve2) => {
1737
+ if (response.destroyed || response.writableEnded) return resolve2();
1738
+ response.once("close", () => resolve2());
1570
1739
  response.destroy();
1571
1740
  })
1572
1741
  );
@@ -1577,9 +1746,9 @@ var AuthConnections = class {
1577
1746
  const entry = this.makeEntry(
1578
1747
  hash,
1579
1748
  session.expiresAt,
1580
- () => new Promise((resolve) => {
1581
- if (socket.destroyed) return resolve();
1582
- socket.once("close", () => resolve());
1749
+ () => new Promise((resolve2) => {
1750
+ if (socket.destroyed) return resolve2();
1751
+ socket.once("close", () => resolve2());
1583
1752
  socket.destroy();
1584
1753
  })
1585
1754
  );
@@ -1701,11 +1870,11 @@ var AdminSocket = class {
1701
1870
  }
1702
1871
  const server = createServer((socket) => this.accept(socket));
1703
1872
  server.on("error", () => this.onUnavailable());
1704
- await new Promise((resolve, reject) => {
1873
+ await new Promise((resolve2, reject) => {
1705
1874
  server.once("error", reject);
1706
1875
  server.listen(this.path, () => {
1707
1876
  server.off("error", reject);
1708
- resolve();
1877
+ resolve2();
1709
1878
  });
1710
1879
  });
1711
1880
  this.server = server;
@@ -1792,7 +1961,7 @@ var AdminSocket = class {
1792
1961
  const server = this.server;
1793
1962
  this.server = void 0;
1794
1963
  if (server) {
1795
- const closed = new Promise((resolve) => server.close(() => resolve()));
1964
+ const closed = new Promise((resolve2) => server.close(() => resolve2()));
1796
1965
  for (const socket of this.sockets) socket.destroy();
1797
1966
  await Promise.allSettled(this.operations);
1798
1967
  await closed;
@@ -1885,7 +2054,7 @@ async function readJsonBody(req) {
1885
2054
  throw new HttpFailure(413, "body_too_large");
1886
2055
  if (!/^application\/json(?:\s*;|$)/iu.test(String(req.headers["content-type"] ?? "")))
1887
2056
  throw new HttpFailure(415, "unsupported_media_type");
1888
- return new Promise((resolve, reject) => {
2057
+ return new Promise((resolve2, reject) => {
1889
2058
  let done = false;
1890
2059
  let bytes = 0;
1891
2060
  const chunks = [];
@@ -1916,7 +2085,7 @@ async function readJsonBody(req) {
1916
2085
  const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
1917
2086
  if (typeof body !== "object" || body === null || Array.isArray(body))
1918
2087
  throw new HttpFailure(400, "invalid_input");
1919
- resolve(body);
2088
+ resolve2(body);
1920
2089
  } catch {
1921
2090
  reject(new HttpFailure(400, "invalid_json"));
1922
2091
  }
@@ -2239,15 +2408,13 @@ function downstreamCookie(original, native) {
2239
2408
  return [...unrelated, native].join("; ");
2240
2409
  }
2241
2410
  var AuthGate = class {
2242
- constructor(serverPort, config, store, auth, readiness, connections) {
2243
- this.serverPort = serverPort;
2411
+ constructor(config, store, auth, readiness, connections) {
2244
2412
  this.config = config;
2245
2413
  this.store = store;
2246
2414
  this.auth = auth;
2247
2415
  this.readiness = readiness;
2248
2416
  this.connections = connections;
2249
2417
  }
2250
- serverPort;
2251
2418
  config;
2252
2419
  store;
2253
2420
  auth;
@@ -2327,8 +2494,8 @@ var AuthGate = class {
2327
2494
  }
2328
2495
  bridge(req, context) {
2329
2496
  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}`;
2497
+ const authority = preserve ? context.downstreamAuthority : this.config.nativeAuthority;
2498
+ const origin = preserve ? context.origin : this.config.nativeOrigin;
2332
2499
  const native = this.readiness.nativeCookie(authority, origin);
2333
2500
  req.headers.cookie = downstreamCookie(req.headers.cookie, native);
2334
2501
  req.headers.host = authority;
@@ -2342,22 +2509,26 @@ var AuthRemoteWebServer = class extends GuardedWebServer {
2342
2509
  static Config = Config;
2343
2510
  stateStore;
2344
2511
  authService;
2345
- resolved;
2512
+ pending;
2513
+ resolvedConfig;
2346
2514
  switchGate;
2347
2515
  constructor(ctx, input) {
2348
2516
  const startup = ctx.get("webStartup");
2349
2517
  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"
2518
+ const profile = ctx.get("profileContext");
2519
+ if (!profile?.dir) throw new Error("dsh-auth-remote: profileContext is required for storage");
2520
+ const config = resolveStartupConfig(input, startup, {
2521
+ version: assertWebServerCompatibility(ctx),
2522
+ profileDir: profile.dir,
2523
+ cwd: process.cwd()
2354
2524
  });
2355
- assertWebServerCompatibility(ctx);
2356
2525
  const gate = new SwitchGate();
2357
2526
  super(ctx, config, gate);
2358
- this.resolved = config;
2527
+ this.pending = config;
2359
2528
  this.switchGate = gate;
2360
2529
  installAuthenticatedHostCapability(ctx);
2530
+ if (config.legacyWarning)
2531
+ console.warn("auth-remote: allowedOrigins is deprecated; use publicUrl with one root URL");
2361
2532
  }
2362
2533
  async [Service.init]() {
2363
2534
  const profile = this.ctx.get("profileContext");
@@ -2375,19 +2546,24 @@ var AuthRemoteWebServer = class extends GuardedWebServer {
2375
2546
  });
2376
2547
  try {
2377
2548
  const auth = new AuthService(store, {
2378
- requireTotp: this.resolved.requireTotp,
2379
- sessionHours: this.resolved.sessionHours
2549
+ requireTotp: this.pending.requireTotp,
2550
+ sessionHours: this.pending.sessionHours
2380
2551
  });
2381
2552
  await auth.enforceCurrentPolicy();
2382
2553
  this.stateStore = store;
2383
2554
  this.authService = auth;
2555
+ await super[Service.init]();
2556
+ this.resolvedConfig = finalizeAuthConfig(this.pending, {
2557
+ host: this.host,
2558
+ port: this.port,
2559
+ protocol: listenerProtocol(this, this.pending.capabilities)
2560
+ });
2561
+ this.setOriginPolicy(this.resolved.originPolicy);
2384
2562
  connections = new AuthConnections(store, auth);
2385
2563
  readiness = new DshReadiness(this, this.resolved, () => {
2386
2564
  if (connections) void connections.closeAll();
2387
2565
  });
2388
- this.switchGate.set(
2389
- new AuthGate(() => this.port, this.resolved, store, auth, readiness, connections)
2390
- );
2566
+ this.switchGate.set(new AuthGate(this.resolved, store, auth, readiness, connections));
2391
2567
  new AuthRoutes(auth, profileName).install(this);
2392
2568
  admin = new AdminSocket(
2393
2569
  profile.dir,
@@ -2414,18 +2590,26 @@ var AuthRemoteWebServer = class extends GuardedWebServer {
2414
2590
  },
2415
2591
  "auth-remote.storage-and-gate"
2416
2592
  );
2417
- await super[Service.init]();
2418
2593
  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
- });
2594
+ watchConnection(
2595
+ this.ctx,
2596
+ readiness,
2597
+ () => {
2598
+ const loader = this.ctx.get("loader");
2599
+ const settled = loader?.await() ?? Promise.resolve();
2600
+ void settled.then(() => {
2601
+ if (announced || !activeReadiness.ready()) return;
2602
+ announced = true;
2603
+ console.log(startupLines(profileName, this.resolved).join("\n"));
2604
+ }).catch(() => {
2605
+ });
2606
+ },
2607
+ async () => {
2608
+ this.switchGate.set(new DenyGate());
2609
+ activeReadiness.detach();
2610
+ await this.ctx.fiber.dispose();
2611
+ }
2612
+ );
2429
2613
  } catch (error) {
2430
2614
  this.switchGate.set(new DenyGate());
2431
2615
  await admin?.dispose();
@@ -2435,6 +2619,14 @@ var AuthRemoteWebServer = class extends GuardedWebServer {
2435
2619
  throw error;
2436
2620
  }
2437
2621
  }
2622
+ get resolved() {
2623
+ if (!this.resolvedConfig) throw new Error("auth-remote: listener entry is not finalized");
2624
+ return this.resolvedConfig;
2625
+ }
2626
+ /** Native WebApp evaluates this only after the authenticated service initializes. */
2627
+ get publicUrl() {
2628
+ return this.resolved.publicUrl;
2629
+ }
2438
2630
  get storage() {
2439
2631
  if (!this.stateStore) throw new Error("dsh-auth-remote: storage is not initialized");
2440
2632
  return this.stateStore;
@@ -2465,9 +2657,10 @@ export {
2465
2657
  READY_PATH,
2466
2658
  READY_PROTOCOL_VERSION,
2467
2659
  src_default as default,
2660
+ finalizeAuthConfig,
2468
2661
  installAuthenticatedHostCapability,
2469
2662
  name,
2470
- resolveAuthConfig,
2663
+ resolveStartupConfig,
2471
2664
  watchConnection
2472
2665
  };
2473
2666
  //# sourceMappingURL=index.js.map