@duke-dsh-plugins/dsh-remote-control 0.0.0-stage → 1.1.4

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.
@@ -0,0 +1,266 @@
1
+ // lib/pairing.mjs —— 配对二维码(契约 §3.5,v1.0.3;v1.1.x 入口搬到设置面板)。
2
+ //
3
+ // 职责:
4
+ // 1. buildPairingUri:按 §3.5 逐字组装
5
+ // dshrc://pair?r=<encodeURIComponent(relayUrl)>&c=<channel>&s=<secret>[&t=<encodeURIComponent(relayToken)>]
6
+ // relayUrl 为空时抛出带明确指引的错误(先配置 relayUrl)。
7
+ // 2. 渲染产物:矩阵 + SVG(设置面板注入 qrSvg;ASCII 供终端参考)。
8
+ // 3. rotatePairingIdentity / setPairingHidden:轮换配对信息、隐藏/恢复配对
9
+ // (v1.1.x:入口是 DSH 设置面板的 Remote 方法,命令已删;逻辑留在这里复用)。
10
+ // 4. isLoopbackRelayUrl / loopbackWarning:回环地址判定(手机连不上,必须醒目提示)。
11
+ //
12
+ // **安全**:URI/二维码内容含 secret 明文,**绝不写日志**——日志只允许 redactUri 的脱敏形式。
13
+ import { spawn } from "node:child_process";
14
+ import { mkdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { dataDir, defaultEpoch, generateChannel, generateSecret, loadConfig, saveConfig } from "./config.mjs";
17
+ import { encodeToMatrix, toAscii, toSvg } from "./qr.mjs";
18
+
19
+ /** 二维码 SVG 文件名(位于 dataDir() 下)。 */
20
+ export const PAIRING_SVG_NAME = "pairing.svg";
21
+
22
+ /** pairing.svg 的绝对路径。 */
23
+ export function pairingSvgPath() {
24
+ return join(dataDir(), PAIRING_SVG_NAME);
25
+ }
26
+
27
+ /**
28
+ * 中继地址是否指向**本机回环**(127.0.0.1 / localhost / ::1)。
29
+ *
30
+ * 回环地址只在本机可达——手机扫码后连不上,界面必须醒目提示用户填局域网地址。
31
+ * 判定放在这里是为了让「设置页填写」「命令输出」等所有入口共用同一套规则。
32
+ *
33
+ * @param {string} url 中继地址(如 ws://192.168.1.10:8788)
34
+ * @returns {boolean}
35
+ */
36
+ export function isLoopbackRelayUrl(url) {
37
+ const raw = typeof url === "string" ? url.trim() : "";
38
+ if (raw === "") return false;
39
+ let host = "";
40
+ try {
41
+ host = new URL(raw).hostname.toLowerCase();
42
+ } catch {
43
+ return false;
44
+ }
45
+ return host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "[::1]";
46
+ }
47
+
48
+ /**
49
+ * 回环地址的醒目警告文案(非回环返回空串)。
50
+ * @param {string} url
51
+ * @returns {string}
52
+ */
53
+ export function loopbackWarning(url) {
54
+ if (!isLoopbackRelayUrl(url)) return "";
55
+ let host = "";
56
+ try {
57
+ host = new URL(String(url).trim()).hostname;
58
+ } catch {
59
+ host = String(url).trim();
60
+ }
61
+ return (
62
+ "警告:中继地址是本机回环地址(" + host + "),手机连不上——请填这台电脑在局域网里的地址" +
63
+ "(例如 ws://192.168.1.10:8788)。"
64
+ );
65
+ }
66
+
67
+ /**
68
+ * 按契约 §3.5 组装配对 URI。
69
+ * @param {{relayUrl:string, channel:string, secret:string, relayToken?:string}} cfg
70
+ * @returns {string} dshrc://pair?...
71
+ */
72
+ export function buildPairingUri(cfg) {
73
+ const relayUrl = typeof cfg?.relayUrl === "string" ? cfg.relayUrl.trim() : "";
74
+ if (relayUrl === "") {
75
+ throw new Error(
76
+ "relayUrl 尚未配置:请在 DSH「设置 → DSH Pocket」分区里填写中继地址" +
77
+ "(例如 ws://192.168.1.10:8788),保存后即可扫码配对。",
78
+ );
79
+ }
80
+ const channel = typeof cfg?.channel === "string" ? cfg.channel : "";
81
+ if (!/^[A-Z2-7]{16,64}$/.test(channel)) {
82
+ throw new Error("channel 不符合 ^[A-Z2-7]{16,64}$(应由插件自动生成;config.json 被改坏时可删除后重启插件重建)。");
83
+ }
84
+ const secret = typeof cfg?.secret === "string" ? cfg.secret : "";
85
+ if (secret.length < 32) {
86
+ throw new Error("secret 无效(应为 ≥32 字符的 base64url 串;config.json 被改坏时可删除后重启插件重建)。");
87
+ }
88
+ // §3.5:r 必须 URL 编码;c/s 为 URL 安全字符集无需编码;t 可选、同样编码。
89
+ let uri = "dshrc://pair?r=" + encodeURIComponent(relayUrl) + "&c=" + channel + "&s=" + secret;
90
+ const relayToken = typeof cfg?.relayToken === "string" ? cfg.relayToken : "";
91
+ if (relayToken !== "") uri += "&t=" + encodeURIComponent(relayToken);
92
+ return uri;
93
+ }
94
+
95
+ /**
96
+ * 日志脱敏(§3.5:URI/二维码内容不得写入日志)。保留形状、抹掉 secret/token。
97
+ * @param {string} uri
98
+ */
99
+ export function redactUri(uri) {
100
+ return String(uri)
101
+ .replace(/([?&]s=)[^&]*/g, "$1***")
102
+ .replace(/([?&]t=)[^&]*/g, "$1***");
103
+ }
104
+
105
+ /**
106
+ * 渲染配对二维码(矩阵 + ASCII + SVG)。
107
+ * @param {string} uri
108
+ * @returns {{uri:string, version:number, size:number, ascii:string, svg:string}}
109
+ */
110
+ export function renderPairing(uri) {
111
+ const qr = encodeToMatrix(uri);
112
+ return {
113
+ uri,
114
+ version: qr.version,
115
+ size: qr.size,
116
+ ascii: toAscii(qr),
117
+ svg: toSvg(qr),
118
+ };
119
+ }
120
+
121
+ /**
122
+ * 把 SVG 写到 %DSH_HOME%/remote-control/pairing.svg(原子写:tmp + rename)。
123
+ * @param {string} svg
124
+ * @returns {string} 写入路径
125
+ */
126
+ export function writePairingSvg(svg) {
127
+ const path = pairingSvgPath();
128
+ mkdirSync(dataDir(), { recursive: true });
129
+ const tmp = path + ".tmp";
130
+ writeFileSync(tmp, svg, "utf8");
131
+ // 同目录 rename(与 config.mjs 同一原子写范式);Windows 上 rename 覆盖
132
+ // 已存在目标前先 unlink,规避个别版本的 EPERM。
133
+ try {
134
+ unlinkSync(path);
135
+ } catch {
136
+ /* 目标不存在即可 */
137
+ }
138
+ renameSync(tmp, path);
139
+ return path;
140
+ }
141
+
142
+ /** 删除 pairing.svg(§3.5 隐藏能力)。@returns {{removed:boolean, path:string}} */
143
+ export function hidePairingSvg() {
144
+ const path = pairingSvgPath();
145
+ try {
146
+ unlinkSync(path);
147
+ return { removed: true, path };
148
+ } catch {
149
+ return { removed: false, path };
150
+ }
151
+ }
152
+
153
+ /**
154
+ * 用系统默认程序打开文件(win32: cmd /c start "";macOS: open;linux: xdg-open)。
155
+ * 失败只返回 false,绝不抛出、绝不阻塞命令。
156
+ * v1.1.x:/remote-pairing 命令已删,这里暂留为通用工具(设置页未来加「打开配对文件」
157
+ * 按钮时可直接用;当前无调用方)。
158
+ * @param {string} path
159
+ * @returns {boolean} 是否成功发起(不代表程序已打开)
160
+ */
161
+ export function openFileDefault(path) {
162
+ try {
163
+ const quoted = '"' + String(path).replace(/"/g, '\\"') + '"';
164
+ let child;
165
+ if (process.platform === "win32") {
166
+ child = spawn("cmd /c start \"\" " + quoted, { shell: true, detached: true, stdio: "ignore", windowsHide: true });
167
+ } else if (process.platform === "darwin") {
168
+ child = spawn("open " + quoted, { shell: true, detached: true, stdio: "ignore" });
169
+ } else {
170
+ child = spawn("xdg-open " + quoted, { shell: true, detached: true, stdio: "ignore" });
171
+ }
172
+ child.on("error", () => {
173
+ /* 打开失败不影响命令回复 */
174
+ });
175
+ child.unref();
176
+ return true;
177
+ } catch {
178
+ return false;
179
+ }
180
+ }
181
+
182
+ /**
183
+ * 轮换配对信息(契约 §3.5 rotate):换 channel+secret → 落盘 → 内存同步 →
184
+ * 链路热更换(旧 secret 不再保留,旧二维码立即失效)。
185
+ * @param {{config:any, configPath:string, log:Function, getRelay:()=>({reload?:(o:object)=>void}|null)}} deps
186
+ * @returns {{ok:boolean, channel?:string, savedPath?:string, note?:string, error?:string}}
187
+ */
188
+ export function rotatePairingIdentity(deps) {
189
+ const { config: cfg, configPath, log, getRelay } = deps;
190
+ const newChannel = generateChannel();
191
+ const newSecret = generateSecret();
192
+ // 只把 channel/secret 写回磁盘配置(磁盘文件为准,避免把行内紧急覆盖持久化)
193
+ let savedPath = "";
194
+ try {
195
+ const fresh = loadConfig().config;
196
+ fresh.channel = newChannel;
197
+ fresh.secret = newSecret;
198
+ // v1.1.3:**重置纪元锚点**(契约 §3.4.1)——换了 channel 就是换了「对端身份」,
199
+ // 旧锚点对新 channel 无意义;更重要的是它是**逃生口**:手机清过数据 → 它的纪元
200
+ // 归 1 → 本机记着「已接受的对端纪元 = N」→ 双方互判回退 → 硬断且无路可走。
201
+ // 轮换密钥(换 channel+secret)后双方都是新身份 → 锚点归零,重新配对即可恢复。
202
+ fresh.epoch = defaultEpoch();
203
+ savedPath = saveConfig(fresh);
204
+ } catch (e) {
205
+ return {
206
+ ok: false,
207
+ error: "配对信息已生成但保存失败:" + String(e && e.message) + "(请检查 " + configPath + ")",
208
+ };
209
+ }
210
+ // 内存配置同步更新(HostBridge 等持有同一对象)
211
+ cfg.channel = newChannel;
212
+ cfg.secret = newSecret;
213
+ // 链路热更换(§3.5:旧 secret 不再保留,旧二维码立即失效)
214
+ const relay = getRelay();
215
+ let note;
216
+ if (relay && typeof relay.reload === "function") {
217
+ try {
218
+ relay.reload({ channel: newChannel, secret: newSecret, relayToken: cfg.relayToken });
219
+ note = "中继链路已用新配对信息重连;旧配对信息(及旧二维码)即刻失效。";
220
+ } catch (e) {
221
+ log("warn", "relay reload after rotate failed", { error: String(e && e.message) });
222
+ note = "链路重连失败(" + String(e && e.message) + ")——请用 plugin_manager 重载本插件。";
223
+ }
224
+ } else {
225
+ note = "当前链路未启用(未配置 relayUrl / 插件空转 / KAT 失败),新配对信息将在下次连接时生效。";
226
+ }
227
+ // §3.5:只记 channel 与落盘路径,**不记 secret**
228
+ log("info", "pairing identity rotated", { channel: newChannel, savedPath });
229
+ return { ok: true, channel: newChannel, savedPath, note };
230
+ }
231
+
232
+ /**
233
+ * 隐藏 / 恢复配对(对应原 /remote-pairing hide 的语义):
234
+ * hidden=true → 删除本机 pairing.svg,并把 hidden=true 记进 config(设置页不再展示二维码);
235
+ * hidden=false → 重新生成并落盘 pairing.svg,hidden=false。
236
+ * @param {boolean} hidden
237
+ * @param {{config:any, log:Function}} deps
238
+ * @returns {{ok:boolean, hidden?:boolean, path?:string, removed?:boolean, error?:string}}
239
+ */
240
+ export function setPairingHidden(hidden, deps) {
241
+ const { config: cfg, log } = deps;
242
+ const want = hidden === true;
243
+ try {
244
+ const fresh = loadConfig().config;
245
+ fresh.hidden = want;
246
+ saveConfig(fresh);
247
+ } catch (e) {
248
+ return { ok: false, error: "配对隐藏状态保存失败:" + String(e && e.message) };
249
+ }
250
+ cfg.hidden = want;
251
+ if (want) {
252
+ const { removed, path } = hidePairingSvg();
253
+ log("info", "pairing hidden", { removed, path });
254
+ return { ok: true, hidden: true, removed, path };
255
+ }
256
+ // 恢复:重新渲染并落盘(失败不致命——设置页仍可直接展示内联二维码)
257
+ let path = "";
258
+ try {
259
+ const uri = buildPairingUri(cfg);
260
+ path = writePairingSvg(renderPairing(uri).svg);
261
+ } catch (e) {
262
+ log("warn", "pairing svg rewrite failed", { error: String(e && e.message) });
263
+ }
264
+ log("info", "pairing shown", { path: path || "(none)" });
265
+ return { ok: true, hidden: false, path };
266
+ }
@@ -0,0 +1,390 @@
1
+ // lib/protocol.mjs — dsh-remote-control 协议 v1 的加密与信封层(契约
2
+ // docs/PROTOCOL.md §3 / §5 / §7)。
3
+ //
4
+ // 职责(严格限定在协议内,不含传输与业务):
5
+ // - HKDF-SHA256 E2E 密钥派生(§3.3)
6
+ // - hello 帧 HMAC 签名(§3.4 v1 旧格式 + §3.4.1 v2 会话纪元格式)
7
+ // - AES-256-GCM 业务消息封解(§7:base64url(iv(12) || ct || tag(16)),
8
+ // AAD = UTF8("dshrc|" + 发送方 role + "|" + seq [ + "|" + sid ]))
9
+ // - 业务信封编解码(§5:{id, type, ts, payload})
10
+ // - 契约 §7 KAT 自测 assertKat():启动时调用,失败必须禁用连接。
11
+ //
12
+ // **v1.1.3(契约 §3.4.1 会话纪元 / §4 传输层帧 / §7 AAD)**:
13
+ // - hello 帧新增 e/ts/pv/sid 四个字段,sig 字段改用 v2 证明串
14
+ // "hello2|role|channel|e|ts|pv|sid"(旧格式 helloSig 保留:旧端互操作 + 单测)。
15
+ // - 业务帧 AAD 在**加固模式**(双方 pv≥2)额外绑定发送方的连接实例 id:
16
+ // "dshrc|role|seq|sid";兼容模式仍是旧的 "dshrc|role|seq"。
17
+ // - 模式判定与纪元单调性是**纯函数**(negotiateMode / acceptPeerEpoch),
18
+ // 放在协议层便于两端与单测共用同一份判定口径。
19
+ //
20
+ // 与 dsh-remote-control-e2e/protocol.mjs(Lead 维护的第三份实现)逐字节
21
+ // 兼容;两份实现的 KAT 向量一致即证明两端互通。
22
+ import crypto from "node:crypto";
23
+
24
+ export const PROTO_VERSION = 1;
25
+ export const ROLE_HOST = "host";
26
+ export const ROLE_CLIENT = "client";
27
+
28
+ /**
29
+ * v1.1.3 传输层协议版本(hello 帧的 pv 字段)。
30
+ * 旧端不带 pv → 视为 1(§3.4.1)。
31
+ */
32
+ export const HELLO_PROTO_VERSION = 2;
33
+
34
+ /** 握手模式:兼容模式(任一方 pv<2)与加固模式(双方 pv≥2)。 */
35
+ export const MODE_COMPAT = "compat";
36
+ export const MODE_HARDENED = "hardened";
37
+
38
+ const HKDF_SALT = "dsh-remote-control/v1";
39
+ const HKDF_INFO_PREFIX = "e2e|";
40
+ /** v2 证明串前缀(§3.4.1):"hello2|role|channel|e|ts|pv|sid"。 */
41
+ const HELLO_SIG2_PREFIX = "hello2|";
42
+ /** 连接实例 id 的形状:8 位十六进制(§3.4.1 / §4)。 */
43
+ const SID_RE = /^[0-9a-f]{8}$/i;
44
+
45
+ /**
46
+ * HKDF-SHA256 派生 32 字节 E2E key(契约 §3.3)。
47
+ * key = HKDF-SHA256(ikm=UTF8(secret), salt=UTF8("dsh-remote-control/v1"),
48
+ * info=UTF8("e2e|" + channel), L=32)
49
+ * @param {string} secret 配对 secret(≥32 字符随机串)
50
+ * @param {string} channel 配对 channel(16 位 base32)
51
+ * @returns {Buffer} 32 字节密钥
52
+ */
53
+ export function deriveKey(secret, channel) {
54
+ if (typeof secret !== "string" || secret === "") throw new Error("deriveKey: secret required");
55
+ if (typeof channel !== "string" || channel === "") throw new Error("deriveKey: channel required");
56
+ return Buffer.from(
57
+ crypto.hkdfSync(
58
+ "sha256",
59
+ Buffer.from(secret, "utf8"),
60
+ Buffer.from(HKDF_SALT, "utf8"),
61
+ Buffer.from(HKDF_INFO_PREFIX + channel, "utf8"),
62
+ 32,
63
+ ),
64
+ );
65
+ }
66
+
67
+ /**
68
+ * hello 帧轻量握手证明(契约 §3.4):
69
+ * sig = base64url(HMAC-SHA256(key, UTF8("hello|" + role + "|" + channel)))
70
+ * @param {Buffer} key deriveKey 的产物
71
+ * @param {"host"|"client"} role
72
+ * @param {string} channel
73
+ */
74
+ export function helloSig(key, role, channel) {
75
+ return crypto
76
+ .createHmac("sha256", key)
77
+ .update("hello|" + role + "|" + channel, "utf8")
78
+ .digest("base64url");
79
+ }
80
+
81
+ /**
82
+ * hello 帧 **v2 会话纪元证明**(契约 §3.4.1):
83
+ * sig = base64url(HMAC-SHA256(key, UTF8("hello2|" + role + "|" + channel + "|" + e + "|" + ts + "|" + pv + "|" + sid)))
84
+ *
85
+ * 与旧格式 helloSig("hello|role|channel")并存:旧格式保留给旧端互操作与单测,
86
+ * v2 证明串**取代** hello 帧 sig 字段里的旧内容。
87
+ *
88
+ * @param {Buffer} key deriveKey 的产物
89
+ * @param {"host"|"client"} role
90
+ * @param {string} channel
91
+ * @param {number} e 会话纪元(跨进程重启单调递增)
92
+ * @param {number} ts 发送时刻 Unix 毫秒(仅诊断用,不参与安全判定)
93
+ * @param {number} pv 协议版本(v1.1.3 = 2)
94
+ * @param {string} sid 发送方的连接实例 id(8 位十六进制)
95
+ * @returns {string} base64url 证明串
96
+ */
97
+ export function helloSig2(key, role, channel, e, ts, pv, sid) {
98
+ return crypto
99
+ .createHmac("sha256", key)
100
+ .update(HELLO_SIG2_PREFIX + role + "|" + channel + "|" + e + "|" + ts + "|" + pv + "|" + sid, "utf8")
101
+ .digest("base64url");
102
+ }
103
+
104
+ /**
105
+ * 校验对端的 v2 证明串(恒定时间比较;失败返回 false,调用方拒绝连接)。
106
+ * 中继没有密钥、只能原样复制对端证明 → 验签通过即可信任对端的 e/ts/pv/sid。
107
+ *
108
+ * @param {Buffer} key deriveKey 的产物
109
+ * @param {"host"|"client"} role 对端 role
110
+ * @param {string} channel
111
+ * @param {number} e
112
+ * @param {number} ts
113
+ * @param {number} pv
114
+ * @param {string} sid
115
+ * @param {string} sig 对端带来的证明串
116
+ * @returns {boolean}
117
+ */
118
+ export function verifyHelloSig2(key, role, channel, e, ts, pv, sid, sig) {
119
+ if (typeof sig !== "string" || sig === "") return false;
120
+ let expect;
121
+ try {
122
+ expect = Buffer.from(helloSig2(key, role, channel, e, ts, pv, sid), "utf8");
123
+ } catch {
124
+ return false;
125
+ }
126
+ const got = Buffer.from(sig, "utf8");
127
+ if (expect.length !== got.length) return false;
128
+ return crypto.timingSafeEqual(expect, got);
129
+ }
130
+
131
+ /**
132
+ * AAD(契约 §7):
133
+ * 兼容模式 = UTF8("dshrc|" + 发送方 role + "|" + seq)
134
+ * 加固模式 = UTF8("dshrc|" + 发送方 role + "|" + seq + "|" + sid)
135
+ * sid 省略/空串 → 兼容模式(旧 AAD 格式,逐字节兼容 v1.1.2)。
136
+ * @param {"host"|"client"} role 发送方 role
137
+ * @param {number} seq 该消息的 frame.seq
138
+ * @param {string} [sid] 发送方的连接实例 id(加固模式)
139
+ * @returns {Buffer}
140
+ */
141
+ export function aadOf(role, seq, sid) {
142
+ const base = "dshrc|" + role + "|" + seq;
143
+ const hardened = typeof sid === "string" && sid !== "";
144
+ return Buffer.from(hardened ? base + "|" + sid : base, "utf8");
145
+ }
146
+
147
+ /**
148
+ * 加密一条业务消息为 frame.data(契约 §7)。
149
+ * 载荷布局:base64url( iv(12) || ciphertext || tag(16) );iv 每消息随机。
150
+ * @param {Buffer} key
151
+ * @param {"host"|"client"} role 发送方 role(进入 AAD)
152
+ * @param {number} seq 该消息的 frame.seq(进入 AAD,防重放/串帧)
153
+ * @param {object} message 明文业务消息(JSON 可序列化)
154
+ * @param {Buffer} [iv] 固定 iv(仅供 KAT;正常发送省略 = CSPRNG 随机)
155
+ * @param {string} [sid] 发送方的连接实例 id(**加固模式**;省略 = 兼容模式旧 AAD)
156
+ * @returns {string} base64url 密文
157
+ */
158
+ export function seal(key, role, seq, message, iv, sid) {
159
+ const ivBuf = iv ?? crypto.randomBytes(12);
160
+ if (ivBuf.length !== 12) throw new Error("seal: iv must be 12 bytes");
161
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, ivBuf);
162
+ cipher.setAAD(aadOf(role, seq, sid));
163
+ const pt = Buffer.from(JSON.stringify(message), "utf8");
164
+ const ct = Buffer.concat([cipher.update(pt), cipher.final()]);
165
+ return Buffer.concat([ivBuf, ct, cipher.getAuthTag()]).toString("base64url");
166
+ }
167
+
168
+ /**
169
+ * 解密 frame.data(iv||ct||tag 布局)。认证失败抛错,调用方必须丢弃该帧。
170
+ * @param {Buffer} key
171
+ * @param {"host"|"client"} role **发送方** role(接收端解密时传对端的 role)
172
+ * @param {number} seq
173
+ * @param {string} dataB64
174
+ * @param {string} [sid] 发送方的连接实例 id(**加固模式**;省略 = 兼容模式旧 AAD)
175
+ * @returns {object} 解密后的业务消息
176
+ */
177
+ export function open(key, role, seq, dataB64, sid) {
178
+ const raw = Buffer.from(dataB64, "base64url");
179
+ if (raw.length < 12 + 16 + 1) throw new Error("open: ciphertext too short");
180
+ const iv = raw.subarray(0, 12);
181
+ const tag = raw.subarray(raw.length - 16);
182
+ const ct = raw.subarray(12, raw.length - 16);
183
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
184
+ decipher.setAAD(aadOf(role, seq, sid));
185
+ decipher.setAuthTag(tag);
186
+ const pt = Buffer.concat([decipher.update(ct), decipher.final()]);
187
+ return JSON.parse(pt.toString("utf8"));
188
+ }
189
+
190
+ /**
191
+ * 握手模式判定(契约 §3.4.1,**双方各自独立判断、必须一致**):
192
+ * 加固模式 = 本端 pv≥2 **且** 对端 pv≥2;任一方 pv<2 → 兼容模式。
193
+ * 对端 pv 未知(旧端 / 中继没透传证明)按 1 处理 → 兼容模式。
194
+ * @param {number} selfPv 本端协议版本
195
+ * @param {number} peerPv 对端协议版本(undefined/非法 → 1)
196
+ * @returns {typeof MODE_COMPAT | typeof MODE_HARDENED}
197
+ */
198
+ export function negotiateMode(selfPv, peerPv) {
199
+ const s = Number.isInteger(selfPv) ? selfPv : 1;
200
+ const p = Number.isInteger(peerPv) ? peerPv : 1;
201
+ return s >= 2 && p >= 2 ? MODE_HARDENED : MODE_COMPAT;
202
+ }
203
+
204
+ /**
205
+ * 对端会话纪元的单调性判定(契约 §3.4.1,纯函数,便于两端与单测共用口径)。
206
+ *
207
+ * 规则(state = 已接受的对端纪元锚点 {peerEpoch, peerSid}):
208
+ * - e === peerEpoch && sid === peerSid → 同一证明的重复(welcome 与 peer-joined 都带它)
209
+ * → **幂等接受**,不更新锚点;
210
+ * - 否则 e <= peerEpoch → **纪元回退**(疑似重放)→ 拒绝连接;
211
+ * - 否则 → 接受,钉扎 (e, sid)。
212
+ *
213
+ * @param {{peerEpoch?:number, peerSid?:string}} state 已接受的对端纪元锚点
214
+ * @param {{e:number, sid:string}} proof 对端证明里的纪元与连接实例 id
215
+ * @returns {{ok:boolean, duplicate?:boolean, reason?:string, peerEpoch:number, peerSid:string}}
216
+ */
217
+ export function acceptPeerEpoch(state, proof) {
218
+ const e = proof && proof.e;
219
+ const sid = proof && proof.sid;
220
+ const lastEpoch = state && Number.isInteger(state.peerEpoch) ? state.peerEpoch : 0;
221
+ const lastSid = state && typeof state.peerSid === "string" ? state.peerSid : "";
222
+ if (!Number.isInteger(e) || e < 0) {
223
+ return { ok: false, reason: "bad-epoch", peerEpoch: lastEpoch, peerSid: lastSid };
224
+ }
225
+ if (typeof sid !== "string" || !SID_RE.test(sid)) {
226
+ return { ok: false, reason: "bad-sid", peerEpoch: lastEpoch, peerSid: lastSid };
227
+ }
228
+ // 还没接受过任何对端证明(首次):直接钉扎(对端从 1 开始自增,不会撞)。
229
+ if (lastSid === "") {
230
+ return { ok: true, duplicate: false, peerEpoch: e, peerSid: sid };
231
+ }
232
+ // 同一证明的重复:幂等接受(不更新锚点)。
233
+ if (e === lastEpoch && sid === lastSid) {
234
+ return { ok: true, duplicate: true, peerEpoch: lastEpoch, peerSid: lastSid };
235
+ }
236
+ // 纪元回退 = 疑似重放 → 拒绝连接。
237
+ if (e <= lastEpoch) {
238
+ return { ok: false, reason: "epoch-regression", peerEpoch: lastEpoch, peerSid: lastSid };
239
+ }
240
+ return { ok: true, duplicate: false, peerEpoch: e, peerSid: sid };
241
+ }
242
+
243
+ /**
244
+ * 业务消息工厂(契约 §5):{id: uuid-v4, type, ts, payload}。
245
+ * @param {string} type
246
+ * @param {object} [payload]
247
+ * @param {string} [id] 已有 id 时复用(result 回包用请求的 id)
248
+ */
249
+ export function msg(type, payload, id) {
250
+ return {
251
+ id: id ?? crypto.randomUUID(),
252
+ type,
253
+ ts: Date.now(),
254
+ payload: payload ?? {},
255
+ };
256
+ }
257
+
258
+ /**
259
+ * 校验一条**入站明文**业务消息的信封形状(解密之后、分发之前调用)。
260
+ * 非法信封返回 null,调用方丢弃(不回包——对端可能在探测)。
261
+ * @param {unknown} m
262
+ * @returns {{id:string,type:string,ts:number,payload:object}|null}
263
+ */
264
+ export function sanitizeEnvelope(m) {
265
+ if (m === null || typeof m !== "object") return null;
266
+ const { id, type, ts, payload } = /** @type {Record<string, unknown>} */ (m);
267
+ if (typeof id !== "string" || id === "") return null;
268
+ if (typeof type !== "string" || type === "") return null;
269
+ if (ts !== undefined && typeof ts !== "number") return null;
270
+ if (payload !== undefined && (payload === null || typeof payload !== "object")) return null;
271
+ return { id, type, ts: typeof ts === "number" ? ts : 0, payload: payload === undefined ? {} : payload };
272
+ }
273
+
274
+ /**
275
+ * 契约 §7 KAT(已知答案测试):两端实现必须逐字节一致。
276
+ * 校验点:① key 派生;② 固定 iv 下 ct/tag 与契约向量一致;
277
+ * ③ AAD 绑定(role 交叉解密必须失败);
278
+ * ④ **v1.1.3 加固模式**:AAD 绑定 sid(换 sid 解密必须失败);兼容模式仍是旧格式;
279
+ * ⑤ v2 握手证明串自洽(helloSig2 / verifyHelloSig2)与模式/纪元判定口径。
280
+ * @returns {true} 失败抛错
281
+ */
282
+ export function assertKat() {
283
+ // ① key 派生
284
+ const key = deriveKey("dsh-remote-demo-secret-0123456789", "ABCDEFGH23456789");
285
+ const keyHex = key.toString("hex");
286
+ const expectKey = "6a76161fb789e8a48e1004cdcba483c2908bf4123180dae162dfb7e61e342a1d";
287
+ if (keyHex !== expectKey) throw new Error("KAT key mismatch: " + keyHex);
288
+
289
+ // ② 固定 iv 的 ct/tag 向量(契约 §7,空 AAD)
290
+ const ivBuf = Buffer.from("000102030405060708090a0b", "hex");
291
+ const pt = Buffer.from('{"id":"r1","type":"ping","ts":1700000000000,"payload":{}}', "utf8");
292
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, ivBuf);
293
+ cipher.setAAD(Buffer.alloc(0));
294
+ const ct = Buffer.concat([cipher.update(pt), cipher.final()]);
295
+ const ctHex = ct.toString("hex");
296
+ const tagHex = cipher.getAuthTag().toString("hex");
297
+ const expectCt =
298
+ "72b6fd46c5981533620ae9edc88cf0d607c89b5ad3da2d5ddd0548d6aef0c53e" +
299
+ "4b242be9c97ead9930a1374918a2f46dc861811055c1cbe1a3";
300
+ const expectTag = "292260ad46868699ac0bda00a1336cb4";
301
+ if (ctHex !== expectCt) throw new Error("KAT ct mismatch: " + ctHex);
302
+ if (tagHex !== expectTag) throw new Error("KAT tag mismatch: " + tagHex);
303
+
304
+ // 反向:解密契约向量必须还原明文
305
+ const vecData = Buffer.concat([ivBuf, Buffer.from(expectCt, "hex"), Buffer.from(expectTag, "hex")]).toString("base64url");
306
+ const cipher2 = crypto.createDecipheriv("aes-256-gcm", key, ivBuf);
307
+ cipher2.setAAD(Buffer.alloc(0));
308
+ cipher2.setAuthTag(Buffer.from(expectTag, "hex"));
309
+ const back = Buffer.concat([cipher2.update(Buffer.from(expectCt, "hex")), cipher2.final()]);
310
+ if (back.toString("utf8") !== pt.toString("utf8")) throw new Error("KAT decrypt mismatch");
311
+ void vecData;
312
+
313
+ // ③ AAD 绑定往返(契约 §7:encrypt(role="host", seq=7) → AAD "dshrc|host|7")
314
+ const data = seal(key, "host", 7, { hello: "world" });
315
+ const round = open(key, "host", 7, data);
316
+ if (round.hello !== "world") throw new Error("KAT aad roundtrip failed");
317
+ let crossRejected = false;
318
+ try {
319
+ open(key, "client", 7, data);
320
+ } catch {
321
+ crossRejected = true;
322
+ }
323
+ if (!crossRejected) throw new Error("KAT: AAD role binding not enforced");
324
+ // seq 也必须绑定:换 seq 解密必须失败
325
+ let seqRejected = false;
326
+ try {
327
+ open(key, "host", 8, data);
328
+ } catch {
329
+ seqRejected = true;
330
+ }
331
+ if (!seqRejected) throw new Error("KAT: AAD seq binding not enforced");
332
+
333
+ // ④ v1.1.3 加固模式 AAD(契约 §7:"dshrc|host|7|a1b2c3d4")
334
+ const hardSid = "a1b2c3d4";
335
+ const hardData = seal(key, "host", 7, { hello: "world" }, undefined, hardSid);
336
+ const hardRound = open(key, "host", 7, hardData, hardSid);
337
+ if (hardRound.hello !== "world") throw new Error("KAT: hardened aad roundtrip failed");
338
+ // 换 sid 解密必须失败(加固模式绑定连接实例 id)
339
+ let sidRejected = false;
340
+ try {
341
+ open(key, "host", 7, hardData, "b1b2b3b4");
342
+ } catch {
343
+ sidRejected = true;
344
+ }
345
+ if (!sidRejected) throw new Error("KAT: AAD sid binding not enforced");
346
+ // 加固密文用兼容 AAD 解也必须失败(模式不得混用)
347
+ let modeRejected = false;
348
+ try {
349
+ open(key, "host", 7, hardData);
350
+ } catch {
351
+ modeRejected = true;
352
+ }
353
+ if (!modeRejected) throw new Error("KAT: hardened/compat AAD mixing not rejected");
354
+ // 兼容模式的 AAD 逐字节等于旧格式(不带 sid)
355
+ if (aadOf("host", 7).toString("utf8") !== "dshrc|host|7") throw new Error("KAT: compat AAD format changed");
356
+ if (aadOf("host", 7, hardSid).toString("utf8") !== "dshrc|host|7|a1b2c3d4") throw new Error("KAT: hardened AAD format changed");
357
+
358
+ // ⑤ v2 握手证明串(契约 §3.4.1)
359
+ const sig2 = helloSig2(key, "host", "ABCDEFGH23456789", 3, 1700000000000, HELLO_PROTO_VERSION, hardSid);
360
+ if (!verifyHelloSig2(key, "host", "ABCDEFGH23456789", 3, 1700000000000, HELLO_PROTO_VERSION, hardSid, sig2)) {
361
+ throw new Error("KAT: hello2 proof self-verification failed");
362
+ }
363
+ if (verifyHelloSig2(key, "client", "ABCDEFGH23456789", 3, 1700000000000, HELLO_PROTO_VERSION, hardSid, sig2)) {
364
+ throw new Error("KAT: hello2 proof role binding not enforced");
365
+ }
366
+ if (verifyHelloSig2(key, "host", "ABCDEFGH23456789", 4, 1700000000000, HELLO_PROTO_VERSION, hardSid, sig2)) {
367
+ throw new Error("KAT: hello2 proof epoch binding not enforced");
368
+ }
369
+ if (verifyHelloSig2(key, "host", "ABCDEFGH23456789", 3, 1700000000000, HELLO_PROTO_VERSION, "b1b2b3b4", sig2)) {
370
+ throw new Error("KAT: hello2 proof sid binding not enforced");
371
+ }
372
+ // 模式判定口径(契约 §3.4.1)
373
+ if (negotiateMode(HELLO_PROTO_VERSION, HELLO_PROTO_VERSION) !== MODE_HARDENED) {
374
+ throw new Error("KAT: mode negotiation (both pv>=2) must be hardened");
375
+ }
376
+ if (negotiateMode(HELLO_PROTO_VERSION, 1) !== MODE_COMPAT) {
377
+ throw new Error("KAT: mode negotiation (peer pv<2) must be compat");
378
+ }
379
+ if (negotiateMode(HELLO_PROTO_VERSION, undefined) !== MODE_COMPAT) {
380
+ throw new Error("KAT: mode negotiation (unknown peer) must be compat");
381
+ }
382
+ // 纪元单调性判定口径(契约 §3.4.1)
383
+ const first = acceptPeerEpoch({ peerEpoch: 0, peerSid: "" }, { e: 5, sid: "aaaaaaaa" });
384
+ if (!first.ok || first.duplicate) throw new Error("KAT: first peer epoch must be accepted");
385
+ const dup = acceptPeerEpoch({ peerEpoch: 5, peerSid: "aaaaaaaa" }, { e: 5, sid: "aaaaaaaa" });
386
+ if (!dup.ok || !dup.duplicate) throw new Error("KAT: duplicate peer proof must be idempotent");
387
+ const regress = acceptPeerEpoch({ peerEpoch: 5, peerSid: "aaaaaaaa" }, { e: 4, sid: "aaaaaaaa" });
388
+ if (regress.ok) throw new Error("KAT: peer epoch regression must be rejected");
389
+ return true;
390
+ }