dsh-remote-plugin 0.8.5 → 0.8.7

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/gateway.cjs CHANGED
@@ -267,7 +267,7 @@ function upgradeChannel(origin, ca) {
267
267
  }
268
268
 
269
269
  class RelayClient extends EventEmitter {
270
- constructor({ grantId, privateKey, tunnelHost, tunnelPort, tunnelOrigin, expiresAt, gateway = 'http://127.0.0.1:8787', ca, poolSize = 4, reconnectMs = 1500, e2ee }) {
270
+ constructor({ grantId, privateKey, tunnelHost, tunnelPort, tunnelOrigin, expiresAt, gateway = 'http://127.0.0.1:8787', ca, poolSize, reconnectMs = 1500, e2ee }) {
271
271
  super()
272
272
  if (!/^[a-f0-9]{16}$/.test(grantId || '') || !Number.isInteger(Number(tunnelPort)) || tunnelPort < 1 || tunnelPort > 65535 || !Number.isFinite(expiresAt)) throw fault('INVALID_CLIENT_CONFIG')
273
273
  this.grantId = grantId; this.privateKey = crypto.createPrivateKey(privateKey)
@@ -277,7 +277,11 @@ class RelayClient extends EventEmitter {
277
277
  if (e2ee && (!/^[a-f0-9]{64}$/.test(e2ee.routeTokenHash || '') || !['standard', 'sponsor-basic'].includes(e2ee.policy) || typeof e2ee.accept !== 'function')) throw fault('INVALID_E2EE_CONFIG')
278
278
  this.tunnelHost = tunnelHost; this.tunnelPort = Number(tunnelPort); this.expiresAt = expiresAt; this.ca = ca
279
279
  this.tunnelOrigin = tunnelOrigin
280
- this.poolSize = Math.min(6, Math.max(1, poolSize)); this.reconnectMs = reconnectMs
280
+ // Park a few authenticated work channels ahead of demand so an E2EE request starts without
281
+ // waiting for a fresh host->relay handshake. DSH_REMOTE_RELAY_POOL overrides (1-6; the broker
282
+ // parks at most 8). Explicit poolSize from callers (and tests) still wins.
283
+ const configuredPool = Number.isInteger(poolSize) ? poolSize : Number(process.env.DSH_REMOTE_RELAY_POOL)
284
+ this.poolSize = Math.min(6, Math.max(1, Number.isInteger(configuredPool) ? configuredPool : 6)); this.reconnectMs = reconnectMs
281
285
  this.context = null; this.running = false; this.timer = null; this.failures = 0; this.controlSocket = null; this.epoch = 0
282
286
  }
283
287
  async authenticate(role, session = '', context) {
@@ -326,7 +330,11 @@ class RelayClient extends EventEmitter {
326
330
  if (context) this.dispose(context)
327
331
  if (context && this.controlSocket === context.socket) this.controlSocket = null
328
332
  if (this.running && epoch === this.epoch) {
329
- const wait = Math.min(60000, this.reconnectMs * 2 ** Math.min(this.failures++, 6))
333
+ // A restarted gateway can race a broker that still holds the previous control
334
+ // socket. Retry quickly for the first minute so recovery does not inherit the
335
+ // exponential backoff of a stale registration.
336
+ const failures = this.failures++
337
+ const wait = Math.min(failures < 12 ? 5000 : 60000, this.reconnectMs * 2 ** Math.min(failures, 6))
330
338
  this.timer = setTimeout(() => this.connect(), wait)
331
339
  }
332
340
  }
@@ -654,14 +662,21 @@ class DeviceStore{
654
662
  finally{fs.rmSync(temp,{force:true})}
655
663
  }
656
664
  active(id){const d=this.state.devices.find(d=>d.id===id);return d&&!d.revokedAt&&d.expiresAt>Date.now()?d:null}
657
- list(){return this.state.devices.map(({id,label,createdAt,expiresAt,revokedAt})=>({id,label,createdAt,expiresAt,revokedAt:revokedAt||null,active:!!this.active(id)}))}
665
+ list(){return this.state.devices.map(({id,label,createdAt,expiresAt,revokedAt,firstPublicAccessAt,setupId})=>({id,label,createdAt,expiresAt,revokedAt:revokedAt||null,active:!!this.active(id),firstPublicAccessAt:Number.isFinite(firstPublicAccessAt)?firstPublicAccessAt:null,...(ID.test(setupId||'')?{setupId}:{})}))}
666
+ rememberPublicAccess(id) {
667
+ const device = this.active(id)
668
+ if (!device || Number.isFinite(device.firstPublicAccessAt)) return
669
+ const firstPublicAccessAt = Date.now()
670
+ this.save({...this.state, devices: this.state.devices.map(row => row.id === id ? {...row, firstPublicAccessAt} : row)})
671
+ }
658
672
  routes(){return this.state.devices.filter(d=>this.active(d.id)).map(({id,routeTokenHash,expiresAt})=>({id,routeTokenHash,expiresAt})).sort((a,b)=>a.id.localeCompare(b.id))}
659
- create({label,expiresAt,publicUrl}){
673
+ create({label,expiresAt,publicUrl,setupId}){
660
674
  if(typeof label!=='string'||!label.trim()||label.length>80||/[\x00-\x1f]/.test(label)||!Number.isFinite(expiresAt)||expiresAt<=Date.now()||expiresAt>Date.now()+366*86400000)throw fault('INVALID_DEVICE')
675
+ if(setupId&&this.state.devices.some(device=>device.setupId===setupId))throw fault('E2EE_SETUP_ALREADY_USED',409)
661
676
  if(this.routes().length>=32)throw fault('E2EE_DEVICE_LIMIT',409)
662
677
  const origin=new URL(publicUrl);if(origin.protocol!=='https:'||origin.username||origin.password)throw fault('INVALID_DEVICE')
663
678
  const id=crypto.randomBytes(16).toString('hex'),routeToken=crypto.randomBytes(32).toString('base64url'),deviceSecret=crypto.randomBytes(32).toString('base64url')
664
- const record={id,label:label.trim(),routeTokenHash:hash(routeToken),secretHash:hash(deviceSecret),createdAt:Date.now(),expiresAt,revokedAt:null}
679
+ const record={id,label:label.trim(),routeTokenHash:hash(routeToken),secretHash:hash(deviceSecret),createdAt:Date.now(),expiresAt,revokedAt:null,...(ID.test(setupId||'')?{setupId}:{})}
665
680
  const retained=this.state.devices.filter(d=>this.active(d.id)).concat(this.state.devices.filter(d=>!this.active(d.id)).slice(-31))
666
681
  this.save({...this.state,devices:[...retained,record]})
667
682
  const certificate=new crypto.X509Certificate(this.identity.certificate)
@@ -743,7 +758,7 @@ class E2eeEndpoint {
743
758
  if (!req.url.startsWith('/') || req.url.startsWith('//')) throw fault('INVALID_REQUEST_TARGET')
744
759
  if (Date.now() >= this.expiresAt) throw fault('AUTHORIZATION_INACTIVE', 403)
745
760
  if (this.devices) req.socket.deviceId = this.devices.authorize(req.headers['x-dsh-relay-device'])
746
- if (this.active >= 16) throw fault('HOST_BUSY', 503)
761
+ if (this.active >= 32) throw fault('HOST_BUSY', 503)
747
762
  if (this.policy !== 'sponsor-basic') return null
748
763
  const mode = basicPolicy(req)
749
764
  if (upgrade && (mode || req.method !== 'GET' || !/^\/api\/events\.(?:mux|host)(?:\?|$)/.test(req.url))) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
@@ -790,6 +805,10 @@ class E2eeEndpoint {
790
805
  request.on('error', fail)
791
806
  request.on('response', response => {
792
807
  if (res.destroyed) return response.destroy()
808
+ if (pathname === '/relay' && req.method === 'GET' && response.statusCode === 200 && req.socket.deviceId) {
809
+ // This is an authenticated public read. A metadata write failure must not interrupt it.
810
+ try { this.devices.rememberPublicAccess(req.socket.deviceId) } catch {}
811
+ }
793
812
  if (mode) { void imageResponse(response, res, mode); return }
794
813
  res.writeHead(response.statusCode, headersOf(response.headers))
795
814
  response.on('error', () => res.destroy())
@@ -927,6 +946,7 @@ async function basicBody(req) {
927
946
  const parts = []; let size = 0
928
947
  for await (const chunk of req) { size += chunk.length; if (size > 16 * 1024 * 1024) throw fault('BODY_TOO_LARGE', 413); parts.push(chunk) }
929
948
  const raw = Buffer.concat(parts)
949
+ if (raw.length === 0 && url.pathname === '/api/ws-ticket') return raw
930
950
  let value
931
951
  try { value = JSON.parse(raw.toString('utf8')) } catch { throw fault('INVALID_JSON') }
932
952
  if (value?.type === 'client-request' && value.method !== decodeURIComponent(url.pathname.slice(5))) throw fault('RPC_ROUTE_MISMATCH', 403)
@@ -1033,6 +1053,10 @@ class RelayHost {
1033
1053
  stop() { const client = this.client; this.client = null; client?.stop(); this.endpoint?.close(); this.endpoint = null; this.phase = 'disabled' }
1034
1054
  isRelayRequest(req) { return require('./gateway-sockets.cjs').contains(req) }
1035
1055
  deviceStatus() { return { ...this.status(), devices: this.devices?.list() || [] } }
1056
+ pairingActivity() {
1057
+ return (this.devices?.list() || []).filter(device => device.active)
1058
+ .map(({setupId, createdAt, firstPublicAccessAt}) => ({setupId, createdAt, firstPublicAccessAt}))
1059
+ }
1036
1060
  async changeDevice(value) {
1037
1061
  if (this.busy) throw fault('RELAY_OPERATION_BUSY',409)
1038
1062
  if (!this.config) throw fault('HOST_NOT_CONFIGURED',409)
@@ -1054,7 +1078,7 @@ class RelayHost {
1054
1078
  if (!Number.isInteger(days) || days < 1 || days > 30) throw fault('INVALID_DEVICE')
1055
1079
  const identity = loadIdentity(this.root)
1056
1080
  const expiresAt = Math.min(this.config.expiresAt, Date.parse(new crypto.X509Certificate(identity.certificate).validTo), Date.now()+days*86400000)
1057
- const result = this.devices.create({label:value.label,expiresAt,publicUrl:this.config.publicUrl})
1081
+ const result = this.devices.create({label:value.label,expiresAt,publicUrl:this.config.publicUrl,setupId:value.setupId})
1058
1082
  if (this.config.enabled) this.start()
1059
1083
  return {...this.deviceStatus(),...result}
1060
1084
  } else if (value.action === 'revoke-device') this.devices.revoke(value.id)
@@ -1242,6 +1266,9 @@ for(const stream of [process.stdout,process.stderr]) {
1242
1266
  // A per-user Windows login entry. No registration happens until the admin opts in.
1243
1267
  function createLoginAutostart(options) {
1244
1268
  const { home, platform, executable, script, packaged, electron, sourceDir, env, port, host, upstream, run } = options
1269
+ // The upstream can change while the gateway stays alive (DSH restarts on a new port),
1270
+ // so allow the caller to pass a getter and always persist the current origin.
1271
+ const upstreamOrigin = () => String(typeof upstream === 'function' ? upstream() : upstream)
1245
1272
  const dir = path.join(home, '.dsh-remote', 'autostart')
1246
1273
  const launcher = path.join(dir, 'launch.ps1'), configFile = path.join(dir, 'launch.json')
1247
1274
  const name = 'DSHRemoteGateway'
@@ -1304,7 +1331,7 @@ function createLoginAutostart(options) {
1304
1331
  for (const [key, value] of Object.entries(env)) {
1305
1332
  if ((key.startsWith('DSH_REMOTE_') || /^(HOME|USERPROFILE|DSH_HOME|TOKEN|TOKEN_FILE|HTTP_PROXY|HTTPS_PROXY|ALL_PROXY|NO_PROXY|http_proxy|https_proxy|all_proxy|no_proxy|UPDATE_CHECK_URL|UPDATE_PROXY)$/.test(key)) && !/^DSH_REMOTE_SUPERVIS/.test(key)) savedEnv[key] = value
1306
1333
  }
1307
- Object.assign(savedEnv, { HOME: home, USERPROFILE: home, PORT: String(port), HOST: host, DSH_UPSTREAM: upstream })
1334
+ Object.assign(savedEnv, { HOME: home, USERPROFILE: home, PORT: String(port), HOST: host, DSH_UPSTREAM: upstreamOrigin() })
1308
1335
  if (electron && !packaged) savedEnv.ELECTRON_RUN_AS_NODE = '1'
1309
1336
  const config = { version: 1, fingerprint, bundle, executable: packaged ? path.join(bundle, 'gateway.exe') : executable,
1310
1337
  args: packaged ? ['--supervise'] : [path.join(bundle, 'gateway.cjs'), '--supervise'], env: savedEnv }
@@ -1557,12 +1584,36 @@ const WS_PONG_TIMEOUT_MS = durationEnv('GATEWAY_WS_PONG_TIMEOUT_MS', 90000, 1000
1557
1584
  const WS_IDLE_MS = durationEnv('GATEWAY_WS_IDLE_MS', 180000, 0, 24 * 60 * 60 * 1000)
1558
1585
  const WS_UPGRADE_TIMEOUT_MS = durationEnv('GATEWAY_WS_UPGRADE_TIMEOUT_MS', 15000, 1000, 5 * 60 * 1000)
1559
1586
  const UPSTREAM_REQUEST_TIMEOUT_MS = durationEnv('GATEWAY_UPSTREAM_TIMEOUT_MS', 30000, 1000, 10 * 60 * 1000)
1560
- const UPSTREAM = new URL(process.env.DSH_UPSTREAM || 'http://127.0.0.1:3080')
1587
+ // DSH restarts on a new loopback port. Keeping the gateway process alive avoids
1588
+ // tearing down the relay control channel (and the public path) for every restart.
1589
+ let UPSTREAM = new URL(process.env.DSH_UPSTREAM || 'http://127.0.0.1:3080')
1561
1590
  // URL 中 IPv6 带方括号,http.request 的 hostname 则要求裸地址。
1562
- const UPSTREAM_HOSTNAME = UPSTREAM.hostname.replace(/^\[|\]$/g, '')
1563
- const UPSTREAM_TRANSPORT = UPSTREAM.protocol === 'https:' ? https : http
1564
- const UPSTREAM_PORT = Number(UPSTREAM.port) || (UPSTREAM.protocol === 'https:' ? 443 : 80)
1565
- const UPSTREAM_AUTHORITY = `${UPSTREAM.hostname}${UPSTREAM.port ? ':' + UPSTREAM.port : ''}`
1591
+ let UPSTREAM_HOSTNAME = UPSTREAM.hostname.replace(/^\[|\]$/g, '')
1592
+ let UPSTREAM_TRANSPORT = UPSTREAM.protocol === 'https:' ? https : http
1593
+ let UPSTREAM_PORT = Number(UPSTREAM.port) || (UPSTREAM.protocol === 'https:' ? 443 : 80)
1594
+ let UPSTREAM_AUTHORITY = `${UPSTREAM.hostname}${UPSTREAM.port ? ':' + UPSTREAM.port : ''}`
1595
+ /** Point the gateway at another loopback DSH origin without restarting the process. */
1596
+ function applyUpstream(value) {
1597
+ let next
1598
+ try { next = new URL(String(value || '').trim()) } catch { return null }
1599
+ if (next.protocol !== 'http:' && next.protocol !== 'https:') return null
1600
+ if (next.username || next.password || next.search || next.hash) return null
1601
+ const host = next.hostname.replace(/^\[|\]$/g, '')
1602
+ if (!['127.0.0.1', 'localhost', '::1'].includes(host)) return null
1603
+ UPSTREAM = new URL(next.origin)
1604
+ UPSTREAM_HOSTNAME = UPSTREAM.hostname.replace(/^\[|\]$/g, '')
1605
+ UPSTREAM_TRANSPORT = UPSTREAM.protocol === 'https:' ? https : http
1606
+ UPSTREAM_PORT = Number(UPSTREAM.port) || (UPSTREAM.protocol === 'https:' ? 443 : 80)
1607
+ UPSTREAM_AUTHORITY = `${UPSTREAM.hostname}${UPSTREAM.port ? ':' + UPSTREAM.port : ''}`
1608
+ upstreamApiFlavor = 'unknown'
1609
+ upstreamApiFlavorProbe = null
1610
+ upstreamApiFlavorCheckedAt = 0
1611
+ healthProbeState = { ok: false, reachable: false, status: 0, checkedAt: 0, error: '' }
1612
+ try { void startCompatibleEventCollectors().catch(() => {}) } catch {}
1613
+ try { void loginAutostart.refresh().catch(() => {}) } catch {}
1614
+ void refreshHealthProbe(true).catch(() => {})
1615
+ return UPSTREAM.origin
1616
+ }
1566
1617
  const DSH_HEALTH_PATH = String(process.env.DSH_HEALTH_PATH || '/').startsWith('/')
1567
1618
  ? String(process.env.DSH_HEALTH_PATH || '/')
1568
1619
  : '/' + String(process.env.DSH_HEALTH_PATH)
@@ -1835,7 +1886,7 @@ const FS_PREVIEW_EXTENSIONS = new Set([
1835
1886
  const loginAutostart = createLoginAutostart({
1836
1887
  home: os.homedir(), platform: process.platform, executable: process.execPath,
1837
1888
  script: __filename, packaged: !!process.pkg, electron: !!process.versions.electron,
1838
- sourceDir: ROOT, env: process.env, port: PORT, host: HOST, upstream: UPSTREAM.origin,
1889
+ sourceDir: ROOT, env: process.env, port: PORT, host: HOST, upstream: () => UPSTREAM.origin,
1839
1890
  run: code => new Promise((resolve, reject) => {
1840
1891
  execFile('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(code, 'utf16le').toString('base64')],
1841
1892
  { windowsHide: true, timeout: 15000, maxBuffer: 64 * 1024, encoding: 'utf8' }, (error, stdout) => {
@@ -4046,8 +4097,14 @@ function serveWsTicket(req, res, url) {
4046
4097
  }
4047
4098
 
4048
4099
  function serveEventPoll(req, res, url) {
4100
+ if (req.method === 'OPTIONS') {
4101
+ cors(res)
4102
+ res.writeHead(204)
4103
+ res.end()
4104
+ return
4105
+ }
4049
4106
  if (req.method !== 'GET') {
4050
- res.writeHead(405, { allow: 'GET' })
4107
+ res.writeHead(405, { allow: 'GET, OPTIONS' })
4051
4108
  res.end()
4052
4109
  return
4053
4110
  }
@@ -4586,6 +4643,10 @@ function startModernEventCollector() {
4586
4643
  for (const sessionId of sessionStreams.keys()) forgetModernSessionStream(sessionId)
4587
4644
  sessionStreams.clear()
4588
4645
  modernState.eventClientId = ''
4646
+ // A closed upstream stream leaves every pending approval/question unanswerable:
4647
+ // its old event clientId will never return. Resolve them as cancelled now, or
4648
+ // reconnecting clients replay dead cards from the baseline forever.
4649
+ for (const eventId of [...modernState.pendingEvents.keys()]) resolveModernPendingEvent(eventId, true)
4589
4650
  setConnected(false, error)
4590
4651
  for (const state of Object.values(eventCollectorState)) {
4591
4652
  state.lastCloseCode = Number(code) || 0
@@ -5598,6 +5659,26 @@ async function serveAdminApi(req, res, url) {
5598
5659
  }, 150)
5599
5660
  return
5600
5661
  }
5662
+ if (sub === '/upstream' && req.method === 'POST') {
5663
+ if (!adminAuthorized(req, url)) {
5664
+ res.writeHead(401, { 'content-type': 'application/json; charset=utf-8' })
5665
+ res.end(JSON.stringify({ error: 'unauthorized' }))
5666
+ return
5667
+ }
5668
+ withRequestBody(req, res, 4096, body => {
5669
+ let value
5670
+ try { value = JSON.parse(body || '{}') } catch { value = null }
5671
+ const applied = value && typeof value.url === 'string' ? applyUpstream(value.url) : null
5672
+ if (!applied) {
5673
+ res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
5674
+ res.end(JSON.stringify({ error: 'invalid-upstream' }))
5675
+ return
5676
+ }
5677
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
5678
+ res.end(JSON.stringify({ ok: true, upstream: applied }))
5679
+ })
5680
+ return
5681
+ }
5601
5682
  if (sub === '/note' && req.method === 'POST') {
5602
5683
  if (!adminAuthorized(req, url)) {
5603
5684
  res.writeHead(401, { 'content-type': 'application/json; charset=utf-8' })
@@ -5651,7 +5732,11 @@ async function serveRelaySettings(req, res, url) {
5651
5732
  if (!['GET', 'POST'].includes(req.method)) { res.setHeader('allow', 'GET, POST, OPTIONS'); return reply(405, { error: 'METHOD_NOT_ALLOWED' }) }
5652
5733
  const canManage = adminAuthorized(req, url)
5653
5734
  if (!canManage && !authorized(req, url)) return reply(401, { error: 'unauthorized' })
5654
- if (req.method === 'GET') return reply(200, { ...relayHost.status(), canManage, canManageDevices: canManage && localRelayManagement(req), canPairLocally: localRelayPairing(req) })
5735
+ if (req.method === 'GET') {
5736
+ const canManageDevices = canManage && localRelayManagement(req)
5737
+ const pairingActivity = canManageDevices ? relayHost.pairingActivity() : undefined
5738
+ return reply(200, { ...relayHost.status(), canManage, canManageDevices, canPairLocally: localRelayPairing(req), pairingActivity })
5739
+ }
5655
5740
  if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
5656
5741
  try {
5657
5742
  const chunks = []; let size = 0
@@ -5713,14 +5798,14 @@ async function serveRelayPair(req, res, url) {
5713
5798
  for await (const chunk of req) {size+=chunk.length;if(size>1024){pairLog('pair.rejected',{code:'BODY_TOO_LARGE'});return reply(413,{error:'BODY_TOO_LARGE'})};chunks.push(chunk)}
5714
5799
  let value
5715
5800
  try {value=JSON.parse(Buffer.concat(chunks).toString('utf8'))}catch{pairLog('pair.rejected',{code:'INVALID_JSON'});return reply(400,{error:'INVALID_JSON'})}
5716
- if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key=>!['fingerprint','label'].includes(key))) { pairLog('pair.rejected',{code:'INVALID_DEVICE'}); return reply(400,{error:'INVALID_DEVICE'}) }
5801
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key=>!['fingerprint','label','setupId'].includes(key)) || (value.setupId !== undefined && (typeof value.setupId !== 'string' || !/^[a-f0-9]{32}$/.test(value.setupId)))) { pairLog('pair.rejected',{code:'INVALID_DEVICE'}); return reply(400,{error:'INVALID_DEVICE'}) }
5717
5802
  if (!relayHost.e2eeEnabled || !relayHost.endpoint) { pairLog('pair.rejected',{code:'E2EE_NOT_CONFIGURED'}); return reply(409,{error:'E2EE_NOT_CONFIGURED'}) }
5718
5803
  if (value.fingerprint !== relayHost.e2eeFingerprint) { pairLog('pair.rejected',{code:'E2EE_PAIRING_CHANGED'}); return reply(409,{error:'E2EE_PAIRING_CHANGED'}) }
5719
- const result=await relayHost.changeDevice({action:'create-device',label:value.label,days:30})
5804
+ const result=await relayHost.changeDevice({action:'create-device',label:value.label,days:30,setupId:value.setupId})
5720
5805
  pairLog('pair.created', { deviceId: String(result?.pairing?.deviceId || '').slice(0, 64), expiresAt: Number(result?.pairing?.expiresAt) || 0, label: String(value.label || '').slice(0, 80), relayPhase: String(relayHost.phase || '') })
5721
5806
  return reply(200,{pairing:result.pairing})
5722
5807
  } catch(error) {
5723
- const known=new Set(['INVALID_DEVICE','E2EE_DEVICE_LIMIT','RELAY_OPERATION_BUSY','E2EE_NOT_CONFIGURED','HOST_NOT_CONFIGURED'])
5808
+ const known=new Set(['INVALID_DEVICE','E2EE_DEVICE_LIMIT','E2EE_SETUP_ALREADY_USED','RELAY_OPERATION_BUSY','E2EE_NOT_CONFIGURED','HOST_NOT_CONFIGURED'])
5724
5809
  pairLog('pair.failed', { code: String(error?.code || 'E2EE_OPERATION_FAILED'), httpStatus: Number(error?.status) || 503 })
5725
5810
  return reply(error.status||503,{error:known.has(error.code)?error.code:'E2EE_OPERATION_FAILED'})
5726
5811
  }
@@ -7016,6 +7101,13 @@ async function forwardLegacyRpc(url, raw, allowVisionBridge = true) {
7016
7101
 
7017
7102
  function sendBufferedUpstreamResponse(res, response) {
7018
7103
  cors(res)
7104
+ if (isSessionListRequest(res.req) && typeof response.raw === 'string') {
7105
+ try {
7106
+ const parsed = JSON.parse(response.raw)
7107
+ compactSessionList(parsed)
7108
+ response = { ...response, raw: JSON.stringify(parsed) }
7109
+ } catch { }
7110
+ }
7019
7111
  sendHttpBody(res, response.status || 502, {
7020
7112
  'content-type': response.headers?.get?.('content-type') || 'application/json; charset=utf-8',
7021
7113
  'cache-control': 'no-store',
@@ -7091,7 +7183,7 @@ function operationResult(body) {
7091
7183
  message: (code === 'image-vision-failed' && Object.hasOwn(visionGuidance, body.result.error?.details?.reason) && visionGuidance[body.result.error.details.reason]) || (Object.hasOwn(guidance, code) && guidance[code]) || '主机拒绝了操作,请核对会话和当前配置。'
7092
7184
  } } }
7093
7185
  const input = body.result.value || {}, value = {}
7094
- for (const key of ['accepted', 'sessionId', 'workspaceId', 'archivedSessionIds', 'ref', 'selected', 'model', 'cleared']) {
7186
+ for (const key of ['accepted', 'sessionId', 'workspaceId', 'archivedSessionIds', 'ref', 'selected', 'model', 'cleared', 'title', 'seq']) {
7095
7187
  if (input[key] !== undefined) value[key] = input[key]
7096
7188
  }
7097
7189
  if (input.workspace) value.workspace = Object.fromEntries(['workspaceId','path','title','sessionIds'].filter(key => input.workspace[key] !== undefined).map(key => [key,input.workspace[key]]))
@@ -7224,9 +7316,26 @@ async function proxyLegacyRpcWithModernFallback(req, res, url) {
7224
7316
  }
7225
7317
  }
7226
7318
  cors(res)
7319
+ if (body.method === 'session.list') compactSessionList(translated)
7227
7320
  sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify(translated), compressibleRpc(req))
7228
7321
  }
7229
7322
 
7323
+ // Session projections include the full per-session context headers and activity feed. The
7324
+ // Remote session list never renders either one, and here they were about 76% of the payload.
7325
+ function isSessionListRequest(req) {
7326
+ return String(req?.url || '').split('?')[0] === '/api/session.list'
7327
+ }
7328
+ function compactSessionList(response) {
7329
+ const items = response?.result?.value?.items
7330
+ if (!Array.isArray(items)) return
7331
+ for (const item of items) {
7332
+ const values = item?.projections?.values
7333
+ if (!values || typeof values !== 'object') continue
7334
+ delete values.contextHeaders
7335
+ delete values.contextActivity
7336
+ }
7337
+ }
7338
+
7230
7339
  async function proxyModernApi(req, res, url) {
7231
7340
  if (req.method !== 'POST' || url.pathname.startsWith('/remote/')) return false
7232
7341
  // dsh-context is a Connection Fetch route with its own JSON contract, not RPC.
@@ -7241,6 +7350,9 @@ async function proxyModernApi(req, res, url) {
7241
7350
  const eventId = body.rpcId
7242
7351
  const pending = modernState.pendingEvents.get(eventId)
7243
7352
  if (!pending || !modernState.eventClientId) {
7353
+ // A pending request without a live event client is dead: drop it and tell
7354
+ // every connected client, so the card does not reappear after reconnect.
7355
+ if (pending) resolveModernPendingEvent(eventId, true)
7244
7356
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
7245
7357
  res.end(JSON.stringify({ accepted: false }))
7246
7358
  return true
@@ -7254,7 +7366,11 @@ async function proxyModernApi(req, res, url) {
7254
7366
  outcome: { kind: 'result', value: answer },
7255
7367
  })
7256
7368
  const accepted = response.status === 200 && response.body?.result?.ok === true
7369
+ // accepted:false means the host no longer holds this request. Clear the
7370
+ // replay baseline and broadcast a cancelled resolution instead of leaving a
7371
+ // stale card that every reconnect restores.
7257
7372
  if (accepted) resolveModernPendingEvent(eventId, false)
7373
+ else resolveModernPendingEvent(eventId, true)
7258
7374
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
7259
7375
  res.end(JSON.stringify({ accepted }))
7260
7376
  return true
@@ -7271,6 +7387,7 @@ async function proxyModernApi(req, res, url) {
7271
7387
  sendBufferedUpstreamResponse(res, legacy)
7272
7388
  return true
7273
7389
  }
7390
+ if (body.method === 'session.list') compactSessionList(translated)
7274
7391
  sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify(translated), compressibleRpc(req))
7275
7392
  return true
7276
7393
  } catch (error) {
@@ -7283,8 +7400,59 @@ async function proxyModernApi(req, res, url) {
7283
7400
  }
7284
7401
  }
7285
7402
 
7403
+ // Legacy /api/respond proxies straight to DSH. When DSH answers accepted:false the
7404
+ // request is already gone; clear its replay baseline and broadcast the resolution so
7405
+ // phones do not restore a dead card on every reconnect.
7406
+ function resolveLegacyPending(body) {
7407
+ const value = body?.result?.value && typeof body.result.value === 'object' ? body.result.value : {}
7408
+ const rpcId = typeof body?.rpcId === 'string' ? body.rpcId : ''
7409
+ const sessionId = typeof value.sessionId === 'string' ? value.sessionId : ''
7410
+ const approvalId = typeof value.approvalId === 'string' ? value.approvalId : ''
7411
+ if (approvalId) legacyPush('mux', { type: 'approval/resolved', sessionId, approvalId, outcome: 'cancelled' })
7412
+ else if (rpcId) legacyPush('mux', { type: 'question/resolved', sessionId, questionRpcId: rpcId, outcome: 'cancelled' })
7413
+ }
7414
+
7415
+ async function proxyLegacyRespond(req, res) {
7416
+ let raw
7417
+ try {
7418
+ raw = await readBody(req, 64 * 1024)
7419
+ } catch (error) {
7420
+ cors(res)
7421
+ res.writeHead(error.status === 413 ? 413 : 400, { 'content-type': 'application/json; charset=utf-8' })
7422
+ res.end(JSON.stringify({ error: error.status === 413 ? 'body-too-large' : 'bad-request' }))
7423
+ return
7424
+ }
7425
+ const headers = { host: UPSTREAM.host, 'content-type': 'application/json', 'content-length': String(Buffer.byteLength(raw)) }
7426
+ Object.assign(headers, dshUpstreamHeaders())
7427
+ let upstream, text = ''
7428
+ try {
7429
+ upstream = await fetch(UPSTREAM.origin + '/api/respond', {
7430
+ method: 'POST', headers, body: raw, redirect: 'error',
7431
+ signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS),
7432
+ })
7433
+ text = await upstream.text()
7434
+ } catch (error) {
7435
+ cors(res)
7436
+ if (!res.headersSent) res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
7437
+ res.end(JSON.stringify({ error: 'upstream-unreachable', detail: String(error?.message || error) }))
7438
+ return
7439
+ }
7440
+ let accepted = null
7441
+ try { accepted = JSON.parse(text)?.accepted } catch {}
7442
+ if (upstream.ok && accepted === false) {
7443
+ try { resolveLegacyPending(JSON.parse(raw)) } catch {}
7444
+ }
7445
+ cors(res)
7446
+ res.writeHead(upstream.status, {
7447
+ 'content-type': upstream.headers.get('content-type') || 'application/json; charset=utf-8',
7448
+ 'cache-control': 'no-store',
7449
+ })
7450
+ res.end(text)
7451
+ }
7452
+
7286
7453
  async function proxyLegacyApi(req, res, url) {
7287
7454
  const method = url.pathname.startsWith('/api/') ? decodeURIComponent(url.pathname.slice('/api/'.length)) : ''
7455
+ if (req.method === 'POST' && url.pathname === '/api/respond') return proxyLegacyRespond(req, res)
7288
7456
  if (req.method === 'POST' && ADAPTIVE_RPC_METHODS.has(method)) {
7289
7457
  return proxyLegacyRpcWithModernFallback(req, res, url)
7290
7458
  }
package/index.mjs CHANGED
@@ -303,6 +303,13 @@ function portInUse(port) {
303
303
  }
304
304
 
305
305
  let gatewayHealthJob = null
306
+ /** Probe a loopback DSH origin with a short timeout; any non-5xx answer proves the listener is up. */
307
+ async function upstreamReachable(url) {
308
+ try {
309
+ const res = await fetch(String(url).replace(/\/+$/, '') + '/', { signal: AbortSignal.timeout(2500), redirect: 'manual' })
310
+ return res.status < 500
311
+ } catch { return false }
312
+ }
306
313
  async function gatewayRunning() {
307
314
  const base = gatewayBase()
308
315
  if (gatewayHealthJob?.base === base) return gatewayHealthJob.promise
@@ -911,9 +918,13 @@ async function startGateway() {
911
918
  delete gatewayEnv.NODE_CHANNEL_SERIALIZATION_MODE
912
919
  let child = null
913
920
  try {
921
+ // Windows: a detached console child gets its own console window. Without
922
+ // windowsHide the user sees a stray black window, and closing that window
923
+ // terminates the gateway. Keep the supervisor invisible and log-only.
914
924
  child = spawn(candidate.executable, [script, '--supervise'], {
915
925
  cwd: gatewayCwd,
916
926
  detached: true,
927
+ windowsHide: true,
917
928
  stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'],
918
929
  env: gatewayEnv,
919
930
  })
@@ -990,9 +1001,22 @@ function ensureGateway() {
990
1001
  && normalizeRuntimePath(actualRuntime.executable, process.platform) !== normalizeRuntimePath(runtime.executable, process.platform)
991
1002
  // 上游暂时不可达不应重启网关: VPN/DSH 重启/短暂网络抖动时,
992
1003
  // 重启只能制造额外断线,网关应保持运行并通过 /health 暴露 degraded 状态。
993
- if (versionMismatch || runtimeMismatch || (oldUpstream && oldUpstream !== upstream) || (!oldUpstream && upstream)) {
1004
+ const upstreamChanged = (oldUpstream && oldUpstream !== upstream) || (!oldUpstream && upstream)
1005
+ if (versionMismatch || runtimeMismatch || upstreamChanged) {
994
1006
  logGateway(`网关需刷新: 版本 ${oldVersion} -> ${version}, 上游 ${oldUpstream || '?'} -> ${upstream}`)
995
1007
  if (runtimeMismatch) logGateway('网关解释器需迁移: ' + actualRuntime.executable + ' -> ' + runtime.executable)
1008
+ // DSH desktop restarts on a new loopback port. A live gateway can repoint its
1009
+ // upstream in place, which keeps the relay control channel and public path up;
1010
+ // only a version/runtime change still needs a gateway restart.
1011
+ if (upstreamChanged && oldUpstream && !versionMismatch && !runtimeMismatch) {
1012
+ const reachable = await upstreamReachable(upstream)
1013
+ const swapped = reachable ? await proxyGateway('/admin/api/upstream', 'POST', JSON.stringify({ url: upstream })) : null
1014
+ if (swapped?.status === 200 && swapped.json?.ok === true) {
1015
+ logGateway(`上游已热切换: ${oldUpstream} -> ${upstream}`)
1016
+ return true
1017
+ }
1018
+ logGateway(`上游热切换未生效(${reachable ? swapped?.json?.error || swapped?.status || 'unknown' : '上游暂不可达'}), 回退重启网关`)
1019
+ }
996
1020
  if (!await killGateway(health)) {
997
1021
  logGateway('拒绝自动重启: 无法通过认证关闭旧网关,请检查令牌或端口占用')
998
1022
  return false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.8.5",
3
+ "version": "0.8.7",
4
4
  "description": "DSH Remote 官方 bundle 插件:更多菜单中的手机连接入口、首次连接提示与浏览器管理控制台;内置网关自动启停,支持手机远程会话、审批、文件互传和设备管理。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
package/public/admin.html CHANGED
@@ -1,24 +1,24 @@
1
1
  <!doctype html>
2
2
  <html lang="zh-CN">
3
3
  <head>
4
- <meta name="dsh-remote-build" content="7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
4
+ <meta name="dsh-remote-build" content="7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
5
5
  <meta charset="utf-8">
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
7
7
  <meta name="theme-color" content="#0D1117">
8
8
  <title>DSH Remote · 管理</title>
9
9
  <script>/* 首帧前应用皮肤 */ (function(){try{var t=localStorage.getItem('dshTheme');if(t!=='default'&&t!=='dark'&&t!=='light'&&t!=='neutral'&&t!=='mono'&&t!=='fish'&&t!=='penguin'&&t!=='penguin-night'&&t!=='bocchi'&&t!=='nijika'&&t!=='ryo'&&t!=='kita'){t='fish'}}catch(e){t='fish'}document.documentElement.setAttribute('data-theme',t)})()</script>
10
- <link rel="stylesheet" href="../styles.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
11
- <link rel="stylesheet" href="../relay-settings.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
12
- <link rel="stylesheet" href="../insights.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
13
- <link rel="stylesheet" href="../setup.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
14
- <link rel="stylesheet" href="../doctor.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
15
- <link rel="stylesheet" href="../skins/blue-fish/skin.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
16
- <link rel="stylesheet" href="../skins/penguin/skin.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
17
- <link rel="stylesheet" href="../skins/bocchi/skin.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
18
- <link rel="stylesheet" href="../skins/kessoku/skin.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
19
- <link rel="stylesheet" href="../skins/nijika/skin.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
20
- <link rel="stylesheet" href="../skins/ryo/skin.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
21
- <link rel="stylesheet" href="../skins/kita/skin.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
10
+ <link rel="stylesheet" href="../styles.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
11
+ <link rel="stylesheet" href="../relay-settings.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
12
+ <link rel="stylesheet" href="../insights.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
13
+ <link rel="stylesheet" href="../setup.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
14
+ <link rel="stylesheet" href="../doctor.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
15
+ <link rel="stylesheet" href="../skins/blue-fish/skin.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
16
+ <link rel="stylesheet" href="../skins/penguin/skin.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
17
+ <link rel="stylesheet" href="../skins/bocchi/skin.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
18
+ <link rel="stylesheet" href="../skins/kessoku/skin.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
19
+ <link rel="stylesheet" href="../skins/nijika/skin.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
20
+ <link rel="stylesheet" href="../skins/ryo/skin.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
21
+ <link rel="stylesheet" href="../skins/kita/skin.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
22
22
  <style>
23
23
  .admin-wrap { max-width: 1180px; margin: 0 auto; padding: calc(env(safe-area-inset-top, 0px) + 14px) 14px 40px; }
24
24
  .admin-title {
@@ -348,8 +348,8 @@
348
348
  .admin-title .left { gap: 7px; }
349
349
  }
350
350
  </style>
351
- <link rel="stylesheet" href="../remote-ui.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
352
- <link rel="stylesheet" href="../theme-picker.css?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623">
351
+ <link rel="stylesheet" href="../remote-ui.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
352
+ <link rel="stylesheet" href="../theme-picker.css?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3">
353
353
  </head>
354
354
  <body>
355
355
  <div class="admin-wrap">
@@ -801,20 +801,20 @@
801
801
  }
802
802
  }
803
803
  </script>
804
- <script src="../setup.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
805
- <script src="../qrcode.min.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
806
- <script src="../i18n.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
807
- <script src="../theme.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
808
- <script src="../vendor/gsap/gsap.min.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
809
- <script src="../motion.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
810
- <script src="../remote-state.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
811
- <script src="../remote-ui.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
812
- <script src="../admin.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
813
- <script src="../doctor.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
814
- <script src="../doctor-entry.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
815
- <script src="../sponsor-entry.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
816
- <script src="../relay-devices.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
817
- <script src="../relay-settings.js?dsr-build=7006a2673f19f69788f5c533fbcf9ca1f077d0b4f3b92f4eb3b000ed4ee85623"></script>
804
+ <script src="../setup.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
805
+ <script src="../qrcode.min.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
806
+ <script src="../i18n.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
807
+ <script src="../theme.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
808
+ <script src="../vendor/gsap/gsap.min.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
809
+ <script src="../motion.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
810
+ <script src="../remote-state.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
811
+ <script src="../remote-ui.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
812
+ <script src="../admin.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
813
+ <script src="../doctor.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
814
+ <script src="../doctor-entry.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
815
+ <script src="../sponsor-entry.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
816
+ <script src="../relay-devices.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
817
+ <script src="../relay-settings.js?dsr-build=7b7352352544bd35e441ffdb4de480368defbe9386c58dff9a6ed41c2318b2e3"></script>
818
818
  <script>window.mountAdminRelaySettings?.()</script>
819
819
  </body>
820
820
  </html>
package/public/admin.js CHANGED
@@ -13,7 +13,7 @@ const pluginMode = location.pathname === '/remote'
13
13
  const API = pluginMode ? '/remote/admin/api' : '/admin/api'
14
14
  window.mountAdminRelaySettings = () => window.DshRelaySettings?.mount($('relay-settings'), {
15
15
  connection: () => { const saved=token;return {url:route=>API+route,headers:adminHeaders({},saved),valid:()=>token===saved} },
16
- path:'/relay', credentials:'same-origin'
16
+ path:'/relay', credentials:'same-origin', phonePairingCode, deviceManagement:!pluginMode
17
17
  })
18
18
  // 沙箱 iframe/隐私模式里 localStorage 可能抛 SecurityError, 不能让它杀死整个页面
19
19
  const store = {
@@ -661,6 +661,27 @@ function pairTarget(st, accessToken) {
661
661
  }
662
662
  }
663
663
 
664
+ function pairQrSvg(url) {
665
+ const qr = window.qrcode(0, 'M')
666
+ qr.addData(url)
667
+ qr.make()
668
+ return qr.createSvgTag({ cellSize: 4, margin: 2, scalable: true })
669
+ }
670
+
671
+ async function phonePairingCode(setupId) {
672
+ const st = lastState, currentToken = token
673
+ if (st?.mode !== 'gateway' || st.gatewayAuthError || !enabledHostIPs(st).length) return ''
674
+ let access = shownToken
675
+ if (st.deviceKeys?.enabled) {
676
+ const note = I18N.lang === 'en' ? 'Android phone' : 'Android 手机'
677
+ access = (await deviceKeyMutation('create', { note }))?.entry?.token
678
+ }
679
+ if (!access || token !== currentToken) return ''
680
+ const url = new URL(pairTarget(st, access).url)
681
+ url.searchParams.set('relaySetup', setupId)
682
+ return pairQrSvg(url.href)
683
+ }
684
+
664
685
  function renderQr(st) {
665
686
  const box = $('pair-box')
666
687
  const accessToken = qrToken || shownToken
@@ -670,10 +691,7 @@ function renderQr(st) {
670
691
  }
671
692
  try {
672
693
  const pt = pairTarget(st, accessToken)
673
- const qr = window.qrcode(0, 'M')
674
- qr.addData(pt.url)
675
- qr.make()
676
- $('pair-qr').innerHTML = qr.createSvgTag({ cellSize: 4, margin: 2, scalable: true })
694
+ $('pair-qr').innerHTML = pairQrSvg(pt.url)
677
695
  $('pair-hint').textContent = `${qrLabel ? qrLabel + ' · ' : ''}${t('pair.hint', { base: pt.base })}`
678
696
  box.classList.remove('hidden')
679
697
  } catch (e) {