@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/src/routes.ts CHANGED
@@ -5,9 +5,9 @@
5
5
  * POST /api/v1/huaqiu/auth/session body { token, userId, nickname?, expiresAt? } → cache set
6
6
  * POST /api/v1/huaqiu/auth/logout → cache cleared
7
7
  * GET /api/v1/huaqiu/auth/session → { authenticated, user }
8
- * GET /api/v1/huaqiu/auth/config → { hostMode }
8
+ * GET /api/v1/huaqiu/auth/config → { hostMode, subscriptionOrigin, subscriptionApiBaseUrl }
9
9
  * GET /api/v1/huaqiu/auth/user-info → { userInfo } (node-side eda.cn call)
10
- * GET /api/v1/huaqiu/auth/ai-usage → { usage } (node-side AI balance call)
10
+ * GET /api/v1/huaqiu/auth/ai-usage → { usage } (node-side subscription-balances call)
11
11
  *
12
12
  * `config` tells the browser half whether it is running under an HQ Edge host
13
13
  * (hq-edge passes the operator credential to hq-edge itself, so the sidebar
@@ -19,6 +19,7 @@
19
19
  import type { IncomingMessage, ServerResponse } from 'node:http'
20
20
  import { getLogger, type PluginLogger } from '@huaqiu/dsh-plugin-log'
21
21
  import type { HuaqiuAuthService, HuaqiuUserInfo } from './service.js'
22
+ import { aiUsageFromPayload, type AiUsage } from './subscription-balances.js'
22
23
 
23
24
  // Lazy so test suites that `vi.mock('@deepseek-ai/dsh-home-paths', …)` before
24
25
  // their TMP constant is initialised don't trigger `dshHomePath('logs')` at
@@ -75,82 +76,84 @@ export async function fetchEdaUserProfile(
75
76
 
76
77
  export const AUTH_ROUTE_PREFIX = '/api/v1/huaqiu/auth'
77
78
 
78
- // ── AI token usage (proxied by the node half) ────────────────────────────────
79
+ // ── Subscription balances / AI usage (proxied by the node half) ──────────────
79
80
 
80
81
  /**
81
- * The account's AI balance endpoint.
82
+ * The authoritative subscription-balances endpoint
83
+ * (`GET /sub-api/subscriptions/balances/current`).
82
84
  *
83
- * It is served over PLAIN `http`, which is why the node half must be the one to
84
- * call it: a WebView fetch is refused by App Transport Security ("the resource
85
- * could not be loaded because the App Transport Security policy requires the
86
- * use of a secure connection") and, independently, by CORS (the response sends
87
- * no `Access-Control-Allow-Origin`). Node's fetch is subject to neither, and
88
- * this process already talks to this very host for the Huaqiu AI gateway
89
- * (`http://www.fdatasheets.com/user-rest/ai/v1`, see hq-edge's
90
- * `HUAQIU_AI_GATEWAY_BASE_URL`) — so the call is known to work from here.
85
+ * It may be served over PLAIN `http`, which is why the node half must be the one
86
+ * to call it: a WebView fetch is refused by App Transport Security ("the
87
+ * resource could not be loaded because the App Transport Security policy
88
+ * requires the use of a secure connection") and, independently, by CORS (the
89
+ * response sends no `Access-Control-Allow-Origin`). Node's fetch is subject to
90
+ * neither. The URL is injected as resolved config by HQ Edge (`HQ_AI_ENV`);
91
+ * this module has no hardcoded environment URL, and every payload is validated
92
+ * against the single schema in `./subscription-balances.js`.
91
93
  */
92
- export const AI_USAGE_URL = 'http://www.fdatasheets.com/user-rest/api/ai/usage'
93
94
 
94
- /**
95
- * Normalized AI token usage — the `/user-rest/api/ai/usage` result.
96
- *
97
- * `points` is the account-level token balance (what the user thinks of as
98
- * "tokens"); `quota` is the same figure in the gateway's internal unit
99
- * (points × 50) and `usd` its money equivalent. All three pairs are reported
100
- * because the endpoint reports all three; the UI reads `points`.
101
- *
102
- * (Mirrored as a type-only declaration in `client/lib.ts` — the browser half
103
- * must not import node modules, and the two halves are built as separate
104
- * bundles.)
105
- */
106
- export interface AiTokenUsage {
107
- availablePoints: number
108
- availableQuota: number
109
- availableUsd: number
110
- usedPoints: number
111
- usedQuota: number
112
- usedUsd: number
95
+ /** Upstream budget for one balances call. */
96
+ export const AI_USAGE_TIMEOUT_MS = 10_000
97
+
98
+ /** Host-only label for diagnostics (never log the full URL or the token). */
99
+ function safeHost(url: string): string {
100
+ try {
101
+ return new URL(url).host
102
+ } catch {
103
+ return '<invalid-url>'
104
+ }
113
105
  }
114
106
 
115
107
  /**
116
- * Fetch the account's AI token usage for a token. Null on any failure (the UI
117
- * degrades to「—」) — never throws.
108
+ * Fetch and normalize AI usage for a token.
118
109
  *
119
- * The header is `X-Token` (capital T), which is what this endpoint expects; the
120
- * subscription endpoint next door uses `x-token` + `X-User-Id`.
110
+ * `quotaRemainPercent` comes straight from the AI Points group — no local ratio
111
+ * is derived. `null` on any failure (invalid payload, timeout, network, non-2xx)
112
+ * so the UI degrades to「—」; never throws.
113
+ *
114
+ * The upstream header is `X-Token` (capital T).
121
115
  */
122
- export async function fetchAiTokenUsage(
116
+ export async function fetchAiUsage(
123
117
  token: string,
118
+ subscriptionBalancesUrl: string,
124
119
  doFetch: typeof fetch = globalThis.fetch.bind(globalThis),
125
- ): Promise<AiTokenUsage | null> {
120
+ options: { signal?: AbortSignal; timeoutMs?: number } = {},
121
+ ): Promise<AiUsage | null> {
122
+ const timeoutMs = options.timeoutMs ?? AI_USAGE_TIMEOUT_MS
123
+ const controller = new AbortController()
124
+ const onAbort = () => controller.abort(options.signal?.reason)
125
+ if (options.signal) {
126
+ if (options.signal.aborted) controller.abort(options.signal.reason)
127
+ else options.signal.addEventListener('abort', onAbort, { once: true })
128
+ }
129
+ const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs)
130
+ const host = safeHost(subscriptionBalancesUrl)
126
131
  try {
127
- const res = await doFetch(AI_USAGE_URL, {
132
+ const res = await doFetch(subscriptionBalancesUrl, {
128
133
  method: 'GET',
129
134
  headers: {
130
- Accept: 'application/json, text/plain, */*',
131
- 'Content-Type': 'application/json',
135
+ Accept: 'application/json',
136
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
132
137
  'X-Token': token,
133
138
  },
139
+ signal: controller.signal,
134
140
  })
135
- if (!res.ok) return null
136
- const body = (await res.json()) as { code?: number; result?: Record<string, unknown> }
137
- if (body.code !== 200000 || !body.result) return null
138
- const result = body.result
139
- const num = (key: string): number => {
140
- const v = Number(result[key])
141
- return Number.isFinite(v) ? v : 0
142
- }
143
- return {
144
- availablePoints: num('availablePoints'),
145
- availableQuota: num('availableQuota'),
146
- availableUsd: num('availableUsd'),
147
- usedPoints: num('usedPoints'),
148
- usedQuota: num('usedQuota'),
149
- usedUsd: num('usedUsd'),
141
+ if (!res.ok) {
142
+ log().warn('subscription balances request failed', { host, status: res.status })
143
+ return null
150
144
  }
145
+ const usage = aiUsageFromPayload(await res.json())
146
+ if (!usage) log().warn('subscription balances payload unusable', { host })
147
+ return usage
151
148
  } catch (err) {
152
- log().warn('fetchAiTokenUsage failed', { error: String((err as Error)?.message || err) })
149
+ log().warn('subscription balances request failed', {
150
+ host,
151
+ error: String((err as Error)?.message || err),
152
+ })
153
153
  return null
154
+ } finally {
155
+ clearTimeout(timer)
156
+ options.signal?.removeEventListener('abort', onAbort)
154
157
  }
155
158
  }
156
159
 
@@ -228,7 +231,16 @@ export function createAuthHandler(service: HuaqiuAuthService): AuthHandler {
228
231
  }
229
232
 
230
233
  if (req.method === 'GET' && pathname === `${AUTH_ROUTE_PREFIX}/config`) {
231
- sendJson(res, 200, { hostMode: service.hostMode })
234
+ // `subscriptionOrigin` is the SAME resolved HQ_AI_ENV value as the
235
+ // usage endpoint; the browser half uses it to build the host-dialog
236
+ // URL instead of hardcoding gen.eda.cn.
237
+ sendJson(res, 200, {
238
+ hostMode: service.hostMode,
239
+ subscriptionOrigin: service.subscriptionOrigin,
240
+ // Origin of the resolved balances API — lets the browser build the
241
+ // GEN/ERC active-subscription calls without hardcoding eda.cn.
242
+ subscriptionApiBaseUrl: service.subscriptionApiBaseUrl,
243
+ })
232
244
  return
233
245
  }
234
246
 
@@ -248,15 +260,29 @@ export function createAuthHandler(service: HuaqiuAuthService): AuthHandler {
248
260
 
249
261
  if (req.method === 'GET' && pathname === `${AUTH_ROUTE_PREFIX}/ai-usage`) {
250
262
  // The WebView CANNOT reach this endpoint itself (plain http → ATS +
251
- // CORS, see AI_USAGE_URL), so the node half performs the call with the
252
- // credential IT resolved (host → pushed → persisted) — the same shape
253
- // as /user-info above.
263
+ // CORS), so the node half performs the call with the credential IT
264
+ // resolved (host → pushed → persisted) — the same shape as /user-info
265
+ // above. The URL itself is resolved by HQ Edge; absent → no call.
254
266
  const token = await service.auth.getAccessToken()
255
- if (!token) {
267
+ if (!token || !service.subscriptionBalancesUrl) {
256
268
  sendJson(res, 200, { usage: null })
257
269
  return
258
270
  }
259
- sendJson(res, 200, { usage: await fetchAiTokenUsage(token) })
271
+ const controller = new AbortController()
272
+ const onClose = () => controller.abort()
273
+ res.on('close', onClose)
274
+ let usage: AiUsage | null
275
+ try {
276
+ usage = await fetchAiUsage(
277
+ token,
278
+ service.subscriptionBalancesUrl,
279
+ globalThis.fetch.bind(globalThis),
280
+ { signal: controller.signal },
281
+ )
282
+ } finally {
283
+ res.off('close', onClose)
284
+ }
285
+ sendJson(res, 200, { usage })
260
286
  return
261
287
  }
262
288
 
package/src/service.ts CHANGED
@@ -95,11 +95,46 @@ export interface HuaqiuAuthService {
95
95
  * hq-edge, so the auth plugin's own login UI is suppressed.
96
96
  */
97
97
  readonly hostMode: boolean
98
+ /**
99
+ * Resolved subscription balances endpoint injected by HQ Edge
100
+ * (`config.subscriptionBalancesUrl`), or null when none was configured.
101
+ * `/ai-usage` never falls back to a stale hardcoded environment endpoint.
102
+ */
103
+ readonly subscriptionBalancesUrl: string | null
104
+ /**
105
+ * Origin of {@link subscriptionBalancesUrl} (e.g. `https://www.eda.cn`), used
106
+ * by the browser half for the GEN/ERC active-subscription calls. Null when no
107
+ * endpoint was configured — DSH Auth never hardcodes a production host.
108
+ */
109
+ readonly subscriptionApiBaseUrl: string | null
110
+ /**
111
+ * Resolved subscription origin injected by HQ Edge (`config.subscriptionOrigin`),
112
+ * or null when none was configured (standalone keeps its PROD default).
113
+ */
114
+ readonly subscriptionOrigin: string | null
98
115
  }
99
116
 
100
117
  const PERSIST_FILE = 'session.json'
101
118
  const PERSIST_DIR = () => dshHomePath('auth')
102
119
 
120
+ /** Host-only label for diagnostics (never log a complete AI usage URL). */
121
+ function safeHost(url: string): string {
122
+ try {
123
+ return new URL(url).host
124
+ } catch {
125
+ return '<invalid-url>'
126
+ }
127
+ }
128
+
129
+ /** Scheme + host origin of a URL, or null when it does not parse. */
130
+ function originOf(url: string): string | null {
131
+ try {
132
+ return new URL(url).origin
133
+ } catch {
134
+ return null
135
+ }
136
+ }
137
+
103
138
  /**
104
139
  * Bounded wait for the host to confirm a logout. Shorter than the login wait
105
140
  * (which must cover a human completing the EDA dialog): logout is a host-side
@@ -202,15 +237,35 @@ export class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
202
237
  fetchImpl: this.doFetch,
203
238
  })
204
239
  this.hostMode = this.host.enabled
240
+ this.subscriptionBalancesUrl = resolved.subscriptionBalancesUrl?.length
241
+ ? resolved.subscriptionBalancesUrl
242
+ : null
243
+ this.subscriptionApiBaseUrl = this.subscriptionBalancesUrl
244
+ ? originOf(this.subscriptionBalancesUrl)
245
+ : null
246
+ this.subscriptionOrigin = resolved.subscriptionOrigin?.length
247
+ ? resolved.subscriptionOrigin
248
+ : null
205
249
  this.log.info('auth service started', {
206
250
  hostMode: this.hostMode,
207
251
  hostAuthPath: resolved.hostAuthPath,
208
252
  hostSessionTtlSeconds: resolved.hostSessionTtlSeconds,
253
+ // Hosts only — never a complete URL that could carry a credential.
254
+ subscriptionBalancesHost: this.subscriptionBalancesUrl
255
+ ? safeHost(this.subscriptionBalancesUrl)
256
+ : null,
257
+ subscriptionOrigin: this.subscriptionOrigin,
209
258
  })
210
259
  }
211
260
 
212
261
  /** Host mode is active iff a host base URL was configured (see HostSessionResolver.enabled). */
213
262
  readonly hostMode: boolean
263
+ /** Subscription balances endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
264
+ readonly subscriptionBalancesUrl: string | null
265
+ /** Origin used for GEN/ERC active-subscription calls; null → unavailable. */
266
+ readonly subscriptionApiBaseUrl: string | null
267
+ /** Subscription origin resolved by HQ Edge (`HQ_AI_ENV`); null → standalone. */
268
+ readonly subscriptionOrigin: string | null
214
269
 
215
270
  readonly auth: HuaqiuAuthApi = {
216
271
  isAuthenticated: async () => {
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Single authoritative contract for the subscription-balances API
3
+ * (`GET /sub-api/subscriptions/balances/current`).
4
+ *
5
+ * Both halves import these types (the browser half type-only), and the node
6
+ * half's parser is the ONE place an upstream payload is turned into usage data.
7
+ * There must be no second response shape, no second parser and no locally
8
+ * derived percentage: `quotaRemainPercent` is the only source of truth.
9
+ *
10
+ * This module is intentionally dependency-free so the browser bundle can import
11
+ * the types without pulling node modules in.
12
+ */
13
+
14
+ /** One quota group in `result[]` (AI and non-AI groups share this shape). */
15
+ export interface SubscriptionBalanceGroup {
16
+ id: number
17
+ groupCode: string
18
+ groupName: string
19
+ quotaTotal: number | null
20
+ quotaUsed: number | null
21
+ quotaRemain: number | null
22
+ /** Remaining percentage. `null` for groups that do not report one. */
23
+ quotaRemainPercent: number | null
24
+ /** `true` ONLY for the AI Points group — the discriminator. */
25
+ aiPoints: boolean
26
+ status: number
27
+ }
28
+
29
+ /** The upstream envelope. */
30
+ export interface SubscriptionBalancesResponse {
31
+ code: number
32
+ message: string
33
+ result: SubscriptionBalanceGroup[]
34
+ }
35
+
36
+ /** Client-facing view: only the authoritative remaining percentage. */
37
+ export interface AiUsage {
38
+ quotaRemainPercent: number | null
39
+ }
40
+
41
+ /** The only success code accepted from the subscription balances API. */
42
+ export const SUBSCRIPTION_BALANCES_SUCCESS_CODE = 200000
43
+
44
+ function asRecord(value: unknown): Record<string, unknown> | null {
45
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
46
+ ? (value as Record<string, unknown>)
47
+ : null
48
+ }
49
+
50
+ /** `null`/missing/non-numeric → `null` (never a coerced 0). */
51
+ function numberOrNull(value: unknown): number | null {
52
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
53
+ }
54
+
55
+ function numberOf(value: unknown): number {
56
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0
57
+ }
58
+
59
+ function stringOf(value: unknown): string {
60
+ return typeof value === 'string' ? value : ''
61
+ }
62
+
63
+ function parseGroup(raw: unknown): SubscriptionBalanceGroup | null {
64
+ const group = asRecord(raw)
65
+ if (!group) return null
66
+ // `aiPoints` is the ONLY AI-group discriminator. A non-boolean value makes
67
+ // the payload unusable: guessing would risk showing a non-AI group.
68
+ if (typeof group.aiPoints !== 'boolean') return null
69
+ return {
70
+ id: numberOf(group.id),
71
+ groupCode: stringOf(group.groupCode),
72
+ groupName: stringOf(group.groupName),
73
+ quotaTotal: numberOrNull(group.quotaTotal),
74
+ quotaUsed: numberOrNull(group.quotaUsed),
75
+ quotaRemain: numberOrNull(group.quotaRemain),
76
+ quotaRemainPercent: numberOrNull(group.quotaRemainPercent),
77
+ aiPoints: group.aiPoints,
78
+ status: numberOf(group.status),
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Validate an upstream payload against the authoritative schema.
84
+ * Returns `null` for a non-2xx-style envelope, a non-array `result`, or any
85
+ * malformed group — callers degrade to "unavailable" rather than guessing.
86
+ */
87
+ export function parseSubscriptionBalancesResponse(
88
+ payload: unknown,
89
+ ): SubscriptionBalancesResponse | null {
90
+ const body = asRecord(payload)
91
+ if (!body) return null
92
+ if (body.code !== SUBSCRIPTION_BALANCES_SUCCESS_CODE) return null
93
+ if (!Array.isArray(body.result)) return null
94
+ const result = body.result.map(parseGroup)
95
+ if (result.some((group) => group === null)) return null
96
+ return {
97
+ code: body.code,
98
+ message: typeof body.message === 'string' ? body.message : '',
99
+ result: result as SubscriptionBalanceGroup[],
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Select the AI Points group and read its remaining percentage.
105
+ *
106
+ * No AI group → `null`; a missing/`null`/non-finite `quotaRemainPercent` →
107
+ * `null` (unavailable). `0` is preserved as a valid exhausted balance.
108
+ */
109
+ export function selectAiUsage(
110
+ response: SubscriptionBalancesResponse | null,
111
+ ): AiUsage | null {
112
+ const group = response?.result.find((entry) => entry.aiPoints === true)
113
+ if (!group) return null
114
+ const percent = group.quotaRemainPercent
115
+ if (percent === null || !Number.isFinite(percent)) return null
116
+ return { quotaRemainPercent: percent }
117
+ }
118
+
119
+ /** Parse + select in one step — the single upstream→usage normalization. */
120
+ export function aiUsageFromPayload(payload: unknown): AiUsage | null {
121
+ return selectAiUsage(parseSubscriptionBalancesResponse(payload))
122
+ }