dsh-remote-plugin 0.7.5 → 0.8.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/gateway.cjs CHANGED
@@ -39,6 +39,509 @@ const crypto = require('node:crypto')
39
39
  const zlib = require('node:zlib')
40
40
  const { pipeline } = require('node:stream')
41
41
 
42
+ // BEGIN GENERATED RELAY HOST
43
+ const embeddedRelayHost = (() => {
44
+ const factories = {
45
+ "./registry.cjs": function(require, module, exports) {
46
+ 'use strict'
47
+ // Operator-owned relay state. This is separate from every user's Remote profile.
48
+ const fs = require('node:fs')
49
+ const path = require('node:path')
50
+ const crypto = require('node:crypto')
51
+ const net = require('node:net')
52
+
53
+ function fault(code, status = 400) { return Object.assign(new Error(code), { code, status }) }
54
+ function hostname(value) {
55
+ const name = String(value || '').toLowerCase()
56
+ if (name.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]*$/.test(name)) throw fault('INVALID_HOST')
57
+ return name
58
+ }
59
+ function publicKey(value) {
60
+ if (typeof value !== 'string' || value.length > 1024) throw fault('INVALID_PUBLIC_KEY')
61
+ let key
62
+ try { key = crypto.createPublicKey(value) } catch { throw fault('INVALID_PUBLIC_KEY') }
63
+ if (key.asymmetricKeyType !== 'ed25519') throw fault('INVALID_PUBLIC_KEY')
64
+ return key.export({ format: 'pem', type: 'spki' }).toString()
65
+ }
66
+ const digest = value => crypto.createHash('sha256').update(value).digest('hex')
67
+ const live = (grant, now = Date.now()) => grant && !grant.revokedAt && grant.expiresAt > now
68
+ const signingText = (nonce, id, role, session = '') => Buffer.from(JSON.stringify(['dsh-relay-v1', nonce, id, role, session]))
69
+
70
+ class Registry {
71
+ constructor(file) { this.file = path.resolve(file) }
72
+ read() {
73
+ const state = JSON.parse(fs.readFileSync(this.file, 'utf8'))
74
+ if (state.version !== 1 || !Array.isArray(state.grants)) throw fault('INVALID_REGISTRY', 503)
75
+ return state
76
+ }
77
+ change(fn) {
78
+ const lock = this.file + '.lock'
79
+ let fd
80
+ try { fd = fs.openSync(lock, 'wx', 0o600) } catch { throw fault('REGISTRY_BUSY', 503) }
81
+ try {
82
+ const state = this.read()
83
+ const result = fn(state)
84
+ const temp = this.file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp'
85
+ try {
86
+ fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
87
+ fs.renameSync(temp, this.file)
88
+ } finally { try { fs.unlinkSync(temp) } catch {} }
89
+ return result
90
+ } finally { fs.closeSync(fd); fs.unlinkSync(lock) }
91
+ }
92
+ static init(file, config) {
93
+ const origin = new URL(config.origin)
94
+ if (origin.protocol !== 'https:' || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash) throw fault('HTTPS_ORIGIN_REQUIRED')
95
+ const baseDomain = hostname(config.baseDomain)
96
+ const tunnelValue = config.tunnelHost || origin.hostname
97
+ const tunnelHost = net.isIP(tunnelValue) ? tunnelValue : hostname(tunnelValue)
98
+ const tunnelPort = Number(config.tunnelPort || origin.port || 443)
99
+ if (!Number.isInteger(tunnelPort) || tunnelPort < 1 || tunnelPort > 65535) throw fault('INVALID_PORT')
100
+ fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true, mode: 0o700 })
101
+ fs.writeFileSync(file, JSON.stringify({ version: 1, origin: origin.origin, baseDomain, tunnelHost, tunnelPort, maxUsers: 5, grants: [] }, null, 2) + '\n', { flag: 'wx', mode: 0o600 })
102
+ return new Registry(file)
103
+ }
104
+ issue({ label = '', domain, expiresAt }) {
105
+ const expires = Number(expiresAt)
106
+ if (!Number.isFinite(expires) || expires <= Date.now() || expires > Date.now() + 90 * 86400000) throw fault('INVALID_EXPIRY')
107
+ return this.change(state => {
108
+ if (state.grants.filter(g => live(g)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
109
+ const id = crypto.randomBytes(8).toString('hex')
110
+ const assigned = hostname(domain || `r-${id}.${state.baseDomain}`)
111
+ if (!assigned.endsWith('.' + state.baseDomain) || assigned === new URL(state.origin).hostname || assigned === state.tunnelHost) throw fault('INVALID_TENANT_DOMAIN')
112
+ if (state.grants.some(g => g.domain === assigned)) throw fault('DOMAIN_ALREADY_ASSIGNED', 409)
113
+ const code = `dsrp_${id}.${crypto.randomBytes(32).toString('base64url')}`
114
+ const grant = { id, label: String(label).slice(0, 80), domain: assigned, expiresAt: expires, createdAt: Date.now(), codeHash: digest(code), publicKey: null, revokedAt: null }
115
+ state.grants.push(grant)
116
+ return { code, grant: this.view(grant) }
117
+ })
118
+ }
119
+ view(g) { return { id: g.id, label: g.label, domain: g.domain, expiresAt: g.expiresAt, state: g.revokedAt ? 'revoked' : !live(g) ? 'expired' : g.publicKey ? 'bound' : 'invited', fingerprint: g.publicKey ? digest(g.publicKey) : null } }
120
+ list() { return this.read().grants.map(g => this.view(g)) }
121
+ revoke(id) {
122
+ return this.change(state => {
123
+ const grant = state.grants.find(g => g.id === id)
124
+ if (!grant) throw fault('NOT_FOUND', 404)
125
+ grant.revokedAt ||= Date.now()
126
+ return this.view(grant)
127
+ })
128
+ }
129
+ enroll(code, key) {
130
+ const match = /^dsrp_([a-f0-9]{16})\.[A-Za-z0-9_-]{43}$/.exec(String(code || ''))
131
+ if (!match) throw fault('INVALID_AUTHORIZATION', 403)
132
+ const normalized = publicKey(key)
133
+ return this.change(state => {
134
+ const grant = state.grants.find(g => g.id === match[1])
135
+ if (!live(grant) || !crypto.timingSafeEqual(Buffer.from(grant.codeHash, 'hex'), Buffer.from(digest(code), 'hex'))) throw fault('INVALID_AUTHORIZATION', 403)
136
+ if (grant.publicKey && grant.publicKey !== normalized) throw fault('HOST_ALREADY_BOUND', 409)
137
+ grant.publicKey = normalized
138
+ return { grantId: grant.id, domain: grant.domain, expiresAt: grant.expiresAt, publicUrl: `https://${grant.domain}`, dailyLimitBytes: 5_000_000_000, timezone: 'Asia/Shanghai', transport: 'https-upgrade', tunnelOrigin: state.origin, tunnelHost: state.tunnelHost, tunnelPort: state.tunnelPort }
139
+ })
140
+ }
141
+ get(id) { return this.read().grants.find(g => g.id === id) }
142
+ }
143
+
144
+ module.exports = { Registry, fault, hostname, publicKey, digest, live, signingText }
145
+ },
146
+ "./wire.cjs": function(require, module, exports) {
147
+ 'use strict'
148
+ const { fault } = require('./registry.cjs')
149
+
150
+ // One bounded JSON line for each state transition, then unmodified TCP bytes.
151
+ // Pausing and unshifting the tail preserves coalesced handshake + HTTP packets.
152
+ function line(socket, timeout = 10000) {
153
+ return new Promise((resolve, reject) => {
154
+ let buffered = Buffer.alloc(0)
155
+ const timer = setTimeout(() => finish(fault('HANDSHAKE_TIMEOUT', 408)), timeout)
156
+ const clean = () => { clearTimeout(timer); socket.off('data', data); socket.off('error', error); socket.off('close', closed) }
157
+ const finish = (err, result) => { clean(); err ? reject(err) : resolve(result) }
158
+ const error = () => finish(fault('CHANNEL_ERROR', 503))
159
+ const closed = () => finish(fault('CHANNEL_CLOSED', 503))
160
+ const data = chunk => {
161
+ buffered = Buffer.concat([buffered, chunk])
162
+ const end = buffered.indexOf(10)
163
+ if (end < 0 && buffered.length <= 8192) return
164
+ if (end < 0 || end > 8192) return finish(fault('HANDSHAKE_TOO_LARGE', 413))
165
+ socket.pause()
166
+ const tail = buffered.subarray(end + 1)
167
+ if (tail.length) socket.unshift(tail)
168
+ try { finish(null, JSON.parse(buffered.subarray(0, end).toString('utf8'))) } catch { finish(fault('INVALID_HANDSHAKE')) }
169
+ }
170
+ socket.on('data', data); socket.once('error', error); socket.once('close', closed)
171
+ socket.resume()
172
+ })
173
+ }
174
+ function send(socket, value) { if (!socket.destroyed) socket.write(JSON.stringify(value) + '\n') }
175
+ function link(left, right) {
176
+ left.on('error', () => right.destroy()); right.on('error', () => left.destroy())
177
+ left.once('close', () => right.destroy()); right.once('close', () => left.destroy())
178
+ left.pipe(right); right.pipe(left)
179
+ left.resume(); right.resume()
180
+ }
181
+ module.exports = { line, send, link }
182
+ },
183
+ "./options.cjs": function(require, module, exports) {
184
+ 'use strict'
185
+ module.exports = function options(args) {
186
+ const result = { _: [] }
187
+ for (let i = 0; i < args.length; i++) {
188
+ if (!args[i].startsWith('--')) result._.push(args[i])
189
+ else {
190
+ const key = args[i].slice(2)
191
+ if (!key || i + 1 >= args.length || args[i + 1].startsWith('--') || Object.hasOwn(result, key)) throw new Error('Invalid CLI option')
192
+ result[key] = args[++i]
193
+ }
194
+ }
195
+ return result
196
+ }
197
+ },
198
+ "./client.cjs": function(require, module, exports) {
199
+ 'use strict'
200
+ const fs = require('node:fs')
201
+ const path = require('node:path')
202
+ const crypto = require('node:crypto')
203
+ const https = require('node:https')
204
+ const tls = require('node:tls')
205
+ const net = require('node:net')
206
+ const { EventEmitter } = require('node:events')
207
+ const { line, send, link } = require('./wire.cjs')
208
+ const { signingText, fault } = require('./registry.cjs')
209
+
210
+ function gatewayAddress(value) {
211
+ const url = new URL(value)
212
+ if (url.protocol !== 'http:' || !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) || url.username || url.password || url.pathname !== '/' || url.search || url.hash) throw fault('LOCAL_GATEWAY_REQUIRED')
213
+ return { host: url.hostname.replace(/^\[|\]$/g, ''), port: Number(url.port || 80) }
214
+ }
215
+ function enroll(origin, code, publicKey, ca) {
216
+ const url = new URL('/relay/v1/enroll', origin)
217
+ if (new URL(origin).origin !== String(origin).replace(/\/$/, '') || url.protocol !== 'https:' || url.username || url.password) return Promise.reject(fault('HTTPS_ORIGIN_REQUIRED'))
218
+ return new Promise((resolve, reject) => {
219
+ const data = Buffer.from(JSON.stringify({ code, publicKey }))
220
+ const request = https.request(url, { method: 'POST', ca, headers: { 'content-type': 'application/json', 'content-length': data.length }, timeout: 12000 }, response => {
221
+ const chunks = []; let bytes = 0
222
+ response.on('data', chunk => { bytes += chunk.length; if (bytes > 8192) request.destroy(); else chunks.push(chunk) })
223
+ response.on('end', () => {
224
+ if (response.statusCode !== 200) {
225
+ let code = 'ENROLLMENT_REJECTED'
226
+ try {
227
+ const candidate = JSON.parse(Buffer.concat(chunks).toString('utf8')).error
228
+ if (['INVALID_AUTHORIZATION', 'HOST_ALREADY_BOUND', 'REGISTRY_BUSY', 'TRY_LATER', 'INVALID_PUBLIC_KEY', 'INVALID_ENROLLMENT'].includes(candidate)) code = candidate
229
+ } catch {}
230
+ return reject(fault(code, response.statusCode))
231
+ }
232
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) } catch { reject(fault('INVALID_SERVER_RESPONSE')) }
233
+ })
234
+ })
235
+ request.on('timeout', () => request.destroy())
236
+ request.on('error', () => reject(fault('ENROLLMENT_CONNECTION_FAILED', 503)))
237
+ request.end(data)
238
+ })
239
+ }
240
+
241
+ function upgradeChannel(origin, ca) {
242
+ const target = new URL(origin)
243
+ if (target.protocol !== 'https:' || target.username || target.password || target.pathname !== '/' || target.search || target.hash) return Promise.reject(fault('HTTPS_ORIGIN_REQUIRED'))
244
+ return new Promise((resolve, reject) => {
245
+ const request = https.request(new URL('/relay/v1/tunnel', target), { ca, headers: { connection: 'Upgrade', upgrade: 'dsh-relay-v1' }, timeout: 12000 })
246
+ request.on('upgrade', (response, socket, head) => {
247
+ request.setTimeout(0)
248
+ if (String(response.headers.upgrade).toLowerCase() !== 'dsh-relay-v1') { socket.destroy(); return reject(fault('INVALID_TUNNEL_UPGRADE')) }
249
+ socket.pause()
250
+ if (head.length) socket.unshift(head)
251
+ resolve(socket)
252
+ })
253
+ request.on('response', response => { response.resume(); reject(fault('TUNNEL_UPGRADE_REJECTED', response.statusCode)) })
254
+ request.on('timeout', () => request.destroy())
255
+ request.on('error', () => reject(fault('TUNNEL_CONNECTION_FAILED', 503)))
256
+ request.end()
257
+ })
258
+ }
259
+
260
+ class RelayClient extends EventEmitter {
261
+ constructor({ grantId, privateKey, tunnelHost, tunnelPort, tunnelOrigin, expiresAt, gateway = 'http://127.0.0.1:8787', ca, poolSize = 4, reconnectMs = 1500 }) {
262
+ super()
263
+ if (!/^[a-f0-9]{16}$/.test(grantId || '') || !Number.isInteger(Number(tunnelPort)) || tunnelPort < 1 || tunnelPort > 65535 || !Number.isFinite(expiresAt)) throw fault('INVALID_CLIENT_CONFIG')
264
+ this.grantId = grantId; this.privateKey = crypto.createPrivateKey(privateKey)
265
+ if (this.privateKey.asymmetricKeyType !== 'ed25519') throw fault('INVALID_PRIVATE_KEY')
266
+ this.target = gatewayAddress(gateway)
267
+ this.tunnelHost = tunnelHost; this.tunnelPort = Number(tunnelPort); this.expiresAt = expiresAt; this.ca = ca
268
+ this.tunnelOrigin = tunnelOrigin
269
+ this.poolSize = Math.min(6, Math.max(1, poolSize)); this.reconnectMs = reconnectMs
270
+ this.context = null; this.running = false; this.timer = null; this.failures = 0; this.controlSocket = null; this.epoch = 0
271
+ }
272
+ async authenticate(role, session = '', context) {
273
+ const socket = this.tunnelOrigin ? await upgradeChannel(this.tunnelOrigin, this.ca) : tls.connect({ host: this.tunnelHost, port: this.tunnelPort, servername: net.isIP(this.tunnelHost) ? undefined : this.tunnelHost, ca: this.ca, minVersion: 'TLSv1.2', rejectUnauthorized: true })
274
+ socket.on('error', () => {}); socket.setNoDelay(true); socket.setKeepAlive(true, 30000)
275
+ if (context) { context.sockets.add(socket); socket.once('close', () => context.sockets.delete(socket)) }
276
+ else this.controlSocket = socket
277
+ try {
278
+ const challenge = await line(socket)
279
+ if (challenge.type !== 'challenge' || !/^[A-Za-z0-9_-]{43}$/.test(challenge.nonce || '')) throw fault('INVALID_CHALLENGE')
280
+ const signature = crypto.sign(null, signingText(challenge.nonce, this.grantId, role, session), this.privateKey).toString('base64url')
281
+ send(socket, { grantId: this.grantId, role, session, signature })
282
+ const accepted = await line(socket)
283
+ if (accepted.type === 'rejected' && accepted.code === 'AUTHORIZATION_INACTIVE') throw fault('AUTHORIZATION_INACTIVE', 403)
284
+ if (!this.running || Date.now() >= this.expiresAt || accepted.type !== (role === 'control' ? 'accepted' : 'parked')) throw fault('CONNECTION_NOT_ACCEPTED')
285
+ return { socket, accepted }
286
+ } catch (error) { socket.destroy(); throw error }
287
+ }
288
+ start() { if (!this.running) { this.running = true; this.epoch++; this.connect() }; return this }
289
+ async connect() {
290
+ if (!this.running) return
291
+ if (Date.now() >= this.expiresAt) { this.stop(); this.emit('status', 'expired'); return }
292
+ let context
293
+ const epoch = this.epoch
294
+ try {
295
+ const { socket, accepted } = await this.authenticate('control')
296
+ if (epoch !== this.epoch) { socket.destroy(); return }
297
+ context = { socket, session: accepted.session, sockets: new Set([socket]), pending: 0, closing: false, retryTimer: null }
298
+ this.context = context; this.failures = 0
299
+ if (accepted.usage) this.emit('usage', accepted.usage)
300
+ this.emit('status', 'online'); this.refill(context)
301
+ while (this.running && !context.closing) {
302
+ const message = await line(socket, 65000)
303
+ if (message.type === 'usage') { this.emit('usage', message.usage); continue }
304
+ if (message.type !== 'ping') throw fault('INVALID_CONTROL_MESSAGE')
305
+ if (message.usage) this.emit('usage', message.usage)
306
+ send(socket, { type: 'pong' })
307
+ }
308
+ } catch (error) {
309
+ if (error.code === 'AUTHORIZATION_INACTIVE') { this.stop(); this.emit('status', 'authorization-inactive') }
310
+ else if (this.running) this.emit('status', 'reconnecting')
311
+ }
312
+ finally {
313
+ if (context) this.dispose(context)
314
+ if (context && this.controlSocket === context.socket) this.controlSocket = null
315
+ if (this.running && epoch === this.epoch) {
316
+ const wait = Math.min(60000, this.reconnectMs * 2 ** Math.min(this.failures++, 6))
317
+ this.timer = setTimeout(() => this.connect(), wait)
318
+ }
319
+ }
320
+ }
321
+ refill(context) {
322
+ if (!this.running || context.closing || this.context !== context || Date.now() >= this.expiresAt) return
323
+ while (context.pending < this.poolSize) { context.pending++; this.work(context) }
324
+ }
325
+ async work(context) {
326
+ let pending = true, remote, local, failed = false
327
+ try {
328
+ const accepted = await this.authenticate('work', context.session, context)
329
+ remote = accepted.socket
330
+ const start = await line(remote, 60000)
331
+ if (start.type !== 'start' || context.closing || this.context !== context) throw fault('STALE_WORK')
332
+ context.pending--; pending = false
333
+ this.refill(context)
334
+ local = net.connect(this.target); context.sockets.add(local)
335
+ local.setNoDelay(true)
336
+ const connectTimer = setTimeout(() => local.destroy(), 5000)
337
+ local.once('connect', () => clearTimeout(connectTimer))
338
+ local.once('close', () => clearTimeout(connectTimer))
339
+ // A work channel is single-use. Failed writes are never replayed.
340
+ link(remote, local)
341
+ await new Promise(resolve => remote.once('close', resolve))
342
+ } catch (error) {
343
+ failed = true
344
+ if (error.code === 'AUTHORIZATION_INACTIVE') { this.stop(); this.emit('status', 'authorization-inactive') }
345
+ }
346
+ finally {
347
+ remote?.destroy(); local?.destroy()
348
+ if (remote) context.sockets.delete(remote)
349
+ if (local) context.sockets.delete(local)
350
+ if (pending) context.pending--
351
+ if (!context.closing && this.running && this.context === context) {
352
+ // Retry failed pool connections at most once per second, not in a hot loop.
353
+ if (failed) {
354
+ if (!context.retryTimer) context.retryTimer = setTimeout(() => { context.retryTimer = null; this.refill(context) }, 1000)
355
+ } else this.refill(context)
356
+ }
357
+ }
358
+ }
359
+ dispose(context) {
360
+ context.closing = true; clearTimeout(context.retryTimer)
361
+ for (const socket of context.sockets) socket.destroy()
362
+ context.sockets.clear()
363
+ if (this.context === context) this.context = null
364
+ }
365
+ stop() {
366
+ this.running = false; this.epoch++; clearTimeout(this.timer); this.controlSocket?.destroy()
367
+ if (this.context) this.dispose(this.context)
368
+ }
369
+ }
370
+
371
+ async function main() {
372
+ const args = require('./options.cjs')(process.argv.slice(2))
373
+ if (!args.state) throw fault('STATE_DIRECTORY_REQUIRED')
374
+ const root = path.resolve(args.state)
375
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 })
376
+ const ca = args.ca ? fs.readFileSync(args.ca) : undefined
377
+ const configFile = path.join(root, 'connection.json')
378
+ const keyFile = path.join(root, 'host-private.pem')
379
+ const stopFile = path.join(root, 'stop.request')
380
+ if (args._[0] === 'enroll') {
381
+ const invite = JSON.parse(fs.readFileSync(args.invite, 'utf8'))
382
+ const gateway = args.gateway || 'http://127.0.0.1:8787'
383
+ gatewayAddress(gateway)
384
+ if (!fs.existsSync(keyFile)) {
385
+ const keys = crypto.generateKeyPairSync('ed25519')
386
+ fs.writeFileSync(keyFile, keys.privateKey.export({ format: 'pem', type: 'pkcs8' }), { flag: 'wx', mode: 0o600 })
387
+ }
388
+ const key = crypto.createPrivateKey(fs.readFileSync(keyFile))
389
+ const pub = crypto.createPublicKey(key).export({ format: 'pem', type: 'spki' }).toString()
390
+ const config = await enroll(invite.server, invite.code, pub, ca)
391
+ fs.writeFileSync(configFile, JSON.stringify({ ...config, gateway }, null, 2) + '\n', { mode: 0o600 })
392
+ console.log(JSON.stringify({ publicUrl: config.publicUrl, expiresAt: config.expiresAt }))
393
+ } else if (args._[0] === 'run') {
394
+ if (fs.existsSync(stopFile)) fs.unlinkSync(stopFile)
395
+ const config = JSON.parse(fs.readFileSync(configFile, 'utf8'))
396
+ const client = new RelayClient({ ...config, privateKey: fs.readFileSync(keyFile), ca })
397
+ let stopTimer
398
+ const stop = () => { clearInterval(stopTimer); client.stop(); setTimeout(() => process.exit(0), 100) }
399
+ client.on('status', status => { console.log(JSON.stringify({ status })); if (['expired', 'authorization-inactive'].includes(status)) stop() })
400
+ stopTimer = setInterval(() => { if (fs.existsSync(stopFile)) stop() }, 500)
401
+ process.once('SIGTERM', stop); process.once('SIGINT', stop)
402
+ client.start()
403
+ } else if (args._[0] === 'stop') {
404
+ fs.writeFileSync(stopFile, 'stop\n', { mode: 0o600 })
405
+ console.log('Relay stop requested.')
406
+ } else throw fault('USE_ENROLL_RUN_OR_STOP')
407
+ }
408
+ if (require.main === module) main().catch(error => { console.error(error.code || 'CLIENT_FAILED'); process.exitCode = 1 })
409
+ module.exports = { RelayClient, enroll, gatewayAddress }
410
+ },
411
+ "./host.cjs": function(require, module, exports) {
412
+ 'use strict'
413
+ const fs = require('node:fs')
414
+ const path = require('node:path')
415
+ const crypto = require('node:crypto')
416
+ const { RelayClient, enroll } = require('./client.cjs')
417
+ const { fault } = require('./registry.cjs')
418
+ const DEFAULT_ORIGIN = 'https://relay-pilot.blankalwaysgoeson.site'
419
+
420
+ // Runs inside the gateway process: no launcher, scheduled task or runtime install.
421
+ class RelayHost {
422
+ constructor({ root, gateway, origin = DEFAULT_ORIGIN, ca }) {
423
+ this.root = root; this.gateway = gateway; this.origin = origin; this.ca = ca
424
+ this.file = path.join(root, 'connection.json'); this.keyFile = path.join(root, 'host-private.pem')
425
+ this.legacyRoot = path.join(path.dirname(root), 'owner-preview')
426
+ this.client = null; this.phase = 'disabled'; this.daily = null; this.updatedAt = null; this.busy = false
427
+ this.config = null; this.error = ''
428
+ if (fs.existsSync(this.file)) {
429
+ try { this.config = JSON.parse(fs.readFileSync(this.file, 'utf8')) }
430
+ catch { this.phase = 'error'; this.error = 'LOCAL_STATE_INVALID' }
431
+ }
432
+ }
433
+ save(config) {
434
+ fs.mkdirSync(this.root, { recursive: true, mode: 0o700 })
435
+ const temp = this.file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp'
436
+ try { fs.writeFileSync(temp, JSON.stringify(config) + '\n', { mode: 0o600, flag: 'wx' }); fs.renameSync(temp, this.file) }
437
+ finally { try { fs.unlinkSync(temp) } catch {} }
438
+ this.config = config
439
+ }
440
+ status() {
441
+ const config = this.config
442
+ let phase = this.phase
443
+ if (config && Date.now() >= config.expiresAt) phase = 'expired'
444
+ else if (config?.enabled && this.daily?.exhausted) phase = 'quota-exceeded'
445
+ else if (config?.enabled && this.daily?.unavailable) phase = 'quota-unavailable'
446
+ return { supported: true, enabled: !!config?.enabled, configured: !!config, phase,
447
+ publicUrl: config?.publicUrl || '', expiresAt: config?.expiresAt || null,
448
+ fingerprint: config?.fingerprint || '', daily: this.daily, usageUpdatedAt: this.updatedAt,
449
+ quotaPending: !!config?.enabled && !this.daily, error: this.error,
450
+ server: this.origin, busy: this.busy, legacyAvailable: !config && !!this.legacy() }
451
+ }
452
+ legacy() {
453
+ try {
454
+ const config = JSON.parse(fs.readFileSync(path.join(this.legacyRoot,'connection.json'),'utf8'))
455
+ if (config.tunnelOrigin !== this.origin || config.expiresAt <= Date.now() || !fs.existsSync(path.join(this.legacyRoot,'host-private.pem'))) return null
456
+ return config
457
+ } catch { return null }
458
+ }
459
+ startSaved() {
460
+ if (this.config?.enabled) {
461
+ try { this.start() } catch { this.phase = 'error'; this.error = 'LOCAL_STATE_INVALID' }
462
+ }
463
+ }
464
+ start() {
465
+ this.stop()
466
+ if (!this.config || !fs.existsSync(this.keyFile)) throw fault('HOST_NOT_CONFIGURED', 409)
467
+ if (this.config.expiresAt <= Date.now()) { this.phase = 'expired'; return }
468
+ // Only the operator-configured service is allowed, never a target supplied by a browser.
469
+ if (this.config.tunnelOrigin !== this.origin) throw fault('RELAY_SERVER_MISMATCH', 409)
470
+ const client = new RelayClient({ ...this.config, gateway: this.gateway, privateKey: fs.readFileSync(this.keyFile), ca: this.ca })
471
+ this.client = client; this.phase = 'connecting'; this.error = ''
472
+ client.on('status', status => { if (this.client === client) this.phase = status })
473
+ client.on('usage', daily => {
474
+ if (this.client !== client) return
475
+ this.daily = daily; this.updatedAt = Date.now()
476
+ })
477
+ client.start()
478
+ }
479
+ stop() { const client = this.client; this.client = null; client?.stop(); this.phase = 'disabled' }
480
+ async change(action, key) {
481
+ if (this.busy) throw fault('RELAY_OPERATION_BUSY', 409)
482
+ this.busy = true
483
+ try {
484
+ if (action === 'import') {
485
+ if (this.config) throw fault('HOST_ALREADY_CONFIGURED',409)
486
+ const config=this.legacy()
487
+ if (!config) throw fault('LEGACY_RELAY_UNAVAILABLE',409)
488
+ const privateKey=fs.readFileSync(path.join(this.legacyRoot,'host-private.pem'))
489
+ new RelayClient({...config,gateway:this.gateway,privateKey,ca:this.ca})
490
+ const publicKey=crypto.createPublicKey(crypto.createPrivateKey(privateKey)).export({format:'pem',type:'spki'}).toString()
491
+ fs.mkdirSync(this.root,{recursive:true,mode:0o700})
492
+ if (fs.existsSync(this.keyFile)) fs.copyFileSync(this.keyFile,this.keyFile+'.before-import-'+crypto.randomBytes(8).toString('hex'),fs.constants.COPYFILE_EXCL)
493
+ const temp=this.keyFile+'.'+crypto.randomBytes(8).toString('hex')+'.tmp'
494
+ try { fs.writeFileSync(temp,privateKey,{flag:'wx',mode:0o600});fs.renameSync(temp,this.keyFile) }
495
+ finally { try { fs.unlinkSync(temp) } catch {} }
496
+ this.save({...config,fingerprint:crypto.createHash('sha256').update(publicKey).digest('hex'),enabled:true})
497
+ // The old launcher observes this file and exits normally. Never kill a PID
498
+ // supplied by a browser or terminate the user's DSH/gateway processes.
499
+ fs.writeFileSync(path.join(this.legacyRoot,'stop.request'),'stop\n',{mode:0o600})
500
+ await new Promise(resolve=>setTimeout(resolve,700))
501
+ this.start()
502
+ } else if (action === 'enroll') {
503
+ if (!/^dsrp_[a-f0-9]{16}\.[A-Za-z0-9_-]{43}$/.test(String(key || '').trim())) throw fault('INVALID_AUTHORIZATION', 400)
504
+ fs.mkdirSync(this.root, { recursive: true, mode: 0o700 })
505
+ if (!fs.existsSync(this.keyFile)) {
506
+ const pair = crypto.generateKeyPairSync('ed25519')
507
+ fs.writeFileSync(this.keyFile, pair.privateKey.export({ format: 'pem', type: 'pkcs8' }), { flag: 'wx', mode: 0o600 })
508
+ }
509
+ const privateKey = crypto.createPrivateKey(fs.readFileSync(this.keyFile))
510
+ const publicKey = crypto.createPublicKey(privateKey).export({ format: 'pem', type: 'spki' }).toString()
511
+ const config = await enroll(this.origin, key.trim(), publicKey, this.ca)
512
+ // Construct before replacing a working configuration; a malformed response cannot disable it.
513
+ new RelayClient({ ...config, gateway: this.gateway, privateKey: privateKey.export({ format: 'pem', type: 'pkcs8' }), ca: this.ca })
514
+ if (config.tunnelOrigin !== this.origin || new URL(config.publicUrl).protocol !== 'https:') throw fault('INVALID_SERVER_RESPONSE', 502)
515
+ this.save({ ...config, fingerprint: crypto.createHash('sha256').update(publicKey).digest('hex'), enabled: true })
516
+ this.daily = null; this.updatedAt = null; this.start()
517
+ } else if (action === 'enable') {
518
+ if (!this.config) throw fault('HOST_NOT_CONFIGURED', 409)
519
+ this.save({ ...this.config, enabled: true }); this.start()
520
+ } else if (action === 'disable') {
521
+ if (this.config) this.save({ ...this.config, enabled: false })
522
+ // Allow the setting response to cross the tunnel before closing it.
523
+ const client = this.client; this.client = null; this.phase = 'disabled'
524
+ const timer = setTimeout(() => client?.stop(), 250); timer.unref?.()
525
+ } else throw fault('INVALID_RELAY_ACTION', 400)
526
+ return this.status()
527
+ } finally { this.busy = false }
528
+ }
529
+ }
530
+ module.exports = { RelayHost, DEFAULT_ORIGIN }
531
+ }
532
+ }
533
+ const cache = Object.create(null)
534
+ function load(name) {
535
+ if (!factories[name]) return require(name)
536
+ if (cache[name]) return cache[name].exports
537
+ const entry = cache[name] = { exports: {} }
538
+ factories[name](load, entry, entry.exports)
539
+ return entry.exports
540
+ }
541
+ return load('./host.cjs')
542
+ })()
543
+ // END GENERATED RELAY HOST
544
+
42
545
  // Compression is local to Remote responses, without changing DSH prototypes.
43
546
  const HTTP_COMPRESSION = process.env.GATEWAY_HTTP_COMPRESSION !== '0'
44
547
  function acceptsGzip(req) {
@@ -192,6 +695,12 @@ const ANNOUNCEMENTS_CACHE_MS = durationEnv('DSH_REMOTE_ANNOUNCEMENTS_CACHE_MS',
192
695
  const ANNOUNCEMENTS_MAX_BYTES = 512 * 1024
193
696
  const PORT = Number(process.env.PORT) || 8787
194
697
  const HOST = process.env.HOST || '0.0.0.0'
698
+ const relayHost = new embeddedRelayHost.RelayHost({
699
+ root: process.env.DSH_REMOTE_RELAY_STATE || path.join(os.homedir(), '.dsh-remote', 'relay-pilot', 'integrated'),
700
+ gateway: `http://127.0.0.1:${PORT}`,
701
+ origin: process.env.DSH_REMOTE_RELAY_ORIGIN || embeddedRelayHost.DEFAULT_ORIGIN,
702
+ ca: process.env.DSH_REMOTE_RELAY_CA_FILE ? fs.readFileSync(process.env.DSH_REMOTE_RELAY_CA_FILE) : undefined,
703
+ })
195
704
 
196
705
  function durationEnv(name, fallback, min, max) {
197
706
  const raw = process.env[name]
@@ -320,6 +829,9 @@ const PROTOCOL_VERSION = 1
320
829
  const CAPABILITIES = Object.freeze({
321
830
  wsTicket: 1,
322
831
  eventPolling: 1,
832
+ eventEpoch: 1,
833
+ operations: 1,
834
+ cloudRelay: 1,
323
835
  workspaceFiles: 2,
324
836
  imagePromptTransport: 1,
325
837
  dshLifecycle: DSH_CONTROL_SUPPORT.supported ? 2 : 0,
@@ -1787,6 +2299,8 @@ const EVENT_MAX_STRING = 16 * 1024
1787
2299
  const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
1788
2300
  const eventBuffers = { mux: [], host: [] }
1789
2301
  const eventNextSeq = { mux: 1, host: 1 }
2302
+ const EVENT_STREAM_EPOCH = crypto.randomUUID()
2303
+ const WS_CLIENT_BUFFER_MAX = durationEnv('GATEWAY_WS_CLIENT_BUFFER_MAX', 2 * 1024 * 1024, 65536, 16 * 1024 * 1024)
1790
2304
  const collectorClients = { mux: new Set(), host: new Set() }
1791
2305
  const collectorReplay = { mux: new Map(), host: new Map() }
1792
2306
  const eventPollWaiters = { mux: new Set(), host: new Set() }
@@ -1967,7 +2481,7 @@ async function refreshModernSessions() {
1967
2481
  return response
1968
2482
  }
1969
2483
 
1970
- async function translateModernRpc(method, payload, rpcId) {
2484
+ async function translateModernRpc(method, payload, rpcId, strictReceipt = false) {
1971
2485
  let endpoint = ''
1972
2486
  let args = {}
1973
2487
  let transform = value => value
@@ -2090,11 +2604,13 @@ async function translateModernRpc(method, payload, rpcId) {
2090
2604
  }
2091
2605
 
2092
2606
  let response = await callUpstreamRemote(endpoint, args, rpcId)
2607
+ if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (!response.body?.result && ![404,405,501].includes(response.status)))) throw new Error('upstream-uncertain')
2093
2608
  if (method === 'session.prompt' && imageAdmissionRejected(response.body)) {
2094
2609
  try {
2095
2610
  const bridged = await bridgeVisionPrompt(args.request)
2096
2611
  if (bridged) response = await callUpstreamRemote(endpoint, { ...args, request: bridged }, rpcId)
2097
2612
  } catch (error) {
2613
+ if (strictReceipt) throw error
2098
2614
  return legacyEnvelope(rpcId, modernError(error.message, 'image-vision-failed'))
2099
2615
  }
2100
2616
  }
@@ -2123,6 +2639,7 @@ async function translateModernRpc(method, payload, rpcId) {
2123
2639
  }))
2124
2640
  return legacyEnvelope(rpcId, { ok: true, value: { entries, parentAvailable: !!modernState.sessions.get(payload.parentSessionId)?.agentAvailable } })
2125
2641
  }
2642
+ if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (!response.body?.result && ![404,405,501].includes(response.status)))) throw new Error('upstream-uncertain')
2126
2643
  if (modernResponseNeedsLegacyFallback(response)) return legacyFallback(`generated RPC ${endpoint} unavailable`)
2127
2644
  if (!response.body?.result?.ok) {
2128
2645
  recordCompatibility('generated-rpc-error', { method, status: response.status, detail: remoteFailureKind(response) })
@@ -2195,6 +2712,13 @@ function broadcastCollectorFrame(kind, raw) {
2195
2712
  collectorClients[kind].delete(socket)
2196
2713
  continue
2197
2714
  }
2715
+ // A slow phone must not retain an unbounded queue on the host. Reconnection
2716
+ // restores the baseline/history; committed events are never selectively dropped.
2717
+ if (socket.writableLength + frame.length > WS_CLIENT_BUFFER_MAX) {
2718
+ collectorClients[kind].delete(socket)
2719
+ socket.destroy()
2720
+ continue
2721
+ }
2198
2722
  try { socket.write(frame) } catch { try { socket.destroy() } catch {} }
2199
2723
  }
2200
2724
  state.clients = collectorClients[kind].size
@@ -2213,12 +2737,17 @@ function pushEvent(kind, full, raw = JSON.stringify(full)) {
2213
2737
  flushEventPollWaiters(kind)
2214
2738
  }
2215
2739
 
2216
- function eventPollPayload(kind, since, waitSupported = false) {
2740
+ function eventPollPayload(kind, since, waitSupported = false, epoch = '') {
2217
2741
  const buf = eventBuffers[kind]
2218
2742
  const events = buf.filter(r => r.seq > since)
2219
2743
  const latestSeq = buf.length ? buf[buf.length - 1].seq : 0
2220
2744
  const truncated = buf.length > 0 && since < buf[0].seq - 1
2221
- return { ok: true, kind, since, latestSeq, truncated, waitSupported, events }
2745
+ const reset = !!epoch && epoch !== EVENT_STREAM_EPOCH || latestSeq < since || truncated
2746
+ const baseline = since === 0 || reset ? [...collectorReplay[kind].values()].map(raw => {
2747
+ try { return JSON.parse(raw) } catch { return null }
2748
+ }).filter(Boolean) : []
2749
+ return { ok: true, kind, epoch: EVENT_STREAM_EPOCH, since, latestSeq, truncated, reset, waitSupported,
2750
+ baseline, events: reset ? buf.slice() : events }
2222
2751
  }
2223
2752
 
2224
2753
  function sendEventPollResponse(waiter, payload) {
@@ -2233,13 +2762,13 @@ function sendEventPollResponse(waiter, payload) {
2233
2762
  function finishEventPollWaiter(waiter, send = true) {
2234
2763
  if (!eventPollWaiters[waiter.kind]?.delete(waiter)) return
2235
2764
  clearTimeout(waiter.timer)
2236
- if (send) sendEventPollResponse(waiter, eventPollPayload(waiter.kind, waiter.since, true))
2765
+ if (send) sendEventPollResponse(waiter, eventPollPayload(waiter.kind, waiter.since, true, waiter.epoch))
2237
2766
  }
2238
2767
 
2239
2768
  function flushEventPollWaiters(kind) {
2240
2769
  for (const waiter of [...eventPollWaiters[kind]]) {
2241
- const payload = eventPollPayload(kind, waiter.since, true)
2242
- if (payload.events.length) finishEventPollWaiter(waiter, true)
2770
+ const payload = eventPollPayload(kind, waiter.since, true, waiter.epoch)
2771
+ if (payload.events.length || payload.reset) finishEventPollWaiter(waiter, true)
2243
2772
  }
2244
2773
  }
2245
2774
 
@@ -2308,8 +2837,9 @@ function serveEventPoll(req, res, url) {
2308
2837
  }
2309
2838
  const wait = Math.min(Math.floor(requestedWait), EVENT_POLL_WAIT_MAX)
2310
2839
  const waitSupported = wait > 0 && EVENT_POLL_WAIT_MAX > 0
2311
- const payload = eventPollPayload(kind, since, waitSupported)
2312
- if (payload.events.length || wait <= 0 || EVENT_POLL_WAIT_MAX <= 0) {
2840
+ const epoch = String(url.searchParams.get('epoch') || '').slice(0, 80)
2841
+ const payload = eventPollPayload(kind, since, waitSupported, epoch)
2842
+ if (payload.events.length || payload.reset || payload.baseline.length || wait <= 0 || EVENT_POLL_WAIT_MAX <= 0) {
2313
2843
  cors(res)
2314
2844
  sendHttpBody(res, 200, {
2315
2845
  'content-type': 'application/json; charset=utf-8',
@@ -2317,13 +2847,13 @@ function serveEventPoll(req, res, url) {
2317
2847
  }, JSON.stringify(payload), true)
2318
2848
  return
2319
2849
  }
2320
- const waiter = { req, res, kind, since, timer: null }
2850
+ const waiter = { req, res, kind, since, epoch, timer: null }
2321
2851
  eventPollWaiters[kind].add(waiter)
2322
2852
  waiter.timer = setTimeout(() => finishEventPollWaiter(waiter, true), wait)
2323
2853
  waiter.timer.unref?.()
2324
2854
  req.once('close', () => finishEventPollWaiter(waiter, false))
2325
2855
  // 事件可能刚好在首次检查和加入等待集合之间到达,加入后再检查一次避免漏唤醒。
2326
- if (eventPollPayload(kind, since, true).events.length) finishEventPollWaiter(waiter, true)
2856
+ if (eventPollPayload(kind, since, true, epoch).events.length) finishEventPollWaiter(waiter, true)
2327
2857
  }
2328
2858
 
2329
2859
  /** 网关自带上游事件采集:mux/host 各一条 WS,断线自动重连。 */
@@ -3307,6 +3837,7 @@ function upstreamReachable(cb) {
3307
3837
 
3308
3838
  async function serveAdminApi(req, res, url) {
3309
3839
  const sub = url.pathname.slice('/admin/api'.length) || '/'
3840
+ if (sub === '/relay') return serveRelaySettings(req, res, url)
3310
3841
  if (sub === '/dsh') return serveDshControl(req, res, url)
3311
3842
  if (sub === '/state' && req.method === 'GET') {
3312
3843
  if (!adminAuthorized(req, url)) {
@@ -3534,6 +4065,29 @@ async function serveAdminApi(req, res, url) {
3534
4065
  res.end(JSON.stringify({ error: 'not-found' }))
3535
4066
  }
3536
4067
 
4068
+ async function serveRelaySettings(req, res, url) {
4069
+ cors(res)
4070
+ const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
4071
+ if (req.method === 'OPTIONS') { res.writeHead(204); return res.end() }
4072
+ if (!['GET', 'POST'].includes(req.method)) { res.setHeader('allow', 'GET, POST, OPTIONS'); return reply(405, { error: 'METHOD_NOT_ALLOWED' }) }
4073
+ const canManage = adminAuthorized(req, url)
4074
+ if (!canManage && !authorized(req, url)) return reply(401, { error: 'unauthorized' })
4075
+ if (req.method === 'GET') return reply(200, { ...relayHost.status(), canManage })
4076
+ if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
4077
+ try {
4078
+ const chunks = []; let size = 0
4079
+ for await (const chunk of req) { size += chunk.length; if (size > 4096) return reply(413, { error: 'BODY_TOO_LARGE' }); chunks.push(chunk) }
4080
+ let value
4081
+ try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { return reply(400, { error: 'INVALID_JSON' }) }
4082
+ if (!value || Object.keys(value).some(key => !['action', 'key'].includes(key))) return reply(400, { error: 'INVALID_RELAY_ACTION' })
4083
+ const result = await relayHost.change(value.action, value.key)
4084
+ return reply(200, { ...result, canManage: true })
4085
+ } catch (error) {
4086
+ const known = new Set(['INVALID_AUTHORIZATION', 'HOST_ALREADY_BOUND', 'REGISTRY_BUSY', 'TRY_LATER', 'ENROLLMENT_CONNECTION_FAILED', 'ENROLLMENT_REJECTED', 'RELAY_OPERATION_BUSY', 'HOST_NOT_CONFIGURED', 'INVALID_RELAY_ACTION', 'RELAY_SERVER_MISMATCH', 'INVALID_SERVER_RESPONSE', 'HOST_ALREADY_CONFIGURED', 'LEGACY_RELAY_UNAVAILABLE'])
4087
+ return reply(error.status || 503, { error: known.has(error.code) ? error.code : 'RELAY_OPERATION_FAILED' })
4088
+ }
4089
+ }
4090
+
3537
4091
  // ---------- /fs 文件传输: 实现 ----------
3538
4092
  function fsJson(res, status, body, extraHeaders = {}) {
3539
4093
  cors(res)
@@ -4800,6 +5354,139 @@ function sendBufferedUpstreamResponse(res, response) {
4800
5354
  }, response.raw || '', compressibleRpc(res.req))
4801
5355
  }
4802
5356
 
5357
+ // A durable receipt records intent before forwarding. Only a hash of the
5358
+ // payload is stored. A crash/timeout is UNKNOWN, never permission to replay a
5359
+ // potentially committed upstream write. Old DSH needs no invented RPC support.
5360
+ const OPERATION_METHODS = new Set(['session.create', 'session.prompt', 'session.updateQueue',
5361
+ 'session.selectModel', 'session.rename', 'session.cancel', 'workspace.create',
5362
+ 'workspace.archiveSession', 'goal.edit', 'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear'])
5363
+ const OPERATION_DIR = path.join(path.dirname(TOKEN_FILE), 'operations')
5364
+ const OPERATION_TTL = 24 * 60 * 60 * 1000
5365
+ const operationJobs = new Map()
5366
+ function operationHash(value) { return crypto.createHash('sha256').update(value).digest('hex') }
5367
+ function operationJson(value) {
5368
+ if (Array.isArray(value)) return '[' + value.map(operationJson).join(',') + ']'
5369
+ if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + operationJson(value[k])).join(',') + '}'
5370
+ return JSON.stringify(value)
5371
+ }
5372
+ function saveOperation(key, job) {
5373
+ fs.mkdirSync(OPERATION_DIR, { recursive: true, mode: 0o700 })
5374
+ const target = path.join(OPERATION_DIR, key + '.json')
5375
+ fs.writeFileSync(target + '.tmp', JSON.stringify(job), { mode: 0o600 })
5376
+ fs.renameSync(target + '.tmp', target)
5377
+ }
5378
+ function loadOperation(key) {
5379
+ if (operationJobs.has(key)) {
5380
+ const job = operationJobs.get(key)
5381
+ if (Date.now() - job.createdAt <= OPERATION_TTL) return job
5382
+ operationJobs.delete(key)
5383
+ }
5384
+ try {
5385
+ const job = JSON.parse(fs.readFileSync(path.join(OPERATION_DIR, key + '.json'), 'utf8'))
5386
+ if (Date.now() - job.createdAt > OPERATION_TTL) return null
5387
+ if (job.phase === 'running') { job.phase = 'unknown'; job.error = 'gateway-restarted'; saveOperation(key, job) }
5388
+ operationJobs.set(key, job)
5389
+ return job
5390
+ } catch { return null }
5391
+ }
5392
+ function operationSnapshot(job) {
5393
+ return { id: job.id, method: job.method, phase: job.phase, createdAt: job.createdAt,
5394
+ completedAt: job.completedAt || null, ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}) }
5395
+ }
5396
+ function operationResult(body) {
5397
+ if (body.result.ok !== true) return { result: { ok: false, error: {
5398
+ code: String(body.result.error?.code || 'operation-rejected').slice(0, 120),
5399
+ message: '主机拒绝了操作,请核对会话和当前配置。'
5400
+ } } }
5401
+ const input = body.result.value || {}, value = {}
5402
+ for (const key of ['accepted', 'sessionId', 'workspaceId', 'archivedSessionIds', 'ref', 'selected', 'model', 'cleared']) {
5403
+ if (input[key] !== undefined) value[key] = input[key]
5404
+ }
5405
+ if (input.workspace) value.workspace = Object.fromEntries(['workspaceId','path','title','sessionIds'].filter(key => input.workspace[key] !== undefined).map(key => [key,input.workspace[key]]))
5406
+ return { result: { ok: true, value } }
5407
+ }
5408
+ async function executeOperation(key, job, payload) {
5409
+ const request = { type: 'client-request', rpcId: job.id, method: job.method,
5410
+ payload: job.method === 'session.prompt' ? { ...payload, requestId: job.id } : payload }
5411
+ try {
5412
+ let body
5413
+ const url = new URL('/api/' + job.method, UPSTREAM)
5414
+ if (await detectUpstreamApiFlavor() === 'modern') {
5415
+ body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
5416
+ }
5417
+ if (!body || body.__dshRemoteLegacyFallback) {
5418
+ const legacy = await forwardLegacyRpc(url, JSON.stringify(request))
5419
+ if ([404, 405, 501].includes(legacy.status)) {
5420
+ body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
5421
+ if (body?.__dshRemoteLegacyFallback) body = null
5422
+ } else if (legacy.status >= 500) throw new Error('upstream-uncertain')
5423
+ else {
5424
+ try { body = JSON.parse(legacy.raw) } catch { throw new Error('upstream-uncertain') }
5425
+ }
5426
+ }
5427
+ if (!body?.result || Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) throw new Error('upstream-uncertain')
5428
+ job.result = operationResult(body)
5429
+ job.phase = body.result.ok === true ? 'complete' : 'rejected'
5430
+ } catch {
5431
+ job.phase = 'unknown'
5432
+ job.error = 'result-unconfirmed'
5433
+ }
5434
+ job.completedAt = Date.now()
5435
+ try { saveOperation(key, job) } catch {
5436
+ // The durable intent remains running and becomes unknown after restart.
5437
+ // Do not return a success that could not be durably recorded.
5438
+ job.phase = 'unknown'; delete job.result; job.error = 'receipt-save-failed'
5439
+ }
5440
+ }
5441
+ async function serveOperations(req, res, url) {
5442
+ cors(res, req)
5443
+ const reply = (status, value) => sendHttpBody(res, status, {
5444
+ 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store'
5445
+ }, JSON.stringify(value), true)
5446
+ if (req.method === 'OPTIONS') return reply(204, {})
5447
+ if (!['GET', 'POST'].includes(req.method)) return reply(405, { error: 'method-not-allowed' })
5448
+ if (!controlAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
5449
+ touchDevice(req)
5450
+ const id = String(url.searchParams.get('id') || '')
5451
+ if (!/^[A-Za-z0-9_-]{16,80}$/.test(id)) return reply(400, { error: 'bad-operation-id' })
5452
+ // Credentials and upstream participate in the scope. An address alias is not
5453
+ // automatically trusted as the same logical host, and device keys cannot read
5454
+ // the shared token's operation results.
5455
+ const key = operationHash(UPSTREAM.origin + '\0' + String(tokenOf(req, url) || '') + '\0' + id)
5456
+ let old = loadOperation(key)
5457
+ if (req.method === 'GET') return old ? reply(200, operationSnapshot(old)) : reply(404, { error: 'operation-not-found' })
5458
+ let body
5459
+ try { body = JSON.parse(await readApiRequest(req)) } catch { return reply(400, { error: 'bad-operation' }) }
5460
+ if (!OPERATION_METHODS.has(body?.method) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) {
5461
+ return reply(400, { error: 'unsupported-operation' })
5462
+ }
5463
+ const fingerprint = operationHash(operationJson({ method: body.method, payload: body.payload }))
5464
+ old = loadOperation(key) // The request body yielded; another POST may have won.
5465
+ if (old) {
5466
+ if (old.fingerprint !== fingerprint) return reply(409, { error: 'operation-conflict' })
5467
+ return reply(old.phase === 'running' ? 202 : 200, operationSnapshot(old))
5468
+ }
5469
+ // Bounded receipts. Never evict an uncertain intent merely to allow replay.
5470
+ try {
5471
+ fs.mkdirSync(OPERATION_DIR, { recursive: true, mode: 0o700 })
5472
+ for (const name of fs.readdirSync(OPERATION_DIR)) {
5473
+ if (!/^[a-f0-9]{64}\.json$/.test(name)) continue
5474
+ const target = path.join(OPERATION_DIR, name)
5475
+ if (Date.now() - fs.statSync(target).mtimeMs > OPERATION_TTL) {
5476
+ fs.unlinkSync(target); operationJobs.delete(name.slice(0, -5))
5477
+ }
5478
+ }
5479
+ if (fs.readdirSync(OPERATION_DIR).filter(n => n.endsWith('.json')).length >= 1000) return reply(429, { error: 'operation-capacity' })
5480
+ } catch { return reply(503, { error: 'receipt-unavailable' }) }
5481
+ const job = { id, method: body.method, fingerprint, phase: 'running', createdAt: Date.now() }
5482
+ try { saveOperation(key, job) } catch { return reply(503, { error: 'receipt-unavailable' }) }
5483
+ operationJobs.set(key, job)
5484
+ // Reply before the upstream completes. A dropped HTTP response never cancels
5485
+ // or starts a second operation. The client only retries GET status requests.
5486
+ reply(202, operationSnapshot(job))
5487
+ void executeOperation(key, job, body.payload)
5488
+ }
5489
+
4803
5490
  async function proxyLegacyRpcWithModernFallback(req, res, url) {
4804
5491
  const raw = await readApiRequest(req)
4805
5492
  const legacy = await forwardLegacyRpc(url, raw)
@@ -4933,7 +5620,9 @@ async function proxyLegacyApi(req, res, url) {
4933
5620
  upstreamRes.pipe(res)
4934
5621
  })
4935
5622
 
4936
- upstreamReq.setTimeout(UPSTREAM_REQUEST_TIMEOUT_MS, () => {
5623
+ const requestTimeout = ['/api/session.export', '/remote/api/command'].includes(url.pathname)
5624
+ ? Math.max(UPSTREAM_REQUEST_TIMEOUT_MS, 130000) : UPSTREAM_REQUEST_TIMEOUT_MS
5625
+ upstreamReq.setTimeout(requestTimeout, () => {
4937
5626
  upstreamReq.destroy(new Error('upstream request timeout'))
4938
5627
  })
4939
5628
  upstreamReq.on('error', (err) => {
@@ -5088,6 +5777,7 @@ function lanAddresses() {
5088
5777
  const server = http.createServer(async (req, res) => {
5089
5778
  try {
5090
5779
  const url = new URL(req.url, 'http://dsh-remote.local')
5780
+ if (url.pathname === '/relay') return await serveRelaySettings(req, res, url)
5091
5781
  if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)
5092
5782
  if (url.pathname === '/workbench' || url.pathname.startsWith('/workbench/')) return serveWorkbench(req, res, url)
5093
5783
  if (url.pathname === '/diagnostics') return serveDiagnostics(req, res, url)
@@ -5104,6 +5794,7 @@ const server = http.createServer(async (req, res) => {
5104
5794
  if (url.pathname.startsWith('/admin/api')) return await serveAdminApi(req, res, url)
5105
5795
  if (url.pathname.startsWith('/stats')) return serveStats(req, res, url)
5106
5796
  if (url.pathname === '/api/ws-ticket') return serveWsTicket(req, res, url)
5797
+ if (url.pathname === '/api/operations') return await serveOperations(req, res, url)
5107
5798
  if (url.pathname === '/api/events.poll') return serveEventPoll(req, res, url)
5108
5799
  if (url.pathname.startsWith('/remote/')) return proxyApi(req, res, url)
5109
5800
  if (url.pathname.startsWith('/api/')) return proxyApi(req, res, url)
@@ -5326,7 +6017,11 @@ function acceptCollectorClient(req, socket, head, kind, device) {
5326
6017
  })
5327
6018
  for (const raw of collectorReplay[kind].values()) {
5328
6019
  if (socket.destroyed || !socket.writable) break
5329
- try { socket.write(encodeWsText(raw)) } catch { break }
6020
+ try {
6021
+ const frame=encodeWsText(raw)
6022
+ if(socket.writableLength+frame.length>WS_CLIENT_BUFFER_MAX){socket.destroy();break}
6023
+ socket.write(frame)
6024
+ } catch { break }
5330
6025
  }
5331
6026
  const stopHeartbeat = startWsClientHeartbeat(socket, () => socket.destroy())
5332
6027
  const release = () => {
@@ -5490,6 +6185,7 @@ server.on('clientError', (err, socket) => {
5490
6185
  })
5491
6186
 
5492
6187
  server.listen(PORT, HOST, () => {
6188
+ relayHost.startSaved()
5493
6189
  void refreshHealthProbe()
5494
6190
  void dshControlDescription()
5495
6191
  const healthRefresh = setInterval(() => { void refreshHealthProbe(true); void dshControlDescription(true) }, 5000)