dsh-remote-plugin 0.8.0 → 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.
package/gateway.cjs CHANGED
@@ -588,9 +588,9 @@ function compressibleRpc(req) {
588
588
  // Crash records deliberately contain facts and source positions, never arbitrary error text.
589
589
  const CRASH_LOG_FILE=process.env.DSH_REMOTE_CRASH_LOG_FILE || path.join(os.homedir(),'.dsh-remote','crashes.jsonl')
590
590
  const AUTO_RESTART=process.env.DSH_REMOTE_AUTO_RESTART!=='0'
591
- const CRASH_KINDS=new Set(['fatal','exit','restart','restart-failed','restart-limit','manual-stop','startup','desktop-crash','lease-recovered','lease-conflict','lease-failed'])
591
+ const CRASH_KINDS=new Set(['fatal','exit','restart','restart-failed','restart-limit','manual-stop','startup','desktop-crash','lease-recovered','lease-conflict','lease-failed','log-unavailable'])
592
592
  const CRASH_COMPONENTS=new Set(['gateway','dsh','desktop'])
593
- const CRASH_CODES=new Set(['EADDRINUSE','EACCES','EPERM','ENOENT','ENOMEM','ECONNRESET','ETIMEDOUT','EINVAL','ENAMETOOLONG','ERR_OUT_OF_MEMORY','WINDOWS_APPLICATION_ERROR','PROCESS_START_FAILED','PROCESS_STOP_TIMEOUT','EXTERNAL_PROCESS','PORT_IN_USE','SERVICE_FAILED','SERVICE_TIMEOUT','EVENTS_TIMEOUT','UPSTREAM_TIMEOUT','INTERNAL_ERROR','LAUNCH_CONFIG_INVALID','STATUS_PARSE_FAILED','SUPERVISOR_ALREADY_RUNNING','SUPERVISOR_IDENTITY_UNAVAILABLE','SUPERVISOR_ENDPOINT_TOO_LONG','SUPERVISOR_LEASE_STALE','SUPERVISOR_LEASE_INVALID'])
593
+ const CRASH_CODES=new Set(['EADDRINUSE','EACCES','EPERM','ENOENT','ENOMEM','ECONNRESET','ETIMEDOUT','EINVAL','ENAMETOOLONG','EPIPE','EBADF','EIO','ERR_STREAM_DESTROYED','ERR_OUT_OF_MEMORY','WINDOWS_APPLICATION_ERROR','PROCESS_START_FAILED','PROCESS_STOP_TIMEOUT','EXTERNAL_PROCESS','PORT_IN_USE','SERVICE_FAILED','SERVICE_TIMEOUT','EVENTS_TIMEOUT','UPSTREAM_TIMEOUT','INTERNAL_ERROR','LAUNCH_CONFIG_INVALID','STATUS_PARSE_FAILED','SUPERVISOR_ALREADY_RUNNING','SUPERVISOR_IDENTITY_UNAVAILABLE','SUPERVISOR_ENDPOINT_TOO_LONG','SUPERVISOR_LEASE_STALE','SUPERVISOR_LEASE_INVALID'])
594
594
  function safeCrashRecord(value) {
595
595
  const row={at:Number.isFinite(value?.at)?value.at:Date.now(),component:CRASH_COMPONENTS.has(value?.component)?value.component:'gateway',kind:CRASH_KINDS.has(value?.kind)?value.kind:'fatal'}
596
596
  if(Number.isInteger(value?.exitCode))row.exitCode=value.exitCode
@@ -631,6 +631,20 @@ function crashUploadSummary() {
631
631
  while(JSON.stringify(report).length>490){if(report.records.some(r=>r.frames?.length)){for(const r of report.records)delete r.frames}else report.records.shift()}
632
632
  return report
633
633
  }
634
+ // A detached gateway can outlive the launcher that was reading its output.
635
+ // Only output-stream I/O failures are recoverable here; never ignore a socket
636
+ // error or an arbitrary uncaught exception merely because it has the same code.
637
+ const OUTPUT_CLOSED_CODES=new Set(['EPIPE','EBADF','EIO','ERR_STREAM_DESTROYED'])
638
+ for(const stream of [process.stdout,process.stderr]) {
639
+ let reported=false
640
+ stream.on('error',error=>{
641
+ if(!OUTPUT_CLOSED_CODES.has(error?.code))throw error
642
+ if(reported)return
643
+ reported=true
644
+ // Do not log to either console stream from its error handler.
645
+ recordCrash('gateway','log-unavailable',{code:error.code})
646
+ })
647
+ }
634
648
  // BEGIN LOGIN AUTOSTART
635
649
  // A per-user Windows login entry. No registration happens until the admin opts in.
636
650
  function createLoginAutostart(options) {
@@ -880,6 +894,11 @@ async function runGatewaySupervisor() {
880
894
  const env={...process.env,DSH_REMOTE_SUPERVISED:'1',DSH_REMOTE_SUPERVISOR_PID:String(process.pid)}
881
895
  delete env.NODE_CHANNEL_FD;delete env.NODE_CHANNEL_SERIALIZATION_MODE
882
896
  const args=process.pkg?process.argv.slice(2).filter(a=>a!=='--supervise'):[__filename,...process.argv.slice(2).filter(a=>a!=='--supervise')]
897
+ // 复用 supervisor 自己的 process.execPath 拉起 worker,前提是它已经是"正确的解释器":
898
+ // 插件托管网关时,packages/plugin/index.mjs 的 resolveGatewayRuntime() 会保证它是
899
+ // 位于 DSH 安装目录之外的 node(~/.dsh-remote/runtime/node-<ver>.exe 或 PATH 中的 node),
900
+ // 不能再把它当作 DSH 桌面版可执行文件;独立运行(node / pkg 单文件)时它就是普通 node
901
+ // 或网关自身。Windows 上若这里回落到安装目录内的 exe,DSH 原地更新会被占用而失败。
883
902
  try{worker=spawn(process.execPath,args,{cwd:process.cwd(),env,windowsHide:true,stdio:['ignore','inherit','inherit']})}catch(error){recordCrash('gateway','restart-failed',crashErrorFacts(error));process.exit(1)}
884
903
  let handled=false
885
904
  const exited=(code,signal)=>{
@@ -1061,6 +1080,7 @@ const CAPABILITIES = Object.freeze({
1061
1080
  operations: 1,
1062
1081
  cloudRelay: 1,
1063
1082
  workspaceFiles: 2,
1083
+ fileInbox: 1,
1064
1084
  imagePromptTransport: 1,
1065
1085
  dshLifecycle: DSH_CONTROL_SUPPORT.supported ? 2 : 0,
1066
1086
  centralAnnouncements: 2,
@@ -1271,6 +1291,126 @@ function restoreMissingTokenFile() {
1271
1291
  const WS_TICKET_TTL_MS = durationEnv('GATEWAY_WS_TICKET_TTL_MS', 90000, 10000, 10 * 60 * 1000)
1272
1292
  const wsTickets = new Map()
1273
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
+
1274
1414
  function newAccessToken() {
1275
1415
  return crypto.randomBytes(24).toString('base64url')
1276
1416
  }
@@ -1358,6 +1498,29 @@ function deviceKeyViews() {
1358
1498
  return deviceKeyState.keys.map(record => ({ ...record }))
1359
1499
  }
1360
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
+
1361
1524
  function findDeviceKeyByToken(value) {
1362
1525
  return deviceKeyState.keys.find(record => safeTokenEqual(value, record.token)) || null
1363
1526
  }
@@ -1390,6 +1553,7 @@ function rotateToken() {
1390
1553
  return { error: 'write-failed', detail: err.message }
1391
1554
  }
1392
1555
  TOKEN = next
1556
+ lanPairing.close()
1393
1557
  wsTickets.clear()
1394
1558
  return { ok: true, token: next }
1395
1559
  }
@@ -1821,7 +1985,7 @@ function cors(res, req = res.req) {
1821
1985
  }
1822
1986
  if (allowed) res.setHeader('access-control-allow-origin', origin || '*')
1823
1987
  res.setHeader('vary', 'Origin')
1824
- res.setHeader('access-control-allow-headers', 'authorization, content-type, x-dsh-remote-client, x-dsh-remote-client-id')
1988
+ res.setHeader('access-control-allow-headers', 'authorization, content-type, x-dsh-remote-client, x-dsh-remote-client-id, x-dsh-remote-inbox-key')
1825
1989
  res.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS')
1826
1990
  res.setHeader('access-control-max-age', '600')
1827
1991
  }
@@ -3210,6 +3374,12 @@ function broadcastCollectorFrame(kind, raw) {
3210
3374
 
3211
3375
  function pushEvent(kind, full, raw = JSON.stringify(full)) {
3212
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
+ }
3213
3383
  if (eventCollectorState[kind]) eventCollectorState[kind].lastEventAt = Date.now()
3214
3384
  const buf = eventBuffers[kind]
3215
3385
  buf.push({ seq: eventNextSeq[kind]++, ts: Date.now(), event: truncateEventValue(full) })
@@ -4245,6 +4415,66 @@ async function validatePollVote(payload) {
4245
4415
  return result
4246
4416
  }
4247
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
+
4248
4478
  function compatibilityDiagnostics() {
4249
4479
  const events = Object.fromEntries(Object.entries(eventCollectorState).map(([kind, state]) => [kind, {
4250
4480
  connected: state.connected === true,
@@ -4291,6 +4521,18 @@ function serveDiagnostics(req, res, url) {
4291
4521
  res.end(JSON.stringify(compatibilityDiagnostics()))
4292
4522
  }
4293
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
+
4294
4536
  function serveFeedback(req, res, url) {
4295
4537
  cors(res)
4296
4538
  if (req.method === 'OPTIONS') {
@@ -4312,7 +4554,7 @@ function serveFeedback(req, res, url) {
4312
4554
  }
4313
4555
  touchDevice(req)
4314
4556
 
4315
- withRequestBody(req, res, 16 * 1024, async body => {
4557
+ withRequestBody(req, res, 96 * 1024, async body => {
4316
4558
  let payload
4317
4559
  try {
4318
4560
  payload = JSON.parse(body || '{}')
@@ -4328,6 +4570,12 @@ function serveFeedback(req, res, url) {
4328
4570
  const appVersion = String(payload.appVersion || '').trim()
4329
4571
  const includeDiagnostics = payload.includeDiagnostics === true
4330
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
+ }
4331
4579
  if (!['bug', 'suggestion', 'other', 'poll'].includes(type)) {
4332
4580
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
4333
4581
  res.end(JSON.stringify({ error: 'invalid type', expect: 'bug|suggestion|other|poll' }))
@@ -4376,30 +4624,35 @@ function serveFeedback(req, res, url) {
4376
4624
 
4377
4625
  // 转发收集器(收集器服务端已做校验/节流/落盘)。节流只在收集器确认成功后占位,
4378
4626
  // 失败(429/502/网络错误)不占位, 用户可立即重试。
4379
- fetch(FEEDBACK_URL, {
4380
- method: 'POST',
4381
- headers: { 'content-type': 'application/json' },
4382
- body: JSON.stringify({
4627
+ const gatewayDiagnostics=includeDiagnostics?compatibilityDiagnostics():null
4628
+ const crashes=includeCrashLogs?crashUploadSummary():null
4629
+ const outbound={
4383
4630
  type,
4384
4631
  message,
4385
4632
  contact: contact || undefined,
4386
4633
  appVersion: appVersion || 'unknown',
4387
4634
  gatewayVersion: VERSION,
4388
4635
  clientIp: maskIp(ip),
4389
- ...(includeDiagnostics ? { diagnostics: compatibilityDiagnostics() } : {}),
4390
- ...(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)}:{}),
4391
4638
  ...(pollVote || {})
4392
- }),
4393
- signal: AbortSignal.timeout(8000)
4394
- }).then(async (r) => {
4395
- 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
+ }
4396
4649
  if (r.status === 429) {
4397
4650
  res.writeHead(429, { 'content-type': 'application/json; charset=utf-8' })
4398
4651
  res.end(JSON.stringify({ error: 'rate_limited' }))
4399
4652
  } else if (r.ok && data.ok) {
4400
4653
  feedbackThrottle.set(ip, now)
4401
4654
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
4402
- res.end(JSON.stringify({ ok: true }))
4655
+ res.end(JSON.stringify({ ok: true,...(clientDiagnostics?{diagnostics:{reportId:clientDiagnostics.reportId,saved:data.clientDiagnosticsReceived===clientDiagnostics.reportId}}:{}) }))
4403
4656
  } else {
4404
4657
  res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
4405
4658
  res.end(JSON.stringify({ error: 'upstream_error' }))
@@ -4505,8 +4758,35 @@ function upstreamReachable(cb) {
4505
4758
  cb(healthProbeState.reachable)
4506
4759
  }
4507
4760
 
4761
+ function gatewayRuntimeIdentity() {
4762
+ return { pid: process.pid, executable: process.execPath, version: process.versions.node,
4763
+ supervisorPid: Number(process.env.DSH_REMOTE_SUPERVISOR_PID) || 0 }
4764
+ }
4765
+
4508
4766
  async function serveAdminApi(req, res, url) {
4509
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
+ }
4780
+ // 实际进程信息只通过认证管理接口返回,公共 /health 不暴露本机解释器路径。
4781
+ if (sub === '/runtime') {
4782
+ const reply = (status, body) => {
4783
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
4784
+ res.end(JSON.stringify(body))
4785
+ }
4786
+ if (!adminAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
4787
+ if (req.method !== 'GET') { res.setHeader('allow', 'GET'); return reply(405, { error: 'method-not-allowed' }) }
4788
+ return reply(200, { ok: true, gatewayRuntime: gatewayRuntimeIdentity() })
4789
+ }
4510
4790
  if (sub === '/autostart') {
4511
4791
  const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
4512
4792
  if (!adminAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
@@ -4539,6 +4819,7 @@ async function serveAdminApi(req, res, url) {
4539
4819
  version: VERSION,
4540
4820
  pid: process.pid,
4541
4821
  platform: process.platform,
4822
+ gatewayRuntime: gatewayRuntimeIdentity(),
4542
4823
  hostname: os.hostname(),
4543
4824
  lanIPs: lanAddresses(),
4544
4825
  startedAt: STARTED_AT,
@@ -4606,6 +4887,7 @@ async function serveAdminApi(req, res, url) {
4606
4887
  return send(500, { error: 'write-failed', detail: '无法保存独立设备密钥设置' })
4607
4888
  }
4608
4889
  wsTickets.clear()
4890
+ lanPairing.close()
4609
4891
  const disconnected = kickRemoteClients()
4610
4892
  return send(200, { ok: true, disconnected, deviceKeys: deviceKeysPayload() })
4611
4893
  }
@@ -6405,6 +6687,213 @@ function proxyApi(req, res, url) {
6405
6687
  })
6406
6688
  }
6407
6689
 
6690
+ // BEGIN FILE INBOX — local durable single-file deliveries, no external service.
6691
+ function createFileInbox({ root, resolveSource, validAuth, now = Date.now, maxFile = 50 * 1024 * 1024, ttl = 86400000 }) {
6692
+ const digest = value => crypto.createHash('sha256').update(value).digest('hex')
6693
+ const fail = (code, status = 400) => Object.assign(new Error(code), { code, status })
6694
+ const idOk = value => typeof value === 'string' && value.length >= 16 && value.length <= 80 && !/[^a-zA-Z0-9-]/.test(value)
6695
+ const keyOk = value => typeof value === 'string' && value.length === 64 && !/[^a-f0-9]/.test(value)
6696
+ const terminal = new Set(['complete', 'downloaded', 'rejected', 'expired'])
6697
+ let state, persisted, serial = Promise.resolve()
6698
+ const file = id => path.join(root, id + '.bin')
6699
+ const save = () => {
6700
+ const temp = path.join(root, 'index.' + process.pid + '.tmp')
6701
+ try {
6702
+ fs.writeFileSync(temp, JSON.stringify(state), { mode: 0o600 })
6703
+ fs.renameSync(temp, path.join(root, 'index.json'))
6704
+ persisted = JSON.parse(JSON.stringify(state))
6705
+ } catch (error) { state = JSON.parse(JSON.stringify(persisted)); throw error }
6706
+ }
6707
+ const clean = () => {
6708
+ let changed = false
6709
+ for (const row of state.transfers) if ((row.expiresAt <= now() || !validAuth(row.auth)) && !row.snapshotDeleted) {
6710
+ if (!terminal.has(row.phase)) { row.phase = 'expired'; row.expiresAt = Math.min(row.expiresAt, now()) }
6711
+ delete row.ticketHash; row.snapshotDeleted = true; changed = true
6712
+ try { fs.unlinkSync(file(row.id)) } catch (e) { if (e.code !== 'ENOENT') throw e }
6713
+ }
6714
+ const old = state.transfers.length
6715
+ state.transfers = state.transfers.filter(row => row.expiresAt > now() - ttl)
6716
+ if (changed || old !== state.transfers.length) save()
6717
+ }
6718
+ const lock = work => {
6719
+ const result = serial.catch(() => {}).then(async () => {
6720
+ if (!state) {
6721
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 })
6722
+ try { state = JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8')) }
6723
+ catch (e) { if (e.code !== 'ENOENT') throw fail('inbox-storage-invalid', 503); state = { devices: [], transfers: [] } }
6724
+ if (!Array.isArray(state?.devices) || !Array.isArray(state?.transfers) || state.transfers.some(r => !idOk(r.id))) { state = null; throw fail('inbox-storage-invalid', 503) }
6725
+ persisted = JSON.parse(JSON.stringify(state))
6726
+ // Failed/crashed snapshots are private, bounded, and never exposed as deliveries.
6727
+ for (const name of fs.readdirSync(root)) if (/^[a-zA-Z0-9-]{16,80}\.(bin|part)$/.test(name)) {
6728
+ const id = name.replace(/\.(bin|part)$/, '')
6729
+ if (!state.transfers.some(row => row.id === id)) fs.unlinkSync(path.join(root, name))
6730
+ }
6731
+ }
6732
+ clean()
6733
+ return work()
6734
+ })
6735
+ serial = result
6736
+ return result
6737
+ }
6738
+ const device = (auth, key) => {
6739
+ if (!keyOk(key)) throw fail('receiver-key-required', 403)
6740
+ const found = state.devices.find(row => row.auth === auth && row.keyHash === digest(key))
6741
+ if (!found || !validAuth(auth)) throw fail('receiver-not-registered', 403)
6742
+ return found
6743
+ }
6744
+ const view = row => Object.fromEntries(['id', 'deviceId', 'fileName', 'size', 'sha256', 'phase', 'title', 'message', 'sessionId', 'createdAt', 'expiresAt', 'updatedAt'].map(k => [k, row[k]]))
6745
+ const owned = (auth, key, id) => {
6746
+ const d = device(auth, key), row = state.transfers.find(row => row.id === id && row.deviceId === d.id)
6747
+ if (!row) throw fail('transfer-not-found', 404)
6748
+ return row
6749
+ }
6750
+ return {
6751
+ register: (auth, key, name) => lock(() => {
6752
+ if (!keyOk(key) || !validAuth(auth)) throw fail('invalid-receiver', 403)
6753
+ let d = state.devices.find(row => row.auth === auth && row.keyHash === digest(key))
6754
+ if (!d) {
6755
+ state.devices = state.devices.filter(row => validAuth(row.auth) && row.lastSeenAt > now() - 30 * ttl)
6756
+ if (state.devices.length >= 100) throw fail('too-many-receivers', 409)
6757
+ d = { id: crypto.randomUUID(), auth, keyHash: digest(key) }; state.devices.push(d)
6758
+ }
6759
+ d.name = String(name || 'Remote 设备').replace(/[\x00-\x1f]/g, '').slice(0, 60)
6760
+ d.lastSeenAt = now(); save()
6761
+ return { id: d.id, name: d.name, maxFile, ttl }
6762
+ }),
6763
+ devices: () => lock(() => state.devices.filter(d => validAuth(d.auth)).map(d => ({ id: d.id, name: d.name, lastSeenAt: d.lastSeenAt, online: now() - d.lastSeenAt < 45000 }))),
6764
+ list: (auth, key) => lock(() => {
6765
+ const d = device(auth, key)
6766
+ return state.transfers.filter(row => row.deviceId === d.id).slice(-50).reverse().map(view)
6767
+ }),
6768
+ send: body => lock(async () => {
6769
+ if (!idOk(body.id) || typeof body.path !== 'string' || typeof body.workspaceRoot !== 'string' || typeof body.deviceId !== 'string' || typeof body.sessionId !== 'string') throw fail('invalid-delivery')
6770
+ const requestHash = digest(JSON.stringify([body.deviceId, body.path, body.workspaceRoot, body.sessionId, body.title || '', body.message || '']))
6771
+ const previous = state.transfers.find(row => row.id === body.id)
6772
+ if (previous) { if (previous.requestHash !== requestHash) throw fail('delivery-id-conflict', 409); return view(previous) }
6773
+ const recipient = state.devices.find(d => d.id === body.deviceId && validAuth(d.auth))
6774
+ if (!recipient) throw fail('receiver-not-found', 404)
6775
+ if (state.transfers.length >= 200 || state.transfers.filter(row => !terminal.has(row.phase)).length >= 20 || state.transfers.filter(row => row.expiresAt > now() && !row.snapshotDeleted && row.phase !== 'rejected').reduce((sum, row) => sum + row.size, 0) >= 200 * 1024 * 1024) throw fail('inbox-full', 409)
6776
+ const source = await resolveSource(body.path, body.workspaceRoot)
6777
+ let input, output
6778
+ const part = path.join(root, body.id + '.part')
6779
+ try {
6780
+ input = await fs.promises.open(source, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0))
6781
+ const before = await input.stat()
6782
+ if (!before.isFile() || before.size > maxFile) throw fail('file-too-large-or-not-regular', 413)
6783
+ if (state.transfers.filter(row => row.expiresAt > now() && !row.snapshotDeleted && row.phase !== 'rejected').reduce((sum, row) => sum + row.size, 0) + before.size > 200 * 1024 * 1024) throw fail('inbox-full', 409)
6784
+ // Recheck path policy after opening; aliases must still identify the opened inode.
6785
+ if (await resolveSource(body.path, body.workspaceRoot) !== source) throw fail('source-changed', 409)
6786
+ const current = await fs.promises.stat(source)
6787
+ if (current.dev !== before.dev || current.ino !== before.ino) throw fail('source-changed', 409)
6788
+ output = await fs.promises.open(part, 'wx', 0o600)
6789
+ const hasher = crypto.createHash('sha256'), buffer = Buffer.alloc(65536)
6790
+ let size = 0
6791
+ for (;;) {
6792
+ const { bytesRead } = await input.read(buffer, 0, buffer.length, null)
6793
+ if (!bytesRead) break
6794
+ size += bytesRead
6795
+ if (size > maxFile) throw fail('file-too-large', 413)
6796
+ const chunk = buffer.subarray(0, bytesRead); hasher.update(chunk); await output.writeFile(chunk)
6797
+ }
6798
+ const after = await input.stat()
6799
+ if (size !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw fail('source-changed', 409)
6800
+ await output.close(); output = null
6801
+ await fs.promises.rename(part, file(body.id))
6802
+ const row = { id: body.id, deviceId: recipient.id, auth: recipient.auth, requestHash, fileName: path.basename(source).replace(/[\x00-\x1f]/g, '').slice(0, 180), size, sha256: hasher.digest('hex'), phase: 'pending', title: String(body.title || '').slice(0, 120), message: String(body.message || '').slice(0, 600), sessionId: body.sessionId.slice(0, 200), createdAt: now(), updatedAt: now(), expiresAt: now() + ttl }
6803
+ state.transfers.push(row)
6804
+ try { save() } catch (e) { state.transfers = state.transfers.filter(row => row.id !== body.id); await fs.promises.unlink(file(body.id)); throw e }
6805
+ return view(row)
6806
+ } finally {
6807
+ await input?.close(); await output?.close()
6808
+ try { await fs.promises.unlink(part) } catch (e) { if (e.code !== 'ENOENT') throw e }
6809
+ }
6810
+ }),
6811
+ status: (id, sessionId) => lock(() => {
6812
+ const row = state.transfers.find(r => r.id === id && r.sessionId === sessionId)
6813
+ if (!row) throw fail('transfer-not-found', 404)
6814
+ return view(row)
6815
+ }),
6816
+ decide: (auth, key, id, action) => lock(() => {
6817
+ const row = owned(auth, key, id)
6818
+ if (row.expiresAt <= now()) throw fail('transfer-expired', 410)
6819
+ if (action === 'reject') {
6820
+ if (row.phase === 'rejected') return view(row)
6821
+ if (row.phase !== 'pending') throw fail('transfer-already-decided', 409)
6822
+ row.phase = 'rejected'; row.updatedAt = now(); save()
6823
+ try { fs.unlinkSync(file(row.id)) } catch (e) { if (e.code !== 'ENOENT') throw e }
6824
+ return view(row)
6825
+ }
6826
+ if (action !== 'accept' || !['pending', 'accepted', 'downloading', 'failed'].includes(row.phase)) throw fail('transfer-already-decided', 409)
6827
+ const ticket = crypto.randomBytes(24).toString('hex')
6828
+ row.phase = 'accepted'; row.ticketHash = digest(ticket); row.ticketExpiresAt = Math.min(row.expiresAt, now() + 1800000); row.updatedAt = now(); save()
6829
+ return { ...view(row), ticket }
6830
+ }),
6831
+ download: (auth, id, ticket) => lock(async () => {
6832
+ const row = state.transfers.find(r => r.id === id && r.auth === auth)
6833
+ if (!row || !validAuth(auth) || typeof ticket !== 'string' || !row.ticketHash || row.ticketHash !== digest(ticket) || row.ticketExpiresAt <= now() || !['accepted', 'downloading'].includes(row.phase)) throw fail('download-not-authorized', 403)
6834
+ const bytes = await fs.promises.readFile(file(row.id))
6835
+ if (bytes.length !== row.size || digest(bytes) !== row.sha256) { row.phase = 'failed'; delete row.ticketHash; save(); throw fail('snapshot-integrity-failed', 409) }
6836
+ row.phase = 'downloading'; row.updatedAt = now(); save()
6837
+ return { bytes, row: view(row) }
6838
+ }),
6839
+ acknowledge: (auth, key, id, phase) => lock(() => {
6840
+ const row = owned(auth, key, id)
6841
+ if (!['downloaded', 'complete', 'failed'].includes(phase)) throw fail('invalid-receipt')
6842
+ if (row.phase === phase) return view(row)
6843
+ if (row.phase !== 'downloading' && !(phase === 'failed' && row.phase === 'accepted')) throw fail('download-not-started', 409)
6844
+ row.phase = phase; row.updatedAt = now(); delete row.ticketHash; save()
6845
+ return view(row)
6846
+ }),
6847
+ }
6848
+ }
6849
+ // END FILE INBOX STORE
6850
+ const inboxAuthHash = token => crypto.createHash('sha256').update(String(token || '')).digest('hex')
6851
+ const fileInbox = createFileInbox({
6852
+ root: path.join(os.homedir(), '.dsh-remote', 'file-inbox'),
6853
+ validAuth: hash => (deviceKeyState.enabled ? deviceKeyState.keys.map(d => d.token) : [TOKEN]).some(token => inboxAuthHash(token) === hash),
6854
+ resolveSource: async (input, workspaceRoot) => {
6855
+ if (!path.isAbsolute(input) || !path.isAbsolute(workspaceRoot)) throw Object.assign(Error('absolute-local-path-required'), { status: 400 })
6856
+ const resolved = await fsResolve(input)
6857
+ const checked = !resolved.error && fsRealChecked(resolved.abs)
6858
+ let root
6859
+ try { root = (fs.realpathSync.native || fs.realpathSync)(workspaceRoot) } catch {}
6860
+ if (!root || !checked?.abs || !fsInsideRoot(checked.abs, root)) throw Object.assign(Error('source-outside-workspace-or-forbidden'), { status: 403 })
6861
+ return checked.abs
6862
+ },
6863
+ })
6864
+ async function serveFileInbox(req, res, url) {
6865
+ cors(res)
6866
+ const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }); res.end(JSON.stringify(value)) }
6867
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
6868
+ const admin = url.pathname === '/admin/api/file-inbox'
6869
+ if (!(admin ? adminAuthorized(req, url) : authorized(req, url))) return reply(401, { error: 'unauthorized' })
6870
+ const auth = inboxAuthHash(tokenOf(req, url)), key = req.headers['x-dsh-remote-inbox-key']
6871
+ try {
6872
+ const body = req.method === 'POST' ? JSON.parse(await readBody(req, 16384)) : {}
6873
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return reply(400, { error: 'invalid-body' })
6874
+ if (admin) {
6875
+ if (req.method === 'GET') return reply(200, { devices: await fileInbox.devices() })
6876
+ if (req.method !== 'POST') return reply(405, { error: 'method-not-allowed' })
6877
+ if (body.action === 'send') return reply(200, await fileInbox.send(body))
6878
+ if (body.action === 'status') return reply(200, await fileInbox.status(body.id, body.sessionId))
6879
+ return reply(400, { error: 'invalid-action' })
6880
+ }
6881
+ touchDevice(req)
6882
+ if (url.pathname === '/fs/inbox-file') {
6883
+ if (req.method !== 'GET') return reply(405, { error: 'method-not-allowed' })
6884
+ const out = await fileInbox.download(auth, url.searchParams.get('id'), url.searchParams.get('ticket'))
6885
+ res.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': out.bytes.length, 'content-disposition': fsContentDisposition(out.row.fileName), 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' })
6886
+ res.end(out.bytes); return
6887
+ }
6888
+ if (url.pathname !== '/api/file-inbox') return reply(404, { error: 'not-found' })
6889
+ if (req.method === 'GET') return reply(200, { transfers: await fileInbox.list(auth, key) })
6890
+ if (req.method !== 'POST') return reply(405, { error: 'method-not-allowed' })
6891
+ if (body.action === 'register') return reply(200, await fileInbox.register(auth, key, body.name))
6892
+ if (['accept', 'reject'].includes(body.action)) return reply(200, await fileInbox.decide(auth, key, body.id, body.action))
6893
+ if (body.action === 'receipt') return reply(200, await fileInbox.acknowledge(auth, key, body.id, body.phase))
6894
+ return reply(400, { error: 'invalid-action' })
6895
+ } catch (e) { return reply(e.status || (e instanceof SyntaxError ? 400 : 503), { error: e.status ? e.message : 'inbox-unavailable' }) }
6896
+ }
6408
6897
  // ---------- 其它 ----------
6409
6898
  // Expensive OS/upstream checks run once in the background; public status never
6410
6899
  // grants restart authority. Actual lifecycle actions still verify fresh evidence.
@@ -6517,6 +7006,8 @@ function lanAddresses() {
6517
7006
  const server = http.createServer(async (req, res) => {
6518
7007
  try {
6519
7008
  const url = new URL(req.url, 'http://dsh-remote.local')
7009
+ if (url.pathname === '/api/lan-pair') return await serveLanPair(req, res)
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)
6520
7011
  if (url.pathname === '/relay') return await serveRelaySettings(req, res, url)
6521
7012
  if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)
6522
7013
  if (url.pathname === '/workbench' || url.pathname.startsWith('/workbench/')) return serveWorkbench(req, res, url)