@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,415 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { codexModelsUrl, fetchAccountModels, modelListRequest, parseModelList, preferredMedia } from "./models.js";
4
+ import { OAuthRequestError, withGrantRecovery } from "./request-errors.js";
5
+
6
+ test("codex model list URL includes client_version", () => {
7
+ const url = new URL(codexModelsUrl());
8
+ assert.equal(url.origin + url.pathname, "https://chatgpt.com/backend-api/codex/models");
9
+ assert.equal(url.searchParams.get("client_version"), "0.156.1");
10
+ });
11
+
12
+ test("each OAuth model list sends the fields that provider requires", () => {
13
+ const codex = modelListRequest("openai-codex", "header.payload.sig");
14
+ assert.equal(new URL(codex.url).searchParams.get("client_version"), "0.156.1");
15
+
16
+ const claude = modelListRequest("anthropic", "token");
17
+ assert.equal(claude.headers["anthropic-version"], "2023-06-01");
18
+ assert.equal(claude.headers["anthropic-beta"], "oauth-2025-04-20");
19
+ assert.equal(new URL(claude.url).searchParams.get("limit"), "1000");
20
+
21
+ const kimi = modelListRequest("kimi-coding", "token");
22
+ assert.equal(kimi.url, "https://api.kimi.com/coding/v1/models");
23
+ assert.equal(kimi.headers["user-agent"], "KimiCLI/1.0");
24
+
25
+ const copilot = modelListRequest("github-copilot", "tid=1;proxy-ep=proxy.individual.githubcopilot.com");
26
+ assert.equal(copilot.url, "https://api.individual.githubcopilot.com/models");
27
+ assert.equal(copilot.headers["copilot-integration-id"], "vscode-chat");
28
+ assert.equal(copilot.headers["x-github-api-version"], "2026-06-01");
29
+
30
+ const qwen = modelListRequest("qwen", "token", { resourceUrl: "https://portal.qwen.ai/v1" });
31
+ assert.equal(qwen.url, "https://portal.qwen.ai/v1/models");
32
+
33
+ assert.equal(modelListRequest("openrouter", "token").url, "https://openrouter.ai/api/v1/models/user");
34
+ assert.equal(modelListRequest("xai", "token").url, "https://cli-chat-proxy.grok.com/v1/models");
35
+ });
36
+
37
+ test("parseModelList reads id, slug, and display name without a catalog", () => {
38
+ const models = parseModelList({
39
+ models: [{ slug: "gpt-5.4", title: "GPT 5.4" }, { id: "gpt-5.4" }],
40
+ data: [{ id: "claude-sonnet", display_name: "Claude Sonnet" }],
41
+ });
42
+ assert.deepEqual(models, [
43
+ { id: "gpt-5.4", name: "GPT 5.4", role: "chat" },
44
+ { id: "claude-sonnet", name: "Claude Sonnet", role: "chat" },
45
+ ]);
46
+ });
47
+
48
+ test("parseModelList ignores entries that have no id", () => {
49
+ assert.deepEqual(parseModelList({ data: [{ name: "nameless" }, { id: "kept" }] }), [
50
+ { id: "kept", name: "kept", role: "chat" },
51
+ ]);
52
+ });
53
+
54
+ test("subscription model maps keep grok-4.7-build-fast and drop hidden or embedding rows", () => {
55
+ const models = parseModelList({
56
+ data: [
57
+ {
58
+ id: "grok-4.7-build-fast",
59
+ name: "Grok 4.7 Fast",
60
+ context_window: 500000,
61
+ reasoning_efforts: [{ id: "xhigh", value: "xhigh" }, { id: "high", value: "high" }],
62
+ },
63
+ { id: "grok-embed", name: "Embed" },
64
+ { id: "grok-2", name: "Old", hidden: true },
65
+ ],
66
+ }, "xai");
67
+ assert.deepEqual(models, [{
68
+ id: "grok-4.7-build-fast",
69
+ name: "Grok 4.7 Fast",
70
+ role: "chat",
71
+ contextWindow: 500000,
72
+ input: ["text", "image"],
73
+ reasoningEfforts: { xhigh: "xhigh", high: "high" },
74
+ }]);
75
+ });
76
+
77
+ test("reasoning levels stay the ones each account advertises", () => {
78
+ const [codex] = parseModelList({
79
+ models: [{
80
+ slug: "gpt-5.4",
81
+ display_name: "GPT-5.4",
82
+ supported_reasoning_levels: [
83
+ { effort: "low", description: "low" },
84
+ { effort: "high", description: "high" },
85
+ { effort: "xhigh", description: "extra" },
86
+ { effort: "ultra", description: "not a harness level" },
87
+ ],
88
+ }],
89
+ });
90
+ assert.deepEqual(codex.reasoningEfforts, { low: "low", high: "high", xhigh: "xhigh" });
91
+
92
+ const [openai] = parseModelList({
93
+ data: [{
94
+ id: "gpt-5.4",
95
+ supported_reasoning_levels: [{ effort: "none" }, { effort: "medium" }],
96
+ }],
97
+ });
98
+ assert.deepEqual(openai.reasoningEfforts, { off: "none", medium: "medium" });
99
+
100
+ const [plain] = parseModelList({ data: [{ id: "claude-sonnet", display_name: "Claude" }] });
101
+ assert.equal(plain.reasoningEfforts, undefined);
102
+ });
103
+
104
+ test("anthropic capability flags become reasoning levels and max_input_tokens the context window", () => {
105
+ const [claude, noEffort] = parseModelList({
106
+ data: [
107
+ {
108
+ type: "model",
109
+ id: "claude-opus",
110
+ display_name: "Claude Opus",
111
+ max_input_tokens: 200000,
112
+ capabilities: {
113
+ effort: {
114
+ supported: true,
115
+ low: { supported: true },
116
+ medium: { supported: true },
117
+ high: { supported: true },
118
+ max: { supported: true },
119
+ xhigh: { supported: false },
120
+ },
121
+ thinking: { supported: true, types: { adaptive: { supported: true }, enabled: { supported: true } } },
122
+ },
123
+ },
124
+ {
125
+ type: "model",
126
+ id: "claude-haiku",
127
+ display_name: "Claude Haiku",
128
+ capabilities: { effort: { supported: false, low: { supported: true } } },
129
+ },
130
+ ],
131
+ has_more: false,
132
+ });
133
+ assert.equal(claude.contextWindow, 200000);
134
+ assert.deepEqual(claude.reasoningEfforts, { low: "low", medium: "medium", high: "high", max: "max" });
135
+ assert.equal(noEffort.reasoningEfforts, false);
136
+ });
137
+
138
+ test("preferred media keeps the current image and video models", () => {
139
+ const media = preferredMedia([
140
+ { id: "grok-imagine-image", name: "old image", role: "image" },
141
+ { id: "grok-imagine-image-quality", name: "quality", role: "image" },
142
+ { id: "grok-imagine-image-2.0", name: "Grok Imagine Image", role: "image" },
143
+ { id: "grok-imagine-video", name: "old video", role: "video" },
144
+ { id: "grok-imagine-video-1.5", name: "Grok Imagine Video", role: "video" },
145
+ { id: "grok-4.7", name: "Grok 4.7", role: "chat" },
146
+ ]);
147
+ assert.deepEqual(media.map((model) => model.id), ["grok-imagine-image-2.0", "grok-imagine-video-1.5"]);
148
+ });
149
+
150
+ test("anthropic pull follows has_more pages and keeps effort levels", async (t) => {
151
+ const pages = {
152
+ first: {
153
+ data: [{
154
+ id: "claude-a",
155
+ display_name: "Claude A",
156
+ max_input_tokens: 200000,
157
+ capabilities: { effort: { supported: true, high: { supported: true }, max: { supported: true } } },
158
+ }],
159
+ has_more: true,
160
+ last_id: "claude-a",
161
+ },
162
+ second: {
163
+ data: [{ id: "claude-b", display_name: "Claude B", capabilities: { effort: { supported: false } } }],
164
+ has_more: false,
165
+ last_id: "claude-b",
166
+ },
167
+ };
168
+ const urls = [];
169
+ t.mock.method(globalThis, "fetch", async (url) => {
170
+ urls.push(String(url));
171
+ const body = new URL(url).searchParams.get("after_id") === "claude-a" ? pages.second : pages.first;
172
+ return new Response(JSON.stringify(body), { status: 200 });
173
+ });
174
+ const models = await fetchAccountModels("anthropic", { access: "token" });
175
+ assert.equal(urls.length, 2);
176
+ assert.equal(new URL(urls[1]).searchParams.get("limit"), "1000");
177
+ assert.deepEqual(models, [
178
+ { id: "claude-a", name: "Claude A", role: "chat", contextWindow: 200000, reasoningEfforts: { high: "high", max: "max" }, source: 'account', entitlement: 'account' },
179
+ { id: "claude-b", name: "Claude B", role: "chat", reasoningEfforts: false, source: 'account', entitlement: 'account' },
180
+ ]);
181
+ });
182
+
183
+ test("Codex visibility, modalities, and explicit empty reasoning survive catalog parsing", () => {
184
+ const models = parseModelList({ models: [
185
+ {
186
+ slug: "codex-visible",
187
+ display_name: "Codex Visible",
188
+ visibility: "list",
189
+ context_window: 272000,
190
+ max_context_window: 400000,
191
+ input_modalities: ["text", "image", "audio"],
192
+ supported_reasoning_levels: [{ effort: "low" }, { effort: "max" }],
193
+ },
194
+ { slug: "codex-hide", visibility: "hide" },
195
+ { slug: "codex-none", visibility: "none" },
196
+ { slug: "codex-off", visibility: "list", supported_reasoning_levels: [{ effort: "none" }] },
197
+ { slug: "codex-empty", visibility: "list", supported_reasoning_levels: [] },
198
+ ] });
199
+ assert.deepEqual(models, [
200
+ {
201
+ id: "codex-visible", name: "Codex Visible", role: "chat", contextWindow: 272000,
202
+ input: ["text", "image"], reasoningEfforts: { low: "low", max: "max" },
203
+ },
204
+ { id: "codex-off", name: "codex-off", role: "chat", reasoningEfforts: false },
205
+ { id: "codex-empty", name: "codex-empty", role: "chat", reasoningEfforts: false },
206
+ ]);
207
+ });
208
+
209
+ test("Copilot account catalog honors picker availability and retains declared capabilities", async (t) => {
210
+ t.mock.method(globalThis, "fetch", async () => new Response(JSON.stringify({ data: [
211
+ {
212
+ id: "copilot-chat", name: "Copilot Chat", model_picker_enabled: true, policy: { state: "enabled" },
213
+ capabilities: {
214
+ type: "chat",
215
+ limits: { max_context_window_tokens: 200000, max_prompt_tokens: 150000, max_output_tokens: 32000 },
216
+ supports: { vision: true, tool_calls: true, reasoning_effort: ["low", "medium", "high"] },
217
+ },
218
+ },
219
+ { id: "copilot-disabled", model_picker_enabled: true, policy: { state: "disabled" }, capabilities: { type: "chat" } },
220
+ { id: "copilot-no-tools", model_picker_enabled: true, capabilities: { type: "chat", supports: { tool_calls: false } } },
221
+ { id: "copilot-hidden", model_picker_enabled: false, policy: { state: "enabled" }, capabilities: { type: "chat" } },
222
+ { id: "copilot-embedding", model_picker_enabled: true, capabilities: { type: "embeddings" } },
223
+ { id: "copilot-completion", model_picker_enabled: true, capabilities: { type: "completion" } },
224
+ ] }), { status: 200 }));
225
+ assert.deepEqual(await fetchAccountModels("github-copilot", { access: "token" }), [{
226
+ id: "copilot-chat", name: "Copilot Chat", role: "chat", contextWindow: 200000, maxTokens: 32000,
227
+ input: ["text", "image"], reasoningEfforts: { low: "low", medium: "medium", high: "high" },
228
+ tools: true, source: 'account', entitlement: 'account',
229
+ }]);
230
+ });
231
+
232
+ test("Copilot enabled-policy fallback applies only to Individual accounts with an empty picker", async (t) => {
233
+ t.mock.method(globalThis, "fetch", async () => new Response(JSON.stringify({ data: [
234
+ {
235
+ id: "individual-enabled", model_picker_enabled: false, policy: { state: "enabled" },
236
+ capabilities: { type: "chat", supports: { vision: false, tool_calls: true, reasoning_effort: ["none"] } },
237
+ },
238
+ { id: "individual-disabled", model_picker_enabled: false, policy: { state: "disabled" }, capabilities: { type: "chat" } },
239
+ { id: "individual-unknown", model_picker_enabled: false, capabilities: { type: "chat" } },
240
+ ] }), { status: 200 }));
241
+ assert.deepEqual(await fetchAccountModels("github-copilot", { access: "token" }), [{
242
+ id: "individual-enabled", name: "individual-enabled", role: "chat", input: ["text"], reasoningEfforts: false,
243
+ tools: true, source: 'account', entitlement: 'account',
244
+ }]);
245
+ await assert.rejects(fetchAccountModels("github-copilot", {
246
+ access: "token", apiBase: "https://api.business.githubcopilot.com",
247
+ }), /没有返回可用模型/);
248
+ });
249
+
250
+ test("undeclared chat input is vision only for xAI, and explicit modalities still win", () => {
251
+ const [grok] = parseModelList({ data: [{ id: "grok-4.7-build-fast" }] }, "xai");
252
+ assert.deepEqual(grok.input, ["text", "image"]);
253
+
254
+ const explicit = parseModelList({ data: [
255
+ { id: "grok-text", input: ["text"] },
256
+ { id: "grok-blind", capabilities: { supports: { vision: false } } },
257
+ { id: "grok-see", input_modalities: ["image", "audio"] },
258
+ { id: "claude-blind", capabilities: { image_input: { supported: false } } },
259
+ { id: "grok-imagine-image-2.0" },
260
+ ] }, "xai");
261
+ assert.deepEqual(explicit.map((model) => model.input), [
262
+ ["text"], ["text"], ["text", "image"], ["text"], undefined,
263
+ ]);
264
+
265
+ const [omitted, claude, routerText, routerVision, kimi] = [
266
+ ...parseModelList({ data: [{ id: "claude-undeclared" }] }, "anthropic"),
267
+ ...parseModelList({ data: [{ id: "claude-new", capabilities: { image_input: { supported: true } } }] }, "anthropic"),
268
+ ...parseModelList({ data: [{ id: "vendor/text", architecture: { input_modalities: ["text"], modality: "text+image->text" } }] }, "openrouter"),
269
+ ...parseModelList({ data: [{ id: "vendor/vision", architecture: { modality: "text+image->text" } }] }, "openrouter"),
270
+ ...parseModelList({ data: [{ id: "kimi-new" }] }, "kimi-coding"),
271
+ ];
272
+ assert.equal(omitted.input, undefined);
273
+ assert.deepEqual(claude.input, ["text", "image"]);
274
+ assert.deepEqual(routerText.input, ["text"]);
275
+ assert.deepEqual(routerVision.input, ["text", "image"]);
276
+ assert.equal(kimi.input, undefined);
277
+ });
278
+
279
+ test("missing output or reasoning metadata stays unknown rather than becoming a generic capability", () => {
280
+ assert.deepEqual(parseModelList({ data: [
281
+ { id: "known-output", max_output_tokens: 16384, input_modalities: ["text"] },
282
+ { id: "unknown-output", max_output_tokens: "32768" },
283
+ { id: "prompt-only", capabilities: { limits: { max_prompt_tokens: 64000 } } },
284
+ ] }), [
285
+ { id: "known-output", name: "known-output", role: "chat", maxTokens: 16384, input: ["text"] },
286
+ { id: "unknown-output", name: "unknown-output", role: "chat" },
287
+ { id: "prompt-only", name: "prompt-only", role: "chat" },
288
+ ]);
289
+ });
290
+
291
+ test("refreshed upstream auth headers and base URLs reach catalog requests", () => {
292
+ const copilot = modelListRequest("github-copilot", "token", {
293
+ apiBase: "https://copilot-api.example.test///",
294
+ requestHeaders: { "User-Agent": "upstream-client", "X-GitHub-Api-Version": "upstream-version" },
295
+ });
296
+ assert.equal(copilot.url, "https://copilot-api.example.test/models");
297
+ assert.equal(copilot.headers["user-agent"], "upstream-client");
298
+ assert.equal(copilot.headers["x-github-api-version"], "upstream-version");
299
+ assert.equal(copilot.headers.authorization, "Bearer token");
300
+ const anthropic = modelListRequest("anthropic", "token", {
301
+ requestHeaders: { "Anthropic-Beta": "upstream-oauth-beta", "User-Agent": "upstream-claude" },
302
+ });
303
+ assert.equal(anthropic.headers["anthropic-beta"], "upstream-oauth-beta");
304
+ assert.equal(anthropic.headers["user-agent"], "upstream-claude");
305
+ assert.equal(modelListRequest("kimi-coding", "token", { apiBase: "https://kimi.example.test/v1/" }).url,
306
+ "https://kimi.example.test/v1/models");
307
+ assert.equal(modelListRequest("xai", "token", { apiBase: "https://grok.example.test/v1/" }).url,
308
+ "https://grok.example.test/v1/models");
309
+ assert.equal(new URL(modelListRequest("openai-codex", "token", {
310
+ apiBase: "https://chatgpt.com/backend-api/codex/responses",
311
+ }).url).pathname, "/backend-api/codex/models");
312
+ });
313
+
314
+ test("preferred media never invents a model absent from an account catalog", () => {
315
+ assert.deepEqual(preferredMedia([]), []);
316
+ assert.deepEqual(preferredMedia([{ id: "grok-imagine-image", name: "Image", role: "image" }]), [
317
+ { id: "grok-imagine-image", name: "Image", role: "image" },
318
+ ]);
319
+ });
320
+
321
+ test("Grok media catalog failures keep only models returned by the OAuth catalog", async (t) => {
322
+ const requests = [];
323
+ t.mock.method(globalThis, "fetch", async (url) => {
324
+ requests.push(String(url));
325
+ if (String(url).startsWith("https://api.x.ai/")) return new Response("denied", { status: 401 });
326
+ return new Response(JSON.stringify({ data: [{ id: "grok-chat" }] }), { status: 200 });
327
+ });
328
+ assert.deepEqual(await fetchAccountModels("xai", { access: "token" }), [
329
+ { id: "grok-chat", name: "grok-chat", role: "chat", input: ["text", "image"], source: 'account', entitlement: 'account' },
330
+ ]);
331
+ assert.equal(requests.length, 2);
332
+ });
333
+
334
+ test("Grok media listed by OAuth remains available when the separate media endpoint is unavailable", async (t) => {
335
+ t.mock.method(globalThis, "fetch", async (url) => {
336
+ if (String(url).startsWith("https://api.x.ai/")) throw new Error("offline");
337
+ return new Response(JSON.stringify({ data: [{ id: "grok-chat" }, { id: "grok-imagine-image-2.0" }] }), { status: 200 });
338
+ });
339
+ assert.deepEqual((await fetchAccountModels("xai", { access: "token" })).map((model) => model.id), [
340
+ "grok-chat", "grok-imagine-image-2.0",
341
+ ]);
342
+ });
343
+
344
+ test("a primary model catalog rejection carries structured status without retaining its token response", async (t) => {
345
+ const token = "sensitive-token-that-must-not-be-displayed";
346
+ t.mock.method(globalThis, "fetch", async () => new Response(JSON.stringify({
347
+ error: { code: "permission_denied", message: `Do not reveal ${token}` }, access_token: token,
348
+ }), { status: 403 }));
349
+ await assert.rejects(fetchAccountModels("openrouter", { access: "signed-in" }), (error) => {
350
+ assert.ok(error instanceof OAuthRequestError);
351
+ assert.equal(error.provider, "openrouter");
352
+ assert.equal(error.status, 403);
353
+ assert.equal(error.authenticationRejected, false);
354
+ assert.equal(error.code, "permission_denied");
355
+ assert.doesNotMatch(String(error), new RegExp(token));
356
+ assert.doesNotMatch(JSON.stringify(error), new RegExp(token));
357
+ return true;
358
+ });
359
+ });
360
+
361
+ test("an xAI primary catalog bad-credentials rejection rebuilds the request with one renewed grant", async (t) => {
362
+ const old = { access: "old", expires: Date.now() + 3600000 };
363
+ const renewed = { access: "renewed", expires: Date.now() + 3600000 };
364
+ const requests = [];
365
+ const resolutions = [];
366
+ t.mock.method(globalThis, "fetch", async (url, options) => {
367
+ if (String(url).startsWith("https://api.x.ai/")) return new Response("no media permission", { status: 403 });
368
+ requests.push(options.headers.authorization);
369
+ if (options.headers.authorization === "Bearer old") return new Response(JSON.stringify({
370
+ code: "unauthenticated:bad-credentials", error: "The OAuth2 access token could not be validated.",
371
+ }), { status: 403 });
372
+ return new Response(JSON.stringify({ data: [{ id: "grok-chat" }] }), { status: 200 });
373
+ });
374
+ const models = await withGrantRecovery("xai", async (provider, options) => {
375
+ resolutions.push({ provider, options });
376
+ return options ? renewed : old;
377
+ }, (grant) => fetchAccountModels("xai", grant));
378
+ assert.deepEqual(models.map((model) => model.id), ["grok-chat"]);
379
+ assert.deepEqual(requests, ["Bearer old", "Bearer renewed"]);
380
+ assert.deepEqual(resolutions[1], { provider: "xai", options: { rejectedGrant: old } });
381
+ assert.equal(resolutions.length, 2);
382
+ });
383
+
384
+ test("an optional Grok media catalog 401 does not refresh a grant whose primary catalog succeeded", async (t) => {
385
+ let resolveCalls = 0;
386
+ t.mock.method(globalThis, "fetch", async (url) => String(url).startsWith("https://api.x.ai/")
387
+ ? new Response(JSON.stringify({ code: "unauthorized" }), { status: 401 })
388
+ : new Response(JSON.stringify({ data: [{ id: "grok-chat" }] }), { status: 200 }));
389
+ const models = await withGrantRecovery("xai", async () => { resolveCalls += 1; return { access: "signed-in" }; },
390
+ (grant) => fetchAccountModels("xai", grant));
391
+ assert.equal(resolveCalls, 1);
392
+ assert.deepEqual(models.map((model) => model.id), ["grok-chat"]);
393
+ });
394
+
395
+ test("an authentication rejection on a later Anthropic page retries the read-only catalog from its first page", async (t) => {
396
+ const requests = [];
397
+ let resolveCalls = 0;
398
+ t.mock.method(globalThis, "fetch", async (url, options) => {
399
+ const after = new URL(url).searchParams.get("after_id");
400
+ requests.push({ after, authorization: options.headers.authorization });
401
+ if (!after) return new Response(JSON.stringify({ data: [{ id: "claude-a" }], has_more: true, last_id: "claude-a" }));
402
+ if (options.headers.authorization === "Bearer old") return new Response(JSON.stringify({ error: { type: "authentication_error" } }), { status: 401 });
403
+ return new Response(JSON.stringify({ data: [{ id: "claude-b" }], has_more: false }));
404
+ });
405
+ const models = await withGrantRecovery("anthropic", async () => ({ access: ++resolveCalls === 1 ? "old" : "renewed" }),
406
+ (grant) => fetchAccountModels("anthropic", grant));
407
+ assert.deepEqual(models.map((model) => model.id), ["claude-a", "claude-b"]);
408
+ assert.deepEqual(requests, [
409
+ { after: null, authorization: "Bearer old" },
410
+ { after: "claude-a", authorization: "Bearer old" },
411
+ { after: null, authorization: "Bearer renewed" },
412
+ { after: "claude-a", authorization: "Bearer renewed" },
413
+ ]);
414
+ assert.equal(resolveCalls, 2);
415
+ });
@@ -0,0 +1,51 @@
1
+ import { mkdir, readFile, rename, rm, writeFile, stat } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { join, dirname } from 'node:path';
4
+
5
+ export async function withStoreLock(path, callback) {
6
+ await mkdir(dirname(path), { recursive: true });
7
+ const lock = `${path}.lock`;
8
+ const deadline = Date.now() + 5000;
9
+ while (true) {
10
+ try { await mkdir(lock); await writeFile(join(lock, 'owner'), String(process.pid), { mode: 0o600 }); break; }
11
+ catch (error) {
12
+ if (error.code !== 'EEXIST') throw error;
13
+ if (Date.now() - (await stat(lock).catch(() => ({ mtimeMs: Date.now() }))).mtimeMs > 30000) {
14
+ const pid = Number(await readFile(join(lock, 'owner'), 'utf8').catch(() => ''));
15
+ let alive = false;
16
+ if (Number.isInteger(pid) && pid > 0) try { process.kill(pid, 0); alive = true; } catch (cause) { alive = cause.code !== 'ESRCH'; }
17
+ if (!alive) { await rm(lock, { recursive: true, force: true }); continue; }
18
+ }
19
+ if (Date.now() > deadline) throw new Error('Profile store is busy; try again.');
20
+ await new Promise(resolve => setTimeout(resolve, 20));
21
+ }
22
+ }
23
+ try { return await callback(); }
24
+ finally { await rm(lock, { recursive: true, force: true }); }
25
+ }
26
+
27
+ /** Atomic, profile-scoped JSON. Only non-secret derived state belongs here. */
28
+ export function createProfileStore(directory, filename) {
29
+ if (!directory) throw new Error('A profile directory is required.');
30
+ const path = join(directory, filename);
31
+ const read = async () => {
32
+ try {
33
+ const data = JSON.parse(await readFile(path, 'utf8'));
34
+ if (data?.version !== 1 || !data.entries || typeof data.entries !== 'object' || Array.isArray(data.entries)) throw new Error('Invalid profile store; original file retained.');
35
+ return data.entries;
36
+ } catch (error) { if (error.code === 'ENOENT') return {}; throw error; }
37
+ };
38
+ const mutate = callback => withStoreLock(path, async () => {
39
+ const temp = `${path}.${randomUUID()}.tmp`;
40
+ try {
41
+ const entries = await read(); if (await callback(entries) === false) return;
42
+ await writeFile(temp, JSON.stringify({ version: 1, entries }, null, 2), { mode: 0o600 });
43
+ await rename(temp, path);
44
+ } finally { await rm(temp, { force: true }); }
45
+ });
46
+ return {
47
+ read: async id => (await read())[id],
48
+ write: (id, value, condition = () => true) => mutate(entries => { if (!condition()) return false; entries[id] = value; }),
49
+ delete: id => mutate(entries => { delete entries[id]; }),
50
+ };
51
+ }
package/src/pulls.js ADDED
@@ -0,0 +1,100 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { withStoreLock } from './profile-store.js';
6
+
7
+ function storePath(directory) {
8
+ const home = process.env.DSH_HOME || join(homedir(), ".dsh");
9
+ return join(directory ?? home, "dsh-oauth-pulls.json");
10
+ }
11
+
12
+ async function readAll(directory) {
13
+ try {
14
+ const parsed = JSON.parse(await readFile(storePath(directory), "utf8"));
15
+ if (parsed?.version === 1 && parsed.pulls && typeof parsed.pulls === "object" && !Array.isArray(parsed.pulls)) return parsed.pulls;
16
+ throw new Error("OAuth 拉取记录格式无效,已保留原文件");
17
+ } catch (error) {
18
+ if (error.code !== "ENOENT") throw error;
19
+ }
20
+ return {};
21
+ }
22
+
23
+ async function writeAll(pulls, directory) {
24
+ const path = storePath(directory);
25
+ await mkdir(dirname(path), { recursive: true });
26
+ const temporary = `${path}.${randomUUID()}.tmp`;
27
+ await writeFile(temporary, JSON.stringify({ version: 1, pulls }, null, 2), { mode: 0o600 });
28
+ await rename(temporary, path);
29
+ }
30
+
31
+ /** @param {string} id */
32
+ export async function readPull(id, directory) {
33
+ const pull = (await readAll(directory))[id];
34
+ if (!pull || typeof pull !== "object") return undefined;
35
+ if (!Array.isArray(pull.models) || pull.expiresAt !== null && !Number.isFinite(pull.expiresAt)) return undefined;
36
+ const mapModels = (list) => (Array.isArray(list) ? list : []).filter((model) => model && typeof model.id === "string").map((model) => ({
37
+ ...model,
38
+ id: model.id,
39
+ name: typeof model.name === "string" ? model.name : model.id,
40
+ role: model.role === "image" || model.role === "video" ? model.role : "chat",
41
+ }));
42
+ return {
43
+ ...pull,
44
+ models: mapModels(pull.models),
45
+ media: mapModels(pull.media),
46
+ expiresAt: pull.expiresAt,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * @param {string} id
52
+ * @param {{ models: {id: string, name: string}[], expiresAt: number }} pull
53
+ */
54
+ export async function writePull(id, pull, directory) {
55
+ return updateAll(async (pulls) => { pulls[id] = pull; }, directory);
56
+ }
57
+
58
+ export async function listPulls({ includeExpired = false, directory } = {}) {
59
+ const pulls = await readAll(directory);
60
+ const live = [];
61
+ for (const [id, pull] of Object.entries(pulls)) {
62
+ if (!pull || pull.expiresAt !== null && (!Number.isFinite(pull.expiresAt) || !includeExpired && pull.expiresAt <= Date.now())) continue;
63
+ live.push({
64
+ ...pull,
65
+ id,
66
+ models: Array.isArray(pull.models) ? pull.models : [],
67
+ media: Array.isArray(pull.media) ? pull.media : [],
68
+ expiresAt: pull.expiresAt,
69
+ });
70
+ }
71
+ return live;
72
+ }
73
+
74
+ /** @param {string} id */
75
+ export async function deletePull(id, directory) {
76
+ return updateAll(async (pulls) => { delete pulls[id]; }, directory);
77
+ }
78
+
79
+ const writes = new Map();
80
+ function updateAll(mutate, directory) {
81
+ const key = storePath(directory);
82
+ const next = (writes.get(key) ?? Promise.resolve()).then(() => withStoreLock(key, async () => {
83
+ const pulls = await readAll(directory);
84
+ await mutate(pulls);
85
+ await writeAll(pulls, directory);
86
+ }));
87
+ writes.set(key, next.catch(() => {}));
88
+ return next;
89
+ }
90
+
91
+ /** Scope new records to the launcher-owned profile; the old global file is left untouched. */
92
+ export function createPullStore(directory) {
93
+ if (typeof directory !== "string" || directory.length === 0) throw new Error("OAuth 拉取记录需要当前 profileContext.dir");
94
+ return {
95
+ read: (id) => readPull(id, directory),
96
+ write: (id, pull) => writePull(id, pull, directory),
97
+ delete: (id) => deletePull(id, directory),
98
+ list: (options = {}) => listPulls({ ...options, directory }),
99
+ };
100
+ }