@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,307 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Offline persistence smoke using real Cordis, credentials-local and pi-ai.
4
+ * No login, real profile, credential import or live request is performed.
5
+ *
6
+ * node scripts/verify-persistence.mjs --runtime /path/to/published-runtime
7
+ * If that runtime omits credentials-local, prepare an independent dependency
8
+ * directory once (VERSION must match its dsh-credentials version):
9
+ * npm install --prefix /tmp/dsh-persistence-deps --ignore-scripts --no-audit --no-fund @deepseek-ai/dsh-credentials-local@VERSION
10
+ * Then append:
11
+ * --credentials-local /tmp/dsh-persistence-deps/node_modules/@deepseek-ai/dsh-credentials-local
12
+ * The verification itself is offline. The provider is copied into a sandbox;
13
+ * selected runtime packages take precedence over supplementary dependencies.
14
+ */
15
+ import assert from "node:assert/strict";
16
+ import { execFile as execFileCallback } from "node:child_process";
17
+ import { createHash, randomUUID } from "node:crypto";
18
+ import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, symlink, writeFile } from "node:fs/promises";
19
+ import { createRequire } from "node:module";
20
+ import { tmpdir } from "node:os";
21
+ import { dirname, join, resolve } from "node:path";
22
+ import { Readable } from "node:stream";
23
+ import { fileURLToPath, pathToFileURL } from "node:url";
24
+ import { promisify } from "node:util";
25
+
26
+ const execFile = promisify(execFileCallback);
27
+ const script = fileURLToPath(import.meta.url);
28
+ const root = resolve(dirname(script), "..");
29
+ const argument = (name) => {
30
+ const index = process.argv.indexOf(name);
31
+ if (index < 0) return undefined;
32
+ if (!process.argv[index + 1] || process.argv[index + 1].startsWith("--")) throw new Error(`${name} requires a path or value`);
33
+ return process.argv[index + 1];
34
+ };
35
+ const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
36
+ const MOCK_MODELS = [{ id: "mock-persisted-model", name: "Mock persisted model", role: "chat" }];
37
+ const ORIGINAL_MODELS = [{ id: "mock-original-model", name: "Mock original model" }];
38
+ const MOCK = { initialAccess: "mock-persistence-access-initial", initialRefresh: "mock-persistence-refresh-initial", firstAccess: "mock-persistence-access-refreshed", rotatedAccess: "mock-persistence-access-rotated", rotatedRefresh: "mock-persistence-refresh-rotated" };
39
+ const RESULT_PREFIX = "DSH_PERSISTENCE_RESULT=";
40
+
41
+ if (argument("--worker")) {
42
+ await worker(argument("--worker"), resolve(argument("--sandbox")));
43
+ } else {
44
+ await orchestrate();
45
+ }
46
+
47
+ async function overlayPackages(source, destination, added) {
48
+ for (const entry of await readdir(source, { withFileTypes: true })) {
49
+ if (entry.name.startsWith(".")) continue;
50
+ if (entry.name.startsWith("@")) {
51
+ const target = join(destination, entry.name);
52
+ await mkdir(target, { recursive: true });
53
+ for (const name of await readdir(join(source, entry.name))) {
54
+ const key = `${entry.name}/${name}`;
55
+ if (added.has(key)) continue;
56
+ await symlink(await realpath(join(source, entry.name, name)), join(target, name), "dir");
57
+ added.add(key);
58
+ }
59
+ } else if (!added.has(entry.name)) {
60
+ await symlink(await realpath(join(source, entry.name)), join(destination, entry.name), "dir");
61
+ added.add(entry.name);
62
+ }
63
+ }
64
+ }
65
+
66
+ async function orchestrate() {
67
+ const runtime = resolve(argument("--runtime") ?? root);
68
+ const modules = runtime.endsWith("node_modules") ? runtime : join(runtime, "node_modules");
69
+ const selected = createRequire(join(modules, ".persistence-resolver.cjs"));
70
+ let providerRoot = argument("--credentials-local");
71
+ if (providerRoot) providerRoot = resolve(providerRoot);
72
+ else {
73
+ try { providerRoot = dirname(selected.resolve("@deepseek-ai/dsh-credentials-local/package.json")); }
74
+ catch { throw new Error("Selected runtime omits @deepseek-ai/dsh-credentials-local. Install the matching published version in an independent /tmp directory and pass --credentials-local; see this script's header."); }
75
+ }
76
+ const credentialsVersion = JSON.parse(await readFile(join(modules, "@deepseek-ai/dsh-credentials/package.json"), "utf8")).version;
77
+ const providerPackage = JSON.parse(await readFile(join(providerRoot, "package.json"), "utf8"));
78
+ assert.equal(providerPackage.name, "@deepseek-ai/dsh-credentials-local");
79
+ assert.equal(providerPackage.version, credentialsVersion, "credentials-local must match the selected runtime's credentials package");
80
+ const sandbox = await mkdtemp(join(tmpdir(), "dsh-oauth-persistence-"));
81
+ const manifest = { marker: randomUUID(), createdAt: Date.now(), runtime, credentialsVersion, thirtyDayExpiry: Date.now() + 30 * 24 * 60 * 60 * 1000 };
82
+ try {
83
+ await mkdir(join(sandbox, "modules"), { recursive: true });
84
+ const added = new Set();
85
+ await overlayPackages(modules, join(sandbox, "modules"), added);
86
+ // npm-installed supplemental dependencies supply home-paths/chokidar if the
87
+ // host-smoke runtime omitted them. They never replace a selected peer.
88
+ const supplement = join(providerRoot, "..", "..");
89
+ if (dirname(supplement).endsWith("node_modules") || supplement.endsWith("node_modules")) {
90
+ await overlayPackages(supplement, join(sandbox, "modules"), added);
91
+ }
92
+ await mkdir(join(sandbox, "provider"), { recursive: true });
93
+ for (const entry of await readdir(providerRoot)) {
94
+ if (entry === "node_modules") continue;
95
+ await cp(join(providerRoot, entry), join(sandbox, "provider", entry), { recursive: true });
96
+ }
97
+ await symlink(join(sandbox, "modules"), join(sandbox, "provider", "node_modules"), "dir");
98
+ await mkdir(join(sandbox, "plugin"), { recursive: true });
99
+ for (const path of ["src", "package.json"]) await cp(join(root, path), join(sandbox, "plugin", path), { recursive: true });
100
+ await symlink(join(sandbox, "modules"), join(sandbox, "plugin", "node_modules"), "dir");
101
+ await mkdir(join(sandbox, "home", "profiles", "offline"), { recursive: true });
102
+ await writeFile(join(sandbox, "manifest.json"), JSON.stringify(manifest), { mode: 0o600 });
103
+ const checks = [];
104
+ for (const stage of ["seed", "refresh-without-rotation", "rotate", "network-failure", "expire-pull-through-host", "final-restart"]) {
105
+ const { stdout, stderr } = await execFile(process.execPath, [script, "--worker", stage, "--sandbox", sandbox], {
106
+ cwd: sandbox, env: { ...process.env, DSH_HOME: join(sandbox, "home"), DSH_OAUTH_PERSISTENCE_MARKER: manifest.marker },
107
+ encoding: "utf8", timeout: 30000, maxBuffer: 1024 * 1024,
108
+ });
109
+ const line = stdout.split("\n").find((value) => value.startsWith(RESULT_PREFIX));
110
+ assert.ok(line, `${stage} did not return its structured result: ${stderr}`);
111
+ checks.push(JSON.parse(line.slice(RESULT_PREFIX.length)));
112
+ }
113
+ assert.equal(new Set(checks.map((check) => check.pid)).size, checks.length, "each phase must run in a separate Node process");
114
+ const versions = { credentialsLocal: providerPackage.version };
115
+ for (const name of ["@deepseek-ai/cordis", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-authorization", "@earendil-works/pi-ai"]) {
116
+ versions[name] = JSON.parse(await readFile(join(modules, name, "package.json"), "utf8")).version;
117
+ }
118
+ const sourceSha256 = {};
119
+ for (const path of ["src/grants.js", "src/pulls.js", "src/index.js", "src/routes.js", "src/request-errors.js", "src/chat-recovery.js", "src/xai-browser.js", "src/xai-login.js"]) sourceSha256[path] = digest(await readFile(join(sandbox, "plugin", path)));
120
+ let selectedRuntimeProviderSha256 = null;
121
+ try { selectedRuntimeProviderSha256 = digest(await readFile(selected.resolve("@deepseek-ai/dsh-credentials-local"))); } catch { /* The runtime may omit this optional provider. */ }
122
+ const providerSha256 = digest(await readFile(join(sandbox, "provider", "lib", "index.js")));
123
+ console.log(JSON.stringify({
124
+ verificationScriptSha256: digest(await readFile(script)),
125
+ ok: true, checkedAt: new Date().toISOString(), runtime, versions, sourceSha256,
126
+ credentialsProvider: { source: argument("--credentials-local") ? "External package directory supplied by --credentials-local; this run used a separately npm-installed published provider" : "Package resolved from selected runtime", packageRoot: providerRoot, sha256: providerSha256, versionMatchesRuntimeCredentials: true, selectedRuntimeProviderSha256, selectedRuntimeProviderHashMatches: selectedRuntimeProviderSha256 === null ? null : selectedRuntimeProviderSha256 === providerSha256, actualDesktopAppProviderExtracted: false },
127
+ checks, network: "All fetch calls are mocked and allow only the xAI refresh endpoint; no authentication or paid requests",
128
+ storage: "Real published file-backed credentials-local provider, temporary DSH_HOME, six separate Node processes; sandbox deleted after verification",
129
+ settingsBoundary: "The route-expiry phase uses the real host/pull/route components with in-memory settings; credential and pull files are real",
130
+ evidenceBoundary: "Process restarts, forced expiry and rejection-before-expiry recovery are tested. Early rejection is simulated by passing the observed rejectedGrant, not a reproduced live upstream failure. This does not prove 30 elapsed days or a real account's refresh-token lifetime.",
131
+ reproduce: { command: `node scripts/verify-persistence.mjs --runtime ${runtime} --credentials-local ${providerRoot}`, providerInstall: `npm install --prefix /tmp/dsh-persistence-deps --ignore-scripts --no-audit --no-fund @deepseek-ai/dsh-credentials-local@${credentialsVersion}` },
132
+ }, null, 2));
133
+ } finally { await rm(sandbox, { recursive: true, force: true }); }
134
+ }
135
+
136
+ async function worker(stage, sandbox) {
137
+ const manifest = JSON.parse(await readFile(join(sandbox, "manifest.json"), "utf8"));
138
+ assert.equal(manifest.marker, process.env.DSH_OAUTH_PERSISTENCE_MARKER, "workers only use this invocation's isolated sandbox");
139
+ assert.equal(process.env.DSH_HOME, join(sandbox, "home"));
140
+ const profile = join(sandbox, "home", "profiles", "offline");
141
+ const credentialsFile = join(sandbox, "home", ".credentials.yaml");
142
+ const requireRuntime = createRequire(join(sandbox, "plugin", "package.json"));
143
+ const load = (name) => import(pathToFileURL(requireRuntime.resolve(name)).href);
144
+ const [{ Context, Service }, { credentialKey }, provider, { createGrantResolver }, { createPullStore }, { createConnections, connectionRef }, { createUsageService }] = await Promise.all([
145
+ load("@deepseek-ai/cordis"), load("@deepseek-ai/dsh-credentials"), import(pathToFileURL(join(sandbox, "provider", "lib", "index.js")).href),
146
+ import(pathToFileURL(join(sandbox, "plugin", "src", "grants.js")).href), import(pathToFileURL(join(sandbox, "plugin", "src", "pulls.js")).href),
147
+ import(pathToFileURL(join(sandbox, 'plugin', 'src', 'connections.js')).href), import(pathToFileURL(join(sandbox, 'plugin', 'src', 'usage', 'index.js')).href),
148
+ ]);
149
+ const ctx = new Context();
150
+ ctx.provide("profileContext", { name: "offline", dir: profile, home: process.env.DSH_HOME, patchPath: join(profile, "cordis.patch.yml") });
151
+ let calls = 0;
152
+ globalThis.fetch = async () => { throw new Error("Unexpected network request refused by persistence smoke"); };
153
+ try {
154
+ await ctx.plugin(provider.default, { path: credentialsFile, watch: false });
155
+ const credentials = ctx.credentials;
156
+ const key = credentialKey("llm-pi-ai", "xai");
157
+ const pulls = createPullStore(profile);
158
+ const connections = createConnections(credentials);
159
+ const resolveGrant = createGrantResolver(credentials);
160
+ const result = { stage, pid: process.pid, checks: [] };
161
+ const mockRefresh = (refreshToken, response, failure = false) => {
162
+ globalThis.fetch = async (url, options) => {
163
+ calls += 1;
164
+ assert.equal(String(url), "https://auth.x.ai/oauth2/token");
165
+ assert.equal(options.method, "POST");
166
+ const form = new URLSearchParams(options.body);
167
+ assert.equal(form.get("grant_type"), "refresh_token");
168
+ assert.equal(form.get("client_id"), "b1a00492-073a-47ea-816f-4c329264a828");
169
+ assert.equal(form.get("refresh_token"), refreshToken);
170
+ if (failure) throw new TypeError("mock temporary network failure");
171
+ return new Response(JSON.stringify(response), { headers: { "content-type": "application/json" } });
172
+ };
173
+ };
174
+ if (stage === "seed") {
175
+ assert.equal(await credentials.readRecord(key), undefined);
176
+ await credentials.modifyRecord(key, async () => ({ kind: "grant", payload: { type: "oauth", access: MOCK.initialAccess, refresh: MOCK.initialRefresh, expires: Date.now() - 1000 } }));
177
+ await pulls.write("xai", { models: MOCK_MODELS, media: [], expiresAt: manifest.thirtyDayExpiry, route: { edits: [{ path: ["providers", "xai", "models"], written: MOCK_MODELS, before: ORIGINAL_MODELS }] } });
178
+ assert.equal((await stat(credentialsFile)).mode & 0o777, 0o600);
179
+ assert.equal((await pulls.read("xai")).expiresAt, manifest.thirtyDayExpiry);
180
+ result.checks.push("mock OAuth grant written through real file provider", "30-day pull written in isolated profile", "credential file mode is 0600");
181
+ await connections.connect('openrouter', { access: 'offline-persistent-key', billingAccess: 'offline-persistent-billing', label: 'Offline saved account' });
182
+ await pulls.write('openrouter', { models: [{ id: 'offline/rich', name: 'Offline', role: 'chat', input: ['text', 'image'], output: ['text'], tools: true, reasoningEfforts: { high: 'high' }, contextWindow: 128000, maxTokens: 8192, source: 'account', entitlement: 'account' }], media: [], expiresAt: null });
183
+ const usage = createUsageService({ directory: profile, contextFor: async () => ({ access: 'offline-persistent-key', rawGrant: { access: 'offline-persistent-key' }, connection: await connections.read('openrouter') }), reader: async () => ({ windows: [{ id: 'budget', unit: 'money', used: 2, limit: 10, remaining: 8 }], balances: [] }) });
184
+ assert.equal((await usage.get('openrouter')).status, 'fresh');
185
+ result.checks.push('subscription call and billing credentials stored by real credential provider', 'permanent model capabilities and real-source quota snapshot persisted');
186
+ } else if (stage === "refresh-without-rotation") {
187
+ const stored = await credentials.readRecord(key);
188
+ assert.equal(stored.payload.access, MOCK.initialAccess);
189
+ assert.equal(stored.payload.refresh, MOCK.initialRefresh);
190
+ assert.equal((await pulls.read("xai")).expiresAt, manifest.thirtyDayExpiry);
191
+ mockRefresh(MOCK.initialRefresh, { access_token: MOCK.firstAccess, expires_in: 3600 });
192
+ const renewed = await resolveGrant("xai");
193
+ assert.equal(renewed.access, MOCK.firstAccess);
194
+ assert.equal(renewed.refresh, MOCK.initialRefresh);
195
+ assert.ok(renewed.expires > Date.now());
196
+ assert.equal((await credentials.readRecord(key)).payload.refresh, MOCK.initialRefresh);
197
+ assert.equal(calls, 1);
198
+ result.checks.push("new process reads prior grant and 30-day pull", "real pi xAI refresh protocol used with fetch mock", "omitted refresh_token preserves prior refresh token");
199
+ } else if (stage === "rotate") {
200
+ const stored = await credentials.readRecord(key);
201
+ assert.equal(stored.payload.access, MOCK.firstAccess);
202
+ assert.equal(stored.payload.refresh, MOCK.initialRefresh);
203
+ assert.ok(stored.payload.expires > Date.now() + 20 * 60 * 1000, "stored access is still locally valid before forced recovery");
204
+ const observedGrant = await resolveGrant("xai");
205
+ assert.equal(observedGrant.access, MOCK.firstAccess);
206
+ assert.equal(calls, 0, "ordinary resolution must not refresh a future-expiry access token");
207
+ mockRefresh(MOCK.initialRefresh, { access_token: MOCK.rotatedAccess, refresh_token: MOCK.rotatedRefresh, expires_in: 3600 });
208
+ const renewed = await resolveGrant("xai", { rejectedGrant: observedGrant });
209
+ assert.equal(renewed.access, MOCK.rotatedAccess);
210
+ assert.equal(renewed.refresh, MOCK.rotatedRefresh);
211
+ assert.equal(calls, 1, "observed upstream rejection forces refresh even before local expiry");
212
+ const recoveredFromStaleSnapshot = await resolveGrant("xai", { rejectedGrant: observedGrant });
213
+ assert.equal(recoveredFromStaleSnapshot.access, MOCK.rotatedAccess);
214
+ assert.equal(recoveredFromStaleSnapshot.refresh, MOCK.rotatedRefresh);
215
+ assert.equal(calls, 1, "a late rejection of the old snapshot reuses the already refreshed token");
216
+ result.checks.push("new process reads previous refreshed access with future expiry", "ordinary resolution sends no refresh request before expiry", "observed rejectedGrant forces real pi refresh protocol before advertised expiry", "rotating refresh response is committed through real file provider", "a stale rejected snapshot reuses the newer saved token without a second refresh");
217
+ } else if (stage === "network-failure") {
218
+ const stored = await credentials.readRecord(key);
219
+ assert.equal(stored.payload.access, MOCK.rotatedAccess);
220
+ assert.equal(stored.payload.refresh, MOCK.rotatedRefresh);
221
+ await credentials.modifyRecord(key, async (current) => ({ ...current, payload: { ...current.payload, expires: Date.now() - 1000 } }));
222
+ const before = await credentials.readRecord(key);
223
+ const bytesBefore = await readFile(credentialsFile);
224
+ mockRefresh(MOCK.rotatedRefresh, undefined, true);
225
+ await assert.rejects(resolveGrant("xai"));
226
+ assert.deepEqual(await credentials.readRecord(key), before);
227
+ assert.equal(digest(await readFile(credentialsFile)), digest(bytesBefore));
228
+ assert.equal((await pulls.read("xai")).expiresAt, manifest.thirtyDayExpiry);
229
+ assert.equal(calls, 1);
230
+ result.checks.push("new process reads rotated refresh token", "temporary refresh network failure leaves record and credential file unchanged", "30-day pull remains unchanged");
231
+ } else if (stage === "expire-pull-through-host") {
232
+ const before = await credentials.readRecord(key);
233
+ assert.equal(before.payload.refresh, MOCK.rotatedRefresh);
234
+ assert.equal((await pulls.read("xai")).expiresAt, manifest.thirtyDayExpiry);
235
+ const previous = await pulls.read("xai");
236
+ await pulls.write("xai", { ...previous, expiresAt: Date.now() - 1000 });
237
+ let settings = { providers: { xai: { models: MOCK_MODELS } } };
238
+ let revision = 0;
239
+ const routes = [];
240
+ class MemorySettings extends Service {
241
+ constructor(context) { super(context, "settings"); }
242
+ describe() { return [{ ns: "llm-pi-ai", user: structuredClone(settings), value: structuredClone(settings), revision }]; }
243
+ async mutate(namespace, operations, expectedRevision) {
244
+ assert.equal(namespace, "llm-pi-ai"); assert.equal(expectedRevision, revision);
245
+ for (const operation of operations) {
246
+ let object = settings;
247
+ for (const segment of operation.path.slice(0, -1)) object = object[segment] ??= {};
248
+ if (operation.op === "unset") delete object[operation.path.at(-1)]; else object[operation.path.at(-1)] = structuredClone(operation.value);
249
+ }
250
+ revision += 1;
251
+ }
252
+ }
253
+ class MemoryWebServer extends Service {
254
+ constructor(context) { super(context, "webServer"); }
255
+ register(route) { routes.push(route); return () => {}; }
256
+ }
257
+ await ctx.plugin(MemorySettings); await ctx.plugin(MemoryWebServer);
258
+ const { default: AuthorizationService } = await load("@deepseek-ai/dsh-authorization");
259
+ await ctx.plugin(AuthorizationService);
260
+ ctx.authorization.registerFlow({ key, label: "Mock xAI", methods: [{ id: "oauth", label: "Mock OAuth" }], async run() { throw new Error("Smoke must not initiate authentication"); } });
261
+ const host = await import(pathToFileURL(join(sandbox, "plugin", "src", "index.js")).href);
262
+ await ctx.plugin(host);
263
+ const route = routes.find((entry) => entry.path === "/oauth");
264
+ assert.ok(route);
265
+ // Startup maintenance runs asynchronously. Wait only for this temporary
266
+ // pull's cleanup, then check the public provider endpoint as well.
267
+ const deadline = Date.now() + 2000;
268
+ while (await pulls.read("xai")) {
269
+ assert.ok(Date.now() < deadline, "host did not clean expired pull");
270
+ await new Promise((resolveWait) => setTimeout(resolveWait, 10));
271
+ }
272
+ const req = Readable.from([]);
273
+ Object.assign(req, { method: "GET", url: "/oauth/api/providers", headers: { host: "127.0.0.1:19387" } });
274
+ const response = { status: 0, body: "", writeHead(code) { this.status = code; }, end(body) { this.body = String(body ?? ""); } };
275
+ await route.handler(req, response);
276
+ assert.equal(response.status, 200);
277
+ const row = JSON.parse(response.body).providers.find((entry) => entry.id === "xai");
278
+ assert.equal(row.loggedIn, true);
279
+ assert.equal(row.pullExpiresAt, null);
280
+ assert.deepEqual(settings.providers.xai.models, ORIGINAL_MODELS);
281
+ assert.deepEqual(await credentials.readRecord(key), before);
282
+ assert.equal(calls, 0);
283
+ result.checks.push("real host restores only expired pull's owned route edits", "expired pull removed while OAuth grant stays byte-equivalent", "provider endpoint still reports configured grant after route expiry");
284
+ } else if (stage === "final-restart") {
285
+ const stored = await credentials.readRecord(key);
286
+ assert.equal(stored.payload.access, MOCK.rotatedAccess);
287
+ assert.equal(stored.payload.refresh, MOCK.rotatedRefresh);
288
+ assert.equal(await pulls.read("xai"), undefined);
289
+ result.checks.push("final independent process reads surviving rotated grant", "pull expiry cleanup persists across restart");
290
+ } else throw new Error(`Unknown worker stage: ${stage}`);
291
+ if (stage !== 'seed') {
292
+ const connection = await connections.read('openrouter');
293
+ assert.equal(connection.access, 'offline-persistent-key');
294
+ assert.equal(connection.billingAccess, 'offline-persistent-billing');
295
+ assert.equal((await credentials.resolve(connectionRef('openrouter'))).value, 'offline-persistent-key');
296
+ const permanent = await pulls.read('openrouter');
297
+ assert.equal(permanent.expiresAt, null); assert.equal(permanent.models[0].tools, true);
298
+ assert.deepEqual(permanent.models[0].input, ['text', 'image']); assert.deepEqual(permanent.models[0].reasoningEfforts, { high: 'high' });
299
+ assert.equal((await readFile(join(profile, 'dsh-oauth-pulls.json'), 'utf8')).includes('offline-persistent-key'), false);
300
+ const quota = await readFile(join(profile, 'dsh-oauth-usage.json'), 'utf8');
301
+ assert.equal(quota.includes('offline-persistent-key'), false); assert.equal(JSON.parse(quota).entries.openrouter.result.snapshot.windows[0].remaining, 8);
302
+ result.checks.push('independent process retains permanent subscription models, capabilities, scoped credentials and quota observation without leaking secrets into JSON');
303
+ }
304
+ result.mockRefreshRequests = calls;
305
+ console.log(RESULT_PREFIX + JSON.stringify(result));
306
+ } finally { await ctx.fiber.dispose(); }
307
+ }
@@ -0,0 +1,304 @@
1
+ /** Subscription UI acceptance against local mocks. Never contacts a provider or reads credentials. */
2
+ import assert from 'node:assert/strict';
3
+ import { createServer } from 'node:http';
4
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
+ import { createRequire } from 'node:module';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, join, resolve } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ const require = createRequire(import.meta.url);
10
+ let playwright;
11
+ try { playwright = require('playwright'); }
12
+ catch { playwright = require(process.env.DSH_PLAYWRIGHT_MODULE || join(homedir(), '.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright')); }
13
+ const root = dirname(dirname(fileURLToPath(import.meta.url)));
14
+ const outArg = process.argv.indexOf('--out-dir');
15
+ const outDir = resolve(outArg >= 0 ? process.argv[outArg + 1] : join(root, 'artifacts/subscriptions-ui'));
16
+ await mkdir(outDir, { recursive: true });
17
+ const completed = [], pageErrors = [], blockedRequests = [], calls = [];
18
+ let usageMode = 'fresh', lateUsage, releaseLate;
19
+ const providers = [
20
+ { id: 'google-antigravity', name: 'Google Antigravity', flow: 'pkce', authMethods: ['oauth'], usageSupported: true, loggedIn: true, pullable: false, supportReason: 'host-oauth-model-integration-unavailable', pulledModels: [] },
21
+ { id: 'qwen', name: 'Qwen CLI', flow: 'device_code', authMethods: ['oauth'], usageSupported: false, loggedIn: true, pullable: true, pulledModels: [] },
22
+ { id: 'new-api', name: 'New API', flow: 'key', authMethods: ['key'], keyConnect: true, usageSupported: true, loggedIn: false, pulledModels: [] },
23
+ { id: 'zenmux', name: 'ZenMux', flow: 'key', authMethods: ['key'], keyConnect: true, usageSupported: true, loggedIn: false, pulledModels: [] },
24
+ { id: 'openai-codex', name: 'ChatGPT / Codex', flow: 'pkce', authMethods: ['oauth', 'local'], usageSupported: true, loggedIn: true, tokenPreview: 'DO-NOT-DISPLAY-TOKEN', pulledModels: [] },
25
+ { id: 'anthropic', name: 'Claude Pro/Max', flow: 'pkce', authMethods: ['oauth'], usageSupported: true, loggedIn: false, pullable: false },
26
+ ];
27
+ const models = [{ id: 'mock-model', name: 'Mock <img src=x onerror=alert(1)>', role: 'chat', input: ['text', 'image'], output: ['text'], tools: true, contextWindow: 200000, maxTokens: 32000, reasoningEfforts: { low: 'low', high: 'high' }, source: 'public-catalog', entitlement: 'unknown' }, { id: 'mock-image', name: 'Image model', role: 'image', input: ['text'], output: ['image'], source: 'account', entitlement: 'account' }];
28
+ const snapshot = { plan: { name: 'Mock subscription', renewsAt: '2026-12-01T00:00:00Z' }, source: 'provider-api', observedAt: '2026-11-16T12:00:00Z', windows: [
29
+ { id: 'five-hour', label: 'Five-hour window', unit: 'percent', usedPercent: 25, resetAt: '2026-11-16T17:00:00Z', scope: 'account' },
30
+ { id: 'monthly', label: 'Monthly cap', unit: 'credits', limit: '500', scope: 'account', nextRegenAt: '2026-11-17T00:00:00Z', nextRegenPercent: 10 },
31
+ ], balances: [{ id: 'payg', label: 'PAYG', amount: '-2.5', currency: 'USD', unit: 'money' }], notes: [] };
32
+ let auth = { attemptId: 'mock-attempt', status: 'pending', prompt: { id: 'code', kind: 'text', message: 'Paste authorization code', placeholder: 'code' } };
33
+ const server = createServer(async (req, res) => {
34
+ const pathname = new URL(req.url, 'http://localhost').pathname;
35
+ const json = (body, status = 200) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };
36
+ try {
37
+ if (pathname.startsWith('/oauth/api/')) {
38
+ const chunks = []; for await (const chunk of req) chunks.push(chunk);
39
+ const raw = Buffer.concat(chunks).toString(); const body = raw ? JSON.parse(raw) : {};
40
+ calls.push({ pathname, body });
41
+ if (pathname.endsWith('/providers')) return json({ providers });
42
+ if (pathname.endsWith('/connect') || pathname.endsWith('/connection')) {
43
+ const item = providers.find((item) => item.id === body.provider);
44
+ assert.ok(item);
45
+ item.loggedIn = true; item.credentialConfigured = true;
46
+ if (body.billingAccess) item.billingCredentialConfigured = true;
47
+ item.connection = { ...item.connection, ...Object.fromEntries(Object.entries(body).filter(([key]) => !['provider', 'access', 'billingAccess'].includes(key))) };
48
+ return json({ ok: true });
49
+ }
50
+ if (pathname.endsWith('/models')) return json({ models });
51
+ if (pathname.endsWith('/pull')) {
52
+ const item = providers.find((item) => item.id === body.provider);
53
+ item.pulledModels = models.filter((item) => body.models.includes(item.id));
54
+ item.pullPermanent = body.expiresAt === null; item.pullExpiresAt = body.expiresAt;
55
+ return json({ models: item.pulledModels });
56
+ }
57
+ if (pathname.endsWith('/usage')) {
58
+ if (usageMode === 'failure') return json({ error: 'Mock usage service offline' }, 503);
59
+ if (usageMode === 'late') { lateUsage?.(); await new Promise((resolve) => { releaseLate = resolve; }); }
60
+ if (['needs-permission', 'needs-configuration', 'rate-limited', 'reauth-required'].includes(usageMode)) return json({ status: usageMode, message: 'Management key required', lastAttemptAt: new Date().toISOString() });
61
+ return json({ status: usageMode === 'partial' ? 'partial' : 'fresh', snapshot, lastAttemptAt: new Date().toISOString() });
62
+ }
63
+ if (pathname.endsWith('/import/sources')) return json({ sources: [{ id: 'codex', label: 'Codex CLI', available: true, providers: [{ provider: 'openai-codex', authType: 'oauth', available: true }] }, { id: 'opencode', label: 'OpenCode', available: false, providers: [{ provider: 'openai-codex', authType: 'oauth', available: false }] }] });
64
+ if (pathname.endsWith('/import')) return json({ ok: true });
65
+ if (pathname.endsWith('/logout')) { providers.find((item) => item.id === body.provider).loggedIn = false; return json({ ok: true }); }
66
+ if (pathname.endsWith('/login')) return json(auth);
67
+ if (pathname.endsWith('/login/status')) return json(auth);
68
+ if (pathname.endsWith('/login/answer')) { assert.equal(body.value, 'mock-authorization-input'); providers.find((item) => item.id === body.provider).loggedIn = true; auth = { attemptId: 'mock-attempt', status: 'authorized' }; return json(auth); }
69
+ if (pathname.endsWith('/login/cancel')) { auth = { ...auth, status: 'cancelled' }; return json(auth); }
70
+ return json({ error: 'Unexpected mock API route' }, 404);
71
+ }
72
+ const name = pathname.replace(/^\/oauth\/?|^\//, '') || 'index.html';
73
+ if (!['index.html', 'app.js', 'styles.css', 'providers.js', 'theme.js', 'auth.html'].includes(name)) { res.writeHead(404); res.end(); return; }
74
+ res.writeHead(200, { 'content-type': name.endsWith('.html') ? 'text/html' : name.endsWith('.css') ? 'text/css' : 'text/javascript' });
75
+ res.end(await readFile(join(root, name)));
76
+ } catch (error) { json({ error: error.message }, 500); }
77
+ });
78
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
79
+ const origin = `http://127.0.0.1:${server.address().port}`;
80
+ const browser = await playwright.chromium.launch({ headless: true });
81
+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, reducedMotion: 'reduce' });
82
+ await context.route('**/*', (route) => {
83
+ if (route.request().url().startsWith(origin)) return route.continue();
84
+ blockedRequests.push(route.request().url()); return route.abort();
85
+ });
86
+ context.on('page', (page) => page.on('pageerror', (error) => pageErrors.push(error.message)));
87
+ const page = await context.newPage();
88
+ page.setDefaultTimeout(7000);
89
+ const row = (id) => page.locator(`[data-provider="${id}"]`);
90
+ try {
91
+ await page.goto(`${origin}/oauth/`);
92
+ await row('zenmux').getByRole('button', { name: '连接密钥', exact: true }).waitFor();
93
+ assert.equal(await page.locator('.nav').isVisible(), true);
94
+ assert.equal(await page.getByText('DO-NOT-DISPLAY-TOKEN').count(), 0);
95
+ assert.equal(calls.filter((item) => item.pathname.endsWith('/usage')).length, 0);
96
+ completed.push('Original sidebar and rows retained; credentials hidden; no automatic quota calls');
97
+ assert.equal(await row('google-antigravity').getByRole('button', { name: '拉取模型', exact: true }).count(), 0);
98
+ await row('google-antigravity').getByText('可查询套餐用量;当前宿主尚未接入此来源的模型调用。', { exact: true }).waitFor();
99
+ await row('qwen').getByRole('button', { name: '套餐与用量', exact: true }).click();
100
+ await row('qwen').getByText('此来源暂不提供用量', { exact: true }).waitFor();
101
+ assert.equal(calls.filter((item) => item.pathname.endsWith('/usage')).length, 0);
102
+ completed.push('Google usage-only integration does not promise model access; unsupported usage makes no API request');
103
+
104
+ await row('zenmux').getByRole('button', { name: '连接密钥', exact: true }).click();
105
+ await page.locator('#connection-access').fill('mock-inference-secret');
106
+ await page.locator('#connection-billing').fill('mock-management-secret');
107
+ await page.locator('#connection-label').fill('My subscription');
108
+ assert.equal(await page.locator('#connection-access').getAttribute('type'), 'password');
109
+ await page.locator('[data-modal-locale]').selectOption('en');
110
+ assert.equal(await page.locator('#connection-access').inputValue(), 'mock-inference-secret');
111
+ assert.equal(await page.locator('#connection-label').inputValue(), 'My subscription');
112
+ assert.ok(!(await page.evaluate(() => JSON.stringify(localStorage))).includes('mock-inference-secret'));
113
+ await page.getByRole('button', { name: 'Save and connect', exact: true }).click();
114
+ await row('zenmux').getByText('Connected', { exact: true }).waitFor();
115
+ assert.equal(calls.find((item) => item.pathname.endsWith('/connect')).body.billingAccess, 'mock-management-secret');
116
+ assert.equal(await page.locator('#connection-access').count(), 0);
117
+ completed.push('Key connection and distinct billing credential; locale preserves draft without persistence');
118
+
119
+ await row('zenmux').getByRole('button', { name: 'Connection settings', exact: true }).click();
120
+ assert.equal(await page.locator('#connection-access').count(), 0);
121
+ assert.equal(await page.locator('#connection-billing').inputValue(), '');
122
+ await page.getByRole('button', { name: 'Save settings', exact: true }).click();
123
+ await page.locator('#modal').waitFor({ state: 'hidden' });
124
+ assert.deepEqual(calls.find((item) => item.pathname.endsWith('/connection')).body, { provider: 'zenmux' });
125
+ completed.push('Saved authorization never echoed; blank billing field retains existing credential');
126
+ for (const region of ['cn', 'global']) {
127
+ await row('zenmux').getByRole('button', { name: 'Connection settings', exact: true }).click();
128
+ if (!(await page.locator('#connection-region').isVisible())) await page.locator('.scope-fields summary').click();
129
+ await page.locator('#connection-region').selectOption(region);
130
+ await page.getByRole('button', { name: 'Save settings', exact: true }).click();
131
+ await page.locator('#modal').waitFor({ state: 'hidden' });
132
+ assert.equal(calls.filter((item) => item.pathname.endsWith('/connection')).at(-1).body.region, region);
133
+ }
134
+ completed.push('Region changes use global/cn and can return to the global default without sending an empty region');
135
+
136
+ await row('zenmux').getByRole('button', { name: 'Fetch models', exact: true }).click();
137
+ await page.locator('.model-capabilities').getByText(/Tools supported/).waitFor();
138
+ await page.locator('.model-capabilities').getByText(/Reasoning: low \/ high/).waitFor();
139
+ await page.locator('.model-capabilities').getByText(/Plan entitlement unconfirmed/).waitFor();
140
+ assert.equal(await page.locator('#modal img').count(), 0);
141
+ assert.equal(await page.locator('#pull-permanent').isChecked(), true);
142
+ await page.getByRole('button', { name: 'Select all / clear', exact: true }).click();
143
+ assert.equal(await page.locator('.choice input').isChecked(), false);
144
+ await page.getByRole('button', { name: 'Save selected models', exact: true }).click();
145
+ await page.getByText('Select at least one chat model.', { exact: true }).waitFor();
146
+ await page.getByRole('button', { name: 'Select all / clear', exact: true }).click();
147
+ models[0].name = 'Mock reasoning model';
148
+ await page.getByRole('button', { name: 'Save selected models', exact: true }).click();
149
+ await row('zenmux').getByText('Models stay enabled', { exact: true }).waitFor();
150
+ assert.equal(calls.find((item) => item.pathname.endsWith('/pull')).body.expiresAt, null);
151
+ completed.push('Capabilities and entitlement provenance; malicious model name escaped; single-model selection; permanent default');
152
+
153
+ await row('zenmux').getByRole('button', { name: 'Fetch models', exact: true }).click();
154
+ await page.locator('#pull-title').waitFor();
155
+ await page.locator('#toast').waitFor({ state: 'hidden', timeout: 4000 });
156
+ await page.screenshot({ path: join(outDir, 'models-en.png') });
157
+ await page.locator('#pull-until').check();
158
+ await page.locator('#pull-expiry').fill('2030-01-01T12:00');
159
+ await page.getByRole('button', { name: 'Save selected models', exact: true }).click();
160
+ await page.getByText('Choose an expiry date within the next 366 days.', { exact: true }).waitFor();
161
+ await page.getByRole('button', { name: '7 days', exact: true }).click();
162
+ assert.equal(await page.locator('#pull-until').isChecked(), true);
163
+ await page.locator('[data-modal-locale]').selectOption('zh');
164
+ assert.equal(await page.locator('#pull-until').isChecked(), true);
165
+ assert.equal(await page.locator('.choice input').isChecked(), true);
166
+ await page.getByRole('button', { name: '写入所选模型', exact: true }).click();
167
+ await page.locator('#modal').waitFor({ state: 'hidden' });
168
+ assert.ok(calls.filter((item) => item.pathname.endsWith('/pull')).at(-1).body.expiresAt > Date.now());
169
+ await row('zenmux').getByRole('button', { name: '拉取模型', exact: true }).click();
170
+ assert.equal(await page.locator('#pull-until').isChecked(), true);
171
+ await page.keyboard.press('Escape');
172
+ completed.push('Optional expiry remains selectable, survives locale change and reopening');
173
+
174
+ await row('zenmux').getByRole('button', { name: '套餐与用量', exact: true }).click();
175
+ await row('zenmux').getByText('Mock subscription', { exact: true }).waitFor();
176
+ assert.equal(await row('zenmux').getByRole('meter').count(), 1);
177
+ await row('zenmux').getByText('用量比例未知', { exact: true }).waitFor();
178
+ await row('zenmux').getByText('-2.5 USD', { exact: false }).waitFor();
179
+ await row('zenmux').getByText(/下次部分恢复/).waitFor();
180
+ await row('zenmux').getByText(/provider-api/).waitFor();
181
+ completed.push('Real quota windows, unknown percentages, signed balances, partial recovery and timestamp/source');
182
+
183
+ usageMode = 'failure';
184
+ await row('zenmux').getByRole('button', { name: '刷新用量', exact: true }).click();
185
+ await row('zenmux').getByText('上次成功数据 · 本次更新失败', { exact: true }).waitFor();
186
+ assert.equal(await row('zenmux').getByRole('meter').count(), 1);
187
+ completed.push('Transient usage failure preserves a clearly stale last-good snapshot');
188
+ await page.locator('#toast').waitFor({ state: 'hidden', timeout: 4000 });
189
+ await page.screenshot({ path: join(outDir, 'subscriptions-zh-desktop.png'), fullPage: true });
190
+
191
+ usageMode = 'needs-permission';
192
+ await row('zenmux').getByRole('button', { name: '刷新用量', exact: true }).click();
193
+ await row('zenmux').getByText('需要查询权限', { exact: true }).waitFor();
194
+ assert.equal(await row('zenmux').getByRole('meter').count(), 0);
195
+ assert.equal(await row('zenmux').getByText('已连接', { exact: true }).count(), 1);
196
+ completed.push('Usage permission failure does not claim disconnected or exhausted');
197
+ usageMode = 'needs-configuration';
198
+ await row('zenmux').getByRole('button', { name: '刷新用量', exact: true }).click();
199
+ await row('zenmux').getByText('需要补充查询配置', { exact: true }).waitFor();
200
+ await row('zenmux').getByText(/请在「连接配置」中补充查询授权/).waitFor();
201
+ assert.equal(await row('zenmux').getByRole('meter').count(), 0);
202
+ usageMode = 'partial';
203
+ snapshot.notes = ['subscription-split-and-reset-not-provided'];
204
+ await row('zenmux').getByRole('button', { name: '刷新用量', exact: true }).click();
205
+ await row('zenmux').getByText('部分数据可用', { exact: true }).waitFor();
206
+ await row('zenmux').getByText('未提供订阅与充值分项或重置时间。', { exact: true }).waitFor();
207
+ assert.equal(await row('zenmux').getByRole('meter').count(), 1);
208
+ snapshot.notes = [];
209
+ completed.push('Missing query configuration remains actionable; partial quota data retains known values and translated limitations');
210
+
211
+ await row('openai-codex').getByRole('button', { name: '连接配置', exact: true }).click();
212
+ await page.getByRole('button', { name: '改用本机 CLI 管理的授权', exact: true }).click();
213
+ await page.getByText('Codex CLI', { exact: true }).waitFor();
214
+ assert.equal(await page.locator('input[name="source"][value="opencode"]').isDisabled(), true);
215
+ await page.locator('input[name="source"][value="codex"]').check();
216
+ await page.getByRole('button', { name: '确认复用此来源', exact: true }).click();
217
+ await page.locator('#modal').waitFor({ state: 'hidden' });
218
+ assert.deepEqual(calls.find((item) => item.pathname.endsWith('/import')).body, { source: 'codex', provider: 'openai-codex' });
219
+ completed.push('Fixed local CLI sources reflect actual availability and selected provider');
220
+
221
+ await row('anthropic').getByRole('button', { name: '登录', exact: true }).click();
222
+ await page.locator('#authorization-answer').fill('mock-authorization-input');
223
+ await page.locator('[data-modal-locale]').selectOption('en');
224
+ assert.equal(await page.locator('#authorization-answer').inputValue(), 'mock-authorization-input');
225
+ await page.getByRole('button', { name: 'Submit authorization input', exact: true }).click();
226
+ await row('anthropic').getByText('Connected', { exact: true }).waitFor();
227
+ completed.push('Existing OAuth manual-input flow survives locale switch and confirms local credentials');
228
+
229
+ usageMode = 'fresh';
230
+ await row('zenmux').getByRole('button', { name: 'Refresh usage', exact: true }).click();
231
+ await row('zenmux').getByText('Updated', { exact: true }).waitFor();
232
+ await page.locator('#toast').waitFor({ state: 'hidden', timeout: 4000 });
233
+ await page.screenshot({ path: join(outDir, 'subscriptions-en-desktop.png'), fullPage: true });
234
+ for (const width of [390, 320]) {
235
+ await page.setViewportSize({ width, height: 844 });
236
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true);
237
+ await row('zenmux').getByRole('button', { name: 'Connection settings', exact: true }).click();
238
+ await page.keyboard.press('Tab');
239
+ assert.equal(await page.evaluate(() => document.querySelector('#modal').contains(document.activeElement)), true);
240
+ for (let i = 0; i < 14; i++) await page.keyboard.press('Tab');
241
+ assert.equal(await page.evaluate(() => document.querySelector('#modal').contains(document.activeElement)), true);
242
+ await page.screenshot({ path: join(outDir, `connection-en-${width}.png`) });
243
+ await page.keyboard.press('Escape');
244
+ assert.equal(await page.locator('#modal').isHidden(), true);
245
+ await page.screenshot({ path: join(outDir, `subscriptions-en-${width}.png`), fullPage: true });
246
+ }
247
+ await page.locator('#locale').selectOption('zh');
248
+ await page.setViewportSize({ width: 390, height: 844 });
249
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true);
250
+ await page.screenshot({ path: join(outDir, 'subscriptions-zh-390.png'), fullPage: true });
251
+ await row('zenmux').getByRole('button', { name: '连接配置', exact: true }).click();
252
+ await page.screenshot({ path: join(outDir, 'connection-zh-390.png') });
253
+ await page.keyboard.press('Escape');
254
+ await page.locator('#locale').selectOption('en');
255
+ completed.push('390px and 320px layouts in both locales; modal focus trap, Escape and reduced-motion environment');
256
+
257
+ await page.reload();
258
+ await page.getByText('OAuth authentication', { exact: true }).waitFor();
259
+ assert.equal(await page.locator('#locale').inputValue(), 'en');
260
+ completed.push('Locale preference persists independently of authorization');
261
+
262
+ await row('new-api').getByRole('button', { name: 'Connect key', exact: true }).click();
263
+ await page.locator('#connection-access').fill('mock-custom-gateway-key');
264
+ await page.locator('#connection-baseURL').fill('http://api.example.test/v1');
265
+ await page.getByRole('button', { name: 'Save and connect', exact: true }).click();
266
+ await page.getByText('Enter an HTTPS API URL without credentials, query parameters or a fragment.', { exact: true }).waitFor();
267
+ await page.locator('#connection-baseURL').fill('https://api.example.test/v1');
268
+ await page.getByRole('button', { name: 'Save and connect', exact: true }).click();
269
+ await row('new-api').getByText('Connected', { exact: true }).waitFor();
270
+ assert.equal(calls.filter((call) => call.pathname.endsWith('/connect')).at(-1).body.baseURL, 'https://api.example.test/v1');
271
+ completed.push('New API requires explicit HTTPS API root and stores it only for that provider');
272
+
273
+ const startPage = await context.newPage();
274
+ await startPage.goto(`${origin}/oauth/auth.html?provider=anthropic&locale=en`);
275
+ await startPage.getByText('Starting Claude Pro/Max sign-in', { exact: true }).waitFor();
276
+ await startPage.close();
277
+ completed.push('Authorization startup page follows selected locale');
278
+
279
+ await page.setViewportSize({ width: 1280, height: 900 });
280
+ usageMode = 'late';
281
+ const waiting = new Promise((resolve) => { lateUsage = resolve; });
282
+ await row('zenmux').getByRole('button', { name: 'Plan & usage', exact: true }).click();
283
+ await waiting;
284
+ await row('zenmux').getByRole('button', { name: 'Disconnect', exact: true }).click();
285
+ await page.getByText(/same shared credential/).waitFor();
286
+ await page.locator('#confirm-disconnect').click();
287
+ await row('zenmux').getByRole('button', { name: 'Connect key', exact: true }).waitFor();
288
+ releaseLate();
289
+ await page.waitForTimeout(120);
290
+ assert.equal(await row('zenmux').locator('[data-usage-panel]').count(), 0);
291
+ completed.push('Late quota response cannot restore data after disconnect; shared credential impact is explicit');
292
+
293
+ const stored = await page.evaluate(() => JSON.stringify(localStorage));
294
+ assert.ok(!stored.includes('mock-management-secret') && !stored.includes('mock-inference-secret'));
295
+ assert.ok(!calls.some((call) => /chat\/completions|generate|messages/.test(call.pathname)));
296
+ assert.deepEqual(pageErrors, []);
297
+ assert.deepEqual(blockedRequests, []);
298
+ completed.push('No credential persistence in browser, no inference requests, no browser errors or external network');
299
+ await writeFile(join(outDir, 'report.json'), JSON.stringify({ passed: completed.length, completed, pageErrors, blockedRequests, endpoints: [...new Set(calls.map((call) => call.pathname))] }, null, 2));
300
+ process.stdout.write(JSON.stringify({ passed: completed.length, outDir, completed }, null, 2) + '\n');
301
+ } finally {
302
+ releaseLate?.();
303
+ await context.close(); await browser.close(); await new Promise((resolve) => server.close(resolve));
304
+ }