@huaqiu/dsh-auth 0.5.8 → 0.5.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/src/index.ts CHANGED
@@ -80,9 +80,21 @@ export function apply(ctx: Context, config?: Partial<HuaqiuAuthConfig>): void {
80
80
  const sync = new HuaqiuApiKeySync(
81
81
  resolved.hqEdgeBaseUrl ?? '',
82
82
  resolved.hostAuthPath ?? DEFAULT_HOST_AUTH_PATH,
83
- {
84
- set: (ref, value) => ctx.credentials.set(ref as CredentialRef, value),
85
- unset: (ref) => ctx.credentials.unset(ref as CredentialRef),
83
+ // Lazy per-round resolution: the `credentials` service may not be
84
+ // activated yet while this plugin boots (activation order). Direct
85
+ // `ctx.credentials` property access would throw "cannot get property
86
+ // ... without inject" in that window; `ctx.get('credentials')`
87
+ // returns undefined instead, so the round is skipped and the next
88
+ // poll retries once the service is live (self-healing, no restart).
89
+ () => {
90
+ const credentials = ctx.get('credentials') as
91
+ | { set(ref: string, value: string): Promise<void>; unset(ref: string): Promise<void> }
92
+ | undefined
93
+ if (credentials === undefined) return null
94
+ return {
95
+ set: (ref, value) => credentials.set(ref as CredentialRef, value),
96
+ unset: (ref) => credentials.unset(ref as CredentialRef),
97
+ }
86
98
  },
87
99
  {
88
100
  debug: (msg, ctx2) => log.debug(msg, ctx2),
package/src/routes.ts CHANGED
@@ -6,6 +6,8 @@
6
6
  * POST /api/v1/huaqiu/auth/logout → cache cleared
7
7
  * GET /api/v1/huaqiu/auth/session → { authenticated, user }
8
8
  * GET /api/v1/huaqiu/auth/config → { hostMode }
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)
9
11
  *
10
12
  * `config` tells the browser half whether it is running under an HQ Edge host
11
13
  * (hq-edge passes the operator credential to hq-edge itself, so the sidebar
@@ -73,6 +75,85 @@ export async function fetchEdaUserProfile(
73
75
 
74
76
  export const AUTH_ROUTE_PREFIX = '/api/v1/huaqiu/auth'
75
77
 
78
+ // ── AI token usage (proxied by the node half) ────────────────────────────────
79
+
80
+ /**
81
+ * The account's AI balance endpoint.
82
+ *
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.
91
+ */
92
+ export const AI_USAGE_URL = 'http://www.fdatasheets.com/user-rest/api/ai/usage'
93
+
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
113
+ }
114
+
115
+ /**
116
+ * Fetch the account's AI token usage for a token. Null on any failure (the UI
117
+ * degrades to「—」) — never throws.
118
+ *
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`.
121
+ */
122
+ export async function fetchAiTokenUsage(
123
+ token: string,
124
+ doFetch: typeof fetch = globalThis.fetch.bind(globalThis),
125
+ ): Promise<AiTokenUsage | null> {
126
+ try {
127
+ const res = await doFetch(AI_USAGE_URL, {
128
+ method: 'GET',
129
+ headers: {
130
+ Accept: 'application/json, text/plain, */*',
131
+ 'Content-Type': 'application/json',
132
+ 'X-Token': token,
133
+ },
134
+ })
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'),
150
+ }
151
+ } catch (err) {
152
+ log().warn('fetchAiTokenUsage failed', { error: String((err as Error)?.message || err) })
153
+ return null
154
+ }
155
+ }
156
+
76
157
  export type AuthHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void> | void
77
158
 
78
159
  function sendJson(res: ServerResponse, status: number, body: unknown): void {
@@ -165,6 +246,20 @@ export function createAuthHandler(service: HuaqiuAuthService): AuthHandler {
165
246
  return
166
247
  }
167
248
 
249
+ if (req.method === 'GET' && pathname === `${AUTH_ROUTE_PREFIX}/ai-usage`) {
250
+ // 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.
254
+ const token = await service.auth.getAccessToken()
255
+ if (!token) {
256
+ sendJson(res, 200, { usage: null })
257
+ return
258
+ }
259
+ sendJson(res, 200, { usage: await fetchAiTokenUsage(token) })
260
+ return
261
+ }
262
+
168
263
  if (req.method === 'POST' && pathname === `${AUTH_ROUTE_PREFIX}/login`) {
169
264
  // Host-mode login: forward to HQ Edge, which asks EDA (KiCad) to open
170
265
  // its TriggerLoginDialog. Blocks until the dialog is completed.