dsh-remote-plugin 0.7.2 → 0.7.4
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/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +453 -90
- package/index.mjs +55 -18
- package/package.json +1 -1
- package/public/admin.js +15 -2
- package/public/app.js +468 -371
- package/public/desktop/desktop.css +101 -0
- package/public/desktop/desktop.html +67 -23
- package/public/desktop/desktop.js +445 -175
- package/public/history.js +167 -0
- package/public/index.html +62 -22
- package/public/link-check.js +109 -0
- package/public/network.js +56 -0
- package/public/plugin-center.css +11 -0
- package/public/plugin-center.js +92 -39
- package/public/plugin.js +8 -1
- package/public/styles.css +107 -2
- package/public/update.json +12 -12
- package/public/version.json +1 -1
package/gateway.cjs
CHANGED
|
@@ -36,6 +36,141 @@ const fs = require('node:fs')
|
|
|
36
36
|
const path = require('node:path')
|
|
37
37
|
const os = require('node:os')
|
|
38
38
|
const crypto = require('node:crypto')
|
|
39
|
+
const zlib = require('node:zlib')
|
|
40
|
+
const { pipeline } = require('node:stream')
|
|
41
|
+
|
|
42
|
+
// Compression is local to Remote responses, without changing DSH prototypes.
|
|
43
|
+
const HTTP_COMPRESSION = process.env.GATEWAY_HTTP_COMPRESSION !== '0'
|
|
44
|
+
function acceptsGzip(req) {
|
|
45
|
+
const choices = new Map(String(req.headers['accept-encoding'] || '').toLowerCase().split(',').map(part => {
|
|
46
|
+
const [name, ...params] = part.trim().split(';')
|
|
47
|
+
const weight = params.find(p => /^\s*q\s*=/.test(p))
|
|
48
|
+
const q = weight ? Number(weight.split('=')[1]) : 1
|
|
49
|
+
return [name, Number.isFinite(q) && q >= 0 && q <= 1 ? q : 0]
|
|
50
|
+
}))
|
|
51
|
+
return (choices.get('gzip') ?? choices.get('*') ?? 0) > 0
|
|
52
|
+
}
|
|
53
|
+
function compressibleType(type) {
|
|
54
|
+
return /^(?:text\/(?:html|css|plain|javascript|xml)|application\/(?:javascript|json|manifest\+json|xml)|image\/svg\+xml)(?:;|$)/i.test(String(type || ''))
|
|
55
|
+
}
|
|
56
|
+
function addEncodingVary(headers, existing = '') {
|
|
57
|
+
const values = (String(existing || '') + ',' + String(headers.vary || '')).split(',').map(v => v.trim()).filter(Boolean)
|
|
58
|
+
if (!values.some(v => v.toLowerCase() === 'accept-encoding' || v === '*')) values.push('Accept-Encoding')
|
|
59
|
+
headers.vary = values.join(', ')
|
|
60
|
+
return headers
|
|
61
|
+
}
|
|
62
|
+
function sendHttpBody(res, status, headers, body, compress = false) {
|
|
63
|
+
const data = Buffer.isBuffer(body) ? body : Buffer.from(String(body || ''))
|
|
64
|
+
const req = res.req, out = { ...headers }
|
|
65
|
+
if (compress) addEncodingVary(out, res.getHeader?.('vary'))
|
|
66
|
+
const finish = bytes => {
|
|
67
|
+
if (res.destroyed || res.writableEnded) return
|
|
68
|
+
res.writeHead(status, { ...out, 'content-length': bytes.length })
|
|
69
|
+
res.end(req?.method === 'HEAD' ? undefined : bytes)
|
|
70
|
+
}
|
|
71
|
+
if (!compress || !HTTP_COMPRESSION || !req || req.method === 'HEAD' || status !== 200 || data.length < 1024
|
|
72
|
+
|| req.headers.range || out['content-encoding'] || /no-transform/i.test(out['cache-control'] || '')
|
|
73
|
+
|| !compressibleType(out['content-type']) || !acceptsGzip(req)) return finish(data)
|
|
74
|
+
zlib.gzip(data, { level: 3 }, (error, zipped) => {
|
|
75
|
+
if (error || zipped.length >= data.length) return finish(data)
|
|
76
|
+
out['content-encoding'] = 'gzip'
|
|
77
|
+
finish(zipped)
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
function compressibleRpc(req) {
|
|
81
|
+
const pathname = String(req?.url || '').split('?')[0]
|
|
82
|
+
return ['/api/session.history', '/api/session.list', '/api/workspace.list', '/api/host.describe'].includes(pathname)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Crash records deliberately contain facts and source positions, never arbitrary error text.
|
|
86
|
+
const CRASH_LOG_FILE=process.env.DSH_REMOTE_CRASH_LOG_FILE || path.join(os.homedir(),'.dsh-remote','crashes.jsonl')
|
|
87
|
+
const AUTO_RESTART=process.env.DSH_REMOTE_AUTO_RESTART!=='0'
|
|
88
|
+
const CRASH_KINDS=new Set(['fatal','exit','restart','restart-failed','restart-limit','manual-stop','startup','desktop-crash'])
|
|
89
|
+
const CRASH_COMPONENTS=new Set(['gateway','dsh','desktop'])
|
|
90
|
+
const CRASH_CODES=new Set(['EADDRINUSE','EACCES','EPERM','ENOENT','ENOMEM','ECONNRESET','ETIMEDOUT','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'])
|
|
91
|
+
function safeCrashRecord(value) {
|
|
92
|
+
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'}
|
|
93
|
+
if(Number.isInteger(value?.exitCode))row.exitCode=value.exitCode
|
|
94
|
+
if(/^(SIG[A-Z]+)$/.test(value?.signal||''))row.signal=value.signal
|
|
95
|
+
if(CRASH_CODES.has(value?.code))row.code=value.code
|
|
96
|
+
if(['Error','TypeError','RangeError','ReferenceError','SyntaxError','URIError','AggregateError'].includes(value?.errorName))row.errorName=value.errorName
|
|
97
|
+
if(Number.isInteger(value?.attempt)&&value.attempt>=0&&value.attempt<=10)row.attempt=value.attempt
|
|
98
|
+
if(Array.isArray(value?.frames))row.frames=value.frames.slice(0,4).filter(f=>['gateway.js','gateway.cjs','index.js'].includes(f?.file)&&Number.isInteger(f.line)&&Number.isInteger(f.column)).map(f=>({file:f.file,line:f.line,column:f.column}))
|
|
99
|
+
return row
|
|
100
|
+
}
|
|
101
|
+
function crashErrorFacts(error) {
|
|
102
|
+
const frames=[]
|
|
103
|
+
for(const line of String(error?.stack||'').split('\n').slice(1,12)){
|
|
104
|
+
const match=line.match(/(?:[\\/])(gateway\.(?:js|cjs)|index\.js):(\d+):(\d+)\)?$/)
|
|
105
|
+
if(match)frames.push({file:match[1],line:Number(match[2]),column:Number(match[3])})
|
|
106
|
+
}
|
|
107
|
+
return {code:error?.code,errorName:error?.name,frames}
|
|
108
|
+
}
|
|
109
|
+
function recordCrash(component,kind,facts={}) {
|
|
110
|
+
const row=safeCrashRecord({at:Date.now(),component,kind,...facts})
|
|
111
|
+
try {
|
|
112
|
+
fs.mkdirSync(path.dirname(CRASH_LOG_FILE),{recursive:true,mode:0o700})
|
|
113
|
+
if(fs.existsSync(CRASH_LOG_FILE)&&fs.statSync(CRASH_LOG_FILE).size>128*1024){try{fs.unlinkSync(CRASH_LOG_FILE+'.1')}catch{};fs.renameSync(CRASH_LOG_FILE,CRASH_LOG_FILE+'.1')}
|
|
114
|
+
fs.appendFileSync(CRASH_LOG_FILE,JSON.stringify(row)+'\n',{mode:0o600})
|
|
115
|
+
} catch {}
|
|
116
|
+
return row
|
|
117
|
+
}
|
|
118
|
+
function crashRecords(limit=40) {
|
|
119
|
+
const rows=[]
|
|
120
|
+
for(const file of [CRASH_LOG_FILE+'.1',CRASH_LOG_FILE])try{const stat=fs.statSync(file);if(stat.size>256*1024)continue;for(const line of fs.readFileSync(file,'utf8').split('\n'))try{rows.push(safeCrashRecord(JSON.parse(line)))}catch{}}catch{}
|
|
121
|
+
return rows.slice(-Math.min(40,limit))
|
|
122
|
+
}
|
|
123
|
+
function crashReply(res,status,value) {res.writeHead(status,{'content-type':'application/json; charset=utf-8','cache-control':'no-store'});res.end(JSON.stringify(value))}
|
|
124
|
+
function crashUploadSummary() {
|
|
125
|
+
// The deployed collector already persists serverInfo (500 chars), so this works before any server upgrade.
|
|
126
|
+
const recent=crashRecords().filter(r=>r.kind!=='startup'&&r.kind!=='manual-stop').slice(-3)
|
|
127
|
+
const report={schema:1,records:recent}
|
|
128
|
+
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()}
|
|
129
|
+
return report
|
|
130
|
+
}
|
|
131
|
+
function runGatewaySupervisor() {
|
|
132
|
+
const port=Number(process.env.PORT)||8787,lease=path.join(path.dirname(CRASH_LOG_FILE),'gateway-supervisor-'+port+'.json')
|
|
133
|
+
const nonce=crypto.randomBytes(12).toString('hex')
|
|
134
|
+
try {
|
|
135
|
+
fs.mkdirSync(path.dirname(lease),{recursive:true,mode:0o700})
|
|
136
|
+
if(fs.existsSync(lease)){
|
|
137
|
+
const old=JSON.parse(fs.readFileSync(lease,'utf8'));let alive=false
|
|
138
|
+
try{process.kill(old.pid,0);alive=true}catch(e){alive=e.code!=='ESRCH'}
|
|
139
|
+
if(alive){console.error('[recovery] supervisor already running');process.exit(78)}
|
|
140
|
+
fs.unlinkSync(lease)
|
|
141
|
+
}
|
|
142
|
+
fs.writeFileSync(lease,JSON.stringify({pid:process.pid,nonce}),{flag:'wx',mode:0o600})
|
|
143
|
+
} catch {console.error('[recovery] cannot acquire supervisor lease');process.exit(78)}
|
|
144
|
+
let worker=null,stopping=false,timer=null,attempts=[]
|
|
145
|
+
const cleanup=()=>{try{if(JSON.parse(fs.readFileSync(lease,'utf8')).nonce===nonce)fs.unlinkSync(lease)}catch{}}
|
|
146
|
+
process.once('exit',cleanup)
|
|
147
|
+
const stop=()=>{if(stopping)return;stopping=true;clearTimeout(timer);recordCrash('gateway','manual-stop');if(worker)worker.kill();else process.exit(0)}
|
|
148
|
+
process.on('SIGTERM',stop);process.on('SIGINT',stop)
|
|
149
|
+
const launch=()=>{
|
|
150
|
+
const env={...process.env,DSH_REMOTE_SUPERVISED:'1',DSH_REMOTE_SUPERVISOR_PID:String(process.pid)}
|
|
151
|
+
delete env.NODE_CHANNEL_FD;delete env.NODE_CHANNEL_SERIALIZATION_MODE
|
|
152
|
+
const args=process.pkg?process.argv.slice(2).filter(a=>a!=='--supervise'):[__filename,...process.argv.slice(2).filter(a=>a!=='--supervise')]
|
|
153
|
+
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)}
|
|
154
|
+
let handled=false
|
|
155
|
+
const exited=(code,signal)=>{
|
|
156
|
+
if(handled)return;handled=true;worker=null
|
|
157
|
+
if(stopping||code===0||code===78){process.exit(code===78?78:0);return}
|
|
158
|
+
recordCrash('gateway','exit',{exitCode:code,signal})
|
|
159
|
+
if(!AUTO_RESTART){process.exit(1);return}
|
|
160
|
+
const now=Date.now();attempts=attempts.filter(t=>now-t<5*60_000)
|
|
161
|
+
if(attempts.length>=5){recordCrash('gateway','restart-limit',{attempt:5});process.exit(1);return}
|
|
162
|
+
attempts.push(now);recordCrash('gateway','restart',{attempt:attempts.length})
|
|
163
|
+
timer=setTimeout(launch,Math.min(30000,1000*2**(attempts.length-1)))
|
|
164
|
+
}
|
|
165
|
+
worker.once('error',error=>{recordCrash('gateway','restart-failed',crashErrorFacts(error));exited(1,null)})
|
|
166
|
+
worker.once('exit',exited)
|
|
167
|
+
}
|
|
168
|
+
launch()
|
|
169
|
+
}
|
|
170
|
+
if(process.argv.includes('--supervise')&&process.env.DSH_REMOTE_SUPERVISED!=='1'){
|
|
171
|
+
runGatewaySupervisor()
|
|
172
|
+
}else{
|
|
173
|
+
|
|
39
174
|
|
|
40
175
|
let statsCore = null
|
|
41
176
|
let statsStore = null
|
|
@@ -259,6 +394,35 @@ function fsInsideReal(real) {
|
|
|
259
394
|
}
|
|
260
395
|
return false
|
|
261
396
|
}
|
|
397
|
+
// 网关自身的状态与安装目录永远不出现在 /fs 通道里: 设备密钥同样能访问 /fs,
|
|
398
|
+
// 若允许读取就等同于把主令牌(以及其它设备密钥)直接交出去, 允许写入还能替换
|
|
399
|
+
// 正在对外提供的静态资源或网关文件。显式配置到其它位置的状态文件按精确路径保护。
|
|
400
|
+
const FS_PROTECTED_DIRS = [...new Set([
|
|
401
|
+
path.resolve(path.join(FS_DEFAULT_ROOT, '.dsh-remote')),
|
|
402
|
+
path.resolve(ROOT),
|
|
403
|
+
])]
|
|
404
|
+
const FS_PROTECTED_FILES = [...new Set([TOKEN_FILE, DEVICE_KEYS_FILE, NOTES_FILE, WORKBENCH_FILE,
|
|
405
|
+
HANDOFF_FILE, DSH_UPSTREAM_COOKIE_FILE, DSH_LAUNCH_FILE].filter(Boolean).map(value => path.resolve(String(value))))]
|
|
406
|
+
|
|
407
|
+
function fsSamePath(left, right) {
|
|
408
|
+
const a = path.resolve(String(left || ''))
|
|
409
|
+
const b = path.resolve(String(right || ''))
|
|
410
|
+
return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** 路径是否命中受保护目录(目录内全部)或受保护文件(精确匹配)。realpath 结果同样适用。 */
|
|
414
|
+
function fsProtectedPath(abs) {
|
|
415
|
+
if (!abs) return true
|
|
416
|
+
const candidate = path.resolve(String(abs))
|
|
417
|
+
for (const dir of FS_PROTECTED_DIRS) {
|
|
418
|
+
if (fsInsideRoot(candidate, dir)) return true
|
|
419
|
+
}
|
|
420
|
+
for (const file of FS_PROTECTED_FILES) {
|
|
421
|
+
if (fsSamePath(candidate, file)) return true
|
|
422
|
+
}
|
|
423
|
+
return false
|
|
424
|
+
}
|
|
425
|
+
|
|
262
426
|
|
|
263
427
|
const FS_MIME = {
|
|
264
428
|
...MIME,
|
|
@@ -534,6 +698,7 @@ const runtimeState = {
|
|
|
534
698
|
unhandledRejections: 0,
|
|
535
699
|
lastErrorAt: 0,
|
|
536
700
|
lastError: '',
|
|
701
|
+
recovery: {enabled:AUTO_RESTART,supervised:process.env.DSH_REMOTE_SUPERVISED==='1',supervisorPid:Number(process.env.DSH_REMOTE_SUPERVISOR_PID)||0},
|
|
537
702
|
}
|
|
538
703
|
|
|
539
704
|
function pruneDevices(now = Date.now()) {
|
|
@@ -1043,8 +1208,11 @@ async function windowsServiceStatus() {
|
|
|
1043
1208
|
// a gateway restart or PID reuse must not turn an unrelated process into our child.
|
|
1044
1209
|
let dshManagedChild = null
|
|
1045
1210
|
let dshManagedExit = null
|
|
1211
|
+
const intentionalDshStops=new WeakSet()
|
|
1212
|
+
const desktopChildren=new Map()
|
|
1046
1213
|
function readDshLaunch() {
|
|
1047
1214
|
const config = JSON.parse(fs.readFileSync(DSH_LAUNCH_FILE, 'utf8'))
|
|
1215
|
+
if (config.kind === 'desktop') return readDesktopLaunch(config)
|
|
1048
1216
|
if (config.version !== 1 || !path.isAbsolute(config.executable || '') ||
|
|
1049
1217
|
!path.isAbsolute(config.cwd || '') || !Array.isArray(config.args) ||
|
|
1050
1218
|
!config.args.length || !config.args.every(arg => typeof arg === 'string' && !arg.includes('\0')) ||
|
|
@@ -1062,6 +1230,82 @@ function readDshLaunch() {
|
|
|
1062
1230
|
return { ...config, env }
|
|
1063
1231
|
}
|
|
1064
1232
|
|
|
1233
|
+
// Desktop roots are adopted only with birth time, executable, Host ancestry and TCP ownership evidence.
|
|
1234
|
+
// Never use taskkill /T: the detached gateway must survive the desktop's exit.
|
|
1235
|
+
function readDesktopLaunch(config) {
|
|
1236
|
+
const d = config.desktop, validPid = value => Number.isSafeInteger(value) && value > 0
|
|
1237
|
+
if (process.platform !== 'win32' || config.version !== 1 || config.profile !== 'desktop' ||
|
|
1238
|
+
!path.isAbsolute(config.executable || '') || !fs.statSync(config.executable).isFile() ||
|
|
1239
|
+
!path.isAbsolute(config.cwd || '') || !fs.statSync(config.cwd).isDirectory() ||
|
|
1240
|
+
!Array.isArray(config.args) || config.args.length || !d || !validPid(d.root?.pid) || !validPid(d.host?.pid) || d.root.pid === d.host.pid ||
|
|
1241
|
+
!/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(d.root.started || '') || !/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(d.host.started || '') ||
|
|
1242
|
+
!path.isAbsolute(d.profilePath || '') || !path.isAbsolute(d.hostScript || '') ||
|
|
1243
|
+
!/[\\/]@deepseek-ai[\\/]dsh-desktop-host[\\/]lib[\\/]index\.js$/.test(d.hostScript) ||
|
|
1244
|
+
!['127.0.0.1','localhost','[::1]'].includes(UPSTREAM.hostname) || config.upstream !== UPSTREAM.origin) throw new Error('Desktop 启动配置无效或与当前上游不匹配')
|
|
1245
|
+
return { ...config, env:typeof config.env?.DSH_HOME === 'string' ? {DSH_HOME:config.env.DSH_HOME} : {} }
|
|
1246
|
+
}
|
|
1247
|
+
async function desktopProcessEvidence(config) {
|
|
1248
|
+
const d = config.desktop
|
|
1249
|
+
const script = '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); $rows=@(' + [d.root.pid,d.host.pid].map(pid =>
|
|
1250
|
+
"Get-CimInstance Win32_Process -Filter 'ProcessId=" + pid + "' | ForEach-Object { @{pid=$_.ProcessId;parent=$_.ParentProcessId;executable=$_.ExecutablePath;command=$_.CommandLine;started=$_.CreationDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ')} }").join('; ') +
|
|
1251
|
+
'); $owners=@(Get-NetTCPConnection -State Listen -LocalPort ' + UPSTREAM_PORT + ' -ErrorAction SilentlyContinue | ForEach-Object {@{pid=$_.OwningProcess;address=$_.LocalAddress}}); @{rows=$rows;owners=$owners} | ConvertTo-Json -Compress -Depth 4'
|
|
1252
|
+
const result = await execFileResult('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command',script],10000)
|
|
1253
|
+
if (!result.ok) throw new Error('无法读取 Desktop 进程身份: ' + result.stderr)
|
|
1254
|
+
return JSON.parse(result.stdout)
|
|
1255
|
+
}
|
|
1256
|
+
function verifyDesktopEvidence(config, evidence) {
|
|
1257
|
+
const d=config.desktop, rows=evidence.rows || []
|
|
1258
|
+
const target=UPSTREAM.hostname.replace(/^\[|\]$/g,'').toLowerCase()
|
|
1259
|
+
const owners=(evidence.owners || []).filter(owner=>typeof owner==='number' ||
|
|
1260
|
+
(owner.address==='0.0.0.0' && !target.includes(':')) || owner.address==='::' ||
|
|
1261
|
+
(target==='localhost' ? ['127.0.0.1','::1'].includes(owner.address) : owner.address===target))
|
|
1262
|
+
.map(owner=>typeof owner==='number'?owner:owner.pid)
|
|
1263
|
+
const root=rows.find(row=>row.pid===d.root.pid), host=rows.find(row=>row.pid===d.host.pid)
|
|
1264
|
+
const sameExecutable=row=>row?.executable && path.resolve(row.executable).toLowerCase()===path.resolve(config.executable).toLowerCase()
|
|
1265
|
+
const rootValid=sameExecutable(root) && root.started===d.root.started && !/--(?:type|expose-internals)\b/.test(root.command || '')
|
|
1266
|
+
const hostValid=sameExecutable(host) && host.started===d.host.started && host.parent===d.root.pid &&
|
|
1267
|
+
(host.command || '').toLowerCase().includes(d.hostScript.toLowerCase()) && (host.command || '').toLowerCase().includes(d.profilePath.toLowerCase())
|
|
1268
|
+
return {rootValid:!!rootValid,hostValid:!!hostValid,occupied:owners.length>0,ownedPort:owners.length>0 && owners.every(pid=>pid===d.host.pid),rootPresent:!!root,hostPresent:!!host}
|
|
1269
|
+
}
|
|
1270
|
+
async function dshDesktopStatus(config) {
|
|
1271
|
+
try {
|
|
1272
|
+
const proof=verifyDesktopEvidence(config,await desktopProcessEvidence(config))
|
|
1273
|
+
const external=(proof.rootPresent&&!proof.rootValid)||(proof.hostPresent&&!proof.hostValid)||(proof.occupied&&(!proof.hostValid||!proof.ownedPort))
|
|
1274
|
+
return {ok:true,supported:true,manager:'desktop',service:'DSH Desktop',running:proof.rootValid,mainPid:proof.rootValid?config.desktop.root.pid:0,
|
|
1275
|
+
canRestart:proof.rootValid&&!external,canStart:!external,activeState:proof.rootValid?'active':'inactive',subState:external?'external':proof.rootValid?'running':'stopped',
|
|
1276
|
+
...(external?{code:'EXTERNAL_PROCESS',message:'Desktop 进程身份或端口归属已变化,请从当前 Desktop 重新加载 Remote 插件'}:{})}
|
|
1277
|
+
} catch(error) {return {ok:false,supported:false,manager:'desktop',code:'STATUS_PARSE_FAILED',message:'无法核验 Desktop 进程身份',detail:error.message,canRestart:false}}
|
|
1278
|
+
}
|
|
1279
|
+
async function executeDshDesktopAction(action, config) {
|
|
1280
|
+
let proof=verifyDesktopEvidence(config,await desktopProcessEvidence(config))
|
|
1281
|
+
if ((proof.rootPresent&&!proof.rootValid)||(proof.hostPresent&&!proof.hostValid)||(proof.occupied&&(!proof.hostValid||!proof.ownedPort))) return {ok:false,code:'EXTERNAL_PROCESS',error:'Desktop 进程身份或端口归属已变化,未停止任何进程'}
|
|
1282
|
+
if (action==='restart' && proof.rootValid) {
|
|
1283
|
+
const literal=value=>"'"+String(value).replace(/'/g,"''")+"'"
|
|
1284
|
+
const script="$ErrorActionPreference='Stop'; $p=Get-Process -Id "+config.desktop.root.pid+"; if($p.Path -ine "+literal(config.executable)+" -or $p.StartTime.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ') -ne "+literal(config.desktop.root.started)+") {throw 'Desktop process identity changed'}; $p.Kill(); if(-not $p.WaitForExit(10000)){throw 'Desktop stop timed out'}"
|
|
1285
|
+
const ownedChild=desktopChildren.get(config.desktop.root.pid)
|
|
1286
|
+
if(ownedChild)intentionalDshStops.add(ownedChild)
|
|
1287
|
+
const stopped=await execFileResult('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command',script],12000)
|
|
1288
|
+
if(!stopped.ok)return {ok:false,code:'PROCESS_STOP_TIMEOUT',error:'Desktop 未完成退出,未启动第二个实例'}
|
|
1289
|
+
// Host handles parent IPC disconnect through its normal shutdown service.
|
|
1290
|
+
const stopDeadline=Date.now()+15000
|
|
1291
|
+
do {
|
|
1292
|
+
proof=verifyDesktopEvidence(config,await desktopProcessEvidence(config))
|
|
1293
|
+
if(!proof.occupied&&!proof.hostPresent)break
|
|
1294
|
+
if(proof.hostPresent&&!proof.hostValid)return {ok:false,code:'EXTERNAL_PROCESS',error:'退出期间 Host 身份已变化,未启动第二个实例'}
|
|
1295
|
+
await delay(250)
|
|
1296
|
+
} while(Date.now()<stopDeadline)
|
|
1297
|
+
if(proof.occupied||proof.hostPresent)return {ok:false,code:'PROCESS_STOP_TIMEOUT',error:'Desktop Host 尚未退出,未启动第二个实例'}
|
|
1298
|
+
} else if(proof.rootValid)return {ok:true,code:'ALREADY_RUNNING'}
|
|
1299
|
+
if(await dshPortOccupied())return {ok:false,code:'PORT_IN_USE',error:'DSH 端口已被占用,未启动重复实例'}
|
|
1300
|
+
const env={...process.env,...config.env}
|
|
1301
|
+
for(const key of ['ELECTRON_RUN_AS_NODE','NODE_CHANNEL_FD','NODE_CHANNEL_SERIALIZATION_MODE','NODE_OPTIONS'])delete env[key]
|
|
1302
|
+
const child=spawn(config.executable,[],{cwd:config.cwd,env,detached:true,windowsHide:true,shell:false,stdio:'ignore'})
|
|
1303
|
+
try {await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject)})}catch(error){return {ok:false,code:'SERVICE_FAILED',error:'Desktop 启动失败: '+error.message}}
|
|
1304
|
+
child.on('error',()=>{});child.unref()
|
|
1305
|
+
desktopChildren.set(child.pid,child);watchDshChild(child,'desktop')
|
|
1306
|
+
return {ok:true,code:'STARTED',pid:child.pid}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1065
1309
|
function dshPortOccupied() {
|
|
1066
1310
|
return new Promise(resolve => {
|
|
1067
1311
|
const socket = net.connect({ host: UPSTREAM.hostname.replace(/^\[|\]$/g, ''), port: UPSTREAM.port || (UPSTREAM.protocol === 'https:' ? 443 : 80) })
|
|
@@ -1072,16 +1316,18 @@ function dshPortOccupied() {
|
|
|
1072
1316
|
})
|
|
1073
1317
|
}
|
|
1074
1318
|
|
|
1075
|
-
async function dshProcessStatus() {
|
|
1319
|
+
async function dshProcessStatus({ cachedProbe = false } = {}) {
|
|
1076
1320
|
const base = { ok: true, supported: true, manager: 'process', service: 'dsh-process', running: false, mainPid: 0, canRestart: false }
|
|
1077
1321
|
try { readDshLaunch() } catch (err) {
|
|
1078
1322
|
return { ...base, supported: false, code: 'LAUNCH_CONFIG_INVALID', message: '缺少有效 DSH 启动配置,请先从 DSH Web 启动 Remote 插件', detail: err.message }
|
|
1079
1323
|
}
|
|
1324
|
+
const launch = readDshLaunch()
|
|
1325
|
+
if (launch.kind === 'desktop') return dshDesktopStatus(launch)
|
|
1080
1326
|
if (dshManagedChild) {
|
|
1081
1327
|
return { ...base, running: true, mainPid: dshManagedChild.pid, owned: true, canRestart: true, activeState: 'active', subState: 'running' }
|
|
1082
1328
|
}
|
|
1083
1329
|
const occupied = await dshPortOccupied()
|
|
1084
|
-
const probe = occupied ? await probeDshUpstream() : null
|
|
1330
|
+
const probe = occupied ? await (cachedProbe ? refreshHealthProbe() : probeDshUpstream()) : null
|
|
1085
1331
|
return { ...base, running: !!probe?.ok, occupied, owned: false,
|
|
1086
1332
|
activeState: occupied ? (probe?.ok ? 'active' : 'inactive') : dshManagedExit ? 'failed' : 'inactive',
|
|
1087
1333
|
subState: occupied ? 'external' : 'stopped',
|
|
@@ -1091,6 +1337,7 @@ async function dshProcessStatus() {
|
|
|
1091
1337
|
|
|
1092
1338
|
async function executeDshProcessAction(action) {
|
|
1093
1339
|
const config = readDshLaunch()
|
|
1340
|
+
if (config.kind === 'desktop') return executeDshDesktopAction(action, config)
|
|
1094
1341
|
if (action === 'restart' && !dshManagedChild && await dshPortOccupied()) {
|
|
1095
1342
|
return { ok: false, code: 'EXTERNAL_PROCESS', error: '当前 DSH 并非本网关启动,不能安全重启;请在原启动器中停止后重试' }
|
|
1096
1343
|
}
|
|
@@ -1101,6 +1348,7 @@ async function executeDshProcessAction(action) {
|
|
|
1101
1348
|
const onExit = () => { clearTimeout(timer); resolve(true) }
|
|
1102
1349
|
child.once('exit', onExit)
|
|
1103
1350
|
})
|
|
1351
|
+
intentionalDshStops.add(child)
|
|
1104
1352
|
child.kill()
|
|
1105
1353
|
if (!await stopped) return { ok: false, code: 'PROCESS_STOP_TIMEOUT', error: 'DSH 进程未及时退出,未启动第二个实例' }
|
|
1106
1354
|
}
|
|
@@ -1117,6 +1365,7 @@ async function executeDshProcessAction(action) {
|
|
|
1117
1365
|
} finally { fs.closeSync(fd) }
|
|
1118
1366
|
dshManagedChild = child
|
|
1119
1367
|
dshManagedExit = null
|
|
1368
|
+
watchDshChild(child,'dsh')
|
|
1120
1369
|
child.once('exit', code => {
|
|
1121
1370
|
if (dshManagedChild === child) { dshManagedChild = null; dshManagedExit = { code, logFile } }
|
|
1122
1371
|
})
|
|
@@ -1129,17 +1378,17 @@ async function executeDshProcessAction(action) {
|
|
|
1129
1378
|
})
|
|
1130
1379
|
}
|
|
1131
1380
|
|
|
1132
|
-
async function dshServiceStatus() {
|
|
1381
|
+
async function dshServiceStatus(options = {}) {
|
|
1133
1382
|
if (!/^[A-Za-z0-9_.@-]+$/.test(DSH_SERVICE)) {
|
|
1134
1383
|
return { ok: false, supported: false, running: false, service: DSH_SERVICE, code: 'INVALID_SERVICE', message: 'DSH_REMOTE_DSH_SERVICE 服务名配置不合法' }
|
|
1135
1384
|
}
|
|
1136
1385
|
if (!DSH_CONTROL_SUPPORT.supported) {
|
|
1137
1386
|
return { ok: true, supported: false, running: false, service: DSH_SERVICE, ...DSH_CONTROL_SUPPORT }
|
|
1138
1387
|
}
|
|
1139
|
-
if (DSH_CONTROL_MODE === 'process') return dshProcessStatus()
|
|
1388
|
+
if (DSH_CONTROL_MODE === 'process') return dshProcessStatus(options)
|
|
1140
1389
|
if (process.platform === 'win32') {
|
|
1141
1390
|
const service = await windowsServiceStatus()
|
|
1142
|
-
if (DSH_CONTROL_MODE === 'auto' && service.code === 'SERVICE_NOT_FOUND') return dshProcessStatus()
|
|
1391
|
+
if (DSH_CONTROL_MODE === 'auto' && service.code === 'SERVICE_NOT_FOUND') return dshProcessStatus(options)
|
|
1143
1392
|
return { ...service, manager: 'windows' }
|
|
1144
1393
|
}
|
|
1145
1394
|
const r = await execFileResult(SYSTEMCTL, [
|
|
@@ -1180,7 +1429,7 @@ async function dshServiceStatus() {
|
|
|
1180
1429
|
}
|
|
1181
1430
|
|
|
1182
1431
|
async function executeDshServiceAction(action, initial) {
|
|
1183
|
-
if (initial?.manager
|
|
1432
|
+
if (['process','desktop'].includes(initial?.manager)) return executeDshProcessAction(action)
|
|
1184
1433
|
if (process.platform !== 'win32') {
|
|
1185
1434
|
return execFileResult(SYSTEMCTL, ['--user', '--no-block', action, DSH_SERVICE], 5000)
|
|
1186
1435
|
}
|
|
@@ -1209,12 +1458,12 @@ function delay(ms) {
|
|
|
1209
1458
|
return new Promise(resolvePromise => setTimeout(resolvePromise, ms))
|
|
1210
1459
|
}
|
|
1211
1460
|
|
|
1212
|
-
async function probeDshUpstream() {
|
|
1461
|
+
async function probeDshUpstream(timeoutMs = 2500) {
|
|
1213
1462
|
const startedAt = Date.now()
|
|
1214
1463
|
try {
|
|
1215
1464
|
const probe = await fetch(new URL(DSH_HEALTH_PATH, UPSTREAM), {
|
|
1216
1465
|
headers: dshUpstreamHeaders(),
|
|
1217
|
-
signal: AbortSignal.timeout(Math.min(
|
|
1466
|
+
signal: AbortSignal.timeout(Math.min(timeoutMs, UPSTREAM_REQUEST_TIMEOUT_MS)),
|
|
1218
1467
|
cache: 'no-store',
|
|
1219
1468
|
})
|
|
1220
1469
|
return {
|
|
@@ -1231,6 +1480,82 @@ async function probeDshUpstream() {
|
|
|
1231
1480
|
|
|
1232
1481
|
let dshControlOperation = null
|
|
1233
1482
|
|
|
1483
|
+
// Owned children expose abnormal exit codes. Adopted Desktop instances require an exact Windows crash event.
|
|
1484
|
+
const recoveryAttempts=new Map(),recoveryTimers=new Map()
|
|
1485
|
+
function watchDshChild(child,component) {
|
|
1486
|
+
child.once('exit',(exitCode,signal)=>{
|
|
1487
|
+
desktopChildren.delete(child.pid)
|
|
1488
|
+
if(intentionalDshStops.has(child)||exitCode===0)return
|
|
1489
|
+
recordCrash(component,'exit',{exitCode,signal})
|
|
1490
|
+
let config;try{config=readDshLaunch()}catch{return}
|
|
1491
|
+
if(component==='desktop'&&config.desktop.root.pid!==child.pid)return
|
|
1492
|
+
scheduleDshRecovery(component,component==='desktop'?config.desktop.root.started:'owned',child.pid,'start')
|
|
1493
|
+
})
|
|
1494
|
+
}
|
|
1495
|
+
function scheduleDshRecovery(component,identity,pid,action) {
|
|
1496
|
+
if(!AUTO_RESTART||recoveryTimers.has(component))return
|
|
1497
|
+
const now=Date.now(),attempts=(recoveryAttempts.get(component)||[]).filter(t=>now-t<5*60_000)
|
|
1498
|
+
if(attempts.length>=5){recordCrash(component,'restart-limit',{attempt:5});return}
|
|
1499
|
+
attempts.push(now);recoveryAttempts.set(component,attempts)
|
|
1500
|
+
recordCrash(component,'restart',{attempt:attempts.length})
|
|
1501
|
+
const run=async()=>{
|
|
1502
|
+
if(dshControlOperation&&!dshControlOperation.done){recoveryTimers.set(component,setTimeout(run,1000));return}
|
|
1503
|
+
recoveryTimers.delete(component)
|
|
1504
|
+
try{
|
|
1505
|
+
const config=readDshLaunch()
|
|
1506
|
+
if(component==='desktop'&&(config.kind!=='desktop'||config.desktop.root.pid!==pid||config.desktop.root.started!==identity))return
|
|
1507
|
+
if(component==='dsh'&&dshManagedChild)return
|
|
1508
|
+
const operation={operationId:crypto.randomUUID(),action,startedAt:Date.now(),updatedAt:Date.now(),done:false,ok:false,stage:'queued',steps:[],automatic:true}
|
|
1509
|
+
dshControlOperation=operation
|
|
1510
|
+
await runDshControlOperation(operation)
|
|
1511
|
+
if(!operation.ok)recordCrash(component,'restart-failed',{code:operation.code})
|
|
1512
|
+
}catch(error){recordCrash(component,'restart-failed',crashErrorFacts(error))}
|
|
1513
|
+
}
|
|
1514
|
+
recoveryTimers.set(component,setTimeout(()=>{void run()},Math.min(30000,1000*2**(attempts.length-1))))
|
|
1515
|
+
}
|
|
1516
|
+
function matchingDesktopCrash(config,records) {
|
|
1517
|
+
const d=config.desktop
|
|
1518
|
+
return records.some(row=>{
|
|
1519
|
+
const pid=Number(row.pid),expected=pid===d.root.pid?d.root:pid===d.host.pid?d.host:null
|
|
1520
|
+
return expected&&path.resolve(String(row.executable||'')).toLowerCase()===path.resolve(config.executable).toLowerCase()&&
|
|
1521
|
+
Number.isFinite(Date.parse(row.at))&&Date.parse(row.at)>=Date.parse(expected.started)&&Date.now()-Date.parse(row.at)<120000
|
|
1522
|
+
})
|
|
1523
|
+
}
|
|
1524
|
+
async function desktopCrashEvidence(config) {
|
|
1525
|
+
// Application Error event 1000 contains executable, PID and timestamp; no message text is retained.
|
|
1526
|
+
const script=String.raw`[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); $rows=@(Get-WinEvent -FilterHashtable @{LogName='Application';Id=1000;StartTime=(Get-Date).AddMinutes(-2)} -MaxEvents 20 -ErrorAction SilentlyContinue | ForEach-Object { [xml]$xml=$_.ToXml(); $data=@{}; foreach($item in $xml.Event.EventData.Data){$data[$item.Name]=$item.'#text'}; @{pid=$data.ProcessId;executable=$data.AppPath;at=$_.TimeCreated.ToUniversalTime().ToString('o')} }); ConvertTo-Json -InputObject $rows -Compress`
|
|
1527
|
+
const result=await execFileResult('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command',script],10000)
|
|
1528
|
+
if(!result.ok)return false
|
|
1529
|
+
try{return matchingDesktopCrash(config,JSON.parse(result.stdout||'[]'))}catch{return false}
|
|
1530
|
+
}
|
|
1531
|
+
let desktopWatchBusy=false
|
|
1532
|
+
const desktopCrashSeen=new Set()
|
|
1533
|
+
const desktopMissingSince=new Map()
|
|
1534
|
+
async function checkDesktopCrash() {
|
|
1535
|
+
if(!AUTO_RESTART||!DSH_CONTROL_SUPPORT.supported||desktopWatchBusy||(dshControlOperation&&!dshControlOperation.done))return
|
|
1536
|
+
let config;try{config=readDshLaunch()}catch{return}
|
|
1537
|
+
if(config.kind!=='desktop')return
|
|
1538
|
+
const alive=pid=>{try{process.kill(pid,0);return true}catch(e){return e.code!=='ESRCH'}}
|
|
1539
|
+
if(alive(config.desktop.root.pid)&&alive(config.desktop.host.pid)){desktopMissingSince.clear();return}
|
|
1540
|
+
const identity=config.desktop.root.started+':'+config.desktop.root.pid+':'+config.desktop.host.pid
|
|
1541
|
+
if(desktopCrashSeen.has(identity)||recoveryTimers.has('desktop'))return
|
|
1542
|
+
if(!desktopMissingSince.has(identity)){desktopMissingSince.clear();desktopMissingSince.set(identity,Date.now())}
|
|
1543
|
+
// Event logs can arrive late, but a normal quit must not poll crash logs forever.
|
|
1544
|
+
if(Date.now()-desktopMissingSince.get(identity)>=120000){
|
|
1545
|
+
desktopCrashSeen.add(identity);if(desktopCrashSeen.size>20)desktopCrashSeen.delete(desktopCrashSeen.values().next().value)
|
|
1546
|
+
desktopMissingSince.delete(identity);return
|
|
1547
|
+
}
|
|
1548
|
+
desktopWatchBusy=true
|
|
1549
|
+
try{
|
|
1550
|
+
if(await desktopCrashEvidence(config)){
|
|
1551
|
+
desktopCrashSeen.add(identity);if(desktopCrashSeen.size>20)desktopCrashSeen.delete(desktopCrashSeen.values().next().value)
|
|
1552
|
+
recordCrash('desktop','desktop-crash',{code:'WINDOWS_APPLICATION_ERROR'})
|
|
1553
|
+
scheduleDshRecovery('desktop',config.desktop.root.started,config.desktop.root.pid,'restart')
|
|
1554
|
+
}
|
|
1555
|
+
}catch{}finally{desktopWatchBusy=false}
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
|
|
1234
1559
|
function dshOperationStep(operation, stage, message, extra = {}) {
|
|
1235
1560
|
const now = Date.now()
|
|
1236
1561
|
operation.stage = stage
|
|
@@ -1275,7 +1600,7 @@ async function runDshControlOperation(operation) {
|
|
|
1275
1600
|
const initial = await dshServiceStatus()
|
|
1276
1601
|
operation.initialStatus = initial
|
|
1277
1602
|
operation.observed = initial
|
|
1278
|
-
const manager = initial.manager === 'process' ? '本机进程' : process.platform === 'win32' ? 'Windows 服务' : 'systemd 用户服务'
|
|
1603
|
+
const manager = initial.manager === 'desktop' ? 'DSH Desktop' : initial.manager === 'process' ? '本机进程' : process.platform === 'win32' ? 'Windows 服务' : 'systemd 用户服务'
|
|
1279
1604
|
operation.service = initial.service
|
|
1280
1605
|
if (!initial.supported) {
|
|
1281
1606
|
failDshOperation(operation, initial.code || 'UNSUPPORTED', initial.message || '当前 DSH 服务不可控', initial.detail, initial)
|
|
@@ -1287,7 +1612,7 @@ async function runDshControlOperation(operation) {
|
|
|
1287
1612
|
: await executeDshServiceAction(operation.action, initial)
|
|
1288
1613
|
operation.command = { ok: command.ok, code: command.code, signal: command.signal }
|
|
1289
1614
|
if (!command.ok) {
|
|
1290
|
-
const failure = initial.manager
|
|
1615
|
+
const failure = ['process','desktop'].includes(initial.manager)
|
|
1291
1616
|
? { code: command.code, message: command.error, detail: '' }
|
|
1292
1617
|
: classifyDshServiceFailure(command)
|
|
1293
1618
|
failDshOperation(operation, failure.code, failure.message, failure.detail, await dshServiceStatus())
|
|
@@ -1899,11 +2224,10 @@ function eventPollPayload(kind, since, waitSupported = false) {
|
|
|
1899
2224
|
function sendEventPollResponse(waiter, payload) {
|
|
1900
2225
|
if (waiter.req.destroyed || waiter.res.destroyed) return
|
|
1901
2226
|
cors(waiter.res)
|
|
1902
|
-
waiter.res
|
|
2227
|
+
sendHttpBody(waiter.res, 200, {
|
|
1903
2228
|
'content-type': 'application/json; charset=utf-8',
|
|
1904
2229
|
'cache-control': 'no-store'
|
|
1905
|
-
})
|
|
1906
|
-
waiter.res.end(JSON.stringify(payload))
|
|
2230
|
+
}, JSON.stringify(payload), true)
|
|
1907
2231
|
}
|
|
1908
2232
|
|
|
1909
2233
|
function finishEventPollWaiter(waiter, send = true) {
|
|
@@ -1987,11 +2311,10 @@ function serveEventPoll(req, res, url) {
|
|
|
1987
2311
|
const payload = eventPollPayload(kind, since, waitSupported)
|
|
1988
2312
|
if (payload.events.length || wait <= 0 || EVENT_POLL_WAIT_MAX <= 0) {
|
|
1989
2313
|
cors(res)
|
|
1990
|
-
res
|
|
2314
|
+
sendHttpBody(res, 200, {
|
|
1991
2315
|
'content-type': 'application/json; charset=utf-8',
|
|
1992
2316
|
'cache-control': 'no-store'
|
|
1993
|
-
})
|
|
1994
|
-
res.end(JSON.stringify(payload))
|
|
2317
|
+
}, JSON.stringify(payload), true)
|
|
1995
2318
|
return
|
|
1996
2319
|
}
|
|
1997
2320
|
const waiter = { req, res, kind, since, timer: null }
|
|
@@ -2812,6 +3135,7 @@ function serveFeedback(req, res, url) {
|
|
|
2812
3135
|
const contact = String(payload.contact || '').trim()
|
|
2813
3136
|
const appVersion = String(payload.appVersion || '').trim()
|
|
2814
3137
|
const includeDiagnostics = payload.includeDiagnostics === true
|
|
3138
|
+
const includeCrashLogs = payload.includeCrashLogs === true
|
|
2815
3139
|
if (!['bug', 'suggestion', 'other', 'poll'].includes(type)) {
|
|
2816
3140
|
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
2817
3141
|
res.end(JSON.stringify({ error: 'invalid type', expect: 'bug|suggestion|other|poll' }))
|
|
@@ -2864,6 +3188,7 @@ function serveFeedback(req, res, url) {
|
|
|
2864
3188
|
gatewayVersion: VERSION,
|
|
2865
3189
|
clientIp: maskIp(ip),
|
|
2866
3190
|
...(includeDiagnostics ? { diagnostics: compatibilityDiagnostics() } : {}),
|
|
3191
|
+
...(includeCrashLogs ? { serverInfo: JSON.stringify(crashUploadSummary()) } : {}),
|
|
2867
3192
|
...(pollVote || {})
|
|
2868
3193
|
}),
|
|
2869
3194
|
signal: AbortSignal.timeout(8000)
|
|
@@ -2937,6 +3262,7 @@ function serveStatic(req, res, url) {
|
|
|
2937
3262
|
return
|
|
2938
3263
|
}
|
|
2939
3264
|
fs.stat(filePath, (err, st) => {
|
|
3265
|
+
if (res.destroyed || res.writableEnded) return
|
|
2940
3266
|
if (err || !st.isFile()) {
|
|
2941
3267
|
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
2942
3268
|
res.end('404 Not Found')
|
|
@@ -2945,40 +3271,38 @@ function serveStatic(req, res, url) {
|
|
|
2945
3271
|
const ext = path.extname(filePath).toLowerCase()
|
|
2946
3272
|
const lastModified = st.mtime.toUTCString()
|
|
2947
3273
|
const mtimeSec = Math.floor(st.mtime.getTime() / 1000) * 1000
|
|
3274
|
+
const type = MIME[ext] || 'application/octet-stream'
|
|
3275
|
+
const text = compressibleType(type)
|
|
3276
|
+
const zipped = HTTP_COMPRESSION && text && st.size >= 1024 && req.method !== 'HEAD' && !req.headers.range && acceptsGzip(req)
|
|
3277
|
+
const etag = `W/"${st.size}-${st.mtimeMs}-${zipped ? 'gzip' : 'identity'}"`
|
|
2948
3278
|
cors(res)
|
|
2949
3279
|
const ims = req.headers['if-modified-since']
|
|
2950
|
-
|
|
2951
|
-
|
|
3280
|
+
const matched = req.headers['if-none-match']
|
|
3281
|
+
const cache = pathname === '/harmonyos-update.json' ? 'no-store' : ext === '.html' || ext === '.js' || ext === '.css' ? 'no-cache' : 'public, max-age=300'
|
|
3282
|
+
const headers = { 'content-type': type, 'cache-control': cache, 'last-modified': lastModified, etag }
|
|
3283
|
+
if (text) addEncodingVary(headers, res.getHeader('vary'))
|
|
3284
|
+
if (cache !== 'no-store' && (matched ? String(matched).split(',').some(v => v.trim() === etag || v.trim() === '*') : ims && new Date(ims).getTime() >= mtimeSec)) {
|
|
3285
|
+
res.writeHead(304, headers)
|
|
2952
3286
|
res.end()
|
|
2953
3287
|
return
|
|
2954
3288
|
}
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
'content-length': st.size,
|
|
2959
|
-
'last-modified': lastModified
|
|
2960
|
-
})
|
|
3289
|
+
if (zipped) headers['content-encoding'] = 'gzip'
|
|
3290
|
+
else headers['content-length'] = st.size
|
|
3291
|
+
res.writeHead(200, headers)
|
|
2961
3292
|
if (req.method === 'HEAD') res.end()
|
|
2962
|
-
else
|
|
3293
|
+
else {
|
|
3294
|
+
const stream = fs.createReadStream(filePath)
|
|
3295
|
+
const done = error => { if (error && !res.destroyed) res.destroy() }
|
|
3296
|
+
if (zipped) pipeline(stream, zlib.createGzip({ level: 3 }), res, done)
|
|
3297
|
+
else pipeline(stream, res, done)
|
|
3298
|
+
}
|
|
2963
3299
|
})
|
|
2964
3300
|
}
|
|
2965
3301
|
|
|
2966
3302
|
// ---------- 管理 API ----------
|
|
2967
3303
|
function upstreamReachable(cb) {
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
port: UPSTREAM_PORT,
|
|
2971
|
-
method: 'GET',
|
|
2972
|
-
path: '/health',
|
|
2973
|
-
headers: dshUpstreamHeaders(),
|
|
2974
|
-
timeout: 1500
|
|
2975
|
-
}, (res) => {
|
|
2976
|
-
res.resume()
|
|
2977
|
-
cb(true)
|
|
2978
|
-
})
|
|
2979
|
-
req.on('error', () => cb(false))
|
|
2980
|
-
req.on('timeout', () => { req.destroy(); cb(false) })
|
|
2981
|
-
req.end()
|
|
3304
|
+
void refreshHealthProbe()
|
|
3305
|
+
cb(healthProbeState.reachable)
|
|
2982
3306
|
}
|
|
2983
3307
|
|
|
2984
3308
|
async function serveAdminApi(req, res, url) {
|
|
@@ -3154,6 +3478,7 @@ async function serveAdminApi(req, res, url) {
|
|
|
3154
3478
|
res.end(JSON.stringify({ ok: true, bye: true }))
|
|
3155
3479
|
// 给响应留出发送时间, 然后退出; 由插件/系统按需再拉起
|
|
3156
3480
|
setTimeout(() => {
|
|
3481
|
+
recordCrash('gateway','manual-stop')
|
|
3157
3482
|
console.log('[shutdown] 收到管理端停止指令, 网关退出')
|
|
3158
3483
|
process.exit(0)
|
|
3159
3484
|
}, 150)
|
|
@@ -3305,6 +3630,7 @@ async function fsResolve(input) {
|
|
|
3305
3630
|
else if (/^~[\\/]/.test(raw)) abs = path.resolve(FS_DEFAULT_ROOT, raw.slice(2))
|
|
3306
3631
|
else if (path.isAbsolute(raw)) abs = path.resolve(raw)
|
|
3307
3632
|
else abs = path.resolve(FS_ROOTS[0], raw) // 相对路径按默认根解析
|
|
3633
|
+
if (fsProtectedPath(abs)) return { error: 'forbidden' }
|
|
3308
3634
|
if (FS_ROOTS.some(root => fsInsideRoot(abs, root))) return { abs }
|
|
3309
3635
|
if (FS_WINDOWS_DEFAULT) return { error: 'forbidden' }
|
|
3310
3636
|
let workspaces = await loadFsWorkspaceRoots(false)
|
|
@@ -3324,6 +3650,7 @@ function fsRealChecked(abs) {
|
|
|
3324
3650
|
return { error: err.code === 'ENOENT' ? 'not-found' : 'permission-denied' }
|
|
3325
3651
|
}
|
|
3326
3652
|
if (!fsInsideReal(real)) return { error: 'forbidden' }
|
|
3653
|
+
if (fsProtectedPath(real)) return { error: 'forbidden' }
|
|
3327
3654
|
return { abs: real }
|
|
3328
3655
|
}
|
|
3329
3656
|
|
|
@@ -3390,11 +3717,12 @@ async function fsList(req, res, url) {
|
|
|
3390
3717
|
const entries = []
|
|
3391
3718
|
for (const d of dirents) {
|
|
3392
3719
|
const full = path.join(checked.abs, d.name)
|
|
3720
|
+
if (fsProtectedPath(full)) continue
|
|
3393
3721
|
try {
|
|
3394
3722
|
// 符号链接指向允许根之外时直接不展示, 点进去/下载也必然被 realpath 复核拒绝
|
|
3395
3723
|
if (d.isSymbolicLink()) {
|
|
3396
3724
|
const real = fs.realpathSync(full)
|
|
3397
|
-
if (!fsInsideReal(real)) continue
|
|
3725
|
+
if (!fsInsideReal(real) || fsProtectedPath(real)) continue
|
|
3398
3726
|
}
|
|
3399
3727
|
const info = fs.statSync(full)
|
|
3400
3728
|
if (!info.isFile() && !info.isDirectory()) continue
|
|
@@ -3598,6 +3926,10 @@ function fsOpenUploadTarget(res, url, dirLex, dirReal, name) {
|
|
|
3598
3926
|
}
|
|
3599
3927
|
const target = path.join(dirReal, name)
|
|
3600
3928
|
const overwrite = url.searchParams.get('overwrite') === '1' || url.searchParams.get('overwrite') === 'true'
|
|
3929
|
+
if (fsProtectedPath(target)) {
|
|
3930
|
+
fsJson(res, 403, { error: 'forbidden' })
|
|
3931
|
+
return null
|
|
3932
|
+
}
|
|
3601
3933
|
let exists = false
|
|
3602
3934
|
try {
|
|
3603
3935
|
const st = fs.lstatSync(target)
|
|
@@ -3821,7 +4153,9 @@ async function fsUploadProbe(req, res, url) {
|
|
|
3821
4153
|
if (uploadLength !== null && (!Number.isSafeInteger(uploadLength) || uploadLength < 0)) {
|
|
3822
4154
|
return fsJson(res, 400, { error: 'bad-length', detail: 'size 必须是非负整数' })
|
|
3823
4155
|
}
|
|
3824
|
-
const
|
|
4156
|
+
const probeTarget = path.join(checked.abs, name)
|
|
4157
|
+
if (fsProtectedPath(probeTarget)) return fsJson(res, 403, { error: 'forbidden' })
|
|
4158
|
+
const target = fsTargetState(probeTarget)
|
|
3825
4159
|
let targetSize = 0
|
|
3826
4160
|
if (target.exists) {
|
|
3827
4161
|
try { targetSize = fs.statSync(path.join(checked.abs, name)).size } catch {}
|
|
@@ -3860,6 +4194,7 @@ async function fsMkdir(req, res, url) {
|
|
|
3860
4194
|
const name = url.searchParams.get('name') || ''
|
|
3861
4195
|
if (!fsValidName(name)) return fsJson(res, 400, { error: 'bad-name', detail: '目录名不能为空且不能包含路径分隔符' })
|
|
3862
4196
|
const target = path.join(checked.abs, name)
|
|
4197
|
+
if (fsProtectedPath(target)) return fsJson(res, 403, { error: 'forbidden' })
|
|
3863
4198
|
try {
|
|
3864
4199
|
fs.mkdirSync(target)
|
|
3865
4200
|
} catch (err) {
|
|
@@ -3903,6 +4238,7 @@ function fsUploadResumable(req, res, url, dirLex, dirReal) {
|
|
|
3903
4238
|
const target = path.join(dirReal, name)
|
|
3904
4239
|
|
|
3905
4240
|
// 已有分片尺寸对齐: 回卷重写允许, 越界/缺洞拒绝
|
|
4241
|
+
if (fsProtectedPath(target)) return fsJson(res, 403, { error: 'forbidden' })
|
|
3906
4242
|
let existing = 0
|
|
3907
4243
|
try {
|
|
3908
4244
|
const st = fs.statSync(part)
|
|
@@ -4458,11 +4794,10 @@ async function forwardLegacyRpc(url, raw, allowVisionBridge = true) {
|
|
|
4458
4794
|
|
|
4459
4795
|
function sendBufferedUpstreamResponse(res, response) {
|
|
4460
4796
|
cors(res)
|
|
4461
|
-
res
|
|
4797
|
+
sendHttpBody(res, response.status || 502, {
|
|
4462
4798
|
'content-type': response.headers?.get?.('content-type') || 'application/json; charset=utf-8',
|
|
4463
4799
|
'cache-control': 'no-store',
|
|
4464
|
-
})
|
|
4465
|
-
res.end(response.raw || '')
|
|
4800
|
+
}, response.raw || '', compressibleRpc(res.req))
|
|
4466
4801
|
}
|
|
4467
4802
|
|
|
4468
4803
|
async function proxyLegacyRpcWithModernFallback(req, res, url) {
|
|
@@ -4498,8 +4833,7 @@ async function proxyLegacyRpcWithModernFallback(req, res, url) {
|
|
|
4498
4833
|
}
|
|
4499
4834
|
}
|
|
4500
4835
|
cors(res)
|
|
4501
|
-
res
|
|
4502
|
-
res.end(JSON.stringify(translated))
|
|
4836
|
+
sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify(translated), compressibleRpc(req))
|
|
4503
4837
|
}
|
|
4504
4838
|
|
|
4505
4839
|
async function proxyModernApi(req, res, url) {
|
|
@@ -4546,8 +4880,7 @@ async function proxyModernApi(req, res, url) {
|
|
|
4546
4880
|
sendBufferedUpstreamResponse(res, legacy)
|
|
4547
4881
|
return true
|
|
4548
4882
|
}
|
|
4549
|
-
res
|
|
4550
|
-
res.end(JSON.stringify(translated))
|
|
4883
|
+
sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify(translated), compressibleRpc(req))
|
|
4551
4884
|
return true
|
|
4552
4885
|
} catch (error) {
|
|
4553
4886
|
if (!res.headersSent) {
|
|
@@ -4651,13 +4984,42 @@ function proxyApi(req, res, url) {
|
|
|
4651
4984
|
}
|
|
4652
4985
|
|
|
4653
4986
|
// ---------- 其它 ----------
|
|
4654
|
-
|
|
4987
|
+
// Expensive OS/upstream checks run once in the background; public status never
|
|
4988
|
+
// grants restart authority. Actual lifecycle actions still verify fresh evidence.
|
|
4989
|
+
let healthProbeState = { ok: false, reachable: false, status: 0, checkedAt: 0, error: '' }
|
|
4990
|
+
let healthProbeTask = null
|
|
4991
|
+
function refreshHealthProbe(force = false) {
|
|
4992
|
+
if (healthProbeTask) return healthProbeTask
|
|
4993
|
+
if (!force && healthProbeState.checkedAt && Date.now() - healthProbeState.checkedAt < 5000) return Promise.resolve(healthProbeState)
|
|
4994
|
+
healthProbeTask = probeDshUpstream(5000).then(value => {
|
|
4995
|
+
healthProbeState = { ...value, checkedAt: Date.now() }
|
|
4996
|
+
return healthProbeState
|
|
4997
|
+
}).finally(() => { healthProbeTask = null })
|
|
4998
|
+
return healthProbeTask
|
|
4999
|
+
}
|
|
5000
|
+
let controlDescriptionState = null
|
|
5001
|
+
let controlDescriptionTask = null
|
|
5002
|
+
let controlDescriptionAt = 0
|
|
5003
|
+
async function dshControlDescription(force = false) {
|
|
4655
5004
|
if (!DSH_CONTROL_SUPPORT.supported) return DSH_CONTROL_SUPPORT
|
|
4656
5005
|
if (process.platform !== 'win32' && DSH_CONTROL_MODE !== 'process') return DSH_CONTROL_SUPPORT
|
|
4657
|
-
|
|
4658
|
-
|
|
4659
|
-
|
|
4660
|
-
|
|
5006
|
+
if (DSH_CONTROL_MODE === 'process') {
|
|
5007
|
+
try { readDshLaunch() } catch (error) {
|
|
5008
|
+
return { supported: false, manager: 'process', code: 'LAUNCH_CONFIG_INVALID', message: '缺少有效 DSH 启动配置,请先从 DSH 插件重新生成', canRestart: false }
|
|
5009
|
+
}
|
|
5010
|
+
}
|
|
5011
|
+
if (!controlDescriptionTask && (force || Date.now() - controlDescriptionAt >= 5000)) {
|
|
5012
|
+
controlDescriptionTask = dshServiceStatus({ cachedProbe: true }).then(status => {
|
|
5013
|
+
controlDescriptionState = { supported: status.supported, manager: status.manager || DSH_CONTROL_SUPPORT.manager,
|
|
5014
|
+
...(status.code ? { code: status.code, message: status.message } : {}),
|
|
5015
|
+
...(status.canRestart !== undefined ? { canRestart: status.canRestart } : {}) }
|
|
5016
|
+
controlDescriptionAt = Date.now()
|
|
5017
|
+
}).catch(() => {
|
|
5018
|
+
controlDescriptionState = { supported: false, code: 'STATUS_PARSE_FAILED', message: '无法读取 DSH 生命周期状态', canRestart: false }
|
|
5019
|
+
controlDescriptionAt = Date.now()
|
|
5020
|
+
}).finally(() => { controlDescriptionTask = null })
|
|
5021
|
+
}
|
|
5022
|
+
return controlDescriptionState || { ...DSH_CONTROL_SUPPORT, canRestart: false, checking: true }
|
|
4661
5023
|
}
|
|
4662
5024
|
|
|
4663
5025
|
async function serveHealth(req, res, url) {
|
|
@@ -4673,30 +5035,11 @@ async function serveHealth(req, res, url) {
|
|
|
4673
5035
|
clients: state.clients,
|
|
4674
5036
|
}]))
|
|
4675
5037
|
const liveness = { ok: true, pid: process.pid, uptimeMs: Math.max(0, Date.now() - STARTED_AT), runtime: runtimeState }
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
}
|
|
4682
|
-
let upstreamOk = false
|
|
4683
|
-
let upstreamReachable = false
|
|
4684
|
-
let upstreamStatus = 0
|
|
4685
|
-
let upstreamError = ''
|
|
4686
|
-
let timer = null
|
|
4687
|
-
try {
|
|
4688
|
-
const ctrl = new AbortController()
|
|
4689
|
-
timer = setTimeout(() => ctrl.abort(), 5000)
|
|
4690
|
-
const probeUrl = new URL(DSH_HEALTH_PATH, UPSTREAM).toString()
|
|
4691
|
-
const probe = await fetch(probeUrl, { headers: dshUpstreamHeaders(), signal: ctrl.signal, cache: 'no-store' })
|
|
4692
|
-
upstreamReachable = true
|
|
4693
|
-
upstreamStatus = probe.status
|
|
4694
|
-
upstreamOk = probe.ok
|
|
4695
|
-
} catch (err) {
|
|
4696
|
-
upstreamError = String(err?.message || err || '')
|
|
4697
|
-
} finally {
|
|
4698
|
-
if (timer) clearTimeout(timer)
|
|
4699
|
-
}
|
|
5038
|
+
const live = url?.searchParams.get('probe') === 'live'
|
|
5039
|
+
const probeTask = refreshHealthProbe()
|
|
5040
|
+
// A small cold-start budget preserves useful readiness on fast local upstreams.
|
|
5041
|
+
if (!live && !healthProbeState.checkedAt) await Promise.race([probeTask, delay(100)])
|
|
5042
|
+
const { ok: upstreamOk, reachable: upstreamReachable, status: upstreamStatus, error: upstreamError } = healthProbeState
|
|
4700
5043
|
const eventsOk = eventHealth.mux.connected && eventHealth.host.connected
|
|
4701
5044
|
const readiness = { ok: upstreamOk && eventsOk, upstreamOk, eventsOk }
|
|
4702
5045
|
const status = readiness.ok ? 'ready' : upstreamReachable ? 'degraded' : 'offline'
|
|
@@ -4706,6 +5049,7 @@ async function serveHealth(req, res, url) {
|
|
|
4706
5049
|
res.end(JSON.stringify({
|
|
4707
5050
|
ok: true,
|
|
4708
5051
|
service: 'dsh-remote',
|
|
5052
|
+
...(live ? { probe: 'live' } : {}),
|
|
4709
5053
|
status,
|
|
4710
5054
|
liveness,
|
|
4711
5055
|
readiness,
|
|
@@ -4719,6 +5063,8 @@ async function serveHealth(req, res, url) {
|
|
|
4719
5063
|
upstreamOk,
|
|
4720
5064
|
upstreamReachable,
|
|
4721
5065
|
upstreamStatus,
|
|
5066
|
+
upstreamCheckedAt: healthProbeState.checkedAt,
|
|
5067
|
+
upstreamChecking: !!healthProbeTask,
|
|
4722
5068
|
...(upstreamError ? { upstreamError } : {}),
|
|
4723
5069
|
events: eventHealth,
|
|
4724
5070
|
runtime: runtimeState,
|
|
@@ -4743,6 +5089,14 @@ const server = http.createServer(async (req, res) => {
|
|
|
4743
5089
|
if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)
|
|
4744
5090
|
if (url.pathname === '/workbench' || url.pathname.startsWith('/workbench/')) return serveWorkbench(req, res, url)
|
|
4745
5091
|
if (url.pathname === '/diagnostics') return serveDiagnostics(req, res, url)
|
|
5092
|
+
if (url.pathname === '/crash-logs') {
|
|
5093
|
+
cors(res)
|
|
5094
|
+
if(req.method==='OPTIONS'){res.writeHead(204);res.end();return}
|
|
5095
|
+
if(req.method!=='GET'){res.setHeader('allow','GET, OPTIONS');return crashReply(res,405,{error:'read-only'})}
|
|
5096
|
+
if(!authorized(req,url))return crashReply(res,401,{error:'unauthorized'})
|
|
5097
|
+
touchDevice(req)
|
|
5098
|
+
return crashReply(res,200,{schema:1,recovery:runtimeState.recovery,records:crashRecords(),upload:crashUploadSummary()})
|
|
5099
|
+
}
|
|
4746
5100
|
if (url.pathname === '/feedback') return serveFeedback(req, res, url)
|
|
4747
5101
|
if (url.pathname === '/handoff') return serveHandoff(req, res, url)
|
|
4748
5102
|
if (url.pathname.startsWith('/admin/api')) return await serveAdminApi(req, res, url)
|
|
@@ -4773,19 +5127,20 @@ server.headersTimeout = HTTP_HEADERS_TIMEOUT_MS
|
|
|
4773
5127
|
server.keepAliveTimeout = HTTP_KEEPALIVE_TIMEOUT_MS
|
|
4774
5128
|
server.timeout = 0
|
|
4775
5129
|
|
|
4776
|
-
//
|
|
4777
|
-
|
|
4778
|
-
|
|
4779
|
-
|
|
4780
|
-
|
|
4781
|
-
|
|
4782
|
-
|
|
4783
|
-
|
|
4784
|
-
|
|
4785
|
-
|
|
4786
|
-
|
|
4787
|
-
|
|
4788
|
-
|
|
5130
|
+
// Fatal state is recorded synchronously, then a supervised worker exits for a clean restart.
|
|
5131
|
+
let fatalExiting=false
|
|
5132
|
+
function fatalGateway(error,kind) {
|
|
5133
|
+
if(fatalExiting)return
|
|
5134
|
+
fatalExiting=true
|
|
5135
|
+
runtimeState[kind==='uncaughtException'?'uncaughtExceptions':'unhandledRejections']++
|
|
5136
|
+
runtimeState.lastErrorAt=Date.now();runtimeState.lastError='fatal '+kind
|
|
5137
|
+
recordCrash('gateway','fatal',crashErrorFacts(error))
|
|
5138
|
+
try{console.error('[recovery] '+kind+'; see local crash records')}catch{}
|
|
5139
|
+
// Exit on the next turn; never continue accepting work in an undefined state.
|
|
5140
|
+
setImmediate(()=>process.exit(error?.code==='EADDRINUSE'?78:1))
|
|
5141
|
+
}
|
|
5142
|
+
process.on('uncaughtException',error=>fatalGateway(error,'uncaughtException'))
|
|
5143
|
+
process.on('unhandledRejection',error=>fatalGateway(error,'unhandledRejection'))
|
|
4789
5144
|
|
|
4790
5145
|
function wsPingFrame(masked) {
|
|
4791
5146
|
if (!masked) return Buffer.from([0x89, 0x00])
|
|
@@ -5133,6 +5488,12 @@ server.on('clientError', (err, socket) => {
|
|
|
5133
5488
|
})
|
|
5134
5489
|
|
|
5135
5490
|
server.listen(PORT, HOST, () => {
|
|
5491
|
+
void refreshHealthProbe()
|
|
5492
|
+
void dshControlDescription()
|
|
5493
|
+
const healthRefresh = setInterval(() => { void refreshHealthProbe(true); void dshControlDescription(true) }, 5000)
|
|
5494
|
+
healthRefresh.unref?.()
|
|
5495
|
+
recordCrash('gateway','startup')
|
|
5496
|
+
const crashWatch=setInterval(()=>{void checkDesktopCrash()},5000);crashWatch.unref?.()
|
|
5136
5497
|
const clientToken = deviceKeyState.enabled ? deviceKeyState.keys[0]?.token : TOKEN
|
|
5137
5498
|
console.log('DSH Remote 网关 v' + VERSION + ' 已启动')
|
|
5138
5499
|
console.log(' 本机: http://127.0.0.1:' + PORT + '/?token=' + (clientToken || '请在管理页创建设备密钥'))
|
|
@@ -5153,3 +5514,5 @@ server.listen(PORT, HOST, () => {
|
|
|
5153
5514
|
scanStatsOnce(2000)
|
|
5154
5515
|
setInterval(() => scanStatsOnce(0), 5 * 60 * 1000)
|
|
5155
5516
|
})
|
|
5517
|
+
|
|
5518
|
+
} // gateway worker
|