@lks347/dsh-oauth 0.0.0-stage → 1.0.2

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 (67) hide show
  1. package/README.en.md +155 -0
  2. package/README.md +101 -2
  3. package/app.js +1045 -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 +48 -0
  10. package/docs/RELEASE-1.0.2.md +8 -0
  11. package/docs/VALIDATION.md +59 -0
  12. package/docs/evidence/live-1.0.1.json +135 -0
  13. package/docs/evidence/release-1.0.1.json +38 -0
  14. package/index.html +43 -0
  15. package/package.json +64 -4
  16. package/providers.js +73 -0
  17. package/scripts/check-upstreams.mjs +27 -0
  18. package/scripts/link-peers.js +38 -0
  19. package/scripts/verify-browser.mjs +297 -0
  20. package/scripts/verify-host.mjs +431 -0
  21. package/scripts/verify-live.mjs +268 -0
  22. package/scripts/verify-package.mjs +168 -0
  23. package/scripts/verify-persistence.mjs +307 -0
  24. package/scripts/verify-subscriptions-ui.mjs +321 -0
  25. package/src/account.js +85 -0
  26. package/src/account.test.js +52 -0
  27. package/src/authorization.js +199 -0
  28. package/src/authorization.test.js +332 -0
  29. package/src/catalog.js +180 -0
  30. package/src/catalog.test.js +146 -0
  31. package/src/chat-recovery.js +110 -0
  32. package/src/chat-recovery.test.js +261 -0
  33. package/src/connection-runtime.js +129 -0
  34. package/src/connection-runtime.test.js +244 -0
  35. package/src/connections.js +70 -0
  36. package/src/grants.js +104 -0
  37. package/src/grants.test.js +340 -0
  38. package/src/index.js +676 -0
  39. package/src/local-imports.js +263 -0
  40. package/src/local-imports.test.js +201 -0
  41. package/src/media.js +152 -0
  42. package/src/models.js +610 -0
  43. package/src/models.test.js +503 -0
  44. package/src/profile-store.js +51 -0
  45. package/src/pulls.js +100 -0
  46. package/src/pulls.test.js +156 -0
  47. package/src/qwen.js +141 -0
  48. package/src/qwen.test.js +35 -0
  49. package/src/request-errors.js +50 -0
  50. package/src/request-errors.test.js +131 -0
  51. package/src/routes.js +47 -0
  52. package/src/routes.test.js +136 -0
  53. package/src/subscription-models.test.js +160 -0
  54. package/src/usage/aggregators.js +292 -0
  55. package/src/usage/aggregators.test.js +316 -0
  56. package/src/usage/core.js +68 -0
  57. package/src/usage/index.js +93 -0
  58. package/src/usage/official.js +339 -0
  59. package/src/usage/official.test.js +273 -0
  60. package/src/usage/service.test.js +89 -0
  61. package/src/xai-browser.js +272 -0
  62. package/src/xai-browser.test.js +256 -0
  63. package/src/xai-login.js +121 -0
  64. package/src/xai-login.test.js +259 -0
  65. package/styles.css +364 -0
  66. package/theme.js +118 -0
  67. package/upstreams.json +10 -0
@@ -0,0 +1,156 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { execFile } from 'node:child_process';
7
+ import { promisify } from 'node:util';
8
+ import { createPullStore } from "./pulls.js";
9
+
10
+ async function temporaryProfiles(t) {
11
+ const directory = await mkdtemp(join(tmpdir(), "dsh-oauth-pulls-test-"));
12
+ t.after(() => rm(directory, { recursive: true, force: true }));
13
+ return { directory, a: join(directory, "profiles", "a"), b: join(directory, "profiles", "b") };
14
+ }
15
+
16
+ const pull = (id) => ({ models: [{ id, name: id, role: "chat" }], media: [], expiresAt: Date.now() + 3600000 });
17
+
18
+ test('permanent imports retain model capabilities and route ownership after reopening', async t => {
19
+ const { a: directory } = await temporaryProfiles(t);
20
+ const model = { id: 'rich', name: 'Rich model', role: 'chat', input: ['text', 'image'], output: ['text'], tools: true, contextWindow: 128000, maxTokens: 8192, reasoningEfforts: { high: 'high' }, source: 'account', entitlement: 'account' };
21
+ const saved = { models: [model], media: [], expiresAt: null, route: { edits: [] } };
22
+ await createPullStore(directory).write('openrouter', saved);
23
+ const fresh = createPullStore(directory);
24
+ assert.deepEqual(await fresh.read('openrouter'), saved);
25
+ assert.equal((await fresh.list())[0].expiresAt, null);
26
+ });
27
+
28
+ test('separate processes cannot lose another provider during concurrent persistence', async t => {
29
+ const { a: directory } = await temporaryProfiles(t);
30
+ const module = new URL('./pulls.js', import.meta.url).href;
31
+ const script = `import {createPullStore} from ${JSON.stringify(module)}; const [dir,id]=process.argv.slice(1); await createPullStore(dir).write(id,{models:[{id,name:id,role:'chat'}],expiresAt:null});`;
32
+ await Promise.all(Array.from({ length: 6 }, (_, i) => promisify(execFile)(process.execPath, ['--input-type=module', '-e', script, directory, `provider-${i}`])));
33
+ assert.equal((await createPullStore(directory).list()).length, 6);
34
+ });
35
+
36
+ test("two profiles retain independent pulls for the same provider", async (t) => {
37
+ const paths = await temporaryProfiles(t);
38
+ const a = createPullStore(paths.a);
39
+ const b = createPullStore(paths.b);
40
+ await Promise.all([a.write("xai", pull("model-a")), b.write("xai", pull("model-b"))]);
41
+ assert.equal((await a.read("xai")).models[0].id, "model-a");
42
+ assert.equal((await b.read("xai")).models[0].id, "model-b");
43
+ assert.deepEqual((await a.list()).map((row) => row.models[0].id), ["model-a"]);
44
+ assert.deepEqual((await b.list()).map((row) => row.models[0].id), ["model-b"]);
45
+ });
46
+
47
+ test("concurrent writes through separate stores for one profile retain every provider", async (t) => {
48
+ const { a: directory } = await temporaryProfiles(t);
49
+ const stores = [createPullStore(directory), createPullStore(directory)];
50
+ const ids = Array.from({ length: 32 }, (_, index) => `provider-${index}`);
51
+ await Promise.all(ids.map((id, index) => stores[index % stores.length].write(id, pull(`model-${index}`))));
52
+ const rows = await stores[0].list();
53
+ assert.equal(rows.length, ids.length);
54
+ assert.deepEqual(new Set(rows.map((row) => row.id)), new Set(ids));
55
+ for (let index = 0; index < ids.length; index += 1) {
56
+ assert.equal((await stores[1].read(ids[index])).models[0].id, `model-${index}`);
57
+ }
58
+ });
59
+
60
+ test("route ownership retains exact prior and written capabilities across persistence", async (t) => {
61
+ const { a: directory } = await temporaryProfiles(t);
62
+ const store = createPullStore(directory);
63
+ const route = { edits: [
64
+ {
65
+ path: ["providers", "xai", "models"],
66
+ before: [{ id: "before", maxTokens: 4096, reasoningEfforts: false }],
67
+ written: [{ id: "new", contextWindow: 200000, maxTokens: 32000, input: ["text", "image"], reasoningEfforts: { low: "low", high: "high" } }],
68
+ },
69
+ { path: ["providers", "xai", "displayName"], written: "Pulled provider" },
70
+ ] };
71
+ await store.write("xai", { ...pull("new"), route });
72
+ const readBack = await createPullStore(directory).read("xai");
73
+ assert.deepEqual(readBack.route, route);
74
+ assert.equal(Object.hasOwn(readBack.route.edits[1], "before"), false);
75
+ assert.deepEqual((await store.list())[0].route, route);
76
+ });
77
+
78
+ test("malformed JSON and malformed store documents reject reads and writes without replacing their bytes", async (t) => {
79
+ const { directory } = await temporaryProfiles(t);
80
+ const documents = ["{broken-json", JSON.stringify({ version: 1, pulls: null }), JSON.stringify({ version: 1, pulls: [] })];
81
+ for (let index = 0; index < documents.length; index += 1) {
82
+ const profile = join(directory, `corrupt-${index}`);
83
+ await mkdir(profile, { recursive: true });
84
+ const path = join(profile, "dsh-oauth-pulls.json");
85
+ const bytes = documents[index];
86
+ await writeFile(path, bytes);
87
+ const store = createPullStore(profile);
88
+ await assert.rejects(store.read("xai"), `read must reject corrupt store ${index}`);
89
+ await assert.rejects(store.write("xai", pull("replacement")), `write must reject corrupt store ${index}`);
90
+ assert.equal(await readFile(path, "utf8"), bytes);
91
+ }
92
+ });
93
+
94
+ test("a rejected write does not prevent later writes after the damaged store is explicitly repaired", async (t) => {
95
+ const { a: directory } = await temporaryProfiles(t);
96
+ await mkdir(directory, { recursive: true });
97
+ const path = join(directory, "dsh-oauth-pulls.json");
98
+ await writeFile(path, "invalid-json");
99
+ const store = createPullStore(directory);
100
+ await assert.rejects(store.write("xai", pull("failed")));
101
+ await writeFile(path, JSON.stringify({ version: 1, pulls: {} }));
102
+ await store.write("xai", pull("repaired"));
103
+ assert.equal((await store.read("xai")).models[0].id, "repaired");
104
+ });
105
+
106
+ test("legacy global records are neither imported nor modified by a scoped profile store", async (t) => {
107
+ const { directory, a: profile } = await temporaryProfiles(t);
108
+ const legacyPath = join(directory, "dsh-oauth-pulls.json");
109
+ const legacyBytes = JSON.stringify({ version: 1, pulls: { xai: { ...pull("legacy"), route: { edits: [{ path: ["providers", "xai"], written: { models: [{ id: "legacy" }] } }] } } } }, null, 2);
110
+ await writeFile(legacyPath, legacyBytes);
111
+ const oldHome = process.env.DSH_HOME;
112
+ process.env.DSH_HOME = directory;
113
+ try {
114
+ const store = createPullStore(profile);
115
+ assert.equal(await store.read("xai"), undefined);
116
+ assert.deepEqual(await store.list({ includeExpired: true }), []);
117
+ await store.write("xai", pull("profile-only"));
118
+ assert.equal((await store.read("xai")).models[0].id, "profile-only");
119
+ await store.delete("xai");
120
+ assert.equal(await readFile(legacyPath, "utf8"), legacyBytes);
121
+ } finally {
122
+ if (oldHome === undefined) delete process.env.DSH_HOME;
123
+ else process.env.DSH_HOME = oldHome;
124
+ }
125
+ });
126
+
127
+ test("deleting one profile's provider leaves the other profile and its ownership unchanged", async (t) => {
128
+ const paths = await temporaryProfiles(t);
129
+ const a = createPullStore(paths.a);
130
+ const b = createPullStore(paths.b);
131
+ const ownership = { edits: [{ path: ["providers", "xai", "models"], before: [{ id: "prior-b" }], written: [{ id: "model-b" }] }] };
132
+ await a.write("xai", pull("model-a"));
133
+ await b.write("xai", { ...pull("model-b"), route: ownership });
134
+ const bPath = join(paths.b, "dsh-oauth-pulls.json");
135
+ const before = await readFile(bPath, "utf8");
136
+ await a.delete("xai");
137
+ assert.equal(await a.read("xai"), undefined);
138
+ assert.equal((await b.read("xai")).models[0].id, "model-b");
139
+ assert.deepEqual((await b.read("xai")).route, ownership);
140
+ assert.equal(await readFile(bPath, "utf8"), before);
141
+ });
142
+
143
+ test("expired pulls remain available to maintenance while normal listing excludes them", async (t) => {
144
+ const { a: directory } = await temporaryProfiles(t);
145
+ const store = createPullStore(directory);
146
+ await store.write("expired", { ...pull("old"), expiresAt: 1 });
147
+ await store.write("live", pull("current"));
148
+ assert.deepEqual((await store.list()).map((row) => row.id), ["live"]);
149
+ assert.deepEqual(new Set((await store.list({ includeExpired: true })).map((row) => row.id)), new Set(["expired", "live"]));
150
+ assert.equal((await store.read("expired")).models[0].id, "old");
151
+ });
152
+
153
+ test("creating a scoped store requires an explicit profile directory", () => {
154
+ assert.throws(() => createPullStore(undefined), /profileContext.dir/);
155
+ assert.throws(() => createPullStore(""), /profileContext.dir/);
156
+ });
package/src/qwen.js ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Official Qwen account login (chat.qwen.ai device flow).
3
+ * The access token is what the coding endpoint accepts as a bearer.
4
+ */
5
+
6
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
7
+
8
+ const CLIENT_ID = "f0304373b74a44d2b584a3fb70ca9e56";
9
+ const SCOPE = "openid profile email model.completion";
10
+ const DEVICE_URL = "https://chat.qwen.ai/api/v1/oauth2/device/code";
11
+ const TOKEN_URL = "https://chat.qwen.ai/api/v1/oauth2/token";
12
+ const DEFAULT_BASE = "https://dashscope.aliyuncs.com/compatible-mode/v1";
13
+
14
+ /**
15
+ * OpenAI-compatible base URL for a Qwen OAuth resource.
16
+ * @param {unknown} resourceUrl
17
+ */
18
+ export function qwenEndpoint(resourceUrl) {
19
+ const raw = typeof resourceUrl === "string" && resourceUrl.trim().length > 0 ? resourceUrl.trim() : DEFAULT_BASE;
20
+ const withProtocol = /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;
21
+ const trimmed = withProtocol.replace(/\/+$/, "");
22
+ return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
23
+ }
24
+
25
+ /**
26
+ * @param {{ notify: (notice: { message?: string, url?: string }) => void, signal: AbortSignal }} session
27
+ */
28
+ export async function loginQwen(session) {
29
+ const verifier = randomBytes(32).toString("base64url");
30
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
31
+ const device = await postForm(DEVICE_URL, {
32
+ client_id: CLIENT_ID,
33
+ scope: SCOPE,
34
+ code_challenge: challenge,
35
+ code_challenge_method: "S256",
36
+ }, session.signal);
37
+ const url = firstString(device.verification_uri_complete, device.verification_uri);
38
+ if (url === undefined || typeof device.device_code !== "string") {
39
+ throw new Error("通义千问没有返回登录地址");
40
+ }
41
+ session.notify({ message: "在浏览器里完成通义千问登录", url, ...(device.user_code ? { code: device.user_code } : {}) });
42
+ const expiresIn = Number(device.expires_in);
43
+ const deadline = Date.now() + (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 300) * 1000;
44
+ let waitMs = 2000;
45
+ while (Date.now() < deadline) {
46
+ session.signal.throwIfAborted();
47
+ await delay(waitMs, session.signal);
48
+ const token = await postForm(TOKEN_URL, {
49
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
50
+ client_id: CLIENT_ID,
51
+ device_code: device.device_code,
52
+ code_verifier: verifier,
53
+ }, session.signal);
54
+ if (token.pending === true) {
55
+ if (token.slowDown === true) waitMs += 2000;
56
+ continue;
57
+ }
58
+ const access = firstString(token.access_token);
59
+ if (access === undefined) throw new Error("通义千问登录没有返回 access token");
60
+ const lifetime = Number(token.expires_in);
61
+ return {
62
+ access,
63
+ refresh: firstString(token.refresh_token),
64
+ expires: Date.now() + (Number.isFinite(lifetime) && lifetime > 0 ? lifetime : 3600) * 1000,
65
+ resourceUrl: qwenEndpoint(token.resource_url),
66
+ };
67
+ }
68
+ throw new Error("通义千问登录超时");
69
+ }
70
+
71
+ /** Refresh the OAuth grant without losing a non-rotated refresh token or resource URL. */
72
+ export async function refreshQwen(grant, signal = AbortSignal.timeout(20000)) {
73
+ if (typeof grant.refresh !== "string" || grant.refresh.length === 0) {
74
+ throw new Error("通义千问登录已过期,请重新登录");
75
+ }
76
+ const token = await postForm(TOKEN_URL, {
77
+ grant_type: "refresh_token",
78
+ client_id: CLIENT_ID,
79
+ refresh_token: grant.refresh,
80
+ }, signal);
81
+ const access = firstString(token.access_token);
82
+ if (access === undefined) throw new Error("通义千问刷新没有返回 access token,请重新登录");
83
+ const lifetime = Number(token.expires_in);
84
+ return {
85
+ ...grant,
86
+ access,
87
+ refresh: firstString(token.refresh_token) ?? grant.refresh,
88
+ expires: Date.now() + (Number.isFinite(lifetime) && lifetime > 0 ? lifetime : 3600) * 1000,
89
+ resourceUrl: qwenEndpoint(firstString(token.resource_url) ?? grant.resourceUrl),
90
+ };
91
+ }
92
+
93
+ async function postForm(url, fields, signal) {
94
+ const body = new URLSearchParams();
95
+ for (const [key, value] of Object.entries(fields)) {
96
+ if (typeof value === "string") body.set(key, value);
97
+ }
98
+ const response = await fetch(url, {
99
+ method: "POST",
100
+ headers: {
101
+ accept: "application/json",
102
+ "content-type": "application/x-www-form-urlencoded",
103
+ "x-request-id": randomUUID(),
104
+ },
105
+ body,
106
+ signal,
107
+ });
108
+ const text = await response.text();
109
+ let payload = {};
110
+ try {
111
+ payload = text.length > 0 ? JSON.parse(text) : {};
112
+ } catch {
113
+ payload = {};
114
+ }
115
+ const error = typeof payload.error === "string" ? payload.error : "";
116
+ if (response.status === 400 && error === "authorization_pending") return { pending: true };
117
+ if ((response.status === 429 || response.status === 400) && error === "slow_down") return { pending: true, slowDown: true };
118
+ if (!response.ok) {
119
+ throw new Error(`通义千问登录返回 ${response.status}${error ? `: ${error}` : ""}`);
120
+ }
121
+ return payload;
122
+ }
123
+
124
+ function delay(ms, signal) {
125
+ return new Promise((resolve, reject) => {
126
+ const timer = setTimeout(() => {
127
+ signal.removeEventListener("abort", onAbort);
128
+ resolve(undefined);
129
+ }, ms);
130
+ const onAbort = () => {
131
+ clearTimeout(timer);
132
+ reject(signal.reason ?? new Error("登录已取消"));
133
+ };
134
+ if (signal.aborted) onAbort();
135
+ else signal.addEventListener("abort", onAbort, { once: true });
136
+ });
137
+ }
138
+
139
+ function firstString(...values) {
140
+ return values.find((value) => typeof value === "string" && value.length > 0);
141
+ }
@@ -0,0 +1,35 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { loginQwen, qwenEndpoint } from "./qwen.js";
4
+
5
+ test("qwen endpoint keeps an explicit /v1 resource", () => {
6
+ assert.equal(qwenEndpoint("https://portal.qwen.ai/v1"), "https://portal.qwen.ai/v1");
7
+ });
8
+
9
+ test("qwen endpoint adds https and /v1", () => {
10
+ assert.equal(qwenEndpoint("dashscope.aliyuncs.com/compatible-mode"), "https://dashscope.aliyuncs.com/compatible-mode/v1");
11
+ });
12
+
13
+ test("qwen endpoint falls back when the token has no resource", () => {
14
+ assert.equal(qwenEndpoint(undefined), "https://dashscope.aliyuncs.com/compatible-mode/v1");
15
+ });
16
+
17
+ for (const [label, device, expected] of [
18
+ ["prefers the complete verification URI", { verification_uri_complete: "https://example.invalid/complete", verification_uri: "https://example.invalid/base" }, "https://example.invalid/complete"],
19
+ ["accepts the standard verification URI", { verification_uri: "https://example.invalid/base" }, "https://example.invalid/base"],
20
+ ["falls back from an empty complete verification URI", { verification_uri_complete: "", verification_uri: "https://example.invalid/base" }, "https://example.invalid/base"],
21
+ ]) {
22
+ test(`Qwen device login ${label}`, async (t) => {
23
+ const controller = new AbortController();
24
+ const notices = [];
25
+ t.mock.method(globalThis, "fetch", async () => new Response(JSON.stringify({ ...device, device_code: "offline-device", user_code: "OFFLINE-CODE", expires_in: 30 })));
26
+ const pending = loginQwen({
27
+ signal: controller.signal,
28
+ notify(notice) { notices.push(notice); controller.abort(new Error("offline test stopped after notice")); },
29
+ });
30
+ await assert.rejects(pending, /offline test stopped after notice/);
31
+ assert.equal(notices.length, 1);
32
+ assert.equal(notices[0].url, expected);
33
+ assert.equal(notices[0].code, "OFFLINE-CODE");
34
+ });
35
+ }
@@ -0,0 +1,50 @@
1
+ const BAD_CREDENTIALS_CODES = new Set(["bad-credentials", "unauthenticated:bad-credentials"]);
2
+ const SAFE_ERROR_CODES = new Set([
3
+ ...BAD_CREDENTIALS_CODES,
4
+ "invalid_token", "invalid_grant", "invalid_api_key", "unauthorized", "authentication_error",
5
+ "access_denied", "insufficient_scope", "permission_denied", "forbidden",
6
+ "rate_limit_exceeded", "too_many_requests", "subscription:free-usage-exhausted", "free-usage-exhausted",
7
+ ]);
8
+
9
+ const providerLabel = (provider) => typeof provider === "string" && /^[a-z][a-z0-9-]{0,63}$/.test(provider) ? provider : "OAuth";
10
+ const normalized = (value) => typeof value === "string" ? value.trim().toLowerCase() : undefined;
11
+ const tokenValidationFailure = (value) => typeof value === "string" &&
12
+ /^(?:the\s+)?(?:oauth2\s+)?access[ _]token could not be validated[.!]?$/i.test(value.trim());
13
+
14
+ /** Keep response diagnostics useful without retaining arbitrary upstream text or credentials. */
15
+ export class OAuthRequestError extends Error {
16
+ constructor(provider, status, text) {
17
+ let body;
18
+ try { body = JSON.parse(typeof text === "string" ? text : ""); }
19
+ catch { /* Only an exact plain-text token-validation failure is recognized below. */ }
20
+ const codes = [body?.code, body?.error?.code, body?.body?.error?.code, body?.error].map(normalized);
21
+ const code = codes.find((value) => SAFE_ERROR_CODES.has(value));
22
+ const messages = [body?.message, body?.error?.message, body?.error, body?.body?.error?.message,
23
+ body?.body?.error, typeof body === "string" ? body : undefined, typeof body === "undefined" ? text : undefined];
24
+ const badCredentials = codes.some((value) => BAD_CREDENTIALS_CODES.has(value)) || messages.some(tokenValidationFailure);
25
+ super(`${providerLabel(provider)} 请求返回 HTTP ${status}${code ? `(${code})` : ""}`);
26
+ this.name = "OAuthRequestError";
27
+ this.provider = provider;
28
+ this.status = status;
29
+ if (code) this.code = code;
30
+ this.authenticationRejected = status === 401 || provider === "xai" && status === 403 && badCredentials;
31
+ }
32
+ }
33
+
34
+ /** Retry an operation once after an explicit rejection of the grant it used. */
35
+ export async function withGrantRecovery(provider, resolveGrant, operation) {
36
+ const grant = await resolveGrant(provider);
37
+ try { return await operation(grant); }
38
+ catch (error) {
39
+ if (!(error instanceof OAuthRequestError) || error.provider !== provider || !error.authenticationRejected) throw error;
40
+ let renewed;
41
+ try { renewed = await resolveGrant(provider, { rejectedGrant: grant }); }
42
+ catch (refreshError) {
43
+ const failure = new Error(`${providerLabel(provider)} 请求被拒绝后自动续期失败(HTTP ${error.status})`, { cause: refreshError });
44
+ failure.name = "OAuthRecoveryError";
45
+ failure.requestError = error;
46
+ throw failure;
47
+ }
48
+ return operation(renewed);
49
+ }
50
+ }
@@ -0,0 +1,131 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { OAuthRequestError, withGrantRecovery } from "./request-errors.js";
4
+
5
+ test("HTTP authentication rejection refreshes the rejected grant and retries once", async () => {
6
+ const old = { access: "old", refresh: "refresh-old" };
7
+ const renewed = { access: "renewed", refresh: "refresh-new" };
8
+ const resolutions = [];
9
+ const operations = [];
10
+ const result = await withGrantRecovery("anthropic", async (provider, options) => {
11
+ resolutions.push({ provider, options });
12
+ return options ? renewed : old;
13
+ }, async (grant) => {
14
+ operations.push(grant);
15
+ if (grant === old) throw new OAuthRequestError("anthropic", 401, JSON.stringify({ error: { type: "authentication_error", message: "denied" } }));
16
+ return "models-returned";
17
+ });
18
+ assert.equal(result, "models-returned");
19
+ assert.deepEqual(resolutions, [{ provider: "anthropic", options: undefined }, { provider: "anthropic", options: { rejectedGrant: old } }]);
20
+ assert.deepEqual(operations, [old, renewed]);
21
+ });
22
+
23
+ test("xAI's precise bad-credentials responses allow one recovery despite HTTP 403", async () => {
24
+ const bodies = [
25
+ { code: "unauthenticated:bad-credentials", error: "The OAuth2 access token could not be validated." },
26
+ { error: { code: "bad-credentials" } },
27
+ { body: { error: { code: "unauthenticated:bad-credentials" } } },
28
+ { error: { message: "The OAuth2 access token could not be validated." } },
29
+ ];
30
+ for (const body of bodies) {
31
+ let resolveCalls = 0;
32
+ let operationCalls = 0;
33
+ const result = await withGrantRecovery("xai", async () => ({ access: `grant-${++resolveCalls}` }), async () => {
34
+ if (++operationCalls === 1) throw new OAuthRequestError("xai", 403, JSON.stringify(body));
35
+ return "success";
36
+ });
37
+ assert.equal(result, "success");
38
+ assert.equal(resolveCalls, 2);
39
+ assert.equal(operationCalls, 2);
40
+ }
41
+ });
42
+
43
+ test("a second authentication rejection is returned without a third request or another refresh", async () => {
44
+ const first = new OAuthRequestError("xai", 401, "unauthorized");
45
+ const second = new OAuthRequestError("xai", 403, JSON.stringify({ code: "unauthenticated:bad-credentials" }));
46
+ let resolveCalls = 0;
47
+ let operationCalls = 0;
48
+ await assert.rejects(withGrantRecovery("xai", async () => ({ access: `grant-${++resolveCalls}` }), async () => {
49
+ throw ++operationCalls === 1 ? first : second;
50
+ }), (error) => error === second);
51
+ assert.equal(resolveCalls, 2);
52
+ assert.equal(operationCalls, 2);
53
+ });
54
+
55
+ test("permission, billing, rate, network, and unrelated provider failures never refresh or repeat the request", async () => {
56
+ const failures = [
57
+ new OAuthRequestError("xai", 403, JSON.stringify({ code: "permission_denied" })),
58
+ new OAuthRequestError("xai", 403, JSON.stringify({ error: { code: "insufficient_scope" } })),
59
+ new OAuthRequestError("xai", 403, "<html>Cloudflare challenge</html>"),
60
+ new OAuthRequestError("xai", 403, JSON.stringify({ message: "Try refreshing; error code unknown" })),
61
+ new OAuthRequestError("xai", 402, JSON.stringify({ code: "bad-credentials" })),
62
+ new OAuthRequestError("xai", 429, JSON.stringify({ code: "bad-credentials" })),
63
+ new OAuthRequestError("xai", 503, JSON.stringify({ code: "bad-credentials" })),
64
+ new OAuthRequestError("anthropic", 403, JSON.stringify({ code: "bad-credentials" })),
65
+ new OAuthRequestError("anthropic", 401, "unauthorized"),
66
+ new Error("network failure mentions 401"),
67
+ Object.assign(new Error("request timed out"), { name: "TimeoutError" }),
68
+ Object.assign(new Error("user cancelled"), { name: "AbortError" }),
69
+ ];
70
+ for (const failure of failures) {
71
+ let resolveCalls = 0;
72
+ let operationCalls = 0;
73
+ await assert.rejects(withGrantRecovery("xai", async () => { resolveCalls += 1; return { access: "old" }; }, async () => {
74
+ operationCalls += 1;
75
+ throw failure;
76
+ }), (error) => error === failure);
77
+ assert.equal(resolveCalls, 1);
78
+ assert.equal(operationCalls, 1);
79
+ }
80
+ });
81
+
82
+ test("refresh failure preserves its cause and original request failure without making a second request", async () => {
83
+ const rejection = new OAuthRequestError("xai", 401, "unauthorized");
84
+ const refreshError = new Error("temporary refresh transport failure");
85
+ let resolveCalls = 0;
86
+ let operationCalls = 0;
87
+ await assert.rejects(withGrantRecovery("xai", async () => {
88
+ if (++resolveCalls === 2) throw refreshError;
89
+ return { access: "old" };
90
+ }, async () => { operationCalls += 1; throw rejection; }), (error) => {
91
+ assert.equal(error.name, "OAuthRecoveryError");
92
+ assert.equal(error.cause, refreshError);
93
+ assert.equal(error.requestError, rejection);
94
+ assert.doesNotMatch(error.message, /重新登录|重登|登录已过期/);
95
+ return true;
96
+ });
97
+ assert.equal(resolveCalls, 2);
98
+ assert.equal(operationCalls, 1);
99
+ });
100
+
101
+ test("initial grant resolution errors propagate without attempting the operation or forced refresh", async () => {
102
+ const failure = new Error("credential store is unavailable");
103
+ let resolveCalls = 0;
104
+ let operationCalls = 0;
105
+ await assert.rejects(withGrantRecovery("xai", async () => { resolveCalls += 1; throw failure; }, async () => { operationCalls += 1; }), (error) => error === failure);
106
+ assert.equal(resolveCalls, 1);
107
+ assert.equal(operationCalls, 0);
108
+ });
109
+
110
+ test("request diagnostics do not retain arbitrary response text, token-like error codes, or token values", () => {
111
+ const token = "sensitive-access-token-must-not-appear";
112
+ for (const status of [401, 403, 429, 500]) {
113
+ const error = new OAuthRequestError("xai", status, JSON.stringify({
114
+ code: token, error: { code: "unauthenticated:bad-credentials", message: `Bearer ${token}` }, access_token: token,
115
+ }));
116
+ assert.doesNotMatch(String(error), new RegExp(token));
117
+ assert.doesNotMatch(JSON.stringify(error), new RegExp(token));
118
+ assert.equal(error.code, "unauthenticated:bad-credentials");
119
+ assert.equal(Object.hasOwn(error, "body"), false);
120
+ assert.equal(Object.hasOwn(error, "text"), false);
121
+ }
122
+ });
123
+
124
+ test("an arbitrary sentence or error code containing bad-credentials does not authorize a refresh", () => {
125
+ for (const body of [
126
+ { code: "permission_denied:bad-credentials" },
127
+ { message: "This permission error is unrelated to access token could not be validated" },
128
+ { error: "bad-credentials was mentioned by a user" },
129
+ ]) assert.equal(new OAuthRequestError("xai", 403, JSON.stringify(body)).authenticationRejected, false);
130
+ assert.equal(new OAuthRequestError("xai", 403, "access_token could not be validated").authenticationRejected, true);
131
+ });
package/src/routes.js ADDED
@@ -0,0 +1,47 @@
1
+ /** Restore only settings written by this pull, leaving later user edits intact. */
2
+ import { isDeepStrictEqual } from "node:util";
3
+
4
+ const NS = "llm-pi-ai";
5
+ const at = (object, path) => path.reduce((value, key) => value?.[key], object);
6
+ const descriptor = (settings) => settings.describe({ redactSecrets: false }).find((row) => row.ns === NS);
7
+
8
+ /** Capture the prior user values for the exact paths being changed. */
9
+ export async function writeRoute(settings, id, models, codingPlan, previous) {
10
+ const row = descriptor(settings);
11
+ if (!row) throw new Error("llm-pi-ai 设置尚未挂载");
12
+ const providerPath = ["providers", id];
13
+ const provider = at(row.user, providerPath);
14
+ const entries = codingPlan && provider === undefined
15
+ ? [{ path: providerPath, value: codingPlan }]
16
+ : Object.entries(codingPlan ?? { models }).map(([key, value]) => ({ path: [...providerPath, key], value }));
17
+ const edits = entries.map(({ path, value }) => {
18
+ const earlier = previous?.edits?.find((edit) => isDeepStrictEqual(edit.path, path));
19
+ const before = at(row.user, path);
20
+ return { path, written: value, ...(earlier && isDeepStrictEqual(before, earlier.written)
21
+ ? (Object.hasOwn(earlier, "before") ? { before: earlier.before } : {})
22
+ : before === undefined ? {} : { before }) };
23
+ });
24
+ // A second Qwen pull still owns the initially created provider entry.
25
+ const owned = previous?.edits?.find((edit) => isDeepStrictEqual(edit.path, providerPath));
26
+ if (codingPlan && owned && isDeepStrictEqual(provider, owned.written)) {
27
+ edits.splice(0, edits.length, { ...owned, written: { ...provider, ...codingPlan } });
28
+ }
29
+ await settings.mutate(NS, edits.map((edit) => ({ op: "set", path: edit.path, value: edit.written })), row.revision);
30
+ const rollback = { edits: edits.map((edit) => {
31
+ const before = at(row.user, edit.path);
32
+ return { path: edit.path, written: edit.written, ...(before === undefined ? {} : { before }) };
33
+ }) };
34
+ return { edits, rollback };
35
+ }
36
+
37
+ /** Missing legacy ownership data never authorizes deleting a whole provider. */
38
+ export async function restoreRoute(settings, route) {
39
+ if (!Array.isArray(route?.edits)) return;
40
+ const row = descriptor(settings);
41
+ if (!row) throw new Error("llm-pi-ai 设置尚未挂载,稍后重试清理");
42
+ const ops = route.edits.filter((edit) => isDeepStrictEqual(at(row.user, edit.path), edit.written))
43
+ .map((edit) => Object.hasOwn(edit, "before")
44
+ ? { op: "set", path: edit.path, value: edit.before }
45
+ : { op: "unset", path: edit.path });
46
+ if (ops.length > 0) await settings.mutate(NS, ops, row.revision);
47
+ }