ai_co_discuss 0.3.71 → 0.3.73
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/backend/free_room.py +81 -9
- package/backend/schema.sql +1675 -1645
- package/backend/server.py +19 -8
- package/docs/runner.md +12 -1
- package/package.json +1 -1
- package/runner/adapters/antigravity_cli.mjs +37 -7
- package/runner/adapters/api.mjs +25 -4
- package/runner/adapters/api_files.mjs +36 -19
- package/runner/adapters/claude.mjs +448 -385
- package/runner/adapters/cli.mjs +175 -155
- package/runner/adapters/codex_app.mjs +19 -3
- package/runner/adapters/codex_bridge.mjs +123 -0
- package/runner/adapters/codex_cli.mjs +47 -10
- package/runner/adapters/index.mjs +34 -2
- package/runner/adapters/profiles.mjs +5 -3
- package/runner/device_auth.mjs +39 -21
- package/runner/discussion_launch.mjs +83 -21
- package/runner/discussion_local.mjs +2 -0
- package/runner/discussion_runner.mjs +34 -1
- package/runner/discussion_service.mjs +6 -3
- package/runner/expert_prompts.mjs +21 -11
- package/runner/free_runner.mjs +73 -14
- package/runner/project_files.mjs +57 -5
- package/runner/relay_channel.mjs +4 -3
- package/runner/remote_launch.mjs +268 -268
- package/runner/remote_policy.mjs +2 -1
- package/web/app.js +4955 -4862
- package/web/backup.js +1 -1
- package/web/modern.css +1 -1
- package/web/modern.js +9793 -9187
package/runner/remote_launch.mjs
CHANGED
|
@@ -1,268 +1,268 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Run what other devices relay through a paired website: room launches, and every other local-service operation as an
|
|
3
|
-
* end-to-end encrypted command that only this computer can read; directories and credentials stay here.
|
|
4
|
-
*/
|
|
5
|
-
import { execFileSync, spawn } from 'node:child_process';
|
|
6
|
-
import { generateKeyPairSync, randomBytes, randomUUID } from 'node:crypto';
|
|
7
|
-
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
8
|
-
import { hostname } from 'node:os';
|
|
9
|
-
import { join } from 'node:path';
|
|
10
|
-
import { fileURLToPath } from 'node:url';
|
|
11
|
-
|
|
12
|
-
import { adapter_profile } from './adapters/profiles.mjs';
|
|
13
|
-
import { atomic_json } from './files.mjs';
|
|
14
|
-
import { saved_api_keys } from './discussion_api.mjs';
|
|
15
|
-
import { launch_projects, launch_settings } from './discussion_launch.mjs';
|
|
16
|
-
import { claim_relayed_command } from './remote_policy.mjs';
|
|
17
|
-
import { audit, DEVICE_ACTIONS, device_command, open_signed_request, signed_device_list } from './device_auth.mjs';
|
|
18
|
-
|
|
19
|
-
const MACHINE_TOKEN_BYTES = 32;
|
|
20
|
-
const MACHINE_NAME_MAX = 60;
|
|
21
|
-
const SYNC_TIMEOUT_MS = 10000;
|
|
22
|
-
const LINKS_FILE = 'machine-links.json';
|
|
23
|
-
// The website holds a claim this long when nothing is queued, so a waiting device is answered at once.
|
|
24
|
-
export const COMMAND_WAIT_SECONDS = 20;
|
|
25
|
-
const COMMAND_REQUEST_MARGIN_MS = 10000;
|
|
26
|
-
// Matches LOCAL_LAUNCH_TIMEOUT in backend/server.py, which runs the same entrypoint for the local website.
|
|
27
|
-
const COMMAND_TIMEOUT_MS = 60000;
|
|
28
|
-
const RELAY_CIPHER_INFO = 'codiscuss-relay-v1';
|
|
29
|
-
const LAUNCH_SCRIPT = fileURLToPath(new URL('./discussion_launch.mjs', import.meta.url));
|
|
30
|
-
// What a connected browser may ask the local bridge for, minus the folder dialog nobody would see and pairing itself.
|
|
31
|
-
const RELAYED_ACTIONS = new Set(['settings', 'launch', 'room-models', 'room-member', 'room-member-access', 'room-member-allow', 'room-member-adapter',
|
|
32
|
-
'room-member-model', 'room-profiles', 'room-files', 'room-restore', 'room-fork', 'models', 'api-key', 'api-check', 'scheduler-check', 'tts-settings', 'tts', 'stt', 'projects', 'presets', 'workflows', 'room-workflow', 'room-settings', 'browse-directory']);
|
|
33
|
-
export const ROOM_ACTIONS = new Set(['launch', 'room-models', 'room-member', 'room-member-access', 'room-member-allow', 'room-member-adapter',
|
|
34
|
-
'room-member-model', 'room-profiles', 'room-files', 'room-restore', 'room-fork', 'room-workflow', 'room-settings', 'workflows']);
|
|
35
|
-
|
|
36
|
-
// On Windows the file holding this computer's private keys and tokens is sealed with DPAPI for the signed-in user, so a
|
|
37
|
-
// copy of the file alone is useless elsewhere; other systems rely on the file's 0600 mode.
|
|
38
|
-
const DPAPI = process.platform === 'win32';
|
|
39
|
-
const DPAPI_SCRIPT = mode => 'Add-Type -AssemblyName System.Security;'
|
|
40
|
-
+ '$bytes=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim());'
|
|
41
|
-
+ `[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::${mode}($bytes,$null,'CurrentUser'))`;
|
|
42
|
-
// What the file held when last read or written here, so reading it again does not start PowerShell.
|
|
43
|
-
const links_cache = new Map();
|
|
44
|
-
|
|
45
|
-
/** Seal or open bytes with DPAPI for the current Windows user. */
|
|
46
|
-
function dpapi(mode, base64) {
|
|
47
|
-
return execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', DPAPI_SCRIPT(mode)],
|
|
48
|
-
{ input: base64, encoding: 'utf8', windowsHide: true }).trim();
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Save every site this computer is paired with, sealed on Windows. */
|
|
52
|
-
export function save_machine_links(home, links) {
|
|
53
|
-
const path = join(home, LINKS_FILE);
|
|
54
|
-
const text = JSON.stringify(links);
|
|
55
|
-
const stored = DPAPI ? { dpapi: dpapi('Protect', Buffer.from(text).toString('base64')) } : links;
|
|
56
|
-
atomic_json(path, stored);
|
|
57
|
-
links_cache.set(path, { raw: readFileSync(path, 'utf8'), text });
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** Read every site this computer is paired with; a file saved in the clear by an older version is sealed on first read. */
|
|
61
|
-
export function machine_links(home) {
|
|
62
|
-
const path = join(home, LINKS_FILE);
|
|
63
|
-
if (!existsSync(path)) return { sites: {} };
|
|
64
|
-
const raw = readFileSync(path, 'utf8');
|
|
65
|
-
const cached = links_cache.get(path);
|
|
66
|
-
if (cached?.raw === raw) return JSON.parse(cached.text);
|
|
67
|
-
const stored = JSON.parse(raw);
|
|
68
|
-
if (stored.dpapi) {
|
|
69
|
-
const text = Buffer.from(dpapi('Unprotect', stored.dpapi), 'base64').toString('utf8');
|
|
70
|
-
links_cache.set(path, { raw, text });
|
|
71
|
-
return JSON.parse(text);
|
|
72
|
-
}
|
|
73
|
-
if (DPAPI) save_machine_links(home, stored);
|
|
74
|
-
else links_cache.set(path, { raw, text: JSON.stringify(stored) });
|
|
75
|
-
return stored;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** A fresh P-256 key pair as JWKs; the private half never leaves this computer. */
|
|
79
|
-
function p256_pair() {
|
|
80
|
-
const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
|
|
81
|
-
const { kty, crv, x, y } = publicKey.export({ format: 'jwk' });
|
|
82
|
-
return { public: { kty, crv, x, y }, private: privateKey.export({ format: 'jwk' }) };
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** One key pair to decrypt relayed commands and one to sign the device list the website checks devices against. */
|
|
86
|
-
function command_keys() {
|
|
87
|
-
const command = p256_pair(), signing = p256_pair();
|
|
88
|
-
return { public_key: command.public, private_key: command.private, sign_public_key: signing.public, sign_private_key: signing.private };
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/** Give every paired site both key pairs, kept beside its token; older pairings gain the missing ones on first use. */
|
|
92
|
-
export function keyed_links(home) {
|
|
93
|
-
const links = machine_links(home);
|
|
94
|
-
const missing = Object.values(links.sites).filter(link => !link.private_key || !link.sign_private_key);
|
|
95
|
-
for (const link of missing) {
|
|
96
|
-
const keys = command_keys();
|
|
97
|
-
Object.assign(link, link.private_key ? { sign_public_key: keys.sign_public_key, sign_private_key: keys.sign_private_key } : keys);
|
|
98
|
-
}
|
|
99
|
-
if (missing.length) save_machine_links(home, links);
|
|
100
|
-
return links;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** Return this computer's identity for one site, creating it on first use; the browser then pairs it as administrator. */
|
|
104
|
-
export function machine_link(home, site) {
|
|
105
|
-
const origin = new URL(site).origin;
|
|
106
|
-
const links = machine_links(home);
|
|
107
|
-
links.sites[origin] ||= { id: randomUUID().replaceAll('-', ''), token: randomBytes(MACHINE_TOKEN_BYTES).toString('hex'),
|
|
108
|
-
name: (hostname() || '本机').slice(0, MACHINE_NAME_MAX), ...command_keys() };
|
|
109
|
-
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
110
|
-
save_machine_links(home, links);
|
|
111
|
-
// The browser forwards this to the website, so the private key stays out of it.
|
|
112
|
-
const { id, token, name } = links.sites[origin];
|
|
113
|
-
return { id, token, name };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/** Forget a site's pairing so it can no longer hand launches to this computer. */
|
|
117
|
-
export function unlink_machine(home, site) {
|
|
118
|
-
const links = machine_links(home);
|
|
119
|
-
if (!links.sites[site]) return;
|
|
120
|
-
delete links.sites[site];
|
|
121
|
-
save_machine_links(home, links);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** Resolve the API key saved for a profile's base URL, as the connected browser does. */
|
|
125
|
-
function api_key_ref(profile, keys) {
|
|
126
|
-
if (profile.api_key_ref || !profile.base_url) return profile.api_key_ref;
|
|
127
|
-
try { return keys[new URL(profile.base_url).href.replace(/\/+$/, '')]; } catch { return undefined; }
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/** Platforms this computer can wake without further setup, and the client each uses. */
|
|
131
|
-
export function ready_clients(home) {
|
|
132
|
-
const keys = saved_api_keys(home);
|
|
133
|
-
return Object.fromEntries(Object.entries(launch_settings(home).participants).filter(([, profile]) => {
|
|
134
|
-
const facts = adapter_profile(profile.adapter);
|
|
135
|
-
if (!facts) return false;
|
|
136
|
-
// A model API needs its endpoint and key; other software needs its installed location.
|
|
137
|
-
return facts.kind === 'api' ? Boolean(profile.base_url && profile.api_protocol && profile.model && api_key_ref(profile, keys))
|
|
138
|
-
: Boolean(profile[facts.location]);
|
|
139
|
-
}).map(([name, profile]) => [name, profile.adapter]));
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
async function machine_request(site, link, path, body, { timeout = SYNC_TIMEOUT_MS, signal } = {}) {
|
|
143
|
-
const response = await fetch(`${site}/api/machines/${link.id}${path}`, { method: 'POST', redirect: 'error',
|
|
144
|
-
signal: AbortSignal.any([AbortSignal.timeout(timeout), ...(signal ? [signal] : [])]),
|
|
145
|
-
headers: { 'Content-Type': 'application/json', 'X-Machine-Token': link.token }, body: JSON.stringify(body) });
|
|
146
|
-
const result = await response.json();
|
|
147
|
-
if (!response.ok) throw new Error(`HTTP ${response.status}: ${result.error || '请求失败'}`);
|
|
148
|
-
return result;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Publish projects, clients and this computer's key to each paired site. Launch tasks a site returns are never run:
|
|
153
|
-
* every remote operation must arrive as a device-signed command, and a site's own answer proves nothing.
|
|
154
|
-
*/
|
|
155
|
-
export async function sync_remote_launches(home, { log = () => {} } = {}) {
|
|
156
|
-
const projects = launch_projects(home).projects.filter(project => project.id).map(({ id, name }) => ({ id, name }));
|
|
157
|
-
const clients = ready_clients(home);
|
|
158
|
-
for (const [site, link] of Object.entries(keyed_links(home).sites)) {
|
|
159
|
-
let launches;
|
|
160
|
-
// The device list is signed here, so the website can check devices against it but never add one itself.
|
|
161
|
-
try { ({ launches } = await machine_request(site, link, '/sync', { projects, clients, public_key: link.public_key, sign_key: link.sign_public_key,
|
|
162
|
-
devices: await signed_device_list(home, link) })); }
|
|
163
|
-
catch (error) { log(`${site}: 同步电脑状态失败:${error.message}`); continue; }
|
|
164
|
-
if (launches?.length) log(`${site}: 网站返回了 ${launches.length} 个旧格式启动任务,已忽略;远程启动须由已配对设备签名`);
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/** The AES-GCM key shared with one sending device, derived from its ephemeral key and this computer's private key. */
|
|
169
|
-
export async function relay_cipher(private_jwk, public_jwk) {
|
|
170
|
-
const curve = { name: 'ECDH', namedCurve: 'P-256' };
|
|
171
|
-
const own = await crypto.subtle.importKey('jwk', private_jwk, curve, false, ['deriveBits']);
|
|
172
|
-
const peer = await crypto.subtle.importKey('jwk', public_jwk, curve, false, []);
|
|
173
|
-
const material = await crypto.subtle.importKey('raw', await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, own, 256), 'HKDF', false, ['deriveKey']);
|
|
174
|
-
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: new TextEncoder().encode(RELAY_CIPHER_INFO) },
|
|
175
|
-
material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/** Encrypt a value bound to its command, so the site cannot swap one command's content into another. */
|
|
179
|
-
export async function seal(key, value, label) {
|
|
180
|
-
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
181
|
-
const data = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(label) }, key, new TextEncoder().encode(JSON.stringify(value)));
|
|
182
|
-
return { iv: Buffer.from(iv).toString('base64'), data: Buffer.from(data).toString('base64') };
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** Decrypt a value sealed for the same command label. */
|
|
186
|
-
export async function unseal(key, envelope, label) {
|
|
187
|
-
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: Buffer.from(envelope.iv, 'base64'), additionalData: new TextEncoder().encode(label) },
|
|
188
|
-
key, Buffer.from(envelope.data, 'base64'));
|
|
189
|
-
return JSON.parse(new TextDecoder().decode(plain));
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/** Turn a relayed action into the local entrypoint call the local website makes, pinned to the relaying site. */
|
|
193
|
-
export function relayed_command(site, action, payload) {
|
|
194
|
-
if (!RELAYED_ACTIONS.has(action)) throw new Error('该操作不能经其他设备执行');
|
|
195
|
-
if (payload === undefined ? action !== 'settings' : !payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('命令内容无效');
|
|
196
|
-
let input = payload;
|
|
197
|
-
if (ROOM_ACTIONS.has(action)) {
|
|
198
|
-
const { access_file, ...rest } = payload;
|
|
199
|
-
input = { ...rest, site, entry: 'web' };
|
|
200
|
-
}
|
|
201
|
-
// A path names a folder on the computer itself; another device sends the files it opened.
|
|
202
|
-
if (action === 'workflows' && payload.folder) throw new Error('其他设备请选择 zip 或文件夹导入工作流');
|
|
203
|
-
return { command: action === 'launch' ? 'start' : action, input, browser: action === 'launch' };
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
/** Run the local entrypoint as the local website does, under the limits for other devices, and answer in its HTTP shape. */
|
|
207
|
-
export function run_launch_command({ command, input, browser, device }) {
|
|
208
|
-
return new Promise(resolve => {
|
|
209
|
-
const args = [LAUNCH_SCRIPT, command, '--remote', ...(device ? ['--device', device] : []), ...(browser ? ['--browser'] : []),
|
|
210
|
-
...(input === undefined ? [] : ['--stdin'])];
|
|
211
|
-
const child = spawn(process.execPath, args, { windowsHide: true });
|
|
212
|
-
let stdout = '', stderr = '', timed_out = false;
|
|
213
|
-
child.stdout.setEncoding('utf8').on('data', chunk => { stdout += chunk; });
|
|
214
|
-
child.stderr.setEncoding('utf8').on('data', chunk => { stderr += chunk; });
|
|
215
|
-
const timer = setTimeout(() => { timed_out = true; child.kill(); }, COMMAND_TIMEOUT_MS);
|
|
216
|
-
child.on('error', error => { clearTimeout(timer); resolve({ status: 400, body: { error: error.message } }); });
|
|
217
|
-
child.on('close', code => {
|
|
218
|
-
clearTimeout(timer);
|
|
219
|
-
if (timed_out) return resolve({ status: 400, body: { error: '启动结果未确认,请核对房间状态后沿用原配置重试' } });
|
|
220
|
-
try { resolve(code ? { status: 400, body: JSON.parse(stderr.trim()) } : { status: 200, body: JSON.parse(stdout) }); }
|
|
221
|
-
catch { resolve({ status: 400, body: { error: stderr.trim() || '本机操作失败' } }); }
|
|
222
|
-
});
|
|
223
|
-
child.stdin.end(input === undefined ? '' : JSON.stringify(input));
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/** Decrypt one claimed command, run it, and return the encrypted answer to the device waiting on it. */
|
|
228
|
-
async function answer_command(home, site, link, { id, envelope }, run, log) {
|
|
229
|
-
let key, sealed;
|
|
230
|
-
try {
|
|
231
|
-
key = await relay_cipher(link.private_key, envelope.key);
|
|
232
|
-
sealed = await unseal(key, envelope, id);
|
|
233
|
-
} catch { return log(`${site}: 远程命令 ${id} 无法解密,已忽略`); }
|
|
234
|
-
let response;
|
|
235
|
-
try {
|
|
236
|
-
const { request, device_id } = await open_signed_request(home, id, sealed, link.id);
|
|
237
|
-
claim_relayed_command(home, id, request.sent_at);
|
|
238
|
-
response = DEVICE_ACTIONS.has(request.action) ? await device_command(home, { site, machine_id: link.id, device_id, on_change: () => sync_remote_launches(home) }, request.action, request.payload)
|
|
239
|
-
: await run({ ...relayed_command(site, request.action, request.payload), device: device_id });
|
|
240
|
-
if (!DEVICE_ACTIONS.has(request.action)) audit(home, { event: 'command', action: request.action, route: '', device: device_id, status: response.status });
|
|
241
|
-
}
|
|
242
|
-
catch (error) { response = { status: 400, body: { error: error.message, ...(error.need ? { need: error.need } : {}) } }; }
|
|
243
|
-
try { await machine_request(site, link, `/commands/${encodeURIComponent(id)}`, { envelope: await seal(key, response, `${id}:response`) }); }
|
|
244
|
-
catch (error) { log(`${site}: 远程命令 ${id} 回传失败:${error.message}`); }
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Wait on every paired site for relayed commands and start each one; resolves once the claims return, with the commands
|
|
249
|
-
* still running in `running` so a slow model list never holds up the next claim. `on_failure` hears a claim that failed,
|
|
250
|
-
* so the caller can wait before retrying while a successful claim is followed at once.
|
|
251
|
-
*/
|
|
252
|
-
export async function relay_commands(home, { run = run_launch_command, log = () => {}, wait = COMMAND_WAIT_SECONDS, signal, running = new Set(), on_failure = () => {}, skip = new Set() } = {}) {
|
|
253
|
-
// Keys are created by the sync, which publishes them; a site without one yet has nothing to claim. A site reached
|
|
254
|
-
// through its live relay channel needs no D1 polling.
|
|
255
|
-
await Promise.all(Object.entries(machine_links(home).sites).filter(([site, link]) => link.private_key && !skip.has(site)).map(async ([site, link]) => {
|
|
256
|
-
let commands;
|
|
257
|
-
try { ({ commands } = await machine_request(site, link, '/commands/claim', { wait }, { timeout: wait * 1000 + COMMAND_REQUEST_MARGIN_MS, signal })); }
|
|
258
|
-
catch (error) { if (!signal?.aborted) { log(`${site}: 领取远程命令失败:${error.message}`); on_failure(); } return; }
|
|
259
|
-
for (const command of commands) {
|
|
260
|
-
// A pairing removed or replaced while the claim waited ends here, as on the live channel.
|
|
261
|
-
const current = machine_links(home).sites[site];
|
|
262
|
-
if (current?.token !== link.token || current?.private_key?.d !== link.private_key?.d) { log(`${site}: 配对已撤销或更换,忽略远程命令 ${command.id}`); continue; }
|
|
263
|
-
const task = answer_command(home, site, link, command, run, log).finally(() => running.delete(task));
|
|
264
|
-
running.add(task);
|
|
265
|
-
}
|
|
266
|
-
}));
|
|
267
|
-
return running;
|
|
268
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Run what other devices relay through a paired website: room launches, and every other local-service operation as an
|
|
3
|
+
* end-to-end encrypted command that only this computer can read; directories and credentials stay here.
|
|
4
|
+
*/
|
|
5
|
+
import { execFileSync, spawn } from 'node:child_process';
|
|
6
|
+
import { generateKeyPairSync, randomBytes, randomUUID } from 'node:crypto';
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { hostname } from 'node:os';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
|
|
12
|
+
import { adapter_profile } from './adapters/profiles.mjs';
|
|
13
|
+
import { atomic_json } from './files.mjs';
|
|
14
|
+
import { saved_api_keys } from './discussion_api.mjs';
|
|
15
|
+
import { launch_projects, launch_settings } from './discussion_launch.mjs';
|
|
16
|
+
import { claim_relayed_command } from './remote_policy.mjs';
|
|
17
|
+
import { audit, DEVICE_ACTIONS, device_command, open_signed_request, signed_device_list } from './device_auth.mjs';
|
|
18
|
+
|
|
19
|
+
const MACHINE_TOKEN_BYTES = 32;
|
|
20
|
+
const MACHINE_NAME_MAX = 60;
|
|
21
|
+
const SYNC_TIMEOUT_MS = 10000;
|
|
22
|
+
const LINKS_FILE = 'machine-links.json';
|
|
23
|
+
// The website holds a claim this long when nothing is queued, so a waiting device is answered at once.
|
|
24
|
+
export const COMMAND_WAIT_SECONDS = 20;
|
|
25
|
+
const COMMAND_REQUEST_MARGIN_MS = 10000;
|
|
26
|
+
// Matches LOCAL_LAUNCH_TIMEOUT in backend/server.py, which runs the same entrypoint for the local website.
|
|
27
|
+
const COMMAND_TIMEOUT_MS = 60000;
|
|
28
|
+
const RELAY_CIPHER_INFO = 'codiscuss-relay-v1';
|
|
29
|
+
const LAUNCH_SCRIPT = fileURLToPath(new URL('./discussion_launch.mjs', import.meta.url));
|
|
30
|
+
// What a connected browser may ask the local bridge for, minus the folder dialog nobody would see and pairing itself.
|
|
31
|
+
const RELAYED_ACTIONS = new Set(['settings', 'launch', 'room-models', 'room-member', 'room-member-access', 'room-member-allow', 'room-member-adapter',
|
|
32
|
+
'room-member-model', 'room-profiles', 'room-files', 'execution-details', 'room-restore', 'room-fork', 'models', 'api-key', 'api-check', 'scheduler-check', 'tts-settings', 'tts', 'stt', 'projects', 'presets', 'workflows', 'room-workflow', 'room-settings', 'browse-directory']);
|
|
33
|
+
export const ROOM_ACTIONS = new Set(['launch', 'room-models', 'room-member', 'room-member-access', 'room-member-allow', 'room-member-adapter',
|
|
34
|
+
'room-member-model', 'room-profiles', 'room-files', 'execution-details', 'room-restore', 'room-fork', 'room-workflow', 'room-settings', 'workflows']);
|
|
35
|
+
|
|
36
|
+
// On Windows the file holding this computer's private keys and tokens is sealed with DPAPI for the signed-in user, so a
|
|
37
|
+
// copy of the file alone is useless elsewhere; other systems rely on the file's 0600 mode.
|
|
38
|
+
const DPAPI = process.platform === 'win32';
|
|
39
|
+
const DPAPI_SCRIPT = mode => 'Add-Type -AssemblyName System.Security;'
|
|
40
|
+
+ '$bytes=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim());'
|
|
41
|
+
+ `[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::${mode}($bytes,$null,'CurrentUser'))`;
|
|
42
|
+
// What the file held when last read or written here, so reading it again does not start PowerShell.
|
|
43
|
+
const links_cache = new Map();
|
|
44
|
+
|
|
45
|
+
/** Seal or open bytes with DPAPI for the current Windows user. */
|
|
46
|
+
function dpapi(mode, base64) {
|
|
47
|
+
return execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', DPAPI_SCRIPT(mode)],
|
|
48
|
+
{ input: base64, encoding: 'utf8', windowsHide: true }).trim();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Save every site this computer is paired with, sealed on Windows. */
|
|
52
|
+
export function save_machine_links(home, links) {
|
|
53
|
+
const path = join(home, LINKS_FILE);
|
|
54
|
+
const text = JSON.stringify(links);
|
|
55
|
+
const stored = DPAPI ? { dpapi: dpapi('Protect', Buffer.from(text).toString('base64')) } : links;
|
|
56
|
+
atomic_json(path, stored);
|
|
57
|
+
links_cache.set(path, { raw: readFileSync(path, 'utf8'), text });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Read every site this computer is paired with; a file saved in the clear by an older version is sealed on first read. */
|
|
61
|
+
export function machine_links(home) {
|
|
62
|
+
const path = join(home, LINKS_FILE);
|
|
63
|
+
if (!existsSync(path)) return { sites: {} };
|
|
64
|
+
const raw = readFileSync(path, 'utf8');
|
|
65
|
+
const cached = links_cache.get(path);
|
|
66
|
+
if (cached?.raw === raw) return JSON.parse(cached.text);
|
|
67
|
+
const stored = JSON.parse(raw);
|
|
68
|
+
if (stored.dpapi) {
|
|
69
|
+
const text = Buffer.from(dpapi('Unprotect', stored.dpapi), 'base64').toString('utf8');
|
|
70
|
+
links_cache.set(path, { raw, text });
|
|
71
|
+
return JSON.parse(text);
|
|
72
|
+
}
|
|
73
|
+
if (DPAPI) save_machine_links(home, stored);
|
|
74
|
+
else links_cache.set(path, { raw, text: JSON.stringify(stored) });
|
|
75
|
+
return stored;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A fresh P-256 key pair as JWKs; the private half never leaves this computer. */
|
|
79
|
+
function p256_pair() {
|
|
80
|
+
const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
|
|
81
|
+
const { kty, crv, x, y } = publicKey.export({ format: 'jwk' });
|
|
82
|
+
return { public: { kty, crv, x, y }, private: privateKey.export({ format: 'jwk' }) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** One key pair to decrypt relayed commands and one to sign the device list the website checks devices against. */
|
|
86
|
+
function command_keys() {
|
|
87
|
+
const command = p256_pair(), signing = p256_pair();
|
|
88
|
+
return { public_key: command.public, private_key: command.private, sign_public_key: signing.public, sign_private_key: signing.private };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Give every paired site both key pairs, kept beside its token; older pairings gain the missing ones on first use. */
|
|
92
|
+
export function keyed_links(home) {
|
|
93
|
+
const links = machine_links(home);
|
|
94
|
+
const missing = Object.values(links.sites).filter(link => !link.private_key || !link.sign_private_key);
|
|
95
|
+
for (const link of missing) {
|
|
96
|
+
const keys = command_keys();
|
|
97
|
+
Object.assign(link, link.private_key ? { sign_public_key: keys.sign_public_key, sign_private_key: keys.sign_private_key } : keys);
|
|
98
|
+
}
|
|
99
|
+
if (missing.length) save_machine_links(home, links);
|
|
100
|
+
return links;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Return this computer's identity for one site, creating it on first use; the browser then pairs it as administrator. */
|
|
104
|
+
export function machine_link(home, site) {
|
|
105
|
+
const origin = new URL(site).origin;
|
|
106
|
+
const links = machine_links(home);
|
|
107
|
+
links.sites[origin] ||= { id: randomUUID().replaceAll('-', ''), token: randomBytes(MACHINE_TOKEN_BYTES).toString('hex'),
|
|
108
|
+
name: (hostname() || '本机').slice(0, MACHINE_NAME_MAX), ...command_keys() };
|
|
109
|
+
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
110
|
+
save_machine_links(home, links);
|
|
111
|
+
// The browser forwards this to the website, so the private key stays out of it.
|
|
112
|
+
const { id, token, name } = links.sites[origin];
|
|
113
|
+
return { id, token, name };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Forget a site's pairing so it can no longer hand launches to this computer. */
|
|
117
|
+
export function unlink_machine(home, site) {
|
|
118
|
+
const links = machine_links(home);
|
|
119
|
+
if (!links.sites[site]) return;
|
|
120
|
+
delete links.sites[site];
|
|
121
|
+
save_machine_links(home, links);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Resolve the API key saved for a profile's base URL, as the connected browser does. */
|
|
125
|
+
function api_key_ref(profile, keys) {
|
|
126
|
+
if (profile.api_key_ref || !profile.base_url) return profile.api_key_ref;
|
|
127
|
+
try { return keys[new URL(profile.base_url).href.replace(/\/+$/, '')]; } catch { return undefined; }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Platforms this computer can wake without further setup, and the client each uses. */
|
|
131
|
+
export function ready_clients(home) {
|
|
132
|
+
const keys = saved_api_keys(home);
|
|
133
|
+
return Object.fromEntries(Object.entries(launch_settings(home).participants).filter(([, profile]) => {
|
|
134
|
+
const facts = adapter_profile(profile.adapter);
|
|
135
|
+
if (!facts) return false;
|
|
136
|
+
// A model API needs its endpoint and key; other software needs its installed location.
|
|
137
|
+
return facts.kind === 'api' ? Boolean(profile.base_url && profile.api_protocol && profile.model && api_key_ref(profile, keys))
|
|
138
|
+
: Boolean(profile[facts.location]);
|
|
139
|
+
}).map(([name, profile]) => [name, profile.adapter]));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function machine_request(site, link, path, body, { timeout = SYNC_TIMEOUT_MS, signal } = {}) {
|
|
143
|
+
const response = await fetch(`${site}/api/machines/${link.id}${path}`, { method: 'POST', redirect: 'error',
|
|
144
|
+
signal: AbortSignal.any([AbortSignal.timeout(timeout), ...(signal ? [signal] : [])]),
|
|
145
|
+
headers: { 'Content-Type': 'application/json', 'X-Machine-Token': link.token }, body: JSON.stringify(body) });
|
|
146
|
+
const result = await response.json();
|
|
147
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}: ${result.error || '请求失败'}`);
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Publish projects, clients and this computer's key to each paired site. Launch tasks a site returns are never run:
|
|
153
|
+
* every remote operation must arrive as a device-signed command, and a site's own answer proves nothing.
|
|
154
|
+
*/
|
|
155
|
+
export async function sync_remote_launches(home, { log = () => {} } = {}) {
|
|
156
|
+
const projects = launch_projects(home).projects.filter(project => project.id).map(({ id, name }) => ({ id, name }));
|
|
157
|
+
const clients = ready_clients(home);
|
|
158
|
+
for (const [site, link] of Object.entries(keyed_links(home).sites)) {
|
|
159
|
+
let launches;
|
|
160
|
+
// The device list is signed here, so the website can check devices against it but never add one itself.
|
|
161
|
+
try { ({ launches } = await machine_request(site, link, '/sync', { projects, clients, public_key: link.public_key, sign_key: link.sign_public_key,
|
|
162
|
+
devices: await signed_device_list(home, link) })); }
|
|
163
|
+
catch (error) { log(`${site}: 同步电脑状态失败:${error.message}`); continue; }
|
|
164
|
+
if (launches?.length) log(`${site}: 网站返回了 ${launches.length} 个旧格式启动任务,已忽略;远程启动须由已配对设备签名`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The AES-GCM key shared with one sending device, derived from its ephemeral key and this computer's private key. */
|
|
169
|
+
export async function relay_cipher(private_jwk, public_jwk) {
|
|
170
|
+
const curve = { name: 'ECDH', namedCurve: 'P-256' };
|
|
171
|
+
const own = await crypto.subtle.importKey('jwk', private_jwk, curve, false, ['deriveBits']);
|
|
172
|
+
const peer = await crypto.subtle.importKey('jwk', public_jwk, curve, false, []);
|
|
173
|
+
const material = await crypto.subtle.importKey('raw', await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, own, 256), 'HKDF', false, ['deriveKey']);
|
|
174
|
+
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: new TextEncoder().encode(RELAY_CIPHER_INFO) },
|
|
175
|
+
material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Encrypt a value bound to its command, so the site cannot swap one command's content into another. */
|
|
179
|
+
export async function seal(key, value, label) {
|
|
180
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
181
|
+
const data = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(label) }, key, new TextEncoder().encode(JSON.stringify(value)));
|
|
182
|
+
return { iv: Buffer.from(iv).toString('base64'), data: Buffer.from(data).toString('base64') };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Decrypt a value sealed for the same command label. */
|
|
186
|
+
export async function unseal(key, envelope, label) {
|
|
187
|
+
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: Buffer.from(envelope.iv, 'base64'), additionalData: new TextEncoder().encode(label) },
|
|
188
|
+
key, Buffer.from(envelope.data, 'base64'));
|
|
189
|
+
return JSON.parse(new TextDecoder().decode(plain));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Turn a relayed action into the local entrypoint call the local website makes, pinned to the relaying site. */
|
|
193
|
+
export function relayed_command(site, action, payload) {
|
|
194
|
+
if (!RELAYED_ACTIONS.has(action)) throw new Error('该操作不能经其他设备执行');
|
|
195
|
+
if (payload === undefined ? action !== 'settings' : !payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('命令内容无效');
|
|
196
|
+
let input = payload;
|
|
197
|
+
if (ROOM_ACTIONS.has(action)) {
|
|
198
|
+
const { access_file, ...rest } = payload;
|
|
199
|
+
input = { ...rest, site, entry: 'web' };
|
|
200
|
+
}
|
|
201
|
+
// A path names a folder on the computer itself; another device sends the files it opened.
|
|
202
|
+
if (action === 'workflows' && payload.folder) throw new Error('其他设备请选择 zip 或文件夹导入工作流');
|
|
203
|
+
return { command: action === 'launch' ? 'start' : action, input, browser: action === 'launch' };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Run the local entrypoint as the local website does, under the limits for other devices, and answer in its HTTP shape. */
|
|
207
|
+
export function run_launch_command({ command, input, browser, device }) {
|
|
208
|
+
return new Promise(resolve => {
|
|
209
|
+
const args = [LAUNCH_SCRIPT, command, '--remote', ...(device ? ['--device', device] : []), ...(browser ? ['--browser'] : []),
|
|
210
|
+
...(input === undefined ? [] : ['--stdin'])];
|
|
211
|
+
const child = spawn(process.execPath, args, { windowsHide: true });
|
|
212
|
+
let stdout = '', stderr = '', timed_out = false;
|
|
213
|
+
child.stdout.setEncoding('utf8').on('data', chunk => { stdout += chunk; });
|
|
214
|
+
child.stderr.setEncoding('utf8').on('data', chunk => { stderr += chunk; });
|
|
215
|
+
const timer = setTimeout(() => { timed_out = true; child.kill(); }, COMMAND_TIMEOUT_MS);
|
|
216
|
+
child.on('error', error => { clearTimeout(timer); resolve({ status: 400, body: { error: error.message } }); });
|
|
217
|
+
child.on('close', code => {
|
|
218
|
+
clearTimeout(timer);
|
|
219
|
+
if (timed_out) return resolve({ status: 400, body: { error: '启动结果未确认,请核对房间状态后沿用原配置重试' } });
|
|
220
|
+
try { resolve(code ? { status: 400, body: JSON.parse(stderr.trim()) } : { status: 200, body: JSON.parse(stdout) }); }
|
|
221
|
+
catch { resolve({ status: 400, body: { error: stderr.trim() || '本机操作失败' } }); }
|
|
222
|
+
});
|
|
223
|
+
child.stdin.end(input === undefined ? '' : JSON.stringify(input));
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Decrypt one claimed command, run it, and return the encrypted answer to the device waiting on it. */
|
|
228
|
+
async function answer_command(home, site, link, { id, envelope }, run, log) {
|
|
229
|
+
let key, sealed;
|
|
230
|
+
try {
|
|
231
|
+
key = await relay_cipher(link.private_key, envelope.key);
|
|
232
|
+
sealed = await unseal(key, envelope, id);
|
|
233
|
+
} catch { return log(`${site}: 远程命令 ${id} 无法解密,已忽略`); }
|
|
234
|
+
let response;
|
|
235
|
+
try {
|
|
236
|
+
const { request, device_id } = await open_signed_request(home, id, sealed, link.id);
|
|
237
|
+
claim_relayed_command(home, id, request.sent_at);
|
|
238
|
+
response = DEVICE_ACTIONS.has(request.action) ? await device_command(home, { site, machine_id: link.id, device_id, on_change: () => sync_remote_launches(home) }, request.action, request.payload)
|
|
239
|
+
: await run({ ...relayed_command(site, request.action, request.payload), device: device_id });
|
|
240
|
+
if (!DEVICE_ACTIONS.has(request.action)) audit(home, { event: 'command', action: request.action, route: '', device: device_id, status: response.status });
|
|
241
|
+
}
|
|
242
|
+
catch (error) { response = { status: 400, body: { error: error.message, ...(error.need ? { need: error.need } : {}) } }; }
|
|
243
|
+
try { await machine_request(site, link, `/commands/${encodeURIComponent(id)}`, { envelope: await seal(key, response, `${id}:response`) }); }
|
|
244
|
+
catch (error) { log(`${site}: 远程命令 ${id} 回传失败:${error.message}`); }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Wait on every paired site for relayed commands and start each one; resolves once the claims return, with the commands
|
|
249
|
+
* still running in `running` so a slow model list never holds up the next claim. `on_failure` hears a claim that failed,
|
|
250
|
+
* so the caller can wait before retrying while a successful claim is followed at once.
|
|
251
|
+
*/
|
|
252
|
+
export async function relay_commands(home, { run = run_launch_command, log = () => {}, wait = COMMAND_WAIT_SECONDS, signal, running = new Set(), on_failure = () => {}, skip = new Set() } = {}) {
|
|
253
|
+
// Keys are created by the sync, which publishes them; a site without one yet has nothing to claim. A site reached
|
|
254
|
+
// through its live relay channel needs no D1 polling.
|
|
255
|
+
await Promise.all(Object.entries(machine_links(home).sites).filter(([site, link]) => link.private_key && !skip.has(site)).map(async ([site, link]) => {
|
|
256
|
+
let commands;
|
|
257
|
+
try { ({ commands } = await machine_request(site, link, '/commands/claim', { wait }, { timeout: wait * 1000 + COMMAND_REQUEST_MARGIN_MS, signal })); }
|
|
258
|
+
catch (error) { if (!signal?.aborted) { log(`${site}: 领取远程命令失败:${error.message}`); on_failure(); } return; }
|
|
259
|
+
for (const command of commands) {
|
|
260
|
+
// A pairing removed or replaced while the claim waited ends here, as on the live channel.
|
|
261
|
+
const current = machine_links(home).sites[site];
|
|
262
|
+
if (current?.token !== link.token || current?.private_key?.d !== link.private_key?.d) { log(`${site}: 配对已撤销或更换,忽略远程命令 ${command.id}`); continue; }
|
|
263
|
+
const task = answer_command(home, site, link, command, run, log).finally(() => running.delete(task));
|
|
264
|
+
running.add(task);
|
|
265
|
+
}
|
|
266
|
+
}));
|
|
267
|
+
return running;
|
|
268
|
+
}
|
package/runner/remote_policy.mjs
CHANGED
|
@@ -78,7 +78,7 @@ function walk(value, visit) {
|
|
|
78
78
|
/**
|
|
79
79
|
* Refuse a relayed request that would reach past what this computer granted: a folder outside the saved projects,
|
|
80
80
|
* a program location not already saved here, or 全放开 saved as a default. A device reaches this point only unlocked
|
|
81
|
-
* by its passkey that day, so a room may be given any level.
|
|
81
|
+
* by its passkey that day (or, lacking passkey support, paired at this computer), so a room may be given any level.
|
|
82
82
|
*/
|
|
83
83
|
export function guard_remote_request(command, input, { projects, participants, home }) {
|
|
84
84
|
if (LOCAL_ONLY_ACTIONS.has(command)) throw new Error('此操作只能在这台电脑上执行');
|
|
@@ -88,6 +88,7 @@ export function guard_remote_request(command, input, { projects, participants, h
|
|
|
88
88
|
const known = Object.fromEntries(SOFTWARE_FIELDS.map(field => [field, new Set(saved.map(profile => profile[field]).filter(Boolean))]));
|
|
89
89
|
walk(input, (key, value) => {
|
|
90
90
|
if (key === 'cwd' && value) remote_directory(value, { roots, home });
|
|
91
|
+
else if (key === 'extra_directories' && Array.isArray(value)) value.forEach(directory => remote_directory(directory, { roots, home }));
|
|
91
92
|
else if (SOFTWARE_FIELDS.includes(key) && value && !known[key].has(value)) throw new Error(`其他设备不能更改软件位置(${key}),请在电脑上设置`);
|
|
92
93
|
// 全放开 may be given to a room's member; it never becomes a saved default from afar.
|
|
93
94
|
else if (key === 'project_access' && value === 'full' && !WRITE_COMMANDS.has(command)) throw new Error('“全放开”不能从其他设备存为默认设置');
|