feat(companion): add HTTPS pairing and scoped device authority
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
import fs from 'node:fs';
|
||||
import { randomBytes, randomUUID } from 'node:crypto';
|
||||
import { companionError, companionHash, companionName, deviceGrant, COMPANION_SCHEMA } from '../../shared/contracts/companion.mjs';
|
||||
import { assertLocalTree } from '../desktop/file-state.mjs';
|
||||
|
||||
const key = 'mobileCompanion';
|
||||
const instant = value => new Date(value).toISOString();
|
||||
const secret = () => randomBytes(32).toString('base64url');
|
||||
export class DeviceRegistry {
|
||||
constructor(store, identity, { clock = Date.now } = {}) {
|
||||
this.store = store; this.identity = identity; this.clock = clock; this.pairings = new Map();
|
||||
assertLocalTree(store.directory);
|
||||
const host = identity();
|
||||
if (!host?.instanceId || !host?.userSid || !host?.ownerId) throw companionError('手机连接需要已登记的Windows执行宿主。', 409);
|
||||
this.host = structuredClone(host);
|
||||
this.binding = companionHash(JSON.stringify({ userSid: host.userSid, directory: fs.realpathSync.native(store.directory).toLowerCase() }));
|
||||
this.read();
|
||||
}
|
||||
assertHost() {
|
||||
const host = this.identity();
|
||||
if (!host || ['instanceId', 'ownerId', 'userSid', 'pid', 'createdAt'].some(key => host[key] !== this.host[key])) throw companionError('原执行宿主已变化,请在电脑上重新开启手机连接。', 409);
|
||||
}
|
||||
read() {
|
||||
const state = this.store.storage.meta(key);
|
||||
if (state && (state.schema !== COMPANION_SCHEMA || state.binding !== this.binding || !Number.isSafeInteger(state.revision)
|
||||
|| !state.devices || Array.isArray(state.devices) || Object.keys(state.devices).length > 128 || !Array.isArray(state.audit)
|
||||
|| !state.operations || Array.isArray(state.operations))) throw companionError('原手机登记无法核对;请保留数据并检查原Windows用户和目录。', 409);
|
||||
return state ?? { schema: COMPANION_SCHEMA, binding: this.binding, gatewayId: randomUUID(), revision: 0, devices: {}, audit: [], operations: {} };
|
||||
}
|
||||
mutate(action) {
|
||||
this.assertHost();
|
||||
return this.store.storage.transaction(() => {
|
||||
const state = this.read(), result = action(state);
|
||||
state.revision++; this.store.storage.setMeta(key, state); return result;
|
||||
});
|
||||
}
|
||||
audit(state, action, deviceId, status, extra = {}) {
|
||||
state.audit.push({ id: randomUUID(), at: instant(this.clock()), deviceId, action, status, ...extra });
|
||||
state.audit = state.audit.slice(-500);
|
||||
}
|
||||
initialize() { return this.mutate(state => ({ gatewayId: state.gatewayId })); }
|
||||
view() {
|
||||
const state = this.read();
|
||||
return { gatewayId: state.gatewayId, revision: state.revision, devices: Object.values(state.devices).map(({ credentialHash, ...device }) => ({ ...device,
|
||||
status: device.revokedAt ? 'revoked' : Date.parse(device.expiresAt) <= this.clock() ? 'expired' : credentialHash ? 'active' : 'reconnect_required' })), audit: state.audit.slice(-50).reverse() };
|
||||
}
|
||||
pair(grant, generation) {
|
||||
this.assertHost(); deviceGrant(this.store, grant);
|
||||
const token = secret(), hash = companionHash(token), expiresAt = this.clock() + 120000;
|
||||
this.pairings.clear(); this.pairings.set(hash, { grant: structuredClone(grant), generation, expiresAt });
|
||||
return { token, expiresAt: instant(expiresAt) };
|
||||
}
|
||||
consume(token, name, generation) {
|
||||
this.assertHost(); name = companionName(name);
|
||||
if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw companionError('配对码无效或已过期。', 401);
|
||||
const hash = companionHash(token), pairing = this.pairings.get(hash);
|
||||
if (!pairing || pairing.generation !== generation || pairing.expiresAt <= this.clock()) throw companionError('配对码无效或已过期,请在电脑重新生成。', 401);
|
||||
deviceGrant(this.store, pairing.grant);
|
||||
const tokenValue = secret();
|
||||
const device = this.mutate(state => {
|
||||
if (Object.keys(state.devices).length >= 128) throw companionError('设备登记达到128条上限,请保留原审计并检查设备登记。', 409);
|
||||
const at = this.clock(), device = { id: randomUUID(), name, projectIds: pairing.grant.projectIds, permissions: pairing.grant.permissions,
|
||||
revision: 1, createdAt: instant(at), expiresAt: instant(at + pairing.grant.expiresInHours * 3600000), revokedAt: null,
|
||||
credentialHash: companionHash(tokenValue) };
|
||||
state.devices[device.id] = device; this.audit(state, 'pair', device.id, 'completed');
|
||||
const { credentialHash, ...view } = device; return view;
|
||||
});
|
||||
this.pairings.delete(hash);
|
||||
return { device, token: tokenValue };
|
||||
}
|
||||
authenticate(token) {
|
||||
this.assertHost();
|
||||
if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw companionError('请在电脑生成配对码,重新连接此设备。', 401);
|
||||
const hash = companionHash(token), device = Object.values(this.read().devices).find(value => value.credentialHash === hash);
|
||||
if (!device || device.revokedAt || Date.parse(device.expiresAt) <= this.clock()) throw companionError('设备已撤销、到期或会话已轮换,请重新配对。', 401);
|
||||
return structuredClone(device);
|
||||
}
|
||||
authorize(device, projectId, permission = 'observe') {
|
||||
const current = this.read().devices[device.id];
|
||||
if (!current || current.revision !== device.revision || current.credentialHash !== device.credentialHash || current.revokedAt || Date.parse(current.expiresAt) <= this.clock()) throw companionError('设备授权已变化,请重新连接。', 401);
|
||||
if (!current.projectIds.includes(projectId) || current.permissions[permission] !== true) throw companionError('此设备没有当前项目或操作权限。', 403);
|
||||
return current;
|
||||
}
|
||||
revoke(id, revision) {
|
||||
this.pairings.clear();
|
||||
return this.mutate(state => {
|
||||
const device = state.devices[id];
|
||||
if (!device || device.revision !== revision) throw companionError('设备登记已变化,请刷新列表。', 409);
|
||||
device.revokedAt = instant(this.clock()); device.credentialHash = null; device.revision++;
|
||||
this.audit(state, 'revoke', id, 'completed'); return { revoked: true };
|
||||
});
|
||||
}
|
||||
rotate(device) {
|
||||
const token = secret();
|
||||
this.mutate(state => {
|
||||
this.authorize(device, device.projectIds[0]);
|
||||
const current = state.devices[device.id]; current.credentialHash = companionHash(token); current.revision++;
|
||||
current.rotatedAt = instant(this.clock()); this.audit(state, 'rotate', device.id, 'completed');
|
||||
});
|
||||
return token;
|
||||
}
|
||||
reserve(device, action, session, input) {
|
||||
const hash = companionHash(JSON.stringify({ action, sessionId: session.id, input })), id = device.id + ':' + input.requestId;
|
||||
return this.mutate(state => {
|
||||
const existing = state.operations[id];
|
||||
if (existing) {
|
||||
if (existing.hash !== hash) throw companionError('同一请求ID不能更换操作或输入。', 409);
|
||||
return { ...existing, duplicate: true };
|
||||
}
|
||||
if (Object.keys(state.operations).length >= 2000) throw companionError('手机操作账本达到上限,请在电脑处理。', 409);
|
||||
const operation = { hash, deviceId: device.id, requestId: input.requestId, action, sessionId: session.id,
|
||||
taskId: session.taskId, runId: session.runId, projectId: session.projectId, status: 'pending', createdAt: instant(this.clock()) };
|
||||
state.operations[id] = operation;
|
||||
this.audit(state, action, device.id, 'pending', { requestId: input.requestId, projectId: session.projectId, taskId: session.taskId, runId: session.runId });
|
||||
return operation;
|
||||
});
|
||||
}
|
||||
finish(device, input, status) {
|
||||
return this.mutate(state => {
|
||||
const operation = state.operations[device.id + ':' + input.requestId];
|
||||
if (!operation) throw companionError('原手机操作登记丢失,请在电脑核对。', 409);
|
||||
operation.status = status; operation.finishedAt = instant(this.clock());
|
||||
this.audit(state, operation.action, device.id, status, { requestId: input.requestId, projectId: operation.projectId, taskId: operation.taskId, runId: operation.runId });
|
||||
return structuredClone(operation);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { approvalBinding } from '../../shared/contracts/companion.mjs';
|
||||
|
||||
export const pick = (value, names) => Object.fromEntries(names.filter(key => value?.[key] !== undefined).map(key => [key, structuredClone(value[key])]));
|
||||
export const reportKinds = new Set(['delivery-report', 'delivery-report-markdown']);
|
||||
export const sessionBrief = (session, redact = String) => ({ ...pick(session, ['id', 'projectId', 'taskId', 'runId', 'status', 'revision', 'eventSeq', 'updatedAt']), title: redact(String(session.title).slice(0, 240)) });
|
||||
export function mobileSession(store, runtime, session, redact = String) {
|
||||
const task = store.core.task.get(session.taskId), run = store.core.run.get(session.runId);
|
||||
const tools = [...store.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId);
|
||||
const checks = [...store.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId);
|
||||
const result = {
|
||||
...sessionBrief(session, redact),
|
||||
task: task ? { ...pick(task, ['id', 'status', 'budget', 'usage', 'verification']), goal: String(task.goal).slice(0, 12000) } : null,
|
||||
run: run ? pick(run, ['id', 'taskId', 'status', 'budget', 'usage', 'steps', 'toolCalls', 'stopReason', 'startedAt', 'finishedAt']) : null,
|
||||
progress: { total: tools.length, completed: tools.filter(value => value.state === 'completed').length,
|
||||
unknown: tools.filter(value => value.requiresVerification).map(value => pick(value, ['id', 'tool', 'state', 'runId'])) },
|
||||
events: session.events.slice(-60).map(value => ({ ...pick(value, ['id', 'kind', 'phase', 'taskId', 'runId', 'createdAt', 'exitCode', 'durationMs']),
|
||||
label: String(value.label ?? value.tool ?? '').slice(0, 240), output: String(value.output ?? '').slice(-4000) })),
|
||||
messages: session.messages.filter(value => ['assistant', 'system'].includes(value.role)).slice(-8).map(value => ({ ...pick(value, ['id', 'role', 'createdAt']), content: String(value.content).slice(0, 12000) })),
|
||||
approvals: session.approvals.filter(value => value.status === 'pending' && value.taskId === session.taskId && value.runId === session.runId).map(value => ({
|
||||
...pick(value, ['id', 'taskId', 'runId', 'projectId', 'command', 'reason', 'shell', 'createdAt']),
|
||||
fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })),
|
||||
changes: session.changes.filter(value => value.taskId === session.taskId).slice(-100).map(value => pick(value, ['id', 'path', 'reason', 'status', 'sha256', 'baseSha256', 'additions', 'deletions'])),
|
||||
checks: checks.slice(-12).map(value => ({ ...pick(value, ['id', 'status', 'summary', 'requiresVerification', 'createdAt', 'finishedAt']),
|
||||
results: (value.results ?? []).map(item => pick(item, ['name', 'status', 'exitCode', 'counts', 'durationMs'])) })),
|
||||
reports: [...store.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && reportKinds.has(value.kind))
|
||||
.slice(-10).map(value => pick(value, ['id', 'kind', 'sha256', 'bytes', 'createdAt', 'taskId', 'runId'])),
|
||||
};
|
||||
// Only this explicit projection crosses the remote boundary. Never expose
|
||||
// providerMessages, model configuration, tool input, host paths or full exports.
|
||||
const clean = value => typeof value === 'string' ? redact(value) : Array.isArray(value) ? value.map(clean)
|
||||
: value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, clean(entry)])) : value;
|
||||
return clean(result);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import 'reflect-metadata';
|
||||
import { webcrypto, createPrivateKey, X509Certificate as NativeCertificate } from 'node:crypto';
|
||||
import { X509CertificateGenerator, BasicConstraintsExtension, KeyUsagesExtension, KeyUsageFlags,
|
||||
ExtendedKeyUsageExtension, ExtendedKeyUsage, SubjectAlternativeNameExtension, SubjectKeyIdentifierExtension, AuthorityKeyIdentifierExtension } from '@peculiar/x509';
|
||||
import { protectCredential, unprotectCredential } from '../desktop/windows-dpapi.mjs';
|
||||
import { companionError, companionHash } from '../../shared/contracts/companion.mjs';
|
||||
|
||||
const algorithm = { name: 'ECDSA', namedCurve: 'P-256', hash: 'SHA-256' };
|
||||
const signing = { name: 'ECDSA', hash: 'SHA-256' };
|
||||
const day = 86400000;
|
||||
export class CompanionTLS {
|
||||
constructor(registry, { protect = protectCredential, unprotect = unprotectCredential } = {}) {
|
||||
this.registry = registry; this.protect = protect; this.unprotect = unprotect;
|
||||
}
|
||||
publicCertificate() {
|
||||
const tls = this.registry.read().tls;
|
||||
if (!tls) throw companionError('请先在电脑开启手机连接以生成证书。', 409);
|
||||
const cert = new NativeCertificate(tls.certificate);
|
||||
if (companionHash(cert.raw) !== tls.sha256) throw companionError('手机证书登记校验失败。', 409);
|
||||
return { bytes: cert.raw, sha256: tls.sha256, expiresAt: tls.expiresAt };
|
||||
}
|
||||
async material(address) {
|
||||
const registry = this.registry, entropy = Buffer.from(companionHash('companion-tls:' + registry.binding), 'hex');
|
||||
let record = registry.read().tls, privateBytes, keys, certificate;
|
||||
try {
|
||||
if (record) {
|
||||
const cert = new NativeCertificate(record.certificate);
|
||||
if (companionHash(cert.raw) !== record.sha256 || Date.parse(cert.validTo) <= Date.now() + day) throw companionError('原手机根证书已变化或即将到期,请在电脑处理证书更新。', 409);
|
||||
privateBytes = this.unprotect(Buffer.from(record.ciphertext, 'base64'), entropy);
|
||||
const payload = JSON.parse(privateBytes.toString('utf8'));
|
||||
if (payload.binding !== registry.binding || payload.sha256 !== record.sha256) throw companionError('手机TLS私钥不属于当前Windows用户和数据目录。', 409);
|
||||
const privateKey = await webcrypto.subtle.importKey('pkcs8', Buffer.from(payload.pkcs8, 'base64'), algorithm, false, ['sign']);
|
||||
if (!cert.checkPrivateKey(createPrivateKey({ key: Buffer.from(payload.pkcs8, 'base64'), format: 'der', type: 'pkcs8' }))) throw companionError('手机证书与私钥不匹配。', 409);
|
||||
keys = { privateKey }; certificate = record.certificate;
|
||||
} else {
|
||||
keys = await webcrypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);
|
||||
const ca = await X509CertificateGenerator.createSelfSigned({ name: 'CN=Agent Workbench Mobile ' + registry.read().gatewayId,
|
||||
keys, signingAlgorithm: signing, notBefore: new Date(Date.now() - 300000), notAfter: new Date(Date.now() + 730 * day),
|
||||
extensions: [new BasicConstraintsExtension(true, 0, true), new KeyUsagesExtension(KeyUsageFlags.keyCertSign | KeyUsageFlags.cRLSign, true),
|
||||
await SubjectKeyIdentifierExtension.create(keys.publicKey)] }, webcrypto);
|
||||
certificate = ca.toString('pem');
|
||||
const pkcs8 = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', keys.privateKey));
|
||||
let encrypted;
|
||||
try {
|
||||
privateBytes = Buffer.from(JSON.stringify({ binding: registry.binding, sha256: companionHash(new NativeCertificate(certificate).raw), pkcs8: pkcs8.toString('base64') }));
|
||||
encrypted = this.protect(privateBytes, entropy);
|
||||
record = { certificate, sha256: companionHash(new NativeCertificate(certificate).raw), expiresAt: ca.notAfter.toISOString(), ciphertext: encrypted.toString('base64') };
|
||||
registry.mutate(state => { if (state.tls) throw companionError('证书已由另一操作生成,请刷新。', 409); state.tls = record; });
|
||||
} finally { pkcs8.fill(0); encrypted?.fill(0); }
|
||||
}
|
||||
const leafKeys = await webcrypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);
|
||||
const leaf = await X509CertificateGenerator.create({ subject: 'CN=Agent Workbench Companion', issuer: new NativeCertificate(certificate).subject,
|
||||
publicKey: leafKeys.publicKey, signingKey: keys.privateKey, signingAlgorithm: signing,
|
||||
notBefore: new Date(Date.now() - 300000), notAfter: new Date(Date.now() + 90 * day),
|
||||
extensions: [new BasicConstraintsExtension(false, undefined, true), new KeyUsagesExtension(KeyUsageFlags.digitalSignature, true),
|
||||
new ExtendedKeyUsageExtension([ExtendedKeyUsage.serverAuth]), new SubjectAlternativeNameExtension([{ type: 'ip', value: address }]),
|
||||
await SubjectKeyIdentifierExtension.create(leafKeys.publicKey), await AuthorityKeyIdentifierExtension.create(new NativeCertificate(certificate).publicKey.export({ type: 'spki', format: 'der' }))] }, webcrypto);
|
||||
const der = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', leafKeys.privateKey));
|
||||
try { return { key: createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }).export({ format: 'pem', type: 'pkcs8' }), cert: leaf.toString('pem') + '\n' + certificate, ca: certificate }; }
|
||||
finally { der.fill(0); }
|
||||
} finally { privateBytes?.fill(0); entropy.fill(0); }
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { ConfigImporter } from '../core/models/config-import.mjs';
|
||||
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
|
||||
import { workerForProject, workerConflict, assertWorkersResolved } from '../shared/contracts/workers.mjs';
|
||||
import { hostAuthority } from '../core/desktop/host-authority.mjs';
|
||||
import { companionGateway } from './companion-gateway.mjs';
|
||||
import { inspectOperations } from './operations.mjs';
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
@@ -85,6 +86,25 @@ return async (request, response) => {
|
||||
const method = request.method;
|
||||
const route = url.pathname;
|
||||
if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: server?.workbenchReady !== false, uptimeMs: Date.now() - started });
|
||||
if (route.startsWith('/api/companion')) {
|
||||
const gateway = companionGateway({ appDirectory, server, store, provider, runtime });
|
||||
if (method === 'GET' && route === '/api/companion') return json(response, gateway.status());
|
||||
if (method === 'POST' && route === '/api/companion/start') return json(response, await gateway.start(await body(request)));
|
||||
if (method === 'POST' && route === '/api/companion/close') { const value = await body(request); if (Object.keys(value).length) throw Object.assign(new Error('关闭手机连接不接受额外字段。'), { status: 400 }); return json(response, await gateway.close()); }
|
||||
if (method === 'POST' && route === '/api/companion/pair') return json(response, await gateway.pairing(await body(request)));
|
||||
const revoke = route.match(/^\/api\/companion\/devices\/([a-f0-9-]+)\/revoke$/);
|
||||
if (method === 'POST' && revoke) {
|
||||
const value = await body(request);
|
||||
if (Object.keys(value).length !== 1 || !Number.isSafeInteger(value.revision)) throw Object.assign(new Error('设备撤销需要原登记修订。'), { status: 400 });
|
||||
return json(response, gateway.revoke(revoke[1], value.revision));
|
||||
}
|
||||
if (method === 'GET' && route === '/api/companion/certificate') {
|
||||
const certificate = gateway.tls.publicCertificate();
|
||||
response.writeHead(200, { 'Content-Type': 'application/pkix-cert', 'Content-Disposition': 'attachment; filename="Agent-Workbench-Mobile-CA.cer"', 'Cache-Control': 'no-store' });
|
||||
return response.end(certificate.bytes);
|
||||
}
|
||||
return json(response, { error: '手机连接管理操作不存在。' }, 404);
|
||||
}
|
||||
if (method === 'GET' && route === '/api/host/identity') return json(response, host().attest(url.searchParams.get('challenge')));
|
||||
if (method === 'GET' && route === '/api/host/status') return json(response, host().status());
|
||||
if (method === 'POST' && route === '/api/host/windows/register') return json(response, host().registerWindow(await body(request)));
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import https from 'node:https';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import QRCode from 'qrcode';
|
||||
import { DeviceRegistry } from '../core/companion/device-registry.mjs';
|
||||
import { CompanionTLS } from '../core/companion/tls-authority.mjs';
|
||||
import { fields, companionError, companionHash, approvalBinding, operationInput } from '../shared/contracts/companion.mjs';
|
||||
import { isId } from '../shared/contracts/execution.mjs';
|
||||
import { mobileSession, sessionBrief, reportKinds } from '../core/companion/projection.mjs';
|
||||
import { hostAuthority } from '../core/desktop/host-authority.mjs';
|
||||
|
||||
export function companionGateway(context) {
|
||||
if (!context.server.workbenchCompanion) {
|
||||
const authority = hostAuthority(context); authority.initialize();
|
||||
const identity = () => {
|
||||
const registration = context.server.listening ? context.server.workbenchHostAuthority?.registration : null;
|
||||
return registration ? Object.fromEntries(['instanceId', 'ownerId', 'userSid', 'pid', 'createdAt'].map(key => [key, registration[key]])) : null;
|
||||
};
|
||||
context.server.workbenchCompanion = new CompanionGateway({ ...context, identity, redact: value => context.provider.redact(value) });
|
||||
if (!context.server.workbenchCompanionCloseHook) {
|
||||
context.server.workbenchCompanionCloseHook = () => context.server.workbenchCompanion?.dispose();
|
||||
context.server.on('close', context.server.workbenchCompanionCloseHook);
|
||||
}
|
||||
}
|
||||
return context.server.workbenchCompanion;
|
||||
}
|
||||
|
||||
const cookieName = '__Host-Workbench-Device';
|
||||
const privateV4 = value => /^10\./.test(value) || /^192\.168\./.test(value) || /^172\.(1[6-9]|2\d|3[01])\./.test(value);
|
||||
export function companionAddresses() {
|
||||
return Object.entries(os.networkInterfaces()).flatMap(([name, entries]) => (entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal && privateV4(entry.address))
|
||||
.map(entry => ({ name, address: entry.address })));
|
||||
}
|
||||
function reply(response, data, status = 200) {
|
||||
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); response.end(JSON.stringify(data));
|
||||
}
|
||||
async function input(request) {
|
||||
if (!/^application\/json(?:;|$)/i.test(request.headers['content-type'] ?? '')) throw companionError('手机操作需要JSON请求。', 415);
|
||||
const chunks = []; let length = 0;
|
||||
for await (const chunk of request) {
|
||||
length += chunk.length;
|
||||
if (length > 16384) { request.resume(); throw companionError('手机请求超过16KB。', 413); }
|
||||
chunks.push(chunk);
|
||||
}
|
||||
let value; try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw companionError('手机请求JSON无效。'); }
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw companionError('手机请求需要JSON对象。');
|
||||
return value;
|
||||
}
|
||||
const cookie = request => {
|
||||
const values = String(request.headers.cookie ?? '').split(';').map(value => value.trim()).filter(value => value.startsWith(cookieName + '='));
|
||||
return values.length === 1 ? values[0].slice(cookieName.length + 1) : '';
|
||||
};
|
||||
function setCookie(response, token, expiresAt) {
|
||||
const seconds = Math.max(0, Math.floor((Date.parse(expiresAt) - Date.now()) / 1000));
|
||||
response.setHeader('Set-Cookie', cookieName + '=' + token + '; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=' + seconds);
|
||||
}
|
||||
const cursor = value => {
|
||||
if (!/^\d+$/.test(value ?? '') || !Number.isSafeInteger(Number(value))) throw companionError('手机事件游标无效。');
|
||||
return Number(value);
|
||||
};
|
||||
|
||||
export class CompanionGateway {
|
||||
constructor({ store, runtime, appDirectory, identity, redact = String }, { registryOptions, tlsOptions, allowLoopback = false } = {}) {
|
||||
this.store = store; this.runtime = runtime; this.appDirectory = appDirectory; this.redact = redact;
|
||||
this.registry = new DeviceRegistry(store, identity, registryOptions); this.tls = new CompanionTLS(this.registry, tlsOptions);
|
||||
this.allowLoopback = allowLoopback; this.server = null; this.busy = false; this.generation = null; this.origin = null;
|
||||
this.rates = new Map(); this.sockets = new Map();
|
||||
}
|
||||
status() {
|
||||
return { enabled: !!this.server?.listening, busy: this.busy, origin: this.origin, addresses: companionAddresses(), ...this.registry.view(),
|
||||
certificate: this.registry.read().tls ? { sha256: this.tls.publicCertificate().sha256, expiresAt: this.tls.publicCertificate().expiresAt } : null };
|
||||
}
|
||||
async start(options) {
|
||||
fields(options, ['address', 'port']);
|
||||
if (this.disposed || this.busy || this.server) throw companionError('手机网关正在开启、已开启或原宿主已关闭。', 409);
|
||||
if (!companionAddresses().some(value => value.address === options.address) && !(this.allowLoopback && options.address === '127.0.0.1')) throw companionError('请选择本机已连接的局域网IPv4地址。');
|
||||
if (!Number.isInteger(options.port) || options.port < (this.allowLoopback ? 0 : 1024) || options.port > 65535) throw companionError('手机端口需要1024至65535。');
|
||||
this.busy = true;
|
||||
try {
|
||||
this.registry.initialize(); const material = await this.tls.material(options.address);
|
||||
this.registry.assertHost();
|
||||
if (this.disposed) throw companionError('原宿主已关闭。', 409);
|
||||
const server = https.createServer({ key: material.key, cert: material.cert, minVersion: 'TLSv1.2', maxHeaderSize: 16384, handshakeTimeout: 10000 }, (request, response) => void this.handle(request, response));
|
||||
server.requestTimeout = 15000; server.headersTimeout = 10000; server.keepAliveTimeout = 5000; server.maxConnections = 64;
|
||||
server.on('connection', socket => { this.sockets.set(socket, null); socket.on('close', () => this.sockets.delete(socket)); });
|
||||
server.on('clientError', (_error, socket) => socket.destroy());
|
||||
try { await new Promise((resolve, reject) => { server.once('error', reject); server.listen(options.port, options.address, resolve); }); }
|
||||
catch (error) { server.close(); for (const socket of this.sockets.keys()) socket.destroy(); throw error; }
|
||||
if (this.disposed) { server.close(); throw companionError('原宿主已关闭。', 409); }
|
||||
server.removeAllListeners('error'); server.on('error', () => this.dispose());
|
||||
this.server = server; this.origin = 'https://' + options.address + ':' + server.address().port;
|
||||
this.generation = randomUUID(); this.rates.clear();
|
||||
return this.status();
|
||||
} catch (error) {
|
||||
if (error.companion) throw error;
|
||||
throw companionError(error.code === 'EADDRINUSE' ? '手机端口已占用,请换一个端口。' : '手机HTTPS启动失败,请核对证书、Windows用户及网络地址。', 409);
|
||||
} finally { this.busy = false; }
|
||||
}
|
||||
async close() {
|
||||
if (this.busy) throw companionError('网关正在启动,请等待完成后再关闭。', 409);
|
||||
const server = this.server; this.server = null; this.origin = null; this.generation = null; this.registry.pairings.clear();
|
||||
for (const socket of this.sockets.keys()) socket.destroy(); this.sockets.clear();
|
||||
if (server) await new Promise(resolve => server.close(resolve));
|
||||
return { enabled: false };
|
||||
}
|
||||
dispose() {
|
||||
this.disposed = true;
|
||||
for (const socket of this.sockets.keys()) socket.destroy();
|
||||
this.server?.close(); this.server = null; this.origin = null; this.generation = null; this.registry.pairings.clear();
|
||||
}
|
||||
async pairing(grant) {
|
||||
if (!this.server?.listening || !this.origin) throw companionError('请先开启手机HTTPS连接。', 409);
|
||||
const generation = this.generation, origin = this.origin, pair = this.registry.pair(grant, generation), url = origin + '/#pair=' + pair.token;
|
||||
const qr = await QRCode.toDataURL(url, { errorCorrectionLevel: 'M', margin: 2, width: 256 });
|
||||
if (generation !== this.generation) throw companionError('网关已变化,请重新生成配对码。', 409);
|
||||
return { url, qr, expiresAt: pair.expiresAt };
|
||||
}
|
||||
revoke(id, revision) {
|
||||
const result = this.registry.revoke(id, revision);
|
||||
for (const [socket, deviceId] of this.sockets) if (deviceId === id) socket.destroy();
|
||||
return result;
|
||||
}
|
||||
limit(key, maximum) {
|
||||
const at = Date.now(), existing = this.rates.get(key), entry = existing?.until > at ? existing : { count: 0, until: at + 60000 };
|
||||
if (++entry.count > maximum) throw companionError('手机请求过于频繁,请稍后重试。', 429);
|
||||
if (!existing && this.rates.size >= 2048) {
|
||||
for (const [id, value] of this.rates) if (value.until <= at) this.rates.delete(id);
|
||||
if (this.rates.size >= 2048) throw companionError('手机连接繁忙,请稍后重试。', 429);
|
||||
}
|
||||
this.rates.set(key, entry);
|
||||
}
|
||||
session(device, id, permission = 'observe') {
|
||||
if (!isId(id)) throw companionError('手机任务不存在。', 404);
|
||||
const session = this.store.sessions.get(id);
|
||||
if (!session) throw companionError('手机任务不存在。', 404);
|
||||
this.registry.authorize(device, session.projectId, permission); return session;
|
||||
}
|
||||
events(device, after, limit = 100) {
|
||||
const projects = device.projectIds.filter(id => this.store.projects.some(project => project.id === id));
|
||||
if (!projects.length) return { events: [], nextCursor: after, hasMore: false };
|
||||
const rows = this.store.storage.database.prepare('SELECT seq,id,session_id,project_id,task_id,run_id,type,revision,created_at FROM events WHERE seq>? AND project_id IN (' + projects.map(() => '?').join(',') + ') ORDER BY seq LIMIT ?').all(after, ...projects, limit + 1);
|
||||
const events = rows.slice(0, limit).map(row => ({ seq: row.seq, id: row.id, sessionId: row.session_id, projectId: row.project_id, taskId: row.task_id, runId: row.run_id, type: row.type, revision: row.revision, createdAt: row.created_at }));
|
||||
return { events, nextCursor: events.at(-1)?.seq ?? after, hasMore: rows.length > limit };
|
||||
}
|
||||
async operate(device, sessionId, action, value) {
|
||||
const approve = action === 'approve'; operationInput(value, approve);
|
||||
const session = this.session(device, sessionId, approve ? 'approve' : 'stop');
|
||||
// Look up idempotency before checking the now-changed session revision.
|
||||
const prior = this.registry.read().operations[device.id + ':' + value.requestId];
|
||||
if (prior) {
|
||||
if (prior.hash !== companionHash(JSON.stringify({ action, sessionId, input: value }))) throw companionError('同一请求ID不能更换操作或输入。', 409);
|
||||
return { requestId: value.requestId, status: prior.status === 'pending' ? 'unknown' : prior.status, duplicate: true };
|
||||
}
|
||||
if (session.taskId !== value.taskId || session.runId !== value.runId || session.revision !== value.revision) throw companionError('原任务或修订已变化,请刷新后核对。', 409);
|
||||
if (approve) {
|
||||
const approval = session.approvals.find(item => item.id === value.approvalId);
|
||||
if (!approval || approval.status !== 'pending' || approvalBinding(session, approval) !== value.fingerprint
|
||||
|| this.runtime.waiters.get(approval.id)?.runId !== session.runId) throw companionError('原审批已变化或过期,请在电脑核对。', 409);
|
||||
}
|
||||
this.registry.reserve(device, action, session, value);
|
||||
try {
|
||||
if (approve) this.runtime.decide(session.id, value.approvalId, value.allow);
|
||||
else await this.runtime.stop(session.id, { taskId: value.taskId, runId: value.runId });
|
||||
this.registry.finish(device, value, 'completed');
|
||||
} catch {
|
||||
// A durable pending record is intentionally not replayable, even when
|
||||
// the process or response fails between the original effect and receipt.
|
||||
try { this.registry.finish(device, value, 'unknown'); } catch {}
|
||||
throw companionError('原操作结果需要在电脑核对;不会自动重放。', 409);
|
||||
}
|
||||
this.registry.authorize(device, session.projectId, approve ? 'approve' : 'stop');
|
||||
return { requestId: value.requestId, status: 'completed', taskId: value.taskId, runId: value.runId };
|
||||
}
|
||||
async handle(request, response) {
|
||||
response.setHeader('Cache-Control', 'no-store'); response.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
response.setHeader('Referrer-Policy', 'no-referrer'); response.setHeader('X-Frame-Options', 'DENY');
|
||||
response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
|
||||
try {
|
||||
this.registry.assertHost();
|
||||
if (!this.server?.listening || !this.origin || request.headers.host !== new URL(this.origin).host) throw companionError('手机网关地址已变化,请重新连接。', 421);
|
||||
this.limit('all', 1200); this.limit('ip:' + request.socket.remoteAddress, 400);
|
||||
const mobileUrl = new URL(request.url, this.origin), route = mobileUrl.pathname, method = request.method;
|
||||
if (mobileUrl.origin !== this.origin || request.headers.origin && request.headers.origin !== this.origin) throw companionError('请求来源不属于当前手机网关。', 403);
|
||||
if (method === 'POST' && request.headers.origin !== this.origin) throw companionError('手机操作需要来自当前HTTPS页面。', 403);
|
||||
if (mobileUrl.search && route !== '/mobile-api/events' && !/^\/mobile-api\/sessions\/[a-f0-9-]+\/changes\/[a-f0-9-]+$/.test(route)) throw companionError('手机接口不接受额外查询字段。');
|
||||
if (method === 'POST' && route === '/mobile-api/pair') {
|
||||
this.limit('pair:' + request.socket.remoteAddress, 8);
|
||||
const value = await input(request); fields(value, ['token', 'name']);
|
||||
// The gateway may have closed while receiving a request body.
|
||||
if (!this.server?.listening) throw companionError('手机网关已关闭。', 409);
|
||||
const paired = this.registry.consume(value.token, value.name, this.generation);
|
||||
setCookie(response, paired.token, paired.device.expiresAt); return reply(response, { device: paired.device }, 201);
|
||||
}
|
||||
if (route.startsWith('/mobile-api/')) {
|
||||
const device = this.registry.authenticate(cookie(request)); this.limit('device:' + device.id, 240);
|
||||
if (!this.sockets.has(request.socket)) request.socket.once('close', () => this.sockets.delete(request.socket));
|
||||
this.sockets.set(request.socket, device.id);
|
||||
if (method === 'GET' && route === '/mobile-api/me') return reply(response, { device: { id: device.id, name: device.name, projectIds: device.projectIds, permissions: device.permissions, expiresAt: device.expiresAt, revision: device.revision }, gatewayId: this.registry.read().gatewayId });
|
||||
if (method === 'POST' && route === '/mobile-api/rotate') {
|
||||
fields(await input(request), []); const token = this.registry.rotate(device); setCookie(response, token, device.expiresAt); return reply(response, { rotated: true });
|
||||
}
|
||||
if (method === 'POST' && route === '/mobile-api/logout') {
|
||||
fields(await input(request), []); this.registry.revoke(device.id, device.revision); setCookie(response, '', new Date(0).toISOString()); return reply(response, { revoked: true });
|
||||
}
|
||||
if (method === 'GET' && route === '/mobile-api/projects') return reply(response, this.store.projects.filter(value => device.projectIds.includes(value.id)).map(value => ({ id: value.id, name: this.redact(value.name) })));
|
||||
if (method === 'GET' && route === '/mobile-api/sessions') return reply(response, [...this.store.sessions.values()].filter(value => device.projectIds.includes(value.projectId) && !value.archived).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 200).map(value => sessionBrief(value, this.redact)));
|
||||
if (method === 'GET' && route === '/mobile-api/events') {
|
||||
if ([...mobileUrl.searchParams.keys()].some(key => !['after', 'limit'].includes(key)) || mobileUrl.searchParams.getAll('after').length > 1 || mobileUrl.searchParams.getAll('limit').length > 1) throw companionError('手机事件分页参数无效。');
|
||||
const after = cursor(mobileUrl.searchParams.get('after') ?? '0'), limit = cursor(mobileUrl.searchParams.get('limit') ?? '100');
|
||||
if (limit < 1 || limit > 200) throw companionError('手机事件每页需要1至200条。');
|
||||
return reply(response, this.events(device, after, limit));
|
||||
}
|
||||
const match = route.match(/^\/mobile-api\/sessions\/([a-f0-9-]+)(?:\/(approve|stop|changes\/([a-f0-9-]+)|reports\/([a-f0-9-]+)))?$/);
|
||||
if (match) {
|
||||
const session = this.session(device, match[1]);
|
||||
if (method === 'GET' && !match[2]) return reply(response, mobileSession(this.store, this.runtime, session, this.redact));
|
||||
if (method === 'POST' && ['approve', 'stop'].includes(match[2])) return reply(response, await this.operate(this.registry.authenticate(cookie(request)), session.id, match[2], await input(request)));
|
||||
if (method === 'GET' && match[3]) {
|
||||
const change = session.changes.find(value => value.id === match[3] && value.taskId === session.taskId);
|
||||
if (!change) throw companionError('当前任务没有这项文件差异。', 404);
|
||||
if ([...mobileUrl.searchParams.keys()].some(key => key !== 'offset') || mobileUrl.searchParams.getAll('offset').length > 1) throw companionError('文件差异分页参数无效。');
|
||||
const offset = cursor(mobileUrl.searchParams.get('offset') ?? '0');
|
||||
const text = this.redact(change.diff.map(part => part.value.split(/(?<=\n)/).map(line => (part.added ? '+' : part.removed ? '-' : ' ') + line).join('')).join(''));
|
||||
if (offset > text.length) throw companionError('文件差异游标超出范围。');
|
||||
return reply(response, { id: change.id, path: this.redact(change.path), sourceSha256: change.sha256, baseSha256: change.baseSha256,
|
||||
sha256: companionHash(text), text: text.slice(offset, offset + 48000), offset, nextOffset: Math.min(offset + 48000, text.length), hasMore: offset + 48000 < text.length });
|
||||
}
|
||||
if (method === 'GET' && match[4]) {
|
||||
const artifact = this.store.core.artifact.get(match[4]);
|
||||
if (!artifact || artifact.sessionId !== session.id || artifact.projectId !== session.projectId || artifact.taskId !== session.taskId || !reportKinds.has(artifact.kind)) throw companionError('当前任务没有这份报告。', 404);
|
||||
const bytes = this.store.artifactStore.readBytes(artifact), text = this.redact(bytes.toString('utf8'));
|
||||
return reply(response, { id: artifact.id, sourceSha256: artifact.sha256, sha256: companionHash(text), redacted: text !== bytes.toString('utf8'), text });
|
||||
}
|
||||
}
|
||||
throw companionError('手机端没有这项操作,请回电脑工作台处理。', 404);
|
||||
}
|
||||
if (method !== 'GET' && method !== 'HEAD') throw companionError('手机端没有这项操作。', 404);
|
||||
// Mobile HTML and its build-time asset list are separate from the desktop
|
||||
// entry. Do not serve arbitrary paths, source files or management assets.
|
||||
const root = path.join(this.appDirectory, 'dist-client');
|
||||
let file, type;
|
||||
if (route === '/') { file = path.join(root, 'mobile.html'); type = 'text/html; charset=utf-8'; }
|
||||
else if (['/mobile.webmanifest', '/mobile-sw.js', '/mobile-icon.svg', '/mobile-touch-icon.png'].includes(route)) {
|
||||
file = path.join(root, route.slice(1)); type = route.endsWith('.js') ? 'text/javascript' : route.endsWith('.svg') ? 'image/svg+xml' : route.endsWith('.png') ? 'image/png' : 'application/manifest+json';
|
||||
} else {
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'mobile-assets.json'), 'utf8'));
|
||||
if (!manifest.includes(route) || !/^\/assets\/[A-Za-z0-9_.-]+\.(js|css)$/.test(route)) throw companionError('手机页面不存在。', 404);
|
||||
file = path.join(root, route.slice(1)); type = route.endsWith('.js') ? 'text/javascript' : 'text/css';
|
||||
}
|
||||
const bytes = fs.readFileSync(file); response.writeHead(200, { 'Content-Type': type }); response.end(method === 'HEAD' ? undefined : bytes);
|
||||
} catch (error) {
|
||||
if (!response.destroyed && !response.headersSent) reply(response, { error: error.companion ? error.message : '手机请求未完成,请在电脑核对当前任务和连接。' }, error.companion ? error.status : 500);
|
||||
else if (!response.destroyed) response.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,12 +17,14 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context;
|
||||
if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.');
|
||||
if (server.workbenchHostAuthority?.stopping) throw new Error('Wait for the original host stop operation before upgrading.');
|
||||
if (server.workbenchCompanion?.server || server.workbenchCompanion?.busy) throw new Error('Close the mobile companion gateway before upgrading; original tasks remain on the host.');
|
||||
if (server.workbenchHostAuthority?.desktopWindows?.().count) throw new Error('Close the registered desktop windows before upgrading; the execution host remains running.');
|
||||
if (runtime.active.size || runtime.waiters.size || runtime.workers?.active.size || runtime.controlledEngines?.drivers.size || runtime.mcp?.active.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size || runtime.taskPlans?.active.size) throw new Error('Wait for active tasks, workers, controlled engines, MCP operations, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.');
|
||||
if (provider.activeRequests || provider.hub?.waiting || [...(provider.hub?.leases.values() ?? [])].some(count => count > 0)) throw new Error('Wait for active model requests and probes before upgrading.');
|
||||
const root = fs.realpathSync.native(path.resolve(appDirectory));
|
||||
if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.');
|
||||
const oldHandlers = server.listeners('request');
|
||||
const oldCompanion = server.workbenchCompanion;
|
||||
const oldAuthority = server.workbenchHostAuthority, oldAuthorityProperties = oldAuthority ? { ...oldAuthority } : null;
|
||||
const oldAuthorityPrototype = oldAuthority ? Object.getPrototypeOf(oldAuthority) : null;
|
||||
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
|
||||
@@ -46,6 +48,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
if (provider.hub.credentialVault) Object.setPrototypeOf(provider.hub.credentialVault, CredentialVault.prototype);
|
||||
}
|
||||
runtime.appDirectory = root; runtime.workers = null; runtime.controlledEngines = null; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null;
|
||||
delete server.workbenchCompanion;
|
||||
store.ensureStorage();
|
||||
// A SQLite host can retain an artifact object from an earlier bundle.
|
||||
// Reopen the same blobs through the new API without mutating that object;
|
||||
@@ -61,6 +64,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
}
|
||||
return { version: APP_VERSION, pid: process.pid, hasKey: provider.hasKey(), projects: store.projects.length, sessions: store.sessions.size, appDirectory: root };
|
||||
} catch (error) {
|
||||
if (oldCompanion) server.workbenchCompanion = oldCompanion; else delete server.workbenchCompanion;
|
||||
if (oldAuthority) {
|
||||
for (const key of Object.keys(oldAuthority)) if (!Object.hasOwn(oldAuthorityProperties, key)) delete oldAuthority[key];
|
||||
Object.assign(oldAuthority, oldAuthorityProperties); Object.setPrototypeOf(oldAuthority, oldAuthorityPrototype);
|
||||
|
||||
@@ -48,6 +48,8 @@ server.on('request', createRequestHandler({ appDirectory, server, store, provide
|
||||
async function shutdown() {
|
||||
if (closing) return; closing = true;
|
||||
clearInterval(modelImportSync);
|
||||
try { await server.workbenchCompanion?.close(); }
|
||||
catch { closing = false; console.error('Workbench shutdown rejected while companion gateway is starting.'); return; }
|
||||
try { await Promise.all([provider.abortRequests(), runtime.stopAll()]); }
|
||||
catch (cause) { closing = false; provider.resumeRequests(); console.error('Workbench shutdown remains unverified: ' + provider.redact(cause.message)); return; }
|
||||
for (const response of clients) response.end();
|
||||
|
||||
+11
-1
@@ -652,8 +652,18 @@ export class Runtime {
|
||||
if (signal.aborted) terminate();
|
||||
});
|
||||
}
|
||||
async stop(sessionId) {
|
||||
async stop(sessionId, expected = null) {
|
||||
const original = this.active.get(sessionId);
|
||||
const assertOriginal = () => {
|
||||
if (!expected) return;
|
||||
const session = this.store.session(sessionId);
|
||||
if (session.taskId !== expected.taskId || session.runId !== expected.runId || this.active.get(sessionId) && this.active.get(sessionId) !== original) {
|
||||
throw Object.assign(new Error('原停止请求的任务或运行已变化。'), { status: 409 });
|
||||
}
|
||||
};
|
||||
assertOriginal();
|
||||
await this.workers?.stopParent(sessionId);
|
||||
assertOriginal();
|
||||
const run = this.active.get(sessionId);
|
||||
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.stop(sessionId); await this.research?.stop(sessionId); await this.engines?.stop(sessionId); await this.browser?.stop(sessionId); await this.mcp?.stop(sessionId); await this.taskPlans?.settle(sessionId); return; }
|
||||
const session = this.store.session(sessionId);
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { isId } from './execution.mjs';
|
||||
|
||||
export const COMPANION_SCHEMA = 1;
|
||||
export const companionHash = value => createHash('sha256').update(value).digest('hex');
|
||||
export const companionError = (message, status = 400) => Object.assign(new Error(message), { status, companion: true });
|
||||
export function fields(input, allowed, required = allowed) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !allowed.includes(key))
|
||||
|| required.some(key => !Object.hasOwn(input, key))) throw companionError('请求字段不符合手机连接契约。');
|
||||
return input;
|
||||
}
|
||||
export function deviceGrant(store, input) {
|
||||
fields(input, ['projectIds', 'permissions', 'expiresInHours']);
|
||||
if (!Array.isArray(input.projectIds) || !input.projectIds.length || input.projectIds.length > 16
|
||||
|| new Set(input.projectIds).size !== input.projectIds.length || input.projectIds.some(id => !isId(id) || !store.projects.some(project => project.id === id))) {
|
||||
throw companionError('请选择1至16个已打开的项目。');
|
||||
}
|
||||
fields(input.permissions, ['observe', 'approve', 'stop']);
|
||||
if (input.permissions.observe !== true || typeof input.permissions.approve !== 'boolean' || typeof input.permissions.stop !== 'boolean') throw companionError('观察权限必选,审批和停止权限需要明确选择。');
|
||||
if (!Number.isInteger(input.expiresInHours) || input.expiresInHours < 1 || input.expiresInHours > 720) throw companionError('设备有效期应为1至720小时。');
|
||||
return structuredClone(input);
|
||||
}
|
||||
export function companionName(value) {
|
||||
if (typeof value !== 'string' || !value.trim() || value.trim().length > 60 || /[\x00-\x1f\x7f]/.test(value)) throw companionError('设备名称需要1至60个可见字符。');
|
||||
return value.trim();
|
||||
}
|
||||
export function approvalBinding(session, approval) {
|
||||
// Every execution-relevant approval field participates; no caller-supplied
|
||||
// command, path or tool arguments are accepted by the gateway.
|
||||
const { status, decidedAt, ...input } = approval;
|
||||
return companionHash(JSON.stringify({ sessionId: session.id, taskId: session.taskId, runId: session.runId, input }));
|
||||
}
|
||||
export function operationInput(input, approve) {
|
||||
fields(input, ['requestId', 'taskId', 'runId', 'revision', ...(approve ? ['approvalId', 'fingerprint', 'allow'] : [])]);
|
||||
if (![input.requestId, input.taskId, input.runId, ...(approve ? [input.approvalId] : [])].every(isId)
|
||||
|| !Number.isSafeInteger(input.revision) || input.revision < 0 || approve && (!/^[a-f0-9]{64}$/.test(input.fingerprint) || typeof input.allow !== 'boolean')) throw companionError('原任务、运行或审批依据无效。');
|
||||
return input;
|
||||
}
|
||||
Reference in New Issue
Block a user