@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,263 @@
1
+ import { constants } from 'node:fs';
2
+ import { execFile } from 'node:child_process';
3
+ import { open } from 'node:fs/promises';
4
+ import { homedir, tmpdir } from 'node:os';
5
+ import { isAbsolute, join } from 'node:path';
6
+ import { promisify } from 'node:util';
7
+
8
+ const MAX_BYTES = 1024 * 1024;
9
+ const NEAR_EXPIRY_MS = 60_000;
10
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
11
+ const providerID = value => typeof value === 'string' && /^[a-z0-9][a-z0-9._-]{0,99}$/.test(value);
12
+ const secret = value => typeof value === 'string' && value.length > 0 && value.length <= 262144 && !/[\x00-\x20\x7f]/.test(value) ? value : undefined;
13
+ const labels = Object.freeze({ codex: 'Codex CLI', opencode: 'OpenCode CLI' });
14
+ const exec = promisify(execFile);
15
+
16
+ export class LocalSourceError extends Error {
17
+ constructor(code, message) { super(message); this.name = 'LocalSourceError'; this.code = code; }
18
+ }
19
+ const error = (code, message) => new LocalSourceError(code, message);
20
+ const AGY_PROVIDER = 'google-antigravity';
21
+ const AGY_REASON = 'source-does-not-export-credentials';
22
+
23
+ function defaultCodexHome(home = homedir()) {
24
+ const codexHome = process.env.CODEX_HOME;
25
+ return codexHome && isAbsolute(codexHome) ? codexHome : join(home, '.codex');
26
+ }
27
+
28
+ function expiryFromJWT(value) {
29
+ const parts = value.split('.');
30
+ if (parts.length !== 3 || parts[1].length > 32768) return undefined;
31
+ try {
32
+ // Only a lifetime hint; unsigned JWT claims never establish identity or permission.
33
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
34
+ return typeof payload.exp === 'number' && Number.isFinite(payload.exp) && payload.exp > 0 && payload.exp <= 8.64e12 ? payload.exp * 1000 : undefined;
35
+ } catch { return undefined; }
36
+ }
37
+
38
+ function oauth(access, expires, accountId, now) {
39
+ access = secret(access);
40
+ if (!access) throw error('invalid-source', 'The CLI source does not contain a usable OAuth access token.');
41
+ const explicitExpiry = typeof expires === 'number' && Number.isFinite(expires) && expires > 0 && expires <= 8.64e15 ? expires : undefined;
42
+ const expiry = explicitExpiry ?? expiryFromJWT(access);
43
+ if (expiry !== undefined && expiry <= now + NEAR_EXPIRY_MS) throw error('source-reauth-required', 'The source CLI authorization has expired or is about to expire. Sign in or refresh it in that CLI, then retry.');
44
+ const grant = { type: 'oauth', access };
45
+ if (expiry !== undefined) grant.expires = expiry;
46
+ if (typeof accountId === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(accountId)) grant.accountId = accountId;
47
+ return grant;
48
+ }
49
+
50
+ function apiKey(value) {
51
+ const access = secret(value);
52
+ if (!access) throw error('invalid-source', 'The CLI source does not contain a usable API key.');
53
+ return { type: 'api_key', access };
54
+ }
55
+
56
+ function codexEntries(data, now) {
57
+ if (!object(data)) throw error('invalid-source', 'The Codex authorization file has an unsupported format.');
58
+ if (data.auth_mode === 'apikey' || (secret(data.OPENAI_API_KEY) && !object(data.tokens))) {
59
+ return [{ provider: 'openai', authType: 'api-key', grant: () => apiKey(data.OPENAI_API_KEY) }];
60
+ }
61
+ if (data.auth_mode && !['chatgpt', 'chatgptAuthTokens'].includes(data.auth_mode)) throw error('unsupported-source', 'This Codex authorization mode is not supported.');
62
+ if (!object(data.tokens)) throw error('invalid-source', 'The Codex authorization file has no supported token entry.');
63
+ return [{ provider: 'openai-codex', authType: 'oauth', grant: () => oauth(data.tokens.access_token, undefined, data.tokens.account_id, now) }];
64
+ }
65
+
66
+ function openCodeEntries(data, now) {
67
+ if (!object(data)) throw error('invalid-source', 'The OpenCode authorization file has an unsupported format.');
68
+ // This is the legacy dictionary contract, not current SQLite or an export-array guess.
69
+ const entries = [];
70
+ const secrets = Object.values(data).filter(object).flatMap(value => [value.access, value.refresh, value.key, value.token, value.id_token]).filter(value => typeof value === 'string' && value.length);
71
+ for (const [sourceProvider, value] of Object.entries(data).slice(0, 200)) {
72
+ if (!providerID(sourceProvider) || !object(value)) continue;
73
+ if (secrets.some(value => sourceProvider === value || value.length >= 8 && sourceProvider.includes(value))) continue;
74
+ if (value.type === 'oauth') {
75
+ const provider = sourceProvider === 'openai' ? 'openai-codex' : sourceProvider;
76
+ entries.push({ provider, authType: 'oauth', grant: () => oauth(value.access, value.expires, value.accountId ?? value.account_id, now) });
77
+ } else if (value.type === 'api' || value.type === 'api_key') {
78
+ // API keys keep their true source provider. A brand key is not proof of a Coding Plan.
79
+ entries.push({ provider: sourceProvider, authType: 'api-key', grant: () => apiKey(value.key ?? value.access) });
80
+ }
81
+ }
82
+ if (!entries.length) throw error('unsupported-source', 'No supported OAuth or API-key entries were found in the OpenCode auth.json source.');
83
+ return entries;
84
+ }
85
+
86
+ function openCodeProvider(id, type) {
87
+ return id === 'openai' && type === 'oauth' ? 'openai-codex' : id;
88
+ }
89
+
90
+ async function openCodeCommand(args) {
91
+ const configured = process.env.DSH_OAUTH_OPENCODE_BIN;
92
+ const options = { cwd: homedir(), timeout: 8000, maxBuffer: MAX_BYTES, windowsHide: true,
93
+ env: { ...process.env, OPENCODE_DISABLE_EXTERNAL_PLUGINS: 'true' } };
94
+ if (configured && isAbsolute(configured)) return (await exec(configured, args, options)).stdout;
95
+ try { return (await exec('opencode', args, options)).stdout; }
96
+ catch (cause) {
97
+ if (cause.code !== 'ENOENT' || process.platform !== 'darwin') throw cause;
98
+ const prefix = process.arch === 'arm64' ? '/opt/homebrew' : '/usr/local';
99
+ return (await exec(join(prefix, 'bin', 'opencode'), args, options)).stdout;
100
+ }
101
+ }
102
+
103
+ async function openCodeV2(run) {
104
+ if (!run) return false;
105
+ try { return /^(?:opencode\s+)?(?:[2-9]|\d{2,})\.\d+\.\d+(?:[-+][\w.+-]+)?$/i.test((await run(['--version'])).trim()); }
106
+ catch { return false; }
107
+ }
108
+
109
+ async function openCodeJson(run, args) {
110
+ try {
111
+ const rows = JSON.parse(await run(args));
112
+ if (!Array.isArray(rows)) throw new Error('Unexpected result');
113
+ return rows;
114
+ } catch { throw error('source-unavailable', 'The OpenCode v2 CLI did not return usable authorization data.'); }
115
+ }
116
+
117
+ async function listOpenCodeV2(run) {
118
+ const rows = await openCodeJson(run, ['auth', 'list', '--format', 'json']);
119
+ const choices = new Map();
120
+ for (const row of rows) {
121
+ if (!providerID(row?.id) || !Array.isArray(row.connections)) continue;
122
+ const supported = row.connections.filter(item => item?.type === 'credential' && ['key', 'oauth'].includes(item.method));
123
+ for (const item of supported) {
124
+ const provider = openCodeProvider(row.id, item.method);
125
+ const reasonCode = item.status?.status === 'needs_auth' ? 'source-reauth-required' : undefined;
126
+ const previous = choices.get(provider);
127
+ choices.set(provider, { provider, authType: item.method === 'oauth' ? 'oauth' : 'api-key',
128
+ available: !previous && !reasonCode, ...(previous ? { reasonCode: 'ambiguous-source' } : reasonCode ? { reasonCode } : {}) });
129
+ }
130
+ }
131
+ return [...choices.values()];
132
+ }
133
+
134
+ async function readOpenCodeV2(run, provider, now) {
135
+ const id = provider === 'openai-codex' ? 'openai' : provider;
136
+ const rows = await openCodeJson(run, ['auth', 'export', id]);
137
+ const matches = rows.filter(row => row?.integrationID === id && object(row.value) &&
138
+ ['oauth', 'key'].includes(row.value.type) && openCodeProvider(id, row.value.type) === provider);
139
+ const active = matches.filter(row => row.active === true);
140
+ const selected = active.length ? active : matches;
141
+ if (!selected.length) throw error('source-unavailable', 'OpenCode v2 has no supported stored credential for this provider.');
142
+ if (selected.length !== 1) throw error('ambiguous-source', 'OpenCode v2 returned several accounts without an unambiguous active credential.');
143
+ const value = selected[0].value;
144
+ return value.type === 'key' ? apiKey(value.key) : oauth(value.access, value.expires, value.metadata?.accountId ?? value.metadata?.account_id, now);
145
+ }
146
+
147
+ async function readKnownJSON(path, maxBytes = MAX_BYTES) {
148
+ let handle;
149
+ try {
150
+ handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
151
+ const stat = await handle.stat();
152
+ if (!stat.isFile() || stat.size > maxBytes) throw error('invalid-source', 'The CLI authorization source is not a bounded regular JSON file.');
153
+ const buffer = Buffer.alloc(Math.min(stat.size + 1, maxBytes + 1));
154
+ let total = 0;
155
+ while (total < buffer.length) {
156
+ const { bytesRead } = await handle.read(buffer, total, buffer.length - total, total);
157
+ if (!bytesRead) break;
158
+ total += bytesRead;
159
+ }
160
+ if (total > stat.size) throw error('invalid-source', 'The CLI authorization source changed while being read.');
161
+ try { return JSON.parse(buffer.subarray(0, total).toString('utf8')); }
162
+ catch { throw error('invalid-source', 'The CLI authorization source is not valid JSON.'); }
163
+ } catch (cause) {
164
+ if (cause instanceof LocalSourceError) throw cause;
165
+ if (cause.code === 'ENOENT' || cause.code === 'ENOTDIR') throw error('source-unavailable', 'The selected CLI authorization source is not available.');
166
+ throw error('source-unavailable', 'The selected CLI authorization source cannot be read.');
167
+ } finally { await handle?.close().catch(() => {}); }
168
+ }
169
+
170
+ /** Read only version metadata from the cache. Its catalog can belong to a different account. */
171
+ export async function readCodexCatalogClientVersion() {
172
+ try {
173
+ const cache = await readKnownJSON(join(defaultCodexHome(), 'models_cache.json'), 4 * MAX_BYTES);
174
+ return cache?.client_version;
175
+ } catch {
176
+ return undefined;
177
+ }
178
+ }
179
+
180
+ /** Ask the official CLI for its account catalog, without exporting its keyring credentials. */
181
+ export async function fetchAntigravityCliModels() {
182
+ const binary = join(homedir(), '.local', 'bin', process.platform === 'win32' ? 'agy.exe' : 'agy');
183
+ const options = { cwd: tmpdir(), timeout: 15000, maxBuffer: MAX_BYTES, windowsHide: true,
184
+ env: { ...process.env, AGY_CLI_DISABLE_AUTO_UPDATE: 'true' } };
185
+ try {
186
+ let result;
187
+ try { result = await exec(binary, ['models'], options); }
188
+ catch (cause) {
189
+ if (cause.code !== 'ENOENT') throw cause;
190
+ result = await exec('agy', ['models'], options);
191
+ }
192
+ const models = new Map();
193
+ for (const line of result.stdout.split(/\r?\n/)) {
194
+ const [id, name] = line.split('\t');
195
+ if (providerID(id) && name?.trim()) models.set(id, { id, name: name.trim().slice(0, 160), role: 'chat' });
196
+ }
197
+ if (models.size) return [...models.values()];
198
+ } catch {
199
+ // Child errors may include CLI logs or login links and must stay local.
200
+ }
201
+ throw error('source-unavailable', '无法从 AGY 读取模型目录。请确认宿主可运行 agy models,并在 AGY 中完成登录。');
202
+ }
203
+
204
+ /** Roots are trusted server configuration only. HTTP bodies must never reach this factory. */
205
+ export function createLocalSources({ home = homedir(), codexHome, openCodeDataHome, runOpenCode, now = () => Date.now() } = {}) {
206
+ if (!isAbsolute(home) || codexHome !== undefined && !isAbsolute(codexHome) || openCodeDataHome !== undefined && !isAbsolute(openCodeDataHome)) throw error('invalid-configuration', 'CLI source roots must be absolute server-configured directories.');
207
+ const sources = {
208
+ codex: { path: join(codexHome ?? join(home, '.codex'), 'auth.json'), parse: codexEntries },
209
+ opencode: { path: join(openCodeDataHome ?? join(home, '.local', 'share'), 'opencode', 'auth.json'), parse: openCodeEntries },
210
+ };
211
+ async function entries(source) {
212
+ if (typeof source !== 'string' || !Object.hasOwn(sources, source)) throw error('unsupported-source', 'The selected CLI source is not supported.');
213
+ const spec = sources[source];
214
+ return spec.parse(await readKnownJSON(spec.path), now());
215
+ }
216
+ async function discoverLocalSources() {
217
+ const fileSources = await Promise.all(Object.keys(sources).map(async id => {
218
+ try {
219
+ if (id === 'opencode' && await openCodeV2(runOpenCode)) {
220
+ const providers = await listOpenCodeV2(runOpenCode);
221
+ return { id, label: labels[id], available: providers.some(item => item.available), providers };
222
+ }
223
+ const list = await entries(id);
224
+ const counts = new Map();
225
+ for (const item of list) counts.set(item.provider, (counts.get(item.provider) ?? 0) + 1);
226
+ const providers = [...new Map(list.map(item => {
227
+ let reasonCode;
228
+ if (counts.get(item.provider) > 1) reasonCode = 'ambiguous-source';
229
+ else try { item.grant(); } catch (cause) { reasonCode = cause instanceof LocalSourceError ? cause.code : 'invalid-source'; }
230
+ return [item.provider, { provider: item.provider, authType: item.authType, available: reasonCode === undefined, ...(reasonCode ? { reasonCode } : {}) }];
231
+ })).values()];
232
+ return { id, label: labels[id], available: providers.some(item => item.available), providers };
233
+ } catch (cause) {
234
+ return { id, label: labels[id], available: false, reasonCode: cause instanceof LocalSourceError ? cause.code : 'invalid-source', providers: [] };
235
+ }
236
+ }));
237
+ return [...fileSources, { id: 'agy', label: 'Antigravity CLI (agy)', available: false, reasonCode: AGY_REASON,
238
+ providers: [{ provider: AGY_PROVIDER, authType: 'oauth', available: false, reasonCode: AGY_REASON }] }];
239
+ }
240
+ async function readLocalSource(source, provider) {
241
+ if (!providerID(provider)) throw error('unsupported-provider', 'The selected source provider is not supported.');
242
+ if (source === 'agy' && provider === AGY_PROVIDER) {
243
+ throw error(AGY_REASON, 'Antigravity CLI manages its login in the system keyring and does not export reusable credentials. Use /usage in agy to view subscription quota.');
244
+ }
245
+ if (source === 'opencode' && await openCodeV2(runOpenCode)) {
246
+ return { provider, grant: await readOpenCodeV2(runOpenCode, provider, now()), owner: 'external-managed', source: { id: source, provider }, label: labels[source] };
247
+ }
248
+ // Reread the same fixed source on every use: no cached token or refresh chain survives source logout.
249
+ const matches = (await entries(source)).filter(item => item.provider === provider);
250
+ if (!matches.length) throw error('source-unavailable', 'The selected provider is no longer present in the source CLI.');
251
+ if (matches.length > 1) throw error('ambiguous-source', 'Multiple source entries map to this provider. Select one in the source CLI before connecting.');
252
+ return { provider, grant: matches[0].grant(), owner: 'external-managed', source: { id: source, provider }, label: labels[source] };
253
+ }
254
+ return { discoverLocalSources, readLocalSource };
255
+ }
256
+
257
+ const defaults = createLocalSources({
258
+ codexHome: defaultCodexHome(),
259
+ openCodeDataHome: process.env.XDG_DATA_HOME && isAbsolute(process.env.XDG_DATA_HOME) ? process.env.XDG_DATA_HOME : undefined,
260
+ runOpenCode: openCodeCommand,
261
+ });
262
+ export const discoverLocalSources = () => defaults.discoverLocalSources();
263
+ export const readLocalSource = (source, provider) => defaults.readLocalSource(source, provider);
@@ -0,0 +1,201 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtemp, mkdir, writeFile, rm, symlink, readFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { createLocalSources } from './local-imports.js';
7
+
8
+ const NOW = Date.parse('2026-11-16T12:00:00Z');
9
+ const jwt = (expires = NOW + 3600000) => `eyJhbGciOiJub25lIn0.${Buffer.from(JSON.stringify({ exp: expires / 1000 })).toString('base64url')}.fixture-signature`;
10
+ async function fixture(t) {
11
+ const home = await mkdtemp(join(tmpdir(), 'dsh-local-import-test-'));
12
+ t.after(() => rm(home, { recursive: true, force: true }));
13
+ const paths = { codex: join(home, '.codex', 'auth.json'), opencode: join(home, '.local', 'share', 'opencode', 'auth.json') };
14
+ async function put(source, value) { await mkdir(join(paths[source], '..'), { recursive: true }); await writeFile(paths[source], typeof value === 'string' ? value : JSON.stringify(value)); }
15
+ return { home, paths, put, ...createLocalSources({ home, now: () => NOW }) };
16
+ }
17
+
18
+ test('empty isolated roots discover known sources without leaking host paths', async t => {
19
+ const f = await fixture(t), sources = await f.discoverLocalSources();
20
+ assert.deepEqual(sources.map(x => x.id), ['codex', 'opencode', 'agy']);
21
+ assert.ok(sources.slice(0, 2).every(x => !x.available && x.reasonCode === 'source-unavailable'));
22
+ assert.equal(JSON.stringify(sources).includes(f.home), false);
23
+ });
24
+
25
+ test('AGY reports the CLI credential constraint and leaves supported imports available', async t => {
26
+ const f = await fixture(t);
27
+ await f.put('opencode', { 'google-antigravity': { type: 'oauth', access: 'synthetic-opencode-access' } });
28
+ const sources = await f.discoverLocalSources();
29
+ const agy = sources.find(source => source.id === 'agy');
30
+ assert.equal(agy.available, false);
31
+ assert.deepEqual(agy.providers, [{ provider: 'google-antigravity', authType: 'oauth', available: false, reasonCode: 'source-does-not-export-credentials' }]);
32
+ assert.equal(sources.find(source => source.id === 'opencode').available, true);
33
+ await assert.rejects(f.readLocalSource('agy', 'google-antigravity'), { code: 'source-does-not-export-credentials' });
34
+ await assert.rejects(f.readLocalSource('agy', 'openai-codex'), { code: 'unsupported-source' });
35
+ });
36
+
37
+ test('Codex ChatGPT token normalizes account and expiry, but never exports refresh or ID tokens', async t => {
38
+ const f = await fixture(t), access = jwt();
39
+ await f.put('codex', { auth_mode: 'chatgpt', tokens: { access_token: access, refresh_token: 'synthetic-refresh-secret', id_token: 'synthetic-id-secret', account_id: 'account-fixture' }, last_refresh: '2026-11-16T11:00:00Z' });
40
+ const preview = await f.discoverLocalSources();
41
+ assert.deepEqual(preview[0].providers, [{ provider: 'openai-codex', authType: 'oauth', available: true }]);
42
+ assert.equal(JSON.stringify(preview).includes(access), false);
43
+ assert.equal(JSON.stringify(preview).includes('secret'), false);
44
+ assert.equal(JSON.stringify(preview).includes('account-fixture'), false);
45
+ const read = await f.readLocalSource('codex', 'openai-codex');
46
+ assert.equal(read.owner, 'external-managed');
47
+ assert.deepEqual(read.source, { id: 'codex', provider: 'openai-codex' });
48
+ assert.deepEqual(read.grant, { type: 'oauth', access, expires: NOW + 3600000, accountId: 'account-fixture' });
49
+ assert.equal(JSON.stringify(read).includes('refresh-secret'), false);
50
+ });
51
+
52
+ test('source changes and logout are observed on every read, without a plugin-owned refresh', async t => {
53
+ const f = await fixture(t);
54
+ await f.put('codex', { tokens: { access_token: 'synthetic-token-a', refresh_token: 'must-not-copy' } });
55
+ const first = await f.readLocalSource('codex', 'openai-codex');
56
+ await f.put('codex', { tokens: { access_token: 'synthetic-token-b' } });
57
+ const second = await f.readLocalSource('codex', 'openai-codex');
58
+ assert.equal(first.grant.access, 'synthetic-token-a');
59
+ assert.equal(second.grant.access, 'synthetic-token-b');
60
+ assert.equal(second.grant.expires, undefined);
61
+ await rm(f.paths.codex);
62
+ await assert.rejects(f.readLocalSource('codex', 'openai-codex'), { code: 'source-unavailable' });
63
+ });
64
+
65
+ for (const lifetime of [-1000, 0, 59999, 60000]) {
66
+ test(`Codex expired or near-expiry source (${lifetime} ms) asks the source CLI to refresh`, async t => {
67
+ const f = await fixture(t);
68
+ await f.put('codex', { tokens: { access_token: jwt(NOW + lifetime) } });
69
+ const preview = await f.discoverLocalSources();
70
+ assert.equal(preview[0].providers[0].reasonCode, 'source-reauth-required');
71
+ await assert.rejects(f.readLocalSource('codex', 'openai-codex'), error => error.code === 'source-reauth-required' && /source CLI/.test(error.message));
72
+ });
73
+ }
74
+
75
+ test('Codex API-key mode is OpenAI, never a ChatGPT subscription', async t => {
76
+ const f = await fixture(t);
77
+ await f.put('codex', { auth_mode: 'apikey', OPENAI_API_KEY: 'synthetic-openai-key', tokens: { access_token: jwt() } });
78
+ const read = await f.readLocalSource('codex', 'openai');
79
+ assert.deepEqual(read.grant, { type: 'api_key', access: 'synthetic-openai-key' });
80
+ await assert.rejects(f.readLocalSource('codex', 'openai-codex'), { code: 'source-unavailable' });
81
+ });
82
+
83
+ test('OpenCode maps openai OAuth only, and retains true provider IDs for API keys', async t => {
84
+ const f = await fixture(t);
85
+ await f.put('opencode', {
86
+ openai: { type: 'oauth', access: 'synthetic-codex', refresh: 'do-not-copy', expires: NOW + 3600000, accountId: 'account-a' },
87
+ anthropic: { type: 'oauth', access: 'synthetic-claude', refresh: 'do-not-copy', expires: NOW + 3600000 },
88
+ 'opencode-go': { type: 'api', key: 'synthetic-go-key' },
89
+ 'opencode-zen': { type: 'api', key: 'synthetic-zen-key' },
90
+ minimax: { type: 'api', key: 'synthetic-brand-key' },
91
+ openrouter: { type: 'api', key: 'synthetic-router-key' },
92
+ });
93
+ const preview = (await f.discoverLocalSources())[1];
94
+ assert.equal(preview.providers.length, 6);
95
+ assert.equal(preview.providers.some(x => x.provider === 'openai'), false);
96
+ assert.equal((await f.readLocalSource('opencode', 'openai-codex')).grant.refresh, undefined);
97
+ assert.deepEqual((await f.readLocalSource('opencode', 'opencode-go')).grant, { type: 'api_key', access: 'synthetic-go-key' });
98
+ assert.equal((await f.readLocalSource('opencode', 'minimax')).provider, 'minimax');
99
+ await f.put('opencode', { openai: { type: 'api', key: 'synthetic-openai-api' } });
100
+ assert.equal((await f.readLocalSource('opencode', 'openai')).grant.type, 'api_key');
101
+ await assert.rejects(f.readLocalSource('opencode', 'openai-codex'), { code: 'source-unavailable' });
102
+ });
103
+
104
+ test('ambiguous OpenCode aliases are visible but cannot silently overwrite one another', async t => {
105
+ const f = await fixture(t);
106
+ await f.put('opencode', { openai: { type: 'oauth', access: 'account-a' }, 'openai-codex': { type: 'oauth', access: 'account-b' } });
107
+ assert.deepEqual((await f.discoverLocalSources())[1].providers, [{ provider: 'openai-codex', authType: 'oauth', available: false, reasonCode: 'ambiguous-source' }]);
108
+ await assert.rejects(f.readLocalSource('opencode', 'openai-codex'), { code: 'ambiguous-source' });
109
+ });
110
+
111
+ test('OpenCode explicit expiry is checked and valid neighbors survive an invalid entry', async t => {
112
+ const f = await fixture(t);
113
+ await f.put('opencode', { anthropic: { type: 'oauth', access: 'synthetic-claude', expires: NOW - 1 }, openrouter: { type: 'api', key: 'synthetic-key' } });
114
+ const source = (await f.discoverLocalSources())[1];
115
+ assert.equal(source.available, true);
116
+ assert.equal(source.providers[0].reasonCode, 'source-reauth-required');
117
+ assert.equal(source.providers[1].available, true);
118
+ await assert.rejects(f.readLocalSource('opencode', 'anthropic'), { code: 'source-reauth-required' });
119
+ });
120
+
121
+ test('unknown source formats and invalid token content are rejected without raw messages', async t => {
122
+ const f = await fixture(t);
123
+ for (const payload of [[], null, 'not JSON secret-value', { version: 2, credentials: [{ access: 'secret-value' }] }]) {
124
+ await f.put('opencode', payload === null ? 'null' : payload);
125
+ const source = (await f.discoverLocalSources())[1];
126
+ assert.equal(source.available, false);
127
+ assert.equal(JSON.stringify(source).includes('secret-value'), false);
128
+ }
129
+ await f.put('opencode', { anthropic: { type: 'oauth', access: 'token\nInjected: yes' } });
130
+ await assert.rejects(f.readLocalSource('opencode', 'anthropic'), { code: 'invalid-source' });
131
+ });
132
+
133
+ test('paths, source IDs, and inherited object properties cannot select arbitrary files', async t => {
134
+ const f = await fixture(t);
135
+ for (const source of [f.paths.codex, '../codex', 'constructor', '__proto__', { path: f.paths.codex }]) await assert.rejects(f.readLocalSource(source, 'openai-codex'), { code: 'unsupported-source' });
136
+ for (const provider of ['../openai', '/tmp/auth.json', { provider: 'openai' }]) await assert.rejects(f.readLocalSource('codex', provider), { code: 'unsupported-provider' });
137
+ });
138
+
139
+ test('trusted absolute server root overrides stay fixed and source files remain unchanged', async t => {
140
+ const f = await fixture(t), codexHome = join(f.home, 'alternate-codex'), dataHome = join(f.home, 'alternate-data');
141
+ await mkdir(codexHome); await mkdir(join(dataHome, 'opencode'), { recursive: true });
142
+ const path = join(codexHome, 'auth.json'), original = JSON.stringify({ tokens: { access_token: jwt(), refresh_token: 'owned-by-cli' } });
143
+ await writeFile(path, original);
144
+ await writeFile(join(dataHome, 'opencode', 'auth.json'), JSON.stringify({ openrouter: { type: 'api', key: 'synthetic-key' } }));
145
+ const custom = createLocalSources({ home: f.home, codexHome, openCodeDataHome: dataHome, now: () => NOW });
146
+ assert.equal((await custom.readLocalSource('codex', 'openai-codex')).grant.type, 'oauth');
147
+ assert.equal((await custom.readLocalSource('opencode', 'openrouter')).grant.type, 'api_key');
148
+ assert.equal(await readFile(path, 'utf8'), original);
149
+ assert.throws(() => createLocalSources({ home: f.home, codexHome: '../relative' }), { code: 'invalid-configuration' });
150
+ });
151
+
152
+ test('symlinks, directories, and over-size credentials are not opened as authorization documents', async t => {
153
+ const f = await fixture(t);
154
+ await mkdir(join(f.paths.codex, '..'), { recursive: true });
155
+ const other = join(f.home, 'other.json');
156
+ await writeFile(other, JSON.stringify({ tokens: { access_token: jwt() } }));
157
+ await symlink(other, f.paths.codex);
158
+ await assert.rejects(f.readLocalSource('codex', 'openai-codex'), { code: 'source-unavailable' });
159
+ await rm(f.paths.codex); await mkdir(f.paths.codex);
160
+ await assert.rejects(f.readLocalSource('codex', 'openai-codex'), { code: 'invalid-source' });
161
+ await rm(f.paths.codex, { recursive: true });
162
+ await writeFile(f.paths.codex, ' '.repeat(1024 * 1024 + 1));
163
+ await assert.rejects(f.readLocalSource('codex', 'openai-codex'), { code: 'invalid-source' });
164
+ });
165
+
166
+ test('unverified JWT identity fields are not used as account metadata', async t => {
167
+ const f = await fixture(t), payload = Buffer.from(JSON.stringify({ exp: NOW / 1000 + 3600, account_id: 'unverified-account', email: 'private@example.invalid' })).toString('base64url');
168
+ await f.put('codex', { tokens: { access_token: `header.${payload}.signature` } });
169
+ const out = await f.readLocalSource('codex', 'openai-codex');
170
+ assert.equal(out.grant.accountId, undefined);
171
+ assert.equal(JSON.stringify(await f.discoverLocalSources()).includes('private@example.invalid'), false);
172
+ });
173
+
174
+ test('provider dictionary names cannot disclose another entry secret in preview', async t => {
175
+ const f = await fixture(t);
176
+ await f.put('opencode', { 'synthetic-token-value': { type: 'api', key: 'other-key' }, anthropic: { type: 'oauth', access: 'synthetic-token-value' } });
177
+ const preview = await f.discoverLocalSources();
178
+ assert.equal(JSON.stringify(preview).includes('synthetic-token-value'), false);
179
+ assert.deepEqual(preview[1].providers.map(x => x.provider), ['anthropic']);
180
+ });
181
+
182
+ test('OpenCode v2 discovery uses redacted metadata; imports reread only the requested credential', async t => {
183
+ const f = await fixture(t);
184
+ await f.put('opencode', { openrouter: { type: 'api', key: 'obsolete-legacy-key' } });
185
+ let key = 'v2-first-key';
186
+ const calls = [];
187
+ const runOpenCode = async args => {
188
+ calls.push(args);
189
+ if (args[0] === '--version') return '2.1.0\n';
190
+ if (args[1] === 'list') return JSON.stringify([{ id: 'openrouter', connections: [{ type: 'credential', method: 'key' }] }]);
191
+ assert.deepEqual(args, ['auth', 'export', 'openrouter']);
192
+ return JSON.stringify([{ integrationID: 'openrouter', value: { type: 'key', key } }]);
193
+ };
194
+ const sources = createLocalSources({ home: f.home, runOpenCode });
195
+ const results = await sources.discoverLocalSources();
196
+ assert.deepEqual(results.find(source => source.id === 'opencode').providers, [{ provider: 'openrouter', authType: 'api-key', available: true }]);
197
+ assert.deepEqual(calls, [['--version'], ['auth', 'list', '--format', 'json']]);
198
+ assert.equal((await sources.readLocalSource('opencode', 'openrouter')).grant.access, 'v2-first-key');
199
+ key = 'v2-rotated-key';
200
+ assert.equal((await sources.readLocalSource('opencode', 'openrouter')).grant.access, key);
201
+ });
package/src/media.js ADDED
@@ -0,0 +1,152 @@
1
+ import { defineTool } from "@deepseek-ai/dsh-tools";
2
+
3
+ /**
4
+ * Image and video requests run as tools against the account's media model.
5
+ * The session's selected chat model is not changed, so the conversation continues.
6
+ * @param {import("@deepseek-ai/cordis").Context} ctx
7
+ */
8
+ export function registerMediaTools(ctx, resolveGrant, pulls) {
9
+ ctx.effect(() => ctx.systemPrompt.section({
10
+ name: "oauth-media",
11
+ order: 860,
12
+ text: [
13
+ "Image and video generation stay inside this conversation.",
14
+ "When the user asks for a new image, illustration, or edit of a picture, call generate_image.",
15
+ "When the user asks for a video or animation, call generate_video.",
16
+ "Those tools use the image or video model pulled for this conversation's provider.",
17
+ "Do not switch the conversation model, and do not ask the user to pick a different chat model for that request.",
18
+ ].join(" "),
19
+ }));
20
+ ctx.effect(() => ctx.tools.register(defineTool({
21
+ name: "generate_image",
22
+ description: "Generate an image with the signed-in account's image model. The current conversation and its chat model stay as they are.",
23
+ parameters: {
24
+ prompt: { type: "string", required: true, description: "What the image should show." },
25
+ model: { type: "string", description: "Optional image model ID from this connection's imported models." },
26
+ aspect_ratio: { type: "string", description: "Optional ratio such as 1:1, 16:9, or 9:16." },
27
+ image_url: { type: "string", description: "Optional source image URL when the user wants an edit rather than a new image." },
28
+ },
29
+ output: {
30
+ schema: { type: "string" },
31
+ render: (_args, value) => [{ type: "text", text: value }],
32
+ },
33
+ timeoutMs: 120000,
34
+ async execute(args, exec) {
35
+ return runMedia(ctx, "image", args, exec, resolveGrant, pulls);
36
+ },
37
+ })));
38
+ ctx.effect(() => ctx.tools.register(defineTool({
39
+ name: "generate_video",
40
+ description: "Generate a short video with the signed-in account's video model. The current conversation and its chat model stay as they are.",
41
+ parameters: {
42
+ prompt: { type: "string", required: true, description: "What the video should show." },
43
+ model: { type: "string", description: "Optional video model ID from this connection's imported models." },
44
+ aspect_ratio: { type: "string", description: "Optional ratio such as 16:9 or 9:16." },
45
+ duration: { type: "number", description: "Length in seconds, from 1 to 15." },
46
+ image_url: { type: "string", description: "Optional still image URL to animate." },
47
+ },
48
+ output: {
49
+ schema: { type: "string" },
50
+ render: (_args, value) => [{ type: "text", text: value }],
51
+ },
52
+ timeoutMs: 180000,
53
+ async execute(args, exec) {
54
+ return runMedia(ctx, "video", args, exec, resolveGrant, pulls);
55
+ },
56
+ })));
57
+ }
58
+
59
+ const MEDIA_BASE = {
60
+ xai: "https://api.x.ai/v1",
61
+ };
62
+
63
+ async function runMedia(ctx, role, args, exec, resolveGrant, pulls) {
64
+ const chatProvider = exec.agent?.options?.provider;
65
+ const chatModel = exec.agent?.options?.model;
66
+ const target = await mediaTarget(chatProvider, role, args.model, pulls);
67
+ if (target === undefined) {
68
+ if (args.model) throw new Error("所选媒体模型不在此连接已导入的对应目录中。");
69
+ throw new Error(`当前对话还没有可用的${role === "image" ? "生图" : "生视频"}模型。对话模型保持不变。`);
70
+ }
71
+ if (target.base === undefined) {
72
+ throw new Error(`${target.provider} 的${role === "image" ? "生图" : "生视频"}模型还不能在当前对话里调用。对话模型保持不变。`);
73
+ }
74
+ const grant = await resolveGrant(target.provider);
75
+ const access = grant.access;
76
+ if (access.length === 0) throw new Error("OAuth 登录已失效,无法调用媒体模型。对话模型保持不变。");
77
+ const url = role === "image"
78
+ ? await generateImage(target.base, access, target.model, args.prompt, args.aspect_ratio, args.image_url, exec.signal)
79
+ : await generateVideo(target.base, access, target.model, args.prompt, args.aspect_ratio, args.duration, args.image_url, exec.signal);
80
+ const stayed = chatModel ? `当前对话模型仍是 ${chatModel}。` : "当前对话模型未改变。";
81
+ return `已用 ${target.model} 完成${role === "image" ? "生图" : "生视频"}。${stayed}\n${url}`;
82
+ }
83
+
84
+ async function mediaTarget(chatProvider, role, selected, pulls) {
85
+ if (typeof chatProvider !== "string" || chatProvider.length === 0) return undefined;
86
+ const pull = (await pulls.list()).find((item) => item.id === chatProvider);
87
+ const model = pull?.media?.find((item) => item.role === role && (!selected || item.id === selected));
88
+ if (!model) return undefined;
89
+ return { provider: chatProvider, model: model.id, base: MEDIA_BASE[chatProvider] };
90
+ }
91
+
92
+ async function generateImage(base, access, model, prompt, aspectRatio, imageUrl, signal) {
93
+ const edit = typeof imageUrl === "string" && imageUrl.length > 0;
94
+ const body = edit
95
+ ? { model, prompt, image: { url: imageUrl, type: "image_url" } }
96
+ : { model, prompt, response_format: "url" };
97
+ if (typeof aspectRatio === "string" && aspectRatio.length > 0) body.aspect_ratio = aspectRatio;
98
+ const payload = await postMedia(base, access, edit ? "/images/edits" : "/images/generations", body, signal);
99
+ const url = payload?.data?.[0]?.url ?? payload?.url;
100
+ if (typeof url !== "string" || url.length === 0) throw new Error("生图接口没有返回图片地址");
101
+ return url;
102
+ }
103
+
104
+ async function generateVideo(base, access, model, prompt, aspectRatio, duration, imageUrl, signal) {
105
+ const seconds = Number.isFinite(duration) ? Math.min(15, Math.max(1, Math.round(duration))) : 6;
106
+ const body = { model, prompt, duration: seconds, resolution: "720p" };
107
+ if (typeof aspectRatio === "string" && aspectRatio.length > 0) body.aspect_ratio = aspectRatio;
108
+ if (typeof imageUrl === "string" && imageUrl.length > 0) body.image = { url: imageUrl };
109
+ const started = await postMedia(base, access, "/videos/generations", body, signal);
110
+ const immediate = started?.video?.url ?? started?.url;
111
+ if (typeof immediate === "string" && immediate.length > 0) return immediate;
112
+ const requestId = started?.request_id ?? started?.id;
113
+ if (typeof requestId !== "string" || requestId.length === 0) throw new Error("生视频接口没有返回任务编号");
114
+ const deadline = Date.now() + 150000;
115
+ while (Date.now() < deadline) {
116
+ if (signal?.aborted) throw new Error("生视频已取消");
117
+ await new Promise((resolve) => setTimeout(resolve, 3000));
118
+ const status = await getMedia(base, access, `/videos/${encodeURIComponent(requestId)}`, signal);
119
+ const url = status?.video?.url ?? status?.url;
120
+ if (typeof url === "string" && url.length > 0) return url;
121
+ const state = String(status?.status ?? status?.state ?? "").toLowerCase();
122
+ if (state === "failed" || state === "error") throw new Error(status?.error ?? "生视频失败");
123
+ }
124
+ throw new Error("生视频超时,对话模型未改变");
125
+ }
126
+
127
+ async function postMedia(base, access, path, body, signal) {
128
+ return mediaRequest(base, access, path, { method: "POST", body: JSON.stringify(body) }, signal);
129
+ }
130
+
131
+ async function getMedia(base, access, path, signal) {
132
+ return mediaRequest(base, access, path, { method: "GET" }, signal);
133
+ }
134
+
135
+ async function mediaRequest(base, access, path, init, signal) {
136
+ const response = await fetch(`${base}${path}`, {
137
+ ...init,
138
+ headers: {
139
+ accept: "application/json",
140
+ authorization: `Bearer ${access}`,
141
+ ...(init.body ? { "content-type": "application/json" } : {}),
142
+ },
143
+ signal,
144
+ });
145
+ const text = await response.text();
146
+ if (!response.ok) throw new Error(`${response.status}${text ? `: ${text.slice(0, 180)}` : ""}`);
147
+ try {
148
+ return JSON.parse(text);
149
+ } catch {
150
+ throw new Error("媒体接口返回的不是 JSON");
151
+ }
152
+ }