one-model-router 0.0.10 → 0.0.12

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 (80) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +32 -5
  3. package/bin/omr.js +46 -0
  4. package/package.json +3 -2
  5. package/src/admin.js +965 -941
  6. package/src/balances.js +61 -61
  7. package/src/boot.js +117 -117
  8. package/src/channels/buddy.js +2031 -2031
  9. package/src/channels/cline.js +753 -753
  10. package/src/channels/codearts.js +2051 -2051
  11. package/src/channels/comate.js +830 -830
  12. package/src/channels/doubaowork.js +1784 -1784
  13. package/src/channels/freebuff.js +1316 -1316
  14. package/src/channels/gemini.js +1721 -1721
  15. package/src/channels/index.js +270 -270
  16. package/src/channels/joycode.js +936 -936
  17. package/src/channels/kimi.js +572 -572
  18. package/src/channels/lobsterai.js +1226 -1226
  19. package/src/channels/loomy.js +1032 -1032
  20. package/src/channels/miaoshou.js +1396 -1396
  21. package/src/channels/mimo.js +474 -474
  22. package/src/channels/minimax.js +1451 -1451
  23. package/src/channels/qoder-wasm.js +434 -434
  24. package/src/channels/qoder.js +1619 -1619
  25. package/src/channels/raccoon.js +1842 -1842
  26. package/src/channels/tabbit.js +1457 -1457
  27. package/src/channels/trae.js +1405 -1405
  28. package/src/channels/zcode-global.js +35 -35
  29. package/src/channels/zcode.js +2085 -2085
  30. package/src/checkin.js +496 -496
  31. package/src/credits.js +464 -464
  32. package/src/crypto.js +132 -132
  33. package/src/free-models.js +683 -683
  34. package/src/gateway.js +596 -578
  35. package/src/health.js +86 -86
  36. package/src/model-key.js +35 -35
  37. package/src/paths.js +96 -96
  38. package/src/probe.js +318 -318
  39. package/src/providers/builtin.js +626 -626
  40. package/src/providers/index.js +483 -457
  41. package/src/providers/kilo.js +111 -111
  42. package/src/providers/last-good.js +69 -69
  43. package/src/providers/modelsdev.js +242 -242
  44. package/src/providers/openai-compat.js +312 -312
  45. package/src/providers/opencode/bun-fetch.js +226 -226
  46. package/src/providers/opencode/lane.js +186 -186
  47. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  48. package/src/providers/opencode/o2a/asset-source.js +43 -43
  49. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  50. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  51. package/src/providers/opencode/o2a/entry.js +17 -17
  52. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  53. package/src/providers/opencode/o2a/headers.js +133 -133
  54. package/src/providers/opencode/o2a/identity.js +148 -148
  55. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  56. package/src/providers/opencode/o2a/official-tools.js +110 -110
  57. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  58. package/src/providers/opencode/o2a/toolshape.js +418 -418
  59. package/src/providers/opencode/o2a/version.js +37 -37
  60. package/src/providers/opencode/upstream.js +403 -403
  61. package/src/providers/opencode/wire.js +496 -496
  62. package/src/providers/opencode.js +652 -652
  63. package/src/router.js +629 -629
  64. package/src/server.js +49 -33
  65. package/src/store.js +467 -467
  66. package/src/sync/index.js +1529 -1529
  67. package/src/sync/login-preload.cjs +52 -52
  68. package/src/sync/noise.js +141 -141
  69. package/src/sync/relay-http.js +176 -176
  70. package/src/sync/remote-host.js +818 -818
  71. package/src/sync/remote-http.js +112 -112
  72. package/src/sync/remote-login.js +657 -657
  73. package/src/sync/remote-pairing.js +204 -204
  74. package/src/sync/remote-protocol.js +321 -321
  75. package/src/sync/snapshot.js +211 -211
  76. package/src/update.js +458 -0
  77. package/src/util.js +334 -334
  78. package/web/app.js +4010 -3972
  79. package/web/index.html +32 -32
  80. package/web/style.css +971 -971
@@ -1,321 +1,321 @@
1
- /**
2
- * DSH Remote Protocol v1 —— 一模路通桌面端共用的线协议工具层。
3
- *
4
- * 协议契约依据本机 P0 公共中继实测
5
- * (`scripts/omr-relay-probe.cjs`,2026-11-09 全链路通过)。
6
- *
7
- * 公共 Server 校验很严:控制帧**顶层与 payload 都 strict**,多一个字段
8
- * 就 `close 4008 "unknown field"`。因此出站帧一律走 `outboundFrame()` 裁剪白名单,
9
- * 绝不直接 `createControlFrame()` 后再补字段。
10
- *
11
- * 小程序适配说明(B2):除 `generateIdentityKeyPair()` 用 node:crypto、
12
- * 业务帧压缩用 node:zlib 外,其余均为 Web 标准 API(TextEncoder / btoa / atob /
13
- * crypto.randomUUID),小程序替换随机数与 base64 shim、
14
- * 把 zlib 换成 vendor/pako_*.umd.min.js 即可复用(gzip 格式两端一致)。
15
- */
16
-
17
- import { generateKeyPairSync, randomUUID } from 'node:crypto'
18
- import { gzipSync, gunzipSync } from 'node:zlib'
19
- import { sha256 } from '@noble/hashes/sha2.js'
20
- import { bytesToHex } from '@noble/hashes/utils.js'
21
-
22
- export const PROTOCOL_VERSION = 1
23
- export const DEFAULT_API_ORIGIN = 'https://dsh.r2049.cn'
24
- export const DEFAULT_RELAY_URL = 'wss://dsh.r2049.cn/ws/v1/connect'
25
- /**
26
- * ≥0.2.15 才被网关判为 modernHost,transport.selected / error 才会转发给 Host。
27
- * 网关的 modernHost 正则只接受 `major.minor.patch(+build)`,
28
- * 因此用 `+omr` 而非 `-omr`,两边都兼容(公共版实测更宽松)。
29
- */
30
- export const CLIENT_VERSION = '0.2.15+omr'
31
- /** 小程序没有 RTCPeerConnection:只宣告 relay,绝不宣告 lan/p2p/turn。 */
32
- export const CAPABILITIES = ['transport.relay']
33
-
34
- export const HELLO_TIMEOUT_MS = 5_000
35
- export const HEARTBEAT_INTERVAL_MS = 25_000
36
- export const HEARTBEAT_DISCONNECT_MS = 75_000
37
- export const MAX_CONTROL_FRAME_BYTES = 64 * 1024
38
- export const MAX_RELAY_FRAME_BYTES = 1024 * 1024
39
- /** Noise transport 单消息上限 65,535 B,32 KiB 分片留足 tag 与帧头余量。 */
40
- export const MAX_NOISE_MESSAGE_BYTES = 65_535
41
- // 32 KiB 明文分片:加密 + base64url 膨胀后单帧约 44KB,远离 64KB 控制帧档位,
42
- // 降低微信小程序运行时对大消息的处理压力(48KiB 分片单帧约 65.7KB 曾致手机端断连)。
43
- export const SECURE_FRAGMENT_CHUNK_BYTES = 32 * 1024
44
- export const MAX_SECURE_MESSAGE_BYTES = 4 * 1024 * 1024
45
-
46
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu
47
- const ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/iu
48
- export const isDeviceId = v => typeof v === 'string' && (UUID_RE.test(v) || ULID_RE.test(v))
49
- export const newDeviceId = () => randomUUID()
50
-
51
- const enc = new TextEncoder()
52
- const dec = new TextDecoder('utf-8', { fatal: true })
53
-
54
- /** X25519 raw 32 字节公钥/私钥,base64url(43 字符,符合 identityKey schema)。 */
55
- export function generateIdentityKeyPair() {
56
- const { publicKey, privateKey } = generateKeyPairSync('x25519')
57
- const spki = publicKey.export({ format: 'der', type: 'spki' })
58
- const pkcs8 = privateKey.export({ format: 'der', type: 'pkcs8' })
59
- return {
60
- publicKey: Buffer.from(spki.subarray(spki.length - 32)).toString('base64url'),
61
- privateKey: Buffer.from(pkcs8.subarray(pkcs8.length - 32)).toString('base64url'),
62
- }
63
- }
64
-
65
- /** 带外指纹:sha256(identityKey 字符串) 前 16 位 hex,供扫码人眼核对。 */
66
- export function identityFingerprint(publicKeyB64Url) {
67
- return bytesToHex(sha256(enc.encode(String(publicKeyB64Url)))).slice(0, 16)
68
- }
69
-
70
- /** Noise prologue 必须由两端逐字节一致地构造(两端必须用同一套格式)。 */
71
- export function createNoisePrologue(connectionId, hostDeviceId, clientDeviceId) {
72
- for (const [name, value] of Object.entries({ connectionId, hostDeviceId, clientDeviceId })) {
73
- if (typeof value !== 'string' || value === '' || value.includes('\0')) {
74
- throw new TypeError(`${name} is not safe for a Noise prologue`)
75
- }
76
- }
77
- return enc.encode(`DSH-REMOTE\0v=1\0connection=${connectionId}\0host=${hostDeviceId}\0client=${clientDeviceId}`)
78
- }
79
-
80
- // ── 控制帧 ──────────────────────────────────────────────────────────────────
81
-
82
- export const CONTROL_FRAME_TYPES = new Set([
83
- 'hello', 'hello.ack', 'connect.request', 'connect.incoming', 'connect.accepted',
84
- 'connect.rejected', 'secure.handshake', 'relay', 'signal.offer', 'signal.answer',
85
- 'signal.ice', 'transport.selected', 'ping', 'pong', 'error',
86
- ])
87
-
88
- /** payload 字段白名单:公共 Server 对 payload 也 strict,多余字段一律剔除。 */
89
- const OUTBOUND_FIELDS = {
90
- hello: ['role', 'deviceId', 'accessToken', 'protocols', 'capabilities', 'clientVersion'],
91
- pong: ['nonce'],
92
- 'connect.request': ['hostDeviceId', 'preferredTransports'],
93
- 'connect.accepted': ['connectionId'],
94
- 'connect.rejected': ['connectionId', 'code', 'message'],
95
- 'secure.handshake': ['connectionId', 'targetDeviceId', 'step', 'data'],
96
- 'transport.selected': ['connectionId', 'targetDeviceId', 'transport'],
97
- relay: ['connectionId', 'targetDeviceId', 'counter', 'ciphertext'],
98
- error: ['code', 'message', 'retryable', 'connectionId'],
99
- }
100
-
101
- export function createControlFrame(type, payload = {}) {
102
- if (!CONTROL_FRAME_TYPES.has(type)) throw new Error(`unknown control frame type: ${type}`)
103
- return {
104
- v: PROTOCOL_VERSION,
105
- id: randomUUID(),
106
- type,
107
- timestamp: Date.now(),
108
- payload,
109
- }
110
- }
111
-
112
- /** 构造并裁剪一帧(所有出站帧必须走这里)。 */
113
- export function outboundFrame(type, payload = {}) {
114
- const fields = OUTBOUND_FIELDS[type]
115
- const clean = {}
116
- if (fields) {
117
- for (const key of fields) if (payload?.[key] !== undefined) clean[key] = payload[key]
118
- } else {
119
- Object.assign(clean, payload ?? {})
120
- }
121
- return createControlFrame(type, clean)
122
- }
123
-
124
- export function encodeControlFrame(frame) {
125
- const text = JSON.stringify(frame)
126
- const max = frame.type === 'relay' ? MAX_RELAY_FRAME_BYTES : MAX_CONTROL_FRAME_BYTES
127
- const bytes = enc.encode(text).byteLength
128
- if (bytes > max) throw new Error(`${frame.type} frame exceeds ${max} bytes (${bytes})`)
129
- return text
130
- }
131
-
132
- export function decodeControlFrame(data) {
133
- const text = typeof data === 'string' ? data : dec.decode(data)
134
- const f = JSON.parse(text)
135
- if (f?.v !== PROTOCOL_VERSION || typeof f?.id !== 'string' || typeof f?.type !== 'string'
136
- || !Number.isInteger(f?.timestamp) || f.timestamp <= 0 || f.payload === undefined) {
137
- throw new Error('invalid control frame')
138
- }
139
- return f
140
- }
141
-
142
- // ── base64url(公共中继对 secure.handshake.data / relay.ciphertext 强制要求)──
143
- // 实测:发标准 base64 会被 Server 以 `close 4008 data must be bounded base64url` 拒绝,
144
- // 因为随机密文几乎必然含 `+` / `/` / `=`;P0 探针用固定 ASCII 串恰好没触发。
145
-
146
- export function bytesToBase64(bytes) {
147
- const u = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
148
- let bin = ''
149
- const STEP = 0x8000
150
- for (let i = 0; i < u.byteLength; i += STEP) {
151
- bin += String.fromCharCode(...u.subarray(i, Math.min(i + STEP, u.byteLength)))
152
- }
153
- return btoa(bin)
154
- }
155
-
156
- /** 出站二进制字段统一用 base64url(无 + / /、无 padding)。 */
157
- export function bytesToBase64Url(bytes) {
158
- return bytesToBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
159
- }
160
-
161
- /** 兼容标准 base64 与 base64url(含无 padding);两端可能处于不同版本。 */
162
- export function base64ToBytes(str) {
163
- const raw = String(str).trim().replace(/-/g, '+').replace(/_/g, '/')
164
- const padded = raw + '='.repeat((4 - (raw.length % 4)) % 4)
165
- const bin = atob(padded)
166
- const out = new Uint8Array(bin.length)
167
- for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i)
168
- return out
169
- }
170
-
171
- // ── 业务帧(Noise 密文内,Server 完全看不到)────────────────────────────────
172
- //
173
- // 压缩信封(降流量/降分片数):JSON → utf8 → gzip。gzip 自带 2 字节魔数
174
- // 0x1f 0x8b,而明文业务帧永远是 JSON(首字节 `{` = 0x7b),因此 decodeBusinessFrame
175
- // 可以「见到魔数就解压、否则按明文解析」,新老版本混跑不炸,无需能力协商。
176
- // 小帧(< COMPRESS_MIN_BYTES)不压:gzip 头尾固定开销 ~18B,压了反而更大。
177
- // 压缩在 SecureMessageCodec 分片**之前**完成,分片数因此真正下降。
178
- // 两端必须严格对称:小程序侧用 pako.gzip / pako.ungzip(同一魔数)。
179
-
180
- /** 明文达到该字节数才压缩(小于此值 gzip 后反而更大)。 */
181
- export const BUSINESS_COMPRESS_MIN_BYTES = 512
182
-
183
- export function encodeBusinessFrame(obj) {
184
- const plain = enc.encode(JSON.stringify(obj))
185
- if (plain.byteLength < BUSINESS_COMPRESS_MIN_BYTES) return plain
186
- try {
187
- return new Uint8Array(gzipSync(plain))
188
- } catch {
189
- return plain // 压缩异常绝不影响发送,回落明文(对端按前缀自动识别)
190
- }
191
- }
192
-
193
- export function decodeBusinessFrame(bytes) {
194
- const u = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
195
- if (isGzipBytes(u)) return JSON.parse(dec.decode(new Uint8Array(gunzipSync(u))))
196
- return JSON.parse(dec.decode(u))
197
- }
198
-
199
- /** gzip 魔数识别:0x1f 0x8b(与小程序 remote-protocol.js 同款判定)。 */
200
- export function isGzipBytes(bytes) {
201
- return !!bytes && bytes.byteLength >= 2 && bytes[0] === 0x1f && bytes[1] === 0x8b
202
- }
203
-
204
- // ── DSHF 分片(SecureMessageCodec 规范,逐字节保持兼容)───────────────────
205
-
206
- const FRAGMENT_MAGIC = new Uint8Array([0x44, 0x53, 0x48, 0x46]) // DSHF
207
- const FRAGMENT_VERSION = 1
208
- const FRAGMENT_HEADER_BYTES = 17
209
- const MAX_IN_FLIGHT = 8
210
-
211
- export class SecureMessageCodec {
212
- constructor() {
213
- this.nextMessageId = 1
214
- this.assemblies = new Map()
215
- }
216
-
217
- /** 先分片再逐片加密;≤48 KiB 不分片(不带头,decode 会自动识别)。 */
218
- encode(message) {
219
- const bytes = message instanceof Uint8Array ? message : new Uint8Array(message)
220
- if (bytes.byteLength > MAX_SECURE_MESSAGE_BYTES) throw new Error('Secure message exceeds the reassembly limit.')
221
- if (bytes.byteLength <= SECURE_FRAGMENT_CHUNK_BYTES) return [bytes]
222
-
223
- const messageId = this.nextMessageId
224
- this.nextMessageId = messageId === 0xffff_ffff ? 1 : messageId + 1
225
- const total = Math.ceil(bytes.byteLength / SECURE_FRAGMENT_CHUNK_BYTES)
226
- const frames = []
227
- for (let index = 0; index < total; index += 1) {
228
- const start = index * SECURE_FRAGMENT_CHUNK_BYTES
229
- const chunk = bytes.subarray(start, Math.min(bytes.byteLength, start + SECURE_FRAGMENT_CHUNK_BYTES))
230
- const frame = new Uint8Array(FRAGMENT_HEADER_BYTES + chunk.byteLength)
231
- frame.set(FRAGMENT_MAGIC)
232
- frame[4] = FRAGMENT_VERSION
233
- const view = new DataView(frame.buffer)
234
- view.setUint32(5, messageId)
235
- view.setUint16(9, index)
236
- view.setUint16(11, total)
237
- view.setUint32(13, bytes.byteLength)
238
- frame.set(chunk, FRAGMENT_HEADER_BYTES)
239
- frames.push(frame)
240
- }
241
- return frames
242
- }
243
-
244
- /** 返回完整消息,或 undefined(分片未齐);非法帧直接抛错(fail closed)。 */
245
- decode(frame) {
246
- if (!isSecureFragment(frame)) return frame
247
- if (frame.byteLength < FRAGMENT_HEADER_BYTES || frame[4] !== FRAGMENT_VERSION) {
248
- throw new Error('Secure fragment header is invalid.')
249
- }
250
- const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength)
251
- const messageId = view.getUint32(5)
252
- const index = view.getUint16(9)
253
- const total = view.getUint16(11)
254
- const totalBytes = view.getUint32(13)
255
- if (messageId === 0 || total < 2 || index >= total || totalBytes <= SECURE_FRAGMENT_CHUNK_BYTES
256
- || totalBytes > MAX_SECURE_MESSAGE_BYTES
257
- || total !== Math.ceil(totalBytes / SECURE_FRAGMENT_CHUNK_BYTES)) {
258
- throw new Error('Secure fragment metadata is invalid.')
259
- }
260
- const expected = Math.min(SECURE_FRAGMENT_CHUNK_BYTES, totalBytes - index * SECURE_FRAGMENT_CHUNK_BYTES)
261
- const chunk = frame.subarray(FRAGMENT_HEADER_BYTES)
262
- if (chunk.byteLength !== expected) throw new Error('Secure fragment length is invalid.')
263
-
264
- let assembly = this.assemblies.get(messageId)
265
- if (assembly === undefined) {
266
- if (index !== 0 || this.assemblies.size >= MAX_IN_FLIGHT) throw new Error('Secure fragment sequence is invalid.')
267
- assembly = { total, totalBytes, receivedBytes: 0, chunks: [] }
268
- this.assemblies.set(messageId, assembly)
269
- }
270
- if (assembly.total !== total || assembly.totalBytes !== totalBytes || index !== assembly.chunks.length) {
271
- this.assemblies.delete(messageId)
272
- throw new Error('Secure fragment sequence is invalid.')
273
- }
274
- assembly.chunks.push(Uint8Array.from(chunk))
275
- assembly.receivedBytes += chunk.byteLength
276
- if (assembly.chunks.length < total) return undefined
277
- this.assemblies.delete(messageId)
278
- if (assembly.receivedBytes !== totalBytes) throw new Error('Secure message length is invalid.')
279
- const message = new Uint8Array(totalBytes)
280
- let offset = 0
281
- for (const part of assembly.chunks) { message.set(part, offset); offset += part.byteLength }
282
- return message
283
- }
284
-
285
- reset() {
286
- this.nextMessageId = 1
287
- this.assemblies.clear()
288
- }
289
- }
290
-
291
- function isSecureFragment(frame) {
292
- if (frame.byteLength < FRAGMENT_MAGIC.byteLength) return false
293
- for (let i = 0; i < FRAGMENT_MAGIC.byteLength; i += 1) if (frame[i] !== FRAGMENT_MAGIC[i]) return false
294
- return true
295
- }
296
-
297
- // ── 连接错误分层:terminal 不重连并直出原因(治「连接中→未连接」刷屏)──────
298
-
299
- export const TERMINAL_ERROR_CODES = new Set([
300
- 'AUTH_INVALID', 'AUTH_REQUIRED', 'ACCOUNT_AUTH_REQUIRED', 'DEVICE_NOT_FOUND',
301
- 'DEVICE_REVOKED', 'DEVICE_OWNERSHIP_REQUIRED', 'MEMBERSHIP_REQUIRED',
302
- 'UNSUPPORTED_VERSION', 'INVALID_MESSAGE', 'CAPABILITY_NOT_SUPPORTED',
303
- 'PEER_IDENTITY_MISMATCH', 'METHOD_NOT_ALLOWED', 'SECURE_CHANNEL_FAILED',
304
- ])
305
- /** 4002 单列:token 失效可 refresh 重试,不属于纯 terminal。 */
306
- export const TERMINAL_CLOSE_CODES = new Set([4003, 4008, 4011])
307
-
308
- export function classifyDisconnect({ closeCode = 0, errorCode = '', message = '' } = {}) {
309
- const code = Number(closeCode) || 0
310
- if (TERMINAL_CLOSE_CODES.has(code)) {
311
- return { terminal: true, retryable: false, reason: `中继拒绝(${code} ${message || errorCode || '配置或帧格式错误'}):不会自动重连,请检查设备凭据与协议版本` }
312
- }
313
- if (TERMINAL_ERROR_CODES.has(String(errorCode))) {
314
- return { terminal: true, retryable: false, reason: `${errorCode}: ${message || '鉴权或协议错误'}(terminal,不重连)` }
315
- }
316
- return { terminal: false, retryable: true, reason: message || errorCode || `连接断开(${code || '网络'})` }
317
- }
318
-
319
- export function retryDelayMs(failures) {
320
- return Math.min(10_000, 500 * 2 ** Math.min(failures, 5))
321
- }
1
+ /**
2
+ * DSH Remote Protocol v1 —— 一模路通桌面端共用的线协议工具层。
3
+ *
4
+ * 协议契约依据本机 P0 公共中继实测
5
+ * (`scripts/omr-relay-probe.cjs`,2026-11-09 全链路通过)。
6
+ *
7
+ * 公共 Server 校验很严:控制帧**顶层与 payload 都 strict**,多一个字段
8
+ * 就 `close 4008 "unknown field"`。因此出站帧一律走 `outboundFrame()` 裁剪白名单,
9
+ * 绝不直接 `createControlFrame()` 后再补字段。
10
+ *
11
+ * 小程序适配说明(B2):除 `generateIdentityKeyPair()` 用 node:crypto、
12
+ * 业务帧压缩用 node:zlib 外,其余均为 Web 标准 API(TextEncoder / btoa / atob /
13
+ * crypto.randomUUID),小程序替换随机数与 base64 shim、
14
+ * 把 zlib 换成 vendor/pako_*.umd.min.js 即可复用(gzip 格式两端一致)。
15
+ */
16
+
17
+ import { generateKeyPairSync, randomUUID } from 'node:crypto'
18
+ import { gzipSync, gunzipSync } from 'node:zlib'
19
+ import { sha256 } from '@noble/hashes/sha2.js'
20
+ import { bytesToHex } from '@noble/hashes/utils.js'
21
+
22
+ export const PROTOCOL_VERSION = 1
23
+ export const DEFAULT_API_ORIGIN = 'https://dsh.r2049.cn'
24
+ export const DEFAULT_RELAY_URL = 'wss://dsh.r2049.cn/ws/v1/connect'
25
+ /**
26
+ * ≥0.2.15 才被网关判为 modernHost,transport.selected / error 才会转发给 Host。
27
+ * 网关的 modernHost 正则只接受 `major.minor.patch(+build)`,
28
+ * 因此用 `+omr` 而非 `-omr`,两边都兼容(公共版实测更宽松)。
29
+ */
30
+ export const CLIENT_VERSION = '0.2.15+omr'
31
+ /** 小程序没有 RTCPeerConnection:只宣告 relay,绝不宣告 lan/p2p/turn。 */
32
+ export const CAPABILITIES = ['transport.relay']
33
+
34
+ export const HELLO_TIMEOUT_MS = 5_000
35
+ export const HEARTBEAT_INTERVAL_MS = 25_000
36
+ export const HEARTBEAT_DISCONNECT_MS = 75_000
37
+ export const MAX_CONTROL_FRAME_BYTES = 64 * 1024
38
+ export const MAX_RELAY_FRAME_BYTES = 1024 * 1024
39
+ /** Noise transport 单消息上限 65,535 B,32 KiB 分片留足 tag 与帧头余量。 */
40
+ export const MAX_NOISE_MESSAGE_BYTES = 65_535
41
+ // 32 KiB 明文分片:加密 + base64url 膨胀后单帧约 44KB,远离 64KB 控制帧档位,
42
+ // 降低微信小程序运行时对大消息的处理压力(48KiB 分片单帧约 65.7KB 曾致手机端断连)。
43
+ export const SECURE_FRAGMENT_CHUNK_BYTES = 32 * 1024
44
+ export const MAX_SECURE_MESSAGE_BYTES = 4 * 1024 * 1024
45
+
46
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu
47
+ const ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/iu
48
+ export const isDeviceId = v => typeof v === 'string' && (UUID_RE.test(v) || ULID_RE.test(v))
49
+ export const newDeviceId = () => randomUUID()
50
+
51
+ const enc = new TextEncoder()
52
+ const dec = new TextDecoder('utf-8', { fatal: true })
53
+
54
+ /** X25519 raw 32 字节公钥/私钥,base64url(43 字符,符合 identityKey schema)。 */
55
+ export function generateIdentityKeyPair() {
56
+ const { publicKey, privateKey } = generateKeyPairSync('x25519')
57
+ const spki = publicKey.export({ format: 'der', type: 'spki' })
58
+ const pkcs8 = privateKey.export({ format: 'der', type: 'pkcs8' })
59
+ return {
60
+ publicKey: Buffer.from(spki.subarray(spki.length - 32)).toString('base64url'),
61
+ privateKey: Buffer.from(pkcs8.subarray(pkcs8.length - 32)).toString('base64url'),
62
+ }
63
+ }
64
+
65
+ /** 带外指纹:sha256(identityKey 字符串) 前 16 位 hex,供扫码人眼核对。 */
66
+ export function identityFingerprint(publicKeyB64Url) {
67
+ return bytesToHex(sha256(enc.encode(String(publicKeyB64Url)))).slice(0, 16)
68
+ }
69
+
70
+ /** Noise prologue 必须由两端逐字节一致地构造(两端必须用同一套格式)。 */
71
+ export function createNoisePrologue(connectionId, hostDeviceId, clientDeviceId) {
72
+ for (const [name, value] of Object.entries({ connectionId, hostDeviceId, clientDeviceId })) {
73
+ if (typeof value !== 'string' || value === '' || value.includes('\0')) {
74
+ throw new TypeError(`${name} is not safe for a Noise prologue`)
75
+ }
76
+ }
77
+ return enc.encode(`DSH-REMOTE\0v=1\0connection=${connectionId}\0host=${hostDeviceId}\0client=${clientDeviceId}`)
78
+ }
79
+
80
+ // ── 控制帧 ──────────────────────────────────────────────────────────────────
81
+
82
+ export const CONTROL_FRAME_TYPES = new Set([
83
+ 'hello', 'hello.ack', 'connect.request', 'connect.incoming', 'connect.accepted',
84
+ 'connect.rejected', 'secure.handshake', 'relay', 'signal.offer', 'signal.answer',
85
+ 'signal.ice', 'transport.selected', 'ping', 'pong', 'error',
86
+ ])
87
+
88
+ /** payload 字段白名单:公共 Server 对 payload 也 strict,多余字段一律剔除。 */
89
+ const OUTBOUND_FIELDS = {
90
+ hello: ['role', 'deviceId', 'accessToken', 'protocols', 'capabilities', 'clientVersion'],
91
+ pong: ['nonce'],
92
+ 'connect.request': ['hostDeviceId', 'preferredTransports'],
93
+ 'connect.accepted': ['connectionId'],
94
+ 'connect.rejected': ['connectionId', 'code', 'message'],
95
+ 'secure.handshake': ['connectionId', 'targetDeviceId', 'step', 'data'],
96
+ 'transport.selected': ['connectionId', 'targetDeviceId', 'transport'],
97
+ relay: ['connectionId', 'targetDeviceId', 'counter', 'ciphertext'],
98
+ error: ['code', 'message', 'retryable', 'connectionId'],
99
+ }
100
+
101
+ export function createControlFrame(type, payload = {}) {
102
+ if (!CONTROL_FRAME_TYPES.has(type)) throw new Error(`unknown control frame type: ${type}`)
103
+ return {
104
+ v: PROTOCOL_VERSION,
105
+ id: randomUUID(),
106
+ type,
107
+ timestamp: Date.now(),
108
+ payload,
109
+ }
110
+ }
111
+
112
+ /** 构造并裁剪一帧(所有出站帧必须走这里)。 */
113
+ export function outboundFrame(type, payload = {}) {
114
+ const fields = OUTBOUND_FIELDS[type]
115
+ const clean = {}
116
+ if (fields) {
117
+ for (const key of fields) if (payload?.[key] !== undefined) clean[key] = payload[key]
118
+ } else {
119
+ Object.assign(clean, payload ?? {})
120
+ }
121
+ return createControlFrame(type, clean)
122
+ }
123
+
124
+ export function encodeControlFrame(frame) {
125
+ const text = JSON.stringify(frame)
126
+ const max = frame.type === 'relay' ? MAX_RELAY_FRAME_BYTES : MAX_CONTROL_FRAME_BYTES
127
+ const bytes = enc.encode(text).byteLength
128
+ if (bytes > max) throw new Error(`${frame.type} frame exceeds ${max} bytes (${bytes})`)
129
+ return text
130
+ }
131
+
132
+ export function decodeControlFrame(data) {
133
+ const text = typeof data === 'string' ? data : dec.decode(data)
134
+ const f = JSON.parse(text)
135
+ if (f?.v !== PROTOCOL_VERSION || typeof f?.id !== 'string' || typeof f?.type !== 'string'
136
+ || !Number.isInteger(f?.timestamp) || f.timestamp <= 0 || f.payload === undefined) {
137
+ throw new Error('invalid control frame')
138
+ }
139
+ return f
140
+ }
141
+
142
+ // ── base64url(公共中继对 secure.handshake.data / relay.ciphertext 强制要求)──
143
+ // 实测:发标准 base64 会被 Server 以 `close 4008 data must be bounded base64url` 拒绝,
144
+ // 因为随机密文几乎必然含 `+` / `/` / `=`;P0 探针用固定 ASCII 串恰好没触发。
145
+
146
+ export function bytesToBase64(bytes) {
147
+ const u = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
148
+ let bin = ''
149
+ const STEP = 0x8000
150
+ for (let i = 0; i < u.byteLength; i += STEP) {
151
+ bin += String.fromCharCode(...u.subarray(i, Math.min(i + STEP, u.byteLength)))
152
+ }
153
+ return btoa(bin)
154
+ }
155
+
156
+ /** 出站二进制字段统一用 base64url(无 + / /、无 padding)。 */
157
+ export function bytesToBase64Url(bytes) {
158
+ return bytesToBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
159
+ }
160
+
161
+ /** 兼容标准 base64 与 base64url(含无 padding);两端可能处于不同版本。 */
162
+ export function base64ToBytes(str) {
163
+ const raw = String(str).trim().replace(/-/g, '+').replace(/_/g, '/')
164
+ const padded = raw + '='.repeat((4 - (raw.length % 4)) % 4)
165
+ const bin = atob(padded)
166
+ const out = new Uint8Array(bin.length)
167
+ for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i)
168
+ return out
169
+ }
170
+
171
+ // ── 业务帧(Noise 密文内,Server 完全看不到)────────────────────────────────
172
+ //
173
+ // 压缩信封(降流量/降分片数):JSON → utf8 → gzip。gzip 自带 2 字节魔数
174
+ // 0x1f 0x8b,而明文业务帧永远是 JSON(首字节 `{` = 0x7b),因此 decodeBusinessFrame
175
+ // 可以「见到魔数就解压、否则按明文解析」,新老版本混跑不炸,无需能力协商。
176
+ // 小帧(< COMPRESS_MIN_BYTES)不压:gzip 头尾固定开销 ~18B,压了反而更大。
177
+ // 压缩在 SecureMessageCodec 分片**之前**完成,分片数因此真正下降。
178
+ // 两端必须严格对称:小程序侧用 pako.gzip / pako.ungzip(同一魔数)。
179
+
180
+ /** 明文达到该字节数才压缩(小于此值 gzip 后反而更大)。 */
181
+ export const BUSINESS_COMPRESS_MIN_BYTES = 512
182
+
183
+ export function encodeBusinessFrame(obj) {
184
+ const plain = enc.encode(JSON.stringify(obj))
185
+ if (plain.byteLength < BUSINESS_COMPRESS_MIN_BYTES) return plain
186
+ try {
187
+ return new Uint8Array(gzipSync(plain))
188
+ } catch {
189
+ return plain // 压缩异常绝不影响发送,回落明文(对端按前缀自动识别)
190
+ }
191
+ }
192
+
193
+ export function decodeBusinessFrame(bytes) {
194
+ const u = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
195
+ if (isGzipBytes(u)) return JSON.parse(dec.decode(new Uint8Array(gunzipSync(u))))
196
+ return JSON.parse(dec.decode(u))
197
+ }
198
+
199
+ /** gzip 魔数识别:0x1f 0x8b(与小程序 remote-protocol.js 同款判定)。 */
200
+ export function isGzipBytes(bytes) {
201
+ return !!bytes && bytes.byteLength >= 2 && bytes[0] === 0x1f && bytes[1] === 0x8b
202
+ }
203
+
204
+ // ── DSHF 分片(SecureMessageCodec 规范,逐字节保持兼容)───────────────────
205
+
206
+ const FRAGMENT_MAGIC = new Uint8Array([0x44, 0x53, 0x48, 0x46]) // DSHF
207
+ const FRAGMENT_VERSION = 1
208
+ const FRAGMENT_HEADER_BYTES = 17
209
+ const MAX_IN_FLIGHT = 8
210
+
211
+ export class SecureMessageCodec {
212
+ constructor() {
213
+ this.nextMessageId = 1
214
+ this.assemblies = new Map()
215
+ }
216
+
217
+ /** 先分片再逐片加密;≤48 KiB 不分片(不带头,decode 会自动识别)。 */
218
+ encode(message) {
219
+ const bytes = message instanceof Uint8Array ? message : new Uint8Array(message)
220
+ if (bytes.byteLength > MAX_SECURE_MESSAGE_BYTES) throw new Error('Secure message exceeds the reassembly limit.')
221
+ if (bytes.byteLength <= SECURE_FRAGMENT_CHUNK_BYTES) return [bytes]
222
+
223
+ const messageId = this.nextMessageId
224
+ this.nextMessageId = messageId === 0xffff_ffff ? 1 : messageId + 1
225
+ const total = Math.ceil(bytes.byteLength / SECURE_FRAGMENT_CHUNK_BYTES)
226
+ const frames = []
227
+ for (let index = 0; index < total; index += 1) {
228
+ const start = index * SECURE_FRAGMENT_CHUNK_BYTES
229
+ const chunk = bytes.subarray(start, Math.min(bytes.byteLength, start + SECURE_FRAGMENT_CHUNK_BYTES))
230
+ const frame = new Uint8Array(FRAGMENT_HEADER_BYTES + chunk.byteLength)
231
+ frame.set(FRAGMENT_MAGIC)
232
+ frame[4] = FRAGMENT_VERSION
233
+ const view = new DataView(frame.buffer)
234
+ view.setUint32(5, messageId)
235
+ view.setUint16(9, index)
236
+ view.setUint16(11, total)
237
+ view.setUint32(13, bytes.byteLength)
238
+ frame.set(chunk, FRAGMENT_HEADER_BYTES)
239
+ frames.push(frame)
240
+ }
241
+ return frames
242
+ }
243
+
244
+ /** 返回完整消息,或 undefined(分片未齐);非法帧直接抛错(fail closed)。 */
245
+ decode(frame) {
246
+ if (!isSecureFragment(frame)) return frame
247
+ if (frame.byteLength < FRAGMENT_HEADER_BYTES || frame[4] !== FRAGMENT_VERSION) {
248
+ throw new Error('Secure fragment header is invalid.')
249
+ }
250
+ const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength)
251
+ const messageId = view.getUint32(5)
252
+ const index = view.getUint16(9)
253
+ const total = view.getUint16(11)
254
+ const totalBytes = view.getUint32(13)
255
+ if (messageId === 0 || total < 2 || index >= total || totalBytes <= SECURE_FRAGMENT_CHUNK_BYTES
256
+ || totalBytes > MAX_SECURE_MESSAGE_BYTES
257
+ || total !== Math.ceil(totalBytes / SECURE_FRAGMENT_CHUNK_BYTES)) {
258
+ throw new Error('Secure fragment metadata is invalid.')
259
+ }
260
+ const expected = Math.min(SECURE_FRAGMENT_CHUNK_BYTES, totalBytes - index * SECURE_FRAGMENT_CHUNK_BYTES)
261
+ const chunk = frame.subarray(FRAGMENT_HEADER_BYTES)
262
+ if (chunk.byteLength !== expected) throw new Error('Secure fragment length is invalid.')
263
+
264
+ let assembly = this.assemblies.get(messageId)
265
+ if (assembly === undefined) {
266
+ if (index !== 0 || this.assemblies.size >= MAX_IN_FLIGHT) throw new Error('Secure fragment sequence is invalid.')
267
+ assembly = { total, totalBytes, receivedBytes: 0, chunks: [] }
268
+ this.assemblies.set(messageId, assembly)
269
+ }
270
+ if (assembly.total !== total || assembly.totalBytes !== totalBytes || index !== assembly.chunks.length) {
271
+ this.assemblies.delete(messageId)
272
+ throw new Error('Secure fragment sequence is invalid.')
273
+ }
274
+ assembly.chunks.push(Uint8Array.from(chunk))
275
+ assembly.receivedBytes += chunk.byteLength
276
+ if (assembly.chunks.length < total) return undefined
277
+ this.assemblies.delete(messageId)
278
+ if (assembly.receivedBytes !== totalBytes) throw new Error('Secure message length is invalid.')
279
+ const message = new Uint8Array(totalBytes)
280
+ let offset = 0
281
+ for (const part of assembly.chunks) { message.set(part, offset); offset += part.byteLength }
282
+ return message
283
+ }
284
+
285
+ reset() {
286
+ this.nextMessageId = 1
287
+ this.assemblies.clear()
288
+ }
289
+ }
290
+
291
+ function isSecureFragment(frame) {
292
+ if (frame.byteLength < FRAGMENT_MAGIC.byteLength) return false
293
+ for (let i = 0; i < FRAGMENT_MAGIC.byteLength; i += 1) if (frame[i] !== FRAGMENT_MAGIC[i]) return false
294
+ return true
295
+ }
296
+
297
+ // ── 连接错误分层:terminal 不重连并直出原因(治「连接中→未连接」刷屏)──────
298
+
299
+ export const TERMINAL_ERROR_CODES = new Set([
300
+ 'AUTH_INVALID', 'AUTH_REQUIRED', 'ACCOUNT_AUTH_REQUIRED', 'DEVICE_NOT_FOUND',
301
+ 'DEVICE_REVOKED', 'DEVICE_OWNERSHIP_REQUIRED', 'MEMBERSHIP_REQUIRED',
302
+ 'UNSUPPORTED_VERSION', 'INVALID_MESSAGE', 'CAPABILITY_NOT_SUPPORTED',
303
+ 'PEER_IDENTITY_MISMATCH', 'METHOD_NOT_ALLOWED', 'SECURE_CHANNEL_FAILED',
304
+ ])
305
+ /** 4002 单列:token 失效可 refresh 重试,不属于纯 terminal。 */
306
+ export const TERMINAL_CLOSE_CODES = new Set([4003, 4008, 4011])
307
+
308
+ export function classifyDisconnect({ closeCode = 0, errorCode = '', message = '' } = {}) {
309
+ const code = Number(closeCode) || 0
310
+ if (TERMINAL_CLOSE_CODES.has(code)) {
311
+ return { terminal: true, retryable: false, reason: `中继拒绝(${code} ${message || errorCode || '配置或帧格式错误'}):不会自动重连,请检查设备凭据与协议版本` }
312
+ }
313
+ if (TERMINAL_ERROR_CODES.has(String(errorCode))) {
314
+ return { terminal: true, retryable: false, reason: `${errorCode}: ${message || '鉴权或协议错误'}(terminal,不重连)` }
315
+ }
316
+ return { terminal: false, retryable: true, reason: message || errorCode || `连接断开(${code || '网络'})` }
317
+ }
318
+
319
+ export function retryDelayMs(failures) {
320
+ return Math.min(10_000, 500 * 2 ** Math.min(failures, 5))
321
+ }