@huaqiu/dsh-auth 0.6.21 → 0.6.23
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/client.js +217 -43
- package/lib/client.js.map +1 -1
- package/lib/index.d.mts +18 -10
- package/lib/index.mjs +141 -36
- package/package.json +2 -2
- package/src/client/client.ts +63 -22
- package/src/client/i18n.ts +14 -10
- package/src/client/index.tsx +15 -3
- package/src/client/lib.ts +20 -27
- package/src/client/transport.ts +41 -14
- package/src/client/ui/sidebar-action.tsx +15 -33
- package/src/client/ui/turn-error-cta.tsx +165 -0
- package/src/host.ts +10 -6
- package/src/routes.ts +79 -59
- package/src/service.ts +32 -8
- package/src/subscription-balances.ts +122 -0
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
|
-
*
|
|
40
|
-
*
|
|
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
|
-
|
|
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
|
|
155
|
-
* or null when none was configured.
|
|
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
|
|
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
|
-
/**
|
|
191
|
-
readonly
|
|
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
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
/**
|
|
556
|
-
|
|
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
|
|
787
|
-
*
|
|
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)
|
|
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
|
|
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(
|
|
888
|
+
const res = await doFetch(subscriptionBalancesUrl, {
|
|
795
889
|
method: "GET",
|
|
796
890
|
headers: {
|
|
797
|
-
Accept: "application/json
|
|
798
|
-
"
|
|
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)
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
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("
|
|
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.
|
|
991
|
+
if (!token || !service.subscriptionBalancesUrl) {
|
|
896
992
|
sendJson(res, 200, { usage: null });
|
|
897
993
|
return;
|
|
898
994
|
}
|
|
899
|
-
|
|
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.
|
|
3
|
+
"version": "0.6.23",
|
|
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.
|
|
36
|
+
"@huaqiu/dsh-plugin-log": "0.6.23"
|
|
37
37
|
},
|
|
38
38
|
"files": [
|
|
39
39
|
"lib",
|
package/src/client/client.ts
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
fetchSubscriptionQuota,
|
|
10
10
|
handleAuthMessage,
|
|
11
11
|
SUBSCRIPTION_PREFERRED_SIZE,
|
|
12
|
-
type
|
|
12
|
+
type AiUsage,
|
|
13
13
|
type AuthMessageEventLike,
|
|
14
14
|
type AuthTokenPayload,
|
|
15
15
|
type LoginOptions,
|
|
@@ -33,8 +33,8 @@ export interface AuthClientDeps {
|
|
|
33
33
|
* `hqEdge` service). In host mode the subscription dialog must be opened by
|
|
34
34
|
* the EDA host through DialogService.OpenUrl (hqEdge.openUrl) — a browser
|
|
35
35
|
* iframe cannot be shown over the host UI. Absent/undefined = the host has
|
|
36
|
-
* no dialog service; `openSubscriptionDialog()` then
|
|
37
|
-
* degrades gracefully.
|
|
36
|
+
* no dialog service; `openSubscriptionDialog()` then resolves
|
|
37
|
+
* `host-unavailable` and the caller degrades gracefully.
|
|
38
38
|
*/
|
|
39
39
|
openHostDialog?: (url: string, options: {
|
|
40
40
|
title?: string
|
|
@@ -43,6 +43,15 @@ export interface AuthClientDeps {
|
|
|
43
43
|
}) => Promise<void>
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
/** Explicit result of {@link AuthClient['auth']['openSubscriptionDialog']}. */
|
|
47
|
+
export type SubscriptionDialogOutcome =
|
|
48
|
+
| { readonly status: 'opened' }
|
|
49
|
+
| { readonly status: 'already-open' }
|
|
50
|
+
/** No usable credential; the caller should offer login. */
|
|
51
|
+
| { readonly status: 'signed-out' }
|
|
52
|
+
/** Host mode with no dialog service wired (or nothing to open). */
|
|
53
|
+
| { readonly status: 'host-unavailable' }
|
|
54
|
+
|
|
46
55
|
export interface AuthClient {
|
|
47
56
|
auth: {
|
|
48
57
|
isAuthenticated(): boolean
|
|
@@ -66,10 +75,11 @@ export interface AuthClient {
|
|
|
66
75
|
*/
|
|
67
76
|
logout(): Promise<void>
|
|
68
77
|
/**
|
|
69
|
-
* Active subscription quota for one eda.cn product, fetched
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
78
|
+
* Active subscription quota for one eda.cn product, fetched directly from
|
|
79
|
+
* the environment's subscription API (`/sub-api/subscriptions/active`) —
|
|
80
|
+
* the origin is injected by HQ Edge via the node `/config` route, so this
|
|
81
|
+
* follows `HQ_AI_ENV` and no host is hardcoded. Null on fetch failure /
|
|
82
|
+
* no credential / no configured origin.
|
|
73
83
|
*/
|
|
74
84
|
getSubscriptionQuota(productCode: string): Promise<SubscriptionQuota | null>
|
|
75
85
|
/**
|
|
@@ -79,16 +89,19 @@ export interface AuthClient {
|
|
|
79
89
|
* request must not be made from here. Null on fetch failure / no credential,
|
|
80
90
|
* the same one-round-trip shape as {@link getSubscriptionQuota}.
|
|
81
91
|
*/
|
|
82
|
-
getAiTokenUsage(): Promise<
|
|
92
|
+
getAiTokenUsage(): Promise<AiUsage | null>
|
|
83
93
|
/**
|
|
84
94
|
* Open the subscription landing page (`gen.eda.cn/subscription` with the
|
|
85
95
|
* token). Host mode: ask the EDA host to open its NATIVE dialog through
|
|
86
96
|
* DialogService.OpenUrl (preferred size 1400×740). Standalone DSH: open
|
|
87
|
-
* the in-app iframe dialog at the same preferred size.
|
|
88
|
-
*
|
|
89
|
-
*
|
|
97
|
+
* the in-app iframe dialog at the same preferred size.
|
|
98
|
+
*
|
|
99
|
+
* Returns an explicit outcome instead of silently no-op'ing: without a
|
|
100
|
+
* credential the caller may open login; without a host dialog service it
|
|
101
|
+
* shows its own fallback copy; when a standalone dialog is already open
|
|
102
|
+
* it is left untouched. Transport/dialog failures reject.
|
|
90
103
|
*/
|
|
91
|
-
openSubscriptionDialog(): Promise<
|
|
104
|
+
openSubscriptionDialog(): Promise<SubscriptionDialogOutcome>
|
|
92
105
|
onAuthStateChanged(listener: (info: AuthTokenPayload | null) => void): () => void
|
|
93
106
|
}
|
|
94
107
|
/** Route window 'message' events here. Exposed for direct testing. */
|
|
@@ -122,11 +135,22 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
|
|
|
122
135
|
let hostMode = false
|
|
123
136
|
let hostSession: AuthTokenPayload | null = null
|
|
124
137
|
let hostSessionLoaded = false
|
|
138
|
+
/**
|
|
139
|
+
* Why the last host-session resolution failed, if it did. Transport errors
|
|
140
|
+
* must NOT masquerade as a healthy `signed-out`: the dialog opener surfaces
|
|
141
|
+
* them as a rejection so callers can show retry copy instead of "sign in".
|
|
142
|
+
*/
|
|
143
|
+
let hostResolveError: unknown
|
|
125
144
|
/**
|
|
126
145
|
* Subscription origin resolved by HQ Edge from `HQ_AI_ENV` and served on the
|
|
127
146
|
* node `/config` route. Null in standalone → lib's PROD fallback.
|
|
128
147
|
*/
|
|
129
148
|
let subscriptionOrigin: string | null = null
|
|
149
|
+
/**
|
|
150
|
+
* Origin of the resolved subscription-balances API (node `/config`). Null
|
|
151
|
+
* when no environment is configured → GEN/ERC quota calls are skipped.
|
|
152
|
+
*/
|
|
153
|
+
let subscriptionApiBaseUrl: string | null = null
|
|
130
154
|
|
|
131
155
|
const emit = (info: AuthTokenPayload | null): void => {
|
|
132
156
|
for (const listener of listeners) listener(info)
|
|
@@ -170,6 +194,7 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
|
|
|
170
194
|
*/
|
|
171
195
|
const resolveHost = async (): Promise<void> => {
|
|
172
196
|
hostSessionLoaded = true
|
|
197
|
+
hostResolveError = undefined
|
|
173
198
|
if (!hostMode) {
|
|
174
199
|
hostSession = null
|
|
175
200
|
return
|
|
@@ -177,9 +202,12 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
|
|
|
177
202
|
try {
|
|
178
203
|
const session = await transport.fetchSession()
|
|
179
204
|
hostSession = session.authenticated ? normalizeHostUserPayload(session.user) : null
|
|
180
|
-
} catch {
|
|
205
|
+
} catch (error) {
|
|
181
206
|
// Host unreachable: stay logged out rather than inventing a session.
|
|
207
|
+
// The error is retained for the dialog opener, which must not report it
|
|
208
|
+
// as a genuine signed-out state.
|
|
182
209
|
hostSession = null
|
|
210
|
+
hostResolveError = error
|
|
183
211
|
}
|
|
184
212
|
}
|
|
185
213
|
|
|
@@ -250,36 +278,46 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
|
|
|
250
278
|
? (hostSession?.id ?? null)
|
|
251
279
|
: (hostSession?.id ?? storage.get()?.id ?? null)
|
|
252
280
|
if (!token || !id) return null
|
|
253
|
-
return fetchSubscriptionQuota({
|
|
281
|
+
return fetchSubscriptionQuota({
|
|
282
|
+
userId: id,
|
|
283
|
+
token,
|
|
284
|
+
productCode,
|
|
285
|
+
...(subscriptionApiBaseUrl ? { baseUrl: subscriptionApiBaseUrl } : {}),
|
|
286
|
+
})
|
|
254
287
|
},
|
|
255
|
-
getAiTokenUsage: async (): Promise<
|
|
288
|
+
getAiTokenUsage: async (): Promise<AiUsage | null> => {
|
|
256
289
|
if (hostMode && !hostSessionLoaded) await resolveHost()
|
|
257
290
|
// Gate on a credential first: the node route resolves the token itself,
|
|
258
291
|
// so a request without one is a guaranteed-null round trip.
|
|
259
292
|
if (!(await auth.getAccessToken())) return null
|
|
260
293
|
return transport.fetchAiUsage()
|
|
261
294
|
},
|
|
262
|
-
openSubscriptionDialog: async (): Promise<
|
|
295
|
+
openSubscriptionDialog: async (): Promise<SubscriptionDialogOutcome> => {
|
|
263
296
|
if (hostMode && !hostSessionLoaded) await resolveHost()
|
|
264
297
|
const token = await auth.getAccessToken()
|
|
265
|
-
if (!token)
|
|
298
|
+
if (!token) {
|
|
299
|
+
// A failed host resolution is a transport failure, not "signed out".
|
|
300
|
+
if (hostMode && hostResolveError !== undefined) throw hostResolveError
|
|
301
|
+
return { status: 'signed-out' }
|
|
302
|
+
}
|
|
266
303
|
const url = buildSubscriptionUrl({
|
|
267
304
|
token,
|
|
268
305
|
...(subscriptionOrigin ? { origin: subscriptionOrigin } : {}),
|
|
269
306
|
})
|
|
270
307
|
if (hostMode) {
|
|
271
|
-
// The EDA host owns the UI — open its native dialog
|
|
272
|
-
//
|
|
273
|
-
if (!deps.openHostDialog) return
|
|
308
|
+
// The EDA host owns the UI — open its native dialog. No dialog service
|
|
309
|
+
// means the caller keeps its own affordance and shows fallback copy.
|
|
310
|
+
if (!deps.openHostDialog) return { status: 'host-unavailable' }
|
|
274
311
|
await deps.openHostDialog(url, {
|
|
275
312
|
title: 'Huaqiu EDA subscription',
|
|
276
313
|
size: { width: SUBSCRIPTION_PREFERRED_SIZE.width, height: SUBSCRIPTION_PREFERRED_SIZE.height },
|
|
277
314
|
key: 'hq-subscription-dialog',
|
|
278
315
|
})
|
|
279
|
-
return
|
|
316
|
+
return { status: 'opened' }
|
|
280
317
|
}
|
|
281
|
-
if (isSubscriptionDialogOpen()) return
|
|
318
|
+
if (isSubscriptionDialogOpen()) return { status: 'already-open' }
|
|
282
319
|
openSubscriptionDialog(url, { size: SUBSCRIPTION_PREFERRED_SIZE })
|
|
320
|
+
return { status: 'opened' }
|
|
283
321
|
},
|
|
284
322
|
onAuthStateChanged: (listener: (info: AuthTokenPayload | null) => void): (() => void) => {
|
|
285
323
|
listeners.add(listener)
|
|
@@ -346,9 +384,11 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
|
|
|
346
384
|
const runtime = await transport.fetchRuntimeConfig()
|
|
347
385
|
mode = runtime.hostMode
|
|
348
386
|
subscriptionOrigin = runtime.subscriptionOrigin
|
|
387
|
+
subscriptionApiBaseUrl = runtime.subscriptionApiBaseUrl
|
|
349
388
|
} catch {
|
|
350
389
|
mode = false
|
|
351
390
|
subscriptionOrigin = null
|
|
391
|
+
subscriptionApiBaseUrl = null
|
|
352
392
|
}
|
|
353
393
|
hostMode = mode
|
|
354
394
|
hostSessionLoaded = false
|
|
@@ -387,6 +427,7 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
|
|
|
387
427
|
hostSession = null
|
|
388
428
|
hostSessionLoaded = false
|
|
389
429
|
subscriptionOrigin = null
|
|
430
|
+
subscriptionApiBaseUrl = null
|
|
390
431
|
void trustedOrigin // referenced for clarity: the auth iframe URL comes from it
|
|
391
432
|
},
|
|
392
433
|
}
|
package/src/client/i18n.ts
CHANGED
|
@@ -45,14 +45,16 @@ const zh = {
|
|
|
45
45
|
'subscription.quotaHeader': '套餐与使用额度',
|
|
46
46
|
'subscription.upgrade': '订阅 / 升级套餐',
|
|
47
47
|
'subscription.online': '在线',
|
|
48
|
-
// AI
|
|
49
|
-
//
|
|
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': '暂无数据',
|
|
53
|
+
// Turn-error quota CTA (rendered inside the Chat turn-error card when the
|
|
54
|
+
// huaqiu gateway reports `insufficient_user_quota`).
|
|
55
|
+
'turnError.aiQuotaCta': '升级获取更多 AI 额度',
|
|
56
|
+
'turnError.aiQuotaSignIn': '登录后升级',
|
|
57
|
+
'turnError.aiQuotaOpenFailed': '无法打开订阅页面,请稍后重试。',
|
|
56
58
|
|
|
57
59
|
'card.title': '华秋 EDA AI(eda.cn)登录',
|
|
58
60
|
'card.desc': '工具「{tool}」需要登录华秋 EDA AI 账号才能继续。请在下方的登录框完成登录(或点击左侧「华秋EDA AI登录」按钮);登录完成后,回复助手「已登录,请重试」,助手会自动重新调用该工具。',
|
|
@@ -98,14 +100,16 @@ const en: Record<AuthCopyKey, string> = {
|
|
|
98
100
|
'subscription.quotaHeader': 'Plan & usage quota',
|
|
99
101
|
'subscription.upgrade': 'Subscribe / Upgrade plan',
|
|
100
102
|
'subscription.online': 'Online',
|
|
101
|
-
// AI
|
|
102
|
-
//
|
|
103
|
-
// "{available} / {total} pts" balance is shown as the hover title, because
|
|
104
|
-
// the bar itself only shows the ratio visually.
|
|
103
|
+
// AI usage — the third metric beside GEN and ERC. The headline is the
|
|
104
|
+
// upstream `quotaRemainPercent`, passed through unchanged (`99.68%`).
|
|
105
105
|
'subscription.ai': 'AI usage',
|
|
106
|
-
'subscription.aiUsageCount': '{available} / {total} pts',
|
|
107
106
|
'subscription.aiUsagePercent': '{percent}%',
|
|
108
107
|
'subscription.aiUsageUnknown': 'No data',
|
|
108
|
+
// Turn-error quota CTA (rendered inside the Chat turn-error card when the
|
|
109
|
+
// huaqiu gateway reports `insufficient_user_quota`).
|
|
110
|
+
'turnError.aiQuotaCta': 'Upgrade for more AI tokens',
|
|
111
|
+
'turnError.aiQuotaSignIn': 'Sign in to upgrade',
|
|
112
|
+
'turnError.aiQuotaOpenFailed': 'Could not open the subscription page. Please try again later.',
|
|
109
113
|
|
|
110
114
|
'card.title': 'Huaqiu EDA AI (eda.cn) login',
|
|
111
115
|
// The reply phrase used to be hardcoded to the Chinese "已登录,请重试" even
|
package/src/client/index.tsx
CHANGED
|
@@ -21,6 +21,7 @@ import { createAuthClient, type AuthClient } from './client.js'
|
|
|
21
21
|
import { disposeAuth, registerAuth, registerAuthSync, registerHqEdgeGetter } from './auth-state.js'
|
|
22
22
|
import { HuaqiuToolView } from './ui/needs-auth-toolview.jsx'
|
|
23
23
|
import { HuaqiuAuthSidebarAction } from './ui/sidebar-action.jsx'
|
|
24
|
+
import { HuaqiuTurnErrorSubscribeAction } from './ui/turn-error-cta.jsx'
|
|
24
25
|
import { disposeUiEnv } from './ui-env.js'
|
|
25
26
|
|
|
26
27
|
/**
|
|
@@ -75,13 +76,17 @@ export function apply(ctx: ClientContext): () => void {
|
|
|
75
76
|
documentLike: document,
|
|
76
77
|
// Host mode subscription dialog: the EDA host owns the UI. Open its
|
|
77
78
|
// native window through the hqEdge service's DialogService.OpenUrl
|
|
78
|
-
// bridge
|
|
79
|
-
// subscribe button stays usable and reports the limitation.
|
|
79
|
+
// bridge, which acknowledges once the dialog is launched.
|
|
80
80
|
openHostDialog: async (url, options) => {
|
|
81
81
|
const hqEdge = ctx.get?.<{
|
|
82
82
|
openUrl?(url: string, opts?: Record<string, unknown>): Promise<unknown>
|
|
83
83
|
} | undefined>('hqEdge')
|
|
84
|
-
if (!hqEdge || typeof hqEdge.openUrl !== 'function')
|
|
84
|
+
if (!hqEdge || typeof hqEdge.openUrl !== 'function') {
|
|
85
|
+
// Without the EDA bridge no native dialog can ever appear. Reject so
|
|
86
|
+
// callers surface their fallback copy instead of reporting a launch
|
|
87
|
+
// that never happened.
|
|
88
|
+
throw new Error('hqEdge.openUrl is unavailable')
|
|
89
|
+
}
|
|
85
90
|
await hqEdge.openUrl(url, {
|
|
86
91
|
...(options.title ? { title: options.title } : {}),
|
|
87
92
|
...(options.size ? { size: options.size } : {}),
|
|
@@ -170,6 +175,13 @@ export function apply(ctx: ClientContext): () => void {
|
|
|
170
175
|
disposers.push(slots.inject('tool.call.toolview', () => slots.register({ name: 'tool.call.toolview', key: toolName }, HuaqiuToolView) as () => void))
|
|
171
176
|
}
|
|
172
177
|
disposers.push(slots.inject('sidebar.footer.action', () => slots.register({ name: 'sidebar.footer.action', id: 'huaqiu-auth' }, HuaqiuAuthSidebarAction) as () => void))
|
|
178
|
+
// The turn-error action slot only exists on harness versions that ship
|
|
179
|
+
// the seam; `inject` waits for its declaration, so an older harness
|
|
180
|
+
// simply never calls this and the shipped error card stays unchanged.
|
|
181
|
+
disposers.push(slots.inject('conversation.chat.turn-error.action', () => slots.register({
|
|
182
|
+
name: 'conversation.chat.turn-error.action',
|
|
183
|
+
id: 'huaqiu-turn-error-cta',
|
|
184
|
+
}, HuaqiuTurnErrorSubscribeAction) as () => void))
|
|
173
185
|
}
|
|
174
186
|
})
|
|
175
187
|
|