@huaqiu/dsh-auth 0.6.20 → 0.6.22

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.
package/lib/index.d.mts CHANGED
@@ -35,6 +35,17 @@ interface HuaqiuAuthConfig {
35
35
  hostSessionTtlSeconds?: number;
36
36
  /** Seconds remote token-validation results are cached. Default 60. */
37
37
  validationTtlSeconds?: number;
38
+ /**
39
+ * Subscription balances endpoint resolved by HQ Edge from `HQ_AI_ENV`
40
+ * (`GET /sub-api/subscriptions/balances/current`). Absent → `/ai-usage`
41
+ * returns null instead of calling a stale/default endpoint.
42
+ */
43
+ subscriptionBalancesUrl?: string;
44
+ /**
45
+ * Subscription landing-page origin resolved by HQ Edge from the SAME
46
+ * `HQ_AI_ENV`. Absent → the browser half keeps its standalone PROD default.
47
+ */
48
+ subscriptionOrigin?: string;
38
49
  }
39
50
  //#endregion
40
51
  //#region src/validation.d.ts
@@ -139,6 +150,23 @@ interface HuaqiuAuthService {
139
150
  * hq-edge, so the auth plugin's own login UI is suppressed.
140
151
  */
141
152
  readonly hostMode: boolean;
153
+ /**
154
+ * Resolved subscription balances endpoint injected by HQ Edge
155
+ * (`config.subscriptionBalancesUrl`), or null when none was configured.
156
+ * `/ai-usage` never falls back to a stale hardcoded environment endpoint.
157
+ */
158
+ readonly subscriptionBalancesUrl: string | null;
159
+ /**
160
+ * Origin of {@link subscriptionBalancesUrl} (e.g. `https://www.eda.cn`), used
161
+ * by the browser half for the GEN/ERC active-subscription calls. Null when no
162
+ * endpoint was configured — DSH Auth never hardcodes a production host.
163
+ */
164
+ readonly subscriptionApiBaseUrl: string | null;
165
+ /**
166
+ * Resolved subscription origin injected by HQ Edge (`config.subscriptionOrigin`),
167
+ * or null when none was configured (standalone keeps its PROD default).
168
+ */
169
+ readonly subscriptionOrigin: string | null;
142
170
  }
143
171
  declare class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
144
172
  private current;
@@ -165,6 +193,12 @@ declare class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
165
193
  });
166
194
  /** Host mode is active iff a host base URL was configured (see HostSessionResolver.enabled). */
167
195
  readonly hostMode: boolean;
196
+ /** Subscription balances endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
197
+ readonly subscriptionBalancesUrl: string | null;
198
+ /** Origin used for GEN/ERC active-subscription calls; null → unavailable. */
199
+ readonly subscriptionApiBaseUrl: string | null;
200
+ /** Subscription origin resolved by HQ Edge (`HQ_AI_ENV`); null → standalone. */
201
+ readonly subscriptionOrigin: string | null;
168
202
  readonly auth: HuaqiuAuthApi;
169
203
  /**
170
204
  * Spec §6.2 resolution order: host → pushed → persisted → null.
@@ -226,6 +260,67 @@ declare const AUTH_ROUTE_PREFIX = "/api/v1/huaqiu/auth";
226
260
  type AuthHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void> | void;
227
261
  declare function createAuthHandler(service: HuaqiuAuthService): AuthHandler;
228
262
  //#endregion
263
+ //#region src/apiKeySync.d.ts
264
+ /** Credential reference the `huaqiu` provider resolves per request. */
265
+ declare const HUAQIU_API_KEY_REF = "HUAQIU_API_KEY";
266
+ /** Default poll interval: 5 s, matching the DSH browser half's host refresh. */
267
+ declare const DEFAULT_HUAQIU_API_KEY_SYNC_MS = 5000;
268
+ /** Minimal writable credential store (the DSH `ctx.credentials` seam). */
269
+ interface CredentialStore {
270
+ set(ref: string, value: string): Promise<void>;
271
+ unset(ref: string): Promise<void>;
272
+ }
273
+ /**
274
+ * Resolves the credential store lazily on every sync round.
275
+ *
276
+ * The DSH `credentials` service may not be activated yet when this plugin
277
+ * boots (service activation order), and direct `ctx.credentials` property
278
+ * access throws "cannot get property ... without inject" in that window.
279
+ * Resolving through `ctx.get('credentials')` per round returns `undefined`
280
+ * while the service is unavailable — the round is skipped and retried on the
281
+ * next poll, so the sync self-heals once the service activates, without a
282
+ * restart (cordis guidance: "switch to `ctx.get('x')` with an absence check").
283
+ */
284
+ type CredentialStoreProvider = () => CredentialStore | null;
285
+ /** Logger surface used by the sync (kept small so tests can pass a spy). */
286
+ interface SyncLogger {
287
+ debug(msg: string, ctx?: Record<string, unknown>): void;
288
+ info(msg: string, ctx?: Record<string, unknown>): void;
289
+ warn(msg: string, ctx?: Record<string, unknown>): void;
290
+ }
291
+ declare class HuaqiuApiKeySync {
292
+ /** HQ Edge base URL ("" → disabled, matches HostSessionResolver.enabled). */
293
+ readonly baseUrl: string;
294
+ /** Token path on the host; default "/api/v1/auth/token". */
295
+ readonly path: string;
296
+ private readonly storeProvider;
297
+ private readonly log;
298
+ private readonly intervalMs;
299
+ private readonly doFetch;
300
+ private timer;
301
+ /** Guards the poll timer so overlapping rounds can never run (task §5.4). */
302
+ private inFlight;
303
+ /** Last token mirrored into the credential store (change detection). */
304
+ private lastToken;
305
+ constructor(
306
+ /** HQ Edge base URL ("" → disabled, matches HostSessionResolver.enabled). */
307
+ baseUrl: string,
308
+ /** Token path on the host; default "/api/v1/auth/token". */
309
+ path: string, storeProvider: CredentialStoreProvider, log: SyncLogger, intervalMs?: number, doFetch?: typeof fetch);
310
+ /** Host-mode sync is active iff a base URL was configured. */
311
+ get enabled(): boolean;
312
+ /** Kick off an immediate sync, then poll on a non-overlapping interval. */
313
+ start(): void;
314
+ /** Stop the poll timer. Safe to call more than once. */
315
+ dispose(): void;
316
+ /**
317
+ * One sync round: fetch the host token endpoint and mirror the verdict into
318
+ * the credential store. Exported separately from `start()` so tests can run
319
+ * rounds deterministically without timers.
320
+ */
321
+ syncNow(): Promise<void>;
322
+ }
323
+ //#endregion
229
324
  //#region src/index.d.ts
230
325
  declare const name = "@huaqiu/dsh-auth";
231
326
  declare const inject: readonly ["webServer"];
@@ -244,4 +339,4 @@ declare module '@deepseek-ai/cordis' {
244
339
  */
245
340
  declare function apply(ctx: Context, config?: Partial<HuaqiuAuthConfig>): void;
246
341
  //#endregion
247
- export { AUTH_ROUTE_PREFIX, type AuthHandler, type HuaqiuAuthApi, type HuaqiuAuthConfig, type HuaqiuAuthService, type HuaqiuUserInfo, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
342
+ export { AUTH_ROUTE_PREFIX, type AuthHandler, type CredentialStore, DEFAULT_HUAQIU_API_KEY_SYNC_MS, HUAQIU_API_KEY_REF, HuaqiuApiKeySync, type HuaqiuAuthApi, type HuaqiuAuthConfig, type HuaqiuAuthService, type HuaqiuUserInfo, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
package/lib/index.mjs CHANGED
@@ -53,13 +53,17 @@ function resolveHostConfig(config, env = process.env) {
53
53
  const parsed = Number.parseInt(vTtlRaw, 10);
54
54
  if (Number.isFinite(parsed) && parsed > 0) validationTtlSeconds = parsed;
55
55
  }
56
+ const subscriptionBalancesUrl = (config?.subscriptionBalancesUrl ?? env.HQ_AI_SUBSCRIPTION_BALANCES_URL ?? "").trim();
57
+ const subscriptionOrigin = (config?.subscriptionOrigin ?? env.HQ_AI_SUBSCRIPTION_ORIGIN ?? "").trim().replace(/\/+$/, "");
56
58
  return {
57
59
  hqEdgeBaseUrl: baseUrl,
58
60
  hostAuthPath,
59
61
  hostLoginPath,
60
62
  hostLogoutPath,
61
63
  hostSessionTtlSeconds: ttl,
62
- validationTtlSeconds
64
+ validationTtlSeconds,
65
+ subscriptionBalancesUrl,
66
+ subscriptionOrigin
63
67
  };
64
68
  }
65
69
  /**
@@ -173,6 +177,125 @@ function normalizeHostUser(data) {
173
177
  ...expiresAt !== void 0 ? { expiresAt } : {}
174
178
  };
175
179
  }
180
+ //#endregion
181
+ //#region src/apiKeySync.ts
182
+ /**
183
+ * Huaqiu AI gateway credential sync (host mode).
184
+ *
185
+ * The bundled DSH's `huaqiu` provider resolves its api key through the
186
+ * `HUAQIU_API_KEY` credential reference (overlay `apiKeyEnv`). In host mode the
187
+ * authoritative credential lives in HQ Edge (mirroring the EDA/KiCad host), and
188
+ * Workstream A strips `HUAQIU_API_KEY` from the child environment — so this
189
+ * sync is the ONLY source of that credential (task huaqiu-ai-gateway §5.5).
190
+ *
191
+ * The sync watches the HQ Edge token endpoint directly with a per-call
192
+ * loopback GET — deliberately NOT `hqEdge.auth.getAccessToken()`, whose
193
+ * initial-null cache has no invalidation path — and mirrors the token into
194
+ * `ctx.credentials` under the `HUAQIU_API_KEY` reference:
195
+ *
196
+ * - authenticated host session → `set` (only when the token value changed);
197
+ * - explicit unauthenticated verdict (2xx + `authenticated: false`, or a 2xx
198
+ * payload without a usable credential) → `unset`;
199
+ * - transient network error / non-2xx host answer → warn and leave the
200
+ * current value untouched (a blip must never log the operator out).
201
+ *
202
+ * The same path serves both the `hq-eda` and `kicad` hosts — host identity is
203
+ * HQ Edge configuration, never this plugin's concern.
204
+ */
205
+ /** Credential reference the `huaqiu` provider resolves per request. */
206
+ const HUAQIU_API_KEY_REF = "HUAQIU_API_KEY";
207
+ /** Default poll interval: 5 s, matching the DSH browser half's host refresh. */
208
+ const DEFAULT_HUAQIU_API_KEY_SYNC_MS = 5e3;
209
+ var HuaqiuApiKeySync = class {
210
+ baseUrl;
211
+ path;
212
+ storeProvider;
213
+ log;
214
+ intervalMs;
215
+ doFetch;
216
+ timer = null;
217
+ /** Guards the poll timer so overlapping rounds can never run (task §5.4). */
218
+ inFlight = false;
219
+ /** Last token mirrored into the credential store (change detection). */
220
+ lastToken = null;
221
+ constructor(baseUrl, path, storeProvider, log, intervalMs = DEFAULT_HUAQIU_API_KEY_SYNC_MS, doFetch = globalThis.fetch.bind(globalThis)) {
222
+ this.baseUrl = baseUrl;
223
+ this.path = path;
224
+ this.storeProvider = storeProvider;
225
+ this.log = log;
226
+ this.intervalMs = intervalMs;
227
+ this.doFetch = doFetch;
228
+ }
229
+ /** Host-mode sync is active iff a base URL was configured. */
230
+ get enabled() {
231
+ return this.baseUrl.length > 0;
232
+ }
233
+ /** Kick off an immediate sync, then poll on a non-overlapping interval. */
234
+ start() {
235
+ this.syncNow();
236
+ this.timer = setInterval(() => {
237
+ if (this.inFlight) return;
238
+ this.inFlight = true;
239
+ this.syncNow().finally(() => {
240
+ this.inFlight = false;
241
+ });
242
+ }, this.intervalMs);
243
+ if (typeof this.timer.unref === "function") this.timer.unref();
244
+ }
245
+ /** Stop the poll timer. Safe to call more than once. */
246
+ dispose() {
247
+ if (this.timer !== null) clearInterval(this.timer);
248
+ this.timer = null;
249
+ }
250
+ /**
251
+ * One sync round: fetch the host token endpoint and mirror the verdict into
252
+ * the credential store. Exported separately from `start()` so tests can run
253
+ * rounds deterministically without timers.
254
+ */
255
+ async syncNow() {
256
+ const store = this.storeProvider();
257
+ if (store === null) {
258
+ this.log.debug("huaqiu api-key sync skipped: credentials service unavailable");
259
+ return;
260
+ }
261
+ const url = `${this.baseUrl}${this.path}`;
262
+ let res = null;
263
+ let info = null;
264
+ try {
265
+ res = await this.doFetch(url, {
266
+ method: "GET",
267
+ headers: { accept: "application/json" }
268
+ });
269
+ if (res.ok) info = normalizeHostUser(await res.json());
270
+ } catch (err) {
271
+ this.log.warn("huaqiu api-key sync fetch failed", {
272
+ url,
273
+ error: String(err)
274
+ });
275
+ return;
276
+ }
277
+ if (info !== null && info.authenticated) {
278
+ if (info.token !== this.lastToken) {
279
+ this.lastToken = info.token;
280
+ await store.set(HUAQIU_API_KEY_REF, info.token);
281
+ this.log.info("huaqiu api-key credential synced", { userId: info.id });
282
+ }
283
+ return;
284
+ }
285
+ if (res !== null && res.ok) {
286
+ if (this.lastToken !== null) {
287
+ this.lastToken = null;
288
+ await store.unset(HUAQIU_API_KEY_REF);
289
+ this.log.info("huaqiu api-key credential cleared", { explicit: true });
290
+ }
291
+ return;
292
+ }
293
+ this.log.warn("huaqiu api-key sync rejected by host", {
294
+ url,
295
+ status: res?.status ?? null
296
+ });
297
+ }
298
+ };
176
299
  /**
177
300
  * Classifies the HTTP status of the validation request.
178
301
  *
@@ -328,6 +451,22 @@ var TokenValidator = class {
328
451
  */
329
452
  const PERSIST_FILE = "session.json";
330
453
  const PERSIST_DIR = () => dshHomePath("auth");
454
+ /** Host-only label for diagnostics (never log a complete AI usage URL). */
455
+ function safeHost$1(url) {
456
+ try {
457
+ return new URL(url).host;
458
+ } catch {
459
+ return "<invalid-url>";
460
+ }
461
+ }
462
+ /** Scheme + host origin of a URL, or null when it does not parse. */
463
+ function originOf(url) {
464
+ try {
465
+ return new URL(url).origin;
466
+ } catch {
467
+ return null;
468
+ }
469
+ }
331
470
  /**
332
471
  * Bounded wait for the host to confirm a logout. Shorter than the login wait
333
472
  * (which must cover a human completing the EDA dialog): logout is a host-side
@@ -409,14 +548,25 @@ var InMemoryHuaqiuAuthService = class {
409
548
  fetchImpl: this.doFetch
410
549
  });
411
550
  this.hostMode = this.host.enabled;
551
+ this.subscriptionBalancesUrl = resolved.subscriptionBalancesUrl?.length ? resolved.subscriptionBalancesUrl : null;
552
+ this.subscriptionApiBaseUrl = this.subscriptionBalancesUrl ? originOf(this.subscriptionBalancesUrl) : null;
553
+ this.subscriptionOrigin = resolved.subscriptionOrigin?.length ? resolved.subscriptionOrigin : null;
412
554
  this.log.info("auth service started", {
413
555
  hostMode: this.hostMode,
414
556
  hostAuthPath: resolved.hostAuthPath,
415
- hostSessionTtlSeconds: resolved.hostSessionTtlSeconds
557
+ hostSessionTtlSeconds: resolved.hostSessionTtlSeconds,
558
+ subscriptionBalancesHost: this.subscriptionBalancesUrl ? safeHost$1(this.subscriptionBalancesUrl) : null,
559
+ subscriptionOrigin: this.subscriptionOrigin
416
560
  });
417
561
  }
418
562
  /** Host mode is active iff a host base URL was configured (see HostSessionResolver.enabled). */
419
563
  hostMode;
564
+ /** Subscription balances endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
565
+ subscriptionBalancesUrl;
566
+ /** Origin used for GEN/ERC active-subscription calls; null → unavailable. */
567
+ subscriptionApiBaseUrl;
568
+ /** Subscription origin resolved by HQ Edge (`HQ_AI_ENV`); null → standalone. */
569
+ subscriptionOrigin;
420
570
  auth = {
421
571
  isAuthenticated: async () => {
422
572
  if (await this.resolve() === null) return false;
@@ -603,6 +753,70 @@ function toUserInfo(host) {
603
753
  ...host.expiresAt !== void 0 ? { expiresAt: host.expiresAt } : {}
604
754
  };
605
755
  }
756
+ function asRecord(value) {
757
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
758
+ }
759
+ /** `null`/missing/non-numeric → `null` (never a coerced 0). */
760
+ function numberOrNull(value) {
761
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
762
+ }
763
+ function numberOf(value) {
764
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
765
+ }
766
+ function stringOf(value) {
767
+ return typeof value === "string" ? value : "";
768
+ }
769
+ function parseGroup(raw) {
770
+ const group = asRecord(raw);
771
+ if (!group) return null;
772
+ if (typeof group.aiPoints !== "boolean") return null;
773
+ return {
774
+ id: numberOf(group.id),
775
+ groupCode: stringOf(group.groupCode),
776
+ groupName: stringOf(group.groupName),
777
+ quotaTotal: numberOrNull(group.quotaTotal),
778
+ quotaUsed: numberOrNull(group.quotaUsed),
779
+ quotaRemain: numberOrNull(group.quotaRemain),
780
+ quotaRemainPercent: numberOrNull(group.quotaRemainPercent),
781
+ aiPoints: group.aiPoints,
782
+ status: numberOf(group.status)
783
+ };
784
+ }
785
+ /**
786
+ * Validate an upstream payload against the authoritative schema.
787
+ * Returns `null` for a non-2xx-style envelope, a non-array `result`, or any
788
+ * malformed group — callers degrade to "unavailable" rather than guessing.
789
+ */
790
+ function parseSubscriptionBalancesResponse(payload) {
791
+ const body = asRecord(payload);
792
+ if (!body) return null;
793
+ if (body.code !== 2e5) return null;
794
+ if (!Array.isArray(body.result)) return null;
795
+ const result = body.result.map(parseGroup);
796
+ if (result.some((group) => group === null)) return null;
797
+ return {
798
+ code: body.code,
799
+ message: typeof body.message === "string" ? body.message : "",
800
+ result
801
+ };
802
+ }
803
+ /**
804
+ * Select the AI Points group and read its remaining percentage.
805
+ *
806
+ * No AI group → `null`; a missing/`null`/non-finite `quotaRemainPercent` →
807
+ * `null` (unavailable). `0` is preserved as a valid exhausted balance.
808
+ */
809
+ function selectAiUsage(response) {
810
+ const group = response?.result.find((entry) => entry.aiPoints === true);
811
+ if (!group) return null;
812
+ const percent = group.quotaRemainPercent;
813
+ if (percent === null || !Number.isFinite(percent)) return null;
814
+ return { quotaRemainPercent: percent };
815
+ }
816
+ /** Parse + select in one step — the single upstream→usage normalization. */
817
+ function aiUsageFromPayload(payload) {
818
+ return selectAiUsage(parseSubscriptionBalancesResponse(payload));
819
+ }
606
820
  //#endregion
607
821
  //#region src/routes.ts
608
822
  let _log = null;
@@ -643,55 +857,62 @@ async function fetchEdaUserProfile(token, doFetch = globalThis.fetch.bind(global
643
857
  }
644
858
  }
645
859
  const AUTH_ROUTE_PREFIX = "/api/v1/huaqiu/auth";
860
+ /** Host-only label for diagnostics (never log the full URL or the token). */
861
+ function safeHost(url) {
862
+ try {
863
+ return new URL(url).host;
864
+ } catch {
865
+ return "<invalid-url>";
866
+ }
867
+ }
646
868
  /**
647
- * The account's AI balance endpoint.
869
+ * Fetch and normalize AI usage for a token.
648
870
  *
649
- * It is served over PLAIN `http`, which is why the node half must be the one to
650
- * call it: a WebView fetch is refused by App Transport Security ("the resource
651
- * could not be loaded because the App Transport Security policy requires the
652
- * use of a secure connection") and, independently, by CORS (the response sends
653
- * no `Access-Control-Allow-Origin`). Node's fetch is subject to neither, and
654
- * this process already talks to this very host for the Huaqiu AI gateway
655
- * (`http://www.fdatasheets.com/user-rest/ai/v1`, see hq-edge's
656
- * `HUAQIU_AI_GATEWAY_BASE_URL`) — so the call is known to work from here.
657
- */
658
- const AI_USAGE_URL = "http://www.fdatasheets.com/user-rest/api/ai/usage";
659
- /**
660
- * Fetch the account's AI token usage for a token. Null on any failure (the UI
661
- * degrades to「—」) — never throws.
871
+ * `quotaRemainPercent` comes straight from the AI Points group — no local ratio
872
+ * is derived. `null` on any failure (invalid payload, timeout, network, non-2xx)
873
+ * so the UI degrades to「—」; never throws.
662
874
  *
663
- * The header is `X-Token` (capital T), which is what this endpoint expects; the
664
- * subscription endpoint next door uses `x-token` + `X-User-Id`.
875
+ * The upstream header is `X-Token` (capital T).
665
876
  */
666
- async function fetchAiTokenUsage(token, doFetch = globalThis.fetch.bind(globalThis)) {
877
+ async function fetchAiUsage(token, subscriptionBalancesUrl, doFetch = globalThis.fetch.bind(globalThis), options = {}) {
878
+ const timeoutMs = options.timeoutMs ?? 1e4;
879
+ const controller = new AbortController();
880
+ const onAbort = () => controller.abort(options.signal?.reason);
881
+ if (options.signal) {
882
+ if (options.signal.aborted) controller.abort(options.signal.reason);
883
+ else options.signal.addEventListener("abort", onAbort, { once: true });
884
+ }
885
+ const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("timeout")), timeoutMs);
886
+ const host = safeHost(subscriptionBalancesUrl);
667
887
  try {
668
- const res = await doFetch(AI_USAGE_URL, {
888
+ const res = await doFetch(subscriptionBalancesUrl, {
669
889
  method: "GET",
670
890
  headers: {
671
- Accept: "application/json, text/plain, */*",
672
- "Content-Type": "application/json",
891
+ Accept: "application/json",
892
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
673
893
  "X-Token": token
674
- }
894
+ },
895
+ signal: controller.signal
675
896
  });
676
- if (!res.ok) return null;
677
- const body = await res.json();
678
- if (body.code !== 2e5 || !body.result) return null;
679
- const result = body.result;
680
- const num = (key) => {
681
- const v = Number(result[key]);
682
- return Number.isFinite(v) ? v : 0;
683
- };
684
- return {
685
- availablePoints: num("availablePoints"),
686
- availableQuota: num("availableQuota"),
687
- availableUsd: num("availableUsd"),
688
- usedPoints: num("usedPoints"),
689
- usedQuota: num("usedQuota"),
690
- usedUsd: num("usedUsd")
691
- };
897
+ if (!res.ok) {
898
+ log$1().warn("subscription balances request failed", {
899
+ host,
900
+ status: res.status
901
+ });
902
+ return null;
903
+ }
904
+ const usage = aiUsageFromPayload(await res.json());
905
+ if (!usage) log$1().warn("subscription balances payload unusable", { host });
906
+ return usage;
692
907
  } catch (err) {
693
- log$1().warn("fetchAiTokenUsage failed", { error: String(err?.message || err) });
908
+ log$1().warn("subscription balances request failed", {
909
+ host,
910
+ error: String(err?.message || err)
911
+ });
694
912
  return null;
913
+ } finally {
914
+ clearTimeout(timer);
915
+ options.signal?.removeEventListener("abort", onAbort);
695
916
  }
696
917
  }
697
918
  function sendJson(res, status, body) {
@@ -749,7 +970,11 @@ function createAuthHandler(service) {
749
970
  return;
750
971
  }
751
972
  if (req.method === "GET" && pathname === `/api/v1/huaqiu/auth/config`) {
752
- sendJson(res, 200, { hostMode: service.hostMode });
973
+ sendJson(res, 200, {
974
+ hostMode: service.hostMode,
975
+ subscriptionOrigin: service.subscriptionOrigin,
976
+ subscriptionApiBaseUrl: service.subscriptionApiBaseUrl
977
+ });
753
978
  return;
754
979
  }
755
980
  if (req.method === "GET" && pathname === `/api/v1/huaqiu/auth/user-info`) {
@@ -763,11 +988,20 @@ function createAuthHandler(service) {
763
988
  }
764
989
  if (req.method === "GET" && pathname === `/api/v1/huaqiu/auth/ai-usage`) {
765
990
  const token = await service.auth.getAccessToken();
766
- if (!token) {
991
+ if (!token || !service.subscriptionBalancesUrl) {
767
992
  sendJson(res, 200, { usage: null });
768
993
  return;
769
994
  }
770
- sendJson(res, 200, { usage: await fetchAiTokenUsage(token) });
995
+ const controller = new AbortController();
996
+ const onClose = () => controller.abort();
997
+ res.on("close", onClose);
998
+ let usage;
999
+ try {
1000
+ usage = await fetchAiUsage(token, service.subscriptionBalancesUrl, globalThis.fetch.bind(globalThis), { signal: controller.signal });
1001
+ } finally {
1002
+ res.off("close", onClose);
1003
+ }
1004
+ sendJson(res, 200, { usage });
771
1005
  return;
772
1006
  }
773
1007
  if (req.method === "POST" && pathname === `/api/v1/huaqiu/auth/login`) {
@@ -815,10 +1049,27 @@ function apply(ctx, config) {
815
1049
  path: AUTH_ROUTE_PREFIX,
816
1050
  handler: createAuthHandler(service)
817
1051
  }));
1052
+ if (service.hostMode) ctx.effect(() => {
1053
+ const resolved = resolveHostConfig(config);
1054
+ const sync = new HuaqiuApiKeySync(resolved.hqEdgeBaseUrl ?? "", resolved.hostAuthPath ?? "/api/v1/auth/token", () => {
1055
+ const credentials = ctx.get("credentials");
1056
+ if (credentials === void 0) return null;
1057
+ return {
1058
+ set: (ref, value) => credentials.set(ref, value),
1059
+ unset: (ref) => credentials.unset(ref)
1060
+ };
1061
+ }, {
1062
+ debug: (msg, ctx2) => log.debug(msg, ctx2),
1063
+ info: (msg, ctx2) => log.info(msg, ctx2),
1064
+ warn: (msg, ctx2) => log.warn(msg, ctx2)
1065
+ });
1066
+ sync.start();
1067
+ return () => sync.dispose();
1068
+ });
818
1069
  log.info("dsh-auth node half ready", {
819
1070
  routes: AUTH_ROUTE_PREFIX,
820
1071
  hostMode: service.hostMode
821
1072
  });
822
1073
  }
823
1074
  //#endregion
824
- export { AUTH_ROUTE_PREFIX, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
1075
+ export { AUTH_ROUTE_PREFIX, DEFAULT_HUAQIU_API_KEY_SYNC_MS, HUAQIU_API_KEY_REF, HuaqiuApiKeySync, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huaqiu/dsh-auth",
3
- "version": "0.6.20",
3
+ "version": "0.6.22",
4
4
  "type": "module",
5
5
  "main": "./lib/index.mjs",
6
6
  "types": "./lib/index.d.mts",
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@deepseek-ai/dsh-home-paths": "^0.1.0-rc.0",
36
- "@huaqiu/dsh-plugin-log": "0.6.20"
36
+ "@huaqiu/dsh-plugin-log": "0.6.22"
37
37
  },
38
38
  "files": [
39
39
  "lib",