dsh-remote-plugin 0.8.0 → 0.8.1
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/README.en.md +2 -2
- package/README.md +2 -2
- package/apk/dsh-remote.apk +0 -0
- package/client.js +96 -115
- package/file-delivery.mjs +84 -0
- package/gateway.cjs +247 -3
- package/index.mjs +574 -48
- package/package.json +3 -2
- package/plugin-center.mjs +4 -0
- package/public/activity.js +8 -3
- package/public/announcements.json +10 -0
- package/public/app.js +60 -20
- package/public/approval-records.js +75 -3
- package/public/build.json +2 -2
- package/public/desktop/desktop.css +9 -1
- package/public/desktop/desktop.html +23 -4
- package/public/desktop/desktop.js +27 -13
- package/public/extensions.css +13 -0
- package/public/extensions.js +74 -3
- package/public/file-inbox.css +66 -0
- package/public/file-inbox.js +289 -0
- package/public/index.html +25 -9
- package/public/plugin.js +21 -6
- package/public/session-deck.css +73 -0
- package/public/session-deck.js +180 -0
- package/public/styles.css +22 -2
- package/public/update.json +8 -8
- package/public/version.json +1 -1
- package/skills/dsh-remote-doctor/references/wiki/plugins.md +22 -1
package/gateway.cjs
CHANGED
|
@@ -588,9 +588,9 @@ function compressibleRpc(req) {
|
|
|
588
588
|
// Crash records deliberately contain facts and source positions, never arbitrary error text.
|
|
589
589
|
const CRASH_LOG_FILE=process.env.DSH_REMOTE_CRASH_LOG_FILE || path.join(os.homedir(),'.dsh-remote','crashes.jsonl')
|
|
590
590
|
const AUTO_RESTART=process.env.DSH_REMOTE_AUTO_RESTART!=='0'
|
|
591
|
-
const CRASH_KINDS=new Set(['fatal','exit','restart','restart-failed','restart-limit','manual-stop','startup','desktop-crash','lease-recovered','lease-conflict','lease-failed'])
|
|
591
|
+
const CRASH_KINDS=new Set(['fatal','exit','restart','restart-failed','restart-limit','manual-stop','startup','desktop-crash','lease-recovered','lease-conflict','lease-failed','log-unavailable'])
|
|
592
592
|
const CRASH_COMPONENTS=new Set(['gateway','dsh','desktop'])
|
|
593
|
-
const CRASH_CODES=new Set(['EADDRINUSE','EACCES','EPERM','ENOENT','ENOMEM','ECONNRESET','ETIMEDOUT','EINVAL','ENAMETOOLONG','ERR_OUT_OF_MEMORY','WINDOWS_APPLICATION_ERROR','PROCESS_START_FAILED','PROCESS_STOP_TIMEOUT','EXTERNAL_PROCESS','PORT_IN_USE','SERVICE_FAILED','SERVICE_TIMEOUT','EVENTS_TIMEOUT','UPSTREAM_TIMEOUT','INTERNAL_ERROR','LAUNCH_CONFIG_INVALID','STATUS_PARSE_FAILED','SUPERVISOR_ALREADY_RUNNING','SUPERVISOR_IDENTITY_UNAVAILABLE','SUPERVISOR_ENDPOINT_TOO_LONG','SUPERVISOR_LEASE_STALE','SUPERVISOR_LEASE_INVALID'])
|
|
593
|
+
const CRASH_CODES=new Set(['EADDRINUSE','EACCES','EPERM','ENOENT','ENOMEM','ECONNRESET','ETIMEDOUT','EINVAL','ENAMETOOLONG','EPIPE','EBADF','EIO','ERR_STREAM_DESTROYED','ERR_OUT_OF_MEMORY','WINDOWS_APPLICATION_ERROR','PROCESS_START_FAILED','PROCESS_STOP_TIMEOUT','EXTERNAL_PROCESS','PORT_IN_USE','SERVICE_FAILED','SERVICE_TIMEOUT','EVENTS_TIMEOUT','UPSTREAM_TIMEOUT','INTERNAL_ERROR','LAUNCH_CONFIG_INVALID','STATUS_PARSE_FAILED','SUPERVISOR_ALREADY_RUNNING','SUPERVISOR_IDENTITY_UNAVAILABLE','SUPERVISOR_ENDPOINT_TOO_LONG','SUPERVISOR_LEASE_STALE','SUPERVISOR_LEASE_INVALID'])
|
|
594
594
|
function safeCrashRecord(value) {
|
|
595
595
|
const row={at:Number.isFinite(value?.at)?value.at:Date.now(),component:CRASH_COMPONENTS.has(value?.component)?value.component:'gateway',kind:CRASH_KINDS.has(value?.kind)?value.kind:'fatal'}
|
|
596
596
|
if(Number.isInteger(value?.exitCode))row.exitCode=value.exitCode
|
|
@@ -631,6 +631,20 @@ function crashUploadSummary() {
|
|
|
631
631
|
while(JSON.stringify(report).length>490){if(report.records.some(r=>r.frames?.length)){for(const r of report.records)delete r.frames}else report.records.shift()}
|
|
632
632
|
return report
|
|
633
633
|
}
|
|
634
|
+
// A detached gateway can outlive the launcher that was reading its output.
|
|
635
|
+
// Only output-stream I/O failures are recoverable here; never ignore a socket
|
|
636
|
+
// error or an arbitrary uncaught exception merely because it has the same code.
|
|
637
|
+
const OUTPUT_CLOSED_CODES=new Set(['EPIPE','EBADF','EIO','ERR_STREAM_DESTROYED'])
|
|
638
|
+
for(const stream of [process.stdout,process.stderr]) {
|
|
639
|
+
let reported=false
|
|
640
|
+
stream.on('error',error=>{
|
|
641
|
+
if(!OUTPUT_CLOSED_CODES.has(error?.code))throw error
|
|
642
|
+
if(reported)return
|
|
643
|
+
reported=true
|
|
644
|
+
// Do not log to either console stream from its error handler.
|
|
645
|
+
recordCrash('gateway','log-unavailable',{code:error.code})
|
|
646
|
+
})
|
|
647
|
+
}
|
|
634
648
|
// BEGIN LOGIN AUTOSTART
|
|
635
649
|
// A per-user Windows login entry. No registration happens until the admin opts in.
|
|
636
650
|
function createLoginAutostart(options) {
|
|
@@ -880,6 +894,11 @@ async function runGatewaySupervisor() {
|
|
|
880
894
|
const env={...process.env,DSH_REMOTE_SUPERVISED:'1',DSH_REMOTE_SUPERVISOR_PID:String(process.pid)}
|
|
881
895
|
delete env.NODE_CHANNEL_FD;delete env.NODE_CHANNEL_SERIALIZATION_MODE
|
|
882
896
|
const args=process.pkg?process.argv.slice(2).filter(a=>a!=='--supervise'):[__filename,...process.argv.slice(2).filter(a=>a!=='--supervise')]
|
|
897
|
+
// 复用 supervisor 自己的 process.execPath 拉起 worker,前提是它已经是"正确的解释器":
|
|
898
|
+
// 插件托管网关时,packages/plugin/index.mjs 的 resolveGatewayRuntime() 会保证它是
|
|
899
|
+
// 位于 DSH 安装目录之外的 node(~/.dsh-remote/runtime/node-<ver>.exe 或 PATH 中的 node),
|
|
900
|
+
// 不能再把它当作 DSH 桌面版可执行文件;独立运行(node / pkg 单文件)时它就是普通 node
|
|
901
|
+
// 或网关自身。Windows 上若这里回落到安装目录内的 exe,DSH 原地更新会被占用而失败。
|
|
883
902
|
try{worker=spawn(process.execPath,args,{cwd:process.cwd(),env,windowsHide:true,stdio:['ignore','inherit','inherit']})}catch(error){recordCrash('gateway','restart-failed',crashErrorFacts(error));process.exit(1)}
|
|
884
903
|
let handled=false
|
|
885
904
|
const exited=(code,signal)=>{
|
|
@@ -1061,6 +1080,7 @@ const CAPABILITIES = Object.freeze({
|
|
|
1061
1080
|
operations: 1,
|
|
1062
1081
|
cloudRelay: 1,
|
|
1063
1082
|
workspaceFiles: 2,
|
|
1083
|
+
fileInbox: 1,
|
|
1064
1084
|
imagePromptTransport: 1,
|
|
1065
1085
|
dshLifecycle: DSH_CONTROL_SUPPORT.supported ? 2 : 0,
|
|
1066
1086
|
centralAnnouncements: 2,
|
|
@@ -1821,7 +1841,7 @@ function cors(res, req = res.req) {
|
|
|
1821
1841
|
}
|
|
1822
1842
|
if (allowed) res.setHeader('access-control-allow-origin', origin || '*')
|
|
1823
1843
|
res.setHeader('vary', 'Origin')
|
|
1824
|
-
res.setHeader('access-control-allow-headers', 'authorization, content-type, x-dsh-remote-client, x-dsh-remote-client-id')
|
|
1844
|
+
res.setHeader('access-control-allow-headers', 'authorization, content-type, x-dsh-remote-client, x-dsh-remote-client-id, x-dsh-remote-inbox-key')
|
|
1825
1845
|
res.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS')
|
|
1826
1846
|
res.setHeader('access-control-max-age', '600')
|
|
1827
1847
|
}
|
|
@@ -4505,8 +4525,23 @@ function upstreamReachable(cb) {
|
|
|
4505
4525
|
cb(healthProbeState.reachable)
|
|
4506
4526
|
}
|
|
4507
4527
|
|
|
4528
|
+
function gatewayRuntimeIdentity() {
|
|
4529
|
+
return { pid: process.pid, executable: process.execPath, version: process.versions.node,
|
|
4530
|
+
supervisorPid: Number(process.env.DSH_REMOTE_SUPERVISOR_PID) || 0 }
|
|
4531
|
+
}
|
|
4532
|
+
|
|
4508
4533
|
async function serveAdminApi(req, res, url) {
|
|
4509
4534
|
const sub = url.pathname.slice('/admin/api'.length) || '/'
|
|
4535
|
+
// 实际进程信息只通过认证管理接口返回,公共 /health 不暴露本机解释器路径。
|
|
4536
|
+
if (sub === '/runtime') {
|
|
4537
|
+
const reply = (status, body) => {
|
|
4538
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
4539
|
+
res.end(JSON.stringify(body))
|
|
4540
|
+
}
|
|
4541
|
+
if (!adminAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
|
|
4542
|
+
if (req.method !== 'GET') { res.setHeader('allow', 'GET'); return reply(405, { error: 'method-not-allowed' }) }
|
|
4543
|
+
return reply(200, { ok: true, gatewayRuntime: gatewayRuntimeIdentity() })
|
|
4544
|
+
}
|
|
4510
4545
|
if (sub === '/autostart') {
|
|
4511
4546
|
const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
|
|
4512
4547
|
if (!adminAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
|
|
@@ -4539,6 +4574,7 @@ async function serveAdminApi(req, res, url) {
|
|
|
4539
4574
|
version: VERSION,
|
|
4540
4575
|
pid: process.pid,
|
|
4541
4576
|
platform: process.platform,
|
|
4577
|
+
gatewayRuntime: gatewayRuntimeIdentity(),
|
|
4542
4578
|
hostname: os.hostname(),
|
|
4543
4579
|
lanIPs: lanAddresses(),
|
|
4544
4580
|
startedAt: STARTED_AT,
|
|
@@ -6405,6 +6441,213 @@ function proxyApi(req, res, url) {
|
|
|
6405
6441
|
})
|
|
6406
6442
|
}
|
|
6407
6443
|
|
|
6444
|
+
// BEGIN FILE INBOX — local durable single-file deliveries, no external service.
|
|
6445
|
+
function createFileInbox({ root, resolveSource, validAuth, now = Date.now, maxFile = 50 * 1024 * 1024, ttl = 86400000 }) {
|
|
6446
|
+
const digest = value => crypto.createHash('sha256').update(value).digest('hex')
|
|
6447
|
+
const fail = (code, status = 400) => Object.assign(new Error(code), { code, status })
|
|
6448
|
+
const idOk = value => typeof value === 'string' && value.length >= 16 && value.length <= 80 && !/[^a-zA-Z0-9-]/.test(value)
|
|
6449
|
+
const keyOk = value => typeof value === 'string' && value.length === 64 && !/[^a-f0-9]/.test(value)
|
|
6450
|
+
const terminal = new Set(['complete', 'downloaded', 'rejected', 'expired'])
|
|
6451
|
+
let state, persisted, serial = Promise.resolve()
|
|
6452
|
+
const file = id => path.join(root, id + '.bin')
|
|
6453
|
+
const save = () => {
|
|
6454
|
+
const temp = path.join(root, 'index.' + process.pid + '.tmp')
|
|
6455
|
+
try {
|
|
6456
|
+
fs.writeFileSync(temp, JSON.stringify(state), { mode: 0o600 })
|
|
6457
|
+
fs.renameSync(temp, path.join(root, 'index.json'))
|
|
6458
|
+
persisted = JSON.parse(JSON.stringify(state))
|
|
6459
|
+
} catch (error) { state = JSON.parse(JSON.stringify(persisted)); throw error }
|
|
6460
|
+
}
|
|
6461
|
+
const clean = () => {
|
|
6462
|
+
let changed = false
|
|
6463
|
+
for (const row of state.transfers) if ((row.expiresAt <= now() || !validAuth(row.auth)) && !row.snapshotDeleted) {
|
|
6464
|
+
if (!terminal.has(row.phase)) { row.phase = 'expired'; row.expiresAt = Math.min(row.expiresAt, now()) }
|
|
6465
|
+
delete row.ticketHash; row.snapshotDeleted = true; changed = true
|
|
6466
|
+
try { fs.unlinkSync(file(row.id)) } catch (e) { if (e.code !== 'ENOENT') throw e }
|
|
6467
|
+
}
|
|
6468
|
+
const old = state.transfers.length
|
|
6469
|
+
state.transfers = state.transfers.filter(row => row.expiresAt > now() - ttl)
|
|
6470
|
+
if (changed || old !== state.transfers.length) save()
|
|
6471
|
+
}
|
|
6472
|
+
const lock = work => {
|
|
6473
|
+
const result = serial.catch(() => {}).then(async () => {
|
|
6474
|
+
if (!state) {
|
|
6475
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 })
|
|
6476
|
+
try { state = JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8')) }
|
|
6477
|
+
catch (e) { if (e.code !== 'ENOENT') throw fail('inbox-storage-invalid', 503); state = { devices: [], transfers: [] } }
|
|
6478
|
+
if (!Array.isArray(state?.devices) || !Array.isArray(state?.transfers) || state.transfers.some(r => !idOk(r.id))) { state = null; throw fail('inbox-storage-invalid', 503) }
|
|
6479
|
+
persisted = JSON.parse(JSON.stringify(state))
|
|
6480
|
+
// Failed/crashed snapshots are private, bounded, and never exposed as deliveries.
|
|
6481
|
+
for (const name of fs.readdirSync(root)) if (/^[a-zA-Z0-9-]{16,80}\.(bin|part)$/.test(name)) {
|
|
6482
|
+
const id = name.replace(/\.(bin|part)$/, '')
|
|
6483
|
+
if (!state.transfers.some(row => row.id === id)) fs.unlinkSync(path.join(root, name))
|
|
6484
|
+
}
|
|
6485
|
+
}
|
|
6486
|
+
clean()
|
|
6487
|
+
return work()
|
|
6488
|
+
})
|
|
6489
|
+
serial = result
|
|
6490
|
+
return result
|
|
6491
|
+
}
|
|
6492
|
+
const device = (auth, key) => {
|
|
6493
|
+
if (!keyOk(key)) throw fail('receiver-key-required', 403)
|
|
6494
|
+
const found = state.devices.find(row => row.auth === auth && row.keyHash === digest(key))
|
|
6495
|
+
if (!found || !validAuth(auth)) throw fail('receiver-not-registered', 403)
|
|
6496
|
+
return found
|
|
6497
|
+
}
|
|
6498
|
+
const view = row => Object.fromEntries(['id', 'deviceId', 'fileName', 'size', 'sha256', 'phase', 'title', 'message', 'sessionId', 'createdAt', 'expiresAt', 'updatedAt'].map(k => [k, row[k]]))
|
|
6499
|
+
const owned = (auth, key, id) => {
|
|
6500
|
+
const d = device(auth, key), row = state.transfers.find(row => row.id === id && row.deviceId === d.id)
|
|
6501
|
+
if (!row) throw fail('transfer-not-found', 404)
|
|
6502
|
+
return row
|
|
6503
|
+
}
|
|
6504
|
+
return {
|
|
6505
|
+
register: (auth, key, name) => lock(() => {
|
|
6506
|
+
if (!keyOk(key) || !validAuth(auth)) throw fail('invalid-receiver', 403)
|
|
6507
|
+
let d = state.devices.find(row => row.auth === auth && row.keyHash === digest(key))
|
|
6508
|
+
if (!d) {
|
|
6509
|
+
state.devices = state.devices.filter(row => validAuth(row.auth) && row.lastSeenAt > now() - 30 * ttl)
|
|
6510
|
+
if (state.devices.length >= 100) throw fail('too-many-receivers', 409)
|
|
6511
|
+
d = { id: crypto.randomUUID(), auth, keyHash: digest(key) }; state.devices.push(d)
|
|
6512
|
+
}
|
|
6513
|
+
d.name = String(name || 'Remote 设备').replace(/[\x00-\x1f]/g, '').slice(0, 60)
|
|
6514
|
+
d.lastSeenAt = now(); save()
|
|
6515
|
+
return { id: d.id, name: d.name, maxFile, ttl }
|
|
6516
|
+
}),
|
|
6517
|
+
devices: () => lock(() => state.devices.filter(d => validAuth(d.auth)).map(d => ({ id: d.id, name: d.name, lastSeenAt: d.lastSeenAt, online: now() - d.lastSeenAt < 45000 }))),
|
|
6518
|
+
list: (auth, key) => lock(() => {
|
|
6519
|
+
const d = device(auth, key)
|
|
6520
|
+
return state.transfers.filter(row => row.deviceId === d.id).slice(-50).reverse().map(view)
|
|
6521
|
+
}),
|
|
6522
|
+
send: body => lock(async () => {
|
|
6523
|
+
if (!idOk(body.id) || typeof body.path !== 'string' || typeof body.workspaceRoot !== 'string' || typeof body.deviceId !== 'string' || typeof body.sessionId !== 'string') throw fail('invalid-delivery')
|
|
6524
|
+
const requestHash = digest(JSON.stringify([body.deviceId, body.path, body.workspaceRoot, body.sessionId, body.title || '', body.message || '']))
|
|
6525
|
+
const previous = state.transfers.find(row => row.id === body.id)
|
|
6526
|
+
if (previous) { if (previous.requestHash !== requestHash) throw fail('delivery-id-conflict', 409); return view(previous) }
|
|
6527
|
+
const recipient = state.devices.find(d => d.id === body.deviceId && validAuth(d.auth))
|
|
6528
|
+
if (!recipient) throw fail('receiver-not-found', 404)
|
|
6529
|
+
if (state.transfers.length >= 200 || state.transfers.filter(row => !terminal.has(row.phase)).length >= 20 || state.transfers.filter(row => row.expiresAt > now() && !row.snapshotDeleted && row.phase !== 'rejected').reduce((sum, row) => sum + row.size, 0) >= 200 * 1024 * 1024) throw fail('inbox-full', 409)
|
|
6530
|
+
const source = await resolveSource(body.path, body.workspaceRoot)
|
|
6531
|
+
let input, output
|
|
6532
|
+
const part = path.join(root, body.id + '.part')
|
|
6533
|
+
try {
|
|
6534
|
+
input = await fs.promises.open(source, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0))
|
|
6535
|
+
const before = await input.stat()
|
|
6536
|
+
if (!before.isFile() || before.size > maxFile) throw fail('file-too-large-or-not-regular', 413)
|
|
6537
|
+
if (state.transfers.filter(row => row.expiresAt > now() && !row.snapshotDeleted && row.phase !== 'rejected').reduce((sum, row) => sum + row.size, 0) + before.size > 200 * 1024 * 1024) throw fail('inbox-full', 409)
|
|
6538
|
+
// Recheck path policy after opening; aliases must still identify the opened inode.
|
|
6539
|
+
if (await resolveSource(body.path, body.workspaceRoot) !== source) throw fail('source-changed', 409)
|
|
6540
|
+
const current = await fs.promises.stat(source)
|
|
6541
|
+
if (current.dev !== before.dev || current.ino !== before.ino) throw fail('source-changed', 409)
|
|
6542
|
+
output = await fs.promises.open(part, 'wx', 0o600)
|
|
6543
|
+
const hasher = crypto.createHash('sha256'), buffer = Buffer.alloc(65536)
|
|
6544
|
+
let size = 0
|
|
6545
|
+
for (;;) {
|
|
6546
|
+
const { bytesRead } = await input.read(buffer, 0, buffer.length, null)
|
|
6547
|
+
if (!bytesRead) break
|
|
6548
|
+
size += bytesRead
|
|
6549
|
+
if (size > maxFile) throw fail('file-too-large', 413)
|
|
6550
|
+
const chunk = buffer.subarray(0, bytesRead); hasher.update(chunk); await output.writeFile(chunk)
|
|
6551
|
+
}
|
|
6552
|
+
const after = await input.stat()
|
|
6553
|
+
if (size !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw fail('source-changed', 409)
|
|
6554
|
+
await output.close(); output = null
|
|
6555
|
+
await fs.promises.rename(part, file(body.id))
|
|
6556
|
+
const row = { id: body.id, deviceId: recipient.id, auth: recipient.auth, requestHash, fileName: path.basename(source).replace(/[\x00-\x1f]/g, '').slice(0, 180), size, sha256: hasher.digest('hex'), phase: 'pending', title: String(body.title || '').slice(0, 120), message: String(body.message || '').slice(0, 600), sessionId: body.sessionId.slice(0, 200), createdAt: now(), updatedAt: now(), expiresAt: now() + ttl }
|
|
6557
|
+
state.transfers.push(row)
|
|
6558
|
+
try { save() } catch (e) { state.transfers = state.transfers.filter(row => row.id !== body.id); await fs.promises.unlink(file(body.id)); throw e }
|
|
6559
|
+
return view(row)
|
|
6560
|
+
} finally {
|
|
6561
|
+
await input?.close(); await output?.close()
|
|
6562
|
+
try { await fs.promises.unlink(part) } catch (e) { if (e.code !== 'ENOENT') throw e }
|
|
6563
|
+
}
|
|
6564
|
+
}),
|
|
6565
|
+
status: (id, sessionId) => lock(() => {
|
|
6566
|
+
const row = state.transfers.find(r => r.id === id && r.sessionId === sessionId)
|
|
6567
|
+
if (!row) throw fail('transfer-not-found', 404)
|
|
6568
|
+
return view(row)
|
|
6569
|
+
}),
|
|
6570
|
+
decide: (auth, key, id, action) => lock(() => {
|
|
6571
|
+
const row = owned(auth, key, id)
|
|
6572
|
+
if (row.expiresAt <= now()) throw fail('transfer-expired', 410)
|
|
6573
|
+
if (action === 'reject') {
|
|
6574
|
+
if (row.phase === 'rejected') return view(row)
|
|
6575
|
+
if (row.phase !== 'pending') throw fail('transfer-already-decided', 409)
|
|
6576
|
+
row.phase = 'rejected'; row.updatedAt = now(); save()
|
|
6577
|
+
try { fs.unlinkSync(file(row.id)) } catch (e) { if (e.code !== 'ENOENT') throw e }
|
|
6578
|
+
return view(row)
|
|
6579
|
+
}
|
|
6580
|
+
if (action !== 'accept' || !['pending', 'accepted', 'downloading', 'failed'].includes(row.phase)) throw fail('transfer-already-decided', 409)
|
|
6581
|
+
const ticket = crypto.randomBytes(24).toString('hex')
|
|
6582
|
+
row.phase = 'accepted'; row.ticketHash = digest(ticket); row.ticketExpiresAt = Math.min(row.expiresAt, now() + 1800000); row.updatedAt = now(); save()
|
|
6583
|
+
return { ...view(row), ticket }
|
|
6584
|
+
}),
|
|
6585
|
+
download: (auth, id, ticket) => lock(async () => {
|
|
6586
|
+
const row = state.transfers.find(r => r.id === id && r.auth === auth)
|
|
6587
|
+
if (!row || !validAuth(auth) || typeof ticket !== 'string' || !row.ticketHash || row.ticketHash !== digest(ticket) || row.ticketExpiresAt <= now() || !['accepted', 'downloading'].includes(row.phase)) throw fail('download-not-authorized', 403)
|
|
6588
|
+
const bytes = await fs.promises.readFile(file(row.id))
|
|
6589
|
+
if (bytes.length !== row.size || digest(bytes) !== row.sha256) { row.phase = 'failed'; delete row.ticketHash; save(); throw fail('snapshot-integrity-failed', 409) }
|
|
6590
|
+
row.phase = 'downloading'; row.updatedAt = now(); save()
|
|
6591
|
+
return { bytes, row: view(row) }
|
|
6592
|
+
}),
|
|
6593
|
+
acknowledge: (auth, key, id, phase) => lock(() => {
|
|
6594
|
+
const row = owned(auth, key, id)
|
|
6595
|
+
if (!['downloaded', 'complete', 'failed'].includes(phase)) throw fail('invalid-receipt')
|
|
6596
|
+
if (row.phase === phase) return view(row)
|
|
6597
|
+
if (row.phase !== 'downloading' && !(phase === 'failed' && row.phase === 'accepted')) throw fail('download-not-started', 409)
|
|
6598
|
+
row.phase = phase; row.updatedAt = now(); delete row.ticketHash; save()
|
|
6599
|
+
return view(row)
|
|
6600
|
+
}),
|
|
6601
|
+
}
|
|
6602
|
+
}
|
|
6603
|
+
// END FILE INBOX STORE
|
|
6604
|
+
const inboxAuthHash = token => crypto.createHash('sha256').update(String(token || '')).digest('hex')
|
|
6605
|
+
const fileInbox = createFileInbox({
|
|
6606
|
+
root: path.join(os.homedir(), '.dsh-remote', 'file-inbox'),
|
|
6607
|
+
validAuth: hash => (deviceKeyState.enabled ? deviceKeyState.keys.map(d => d.token) : [TOKEN]).some(token => inboxAuthHash(token) === hash),
|
|
6608
|
+
resolveSource: async (input, workspaceRoot) => {
|
|
6609
|
+
if (!path.isAbsolute(input) || !path.isAbsolute(workspaceRoot)) throw Object.assign(Error('absolute-local-path-required'), { status: 400 })
|
|
6610
|
+
const resolved = await fsResolve(input)
|
|
6611
|
+
const checked = !resolved.error && fsRealChecked(resolved.abs)
|
|
6612
|
+
let root
|
|
6613
|
+
try { root = (fs.realpathSync.native || fs.realpathSync)(workspaceRoot) } catch {}
|
|
6614
|
+
if (!root || !checked?.abs || !fsInsideRoot(checked.abs, root)) throw Object.assign(Error('source-outside-workspace-or-forbidden'), { status: 403 })
|
|
6615
|
+
return checked.abs
|
|
6616
|
+
},
|
|
6617
|
+
})
|
|
6618
|
+
async function serveFileInbox(req, res, url) {
|
|
6619
|
+
cors(res)
|
|
6620
|
+
const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }); res.end(JSON.stringify(value)) }
|
|
6621
|
+
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
6622
|
+
const admin = url.pathname === '/admin/api/file-inbox'
|
|
6623
|
+
if (!(admin ? adminAuthorized(req, url) : authorized(req, url))) return reply(401, { error: 'unauthorized' })
|
|
6624
|
+
const auth = inboxAuthHash(tokenOf(req, url)), key = req.headers['x-dsh-remote-inbox-key']
|
|
6625
|
+
try {
|
|
6626
|
+
const body = req.method === 'POST' ? JSON.parse(await readBody(req, 16384)) : {}
|
|
6627
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return reply(400, { error: 'invalid-body' })
|
|
6628
|
+
if (admin) {
|
|
6629
|
+
if (req.method === 'GET') return reply(200, { devices: await fileInbox.devices() })
|
|
6630
|
+
if (req.method !== 'POST') return reply(405, { error: 'method-not-allowed' })
|
|
6631
|
+
if (body.action === 'send') return reply(200, await fileInbox.send(body))
|
|
6632
|
+
if (body.action === 'status') return reply(200, await fileInbox.status(body.id, body.sessionId))
|
|
6633
|
+
return reply(400, { error: 'invalid-action' })
|
|
6634
|
+
}
|
|
6635
|
+
touchDevice(req)
|
|
6636
|
+
if (url.pathname === '/fs/inbox-file') {
|
|
6637
|
+
if (req.method !== 'GET') return reply(405, { error: 'method-not-allowed' })
|
|
6638
|
+
const out = await fileInbox.download(auth, url.searchParams.get('id'), url.searchParams.get('ticket'))
|
|
6639
|
+
res.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': out.bytes.length, 'content-disposition': fsContentDisposition(out.row.fileName), 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' })
|
|
6640
|
+
res.end(out.bytes); return
|
|
6641
|
+
}
|
|
6642
|
+
if (url.pathname !== '/api/file-inbox') return reply(404, { error: 'not-found' })
|
|
6643
|
+
if (req.method === 'GET') return reply(200, { transfers: await fileInbox.list(auth, key) })
|
|
6644
|
+
if (req.method !== 'POST') return reply(405, { error: 'method-not-allowed' })
|
|
6645
|
+
if (body.action === 'register') return reply(200, await fileInbox.register(auth, key, body.name))
|
|
6646
|
+
if (['accept', 'reject'].includes(body.action)) return reply(200, await fileInbox.decide(auth, key, body.id, body.action))
|
|
6647
|
+
if (body.action === 'receipt') return reply(200, await fileInbox.acknowledge(auth, key, body.id, body.phase))
|
|
6648
|
+
return reply(400, { error: 'invalid-action' })
|
|
6649
|
+
} catch (e) { return reply(e.status || (e instanceof SyntaxError ? 400 : 503), { error: e.status ? e.message : 'inbox-unavailable' }) }
|
|
6650
|
+
}
|
|
6408
6651
|
// ---------- 其它 ----------
|
|
6409
6652
|
// Expensive OS/upstream checks run once in the background; public status never
|
|
6410
6653
|
// grants restart authority. Actual lifecycle actions still verify fresh evidence.
|
|
@@ -6517,6 +6760,7 @@ function lanAddresses() {
|
|
|
6517
6760
|
const server = http.createServer(async (req, res) => {
|
|
6518
6761
|
try {
|
|
6519
6762
|
const url = new URL(req.url, 'http://dsh-remote.local')
|
|
6763
|
+
if (url.pathname === '/api/file-inbox' || url.pathname.startsWith('/api/file-inbox/') || url.pathname === '/fs/inbox-file' || url.pathname === '/admin/api/file-inbox') return await serveFileInbox(req, res, url)
|
|
6520
6764
|
if (url.pathname === '/relay') return await serveRelaySettings(req, res, url)
|
|
6521
6765
|
if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)
|
|
6522
6766
|
if (url.pathname === '/workbench' || url.pathname.startsWith('/workbench/')) return serveWorkbench(req, res, url)
|