@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,431 @@
1
+ #!/usr/bin/env node
2
+ /** Offline integration against real published DSH packages; no live profile or account is used. */
3
+ import assert from "node:assert/strict";
4
+ import { cp, mkdtemp, readFile, readdir, rm, symlink } from "node:fs/promises";
5
+ import { createHash, generateKeyPairSync, sign } from "node:crypto";
6
+ import { createRequire } from "node:module";
7
+ import { tmpdir } from "node:os";
8
+ import { dirname, join, resolve } from "node:path";
9
+ import { pathToFileURL, fileURLToPath } from "node:url";
10
+ import { Readable } from "node:stream";
11
+
12
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
13
+ const runtimeArg = process.argv.indexOf("--runtime");
14
+ const runtime = runtimeArg < 0 ? root : resolve(process.argv[runtimeArg + 1] ?? "");
15
+ const modules = runtime.endsWith("node_modules") ? runtime : join(runtime, "node_modules");
16
+ const temporary = await mkdtemp(join(tmpdir(), "dsh-oauth-host-smoke-"));
17
+ const previousHome = process.env.DSH_HOME;
18
+ const previousFetch = globalThis.fetch;
19
+ let ctx;
20
+ try {
21
+ process.env.DSH_HOME = join(temporary, "profile");
22
+ const pluginRoot = join(temporary, "plugin");
23
+ for (const path of ["src", "package.json", "client.js", "index.html", "auth.html", "app.js", "providers.js", "styles.css", "theme.js"]) {
24
+ await cp(join(root, path), join(pluginRoot, path), { recursive: true });
25
+ }
26
+ await symlink(modules, join(pluginRoot, "node_modules"), "dir");
27
+ const requireRuntime = createRequire(join(pluginRoot, "package.json"));
28
+ const load = (name) => import(pathToFileURL(requireRuntime.resolve(name)).href);
29
+ const [{ Context, Service }, credentialsModule, authorizationModule, toolsModule, systemPromptModule, slotsModule] = await Promise.all([
30
+ load("@deepseek-ai/cordis"), load("@deepseek-ai/dsh-credentials"), load("@deepseek-ai/dsh-authorization"),
31
+ load("@deepseek-ai/dsh-tools"), load("@deepseek-ai/dsh-system-prompt"), load("@deepseek-ai/dsh-client-ui-slots"),
32
+ ]);
33
+ // Loading these official exports catches package/import drift even though settings are held in memory below.
34
+ await Promise.all([load("@deepseek-ai/dsh-settings"), load("@deepseek-ai/dsh-client-ui-settings"), load("@deepseek-ai/dsh-client-ui-settings-general")]);
35
+ const piAiAdapter = await load("@deepseek-ai/dsh-llm-pi-ai");
36
+ const { credentialKey, CredentialProvider } = credentialsModule;
37
+ const routes = [];
38
+ const mutations = [];
39
+ const references = new Map();
40
+ const records = new Map();
41
+ let userSettings = { providers: {} };
42
+ let revision = 0;
43
+ let deepseekCounter = 0;
44
+ let commitDuringCancel = false;
45
+ const deepseekCancels = [];
46
+ let deepseekState = { status: "signed-out", attempt: null };
47
+ class MemoryCredentials extends CredentialProvider {
48
+ async resolve(ref) { const value = references.get(ref); return value === undefined ? undefined : { value, source: "memory" }; }
49
+ async describe(ref) { return { configured: references.has(ref), writable: true }; }
50
+ async set(ref, value) {
51
+ references.set(ref, value); this.notifyUpdated(ref);
52
+ }
53
+ async unset(ref) { references.delete(ref); this.notifyUpdated(ref); }
54
+ async readRecord(key) { return records.get(key); }
55
+ async describeRecord(key) { const value = records.get(key); return { configured: value !== undefined, writable: true, ...(value === undefined ? {} : { kind: value.kind }) }; }
56
+ async listRecords() { return [...records].map(([key, record]) => ({ key, kind: record.kind })); }
57
+ async modifyRecord(key, mutate) {
58
+ const next = await mutate(records.get(key));
59
+ if (next !== undefined) { records.set(key, next); this.notifyRecordUpdated(key); }
60
+ return records.get(key);
61
+ }
62
+ async deleteRecord(key) { records.delete(key); this.notifyRecordUpdated(key); }
63
+ }
64
+ class MemorySettings extends Service {
65
+ constructor(context) { super(context, "settings"); }
66
+ describe() { return [{ ns: "llm-pi-ai", user: structuredClone(userSettings), value: structuredClone(userSettings), revision }]; }
67
+ async mutate(namespace, operations, expectedRevision) {
68
+ assert.equal(namespace, "llm-pi-ai");
69
+ assert.equal(expectedRevision, revision);
70
+ const next = structuredClone(userSettings);
71
+ for (const operation of operations) {
72
+ let object = next;
73
+ for (const key of operation.path.slice(0, -1)) object = object[key] ??= {};
74
+ const key = operation.path.at(-1);
75
+ if (operation.op === "unset") delete object[key]; else object[key] = structuredClone(operation.value);
76
+ }
77
+ // Parse the actual output through the selected published adapter's schema before accepting the edit.
78
+ piAiAdapter.Config(next);
79
+ userSettings = next;
80
+ revision += 1;
81
+ mutations.push({ namespace, operations });
82
+ }
83
+ }
84
+ class MemoryWebServer extends Service {
85
+ constructor(context) { super(context, "webServer"); }
86
+ register(route) { routes.push(route); return () => { const index = routes.indexOf(route); if (index >= 0) routes.splice(index, 1); }; }
87
+ }
88
+ class MemoryDeepSeekAccount extends Service {
89
+ constructor(context) { super(context, "deepseekAccount"); }
90
+ async getState() { return structuredClone(deepseekState); }
91
+ async startSignIn(client, origin, source) {
92
+ assert.equal(typeof client.version, "string");
93
+ assert.equal(typeof client.timezoneOffsetSeconds, "number");
94
+ assert.equal(origin, "http://127.0.0.1:19387");
95
+ assert.equal(source, "desktop");
96
+ deepseekCounter += 1;
97
+ deepseekState = { status: "signed-out", attempt: { id: `deepseek-attempt-${deepseekCounter}`, phase: "waiting-browser", authorizeUrl: `https://example.invalid/deepseek/${deepseekCounter}` } };
98
+ return this.getState();
99
+ }
100
+ async cancelSignIn(id) {
101
+ assert.equal(id, deepseekState.attempt.id);
102
+ deepseekCancels.push(id);
103
+ deepseekState.attempt.phase = commitDuringCancel ? "succeeded" : "cancelled";
104
+ if (commitDuringCancel) deepseekState.status = "credential-stored";
105
+ return this.getState();
106
+ }
107
+ }
108
+ ctx = new Context();
109
+ const profileDirectory = join(process.env.DSH_HOME, "profiles", "desktop");
110
+ ctx.provide("profileContext", { name: "desktop", dir: profileDirectory, home: process.env.DSH_HOME, patchPath: join(profileDirectory, "cordis.patch.yml") });
111
+ await ctx.plugin(MemoryCredentials);
112
+ await ctx.plugin(MemorySettings);
113
+ await ctx.plugin(MemoryWebServer);
114
+ await ctx.plugin(MemoryDeepSeekAccount);
115
+ await ctx.plugin(systemPromptModule.default);
116
+ await ctx.plugin(toolsModule.default);
117
+ if (typeof ctx.tools.setExecutor === 'function') ctx.tools.setExecutor({
118
+ sections: [],
119
+ describe(definitions) { return { schemas: ctx.tools.schemas(), knownNames: definitions.map(tool => tool.name) }; },
120
+ async execute() { throw new Error('Host smoke must not execute tools.'); },
121
+ });
122
+ const host = await import(pathToFileURL(join(pluginRoot, "src/index.js")).href);
123
+ const fiber = ctx.plugin(host);
124
+ await fiber;
125
+ const route = routes.find((entry) => entry.path === "/oauth");
126
+ assert.ok(route, "the host mounts /oauth through the real Cordis injection lifecycle");
127
+ const request = async (path, body) => {
128
+ const response = { status: 0, body: "", writeHead(status) { this.status = status; }, end(body) { this.body = String(body ?? ""); } };
129
+ const req = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]);
130
+ Object.assign(req, { method: body === undefined ? "GET" : "POST", url: path, headers: { host: "127.0.0.1:19387" } });
131
+ await route.handler(req, response);
132
+ return response;
133
+ };
134
+ assert.equal((await request("/oauth/")).status, 200);
135
+ const listed = await request("/oauth/api/providers");
136
+ assert.equal(listed.status, 200);
137
+ assert.equal(JSON.parse(listed.body).version, JSON.parse(await readFile(join(pluginRoot, "package.json"), "utf8")).version);
138
+ assert.ok(JSON.parse(listed.body).providers.some((provider) => provider.id === "qwen"));
139
+ const deepseekFirst = JSON.parse((await request("/oauth/api/login", { provider: "deepseek-account" })).body);
140
+ assert.equal(deepseekFirst.pending, true);
141
+ assert.equal(deepseekFirst.url, "https://example.invalid/deepseek/1");
142
+ const deepseekSecond = JSON.parse((await request("/oauth/api/login", { provider: "deepseek-account" })).body);
143
+ const staleCancel = await request("/oauth/api/login/cancel", { provider: "deepseek-account", attemptId: deepseekFirst.attemptId });
144
+ assert.equal(staleCancel.status, 400);
145
+ assert.equal(deepseekCancels.length, 0, "a stale panel attempt cannot cancel the current upstream attempt");
146
+ const activeCancel = await request("/oauth/api/login/cancel", { provider: "deepseek-account", attemptId: deepseekSecond.attemptId });
147
+ assert.equal(activeCancel.status, 200, activeCancel.body);
148
+ assert.equal(JSON.parse(activeCancel.body).status, "cancelled");
149
+ assert.deepEqual(deepseekCancels, ["deepseek-attempt-2"]);
150
+ const deepseekThird = JSON.parse((await request("/oauth/api/login", { provider: "deepseek-account" })).body);
151
+ commitDuringCancel = true;
152
+ const committedCancel = await request("/oauth/api/login/cancel", { provider: "deepseek-account", attemptId: deepseekThird.attemptId });
153
+ assert.equal(committedCancel.status, 200, committedCancel.body);
154
+ assert.equal(JSON.parse(committedCancel.body).status, "authorized", "an upstream commit that beats cancellation remains authorized");
155
+ assert.deepEqual(deepseekCancels, ["deepseek-attempt-2", "deepseek-attempt-3"]);
156
+ assert.ok(ctx.authorization instanceof authorizationModule.AuthorizationService);
157
+ const key = credentialKey("dsh-oauth", "qwen");
158
+ assert.equal(ctx.authorization.describe(key), undefined, "new legacy Qwen login is retired");
159
+ globalThis.fetch = async () => assert.fail("retired Qwen login must not reach the provider");
160
+ const retired = await request("/oauth/api/login", { provider: "qwen" });
161
+ assert.equal(retired.status, 400);
162
+ assert.match(JSON.parse(retired.body).error, /Token Plan/);
163
+ records.set(key, { kind: "grant", payload: {
164
+ access: "offline-access", refresh: "offline-refresh", expires: Date.now() + 3600000, resourceUrl: "https://portal.qwen.ai",
165
+ } });
166
+ globalThis.fetch = async (url, options) => {
167
+ assert.equal(String(url), "https://portal.qwen.ai/v1/models");
168
+ assert.equal(options.headers.authorization, "Bearer offline-access");
169
+ return new Response(JSON.stringify({ data: [{ id: "qwen-offline", name: "Offline Qwen", context_window: 65536, max_output_tokens: 4096, input_modalities: ["text"], reasoning_efforts: [] }] }));
170
+ };
171
+ const pulled = await request("/oauth/api/pull", { provider: "qwen", models: ["qwen-offline"], expiresAt: Date.now() + 3600000 });
172
+ assert.equal(pulled.status, 200, pulled.body);
173
+ const savedModel = userSettings.providers.qwen.models[0];
174
+ assert.equal(savedModel.contextWindow, 65536);
175
+ assert.equal(savedModel.maxTokens, 4096);
176
+ assert.deepEqual(savedModel.input, ["text"]);
177
+ assert.equal(savedModel.reasoningEfforts, false);
178
+ assert.equal(userSettings.providers.qwen.apiKeyEnv, "QWEN_OAUTH_ACCESS");
179
+ assert.equal(mutations.length, 1);
180
+ const pullFile = JSON.parse(await readFile(join(profileDirectory, "dsh-oauth-pulls.json"), "utf8"));
181
+ assert.equal(pullFile.pulls.qwen.models[0].id, "qwen-offline");
182
+ const loggedOut = await request("/oauth/api/logout", { provider: "qwen" });
183
+ assert.equal(loggedOut.status, 200, loggedOut.body);
184
+ assert.equal(userSettings.providers.qwen, undefined, "logout restores the previous settings through the adapter schema");
185
+
186
+ const xaiKey = credentialKey("llm-pi-ai", "xai");
187
+ const removeXaiFlow = ctx.authorization.registerFlow({
188
+ key: xaiKey, label: "Offline xAI", methods: [{ id: "oauth", label: "Device" }],
189
+ async run(session) {
190
+ session.notify({ url: "https://example.invalid/xai-device", code: "OFFLINE-DEVICE" });
191
+ await new Promise((_, reject) => session.signal.addEventListener("abort", () => reject(new Error("offline device cancelled")), { once: true }));
192
+ },
193
+ });
194
+ const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
195
+ let browserAuthorize;
196
+ let browserExchanges = 0;
197
+ const clientId = "b1a00492-073a-47ea-816f-4c329264a828";
198
+ globalThis.fetch = async (url, options) => {
199
+ if (String(url) === "https://auth.x.ai/.well-known/openid-configuration") return new Response(JSON.stringify({
200
+ issuer: "https://auth.x.ai", authorization_endpoint: "https://auth.x.ai/oauth2/authorize", token_endpoint: "https://auth.x.ai/oauth2/token",
201
+ jwks_uri: "https://auth.x.ai/.well-known/jwks.json", code_challenge_methods_supported: ["S256"], id_token_signing_alg_values_supported: ["ES256"],
202
+ }));
203
+ if (String(url) === "https://auth.x.ai/.well-known/jwks.json") return new Response(JSON.stringify({ keys: [{ ...publicKey.export({ format: "jwk" }), kid: "offline-host-key", alg: "ES256", use: "sig" }] }));
204
+ assert.equal(String(url), "https://auth.x.ai/oauth2/token");
205
+ browserExchanges += 1;
206
+ assert.equal(options.body.get("grant_type"), "authorization_code");
207
+ assert.equal(options.body.get("client_id"), clientId);
208
+ assert.equal(options.body.get("redirect_uri"), browserAuthorize.searchParams.get("redirect_uri"));
209
+ assert.equal(createHash("sha256").update(options.body.get("code_verifier")).digest("base64url"), browserAuthorize.searchParams.get("code_challenge"));
210
+ const header = Buffer.from(JSON.stringify({ alg: "ES256", kid: "offline-host-key" })).toString("base64url");
211
+ const claims = Buffer.from(JSON.stringify({ iss: "https://auth.x.ai", aud: clientId, sub: "offline-host-user", exp: Math.floor(Date.now() / 1000) + 3600, nonce: browserAuthorize.searchParams.get("nonce") })).toString("base64url");
212
+ const input = `${header}.${claims}`;
213
+ const signature = sign("sha256", Buffer.from(input), { key: privateKey, dsaEncoding: "ieee-p1363" }).toString("base64url");
214
+ return new Response(JSON.stringify({ access_token: "offline-browser-access", refresh_token: "offline-browser-refresh", expires_in: 3600, id_token: `${input}.${signature}` }));
215
+ };
216
+ const browserStarted = JSON.parse((await request("/oauth/api/login", { provider: "xai" })).body);
217
+ browserAuthorize = new URL(browserStarted.url);
218
+ assert.equal(browserAuthorize.pathname, "/oauth2/authorize", "the default xAI panel route must avoid device approval");
219
+ assert.equal(browserAuthorize.searchParams.get("code_challenge_method"), "S256");
220
+ assert.equal(browserAuthorize.searchParams.get("scope"), "openid profile email offline_access grok-cli:access api:access");
221
+ assert.equal(browserExchanges, 0);
222
+ const duplicateBrowser = JSON.parse((await request("/oauth/api/login", { provider: "xai", method: "browser" })).body);
223
+ assert.equal(duplicateBrowser.attemptId, browserStarted.attemptId);
224
+ const prematureDevice = await request("/oauth/api/login", { provider: "xai", method: "device" });
225
+ assert.equal(prematureDevice.status, 400, "the panel cannot switch methods while a browser login is pending");
226
+ const callback = new URL(browserAuthorize.searchParams.get("redirect_uri"));
227
+ callback.searchParams.set("state", browserAuthorize.searchParams.get("state"));
228
+ callback.searchParams.set("code", "offline-authorization-code");
229
+ const callbackResponse = await previousFetch(callback, { headers: { origin: "https://accounts.x.ai" } });
230
+ assert.equal(callbackResponse.status, 200);
231
+ await callbackResponse.text();
232
+ let browserState;
233
+ for (let attempt = 0; attempt < 100; attempt += 1) {
234
+ browserState = JSON.parse((await request("/oauth/api/login/status?provider=xai")).body);
235
+ if (!browserState.pending) break;
236
+ await new Promise((resolve) => setTimeout(resolve, 5));
237
+ }
238
+ assert.equal(browserState.status, "authorized", browserState.error);
239
+ assert.equal(browserExchanges, 1);
240
+ assert.equal(records.get(xaiKey).payload.refresh, "offline-browser-refresh");
241
+ assert.equal(records.has(credentialKey("dsh-oauth", "xai-browser")), false, "browser login must not duplicate a secret under an alias key");
242
+ const browserRow = JSON.parse((await request("/oauth/api/providers")).body).providers.find((provider) => provider.id === "xai");
243
+ assert.equal(browserRow.loggedIn, true);
244
+ assert.deepEqual(browserRow.loginMethods, ["browser", "device"]);
245
+ assert.equal(browserRow.defaultLoginMethod, "browser");
246
+ assert.equal(browserRow.cli, "");
247
+ const deviceStarted = JSON.parse((await request("/oauth/api/login", { provider: "xai", method: "device" })).body);
248
+ assert.equal(deviceStarted.code, "OFFLINE-DEVICE");
249
+ assert.equal((await request("/oauth/api/login/cancel", { provider: "xai", attemptId: deviceStarted.attemptId })).status, 200);
250
+ assert.equal(records.get(xaiKey).payload.refresh, "offline-browser-refresh", "cancelling the explicit device fallback leaves saved browser credentials intact");
251
+ removeXaiFlow();
252
+
253
+ // A token can be rejected before its advertised expiry. Exercise the public
254
+ // host endpoint, real pi refresh implementation and canonical record commit.
255
+ assert.ok(records.get(xaiKey).payload.expires > Date.now() + 300000);
256
+ let catalogRequests = 0;
257
+ let refreshRequests = 0;
258
+ globalThis.fetch = async (url, options) => {
259
+ if (String(url) === "https://auth.x.ai/oauth2/token") {
260
+ refreshRequests += 1;
261
+ assert.equal(options.body.get("grant_type"), "refresh_token");
262
+ assert.equal(options.body.get("refresh_token"), "offline-browser-refresh");
263
+ return new Response(JSON.stringify({ access_token: "offline-new-xai", refresh_token: "offline-new-refresh", expires_in: 3600 }));
264
+ }
265
+ if (String(url) === "https://api.x.ai/v1/models") return new Response("media permission denied", { status: 403 });
266
+ assert.equal(String(url), "https://cli-chat-proxy.grok.com/v1/models");
267
+ catalogRequests += 1;
268
+ if (catalogRequests === 1) {
269
+ assert.equal(options.headers.authorization, "Bearer offline-browser-access");
270
+ return new Response(JSON.stringify({ error: { code: "invalid_token" } }), { status: 401 });
271
+ }
272
+ assert.equal(options.headers.authorization, "Bearer offline-new-xai");
273
+ return new Response(JSON.stringify({ data: [{ id: "grok-offline", name: "Offline Grok" }] }));
274
+ };
275
+ const recovered = await request("/oauth/api/models", { provider: "xai" });
276
+ assert.equal(recovered.status, 200, recovered.body);
277
+ assert.equal(JSON.parse(recovered.body).models[0].id, "grok-offline");
278
+ assert.equal(catalogRequests, 2);
279
+ assert.equal(refreshRequests, 1);
280
+ assert.equal(records.get(xaiKey).payload.refresh, "offline-new-refresh");
281
+ const permissionRequests = [];
282
+ globalThis.fetch = async (url) => {
283
+ permissionRequests.push(String(url));
284
+ return new Response(JSON.stringify({ code: "permission_denied" }), { status: 403 });
285
+ };
286
+ const denied = await request("/oauth/api/models", { provider: "xai" });
287
+ assert.equal(denied.status, 400);
288
+ assert.match(JSON.parse(denied.body).error, /HTTP 403/);
289
+ assert.equal(refreshRequests, 1, "permission denial must not trigger another refresh");
290
+ assert.deepEqual(permissionRequests, ["https://cli-chat-proxy.grok.com/v1/models"]);
291
+ assert.equal(records.get(xaiKey).payload.refresh, "offline-new-refresh");
292
+
293
+ // Exercise chat recovery through Cordis's actual public waterfalls. The LLM
294
+ // stream itself is simulated; no model request or tool execution occurs.
295
+ userSettings.providers.xai = { models: [{ id: "grok-offline", name: "Offline Grok" }] };
296
+ records.set(xaiKey, { kind: "grant", payload: { type: "oauth", access: "offline-chat-old", refresh: "offline-chat-refresh", expires: Date.now() + 3600000 } });
297
+ let chatRefreshRequests = 0;
298
+ globalThis.fetch = async (url, options) => {
299
+ assert.equal(String(url), "https://auth.x.ai/oauth2/token");
300
+ chatRefreshRequests += 1;
301
+ assert.equal(options.body.get("refresh_token"), "offline-chat-refresh");
302
+ return new Response(JSON.stringify({ access_token: "offline-chat-new", refresh_token: "offline-chat-rotated", expires_in: 3600 }));
303
+ };
304
+ const chatAgent = { session: { id: "offline-host-session" } };
305
+ const chatSignal = new AbortController().signal;
306
+ const chatPosition = { agent: chatAgent, turn: 1, step: 1, signal: chatSignal };
307
+ const chatFailure = { code: "AUTH", message: "xai API error (401): unauthorized" };
308
+ const chatOptions = { provider: "xai", model: "grok-offline", sessionId: chatAgent.session.id, signal: chatSignal, messages: [] };
309
+ const chatAttempt = async () => {
310
+ await ctx.waterfall("agent/request", chatPosition, async () => ({ provider: "xai", model: "grok-offline" }));
311
+ const stream = ctx.waterfall("llm/stream", chatOptions, async function* () { yield { type: "finish", reason: { kind: "error", failure: chatFailure } }; });
312
+ for await (const chunk of stream) assert.equal(chunk.type, "finish");
313
+ return ctx.waterfall("agent/request-error", { ...chatPosition, provider: "xai", failure: chatFailure }, async () => undefined);
314
+ };
315
+ assert.deepEqual(await chatAttempt(), { kind: "retry" });
316
+ assert.equal(chatRefreshRequests, 1);
317
+ assert.equal(records.get(xaiKey).payload.refresh, "offline-chat-rotated");
318
+ assert.equal(await chatAttempt(), undefined, "a second rejection in the same step stays terminal");
319
+ assert.equal(chatRefreshRequests, 1);
320
+ assert.deepEqual(ctx.tools.schemas().map((tool) => tool.name).sort(), ["generate_image", "generate_video"]);
321
+ const assembly = await ctx.systemPrompt.assemble();
322
+ assert.ok(assembly.tools.some((tool) => tool.name === "generate_image"));
323
+
324
+ // Subscription imports use real host configuration validation, with every
325
+ // supplier request intercepted. The query key never reaches model settings.
326
+ const connected = await request('/oauth/api/connect', { provider: 'openrouter', access: 'offline-router-key', billingAccess: 'offline-billing-key', label: 'Offline account' });
327
+ assert.equal(connected.status, 200, connected.body);
328
+ const publicRows = await request('/oauth/api/providers');
329
+ assert.equal(publicRows.body.includes('offline-router-key'), false);
330
+ assert.equal(publicRows.body.includes('offline-billing-key'), false);
331
+ const routerRow = JSON.parse(publicRows.body).providers.find(row => row.id === 'openrouter');
332
+ assert.equal(routerRow.credentialConfigured, true);
333
+ assert.equal(routerRow.billingCredentialConfigured, true);
334
+ globalThis.fetch = async (url, options) => {
335
+ const target = String(url); const auth = new Headers(options.headers).get('authorization');
336
+ if (target === 'https://openrouter.ai/api/v1/models/user') {
337
+ assert.equal(auth, 'Bearer offline-router-key');
338
+ return Response.json({ data: [{ id: 'offline/rich', name: 'Offline rich model', context_length: 128000, top_provider: { max_completion_tokens: 8192 }, architecture: { input_modalities: ['text', 'image'], output_modalities: ['text'] }, supported_parameters: ['tools'] }] });
339
+ }
340
+ if (target === 'https://openrouter.ai/api/v1/key') {
341
+ assert.equal(auth, 'Bearer offline-router-key');
342
+ return Response.json({ data: { limit: 10, usage: 2, limit_remaining: 8 } });
343
+ }
344
+ assert.equal(target, 'https://openrouter.ai/api/v1/credits');
345
+ assert.equal(auth, 'Bearer offline-billing-key');
346
+ return Response.json({ data: { total_credits: 25, total_usage: 4 } });
347
+ };
348
+ const permanent = await request('/oauth/api/pull', { provider: 'openrouter', models: ['offline/rich'], expiresAt: null });
349
+ assert.equal(permanent.status, 200, permanent.body);
350
+ assert.equal(JSON.parse(permanent.body).expiresAt, null);
351
+ const importedModel = userSettings.providers.openrouter.models[0];
352
+ assert.deepEqual(importedModel.input, ['text', 'image']);
353
+ assert.equal(importedModel.contextWindow, 128000);
354
+ assert.equal(userSettings.providers.openrouter.apiKeyEnv, 'DSH_OAUTH_OPENROUTER_KEY');
355
+ assert.equal(JSON.stringify(userSettings).includes('offline-router-key'), false);
356
+ const savedRich = JSON.parse(await readFile(join(profileDirectory, 'dsh-oauth-pulls.json'), 'utf8')).pulls.openrouter.models[0];
357
+ assert.equal(savedRich.tools, true); assert.deepEqual(savedRich.output, ['text']);
358
+ assert.equal(savedRich.entitlement, 'account');
359
+ const usage = JSON.parse((await request('/oauth/api/usage', { provider: 'openrouter' })).body);
360
+ assert.equal(usage.status, 'fresh'); assert.equal(usage.snapshot.windows[0].remaining, 8);
361
+ assert.equal(usage.snapshot.balances[0].amount, 21);
362
+ assert.equal((await readFile(join(profileDirectory, 'dsh-oauth-usage.json'), 'utf8')).includes('offline-router-key'), false);
363
+ assert.equal(JSON.parse((await request('/oauth/api/providers')).body).providers.find(row => row.id === 'openrouter').pullPermanent, true);
364
+ const replace = await request('/oauth/api/connect', { provider: 'openrouter', access: 'offline-second-account' });
365
+ assert.equal(replace.status, 200, replace.body);
366
+ assert.equal(userSettings.providers.openrouter, undefined, 'changing accounts clears the old owned model route');
367
+ assert.equal(JSON.parse(await readFile(join(profileDirectory, 'dsh-oauth-usage.json'), 'utf8')).entries.openrouter, undefined);
368
+ assert.equal((await request('/oauth/api/logout', { provider: 'openrouter' })).status, 200);
369
+ assert.equal(references.has('DSH_OAUTH_OPENROUTER_KEY'), false);
370
+ assert.equal(records.has(credentialKey('dsh-oauth-connections', 'openrouter')), false);
371
+ for (const providerId of ['minimax', 'zai', 'aliyun-token-plan']) {
372
+ globalThis.fetch = async (url) => {
373
+ assert.match(new URL(url).pathname, /(?:models|token_plan[/]remains)$/);
374
+ return new Response('', { status: 404 });
375
+ };
376
+ assert.equal((await request('/oauth/api/connect', { provider: providerId, access: `offline-${providerId}`, region: 'cn' })).status, 200);
377
+ const catalog = await request('/oauth/api/models', { provider: providerId });
378
+ assert.equal(catalog.status, 200, catalog.body);
379
+ const model = JSON.parse(catalog.body).models[0];
380
+ assert.equal(model.source, 'installed-catalog'); assert.equal(model.entitlement, 'unknown');
381
+ const save = await request('/oauth/api/pull', { provider: providerId, models: [model.id], expiresAt: null });
382
+ assert.equal(save.status, 200, save.body);
383
+ assert.ok(userSettings.providers[providerId].apiKeyEnv);
384
+ if (providerId === 'minimax') assert.equal(userSettings.providers[providerId].api, 'anthropic-messages');
385
+ else assert.equal(userSettings.providers[providerId].api, 'openai-completions');
386
+ assert.equal((await request('/oauth/api/logout', { provider: providerId })).status, 200);
387
+ }
388
+
389
+ // Execute the published browser bundle's factory with its actual modules, then exercise its real SlotRegistry.
390
+ const browserModules = new Map([
391
+ ["@deepseek-ai/cordis", await load("@deepseek-ai/cordis")], ["@deepseek-ai/dsh-client-ui-slots", slotsModule],
392
+ ...await Promise.all(["react", "react-dom", "react-dom/client", "react/jsx-runtime"].map(async (name) => [name, requireRuntime(name)])),
393
+ ]);
394
+ async function browserPlugin(path) {
395
+ let descriptor;
396
+ new Function("window", await readFile(path, "utf8"))({ __ModuleLoader__: { load: (value) => { descriptor = value; } } });
397
+ assert.ok(descriptor?.factory);
398
+ if (path === join(pluginRoot, 'client.js')) assert.equal(descriptor.id, JSON.parse(await readFile(join(pluginRoot, 'package.json'), 'utf8')).name, 'client module ID must match the published package');
399
+ return descriptor.factory((name) => { assert.ok(browserModules.has(name), `missing browser module ${name}`); return browserModules.get(name); });
400
+ }
401
+ const renderer = await browserPlugin(requireRuntime.resolve("@deepseek-ai/dsh-client-ui-renderer/client"));
402
+ await ctx.plugin(renderer.SlotRegistry);
403
+ ctx.slots.register({ name: "root", children: { "settings.section": { kind: "list", scope: "root" } } }, () => null);
404
+ const client = await browserPlugin(join(pluginRoot, "client.js"));
405
+ const clientFiber = ctx.plugin(client);
406
+ await clientFiber;
407
+ const entry = ctx.slots.entries("settings.section").find((value) => value.options.id === "oauth");
408
+ assert.ok(entry, "OAuth is registered into the actual settings slot registry");
409
+ const iframe = entry.component({});
410
+ assert.equal(iframe.type, "iframe");
411
+ assert.equal(iframe.props.src, "/oauth/");
412
+ await clientFiber.dispose();
413
+ assert.equal(ctx.slots.entries("settings.section").length, 0, "unloading removes the client slot");
414
+ await fiber.dispose();
415
+ assert.equal(routes.length, 0, "unloading removes the web route");
416
+ assert.equal(ctx.tools.schemas().length, 0, "unloading removes media tools");
417
+ assert.equal(ctx.authorization?.describe(key), undefined, "unloading removes the Qwen authorization flow");
418
+ const versions = {};
419
+ for (const name of ["@deepseek-ai/cordis", "@deepseek-ai/dsh-authorization", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-client-ui-slots", "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-llm-pi-ai", "@earendil-works/pi-ai"]) {
420
+ versions[name] = JSON.parse(await readFile(join(modules, name, "package.json"), "utf8")).version;
421
+ }
422
+ const sourceSha256 = {};
423
+ const sourceFiles = ["package.json", "client.js", ...(await readdir(join(pluginRoot, "src"), { recursive: true })).filter((file) => file.endsWith(".js") && !file.endsWith(".test.js")).sort().map((file) => `src/${file}`)];
424
+ for (const file of sourceFiles) sourceSha256[file] = createHash("sha256").update(await readFile(join(pluginRoot, file))).digest("hex");
425
+ console.log(JSON.stringify({ ok: true, versions, sourceSha256, checks: ["host route", "provider listing", "DeepSeek callback metadata and attempt identity", "DeepSeek stale cancellation refusal", "DeepSeek commit before cancellation", "retired Qwen sign-in does not call upstream; existing grant can still pull and log out", "pull settings parsed by actual adapter schema", "pull persistence", "logout route restoration", "xAI defaults to loopback PKCE and preserves existing six scopes", "xAI production OIDC validation precedes the single canonical grant commit", "pending xAI login cannot silently switch methods", "explicit device fallback and cancellation preserve browser grant", "model catalog rejects future-valid token, refreshes once and retries with persisted grant", "permission denial preserves authorization without forced refresh", "public chat waterfalls persist a forced refresh before retrying", "second chat rejection in the same step does not refresh or retry again", "tool schemas", "settings slot", "unload", "subscription key and billing credential isolation", "account-filtered model capabilities and permanent settings", "quota cache without secrets", "account replacement clears old owned route and snapshot", "MiniMax/ZAI/Ali regional protocol profiles validated by real schema"], network: "mock xAI/provider fetch only, with actual loopback callback HTTP", persistentProfile: "temporary directory only" }, null, 2));
426
+ } finally {
427
+ globalThis.fetch = previousFetch;
428
+ if (previousHome === undefined) delete process.env.DSH_HOME; else process.env.DSH_HOME = previousHome;
429
+ await ctx?.fiber.dispose();
430
+ await rm(temporary, { recursive: true, force: true });
431
+ }