@masstensor/diagnose 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +80 -2
- package/deploy/Caddyfile +3 -0
- package/deploy/ecosystem.config.cjs +1 -0
- package/deploy/start-relay.sh +4 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +82 -0
- package/dist/crypto.d.ts +25 -0
- package/dist/crypto.js +60 -0
- package/dist/engine.d.ts +19 -0
- package/dist/engine.js +145 -0
- package/dist/executor.d.ts +18 -0
- package/dist/executor.js +203 -0
- package/dist/mcp.d.ts +1 -0
- package/dist/mcp.js +36 -0
- package/dist/operator.d.ts +21 -0
- package/dist/operator.js +68 -0
- package/dist/peer.d.ts +51 -0
- package/dist/peer.js +253 -0
- package/dist/relay-main.d.ts +2 -0
- package/dist/relay-main.js +6 -0
- package/dist/relay.d.ts +15 -0
- package/dist/relay.js +176 -0
- package/dist/schema.d.ts +102 -0
- package/dist/schema.js +28 -0
- package/dist/util.d.ts +11 -0
- package/dist/util.js +46 -0
- package/npm-shrinkwrap.json +2229 -0
- package/package.json +46 -4
- package/src/cli.ts +57 -0
- package/src/crypto.ts +54 -0
- package/src/engine.ts +87 -0
- package/src/executor.ts +129 -0
- package/src/mcp.ts +25 -0
- package/src/operator.ts +45 -0
- package/src/peer.ts +174 -0
- package/src/relay-main.ts +5 -0
- package/src/relay.ts +97 -0
- package/src/schema.ts +44 -0
- package/src/util.ts +39 -0
- package/src/vendor.d.ts +22 -0
- package/test/CACOPHONY-LICENSE +24 -0
- package/test/cli.test.ts +33 -0
- package/test/mcp.test.ts +29 -0
- package/test/noise-vector.json +40 -0
- package/test/probe.test.ts +131 -0
- package/test/serial.test.ts +24 -0
- package/test/vector.test.ts +32 -0
- package/tsconfig.json +8 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fenginwind contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,81 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Diagnose
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
通用、临时、由用户逐次批准的远程 AI 诊断探针。MIT 开源,TypeScript 源码随安装包提供。Node.js **22.18+**。
|
|
4
|
+
|
|
5
|
+
## 安装及使用
|
|
6
|
+
|
|
7
|
+
使用 npm 安装公开包 `@masstensor/diagnose`:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install -g @masstensor/diagnose
|
|
11
|
+
diagnose start
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
也可无需全局安装,直接运行 `npx @masstensor/diagnose start`。原 HTTPS 下载地址继续保留为首版安装包。
|
|
15
|
+
|
|
16
|
+
用户把终端显示的完整 `D1.…` 配对码私下交给诊断者。诊断者运行:
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
diagnose connect
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
交互输入配对码及诊断者/AI 提供商标签。用户核对自报标签与会话指纹后确认。每次任务再分别确认执行与发送结果。代码不经命令行参数传入;不要公开分享代码。两端都主动连接 443,不需要用户开放端口。
|
|
23
|
+
|
|
24
|
+
诊断者终端输入 JSON,请求立即返回任务 ID,使用 `wait <id>` 查看,`cancel <id>` 取消,`exit` 退出:
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{"operation":"system.inspect","arguments":{},"reason":"检查电脑与串口环境"}
|
|
28
|
+
{"operation":"process.run","arguments":{"executable":"/usr/bin/sw_vers","args":[],"timeoutMs":10000},"reason":"查看 macOS 版本"}
|
|
29
|
+
{"operation":"file.read","arguments":{"path":"/absolute/path/to/log","offset":0,"length":65536},"reason":"检查用户指定日志"}
|
|
30
|
+
{"operation":"serial.capture","arguments":{"path":"/dev/cu.usbserial-2110","baudRate":115200,"durationMs":20000},"reason":"采集设备启动日志;串口可能导致重启"}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
所有命令接受可选的中继地址:`diagnose start https://your-relay.example`。远程中继强制 TLS;回环测试允许 ws/http。
|
|
34
|
+
|
|
35
|
+
## AI / MCP
|
|
36
|
+
|
|
37
|
+
在诊断者电脑的 MCP 客户端配置中加入(确保其环境 PATH 可找到安装后的 diagnose):
|
|
38
|
+
|
|
39
|
+
```json
|
|
40
|
+
{"mcpServers":{"diagnose":{"command":"diagnose","args":["mcp"]}}}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
工具:`diagnose_pair(code,label)`、`diagnose_start(operation,arguments,reason)`、`diagnose_wait(id,timeoutMs,release)`、`diagnose_cancel(id)`、`diagnose_disconnect()`。等待一次最多 25 秒,pending 时继续轮询。大结果读取后可 release 释放诊断端缓存。MCP 使用本地 stdio,不暴露公网执行端口。配对码由你交给 AI,因此也会进入你所用 AI 的上下文;中继的加密边界不覆盖 AI 提供商。
|
|
44
|
+
|
|
45
|
+
## 能力与约束
|
|
46
|
+
|
|
47
|
+
| operation | arguments |
|
|
48
|
+
|---|---|
|
|
49
|
+
| system.inspect | `{}`;OS、Node、串口枚举 |
|
|
50
|
+
| process.run | executable、args、cwd?、timeoutMs?;直接 spawn,不自动加 shell |
|
|
51
|
+
| file.read | path、offset?、length?;每次最多 1 MiB |
|
|
52
|
+
| file.write | path、content、expectedSha256?;预览前后内容,核对旧文件哈希,临时文件加 rename |
|
|
53
|
+
| serial.capture | path、baudRate?、durationMs?;8N1,DTR/RTS=false,可能复位设备 |
|
|
54
|
+
| serial.exchange | 同上,另需 dataHex;发送明确字节后采集 |
|
|
55
|
+
|
|
56
|
+
网络/USB 专用诊断程序可通过 process.run 调用,无设备型号预设。任意获准进程拥有当前 OS 用户权限,**不是沙箱**;不自动提权,不安装常驻服务。通用进程的所有副作用无法完整跟踪,也无法通用回滚。文件写入检查可发现通常的编辑竞争,但不提供对恶意本机并发修改的隔离。
|
|
57
|
+
|
|
58
|
+
单任务执行;进程 60 秒默认、300 秒上限;串口最多300秒;采集输出10MiB上限;重复任务ID不再执行。10分钟空闲或60分钟会话结束。断线不重放,取消进程组并释放串口,重新诊断需新配对。POSIX进程组以外主动脱离的程序不能保证被终止。
|
|
59
|
+
|
|
60
|
+
## 加密、审批与审计
|
|
61
|
+
|
|
62
|
+
Noise `NNpsk0_25519_ChaChaPoly_BLAKE2b`,256位随机配对秘密、临时X25519密钥、独立收发计数器、路由/角色/版本绑定。协议使用 noise-handshake 与 sodium;测试含公开 Cacophony 测试向量。每方向最多100万帧,远低于依赖的32位计数器边界。WSS同时校验证书。尚未经过独立安全审计。
|
|
63
|
+
|
|
64
|
+
中继只保存内存房间和密文缓冲,不持久化内容、密钥或离线消息。仍可见IP、路由、连接时间及流量大小,也能阻断服务。配对秘密不发送给中继,持码仅证明持有权,标签不等于真实身份。
|
|
65
|
+
|
|
66
|
+
本机 `~/.diagnose/audit-*.jsonl` 默认权限0600,记录任务ID、操作类型、目标路径/可执行文件、读取范围/串口参数、完整参数摘要、审批、各输出流采集/发送字节数、取消和结果。工具写入文件时另记录路径、修改前后哈希及字节数。终端展示具体参数、写入前后内容与待发送预览;默认审计不保存内容或完整命令参数,避免落盘秘密。因此历史日志不是完整命令回放或文件修改监控。每次审计写入flush,审计不可写则停止任务。
|
|
67
|
+
|
|
68
|
+
文本先做常见凭据脱敏并移除终端控制字符,再在本机预览并确认发送。正则不能识别所有秘密;二进制不自动脱敏,明确提示后逐次批准。采集到本机不等于已发送。进程输出在本地有上限地缓冲,批准发送后才传输。Ctrl+C撤销待审请求、取消任务并结束会话。
|
|
69
|
+
|
|
70
|
+
## 开发、测试、部署
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
npm ci
|
|
74
|
+
npm test
|
|
75
|
+
npm run check
|
|
76
|
+
npm pack
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`test/live-gateway.ts` 是仅开发机显式调用的硬件验收,不包含在分发包中,也不随 npm test 运行。网关认证日志、固件、设备采集内容均不在包内。macOS探针与Linux中继实测;Windows及Linux探针暂为实验性,尚无真实串口与取消兼容性验收。
|
|
80
|
+
|
|
81
|
+
`deploy/ecosystem.config.cjs`、`deploy/Caddyfile` 提供部署模板。服务绑定127.0.0.1:8792,无数据库和运行密钥;DOWNLOAD_PATH可指定公开安装包路径。Caddy站点不开访问日志,PM2只记录固定启动/失败事件。仅部署打包后的白名单文件,不能同步用户诊断工作区。
|
package/deploy/Caddyfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = { apps: [{ name: 'diagnose-relay', cwd: '/home/ubuntu/diagnose-relay', script: 'deploy/start-relay.sh', interpreter: '/bin/sh', instances: 1, exec_mode: 'fork', max_memory_restart: '200M', kill_timeout: 5000, env: { NODE_ENV: 'production', HOST: '127.0.0.1', PORT: '8792', DOWNLOAD_PATH: '/home/ubuntu/diagnose-relay/diagnose-0.1.0.tgz' } }] };
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createInterface } from 'node:readline/promises';
|
|
3
|
+
import { stdin, stdout } from 'node:process';
|
|
4
|
+
import { createCode } from './crypto.js';
|
|
5
|
+
import { Peer } from './peer.js';
|
|
6
|
+
import { ProbeEngine } from './engine.js';
|
|
7
|
+
import { Operator } from './operator.js';
|
|
8
|
+
import { Audit, safeText } from './util.js';
|
|
9
|
+
import { serveMcp } from './mcp.js';
|
|
10
|
+
async function main() {
|
|
11
|
+
const [command = 'help', ...args] = process.argv.slice(2);
|
|
12
|
+
const relay = args[0] ?? 'https://diagnose.fenginwind.com';
|
|
13
|
+
if (args.length > 1)
|
|
14
|
+
throw new Error('Usage: diagnose start|connect|mcp [relay-url]');
|
|
15
|
+
if (command === 'mcp') {
|
|
16
|
+
await serveMcp(relay);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (!['start', 'connect'].includes(command)) {
|
|
20
|
+
console.log('diagnose start|connect|mcp [relay-url]\nNode.js >=22.18. Pairing codes are entered interactively, never as arguments.');
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (!stdin.isTTY || !stdout.isTTY)
|
|
24
|
+
throw new Error('Interactive terminal required. AI clients should use diagnose mcp.');
|
|
25
|
+
const rl = createInterface({ input: stdin, output: stdout });
|
|
26
|
+
const shutdown = new AbortController();
|
|
27
|
+
let peer;
|
|
28
|
+
const stop = () => { shutdown.abort(); peer?.close('User ended session'); rl.close(); };
|
|
29
|
+
rl.on('SIGINT', stop);
|
|
30
|
+
process.once('SIGTERM', stop);
|
|
31
|
+
const ask = async (text, signal = shutdown.signal) => (await rl.question(safeText(text) + ' [y/N] ', { signal })).trim().toLowerCase() === 'y';
|
|
32
|
+
try {
|
|
33
|
+
if (command === 'start') {
|
|
34
|
+
const audit = new Audit();
|
|
35
|
+
const code = createCode();
|
|
36
|
+
peer = new Peer({ role: 'host', code, relay, accept: async ({ label, fingerprint, signal }) => {
|
|
37
|
+
console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
|
|
38
|
+
const allowed = await ask('Allow this temporary diagnostic session?', signal);
|
|
39
|
+
audit.record('session.pairing-decision', { allowed, fingerprint });
|
|
40
|
+
return allowed;
|
|
41
|
+
} });
|
|
42
|
+
new ProbeEngine(peer, async (request) => {
|
|
43
|
+
console.log(`\n[${request.stage === 'execute' ? 'EXECUTION APPROVAL' : 'TRANSFER APPROVAL'}] ${request.task.operation}\nTask: ${request.task.id}\nSHA256: ${request.digest}\n${safeText(request.preview)}\n`);
|
|
44
|
+
return ask(request.stage === 'execute' ? 'Allow exactly this operation? Commands run with your OS permissions.' : `Send these results (${request.bytes ?? 0} output bytes plus metadata)?`, request.signal);
|
|
45
|
+
}, audit, message => console.log(safeText(message)));
|
|
46
|
+
await peer.open();
|
|
47
|
+
console.log(`Relay: ${relay}\nAudit: ${audit.path}\nPairing code (10 minutes, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
|
|
48
|
+
console.log(`Session ended: ${safeText(await peer.ended)}`);
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
const code = (await rl.question('Pairing code: ', { signal: shutdown.signal })).trim();
|
|
52
|
+
const label = await rl.question('Your label / AI provider: ', { signal: shutdown.signal });
|
|
53
|
+
peer = new Peer({ role: 'join', code, relay, label });
|
|
54
|
+
const operator = new Operator(peer);
|
|
55
|
+
await peer.open();
|
|
56
|
+
console.log(`Connected. Fingerprint: ${peer.fingerprint}\nEnter JSON {"operation":"system.inspect","arguments":{},"reason":"Inspect environment"}.\nOther commands: cancel <task-id>, wait <task-id>, exit. Requests return immediately.`);
|
|
57
|
+
peer.ended.then(() => stop());
|
|
58
|
+
while (!shutdown.signal.aborted) {
|
|
59
|
+
const line = (await rl.question('diagnose> ', { signal: shutdown.signal })).trim();
|
|
60
|
+
if (line === 'exit')
|
|
61
|
+
break;
|
|
62
|
+
try {
|
|
63
|
+
if (line.startsWith('cancel ')) {
|
|
64
|
+
await operator.cancel(line.slice(7).trim());
|
|
65
|
+
console.log('Cancellation requested');
|
|
66
|
+
}
|
|
67
|
+
else if (line.startsWith('wait '))
|
|
68
|
+
console.log(safeText(JSON.stringify(await operator.wait(line.slice(5).trim(), 1000), null, 2)));
|
|
69
|
+
else if (line)
|
|
70
|
+
console.log(`Task: ${await operator.start(JSON.parse(line))}`);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
console.error(safeText(error.message));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
stop();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
main().catch(error => { console.error(safeText(error.name === 'AbortError' ? 'Session ended' : error.message)); process.exitCode = 1; });
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare const NOISE_PROTOCOL = "Noise_NNpsk0_25519_ChaChaPoly_BLAKE2b";
|
|
2
|
+
export declare function createCode(): string;
|
|
3
|
+
export declare function parseCode(code: string): {
|
|
4
|
+
room: string;
|
|
5
|
+
secret: Buffer;
|
|
6
|
+
};
|
|
7
|
+
export declare class Handshake {
|
|
8
|
+
private state;
|
|
9
|
+
constructor(initiator: boolean, room: string, secret: Buffer);
|
|
10
|
+
send(payload: Buffer): Buffer;
|
|
11
|
+
receive(bytes: Buffer): Buffer;
|
|
12
|
+
split(): SecureCipher;
|
|
13
|
+
destroy(): void;
|
|
14
|
+
}
|
|
15
|
+
export declare class SecureCipher {
|
|
16
|
+
private sendCipher;
|
|
17
|
+
private receiveCipher;
|
|
18
|
+
private sent;
|
|
19
|
+
private received;
|
|
20
|
+
readonly fingerprint: string;
|
|
21
|
+
constructor(tx: Buffer, rx: Buffer, hash: Buffer);
|
|
22
|
+
encrypt(bytes: Buffer): Buffer;
|
|
23
|
+
decrypt(bytes: Buffer): Buffer;
|
|
24
|
+
destroy(): void;
|
|
25
|
+
}
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
2
|
+
import Noise from 'noise-handshake';
|
|
3
|
+
import Cipher from 'noise-handshake/cipher.js';
|
|
4
|
+
export const NOISE_PROTOCOL = 'Noise_NNpsk0_25519_ChaChaPoly_BLAKE2b';
|
|
5
|
+
export function createCode() { return `D1.${randomBytes(12).toString('base64url')}.${randomBytes(32).toString('base64url')}`; }
|
|
6
|
+
export function parseCode(code) {
|
|
7
|
+
const match = /^D1\.([A-Za-z0-9_-]{16})\.([A-Za-z0-9_-]{43})$/.exec(code.trim());
|
|
8
|
+
if (!match)
|
|
9
|
+
throw new Error('Invalid pairing code');
|
|
10
|
+
const secret = Buffer.from(match[2], 'base64url');
|
|
11
|
+
if (secret.length !== 32 || secret.toString('base64url') !== match[2])
|
|
12
|
+
throw new Error('Invalid pairing secret');
|
|
13
|
+
return { room: match[1], secret };
|
|
14
|
+
}
|
|
15
|
+
export class Handshake {
|
|
16
|
+
state;
|
|
17
|
+
constructor(initiator, room, secret) {
|
|
18
|
+
this.state = new Noise('NNpsk0', initiator, undefined, { psk: Buffer.from(secret) });
|
|
19
|
+
this.state.initialise(Buffer.from(`diagnose/v1\0${room}\0operator->probe\0${NOISE_PROTOCOL}`));
|
|
20
|
+
}
|
|
21
|
+
send(payload) { return this.state.send(payload); }
|
|
22
|
+
receive(bytes) { return this.state.recv(bytes); }
|
|
23
|
+
split() {
|
|
24
|
+
if (!this.state.complete)
|
|
25
|
+
throw new Error('Handshake not complete');
|
|
26
|
+
const result = new SecureCipher(Buffer.from(this.state.tx), Buffer.from(this.state.rx), Buffer.from(this.state.hash));
|
|
27
|
+
this.destroy();
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
destroy() {
|
|
31
|
+
this.state.psk?.fill(0);
|
|
32
|
+
this.state.tx?.fill(0);
|
|
33
|
+
this.state.rx?.fill(0);
|
|
34
|
+
this.state.e?.secretKey.fill(0);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export class SecureCipher {
|
|
38
|
+
sendCipher;
|
|
39
|
+
receiveCipher;
|
|
40
|
+
sent = 0;
|
|
41
|
+
received = 0;
|
|
42
|
+
fingerprint;
|
|
43
|
+
constructor(tx, rx, hash) {
|
|
44
|
+
this.sendCipher = new Cipher(tx);
|
|
45
|
+
this.receiveCipher = new Cipher(rx);
|
|
46
|
+
this.fingerprint = createHash('sha256').update(hash).digest('hex').slice(0, 24).match(/.{4}/g).join('-');
|
|
47
|
+
}
|
|
48
|
+
encrypt(bytes) {
|
|
49
|
+
// The dependency encodes a 32-bit transport counter. End sessions far before rollover.
|
|
50
|
+
if (++this.sent > 1_000_000)
|
|
51
|
+
throw new Error('Session message limit reached; pair again');
|
|
52
|
+
return this.sendCipher.encrypt(bytes);
|
|
53
|
+
}
|
|
54
|
+
decrypt(bytes) {
|
|
55
|
+
if (++this.received > 1_000_000)
|
|
56
|
+
throw new Error('Session message limit reached; pair again');
|
|
57
|
+
return this.receiveCipher.decrypt(bytes);
|
|
58
|
+
}
|
|
59
|
+
destroy() { this.sendCipher._clear(); this.receiveCipher._clear(); }
|
|
60
|
+
}
|
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Peer } from './peer.js';
|
|
2
|
+
import { type ApprovalHandler } from './schema.js';
|
|
3
|
+
import { Audit } from './util.js';
|
|
4
|
+
export declare class ProbeEngine {
|
|
5
|
+
private peer;
|
|
6
|
+
private approve;
|
|
7
|
+
readonly audit: Audit;
|
|
8
|
+
private notice;
|
|
9
|
+
private jobs;
|
|
10
|
+
private seen;
|
|
11
|
+
private idle;
|
|
12
|
+
private lifetime;
|
|
13
|
+
constructor(peer: Peer, approve: ApprovalHandler, audit: Audit, notice?: (message: string) => void);
|
|
14
|
+
private reply;
|
|
15
|
+
private finish;
|
|
16
|
+
private permission;
|
|
17
|
+
private run;
|
|
18
|
+
private transfer;
|
|
19
|
+
}
|
package/dist/engine.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { execute, prepareWrite } from './executor.js';
|
|
2
|
+
import { CHUNK_SIZE } from './schema.js';
|
|
3
|
+
import { digest, redact } from './util.js';
|
|
4
|
+
function aborted(promise, signal) {
|
|
5
|
+
return new Promise((resolve, reject) => {
|
|
6
|
+
const cancel = () => reject(new Error('Task cancelled'));
|
|
7
|
+
if (signal.aborted) {
|
|
8
|
+
cancel();
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
signal.addEventListener('abort', cancel, { once: true });
|
|
12
|
+
promise.then(value => { signal.removeEventListener('abort', cancel); resolve(value); }, error => { signal.removeEventListener('abort', cancel); reject(error); });
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
export class ProbeEngine {
|
|
16
|
+
peer;
|
|
17
|
+
approve;
|
|
18
|
+
audit;
|
|
19
|
+
notice;
|
|
20
|
+
jobs = new Map();
|
|
21
|
+
seen = new Set();
|
|
22
|
+
idle;
|
|
23
|
+
lifetime;
|
|
24
|
+
constructor(peer, approve, audit, notice = () => { }) {
|
|
25
|
+
this.peer = peer;
|
|
26
|
+
this.approve = approve;
|
|
27
|
+
this.audit = audit;
|
|
28
|
+
this.notice = notice;
|
|
29
|
+
this.idle = setTimeout(() => peer.close('Idle timeout'), 600000);
|
|
30
|
+
this.lifetime = setTimeout(() => peer.close('Session lifetime exceeded'), 3600000);
|
|
31
|
+
peer.on('message', (message) => {
|
|
32
|
+
this.idle.refresh();
|
|
33
|
+
if (message.type === 'task.cancel') {
|
|
34
|
+
try {
|
|
35
|
+
audit.record('task.cancel-requested', { id: message.id });
|
|
36
|
+
this.jobs.get(message.id)?.abort();
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
peer.close('Audit unavailable');
|
|
40
|
+
}
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (message.type !== 'task.request') {
|
|
44
|
+
peer.close('Unexpected operator message');
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const task = message.task;
|
|
48
|
+
if (this.seen.has(task.id)) {
|
|
49
|
+
void this.reply(task.id, { status: 'duplicate' });
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (this.jobs.size || this.seen.size >= 1000) {
|
|
53
|
+
void this.reply(task.id, { status: 'error', error: 'Probe busy or session task limit reached' });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const controller = new AbortController();
|
|
57
|
+
this.jobs.set(task.id, controller);
|
|
58
|
+
this.seen.add(task.id);
|
|
59
|
+
void this.run(task, controller);
|
|
60
|
+
});
|
|
61
|
+
peer.on('closed', () => { clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values())
|
|
62
|
+
controller.abort(); try {
|
|
63
|
+
audit.record('session.closed', {});
|
|
64
|
+
}
|
|
65
|
+
catch { /* Cannot continue a closed session. */ } });
|
|
66
|
+
}
|
|
67
|
+
async reply(id, result) { await this.peer.send({ type: 'task.result', id, result }).catch(() => { }); }
|
|
68
|
+
async finish(id, result) { this.jobs.delete(id); await this.reply(id, result); }
|
|
69
|
+
async permission(request) { return aborted(this.approve(request), request.signal); }
|
|
70
|
+
async run(task, controller) {
|
|
71
|
+
const { signal } = controller;
|
|
72
|
+
const hash = digest(task);
|
|
73
|
+
try {
|
|
74
|
+
const target = 'path' in task.arguments ? task.arguments.path : 'executable' in task.arguments ? task.arguments.executable : undefined;
|
|
75
|
+
const scope = task.operation === 'file.read' ? { offset: task.arguments.offset, length: task.arguments.length }
|
|
76
|
+
: task.operation.startsWith('serial.') ? { baudRate: task.arguments.baudRate, durationMs: task.arguments.durationMs }
|
|
77
|
+
: task.operation === 'process.run' ? { cwd: task.arguments.cwd ?? process.cwd(), argumentCount: task.arguments.args.length, timeoutMs: task.arguments.timeoutMs } : {};
|
|
78
|
+
this.audit.record('task.requested', { id: task.id, operation: task.operation, digest: hash, ...(target ? { target } : {}), ...scope });
|
|
79
|
+
const write = prepareWrite(task);
|
|
80
|
+
const preview = redact(JSON.stringify(task, null, 2)) + (write ? '\n' + write.preview : '') + (task.operation.startsWith('serial.') ? '\nSerial control lines may reset the device.' : '');
|
|
81
|
+
if (!await this.permission({ stage: 'execute', task, digest: hash, preview, signal })) {
|
|
82
|
+
this.audit.record('task.denied', { id: task.id });
|
|
83
|
+
await this.finish(task.id, { status: 'denied' });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
signal.throwIfAborted();
|
|
87
|
+
if (digest(task) !== hash)
|
|
88
|
+
throw new Error('Task parameters changed after approval');
|
|
89
|
+
this.audit.record('task.approved', { id: task.id, digest: hash });
|
|
90
|
+
await this.peer.send({ type: 'task.started', id: task.id, digest: hash });
|
|
91
|
+
this.notice(`Executing ${task.operation}`);
|
|
92
|
+
const execution = await execute(task, signal, write);
|
|
93
|
+
if (execution.outputs.some(item => item.truncated))
|
|
94
|
+
execution.result.truncated = true;
|
|
95
|
+
if (task.operation === 'file.write' && execution.result.status === 'ok')
|
|
96
|
+
this.audit.record('task.file-changed', { id: task.id, ...execution.result.data });
|
|
97
|
+
const count = execution.outputs.reduce((sum, item) => sum + item.bytes.length, 0);
|
|
98
|
+
this.audit.record('task.collected', { id: task.id, bytes: count, status: execution.result.status, streams: execution.outputs.map(item => ({ stream: item.stream, bytes: item.bytes.length, encoding: item.encoding })) });
|
|
99
|
+
if (signal.aborted) {
|
|
100
|
+
await this.finish(task.id, { status: 'cancelled' });
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const resultText = JSON.stringify(execution.result);
|
|
104
|
+
const outputPreview = execution.outputs.map(item => `[${item.stream}/${item.encoding}; ${item.bytes.length} bytes]\n${item.encoding === 'utf8' ? item.bytes.toString('utf8') : `BINARY: no automatic redaction. Preview shows first 256 bytes; approval sends all ${item.bytes.length} bytes.\n${item.bytes.subarray(0, 256).toString('hex')}`}`).join('\n');
|
|
105
|
+
if (!await this.permission({ stage: 'send', task, digest: hash, preview: resultText + '\n' + outputPreview, bytes: count, signal })) {
|
|
106
|
+
this.audit.record('task.send-denied', { id: task.id });
|
|
107
|
+
await this.finish(task.id, { status: 'denied', error: 'Collected locally; user declined transfer' });
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
signal.throwIfAborted();
|
|
111
|
+
this.audit.record('task.transfer-approved', { id: task.id, bytes: count });
|
|
112
|
+
await this.transfer(task.id, execution, signal);
|
|
113
|
+
this.audit.record('task.completed', { id: task.id, status: execution.result.status });
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
const status = signal.aborted ? 'cancelled' : 'error';
|
|
117
|
+
try {
|
|
118
|
+
this.audit.record('task.failed', { id: task.id, status });
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
this.peer.close('Audit unavailable');
|
|
122
|
+
}
|
|
123
|
+
await this.finish(task.id, { status, error: signal.aborted ? 'Cancelled' : redact(error.message).slice(0, 2000) });
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
this.jobs.delete(task.id);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async transfer(id, execution, signal) {
|
|
130
|
+
let index = 0;
|
|
131
|
+
const encodings = {};
|
|
132
|
+
for (const item of execution.outputs) {
|
|
133
|
+
encodings[item.stream] = item.encoding;
|
|
134
|
+
for (let offset = 0; offset < item.bytes.length; offset += CHUNK_SIZE) {
|
|
135
|
+
signal.throwIfAborted();
|
|
136
|
+
const chunk = item.bytes.subarray(offset, offset + CHUNK_SIZE);
|
|
137
|
+
// The audit entry is durable before the corresponding bytes leave this endpoint.
|
|
138
|
+
this.audit.record('task.chunk-sending', { id, index, bytes: chunk.length });
|
|
139
|
+
await this.peer.send({ type: 'task.output', id, stream: item.stream, chunk: chunk.toString('base64'), index: index++ });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
this.jobs.delete(id);
|
|
143
|
+
await this.peer.send({ type: 'task.result', id, result: { ...execution.result, data: { ...(execution.result.data ?? {}), encodings } } });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type ChildProcess } from 'node:child_process';
|
|
2
|
+
import { type Task, type Result } from './schema.js';
|
|
3
|
+
export type Execution = {
|
|
4
|
+
result: Result;
|
|
5
|
+
outputs: {
|
|
6
|
+
stream: string;
|
|
7
|
+
bytes: Buffer;
|
|
8
|
+
encoding: 'utf8' | 'base64';
|
|
9
|
+
truncated?: boolean;
|
|
10
|
+
}[];
|
|
11
|
+
};
|
|
12
|
+
export declare function prepareWrite(task: Task): {
|
|
13
|
+
sha: string | null;
|
|
14
|
+
preview: string;
|
|
15
|
+
parent: string;
|
|
16
|
+
} | undefined;
|
|
17
|
+
export declare function execute(task: Task, signal: AbortSignal, write?: ReturnType<typeof prepareWrite>): Promise<Execution>;
|
|
18
|
+
export declare function killTree(child: ChildProcess, force?: boolean): void;
|