dsh-auth-remote 0.1.9 → 0.1.10

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 (49) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/CHANGELOG.zh-CN.md +11 -0
  3. package/README.md +17 -11
  4. package/README.zh-CN.md +17 -11
  5. package/cordis.patch.yml +2 -1
  6. package/dist/cli.js +91 -46
  7. package/dist/cli.js.map +2 -2
  8. package/dist/client.js +2880 -581
  9. package/dist/client.js.map +4 -4
  10. package/dist/index.js +133 -36
  11. package/dist/index.js.map +3 -3
  12. package/dist/login.css +2 -8
  13. package/dist/login.css.map +2 -2
  14. package/dist/login.js +80 -42
  15. package/dist/login.js.map +2 -2
  16. package/dist/types/adapters/dsh/account-callback.d.ts +3 -0
  17. package/dist/types/adapters/dsh/account-callback.d.ts.map +1 -1
  18. package/dist/types/adapters/dsh/hmr-context.d.ts +10 -0
  19. package/dist/types/adapters/dsh/hmr-context.d.ts.map +1 -0
  20. package/dist/types/auth/service.d.ts +2 -0
  21. package/dist/types/auth/service.d.ts.map +1 -1
  22. package/dist/types/auth/sessions.d.ts +2 -0
  23. package/dist/types/auth/sessions.d.ts.map +1 -1
  24. package/dist/types/config.d.ts +9 -3
  25. package/dist/types/config.d.ts.map +1 -1
  26. package/dist/types/http/account-login.d.ts +5 -3
  27. package/dist/types/http/account-login.d.ts.map +1 -1
  28. package/dist/types/index.d.ts +2 -2
  29. package/dist/types/index.d.ts.map +1 -1
  30. package/dist/types/shared/account-login.d.ts +2 -1
  31. package/dist/types/shared/account-login.d.ts.map +1 -1
  32. package/dist/types/shared/auth-contract.d.ts +2 -0
  33. package/dist/types/shared/auth-contract.d.ts.map +1 -1
  34. package/dist/types/shared/i18n.d.ts +78 -40
  35. package/dist/types/shared/i18n.d.ts.map +1 -1
  36. package/dist/types/shared/locales/en.d.ts +39 -20
  37. package/dist/types/shared/locales/en.d.ts.map +1 -1
  38. package/dist/types/shared/locales/zh.d.ts +39 -20
  39. package/dist/types/shared/locales/zh.d.ts.map +1 -1
  40. package/docs/deployment.md +22 -19
  41. package/docs/deployment.zh-CN.md +22 -19
  42. package/docs/development.md +20 -8
  43. package/docs/development.zh-CN.md +20 -8
  44. package/docs/legacy-compatibility.md +86 -64
  45. package/docs/legacy-compatibility.zh-CN.md +86 -64
  46. package/docs/releasing.md +5 -5
  47. package/docs/releasing.zh-CN.md +5 -5
  48. package/examples/web-profile-auth-remote.patch.yml +4 -2
  49. package/package.json +18 -14
package/dist/index.js CHANGED
@@ -60,11 +60,12 @@ function assertConnectionCompatibility(connection, anchor) {
60
60
  }
61
61
 
62
62
  // src/shared/account-login.ts
63
+ import { satisfies } from "semver";
63
64
  var ACCOUNT_LOGIN_BASE = "/auth-remote/account";
64
65
  var ACCOUNT_CALLBACK_PATH = "/oauth/callback";
65
66
  var ACCOUNT_LOGIN_CAPABILITY = "__DSH_AUTH_REMOTE_MANUAL_ACCOUNT_LOGIN__";
66
67
  function supportsManualAccountLogin(version) {
67
- return version === "0.2.1-alpha.3";
68
+ return satisfies(version, ">=0.2.1-alpha.3", { includePrerelease: true });
68
69
  }
69
70
  function isActiveAccountLogin(phase) {
70
71
  return ["initializing", "waiting-browser", "exchanging", "committing"].includes(phase);
@@ -504,6 +505,17 @@ function listenerTransport(actual, capabilities) {
504
505
  };
505
506
  }
506
507
 
508
+ // src/adapters/dsh/hmr-context.ts
509
+ import { AsyncLocalStorage } from "node:async_hooks";
510
+ function outsideHmrTransaction(ctx, initialize) {
511
+ const hmr = ctx.get("hmr");
512
+ const scope = hmr?.executing;
513
+ if (typeof hmr?.runExclusive === "function" && scope instanceof AsyncLocalStorage && scope.getStore() === true) {
514
+ return scope.exit(initialize);
515
+ }
516
+ return initialize();
517
+ }
518
+
507
519
  // src/adapters/dsh/webserver.ts
508
520
  import WebServer2 from "@deepseek-ai/dsh-host-webserver";
509
521
  var READY_PATH = "/auth-remote/ready";
@@ -1091,10 +1103,11 @@ function issueSession(draft, now, sessionHours) {
1091
1103
  function sessionFor(state, token, now, requireTotp) {
1092
1104
  if (typeof token !== "string" || !/^[A-Za-z0-9_-]{43}$/u.test(token)) return null;
1093
1105
  const session = state.sessions[sessionHash(token)];
1106
+ return session && isActiveSession(state, session, now, requireTotp) ? session : null;
1107
+ }
1108
+ function isActiveSession(state, session, now, requireTotp) {
1094
1109
  const account = state.account;
1095
- if (!session || !account || session.accountId !== account.id || session.securityVersion !== account.securityVersion || session.expiresAt <= now || requireTotp && !account.totp)
1096
- return null;
1097
- return session;
1110
+ return !!(account && session.accountId === account.id && session.securityVersion === account.securityVersion && session.expiresAt > now && (!requireTotp || account.totp));
1098
1111
  }
1099
1112
 
1100
1113
  // src/auth/totp.ts
@@ -1220,11 +1233,12 @@ var AuthService = class {
1220
1233
  }
1221
1234
  status() {
1222
1235
  const state = this.store.current();
1236
+ const now = this.now();
1223
1237
  return {
1224
1238
  initialized: state.account !== null,
1225
1239
  totpEnabled: state.account?.totp !== null && state.account?.totp !== void 0,
1226
1240
  activeSessions: Object.values(state.sessions).filter(
1227
- (session) => state.account && session.accountId === state.account.id && session.securityVersion === state.account.securityVersion && session.expiresAt > this.now() && (!this.policy.requireTotp || state.account.totp)
1241
+ (session) => isActiveSession(state, session, now, this.policy.requireTotp)
1228
1242
  ).length
1229
1243
  };
1230
1244
  }
@@ -1236,12 +1250,17 @@ var AuthService = class {
1236
1250
  }
1237
1251
  me(token) {
1238
1252
  const state = this.store.current();
1239
- const session = sessionFor(state, token, this.now(), this.policy.requireTotp);
1253
+ const now = this.now();
1254
+ const session = sessionFor(state, token, now, this.policy.requireTotp);
1240
1255
  if (!session || !state.account) throw new AuthError("unauthorized");
1241
1256
  return {
1242
1257
  username: state.account.username,
1243
1258
  totpEnabled: state.account.totp !== null,
1244
- expiresAt: session.expiresAt
1259
+ createdAt: session.createdAt,
1260
+ expiresAt: session.expiresAt,
1261
+ activeSessions: Object.values(state.sessions).filter(
1262
+ (entry) => isActiveSession(state, entry, now, this.policy.requireTotp)
1263
+ ).length
1245
1264
  };
1246
1265
  }
1247
1266
  bindingDetails(id) {
@@ -1607,17 +1626,18 @@ var AuthService = class {
1607
1626
  import z from "@deepseek-ai/schemastery";
1608
1627
  import { isIP as isIP3 } from "node:net";
1609
1628
  import { resolve } from "node:path";
1610
- var DEFAULT_REQUIRE_TOTP = true;
1629
+ var DEFAULT_REQUIRE_TOTP = false;
1611
1630
  var DEFAULT_SESSION_HOURS = 168;
1612
1631
  var DEFAULT_WEB_HOST = "127.0.0.1";
1613
1632
  var DEFAULT_WEB_PORT = 3080;
1614
1633
  var AUTH_CONFIG_KEYS = /* @__PURE__ */ new Set([
1615
1634
  "allowedOrigins",
1616
1635
  "requireTotp",
1636
+ "manualAccountLogin",
1617
1637
  "sessionHours",
1618
1638
  "preserveOriginPaths"
1619
1639
  ]);
1620
- var Config = z.object({
1640
+ var StaticConfig = z.object({
1621
1641
  publicUrl: z.string(),
1622
1642
  host: z.string(),
1623
1643
  port: z.number().step(1).min(0).max(65535),
@@ -1628,6 +1648,11 @@ var Config = z.object({
1628
1648
  sessionHours: z.number().step(1).min(1).default(DEFAULT_SESSION_HOURS),
1629
1649
  preserveOriginPaths: z.array(z.string()).default([])
1630
1650
  });
1651
+ var ManualAccountLoginConfig = z.boolean().default(true).volatile();
1652
+ var Config = z.object({
1653
+ ...StaticConfig.dict,
1654
+ manualAccountLogin: ManualAccountLoginConfig
1655
+ });
1631
1656
  function resolveStartupConfig(input, startup, context) {
1632
1657
  if (typeof input !== "object" || input === null || Array.isArray(input))
1633
1658
  throw new Error("auth-remote: config is required");
@@ -1638,7 +1663,16 @@ function resolveStartupConfig(input, startup, context) {
1638
1663
  const explicitUrl = startup.publicUrl !== void 0 || Object.hasOwn(input, "publicUrl");
1639
1664
  if (legacyWarning && explicitUrl)
1640
1665
  throw new Error("auth-remote: publicUrl and allowedOrigins cannot be supplied together");
1641
- const config = Config(input);
1666
+ const { manualAccountLogin: manual, ...ordinary } = input;
1667
+ const config = StaticConfig(ordinary);
1668
+ let manualAccountLogin;
1669
+ if (typeof manual === "object" && manual !== null) {
1670
+ if (typeof manual.get !== "function") throw new Error("auth-remote: invalid manualAccountLogin");
1671
+ z.boolean().required()(manual.get());
1672
+ manualAccountLogin = manual;
1673
+ } else {
1674
+ manualAccountLogin = ManualAccountLoginConfig(manual);
1675
+ }
1642
1676
  const capabilities = getRuntimeCapabilities(context.version);
1643
1677
  let publicUrl;
1644
1678
  let publicUrlSource = "derived";
@@ -1698,6 +1732,7 @@ function resolveStartupConfig(input, startup, context) {
1698
1732
  tlsSource,
1699
1733
  legacyWarning,
1700
1734
  requireTotp: config.requireTotp ?? DEFAULT_REQUIRE_TOTP,
1735
+ manualAccountLogin,
1701
1736
  sessionHours,
1702
1737
  preserveOriginPaths: Object.freeze([...paths])
1703
1738
  };
@@ -2259,7 +2294,7 @@ var AuthRoutes = class {
2259
2294
  "referrer-policy": "no-referrer"
2260
2295
  });
2261
2296
  res.end(
2262
- '<!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="manifest" href="/manifest.webmanifest"><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>'
2297
+ '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in</title><link rel="manifest" href="/manifest.webmanifest"><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>'
2263
2298
  );
2264
2299
  return;
2265
2300
  }
@@ -2555,14 +2590,22 @@ import { IncomingMessage, ServerResponse } from "node:http";
2555
2590
  import { Duplex } from "node:stream";
2556
2591
  import { finished } from "node:stream/promises";
2557
2592
  var AccountCallbackBridge = class {
2593
+ constructor(ownsCallback = () => true) {
2594
+ this.ownsCallback = ownsCallback;
2595
+ }
2596
+ ownsCallback;
2558
2597
  handler;
2598
+ get available() {
2599
+ return this.handler !== void 0;
2600
+ }
2559
2601
  capture(route) {
2560
2602
  if (route.kind !== "exact" || route.path !== ACCOUNT_CALLBACK_PATH) return;
2561
2603
  const handler = route.handler;
2562
2604
  this.handler = handler;
2563
2605
  return {
2564
- handler: (_req, res) => {
2565
- res.writeHead(403, { "cache-control": "no-store" }).end();
2606
+ handler: async (req, res) => {
2607
+ if (await this.ownsCallback()) res.writeHead(403, { "cache-control": "no-store" }).end();
2608
+ else return handler(req, res);
2566
2609
  },
2567
2610
  dispose: () => {
2568
2611
  if (this.handler === handler) this.handler = void 0;
@@ -2601,9 +2644,10 @@ var AccountCallbackBridge = class {
2601
2644
 
2602
2645
  // src/http/account-login.ts
2603
2646
  var ManualAccountLogin = class {
2604
- constructor(ctx, auth, store, version) {
2647
+ constructor(ctx, auth, store, version, enabled = () => true) {
2605
2648
  this.auth = auth;
2606
2649
  this.version = version;
2650
+ this.enabled = enabled;
2607
2651
  this.unsubscribe = store.subscribe((_before, after) => this.reconcile(after));
2608
2652
  if (!supportsManualAccountLogin(version)) return;
2609
2653
  ctx.inject(["deepseekAccount"], (accountCtx) => {
@@ -2619,7 +2663,8 @@ var ManualAccountLogin = class {
2619
2663
  }
2620
2664
  auth;
2621
2665
  version;
2622
- bridge = new AccountCallbackBridge();
2666
+ enabled;
2667
+ bridge = new AccountCallbackBridge(() => this.ownsNativeCallback());
2623
2668
  unsubscribe;
2624
2669
  active;
2625
2670
  starting = false;
@@ -2639,6 +2684,21 @@ var ManualAccountLogin = class {
2639
2684
  const provider = this.currentProvider;
2640
2685
  return provider && typeof provider.getState === "function" && typeof provider.startSignIn === "function" && typeof provider.cancelSignIn === "function" ? provider : void 0;
2641
2686
  }
2687
+ async ownsNativeCallback() {
2688
+ const active = this.active;
2689
+ if (!active?.ownsCallback) return false;
2690
+ if (!active.id) return true;
2691
+ try {
2692
+ const view = await active.provider.getState();
2693
+ if (this.active !== active) return this.active?.ownsCallback === true;
2694
+ if (!active.ownsCallback) return false;
2695
+ if (view.attempt?.id === active.id && isActiveAccountLogin(view.attempt.phase)) return true;
2696
+ active.ownsCallback = false;
2697
+ return false;
2698
+ } catch {
2699
+ return true;
2700
+ }
2701
+ }
2642
2702
  session(token) {
2643
2703
  const session = token && !this.disposed ? this.auth.session(token) : null;
2644
2704
  if (!token || !session) throw new AuthError("unauthorized");
@@ -2666,33 +2726,41 @@ var ManualAccountLogin = class {
2666
2726
  async state(token) {
2667
2727
  const { hash } = this.session(token);
2668
2728
  const provider = this.provider();
2669
- if (!provider) return { supported: false, status: "signed-out", attempt: null };
2729
+ if (!provider)
2730
+ return { supported: false, enabled: this.enabled(), status: "signed-out", attempt: null };
2670
2731
  const view = await provider.getState();
2671
2732
  this.session(token);
2672
2733
  const active = this.active;
2673
2734
  if (!active || active.owner !== hash || active.provider !== provider || active.id !== view.attempt?.id)
2674
- return { supported: true, status: view.status, attempt: null };
2735
+ return { supported: true, enabled: this.enabled(), status: view.status, attempt: null };
2675
2736
  const attempt = view.attempt;
2737
+ if (attempt?.phase === "waiting-browser" && !this.bridge.available)
2738
+ throw new HttpFailure(503, "account_unavailable");
2676
2739
  if (attempt?.expiresAt !== void 0 && attempt.expiresAt < active.deadline) {
2677
2740
  active.deadline = attempt.expiresAt;
2678
2741
  this.schedule(active);
2679
2742
  }
2680
- if (attempt && !isActiveAccountLogin(attempt.phase) && active.timer) clearTimeout(active.timer);
2743
+ if (attempt && !isActiveAccountLogin(attempt.phase)) {
2744
+ if (active.timer) clearTimeout(active.timer);
2745
+ active.ownsCallback = false;
2746
+ }
2681
2747
  return {
2682
2748
  supported: true,
2749
+ enabled: this.enabled(),
2683
2750
  status: view.status,
2684
2751
  attempt: attempt && { ...attempt, expiresAt: active.deadline }
2685
2752
  };
2686
2753
  }
2687
2754
  async start(token, body) {
2688
2755
  const owner = this.session(token);
2756
+ const provider = this.provider();
2757
+ if (!provider) throw new HttpFailure(503, "account_unavailable");
2758
+ if (!this.enabled()) throw new HttpFailure(403, "account_disabled");
2689
2759
  const locale = stringField(body, "locale");
2690
2760
  const offset = body.timezoneOffsetSeconds;
2691
2761
  if (locale.length > 64 || !/^[a-z][a-z0-9_-]*$/iu.test(locale) || !Number.isInteger(offset) || Math.abs(offset) > 86400)
2692
2762
  throw new HttpFailure(400, "invalid_input");
2693
2763
  if (this.starting) throw new HttpFailure(409, "account_busy");
2694
- const provider = this.provider();
2695
- if (!provider) throw new HttpFailure(503, "account_unavailable");
2696
2764
  this.starting = true;
2697
2765
  let entry;
2698
2766
  try {
@@ -2700,7 +2768,7 @@ var ManualAccountLogin = class {
2700
2768
  if (previous.attempt && isActiveAccountLogin(previous.attempt.phase))
2701
2769
  throw new HttpFailure(409, "account_busy");
2702
2770
  if (previous.status === "credential-stored")
2703
- return { ...previous, supported: true, attempt: null };
2771
+ return { ...previous, supported: true, enabled: this.enabled(), attempt: null };
2704
2772
  if (this.active?.timer) clearTimeout(this.active.timer);
2705
2773
  entry = {
2706
2774
  owner: owner.hash,
@@ -2708,7 +2776,8 @@ var ManualAccountLogin = class {
2708
2776
  callbackOrigin: `http://127.0.0.1:${randomInt(49152, 65536)}`,
2709
2777
  deadline: Math.min(Date.now() + 6e5, owner.session.expiresAt),
2710
2778
  cancelled: false,
2711
- submitting: false
2779
+ submitting: false,
2780
+ ownsCallback: true
2712
2781
  };
2713
2782
  this.active = entry;
2714
2783
  this.schedule(entry);
@@ -2729,6 +2798,7 @@ var ManualAccountLogin = class {
2729
2798
  throw error;
2730
2799
  } finally {
2731
2800
  this.starting = false;
2801
+ if (entry?.cancelled && !entry.id) entry.ownsCallback = false;
2732
2802
  }
2733
2803
  }
2734
2804
  callback(value, active) {
@@ -2754,6 +2824,7 @@ var ManualAccountLogin = class {
2754
2824
  if (!before.attempt || before.attempt.id !== active.id || before.attempt.phase !== "waiting-browser")
2755
2825
  throw new HttpFailure(409, "account_attempt_mismatch");
2756
2826
  this.owned(token, active.id);
2827
+ if (!this.bridge.available) throw new HttpFailure(503, "account_unavailable");
2757
2828
  const status = await this.bridge.submit(query);
2758
2829
  if (status === 400) throw new HttpFailure(400, "account_invalid_callback");
2759
2830
  const state = await this.state(token);
@@ -2771,10 +2842,15 @@ var ManualAccountLogin = class {
2771
2842
  attempt.cancelled = true;
2772
2843
  if (attempt.timer) clearTimeout(attempt.timer);
2773
2844
  if (attempt.id) {
2774
- attempt.cancellation ??= Promise.resolve().then(async () => {
2845
+ const cancellation = attempt.cancellation ??= Promise.resolve().then(async () => {
2775
2846
  await attempt.provider.cancelSignIn(attempt.id);
2776
2847
  });
2777
- await attempt.cancellation;
2848
+ try {
2849
+ await cancellation;
2850
+ } catch (error) {
2851
+ if (attempt.cancellation === cancellation) delete attempt.cancellation;
2852
+ throw error;
2853
+ }
2778
2854
  }
2779
2855
  }
2780
2856
  async reconcile(state) {
@@ -2830,6 +2906,17 @@ var ManualAccountLogin = class {
2830
2906
 
2831
2907
  // src/index.ts
2832
2908
  var name = "auth-remote";
2909
+ async function disposeResources(disposers) {
2910
+ const errors = [];
2911
+ for (const dispose of disposers) {
2912
+ try {
2913
+ await dispose();
2914
+ } catch (error) {
2915
+ errors.push(error);
2916
+ }
2917
+ }
2918
+ if (errors.length) throw new AggregateError(errors, "auth-remote: resource cleanup failed");
2919
+ }
2833
2920
  var AuthRemoteWebServer = class extends GuardedWebServer {
2834
2921
  static Config = Config;
2835
2922
  stateStore;
@@ -2880,7 +2967,7 @@ var AuthRemoteWebServer = class extends GuardedWebServer {
2880
2967
  await auth.enforceCurrentPolicy();
2881
2968
  this.stateStore = store;
2882
2969
  this.authService = auth;
2883
- await super[Service.init]();
2970
+ await outsideHmrTransaction(this.ctx, () => super[Service.init]());
2884
2971
  const port = this.port;
2885
2972
  if (port === void 0) throw new Error("auth-remote: listener has not bound a port");
2886
2973
  this.resolvedConfig = finalizeAuthConfig(this.pending, {
@@ -2899,7 +2986,8 @@ var AuthRemoteWebServer = class extends GuardedWebServer {
2899
2986
  this.ctx,
2900
2987
  auth,
2901
2988
  store,
2902
- this.pending.capabilities.version
2989
+ this.pending.capabilities.version,
2990
+ () => this.pending.manualAccountLogin.get()
2903
2991
  );
2904
2992
  accountLogin.install(this);
2905
2993
  admin = new AdminSocket(
@@ -2921,11 +3009,13 @@ var AuthRemoteWebServer = class extends GuardedWebServer {
2921
3009
  () => async () => {
2922
3010
  this.switchGate.set(new DenyGate());
2923
3011
  activeReadiness.detach();
2924
- await activeAccountLogin.dispose();
2925
- await activeAdmin.dispose();
2926
- await activeConnections.dispose();
2927
- auth.dispose();
2928
- await store.close();
3012
+ await disposeResources([
3013
+ () => activeAccountLogin.dispose(),
3014
+ () => activeAdmin.dispose(),
3015
+ () => activeConnections.dispose(),
3016
+ () => auth.dispose(),
3017
+ () => store.close()
3018
+ ]);
2929
3019
  },
2930
3020
  "auth-remote.storage-and-gate"
2931
3021
  );
@@ -2951,11 +3041,18 @@ var AuthRemoteWebServer = class extends GuardedWebServer {
2951
3041
  );
2952
3042
  } catch (error) {
2953
3043
  this.switchGate.set(new DenyGate());
2954
- await admin?.dispose();
2955
- await accountLogin?.dispose();
2956
- await connections?.dispose();
2957
- this.authService?.dispose();
2958
- await store.close();
3044
+ readiness?.detach();
3045
+ try {
3046
+ await disposeResources([
3047
+ () => accountLogin?.dispose(),
3048
+ () => admin?.dispose(),
3049
+ () => connections?.dispose(),
3050
+ () => this.authService?.dispose(),
3051
+ () => store.close()
3052
+ ]);
3053
+ } catch (cleanupError) {
3054
+ throw new AggregateError([error, cleanupError], "auth-remote: startup and cleanup failed");
3055
+ }
2959
3056
  throw error;
2960
3057
  }
2961
3058
  }