@huaqiu/dsh-auth 0.6.21 → 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
@@ -36,11 +36,11 @@ interface HuaqiuAuthConfig {
36
36
  /** Seconds remote token-validation results are cached. Default 60. */
37
37
  validationTtlSeconds?: number;
38
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.
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
42
  */
43
- aiUsageUrl?: string;
43
+ subscriptionBalancesUrl?: string;
44
44
  /**
45
45
  * Subscription landing-page origin resolved by HQ Edge from the SAME
46
46
  * `HQ_AI_ENV`. Absent → the browser half keeps its standalone PROD default.
@@ -151,11 +151,17 @@ interface HuaqiuAuthService {
151
151
  */
152
152
  readonly hostMode: boolean;
153
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.
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
157
  */
158
- readonly aiUsageUrl: string | null;
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;
159
165
  /**
160
166
  * Resolved subscription origin injected by HQ Edge (`config.subscriptionOrigin`),
161
167
  * or null when none was configured (standalone keeps its PROD default).
@@ -187,8 +193,10 @@ declare class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
187
193
  });
188
194
  /** Host mode is active iff a host base URL was configured (see HostSessionResolver.enabled). */
189
195
  readonly hostMode: boolean;
190
- /** AI usage endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
191
- readonly aiUsageUrl: string | null;
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;
192
200
  /** Subscription origin resolved by HQ Edge (`HQ_AI_ENV`); null → standalone. */
193
201
  readonly subscriptionOrigin: string | null;
194
202
  readonly auth: HuaqiuAuthApi;
package/lib/index.mjs CHANGED
@@ -53,7 +53,7 @@ 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();
56
+ const subscriptionBalancesUrl = (config?.subscriptionBalancesUrl ?? env.HQ_AI_SUBSCRIPTION_BALANCES_URL ?? "").trim();
57
57
  const subscriptionOrigin = (config?.subscriptionOrigin ?? env.HQ_AI_SUBSCRIPTION_ORIGIN ?? "").trim().replace(/\/+$/, "");
58
58
  return {
59
59
  hqEdgeBaseUrl: baseUrl,
@@ -62,7 +62,7 @@ function resolveHostConfig(config, env = process.env) {
62
62
  hostLogoutPath,
63
63
  hostSessionTtlSeconds: ttl,
64
64
  validationTtlSeconds,
65
- aiUsageUrl,
65
+ subscriptionBalancesUrl,
66
66
  subscriptionOrigin
67
67
  };
68
68
  }
@@ -452,13 +452,21 @@ var TokenValidator = class {
452
452
  const PERSIST_FILE = "session.json";
453
453
  const PERSIST_DIR = () => dshHomePath("auth");
454
454
  /** Host-only label for diagnostics (never log a complete AI usage URL). */
455
- function safeHost(url) {
455
+ function safeHost$1(url) {
456
456
  try {
457
457
  return new URL(url).host;
458
458
  } catch {
459
459
  return "<invalid-url>";
460
460
  }
461
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
+ }
462
470
  /**
463
471
  * Bounded wait for the host to confirm a logout. Shorter than the login wait
464
472
  * (which must cover a human completing the EDA dialog): logout is a host-side
@@ -540,20 +548,23 @@ var InMemoryHuaqiuAuthService = class {
540
548
  fetchImpl: this.doFetch
541
549
  });
542
550
  this.hostMode = this.host.enabled;
543
- this.aiUsageUrl = resolved.aiUsageUrl?.length ? resolved.aiUsageUrl : null;
551
+ this.subscriptionBalancesUrl = resolved.subscriptionBalancesUrl?.length ? resolved.subscriptionBalancesUrl : null;
552
+ this.subscriptionApiBaseUrl = this.subscriptionBalancesUrl ? originOf(this.subscriptionBalancesUrl) : null;
544
553
  this.subscriptionOrigin = resolved.subscriptionOrigin?.length ? resolved.subscriptionOrigin : null;
545
554
  this.log.info("auth service started", {
546
555
  hostMode: this.hostMode,
547
556
  hostAuthPath: resolved.hostAuthPath,
548
557
  hostSessionTtlSeconds: resolved.hostSessionTtlSeconds,
549
- aiUsageHost: this.aiUsageUrl ? safeHost(this.aiUsageUrl) : null,
558
+ subscriptionBalancesHost: this.subscriptionBalancesUrl ? safeHost$1(this.subscriptionBalancesUrl) : null,
550
559
  subscriptionOrigin: this.subscriptionOrigin
551
560
  });
552
561
  }
553
562
  /** Host mode is active iff a host base URL was configured (see HostSessionResolver.enabled). */
554
563
  hostMode;
555
- /** AI usage endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
556
- aiUsageUrl;
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;
557
568
  /** Subscription origin resolved by HQ Edge (`HQ_AI_ENV`); null → standalone. */
558
569
  subscriptionOrigin;
559
570
  auth = {
@@ -742,6 +753,70 @@ function toUserInfo(host) {
742
753
  ...host.expiresAt !== void 0 ? { expiresAt: host.expiresAt } : {}
743
754
  };
744
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
+ }
745
820
  //#endregion
746
821
  //#region src/routes.ts
747
822
  let _log = null;
@@ -782,42 +857,62 @@ async function fetchEdaUserProfile(token, doFetch = globalThis.fetch.bind(global
782
857
  }
783
858
  }
784
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
+ }
785
868
  /**
786
- * Fetch the account's AI token usage for a token. Null on any failure (the UI
787
- * degrades to「—」) — never throws.
869
+ * Fetch and normalize AI usage for a token.
870
+ *
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.
788
874
  *
789
- * The header is `X-Token` (capital T), which is what this endpoint expects; the
790
- * subscription endpoint next door uses `x-token` + `X-User-Id`.
875
+ * The upstream header is `X-Token` (capital T).
791
876
  */
792
- async function fetchAiTokenUsage(token, usageUrl, 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);
793
887
  try {
794
- const res = await doFetch(usageUrl, {
888
+ const res = await doFetch(subscriptionBalancesUrl, {
795
889
  method: "GET",
796
890
  headers: {
797
- Accept: "application/json, text/plain, */*",
798
- "Content-Type": "application/json",
891
+ Accept: "application/json",
892
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
799
893
  "X-Token": token
800
- }
894
+ },
895
+ signal: controller.signal
801
896
  });
802
- if (!res.ok) return null;
803
- const body = await res.json();
804
- if (body.code !== 2e5 || !body.result) return null;
805
- const result = body.result;
806
- const num = (key) => {
807
- const v = Number(result[key]);
808
- return Number.isFinite(v) ? v : 0;
809
- };
810
- return {
811
- availablePoints: num("availablePoints"),
812
- availableQuota: num("availableQuota"),
813
- availableUsd: num("availableUsd"),
814
- usedPoints: num("usedPoints"),
815
- usedQuota: num("usedQuota"),
816
- usedUsd: num("usedUsd")
817
- };
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;
818
907
  } catch (err) {
819
- 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
+ });
820
912
  return null;
913
+ } finally {
914
+ clearTimeout(timer);
915
+ options.signal?.removeEventListener("abort", onAbort);
821
916
  }
822
917
  }
823
918
  function sendJson(res, status, body) {
@@ -877,7 +972,8 @@ function createAuthHandler(service) {
877
972
  if (req.method === "GET" && pathname === `/api/v1/huaqiu/auth/config`) {
878
973
  sendJson(res, 200, {
879
974
  hostMode: service.hostMode,
880
- subscriptionOrigin: service.subscriptionOrigin
975
+ subscriptionOrigin: service.subscriptionOrigin,
976
+ subscriptionApiBaseUrl: service.subscriptionApiBaseUrl
881
977
  });
882
978
  return;
883
979
  }
@@ -892,11 +988,20 @@ function createAuthHandler(service) {
892
988
  }
893
989
  if (req.method === "GET" && pathname === `/api/v1/huaqiu/auth/ai-usage`) {
894
990
  const token = await service.auth.getAccessToken();
895
- if (!token || !service.aiUsageUrl) {
991
+ if (!token || !service.subscriptionBalancesUrl) {
896
992
  sendJson(res, 200, { usage: null });
897
993
  return;
898
994
  }
899
- sendJson(res, 200, { usage: await fetchAiTokenUsage(token, service.aiUsageUrl) });
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 });
900
1005
  return;
901
1006
  }
902
1007
  if (req.method === "POST" && pathname === `/api/v1/huaqiu/auth/login`) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huaqiu/dsh-auth",
3
- "version": "0.6.21",
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.21"
36
+ "@huaqiu/dsh-plugin-log": "0.6.22"
37
37
  },
38
38
  "files": [
39
39
  "lib",
@@ -9,7 +9,7 @@ import {
9
9
  fetchSubscriptionQuota,
10
10
  handleAuthMessage,
11
11
  SUBSCRIPTION_PREFERRED_SIZE,
12
- type AiTokenUsage,
12
+ type AiUsage,
13
13
  type AuthMessageEventLike,
14
14
  type AuthTokenPayload,
15
15
  type LoginOptions,
@@ -66,10 +66,11 @@ export interface AuthClient {
66
66
  */
67
67
  logout(): Promise<void>
68
68
  /**
69
- * Active subscription quota for one eda.cn product, fetched DIRECTLY from
70
- * eda.cn (`/sub-api/subscriptions/active`) — no hq-edge hop, so the
71
- * sidebar can show live quota even in standalone DSH. Null on fetch
72
- * failure / no credential (callers decide fail-open vs fail-closed).
69
+ * Active subscription quota for one eda.cn product, fetched directly from
70
+ * the environment's subscription API (`/sub-api/subscriptions/active`) —
71
+ * the origin is injected by HQ Edge via the node `/config` route, so this
72
+ * follows `HQ_AI_ENV` and no host is hardcoded. Null on fetch failure /
73
+ * no credential / no configured origin.
73
74
  */
74
75
  getSubscriptionQuota(productCode: string): Promise<SubscriptionQuota | null>
75
76
  /**
@@ -79,7 +80,7 @@ export interface AuthClient {
79
80
  * request must not be made from here. Null on fetch failure / no credential,
80
81
  * the same one-round-trip shape as {@link getSubscriptionQuota}.
81
82
  */
82
- getAiTokenUsage(): Promise<AiTokenUsage | null>
83
+ getAiTokenUsage(): Promise<AiUsage | null>
83
84
  /**
84
85
  * Open the subscription landing page (`gen.eda.cn/subscription` with the
85
86
  * token). Host mode: ask the EDA host to open its NATIVE dialog through
@@ -127,6 +128,11 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
127
128
  * node `/config` route. Null in standalone → lib's PROD fallback.
128
129
  */
129
130
  let subscriptionOrigin: string | null = null
131
+ /**
132
+ * Origin of the resolved subscription-balances API (node `/config`). Null
133
+ * when no environment is configured → GEN/ERC quota calls are skipped.
134
+ */
135
+ let subscriptionApiBaseUrl: string | null = null
130
136
 
131
137
  const emit = (info: AuthTokenPayload | null): void => {
132
138
  for (const listener of listeners) listener(info)
@@ -250,9 +256,14 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
250
256
  ? (hostSession?.id ?? null)
251
257
  : (hostSession?.id ?? storage.get()?.id ?? null)
252
258
  if (!token || !id) return null
253
- return fetchSubscriptionQuota({ userId: id, token, productCode })
259
+ return fetchSubscriptionQuota({
260
+ userId: id,
261
+ token,
262
+ productCode,
263
+ ...(subscriptionApiBaseUrl ? { baseUrl: subscriptionApiBaseUrl } : {}),
264
+ })
254
265
  },
255
- getAiTokenUsage: async (): Promise<AiTokenUsage | null> => {
266
+ getAiTokenUsage: async (): Promise<AiUsage | null> => {
256
267
  if (hostMode && !hostSessionLoaded) await resolveHost()
257
268
  // Gate on a credential first: the node route resolves the token itself,
258
269
  // so a request without one is a guaranteed-null round trip.
@@ -346,9 +357,11 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
346
357
  const runtime = await transport.fetchRuntimeConfig()
347
358
  mode = runtime.hostMode
348
359
  subscriptionOrigin = runtime.subscriptionOrigin
360
+ subscriptionApiBaseUrl = runtime.subscriptionApiBaseUrl
349
361
  } catch {
350
362
  mode = false
351
363
  subscriptionOrigin = null
364
+ subscriptionApiBaseUrl = null
352
365
  }
353
366
  hostMode = mode
354
367
  hostSessionLoaded = false
@@ -387,6 +400,7 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
387
400
  hostSession = null
388
401
  hostSessionLoaded = false
389
402
  subscriptionOrigin = null
403
+ subscriptionApiBaseUrl = null
390
404
  void trustedOrigin // referenced for clarity: the auth iframe URL comes from it
391
405
  },
392
406
  }
@@ -45,12 +45,9 @@ const zh = {
45
45
  'subscription.quotaHeader': '套餐与使用额度',
46
46
  'subscription.upgrade': '订阅 / 升级套餐',
47
47
  'subscription.online': '在线',
48
- // AI token usage (`/user-rest/api/ai/usage`) — the third metric beside GEN
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.
48
+ // AI usage — the third metric beside GEN and ERC. The headline is the
49
+ // upstream `quotaRemainPercent`, passed through unchanged (`99.68%`).
52
50
  'subscription.ai': 'AI 用量',
53
- 'subscription.aiUsageCount': '{available} / {total} 点',
54
51
  'subscription.aiUsagePercent': '{percent}%',
55
52
  'subscription.aiUsageUnknown': '暂无数据',
56
53
 
@@ -98,12 +95,9 @@ const en: Record<AuthCopyKey, string> = {
98
95
  'subscription.quotaHeader': 'Plan & usage quota',
99
96
  'subscription.upgrade': 'Subscribe / Upgrade plan',
100
97
  'subscription.online': 'Online',
101
- // AI token usage (`/user-rest/api/ai/usage`) — the third metric beside GEN
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.
98
+ // AI usage — the third metric beside GEN and ERC. The headline is the
99
+ // upstream `quotaRemainPercent`, passed through unchanged (`99.68%`).
105
100
  'subscription.ai': 'AI usage',
106
- 'subscription.aiUsageCount': '{available} / {total} pts',
107
101
  'subscription.aiUsagePercent': '{percent}%',
108
102
  'subscription.aiUsageUnknown': 'No data',
109
103
 
package/src/client/lib.ts CHANGED
@@ -52,35 +52,23 @@ export const SUBSCRIPTION_PREFERRED_SIZE = { width: 1400, height: 740 } as const
52
52
  export const GEN_PRODUCT_CODE = 'auto-design'
53
53
  export const ERC_PRODUCT_CODE = 'erc'
54
54
 
55
- // ── AI token usage ──────────────────────────────────────────────────────────
55
+ // ── AI usage (subscription balances) ────────────────────────────────────────
56
56
 
57
57
  /**
58
- * Normalized AI token usage — the shape the node half's `/ai-usage` route
59
- * returns (the node half owns the upstream call; see
60
- * `routes.ts#fetchAiTokenUsage`).
58
+ * Client-facing AI usage shape. Re-exported (type-only) from the single
59
+ * authoritative contract in `../subscription-balances.ts`; the browser half
60
+ * must not import node modules, and a type-only re-export adds no runtime
61
+ * code to this bundle.
61
62
  *
62
- * `points` is the account-level token balance (what the user thinks of as
63
- * "tokens"); `quota` is the same figure in the gateway's internal unit
64
- * (points × 50) and `usd` its money equivalent. All three pairs are reported
65
- * because the endpoint reports all three; the UI reads `points`.
66
- *
67
- * WHY THE BROWSER NEVER CALLS THIS ENDPOINT DIRECTLY: the TEST endpoint is
68
- * served over plain `http`, which the WebView refuses twice over — App
63
+ * WHY THE BROWSER NEVER CALLS THE UPSTREAM ENDPOINT DIRECTLY: the TEST endpoint
64
+ * is served over plain `http`, which the WebView refuses twice over — App
69
65
  * Transport Security ("the resource could not be loaded because the App
70
66
  * Transport Security policy requires the use of a secure connection") and CORS
71
67
  * (the response carries no `Access-Control-Allow-Origin`). The node half has
72
- * neither restriction — it is the same process that already calls the AI host
73
- * for the Huaqiu gateway — so IT performs the fetch and this half reads a
68
+ * neither restriction, so IT performs the fetch and this half reads a
74
69
  * same-origin route, exactly like the eda.cn profile on `/user-info`.
75
70
  */
76
- export interface AiTokenUsage {
77
- availablePoints: number
78
- availableQuota: number
79
- availableUsd: number
80
- usedPoints: number
81
- usedQuota: number
82
- usedUsd: number
83
- }
71
+ export type { AiUsage } from '../subscription-balances.js'
84
72
 
85
73
  /**
86
74
  * Build the subscription landing URL. Mirrors `buildProfileUrl`: the token is
@@ -132,11 +120,15 @@ function quotaOf(subscription: Record<string, unknown> | null | undefined): Subs
132
120
  }
133
121
 
134
122
  /**
135
- * Fetch the active subscription quota DIRECTLY from eda.cn
136
- * (`GET {baseUrl}/sub-api/subscriptions/active?userId&productCode` with
137
- * `x-token` + `X-User-Id` headers) — the same API `hq-eda-ai`'s
138
- * `getActiveSubscription` and `hq-edge`'s ERC quota proxy call, so displaying
139
- * the available quota never depends on an hq-edge hop.
123
+ * Fetch the active subscription quota (`GET {baseUrl}/sub-api/subscriptions/
124
+ * active?userId&productCode` with `x-token` + `X-User-Id` headers) — the same
125
+ * API `hq-eda-ai`'s `getActiveSubscription` and `hq-edge`'s ERC quota proxy
126
+ * call.
127
+ *
128
+ * `baseUrl` is the origin the node half derives from the resolved
129
+ * subscription-balances endpoint (`HQ_AI_ENV`), so this call follows the
130
+ * selected environment and DSH Auth never hardcodes a production host. No
131
+ * configured origin → null (the UI shows「—」).
140
132
  *
141
133
  * Returns null when the fetch/unwrap fails (callers decide fail-open vs
142
134
  * fail-closed); a well-formed response always yields a `SubscriptionQuota`
@@ -149,7 +141,8 @@ export async function fetchSubscriptionQuota(options: {
149
141
  baseUrl?: string
150
142
  fetchImpl?: typeof fetch
151
143
  }): Promise<SubscriptionQuota | null> {
152
- const { userId, token, productCode, baseUrl = 'https://www.eda.cn' } = options
144
+ const { userId, token, productCode, baseUrl } = options
145
+ if (!baseUrl) return null
153
146
  const fetchImpl = options.fetchImpl ?? fetch
154
147
  const url = `${baseUrl}${SUB_API_PREFIX}/subscriptions/active?${new URLSearchParams({
155
148
  userId: String(userId),
@@ -4,7 +4,7 @@
4
4
  * browser→host channel — `apiProxy`'s dispatch table is closed, so a
5
5
  * plugin-owned `webServer` route is the smallest supported extension point.
6
6
  */
7
- import type { AiTokenUsage, AuthTokenPayload } from './lib.js'
7
+ import type { AiUsage, AuthTokenPayload } from './lib.js'
8
8
 
9
9
  export interface AuthTransport {
10
10
  pushSession(info: AuthTokenPayload): Promise<void>
@@ -14,7 +14,9 @@ export interface AuthTransport {
14
14
  * - `hostMode`: whether the plugin runs under an HQ Edge host (in host mode
15
15
  * the browser half's own login UI is suppressed);
16
16
  * - `subscriptionOrigin`: the SAME `HQ_AI_ENV`-resolved origin used for the
17
- * subscription dialog (null → standalone PROD fallback).
17
+ * subscription dialog (null → standalone PROD fallback);
18
+ * - `subscriptionApiBaseUrl`: origin of the resolved balances API, used for
19
+ * the GEN/ERC active-subscription calls (null → quota unavailable).
18
20
  */
19
21
  fetchRuntimeConfig(): Promise<AuthRuntimeConfig>
20
22
  /**
@@ -40,15 +42,14 @@ export interface AuthTransport {
40
42
  */
41
43
  fetchUserInfo(): Promise<EdaUserProfile | null>
42
44
  /**
43
- * Fetch the account's AI token usage from the NODE half (`/ai-usage`), which
44
- * performs the upstream usage call (endpoint resolved by HQ Edge from
45
- * `HQ_AI_ENV`) with the `X-Token` header. This half must NOT call that
46
- * endpoint itself: the TEST endpoint is plain `http`, which the WebView
47
- * refuses on two independent grounds — App Transport Security and CORS — and
48
- * the failures are what the browser console reports as a blocked resource.
45
+ * Fetch the account's AI usage from the NODE half (`/ai-usage`), which
46
+ * performs the upstream subscription-balances call (endpoint resolved by HQ
47
+ * Edge from `HQ_AI_ENV`) with the `X-Token` header. This half must NOT call
48
+ * that endpoint itself: the TEST endpoint is plain `http`, which the WebView
49
+ * refuses on two independent grounds — App Transport Security and CORS.
49
50
  * Null on failure (the sidebar shows「—」).
50
51
  */
51
- fetchAiUsage(): Promise<AiTokenUsage | null>
52
+ fetchAiUsage(): Promise<AiUsage | null>
52
53
  }
53
54
 
54
55
  /** Minimal session user shape returned by the node `/session` route. */
@@ -64,6 +65,8 @@ export interface AuthRuntimeConfig {
64
65
  hostMode: boolean
65
66
  /** Absolute http(s) origin; null = standalone (client keeps its default). */
66
67
  subscriptionOrigin: string | null
68
+ /** Origin for GEN/ERC quota calls; null = no environment configured. */
69
+ subscriptionApiBaseUrl: string | null
67
70
  }
68
71
 
69
72
  /** Accept only an absolute http(s) origin; anything else → null. */
@@ -80,6 +83,15 @@ function normalizeOrigin(value: unknown): string | null {
80
83
  }
81
84
  }
82
85
 
86
+ /** Accept only a finite `quotaRemainPercent`; anything else → unavailable. */
87
+ function normalizeUsage(value: unknown): AiUsage | null {
88
+ if (value === null || typeof value !== 'object') return null
89
+ const percent = (value as { quotaRemainPercent?: unknown }).quotaRemainPercent
90
+ return typeof percent === 'number' && Number.isFinite(percent)
91
+ ? { quotaRemainPercent: percent }
92
+ : null
93
+ }
94
+
83
95
  /** Rich eda.cn profile served by the node `/user-info` route. */
84
96
  export interface EdaUserProfile {
85
97
  nickname?: string
@@ -116,17 +128,32 @@ export function createWebServerAuthTransport(
116
128
  method: 'GET',
117
129
  headers: { accept: 'application/json' },
118
130
  })
119
- if (!res.ok) return { hostMode: false, subscriptionOrigin: null }
120
- const body = await res.json() as { hostMode?: unknown; subscriptionOrigin?: unknown }
131
+ if (!res.ok) {
132
+ return {
133
+ hostMode: false,
134
+ subscriptionOrigin: null,
135
+ subscriptionApiBaseUrl: null,
136
+ }
137
+ }
138
+ const body = await res.json() as {
139
+ hostMode?: unknown
140
+ subscriptionOrigin?: unknown
141
+ subscriptionApiBaseUrl?: unknown
142
+ }
121
143
  return {
122
144
  hostMode: body.hostMode === true,
123
145
  subscriptionOrigin: normalizeOrigin(body.subscriptionOrigin),
146
+ subscriptionApiBaseUrl: normalizeOrigin(body.subscriptionApiBaseUrl),
124
147
  }
125
148
  } catch {
126
149
  // Offline/same-origin failure: fall back to standalone (show the login
127
150
  // entrypoint) rather than hiding it — a login UI is never a security
128
151
  // regression, but a missing one in standalone would lock the user out.
129
- return { hostMode: false, subscriptionOrigin: null }
152
+ return {
153
+ hostMode: false,
154
+ subscriptionOrigin: null,
155
+ subscriptionApiBaseUrl: null,
156
+ }
130
157
  }
131
158
  },
132
159
  async fetchSession() {
@@ -166,8 +193,8 @@ export function createWebServerAuthTransport(
166
193
  headers: { accept: 'application/json' },
167
194
  })
168
195
  if (!res.ok) return null
169
- const body = await res.json() as { usage?: AiTokenUsage | null }
170
- return body.usage ?? null
196
+ const body = await res.json() as { usage?: unknown }
197
+ return normalizeUsage(body.usage)
171
198
  } catch {
172
199
  return null
173
200
  }