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/src/peers.js ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * 接收方(client 模式):接入另一台设备分享出来的网关。
3
+ *
4
+ * ## 与发送方的区别
5
+ *
6
+ * `upstream` 模式下本插件是**生产者**:读本机 WorkBuddy,按 key 对外发 API。
7
+ * `client` 模式下它是**消费者**:找到局域网里的网关,配对拿到 base URL + key,
8
+ * 把那边的模型当成自己的模型来源。
9
+ *
10
+ * 两套配置项**完全不重叠**,所以界面按模式整块切换(见 client.js)。
11
+ *
12
+ * ## 为什么接收方不再对外分享
13
+ *
14
+ * 一个接收方把自己的「接入」再分享出去,等于把上游那台机器的额度二次转手,而且
15
+ * 转手链条上没人能撤销中间那一跳。所以 client 模式下**不注册监听、不开发现
16
+ * 应答器、不提供配对批准** —— 这些功能连同它们的配置项一起消失。
17
+ *
18
+ * ## 凭据存在哪
19
+ *
20
+ * 与发送方同一份 keys.json,但放在 `peers` 数组里,与 `keys` 并列。两者语义不同:
21
+ *
22
+ * - `keys` 我对**别人**发出去的凭据(发送方用)
23
+ * - `peers` **别人**发给我的凭据(接收方用)
24
+ *
25
+ * 混在一起会让「撤销」变得含糊:撤销一把 key 是断掉别人的访问,删一条 peer 是
26
+ * 断掉自己的访问。
27
+ */
28
+
29
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'
30
+ import { dirname } from 'node:path'
31
+ import { configPath } from './config.js'
32
+
33
+ /**
34
+ * 读 peers 列表。
35
+ *
36
+ * 与 keys.json 同一个文件,但只取 `peers` 字段。读失败时返回空数组 —— 一条
37
+ * 坏记录不该让整个设置页打不开。
38
+ *
39
+ * @returns `Array<PeerEntry>`
40
+ */
41
+ export function readPeers() {
42
+ const path = configPath()
43
+ if (!existsSync(path)) return []
44
+ try {
45
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
46
+ return normalizePeers(parsed?.peers)
47
+ } catch {
48
+ return []
49
+ }
50
+ }
51
+
52
+ /**
53
+ * 写回 peers,**保留同一个文件里的其它字段**(keys 等)。
54
+ *
55
+ * @param peers 新的 peers 列表
56
+ */
57
+ export function writePeers(peers) {
58
+ const path = configPath()
59
+ let current = {}
60
+ if (existsSync(path)) {
61
+ try {
62
+ current = JSON.parse(readFileSync(path, 'utf8')) ?? {}
63
+ } catch {
64
+ /* 文件坏了:只覆盖 peers,别把它整个清掉之外还丢别的字段。 */
65
+ current = {}
66
+ }
67
+ }
68
+ const next = { ...current, peers: normalizePeers(peers) }
69
+ mkdirSync(dirname(path), { recursive: true })
70
+ writeFileSync(path, JSON.stringify(next, null, 2), 'utf8')
71
+ }
72
+
73
+ /**
74
+ * 规整一条 peer 记录。
75
+ *
76
+ * 只保留真正需要的字段:地址、凭据、以及一个缓存下来的模型清单。缓存是为了让
77
+ * 设置页在没有网络时也能显示「我接入过什么」,而不是一片空白。
78
+ */
79
+ function normalizePeer(value) {
80
+ if (value === null || typeof value !== 'object') return undefined
81
+ const baseUrl = typeof value.baseUrl === 'string' ? value.baseUrl.trim().replace(/\/+$/u, '') : ''
82
+ const secret = typeof value.secret === 'string' ? value.secret.trim() : ''
83
+ if (baseUrl === '' || secret === '') return undefined
84
+
85
+ const models = Array.isArray(value.models)
86
+ ? value.models
87
+ .filter((model) => model !== null && typeof model === 'object' && typeof model.id === 'string')
88
+ .map((model) => ({
89
+ id: model.id,
90
+ ...(typeof model.displayName === 'string' ? { displayName: model.displayName } : {}),
91
+ ...(typeof model.contextWindow === 'number' ? { contextWindow: model.contextWindow } : {}),
92
+ ...(typeof model.maxTokens === 'number' ? { maxTokens: model.maxTokens } : {}),
93
+ ...(Array.isArray(model.reasoningEfforts) ? { reasoningEfforts: model.reasoningEfforts.filter((e) => typeof e === 'string') } : {}),
94
+ }))
95
+ : []
96
+
97
+ return {
98
+ id: typeof value.id === 'string' && value.id !== '' ? value.id : `peer_${Math.random().toString(36).slice(2, 10)}`,
99
+ label: typeof value.label === 'string' ? value.label.slice(0, 64) : '',
100
+ baseUrl,
101
+ secret,
102
+ ...(typeof value.addedAt === 'number' ? { addedAt: value.addedAt } : {}),
103
+ models,
104
+ }
105
+ }
106
+
107
+ /** 规整整张表:丢坏条目、去重(同一个 baseUrl + secret 只留一条)。 */
108
+ export function normalizePeers(value) {
109
+ const out = []
110
+ const seen = new Set()
111
+ for (const entry of Array.isArray(value) ? value : []) {
112
+ const peer = normalizePeer(entry)
113
+ if (peer === undefined) continue
114
+ const key = `${peer.baseUrl}\u0000${peer.secret}`
115
+ if (seen.has(key)) continue
116
+ seen.add(key)
117
+ out.push(peer)
118
+ }
119
+ return out
120
+ }
121
+
122
+ /**
123
+ * 查一台已接入网关的模型清单(在线刷新)。
124
+ *
125
+ * 失败时**不抛**:把错误作为结果返回,让界面显示「这台现在连不上」,而不是让
126
+ * 整个设置页崩掉。这也是为什么要把 model 清单缓存在 peers 里。
127
+ *
128
+ * @param peer 一条 peer 记录
129
+ * @param fetchImpl 注入的 fetch(测试用)
130
+ */
131
+ export async function fetchPeerModels(peer, fetchImpl = fetch) {
132
+ try {
133
+ const response = await fetchImpl(`${peer.baseUrl}/v1/models`, {
134
+ headers: { Authorization: `Bearer ${peer.secret}` },
135
+ signal: AbortSignal.timeout(5000),
136
+ })
137
+ if (response.status === 401) return { error: 'the key this device was given is no longer valid' }
138
+ if (response.status === 403) return { error: 'the gateway refused this device (origin check)' }
139
+ if (!response.ok) return { error: `the gateway answered ${response.status}` }
140
+ const body = await response.json()
141
+ const data = Array.isArray(body?.data) ? body.data : []
142
+ return {
143
+ models: data.map((row) => ({
144
+ id: row.id,
145
+ ...(typeof row.display_name === 'string' ? { displayName: row.display_name } : {}),
146
+ ...(typeof row.context_window === 'number' ? { contextWindow: row.context_window } : {}),
147
+ ...(typeof row.max_output_tokens === 'number' ? { maxTokens: row.max_output_tokens } : {}),
148
+ ...(Array.isArray(row.reasoning_efforts) ? { reasoningEfforts: row.reasoning_efforts.filter((e) => typeof e === 'string') } : {}),
149
+ })),
150
+ }
151
+ } catch (error) {
152
+ if (error?.name === 'TimeoutError') return { error: 'the gateway did not answer within 5 seconds' }
153
+ return { error: `cannot reach the gateway: ${error instanceof Error ? error.message : String(error)}` }
154
+ }
155
+ }
156
+
157
+ /**
158
+ * 向一台网关申请配对。
159
+ *
160
+ * 只发申请、拿 nonce,**不拿凭据** —— 凭据要等那台机器的用户在设置页批准。
161
+ *
162
+ * @param baseUrl 网关地址
163
+ * @param deviceName 本机名称(对方在批准界面看到的就是它)
164
+ * @param fetchImpl 注入的 fetch(测试用)
165
+ */
166
+ export async function requestPairing(baseUrl, deviceName, fetchImpl = fetch) {
167
+ const root = String(baseUrl ?? '').trim().replace(/\/+$/u, '')
168
+ if (root === '') return { error: 'baseUrl is required' }
169
+ try {
170
+ const response = await fetchImpl(`${root}/pair/request`, {
171
+ method: 'POST',
172
+ headers: { 'Content-Type': 'application/json' },
173
+ body: JSON.stringify({ deviceName }),
174
+ signal: AbortSignal.timeout(8000),
175
+ })
176
+ if (response.status === 404) {
177
+ /* 那台机器没开局域网访问,或者根本没装这个插件。 */
178
+ return { error: 'that machine is not accepting pairings; make sure LAN access is on there' }
179
+ }
180
+ const body = await response.json().catch(() => ({}))
181
+ if (!response.ok) return { error: body?.error?.message ?? `the gateway answered ${response.status}` }
182
+ if (typeof body?.nonce !== 'string') return { error: 'the gateway did not return a pairing nonce' }
183
+ return { nonce: body.nonce, expiresAt: body.expiresAt }
184
+ } catch (error) {
185
+ if (error?.name === 'TimeoutError') return { error: 'the gateway did not answer within 8 seconds' }
186
+ return { error: `cannot reach the gateway: ${error instanceof Error ? error.message : String(error)}` }
187
+ }
188
+ }
189
+
190
+ /**
191
+ * 领取被批准的结果。
192
+ *
193
+ * @param baseUrl 网关地址
194
+ * @param nonce 申请的 nonce
195
+ * @param fetchImpl 注入的 fetch
196
+ */
197
+ export async function claimPairing(baseUrl, nonce, fetchImpl = fetch) {
198
+ const root = String(baseUrl ?? '').trim().replace(/\/+$/u, '')
199
+ if (root === '' || typeof nonce !== 'string' || nonce === '') return { error: 'baseUrl and nonce are required' }
200
+ try {
201
+ const response = await fetchImpl(`${root}/pair/claim?nonce=${encodeURIComponent(nonce)}`, {
202
+ signal: AbortSignal.timeout(8000),
203
+ })
204
+ /* 202 = 还没批,这是正常中间态,不是错误。 */
205
+ if (response.status === 202) {
206
+ const body = await response.json().catch(() => ({}))
207
+ return { pending: true, note: body?.note }
208
+ }
209
+ const body = await response.json().catch(() => ({}))
210
+ if (!response.ok) {
211
+ if (response.status === 404) return { error: 'this pairing request expired or was already claimed' }
212
+ return { error: body?.error?.message ?? `the gateway answered ${response.status}` }
213
+ }
214
+ if (typeof body?.secret !== 'string' || typeof body?.baseUrl !== 'string') {
215
+ return { error: 'the gateway returned an incomplete grant' }
216
+ }
217
+ return {
218
+ grant: {
219
+ baseUrl: String(body.baseUrl).replace(/\/+$/u, ''),
220
+ secret: body.secret,
221
+ label: typeof body.keyLabel === 'string' ? body.keyLabel : '',
222
+ models: Array.isArray(body.models) ? body.models : [],
223
+ },
224
+ }
225
+ } catch (error) {
226
+ if (error?.name === 'TimeoutError') return { error: 'the gateway did not answer within 8 seconds' }
227
+ return { error: `cannot reach the gateway: ${error instanceof Error ? error.message : String(error)}` }
228
+ }
229
+ }