@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.
@@ -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
+ }
@@ -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
@@ -122,6 +123,16 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
122
123
  let hostMode = false
123
124
  let hostSession: AuthTokenPayload | null = null
124
125
  let hostSessionLoaded = false
126
+ /**
127
+ * Subscription origin resolved by HQ Edge from `HQ_AI_ENV` and served on the
128
+ * node `/config` route. Null in standalone → lib's PROD fallback.
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
125
136
 
126
137
  const emit = (info: AuthTokenPayload | null): void => {
127
138
  for (const listener of listeners) listener(info)
@@ -245,9 +256,14 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
245
256
  ? (hostSession?.id ?? null)
246
257
  : (hostSession?.id ?? storage.get()?.id ?? null)
247
258
  if (!token || !id) return null
248
- return fetchSubscriptionQuota({ userId: id, token, productCode })
259
+ return fetchSubscriptionQuota({
260
+ userId: id,
261
+ token,
262
+ productCode,
263
+ ...(subscriptionApiBaseUrl ? { baseUrl: subscriptionApiBaseUrl } : {}),
264
+ })
249
265
  },
250
- getAiTokenUsage: async (): Promise<AiTokenUsage | null> => {
266
+ getAiTokenUsage: async (): Promise<AiUsage | null> => {
251
267
  if (hostMode && !hostSessionLoaded) await resolveHost()
252
268
  // Gate on a credential first: the node route resolves the token itself,
253
269
  // so a request without one is a guaranteed-null round trip.
@@ -258,7 +274,10 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
258
274
  if (hostMode && !hostSessionLoaded) await resolveHost()
259
275
  const token = await auth.getAccessToken()
260
276
  if (!token) return
261
- const url = buildSubscriptionUrl({ token })
277
+ const url = buildSubscriptionUrl({
278
+ token,
279
+ ...(subscriptionOrigin ? { origin: subscriptionOrigin } : {}),
280
+ })
262
281
  if (hostMode) {
263
282
  // The EDA host owns the UI — open its native dialog (fire-and-forget).
264
283
  // No dialog service → no-op; the caller keeps its subscribe button.
@@ -335,9 +354,14 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
335
354
  const prevToken = hostSession?.token ?? storage.get()?.token ?? null
336
355
  let mode = false
337
356
  try {
338
- mode = await transport.fetchHostMode()
357
+ const runtime = await transport.fetchRuntimeConfig()
358
+ mode = runtime.hostMode
359
+ subscriptionOrigin = runtime.subscriptionOrigin
360
+ subscriptionApiBaseUrl = runtime.subscriptionApiBaseUrl
339
361
  } catch {
340
362
  mode = false
363
+ subscriptionOrigin = null
364
+ subscriptionApiBaseUrl = null
341
365
  }
342
366
  hostMode = mode
343
367
  hostSessionLoaded = false
@@ -375,6 +399,8 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
375
399
  hostMode = false
376
400
  hostSession = null
377
401
  hostSessionLoaded = false
402
+ subscriptionOrigin = null
403
+ subscriptionApiBaseUrl = null
378
404
  void trustedOrigin // referenced for clarity: the auth iframe URL comes from it
379
405
  },
380
406
  }
@@ -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': '订阅 / 升级',
@@ -44,14 +45,10 @@ const zh = {
44
45
  'subscription.quotaHeader': '套餐与使用额度',
45
46
  'subscription.upgrade': '订阅 / 升级套餐',
46
47
  'subscription.online': '在线',
47
- // 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.
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
- 'subscription.aiUsagePercent': '剩余 {percent}%',
51
+ 'subscription.aiUsagePercent': '{percent}%',
55
52
  'subscription.aiUsageUnknown': '暂无数据',
56
53
 
57
54
  'card.title': '华秋 EDA AI(eda.cn)登录',
@@ -87,6 +84,7 @@ const en: Record<AuthCopyKey, string> = {
87
84
  'subscription.package': 'Plan: {name}',
88
85
  'subscription.quota': 'Available: {count}',
89
86
  'subscription.quotaCount': '{used} / {total}',
87
+ 'subscription.quotaPercent': '{percent}%',
90
88
  'subscription.noQuota': 'No quota left',
91
89
  'subscription.unsubscribed': 'Not subscribed',
92
90
  'subscription.subscribe': 'Subscribe / Upgrade',
@@ -97,14 +95,10 @@ const en: Record<AuthCopyKey, string> = {
97
95
  'subscription.quotaHeader': 'Plan & usage quota',
98
96
  'subscription.upgrade': 'Subscribe / Upgrade plan',
99
97
  'subscription.online': 'Online',
100
- // 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.
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
- 'subscription.aiUsagePercent': '{percent}% remaining',
101
+ 'subscription.aiUsagePercent': '{percent}%',
108
102
  'subscription.aiUsageUnknown': 'No data',
109
103
 
110
104
  'card.title': 'Huaqiu EDA AI (eda.cn) login',
package/src/client/lib.ts CHANGED
@@ -28,12 +28,16 @@ export const PROFILE_URL = 'https://www.eda.cn/account/profile'
28
28
 
29
29
  /**
30
30
  * Subscription landing page — the same page `hq-eda-ai` serves at
31
- * `gen.eda.cn/subscription` (token taken from the URL query; see its
31
+ * `<origin>/subscription` (token taken from the URL query; see its
32
32
  * `UserInfoContext`). The preferred window size for BOTH surfaces (KiCad
33
33
  * native dialog via DialogService.OpenUrl and the standalone iframe dialog)
34
34
  * is 1400×740.
35
+ *
36
+ * This constant is the standalone-DSH fallback only. Under HQ Edge the origin
37
+ * arrives from the node half's `/config` route, resolved ONCE from `HQ_AI_ENV`
38
+ * (PROD: gen.eda.cn / TEST: gen.fdatasheets.com).
35
39
  */
36
- export const SUBSCRIPTION_ORIGIN = 'https://gen.eda.cn'
40
+ export const DEFAULT_SUBSCRIPTION_ORIGIN = 'https://gen.eda.cn'
37
41
  export const SUBSCRIPTION_PATH = '/subscription'
38
42
  export const SUBSCRIPTION_PREFERRED_SIZE = { width: 1400, height: 740 } as const
39
43
 
@@ -48,45 +52,36 @@ export const SUBSCRIPTION_PREFERRED_SIZE = { width: 1400, height: 740 } as const
48
52
  export const GEN_PRODUCT_CODE = 'auto-design'
49
53
  export const ERC_PRODUCT_CODE = 'erc'
50
54
 
51
- // ── AI token usage ──────────────────────────────────────────────────────────
55
+ // ── AI usage (subscription balances) ────────────────────────────────────────
52
56
 
53
57
  /**
54
- * Normalized AI token usage — the shape the node half's `/ai-usage` route
55
- * returns (the node half owns the upstream call; see
56
- * `routes.ts#fetchAiTokenUsage`).
57
- *
58
- * `points` is the account-level token balance (what the user thinks of as
59
- * "tokens"); `quota` is the same figure in the gateway's internal unit
60
- * (points × 50) and `usd` its money equivalent. All three pairs are reported
61
- * because the endpoint reports all three; the UI reads `points`.
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.
62
62
  *
63
- * WHY THE BROWSER NEVER CALLS THIS ENDPOINT DIRECTLY: it is served over plain
64
- * `http` (`http://www.fdatasheets.com/user-rest/api/ai/usage`), which the
65
- * WebView refuses twice over — App Transport Security ("the resource could not
66
- * be loaded because the App Transport Security policy requires the use of a
67
- * secure connection") and CORS (the response carries no
68
- * `Access-Control-Allow-Origin`). The node half has neither restriction — it is
69
- * the same process that already calls this host for the Huaqiu AI gateway — so
70
- * IT performs the fetch and this half reads a same-origin route, exactly like
71
- * the eda.cn profile on `/user-info`.
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
65
+ * Transport Security ("the resource could not be loaded because the App
66
+ * Transport Security policy requires the use of a secure connection") and CORS
67
+ * (the response carries no `Access-Control-Allow-Origin`). The node half has
68
+ * neither restriction, so IT performs the fetch and this half reads a
69
+ * same-origin route, exactly like the eda.cn profile on `/user-info`.
72
70
  */
73
- export interface AiTokenUsage {
74
- availablePoints: number
75
- availableQuota: number
76
- availableUsd: number
77
- usedPoints: number
78
- usedQuota: number
79
- usedUsd: number
80
- }
71
+ export type { AiUsage } from '../subscription-balances.js'
81
72
 
82
73
  /**
83
74
  * Build the subscription landing URL. Mirrors `buildProfileUrl`: the token is
84
- * always attached — `gen.eda.cn/subscription` consumes it to establish the
75
+ * always attached — the subscription page consumes it to establish the
85
76
  * session and hides it itself. `encodeURIComponent` is required (tokens are
86
77
  * base64-ish and may contain `+`, `/` or `=`).
78
+ *
79
+ * `origin` comes from the node half (HQ Edge → `HQ_AI_ENV`); omitted in
80
+ * standalone DSH, which keeps the PROD fallback.
87
81
  */
88
- export function buildSubscriptionUrl(options: { token: string }): string {
89
- return `${SUBSCRIPTION_ORIGIN}${SUBSCRIPTION_PATH}?token=${encodeURIComponent(options.token)}`
82
+ export function buildSubscriptionUrl(options: { token: string; origin?: string }): string {
83
+ const origin = (options.origin ?? DEFAULT_SUBSCRIPTION_ORIGIN).replace(/\/+$/, '')
84
+ return `${origin}${SUBSCRIPTION_PATH}?token=${encodeURIComponent(options.token)}`
90
85
  }
91
86
 
92
87
  /** Normalized active-subscription quota view (whatever the backend sends). */
@@ -125,11 +120,15 @@ function quotaOf(subscription: Record<string, unknown> | null | undefined): Subs
125
120
  }
126
121
 
127
122
  /**
128
- * Fetch the active subscription quota DIRECTLY from eda.cn
129
- * (`GET {baseUrl}/sub-api/subscriptions/active?userId&productCode` with
130
- * `x-token` + `X-User-Id` headers) — the same API `hq-eda-ai`'s
131
- * `getActiveSubscription` and `hq-edge`'s ERC quota proxy call, so displaying
132
- * 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「—」).
133
132
  *
134
133
  * Returns null when the fetch/unwrap fails (callers decide fail-open vs
135
134
  * fail-closed); a well-formed response always yields a `SubscriptionQuota`
@@ -142,7 +141,8 @@ export async function fetchSubscriptionQuota(options: {
142
141
  baseUrl?: string
143
142
  fetchImpl?: typeof fetch
144
143
  }): Promise<SubscriptionQuota | null> {
145
- const { userId, token, productCode, baseUrl = 'https://www.eda.cn' } = options
144
+ const { userId, token, productCode, baseUrl } = options
145
+ if (!baseUrl) return null
146
146
  const fetchImpl = options.fetchImpl ?? fetch
147
147
  const url = `${baseUrl}${SUB_API_PREFIX}/subscriptions/active?${new URLSearchParams({
148
148
  userId: String(userId),
@@ -4,17 +4,21 @@
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>
11
11
  pushLogout(): Promise<void>
12
12
  /**
13
- * Whether the plugin runs under an HQ Edge host. In host mode hq-edge already
14
- * holds the operator credential (EDA hands it over on launch), so the
15
- * browser half's own login UI (sidebar entrypoint) is suppressed.
13
+ * Runtime config resolved by the node half (`/config`):
14
+ * - `hostMode`: whether the plugin runs under an HQ Edge host (in host mode
15
+ * the browser half's own login UI is suppressed);
16
+ * - `subscriptionOrigin`: the SAME `HQ_AI_ENV`-resolved origin used for the
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).
16
20
  */
17
- fetchHostMode(): Promise<boolean>
21
+ fetchRuntimeConfig(): Promise<AuthRuntimeConfig>
18
22
  /**
19
23
  * Fetch the node half's authoritative session. The node resolves host-mode
20
24
  * credentials first (host session → pushed browser session → persisted
@@ -38,14 +42,14 @@ export interface AuthTransport {
38
42
  */
39
43
  fetchUserInfo(): Promise<EdaUserProfile | null>
40
44
  /**
41
- * Fetch the account's AI token usage from the NODE half (`/ai-usage`), which
42
- * performs the upstream `GET http://www.fdatasheets.com/user-rest/api/ai/usage`
43
- * with the `X-Token` header. This half must NOT call that endpoint itself: it
44
- * is plain `http`, which the WebView refuses on two independent grounds — App
45
- * Transport Security and CORS — and the failures are what the browser console
46
- * reports as a blocked resource. Null on failure (the sidebar shows「—」).
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.
50
+ * Null on failure (the sidebar shows「—」).
47
51
  */
48
- fetchAiUsage(): Promise<AiTokenUsage | null>
52
+ fetchAiUsage(): Promise<AiUsage | null>
49
53
  }
50
54
 
51
55
  /** Minimal session user shape returned by the node `/session` route. */
@@ -56,6 +60,38 @@ export interface HostSessionUser {
56
60
  expiresAt?: number
57
61
  }
58
62
 
63
+ /** Runtime config served by the node `/config` route. */
64
+ export interface AuthRuntimeConfig {
65
+ hostMode: boolean
66
+ /** Absolute http(s) origin; null = standalone (client keeps its default). */
67
+ subscriptionOrigin: string | null
68
+ /** Origin for GEN/ERC quota calls; null = no environment configured. */
69
+ subscriptionApiBaseUrl: string | null
70
+ }
71
+
72
+ /** Accept only an absolute http(s) origin; anything else → null. */
73
+ function normalizeOrigin(value: unknown): string | null {
74
+ if (typeof value !== 'string') return null
75
+ const trimmed = value.trim().replace(/\/+$/, '')
76
+ if (!trimmed) return null
77
+ try {
78
+ const url = new URL(trimmed)
79
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
80
+ return trimmed
81
+ } catch {
82
+ return null
83
+ }
84
+ }
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
+
59
95
  /** Rich eda.cn profile served by the node `/user-info` route. */
60
96
  export interface EdaUserProfile {
61
97
  nickname?: string
@@ -86,20 +122,38 @@ export function createWebServerAuthTransport(
86
122
  const res = await doFetch(`${base}/logout`, { method: 'POST' })
87
123
  if (!res.ok) throw new Error(`auth logout push failed: HTTP ${res.status}`)
88
124
  },
89
- async fetchHostMode() {
125
+ async fetchRuntimeConfig() {
90
126
  try {
91
127
  const res = await doFetch(`${base}/config`, {
92
128
  method: 'GET',
93
129
  headers: { accept: 'application/json' },
94
130
  })
95
- if (!res.ok) return false
96
- const body = await res.json() as { hostMode?: unknown }
97
- return body.hostMode === true
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
+ }
143
+ return {
144
+ hostMode: body.hostMode === true,
145
+ subscriptionOrigin: normalizeOrigin(body.subscriptionOrigin),
146
+ subscriptionApiBaseUrl: normalizeOrigin(body.subscriptionApiBaseUrl),
147
+ }
98
148
  } catch {
99
149
  // Offline/same-origin failure: fall back to standalone (show the login
100
150
  // entrypoint) rather than hiding it — a login UI is never a security
101
151
  // regression, but a missing one in standalone would lock the user out.
102
- return false
152
+ return {
153
+ hostMode: false,
154
+ subscriptionOrigin: null,
155
+ subscriptionApiBaseUrl: null,
156
+ }
103
157
  }
104
158
  },
105
159
  async fetchSession() {
@@ -139,8 +193,8 @@ export function createWebServerAuthTransport(
139
193
  headers: { accept: 'application/json' },
140
194
  })
141
195
  if (!res.ok) return null
142
- const body = await res.json() as { usage?: AiTokenUsage | null }
143
- return body.usage ?? null
196
+ const body = await res.json() as { usage?: unknown }
197
+ return normalizeUsage(body.usage)
144
198
  } catch {
145
199
  return null
146
200
  }