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); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user