@lks347/dsh-oauth 0.0.0-stage → 1.0.1

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.
Files changed (65) hide show
  1. package/README.en.md +155 -0
  2. package/README.md +100 -2
  3. package/app.js +1005 -0
  4. package/auth.html +80 -0
  5. package/client.js +31 -0
  6. package/cordis.patch.yml +4 -0
  7. package/docs/CONNECTIONS.md +77 -0
  8. package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
  9. package/docs/RELEASE-1.0.1.md +38 -0
  10. package/docs/VALIDATION.md +59 -0
  11. package/docs/evidence/live-1.0.1.json +135 -0
  12. package/index.html +43 -0
  13. package/package.json +64 -4
  14. package/providers.js +73 -0
  15. package/scripts/check-upstreams.mjs +27 -0
  16. package/scripts/link-peers.js +38 -0
  17. package/scripts/verify-browser.mjs +297 -0
  18. package/scripts/verify-host.mjs +484 -0
  19. package/scripts/verify-live.mjs +268 -0
  20. package/scripts/verify-package.mjs +168 -0
  21. package/scripts/verify-persistence.mjs +307 -0
  22. package/scripts/verify-subscriptions-ui.mjs +304 -0
  23. package/src/account.js +85 -0
  24. package/src/account.test.js +52 -0
  25. package/src/authorization.js +199 -0
  26. package/src/authorization.test.js +332 -0
  27. package/src/catalog.js +177 -0
  28. package/src/catalog.test.js +146 -0
  29. package/src/chat-recovery.js +110 -0
  30. package/src/chat-recovery.test.js +261 -0
  31. package/src/connection-runtime.js +126 -0
  32. package/src/connection-runtime.test.js +244 -0
  33. package/src/connections.js +70 -0
  34. package/src/grants.js +103 -0
  35. package/src/grants.test.js +327 -0
  36. package/src/index.js +704 -0
  37. package/src/local-imports.js +145 -0
  38. package/src/local-imports.test.js +168 -0
  39. package/src/media.js +149 -0
  40. package/src/models.js +546 -0
  41. package/src/models.test.js +415 -0
  42. package/src/profile-store.js +51 -0
  43. package/src/pulls.js +100 -0
  44. package/src/pulls.test.js +156 -0
  45. package/src/qwen.js +141 -0
  46. package/src/qwen.test.js +35 -0
  47. package/src/request-errors.js +50 -0
  48. package/src/request-errors.test.js +131 -0
  49. package/src/routes.js +47 -0
  50. package/src/routes.test.js +136 -0
  51. package/src/subscription-models.test.js +139 -0
  52. package/src/usage/aggregators.js +292 -0
  53. package/src/usage/aggregators.test.js +316 -0
  54. package/src/usage/core.js +68 -0
  55. package/src/usage/index.js +93 -0
  56. package/src/usage/official.js +339 -0
  57. package/src/usage/official.test.js +273 -0
  58. package/src/usage/service.test.js +89 -0
  59. package/src/xai-browser.js +272 -0
  60. package/src/xai-browser.test.js +256 -0
  61. package/src/xai-login.js +121 -0
  62. package/src/xai-login.test.js +259 -0
  63. package/styles.css +364 -0
  64. package/theme.js +118 -0
  65. package/upstreams.json +10 -0
@@ -0,0 +1,70 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { credentialKey } from '@deepseek-ai/dsh-credentials';
3
+
4
+ export const connectionKey = id => credentialKey('dsh-oauth-connections', id);
5
+ export const nativeKey = id => credentialKey(id === 'qwen' ? 'dsh-oauth' : 'llm-pi-ai', id);
6
+ export const connectionRef = id => `DSH_OAUTH_${id.toUpperCase().replaceAll('-', '_')}_KEY`;
7
+ const metadataKeys = ['label', 'region', 'organizationId', 'projectId', 'workspaceId', 'baseURL'];
8
+ export function connectionMetadata(value = {}) {
9
+ const out = {};
10
+ for (const key of metadataKeys) {
11
+ if (value[key] === undefined) continue;
12
+ if (typeof value[key] !== 'string' || value[key].length > 200 || /[\x00-\x1f\x7f]/.test(value[key])) throw new Error(`Invalid connection field: ${key}`);
13
+ if (key === 'region' && !['global', 'cn'].includes(value[key])) throw new Error('Invalid region.');
14
+ if (key === 'baseURL') {
15
+ const url = new URL(value[key]);
16
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) throw new Error('A credential-free HTTPS base URL is required.');
17
+ out[key] = url.toString().replace(/\/+$/, '');
18
+ } else out[key] = value[key].trim();
19
+ }
20
+ return out;
21
+ }
22
+ export function validSecret(value) {
23
+ if (typeof value !== 'string' || !value.trim() || value.length > 32768 || /[\r\n]/.test(value)) throw new Error('A valid credential is required.');
24
+ return value.trim();
25
+ }
26
+ export function accountFingerprint(connection, raw) {
27
+ // Cache entries are bound to credentials and scope. This digest is never a token preview.
28
+ return createHash('sha256').update(JSON.stringify([connection?.revision, raw?.accountId, raw?.account_id, raw?.access, connection?.metadata,
29
+ raw?.region, raw?.organizationId, raw?.workspaceId, raw?.projectId, raw?.metadata, raw?.apiBase, raw?.resourceUrl])).digest('hex');
30
+ }
31
+ export function createConnections(credentials) {
32
+ const read = async id => {
33
+ const record = await credentials.modifyRecord(connectionKey(id), () => undefined);
34
+ return record?.kind === 'grant' ? record.payload : undefined;
35
+ };
36
+ const save = async (id, payload) => credentials.modifyRecord(connectionKey(id), () => ({ kind: 'grant', payload }));
37
+ return {
38
+ read,
39
+ raw: async id => (await credentials.readRecord(nativeKey(id)))?.payload,
40
+ async connect(id, body) {
41
+ const access = validSecret(body.access);
42
+ const next = { mode: 'key', access, metadata: connectionMetadata(body), revision: randomUUID(), ...(body.billingAccess ? { billingAccess: validSecret(body.billingAccess) } : {}) };
43
+ const before = await read(id);
44
+ await save(id, next);
45
+ try { await credentials.set(connectionRef(id), access); }
46
+ catch (error) { if (before) await save(id, before); else await credentials.deleteRecord(connectionKey(id)); throw error; }
47
+ return next;
48
+ },
49
+ async configure(id, body) {
50
+ let saved;
51
+ await credentials.modifyRecord(connectionKey(id), current => {
52
+ const before = current?.kind === 'grant' ? current.payload : { mode: 'oauth' };
53
+ saved = { ...before, metadata: { ...before.metadata, ...connectionMetadata(body) }, revision: randomUUID() };
54
+ if (id === 'zai' && !!saved.metadata.organizationId !== !!saved.metadata.projectId) throw new Error('Z.AI organization and project IDs must be configured together.');
55
+ if (body.billingAccess === '') delete saved.billingAccess;
56
+ else if (body.billingAccess !== undefined) saved.billingAccess = validSecret(body.billingAccess);
57
+ return { kind: 'grant', payload: saved };
58
+ });
59
+ return saved;
60
+ },
61
+ async saveLocal(id, source, sourceLabel) {
62
+ const next = { mode: 'local', localSource: source, sourceLabel, metadata: {}, revision: randomUUID() };
63
+ await save(id, next); return next;
64
+ },
65
+ async disconnect(id) {
66
+ await credentials.deleteRecord(connectionKey(id));
67
+ if (typeof credentials.unset === 'function') await credentials.unset(connectionRef(id));
68
+ },
69
+ };
70
+ }
package/src/grants.js ADDED
@@ -0,0 +1,103 @@
1
+ /** Resolve request credentials through pi-ai's public refresh API and DSH's atomic record store. */
2
+ import { builtinModels } from "@earendil-works/pi-ai/providers/all";
3
+ import { credentialKey } from "@deepseek-ai/dsh-credentials";
4
+ import { refreshQwen } from "./qwen.js";
5
+
6
+ export const QWEN_KEY_NAME = "QWEN_OAUTH_ACCESS";
7
+ const recordKey = (id) => credentialKey(id === "qwen" ? "dsh-oauth" : "llm-pi-ai", id);
8
+
9
+ /** Only grants are accepted; ambient API keys never stand in for a signed-in account. */
10
+ export function createGrantResolver(credentials, modelsFactory = builtinModels) {
11
+ // Request auth may differ from the stored access token (for example Copilot).
12
+ // Keep the rejected grant's storage snapshot private, never in API responses.
13
+ const observed = new WeakMap();
14
+ const remember = (id, grant, stored) => {
15
+ observed.set(grant, { id, access: stored.access, refresh: stored.refresh, expires: stored.expires, payload: { ...stored } });
16
+ return grant;
17
+ };
18
+ const unchanged = (current, rejected) => current && current.access === rejected.access &&
19
+ current.refresh === rejected.refresh && current.expires === rejected.expires;
20
+ const store = {
21
+ async read(id) {
22
+ const record = await credentials.readRecord(recordKey(id));
23
+ return record?.kind === "grant" ? record.payload : undefined;
24
+ },
25
+ async list() { return []; },
26
+ async modify(id, mutate) {
27
+ const next = await credentials.modifyRecord(recordKey(id), async (current) => {
28
+ const changed = await mutate(current?.kind === "grant" ? current.payload : undefined);
29
+ return changed === undefined ? undefined : { kind: "grant", payload: JSON.parse(JSON.stringify(changed)) };
30
+ });
31
+ return next?.kind === "grant" ? next.payload : undefined;
32
+ },
33
+ async delete(id) { await credentials.deleteRecord(recordKey(id)); },
34
+ };
35
+ const models = modelsFactory({
36
+ credentials: store,
37
+ authContext: { async env() { return undefined; }, async fileExists() { return false; } },
38
+ });
39
+ const resolve = async (id, { rejectedGrant } = {}) => {
40
+ const rejected = rejectedGrant === undefined ? undefined : observed.get(rejectedGrant);
41
+ if (rejectedGrant !== undefined && rejected?.id !== id) {
42
+ throw new Error("无法核对被拒绝的 OAuth 请求凭据,请重新读取连接状态");
43
+ }
44
+ let payload = await store.read(id);
45
+ if (!payload || typeof payload.access !== "string" || payload.access.length === 0) {
46
+ throw new Error("先完成这个提供商的 OAuth 登录,再拉取模型");
47
+ }
48
+ if (id === "qwen") {
49
+ if (rejected || typeof payload.expires !== "number" || payload.expires <= Date.now() + 300000) {
50
+ payload = await store.modify(id, async (current) => {
51
+ if (!current) return undefined;
52
+ if (rejected ? !unchanged(current, rejected) : typeof current.expires === "number" && current.expires > Date.now() + 300000) return undefined;
53
+ return refreshQwen(current);
54
+ });
55
+ }
56
+ if (!payload) throw new Error("通义千问登录已断开,请重新登录");
57
+ // Qwen's custom OpenAI route consumes a credential reference, not pi-ai's store.
58
+ await credentials.set(QWEN_KEY_NAME, payload.access);
59
+ return remember(id, payload, payload);
60
+ }
61
+ if (rejected) {
62
+ // The upstream can revoke an access token before its advertised expiry.
63
+ // Exchange only the credential the failed request actually used; another
64
+ // process may already have refreshed it while this request was in flight.
65
+ const oauth = models.getProvider?.(id)?.auth?.oauth;
66
+ if (typeof oauth?.refresh !== "function") throw new Error(`${id} 的适配器没有提供 OAuth 续期接口;已保留本地授权`);
67
+ payload = await store.modify(id, async (current) => {
68
+ if (!unchanged(current, rejected)) return undefined;
69
+ if (current.type !== "oauth" || typeof current.refresh !== "string" || !current.refresh) {
70
+ throw new Error(`${id} 的已保存授权缺少刷新令牌,需要重新登录`);
71
+ }
72
+ try {
73
+ // Once a rotating refresh starts, persist it even if the panel leaves.
74
+ return await oauth.refresh(current, AbortSignal.timeout(15000));
75
+ } catch (cause) {
76
+ throw new Error(`${id} 的 OAuth 自动续期失败;本地授权已保留,请稍后重试。若上游已撤销授权,需要重新登录`, { cause });
77
+ }
78
+ });
79
+ if (!payload) throw new Error("OAuth 登录已断开,请重新登录");
80
+ }
81
+ const resolved = await models.getAuth(id, { signal: AbortSignal.timeout(20000) });
82
+ if (typeof resolved?.auth?.apiKey !== "string" || resolved.auth.apiKey.length === 0) {
83
+ throw new Error(`${id} 的 OAuth 请求凭据不可用,请重新登录`);
84
+ }
85
+ payload = await store.read(id);
86
+ if (!payload) throw new Error("OAuth 登录已断开,请重新登录");
87
+ // Another process may have committed a newer grant after getAuth read it.
88
+ // Derive request auth from the same payload we remember for recovery.
89
+ const oauth = models.getProvider?.(id)?.auth?.oauth;
90
+ const auth = typeof oauth?.toAuth === "function" ? await oauth.toAuth(payload) : resolved.auth;
91
+ if (typeof auth?.apiKey !== "string" || !auth.apiKey) {
92
+ throw new Error(`${id} 的 OAuth 请求凭据不可用,请重新登录`);
93
+ }
94
+ return remember(id, {
95
+ ...payload,
96
+ access: auth.apiKey,
97
+ ...(auth.headers ? { requestHeaders: auth.headers } : {}),
98
+ ...(auth.baseUrl ? { apiBase: auth.baseUrl } : {}),
99
+ }, payload);
100
+ };
101
+ resolve.rawGrant = grant => observed.get(grant)?.payload;
102
+ return resolve;
103
+ }
@@ -0,0 +1,327 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createGrantResolver, QWEN_KEY_NAME } from "./grants.js";
4
+
5
+ const clone = (value) => value === undefined ? undefined : structuredClone(value);
6
+
7
+ /** Simulate DSH modifyRecord's exclusive callback and undefined-means-unchanged contract. */
8
+ function memoryCredentials(initial = {}) {
9
+ const records = new Map(Object.entries(initial).map(([key, value]) => [key, clone(value)]));
10
+ const references = new Map();
11
+ const calls = [];
12
+ let pending = Promise.resolve();
13
+ return {
14
+ records, references, calls,
15
+ async readRecord(key) { return clone(records.get(key)); },
16
+ async modifyRecord(key, mutate) {
17
+ const operation = pending.then(async () => {
18
+ calls.push(key);
19
+ const current = clone(records.get(key));
20
+ const changed = await mutate(current);
21
+ if (changed !== undefined) records.set(key, clone(changed));
22
+ return clone(records.get(key));
23
+ });
24
+ pending = operation.catch(() => {});
25
+ return operation;
26
+ },
27
+ async deleteRecord(key) { records.delete(key); },
28
+ async set(name, value) { references.set(name, value); },
29
+ };
30
+ }
31
+
32
+ test("pi-ai refresh runs inside DSH's atomic record callback and a competing no-op preserves the refreshed grant", async () => {
33
+ const key = "llm-pi-ai/openai-codex";
34
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: { type: "oauth", access: "old", refresh: "refresh-old" } } });
35
+ let release;
36
+ const network = new Promise((resolve) => { release = resolve; });
37
+ let entered;
38
+ const refreshing = new Promise((resolve) => { entered = resolve; });
39
+ let exchanges = 0;
40
+ const resolveGrant = createGrantResolver(credentials, ({ credentials: store }) => ({
41
+ async getAuth(id, options) {
42
+ assert.ok(options.signal instanceof AbortSignal);
43
+ const grant = await store.modify(id, async (current) => {
44
+ if (current.access !== "old") return undefined;
45
+ exchanges += 1;
46
+ entered();
47
+ await network;
48
+ return { ...current, access: "fresh", refresh: "refresh-new", optional: undefined };
49
+ });
50
+ return { auth: { apiKey: grant.access, headers: { "upstream-header": "identity" }, baseUrl: "https://upstream.example.test/v1" } };
51
+ },
52
+ }));
53
+ const first = resolveGrant("openai-codex");
54
+ await refreshing;
55
+ const second = resolveGrant("openai-codex");
56
+ release();
57
+ const results = await Promise.all([first, second]);
58
+ assert.equal(exchanges, 1);
59
+ assert.deepEqual(credentials.calls, [key, key]);
60
+ assert.deepEqual(credentials.records.get(key), { kind: "grant", payload: { type: "oauth", access: "fresh", refresh: "refresh-new" } });
61
+ for (const grant of results) {
62
+ assert.equal(grant.access, "fresh");
63
+ assert.equal(grant.refresh, "refresh-new");
64
+ assert.deepEqual(grant.requestHeaders, { "upstream-header": "identity" });
65
+ assert.equal(grant.apiBase, "https://upstream.example.test/v1");
66
+ }
67
+ });
68
+
69
+ test("account requests reject absent or API-key records without falling back to ambient credentials", async () => {
70
+ for (const record of [undefined, { kind: "api-key", key: "ambient-key" }]) {
71
+ const credentials = memoryCredentials(record ? { "llm-pi-ai/anthropic": record } : {});
72
+ let authCalls = 0;
73
+ const resolveGrant = createGrantResolver(credentials, (options) => {
74
+ assert.equal(typeof options.authContext.env, "function");
75
+ return { async getAuth() { authCalls += 1; return { auth: { apiKey: "ambient-key" } }; } };
76
+ });
77
+ await assert.rejects(resolveGrant("anthropic"), /先完成.*OAuth 登录/);
78
+ assert.equal(authCalls, 0);
79
+ }
80
+ const credentials = memoryCredentials({ "llm-pi-ai/anthropic": { kind: "grant", payload: { access: "signed-in" } } });
81
+ const resolveGrant = createGrantResolver(credentials, ({ authContext }) => ({
82
+ async getAuth() {
83
+ assert.equal(await authContext.env("ANTHROPIC_API_KEY"), undefined);
84
+ assert.equal(await authContext.fileExists("/ambient/credentials"), false);
85
+ return { auth: { apiKey: "signed-in" } };
86
+ },
87
+ }));
88
+ assert.equal((await resolveGrant("anthropic")).access, "signed-in");
89
+ });
90
+
91
+ test("a disconnect during upstream authentication prevents using the resolved request credential", async () => {
92
+ const key = "llm-pi-ai/github-copilot";
93
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: { access: "old" } } });
94
+ const resolveGrant = createGrantResolver(credentials, () => ({
95
+ async getAuth() {
96
+ await credentials.deleteRecord(key);
97
+ return { auth: { apiKey: "fresh" } };
98
+ },
99
+ }));
100
+ await assert.rejects(resolveGrant("github-copilot"), /登录已断开/);
101
+ });
102
+
103
+ test("upstream authentication without a usable request credential fails before returning a grant", async () => {
104
+ const credentials = memoryCredentials({ "llm-pi-ai/xai": { kind: "grant", payload: { access: "old" } } });
105
+ const resolveGrant = createGrantResolver(credentials, () => ({ async getAuth() { return { auth: { apiKey: "" } }; } }));
106
+ await assert.rejects(resolveGrant("xai"), /请求凭据不可用/);
107
+ });
108
+
109
+ test("Qwen refresh persists its new access token without losing a non-rotated refresh token or resource", async (t) => {
110
+ const key = "dsh-oauth/qwen";
111
+ const old = { access: "expired", refresh: "refresh-old", expires: Date.now() - 1000, resourceUrl: "https://portal.qwen.ai/v1" };
112
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: old } });
113
+ t.mock.method(globalThis, "fetch", async (url, init) => {
114
+ assert.equal(url, "https://chat.qwen.ai/api/v1/oauth2/token");
115
+ assert.equal(init.body.get("grant_type"), "refresh_token");
116
+ assert.equal(init.body.get("refresh_token"), "refresh-old");
117
+ return new Response(JSON.stringify({ access_token: "fresh", expires_in: 7200 }), { status: 200 });
118
+ });
119
+ const before = Date.now();
120
+ const resolveGrant = createGrantResolver(credentials, () => ({ async getAuth() { assert.fail("Qwen owns its refresh protocol"); } }));
121
+ const grant = await resolveGrant("qwen");
122
+ assert.equal(grant.access, "fresh");
123
+ assert.equal(grant.refresh, "refresh-old");
124
+ assert.equal(grant.resourceUrl, old.resourceUrl);
125
+ assert.ok(grant.expires >= before + 7200000 && grant.expires <= Date.now() + 7200000);
126
+ assert.deepEqual(credentials.records.get(key), { kind: "grant", payload: grant });
127
+ assert.equal(credentials.references.get(QWEN_KEY_NAME), "fresh");
128
+ });
129
+
130
+ test("Qwen rotating refresh tokens and resources replace the corresponding stored values", async (t) => {
131
+ const key = "dsh-oauth/qwen";
132
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: {
133
+ access: "expired", refresh: "refresh-old", expires: 1, resourceUrl: "https://old.example.test/v1",
134
+ } } });
135
+ t.mock.method(globalThis, "fetch", async () => new Response(JSON.stringify({
136
+ access_token: "rotated", refresh_token: "refresh-new", resource_url: "https://portal.qwen.ai", expires_in: 3600,
137
+ }), { status: 200 }));
138
+ const grant = await createGrantResolver(credentials, () => ({}))("qwen");
139
+ assert.equal(grant.refresh, "refresh-new");
140
+ assert.equal(grant.resourceUrl, "https://portal.qwen.ai/v1");
141
+ assert.deepEqual(credentials.records.get(key).payload, grant);
142
+ assert.equal(credentials.references.get(QWEN_KEY_NAME), "rotated");
143
+ });
144
+
145
+ test("Qwen observes a concurrent refresh inside the record lock without deleting it or exchanging twice", async (t) => {
146
+ const key = "dsh-oauth/qwen";
147
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: { access: "old", refresh: "refresh-old", expires: 1 } } });
148
+ const modifyRecord = credentials.modifyRecord;
149
+ const refreshed = { access: "concurrent-fresh", refresh: "concurrent-refresh", expires: Date.now() + 3600000, resourceUrl: "https://portal.qwen.ai/v1" };
150
+ credentials.modifyRecord = async (recordKey, mutate) => {
151
+ credentials.records.set(recordKey, { kind: "grant", payload: refreshed });
152
+ return modifyRecord(recordKey, mutate);
153
+ };
154
+ t.mock.method(globalThis, "fetch", async () => { assert.fail("concurrent refresh already produced a fresh grant"); });
155
+ const grant = await createGrantResolver(credentials, () => ({}))("qwen");
156
+ assert.deepEqual(grant, refreshed);
157
+ assert.deepEqual(credentials.records.get(key), { kind: "grant", payload: refreshed });
158
+ assert.equal(credentials.references.get(QWEN_KEY_NAME), "concurrent-fresh");
159
+ });
160
+
161
+ test("Qwen disconnect inside the record lock rejects without recreating the grant or credential reference", async (t) => {
162
+ const key = "dsh-oauth/qwen";
163
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: { access: "old", refresh: "refresh-old", expires: 1 } } });
164
+ const modifyRecord = credentials.modifyRecord;
165
+ credentials.modifyRecord = async (recordKey, mutate) => {
166
+ credentials.records.delete(recordKey);
167
+ return modifyRecord(recordKey, mutate);
168
+ };
169
+ t.mock.method(globalThis, "fetch", async () => { assert.fail("a disconnected grant must not refresh"); });
170
+ await assert.rejects(createGrantResolver(credentials, () => ({}))("qwen"), /登录已断开/);
171
+ assert.equal(credentials.records.has(key), false);
172
+ assert.equal(credentials.references.has(QWEN_KEY_NAME), false);
173
+ });
174
+
175
+ function refreshableModels(refresh) {
176
+ return ({ credentials: store }) => ({
177
+ getProvider() { return { auth: { oauth: { refresh } } }; },
178
+ async getAuth(id) { return { auth: { apiKey: (await store.read(id))?.access } }; },
179
+ });
180
+ }
181
+
182
+ const futureGrant = () => ({ type: "oauth", access: "old-access", refresh: "old-refresh", expires: Date.now() + 3600000 });
183
+
184
+ test("an explicitly rejected access token is refreshed even before its advertised expiry", async () => {
185
+ const key = "llm-pi-ai/xai";
186
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: futureGrant() } });
187
+ let exchanges = 0;
188
+ const resolveGrant = createGrantResolver(credentials, refreshableModels(async (current, signal) => {
189
+ exchanges += 1;
190
+ assert.ok(signal instanceof AbortSignal);
191
+ assert.equal(current.refresh, "old-refresh");
192
+ return { ...current, access: "new-access", refresh: "rotated-refresh" };
193
+ }));
194
+ const rejectedGrant = await resolveGrant("xai");
195
+ const renewed = await resolveGrant("xai", { rejectedGrant });
196
+ assert.equal(exchanges, 1);
197
+ assert.equal(renewed.access, "new-access");
198
+ assert.equal(credentials.records.get(key).payload.refresh, "rotated-refresh");
199
+ });
200
+
201
+ test("concurrent rejected requests refresh once and reuse the persisted winner", async () => {
202
+ const key = "llm-pi-ai/xai";
203
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: futureGrant() } });
204
+ let exchanges = 0;
205
+ const resolveGrant = createGrantResolver(credentials, refreshableModels(async (current) => {
206
+ exchanges += 1;
207
+ await new Promise((resolve) => setTimeout(resolve, 5));
208
+ return { ...current, access: "new-access", refresh: "rotated-refresh" };
209
+ }));
210
+ const first = await resolveGrant("xai");
211
+ const second = await resolveGrant("xai");
212
+ const renewed = await Promise.all([resolveGrant("xai", { rejectedGrant: first }), resolveGrant("xai", { rejectedGrant: second })]);
213
+ assert.equal(exchanges, 1);
214
+ assert.deepEqual(renewed.map((grant) => grant.access), ["new-access", "new-access"]);
215
+ assert.equal((await resolveGrant("xai", { rejectedGrant: first })).access, "new-access");
216
+ assert.equal(exchanges, 1, "a late failure of the old request cannot rotate the new token again");
217
+ });
218
+
219
+ test("failed forced refresh preserves the entire stored grant and reports a safe retryable error", async () => {
220
+ const key = "llm-pi-ai/xai";
221
+ const original = futureGrant();
222
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: original } });
223
+ const cause = new TypeError("mock network failure with private upstream detail");
224
+ const resolveGrant = createGrantResolver(credentials, refreshableModels(async () => { throw cause; }));
225
+ const rejectedGrant = await resolveGrant("xai");
226
+ await assert.rejects(resolveGrant("xai", { rejectedGrant }), (error) => {
227
+ assert.match(error.message, /本地授权已保留/);
228
+ assert.ok(!error.message.includes("private upstream detail"));
229
+ assert.equal(error.cause, cause);
230
+ return true;
231
+ });
232
+ assert.deepEqual(credentials.records.get(key), { kind: "grant", payload: original });
233
+ });
234
+
235
+ test("forced refresh cannot recreate a disconnected grant or act on an unknown request snapshot", async () => {
236
+ const key = "llm-pi-ai/xai";
237
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: futureGrant() } });
238
+ let exchanges = 0;
239
+ const resolveGrant = createGrantResolver(credentials, refreshableModels(async () => { exchanges += 1; }));
240
+ const rejectedGrant = await resolveGrant("xai");
241
+ await assert.rejects(resolveGrant("xai", { rejectedGrant: { ...rejectedGrant } }), /无法核对/);
242
+ await assert.rejects(resolveGrant("anthropic", { rejectedGrant }), /无法核对/);
243
+ credentials.records.delete(key);
244
+ await assert.rejects(resolveGrant("xai", { rejectedGrant }), /先完成/);
245
+ assert.equal(exchanges, 0);
246
+ assert.equal(credentials.records.has(key), false);
247
+ });
248
+
249
+ test("forced refresh compares the stored credential rather than derived request auth", async () => {
250
+ const key = "llm-pi-ai/github-copilot";
251
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: futureGrant() } });
252
+ let exchanges = 0;
253
+ const resolveGrant = createGrantResolver(credentials, ({ credentials: store }) => ({
254
+ getProvider() { return { auth: { oauth: { async refresh(current) { exchanges += 1; return { ...current, access: "refreshed-upstream-access" }; } } } }; },
255
+ async getAuth(id) {
256
+ const current = await store.read(id);
257
+ return { auth: { apiKey: `derived-${current.access}` } };
258
+ },
259
+ }));
260
+ const rejectedGrant = await resolveGrant("github-copilot");
261
+ assert.equal(rejectedGrant.access, "derived-old-access");
262
+ const renewed = await resolveGrant("github-copilot", { rejectedGrant });
263
+ assert.equal(exchanges, 1);
264
+ assert.equal(renewed.access, "derived-refreshed-upstream-access");
265
+ });
266
+
267
+ test("a concurrent grant commit before request-auth derivation uses the matching new storage snapshot", async () => {
268
+ const key = "llm-pi-ai/xai";
269
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: futureGrant() } });
270
+ let exchanges = 0;
271
+ let first = true;
272
+ const resolveGrant = createGrantResolver(credentials, () => ({
273
+ getProvider() { return { auth: { oauth: {
274
+ async toAuth(current) { return { apiKey: current.access }; },
275
+ async refresh(current) { exchanges += 1; return { ...current, access: "recovered-access" }; },
276
+ } } }; },
277
+ async getAuth() {
278
+ if (first) {
279
+ first = false;
280
+ credentials.records.set(key, { kind: "grant", payload: { ...futureGrant(), access: "concurrent-access", refresh: "concurrent-refresh" } });
281
+ return { auth: { apiKey: "old-access" } };
282
+ }
283
+ return { auth: { apiKey: credentials.records.get(key).payload.access } };
284
+ },
285
+ }));
286
+ const observed = await resolveGrant("xai");
287
+ assert.equal(observed.access, "concurrent-access");
288
+ assert.equal(observed.refresh, "concurrent-refresh");
289
+ assert.equal((await resolveGrant("xai", { rejectedGrant: observed })).access, "recovered-access");
290
+ assert.equal(exchanges, 1);
291
+ });
292
+
293
+ test("a Qwen catalog rejection renews a future-valid grant and updates its request reference", async (t) => {
294
+ const key = "dsh-oauth/qwen";
295
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: { ...futureGrant(), resourceUrl: "https://portal.qwen.ai/v1" } } });
296
+ let exchanges = 0;
297
+ t.mock.method(globalThis, "fetch", async (url, options) => {
298
+ exchanges += 1;
299
+ assert.equal(url, "https://chat.qwen.ai/api/v1/oauth2/token");
300
+ assert.equal(options.body.get("refresh_token"), "old-refresh");
301
+ return new Response(JSON.stringify({ access_token: "qwen-renewed", expires_in: 3600 }));
302
+ });
303
+ const resolveGrant = createGrantResolver(credentials, () => ({}));
304
+ const observed = await resolveGrant("qwen");
305
+ assert.equal(exchanges, 0);
306
+ const renewed = await resolveGrant("qwen", { rejectedGrant: observed });
307
+ assert.equal(exchanges, 1);
308
+ assert.equal(renewed.access, "qwen-renewed");
309
+ assert.equal(renewed.refresh, "old-refresh");
310
+ assert.equal(credentials.references.get(QWEN_KEY_NAME), "qwen-renewed");
311
+ });
312
+
313
+ test("a disconnect while waiting for the forced-refresh lock never restores an old account", async () => {
314
+ const key = "llm-pi-ai/xai";
315
+ const credentials = memoryCredentials({ [key]: { kind: "grant", payload: futureGrant() } });
316
+ let exchanges = 0;
317
+ const resolveGrant = createGrantResolver(credentials, refreshableModels(async () => { exchanges += 1; }));
318
+ const observed = await resolveGrant("xai");
319
+ const modify = credentials.modifyRecord;
320
+ credentials.modifyRecord = async (recordKey, mutate) => {
321
+ credentials.records.delete(recordKey);
322
+ return modify(recordKey, mutate);
323
+ };
324
+ await assert.rejects(resolveGrant("xai", { rejectedGrant: observed }), /登录已断开/);
325
+ assert.equal(exchanges, 0);
326
+ assert.equal(credentials.records.has(key), false);
327
+ });