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/client.js CHANGED
@@ -96,6 +96,69 @@ window.__ModuleLoader__.load({
96
96
  lanChanged: '已保存,插件会重新加载',
97
97
  lanChoose: '有多个地址时选「其他设备能 ping 通本机」的那个。',
98
98
  lanKeyHint: '把 key 发给别人等于把额度分给他用 —— 按需新建一把只勾必要模型的 key。',
99
+ /* 浏览器来源校验 */
100
+ origin: '网页来源校验',
101
+ originHint: '网关只认 API key,没有 DSH 的同源检查。这里决定「哪些网页可以调用它」——命令行客户端不发 Origin 头,不受影响。',
102
+ originCurrent: '当前策略',
103
+ originUnsafe: '宽松',
104
+ originSave: '保存策略',
105
+ originSaved: '已保存,插件会重新加载',
106
+ originNoOrigin: 'curl、SDK、Codex、Claude Code 这类客户端不发 Origin 头,任何策略下都能正常用。',
107
+ /* 局域网配对 */
108
+ pairing: '共享给其他设备',
109
+ pairingHint: '另一台设备装上本插件后会自动发现这台机器,在这里批准一次即可。',
110
+ pairingOff: '需要先打开「局域网访问」',
111
+ pairingNone: '暂无待批准的请求',
112
+ pairingNoneHint: '让对方在那台设备上点「查找本机的网关」。',
113
+ pairingFrom: '来自',
114
+ pairingExpires: '过期于',
115
+ pairingApprove: '批准并分享',
116
+ pairingDeny: '拒绝',
117
+ pairingPickKey: '用哪把 key 的模型分享',
118
+ pairingPickModels: '勾选要分享的模型',
119
+ pairingShare: '确认分享',
120
+ pairingCancel: '取消',
121
+ pairingDone: '已批准,对方的设备会自动收到',
122
+ pairingNewKeyNote: '会为这次分享新建一把专用 key,撤销它不影响你自己的 key。',
123
+ pairingDiscovery: '发现端口',
124
+ pairingShareName: '本机名称',
125
+ pairingShareNameHint: '对方在列表里会看到这个名字,留空则只显示 IP。',
126
+ pairingSaveName: '保存名称',
127
+ /* 运行模式 */
128
+ mode: '运行模式',
129
+ modeHint: '两种角色做的事完全不同,配置项也不重叠。切换后插件会重启。',
130
+ modeUpstream: '从上游插件获取',
131
+ modeClient: '接入其他设备',
132
+ modeUpstreamDetail: '读本机的 dsh-connect-workbuddy,按 API key 对外提供 HTTP API。',
133
+ modeClientDetail: '连另一台电脑上本插件的网关,用它的模型;本机不对外分享任何东西。',
134
+ modeSwitch: '切换',
135
+ modeSwitching: '切换中…',
136
+ /* 接收方:接入其他设备 */
137
+ peers: '接入其他设备的网关',
138
+ peersHint: '在局域网里找到运行本插件、并已开启分享的电脑,申请一次即可接入它的模型。',
139
+ peersScan: '查找网关',
140
+ peersScanning: '查找中…',
141
+ peersFound: '找到的网关',
142
+ peersNone: '没找到。确认那台电脑开了「局域网访问」,且和本机在同一个网络。',
143
+ peersRequest: '申请接入',
144
+ peersWaiting: '已申请,等待那台电脑上的人批准',
145
+ peersWaitingHint: '让 ta 打开设置页,在「共享给其他设备」里点批准。批准后点下面的按钮。',
146
+ peersClaim: '我已获得批准',
147
+ peersClaiming: '领取中…',
148
+ peersConnected: '已接入',
149
+ peersRemove: '断开',
150
+ peersRefresh: '刷新模型',
151
+ peersEmpty: '还没有接入任何网关',
152
+ peersEmptyHint: '点「查找网关」开始。',
153
+ peersModels: '个模型',
154
+ peersLocalOnly: '接入后,这些模型会出现在本插件的模型来源里。',
155
+ peersManual: '手动输入地址',
156
+ peersManualHint: '广播被路由器拦住时(AP 隔离、跨网段),直接填对方的地址。',
157
+ peersManualPlaceholder: '192.168.31.107:8790',
158
+ peersDiagnose: '为什么找不到',
159
+ peersDiagnosing: '检查中…',
160
+ peersChecks: '检查结果',
161
+ localAddresses: '本机地址',
99
162
  selected: '已选',
100
163
  noneSelected: '还没有勾选任何模型,这把 key 暂时不能用。',
101
164
  willExpose: '客户端会看到',
@@ -191,6 +254,69 @@ window.__ModuleLoader__.load({
191
254
  lanChanged: 'Saved; the plugin reloads to apply it',
192
255
  lanChoose: 'With several addresses, pick the one other devices can ping.',
193
256
  lanKeyHint: 'Handing over a key means handing over your quota - create a key that only ticks the models that person needs.',
257
+ /* Origin policy */
258
+ origin: 'Browser origin check',
259
+ originHint: 'The gateway checks only the API key, with no DSH same-origin gate. This decides which web pages may call it; command-line clients send no Origin header and are unaffected.',
260
+ originCurrent: 'Current policy',
261
+ originUnsafe: 'permissive',
262
+ originSave: 'Save policy',
263
+ originSaved: 'Saved; the plugin reloads to apply it',
264
+ originNoOrigin: 'curl, SDKs, Codex and Claude Code send no Origin header, so they work under any policy.',
265
+ /* LAN pairing */
266
+ pairing: 'Share with other devices',
267
+ pairingHint: 'Another device with this plugin installed discovers this machine automatically; approve once here.',
268
+ pairingOff: 'Turn on LAN access first',
269
+ pairingNone: 'No pending requests',
270
+ pairingNoneHint: 'Have that device press "Find gateways on this network".',
271
+ pairingFrom: 'from',
272
+ pairingExpires: 'expires',
273
+ pairingApprove: 'Approve and share',
274
+ pairingDeny: 'Deny',
275
+ pairingPickKey: 'Share models from which key',
276
+ pairingPickModels: 'Tick the models to share',
277
+ pairingShare: 'Confirm share',
278
+ pairingCancel: 'Cancel',
279
+ pairingDone: 'Approved; the other device receives it automatically',
280
+ pairingNewKeyNote: 'A dedicated key is created for this share; revoking it leaves your own key alone.',
281
+ pairingDiscovery: 'Discovery port',
282
+ pairingShareName: 'Machine name',
283
+ pairingShareNameHint: 'Other devices see this in their list; leave empty to show only the IP.',
284
+ pairingSaveName: 'Save name',
285
+ /* Run mode */
286
+ mode: 'Run mode',
287
+ modeHint: 'The two roles do different things, and their settings do not overlap. Switching reloads the plugin.',
288
+ modeUpstream: 'Serve from the upstream plugin',
289
+ modeClient: 'Connect to another device',
290
+ modeUpstreamDetail: 'Reads this machine\'s dsh-connect-workbuddy and serves an HTTP API per API key.',
291
+ modeClientDetail: 'Connects to another computer running this plugin; shares nothing from this machine.',
292
+ modeSwitch: 'Switch',
293
+ modeSwitching: 'Switching...',
294
+ /* Client side */
295
+ peers: 'Gateways to connect to',
296
+ peersHint: 'Find a computer on the LAN that runs this plugin with sharing on, then request access once.',
297
+ peersScan: 'Find gateways',
298
+ peersScanning: 'Searching...',
299
+ peersFound: 'Gateways found',
300
+ peersNone: 'Nothing found. Check that machine has LAN access on and is on the same network.',
301
+ peersRequest: 'Request access',
302
+ peersWaiting: 'Requested; waiting for approval on that machine',
303
+ peersWaitingHint: 'Ask them to open settings and approve under "Share with other devices", then press the button below.',
304
+ peersClaim: 'I have been approved',
305
+ peersClaiming: 'Claiming...',
306
+ peersConnected: 'Connected',
307
+ peersRemove: 'Disconnect',
308
+ peersRefresh: 'Refresh models',
309
+ peersEmpty: 'No gateways connected yet',
310
+ peersEmptyHint: 'Press "Find gateways" to start.',
311
+ peersModels: 'models',
312
+ peersLocalOnly: 'Once connected, those models become a model source for this plugin.',
313
+ peersManual: 'Enter an address',
314
+ peersManualHint: 'When a router blocks broadcast (AP isolation, different subnet), type the other machine\'s address.',
315
+ peersManualPlaceholder: '192.168.31.107:8790',
316
+ peersDiagnose: 'Why was nothing found',
317
+ peersDiagnosing: 'Checking...',
318
+ peersChecks: 'Checks',
319
+ localAddresses: 'This machine',
194
320
  selected: 'selected',
195
321
  noneSelected: 'No models ticked yet, so this key cannot be used.',
196
322
  willExpose: 'The client will see',
@@ -322,6 +448,12 @@ window.__ModuleLoader__.load({
322
448
  body: JSON.stringify(payload ?? {}),
323
449
  })
324
450
  const body = await response.json().catch(() => ({}))
451
+ /*
452
+ * 202 不是失败:配对领取用它表示「那台机器上还没人批准」,是正常中间态。
453
+ * 当成错误抛出去,界面会显示一条红色报错 —— 而用户其实什么都没做错,
454
+ * 只需要等对方点一下。
455
+ */
456
+ if (response.status === 202) return body
325
457
  if (!response.ok) throw new Error(body.error ?? `HTTP ${response.status}`)
326
458
  return body
327
459
  }
@@ -1000,6 +1132,550 @@ window.__ModuleLoader__.load({
1000
1132
  )
1001
1133
  }
1002
1134
 
1135
+ /* ── 网页来源校验 ───────────────────────────────────────────────── */
1136
+
1137
+ /**
1138
+ * Origin 策略卡片。
1139
+ *
1140
+ * 为什么给三档而不是一个开关:「另一台设备上的网页算不算自己人」没有唯一答案。
1141
+ * 只放行本机最安全但局域网网页用不了;全放行最方便但公共 WiFi 里别人的机器
1142
+ * 也能调。让用户按自己的网络环境选,比替他决定更好。
1143
+ */
1144
+ function OriginCard({ state, t, onSave }) {
1145
+ const origin = state?.origin ?? {}
1146
+ const choices = Array.isArray(origin.choices) ? origin.choices : []
1147
+ const [pick, setPick] = useState(origin.policy ?? 'loopback')
1148
+ const [busy, setBusy] = useState(false)
1149
+ const [error, setError] = useState(undefined)
1150
+ const [saved, setSaved] = useState(false)
1151
+
1152
+ useEffect(() => {
1153
+ if (busy || saved) return
1154
+ setPick(origin.policy ?? 'loopback')
1155
+ }, [origin.policy])
1156
+
1157
+ const commit = async () => {
1158
+ setBusy(true)
1159
+ setError(undefined)
1160
+ try {
1161
+ await onSave(pick)
1162
+ setSaved(true)
1163
+ setTimeout(() => setSaved(false), 4000)
1164
+ } catch (caught) {
1165
+ setError(String(caught.message ?? caught))
1166
+ } finally {
1167
+ setBusy(false)
1168
+ }
1169
+ }
1170
+
1171
+ return h('div', { className: 'wbg-card wbg-card-soft' },
1172
+ h('div', { className: 'wbg-row' },
1173
+ h('strong', { className: 'wbg-sec-title' }, t.origin),
1174
+ pick === 'lan' ? h('span', { className: 'wbg-badge wbg-badge-warn' }, t.originUnsafe) : null,
1175
+ h('span', { className: 'wbg-spacer' }),
1176
+ ),
1177
+ h('p', { className: 'wbg-hint' }, t.originHint),
1178
+
1179
+ h('div', { className: 'wbg-picker', style: { marginTop: 8 } },
1180
+ choices.map((choice) => h('label', {
1181
+ key: choice.id,
1182
+ className: 'wbg-opt',
1183
+ style: { cursor: 'pointer' },
1184
+ },
1185
+ h('input', {
1186
+ type: 'radio',
1187
+ name: 'wbg-origin-policy',
1188
+ checked: pick === choice.id,
1189
+ onChange: () => setPick(choice.id),
1190
+ }),
1191
+ h('span', { className: 'wbg-opt-label' }, choice.label),
1192
+ h('span', { className: 'wbg-opt-meta' }, choice.detail),
1193
+ )),
1194
+ ),
1195
+
1196
+ h('p', { className: 'wbg-caption' }, t.originNoOrigin),
1197
+
1198
+ error === undefined ? null : h('div', { className: 'wbg-alert wbg-alert-error' },
1199
+ h('span', { className: 'wbg-alert-icon', 'aria-hidden': true }, '!'),
1200
+ h('span', { className: 'wbg-alert-body' }, error)),
1201
+
1202
+ h('div', { className: 'wbg-row' },
1203
+ saved ? h('span', { className: 'wbg-caption' }, t.originSaved) : null,
1204
+ h('span', { className: 'wbg-spacer' }),
1205
+ h('button', {
1206
+ type: 'button',
1207
+ className: 'wbg-btn wbg-btn-primary',
1208
+ onClick: commit,
1209
+ disabled: busy,
1210
+ }, t.originSave),
1211
+ ),
1212
+ )
1213
+ }
1214
+
1215
+ /* ── 共享给其他设备 ─────────────────────────────────────────────── */
1216
+
1217
+ /**
1218
+ * 配对批准卡片。
1219
+ *
1220
+ * 这一屏是「谁可以拿走我的模型额度」的唯一决策点,所以它把三件事摆明:
1221
+ * 谁在申请、要分享哪些模型、会新建一把专用 key。
1222
+ */
1223
+ function PairingCard({ state, t, onApprove, onDeny, onSaveShareName }) {
1224
+ const pairing = state?.pairing ?? {}
1225
+ const pending = Array.isArray(pairing.pending) ? pairing.pending : []
1226
+ const keys = Array.isArray(state?.keys) ? state.keys : []
1227
+
1228
+ /* 正在批准哪一个(展开模型勾选)。 */
1229
+ const [openNonce, setOpenNonce] = useState(undefined)
1230
+ const [keyId, setKeyId] = useState('')
1231
+ const [picked, setPicked] = useState([])
1232
+ const [busy, setBusy] = useState(false)
1233
+ const [error, setError] = useState(undefined)
1234
+ const [done, setDone] = useState(undefined)
1235
+ const [shareName, setShareName] = useState(pairing.shareName ?? '')
1236
+
1237
+ useEffect(() => {
1238
+ if (busy) return
1239
+ setShareName(pairing.shareName ?? '')
1240
+ }, [pairing.shareName])
1241
+
1242
+ /* 打开批准面板时,默认选第一把有模型的 key。 */
1243
+ const open = (nonce) => {
1244
+ setOpenNonce(nonce)
1245
+ setError(undefined)
1246
+ setDone(undefined)
1247
+ const first = keys.find((entry) => (entry.catalog ?? []).length > 0) ?? keys[0]
1248
+ setKeyId(first?.id ?? '')
1249
+ setPicked([])
1250
+ }
1251
+
1252
+ const currentKey = keys.find((entry) => entry.id === keyId)
1253
+ const available = Array.isArray(currentKey?.catalog) ? currentKey.catalog : []
1254
+
1255
+ const toggle = (name) => {
1256
+ setPicked((prev) => prev.includes(name) ? prev.filter((item) => item !== name) : [...prev, name])
1257
+ }
1258
+
1259
+ const approve = async () => {
1260
+ setBusy(true)
1261
+ setError(undefined)
1262
+ try {
1263
+ await onApprove(openNonce, keyId, picked)
1264
+ setDone(openNonce)
1265
+ setOpenNonce(undefined)
1266
+ setPicked([])
1267
+ } catch (caught) {
1268
+ setError(String(caught.message ?? caught))
1269
+ } finally {
1270
+ setBusy(false)
1271
+ }
1272
+ }
1273
+
1274
+ return h('div', { className: 'wbg-card wbg-card-soft' },
1275
+ h('div', { className: 'wbg-row' },
1276
+ h('strong', { className: 'wbg-sec-title' }, t.pairing),
1277
+ pairing.available === true
1278
+ ? h('span', { className: 'wbg-badge wbg-badge-ok' }, t.lanOn)
1279
+ : h('span', { className: 'wbg-badge' }, t.pairingOff),
1280
+ h('span', { className: 'wbg-spacer' }),
1281
+ h('span', { className: 'wbg-caption' }, `${t.pairingDiscovery} udp:${pairing.discoveryPort ?? 8791}`),
1282
+ ),
1283
+ h('p', { className: 'wbg-hint' }, t.pairingHint),
1284
+
1285
+ /* 没开局域网:这个功能整体不可用,说明原因而不是让人干等。 */
1286
+ pairing.available !== true
1287
+ ? h('p', { className: 'wbg-warn' }, t.pairingOff)
1288
+ : null,
1289
+
1290
+ pairing.available === true && pending.length === 0
1291
+ ? h('p', { className: 'wbg-caption' }, `${t.pairingNone} —— ${t.pairingNoneHint}`)
1292
+ : null,
1293
+
1294
+ /* 待批准列表。 */
1295
+ pairing.available === true
1296
+ ? pending.map((entry) => h('div', {
1297
+ key: entry.nonce,
1298
+ className: 'wbg-field',
1299
+ style: { borderTop: '1px solid var(--dsw-alias-border-l1, #eee)', paddingTop: 10 },
1300
+ },
1301
+ h('div', { className: 'wbg-row' },
1302
+ h('span', null, `${t.pairingFrom}「${entry.deviceName}」`),
1303
+ h('span', { className: 'wbg-spacer' }),
1304
+ h('span', { className: 'wbg-caption' },
1305
+ `${t.pairingExpires} ${new Date(entry.expiresAt).toLocaleTimeString()}`),
1306
+ ),
1307
+
1308
+ /* 已批准过的只显示状态。 */
1309
+ entry.status === 'approved' || done === entry.nonce
1310
+ ? h('p', { className: 'wbg-caption' }, t.pairingDone)
1311
+ : openNonce === entry.nonce
1312
+ ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8 } },
1313
+ h('label', { className: 'wbg-caption' }, t.pairingPickKey),
1314
+ h('select', {
1315
+ className: 'wbg-input',
1316
+ value: keyId,
1317
+ onChange: (event) => { setKeyId(event.target.value); setPicked([]) },
1318
+ }, keys.map((entry2) => h('option', { key: entry2.id, value: entry2.id },
1319
+ `${entry2.label || entry2.id} (${(entry2.catalog ?? []).length})`))),
1320
+
1321
+ available.length === 0
1322
+ ? h('p', { className: 'wbg-warn' }, t.noneSelected)
1323
+ : h('div', { className: 'wbg-picker', style: { maxHeight: 200 } },
1324
+ available.map((model) => h('label', { key: model.name, className: 'wbg-opt' },
1325
+ h('input', {
1326
+ type: 'checkbox',
1327
+ checked: picked.includes(model.name),
1328
+ onChange: () => toggle(model.name),
1329
+ }),
1330
+ h('span', { className: 'wbg-opt-label' }, model.name),
1331
+ ))),
1332
+
1333
+ h('p', { className: 'wbg-caption' }, t.pairingNewKeyNote),
1334
+ h('p', { className: 'wbg-caption' }, picked.length === 0 ? t.clearAll : `${picked.length}`),
1335
+
1336
+ h('div', { className: 'wbg-row' },
1337
+ h('button', {
1338
+ type: 'button',
1339
+ className: 'wbg-btn',
1340
+ onClick: () => { setOpenNonce(undefined); setPicked([]) },
1341
+ disabled: busy,
1342
+ }, t.pairingCancel),
1343
+ h('span', { className: 'wbg-spacer' }),
1344
+ h('button', {
1345
+ type: 'button',
1346
+ className: 'wbg-btn wbg-btn-primary',
1347
+ onClick: approve,
1348
+ /* 一个都不勾 = 分享这把 key 的全部模型,与后端一致。 */
1349
+ disabled: busy,
1350
+ }, t.pairingShare),
1351
+ ),
1352
+ )
1353
+ : h('div', { className: 'wbg-row' },
1354
+ h('button', {
1355
+ type: 'button',
1356
+ className: 'wbg-btn',
1357
+ onClick: () => onDeny(entry.nonce),
1358
+ disabled: busy,
1359
+ }, t.pairingDeny),
1360
+ h('span', { className: 'wbg-spacer' }),
1361
+ h('button', {
1362
+ type: 'button',
1363
+ className: 'wbg-btn wbg-btn-primary',
1364
+ onClick: () => open(entry.nonce),
1365
+ disabled: busy,
1366
+ }, t.pairingApprove),
1367
+ ),
1368
+ ))
1369
+ : null,
1370
+
1371
+ error === undefined ? null : h('div', { className: 'wbg-alert wbg-alert-error' },
1372
+ h('span', { className: 'wbg-alert-icon', 'aria-hidden': true }, '!'),
1373
+ h('span', { className: 'wbg-alert-body' }, error)),
1374
+
1375
+ /* 本机名称:对方在发现列表里靠它认出该连哪台。 */
1376
+ pairing.available === true
1377
+ ? h('div', { className: 'wbg-field', style: { marginTop: 10 } },
1378
+ h('span', null, t.pairingShareName),
1379
+ h('div', { className: 'wbg-row' },
1380
+ h('input', {
1381
+ className: 'wbg-input wbg-grow',
1382
+ value: shareName,
1383
+ placeholder: t.pairingShareNameHint,
1384
+ onChange: (event) => setShareName(event.target.value),
1385
+ }),
1386
+ h('button', {
1387
+ type: 'button',
1388
+ className: 'wbg-btn',
1389
+ onClick: () => onSaveShareName(shareName),
1390
+ disabled: busy,
1391
+ }, t.pairingSaveName),
1392
+ ),
1393
+ h('p', { className: 'wbg-caption' }, t.pairingShareNameHint),
1394
+ )
1395
+ : null,
1396
+ )
1397
+ }
1398
+
1399
+ /* ── 运行模式 ───────────────────────────────────────────────────── */
1400
+
1401
+ /**
1402
+ * 模式切换卡片。
1403
+ *
1404
+ * 放在最上面,因为选了它才知道下面该显示哪一套配置 —— 两种角色的配置项
1405
+ * 完全不重叠,混在一起只会让人不知道该填哪个。
1406
+ */
1407
+ function ModeCard({ state, t, onSwitch }) {
1408
+ const mode = state?.mode === 'client' ? 'client' : 'upstream'
1409
+ const choices = Array.isArray(state?.modeChoices) ? state.modeChoices : []
1410
+ const [busy, setBusy] = useState(false)
1411
+ const [error, setError] = useState(undefined)
1412
+
1413
+ const pick = async (next) => {
1414
+ if (next === mode) return
1415
+ setBusy(true)
1416
+ setError(undefined)
1417
+ try {
1418
+ await onSwitch(next)
1419
+ } catch (caught) {
1420
+ setError(String(caught.message ?? caught))
1421
+ } finally {
1422
+ setBusy(false)
1423
+ }
1424
+ }
1425
+
1426
+ return h('div', { className: 'wbg-card' },
1427
+ h('div', { className: 'wbg-row' },
1428
+ h('strong', { className: 'wbg-sec-title' }, t.mode),
1429
+ h('span', { className: 'wbg-spacer' }),
1430
+ busy ? h('span', { className: 'wbg-caption' }, t.modeSwitching) : null,
1431
+ ),
1432
+ h('p', { className: 'wbg-hint' }, t.modeHint),
1433
+
1434
+ h('div', { className: 'wbg-picker', style: { marginTop: 8 } },
1435
+ choices.map((choice) => h('label', {
1436
+ key: choice.id,
1437
+ className: 'wbg-opt',
1438
+ style: { cursor: busy ? 'default' : 'pointer' },
1439
+ },
1440
+ h('input', {
1441
+ type: 'radio',
1442
+ name: 'wbg-mode',
1443
+ checked: mode === choice.id,
1444
+ disabled: busy,
1445
+ onChange: () => pick(choice.id),
1446
+ }),
1447
+ h('span', { className: 'wbg-opt-label' }, choice.label),
1448
+ h('span', { className: 'wbg-opt-meta' }, choice.detail),
1449
+ )),
1450
+ ),
1451
+
1452
+ error === undefined ? null : h('div', { className: 'wbg-alert wbg-alert-error' },
1453
+ h('span', { className: 'wbg-alert-icon', 'aria-hidden': true }, '!'),
1454
+ h('span', { className: 'wbg-alert-body' }, error)),
1455
+ )
1456
+ }
1457
+
1458
+ /* ── 接入其他设备(client 模式)──────────────────────────────────── */
1459
+
1460
+ /**
1461
+ * 接收方界面:找网关 → 申请 → 领取 → 管理。
1462
+ *
1463
+ * 这里**没有**任何对外分享的控件 —— client 模式下本机不监听、不发现、不接受
1464
+ * 配对请求,那些配置项连同界面一起消失(见 src/routes.js 的 upstreamMode)。
1465
+ */
1466
+ function PeersCard({ state, t, onScan, onRequest, onClaim, onRemove, onRefresh, onDiagnose }) {
1467
+ const peers = Array.isArray(state?.peers) ? state.peers : []
1468
+ const pending = state?.pendingPairing
1469
+
1470
+ const [found, setFound] = useState([])
1471
+ const [scanning, setScanning] = useState(false)
1472
+ const [busy, setBusy] = useState(false)
1473
+ const [error, setError] = useState(undefined)
1474
+ const [note, setNote] = useState(undefined)
1475
+ const [scanned, setScanned] = useState(false)
1476
+ const [manual, setManual] = useState('')
1477
+ const [diag, setDiag] = useState(undefined)
1478
+
1479
+ const scan = async () => {
1480
+ setScanning(true)
1481
+ setError(undefined)
1482
+ setNote(undefined)
1483
+ try {
1484
+ const result = await onScan()
1485
+ setFound(Array.isArray(result) ? result : [])
1486
+ setScanned(true)
1487
+ } catch (caught) {
1488
+ setError(String(caught.message ?? caught))
1489
+ } finally {
1490
+ setScanning(false)
1491
+ }
1492
+ }
1493
+
1494
+ const diagnose = async () => {
1495
+ setScanning(true)
1496
+ setError(undefined)
1497
+ try {
1498
+ setDiag(await onDiagnose())
1499
+ } catch (caught) {
1500
+ setError(String(caught.message ?? caught))
1501
+ } finally {
1502
+ setScanning(false)
1503
+ }
1504
+ }
1505
+
1506
+ const request = async (baseUrl, name) => {
1507
+ setBusy(true)
1508
+ setError(undefined)
1509
+ setNote(undefined)
1510
+ try {
1511
+ await onRequest(baseUrl, name)
1512
+ setFound([])
1513
+ setNote(`${t.peersWaitingHint}`)
1514
+ } catch (caught) {
1515
+ setError(String(caught.message ?? caught))
1516
+ } finally {
1517
+ setBusy(false)
1518
+ }
1519
+ }
1520
+
1521
+ const claim = async () => {
1522
+ setBusy(true)
1523
+ setError(undefined)
1524
+ try {
1525
+ await onClaim()
1526
+ setNote(undefined)
1527
+ } catch (caught) {
1528
+ /* 202 是「还没批」,onClaim 会把它当成正常中间态,不会到这里。 */
1529
+ setError(String(caught.message ?? caught))
1530
+ } finally {
1531
+ setBusy(false)
1532
+ }
1533
+ }
1534
+
1535
+ return h('div', { className: 'wbg-card wbg-card-soft' },
1536
+ h('div', { className: 'wbg-row' },
1537
+ h('strong', { className: 'wbg-sec-title' }, t.peers),
1538
+ h('span', { className: 'wbg-spacer' }),
1539
+ h('button', {
1540
+ type: 'button',
1541
+ className: 'wbg-btn wbg-btn-primary',
1542
+ onClick: scan,
1543
+ disabled: scanning || busy,
1544
+ }, scanning ? t.peersScanning : t.peersScan),
1545
+ ),
1546
+ h('p', { className: 'wbg-hint' }, t.peersHint),
1547
+
1548
+ /* 等待批准中:这是最容易卡住的一步,单独给一条提示。 */
1549
+ pending === undefined ? null : h('div', { className: 'wbg-alert wbg-alert-warn' },
1550
+ h('span', { className: 'wbg-alert-icon', 'aria-hidden': true }, '…'),
1551
+ h('div', { className: 'wbg-alert-body' },
1552
+ h('div', null, `${t.peersWaiting}(${pending.baseUrl})`),
1553
+ h('p', { className: 'wbg-caption', style: { margin: '2px 0 6px' } }, t.peersWaitingHint),
1554
+ h('button', {
1555
+ type: 'button',
1556
+ className: 'wbg-btn wbg-btn-primary wbg-btn-sm',
1557
+ onClick: claim,
1558
+ disabled: busy,
1559
+ }, busy ? t.peersClaiming : t.peersClaim),
1560
+ ),
1561
+ ),
1562
+
1563
+ /* 扫描结果。 */
1564
+ found.length === 0 ? null : h('div', { className: 'wbg-field' },
1565
+ h('span', null, t.peersFound),
1566
+ found.map((entry) => h('div', { key: entry.baseUrl, className: 'wbg-row', style: { padding: '6px 0' } },
1567
+ h('span', { className: 'wbg-mono' }, entry.name === '' ? entry.baseUrl : `${entry.name} (${entry.baseUrl})`),
1568
+ h('span', { className: 'wbg-spacer' }),
1569
+ h('button', {
1570
+ type: 'button',
1571
+ className: 'wbg-btn wbg-btn-sm',
1572
+ onClick: () => request(entry.baseUrl, entry.name),
1573
+ disabled: busy,
1574
+ }, t.peersRequest),
1575
+ )),
1576
+ ),
1577
+
1578
+ scanned && found.length === 0 && pending === undefined
1579
+ ? h('div', { className: 'wbg-alert wbg-alert-warn' },
1580
+ h('span', { className: 'wbg-alert-icon', 'aria-hidden': true }, '!'),
1581
+ h('div', { className: 'wbg-alert-body' },
1582
+ h('div', null, t.peersNone),
1583
+ h('button', {
1584
+ type: 'button',
1585
+ className: 'wbg-btn wbg-btn-sm',
1586
+ onClick: diagnose,
1587
+ disabled: scanning,
1588
+ style: { marginTop: 6 },
1589
+ }, scanning ? t.peersDiagnosing : t.peersDiagnose),
1590
+ ))
1591
+ : null,
1592
+
1593
+ /* 诊断结果:逐条结论,只把需要处理的那一项标出来。 */
1594
+ diag === undefined ? null : h('div', { className: 'wbg-field' },
1595
+ h('span', null, t.peersChecks),
1596
+ (diag.checks ?? []).map((item) => h('div', {
1597
+ key: item.id,
1598
+ className: 'wbg-row',
1599
+ style: { padding: '4px 0', alignItems: 'flex-start' },
1600
+ },
1601
+ h('span', { className: item.ok ? 'wbg-badge wbg-badge-ok' : 'wbg-badge wbg-badge-warn' },
1602
+ item.ok ? '✓' : '!'),
1603
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 2 } },
1604
+ h('span', null, item.label),
1605
+ h('span', { className: 'wbg-caption' }, item.detail)),
1606
+ )),
1607
+ h('p', { className: 'wbg-caption', style: { marginTop: 6 } }, `${t.localAddresses}: ${(diag.localAddresses ?? []).join(', ') || '—'}`),
1608
+ (diag.hints ?? []).length === 0 ? null : h('div', { style: { marginTop: 6 } },
1609
+ (diag.hints ?? []).map((hint, index) => h('p', { key: `hint-${index}`, className: 'wbg-caption' }, `· ${hint}`))),
1610
+ ),
1611
+
1612
+ /* 手动填地址:广播被拦时唯一的出路。 */
1613
+ h('div', { className: 'wbg-field', style: { marginTop: 10 } },
1614
+ h('span', null, t.peersManual),
1615
+ h('div', { className: 'wbg-row' },
1616
+ h('input', {
1617
+ className: 'wbg-input wbg-grow',
1618
+ value: manual,
1619
+ placeholder: t.peersManualPlaceholder,
1620
+ 'aria-label': t.peersManual,
1621
+ onChange: (event) => setManual(event.target.value),
1622
+ }),
1623
+ h('button', {
1624
+ type: 'button',
1625
+ className: 'wbg-btn',
1626
+ onClick: () => request(manual, ''),
1627
+ disabled: busy || manual.trim() === '',
1628
+ }, t.peersRequest),
1629
+ ),
1630
+ h('p', { className: 'wbg-caption' }, t.peersManualHint),
1631
+ ),
1632
+
1633
+ /* 已接入的网关。 */
1634
+ peers.length === 0
1635
+ ? h('div', { style: { marginTop: 10 } },
1636
+ h('p', { className: 'wbg-caption' }, `${t.peersEmpty} —— ${t.peersEmptyHint}`))
1637
+ : h('div', { className: 'wbg-field', style: { marginTop: 10 } },
1638
+ peers.map((peer) => h('div', {
1639
+ key: peer.id,
1640
+ style: { borderTop: '1px solid var(--dsw-alias-border-l1, #eee)', paddingTop: 8, marginTop: 8 },
1641
+ },
1642
+ h('div', { className: 'wbg-row' },
1643
+ h('span', null, peer.label === '' ? peer.baseUrl : peer.label),
1644
+ h('span', { className: 'wbg-badge wbg-badge-ok' }, t.peersConnected),
1645
+ h('span', { className: 'wbg-spacer' }),
1646
+ h('span', { className: 'wbg-caption' }, `${(peer.models ?? []).length} ${t.peersModels}`),
1647
+ ),
1648
+ h('div', { className: 'wbg-caption', style: { wordBreak: 'break-all' } }, peer.baseUrl),
1649
+ h('div', { className: 'wbg-chips', style: { marginTop: 4 } },
1650
+ (peer.models ?? []).map((model) => h('span', { key: model.id, className: 'wbg-chip wbg-mono' }, model.id)),
1651
+ ),
1652
+ h('div', { className: 'wbg-row', style: { marginTop: 6 } },
1653
+ h('button', {
1654
+ type: 'button',
1655
+ className: 'wbg-btn wbg-btn-sm',
1656
+ onClick: () => onRefresh(peer.id),
1657
+ disabled: busy,
1658
+ }, t.peersRefresh),
1659
+ h('span', { className: 'wbg-spacer' }),
1660
+ h('button', {
1661
+ type: 'button',
1662
+ className: 'wbg-btn wbg-btn-sm',
1663
+ onClick: () => onRemove(peer.id),
1664
+ disabled: busy,
1665
+ }, t.peersRemove),
1666
+ ),
1667
+ )),
1668
+ h('p', { className: 'wbg-caption', style: { marginTop: 8 } }, t.peersLocalOnly),
1669
+ ),
1670
+
1671
+ note === undefined ? null : h('p', { className: 'wbg-caption' }, note),
1672
+
1673
+ error === undefined ? null : h('div', { className: 'wbg-alert wbg-alert-error' },
1674
+ h('span', { className: 'wbg-alert-icon', 'aria-hidden': true }, '!'),
1675
+ h('span', { className: 'wbg-alert-body' }, error)),
1676
+ )
1677
+ }
1678
+
1003
1679
  /* ── 页面 ───────────────────────────────────────────────────────── */
1004
1680
 
1005
1681
  function GatewaySection() {
@@ -1103,6 +1779,78 @@ window.__ModuleLoader__.load({
1103
1779
  await reload()
1104
1780
  }, [reload])
1105
1781
 
1782
+ /* 保存浏览器来源校验策略(loopback / self / lan)。 */
1783
+ const saveOriginPolicy = useCallback(async (policy) => {
1784
+ await adminPost('/config/origin-policy', { policy })
1785
+ await reload()
1786
+ }, [reload])
1787
+
1788
+ /* 批准配对:会新建一把专用 key 并把地址+模型交给对方。 */
1789
+ const approvePairing = useCallback(async (nonce, keyId, models) => {
1790
+ await adminPost('/pair/approve', { nonce, keyId, models })
1791
+ await reload()
1792
+ }, [reload])
1793
+
1794
+ const denyPairing = useCallback(async (nonce) => {
1795
+ await adminPost('/pair/deny', { nonce })
1796
+ await reload()
1797
+ }, [reload])
1798
+
1799
+ const saveShareName = useCallback(async (shareName) => {
1800
+ await adminPost('/config/share-name', { shareName })
1801
+ await reload()
1802
+ }, [reload])
1803
+
1804
+ /* ── 模式切换与接收方动作 ─────────────────────────────────────── */
1805
+
1806
+ const switchMode = useCallback(async (mode) => {
1807
+ await adminPost('/config/mode', { mode })
1808
+ await reload()
1809
+ }, [reload])
1810
+
1811
+ const scanPeers = useCallback(async () => {
1812
+ const body = await adminPost('/peers/scan', {})
1813
+ return body?.peers ?? []
1814
+ }, [])
1815
+
1816
+ const diagnosePeers = useCallback(async () => adminPost('/peers/diagnose', {}), [])
1817
+
1818
+ const requestPeer = useCallback(async (baseUrl, deviceName) => {
1819
+ await adminPost('/peers/request', { baseUrl, deviceName })
1820
+ await reload()
1821
+ }, [reload])
1822
+
1823
+ const claimPeer = useCallback(async () => {
1824
+ const body = await adminPost('/peers/claim', {})
1825
+ /*
1826
+ * 202 = 那台机器上还没人批准。这不是错误,刷新一下就还在等待态;
1827
+ * 抛出去会让界面显示一条红色错误,反而误导。
1828
+ */
1829
+ if (body?.pending === true) {
1830
+ await reload()
1831
+ return
1832
+ }
1833
+ await reload()
1834
+ }, [reload])
1835
+
1836
+ const removePeer = useCallback(async (id) => {
1837
+ await adminPost('/peers/remove', { id })
1838
+ await reload()
1839
+ }, [reload])
1840
+
1841
+ const refreshPeer = useCallback(async (id) => {
1842
+ await adminPost('/peers/refresh', { id })
1843
+ await reload()
1844
+ }, [reload])
1845
+
1846
+ /*
1847
+ * 当前是哪种角色。整套配置项按它切换(见下面的渲染)。
1848
+ *
1849
+ * 用 `=== 'client'` 而不是 `!== 'upstream'`:将来若加了第三种模式,未知值
1850
+ * 会落到「上游」这一侧 —— 那是功能更全的一侧,多显示比少显示安全。
1851
+ */
1852
+ const isClient = state?.mode === 'client'
1853
+
1106
1854
  if (state === undefined) {
1107
1855
  return h('div', { className: 'wbg' },
1108
1856
  h('style', null, CSS),
@@ -1130,7 +1878,23 @@ window.__ModuleLoader__.load({
1130
1878
  h('p', { className: 'wbg-sub' }, t.subtitle),
1131
1879
  ),
1132
1880
 
1133
- h('div', { className: 'wbg-card' },
1881
+ /*
1882
+ * **模式选择永远第一。**
1883
+ *
1884
+ * 它决定下面显示哪一整套配置,所以必须排在所有内容之前 —— 用户要先是
1885
+ * 发送方还是接收方,才知道接下来该看什么。之前它排在接口地址和 API key
1886
+ * 之后,选了「接入其他设备」却发现上面还挂着一堆上游才有的东西。
1887
+ */
1888
+ h(ModeCard, { state, t, onSwitch: switchMode }),
1889
+
1890
+ /*
1891
+ * ↓ 以下**只有上游模式**才有。
1892
+ *
1893
+ * 这几块在之前被漏在模式判断之外:接口地址、账号可用性、API key 列表、
1894
+ * curl 示例全部照旧显示,等于接收方看到一套自己用不上的配置。它们的共同
1895
+ * 点都是「我作为发送方怎么对外提供服务」,接收方一件也用不到。
1896
+ */
1897
+ isClient ? null : h('div', { className: 'wbg-card' },
1134
1898
  h('div', { className: 'wbg-row' },
1135
1899
  h('strong', { className: 'wbg-sec-title' }, t.endpoints),
1136
1900
  h('span', { className: 'wbg-spacer' }),
@@ -1147,7 +1911,7 @@ window.__ModuleLoader__.load({
1147
1911
  * 这里把「移除了几个、为什么、状态有多新」直接说出来 —— 否则用户只会
1148
1912
  * 发现某个账号凭空消失。
1149
1913
  */
1150
- (state.unavailableAccounts?.length ?? 0) === 0 ? null : h('div', { className: 'wbg-alert wbg-alert-warn' },
1914
+ isClient || (state.unavailableAccounts?.length ?? 0) === 0 ? null : h('div', { className: 'wbg-alert wbg-alert-warn' },
1151
1915
  h('span', { className: 'wbg-alert-icon', 'aria-hidden': true }, '!'),
1152
1916
  h('div', { className: 'wbg-alert-body' },
1153
1917
  h('div', null, `${state.unavailableAccounts.length} ${t.unavailable}`),
@@ -1165,7 +1929,8 @@ window.__ModuleLoader__.load({
1165
1929
  ),
1166
1930
  ),
1167
1931
 
1168
- h('div', { className: 'wbg-row' },
1932
+ /* API key 列表:只有发送方需要「发出去的凭据」。 */
1933
+ isClient ? null : h('div', { className: 'wbg-row' },
1169
1934
  h('strong', { className: 'wbg-sec-title' }, t.keys),
1170
1935
  h('span', { className: 'wbg-spacer' }),
1171
1936
  h('button', { type: 'button', className: 'wbg-btn wbg-btn-primary', onClick: addKey, disabled: busy }, t.addKey),
@@ -1176,7 +1941,7 @@ window.__ModuleLoader__.load({
1176
1941
  h('div', { className: 'wbg-alert-body' },
1177
1942
  h('strong', null, `${t.errorTitle}: `), error)),
1178
1943
 
1179
- h('div', { className: 'wbg-list' },
1944
+ isClient ? null : h('div', { className: 'wbg-list' },
1180
1945
  state.keys.length === 0
1181
1946
  ? h('div', { className: 'wbg-card wbg-card-soft' }, h('p', { className: 'wbg-hint' }, t.noKeys))
1182
1947
  : state.keys.map((entry) => h(KeyCard, {
@@ -1191,14 +1956,46 @@ window.__ModuleLoader__.load({
1191
1956
  })),
1192
1957
  ),
1193
1958
 
1194
- h('div', { className: 'wbg-card wbg-card-soft' },
1959
+ /* curl 示例:教人怎么**调用我**的网关,接收方用不到。 */
1960
+ isClient ? null : h('div', { className: 'wbg-card wbg-card-soft' },
1195
1961
  h('strong', { className: 'wbg-sec-title' }, t.guide),
1196
1962
  h('p', { className: 'wbg-hint' }, t.guideHint),
1197
1963
  h('pre', { className: 'wbg-code wbg-mono' }, curlExample),
1198
1964
  ),
1199
1965
 
1200
- h(PortCard, { state, t, onSave: savePort }),
1201
- h(LanCard, { state, t, onToggle: saveAllowLan }),
1966
+ /*
1967
+ * **两套配置按模式整块切换,不混排。**
1968
+ *
1969
+ * upstream(发送方):端口、局域网、配对批准、来源校验、存储位置。
1970
+ * client(接收方) :只有「接入其他设备的网关」和存储位置 —— 它不监听、
1971
+ * 不发现、不接受配对请求,那些配置项对它没有意义,
1972
+ * 显示出来只会让人以为要填。
1973
+ */
1974
+ isClient
1975
+ ? h(PeersCard, {
1976
+ state,
1977
+ t,
1978
+ onScan: scanPeers,
1979
+ onRequest: requestPeer,
1980
+ onClaim: claimPeer,
1981
+ onRemove: removePeer,
1982
+ onRefresh: refreshPeer,
1983
+ onDiagnose: diagnosePeers,
1984
+ })
1985
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12 } },
1986
+ h(PortCard, { state, t, onSave: savePort }),
1987
+ h(LanCard, { state, t, onToggle: saveAllowLan }),
1988
+ h(PairingCard, {
1989
+ state,
1990
+ t,
1991
+ onApprove: approvePairing,
1992
+ onDeny: denyPairing,
1993
+ onSaveShareName: saveShareName,
1994
+ }),
1995
+ h(OriginCard, { state, t, onSave: saveOriginPolicy }),
1996
+ ),
1997
+
1998
+ /* 存储位置两种模式都需要:它就是「配置写在哪」。 */
1202
1999
  h(StorageCard, { state, t, onSave: saveDataDir }),
1203
2000
 
1204
2001
  created === undefined ? null : h(SecretDialog, {