@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,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
+ }