dsh-remote-plugin 0.8.1 → 0.8.3

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 (111) hide show
  1. package/README.md +1 -1
  2. package/apk/dsh-remote.apk +0 -0
  3. package/cordis.patch.yml +2 -1
  4. package/gateway.cjs +323 -64
  5. package/index.mjs +2 -2
  6. package/insights.mjs +5 -3
  7. package/market.mjs +4 -1
  8. package/package.json +1 -1
  9. package/plugin-center.mjs +120 -7
  10. package/plugin-transaction.mjs +10 -3
  11. package/public/admin.html +19 -14
  12. package/public/admin.js +71 -23
  13. package/public/announcements.json +192 -0
  14. package/public/app.js +192 -60
  15. package/public/build.json +2 -2
  16. package/public/chat-copy.js +46 -0
  17. package/public/desktop/desktop.css +10 -0
  18. package/public/desktop/desktop.html +28 -15
  19. package/public/desktop/desktop.js +74 -22
  20. package/public/diagnostics.js +115 -21
  21. package/public/history.js +45 -9
  22. package/public/image-cache.js +141 -0
  23. package/public/image-preview.js +48 -5
  24. package/public/index.html +39 -34
  25. package/public/lan-discovery.js +94 -0
  26. package/public/md.js +8 -2
  27. package/public/plugin-center.js +1 -1
  28. package/public/plugin.html +8 -2
  29. package/public/relay-settings.js +7 -6
  30. package/public/skins/blue-fish/DESIGN.md +24 -0
  31. package/public/skins/blue-fish/preview.html +11 -289
  32. package/public/skins/blue-fish/skin.css +95 -585
  33. package/public/skins/blue-fish/sparkles.svg +18 -0
  34. package/public/skins/bocchi/DESIGN.md +99 -0
  35. package/public/skins/bocchi/face.png +0 -0
  36. package/public/skins/bocchi/grain.png +0 -0
  37. package/public/skins/bocchi/icon-blush.png +0 -0
  38. package/public/skins/bocchi/icon-sleep.png +0 -0
  39. package/public/skins/bocchi/icon-smile.png +0 -0
  40. package/public/skins/bocchi/icon-star.png +0 -0
  41. package/public/skins/bocchi/icon-wink.png +0 -0
  42. package/public/skins/bocchi/icon.png +0 -0
  43. package/public/skins/bocchi/pattern-soft.png +0 -0
  44. package/public/skins/bocchi/pattern.png +0 -0
  45. package/public/skins/bocchi/preview.html +54 -0
  46. package/public/skins/bocchi/skin.css +233 -0
  47. package/public/skins/bocchi/stage-bg.png +0 -0
  48. package/public/skins/bocchi/stage-soft.png +0 -0
  49. package/public/skins/bocchi/stand.png +0 -0
  50. package/public/skins/bocchi/sticker-guitar.png +0 -0
  51. package/public/skins/kessoku/DESIGN.md +38 -0
  52. package/public/skins/kessoku/grain.png +0 -0
  53. package/public/skins/kessoku/skin.css +212 -0
  54. package/public/skins/kita/SOURCES.json +51 -0
  55. package/public/skins/kita/face.png +0 -0
  56. package/public/skins/kita/icon-live.png +0 -0
  57. package/public/skins/kita/icon-reddress.png +0 -0
  58. package/public/skins/kita/icon-seifuku.png +0 -0
  59. package/public/skins/kita/pattern.png +0 -0
  60. package/public/skins/kita/preview.html +55 -0
  61. package/public/skins/kita/skin.css +26 -0
  62. package/public/skins/kita/stand.png +0 -0
  63. package/public/skins/kita/sticker-live.png +0 -0
  64. package/public/skins/nijika/SOURCES.json +51 -0
  65. package/public/skins/nijika/face.png +0 -0
  66. package/public/skins/nijika/icon-live.png +0 -0
  67. package/public/skins/nijika/icon-reddress.png +0 -0
  68. package/public/skins/nijika/icon-seifuku.png +0 -0
  69. package/public/skins/nijika/pattern.png +0 -0
  70. package/public/skins/nijika/preview.html +55 -0
  71. package/public/skins/nijika/skin.css +25 -0
  72. package/public/skins/nijika/stand.png +0 -0
  73. package/public/skins/nijika/sticker-live.png +0 -0
  74. package/public/skins/penguin/DESIGN.md +33 -0
  75. package/public/skins/penguin/SOURCES.json +22 -0
  76. package/public/skins/penguin/aic-blueprint.svg +24 -0
  77. package/public/skins/penguin/endfield-triangles.svg +4 -0
  78. package/public/skins/penguin/face.png +0 -0
  79. package/public/skins/penguin/icon-blush.png +0 -0
  80. package/public/skins/penguin/icon-dizzy.png +0 -0
  81. package/public/skins/penguin/icon-laugh.png +0 -0
  82. package/public/skins/penguin/icon-sleep.png +0 -0
  83. package/public/skins/penguin/icon-smile.png +0 -0
  84. package/public/skins/penguin/icon-star.png +0 -0
  85. package/public/skins/penguin/icon-wink.png +0 -0
  86. package/public/skins/penguin/icon.png +0 -0
  87. package/public/skins/penguin/mascot.png +0 -0
  88. package/public/skins/penguin/pattern-night.png +0 -0
  89. package/public/skins/penguin/pattern.png +0 -0
  90. package/public/skins/penguin/preview.html +11 -0
  91. package/public/skins/penguin/skin.css +212 -0
  92. package/public/skins/ryo/SOURCES.json +51 -0
  93. package/public/skins/ryo/face.png +0 -0
  94. package/public/skins/ryo/icon-live.png +0 -0
  95. package/public/skins/ryo/icon-reddress.png +0 -0
  96. package/public/skins/ryo/icon-seifuku.png +0 -0
  97. package/public/skins/ryo/pattern.png +0 -0
  98. package/public/skins/ryo/preview.html +55 -0
  99. package/public/skins/ryo/skin.css +25 -0
  100. package/public/skins/ryo/stand.png +0 -0
  101. package/public/skins/ryo/sticker-live.png +0 -0
  102. package/public/sponsor-entry.js +22 -0
  103. package/public/styles.css +13 -0
  104. package/public/theme-picker.css +58 -0
  105. package/public/theme-vars.css +532 -5
  106. package/public/theme.js +111 -3
  107. package/public/update.json +12 -12
  108. package/public/version.json +1 -1
  109. package/public/workflow.css +2 -1
  110. package/public/workflow.js +24 -1
  111. package/skills/dsh-remote-doctor/references/wiki/notifications.md +4 -0
package/README.md CHANGED
@@ -24,7 +24,7 @@ dsh plugin --profile web list --depth 0
24
24
  - mux/host 下行、独立长轮询、弱网设置与历史缓存。
25
25
  - 文件多根、分块续传、校验、预览/下载与图片附件。
26
26
  - 当前主机插件管理与可选上下文/费用洞察。
27
- - 手机导航:会话、文件、更多;六套 Web 主题,默认蓝色大肥鱼,保留已有主题选择。
27
+ - 手机导航:会话、文件、更多;十二套 Web 主题(含孤独摇滚四人、企鹅女管·白昼/极夜角色皮肤),默认蓝色大肥鱼,保留已有主题选择。
28
28
  - 手机端八步新手引导;完成或整体跳过后移除首页入口,在「更多 → 偏好与维护 → 新手引导」重新学习。
29
29
  - rc.9 补充冷会话恢复与错误归属修复、发送结果诊断、文件上传与分支恢复验证;具体范围见候选版说明。
30
30
  - Android APK 在已有构建产物时随包分发,通知与后台需设备权限。
Binary file
package/cordis.patch.yml CHANGED
@@ -1,4 +1,5 @@
1
1
  # dsh-remote bundle patch: 把插件自身 insert 进 profile 层栈
2
+ # id 与包名一致: loader 以 entry id 为键, 通用 id 会被同名插件顶掉
2
3
  - insert:
3
- - id: dsh-remote
4
+ - id: dsh-remote-plugin
4
5
  name: 'dsh-remote-plugin'
package/gateway.cjs CHANGED
@@ -66,6 +66,17 @@ function publicKey(value) {
66
66
  const digest = value => crypto.createHash('sha256').update(value).digest('hex')
67
67
  const live = (grant, now = Date.now()) => grant && !grant.revokedAt && grant.expiresAt > now
68
68
  const signingText = (nonce, id, role, session = '') => Buffer.from(JSON.stringify(['dsh-relay-v1', nonce, id, role, session]))
69
+ function issueInState(state, { label = '', domain, expiresAt, plan } = {}) {
70
+ if (state.grants.filter(g => live(g)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
71
+ const id = crypto.randomBytes(8).toString('hex')
72
+ const assigned = hostname(domain || `r-${id}.${state.baseDomain}`)
73
+ if (!assigned.endsWith('.' + state.baseDomain) || assigned === new URL(state.origin).hostname || assigned === state.tunnelHost) throw fault('INVALID_TENANT_DOMAIN')
74
+ if (state.grants.some(g => g.domain === assigned)) throw fault('DOMAIN_ALREADY_ASSIGNED', 409)
75
+ const code = `dsrp_${id}.${crypto.randomBytes(32).toString('base64url')}`
76
+ const grant = { id, label: String(label).slice(0, 80), domain: assigned, expiresAt, createdAt: Date.now(), codeHash: digest(code), publicKey: null, revokedAt: null, ...(plan ? { plan } : {}) }
77
+ state.grants.push(grant)
78
+ return { code, grant }
79
+ }
69
80
 
70
81
  class Registry {
71
82
  constructor(file) { this.file = path.resolve(file) }
@@ -83,8 +94,10 @@ class Registry {
83
94
  const result = fn(state)
84
95
  const temp = this.file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp'
85
96
  try {
86
- fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
97
+ const output = fs.openSync(temp, 'wx', 0o600)
98
+ try { fs.writeFileSync(output, JSON.stringify(state, null, 2) + '\n'); fs.fsyncSync(output) } finally { fs.closeSync(output) }
87
99
  fs.renameSync(temp, this.file)
100
+ if (process.platform !== 'win32') { const dir = fs.openSync(path.dirname(this.file), 'r'); try { fs.fsyncSync(dir) } finally { fs.closeSync(dir) } }
88
101
  } finally { try { fs.unlinkSync(temp) } catch {} }
89
102
  return result
90
103
  } finally { fs.closeSync(fd); fs.unlinkSync(lock) }
@@ -105,14 +118,9 @@ class Registry {
105
118
  const expires = Number(expiresAt)
106
119
  if (!Number.isFinite(expires) || expires <= Date.now() || expires > Date.now() + 90 * 86400000) throw fault('INVALID_EXPIRY')
107
120
  return this.change(state => {
108
- if (state.grants.filter(g => live(g)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
109
- const id = crypto.randomBytes(8).toString('hex')
110
- const assigned = hostname(domain || `r-${id}.${state.baseDomain}`)
111
- if (!assigned.endsWith('.' + state.baseDomain) || assigned === new URL(state.origin).hostname || assigned === state.tunnelHost) throw fault('INVALID_TENANT_DOMAIN')
112
- if (state.grants.some(g => g.domain === assigned)) throw fault('DOMAIN_ALREADY_ASSIGNED', 409)
113
- const code = `dsrp_${id}.${crypto.randomBytes(32).toString('base64url')}`
114
- const grant = { id, label: String(label).slice(0, 80), domain: assigned, expiresAt: expires, createdAt: Date.now(), codeHash: digest(code), publicKey: null, revokedAt: null }
115
- state.grants.push(grant)
121
+ const reserved = (state.sponsorship?.applications || []).filter(a => a.status === 'submitted' || a.status === 'draft' && a.reservedUntil > Date.now()).length
122
+ if (state.grants.filter(g => live(g)).length + reserved >= state.maxUsers) throw fault('PILOT_FULL', 409)
123
+ const { code, grant } = issueInState(state, { label, domain, expiresAt: expires })
116
124
  return { code, grant: this.view(grant) }
117
125
  })
118
126
  }
@@ -135,13 +143,13 @@ class Registry {
135
143
  if (!live(grant) || !crypto.timingSafeEqual(Buffer.from(grant.codeHash, 'hex'), Buffer.from(digest(code), 'hex'))) throw fault('INVALID_AUTHORIZATION', 403)
136
144
  if (grant.publicKey && grant.publicKey !== normalized) throw fault('HOST_ALREADY_BOUND', 409)
137
145
  grant.publicKey = normalized
138
- return { grantId: grant.id, domain: grant.domain, expiresAt: grant.expiresAt, publicUrl: `https://${grant.domain}`, dailyLimitBytes: 5_000_000_000, timezone: 'Asia/Shanghai', transport: 'https-upgrade', tunnelOrigin: state.origin, tunnelHost: state.tunnelHost, tunnelPort: state.tunnelPort }
146
+ return { grantId: grant.id, domain: grant.domain, expiresAt: grant.expiresAt, publicUrl: `https://${grant.domain}`, ...(grant.plan === 'sponsor-basic' ? { quotaPeriod: 'month', monthlyLimitBytes: 5_000_000_000, fileTransfer: false } : { dailyLimitBytes: 5_000_000_000 }), timezone: 'Asia/Shanghai', transport: 'https-upgrade', tunnelOrigin: state.origin, tunnelHost: state.tunnelHost, tunnelPort: state.tunnelPort }
139
147
  })
140
148
  }
141
149
  get(id) { return this.read().grants.find(g => g.id === id) }
142
150
  }
143
151
 
144
- module.exports = { Registry, fault, hostname, publicKey, digest, live, signingText }
152
+ module.exports = { Registry, fault, hostname, publicKey, digest, live, signingText, issueInState }
145
153
  },
146
154
  "./wire.cjs": function(require, module, exports) {
147
155
  'use strict'
@@ -1291,6 +1299,126 @@ function restoreMissingTokenFile() {
1291
1299
  const WS_TICKET_TTL_MS = durationEnv('GATEWAY_WS_TICKET_TTL_MS', 90000, 10000, 10 * 60 * 1000)
1292
1300
  const wsTickets = new Map()
1293
1301
 
1302
+ // BEGIN EMBEDDED LAN PAIRING
1303
+ function createLanPairing(options) {
1304
+ const crypto = require('node:crypto'), dgram = require('node:dgram')
1305
+ const clock = options.clock || Date.now
1306
+ const instanceId = crypto.randomBytes(16).toString('hex')
1307
+ let secret = null, expiresAt = 0, socket = null, timer = null, failures = 0, error = '', revision = 0
1308
+ const challenges = new Map(), peers = new Map()
1309
+ const fail = (status, code) => { throw Object.assign(new Error(code), { status, code }) }
1310
+ const localPeer = address => {
1311
+ const ip = String(address || '').replace(/^::ffff:/, '')
1312
+ if (ip === '::1' || /^(fc|fd)[0-9a-f]{2}:/i.test(ip) || /^fe[89ab][0-9a-f]:/i.test(ip)) return true
1313
+ if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) return false
1314
+ const bytes = ip.split('.').map(Number)
1315
+ if (bytes.length !== 4 || bytes.some(n => !Number.isInteger(n) || n < 0 || n > 255)) return false
1316
+ return bytes[0] === 10 || bytes[0] === 127 || bytes[0] === 192 && bytes[1] === 168
1317
+ || bytes[0] === 172 && bytes[1] >= 16 && bytes[1] <= 31 || bytes[0] === 169 && bytes[1] === 254
1318
+ }
1319
+ const active = () => !!secret && clock() < expiresAt && options.deviceMode()
1320
+ const status = () => ({ supported: true, enabled: active() && !!socket, expiresAt: active() ? expiresAt : 0,
1321
+ port: Number(options.discoveryPort || 8788), error })
1322
+ function close() {
1323
+ revision++
1324
+ secret = null; expiresAt = 0; challenges.clear(); peers.clear()
1325
+ clearTimeout(timer); timer = null
1326
+ if (socket) { try { socket.close() } catch {} socket = null }
1327
+ }
1328
+ async function open() {
1329
+ close(); error = ''
1330
+ const openingRevision = revision
1331
+ if (!options.deviceMode()) fail(409, 'DEVICE_KEYS_REQUIRED')
1332
+ if (options.host === '127.0.0.1' || options.host === '::1') fail(409, 'LAN_LISTENER_REQUIRED')
1333
+ const code = crypto.randomBytes(10).toString('hex').toUpperCase()
1334
+ secret = crypto.createHash('sha256').update(code).digest(); failures = 0
1335
+ expiresAt = clock() + 10 * 60 * 1000
1336
+ const candidate = dgram.createSocket('udp4')
1337
+ try {
1338
+ await new Promise((resolve, reject) => {
1339
+ candidate.once('error', reject)
1340
+ candidate.bind(Number(options.discoveryPort || 8788), options.discoveryHost || '0.0.0.0', () => {
1341
+ candidate.removeListener('error', reject); resolve()
1342
+ })
1343
+ })
1344
+ } catch {
1345
+ try { candidate.close() } catch {}
1346
+ if (revision === openingRevision) { close(); error = 'DISCOVERY_PORT_UNAVAILABLE' }
1347
+ fail(503, 'DISCOVERY_PORT_UNAVAILABLE')
1348
+ }
1349
+ if (revision !== openingRevision) { try { candidate.close() } catch {} fail(409, 'PAIRING_CLOSED') }
1350
+ socket = candidate
1351
+ socket.on('error', () => { close(); error = 'DISCOVERY_SOCKET_FAILED' })
1352
+ socket.on('message', (message, peer) => {
1353
+ if (!active() || !localPeer(peer.address) || message.length < 256 || message.length > 512) return
1354
+ let query
1355
+ try { query = JSON.parse(message.toString('utf8')) } catch { return }
1356
+ if (query?.type !== 'dsh-remote-discover' || query.version !== 1 || !/^[a-f0-9]{32}$/.test(query.nonce)) return
1357
+ const now = clock(), previous = peers.get(peer.address)
1358
+ if (previous && now - previous.at < 500) return
1359
+ if (peers.size >= 128 && !peers.has(peer.address)) return
1360
+ peers.set(peer.address, { at: now, count: previous?.count || 0 })
1361
+ const reply = Buffer.from(JSON.stringify({ type: 'dsh-remote-host', version: 1, nonce: query.nonce,
1362
+ instanceId, name: String(options.name || 'DSH Remote').slice(0, 40), port: options.port }))
1363
+ if (reply.length <= message.length) candidate.send(reply, peer.port, peer.address, () => {})
1364
+ })
1365
+ timer = setTimeout(close, 10 * 60 * 1000); timer.unref?.()
1366
+ socket.unref?.()
1367
+ return { ...status(), code: code.match(/.{4}/g).join('-') }
1368
+ }
1369
+ const proof = (role, transcript) => crypto.createHmac('sha256', secret).update(role + '\n' + transcript).digest('hex')
1370
+ function pair(address, input) {
1371
+ address = String(address || '').replace(/^::ffff:/, '')
1372
+ if (!localPeer(address)) fail(403, 'LAN_ONLY')
1373
+ if (!active()) { close(); fail(410, 'PAIRING_CLOSED') }
1374
+ if (!input || typeof input !== 'object' || Array.isArray(input)) fail(400, 'BAD_REQUEST')
1375
+ const now = clock()
1376
+ for (const [id, challenge] of challenges) if (challenge.expires <= now) challenges.delete(id)
1377
+ if (input.step === 'hello') {
1378
+ const limit = peers.get(address) || { at: 0, count: 0 }
1379
+ if (limit.count >= 12 || challenges.size >= 32 || peers.size >= 128 && !peers.has(address)) fail(429, 'PAIRING_RATE_LIMIT')
1380
+ peers.set(address, { ...limit, count: limit.count + 1 })
1381
+ if (input.instanceId !== instanceId || !/^[a-f0-9]{32}$/.test(input.nonce || '')
1382
+ || typeof input.clientPublic !== 'string' || input.clientPublic.length > 200
1383
+ || !/^[A-Za-z0-9+/]+={0,2}$/.test(input.clientPublic)
1384
+ || Buffer.from(input.clientPublic, 'base64').toString('base64') !== input.clientPublic) fail(400, 'BAD_REQUEST')
1385
+ let clientKey, shared
1386
+ const keys = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
1387
+ try {
1388
+ clientKey = crypto.createPublicKey({ key: Buffer.from(input.clientPublic, 'base64'), format: 'der', type: 'spki' })
1389
+ if (clientKey.asymmetricKeyType !== 'ec' || clientKey.asymmetricKeyDetails?.namedCurve !== 'prime256v1') fail(400, 'BAD_KEY')
1390
+ shared = crypto.diffieHellman({ privateKey: keys.privateKey, publicKey: clientKey })
1391
+ } catch { fail(400, 'BAD_KEY') }
1392
+ const serverPublic = keys.publicKey.export({ format: 'der', type: 'spki' }).toString('base64')
1393
+ const challengeId = crypto.randomBytes(16).toString('hex')
1394
+ const transcript = ['dsh-lan-v1', instanceId, challengeId, input.nonce, input.clientPublic, serverPublic].join('\n')
1395
+ challenges.set(challengeId, { address, shared, transcript, expires: now + 30000 })
1396
+ return { challengeId, serverPublic, serverProof: proof('server', transcript) }
1397
+ }
1398
+ if (input.step !== 'finish') fail(400, 'BAD_REQUEST')
1399
+ const challenge = challenges.get(input.challengeId)
1400
+ challenges.delete(input.challengeId) // A challenge can be used only once, including failed attempts.
1401
+ if (!challenge || challenge.address !== address || challenge.expires <= now) fail(410, 'CHALLENGE_EXPIRED')
1402
+ const expected = proof('client', challenge.transcript), supplied = String(input.proof || '')
1403
+ if (!/^[a-f0-9]{64}$/.test(supplied) || !crypto.timingSafeEqual(Buffer.from(supplied), Buffer.from(expected))) {
1404
+ failures++; if (failures >= 10) close()
1405
+ fail(401, 'PAIRING_CODE_INVALID')
1406
+ }
1407
+ const entry = options.issueDevice()
1408
+ if (!entry) fail(503, 'DEVICE_KEY_WRITE_FAILED')
1409
+ const key = crypto.createHmac('sha256', secret).update('key\n' + challenge.transcript + '\n').update(challenge.shared).digest()
1410
+ const iv = crypto.randomBytes(12), cipher = crypto.createCipheriv('aes-256-gcm', key, iv)
1411
+ cipher.setAAD(Buffer.from(challenge.transcript))
1412
+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify({ token: entry.token, deviceId: entry.id })), cipher.final()])
1413
+ const result = { iv: iv.toString('base64'), ciphertext: ciphertext.toString('base64'), tag: cipher.getAuthTag().toString('base64') }
1414
+ close() // Successful pairing closes discovery and the one-time code.
1415
+ return result
1416
+ }
1417
+ return { open, close, status, pair, localPeer }
1418
+ }
1419
+
1420
+ // END EMBEDDED LAN PAIRING
1421
+
1294
1422
  function newAccessToken() {
1295
1423
  return crypto.randomBytes(24).toString('base64url')
1296
1424
  }
@@ -1378,6 +1506,29 @@ function deviceKeyViews() {
1378
1506
  return deviceKeyState.keys.map(record => ({ ...record }))
1379
1507
  }
1380
1508
 
1509
+ const lanPairing = createLanPairing({
1510
+ host: HOST, port: PORT, name: os.hostname(),
1511
+ discoveryPort: Number(process.env.DSH_REMOTE_DISCOVERY_PORT) || 8788,
1512
+ deviceMode: () => deviceKeyState.enabled,
1513
+ issueDevice: () => deviceKeyState.enabled && deviceKeyState.keys.length < 100 ? createDeviceKey('局域网配对设备') : null,
1514
+ })
1515
+
1516
+ async function serveLanPair(req, res) {
1517
+ cors(res)
1518
+ const reply = (status, body) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(body)) }
1519
+ if (req.headers.origin && !res.getHeader('access-control-allow-origin')) return reply(403, { error: 'ORIGIN_DENIED' })
1520
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
1521
+ if (req.method !== 'POST') return reply(405, { error: 'POST_REQUIRED' })
1522
+ if (!lanPairing.localPeer(req.socket.remoteAddress)) return reply(403, { error: 'LAN_ONLY' })
1523
+ if (!String(req.headers['content-type'] || '').startsWith('application/json')) return reply(415, { error: 'JSON_REQUIRED' })
1524
+ try {
1525
+ const body = await readBody(req, 2048)
1526
+ let input
1527
+ try { input = JSON.parse(body) } catch { return reply(400, { error: 'BAD_REQUEST' }) }
1528
+ return reply(200, lanPairing.pair(req.socket.remoteAddress, input))
1529
+ } catch (err) { return reply(err.status || 400, { error: err.code || 'PAIRING_FAILED' }) }
1530
+ }
1531
+
1381
1532
  function findDeviceKeyByToken(value) {
1382
1533
  return deviceKeyState.keys.find(record => safeTokenEqual(value, record.token)) || null
1383
1534
  }
@@ -1410,6 +1561,7 @@ function rotateToken() {
1410
1561
  return { error: 'write-failed', detail: err.message }
1411
1562
  }
1412
1563
  TOKEN = next
1564
+ lanPairing.close()
1413
1565
  wsTickets.clear()
1414
1566
  return { ok: true, token: next }
1415
1567
  }
@@ -1841,7 +1993,8 @@ function cors(res, req = res.req) {
1841
1993
  }
1842
1994
  if (allowed) res.setHeader('access-control-allow-origin', origin || '*')
1843
1995
  res.setHeader('vary', 'Origin')
1844
- res.setHeader('access-control-allow-headers', 'authorization, content-type, x-dsh-remote-client, x-dsh-remote-client-id, x-dsh-remote-inbox-key')
1996
+ res.setHeader('access-control-allow-headers', 'authorization, content-type, x-dsh-remote-client, x-dsh-remote-client-id, x-dsh-remote-inbox-key, if-none-match, if-modified-since')
1997
+ res.setHeader('access-control-expose-headers', 'etag, last-modified')
1845
1998
  res.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS')
1846
1999
  res.setHeader('access-control-max-age', '600')
1847
2000
  }
@@ -1888,6 +2041,16 @@ function withRequestBody(req, res, limit, callback) {
1888
2041
  })
1889
2042
  }
1890
2043
 
2044
+ async function readResponseText(response, maxBytes) {
2045
+ const chunks = []; let bytes = 0
2046
+ for await (const chunk of response.body) {
2047
+ bytes += chunk.length
2048
+ if (bytes > maxBytes) throw Object.assign(new Error('response too large'), { status: 413 })
2049
+ chunks.push(chunk)
2050
+ }
2051
+ return Buffer.concat(chunks).toString('utf8')
2052
+ }
2053
+
1891
2054
  function execFileResult(file, args, timeout = 5000) {
1892
2055
  return new Promise((resolvePromise) => {
1893
2056
  execFile(file, args, { timeout, windowsHide: true }, (error, stdout, stderr) => {
@@ -2718,7 +2881,7 @@ async function serveDshControl(req, res, url) {
2718
2881
  // 阻断时改走 GET /api/events.poll 增量拉取。
2719
2882
  const EVENT_BUFFER_MAX = durationEnv('GATEWAY_EVENT_BUFFER_MAX', 1000, 100, 10000)
2720
2883
  const EVENT_POLL_WAIT_MAX = durationEnv('GATEWAY_EVENT_POLL_WAIT_MS', 25000, 0, 60000)
2721
- const EVENT_MAX_STRING = 16 * 1024
2884
+ const EVENT_BUFFER_MAX_BYTES = durationEnv('GATEWAY_EVENT_BUFFER_MAX_BYTES', 8 * 1024 * 1024, 65536, 64 * 1024 * 1024)
2722
2885
  const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
2723
2886
  const eventBuffers = { mux: [], host: [] }
2724
2887
  const eventNextSeq = { mux: 1, host: 1 }
@@ -3150,21 +3313,6 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3150
3313
  return legacyEnvelope(rpcId, { ok: true, value: transform(response.body.result.value) })
3151
3314
  }
3152
3315
 
3153
- /** 递归截断超大字段,避免单条超大事件撑爆环形缓冲。 */
3154
- function truncateEventValue(v, depth = 0) {
3155
- if (typeof v === 'string') return v.length > EVENT_MAX_STRING ? v.slice(0, EVENT_MAX_STRING) + '…[truncated]' : v
3156
- if (Array.isArray(v)) {
3157
- if (depth > 3 || v.length > 200) return v.slice(0, 200)
3158
- return v.map(x => truncateEventValue(x, depth + 1))
3159
- }
3160
- if (v && typeof v === 'object' && depth <= 3) {
3161
- const out = {}
3162
- for (const k of Object.keys(v)) out[k] = truncateEventValue(v[k], depth + 1)
3163
- return out
3164
- }
3165
- return v
3166
- }
3167
-
3168
3316
  function wsAccept(key) {
3169
3317
  return crypto.createHash('sha1').update(String(key || '') + WS_GUID).digest('base64')
3170
3318
  }
@@ -3230,10 +3378,20 @@ function broadcastCollectorFrame(kind, raw) {
3230
3378
 
3231
3379
  function pushEvent(kind, full, raw = JSON.stringify(full)) {
3232
3380
  if (!eventBuffers[kind] || !full || typeof full !== 'object') return
3381
+ if (kind === 'host' && ['host/session-status', 'host/agent-error'].includes(full.payload?.type)) {
3382
+ // One delivery identity for the same host lifecycle event over WS and poll.
3383
+ // Upstream rpcId may identify a stream and must not be used as an event ID.
3384
+ full = { ...full, remoteEventId: `${EVENT_STREAM_EPOCH}:${kind}:${eventNextSeq[kind]}` }
3385
+ raw = JSON.stringify(full)
3386
+ }
3233
3387
  if (eventCollectorState[kind]) eventCollectorState[kind].lastEventAt = Date.now()
3234
3388
  const buf = eventBuffers[kind]
3235
- buf.push({ seq: eventNextSeq[kind]++, ts: Date.now(), event: truncateEventValue(full) })
3236
- if (buf.length > EVENT_BUFFER_MAX) buf.shift()
3389
+ const size = Buffer.byteLength(raw), record = { seq: eventNextSeq[kind]++, ts: Date.now(), event: JSON.parse(raw) }
3390
+ Object.defineProperty(record, 'bytes', { value: size })
3391
+ buf.push(record); buf.retainedBytes = (buf.retainedBytes || 0) + size
3392
+ // Evict whole records, never alter message content. Keep the newest complete
3393
+ // event even if it alone exceeds the target budget; cursor gaps trigger reset.
3394
+ while (buf.length > 1 && (buf.length > EVENT_BUFFER_MAX || buf.retainedBytes > EVENT_BUFFER_MAX_BYTES)) buf.retainedBytes -= buf.shift().bytes
3237
3395
  rememberCollectorReplay(kind, full, raw)
3238
3396
  broadcastCollectorFrame(kind, raw)
3239
3397
  flushEventPollWaiters(kind)
@@ -4038,6 +4196,9 @@ function serveStats(req, res, url) {
4038
4196
  // ---------- 反馈提交 ----------
4039
4197
  const feedbackThrottle = new Map() // ip -> 上次受理时间戳
4040
4198
  const FEEDBACK_WINDOW_MS = 60 * 1000
4199
+ // A full diagnostic upload can outlast the former eight-second budget on Funnel.
4200
+ // Share one deadline with the explicit legacy-size fallback; never retry timeouts.
4201
+ const FEEDBACK_FORWARD_TIMEOUT_MS = 30 * 1000
4041
4202
  // 反馈收集器: 环境变量可覆盖, 默认使用 Tailscale Funnel 提供的公网 HTTPS
4042
4203
  // 入口。这里是公开的 ts.net 域名,不要求提交反馈的用户加入 tailnet。
4043
4204
  const FEEDBACK_URL = process.env.DSH_REMOTE_FEEDBACK_URL || 'https://vm-0-2-ubuntu.tail1f6fc4.ts.net/submit'
@@ -4109,8 +4270,8 @@ async function loadCentralAnnouncements(force = false) {
4109
4270
  }
4110
4271
  if (!res.ok) throw new Error(`central announcements HTTP ${res.status}`)
4111
4272
  const declared = Number(res.headers.get('content-length') || 0)
4112
- if (declared > ANNOUNCEMENTS_MAX_BYTES) throw new Error('announcements too large')
4113
- const raw = await res.text()
4273
+ if (declared > ANNOUNCEMENTS_MAX_BYTES) { await res.body?.cancel(); throw new Error('announcements too large') }
4274
+ const raw = await readResponseText(res, ANNOUNCEMENTS_MAX_BYTES)
4114
4275
  const parsed = parseAnnouncements(raw)
4115
4276
  announcementsCache = {
4116
4277
  ...parsed,
@@ -4265,6 +4426,66 @@ async function validatePollVote(payload) {
4265
4426
  return result
4266
4427
  }
4267
4428
 
4429
+ // BEGIN EMBEDDED CLIENT DIAGNOSTICS
4430
+ function createDiagnosticSchema() {
4431
+ const MAX_EVENTS=160,MAX_CRITICAL=40,MAX_BYTES=48000
4432
+ const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit','announcement.storage','announcement.fetch','announcement.show','announcement.close','announcement.vote','storage.write','diagnostics.persist'])
4433
+ const enums={phase:['start','response','prepared','rendered','complete','failed','navigate','cleanup','hit','miss','retry'],channel:['mux','host'],status:['open','closed','connecting','poll','ws','visible','hidden','online','offline','running','stopped','starting','disabled','start-failed','timeout','error','unknown','granted','denied','default'],category:['authentication','timeout','network','render','syntax','upstream','unknown'],errorName:['Error','TypeError','RangeError','SyntaxError','ReferenceError','AbortError','TimeoutError','NetworkError']}
4434
+ enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
4435
+ enums.storageKey=['seen','history','votes']
4436
+ enums.storageBackend=['session','memory']
4437
+ enums.storageBackend.push('local','indexeddb')
4438
+ enums.storageKey.push('settings','session-list','diagnostics','approvals','receipts')
4439
+ enums.phase.push('received','shown','dismissed','acknowledged','skipped')
4440
+ enums.category.push('storage','validation')
4441
+ enums.errorName.push('QuotaExceededError','SecurityError','InvalidStateError','DataError','UnknownError')
4442
+ enums.reason=['already-open','already-read','version-warning','empty','http','network','invalid-json','too-large','unavailable']
4443
+ const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel','storageChars','storageKeys','legacyCacheChars','legacyCacheKeys','historyCacheChars','sessionCacheChars','announcementChars','diagnosticChars','droppedEvents']
4444
+ const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable']
4445
+ const methods=new Set(['session.list','session.history','session.create','session.prompt','session.fork','session.cancel','session.rename','session.selectModel','session.updateQueue','session.getModels','session.getQueue','session.getCompactionStatus','workspace.list','workspace.create','workspace.archiveSession','host.describe','subagent.list','subagent.interrupt','goal.edit','goal.pause','goal.resume','goal.complete','goal.clear'])
4446
+ for(const method of ['session.models','llm.discoverModels','llm.providers','credentials.describe','credentials.set','credentials.unset','settings.describe','settings.mutate','settings.openDocument'])methods.add(method)
4447
+ const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
4448
+ const version=v=>typeof v==='string'&&/^\d+\.\d+\.\d+(?:[.-][a-zA-Z0-9.-]{1,30})?$/.test(v)?v:'unknown'
4449
+ function facts(input={}) {
4450
+ const out={}
4451
+ for(const [key,values]of Object.entries(enums))if(values.includes(input[key]))out[key]=input[key]
4452
+ for(const key of numbers)if(typeof input[key]==='number'&&Number.isFinite(input[key])&&input[key]>=0)out[key]=Math.min(input[key],Number.MAX_SAFE_INTEGER)
4453
+ for(const key of booleans)if(typeof input[key]==='boolean')out[key]=input[key]
4454
+ if(methods.has(input.method))out.method=input.method
4455
+ for(const key of ['sessionRef','serverRef','announcementRef'])if(hex(input[key],16))out[key]=input[key]
4456
+ if(hex(input.traceId,24))out.traceId=input.traceId
4457
+ if(Array.isArray(input.frames))out.frames=input.frames.slice(0,3).filter(f=>['app.js','desktop.js','history.js','activity.js','turn-results.js','network.js','operations.js','diagnostics.js'].includes(f?.file)&&Number.isSafeInteger(f.line)&&f.line>0&&Number.isSafeInteger(f.column)&&f.column>0).map(f=>({file:f.file,line:f.line,column:f.column}))
4458
+ return out
4459
+ }
4460
+ const critical=row=>row.kind==='client.error'||row.phase==='failed'
4461
+ function retain(events) {
4462
+ const errors=events.filter(critical).slice(-MAX_CRITICAL),keep=new Set([...events.slice(-(MAX_EVENTS-errors.length)),...errors])
4463
+ return events.filter(row=>keep.has(row))
4464
+ }
4465
+ function shrink(events,budget) {
4466
+ while(events.length&&JSON.stringify(events).length>budget){const index=events.findIndex(row=>!critical(row));events.splice(index<0?0:index,1)}
4467
+ return events
4468
+ }
4469
+ function sanitizeReport(input) {
4470
+ if(!input||input.schema!==1||!Array.isArray(input.events))return null
4471
+ const report={schema:1,reportId:hex(input.reportId,24)||'000000000000000000000000',capturedAt:typeof input.capturedAt==='number'&&Number.isFinite(input.capturedAt)?input.capturedAt:0,
4472
+ client:{version:version(input.client?.version),buildId:hex(input.client?.buildId,64)||'unknown',surface:['mobile','desktop'].includes(input.client?.surface)?input.client.surface:'mobile'},
4473
+ snapshot:facts(input.snapshot),events:[]}
4474
+ for(const item of input.events)if(item&&kinds.has(item.kind)&&typeof item.at==='number'&&Number.isFinite(item.at))report.events.push({at:item.at,kind:item.kind,...facts(item)})
4475
+ report.events=retain(report.events)
4476
+ if(input.persistence&&typeof input.persistence==='object'){
4477
+ report.persistence={}
4478
+ for(const key of ['local','session','indexeddb'])if(['unknown','saved','failed','unavailable','pending'].includes(input.persistence[key]))report.persistence[key]=input.persistence[key]
4479
+ }
4480
+ while(JSON.stringify(report).length>MAX_BYTES&&report.events.length){const index=report.events.findIndex(row=>!critical(row));report.events.splice(index<0?0:index,1)}
4481
+ return report
4482
+ }
4483
+ return {MAX_EVENTS,MAX_CRITICAL,MAX_BYTES,kinds,facts,sanitizeReport,retain,shrink,
4484
+ definition:{MAX_EVENTS,MAX_CRITICAL,MAX_BYTES,kinds:[...kinds],enums,numbers,booleans,methods:[...methods]}}
4485
+ }
4486
+ const clientDiagnosticSchema = createDiagnosticSchema()
4487
+ // END EMBEDDED CLIENT DIAGNOSTICS
4488
+
4268
4489
  function compatibilityDiagnostics() {
4269
4490
  const events = Object.fromEntries(Object.entries(eventCollectorState).map(([kind, state]) => [kind, {
4270
4491
  connected: state.connected === true,
@@ -4311,6 +4532,18 @@ function serveDiagnostics(req, res, url) {
4311
4532
  res.end(JSON.stringify(compatibilityDiagnostics()))
4312
4533
  }
4313
4534
 
4535
+ function feedbackDiagnosticSummary(client, gateway, crashes) {
4536
+ const summary={schema:2,gateway:gateway.gateway.version}
4537
+ if(client){
4538
+ summary.reportId=client.reportId;summary.client=client.client.version
4539
+ summary.storage={chars:client.snapshot.storageChars,legacy:client.snapshot.legacyCacheChars,keys:client.snapshot.legacyCacheKeys}
4540
+ summary.errors=client.events.filter(row=>row.phase==='failed'||row.kind==='client.error').slice(-2).map(row=>({kind:row.kind,error:row.errorName,status:row.httpStatus,...(row.frames?.[0]?{frame:row.frames[0]}:{})}))
4541
+ }
4542
+ if(crashes)summary.crashes=crashes.records
4543
+ while(JSON.stringify(summary).length>500){if(summary.crashes?.length)summary.crashes.shift();else if(summary.errors?.length)summary.errors.shift();else{delete summary.storage;break}}
4544
+ return JSON.stringify(summary)
4545
+ }
4546
+
4314
4547
  function serveFeedback(req, res, url) {
4315
4548
  cors(res)
4316
4549
  if (req.method === 'OPTIONS') {
@@ -4332,7 +4565,7 @@ function serveFeedback(req, res, url) {
4332
4565
  }
4333
4566
  touchDevice(req)
4334
4567
 
4335
- withRequestBody(req, res, 16 * 1024, async body => {
4568
+ withRequestBody(req, res, 256 * 1024, async body => {
4336
4569
  let payload
4337
4570
  try {
4338
4571
  payload = JSON.parse(body || '{}')
@@ -4348,6 +4581,12 @@ function serveFeedback(req, res, url) {
4348
4581
  const appVersion = String(payload.appVersion || '').trim()
4349
4582
  const includeDiagnostics = payload.includeDiagnostics === true
4350
4583
  const includeCrashLogs = payload.includeCrashLogs === true
4584
+ const clientDiagnostics=includeDiagnostics&&payload.clientDiagnostics?clientDiagnosticSchema.sanitizeReport(payload.clientDiagnostics):null
4585
+ if(includeDiagnostics&&payload.clientDiagnostics&&!clientDiagnostics){
4586
+ res.writeHead(400,{'content-type':'application/json; charset=utf-8'})
4587
+ res.end(JSON.stringify({error:'invalid client diagnostics'}))
4588
+ return
4589
+ }
4351
4590
  if (!['bug', 'suggestion', 'other', 'poll'].includes(type)) {
4352
4591
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
4353
4592
  res.end(JSON.stringify({ error: 'invalid type', expect: 'bug|suggestion|other|poll' }))
@@ -4374,9 +4613,10 @@ function serveFeedback(req, res, url) {
4374
4613
  res.end(JSON.stringify({ error: 'message required' }))
4375
4614
  return
4376
4615
  }
4377
- if (message.length > 2000) {
4616
+ const messageLimit = type === 'poll' ? 2000 : 20000
4617
+ if (message.length > messageLimit) {
4378
4618
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
4379
- res.end(JSON.stringify({ error: 'message too long', max: 2000 }))
4619
+ res.end(JSON.stringify({ error: 'message too long', max: messageLimit }))
4380
4620
  return
4381
4621
  }
4382
4622
  if (contact.length > 200) {
@@ -4396,37 +4636,52 @@ function serveFeedback(req, res, url) {
4396
4636
 
4397
4637
  // 转发收集器(收集器服务端已做校验/节流/落盘)。节流只在收集器确认成功后占位,
4398
4638
  // 失败(429/502/网络错误)不占位, 用户可立即重试。
4399
- fetch(FEEDBACK_URL, {
4400
- method: 'POST',
4401
- headers: { 'content-type': 'application/json' },
4402
- body: JSON.stringify({
4639
+ const gatewayDiagnostics=includeDiagnostics?compatibilityDiagnostics():null
4640
+ const crashes=includeCrashLogs?crashUploadSummary():null
4641
+ const outbound={
4403
4642
  type,
4404
4643
  message,
4405
4644
  contact: contact || undefined,
4406
4645
  appVersion: appVersion || 'unknown',
4407
4646
  gatewayVersion: VERSION,
4408
4647
  clientIp: maskIp(ip),
4409
- ...(includeDiagnostics ? { diagnostics: compatibilityDiagnostics() } : {}),
4410
- ...(includeCrashLogs ? { serverInfo: JSON.stringify(crashUploadSummary()) } : {}),
4648
+ ...(includeDiagnostics ? { includeDiagnostics:true,diagnostics: gatewayDiagnostics, ...(clientDiagnostics?{clientDiagnostics}:{}) } : {}),
4649
+ ...(includeDiagnostics ? {serverInfo:feedbackDiagnosticSummary(clientDiagnostics,gatewayDiagnostics,crashes)} : crashes?{serverInfo:JSON.stringify(crashes)}:{}),
4411
4650
  ...(pollVote || {})
4412
- }),
4413
- signal: AbortSignal.timeout(8000)
4414
- }).then(async (r) => {
4415
- const data = await r.json().catch(() => ({}))
4651
+ }
4652
+ const deadline = Date.now() + FEEDBACK_FORWARD_TIMEOUT_MS
4653
+ const send=body=>fetch(FEEDBACK_URL,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body),signal:AbortSignal.timeout(Math.max(1, deadline - Date.now()))})
4654
+ send(outbound).then(async (r) => {
4655
+ let data = await r.json().catch(() => ({}))
4656
+ // A size rejection happens before acceptance. Retry only this explicit
4657
+ // rejection with the legacy summary; never retry an uncertain network send.
4658
+ if(clientDiagnostics&&(r.status===413||r.status===400&&data.error==='bad body size')){
4659
+ const {clientDiagnostics:ignoredClient,diagnostics:ignoredGateway,includeDiagnostics:ignoredConsent,...brief}=outbound
4660
+ r=await send(brief);data=await r.json().catch(()=>({}))
4661
+ }
4416
4662
  if (r.status === 429) {
4417
4663
  res.writeHead(429, { 'content-type': 'application/json; charset=utf-8' })
4418
4664
  res.end(JSON.stringify({ error: 'rate_limited' }))
4665
+ } else if (r.status === 413 || r.status === 400 && data.error === 'bad body size') {
4666
+ res.writeHead(413, { 'content-type': 'application/json; charset=utf-8' })
4667
+ res.end(JSON.stringify({ error: 'collector-body-limit' }))
4668
+ } else if (r.status === 400 && (/message.*(?:<=|≤)\s*2000/i.test(String(data.error || '')) || Number.isSafeInteger(data.max) && data.max > 0 && data.max < message.length)) {
4669
+ res.writeHead(413, { 'content-type': 'application/json; charset=utf-8' })
4670
+ res.end(JSON.stringify({ error: 'collector-message-limit', max: Number.isSafeInteger(data.max) ? data.max : 2000 }))
4671
+ } else if (r.ok && data.ok && data.messageSha256 && data.messageSha256 !== crypto.createHash('sha256').update(message).digest('hex')) {
4672
+ res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
4673
+ res.end(JSON.stringify({ error: 'feedback-content-unconfirmed' }))
4419
4674
  } else if (r.ok && data.ok) {
4420
4675
  feedbackThrottle.set(ip, now)
4421
4676
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
4422
- res.end(JSON.stringify({ ok: true }))
4677
+ res.end(JSON.stringify({ ok: true,...(clientDiagnostics?{diagnostics:{reportId:clientDiagnostics.reportId,saved:data.clientDiagnosticsReceived===clientDiagnostics.reportId}}:{}) }))
4423
4678
  } else {
4424
4679
  res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
4425
4680
  res.end(JSON.stringify({ error: 'upstream_error' }))
4426
4681
  }
4427
4682
  }).catch(() => {
4428
4683
  res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
4429
- res.end(JSON.stringify({ error: 'feedback_service_unavailable' }))
4684
+ res.end(JSON.stringify({ error: 'feedback_service_unavailable', uncertain: true }))
4430
4685
  })
4431
4686
  })
4432
4687
  }
@@ -4532,6 +4787,18 @@ function gatewayRuntimeIdentity() {
4532
4787
 
4533
4788
  async function serveAdminApi(req, res, url) {
4534
4789
  const sub = url.pathname.slice('/admin/api'.length) || '/'
4790
+ if (sub === '/lan') {
4791
+ const reply = (status, body) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(body)) }
4792
+ if (!adminAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
4793
+ if (req.method === 'GET') return reply(200, { ok: true, ...lanPairing.status() })
4794
+ if (req.method !== 'POST') return reply(405, { error: 'POST_REQUIRED' })
4795
+ try {
4796
+ const input = JSON.parse(await readBody(req, 1024))
4797
+ if (typeof input?.enabled !== 'boolean') return reply(400, { error: 'BAD_REQUEST' })
4798
+ if (!input.enabled) { lanPairing.close(); return reply(200, { ok: true, ...lanPairing.status() }) }
4799
+ return reply(200, { ok: true, ...await lanPairing.open() })
4800
+ } catch (err) { return reply(err.status || 400, { error: err.code || 'PAIRING_FAILED' }) }
4801
+ }
4535
4802
  // 实际进程信息只通过认证管理接口返回,公共 /health 不暴露本机解释器路径。
4536
4803
  if (sub === '/runtime') {
4537
4804
  const reply = (status, body) => {
@@ -4642,6 +4909,7 @@ async function serveAdminApi(req, res, url) {
4642
4909
  return send(500, { error: 'write-failed', detail: '无法保存独立设备密钥设置' })
4643
4910
  }
4644
4911
  wsTickets.clear()
4912
+ lanPairing.close()
4645
4913
  const disconnected = kickRemoteClients()
4646
4914
  return send(200, { ok: true, disconnected, deviceKeys: deviceKeysPayload() })
4647
4915
  }
@@ -5991,17 +6259,7 @@ const ADAPTIVE_RPC_METHODS = new Set([
5991
6259
  ])
5992
6260
 
5993
6261
  function readApiRequest(req, maxBytes = 4 * 1024 * 1024) {
5994
- return new Promise((resolve, reject) => {
5995
- let raw = ''
5996
- req.setEncoding('utf8')
5997
- req.on('data', chunk => {
5998
- raw += chunk
5999
- if (Buffer.byteLength(raw) > maxBytes) reject(new Error('request body too large'))
6000
- })
6001
- req.once('end', () => resolve(raw))
6002
- req.once('error', reject)
6003
- req.once('aborted', () => reject(new Error('request aborted')))
6004
- })
6262
+ return readBody(req, maxBytes)
6005
6263
  }
6006
6264
 
6007
6265
  // Only the explicit pre-admission image rejection is safe to retry. Never retry
@@ -6217,7 +6475,7 @@ async function serveOperations(req, res, url) {
6217
6475
  let old = loadOperation(key)
6218
6476
  if (req.method === 'GET') return old ? reply(200, operationSnapshot(old)) : reply(404, { error: 'operation-not-found' })
6219
6477
  let body
6220
- try { body = JSON.parse(await readApiRequest(req)) } catch { return reply(400, { error: 'bad-operation' }) }
6478
+ try { body = JSON.parse(await readApiRequest(req)) } catch (error) { return reply(error.status === 413 ? 413 : 400, { error: error.status === 413 ? 'body-too-large' : 'bad-operation' }) }
6221
6479
  if (!OPERATION_METHODS.has(body?.method) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) {
6222
6480
  return reply(400, { error: 'unsupported-operation' })
6223
6481
  }
@@ -6333,9 +6591,9 @@ async function proxyModernApi(req, res, url) {
6333
6591
  } catch (error) {
6334
6592
  if (!res.headersSent) {
6335
6593
  cors(res)
6336
- res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
6594
+ res.writeHead(error.status === 413 ? 413 : 502, { 'content-type': 'application/json; charset=utf-8' })
6337
6595
  }
6338
- if (!res.writableEnded) res.end(JSON.stringify({ error: 'upstream-incompatible', detail: String(error?.message || error) }))
6596
+ if (!res.writableEnded) res.end(JSON.stringify(error.status === 413 ? { error: 'body-too-large', max: 4 * 1024 * 1024 } : { error: 'upstream-incompatible', detail: String(error?.message || error) }))
6339
6597
  return true
6340
6598
  }
6341
6599
  }
@@ -6383,7 +6641,7 @@ async function proxyLegacyApi(req, res, url) {
6383
6641
  upstreamRes.pipe(res)
6384
6642
  })
6385
6643
 
6386
- const requestTimeout = ['/api/session.export', '/remote/api/command'].includes(url.pathname)
6644
+ const requestTimeout = ['/api/session.export', '/remote/api/command', '/remote/api/plugins/preflight'].includes(url.pathname)
6387
6645
  ? Math.max(UPSTREAM_REQUEST_TIMEOUT_MS, 130000) : UPSTREAM_REQUEST_TIMEOUT_MS
6388
6646
  upstreamReq.setTimeout(requestTimeout, () => {
6389
6647
  upstreamReq.destroy(new Error('upstream request timeout'))
@@ -6436,8 +6694,8 @@ function proxyApi(req, res, url) {
6436
6694
  if (!handled) return proxyLegacyApi(req, res, url)
6437
6695
  }).catch(error => {
6438
6696
  cors(res)
6439
- if (!res.headersSent) res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
6440
- if (!res.writableEnded) res.end(JSON.stringify({ error: 'upstream-unreachable', detail: String(error?.message || error) }))
6697
+ if (!res.headersSent) res.writeHead(error.status === 413 ? 413 : 502, { 'content-type': 'application/json; charset=utf-8' })
6698
+ if (!res.writableEnded) res.end(JSON.stringify(error.status === 413 ? { error: 'body-too-large', max: 4 * 1024 * 1024 } : { error: 'upstream-unreachable', detail: String(error?.message || error) }))
6441
6699
  })
6442
6700
  }
6443
6701
 
@@ -6760,6 +7018,7 @@ function lanAddresses() {
6760
7018
  const server = http.createServer(async (req, res) => {
6761
7019
  try {
6762
7020
  const url = new URL(req.url, 'http://dsh-remote.local')
7021
+ if (url.pathname === '/api/lan-pair') return await serveLanPair(req, res)
6763
7022
  if (url.pathname === '/api/file-inbox' || url.pathname.startsWith('/api/file-inbox/') || url.pathname === '/fs/inbox-file' || url.pathname === '/admin/api/file-inbox') return await serveFileInbox(req, res, url)
6764
7023
  if (url.pathname === '/relay') return await serveRelaySettings(req, res, url)
6765
7024
  if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)