feat(companion): add HTTPS pairing and scoped device authority

This commit is contained in:
Agent Workbench Dev
2026-10-31 17:38:57 +08:00
parent 06c9fac87e
commit dfe2e40387
24 changed files with 2572 additions and 5 deletions
+38
View File
@@ -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;
}