@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.
- package/README.en.md +155 -0
- package/README.md +101 -2
- package/app.js +1045 -0
- package/auth.html +80 -0
- package/client.js +31 -0
- package/cordis.patch.yml +4 -0
- package/docs/CONNECTIONS.md +77 -0
- package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
- package/docs/RELEASE-1.0.1.md +48 -0
- package/docs/RELEASE-1.0.2.md +8 -0
- package/docs/VALIDATION.md +59 -0
- package/docs/evidence/live-1.0.1.json +135 -0
- package/docs/evidence/release-1.0.1.json +38 -0
- package/index.html +43 -0
- package/package.json +64 -4
- package/providers.js +73 -0
- package/scripts/check-upstreams.mjs +27 -0
- package/scripts/link-peers.js +38 -0
- package/scripts/verify-browser.mjs +297 -0
- package/scripts/verify-host.mjs +431 -0
- package/scripts/verify-live.mjs +268 -0
- package/scripts/verify-package.mjs +168 -0
- package/scripts/verify-persistence.mjs +307 -0
- package/scripts/verify-subscriptions-ui.mjs +321 -0
- package/src/account.js +85 -0
- package/src/account.test.js +52 -0
- package/src/authorization.js +199 -0
- package/src/authorization.test.js +332 -0
- package/src/catalog.js +180 -0
- package/src/catalog.test.js +146 -0
- package/src/chat-recovery.js +110 -0
- package/src/chat-recovery.test.js +261 -0
- package/src/connection-runtime.js +129 -0
- package/src/connection-runtime.test.js +244 -0
- package/src/connections.js +70 -0
- package/src/grants.js +104 -0
- package/src/grants.test.js +340 -0
- package/src/index.js +676 -0
- package/src/local-imports.js +263 -0
- package/src/local-imports.test.js +201 -0
- package/src/media.js +152 -0
- package/src/models.js +610 -0
- package/src/models.test.js +503 -0
- package/src/profile-store.js +51 -0
- package/src/pulls.js +100 -0
- package/src/pulls.test.js +156 -0
- package/src/qwen.js +141 -0
- package/src/qwen.test.js +35 -0
- package/src/request-errors.js +50 -0
- package/src/request-errors.test.js +131 -0
- package/src/routes.js +47 -0
- package/src/routes.test.js +136 -0
- package/src/subscription-models.test.js +160 -0
- package/src/usage/aggregators.js +292 -0
- package/src/usage/aggregators.test.js +316 -0
- package/src/usage/core.js +68 -0
- package/src/usage/index.js +93 -0
- package/src/usage/official.js +339 -0
- package/src/usage/official.test.js +273 -0
- package/src/usage/service.test.js +89 -0
- package/src/xai-browser.js +272 -0
- package/src/xai-browser.test.js +256 -0
- package/src/xai-login.js +121 -0
- package/src/xai-login.test.js +259 -0
- package/styles.css +364 -0
- package/theme.js +118 -0
- package/upstreams.json +10 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Explicit live, read-only supplier acceptance. Never invokes inference.
|
|
4
|
+
* node scripts/verify-live.mjs --runtime /path/to/runtime --plan /private/plan.json --out /path/to/report.json
|
|
5
|
+
* Plan: { entries: [{provider:'openai-codex',mode:'local',source:'codex'},
|
|
6
|
+
* {provider:'openrouter',mode:'local',source:'opencode'},
|
|
7
|
+
* {provider:'xai',mode:'native',credentialsFile:'/canonical/.credentials.yaml'}] }
|
|
8
|
+
* Native refreshes commit only to the original credential file; all connection
|
|
9
|
+
* metadata, local-source mirrors, settings and pulls use a disposable profile.
|
|
10
|
+
* --self-test uses fake sources and intercepts all supplier requests.
|
|
11
|
+
*/
|
|
12
|
+
import assert from 'node:assert/strict';
|
|
13
|
+
import { execFile as execCallback } from 'node:child_process';
|
|
14
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
15
|
+
import { cp, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, symlink, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { createServer } from 'node:http';
|
|
17
|
+
import { createRequire } from 'node:module';
|
|
18
|
+
import { tmpdir } from 'node:os';
|
|
19
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
20
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
21
|
+
import { promisify } from 'node:util';
|
|
22
|
+
|
|
23
|
+
const execFile = promisify(execCallback);
|
|
24
|
+
const script = fileURLToPath(import.meta.url);
|
|
25
|
+
const root = resolve(dirname(script), '..');
|
|
26
|
+
const prefix = 'DSH_LIVE_RESULT=';
|
|
27
|
+
const hash = value => createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(value)).digest('hex');
|
|
28
|
+
const argument = name => { const index = process.argv.indexOf(name); return index < 0 ? undefined : process.argv[index + 1]; };
|
|
29
|
+
const fail = (code, details = {}) => Object.assign(new Error(code), { safeCode: code, safeDetails: details });
|
|
30
|
+
const safeError = error => ({ code: error?.safeCode ?? 'verification-failed', ...(error?.safeDetails ?? {}) });
|
|
31
|
+
const atomic = async (path, value) => { const temporary = `${path}.${randomUUID()}.tmp`; await mkdir(dirname(path), { recursive: true }); await writeFile(temporary, JSON.stringify(value, null, 2), { mode: 0o600 }); await rename(temporary, path); };
|
|
32
|
+
const sourcePaths = (entry, environment) => entry.source === 'codex'
|
|
33
|
+
? join(environment.CODEX_HOME || join(environment.HOME, '.codex'), 'auth.json')
|
|
34
|
+
: join(environment.XDG_DATA_HOME || join(environment.HOME, '.local', 'share'), 'opencode', 'auth.json');
|
|
35
|
+
const redactedModel = model => ({ idHash: hash(model.id), role: model.role, source: model.source, entitlement: model.entitlement,
|
|
36
|
+
declaredCapabilities: ['input', 'output', 'tools', 'reasoning', 'reasoningEfforts', 'contextWindow', 'maxTokens', 'compat'].filter(key => model[key] !== undefined) });
|
|
37
|
+
const redactUsage = result => ({ status: result.status, source: result.snapshot?.source, observedAt: result.snapshot?.observedAt,
|
|
38
|
+
windowCount: result.snapshot?.windows?.length ?? 0, balanceCount: result.snapshot?.balances?.length ?? 0,
|
|
39
|
+
units: [...new Set([...(result.snapshot?.windows ?? []), ...(result.snapshot?.balances ?? [])].map(row => row.unit).filter(Boolean))],
|
|
40
|
+
resetCount: (result.snapshot?.windows ?? []).filter(row => row.resetAt || row.nextRegenAt).length,
|
|
41
|
+
planPresent: !!result.snapshot?.plan, noteCodes: result.snapshot?.notes ?? [],
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
if (argument('--worker')) await worker(argument('--worker'), resolve(argument('--sandbox')));
|
|
46
|
+
else await orchestrate();
|
|
47
|
+
} catch (error) {
|
|
48
|
+
// Never print stack, raw HTTP bodies, child stderr, source files or tokens.
|
|
49
|
+
const result = { ok: false, error: safeError(error) };
|
|
50
|
+
if (argument('--worker')) process.stdout.write(prefix + JSON.stringify(result) + '\n');
|
|
51
|
+
else { if (argument('--out')) await atomic(resolve(argument('--out')), result); process.stdout.write(JSON.stringify(result, null, 2) + '\n'); }
|
|
52
|
+
process.exitCode = 1;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function orchestrate() {
|
|
56
|
+
const runtime = resolve(argument('--runtime') ?? join(root, 'node_modules/.dsh-peers-0.2.2-rc.3'));
|
|
57
|
+
const modules = runtime.endsWith('node_modules') ? runtime : join(runtime, 'node_modules');
|
|
58
|
+
const selfTest = process.argv.includes('--self-test');
|
|
59
|
+
let plan;
|
|
60
|
+
if (selfTest) plan = { entries: [{ provider: 'openai-codex', mode: 'local', source: 'codex' }, { provider: 'openrouter', mode: 'local', source: 'opencode' }] };
|
|
61
|
+
else {
|
|
62
|
+
const path = argument('--plan');
|
|
63
|
+
if (!path || !isAbsolute(path)) throw fail('absolute-private-plan-required');
|
|
64
|
+
if ((await stat(path)).mode & 0o077) throw fail('plan-file-must-be-owner-only');
|
|
65
|
+
plan = JSON.parse(await readFile(path, 'utf8'));
|
|
66
|
+
}
|
|
67
|
+
if (!Array.isArray(plan.entries) || !plan.entries.length || plan.entries.length > 10) throw fail('invalid-plan');
|
|
68
|
+
const supported = new Set(['openai-codex', 'openrouter', 'xai']);
|
|
69
|
+
for (const entry of plan.entries) {
|
|
70
|
+
if (!supported.has(entry.provider) || !['native', 'local'].includes(entry.mode)) throw fail('unsupported-live-plan-entry');
|
|
71
|
+
if (entry.mode === 'local' && !['codex', 'opencode'].includes(entry.source)) throw fail('unsupported-local-source');
|
|
72
|
+
if (entry.mode === 'native' && (!isAbsolute(entry.credentialsFile ?? '') || entry.provider !== 'xai')) throw fail('canonical-native-source-required');
|
|
73
|
+
if (Object.keys(entry).some(key => !['provider', 'mode', 'source', 'credentialsFile'].includes(key))) throw fail('unexpected-plan-field');
|
|
74
|
+
}
|
|
75
|
+
if (new Set(plan.entries.map(entry => entry.provider)).size !== plan.entries.length) throw fail('duplicate-provider');
|
|
76
|
+
const sandbox = await mkdtemp(join(tmpdir(), 'dsh-oauth-live-'));
|
|
77
|
+
const manifest = { marker: randomUUID(), createdAt: new Date().toISOString(), selfTest, entries: plan.entries };
|
|
78
|
+
try {
|
|
79
|
+
await mkdir(join(sandbox, 'plugin'), { recursive: true });
|
|
80
|
+
for (const path of ['src', 'package.json', 'client.js', 'index.html', 'auth.html', 'app.js', 'providers.js', 'styles.css', 'theme.js']) await cp(join(root, path), join(sandbox, 'plugin', path), { recursive: true });
|
|
81
|
+
await symlink(modules, join(sandbox, 'plugin/node_modules'), 'dir');
|
|
82
|
+
const environment = { ...process.env, DSH_HOME: join(sandbox, 'home'), DSH_OAUTH_LIVE_MARKER: manifest.marker };
|
|
83
|
+
if (selfTest) {
|
|
84
|
+
environment.CODEX_HOME = join(sandbox, 'fixtures/codex'); environment.XDG_DATA_HOME = join(sandbox, 'fixtures/data');
|
|
85
|
+
const jwt = `mock.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url')}.signature`;
|
|
86
|
+
await atomic(join(environment.CODEX_HOME, 'auth.json'), { auth_mode: 'chatgpt', tokens: { access_token: jwt, refresh_token: 'never-copy-refresh', account_id: 'fixture-account' } });
|
|
87
|
+
await atomic(join(environment.XDG_DATA_HOME, 'opencode/auth.json'), { openrouter: { type: 'api', key: 'fixture-router-key' } });
|
|
88
|
+
}
|
|
89
|
+
await atomic(join(sandbox, 'manifest.json'), manifest);
|
|
90
|
+
const sourceBefore = new Map();
|
|
91
|
+
for (const entry of plan.entries.filter(row => row.mode === 'local')) {
|
|
92
|
+
const path = sourcePaths(entry, environment);
|
|
93
|
+
sourceBefore.set(entry.provider, hash(await readFile(path)));
|
|
94
|
+
}
|
|
95
|
+
const stages = [];
|
|
96
|
+
for (const stage of ['import-and-query', 'restart-and-query']) {
|
|
97
|
+
try {
|
|
98
|
+
const { stdout } = await execFile(process.execPath, [script, '--worker', stage, '--sandbox', sandbox], { env: environment, cwd: sandbox, encoding: 'utf8', timeout: 180000, maxBuffer: 1024 * 1024 });
|
|
99
|
+
const line = stdout.split('\n').find(line => line.startsWith(prefix));
|
|
100
|
+
if (!line) throw fail('worker-result-missing', { stage });
|
|
101
|
+
const result = JSON.parse(line.slice(prefix.length)); if (!result.ok) throw fail('worker-failed', { stage, workerError: result.error });
|
|
102
|
+
stages.push(result);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
const line = typeof error.stdout === 'string' ? error.stdout.split('\n').find(line => line.startsWith(prefix)) : undefined;
|
|
105
|
+
if (line) throw fail('live-stage-failed', { stage, result: JSON.parse(line.slice(prefix.length)) });
|
|
106
|
+
throw error.safeCode ? error : fail('worker-execution-failed', { stage });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
assert.notEqual(stages[0].pid, stages[1].pid);
|
|
110
|
+
const sourceUnchanged = [];
|
|
111
|
+
for (const entry of plan.entries.filter(row => row.mode === 'local')) sourceUnchanged.push({ provider: entry.provider, unchanged: sourceBefore.get(entry.provider) === hash(await readFile(sourcePaths(entry, environment))) });
|
|
112
|
+
const versions = {};
|
|
113
|
+
for (const name of ['@deepseek-ai/cordis', '@deepseek-ai/dsh-credentials', '@deepseek-ai/dsh-credentials-local', '@deepseek-ai/dsh-llm-pi-ai', '@earendil-works/pi-ai']) versions[name] = JSON.parse(await readFile(join(modules, name, 'package.json'), 'utf8')).version;
|
|
114
|
+
const sourceSha256 = {};
|
|
115
|
+
for (const name of ['package.json', ...(await readdir(join(sandbox, 'plugin/src'), { recursive: true })).filter(name => name.endsWith('.js') && !name.endsWith('.test.js')).map(name => `src/${name}`)]) sourceSha256[name] = hash(await readFile(join(sandbox, 'plugin', name)));
|
|
116
|
+
const report = { ok: true, checkedAt: new Date().toISOString(), mode: selfTest ? 'offline-harness-self-test' : 'live-provider-read-only', versions,
|
|
117
|
+
providers: plan.entries.map(({ provider, mode, source }) => ({ provider, mode, ...(source ? { source } : {}) })), stages, sourceUnchanged, sourceSha256,
|
|
118
|
+
boundaries: { inferenceRequests: 0, liveProviderReads: !selfTest, profile: 'temporary isolated profile removed after verification', credentials: 'local sources read-only; native OAuth uses original canonical record and atomic refresh only', secretsInReport: false, usageAmountsInReport: false, sourcePathsInReport: false, longTermElapsedDaysProven: false } };
|
|
119
|
+
if (argument('--out')) await atomic(resolve(argument('--out')), report);
|
|
120
|
+
process.stdout.write(JSON.stringify(report, null, 2) + '\n');
|
|
121
|
+
} finally { await rm(sandbox, { recursive: true, force: true }); }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function worker(stage, sandbox) {
|
|
125
|
+
const manifest = JSON.parse(await readFile(join(sandbox, 'manifest.json'), 'utf8'));
|
|
126
|
+
if (manifest.marker !== process.env.DSH_OAUTH_LIVE_MARKER || process.env.DSH_HOME !== join(sandbox, 'home')) throw fail('worker-sandbox-mismatch');
|
|
127
|
+
const pluginRoot = join(sandbox, 'plugin');
|
|
128
|
+
const selected = createRequire(join(pluginRoot, 'package.json'));
|
|
129
|
+
const load = name => import(pathToFileURL(selected.resolve(name)).href);
|
|
130
|
+
const [{ Context, Service }, { CredentialProvider, credentialKey }, local, adapter, authorization] = await Promise.all([
|
|
131
|
+
load('@deepseek-ai/cordis'), load('@deepseek-ai/dsh-credentials'), load('@deepseek-ai/dsh-credentials-local'), load('@deepseek-ai/dsh-llm-pi-ai'), load('@deepseek-ai/dsh-authorization'),
|
|
132
|
+
]);
|
|
133
|
+
const profile = join(sandbox, 'home/profiles/live-check'); await mkdir(profile, { recursive: true });
|
|
134
|
+
const settingsPath = join(profile, 'live-settings.json');
|
|
135
|
+
let settings = { providers: {} };
|
|
136
|
+
try { settings = JSON.parse(await readFile(settingsPath, 'utf8')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
137
|
+
let revision = 0;
|
|
138
|
+
const contexts = [];
|
|
139
|
+
const isolated = new Context(); contexts.push(isolated);
|
|
140
|
+
await isolated.plugin(local.default, { path: join(sandbox, 'home/.credentials.yaml'), watch: false });
|
|
141
|
+
const native = new Map();
|
|
142
|
+
for (const entry of manifest.entries.filter(row => row.mode === 'native')) {
|
|
143
|
+
const source = new Context(); contexts.push(source);
|
|
144
|
+
await source.plugin(local.default, { path: entry.credentialsFile, watch: false });
|
|
145
|
+
native.set(credentialKey('llm-pi-ai', entry.provider), source.credentials);
|
|
146
|
+
}
|
|
147
|
+
class SelectedCredentials extends CredentialProvider {
|
|
148
|
+
target(key) { return native.get(key) ?? isolated.credentials; }
|
|
149
|
+
resolve(ref) { return isolated.credentials.resolve(ref); }
|
|
150
|
+
describe(ref) { return isolated.credentials.describe(ref); }
|
|
151
|
+
set(ref, value) { return isolated.credentials.set(ref, value); }
|
|
152
|
+
unset(ref) { return isolated.credentials.unset(ref); }
|
|
153
|
+
readRecord(key) { return this.target(key).readRecord(key); }
|
|
154
|
+
describeRecord(key) { return this.target(key).describeRecord(key); }
|
|
155
|
+
modifyRecord(key, mutate) { return this.target(key).modifyRecord(key, mutate); }
|
|
156
|
+
deleteRecord(key) { if (native.has(key)) throw fail('canonical-deletion-forbidden'); return isolated.credentials.deleteRecord(key); }
|
|
157
|
+
async listRecords() { return [...await isolated.credentials.listRecords(), ...await Promise.all([...native].map(async ([key, value]) => ({ key, ...(await value.describeRecord(key)) })))]; }
|
|
158
|
+
}
|
|
159
|
+
class PersistentSettings extends Service {
|
|
160
|
+
constructor(ctx) { super(ctx, 'settings'); }
|
|
161
|
+
describe() { return [{ ns: 'llm-pi-ai', user: structuredClone(settings), value: structuredClone(settings), revision }]; }
|
|
162
|
+
async mutate(namespace, operations, expectedRevision) {
|
|
163
|
+
assert.equal(namespace, 'llm-pi-ai'); assert.equal(expectedRevision, revision);
|
|
164
|
+
const next = structuredClone(settings);
|
|
165
|
+
for (const operation of operations) {
|
|
166
|
+
let parent = next; for (const part of operation.path.slice(0, -1)) parent = parent[part] ??= {};
|
|
167
|
+
if (operation.op === 'unset') delete parent[operation.path.at(-1)]; else parent[operation.path.at(-1)] = structuredClone(operation.value);
|
|
168
|
+
}
|
|
169
|
+
adapter.Config(next); await atomic(settingsPath, next); settings = next; revision++;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const routes = [];
|
|
173
|
+
class WebServer extends Service { constructor(ctx) { super(ctx, 'webServer'); } register(route) { routes.push(route); return () => routes.splice(routes.indexOf(route), 1); } }
|
|
174
|
+
const ctx = new Context(); contexts.push(ctx);
|
|
175
|
+
ctx.provide('profileContext', { name: 'live-check', dir: profile, home: process.env.DSH_HOME, patchPath: join(profile, 'cordis.patch.yml') });
|
|
176
|
+
const requests = [];
|
|
177
|
+
const originalFetch = globalThis.fetch;
|
|
178
|
+
const allowed = new Map([
|
|
179
|
+
['chatgpt.com', new Set(['/backend-api/codex/models', '/backend-api/wham/usage'])],
|
|
180
|
+
['openrouter.ai', new Set(['/api/v1/models/user', '/api/v1/key', '/api/v1/credits'])],
|
|
181
|
+
['cli-chat-proxy.grok.com', new Set(['/v1/models', '/v1/billing'])], ['api.x.ai', new Set(['/v1/models'])],
|
|
182
|
+
['auth.x.ai', new Set(['/oauth2/token'])],
|
|
183
|
+
]);
|
|
184
|
+
let loopback;
|
|
185
|
+
globalThis.fetch = async (url, options = {}) => {
|
|
186
|
+
const target = new URL(String(url));
|
|
187
|
+
if (target.origin === loopback) return originalFetch(url, options);
|
|
188
|
+
const method = options.method ?? 'GET';
|
|
189
|
+
if (target.protocol !== 'https:' || !allowed.get(target.hostname)?.has(target.pathname) || !['GET', 'POST'].includes(method)) throw fail('unexpected-network-route');
|
|
190
|
+
if (method !== 'GET' && !(target.hostname === 'auth.x.ai' && target.pathname === '/oauth2/token' && new URLSearchParams(options.body).get('grant_type') === 'refresh_token')) throw fail('non-read-only-network-request');
|
|
191
|
+
const item = { host: target.hostname, path: target.pathname, method }; requests.push(item);
|
|
192
|
+
try {
|
|
193
|
+
const response = manifest.selfTest ? fixture(target) : await originalFetch(url, { ...options, redirect: 'error' });
|
|
194
|
+
item.status = response.status; return response;
|
|
195
|
+
} catch (error) { item.failed = true; throw error; }
|
|
196
|
+
};
|
|
197
|
+
let server;
|
|
198
|
+
const result = { ok: false, stage, pid: process.pid, providers: [], requests };
|
|
199
|
+
try {
|
|
200
|
+
await ctx.plugin(SelectedCredentials); await ctx.plugin(PersistentSettings); await ctx.plugin(WebServer); await ctx.plugin(authorization.default);
|
|
201
|
+
for (const entry of manifest.entries.filter(row => row.mode === 'native')) ctx.authorization.registerFlow({ key: credentialKey('llm-pi-ai', entry.provider), label: entry.provider, methods: [{ id: 'oauth', label: 'Existing authorization' }], async run() { throw fail('live-login-forbidden'); } });
|
|
202
|
+
await ctx.plugin(await import(pathToFileURL(join(pluginRoot, 'src/index.js')).href));
|
|
203
|
+
const route = routes.find(route => route.path === '/oauth'); if (!route) throw fail('host-route-missing');
|
|
204
|
+
server = createServer((req, res) => { if (!req.url?.startsWith('/oauth/')) { res.writeHead(404); res.end(); return; } void route.handler(req, res); });
|
|
205
|
+
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); loopback = `http://127.0.0.1:${server.address().port}`;
|
|
206
|
+
const request = async (path, body) => {
|
|
207
|
+
const response = await fetch(`${loopback}${path}`, body === undefined ? {} : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
|
208
|
+
const data = await response.json(); if (!response.ok) throw fail('panel-request-failed', { operation: path, provider: body?.provider, httpStatus: response.status, requests });
|
|
209
|
+
return data;
|
|
210
|
+
};
|
|
211
|
+
const { createPullStore } = await import(pathToFileURL(join(pluginRoot, 'src/pulls.js')).href);
|
|
212
|
+
const pulls = createPullStore(profile);
|
|
213
|
+
const prior = stage === 'restart-and-query' ? JSON.parse(await readFile(join(profile, 'live-expectations.json'), 'utf8')) : {};
|
|
214
|
+
if (stage === 'restart-and-query') {
|
|
215
|
+
const cache = JSON.parse(await readFile(join(profile, 'dsh-oauth-usage.json'), 'utf8'));
|
|
216
|
+
for (const entry of manifest.entries) assert.equal(cache.entries[entry.provider].result.snapshot.observedAt, prior[entry.provider].observedAt);
|
|
217
|
+
// Prove the persisted observation first, then remove only the disposable
|
|
218
|
+
// cache to make the restarted query a genuine second supplier read.
|
|
219
|
+
await rm(join(profile, 'dsh-oauth-usage.json'));
|
|
220
|
+
}
|
|
221
|
+
const expected = {};
|
|
222
|
+
for (const entry of manifest.entries) {
|
|
223
|
+
const id = entry.provider;
|
|
224
|
+
if (stage === 'import-and-query' && entry.mode === 'local') await request('/oauth/api/import', { provider: id, source: entry.source });
|
|
225
|
+
if (stage === 'restart-and-query') {
|
|
226
|
+
const pull = await pulls.read(id); assert.equal(pull?.expiresAt, null);
|
|
227
|
+
assert.equal(hash(pull), prior[id].pullHash); assert.equal(hash(settings.providers[id]), prior[id].routeHash);
|
|
228
|
+
}
|
|
229
|
+
const { models } = await request('/oauth/api/models', { provider: id });
|
|
230
|
+
if (!Array.isArray(models) || !models.some(model => model.role === 'chat')) throw fail('no-chat-models-returned', { provider: id });
|
|
231
|
+
const chosen = stage === 'import-and-query' ? models.filter(model => model.role === 'chat').slice(0, 2).map(model => model.id) : prior[id].selected;
|
|
232
|
+
if (!chosen.every(id => models.some(model => model.id === id))) throw fail('selected-model-not-in-restarted-catalog', { provider: id });
|
|
233
|
+
if (stage === 'import-and-query') await request('/oauth/api/pull', { provider: id, models: chosen, expiresAt: null });
|
|
234
|
+
const pull = await pulls.read(id); assert.equal(pull.expiresAt, null); assert.equal(pull.models.length, chosen.length); adapter.Config(settings);
|
|
235
|
+
if (entry.mode === 'local') {
|
|
236
|
+
const connection = await isolated.credentials.readRecord(credentialKey('dsh-oauth-connections', id));
|
|
237
|
+
assert.equal(connection?.payload.mode, 'local');
|
|
238
|
+
assert.equal(Object.hasOwn(connection.payload, 'access'), false); assert.equal(Object.hasOwn(connection.payload, 'refresh'), false);
|
|
239
|
+
const mirrored = await isolated.credentials.readRecord(credentialKey('llm-pi-ai', id));
|
|
240
|
+
if (mirrored) assert.equal(Object.hasOwn(mirrored.payload, 'refresh'), false);
|
|
241
|
+
const reference = settings.providers[id]?.apiKeyEnv;
|
|
242
|
+
if (reference) assert.equal(typeof (await isolated.credentials.resolve(reference))?.value, 'string');
|
|
243
|
+
}
|
|
244
|
+
const usage = await request('/oauth/api/usage', { provider: id, force: true });
|
|
245
|
+
if (!['fresh', 'partial'].includes(usage.status) || !usage.snapshot || !(usage.snapshot.windows?.length || usage.snapshot.balances?.length)) throw fail('live-usage-unavailable', { provider: id, usage: redactUsage(usage), requests });
|
|
246
|
+
const unexpectedNotes = (usage.snapshot.notes ?? []).filter(note => !['account-balance-needs-permission', 'management-balance-has-independent-account-scope'].includes(note));
|
|
247
|
+
if (usage.status === 'partial' && (id !== 'openrouter' || unexpectedNotes.length)) throw fail('unexpected-partial-usage', { provider: id, usage: redactUsage(usage), requests });
|
|
248
|
+
expected[id] = { selected: chosen, pullHash: hash(pull), routeHash: hash(settings.providers[id]), observedAt: usage.snapshot.observedAt };
|
|
249
|
+
result.providers.push({ provider: id, source: entry.mode === 'local' ? entry.source : 'canonical-native', catalogCount: models.length,
|
|
250
|
+
catalogIdHash: hash(models.map(model => model.id).sort()), importedCount: chosen.length, imported: pull.models.map(redactedModel), permanent: pull.expiresAt === null,
|
|
251
|
+
persistentCapabilitiesVerified: stage === 'restart-and-query', usage: redactUsage(usage) });
|
|
252
|
+
}
|
|
253
|
+
if (stage === 'import-and-query') await atomic(join(profile, 'live-expectations.json'), expected);
|
|
254
|
+
const visible = await request('/oauth/api/providers');
|
|
255
|
+
for (const entry of manifest.entries) { const row = visible.providers.find(row => row.id === entry.provider); assert.equal(row.loggedIn, true); assert.equal(row.pullPermanent, true); }
|
|
256
|
+
const providerCredentialsMode = (await stat(join(sandbox, 'home/.credentials.yaml'))).mode & 0o777;
|
|
257
|
+
assert.equal(providerCredentialsMode, 0o600); result.credentialFileMode = '0600'; result.ok = true;
|
|
258
|
+
process.stdout.write(prefix + JSON.stringify(result) + '\n');
|
|
259
|
+
} catch (error) { throw error.safeCode ? error : fail('live-assertion-failed', { stage, requests }); }
|
|
260
|
+
finally { globalThis.fetch = originalFetch; if (server) await new Promise(resolve => server.close(resolve)); for (const context of contexts.reverse()) await context.fiber.dispose(); }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function fixture(url) {
|
|
264
|
+
if (url.pathname.endsWith('/models') || url.pathname.endsWith('/models/user')) return Response.json({ data: [{ id: 'fixture-model', name: 'Fixture', input_modalities: ['text', 'image'], context_window: 128000, max_output_tokens: 8192, supported_parameters: ['tools'], reasoning_efforts: ['high'] }] });
|
|
265
|
+
if (url.pathname.endsWith('/usage')) return Response.json({ plan_type: 'fixture-plan', rate_limit: { primary_window: { used_percent: 10, limit_window_seconds: 18000, reset_at: Math.floor(Date.now() / 1000) + 300 } } });
|
|
266
|
+
if (url.pathname.endsWith('/key')) return Response.json({ data: { limit: 10, usage: 2, limit_remaining: 8 } });
|
|
267
|
+
throw fail('unexpected-self-test-network-request');
|
|
268
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Install and verify a trusted release tarball without registry access or live
|
|
4
|
+
* credentials. Peers come from the selected, already-installed DSH runtime.
|
|
5
|
+
*
|
|
6
|
+
* node scripts/verify-package.mjs --tarball /path/to/package.tgz --runtime /path/to/runtime
|
|
7
|
+
* Optional: --out /path/to/report.json
|
|
8
|
+
*/
|
|
9
|
+
import assert from 'node:assert/strict';
|
|
10
|
+
import { execFile as execFileCallback } from 'node:child_process';
|
|
11
|
+
import { createHash } from 'node:crypto';
|
|
12
|
+
import { lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, symlink, writeFile } from 'node:fs/promises';
|
|
13
|
+
import { createRequire } from 'node:module';
|
|
14
|
+
import { tmpdir } from 'node:os';
|
|
15
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
16
|
+
import { pathToFileURL } from 'node:url';
|
|
17
|
+
import { promisify } from 'node:util';
|
|
18
|
+
|
|
19
|
+
const execFile = promisify(execFileCallback);
|
|
20
|
+
const packageName = '@lks347/dsh-oauth';
|
|
21
|
+
const argument = name => {
|
|
22
|
+
const index = process.argv.indexOf(name);
|
|
23
|
+
if (index < 0) return undefined;
|
|
24
|
+
const value = process.argv[index + 1];
|
|
25
|
+
if (!value || value.startsWith('--')) throw new Error(`${name} requires a path`);
|
|
26
|
+
return resolve(value);
|
|
27
|
+
};
|
|
28
|
+
const tarball = argument('--tarball');
|
|
29
|
+
const runtime = argument('--runtime');
|
|
30
|
+
const output = argument('--out');
|
|
31
|
+
assert.ok(tarball && runtime, '--tarball and --runtime are required');
|
|
32
|
+
const modules = basename(runtime) === 'node_modules' ? runtime : join(runtime, 'node_modules');
|
|
33
|
+
const runtimeRequire = createRequire(join(modules, '.dsh-package-verifier.cjs'));
|
|
34
|
+
const digest = (bytes, algorithm = 'sha256', encoding = 'hex') => createHash(algorithm).update(bytes).digest(encoding);
|
|
35
|
+
const temporary = await mkdtemp(join(tmpdir(), 'dsh-oauth-package-'));
|
|
36
|
+
const runOptions = { maxBuffer: 8 * 1024 * 1024, timeout: 120000 };
|
|
37
|
+
|
|
38
|
+
async function overlayRuntime() {
|
|
39
|
+
const destination = join(temporary, 'node_modules');
|
|
40
|
+
for (const entry of await readdir(modules, { withFileTypes: true })) {
|
|
41
|
+
if (entry.name.startsWith('.')) continue;
|
|
42
|
+
const add = async (name, source) => {
|
|
43
|
+
const target = join(destination, name);
|
|
44
|
+
if (await lstat(target).catch(() => undefined)) return;
|
|
45
|
+
await mkdir(dirname(target), { recursive: true });
|
|
46
|
+
await symlink(await realpath(source), target, 'dir');
|
|
47
|
+
};
|
|
48
|
+
if (entry.name.startsWith('@')) {
|
|
49
|
+
for (const name of await readdir(join(modules, entry.name))) await add(`${entry.name}/${name}`, join(modules, entry.name, name));
|
|
50
|
+
} else await add(entry.name, join(modules, entry.name));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function checkPath(path) {
|
|
55
|
+
assert.ok(path.startsWith('package/'), 'Archive entry must stay under package/');
|
|
56
|
+
assert.ok(!path.includes('\\') && !path.includes('\0') && !path.split('/').includes('..'), 'Archive has an unsafe entry');
|
|
57
|
+
const inside = path.slice('package/'.length);
|
|
58
|
+
const segments = inside.split('/');
|
|
59
|
+
assert.ok(!segments.some(segment => ['node_modules', 'artifacts', '.git', '.npmrc', '.credentials.yaml', '.credentials.yml', 'auth.json', 'credentials.json'].includes(segment)), `Forbidden packaged path: ${inside}`);
|
|
60
|
+
assert.ok(!segments.some(segment => segment === '.env' || segment.startsWith('.env.')), `Environment file must not be packaged: ${inside}`);
|
|
61
|
+
assert.ok(!inside.endsWith('.tgz'), `Nested package archive must not be shipped: ${inside}`);
|
|
62
|
+
return inside;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// High-confidence accidental secrets only. Matches report filenames, never the
|
|
66
|
+
// matched value. Fixture words such as "offline-key" are intentionally allowed.
|
|
67
|
+
const secretPatterns = [
|
|
68
|
+
['npm-token', /npm_[A-Za-z0-9]{30,}/],
|
|
69
|
+
['github-token', /gh[pousr]_[A-Za-z0-9]{30,}/],
|
|
70
|
+
['openrouter-key', /sk-or-v1-[A-Za-z0-9]{25,}/],
|
|
71
|
+
['openai-project-key', /sk-proj-[A-Za-z0-9_-]{40,}/],
|
|
72
|
+
['private-key', /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/],
|
|
73
|
+
['jwt-literal', /eyJ[A-Za-z0-9_-]{50,}\.[A-Za-z0-9_-]{50,}\.[A-Za-z0-9_-]{30,}/],
|
|
74
|
+
];
|
|
75
|
+
|
|
76
|
+
async function executeInstalledCheck(path, extra = []) {
|
|
77
|
+
const { stdout } = await execFile(process.execPath, [path, '--runtime', runtime, ...extra], {
|
|
78
|
+
...runOptions,
|
|
79
|
+
cwd: temporary,
|
|
80
|
+
env: { ...process.env, DSH_HOME: join(temporary, 'test-home'), CODEX_HOME: join(temporary, 'no-codex'), XDG_DATA_HOME: join(temporary, 'no-cli-data') },
|
|
81
|
+
});
|
|
82
|
+
const report = JSON.parse(stdout);
|
|
83
|
+
assert.equal(report.ok, true, `${basename(path)} did not pass`);
|
|
84
|
+
return report;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
const bytes = await readFile(tarball);
|
|
89
|
+
assert.ok(bytes.length > 0 && bytes.length < 32 * 1024 * 1024, 'Tarball is empty or unexpectedly large');
|
|
90
|
+
const { stdout: listed } = await execFile('tar', ['-tzf', tarball], runOptions);
|
|
91
|
+
const { stdout: verbose } = await execFile('tar', ['-tvzf', tarball], runOptions);
|
|
92
|
+
for (const line of verbose.trim().split('\n')) assert.ok(line.startsWith('-') || line.startsWith('d'), 'Archive may contain only regular files and directories');
|
|
93
|
+
const filePaths = listed.trim().split('\n').filter(Boolean).map(checkPath).filter(path => path && !path.endsWith('/'));
|
|
94
|
+
assert.equal(new Set(filePaths).size, filePaths.length, 'Duplicate archive entries are not allowed');
|
|
95
|
+
const required = ['package.json', 'client.js', 'cordis.patch.yml', 'src/index.js', 'src/usage/index.js', 'README.md', 'README.en.md', 'docs/CONNECTIONS.md', 'docs/VALIDATION.md', 'scripts/verify-host.mjs', 'scripts/verify-persistence.mjs'];
|
|
96
|
+
for (const path of required) assert.ok(filePaths.includes(path), `Missing required release file: ${path}`);
|
|
97
|
+
|
|
98
|
+
// An isolated npm installation proves the scoped directory and exports are
|
|
99
|
+
// actually installed. --offline and --legacy-peer-deps prevent registry/peer
|
|
100
|
+
// downloads; --ignore-scripts prevents package lifecycle execution.
|
|
101
|
+
await writeFile(join(temporary, 'package.json'), JSON.stringify({ name: 'dsh-oauth-package-check', version: '0.0.0', private: true, type: 'module' }));
|
|
102
|
+
const userConfig = join(temporary, 'empty.npmrc');
|
|
103
|
+
await writeFile(userConfig, '', { mode: 0o600 });
|
|
104
|
+
await execFile('npm', ['install', '--offline', '--ignore-scripts', '--legacy-peer-deps', '--no-audit', '--no-fund', '--package-lock=false', '--save=false', tarball], {
|
|
105
|
+
...runOptions, cwd: temporary,
|
|
106
|
+
env: { ...process.env, npm_config_userconfig: userConfig, npm_config_cache: join(temporary, 'npm-cache'), npm_config_registry: 'https://registry.npmjs.org/' },
|
|
107
|
+
});
|
|
108
|
+
const installedPath = join(temporary, 'node_modules', '@lks347', 'dsh-oauth');
|
|
109
|
+
assert.equal((await lstat(installedPath)).isSymbolicLink(), false, 'The tarball must be extracted, not linked to the worktree');
|
|
110
|
+
const installedRoot = await realpath(installedPath);
|
|
111
|
+
const installed = JSON.parse(await readFile(join(installedRoot, 'package.json'), 'utf8'));
|
|
112
|
+
assert.equal(installed.name, packageName);
|
|
113
|
+
assert.notEqual(installed.private, true, 'Release package is marked private');
|
|
114
|
+
assert.equal(installed.publishConfig?.access, 'public');
|
|
115
|
+
assert.match(installed.version, /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/);
|
|
116
|
+
const fileHashes = {};
|
|
117
|
+
for (const path of filePaths) {
|
|
118
|
+
const target = join(installedRoot, path);
|
|
119
|
+
assert.equal((await lstat(target)).isFile(), true, `Installed path is not a regular file: ${path}`);
|
|
120
|
+
const content = await readFile(target);
|
|
121
|
+
fileHashes[path] = digest(content);
|
|
122
|
+
for (const [kind, pattern] of secretPatterns) assert.ok(!pattern.test(content.toString('utf8')), `Possible ${kind} in packaged file ${path}; value withheld`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
await overlayRuntime();
|
|
126
|
+
const installedRequire = createRequire(join(temporary, 'package.json'));
|
|
127
|
+
const main = installedRequire.resolve(packageName);
|
|
128
|
+
const client = installedRequire.resolve(`${packageName}/client`);
|
|
129
|
+
const manifest = installedRequire.resolve(`${packageName}/package.json`);
|
|
130
|
+
for (const entry of [main, client, manifest]) assert.ok(relative(installedRoot, entry) !== '..' && !relative(installedRoot, entry).startsWith(`..${sep}`), 'Package exports escaped the installed package');
|
|
131
|
+
assert.equal(manifest, join(installedRoot, 'package.json'));
|
|
132
|
+
const module = await import(pathToFileURL(main).href);
|
|
133
|
+
assert.equal(typeof module.apply, 'function');
|
|
134
|
+
const patchPath = resolve(installedRoot, installed.dsh.bundle.patch);
|
|
135
|
+
assert.ok(!relative(installedRoot, patchPath).startsWith('..'), 'Bundle patch escaped the installed package');
|
|
136
|
+
const { parse } = runtimeRequire('yaml');
|
|
137
|
+
const patches = parse(await readFile(patchPath, 'utf8'));
|
|
138
|
+
const entries = patches.flatMap(patch => patch.insert ?? []);
|
|
139
|
+
const entry = entries.find(item => item.id === 'dsh-oauth');
|
|
140
|
+
assert.equal(entry?.name, packageName, 'Bundle patch must resolve the scoped package');
|
|
141
|
+
assert.equal(installedRequire.resolve(entry.name), main);
|
|
142
|
+
let descriptor;
|
|
143
|
+
new Function('window', await readFile(client, 'utf8'))({ __ModuleLoader__: { load(value) { assert.equal(descriptor, undefined, 'Client registered more than one module'); descriptor = value; } } });
|
|
144
|
+
assert.equal(descriptor?.id, packageName, 'Client module ID must equal the installed package name');
|
|
145
|
+
assert.equal(typeof descriptor?.factory, 'function');
|
|
146
|
+
for (const name of installed.dsh.client.inject) installedRequire.resolve(name);
|
|
147
|
+
|
|
148
|
+
const [host, persistence] = await Promise.all([
|
|
149
|
+
executeInstalledCheck(join(installedRoot, 'scripts', 'verify-host.mjs')),
|
|
150
|
+
executeInstalledCheck(join(installedRoot, 'scripts', 'verify-persistence.mjs')),
|
|
151
|
+
]);
|
|
152
|
+
for (const [path, hash] of Object.entries(host.sourceSha256 ?? {})) assert.equal(fileHashes[path], hash, `Host check did not use the tarball's bytes: ${path}`);
|
|
153
|
+
const report = {
|
|
154
|
+
ok: true,
|
|
155
|
+
checkedAt: new Date().toISOString(),
|
|
156
|
+
package: `${installed.name}@${installed.version}`,
|
|
157
|
+
tarball: { filename: basename(tarball), bytes: bytes.length, sha256: digest(bytes), integrity: `sha512-${digest(bytes, 'sha512', 'base64')}` },
|
|
158
|
+
installedWith: 'npm install --offline --ignore-scripts --legacy-peer-deps (isolated temporary root and cache)',
|
|
159
|
+
files: filePaths.length,
|
|
160
|
+
checks: ['archive paths and types', 'no credential files or high-confidence literal secrets', 'scoped npm installation', 'package exports resolve inside extracted package', 'bundle patch resolves scoped server entry', 'client loader ID matches package name', 'declared client injections resolve', 'installed host smoke', 'installed persistence smoke', 'host-tested bytes match tarball'],
|
|
161
|
+
host: { versions: host.versions, checks: host.checks },
|
|
162
|
+
persistence: { versions: persistence.versions, processes: persistence.checks?.length, checks: persistence.checks },
|
|
163
|
+
sourceSha256: fileHashes,
|
|
164
|
+
boundaries: { registry: 'No registry requests; installation is offline', providers: 'Mock HTTP; no real credential source or paid inference', isolation: 'Temporary installation/profile/cache removed after verification', secretScan: 'Path checks and high-confidence signatures, not proof that arbitrary text cannot contain a secret' },
|
|
165
|
+
};
|
|
166
|
+
if (output) { await mkdir(dirname(output), { recursive: true }); await writeFile(output, JSON.stringify(report, null, 2) + '\n'); }
|
|
167
|
+
console.log(JSON.stringify(report, null, 2));
|
|
168
|
+
} finally { await rm(temporary, { recursive: true, force: true }); }
|