- packages/protocol: 协议定义(信封/方法/错误码/能力schema/校验/HMAC/ULID) - packages/client: 控制端客户端库(连接/握手/invoke/超时) - apps/agent: Windows 被控端(监听/HMAC认证/能力分发/7项能力/进程执行) - apps/cli: 控制端 CLI(connect/info/status/ps/services/exec/apps/install/list/invoke) - apps/mcp: MCP server(na_* 工具,接入 WorkBuddy) - scripts: install.ps1 / uninstall.ps1(开机自启 + 防火墙 + 密钥生成) - tests/e2e: 端到端测试 13/13 通过(握手/能力/超时强杀/参数校验/鉴权失败/未认证)
33 lines
1.1 KiB
TypeScript
33 lines
1.1 KiB
TypeScript
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||
|
||
/**
|
||
* 计算 HMAC-SHA256,返回 Base64。
|
||
* @param key 预共享密钥
|
||
* @param nonce 被控端下发的随机挑战值
|
||
*/
|
||
export function computeHmac(key: string, nonce: string): string {
|
||
return createHmac('sha256', key).update(nonce, 'utf8').digest('base64');
|
||
}
|
||
|
||
/** 恒定时比较校验 HMAC,防时序侧信道。 */
|
||
export function verifyHmac(key: string, nonce: string, expected: string): boolean {
|
||
const actual = Buffer.from(computeHmac(key, nonce), 'utf8');
|
||
const given = Buffer.from(expected ?? '', 'utf8');
|
||
if (actual.length !== given.length) return false;
|
||
return timingSafeEqual(actual, given);
|
||
}
|
||
|
||
/** 生成随机 nonce(32 字节,Base64)。 */
|
||
export function generateNonce(): string {
|
||
const bytes = new Uint8Array(32);
|
||
crypto.getRandomValues(bytes);
|
||
return Buffer.from(bytes).toString('base64');
|
||
}
|
||
|
||
/** 生成随机预共享密钥(32 字节,hex),用于初始化。 */
|
||
export function generateSharedKey(): string {
|
||
const bytes = new Uint8Array(32);
|
||
crypto.getRandomValues(bytes);
|
||
return Buffer.from(bytes).toString('hex');
|
||
}
|