@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,261 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { registerChatRecovery } from "./chat-recovery.js";
4
+ import { createGrantResolver } from "./grants.js";
5
+
6
+ const grant = (access = "offline-access") => ({ type: "oauth", access, refresh: "offline-refresh", expires: Date.now() + 3600000 });
7
+ const chunks = async function* () { yield { type: "finish", reason: { kind: "stop" } }; };
8
+ const collect = async (stream) => { const result = []; for await (const chunk of stream) result.push(chunk); return result; };
9
+
10
+ /** Public event handler harness; no host internals, profiles, tokens, or network. */
11
+ function harness(resolveGrant = async () => grant()) {
12
+ const handlers = new Map();
13
+ const warnings = [];
14
+ const value = { providers: { xai: { models: ["offline-chat"] } } };
15
+ const ctx = {
16
+ settings: { describe() { return [{ ns: "llm-pi-ai", value, user: { providers: {} } }]; } },
17
+ logger: { warn(message) { warnings.push(message); } },
18
+ on(name, handler) {
19
+ const listeners = handlers.get(name) ?? [];
20
+ listeners.push(handler);
21
+ handlers.set(name, listeners);
22
+ return () => { const index = listeners.indexOf(handler); if (index >= 0) listeners.splice(index, 1); };
23
+ },
24
+ };
25
+ const dispose = registerChatRecovery(ctx, resolveGrant);
26
+ const waterfall = (name, payload, terminal) => {
27
+ const listeners = [...handlers.get(name) ?? []];
28
+ let index = 0;
29
+ const next = () => index < listeners.length ? listeners[index++](payload, next) : terminal();
30
+ return next();
31
+ };
32
+ const emit = async (name, payload) => { for (const handler of [...handlers.get(name) ?? []]) await handler(payload); };
33
+ const agent = { session: { id: "offline-session" } };
34
+ const controller = new AbortController();
35
+ const prepare = async ({ target = agent, turn = 1, step = 1, signal = controller.signal, provider = "xai", purpose, tracked = true } = {}) => {
36
+ const payload = { agent: target, turn, step, signal };
37
+ const config = { provider, model: "offline-chat" };
38
+ if (tracked) assert.equal(await waterfall("agent/request", payload, async () => config), config);
39
+ const options = Object.freeze({ ...config, sessionId: target.session.id, signal, messages: [], ...(purpose === undefined ? {} : { purpose }) });
40
+ return { options, payload: { ...payload, provider } };
41
+ };
42
+ const stream = (options, terminal = chunks) => waterfall("llm/stream", options, terminal);
43
+ const fail = (attempt, failure = { code: "AUTH", message: "xai API error (401): unauthorized" }, terminal = async () => undefined) =>
44
+ waterfall("agent/request-error", { ...attempt.payload, failure }, terminal);
45
+ return { ctx, value, warnings, handlers, waterfall, emit, agent, controller, prepare, stream, fail, dispose };
46
+ }
47
+
48
+ test("a clear xAI OAuth rejection persists recovery before retrying once in the same step", async () => {
49
+ const observed = grant();
50
+ const calls = [];
51
+ let release;
52
+ const stored = new Promise((resolve) => { release = resolve; });
53
+ const host = harness(async (id, options) => {
54
+ calls.push({ id, options });
55
+ if (options) await stored;
56
+ return observed;
57
+ });
58
+ const first = await host.prepare();
59
+ const original = { type: "finish", reason: { kind: "error", failure: { code: "AUTH", message: "xai API error (401): unauthorized" } } };
60
+ assert.deepEqual(await collect(host.stream(first.options, async function* () { yield original; })), [original]);
61
+ let settled = false;
62
+ const recovery = host.fail(first).then((result) => { settled = true; return result; });
63
+ await Promise.resolve();
64
+ assert.equal(settled, false, "a retry cannot precede durable grant resolution");
65
+ release();
66
+ assert.deepEqual(await recovery, { kind: "retry" });
67
+ assert.deepEqual(calls[1], { id: "xai", options: { rejectedGrant: observed } });
68
+ const second = await host.prepare();
69
+ await collect(host.stream(second.options));
70
+ let delegated = 0;
71
+ assert.equal(await host.fail(second, undefined, async () => { delegated += 1; return "terminal"; }), "terminal");
72
+ assert.equal(delegated, 1);
73
+ assert.equal(calls.filter((call) => call.options).length, 1);
74
+ const following = await host.prepare({ step: 2 });
75
+ await collect(host.stream(following.options));
76
+ assert.deepEqual(await host.fail(following), { kind: "retry" }, "a later step owns its own one-time recovery");
77
+ });
78
+
79
+ test("non-target streams and errors delegate without resolving credentials", async () => {
80
+ for (const options of [{ provider: "anthropic" }, { purpose: "compaction" }, { purpose: "session-title" }, { tracked: false }]) {
81
+ let resolutions = 0;
82
+ const host = harness(async () => { resolutions += 1; return grant(); });
83
+ const attempt = await host.prepare(options);
84
+ const source = chunks();
85
+ assert.equal(host.stream(attempt.options, () => source), source);
86
+ assert.equal(await host.fail(attempt, undefined, async () => "delegated"), "delegated");
87
+ assert.equal(resolutions, 0);
88
+ }
89
+ });
90
+
91
+ test("only merged settings with no apiKeyEnv and a usable stored OAuth grant participate", async () => {
92
+ for (const apiKeyEnv of ["XAI_API_KEY", ""]) {
93
+ let resolutions = 0;
94
+ const host = harness(async () => { resolutions += 1; return grant(); });
95
+ host.value.providers.xai.apiKeyEnv = apiKeyEnv;
96
+ const attempt = await host.prepare();
97
+ await collect(host.stream(attempt.options));
98
+ assert.equal(await host.fail(attempt, undefined, async () => "delegated"), "delegated");
99
+ assert.equal(resolutions, 0);
100
+ }
101
+ for (const unusable of [undefined, { type: "api_key", access: "offline-key" }, { type: "oauth", access: "", refresh: "offline" }, { type: "oauth", access: "offline" }]) {
102
+ let forced = 0;
103
+ const host = harness(async (_id, options) => { if (options) forced += 1; return unusable; });
104
+ const attempt = await host.prepare();
105
+ await collect(host.stream(attempt.options));
106
+ assert.equal(await host.fail(attempt, undefined, async () => "delegated"), "delegated");
107
+ assert.equal(forced, 0);
108
+ }
109
+ });
110
+
111
+ test("unknown AUTH, permission, billing, challenge, and network failures cannot refresh a grant", async () => {
112
+ const failures = [
113
+ { code: "AUTH", message: "unauthorized" },
114
+ { code: "AUTH", message: "a request body mentions 401" },
115
+ { code: "AUTH", message: "prefix xai API error (401): unauthorized" },
116
+ { code: "AUTH", message: 'xai API error (403): {"code":"permission_denied"}' },
117
+ { code: "AUTH", message: 'xai API error (403): {"code":"insufficient_scope"}' },
118
+ { code: "AUTH", message: 'xai API error (403): {"code":"subscription:free-usage-exhausted"}' },
119
+ { code: "AUTH", message: "xai API error (403): <html>Cloudflare challenge</html>" },
120
+ { code: "AUTH", status: 403, message: '{"code":"bad-credentials"}' },
121
+ { code: "AUTH", message: 'xai API error (403): {"message":"A user mentioned bad-credentials"}' },
122
+ { code: "TRANSPORT", message: "network failure mentions 401" },
123
+ { code: "ABORTED", status: 401, message: "xai API error (401): cancelled" },
124
+ ];
125
+ for (const failure of failures) {
126
+ let forced = 0;
127
+ const host = harness(async (_id, options) => { if (options) forced += 1; return grant(); });
128
+ const attempt = await host.prepare();
129
+ await collect(host.stream(attempt.options));
130
+ assert.equal(await host.fail(attempt, failure, async () => "delegated"), "delegated");
131
+ assert.equal(forced, 0, JSON.stringify(failure));
132
+ }
133
+ });
134
+
135
+ test("structured 401 and precise xAI 403 bad-credentials permit one recovery", async () => {
136
+ for (const failure of [
137
+ { code: "AUTH", status: 401, message: "upstream denied access" },
138
+ { code: "AUTH", message: 'xai API error (403): {"code":"unauthenticated:bad-credentials"}' },
139
+ { code: "AUTH", message: 'xai API error (403): {"error":{"code":"bad-credentials"}}' },
140
+ { code: "AUTH", message: "xai API error (403): The OAuth2 access token could not be validated." },
141
+ ]) {
142
+ let forced = 0;
143
+ const host = harness(async (_id, options) => { if (options) forced += 1; return grant(); });
144
+ const attempt = await host.prepare();
145
+ await collect(host.stream(attempt.options));
146
+ assert.deepEqual(await host.fail(attempt, failure), { kind: "retry" });
147
+ assert.equal(forced, 1);
148
+ }
149
+ });
150
+
151
+ test("session, signal, and agent identities must all match the observed normal chat attempt", async () => {
152
+ for (const mismatch of ["session", "signal", "agent", "turn", "step"]) {
153
+ let forced = 0;
154
+ const host = harness(async (_id, options) => { if (options) forced += 1; return grant(); });
155
+ const attempt = await host.prepare();
156
+ if (mismatch === "session") {
157
+ await collect(host.stream({ ...attempt.options, sessionId: "another-session" }));
158
+ } else if (mismatch === "signal") {
159
+ await collect(host.stream({ ...attempt.options, signal: new AbortController().signal }));
160
+ } else {
161
+ await collect(host.stream(attempt.options));
162
+ if (mismatch === "agent") attempt.payload.agent = { session: { id: host.agent.session.id } };
163
+ else attempt.payload[mismatch] += 1;
164
+ }
165
+ assert.equal(await host.fail(attempt, undefined, async () => "delegated"), "delegated");
166
+ assert.equal(forced, 0, mismatch);
167
+ }
168
+ });
169
+
170
+ test("cancellation before or during refresh never returns retry, while an active refresh may finish persistence", async () => {
171
+ let forced = 0;
172
+ const host = harness(async (_id, options) => { if (options) forced += 1; return grant(); });
173
+ const attempt = await host.prepare();
174
+ await collect(host.stream(attempt.options));
175
+ host.controller.abort();
176
+ assert.equal(await host.fail(attempt), undefined);
177
+ assert.equal(forced, 0);
178
+
179
+ let entered;
180
+ let release;
181
+ const refreshing = new Promise((resolve) => { entered = resolve; });
182
+ const commit = new Promise((resolve) => { release = resolve; });
183
+ let committed = false;
184
+ const during = harness(async (_id, options) => {
185
+ if (options) { entered(); await commit; committed = true; }
186
+ return grant();
187
+ });
188
+ const pending = await during.prepare();
189
+ await collect(during.stream(pending.options));
190
+ const result = during.fail(pending);
191
+ await refreshing;
192
+ during.controller.abort();
193
+ release();
194
+ assert.equal(await result, undefined);
195
+ assert.equal(committed, true);
196
+ });
197
+
198
+ test("failed observation or refresh delegates safely and leaves the original host failure in control", async () => {
199
+ for (const phase of ["observation", "refresh"]) {
200
+ const host = harness(async (_id, options) => {
201
+ if (phase === "observation" || options) throw new Error("offline-private-detail");
202
+ return grant();
203
+ });
204
+ const attempt = await host.prepare();
205
+ let streamed = 0;
206
+ await collect(host.stream(attempt.options, () => { streamed += 1; return chunks(); }));
207
+ assert.equal(streamed, 1);
208
+ assert.equal(await host.fail(attempt, undefined, async () => "original failure"), "original failure");
209
+ assert.ok(host.warnings.every((message) => !message.includes("offline-private-detail")));
210
+ }
211
+ });
212
+
213
+ test("another request's persisted refresh is reused rather than rotated again", async () => {
214
+ const key = "llm-pi-ai/xai";
215
+ let record = { kind: "grant", payload: grant("offline-old") };
216
+ let exchanges = 0;
217
+ const credentials = {
218
+ async readRecord(requested) { assert.equal(requested, key); return structuredClone(record); },
219
+ async modifyRecord(requested, mutate) {
220
+ assert.equal(requested, key);
221
+ const changed = await mutate(structuredClone(record));
222
+ if (changed !== undefined) record = structuredClone(changed);
223
+ return structuredClone(record);
224
+ },
225
+ };
226
+ const resolveGrant = createGrantResolver(credentials, ({ credentials: store }) => ({
227
+ getProvider() { return { auth: { oauth: { async refresh(current) { exchanges += 1; return { ...current, access: "unexpected" }; } } } }; },
228
+ async getAuth(id) { return { auth: { apiKey: (await store.read(id)).access } }; },
229
+ }));
230
+ const host = harness(resolveGrant);
231
+ const attempt = await host.prepare();
232
+ await collect(host.stream(attempt.options));
233
+ record = { kind: "grant", payload: { ...record.payload, access: "offline-concurrent-winner", refresh: "offline-rotated" } };
234
+ assert.deepEqual(await host.fail(attempt), { kind: "retry" });
235
+ assert.equal(exchanges, 0);
236
+ assert.equal(record.payload.access, "offline-concurrent-winner");
237
+ });
238
+
239
+ test("idle/disposed agents release observations and context disposal removes all registered listeners", async () => {
240
+ for (const event of ["agent/status", "agent/disposed"]) {
241
+ const host = harness();
242
+ const attempt = await host.prepare();
243
+ await collect(host.stream(attempt.options));
244
+ await host.emit(event, { agent: host.agent, status: "idle" });
245
+ assert.equal(await host.fail(attempt, undefined, async () => "delegated"), "delegated");
246
+ }
247
+ let release;
248
+ let entered;
249
+ const blocked = new Promise((resolve) => { release = resolve; });
250
+ const refreshing = new Promise((resolve) => { entered = resolve; });
251
+ const host = harness(async (_id, options) => { if (options) { entered(); await blocked; } return grant(); });
252
+ const attempt = await host.prepare();
253
+ await collect(host.stream(attempt.options));
254
+ const recovery = host.fail(attempt);
255
+ await refreshing;
256
+ await host.emit("dispose");
257
+ assert.ok([...host.handlers.values()].every((listeners) => listeners.length === 0));
258
+ release();
259
+ assert.equal(await recovery, undefined);
260
+ host.dispose();
261
+ });
@@ -0,0 +1,129 @@
1
+ import { builtinModels } from '@earendil-works/pi-ai/providers/all';
2
+ import { createConnections, nativeKey, connectionKey, connectionRef } from './connections.js';
3
+ import { readLocalSource } from './local-imports.js';
4
+
5
+ const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
6
+ const changed = () => Object.assign(new Error('The connection changed while its credential was being resolved. Retry with the selected connection.'), { code: 'connection-changed' });
7
+
8
+ export function createConnectionRuntime(credentials, nativeResolve, { localRead = readLocalSource, modelsFactory = builtinModels } = {}) {
9
+ const connections = createConnections(credentials);
10
+ const registry = modelsFactory({ authContext: { env: async () => undefined, fileExists: async () => false } });
11
+ const resolutions = new Map();
12
+ // No-op atomic reads see canonical storage, not a possibly stale watcher cache.
13
+ const readRecord = key => credentials.modifyRecord(key, () => undefined);
14
+ const connectionFor = async id => {
15
+ const record = await readRecord(connectionKey(id));
16
+ return record?.kind === 'grant' ? record.payload : undefined;
17
+ };
18
+ const sameConnection = (a, b) => a?.revision === b?.revision && a?.mode === b?.mode && a?.localSource === b?.localSource;
19
+ const check = async (id, selected, sequence) => { if (!sameConnection(selected, await connectionFor(id)) || sequence !== undefined && resolutions.get(id) !== sequence) throw changed(); };
20
+ const ownerFor = connection => ({ owner: 'external-managed', revision: connection.revision, source: connection.localSource });
21
+
22
+ async function invalidateMirror(id, selected, expected) {
23
+ // modifyRecord cannot atomically delete. An owner-tagged tombstone blocks
24
+ // host use without deleting a newer native login in a read/delete gap.
25
+ await credentials.modifyRecord(nativeKey(id), current => {
26
+ const owner = current?.payload?.externalManaged;
27
+ if (owner?.owner !== 'external-managed' || owner.revision !== selected.revision || !equal(current.payload, expected)) return undefined;
28
+ return { kind: 'grant', payload: { type: 'oauth', access: '', expires: 0, externalManaged: owner, revoked: true } };
29
+ });
30
+ }
31
+ async function clearLocalFailure(id, selected, expected, sequence) {
32
+ if (resolutions.get(id) !== sequence) return;
33
+ await invalidateMirror(id, selected, expected);
34
+ if (sameConnection(selected, await connectionFor(id)) && resolutions.get(id) === sequence) await credentials.unset?.(connectionRef(id));
35
+ }
36
+ async function repairReference(id) {
37
+ const latest = await connectionFor(id);
38
+ if (latest?.mode === 'key') await credentials.set(connectionRef(id), latest.access);
39
+ else await credentials.unset?.(connectionRef(id));
40
+ }
41
+ async function setReference(id, selected, access, sequence) {
42
+ await check(id, selected, sequence);
43
+ await credentials.set(connectionRef(id), access);
44
+ try { await check(id, selected, sequence); }
45
+ catch (error) { await repairReference(id); throw error; }
46
+ }
47
+
48
+ async function resolveSnapshot(id, options) {
49
+ const connection = await connectionFor(id);
50
+ const sequence = (resolutions.get(id) ?? 0) + 1;
51
+ if (connection?.mode === 'key' || connection?.mode === 'local') resolutions.set(id, sequence);
52
+ if (connection?.mode === 'key') {
53
+ if (options?.rejectedGrant) throw new Error('The saved API key was rejected. Update the connection credential.');
54
+ await setReference(id, connection, connection.access, sequence);
55
+ const rawGrant = { type: 'api_key', access: connection.access };
56
+ return { connection, rawGrant, grant: { ...rawGrant, ...connection.metadata } };
57
+ }
58
+ if (connection?.mode !== 'local') {
59
+ if (id === 'anthropic') throw new Error('Connect a Claude Console API key in this plugin. Claude Code subscription sign-in is managed by Claude Code.');
60
+ const grant = await nativeResolve(id, options);
61
+ const rawGrant = typeof nativeResolve.rawGrant === 'function' ? await nativeResolve.rawGrant(grant) : (await readRecord(nativeKey(id)))?.payload;
62
+ await check(id, connection);
63
+ return { connection, grant, rawGrant };
64
+ }
65
+
66
+ const before = await readRecord(nativeKey(id));
67
+ let imported;
68
+ try { imported = await localRead(connection.localSource, id); }
69
+ catch (error) { await clearLocalFailure(id, connection, before?.payload, sequence); throw error; }
70
+ // Only normalized fields can enter the host mirror. Never transfer the
71
+ // external CLI's rotating refresh token into the host's OAuth manager.
72
+ const source = imported?.grant;
73
+ if (!source || !['oauth', 'api_key'].includes(source.type) || typeof source.access !== 'string' || !source.access) {
74
+ await clearLocalFailure(id, connection, before?.payload, sequence);
75
+ throw Object.assign(new Error('The source CLI returned no usable credential.'), { code: 'source-unavailable' });
76
+ }
77
+ const rawGrant = { type: source.type, access: source.access };
78
+ if (id === 'anthropic' && rawGrant.type === 'oauth') throw new Error('Connect a Claude Console API key in this plugin.');
79
+ for (const key of ['expires', 'accountId', 'scope']) if (source[key] !== undefined) rawGrant[key] = source[key];
80
+ await check(id, connection, sequence);
81
+ if (rawGrant.type === 'api_key') {
82
+ await setReference(id, connection, rawGrant.access, sequence);
83
+ return { connection, rawGrant, grant: { ...rawGrant, ...connection.metadata } };
84
+ }
85
+
86
+ const payload = { ...rawGrant, externalManaged: ownerFor(connection) };
87
+ let conflict = false;
88
+ await credentials.modifyRecord(nativeKey(id), current => {
89
+ if (!equal(current, before) && !equal(current?.payload, payload)) { conflict = true; return undefined; }
90
+ return equal(current?.payload, payload) ? undefined : { kind: 'grant', payload };
91
+ });
92
+ if (conflict) throw changed();
93
+ try { await check(id, connection, sequence); }
94
+ catch (error) { await invalidateMirror(id, connection, payload); throw error; }
95
+ const oauth = registry.getProvider(id)?.auth?.oauth;
96
+ const auth = typeof oauth?.toAuth === 'function' ? await oauth.toAuth(rawGrant) : { apiKey: rawGrant.access };
97
+ await check(id, connection, sequence);
98
+ const access = auth?.apiKey ?? (id === 'kimi-coding' && auth?.headers ? rawGrant.access : undefined);
99
+ if (!access) throw new Error('The source CLI credential cannot authorize this provider.');
100
+ return { connection, rawGrant, grant: { ...rawGrant, access, ...(auth.headers ? { requestHeaders: auth.headers } : {}), ...(auth.baseUrl ? { apiBase: auth.baseUrl } : {}) } };
101
+ }
102
+
103
+ return {
104
+ connections,
105
+ resolve: async (id, options) => (await resolveSnapshot(id, options)).grant,
106
+ async contextFor(id) {
107
+ const { connection, grant, rawGrant } = await resolveSnapshot(id);
108
+ if (!rawGrant?.access) throw new Error('Connection unavailable.');
109
+ const metadata = { ...connection?.metadata };
110
+ if (id === 'kimi-coding' && metadata.region === undefined && rawGrant.type === 'oauth') {
111
+ if (['cn', 'global'].includes(rawGrant.region)) metadata.region = rawGrant.region;
112
+ else {
113
+ let host;
114
+ try { const url = new URL(grant.apiBase); if (url.protocol === 'https:' && !url.username && !url.password && (!url.port || url.port === '443')) host = url.hostname; } catch {}
115
+ metadata.region = host === 'api.kimi.ai' ? 'global' : 'cn';
116
+ }
117
+ }
118
+ return { ...metadata, access: grant.access, rawGrant, connection, billingAccess: connection?.billingAccess };
119
+ },
120
+ async customRoute(id) {
121
+ const connection = await connectionFor(id);
122
+ if (connection?.mode === 'key') return true;
123
+ if (connection?.mode !== 'local') return false;
124
+ const imported = await localRead(connection.localSource, id);
125
+ await check(id, connection);
126
+ return imported.grant.type === 'api_key';
127
+ },
128
+ };
129
+ }
@@ -0,0 +1,244 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createConnectionRuntime } from './connection-runtime.js';
4
+ import { nativeKey, connectionKey, connectionRef } from './connections.js';
5
+
6
+ const clone = value => value === undefined ? undefined : structuredClone(value);
7
+ function memoryCredentials() {
8
+ const records = new Map(), references = new Map();
9
+ let queue = Promise.resolve();
10
+ return {
11
+ records, references,
12
+ async readRecord(key) { return clone(records.get(key)); },
13
+ async modifyRecord(key, mutate) {
14
+ const pending = queue.then(async () => {
15
+ const next = await mutate(clone(records.get(key)));
16
+ if (next !== undefined) records.set(key, clone(next));
17
+ return clone(records.get(key));
18
+ });
19
+ queue = pending.catch(() => {}); return pending;
20
+ },
21
+ async deleteRecord(key) { records.delete(key); },
22
+ async set(key, value) { references.set(key, value); },
23
+ async unset(key) { references.delete(key); },
24
+ };
25
+ }
26
+ const unavailableNative = () => assert.fail('A managed connection must not invoke native OAuth refresh');
27
+
28
+ test('key connection resolves selected access and regional metadata without pi OAuth', async () => {
29
+ const credentials = memoryCredentials();
30
+ const runtime = createConnectionRuntime(credentials, unavailableNative);
31
+ await runtime.connections.connect('minimax', { access: 'fixture-key', region: 'cn', billingAccess: 'fixture-billing' });
32
+ const grant = await runtime.resolve('minimax');
33
+ assert.equal(grant.type, 'api_key');
34
+ assert.equal(grant.access, 'fixture-key');
35
+ assert.equal(grant.region, 'cn');
36
+ assert.equal(credentials.references.get(connectionRef('minimax')), 'fixture-key');
37
+ const context = await runtime.contextFor('minimax');
38
+ assert.equal(context.billingAccess, 'fixture-billing');
39
+ assert.equal(context.rawGrant.access, 'fixture-key');
40
+ assert.equal(context.region, 'cn');
41
+ });
42
+
43
+ test('native account preserves separate request auth and source grant for Copilot quota', async () => {
44
+ const credentials = memoryCredentials();
45
+ credentials.records.set(nativeKey('github-copilot'), { kind: 'grant', payload: { type: 'oauth', access: 'github-long-token', refresh: 'owner-refresh', expires: 0 } });
46
+ let calls = 0;
47
+ const runtime = createConnectionRuntime(credentials, async (id, options) => {
48
+ calls += 1; assert.equal(id, 'github-copilot');
49
+ return { type: 'oauth', access: 'copilot-inference-token', apiBase: 'https://api.githubcopilot.com' };
50
+ });
51
+ const context = await runtime.contextFor('github-copilot');
52
+ assert.equal(calls, 1);
53
+ assert.equal(context.access, 'copilot-inference-token');
54
+ assert.equal(context.rawGrant.access, 'github-long-token');
55
+ });
56
+
57
+ test('native grant recovery options pass through unchanged', async () => {
58
+ const credentials = memoryCredentials(), options = { rejectedGrant: { access: 'old' } };
59
+ const runtime = createConnectionRuntime(credentials, async (id, actual) => { assert.equal(actual, options); return { access: 'new' }; });
60
+ assert.equal((await runtime.resolve('xai', options)).access, 'new');
61
+ });
62
+
63
+ test('external OAuth rereads source and mirrors access only without native refresh', async () => {
64
+ const credentials = memoryCredentials(); let access = 'source-a', reads = 0;
65
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async (source, provider) => {
66
+ reads += 1; assert.equal(source, 'opencode'); assert.equal(provider, 'fixture-provider');
67
+ return { provider, owner: 'external-managed', grant: { type: 'oauth', access, expires: Date.now() + 3600000 } };
68
+ } });
69
+ await runtime.connections.saveLocal('fixture-provider', 'opencode', 'OpenCode CLI');
70
+ assert.equal((await runtime.resolve('fixture-provider')).access, 'source-a');
71
+ access = 'source-b';
72
+ assert.equal((await runtime.resolve('fixture-provider')).access, 'source-b');
73
+ assert.equal(reads, 2);
74
+ assert.equal(credentials.records.get(nativeKey('fixture-provider')).payload.access, 'source-b');
75
+ assert.equal(credentials.records.get(nativeKey('fixture-provider')).payload.refresh, undefined);
76
+ });
77
+
78
+ test('external API key updates permanent reference and does not create native OAuth', async () => {
79
+ const credentials = memoryCredentials(); let access = 'source-key-a';
80
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => ({ grant: { type: 'api_key', access } }) });
81
+ await runtime.connections.saveLocal('openrouter', 'opencode', 'OpenCode CLI');
82
+ assert.equal(await runtime.customRoute('openrouter'), true);
83
+ await runtime.resolve('openrouter');
84
+ access = 'source-key-b'; await runtime.resolve('openrouter');
85
+ assert.equal(credentials.references.get(connectionRef('openrouter')), 'source-key-b');
86
+ assert.equal(credentials.records.has(nativeKey('openrouter')), false);
87
+ });
88
+
89
+ test('local source errors are transparent and never fall back to native or another source', async () => {
90
+ const credentials = memoryCredentials();
91
+ const sourceError = Object.assign(new Error('Renew the source CLI'), { code: 'source-reauth-required' });
92
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => { throw sourceError; } });
93
+ await runtime.connections.saveLocal('fixture-provider', 'opencode', 'OpenCode CLI');
94
+ await assert.rejects(runtime.resolve('fixture-provider'), error => error === sourceError);
95
+ });
96
+
97
+ test('key preflight reconstructs a missing reference from the selected durable connection', async () => {
98
+ const credentials = memoryCredentials();
99
+ const runtime = createConnectionRuntime(credentials, unavailableNative);
100
+ await runtime.connections.connect('minimax', { access: 'durable-key' });
101
+ credentials.references.delete(connectionRef('minimax'));
102
+ await runtime.resolve('minimax');
103
+ assert.equal(credentials.references.get(connectionRef('minimax')), 'durable-key');
104
+ });
105
+
106
+ test('contextFor obtains one coherent external credential snapshot', async () => {
107
+ const credentials = memoryCredentials(); let reads = 0;
108
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => ({ grant: { type: 'oauth', access: ++reads === 1 ? 'account-a' : 'account-b' } }) });
109
+ await runtime.connections.saveLocal('fixture-provider', 'opencode', 'OpenCode CLI');
110
+ const context = await runtime.contextFor('fixture-provider');
111
+ assert.equal(context.access, context.rawGrant.access, 'request token and account fingerprint must describe the same source snapshot');
112
+ assert.equal(reads, 1, 'a single usage context must not read a mutable source twice');
113
+ });
114
+
115
+ test('expired external source invalidates its previous host OAuth mirror', async () => {
116
+ const credentials = memoryCredentials(); let available = true;
117
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => {
118
+ if (!available) throw Object.assign(new Error('Renew source CLI'), { code: 'source-reauth-required' });
119
+ return { grant: { type: 'oauth', access: 'old-source-token' } };
120
+ } });
121
+ await runtime.connections.saveLocal('fixture-provider', 'opencode', 'OpenCode CLI');
122
+ await runtime.resolve('fixture-provider'); available = false;
123
+ await assert.rejects(runtime.resolve('fixture-provider'), { code: 'source-reauth-required' });
124
+ assert.equal(credentials.records.get(nativeKey('fixture-provider'))?.payload.access, '');
125
+ assert.equal(credentials.records.get(nativeKey('fixture-provider'))?.payload.revoked, true);
126
+ });
127
+
128
+ test('deleted external source invalidates its previous API-key reference', async () => {
129
+ const credentials = memoryCredentials(); let available = true;
130
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => {
131
+ if (!available) throw Object.assign(new Error('Source missing'), { code: 'source-unavailable' });
132
+ return { grant: { type: 'api_key', access: 'old-source-key' } };
133
+ } });
134
+ await runtime.connections.saveLocal('openrouter', 'opencode', 'OpenCode CLI');
135
+ await runtime.resolve('openrouter'); available = false;
136
+ await assert.rejects(runtime.resolve('openrouter'), { code: 'source-unavailable' });
137
+ assert.equal(credentials.references.get(connectionRef('openrouter')), undefined);
138
+ });
139
+
140
+ test('a source read completing after disconnect cannot recreate an OAuth mirror', async () => {
141
+ const credentials = memoryCredentials(); let release, entered;
142
+ const gate = new Promise(resolve => { release = resolve; });
143
+ const started = new Promise(resolve => { entered = resolve; });
144
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => { entered(); await gate; return { grant: { type: 'oauth', access: 'late-source' } }; } });
145
+ await runtime.connections.saveLocal('fixture-provider', 'opencode', 'OpenCode CLI');
146
+ const pending = runtime.resolve('fixture-provider'); await started;
147
+ await runtime.connections.disconnect('fixture-provider');
148
+ release();
149
+ await assert.rejects(pending);
150
+ assert.equal(credentials.records.get(nativeKey('fixture-provider')), undefined);
151
+ assert.equal(credentials.records.get(connectionKey('fixture-provider')), undefined);
152
+ });
153
+
154
+ test('a late source snapshot cannot overwrite a newer completed mirror of the same connection', async () => {
155
+ const credentials = memoryCredentials(); let release, entered, calls = 0;
156
+ const gate = new Promise(resolve => { release = resolve; }), started = new Promise(resolve => { entered = resolve; });
157
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => {
158
+ if (++calls === 1) { entered(); await gate; return { grant: { type: 'oauth', access: 'older' } }; }
159
+ return { grant: { type: 'oauth', access: 'newer' } };
160
+ } });
161
+ await runtime.connections.saveLocal('fixture-provider', 'opencode', 'OpenCode CLI');
162
+ const old = runtime.resolve('fixture-provider'); await started;
163
+ assert.equal((await runtime.resolve('fixture-provider')).access, 'newer');
164
+ release(); await assert.rejects(old, { code: 'connection-changed' });
165
+ assert.equal(credentials.records.get(nativeKey('fixture-provider')).payload.access, 'newer');
166
+ });
167
+
168
+ test('an older failed source read cannot revoke a newer successful source mirror', async () => {
169
+ const credentials = memoryCredentials(); let fail, entered, calls = 0;
170
+ const gate = new Promise((resolve, reject) => { fail = reject; }), started = new Promise(resolve => { entered = resolve; });
171
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => {
172
+ if (++calls === 1) { entered(); await gate; }
173
+ return { grant: { type: 'oauth', access: 'newer' } };
174
+ } });
175
+ await runtime.connections.saveLocal('fixture-provider', 'opencode', 'OpenCode CLI');
176
+ const old = runtime.resolve('fixture-provider'); await started;
177
+ await runtime.resolve('fixture-provider');
178
+ fail(Object.assign(new Error('source temporarily missing'), { code: 'source-unavailable' }));
179
+ await assert.rejects(old, { code: 'source-unavailable' });
180
+ assert.equal(credentials.records.get(nativeKey('fixture-provider')).payload.access, 'newer');
181
+ });
182
+
183
+ test('failed external source never clears a newer native login', async () => {
184
+ const credentials = memoryCredentials(); let available = true;
185
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => {
186
+ if (!available) throw new Error('source unavailable');
187
+ return { grant: { type: 'oauth', access: 'source-token' } };
188
+ } });
189
+ await runtime.connections.saveLocal('fixture-provider', 'opencode', 'OpenCode CLI'); await runtime.resolve('fixture-provider');
190
+ const native = { kind: 'grant', payload: { type: 'oauth', access: 'new-native', refresh: 'owned-native-refresh' } };
191
+ credentials.records.set(nativeKey('fixture-provider'), native); available = false;
192
+ await assert.rejects(runtime.resolve('fixture-provider'));
193
+ assert.deepEqual(credentials.records.get(nativeKey('fixture-provider')), native);
194
+ });
195
+
196
+ test('external mirror strips a refresh field even from an injected source implementation', async () => {
197
+ const credentials = memoryCredentials();
198
+ const runtime = createConnectionRuntime(credentials, unavailableNative, { localRead: async () => ({ grant: { type: 'oauth', access: 'source', refresh: 'must-not-enter-host', arbitrary: 'not-forwarded' } }) });
199
+ await runtime.connections.saveLocal('fixture-provider', 'opencode', 'OpenCode CLI');
200
+ const grant = await runtime.resolve('fixture-provider');
201
+ assert.equal(grant.refresh, undefined);
202
+ assert.equal(credentials.records.get(nativeKey('fixture-provider')).payload.refresh, undefined);
203
+ assert.equal(credentials.records.get(nativeKey('fixture-provider')).payload.arbitrary, undefined);
204
+ assert.equal(credentials.records.get(nativeKey('fixture-provider')).payload.externalManaged.owner, 'external-managed');
205
+ });
206
+
207
+ test('canonical no-op reads ignore a stale credential watcher cache', async () => {
208
+ const credentials = memoryCredentials();
209
+ const runtime = createConnectionRuntime(credentials, unavailableNative);
210
+ await runtime.connections.connect('minimax', { access: 'current' });
211
+ credentials.readRecord = async () => ({ kind: 'grant', payload: { mode: 'key', access: 'stale', revision: 'old' } });
212
+ assert.equal((await runtime.resolve('minimax')).access, 'current');
213
+ });
214
+
215
+ test('native context uses the resolver observed grant rather than a later mutable record', async () => {
216
+ const credentials = memoryCredentials(), observed = new WeakMap();
217
+ const nativeResolve = async () => {
218
+ const grant = { access: 'request-a' };
219
+ observed.set(grant, { type: 'oauth', access: 'raw-a', accountId: 'account-a' });
220
+ credentials.records.set(nativeKey('openai-codex'), { kind: 'grant', payload: { access: 'raw-b', accountId: 'account-b' } });
221
+ return grant;
222
+ };
223
+ nativeResolve.rawGrant = grant => observed.get(grant);
224
+ const runtime = createConnectionRuntime(credentials, nativeResolve);
225
+ const context = await runtime.contextFor('openai-codex');
226
+ assert.equal(context.access, 'request-a'); assert.equal(context.rawGrant.access, 'raw-a'); assert.equal(context.rawGrant.accountId, 'account-a');
227
+ });
228
+
229
+ test('Kimi OAuth region follows explicit scope and issuer host, with legacy native CN default', async () => {
230
+ for (const [raw, apiBase, expected] of [
231
+ [{ type: 'oauth', access: 'a' }, undefined, 'cn'],
232
+ [{ type: 'oauth', access: 'a' }, 'https://api.kimi.ai/coding/v1', 'global'],
233
+ [{ type: 'oauth', access: 'a', region: 'global' }, 'https://api.kimi.com/coding/v1', 'global'],
234
+ [{ type: 'oauth', access: 'a' }, 'https://api.kimi.ai.attacker.invalid', 'cn'],
235
+ ]) {
236
+ const credentials = memoryCredentials(), native = async () => ({ access: 'a', apiBase });
237
+ native.rawGrant = () => raw;
238
+ const context = await createConnectionRuntime(credentials, native).contextFor('kimi-coding');
239
+ assert.equal(context.region, expected);
240
+ }
241
+ const credentials = memoryCredentials(), runtime = createConnectionRuntime(credentials, unavailableNative);
242
+ await runtime.connections.connect('kimi-coding', { access: 'key' });
243
+ assert.equal((await runtime.contextFor('kimi-coding')).region, undefined);
244
+ });