dsh-remote-plugin 0.7.6 → 0.8.0-rc.3

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() }
@@ -1923,7 +2437,7 @@ function updateModernSessions(items) {
1923
2437
  if (!item?.sessionId) continue
1924
2438
  modernState.sessions.set(item.sessionId, item)
1925
2439
  const cursor = Number(item.projections?.asOfSeq)
1926
- if (Number.isSafeInteger(cursor) && cursor >= -1) modernState.sessionCursors.set(item.sessionId, cursor)
2440
+ if (item.projections?.kind !== 'cached' && Number.isSafeInteger(cursor) && cursor >= -1) modernState.sessionCursors.set(item.sessionId, cursor)
1927
2441
  }
1928
2442
  }
1929
2443
 
@@ -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
@@ -1989,13 +2503,26 @@ async function translateModernRpc(method, payload, rpcId) {
1989
2503
  await refreshModernSessions()
1990
2504
  summary = modernState.sessions.get(payload.sessionId)
1991
2505
  }
1992
- const throughSeq = modernState.sessionCursors.get(payload.sessionId) ?? Number(summary?.projections?.asOfSeq)
2506
+ if (summary?.formatStatus === 'migration-required') return legacyEnvelope(rpcId, modernError('Open the source session in DSH to complete migration, then refresh.', 'session/migration-required', { sessionId: payload.sessionId }))
2507
+ const isChild = !!payload.parentSessionId && typeof payload.subagentMode === 'string'
2508
+ let throughSeq = modernState.sessionCursors.get(payload.sessionId) ?? Number(summary?.projections?.asOfSeq)
2509
+ if (isChild || summary?.projections?.kind === 'cached') {
2510
+ // Cached storage watermarks are not connected stream sequence numbers.
2511
+ // Child logs also need a fresh durable cursor and Host address validation.
2512
+ const projection = await callUpstreamRemote('session/projections', { request: { sessionId: payload.sessionId } }, rpcId)
2513
+ if (!projection.body?.result?.ok) return projection.body || legacyEnvelope(rpcId, modernError('DSH history cursor unavailable'))
2514
+ if (projection.body.result.value?.kind === 'migration-required') return legacyEnvelope(rpcId, modernError('Open the source session in DSH to complete migration, then refresh.', 'session/migration-required', { sessionId: payload.sessionId }))
2515
+ throughSeq = projection.body.result.value?.asOfSeq
2516
+ if (projection.body.result.value) summary = { ...summary, projections: projection.body.result.value }
2517
+ }
1993
2518
  if (!Number.isSafeInteger(throughSeq) || throughSeq < -1) {
1994
2519
  return legacyEnvelope(rpcId, modernError('DSH did not expose a history cursor for this session', 'session-not-found'))
1995
2520
  }
1996
2521
  endpoint = 'session/page'
1997
2522
  args = { request: {
1998
- address: { kind: 'session', sessionId: payload.sessionId },
2523
+ address: isChild
2524
+ ? { kind: 'subagent', parentSessionId: payload.parentSessionId, childSessionId: payload.sessionId, mode: ['one-shot', 'continuable'].includes(payload.subagentMode) ? payload.subagentMode : 'unknown' }
2525
+ : { kind: 'session', sessionId: payload.sessionId },
1999
2526
  throughSeq,
2000
2527
  ...(payload.beforeSeq === undefined ? {} : { beforeSeq: payload.beforeSeq }),
2001
2528
  ...(payload.maxMessages === undefined ? {} : { maxMessages: payload.maxMessages }),
@@ -2090,11 +2617,13 @@ async function translateModernRpc(method, payload, rpcId) {
2090
2617
  }
2091
2618
 
2092
2619
  let response = await callUpstreamRemote(endpoint, args, rpcId)
2620
+ if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (!response.body?.result && ![404,405,501].includes(response.status)))) throw new Error('upstream-uncertain')
2093
2621
  if (method === 'session.prompt' && imageAdmissionRejected(response.body)) {
2094
2622
  try {
2095
2623
  const bridged = await bridgeVisionPrompt(args.request)
2096
2624
  if (bridged) response = await callUpstreamRemote(endpoint, { ...args, request: bridged }, rpcId)
2097
2625
  } catch (error) {
2626
+ if (strictReceipt) throw error
2098
2627
  return legacyEnvelope(rpcId, modernError(error.message, 'image-vision-failed'))
2099
2628
  }
2100
2629
  }
@@ -2104,14 +2633,16 @@ async function translateModernRpc(method, payload, rpcId) {
2104
2633
  const parent = await callUpstreamRemote('session/projections', { request: { sessionId: payload.parentSessionId } }, rpcId)
2105
2634
  if (modernResponseNeedsLegacyFallback(parent)) return legacyFallback('generated subagent catalog unavailable')
2106
2635
  if (!parent.body?.result?.ok) return parent.body || legacyEnvelope(rpcId, modernError('DSH subagent catalog read failed'))
2636
+ if (parent.body.result.value?.kind === 'migration-required') return legacyEnvelope(rpcId, modernError('Open the source session in DSH to complete migration, then refresh.', 'session/migration-required', { sessionId: payload.parentSessionId }))
2107
2637
  const catalog = parent.body.result.value?.values?.subagentCatalog
2108
2638
  if (!Array.isArray(catalog)) return legacyEnvelope(rpcId, modernError('DSH did not expose a subagent catalog projection', 'subagent/projections-unavailable'))
2109
2639
  await refreshModernSessions()
2110
2640
  const entries = await Promise.all(catalog.map(async child => {
2111
- if (!['one-shot', 'continuable'].includes(child.mode)) return { kind: 'diagnostic', id: child.id, reason: 'unsupported' }
2641
+ if (!['one-shot', 'continuable'].includes(child.mode)) return { kind: 'diagnostic', id: child.id, ...(child.label === undefined ? {} : { label: child.label }), reason: child.mode === 'external' ? 'external' : 'unsupported' }
2112
2642
  try {
2113
2643
  const read = await callUpstreamRemote('session/projections', { request: { sessionId: child.id } })
2114
2644
  if (!read.body?.result?.ok || !read.body.result.value) return { kind: 'diagnostic', id: child.id, reason: 'unavailable' }
2645
+ if (read.body.result.value.kind === 'migration-required') return { kind: 'diagnostic', id: child.id, ...(child.label === undefined ? {} : { label: child.label }), reason: 'migration-required' }
2115
2646
  const values = read.body.result.value.values
2116
2647
  const identity = values?.subagent
2117
2648
  if (!identity || identity.mode !== child.mode) return { kind: 'diagnostic', id: child.id, reason: 'corrupt' }
@@ -2123,6 +2654,7 @@ async function translateModernRpc(method, payload, rpcId) {
2123
2654
  }))
2124
2655
  return legacyEnvelope(rpcId, { ok: true, value: { entries, parentAvailable: !!modernState.sessions.get(payload.parentSessionId)?.agentAvailable } })
2125
2656
  }
2657
+ if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (!response.body?.result && ![404,405,501].includes(response.status)))) throw new Error('upstream-uncertain')
2126
2658
  if (modernResponseNeedsLegacyFallback(response)) return legacyFallback(`generated RPC ${endpoint} unavailable`)
2127
2659
  if (!response.body?.result?.ok) {
2128
2660
  recordCompatibility('generated-rpc-error', { method, status: response.status, detail: remoteFailureKind(response) })
@@ -2195,6 +2727,13 @@ function broadcastCollectorFrame(kind, raw) {
2195
2727
  collectorClients[kind].delete(socket)
2196
2728
  continue
2197
2729
  }
2730
+ // A slow phone must not retain an unbounded queue on the host. Reconnection
2731
+ // restores the baseline/history; committed events are never selectively dropped.
2732
+ if (socket.writableLength + frame.length > WS_CLIENT_BUFFER_MAX) {
2733
+ collectorClients[kind].delete(socket)
2734
+ socket.destroy()
2735
+ continue
2736
+ }
2198
2737
  try { socket.write(frame) } catch { try { socket.destroy() } catch {} }
2199
2738
  }
2200
2739
  state.clients = collectorClients[kind].size
@@ -2213,12 +2752,17 @@ function pushEvent(kind, full, raw = JSON.stringify(full)) {
2213
2752
  flushEventPollWaiters(kind)
2214
2753
  }
2215
2754
 
2216
- function eventPollPayload(kind, since, waitSupported = false) {
2755
+ function eventPollPayload(kind, since, waitSupported = false, epoch = '') {
2217
2756
  const buf = eventBuffers[kind]
2218
2757
  const events = buf.filter(r => r.seq > since)
2219
2758
  const latestSeq = buf.length ? buf[buf.length - 1].seq : 0
2220
2759
  const truncated = buf.length > 0 && since < buf[0].seq - 1
2221
- return { ok: true, kind, since, latestSeq, truncated, waitSupported, events }
2760
+ const reset = !!epoch && epoch !== EVENT_STREAM_EPOCH || latestSeq < since || truncated
2761
+ const baseline = since === 0 || reset ? [...collectorReplay[kind].values()].map(raw => {
2762
+ try { return JSON.parse(raw) } catch { return null }
2763
+ }).filter(Boolean) : []
2764
+ return { ok: true, kind, epoch: EVENT_STREAM_EPOCH, since, latestSeq, truncated, reset, waitSupported,
2765
+ baseline, events: reset ? buf.slice() : events }
2222
2766
  }
2223
2767
 
2224
2768
  function sendEventPollResponse(waiter, payload) {
@@ -2233,13 +2777,13 @@ function sendEventPollResponse(waiter, payload) {
2233
2777
  function finishEventPollWaiter(waiter, send = true) {
2234
2778
  if (!eventPollWaiters[waiter.kind]?.delete(waiter)) return
2235
2779
  clearTimeout(waiter.timer)
2236
- if (send) sendEventPollResponse(waiter, eventPollPayload(waiter.kind, waiter.since, true))
2780
+ if (send) sendEventPollResponse(waiter, eventPollPayload(waiter.kind, waiter.since, true, waiter.epoch))
2237
2781
  }
2238
2782
 
2239
2783
  function flushEventPollWaiters(kind) {
2240
2784
  for (const waiter of [...eventPollWaiters[kind]]) {
2241
- const payload = eventPollPayload(kind, waiter.since, true)
2242
- if (payload.events.length) finishEventPollWaiter(waiter, true)
2785
+ const payload = eventPollPayload(kind, waiter.since, true, waiter.epoch)
2786
+ if (payload.events.length || payload.reset) finishEventPollWaiter(waiter, true)
2243
2787
  }
2244
2788
  }
2245
2789
 
@@ -2308,8 +2852,9 @@ function serveEventPoll(req, res, url) {
2308
2852
  }
2309
2853
  const wait = Math.min(Math.floor(requestedWait), EVENT_POLL_WAIT_MAX)
2310
2854
  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) {
2855
+ const epoch = String(url.searchParams.get('epoch') || '').slice(0, 80)
2856
+ const payload = eventPollPayload(kind, since, waitSupported, epoch)
2857
+ if (payload.events.length || payload.reset || payload.baseline.length || wait <= 0 || EVENT_POLL_WAIT_MAX <= 0) {
2313
2858
  cors(res)
2314
2859
  sendHttpBody(res, 200, {
2315
2860
  'content-type': 'application/json; charset=utf-8',
@@ -2317,13 +2862,13 @@ function serveEventPoll(req, res, url) {
2317
2862
  }, JSON.stringify(payload), true)
2318
2863
  return
2319
2864
  }
2320
- const waiter = { req, res, kind, since, timer: null }
2865
+ const waiter = { req, res, kind, since, epoch, timer: null }
2321
2866
  eventPollWaiters[kind].add(waiter)
2322
2867
  waiter.timer = setTimeout(() => finishEventPollWaiter(waiter, true), wait)
2323
2868
  waiter.timer.unref?.()
2324
2869
  req.once('close', () => finishEventPollWaiter(waiter, false))
2325
2870
  // 事件可能刚好在首次检查和加入等待集合之间到达,加入后再检查一次避免漏唤醒。
2326
- if (eventPollPayload(kind, since, true).events.length) finishEventPollWaiter(waiter, true)
2871
+ if (eventPollPayload(kind, since, true, epoch).events.length) finishEventPollWaiter(waiter, true)
2327
2872
  }
2328
2873
 
2329
2874
  /** 网关自带上游事件采集:mux/host 各一条 WS,断线自动重连。 */
@@ -2445,7 +2990,7 @@ function openModernSessionStream(ws, sessionId) {
2445
2990
  // 直接按 session 地址 open 会被拒(session/agent-busy),错误帧还会污染事件流;
2446
2991
  // 这些会话的投影变化由 control/workspaces 基线推送覆盖,无需单独 follow。
2447
2992
  const summary = modernState.sessions.get(sessionId)
2448
- if (summary?.origin === 'subagent') return
2993
+ if (summary?.origin === 'subagent' || summary?.formatStatus === 'migration-required') return
2449
2994
  const streamId = 'session:' + sessionId
2450
2995
  ws.send(JSON.stringify({
2451
2996
  type: 'open', streamId, endpoint: 'session/follow',
@@ -3228,7 +3773,7 @@ function serveStatic(req, res, url) {
3228
3773
  return
3229
3774
  }
3230
3775
  if (pathname === '/') pathname = '/index.html'
3231
- if (pathname === '/admin') pathname = '/admin.html'
3776
+ if (pathname === '/admin' || pathname === '/admin/') pathname = '/admin.html'
3232
3777
  if (pathname === '/announcements.json') {
3233
3778
  void serveAnnouncements(req, res)
3234
3779
  return
@@ -3307,6 +3852,7 @@ function upstreamReachable(cb) {
3307
3852
 
3308
3853
  async function serveAdminApi(req, res, url) {
3309
3854
  const sub = url.pathname.slice('/admin/api'.length) || '/'
3855
+ if (sub === '/relay') return serveRelaySettings(req, res, url)
3310
3856
  if (sub === '/dsh') return serveDshControl(req, res, url)
3311
3857
  if (sub === '/state' && req.method === 'GET') {
3312
3858
  if (!adminAuthorized(req, url)) {
@@ -3534,6 +4080,29 @@ async function serveAdminApi(req, res, url) {
3534
4080
  res.end(JSON.stringify({ error: 'not-found' }))
3535
4081
  }
3536
4082
 
4083
+ async function serveRelaySettings(req, res, url) {
4084
+ cors(res)
4085
+ const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
4086
+ if (req.method === 'OPTIONS') { res.writeHead(204); return res.end() }
4087
+ if (!['GET', 'POST'].includes(req.method)) { res.setHeader('allow', 'GET, POST, OPTIONS'); return reply(405, { error: 'METHOD_NOT_ALLOWED' }) }
4088
+ const canManage = adminAuthorized(req, url)
4089
+ if (!canManage && !authorized(req, url)) return reply(401, { error: 'unauthorized' })
4090
+ if (req.method === 'GET') return reply(200, { ...relayHost.status(), canManage })
4091
+ if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
4092
+ try {
4093
+ const chunks = []; let size = 0
4094
+ for await (const chunk of req) { size += chunk.length; if (size > 4096) return reply(413, { error: 'BODY_TOO_LARGE' }); chunks.push(chunk) }
4095
+ let value
4096
+ try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { return reply(400, { error: 'INVALID_JSON' }) }
4097
+ if (!value || Object.keys(value).some(key => !['action', 'key'].includes(key))) return reply(400, { error: 'INVALID_RELAY_ACTION' })
4098
+ const result = await relayHost.change(value.action, value.key)
4099
+ return reply(200, { ...result, canManage: true })
4100
+ } catch (error) {
4101
+ 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'])
4102
+ return reply(error.status || 503, { error: known.has(error.code) ? error.code : 'RELAY_OPERATION_FAILED' })
4103
+ }
4104
+ }
4105
+
3537
4106
  // ---------- /fs 文件传输: 实现 ----------
3538
4107
  function fsJson(res, status, body, extraHeaders = {}) {
3539
4108
  cors(res)
@@ -4800,6 +5369,139 @@ function sendBufferedUpstreamResponse(res, response) {
4800
5369
  }, response.raw || '', compressibleRpc(res.req))
4801
5370
  }
4802
5371
 
5372
+ // A durable receipt records intent before forwarding. Only a hash of the
5373
+ // payload is stored. A crash/timeout is UNKNOWN, never permission to replay a
5374
+ // potentially committed upstream write. Old DSH needs no invented RPC support.
5375
+ const OPERATION_METHODS = new Set(['session.create', 'session.prompt', 'session.updateQueue',
5376
+ 'session.selectModel', 'session.rename', 'session.cancel', 'workspace.create',
5377
+ 'workspace.archiveSession', 'goal.edit', 'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear'])
5378
+ const OPERATION_DIR = path.join(path.dirname(TOKEN_FILE), 'operations')
5379
+ const OPERATION_TTL = 24 * 60 * 60 * 1000
5380
+ const operationJobs = new Map()
5381
+ function operationHash(value) { return crypto.createHash('sha256').update(value).digest('hex') }
5382
+ function operationJson(value) {
5383
+ if (Array.isArray(value)) return '[' + value.map(operationJson).join(',') + ']'
5384
+ if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(k => JSON.stringify(k) + ':' + operationJson(value[k])).join(',') + '}'
5385
+ return JSON.stringify(value)
5386
+ }
5387
+ function saveOperation(key, job) {
5388
+ fs.mkdirSync(OPERATION_DIR, { recursive: true, mode: 0o700 })
5389
+ const target = path.join(OPERATION_DIR, key + '.json')
5390
+ fs.writeFileSync(target + '.tmp', JSON.stringify(job), { mode: 0o600 })
5391
+ fs.renameSync(target + '.tmp', target)
5392
+ }
5393
+ function loadOperation(key) {
5394
+ if (operationJobs.has(key)) {
5395
+ const job = operationJobs.get(key)
5396
+ if (Date.now() - job.createdAt <= OPERATION_TTL) return job
5397
+ operationJobs.delete(key)
5398
+ }
5399
+ try {
5400
+ const job = JSON.parse(fs.readFileSync(path.join(OPERATION_DIR, key + '.json'), 'utf8'))
5401
+ if (Date.now() - job.createdAt > OPERATION_TTL) return null
5402
+ if (job.phase === 'running') { job.phase = 'unknown'; job.error = 'gateway-restarted'; saveOperation(key, job) }
5403
+ operationJobs.set(key, job)
5404
+ return job
5405
+ } catch { return null }
5406
+ }
5407
+ function operationSnapshot(job) {
5408
+ return { id: job.id, method: job.method, phase: job.phase, createdAt: job.createdAt,
5409
+ completedAt: job.completedAt || null, ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}) }
5410
+ }
5411
+ function operationResult(body) {
5412
+ if (body.result.ok !== true) return { result: { ok: false, error: {
5413
+ code: String(body.result.error?.code || 'operation-rejected').slice(0, 120),
5414
+ message: '主机拒绝了操作,请核对会话和当前配置。'
5415
+ } } }
5416
+ const input = body.result.value || {}, value = {}
5417
+ for (const key of ['accepted', 'sessionId', 'workspaceId', 'archivedSessionIds', 'ref', 'selected', 'model', 'cleared']) {
5418
+ if (input[key] !== undefined) value[key] = input[key]
5419
+ }
5420
+ if (input.workspace) value.workspace = Object.fromEntries(['workspaceId','path','title','sessionIds'].filter(key => input.workspace[key] !== undefined).map(key => [key,input.workspace[key]]))
5421
+ return { result: { ok: true, value } }
5422
+ }
5423
+ async function executeOperation(key, job, payload) {
5424
+ const request = { type: 'client-request', rpcId: job.id, method: job.method,
5425
+ payload: job.method === 'session.prompt' ? { ...payload, requestId: job.id } : payload }
5426
+ try {
5427
+ let body
5428
+ const url = new URL('/api/' + job.method, UPSTREAM)
5429
+ if (await detectUpstreamApiFlavor() === 'modern') {
5430
+ body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
5431
+ }
5432
+ if (!body || body.__dshRemoteLegacyFallback) {
5433
+ const legacy = await forwardLegacyRpc(url, JSON.stringify(request))
5434
+ if ([404, 405, 501].includes(legacy.status)) {
5435
+ body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
5436
+ if (body?.__dshRemoteLegacyFallback) body = null
5437
+ } else if (legacy.status >= 500) throw new Error('upstream-uncertain')
5438
+ else {
5439
+ try { body = JSON.parse(legacy.raw) } catch { throw new Error('upstream-uncertain') }
5440
+ }
5441
+ }
5442
+ if (!body?.result || Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) throw new Error('upstream-uncertain')
5443
+ job.result = operationResult(body)
5444
+ job.phase = body.result.ok === true ? 'complete' : 'rejected'
5445
+ } catch {
5446
+ job.phase = 'unknown'
5447
+ job.error = 'result-unconfirmed'
5448
+ }
5449
+ job.completedAt = Date.now()
5450
+ try { saveOperation(key, job) } catch {
5451
+ // The durable intent remains running and becomes unknown after restart.
5452
+ // Do not return a success that could not be durably recorded.
5453
+ job.phase = 'unknown'; delete job.result; job.error = 'receipt-save-failed'
5454
+ }
5455
+ }
5456
+ async function serveOperations(req, res, url) {
5457
+ cors(res, req)
5458
+ const reply = (status, value) => sendHttpBody(res, status, {
5459
+ 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store'
5460
+ }, JSON.stringify(value), true)
5461
+ if (req.method === 'OPTIONS') return reply(204, {})
5462
+ if (!['GET', 'POST'].includes(req.method)) return reply(405, { error: 'method-not-allowed' })
5463
+ if (!controlAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
5464
+ touchDevice(req)
5465
+ const id = String(url.searchParams.get('id') || '')
5466
+ if (!/^[A-Za-z0-9_-]{16,80}$/.test(id)) return reply(400, { error: 'bad-operation-id' })
5467
+ // Credentials and upstream participate in the scope. An address alias is not
5468
+ // automatically trusted as the same logical host, and device keys cannot read
5469
+ // the shared token's operation results.
5470
+ const key = operationHash(UPSTREAM.origin + '\0' + String(tokenOf(req, url) || '') + '\0' + id)
5471
+ let old = loadOperation(key)
5472
+ if (req.method === 'GET') return old ? reply(200, operationSnapshot(old)) : reply(404, { error: 'operation-not-found' })
5473
+ let body
5474
+ try { body = JSON.parse(await readApiRequest(req)) } catch { return reply(400, { error: 'bad-operation' }) }
5475
+ if (!OPERATION_METHODS.has(body?.method) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) {
5476
+ return reply(400, { error: 'unsupported-operation' })
5477
+ }
5478
+ const fingerprint = operationHash(operationJson({ method: body.method, payload: body.payload }))
5479
+ old = loadOperation(key) // The request body yielded; another POST may have won.
5480
+ if (old) {
5481
+ if (old.fingerprint !== fingerprint) return reply(409, { error: 'operation-conflict' })
5482
+ return reply(old.phase === 'running' ? 202 : 200, operationSnapshot(old))
5483
+ }
5484
+ // Bounded receipts. Never evict an uncertain intent merely to allow replay.
5485
+ try {
5486
+ fs.mkdirSync(OPERATION_DIR, { recursive: true, mode: 0o700 })
5487
+ for (const name of fs.readdirSync(OPERATION_DIR)) {
5488
+ if (!/^[a-f0-9]{64}\.json$/.test(name)) continue
5489
+ const target = path.join(OPERATION_DIR, name)
5490
+ if (Date.now() - fs.statSync(target).mtimeMs > OPERATION_TTL) {
5491
+ fs.unlinkSync(target); operationJobs.delete(name.slice(0, -5))
5492
+ }
5493
+ }
5494
+ if (fs.readdirSync(OPERATION_DIR).filter(n => n.endsWith('.json')).length >= 1000) return reply(429, { error: 'operation-capacity' })
5495
+ } catch { return reply(503, { error: 'receipt-unavailable' }) }
5496
+ const job = { id, method: body.method, fingerprint, phase: 'running', createdAt: Date.now() }
5497
+ try { saveOperation(key, job) } catch { return reply(503, { error: 'receipt-unavailable' }) }
5498
+ operationJobs.set(key, job)
5499
+ // Reply before the upstream completes. A dropped HTTP response never cancels
5500
+ // or starts a second operation. The client only retries GET status requests.
5501
+ reply(202, operationSnapshot(job))
5502
+ void executeOperation(key, job, body.payload)
5503
+ }
5504
+
4803
5505
  async function proxyLegacyRpcWithModernFallback(req, res, url) {
4804
5506
  const raw = await readApiRequest(req)
4805
5507
  const legacy = await forwardLegacyRpc(url, raw)
@@ -4933,7 +5635,9 @@ async function proxyLegacyApi(req, res, url) {
4933
5635
  upstreamRes.pipe(res)
4934
5636
  })
4935
5637
 
4936
- upstreamReq.setTimeout(UPSTREAM_REQUEST_TIMEOUT_MS, () => {
5638
+ const requestTimeout = ['/api/session.export', '/remote/api/command'].includes(url.pathname)
5639
+ ? Math.max(UPSTREAM_REQUEST_TIMEOUT_MS, 130000) : UPSTREAM_REQUEST_TIMEOUT_MS
5640
+ upstreamReq.setTimeout(requestTimeout, () => {
4937
5641
  upstreamReq.destroy(new Error('upstream request timeout'))
4938
5642
  })
4939
5643
  upstreamReq.on('error', (err) => {
@@ -5088,6 +5792,7 @@ function lanAddresses() {
5088
5792
  const server = http.createServer(async (req, res) => {
5089
5793
  try {
5090
5794
  const url = new URL(req.url, 'http://dsh-remote.local')
5795
+ if (url.pathname === '/relay') return await serveRelaySettings(req, res, url)
5091
5796
  if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)
5092
5797
  if (url.pathname === '/workbench' || url.pathname.startsWith('/workbench/')) return serveWorkbench(req, res, url)
5093
5798
  if (url.pathname === '/diagnostics') return serveDiagnostics(req, res, url)
@@ -5104,6 +5809,7 @@ const server = http.createServer(async (req, res) => {
5104
5809
  if (url.pathname.startsWith('/admin/api')) return await serveAdminApi(req, res, url)
5105
5810
  if (url.pathname.startsWith('/stats')) return serveStats(req, res, url)
5106
5811
  if (url.pathname === '/api/ws-ticket') return serveWsTicket(req, res, url)
5812
+ if (url.pathname === '/api/operations') return await serveOperations(req, res, url)
5107
5813
  if (url.pathname === '/api/events.poll') return serveEventPoll(req, res, url)
5108
5814
  if (url.pathname.startsWith('/remote/')) return proxyApi(req, res, url)
5109
5815
  if (url.pathname.startsWith('/api/')) return proxyApi(req, res, url)
@@ -5326,7 +6032,11 @@ function acceptCollectorClient(req, socket, head, kind, device) {
5326
6032
  })
5327
6033
  for (const raw of collectorReplay[kind].values()) {
5328
6034
  if (socket.destroyed || !socket.writable) break
5329
- try { socket.write(encodeWsText(raw)) } catch { break }
6035
+ try {
6036
+ const frame=encodeWsText(raw)
6037
+ if(socket.writableLength+frame.length>WS_CLIENT_BUFFER_MAX){socket.destroy();break}
6038
+ socket.write(frame)
6039
+ } catch { break }
5330
6040
  }
5331
6041
  const stopHeartbeat = startWsClientHeartbeat(socket, () => socket.destroy())
5332
6042
  const release = () => {
@@ -5490,6 +6200,7 @@ server.on('clientError', (err, socket) => {
5490
6200
  })
5491
6201
 
5492
6202
  server.listen(PORT, HOST, () => {
6203
+ relayHost.startSaved()
5493
6204
  void refreshHealthProbe()
5494
6205
  void dshControlDescription()
5495
6206
  const healthRefresh = setInterval(() => { void refreshHealthProbe(true); void dshControlDescription(true) }, 5000)