import { createHmac, timingSafeEqual } from 'node:crypto'; export const HOST_PROTOCOL = 'agent-workbench-host-v1'; export const HOST_REGISTRATION_FILE = 'host-authority-v1.json'; export const hostError = (message, code = 'HOST_IDENTITY_REJECTED', status = 409) => Object.assign(new Error(message), { code, status }); export const canonicalHost = value => Array.isArray(value) ? value.map(canonicalHost) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonicalHost(value[key])])) : value; export function hostProof(identity, challenge, secret) { if (!/^[a-f0-9]{64}$/.test(challenge) || !Buffer.isBuffer(secret) || secret.length !== 32) throw hostError('宿主核验挑战格式无效。', 'HOST_CHALLENGE_INVALID', 400); return createHmac('sha256', secret).update(JSON.stringify(canonicalHost({ identity, challenge }))).digest('hex'); } export function verifyHostProof(reply, challenge, secret) { if (!reply?.identity || reply.challenge !== challenge || !/^[a-f0-9]{64}$/.test(reply.proof ?? '')) throw hostError('宿主没有提供匹配的实例核验。'); const actual = Buffer.from(reply.proof, 'hex'), expected = Buffer.from(hostProof(reply.identity, challenge, secret), 'hex'); if (!timingSafeEqual(actual, expected)) throw hostError('端口响应不属于登记的执行宿主。'); return reply.identity; } export function assertHostStop(input, identity) { if (input?.confirmation !== 'stop-owned-host' || input.instanceId !== identity.instanceId || input.createdAt !== identity.createdAt || input.runtimeIdentity !== identity.runtimeIdentity) throw hostError('停止确认已过期或不属于当前宿主。'); }