dsh-connect-workbuddy-gateway 1.3.2 → 1.4.2
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/README.md +85 -6
- package/client.js +804 -7
- package/index.js +38 -0
- package/package.json +2 -2
- package/src/discovery.js +289 -0
- package/src/pairing.js +165 -0
- package/src/peers.js +229 -0
- package/src/routes.js +814 -1
package/index.js
CHANGED
|
@@ -29,6 +29,16 @@ export const name = 'workbuddy-gateway'
|
|
|
29
29
|
export const inject = ['webServer']
|
|
30
30
|
|
|
31
31
|
const DEFAULTS = {
|
|
32
|
+
/**
|
|
33
|
+
* 运行模式。两种角色的配置项**完全不重叠**,所以选了一种就把另一种整体隐藏。
|
|
34
|
+
*
|
|
35
|
+
* - `upstream`(默认)从本机的 dsh-connect-workbuddy 取模型,按 key 对外提供
|
|
36
|
+
* HTTP API。这是「发送方」,全功能:端口、局域网、配对批准、来源校验。
|
|
37
|
+
* - `client` 接入另一台设备分享出来的网关,把它当成模型来源。这是
|
|
38
|
+
* 「接收方」,只保留:找网关、申请配对、查看已接入的网关。**不提供**任何
|
|
39
|
+
* 对外分享功能 —— 一个接收方再往外分享既没有意义,也会把别人的额度转手。
|
|
40
|
+
*/
|
|
41
|
+
mode: 'upstream',
|
|
32
42
|
/**
|
|
33
43
|
* 网关监听端口。
|
|
34
44
|
*
|
|
@@ -51,6 +61,34 @@ const DEFAULTS = {
|
|
|
51
61
|
* 局域网设备改不了配置、看不到 key 明文。
|
|
52
62
|
*/
|
|
53
63
|
allowLan: false,
|
|
64
|
+
/**
|
|
65
|
+
* 浏览器来源(Origin)校验策略。
|
|
66
|
+
*
|
|
67
|
+
* 网关只认 API key,没有 DSH 的「会话 + 同源」检查。所以对**带了 Origin 头**的
|
|
68
|
+
* 请求(也就是浏览器发起的)要额外判一下来源。命令行客户端不发这个头,一律放行。
|
|
69
|
+
*
|
|
70
|
+
* - `loopback` 只放行本机页面(默认,最严)
|
|
71
|
+
* - `self` 本机 + 指向本机地址的页面(任意端口)
|
|
72
|
+
* - `lan` 本机 + 任意私有网段页面(最宽松)
|
|
73
|
+
*
|
|
74
|
+
* 默认取最严的那档:需要放宽时由用户在设置页显式选择,而不是装好就替他把门
|
|
75
|
+
* 开到整个网段。
|
|
76
|
+
*/
|
|
77
|
+
originPolicy: 'loopback',
|
|
78
|
+
/**
|
|
79
|
+
* 局域网发现端口(UDP)。
|
|
80
|
+
*
|
|
81
|
+
* 与 HTTP 端口分开:同一个端口号不能同时被 TCP 和 UDP 的不同用途绑,而且用户
|
|
82
|
+
* 改 HTTP 端口时不该顺带把发现也弄坏。
|
|
83
|
+
*/
|
|
84
|
+
discoveryPort: 8791,
|
|
85
|
+
/**
|
|
86
|
+
* 在局域网发现应答里显示的机器名。
|
|
87
|
+
*
|
|
88
|
+
* 留空时接收方只看到 IP。填一个短名字(例如「书房的电脑」)能帮用户在列表里
|
|
89
|
+
* 认出该连哪一台。
|
|
90
|
+
*/
|
|
91
|
+
shareName: '',
|
|
54
92
|
/**
|
|
55
93
|
* 配置目录。
|
|
56
94
|
*
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-connect-workbuddy-gateway",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "把 dsh-connect-workbuddy 的 WorkBuddy 模型开放成 HTTP API:OpenAI Chat / Responses、Anthropic Messages、Gemini 四协议共用一个固定 base URL,模型按 API key
|
|
3
|
+
"version": "1.4.2",
|
|
4
|
+
"description": "把 dsh-connect-workbuddy 的 WorkBuddy 模型开放成 HTTP API:OpenAI Chat / Responses、Anthropic Messages、Gemini 四协议共用一个固定 base URL,模型按 API key 逐个勾选。也可切换成接收方,接入局域网内另一台设备分享的模型。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh-plugin",
|
|
7
7
|
"deepseek-harness",
|
package/src/discovery.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 局域网发现:让另一台设备装上同一个插件后自动找到这台机器。
|
|
3
|
+
*
|
|
4
|
+
* ## 协议设计
|
|
5
|
+
*
|
|
6
|
+
* UDP 广播,一次请求一次应答,**不引入任何依赖**(`node:dgram` 就够):
|
|
7
|
+
*
|
|
8
|
+
* ```
|
|
9
|
+
* 接收方 → 255.255.255.255:port "WBGW1 ?" (广播询问)
|
|
10
|
+
* 发送方 → 单播回来源 "WBGW1 ! <json>" (应答自己的地址与状态)
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* 为什么用广播而不是 mDNS:mDNS 要处理多播组成员、TTL、跨网卡,服务名还要走
|
|
14
|
+
* DNS-SD 编码,零依赖手写容易出细节错误。UDP 广播在同一个二层网络里是可靠的,
|
|
15
|
+
* 而「另一台设备」本来就在同一个网段。
|
|
16
|
+
*
|
|
17
|
+
* ## 为什么应答里不含 key
|
|
18
|
+
*
|
|
19
|
+
* 广播能被同网段任何机器收到。应答里只放「我是谁、要不要配对」,**凭据必须走
|
|
20
|
+
* 后续的一次性 HTTP 配对请求**,由发送方在本机确认后才发出。这样即使有人在监听
|
|
21
|
+
* 广播,他拿到的也只是「这里有个网关」。
|
|
22
|
+
*
|
|
23
|
+
* ## 为什么每次广播换一个 nonce
|
|
24
|
+
*
|
|
25
|
+
* 应答回到一个随机端口,只有发出广播的那个 socket 知道自己的端口。nonce 让接收方
|
|
26
|
+
* 能确认这是针对自己这次询问的应答,而不是别处广播的残留。
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { createSocket } from 'node:dgram'
|
|
30
|
+
import { networkInterfaces } from 'node:os'
|
|
31
|
+
|
|
32
|
+
/** 协议标记与版本。应答方据此忽略不相干的广播。 */
|
|
33
|
+
export const DISCOVERY_MAGIC = 'WBGW1'
|
|
34
|
+
/** 默认发现端口。与网关的 HTTP 端口故意不同,避免两者抢绑定。 */
|
|
35
|
+
export const DEFAULT_DISCOVERY_PORT = 8791
|
|
36
|
+
/** 广播包的最大长度;应答里只有一条 JSON,几百字节足够。 */
|
|
37
|
+
const MAX_PACKET = 4096
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 广播询问,收集一段时间内的应答。
|
|
41
|
+
*
|
|
42
|
+
* @param options 配置
|
|
43
|
+
* @param options.port 发现端口
|
|
44
|
+
* @param options.timeoutMs 收集时长(默认 1.2 秒)
|
|
45
|
+
* @param options.logger 日志
|
|
46
|
+
* @returns `Promise<Array<{ host, port, httpPort, name, paired }>>`
|
|
47
|
+
*/
|
|
48
|
+
export async function discoverPeers({ port = DEFAULT_DISCOVERY_PORT, timeoutMs = 1200, logger } = {}) {
|
|
49
|
+
const nonce = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
|
|
50
|
+
const replies = new Map()
|
|
51
|
+
const socket = createSocket({ type: 'udp4', reuseAddr: true })
|
|
52
|
+
|
|
53
|
+
await new Promise((resolve) => {
|
|
54
|
+
socket.on('error', () => resolve())
|
|
55
|
+
socket.bind(0, () => resolve())
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
socket.on('message', (buffer, remote) => {
|
|
59
|
+
const reply = parseAnnouncement(buffer)
|
|
60
|
+
if (reply === undefined) return
|
|
61
|
+
/* 只认对这次询问的应答。 */
|
|
62
|
+
if (reply.nonce !== nonce) return
|
|
63
|
+
const key = `${remote.address}:${reply.httpPort}`
|
|
64
|
+
replies.set(key, {
|
|
65
|
+
host: remote.address,
|
|
66
|
+
httpPort: reply.httpPort,
|
|
67
|
+
name: typeof reply.name === 'string' ? reply.name : '',
|
|
68
|
+
lan: reply.lan === true,
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
const packet = Buffer.from(JSON.stringify({ magic: DISCOVERY_MAGIC, kind: 'query', nonce, port }), 'utf8')
|
|
73
|
+
|
|
74
|
+
/* 逐个网卡向它的广播地址发;只发 255.255.255.255 在有多个网卡时会漏。 */
|
|
75
|
+
for (const address of broadcastAddresses()) {
|
|
76
|
+
try {
|
|
77
|
+
socket.send(packet, 0, packet.length, port, address, () => {})
|
|
78
|
+
} catch {
|
|
79
|
+
/* 这条网卡发不出去就算了 */
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
await new Promise((resolve) => setTimeout(resolve, timeoutMs))
|
|
84
|
+
try {
|
|
85
|
+
socket.close()
|
|
86
|
+
} catch {
|
|
87
|
+
/* 已经关了 */
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
logger?.info?.(`workbuddy-gateway: discovery found ${String(replies.size)} peer(s)`)
|
|
91
|
+
|
|
92
|
+
/*
|
|
93
|
+
* 排序:让接收方优先选中「真能连上」的那个地址。
|
|
94
|
+
*
|
|
95
|
+
* 实测本机会同时收到 `192.168.128.1` 和 `192.168.31.107`。前者是 Hyper-V 的
|
|
96
|
+
* 默认交换机 —— 它也在 192.168 段,**单看地址看不出来**,所以判据必须换成
|
|
97
|
+
* 「这个地址是不是挂在一张虚拟网卡上」。
|
|
98
|
+
*/
|
|
99
|
+
return [...replies.values()].sort((left, right) => rankHost(left.host) - rankHost(right.host))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 名字里带这些词的网卡通常是虚拟交换机,其地址真实设备连不上。 */
|
|
103
|
+
const VIRTUAL_INTERFACE = /vethernet|hyper-v|docker|vmware|virtualbox|wsl|loopback|tap|tun|vpn|zerotier|tailscale|clash/i
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 地址的可信度排序,越小越可能真能连上。
|
|
107
|
+
*
|
|
108
|
+
* 先看它是否属于虚拟网卡(决定性),再看网段的常见程度。
|
|
109
|
+
* @param host IPv4 地址
|
|
110
|
+
*/
|
|
111
|
+
function rankHost(host) {
|
|
112
|
+
const base = rankSegment(host)
|
|
113
|
+
if (base >= 9) return base
|
|
114
|
+
return isVirtualInterfaceAddress(host) ? base + 100 : base
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 网段的常见程度。 */
|
|
118
|
+
function rankSegment(host) {
|
|
119
|
+
const parts = String(host).split('.').map(Number)
|
|
120
|
+
if (parts.length !== 4) return 9
|
|
121
|
+
const [a, b] = parts
|
|
122
|
+
if (a === 192 && b === 168) return 0
|
|
123
|
+
if (a === 10) return 1
|
|
124
|
+
if (a === 100 && b >= 64 && b <= 127) return 2
|
|
125
|
+
if (a === 172 && b >= 16 && b <= 31) return 5
|
|
126
|
+
return 9
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 这个地址是不是挂在一张虚拟网卡上。
|
|
131
|
+
*
|
|
132
|
+
* 遍历网卡时**同时**看名字与地址:虚拟交换机往往和真实网卡在不同网段,但
|
|
133
|
+
* Hyper-V 默认交换机恰好也用 192.168.x,所以只能靠网卡名判断。
|
|
134
|
+
*/
|
|
135
|
+
function isVirtualInterfaceAddress(host) {
|
|
136
|
+
let interfaces
|
|
137
|
+
try {
|
|
138
|
+
interfaces = networkInterfaces()
|
|
139
|
+
} catch {
|
|
140
|
+
return false
|
|
141
|
+
}
|
|
142
|
+
for (const [name, entries] of Object.entries(interfaces)) {
|
|
143
|
+
if (!VIRTUAL_INTERFACE.test(name)) continue
|
|
144
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
145
|
+
if (entry?.address === host) return true
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return false
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 开一个发现应答器。
|
|
153
|
+
*
|
|
154
|
+
* 只在**允许局域网访问**时开:没开的话别人不该知道这台机器上有网关。
|
|
155
|
+
*
|
|
156
|
+
* @param options 配置
|
|
157
|
+
* @param options.port 发现端口
|
|
158
|
+
* @param options.announce 返回应答内容的函数 `() => ({ httpPort, name, lan })`
|
|
159
|
+
* @param options.logger 日志
|
|
160
|
+
* @returns `{ state, ready, close }`
|
|
161
|
+
*/
|
|
162
|
+
export function startResponder({ port = DEFAULT_DISCOVERY_PORT, announce, logger }) {
|
|
163
|
+
const state = { port, listening: false, error: undefined }
|
|
164
|
+
const socket = createSocket({ type: 'udp4', reuseAddr: true })
|
|
165
|
+
|
|
166
|
+
socket.on('message', (buffer, remote) => {
|
|
167
|
+
const query = parseQuery(buffer)
|
|
168
|
+
if (query === undefined) return
|
|
169
|
+
const info = announce()
|
|
170
|
+
if (info === undefined) return
|
|
171
|
+
const packet = Buffer.from(JSON.stringify({
|
|
172
|
+
magic: DISCOVERY_MAGIC,
|
|
173
|
+
kind: 'announce',
|
|
174
|
+
nonce: query.nonce,
|
|
175
|
+
httpPort: info.httpPort,
|
|
176
|
+
name: info.name ?? '',
|
|
177
|
+
lan: info.lan === true,
|
|
178
|
+
}), 'utf8')
|
|
179
|
+
try {
|
|
180
|
+
socket.send(packet, 0, packet.length, remote.port, remote.address, () => {})
|
|
181
|
+
} catch {
|
|
182
|
+
/* 回不出去就算了 */
|
|
183
|
+
}
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
const ready = new Promise((resolve) => {
|
|
187
|
+
socket.once('error', (error) => {
|
|
188
|
+
state.listening = false
|
|
189
|
+
state.error = error?.code === 'EADDRINUSE'
|
|
190
|
+
? `发现端口 ${port} 已被占用;局域网发现不可用(不影响网关本身)`
|
|
191
|
+
: `局域网发现启动失败:${error instanceof Error ? error.message : String(error)}`
|
|
192
|
+
logger?.warn?.(`workbuddy-gateway: ${state.error}`)
|
|
193
|
+
resolve(state)
|
|
194
|
+
})
|
|
195
|
+
socket.bind(port, () => {
|
|
196
|
+
state.listening = true
|
|
197
|
+
logger?.info?.(`workbuddy-gateway: LAN discovery listening on udp:${port}`)
|
|
198
|
+
resolve(state)
|
|
199
|
+
})
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
return {
|
|
203
|
+
state,
|
|
204
|
+
ready,
|
|
205
|
+
close: () => new Promise((resolve) => {
|
|
206
|
+
try {
|
|
207
|
+
socket.close(() => resolve())
|
|
208
|
+
} catch {
|
|
209
|
+
resolve()
|
|
210
|
+
}
|
|
211
|
+
}),
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** 解析一条应答。 */
|
|
216
|
+
function parseAnnouncement(buffer) {
|
|
217
|
+
const value = parseJson(buffer)
|
|
218
|
+
if (value === undefined) return undefined
|
|
219
|
+
if (value.magic !== DISCOVERY_MAGIC) return undefined
|
|
220
|
+
if (value.kind === 'announce') return {
|
|
221
|
+
nonce: typeof value.nonce === 'string' ? value.nonce : '',
|
|
222
|
+
httpPort: Number.isInteger(value.httpPort) ? value.httpPort : undefined,
|
|
223
|
+
name: value.name,
|
|
224
|
+
lan: value.lan,
|
|
225
|
+
}
|
|
226
|
+
return undefined
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** 解析一条询问。 */
|
|
230
|
+
function parseQuery(buffer) {
|
|
231
|
+
const value = parseJson(buffer)
|
|
232
|
+
if (value === undefined) return undefined
|
|
233
|
+
if (value.magic !== DISCOVERY_MAGIC) return undefined
|
|
234
|
+
if (value.kind !== 'query') return undefined
|
|
235
|
+
if (typeof value.nonce !== 'string' || value.nonce === '') return undefined
|
|
236
|
+
return { nonce: value.nonce }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function parseJson(buffer) {
|
|
240
|
+
if (!Buffer.isBuffer(buffer) || buffer.length === 0 || buffer.length > MAX_PACKET) return undefined
|
|
241
|
+
try {
|
|
242
|
+
const value = JSON.parse(buffer.toString('utf8'))
|
|
243
|
+
return value !== null && typeof value === 'object' ? value : undefined
|
|
244
|
+
} catch {
|
|
245
|
+
return undefined
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* 各网卡的广播地址。
|
|
251
|
+
*
|
|
252
|
+
* 只发 `255.255.255.255` 在有多张网卡时会漏(系统只从默认路由那张发出去),
|
|
253
|
+
* 而我们要的是「哪些网段上都问一遍」。所以按每个 IPv4 网卡的地址与掩码算定向
|
|
254
|
+
* 广播地址,再补上全局广播。
|
|
255
|
+
*/
|
|
256
|
+
export function broadcastAddresses() {
|
|
257
|
+
const out = new Set(['255.255.255.255'])
|
|
258
|
+
let interfaces
|
|
259
|
+
try {
|
|
260
|
+
interfaces = networkInterfaces()
|
|
261
|
+
} catch {
|
|
262
|
+
return [...out]
|
|
263
|
+
}
|
|
264
|
+
for (const entries of Object.values(interfaces)) {
|
|
265
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
266
|
+
if (entry.internal === true) continue
|
|
267
|
+
const isV4 = entry.family === 'IPv4' || entry.family === 4
|
|
268
|
+
if (!isV4) continue
|
|
269
|
+
const broadcast = directedBroadcast(entry.address, entry.netmask)
|
|
270
|
+
if (broadcast !== undefined) out.add(broadcast)
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return [...out]
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 由地址与掩码算定向广播地址。
|
|
278
|
+
* @param address 例如 `192.168.31.107`
|
|
279
|
+
* @param netmask 例如 `255.255.255.0`
|
|
280
|
+
*/
|
|
281
|
+
export function directedBroadcast(address, netmask) {
|
|
282
|
+
if (typeof address !== 'string' || typeof netmask !== 'string') return undefined
|
|
283
|
+
const ip = address.split('.').map(Number)
|
|
284
|
+
const mask = netmask.split('.').map(Number)
|
|
285
|
+
if (ip.length !== 4 || mask.length !== 4) return undefined
|
|
286
|
+
if (ip.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return undefined
|
|
287
|
+
if (mask.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return undefined
|
|
288
|
+
return ip.map((n, i) => (n | (~mask[i] & 0xff))).join('.')
|
|
289
|
+
}
|
package/src/pairing.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 局域网配对:让另一台设备拿到访问本机网关的凭据。
|
|
3
|
+
*
|
|
4
|
+
* ## 流程(三段,缺一不可)
|
|
5
|
+
*
|
|
6
|
+
* ```
|
|
7
|
+
* ① 接收方 → 发送方 POST /pair/request { deviceName, nonce }
|
|
8
|
+
* ② 发送方(本机) ↑ 用户在设置页看到请求,选一把 key、勾要分享的模型,批准
|
|
9
|
+
* ③ 接收方 → 发送方 GET /pair/claim?nonce=… 取回 url + secret + 模型清单
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* 为什么拆成 request / claim 两段而不是一次来回:
|
|
13
|
+
*
|
|
14
|
+
* **批准必须是人做的。** 收到请求就自动发凭据,等于任何同网段的机器都能自助领取
|
|
15
|
+
* key。拆开之后,中间那段时间由用户在本机界面上决定「批不批、给哪些模型」,接收方
|
|
16
|
+
* 只能反复来问「批了没」。没批的请求过了 TTL 就作废。
|
|
17
|
+
*
|
|
18
|
+
* ## 为什么 claim 用 nonce 而不是让发送方反向推送
|
|
19
|
+
*
|
|
20
|
+
* 推送要求发送方主动连接收方 —— 接收方可能在 NAT 后、可能防火墙只出不进,而且
|
|
21
|
+
* 要让发送方记住对方地址,成为一个可被滥用的出站跳板。轮询不引入任何主动连接。
|
|
22
|
+
*
|
|
23
|
+
* ## nonce 的性质
|
|
24
|
+
*
|
|
25
|
+
* 一次性、短时(默认 5 分钟)、只存在内存里。它**不是**凭据:拿到 nonce 只能
|
|
26
|
+
* 领取一个已经被本机批准过的结果。所以即使同网段有人猜到别人的 nonce,他能做的
|
|
27
|
+
* 只是提前把那份已经批准的结果取走 —— 而那份结果本来就是要发给那个 nonce 的
|
|
28
|
+
* 主人的。为把这一点做实,同一 nonce 只允许成功领取一次。
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
32
|
+
|
|
33
|
+
/** 配对请求的存活时间。够用户在设置页点几下,又不会让旧请求堆着。 */
|
|
34
|
+
export const PAIR_TTL_MS = 5 * 60 * 1000
|
|
35
|
+
/** 同时挂起的请求上限,防止有人拿随机 nonce 把内存灌满。 */
|
|
36
|
+
export const MAX_PENDING = 32
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 内存里的配对登记簿。
|
|
40
|
+
*
|
|
41
|
+
* 全部在内存:重启即失效,不落盘。配对是一次性的短暂状态,写进配置文件只会在
|
|
42
|
+
* 磁盘上留下「谁曾经想连我」这种既没用又敏感的历史。
|
|
43
|
+
*/
|
|
44
|
+
export function createPairingRegistry({ logger, now = () => Date.now() } = {}) {
|
|
45
|
+
/** @type {Map<string, PendingRequest>} */
|
|
46
|
+
const pending = new Map()
|
|
47
|
+
|
|
48
|
+
/** 丢掉过期的,并返回当前挂起的列表。 */
|
|
49
|
+
function sweep() {
|
|
50
|
+
const at = now()
|
|
51
|
+
for (const [nonce, entry] of pending) {
|
|
52
|
+
if (entry.expiresAt <= at) pending.delete(nonce)
|
|
53
|
+
}
|
|
54
|
+
return [...pending.values()]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 接收方发起配对请求。
|
|
59
|
+
*
|
|
60
|
+
* @param input `{ deviceName, nonce? }`
|
|
61
|
+
* @returns `{ nonce, expiresAt }` 或 `{ error }`
|
|
62
|
+
*/
|
|
63
|
+
function request(input) {
|
|
64
|
+
sweep()
|
|
65
|
+
const deviceName = typeof input?.deviceName === 'string' ? input.deviceName.trim().slice(0, 64) : ''
|
|
66
|
+
if (deviceName === '') return { error: 'deviceName is required' }
|
|
67
|
+
|
|
68
|
+
if (pending.size >= MAX_PENDING) {
|
|
69
|
+
/* 满了就不收新的:拒绝比静默丢更诚实,接收方知道要等人处理。 */
|
|
70
|
+
return { error: 'too many pending pairing requests; approve or ignore the existing ones first' }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/*
|
|
74
|
+
* nonce 由**发送方**生成,不采信接收方给的值 —— 对方给的东西不能成为
|
|
75
|
+
* 之后领取凭据的凭据。接收方只拿到它,用来轮询。
|
|
76
|
+
*/
|
|
77
|
+
const nonce = randomBytes(16).toString('base64url')
|
|
78
|
+
const entry = {
|
|
79
|
+
nonce,
|
|
80
|
+
deviceName,
|
|
81
|
+
createdAt: now(),
|
|
82
|
+
expiresAt: now() + PAIR_TTL_MS,
|
|
83
|
+
/* 'pending' → 用户批准 → 'approved';批准后带一份要交出去的东西。 */
|
|
84
|
+
status: 'pending',
|
|
85
|
+
grant: undefined,
|
|
86
|
+
}
|
|
87
|
+
pending.set(nonce, entry)
|
|
88
|
+
logger?.info?.(`workbuddy-gateway: pairing request from "${deviceName}"`)
|
|
89
|
+
return { nonce, expiresAt: entry.expiresAt }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 本机批准一个请求,把「要交给对方的东西」挂上去。
|
|
94
|
+
*
|
|
95
|
+
* @param nonce 请求 id
|
|
96
|
+
* @param grant `{ baseUrl, secret, keyLabel, models }`
|
|
97
|
+
*/
|
|
98
|
+
function approve(nonce, grant) {
|
|
99
|
+
const entry = pending.get(nonce)
|
|
100
|
+
if (entry === undefined) return { error: 'no such pairing request' }
|
|
101
|
+
if (entry.expiresAt <= now()) {
|
|
102
|
+
pending.delete(nonce)
|
|
103
|
+
return { error: 'this pairing request has expired' }
|
|
104
|
+
}
|
|
105
|
+
if (entry.status === 'approved') return { error: 'this pairing request was already approved' }
|
|
106
|
+
entry.status = 'approved'
|
|
107
|
+
entry.grant = grant
|
|
108
|
+
entry.approvedAt = now()
|
|
109
|
+
return { ok: true }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 接收方领取被批准的结果。
|
|
114
|
+
*
|
|
115
|
+
* 成功后立刻销毁这条记录 —— 同一 nonce 只能领一次。
|
|
116
|
+
*
|
|
117
|
+
* @param nonce 请求 id
|
|
118
|
+
* @returns `{ status: 'pending' }` / `{ status: 'approved', grant }` / `{ error }`
|
|
119
|
+
*/
|
|
120
|
+
function claim(nonce) {
|
|
121
|
+
sweep()
|
|
122
|
+
if (typeof nonce !== 'string' || nonce === '') return { error: 'nonce is required' }
|
|
123
|
+
const entry = pending.get(nonce)
|
|
124
|
+
if (entry === undefined) return { error: 'unknown or expired pairing request' }
|
|
125
|
+
if (entry.status !== 'approved') return { status: 'pending' }
|
|
126
|
+
/* 先删再返回:即使后面出错,这个 nonce 也不会被第二次领走。 */
|
|
127
|
+
pending.delete(nonce)
|
|
128
|
+
return { status: 'approved', grant: entry.grant }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 用户拒绝(或忽略)。 */
|
|
132
|
+
function deny(nonce) {
|
|
133
|
+
return pending.delete(nonce) ? { ok: true } : { error: 'no such pairing request' }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 设置页要看的列表。 */
|
|
137
|
+
function list() {
|
|
138
|
+
return sweep().map((entry) => ({
|
|
139
|
+
nonce: entry.nonce,
|
|
140
|
+
deviceName: entry.deviceName,
|
|
141
|
+
createdAt: entry.createdAt,
|
|
142
|
+
expiresAt: entry.expiresAt,
|
|
143
|
+
status: entry.status,
|
|
144
|
+
}))
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return { request, approve, claim, deny, list }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 常量时间比较两个字符串,避免按字节泄露时序。
|
|
152
|
+
*
|
|
153
|
+
* 用在比较 nonce 这类「知道就能取东西」的值上。长度不同直接返回 false —— 长度
|
|
154
|
+
* 本身不是秘密。
|
|
155
|
+
*
|
|
156
|
+
* @param left 来自请求
|
|
157
|
+
* @param right 服务端保存的值
|
|
158
|
+
*/
|
|
159
|
+
export function safeEqual(left, right) {
|
|
160
|
+
if (typeof left !== 'string' || typeof right !== 'string') return false
|
|
161
|
+
const a = Buffer.from(left, 'utf8')
|
|
162
|
+
const b = Buffer.from(right, 'utf8')
|
|
163
|
+
if (a.length !== b.length) return false
|
|
164
|
+
return timingSafeEqual(a, b)
|
|
165
|
+
}
|