@huaqiu/dsh-auth 0.6.19 → 0.6.21

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
+ * AI token-usage endpoint resolved by HQ Edge from `HQ_AI_ENV` (task
40
+ * ai-env-swithcing-for-internal-test.md). Absent → `/ai-usage` returns null
41
+ * instead of calling a stale/default endpoint.
42
+ */
43
+ aiUsageUrl?: 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,17 @@ 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 AI token-usage endpoint injected by HQ Edge (`config.aiUsageUrl`),
155
+ * or null when none was configured. `/ai-usage` never falls back to a stale
156
+ * hardcoded environment endpoint.
157
+ */
158
+ readonly aiUsageUrl: string | null;
159
+ /**
160
+ * Resolved subscription origin injected by HQ Edge (`config.subscriptionOrigin`),
161
+ * or null when none was configured (standalone keeps its PROD default).
162
+ */
163
+ readonly subscriptionOrigin: string | null;
142
164
  }
143
165
  declare class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
144
166
  private current;
@@ -165,6 +187,10 @@ declare class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
165
187
  });
166
188
  /** Host mode is active iff a host base URL was configured (see HostSessionResolver.enabled). */
167
189
  readonly hostMode: boolean;
190
+ /** AI usage endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
191
+ readonly aiUsageUrl: string | null;
192
+ /** Subscription origin resolved by HQ Edge (`HQ_AI_ENV`); null → standalone. */
193
+ readonly subscriptionOrigin: string | null;
168
194
  readonly auth: HuaqiuAuthApi;
169
195
  /**
170
196
  * Spec §6.2 resolution order: host → pushed → persisted → null.
@@ -226,6 +252,67 @@ declare const AUTH_ROUTE_PREFIX = "/api/v1/huaqiu/auth";
226
252
  type AuthHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void> | void;
227
253
  declare function createAuthHandler(service: HuaqiuAuthService): AuthHandler;
228
254
  //#endregion
255
+ //#region src/apiKeySync.d.ts
256
+ /** Credential reference the `huaqiu` provider resolves per request. */
257
+ declare const HUAQIU_API_KEY_REF = "HUAQIU_API_KEY";
258
+ /** Default poll interval: 5 s, matching the DSH browser half's host refresh. */
259
+ declare const DEFAULT_HUAQIU_API_KEY_SYNC_MS = 5000;
260
+ /** Minimal writable credential store (the DSH `ctx.credentials` seam). */
261
+ interface CredentialStore {
262
+ set(ref: string, value: string): Promise<void>;
263
+ unset(ref: string): Promise<void>;
264
+ }
265
+ /**
266
+ * Resolves the credential store lazily on every sync round.
267
+ *
268
+ * The DSH `credentials` service may not be activated yet when this plugin
269
+ * boots (service activation order), and direct `ctx.credentials` property
270
+ * access throws "cannot get property ... without inject" in that window.
271
+ * Resolving through `ctx.get('credentials')` per round returns `undefined`
272
+ * while the service is unavailable — the round is skipped and retried on the
273
+ * next poll, so the sync self-heals once the service activates, without a
274
+ * restart (cordis guidance: "switch to `ctx.get('x')` with an absence check").
275
+ */
276
+ type CredentialStoreProvider = () => CredentialStore | null;
277
+ /** Logger surface used by the sync (kept small so tests can pass a spy). */
278
+ interface SyncLogger {
279
+ debug(msg: string, ctx?: Record<string, unknown>): void;
280
+ info(msg: string, ctx?: Record<string, unknown>): void;
281
+ warn(msg: string, ctx?: Record<string, unknown>): void;
282
+ }
283
+ declare class HuaqiuApiKeySync {
284
+ /** HQ Edge base URL ("" → disabled, matches HostSessionResolver.enabled). */
285
+ readonly baseUrl: string;
286
+ /** Token path on the host; default "/api/v1/auth/token". */
287
+ readonly path: string;
288
+ private readonly storeProvider;
289
+ private readonly log;
290
+ private readonly intervalMs;
291
+ private readonly doFetch;
292
+ private timer;
293
+ /** Guards the poll timer so overlapping rounds can never run (task §5.4). */
294
+ private inFlight;
295
+ /** Last token mirrored into the credential store (change detection). */
296
+ private lastToken;
297
+ constructor(
298
+ /** HQ Edge base URL ("" → disabled, matches HostSessionResolver.enabled). */
299
+ baseUrl: string,
300
+ /** Token path on the host; default "/api/v1/auth/token". */
301
+ path: string, storeProvider: CredentialStoreProvider, log: SyncLogger, intervalMs?: number, doFetch?: typeof fetch);
302
+ /** Host-mode sync is active iff a base URL was configured. */
303
+ get enabled(): boolean;
304
+ /** Kick off an immediate sync, then poll on a non-overlapping interval. */
305
+ start(): void;
306
+ /** Stop the poll timer. Safe to call more than once. */
307
+ dispose(): void;
308
+ /**
309
+ * One sync round: fetch the host token endpoint and mirror the verdict into
310
+ * the credential store. Exported separately from `start()` so tests can run
311
+ * rounds deterministically without timers.
312
+ */
313
+ syncNow(): Promise<void>;
314
+ }
315
+ //#endregion
229
316
  //#region src/index.d.ts
230
317
  declare const name = "@huaqiu/dsh-auth";
231
318
  declare const inject: readonly ["webServer"];
@@ -244,4 +331,4 @@ declare module '@deepseek-ai/cordis' {
244
331
  */
245
332
  declare function apply(ctx: Context, config?: Partial<HuaqiuAuthConfig>): void;
246
333
  //#endregion
247
- export { AUTH_ROUTE_PREFIX, type AuthHandler, type HuaqiuAuthApi, type HuaqiuAuthConfig, type HuaqiuAuthService, type HuaqiuUserInfo, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
334
+ 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 aiUsageUrl = (config?.aiUsageUrl ?? env.HQ_AI_USAGE_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
+ aiUsageUrl,
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,14 @@ 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(url) {
456
+ try {
457
+ return new URL(url).host;
458
+ } catch {
459
+ return "<invalid-url>";
460
+ }
461
+ }
331
462
  /**
332
463
  * Bounded wait for the host to confirm a logout. Shorter than the login wait
333
464
  * (which must cover a human completing the EDA dialog): logout is a host-side
@@ -409,14 +540,22 @@ var InMemoryHuaqiuAuthService = class {
409
540
  fetchImpl: this.doFetch
410
541
  });
411
542
  this.hostMode = this.host.enabled;
543
+ this.aiUsageUrl = resolved.aiUsageUrl?.length ? resolved.aiUsageUrl : null;
544
+ this.subscriptionOrigin = resolved.subscriptionOrigin?.length ? resolved.subscriptionOrigin : null;
412
545
  this.log.info("auth service started", {
413
546
  hostMode: this.hostMode,
414
547
  hostAuthPath: resolved.hostAuthPath,
415
- hostSessionTtlSeconds: resolved.hostSessionTtlSeconds
548
+ hostSessionTtlSeconds: resolved.hostSessionTtlSeconds,
549
+ aiUsageHost: this.aiUsageUrl ? safeHost(this.aiUsageUrl) : null,
550
+ subscriptionOrigin: this.subscriptionOrigin
416
551
  });
417
552
  }
418
553
  /** Host mode is active iff a host base URL was configured (see HostSessionResolver.enabled). */
419
554
  hostMode;
555
+ /** AI usage endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
556
+ aiUsageUrl;
557
+ /** Subscription origin resolved by HQ Edge (`HQ_AI_ENV`); null → standalone. */
558
+ subscriptionOrigin;
420
559
  auth = {
421
560
  isAuthenticated: async () => {
422
561
  if (await this.resolve() === null) return false;
@@ -644,28 +783,15 @@ async function fetchEdaUserProfile(token, doFetch = globalThis.fetch.bind(global
644
783
  }
645
784
  const AUTH_ROUTE_PREFIX = "/api/v1/huaqiu/auth";
646
785
  /**
647
- * The account's AI balance endpoint.
648
- *
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
786
  * Fetch the account's AI token usage for a token. Null on any failure (the UI
661
787
  * degrades to「—」) — never throws.
662
788
  *
663
789
  * The header is `X-Token` (capital T), which is what this endpoint expects; the
664
790
  * subscription endpoint next door uses `x-token` + `X-User-Id`.
665
791
  */
666
- async function fetchAiTokenUsage(token, doFetch = globalThis.fetch.bind(globalThis)) {
792
+ async function fetchAiTokenUsage(token, usageUrl, doFetch = globalThis.fetch.bind(globalThis)) {
667
793
  try {
668
- const res = await doFetch(AI_USAGE_URL, {
794
+ const res = await doFetch(usageUrl, {
669
795
  method: "GET",
670
796
  headers: {
671
797
  Accept: "application/json, text/plain, */*",
@@ -749,7 +875,10 @@ function createAuthHandler(service) {
749
875
  return;
750
876
  }
751
877
  if (req.method === "GET" && pathname === `/api/v1/huaqiu/auth/config`) {
752
- sendJson(res, 200, { hostMode: service.hostMode });
878
+ sendJson(res, 200, {
879
+ hostMode: service.hostMode,
880
+ subscriptionOrigin: service.subscriptionOrigin
881
+ });
753
882
  return;
754
883
  }
755
884
  if (req.method === "GET" && pathname === `/api/v1/huaqiu/auth/user-info`) {
@@ -763,11 +892,11 @@ function createAuthHandler(service) {
763
892
  }
764
893
  if (req.method === "GET" && pathname === `/api/v1/huaqiu/auth/ai-usage`) {
765
894
  const token = await service.auth.getAccessToken();
766
- if (!token) {
895
+ if (!token || !service.aiUsageUrl) {
767
896
  sendJson(res, 200, { usage: null });
768
897
  return;
769
898
  }
770
- sendJson(res, 200, { usage: await fetchAiTokenUsage(token) });
899
+ sendJson(res, 200, { usage: await fetchAiTokenUsage(token, service.aiUsageUrl) });
771
900
  return;
772
901
  }
773
902
  if (req.method === "POST" && pathname === `/api/v1/huaqiu/auth/login`) {
@@ -815,10 +944,27 @@ function apply(ctx, config) {
815
944
  path: AUTH_ROUTE_PREFIX,
816
945
  handler: createAuthHandler(service)
817
946
  }));
947
+ if (service.hostMode) ctx.effect(() => {
948
+ const resolved = resolveHostConfig(config);
949
+ const sync = new HuaqiuApiKeySync(resolved.hqEdgeBaseUrl ?? "", resolved.hostAuthPath ?? "/api/v1/auth/token", () => {
950
+ const credentials = ctx.get("credentials");
951
+ if (credentials === void 0) return null;
952
+ return {
953
+ set: (ref, value) => credentials.set(ref, value),
954
+ unset: (ref) => credentials.unset(ref)
955
+ };
956
+ }, {
957
+ debug: (msg, ctx2) => log.debug(msg, ctx2),
958
+ info: (msg, ctx2) => log.info(msg, ctx2),
959
+ warn: (msg, ctx2) => log.warn(msg, ctx2)
960
+ });
961
+ sync.start();
962
+ return () => sync.dispose();
963
+ });
818
964
  log.info("dsh-auth node half ready", {
819
965
  routes: AUTH_ROUTE_PREFIX,
820
966
  hostMode: service.hostMode
821
967
  });
822
968
  }
823
969
  //#endregion
824
- export { AUTH_ROUTE_PREFIX, InMemoryHuaqiuAuthService, apply, createAuthHandler, inject, name };
970
+ 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.19",
3
+ "version": "0.6.21",
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.19"
36
+ "@huaqiu/dsh-plugin-log": "0.6.21"
37
37
  },
38
38
  "files": [
39
39
  "lib",
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Huaqiu AI gateway credential sync (host mode).
3
+ *
4
+ * The bundled DSH's `huaqiu` provider resolves its api key through the
5
+ * `HUAQIU_API_KEY` credential reference (overlay `apiKeyEnv`). In host mode the
6
+ * authoritative credential lives in HQ Edge (mirroring the EDA/KiCad host), and
7
+ * Workstream A strips `HUAQIU_API_KEY` from the child environment — so this
8
+ * sync is the ONLY source of that credential (task huaqiu-ai-gateway §5.5).
9
+ *
10
+ * The sync watches the HQ Edge token endpoint directly with a per-call
11
+ * loopback GET — deliberately NOT `hqEdge.auth.getAccessToken()`, whose
12
+ * initial-null cache has no invalidation path — and mirrors the token into
13
+ * `ctx.credentials` under the `HUAQIU_API_KEY` reference:
14
+ *
15
+ * - authenticated host session → `set` (only when the token value changed);
16
+ * - explicit unauthenticated verdict (2xx + `authenticated: false`, or a 2xx
17
+ * payload without a usable credential) → `unset`;
18
+ * - transient network error / non-2xx host answer → warn and leave the
19
+ * current value untouched (a blip must never log the operator out).
20
+ *
21
+ * The same path serves both the `hq-eda` and `kicad` hosts — host identity is
22
+ * HQ Edge configuration, never this plugin's concern.
23
+ */
24
+ import { normalizeHostUser, type ResolvedHostUser } from './host.js'
25
+
26
+ /** Credential reference the `huaqiu` provider resolves per request. */
27
+ export const HUAQIU_API_KEY_REF = 'HUAQIU_API_KEY'
28
+
29
+ /** Default poll interval: 5 s, matching the DSH browser half's host refresh. */
30
+ export const DEFAULT_HUAQIU_API_KEY_SYNC_MS = 5000
31
+
32
+ /** Minimal writable credential store (the DSH `ctx.credentials` seam). */
33
+ export interface CredentialStore {
34
+ set(ref: string, value: string): Promise<void>
35
+ unset(ref: string): Promise<void>
36
+ }
37
+
38
+ /**
39
+ * Resolves the credential store lazily on every sync round.
40
+ *
41
+ * The DSH `credentials` service may not be activated yet when this plugin
42
+ * boots (service activation order), and direct `ctx.credentials` property
43
+ * access throws "cannot get property ... without inject" in that window.
44
+ * Resolving through `ctx.get('credentials')` per round returns `undefined`
45
+ * while the service is unavailable — the round is skipped and retried on the
46
+ * next poll, so the sync self-heals once the service activates, without a
47
+ * restart (cordis guidance: "switch to `ctx.get('x')` with an absence check").
48
+ */
49
+ export type CredentialStoreProvider = () => CredentialStore | null
50
+
51
+ /** Logger surface used by the sync (kept small so tests can pass a spy). */
52
+ export interface SyncLogger {
53
+ debug(msg: string, ctx?: Record<string, unknown>): void
54
+ info(msg: string, ctx?: Record<string, unknown>): void
55
+ warn(msg: string, ctx?: Record<string, unknown>): void
56
+ }
57
+
58
+ export class HuaqiuApiKeySync {
59
+ private timer: NodeJS.Timeout | null = null
60
+ /** Guards the poll timer so overlapping rounds can never run (task §5.4). */
61
+ private inFlight = false
62
+ /** Last token mirrored into the credential store (change detection). */
63
+ private lastToken: string | null = null
64
+
65
+ constructor(
66
+ /** HQ Edge base URL ("" → disabled, matches HostSessionResolver.enabled). */
67
+ readonly baseUrl: string,
68
+ /** Token path on the host; default "/api/v1/auth/token". */
69
+ readonly path: string,
70
+ private readonly storeProvider: CredentialStoreProvider,
71
+ private readonly log: SyncLogger,
72
+ private readonly intervalMs: number = DEFAULT_HUAQIU_API_KEY_SYNC_MS,
73
+ private readonly doFetch: typeof fetch = globalThis.fetch.bind(globalThis),
74
+ ) {}
75
+
76
+ /** Host-mode sync is active iff a base URL was configured. */
77
+ get enabled(): boolean {
78
+ return this.baseUrl.length > 0
79
+ }
80
+
81
+ /** Kick off an immediate sync, then poll on a non-overlapping interval. */
82
+ start(): void {
83
+ void this.syncNow()
84
+ this.timer = setInterval(() => {
85
+ if (this.inFlight) return
86
+ this.inFlight = true
87
+ void this.syncNow().finally(() => {
88
+ this.inFlight = false
89
+ })
90
+ }, this.intervalMs)
91
+ // Never keep the DSH process alive just for this timer.
92
+ if (typeof this.timer.unref === 'function') this.timer.unref()
93
+ }
94
+
95
+ /** Stop the poll timer. Safe to call more than once. */
96
+ dispose(): void {
97
+ if (this.timer !== null) clearInterval(this.timer)
98
+ this.timer = null
99
+ }
100
+
101
+ /**
102
+ * One sync round: fetch the host token endpoint and mirror the verdict into
103
+ * the credential store. Exported separately from `start()` so tests can run
104
+ * rounds deterministically without timers.
105
+ */
106
+ async syncNow(): Promise<void> {
107
+ // Resolve the credential store lazily: the `credentials` service may not
108
+ // be activated yet while this plugin boots (activation order). Skipping
109
+ // the round is safe — the next poll retries once the service is live.
110
+ const store = this.storeProvider()
111
+ if (store === null) {
112
+ this.log.debug('huaqiu api-key sync skipped: credentials service unavailable')
113
+ return
114
+ }
115
+ const url = `${this.baseUrl}${this.path}`
116
+ let res: Response | null = null
117
+ let info: ResolvedHostUser | null = null
118
+ try {
119
+ res = await this.doFetch(url, {
120
+ method: 'GET',
121
+ headers: { accept: 'application/json' },
122
+ })
123
+ if (res.ok) {
124
+ info = normalizeHostUser(await res.json() as Record<string, unknown>)
125
+ }
126
+ } catch (err) {
127
+ // Transient network error: never unset — a blip must not log the
128
+ // operator out (task §5.4).
129
+ this.log.warn('huaqiu api-key sync fetch failed', { url, error: String(err) })
130
+ return
131
+ }
132
+ if (info !== null && info.authenticated) {
133
+ if (info.token !== this.lastToken) {
134
+ this.lastToken = info.token
135
+ await store.set(HUAQIU_API_KEY_REF, info.token)
136
+ this.log.info('huaqiu api-key credential synced', { userId: info.id })
137
+ }
138
+ return
139
+ }
140
+ // A 2xx answer without a usable authenticated credential is the HOST'S
141
+ // explicit verdict (logout / not-yet-logged-in / cleared token) — mirror
142
+ // the cleared state. Anything else (non-2xx) is a host-side error: warn
143
+ // and keep the current value.
144
+ if (res !== null && res.ok) {
145
+ if (this.lastToken !== null) {
146
+ this.lastToken = null
147
+ await store.unset(HUAQIU_API_KEY_REF)
148
+ this.log.info('huaqiu api-key credential cleared', { explicit: true })
149
+ }
150
+ return
151
+ }
152
+ this.log.warn('huaqiu api-key sync rejected by host', {
153
+ url,
154
+ status: res?.status ?? null,
155
+ })
156
+ }
157
+ }
@@ -122,6 +122,11 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
122
122
  let hostMode = false
123
123
  let hostSession: AuthTokenPayload | null = null
124
124
  let hostSessionLoaded = false
125
+ /**
126
+ * Subscription origin resolved by HQ Edge from `HQ_AI_ENV` and served on the
127
+ * node `/config` route. Null in standalone → lib's PROD fallback.
128
+ */
129
+ let subscriptionOrigin: string | null = null
125
130
 
126
131
  const emit = (info: AuthTokenPayload | null): void => {
127
132
  for (const listener of listeners) listener(info)
@@ -258,7 +263,10 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
258
263
  if (hostMode && !hostSessionLoaded) await resolveHost()
259
264
  const token = await auth.getAccessToken()
260
265
  if (!token) return
261
- const url = buildSubscriptionUrl({ token })
266
+ const url = buildSubscriptionUrl({
267
+ token,
268
+ ...(subscriptionOrigin ? { origin: subscriptionOrigin } : {}),
269
+ })
262
270
  if (hostMode) {
263
271
  // The EDA host owns the UI — open its native dialog (fire-and-forget).
264
272
  // No dialog service → no-op; the caller keeps its subscribe button.
@@ -335,9 +343,12 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
335
343
  const prevToken = hostSession?.token ?? storage.get()?.token ?? null
336
344
  let mode = false
337
345
  try {
338
- mode = await transport.fetchHostMode()
346
+ const runtime = await transport.fetchRuntimeConfig()
347
+ mode = runtime.hostMode
348
+ subscriptionOrigin = runtime.subscriptionOrigin
339
349
  } catch {
340
350
  mode = false
351
+ subscriptionOrigin = null
341
352
  }
342
353
  hostMode = mode
343
354
  hostSessionLoaded = false
@@ -375,6 +386,7 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
375
386
  hostMode = false
376
387
  hostSession = null
377
388
  hostSessionLoaded = false
389
+ subscriptionOrigin = null
378
390
  void trustedOrigin // referenced for clarity: the auth iframe URL comes from it
379
391
  },
380
392
  }
@@ -34,6 +34,7 @@ const zh = {
34
34
  'subscription.package': '套餐:{name}',
35
35
  'subscription.quota': '可用次数:{count}',
36
36
  'subscription.quotaCount': '{used} / {total}次',
37
+ 'subscription.quotaPercent': '{percent}%',
37
38
  'subscription.noQuota': '无可用次数',
38
39
  'subscription.unsubscribed': '未订阅',
39
40
  'subscription.subscribe': '订阅 / 升级',
@@ -45,13 +46,12 @@ const zh = {
45
46
  'subscription.upgrade': '订阅 / 升级套餐',
46
47
  'subscription.online': '在线',
47
48
  // AI token usage (`/user-rest/api/ai/usage`) — the third metric beside GEN
48
- // and ERC. `aiUsageCount` is the available/total point balance (the same
49
- // "what is left" convention as the GEN/ERC cards' `currentQuota`);
50
- // `aiUsagePercent` is the hover detail, because the bar itself only shows
51
- // the ratio visually.
49
+ // and ERC. The headline is the usage percent (e.g. "65%"); the exact
50
+ // "{available} / {total} 点" balance is shown as the hover title, because the
51
+ // bar itself only shows the ratio visually.
52
52
  'subscription.ai': 'AI 用量',
53
53
  'subscription.aiUsageCount': '{available} / {total} 点',
54
- 'subscription.aiUsagePercent': '剩余 {percent}%',
54
+ 'subscription.aiUsagePercent': '{percent}%',
55
55
  'subscription.aiUsageUnknown': '暂无数据',
56
56
 
57
57
  'card.title': '华秋 EDA AI(eda.cn)登录',
@@ -87,6 +87,7 @@ const en: Record<AuthCopyKey, string> = {
87
87
  'subscription.package': 'Plan: {name}',
88
88
  'subscription.quota': 'Available: {count}',
89
89
  'subscription.quotaCount': '{used} / {total}',
90
+ 'subscription.quotaPercent': '{percent}%',
90
91
  'subscription.noQuota': 'No quota left',
91
92
  'subscription.unsubscribed': 'Not subscribed',
92
93
  'subscription.subscribe': 'Subscribe / Upgrade',
@@ -98,13 +99,12 @@ const en: Record<AuthCopyKey, string> = {
98
99
  'subscription.upgrade': 'Subscribe / Upgrade plan',
99
100
  'subscription.online': 'Online',
100
101
  // AI token usage (`/user-rest/api/ai/usage`) — the third metric beside GEN
101
- // and ERC. `aiUsageCount` is the available/total point balance (the same
102
- // "what is left" convention as the GEN/ERC cards' `currentQuota`);
103
- // `aiUsagePercent` is the hover detail, because the bar itself only shows
104
- // the ratio visually.
102
+ // and ERC. The headline is the usage percent (e.g. "65%"); the exact
103
+ // "{available} / {total} pts" balance is shown as the hover title, because
104
+ // the bar itself only shows the ratio visually.
105
105
  'subscription.ai': 'AI usage',
106
106
  'subscription.aiUsageCount': '{available} / {total} pts',
107
- 'subscription.aiUsagePercent': '{percent}% remaining',
107
+ 'subscription.aiUsagePercent': '{percent}%',
108
108
  'subscription.aiUsageUnknown': 'No data',
109
109
 
110
110
  'card.title': 'Huaqiu EDA AI (eda.cn) login',