@huaqiu/dsh-auth 0.6.20 → 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/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
 
@@ -60,15 +64,14 @@ export const ERC_PRODUCT_CODE = 'erc'
60
64
  * (points × 50) and `usd` its money equivalent. All three pairs are reported
61
65
  * because the endpoint reports all three; the UI reads `points`.
62
66
  *
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`.
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
69
+ * Transport Security ("the resource could not be loaded because the App
70
+ * Transport Security policy requires the use of a secure connection") and CORS
71
+ * (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
74
+ * same-origin route, exactly like the eda.cn profile on `/user-info`.
72
75
  */
73
76
  export interface AiTokenUsage {
74
77
  availablePoints: number
@@ -81,12 +84,16 @@ export interface AiTokenUsage {
81
84
 
82
85
  /**
83
86
  * Build the subscription landing URL. Mirrors `buildProfileUrl`: the token is
84
- * always attached — `gen.eda.cn/subscription` consumes it to establish the
87
+ * always attached — the subscription page consumes it to establish the
85
88
  * session and hides it itself. `encodeURIComponent` is required (tokens are
86
89
  * base64-ish and may contain `+`, `/` or `=`).
90
+ *
91
+ * `origin` comes from the node half (HQ Edge → `HQ_AI_ENV`); omitted in
92
+ * standalone DSH, which keeps the PROD fallback.
87
93
  */
88
- export function buildSubscriptionUrl(options: { token: string }): string {
89
- return `${SUBSCRIPTION_ORIGIN}${SUBSCRIPTION_PATH}?token=${encodeURIComponent(options.token)}`
94
+ export function buildSubscriptionUrl(options: { token: string; origin?: string }): string {
95
+ const origin = (options.origin ?? DEFAULT_SUBSCRIPTION_ORIGIN).replace(/\/+$/, '')
96
+ return `${origin}${SUBSCRIPTION_PATH}?token=${encodeURIComponent(options.token)}`
90
97
  }
91
98
 
92
99
  /** Normalized active-subscription quota view (whatever the backend sends). */
@@ -10,11 +10,13 @@ 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).
16
18
  */
17
- fetchHostMode(): Promise<boolean>
19
+ fetchRuntimeConfig(): Promise<AuthRuntimeConfig>
18
20
  /**
19
21
  * Fetch the node half's authoritative session. The node resolves host-mode
20
22
  * credentials first (host session → pushed browser session → persisted
@@ -39,11 +41,12 @@ export interface AuthTransport {
39
41
  fetchUserInfo(): Promise<EdaUserProfile | null>
40
42
  /**
41
43
  * 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「—」).
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.
49
+ * Null on failure (the sidebar shows「—」).
47
50
  */
48
51
  fetchAiUsage(): Promise<AiTokenUsage | null>
49
52
  }
@@ -56,6 +59,27 @@ export interface HostSessionUser {
56
59
  expiresAt?: number
57
60
  }
58
61
 
62
+ /** Runtime config served by the node `/config` route. */
63
+ export interface AuthRuntimeConfig {
64
+ hostMode: boolean
65
+ /** Absolute http(s) origin; null = standalone (client keeps its default). */
66
+ subscriptionOrigin: string | null
67
+ }
68
+
69
+ /** Accept only an absolute http(s) origin; anything else → null. */
70
+ function normalizeOrigin(value: unknown): string | null {
71
+ if (typeof value !== 'string') return null
72
+ const trimmed = value.trim().replace(/\/+$/, '')
73
+ if (!trimmed) return null
74
+ try {
75
+ const url = new URL(trimmed)
76
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
77
+ return trimmed
78
+ } catch {
79
+ return null
80
+ }
81
+ }
82
+
59
83
  /** Rich eda.cn profile served by the node `/user-info` route. */
60
84
  export interface EdaUserProfile {
61
85
  nickname?: string
@@ -86,20 +110,23 @@ export function createWebServerAuthTransport(
86
110
  const res = await doFetch(`${base}/logout`, { method: 'POST' })
87
111
  if (!res.ok) throw new Error(`auth logout push failed: HTTP ${res.status}`)
88
112
  },
89
- async fetchHostMode() {
113
+ async fetchRuntimeConfig() {
90
114
  try {
91
115
  const res = await doFetch(`${base}/config`, {
92
116
  method: 'GET',
93
117
  headers: { accept: 'application/json' },
94
118
  })
95
- if (!res.ok) return false
96
- const body = await res.json() as { hostMode?: unknown }
97
- return body.hostMode === true
119
+ if (!res.ok) return { hostMode: false, subscriptionOrigin: null }
120
+ const body = await res.json() as { hostMode?: unknown; subscriptionOrigin?: unknown }
121
+ return {
122
+ hostMode: body.hostMode === true,
123
+ subscriptionOrigin: normalizeOrigin(body.subscriptionOrigin),
124
+ }
98
125
  } catch {
99
126
  // Offline/same-origin failure: fall back to standalone (show the login
100
127
  // entrypoint) rather than hiding it — a login UI is never a security
101
128
  // regression, but a missing one in standalone would lock the user out.
102
- return false
129
+ return { hostMode: false, subscriptionOrigin: null }
103
130
  }
104
131
  },
105
132
  async fetchSession() {
@@ -17,11 +17,15 @@
17
17
  * `UserMenu`, portalled to `document.body` with fixed positioning so the
18
18
  * sidebar's `overflow: hidden` can never clip it.
19
19
  *
20
- * THEMING: colors prefer DSH's `--dsw-alias-*` tokens (so a custom host theme
21
- * is honored) and fall back to an explicit light/dark pair chosen from
22
- * `useIsDark()`; the two paths cannot disagree, because ui-layout's presenter
23
- * writes `body[data-ds-dark-theme]` from the very snapshot that installs those
24
- * tokens.
20
+ * THEMING: the LIGHT palette stays token-first (DSH `--dsw-alias-*` with an
21
+ * explicit fallback), so a custom host theme is honored. The DARK palette is
22
+ * deliberately EXPLICIT: it follows `docs/prototype/avatar_popup_redesign_prototype.html`,
23
+ * whose "before" is exactly what the host token produces — `--dsw-alias-bg-overlay`
24
+ * resolves to `rgb(97, 102, 107)` in dark mode, the muddy medium-gray surface
25
+ * the prototype calls out as the contrast defect. Keeping the token would
26
+ * silently re-introduce it, so the popup pins its own deep-slate color schema
27
+ * instead. `useIsDark()` still selects the pair, driven by the same
28
+ * `body[data-ds-dark-theme]` snapshot ui-layout's presenter writes.
25
29
  */
26
30
  import { memo, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react'
27
31
  import { createPortal } from 'react-dom'
@@ -38,43 +42,68 @@ export interface SidebarFooterActionOwnerProps {
38
42
  const AVATAR_SIZE = 26
39
43
  const ICON_SIZE = 22
40
44
 
41
- /** One color scheme's menu colors (DSH token first, explicit fallback second). */
45
+ /**
46
+ * The popup's color schema. Every painted value comes from here, so the dark
47
+ * palette can be swapped as one coherent unit. The values are the concrete
48
+ * equivalents of the prototype's Tailwind classes (see `DARK_PALETTE`).
49
+ */
42
50
  interface Palette {
43
51
  surface: string
52
+ /** Popup border + the 1px section dividers. */
44
53
  border: string
45
54
  text: string
55
+ /** Header name + metric headline (prototype `text-white` in dark). */
56
+ heading: string
46
57
  muted: string
47
58
  hover: string
48
59
  danger: string
49
60
  dangerHover: string
50
61
  avatarBg: string
51
62
  shadow: string
52
- /** Profile-header card background (prototype `bg-white/[0.03]`). */
63
+ /** Profile-header card background + hairline. */
53
64
  card: string
54
- /** 1px hairline used on cards inside the popup. */
65
+ headerBorder: string
66
+ /** 1px hairline used on the quota metric card. */
55
67
  cardBorder: string
56
- /** Quota metric card background (prototype `bg-black/20`). */
68
+ /** Quota metric card background. */
57
69
  metric: string
58
70
  metricHover: string
59
- /** Huaqiu brand red (#e62e2d). */
71
+ /** Plan badge: fill, label and hairline (prototype red-500/20 + red-400). */
72
+ badgeBg: string
73
+ badgeText: string
74
+ badgeBorder: string
75
+ /** "Online" pill: dot/text, translucent fill and hairline (emerald). */
76
+ online: string
77
+ onlineBg: string
78
+ onlineBorder: string
79
+ /** Huaqiu brand red — CTA gradient start + hover start. */
60
80
  primary: string
61
81
  primaryHover: string
62
- /** Badge tint: primary at ~10% (prototype `bg-hq-primary/10`). */
63
- primarySoft: string
64
- /** Progress-bar track (prototype `dark:bg-gray-800`). */
82
+ /** CTA gradient end + hover end. */
83
+ ctaEnd: string
84
+ ctaHoverEnd: string
85
+ /** CTA glow. */
86
+ ctaShadow: string
87
+ /** Progress-bar track. */
65
88
  track: string
66
- /** GEN / ERC / AI progress gradients (prototype blue→indigo, purple→pink). */
89
+ /** AI metric sparkles glyph. */
90
+ aiIcon: string
91
+ /** GEN / ERC / AI progress gradients. */
67
92
  genGradient: string
68
93
  ercGradient: string
69
94
  aiGradient: string
70
- /** "Online" dot green. */
71
- online: string
72
95
  }
73
96
 
74
- const LIGHT_PALETTE: Palette = {
97
+ /**
98
+ * Light scheme keeps the DSH token-first convention (custom host themes win).
99
+ * The extra tokens introduced for the dark redesign are filled with the values
100
+ * that were previously hardcoded inline, so light rendering is unchanged.
101
+ */
102
+ export const LIGHT_PALETTE: Palette = {
75
103
  surface: 'var(--dsw-alias-bg-overlay, #ffffff)',
76
104
  border: 'var(--dsw-alias-border-l1, #e4e7ec)',
77
105
  text: 'var(--dsw-alias-label-primary, #3a4356)',
106
+ heading: 'var(--dsw-alias-label-primary, #3a4356)',
78
107
  muted: 'var(--dsw-alias-label-secondary, #8a94a6)',
79
108
  hover: 'var(--dsw-alias-interactive-bg-hover, #f5f7fa)',
80
109
  danger: 'var(--dsw-alias-state-error-primary, #d4380d)',
@@ -82,41 +111,68 @@ const LIGHT_PALETTE: Palette = {
82
111
  avatarBg: 'var(--dsw-alias-bg-layer-2, #eef2f7)',
83
112
  shadow: '0 20px 40px -15px rgba(0, 0, 0, 0.12), 0 0 1px 1px rgba(0, 0, 0, 0.05)',
84
113
  card: '#f7f8fa',
114
+ headerBorder: '#e8ebf0',
85
115
  cardBorder: '#e8ebf0',
86
116
  metric: '#f7f8fa',
87
117
  metricHover: '#eef1f5',
118
+ badgeBg: 'rgba(230, 46, 45, 0.08)',
119
+ badgeText: '#e62e2d',
120
+ badgeBorder: 'rgba(230, 46, 45, 0.08)',
121
+ online: '#10b981',
122
+ onlineBg: 'rgba(16, 185, 129, 0.10)',
123
+ onlineBorder: 'rgba(16, 185, 129, 0.20)',
88
124
  primary: '#e62e2d',
89
125
  primaryHover: '#cc2423',
90
- primarySoft: 'rgba(230, 46, 45, 0.08)',
126
+ ctaEnd: '#e11d48',
127
+ ctaHoverEnd: '#be123c',
128
+ ctaShadow: '0 8px 20px rgba(230, 46, 45, 0.22)',
91
129
  track: '#e4e7ec',
130
+ aiIcon: '#10b981',
92
131
  genGradient: 'linear-gradient(90deg, #3b82f6, #6366f1)',
93
132
  ercGradient: 'linear-gradient(90deg, #a855f7, #ec4899)',
94
133
  aiGradient: 'linear-gradient(90deg, #10b981, #06b6d4)',
95
- online: '#10b981',
96
134
  }
97
135
 
98
- const DARK_PALETTE: Palette = {
99
- surface: 'var(--dsw-alias-bg-overlay, #1e1b24)',
100
- border: 'var(--dsw-alias-border-l1, rgba(255, 255, 255, 0.10))',
101
- text: 'var(--dsw-alias-label-primary, #e6eaf0)',
102
- muted: 'var(--dsw-alias-label-secondary, #8b95a5)',
103
- hover: 'var(--dsw-alias-interactive-bg-hover, rgba(255, 255, 255, 0.08))',
104
- danger: 'var(--dsw-alias-state-error-primary, #ff7875)',
105
- dangerHover: 'rgba(255, 120, 117, 0.14)',
106
- avatarBg: 'var(--dsw-alias-bg-layer-2, rgba(255, 255, 255, 0.10))',
107
- shadow: '0 20px 40px -15px rgba(0, 0, 0, 0.7), 0 0 1px 1px rgba(255, 255, 255, 0.1)',
108
- card: 'rgba(255, 255, 255, 0.03)',
109
- cardBorder: 'rgba(255, 255, 255, 0.08)',
110
- metric: 'rgba(0, 0, 0, 0.20)',
111
- metricHover: 'rgba(0, 0, 0, 0.30)',
112
- primary: '#e62e2d',
113
- primaryHover: '#cc2423',
114
- primarySoft: 'rgba(230, 46, 45, 0.10)',
115
- track: 'rgba(255, 255, 255, 0.10)',
136
+ /**
137
+ * Dark color schema from `avatar_popup_redesign_prototype.html` (the "AFTER"
138
+ * card and the interactive popover's `dark:` classes). Explicit values, not
139
+ * `var(--dsw-alias-*, …)`: the host's dark `--dsw-alias-bg-overlay` is
140
+ * `rgb(97, 102, 107)`, the muddy surface the prototype replaces with a crisp
141
+ * deep slate. Alpha-tinted badges, the cyan→blue meter and the brighter brand
142
+ * red are the other three contrast fixes the prototype prescribes.
143
+ */
144
+ export const DARK_PALETTE: Palette = {
145
+ surface: '#1C1E24', // dark:bg-[#1C1E24]
146
+ border: 'rgba(255, 255, 255, 0.10)', // dark:border-white/10, dividers
147
+ text: '#e2e8f0', // dark:text-slate-200
148
+ heading: '#ffffff', // dark:text-white
149
+ muted: '#94a3b8', // dark:text-slate-400
150
+ hover: 'rgba(255, 255, 255, 0.05)', // dark:hover:bg-white/5
151
+ danger: '#f87171', // dark:text-red-400
152
+ dangerHover: 'rgba(239, 68, 68, 0.10)', // dark:hover:bg-red-500/10
153
+ avatarBg: 'rgba(255, 255, 255, 0.10)',
154
+ shadow: '0 16px 36px -4px rgba(0, 0, 0, 0.6), 0 0 1px 1px rgba(255, 255, 255, 0.08)', // shadow-popover-dark
155
+ card: 'transparent', // flat header, no muddy card
156
+ headerBorder: 'transparent', // prototype has no header outline
157
+ cardBorder: 'rgba(255, 255, 255, 0.05)', // dark:border-white/5
158
+ metric: '#252831', // dark:bg-[#252831]
159
+ metricHover: '#2C303A', // subtle lift on hover
160
+ badgeBg: 'rgba(239, 68, 68, 0.20)', // dark:bg-red-500/20
161
+ badgeText: '#f87171', // dark:text-red-400
162
+ badgeBorder: 'rgba(239, 68, 68, 0.20)', // border-red-500/20
163
+ online: '#34d399', // emerald-400 dot + label
164
+ onlineBg: 'rgba(16, 185, 129, 0.10)', // bg-emerald-500/10
165
+ onlineBorder: 'rgba(16, 185, 129, 0.20)', // border-emerald-500/20
166
+ primary: '#FF4D4F', // eda.brand-dark
167
+ primaryHover: '#FF6B6D', // eda.brand-dark-hover
168
+ ctaEnd: '#ef4444', // dark:to-red-500
169
+ ctaHoverEnd: '#f87171', // brightness-110 equivalent
170
+ ctaShadow: '0 8px 20px rgba(255, 77, 79, 0.24)',
171
+ track: '#334155', // dark:bg-slate-700
172
+ aiIcon: '#22d3ee', // dark:text-cyan-400
116
173
  genGradient: 'linear-gradient(90deg, #3b82f6, #6366f1)',
117
174
  ercGradient: 'linear-gradient(90deg, #a855f7, #ec4899)',
118
- aiGradient: 'linear-gradient(90deg, #10b981, #06b6d4)',
119
- online: '#10b981',
175
+ aiGradient: 'linear-gradient(90deg, #06b6d4, #3b82f6)', // cyan-500 → blue-500
120
176
  }
121
177
 
122
178
  const TRIGGER_BASE: CSSProperties = {
@@ -208,7 +264,16 @@ function MenuItem({
208
264
  onClick={onSelect}
209
265
  >
210
266
  <span style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
211
- {icon}
267
+ <span
268
+ style={{
269
+ display: 'flex',
270
+ flex: '0 0 auto',
271
+ color: danger ? palette.danger : (hovered ? palette.text : palette.muted),
272
+ transition: 'color 0.15s ease',
273
+ }}
274
+ >
275
+ {icon}
276
+ </span>
212
277
  <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
213
278
  </span>
214
279
  {trailing ? (
@@ -353,7 +418,7 @@ function ChevronRightIcon(): React.JSX.Element {
353
418
  }
354
419
 
355
420
  /** AI usage metric glyph (lucide `sparkles`) — the token balance. */
356
- function SparklesIcon(): React.JSX.Element {
421
+ function SparklesIcon({ color }: { color: string }): React.JSX.Element {
357
422
  return (
358
423
  <svg
359
424
  xmlns="http://www.w3.org/2000/svg"
@@ -361,7 +426,7 @@ function SparklesIcon(): React.JSX.Element {
361
426
  height={14}
362
427
  viewBox="0 0 24 24"
363
428
  fill="none"
364
- stroke="#10b981"
429
+ stroke={color}
365
430
  strokeWidth={2}
366
431
  strokeLinecap="round"
367
432
  strokeLinejoin="round"
@@ -431,7 +496,7 @@ function QuotaMetric({
431
496
  <span
432
497
  style={{
433
498
  fontWeight: 700,
434
- color: reading?.ok ? palette.text : palette.danger,
499
+ color: reading?.ok ? palette.heading : palette.danger,
435
500
  fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
436
501
  fontSize: 12,
437
502
  whiteSpace: 'nowrap',
@@ -463,14 +528,20 @@ export function quotaReading(quota: SubscriptionQuota | null, t: Translate): Met
463
528
  const percent = quota.hasSubscription && typeof total === 'number' && total > 0
464
529
  ? Math.max(0, Math.min(100, Math.round((used / total) * 100)))
465
530
  : 0
531
+ const subscribed = quota.hasSubscription
466
532
  return {
467
- value: quota.hasSubscription
533
+ // Headline shows the usage percent (e.g. "65%"); the exact
534
+ // "{used} / {total}" count is preserved as the hover title.
535
+ value: subscribed
468
536
  ? (typeof total === 'number'
469
- ? t('subscription.quotaCount', { used, total })
470
- : String(used))
537
+ ? t('subscription.quotaPercent', { percent })
538
+ : `${percent}%`)
471
539
  : t('subscription.unsubscribed'),
540
+ title: subscribed && typeof total === 'number'
541
+ ? t('subscription.quotaCount', { used, total })
542
+ : undefined,
472
543
  percent,
473
- ok: quota.hasSubscription,
544
+ ok: subscribed,
474
545
  }
475
546
  }
476
547
 
@@ -498,9 +569,12 @@ export function aiUsageReading(usage: AiTokenUsage | null, t: Translate): Metric
498
569
  const percent = total > 0
499
570
  ? Math.min(100, Math.round((available / total) * 1000) / 10)
500
571
  : 0
572
+ // Headline shows the usage percent (e.g. "65%"); the exact
573
+ // "{available} / {total} pts" balance is preserved as the hover title.
574
+ const displayPercent = Math.round(percent)
501
575
  return {
502
- value: t('subscription.aiUsageCount', { available, total }),
503
- title: t('subscription.aiUsagePercent', { percent }),
576
+ value: t('subscription.aiUsagePercent', { percent: displayPercent }),
577
+ title: t('subscription.aiUsageCount', { available, total }),
504
578
  percent,
505
579
  ok: true,
506
580
  }
@@ -530,7 +604,7 @@ function ProfileHeaderCard({
530
604
  padding: 10,
531
605
  borderRadius: 12,
532
606
  background: palette.card,
533
- border: `1px solid ${palette.cardBorder}`,
607
+ border: `1px solid ${palette.headerBorder}`,
534
608
  display: 'flex',
535
609
  alignItems: 'center',
536
610
  justifyContent: 'space-between',
@@ -545,7 +619,7 @@ function ProfileHeaderCard({
545
619
  style={{
546
620
  fontSize: 14,
547
621
  fontWeight: 700,
548
- color: palette.text,
622
+ color: palette.heading,
549
623
  overflow: 'hidden',
550
624
  textOverflow: 'ellipsis',
551
625
  whiteSpace: 'nowrap',
@@ -557,12 +631,12 @@ function ProfileHeaderCard({
557
631
  <span
558
632
  style={{
559
633
  fontSize: 10,
560
- background: palette.primarySoft,
561
- color: palette.primary,
634
+ background: palette.badgeBg,
635
+ color: palette.badgeText,
562
636
  padding: '2px 6px',
563
637
  borderRadius: 4,
564
638
  fontWeight: 500,
565
- border: `1px solid ${palette.primarySoft}`,
639
+ border: `1px solid ${palette.badgeBorder}`,
566
640
  whiteSpace: 'nowrap',
567
641
  flexShrink: 0,
568
642
  }}
@@ -590,12 +664,12 @@ function ProfileHeaderCard({
590
664
  <span
591
665
  style={{
592
666
  fontSize: 10,
593
- background: 'rgba(16, 185, 129, 0.10)',
667
+ background: palette.onlineBg,
594
668
  color: palette.online,
595
669
  padding: '2px 8px',
596
670
  borderRadius: 999,
597
671
  fontWeight: 500,
598
- border: '1px solid rgba(16, 185, 129, 0.20)',
672
+ border: `1px solid ${palette.onlineBorder}`,
599
673
  display: 'flex',
600
674
  alignItems: 'center',
601
675
  gap: 5,
@@ -630,11 +704,9 @@ function UpgradeButton({
630
704
  padding: '9px 12px',
631
705
  borderRadius: 12,
632
706
  border: 'none',
633
- background: subscribing
634
- ? `linear-gradient(90deg, ${palette.primary}, #e11d48)`
635
- : hovered
636
- ? `linear-gradient(90deg, ${palette.primaryHover}, #be123c)`
637
- : `linear-gradient(90deg, ${palette.primary}, #e11d48)`,
707
+ background: hovered && !subscribing
708
+ ? `linear-gradient(90deg, ${palette.primaryHover}, ${palette.ctaHoverEnd})`
709
+ : `linear-gradient(90deg, ${palette.primary}, ${palette.ctaEnd})`,
638
710
  color: '#ffffff',
639
711
  fontSize: 12,
640
712
  fontWeight: 600,
@@ -644,7 +716,7 @@ function UpgradeButton({
644
716
  gap: 8,
645
717
  cursor: subscribing ? 'default' : 'pointer',
646
718
  opacity: subscribing ? 0.72 : 1,
647
- boxShadow: '0 8px 20px rgba(230, 46, 45, 0.22)',
719
+ boxShadow: palette.ctaShadow,
648
720
  transition: 'background 0.15s ease, opacity 0.15s ease',
649
721
  }}
650
722
  onMouseEnter={() => setHovered(true)}
@@ -913,17 +985,10 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
913
985
  </div>
914
986
  <div role="presentation" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
915
987
  <QuotaMetric
916
- label={t('subscription.gen')}
917
- icon={<CpuIcon />}
918
- reading={quotaReading(quota?.gen ?? null, t)}
919
- gradient={palette.genGradient}
920
- palette={palette}
921
- />
922
- <QuotaMetric
923
- label={t('subscription.erc')}
924
- icon={<WaveIcon />}
925
- reading={quotaReading(quota?.erc ?? null, t)}
926
- gradient={palette.ercGradient}
988
+ label={t('subscription.ai')}
989
+ icon={<SparklesIcon color={palette.aiIcon} />}
990
+ reading={aiUsageReading(quota?.ai ?? null, t)}
991
+ gradient={palette.aiGradient}
927
992
  palette={palette}
928
993
  />
929
994
  </div>
package/src/host.ts CHANGED
@@ -45,6 +45,17 @@ export interface HuaqiuAuthConfig {
45
45
  hostSessionTtlSeconds?: number
46
46
  /** Seconds remote token-validation results are cached. Default 60. */
47
47
  validationTtlSeconds?: number
48
+ /**
49
+ * AI token-usage endpoint resolved by HQ Edge from `HQ_AI_ENV` (task
50
+ * ai-env-swithcing-for-internal-test.md). Absent → `/ai-usage` returns null
51
+ * instead of calling a stale/default endpoint.
52
+ */
53
+ aiUsageUrl?: string
54
+ /**
55
+ * Subscription landing-page origin resolved by HQ Edge from the SAME
56
+ * `HQ_AI_ENV`. Absent → the browser half keeps its standalone PROD default.
57
+ */
58
+ subscriptionOrigin?: string
48
59
  }
49
60
 
50
61
  export const DEFAULT_HOST_AUTH_PATH = '/api/v1/auth/token'
@@ -90,6 +101,13 @@ export function resolveHostConfig(
90
101
  const parsed = Number.parseInt(vTtlRaw, 10)
91
102
  if (Number.isFinite(parsed) && parsed > 0) validationTtlSeconds = parsed
92
103
  }
104
+ // Resolved AI endpoints: overlay config (what HQ Edge injects) wins; explicit
105
+ // env URLs are the standalone escape hatch. HQ_AI_ENV itself is NOT read here
106
+ // — the prod/test mapping lives only in HQ Edge's central config.
107
+ const aiUsageUrl = (config?.aiUsageUrl ?? env.HQ_AI_USAGE_URL ?? '').trim()
108
+ const subscriptionOrigin = (config?.subscriptionOrigin ?? env.HQ_AI_SUBSCRIPTION_ORIGIN ?? '')
109
+ .trim()
110
+ .replace(/\/+$/, '')
93
111
  return {
94
112
  hqEdgeBaseUrl: baseUrl,
95
113
  hostAuthPath,
@@ -97,6 +115,8 @@ export function resolveHostConfig(
97
115
  hostLogoutPath,
98
116
  hostSessionTtlSeconds: ttl,
99
117
  validationTtlSeconds,
118
+ aiUsageUrl,
119
+ subscriptionOrigin,
100
120
  }
101
121
  }
102
122
 
package/src/index.ts CHANGED
@@ -5,9 +5,15 @@
5
5
  * mounts the browser→node credential routes on `ctx.webServer`.
6
6
  */
7
7
  import type { Context } from '@deepseek-ai/cordis'
8
+ import type { CredentialRef } from '@deepseek-ai/dsh-credentials'
8
9
  import type {} from '@deepseek-ai/dsh-host-webserver'
9
10
  import { getLogger } from '@huaqiu/dsh-plugin-log'
10
- import type { HuaqiuAuthConfig } from './host.js'
11
+ import {
12
+ DEFAULT_HOST_AUTH_PATH,
13
+ resolveHostConfig,
14
+ type HuaqiuAuthConfig,
15
+ } from './host.js'
16
+ import { HuaqiuApiKeySync, HUAQIU_API_KEY_REF } from './apiKeySync.js'
11
17
  import { InMemoryHuaqiuAuthService, type HuaqiuAuthService } from './service.js'
12
18
  import { AUTH_ROUTE_PREFIX, createAuthHandler } from './routes.js'
13
19
 
@@ -16,6 +22,12 @@ const log = getLogger('dsh-auth')
16
22
  export type { HuaqiuAuthApi, HuaqiuAuthService, HuaqiuUserInfo } from './service.js'
17
23
  export { InMemoryHuaqiuAuthService } from './service.js'
18
24
  export { AUTH_ROUTE_PREFIX, createAuthHandler, type AuthHandler } from './routes.js'
25
+ export {
26
+ DEFAULT_HUAQIU_API_KEY_SYNC_MS,
27
+ HuaqiuApiKeySync,
28
+ HUAQIU_API_KEY_REF,
29
+ type CredentialStore,
30
+ } from './apiKeySync.js'
19
31
  export type { HuaqiuAuthConfig } from './host.js'
20
32
 
21
33
  export const name = '@huaqiu/dsh-auth'
@@ -55,5 +67,45 @@ export function apply(ctx: Context, config?: Partial<HuaqiuAuthConfig>): void {
55
67
  handler: createAuthHandler(service),
56
68
  }))
57
69
 
70
+ // Host mode: mirror the operator token into the DSH credential reference
71
+ // `HUAQIU_API_KEY` so the bundled `huaqiu` AI provider can resolve it per
72
+ // request (task huaqiu-ai-gateway §5). The sync re-fetches the loopback
73
+ // token endpoint on an immediate round plus a 5 s non-overlapping poll;
74
+ // it is host-scoped only — standalone DSH keeps its browser-login flow and
75
+ // the reference stays unset (missing credential → explicit
76
+ // MISSING_CREDENTIAL, never a fallback key).
77
+ if (service.hostMode) {
78
+ ctx.effect(() => {
79
+ const resolved = resolveHostConfig(config)
80
+ const sync = new HuaqiuApiKeySync(
81
+ resolved.hqEdgeBaseUrl ?? '',
82
+ resolved.hostAuthPath ?? DEFAULT_HOST_AUTH_PATH,
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
+ }
98
+ },
99
+ {
100
+ debug: (msg, ctx2) => log.debug(msg, ctx2),
101
+ info: (msg, ctx2) => log.info(msg, ctx2),
102
+ warn: (msg, ctx2) => log.warn(msg, ctx2),
103
+ },
104
+ )
105
+ sync.start()
106
+ return () => sync.dispose()
107
+ })
108
+ }
109
+
58
110
  log.info('dsh-auth node half ready', { routes: AUTH_ROUTE_PREFIX, hostMode: service.hostMode })
59
111
  }