@masstensor/diagnose 0.0.0-stage → 0.2.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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -2
  3. package/deploy/Caddyfile +3 -0
  4. package/deploy/ecosystem.config.cjs +1 -0
  5. package/deploy/start-relay.sh +4 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +145 -0
  8. package/dist/crypto.d.ts +25 -0
  9. package/dist/crypto.js +60 -0
  10. package/dist/engine.d.ts +27 -0
  11. package/dist/engine.js +245 -0
  12. package/dist/executor.d.ts +18 -0
  13. package/dist/executor.js +208 -0
  14. package/dist/mcp.d.ts +1 -0
  15. package/dist/mcp.js +38 -0
  16. package/dist/operator.d.ts +21 -0
  17. package/dist/operator.js +69 -0
  18. package/dist/peer.d.ts +51 -0
  19. package/dist/peer.js +253 -0
  20. package/dist/relay-main.d.ts +2 -0
  21. package/dist/relay-main.js +6 -0
  22. package/dist/relay.d.ts +15 -0
  23. package/dist/relay.js +176 -0
  24. package/dist/schema.d.ts +298 -0
  25. package/dist/schema.js +32 -0
  26. package/dist/util.d.ts +11 -0
  27. package/dist/util.js +46 -0
  28. package/npm-shrinkwrap.json +2229 -0
  29. package/package.json +46 -4
  30. package/src/cli.ts +86 -0
  31. package/src/crypto.ts +54 -0
  32. package/src/engine.ts +156 -0
  33. package/src/executor.ts +131 -0
  34. package/src/mcp.ts +27 -0
  35. package/src/operator.ts +46 -0
  36. package/src/peer.ts +174 -0
  37. package/src/relay-main.ts +5 -0
  38. package/src/relay.ts +97 -0
  39. package/src/schema.ts +50 -0
  40. package/src/util.ts +39 -0
  41. package/src/vendor.d.ts +22 -0
  42. package/test/CACOPHONY-LICENSE +24 -0
  43. package/test/batch.test.ts +132 -0
  44. package/test/cli.test.ts +60 -0
  45. package/test/mcp.test.ts +32 -0
  46. package/test/noise-vector.json +40 -0
  47. package/test/probe.test.ts +131 -0
  48. package/test/serial.test.ts +24 -0
  49. package/test/vector.test.ts +32 -0
  50. 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,124 @@
1
- # Temporary Holding Version
1
+ # Diagnose
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ **0.2.0 权限选择**(只在用户本机决定):
25
+
26
+ - 配对时输入 `y`:每个任务/整批计划各确认一次执行、一次合并结果发送,不按每个子步骤询问。
27
+ - 配对时输入 `a`:明确授权本次会话**自动执行并自动发送**,后续任务不再弹确认。命令有当前OS用户权限;输出会直接提供给诊断者及其AI。终端持续显示任务及发送摘要,审计继续记录。文本脱敏仍不是秘密识别保证,二进制不会自动脱敏。
28
+ - 会话中输入 `permissions` 查看模式;`permissions ask` 撤销自动权限、取消正在运行的任务/整批,后续恢复审批。已发送内容不能撤回。
29
+ - 想在会话中开启自动模式:先输入 `permissions auto` 阅读说明,再在60秒内输入 `permissions allow-auto` 明确确认。远端请求没有切换权限的字段。
30
+ - `cancel` 取消当前任务/整批,保留当前权限模式;`Ctrl+C` 或 `exit` 结束会话。新会话恢复默认逐次审批,不继承自动授权。
31
+
32
+ 诊断者终端输入 JSON,请求立即返回任务 ID,使用 `wait <id>` 查看,`cancel <id>` 取消,`exit` 退出:
33
+
34
+ ```json
35
+ {"operation":"system.inspect","arguments":{},"reason":"检查电脑与串口环境"}
36
+ {"operation":"process.run","arguments":{"executable":"/usr/bin/sw_vers","args":[],"timeoutMs":10000},"reason":"查看 macOS 版本"}
37
+ {"operation":"file.read","arguments":{"path":"/absolute/path/to/log","offset":0,"length":65536},"reason":"检查用户指定日志"}
38
+ {"operation":"serial.capture","arguments":{"path":"/dev/cu.usbserial-2110","baudRate":115200,"durationMs":20000},"reason":"采集设备启动日志;串口可能导致重启"}
39
+ ```
40
+
41
+ 所有命令接受可选的中继地址:`diagnose start https://your-relay.example`。远程中继强制 TLS;回环测试允许 ws/http。
42
+
43
+ ## 一次提交多个操作或整段脚本
44
+
45
+ 两端均需升级到 **0.2.0+**:`npm install -g @masstensor/diagnose@latest`。中继协议不变,现有AWS中继无需升级。旧版本仍可使用原有单操作协议。
46
+
47
+ 批量JSON示例(交互终端粘贴时压成一行,AI/MCP可直接传结构化参数):
48
+
49
+ ```json
50
+ {
51
+ "operation": "batch.run",
52
+ "reason": "一次采集系统环境和运行时信息",
53
+ "arguments": {
54
+ "steps": [
55
+ {"operation":"system.inspect","arguments":{}},
56
+ {"operation":"process.script","arguments":{"interpreter":"node","script":"const os = require('node:os');\nconsole.log(JSON.stringify({uptime: os.uptime(), freeMemory: os.freemem()}));","timeoutMs":10000}}
57
+ ],
58
+ "stopOnError": true,
59
+ "timeoutMs": 60000
60
+ }
61
+ }
62
+ ```
63
+
64
+ 默认顺序执行,最多32步,不允许嵌套批量;遇错停止,显式设置 `stopOnError:false` 可继续独立步骤。整批总时限最多300秒,全部输出合计最多10MiB。返回每步状态及已完成/未运行数量,输出按 `0.stdout`、`1.file` 等区分。任何批次取消/断线/撤权都会终止当前进程组、释放串口并跳过后续步骤;已发生的修改不会自动回滚。
65
+
66
+ 整段脚本也可以独立提交:
67
+
68
+ ```json
69
+ {"operation":"process.script","arguments":{"interpreter":"/bin/sh","script":"uname -a\nprintf '\\n--- Disk ---\\n'\ndf -h\n","timeoutMs":30000},"reason":"一次采集系统和磁盘信息"}
70
+ ```
71
+
72
+ 必须明确指定解释器(如 `node`、`/bin/sh`)及可选 `args`、`cwd`。脚本通过stdin传入,默认不落临时脚本文件;人工审批时展示完整原文,一次授权整段脚本。脚本本身可以并发采集,但不会逐行审批。Windows应选择可从stdin读取脚本的解释器及对应参数。
73
+
74
+ 批量里的所有 `file.write` 会在整批审批前保存预览与旧文件哈希;若前面步骤修改了该目标,后续写入会因快照变化而拒绝,不会静默覆盖新内容。
75
+
76
+ ## AI / MCP
77
+
78
+ 在诊断者电脑的 MCP 客户端配置中加入(确保其环境 PATH 可找到安装后的 diagnose):
79
+
80
+ ```json
81
+ {"mcpServers":{"diagnose":{"command":"diagnose","args":["mcp"]}}}
82
+ ```
83
+
84
+ 工具:`diagnose_pair(code,label)`、`diagnose_start(operation,arguments,reason)`、`diagnose_batch(steps,reason,stopOnError,timeoutMs)`、`diagnose_wait(id,timeoutMs,release)`、`diagnose_cancel(id)`、`diagnose_disconnect()`。AI优先用diagnose_batch提交整份采集计划;整段脚本使用diagnose_start的process.script。批量与脚本都立即返回一个任务ID。等待一次最多 25 秒,pending 时继续轮询。大结果读取后可 release 释放诊断端缓存。MCP 使用本地 stdio,不暴露公网执行端口。配对码由你交给 AI,因此也会进入你所用 AI 的上下文;中继的加密边界不覆盖 AI 提供商。
85
+
86
+ ## 能力与约束
87
+
88
+ | operation | arguments |
89
+ |---|---|
90
+ | system.inspect | `{}`;OS、Node、串口枚举 |
91
+ | process.run | executable、args、cwd?、timeoutMs?;直接 spawn,不自动加 shell |
92
+ | process.script | interpreter、script、args?、cwd?、timeoutMs?;完整脚本通过stdin交给显式解释器 |
93
+ | batch.run | steps、stopOnError?、timeoutMs?;一次审批整个顺序计划及合并结果 |
94
+ | file.read | path、offset?、length?;每次最多 1 MiB |
95
+ | file.write | path、content、expectedSha256?;预览前后内容,核对旧文件哈希,临时文件加 rename |
96
+ | serial.capture | path、baudRate?、durationMs?;8N1,DTR/RTS=false,可能复位设备 |
97
+ | serial.exchange | 同上,另需 dataHex;发送明确字节后采集 |
98
+
99
+ 网络/USB 专用诊断程序可通过 process.run 调用,无设备型号预设。任意获准进程拥有当前 OS 用户权限,**不是沙箱**;不自动提权,不安装常驻服务。通用进程的所有副作用无法完整跟踪,也无法通用回滚。文件写入检查可发现通常的编辑竞争,但不提供对恶意本机并发修改的隔离。
100
+
101
+ 一次执行一个任务或整批计划;批内顺序执行。进程/脚本60秒默认、300秒上限;整批300秒默认/上限;串口最多300秒;整批合并输出10MiB上限;重复任务ID不再执行。10分钟空闲或60分钟会话结束。断线不重放,取消进程组并释放串口,重新诊断需新配对。POSIX进程组以外主动脱离的程序不能保证被终止。
102
+
103
+ ## 加密、审批与审计
104
+
105
+ Noise `NNpsk0_25519_ChaChaPoly_BLAKE2b`,256位随机配对秘密、临时X25519密钥、独立收发计数器、路由/角色/版本绑定。协议使用 noise-handshake 与 sodium;测试含公开 Cacophony 测试向量。每方向最多100万帧,远低于依赖的32位计数器边界。WSS同时校验证书。尚未经过独立安全审计。
106
+
107
+ 中继只保存内存房间和密文缓冲,不持久化内容、密钥或离线消息。仍可见IP、路由、连接时间及流量大小,也能阻断服务。配对秘密不发送给中继,持码仅证明持有权,标签不等于真实身份。
108
+
109
+ 本机 `~/.diagnose/audit-*.jsonl` 默认权限0600,记录任务ID、操作类型、目标路径/可执行文件/解释器、读取范围/串口参数、完整参数摘要、审批、各输出流采集/发送字节数、取消和结果。批内每步有父批次ID和独立结果,自动模式另记权限变更及自动批准的执行/发送阶段。工具写入文件时另记录路径、修改前后哈希及字节数。人工审批终端展示具体参数、完整脚本、写入前后内容与待发送预览;自动模式显示有长度上限的任务/发送摘要。默认审计不保存内容、脚本原文或完整命令参数,避免落盘秘密。因此历史日志不是完整命令回放或文件修改监控。每次审计写入flush,审计不可写则停止任务。
110
+
111
+ 采集文本先做常见凭据脱敏并移除终端控制字符。人工模式在本机合并预览并确认发送;自动模式依据用户本地已授予的会话权限直接发送。正则不能识别所有秘密,二进制不自动脱敏。采集与发送分别审计。进程输出在本地有上限地缓冲,得到本次或会话发送授权后才传输。Ctrl+C撤销待审请求、取消任务并结束会话。
112
+
113
+ ## 开发、测试、部署
114
+
115
+ ```sh
116
+ npm ci
117
+ npm test
118
+ npm run check
119
+ npm pack
120
+ ```
121
+
122
+ `test/live-gateway.ts` 是仅开发机显式调用的硬件验收,不包含在分发包中,也不随 npm test 运行。网关认证日志、固件、设备采集内容均不在包内。macOS探针与Linux中继实测;Windows及Linux探针暂为实验性,尚无真实串口与取消兼容性验收。
123
+
124
+ `deploy/ecosystem.config.cjs`、`deploy/Caddyfile` 提供部署模板。服务绑定127.0.0.1:8792,无数据库和运行密钥;DOWNLOAD_PATH可指定公开安装包路径。Caddy站点不开访问日志,PM2只记录固定启动/失败事件。仅部署打包后的白名单文件,不能同步用户诊断工作区。
@@ -0,0 +1,3 @@
1
+ diagnose.fenginwind.com {
2
+ reverse_proxy 127.0.0.1:8792
3
+ }
@@ -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' } }] };
@@ -0,0 +1,4 @@
1
+ #!/bin/sh
2
+ set -eu
3
+ ulimit -c 0
4
+ exec node --disable-sigusr1 dist/relay-main.js
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,145 @@
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, engine;
28
+ let localCommand = () => false;
29
+ const stop = () => { shutdown.abort(); peer?.close('User ended session'); rl.close(); };
30
+ rl.on('SIGINT', stop);
31
+ process.once('SIGTERM', stop);
32
+ rl.once('close', () => { shutdown.abort(); peer?.close('User terminal closed'); });
33
+ const ask = async (text, signal = shutdown.signal, taskApproval = false) => {
34
+ while (true) {
35
+ const answer = (await rl.question(safeText(text) + ' [y/N] ', { signal })).trim();
36
+ if (!localCommand(answer))
37
+ return answer.toLowerCase() === 'y';
38
+ signal.throwIfAborted();
39
+ if (taskApproval && engine?.permissionMode === 'auto')
40
+ return true;
41
+ }
42
+ };
43
+ try {
44
+ if (command === 'start') {
45
+ const audit = new Audit();
46
+ const code = createCode();
47
+ peer = new Peer({ role: 'host', code, relay, accept: async ({ label, fingerprint, signal }) => {
48
+ console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
49
+ console.log('Choose y: approve each task/batch and its transfer.\nChoose a: grant automatic execution AND transmission for this temporary session.\nAUTO: commands have your OS permissions; results go to the diagnostician and their AI without further prompts. Text redaction is best-effort; binary data is not redacted.\nRevoke locally with "permissions ask", cancel with "cancel", or end with Ctrl+C. Already transmitted data cannot be recalled.');
50
+ const answer = (await rl.question('Allow this temporary diagnostic session? [y / a=auto / N] ', { signal })).trim().toLowerCase();
51
+ const allowed = answer === 'y' || answer === 'a';
52
+ if (answer === 'a')
53
+ engine.setPermissionMode('auto');
54
+ audit.record('session.pairing-decision', { allowed, fingerprint });
55
+ return allowed;
56
+ } });
57
+ engine = new ProbeEngine(peer, async (request) => {
58
+ 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`);
59
+ 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, true);
60
+ }, audit, message => console.log(safeText(message)));
61
+ let active = false, autoRequestedAt = 0;
62
+ peer.on('active', () => { active = true; console.log(`Session permissions: ${engine.permissionMode}. Local commands: permissions, permissions auto, permissions ask, cancel, exit.`); });
63
+ localCommand = value => {
64
+ if (!active)
65
+ return false;
66
+ if (value === 'permissions') {
67
+ console.log(`Permission mode: ${engine.permissionMode}. AUTO means automatic execution AND transmission to the diagnostician/AI. Use permissions ask to revoke and cancel active work.`);
68
+ return true;
69
+ }
70
+ if (value === 'permissions auto') {
71
+ autoRequestedAt = Date.now();
72
+ console.log('AUTO grants this session automatic execution with your OS permissions AND automatic result transmission. Binary output is not redacted. Type "permissions allow-auto" within 60 seconds to grant, or "permissions ask" to decline.');
73
+ return true;
74
+ }
75
+ if (value === 'permissions allow-auto') {
76
+ if (autoRequestedAt && Date.now() - autoRequestedAt < 60000) {
77
+ engine.setPermissionMode('auto');
78
+ autoRequestedAt = 0;
79
+ }
80
+ else
81
+ console.log('No pending grant. First type "permissions auto" and read its explanation.');
82
+ return true;
83
+ }
84
+ if (value === 'permissions ask') {
85
+ autoRequestedAt = 0;
86
+ engine.setPermissionMode('ask');
87
+ console.log('Approval required. Automatic permissions revoked; any active work is cancelled.');
88
+ return true;
89
+ }
90
+ if (value === 'cancel') {
91
+ engine.cancelAll();
92
+ console.log('Cancellation requested for the current task/batch.');
93
+ return true;
94
+ }
95
+ if (value === 'exit') {
96
+ stop();
97
+ return true;
98
+ }
99
+ return false;
100
+ };
101
+ rl.on('line', value => { try {
102
+ if (active && !localCommand(value.trim()))
103
+ console.log('Local commands: permissions, permissions auto, permissions ask, cancel, exit.');
104
+ }
105
+ catch (error) {
106
+ console.error(safeText(error.message));
107
+ stop();
108
+ } });
109
+ await peer.open();
110
+ console.log(`Relay: ${relay}\nAudit: ${audit.path}\nPairing code (10 minutes, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
111
+ console.log(`Session ended: ${safeText(await peer.ended)}`);
112
+ }
113
+ else {
114
+ const code = (await rl.question('Pairing code: ', { signal: shutdown.signal })).trim();
115
+ const label = await rl.question('Your label / AI provider: ', { signal: shutdown.signal });
116
+ peer = new Peer({ role: 'join', code, relay, label });
117
+ const operator = new Operator(peer);
118
+ await peer.open();
119
+ console.log(`Connected. Fingerprint: ${peer.fingerprint}\nEnter task JSON. Use batch.run with {steps:[{operation,arguments}],stopOnError:true}; or process.script with {interpreter,script,args?,cwd?,timeoutMs?}.\nExample: {"operation":"system.inspect","arguments":{},"reason":"Inspect environment"}\nOther commands: cancel <task-id>, wait <task-id>, exit. Requests return immediately. Both endpoints need v0.2+ for batches/scripts.`);
120
+ peer.ended.then(() => stop());
121
+ while (!shutdown.signal.aborted) {
122
+ const line = (await rl.question('diagnose> ', { signal: shutdown.signal })).trim();
123
+ if (line === 'exit')
124
+ break;
125
+ try {
126
+ if (line.startsWith('cancel ')) {
127
+ await operator.cancel(line.slice(7).trim());
128
+ console.log('Cancellation requested');
129
+ }
130
+ else if (line.startsWith('wait '))
131
+ console.log(safeText(JSON.stringify(await operator.wait(line.slice(5).trim(), 1000), null, 2)));
132
+ else if (line)
133
+ console.log(`Task: ${await operator.start(JSON.parse(line))}`);
134
+ }
135
+ catch (error) {
136
+ console.error(safeText(error.message));
137
+ }
138
+ }
139
+ }
140
+ }
141
+ finally {
142
+ stop();
143
+ }
144
+ }
145
+ main().catch(error => { console.error(safeText(error.name === 'AbortError' ? 'Session ended' : error.message)); process.exitCode = 1; });
@@ -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
+ }
@@ -0,0 +1,27 @@
1
+ import { Peer } from './peer.js';
2
+ import { type ApprovalHandler } from './schema.js';
3
+ import { Audit } from './util.js';
4
+ export type PermissionMode = 'ask' | 'auto';
5
+ export declare class ProbeEngine {
6
+ private peer;
7
+ private approve;
8
+ readonly audit: Audit;
9
+ private notice;
10
+ private jobs;
11
+ private seen;
12
+ private idle;
13
+ private lifetime;
14
+ private mode;
15
+ get permissionMode(): PermissionMode;
16
+ setPermissionMode(mode: PermissionMode): void;
17
+ cancelAll(): void;
18
+ constructor(peer: Peer, approve: ApprovalHandler, audit: Audit, notice?: (message: string) => void);
19
+ private reply;
20
+ private finish;
21
+ private permission;
22
+ private recordRequest;
23
+ private runAtomic;
24
+ private runBatch;
25
+ private run;
26
+ private transfer;
27
+ }