dsh-remote-plugin 0.8.1 → 0.8.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.
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
@@ -1291,6 +1291,126 @@ function restoreMissingTokenFile() {
1291
1291
  const WS_TICKET_TTL_MS = durationEnv('GATEWAY_WS_TICKET_TTL_MS', 90000, 10000, 10 * 60 * 1000)
1292
1292
  const wsTickets = new Map()
1293
1293
 
1294
+ // BEGIN EMBEDDED LAN PAIRING
1295
+ function createLanPairing(options) {
1296
+ const crypto = require('node:crypto'), dgram = require('node:dgram')
1297
+ const clock = options.clock || Date.now
1298
+ const instanceId = crypto.randomBytes(16).toString('hex')
1299
+ let secret = null, expiresAt = 0, socket = null, timer = null, failures = 0, error = '', revision = 0
1300
+ const challenges = new Map(), peers = new Map()
1301
+ const fail = (status, code) => { throw Object.assign(new Error(code), { status, code }) }
1302
+ const localPeer = address => {
1303
+ const ip = String(address || '').replace(/^::ffff:/, '')
1304
+ if (ip === '::1' || /^(fc|fd)[0-9a-f]{2}:/i.test(ip) || /^fe[89ab][0-9a-f]:/i.test(ip)) return true
1305
+ if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) return false
1306
+ const bytes = ip.split('.').map(Number)
1307
+ if (bytes.length !== 4 || bytes.some(n => !Number.isInteger(n) || n < 0 || n > 255)) return false
1308
+ return bytes[0] === 10 || bytes[0] === 127 || bytes[0] === 192 && bytes[1] === 168
1309
+ || bytes[0] === 172 && bytes[1] >= 16 && bytes[1] <= 31 || bytes[0] === 169 && bytes[1] === 254
1310
+ }
1311
+ const active = () => !!secret && clock() < expiresAt && options.deviceMode()
1312
+ const status = () => ({ supported: true, enabled: active() && !!socket, expiresAt: active() ? expiresAt : 0,
1313
+ port: Number(options.discoveryPort || 8788), error })
1314
+ function close() {
1315
+ revision++
1316
+ secret = null; expiresAt = 0; challenges.clear(); peers.clear()
1317
+ clearTimeout(timer); timer = null
1318
+ if (socket) { try { socket.close() } catch {} socket = null }
1319
+ }
1320
+ async function open() {
1321
+ close(); error = ''
1322
+ const openingRevision = revision
1323
+ if (!options.deviceMode()) fail(409, 'DEVICE_KEYS_REQUIRED')
1324
+ if (options.host === '127.0.0.1' || options.host === '::1') fail(409, 'LAN_LISTENER_REQUIRED')
1325
+ const code = crypto.randomBytes(10).toString('hex').toUpperCase()
1326
+ secret = crypto.createHash('sha256').update(code).digest(); failures = 0
1327
+ expiresAt = clock() + 10 * 60 * 1000
1328
+ const candidate = dgram.createSocket('udp4')
1329
+ try {
1330
+ await new Promise((resolve, reject) => {
1331
+ candidate.once('error', reject)
1332
+ candidate.bind(Number(options.discoveryPort || 8788), options.discoveryHost || '0.0.0.0', () => {
1333
+ candidate.removeListener('error', reject); resolve()
1334
+ })
1335
+ })
1336
+ } catch {
1337
+ try { candidate.close() } catch {}
1338
+ if (revision === openingRevision) { close(); error = 'DISCOVERY_PORT_UNAVAILABLE' }
1339
+ fail(503, 'DISCOVERY_PORT_UNAVAILABLE')
1340
+ }
1341
+ if (revision !== openingRevision) { try { candidate.close() } catch {} fail(409, 'PAIRING_CLOSED') }
1342
+ socket = candidate
1343
+ socket.on('error', () => { close(); error = 'DISCOVERY_SOCKET_FAILED' })
1344
+ socket.on('message', (message, peer) => {
1345
+ if (!active() || !localPeer(peer.address) || message.length < 256 || message.length > 512) return
1346
+ let query
1347
+ try { query = JSON.parse(message.toString('utf8')) } catch { return }
1348
+ if (query?.type !== 'dsh-remote-discover' || query.version !== 1 || !/^[a-f0-9]{32}$/.test(query.nonce)) return
1349
+ const now = clock(), previous = peers.get(peer.address)
1350
+ if (previous && now - previous.at < 500) return
1351
+ if (peers.size >= 128 && !peers.has(peer.address)) return
1352
+ peers.set(peer.address, { at: now, count: previous?.count || 0 })
1353
+ const reply = Buffer.from(JSON.stringify({ type: 'dsh-remote-host', version: 1, nonce: query.nonce,
1354
+ instanceId, name: String(options.name || 'DSH Remote').slice(0, 40), port: options.port }))
1355
+ if (reply.length <= message.length) candidate.send(reply, peer.port, peer.address, () => {})
1356
+ })
1357
+ timer = setTimeout(close, 10 * 60 * 1000); timer.unref?.()
1358
+ socket.unref?.()
1359
+ return { ...status(), code: code.match(/.{4}/g).join('-') }
1360
+ }
1361
+ const proof = (role, transcript) => crypto.createHmac('sha256', secret).update(role + '\n' + transcript).digest('hex')
1362
+ function pair(address, input) {
1363
+ address = String(address || '').replace(/^::ffff:/, '')
1364
+ if (!localPeer(address)) fail(403, 'LAN_ONLY')
1365
+ if (!active()) { close(); fail(410, 'PAIRING_CLOSED') }
1366
+ if (!input || typeof input !== 'object' || Array.isArray(input)) fail(400, 'BAD_REQUEST')
1367
+ const now = clock()
1368
+ for (const [id, challenge] of challenges) if (challenge.expires <= now) challenges.delete(id)
1369
+ if (input.step === 'hello') {
1370
+ const limit = peers.get(address) || { at: 0, count: 0 }
1371
+ if (limit.count >= 12 || challenges.size >= 32 || peers.size >= 128 && !peers.has(address)) fail(429, 'PAIRING_RATE_LIMIT')
1372
+ peers.set(address, { ...limit, count: limit.count + 1 })
1373
+ if (input.instanceId !== instanceId || !/^[a-f0-9]{32}$/.test(input.nonce || '')
1374
+ || typeof input.clientPublic !== 'string' || input.clientPublic.length > 200
1375
+ || !/^[A-Za-z0-9+/]+={0,2}$/.test(input.clientPublic)
1376
+ || Buffer.from(input.clientPublic, 'base64').toString('base64') !== input.clientPublic) fail(400, 'BAD_REQUEST')
1377
+ let clientKey, shared
1378
+ const keys = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
1379
+ try {
1380
+ clientKey = crypto.createPublicKey({ key: Buffer.from(input.clientPublic, 'base64'), format: 'der', type: 'spki' })
1381
+ if (clientKey.asymmetricKeyType !== 'ec' || clientKey.asymmetricKeyDetails?.namedCurve !== 'prime256v1') fail(400, 'BAD_KEY')
1382
+ shared = crypto.diffieHellman({ privateKey: keys.privateKey, publicKey: clientKey })
1383
+ } catch { fail(400, 'BAD_KEY') }
1384
+ const serverPublic = keys.publicKey.export({ format: 'der', type: 'spki' }).toString('base64')
1385
+ const challengeId = crypto.randomBytes(16).toString('hex')
1386
+ const transcript = ['dsh-lan-v1', instanceId, challengeId, input.nonce, input.clientPublic, serverPublic].join('\n')
1387
+ challenges.set(challengeId, { address, shared, transcript, expires: now + 30000 })
1388
+ return { challengeId, serverPublic, serverProof: proof('server', transcript) }
1389
+ }
1390
+ if (input.step !== 'finish') fail(400, 'BAD_REQUEST')
1391
+ const challenge = challenges.get(input.challengeId)
1392
+ challenges.delete(input.challengeId) // A challenge can be used only once, including failed attempts.
1393
+ if (!challenge || challenge.address !== address || challenge.expires <= now) fail(410, 'CHALLENGE_EXPIRED')
1394
+ const expected = proof('client', challenge.transcript), supplied = String(input.proof || '')
1395
+ if (!/^[a-f0-9]{64}$/.test(supplied) || !crypto.timingSafeEqual(Buffer.from(supplied), Buffer.from(expected))) {
1396
+ failures++; if (failures >= 10) close()
1397
+ fail(401, 'PAIRING_CODE_INVALID')
1398
+ }
1399
+ const entry = options.issueDevice()
1400
+ if (!entry) fail(503, 'DEVICE_KEY_WRITE_FAILED')
1401
+ const key = crypto.createHmac('sha256', secret).update('key\n' + challenge.transcript + '\n').update(challenge.shared).digest()
1402
+ const iv = crypto.randomBytes(12), cipher = crypto.createCipheriv('aes-256-gcm', key, iv)
1403
+ cipher.setAAD(Buffer.from(challenge.transcript))
1404
+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify({ token: entry.token, deviceId: entry.id })), cipher.final()])
1405
+ const result = { iv: iv.toString('base64'), ciphertext: ciphertext.toString('base64'), tag: cipher.getAuthTag().toString('base64') }
1406
+ close() // Successful pairing closes discovery and the one-time code.
1407
+ return result
1408
+ }
1409
+ return { open, close, status, pair, localPeer }
1410
+ }
1411
+
1412
+ // END EMBEDDED LAN PAIRING
1413
+
1294
1414
  function newAccessToken() {
1295
1415
  return crypto.randomBytes(24).toString('base64url')
1296
1416
  }
@@ -1378,6 +1498,29 @@ function deviceKeyViews() {
1378
1498
  return deviceKeyState.keys.map(record => ({ ...record }))
1379
1499
  }
1380
1500
 
1501
+ const lanPairing = createLanPairing({
1502
+ host: HOST, port: PORT, name: os.hostname(),
1503
+ discoveryPort: Number(process.env.DSH_REMOTE_DISCOVERY_PORT) || 8788,
1504
+ deviceMode: () => deviceKeyState.enabled,
1505
+ issueDevice: () => deviceKeyState.enabled && deviceKeyState.keys.length < 100 ? createDeviceKey('局域网配对设备') : null,
1506
+ })
1507
+
1508
+ async function serveLanPair(req, res) {
1509
+ cors(res)
1510
+ const reply = (status, body) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(body)) }
1511
+ if (req.headers.origin && !res.getHeader('access-control-allow-origin')) return reply(403, { error: 'ORIGIN_DENIED' })
1512
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
1513
+ if (req.method !== 'POST') return reply(405, { error: 'POST_REQUIRED' })
1514
+ if (!lanPairing.localPeer(req.socket.remoteAddress)) return reply(403, { error: 'LAN_ONLY' })
1515
+ if (!String(req.headers['content-type'] || '').startsWith('application/json')) return reply(415, { error: 'JSON_REQUIRED' })
1516
+ try {
1517
+ const body = await readBody(req, 2048)
1518
+ let input
1519
+ try { input = JSON.parse(body) } catch { return reply(400, { error: 'BAD_REQUEST' }) }
1520
+ return reply(200, lanPairing.pair(req.socket.remoteAddress, input))
1521
+ } catch (err) { return reply(err.status || 400, { error: err.code || 'PAIRING_FAILED' }) }
1522
+ }
1523
+
1381
1524
  function findDeviceKeyByToken(value) {
1382
1525
  return deviceKeyState.keys.find(record => safeTokenEqual(value, record.token)) || null
1383
1526
  }
@@ -1410,6 +1553,7 @@ function rotateToken() {
1410
1553
  return { error: 'write-failed', detail: err.message }
1411
1554
  }
1412
1555
  TOKEN = next
1556
+ lanPairing.close()
1413
1557
  wsTickets.clear()
1414
1558
  return { ok: true, token: next }
1415
1559
  }
@@ -3230,6 +3374,12 @@ function broadcastCollectorFrame(kind, raw) {
3230
3374
 
3231
3375
  function pushEvent(kind, full, raw = JSON.stringify(full)) {
3232
3376
  if (!eventBuffers[kind] || !full || typeof full !== 'object') return
3377
+ if (kind === 'host' && ['host/session-status', 'host/agent-error'].includes(full.payload?.type)) {
3378
+ // One delivery identity for the same host lifecycle event over WS and poll.
3379
+ // Upstream rpcId may identify a stream and must not be used as an event ID.
3380
+ full = { ...full, remoteEventId: `${EVENT_STREAM_EPOCH}:${kind}:${eventNextSeq[kind]}` }
3381
+ raw = JSON.stringify(full)
3382
+ }
3233
3383
  if (eventCollectorState[kind]) eventCollectorState[kind].lastEventAt = Date.now()
3234
3384
  const buf = eventBuffers[kind]
3235
3385
  buf.push({ seq: eventNextSeq[kind]++, ts: Date.now(), event: truncateEventValue(full) })
@@ -4265,6 +4415,66 @@ async function validatePollVote(payload) {
4265
4415
  return result
4266
4416
  }
4267
4417
 
4418
+ // BEGIN EMBEDDED CLIENT DIAGNOSTICS
4419
+ function createDiagnosticSchema() {
4420
+ const MAX_EVENTS=160,MAX_CRITICAL=40,MAX_BYTES=48000
4421
+ 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'])
4422
+ 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']}
4423
+ enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
4424
+ enums.storageKey=['seen','history','votes']
4425
+ enums.storageBackend=['session','memory']
4426
+ enums.storageBackend.push('local','indexeddb')
4427
+ enums.storageKey.push('settings','session-list','diagnostics','approvals','receipts')
4428
+ enums.phase.push('received','shown','dismissed','acknowledged','skipped')
4429
+ enums.category.push('storage','validation')
4430
+ enums.errorName.push('QuotaExceededError','SecurityError','InvalidStateError','DataError','UnknownError')
4431
+ enums.reason=['already-open','already-read','version-warning','empty','http','network','invalid-json','too-large','unavailable']
4432
+ const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel','storageChars','storageKeys','legacyCacheChars','legacyCacheKeys','historyCacheChars','sessionCacheChars','announcementChars','diagnosticChars','droppedEvents']
4433
+ const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable']
4434
+ 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'])
4435
+ 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)
4436
+ const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
4437
+ const version=v=>typeof v==='string'&&/^\d+\.\d+\.\d+(?:[.-][a-zA-Z0-9.-]{1,30})?$/.test(v)?v:'unknown'
4438
+ function facts(input={}) {
4439
+ const out={}
4440
+ for(const [key,values]of Object.entries(enums))if(values.includes(input[key]))out[key]=input[key]
4441
+ 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)
4442
+ for(const key of booleans)if(typeof input[key]==='boolean')out[key]=input[key]
4443
+ if(methods.has(input.method))out.method=input.method
4444
+ for(const key of ['sessionRef','serverRef','announcementRef'])if(hex(input[key],16))out[key]=input[key]
4445
+ if(hex(input.traceId,24))out.traceId=input.traceId
4446
+ 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}))
4447
+ return out
4448
+ }
4449
+ const critical=row=>row.kind==='client.error'||row.phase==='failed'
4450
+ function retain(events) {
4451
+ const errors=events.filter(critical).slice(-MAX_CRITICAL),keep=new Set([...events.slice(-(MAX_EVENTS-errors.length)),...errors])
4452
+ return events.filter(row=>keep.has(row))
4453
+ }
4454
+ function shrink(events,budget) {
4455
+ while(events.length&&JSON.stringify(events).length>budget){const index=events.findIndex(row=>!critical(row));events.splice(index<0?0:index,1)}
4456
+ return events
4457
+ }
4458
+ function sanitizeReport(input) {
4459
+ if(!input||input.schema!==1||!Array.isArray(input.events))return null
4460
+ const report={schema:1,reportId:hex(input.reportId,24)||'000000000000000000000000',capturedAt:typeof input.capturedAt==='number'&&Number.isFinite(input.capturedAt)?input.capturedAt:0,
4461
+ client:{version:version(input.client?.version),buildId:hex(input.client?.buildId,64)||'unknown',surface:['mobile','desktop'].includes(input.client?.surface)?input.client.surface:'mobile'},
4462
+ snapshot:facts(input.snapshot),events:[]}
4463
+ 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)})
4464
+ report.events=retain(report.events)
4465
+ if(input.persistence&&typeof input.persistence==='object'){
4466
+ report.persistence={}
4467
+ for(const key of ['local','session','indexeddb'])if(['unknown','saved','failed','unavailable','pending'].includes(input.persistence[key]))report.persistence[key]=input.persistence[key]
4468
+ }
4469
+ 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)}
4470
+ return report
4471
+ }
4472
+ return {MAX_EVENTS,MAX_CRITICAL,MAX_BYTES,kinds,facts,sanitizeReport,retain,shrink,
4473
+ definition:{MAX_EVENTS,MAX_CRITICAL,MAX_BYTES,kinds:[...kinds],enums,numbers,booleans,methods:[...methods]}}
4474
+ }
4475
+ const clientDiagnosticSchema = createDiagnosticSchema()
4476
+ // END EMBEDDED CLIENT DIAGNOSTICS
4477
+
4268
4478
  function compatibilityDiagnostics() {
4269
4479
  const events = Object.fromEntries(Object.entries(eventCollectorState).map(([kind, state]) => [kind, {
4270
4480
  connected: state.connected === true,
@@ -4311,6 +4521,18 @@ function serveDiagnostics(req, res, url) {
4311
4521
  res.end(JSON.stringify(compatibilityDiagnostics()))
4312
4522
  }
4313
4523
 
4524
+ function feedbackDiagnosticSummary(client, gateway, crashes) {
4525
+ const summary={schema:2,gateway:gateway.gateway.version}
4526
+ if(client){
4527
+ summary.reportId=client.reportId;summary.client=client.client.version
4528
+ summary.storage={chars:client.snapshot.storageChars,legacy:client.snapshot.legacyCacheChars,keys:client.snapshot.legacyCacheKeys}
4529
+ 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]}:{})}))
4530
+ }
4531
+ if(crashes)summary.crashes=crashes.records
4532
+ 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}}
4533
+ return JSON.stringify(summary)
4534
+ }
4535
+
4314
4536
  function serveFeedback(req, res, url) {
4315
4537
  cors(res)
4316
4538
  if (req.method === 'OPTIONS') {
@@ -4332,7 +4554,7 @@ function serveFeedback(req, res, url) {
4332
4554
  }
4333
4555
  touchDevice(req)
4334
4556
 
4335
- withRequestBody(req, res, 16 * 1024, async body => {
4557
+ withRequestBody(req, res, 96 * 1024, async body => {
4336
4558
  let payload
4337
4559
  try {
4338
4560
  payload = JSON.parse(body || '{}')
@@ -4348,6 +4570,12 @@ function serveFeedback(req, res, url) {
4348
4570
  const appVersion = String(payload.appVersion || '').trim()
4349
4571
  const includeDiagnostics = payload.includeDiagnostics === true
4350
4572
  const includeCrashLogs = payload.includeCrashLogs === true
4573
+ const clientDiagnostics=includeDiagnostics&&payload.clientDiagnostics?clientDiagnosticSchema.sanitizeReport(payload.clientDiagnostics):null
4574
+ if(includeDiagnostics&&payload.clientDiagnostics&&!clientDiagnostics){
4575
+ res.writeHead(400,{'content-type':'application/json; charset=utf-8'})
4576
+ res.end(JSON.stringify({error:'invalid client diagnostics'}))
4577
+ return
4578
+ }
4351
4579
  if (!['bug', 'suggestion', 'other', 'poll'].includes(type)) {
4352
4580
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
4353
4581
  res.end(JSON.stringify({ error: 'invalid type', expect: 'bug|suggestion|other|poll' }))
@@ -4396,30 +4624,35 @@ function serveFeedback(req, res, url) {
4396
4624
 
4397
4625
  // 转发收集器(收集器服务端已做校验/节流/落盘)。节流只在收集器确认成功后占位,
4398
4626
  // 失败(429/502/网络错误)不占位, 用户可立即重试。
4399
- fetch(FEEDBACK_URL, {
4400
- method: 'POST',
4401
- headers: { 'content-type': 'application/json' },
4402
- body: JSON.stringify({
4627
+ const gatewayDiagnostics=includeDiagnostics?compatibilityDiagnostics():null
4628
+ const crashes=includeCrashLogs?crashUploadSummary():null
4629
+ const outbound={
4403
4630
  type,
4404
4631
  message,
4405
4632
  contact: contact || undefined,
4406
4633
  appVersion: appVersion || 'unknown',
4407
4634
  gatewayVersion: VERSION,
4408
4635
  clientIp: maskIp(ip),
4409
- ...(includeDiagnostics ? { diagnostics: compatibilityDiagnostics() } : {}),
4410
- ...(includeCrashLogs ? { serverInfo: JSON.stringify(crashUploadSummary()) } : {}),
4636
+ ...(includeDiagnostics ? { includeDiagnostics:true,diagnostics: gatewayDiagnostics, ...(clientDiagnostics?{clientDiagnostics}:{}) } : {}),
4637
+ ...(includeDiagnostics ? {serverInfo:feedbackDiagnosticSummary(clientDiagnostics,gatewayDiagnostics,crashes)} : crashes?{serverInfo:JSON.stringify(crashes)}:{}),
4411
4638
  ...(pollVote || {})
4412
- }),
4413
- signal: AbortSignal.timeout(8000)
4414
- }).then(async (r) => {
4415
- const data = await r.json().catch(() => ({}))
4639
+ }
4640
+ const send=body=>fetch(FEEDBACK_URL,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body),signal:AbortSignal.timeout(8000)})
4641
+ send(outbound).then(async (r) => {
4642
+ let data = await r.json().catch(() => ({}))
4643
+ // A size rejection happens before acceptance. Retry only this explicit
4644
+ // rejection with the legacy summary; never retry an uncertain network send.
4645
+ if(clientDiagnostics&&(r.status===413||r.status===400&&data.error==='bad body size')){
4646
+ const {clientDiagnostics:ignoredClient,diagnostics:ignoredGateway,includeDiagnostics:ignoredConsent,...brief}=outbound
4647
+ r=await send(brief);data=await r.json().catch(()=>({}))
4648
+ }
4416
4649
  if (r.status === 429) {
4417
4650
  res.writeHead(429, { 'content-type': 'application/json; charset=utf-8' })
4418
4651
  res.end(JSON.stringify({ error: 'rate_limited' }))
4419
4652
  } else if (r.ok && data.ok) {
4420
4653
  feedbackThrottle.set(ip, now)
4421
4654
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
4422
- res.end(JSON.stringify({ ok: true }))
4655
+ res.end(JSON.stringify({ ok: true,...(clientDiagnostics?{diagnostics:{reportId:clientDiagnostics.reportId,saved:data.clientDiagnosticsReceived===clientDiagnostics.reportId}}:{}) }))
4423
4656
  } else {
4424
4657
  res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
4425
4658
  res.end(JSON.stringify({ error: 'upstream_error' }))
@@ -4532,6 +4765,18 @@ function gatewayRuntimeIdentity() {
4532
4765
 
4533
4766
  async function serveAdminApi(req, res, url) {
4534
4767
  const sub = url.pathname.slice('/admin/api'.length) || '/'
4768
+ if (sub === '/lan') {
4769
+ const reply = (status, body) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(body)) }
4770
+ if (!adminAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
4771
+ if (req.method === 'GET') return reply(200, { ok: true, ...lanPairing.status() })
4772
+ if (req.method !== 'POST') return reply(405, { error: 'POST_REQUIRED' })
4773
+ try {
4774
+ const input = JSON.parse(await readBody(req, 1024))
4775
+ if (typeof input?.enabled !== 'boolean') return reply(400, { error: 'BAD_REQUEST' })
4776
+ if (!input.enabled) { lanPairing.close(); return reply(200, { ok: true, ...lanPairing.status() }) }
4777
+ return reply(200, { ok: true, ...await lanPairing.open() })
4778
+ } catch (err) { return reply(err.status || 400, { error: err.code || 'PAIRING_FAILED' }) }
4779
+ }
4535
4780
  // 实际进程信息只通过认证管理接口返回,公共 /health 不暴露本机解释器路径。
4536
4781
  if (sub === '/runtime') {
4537
4782
  const reply = (status, body) => {
@@ -4642,6 +4887,7 @@ async function serveAdminApi(req, res, url) {
4642
4887
  return send(500, { error: 'write-failed', detail: '无法保存独立设备密钥设置' })
4643
4888
  }
4644
4889
  wsTickets.clear()
4890
+ lanPairing.close()
4645
4891
  const disconnected = kickRemoteClients()
4646
4892
  return send(200, { ok: true, disconnected, deviceKeys: deviceKeysPayload() })
4647
4893
  }
@@ -6760,6 +7006,7 @@ function lanAddresses() {
6760
7006
  const server = http.createServer(async (req, res) => {
6761
7007
  try {
6762
7008
  const url = new URL(req.url, 'http://dsh-remote.local')
7009
+ if (url.pathname === '/api/lan-pair') return await serveLanPair(req, res)
6763
7010
  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
7011
  if (url.pathname === '/relay') return await serveRelaySettings(req, res, url)
6765
7012
  if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)
package/index.mjs CHANGED
@@ -1415,10 +1415,10 @@ async function serveStatic(req, res, ctx) {
1415
1415
  [`${MOUNT}/admin/api/device-keys/rotate`, '/device-keys/rotate'],
1416
1416
  [`${MOUNT}/admin/api/device-keys/revoke`, '/device-keys/revoke'],
1417
1417
  ])
1418
- if (pathname === `${MOUNT}/admin/api/relay` || pathname === `${MOUNT}/admin/api/autostart`) {
1418
+ if (pathname === `${MOUNT}/admin/api/relay` || pathname === `${MOUNT}/admin/api/autostart` || pathname === `${MOUNT}/admin/api/lan`) {
1419
1419
  if (!['GET', 'POST'].includes(req.method)) { res.writeHead(405, { allow: 'GET, POST' }); res.end(); return }
1420
1420
  const body = req.method === 'POST' ? await readBody(req, 4096) : undefined
1421
- const proxied = await proxyGateway(pathname.endsWith('/autostart') ? '/admin/api/autostart' : '/admin/api/relay', req.method, body)
1421
+ const proxied = await proxyGateway('/admin/api/' + pathname.split('/').pop(), req.method, body)
1422
1422
  sendJson(res, proxied?.status || 502, proxied?.json || { error: 'GATEWAY_UNAVAILABLE' })
1423
1423
  return
1424
1424
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "description": "DSH Remote 官方 bundle 插件:更多菜单中的手机连接入口、首次连接提示与浏览器管理控制台;内置网关自动启停,支持手机远程会话、审批、文件互传和设备管理。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
package/public/admin.html CHANGED
@@ -510,6 +510,14 @@
510
510
  <div class="muted" id="pair-hint"></div>
511
511
  </div>
512
512
 
513
+ <section class="host-ip-card" id="lan-pairing-panel" aria-labelledby="lan-pairing-title">
514
+ <div class="host-ip-title" id="lan-pairing-title">局域网发现与配对</div>
515
+ <p class="muted" id="lan-pairing-hint"></p>
516
+ <p class="muted" id="lan-pairing-status" role="status"></p>
517
+ <p><code id="lan-pairing-code" hidden></code></p>
518
+ <button id="btn-lan-open" class="mini-btn" type="button" disabled>开放 10 分钟配对</button>
519
+ <button id="btn-lan-close" class="mini-btn" type="button" disabled>关闭配对</button>
520
+ </section>
513
521
  <div class="stat-grid" id="stats"></div>
514
522
 
515
523
  <div class="section-head"><span data-i18n="devices">已连接设备</span><span id="device-summary" class="muted"></span></div>
package/public/admin.js CHANGED
@@ -38,6 +38,63 @@ let qrShown = false
38
38
  let qrToken = ''
39
39
  let qrLabel = ''
40
40
  let deviceKeyBusy = false
41
+ let lanBusy = false, lanCode = '', lanExpiry = 0, lanRevision = 0, lanRead = null
42
+ const lanText = (zh, en) => I18N.lang === 'en' ? en : zh
43
+ function lanError(code) {
44
+ return {
45
+ DEVICE_KEYS_REQUIRED: lanText('请先启用独立设备密钥。', 'Enable independent device keys first.'),
46
+ LAN_LISTENER_REQUIRED: lanText('网关目前仅允许本机访问,请改用可从局域网访问的监听地址。', 'The gateway only accepts local connections. Configure a LAN-accessible listener.'),
47
+ DISCOVERY_PORT_UNAVAILABLE: lanText('发现端口被占用,请检查是否运行了其他网关。', 'The discovery port is occupied. Check for another gateway.'),
48
+ GATEWAY_UNAVAILABLE: lanText('网关暂不可用,请检查运行状态。', 'The gateway is unavailable. Check its status.'),
49
+ PAIRING_CLOSED: lanText('配对已关闭,请重新开放。', 'Pairing is closed. Open a new window.'),
50
+ }[code] || lanText('操作失败,请检查网关后重试。', 'Operation failed. Check the gateway and try again.')
51
+ }
52
+ function renderLan(state = {}) {
53
+ $('lan-pairing-title').textContent = lanText('局域网发现与配对', 'LAN discovery and pairing')
54
+ $('lan-pairing-hint').textContent = lanText('需先启用上方的独立设备密钥,再开放配对。Android 手机可搜索同一 Wi-Fi 下的电脑,输入限时配对码连接。配对码仅显示本次,成功后自动关闭;扫码与手动连接仍可使用。', 'Enable independent device keys above, then open pairing. Find this computer from the Android app on the same Wi-Fi and enter the one-time code. Pairing closes after success; QR and manual connections remain available.')
55
+ $('btn-lan-open').textContent = lanText('开放 10 分钟配对', 'Open pairing for 10 minutes')
56
+ $('btn-lan-close').textContent = lanText('关闭配对', 'Close pairing')
57
+ const enabled = state.enabled === true
58
+ if (!enabled || state.expiresAt !== lanExpiry || Date.now() >= lanExpiry) lanCode = ''
59
+ $('lan-pairing-code').textContent = lanCode
60
+ $('lan-pairing-code').hidden = !lanCode
61
+ $('btn-lan-open').disabled = lanBusy || !lastState?.deviceKeys?.enabled
62
+ $('btn-lan-close').disabled = lanBusy || !enabled
63
+ $('lan-pairing-status').textContent = enabled ? lanText('配对开放至 ', 'Pairing open until ') + new Date(state.expiresAt).toLocaleTimeString()
64
+ : state.error ? lanError(state.error) : lanText('当前未开放配对。', 'Pairing is closed.')
65
+ }
66
+ async function refreshLan() {
67
+ if (lanBusy || lanRead || !lastState) return
68
+ const savedToken = token, revision = lanRevision, job = {}
69
+ lanRead = job
70
+ try {
71
+ const response = await fetch(API + '/lan', { headers: adminHeaders(), credentials: 'same-origin', signal: AbortSignal.timeout(5000) })
72
+ const state = await response.json()
73
+ if (savedToken !== token || lanBusy || revision !== lanRevision) return
74
+ if (!response.ok) { lanCode = ''; renderLan({ error: state.error || 'GATEWAY_UNAVAILABLE' }); return }
75
+ renderLan(state)
76
+ } catch { if (savedToken === token && !lanBusy && revision === lanRevision) { lanCode = ''; renderLan({ error: 'GATEWAY_UNAVAILABLE' }) } }
77
+ finally { if (lanRead === job) lanRead = null }
78
+ }
79
+ async function changeLan(enabled) {
80
+ if (lanBusy) return
81
+ lanRevision++
82
+ lanBusy = true
83
+ $('btn-lan-open').disabled = true; $('btn-lan-close').disabled = true
84
+ const savedToken = token, revision = lanRevision
85
+ try {
86
+ const response = await fetch(API + '/lan', { method: 'POST', headers: adminHeaders({ 'content-type': 'application/json' }),
87
+ credentials: 'same-origin', signal: AbortSignal.timeout(8000), body: JSON.stringify({ enabled }) })
88
+ const state = await response.json()
89
+ if (savedToken !== token || revision !== lanRevision) return
90
+ if (!response.ok || !state.ok) throw Error(state.error || 'PAIRING_FAILED')
91
+ lanCode = state.code || ''; lanExpiry = state.expiresAt || 0
92
+ lanBusy = false; renderLan(state)
93
+ } catch (error) { if (savedToken === token && revision === lanRevision) { lanCode = ''; lanBusy = false; renderLan({ error: error.message }); toast(lanError(error.message), 'err') } }
94
+ finally { if (revision === lanRevision) lanBusy = false }
95
+ }
96
+ $('btn-lan-open').addEventListener('click', () => changeLan(true))
97
+ $('btn-lan-close').addEventListener('click', () => changeLan(false))
41
98
  const revealedDeviceKeys = new Set()
42
99
  let gatewayPort = 8787
43
100
  let gatewayPortLoaded = false
@@ -470,6 +527,7 @@ async function readState(job) {
470
527
 
471
528
  function render(st) {
472
529
  lastState = st
530
+ void refreshLan()
473
531
  const isPlugin = st.mode === 'plugin'
474
532
  const isGateway = st.mode === 'gateway'
475
533
  shownToken = st.gatewayAuthError ? '' : st.token || token
@@ -777,6 +835,8 @@ function showMain() {
777
835
  }
778
836
 
779
837
  function logout() {
838
+ lanRevision++; lanBusy = false; lanCode = ''; lanExpiry = 0
839
+ $('lan-pairing-code').textContent = ''; $('lan-pairing-code').hidden = true
780
840
  token = ''
781
841
  store.del('dshAdminToken')
782
842
  clearInterval(timer)