284 lines
23 KiB
JavaScript
284 lines
23 KiB
JavaScript
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 { InputAttachments } from '../core/context/input-attachments.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 }))).sort((left, right) => {
|
|
const virtual = value => /vethernet|hyper-v|wsl|virtual|vmware|vbox|docker|vpn|\btun\b|\btap\b|虚拟/i.test(value.name) ? 1 : 0;
|
|
return virtual(left) - virtual(right) || left.name.localeCompare(right.name);
|
|
});
|
|
}
|
|
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: blob:; 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') {
|
|
const state = this.registry.read();
|
|
return reply(response, { device: { id: device.id, name: device.name, projectIds: device.projectIds, permissions: device.permissions, expiresAt: device.expiresAt, revision: device.revision },
|
|
gatewayId: state.gatewayId, operations: Object.values(state.operations).filter(value => value.deviceId === device.id && device.projectIds.includes(value.projectId)).slice(-20)
|
|
.map(value => ({ requestId: value.requestId, action: value.action, status: value.status === 'pending' ? 'unknown' : value.status, taskId: value.taskId, runId: value.runId, createdAt: value.createdAt })) });
|
|
}
|
|
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 browserImage=route.match(/^\/mobile-api\/sessions\/([a-f0-9-]+)\/browser-observations\/([a-f0-9-]+)\/image$/);
|
|
if(browserImage&&method==='GET'){
|
|
const session=this.session(device,browserImage[1]),observation=this.store.owned('browsing_observation',browserImage[2],session.id);
|
|
if(observation.taskId!==session.taskId)throw companionError('当前任务没有这份网页观察。',404);
|
|
const artifact=this.store.owned('artifact',observation.screenshotArtifactId,session.id);
|
|
if(artifact.kind!=='browsing-screenshot'||artifact.sha256!==observation.screenshotSha256)throw companionError('原网页截图身份无法核对。',409);
|
|
const bytes=this.store.artifactStore.readBytes(artifact);response.writeHead(200,{'Content-Type':'image/png','Content-Length':bytes.length,'X-Content-SHA256':artifact.sha256,'Cache-Control':'no-store'});response.end(bytes);return;
|
|
}
|
|
const attachment=route.match(/^\/mobile-api\/sessions\/([a-f0-9-]+)\/input-attachments\/([a-f0-9-]+)\/(image|original)$/);
|
|
if(attachment&&method==='GET'){
|
|
const session=this.session(device,attachment[1]),manager=new InputAttachments(this.store),row=manager.get(session,attachment[2]);
|
|
if(row.taskId!==session.taskId||row.status!=='attached'||!(this.store.core.task.get(session.taskId)?.attachmentIds??[]).includes(row.id))throw companionError('当前任务没有这张截图。',404);
|
|
const {artifact,bytes}=manager.read(session,row.id,{original:attachment[3]==='original'});
|
|
response.writeHead(200,{'Content-Type':artifact.mediaType,'Content-Length':bytes.length,'X-Content-SHA256':artifact.sha256,
|
|
...(attachment[3]==='original'?{'Content-Disposition':'attachment; filename="workbench-input-'+row.id+(row.mediaType==='image/png'?'.png':'.jpg')+'"'}:{})});response.end(bytes);return;
|
|
}
|
|
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();
|
|
}
|
|
}
|
|
}
|