dsh-remote-plugin 0.8.8 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +16 -5
- package/README.md +15 -4
- package/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +583 -84
- package/index.mjs +1 -0
- package/package.json +8 -3
- package/public/activity.js +97 -10
- package/public/admin.html +34 -33
- package/public/admin.js +10 -2
- package/public/announcements.json +36 -0
- package/public/app.js +1564 -226
- package/public/bc-integration.css +81 -0
- package/public/build.json +2 -2
- package/public/composer-tools.css +184 -0
- package/public/composer-tools.js +888 -0
- package/public/desktop/desktop.html +94 -73
- package/public/desktop/desktop.js +726 -83
- package/public/e2ee-config.js +5 -0
- package/public/e2ee-transport.js +23 -4
- package/public/file-inbox.js +77 -18
- package/public/genui.css +10 -0
- package/public/genui.js +22 -4
- package/public/history.js +114 -17
- package/public/host-queue.js +232 -0
- package/public/host-schedule.js +301 -0
- package/public/host-state.css +19 -0
- package/public/index.html +332 -140
- package/public/md.js +21 -1
- package/public/network.js +33 -1
- package/public/onboarding.js +3 -3
- package/public/operations.js +4 -3
- package/public/plan-review.css +297 -0
- package/public/plan-review.js +642 -0
- package/public/plugin.html +29 -28
- package/public/relay-autopair.js +30 -10
- package/public/relay-devices.js +7 -3
- package/public/relay-settings.css +11 -0
- package/public/relay-settings.js +372 -30
- package/public/session-cache.js +85 -0
- package/public/session-management.css +61 -0
- package/public/session-management.js +742 -0
- package/public/session-search.css +137 -0
- package/public/session-search.js +977 -0
- package/public/skins/blue-fish/preview.html +3 -3
- package/public/skins/bocchi/preview.html +5 -5
- package/public/skins/kita/preview.html +6 -6
- package/public/skins/miku/SOURCES.json +10 -0
- package/public/skins/miku/chibi.png +0 -0
- package/public/skins/miku/preview.html +33 -0
- package/public/skins/miku/skin.css +82 -0
- package/public/skins/nijika/preview.html +6 -6
- package/public/skins/penguin/preview.html +3 -3
- package/public/skins/ryo/preview.html +6 -6
- package/public/slash-suggestions.js +15 -3
- package/public/sponsor-entry.js +11 -3
- package/public/styles.css +141 -21
- package/public/subagents.css +5 -0
- package/public/subagents.js +52 -0
- package/public/theme-vars.css +65 -1
- package/public/theme.js +4 -3
- package/public/turn-diff.css +323 -0
- package/public/turn-diff.js +778 -0
- package/public/update.json +12 -12
- package/public/version.json +1 -1
- package/public/workflow.css +305 -34
- package/public/workflow.js +141 -41
package/gateway.cjs
CHANGED
|
@@ -65,22 +65,51 @@ function publicKey(value) {
|
|
|
65
65
|
}
|
|
66
66
|
const digest = value => crypto.createHash('sha256').update(value).digest('hex')
|
|
67
67
|
const live = (grant, now = Date.now()) => grant && !grant.revokedAt && grant.expiresAt > now
|
|
68
|
+
const isEarlyTest = grant => grant?.displayPlan === 'early-test' && !grant.plan
|
|
69
|
+
const RENEW_WINDOW = 7 * 86400000
|
|
70
|
+
const SPONSOR_ORDER_WINDOW = 3 * 86400000
|
|
71
|
+
const SPONSOR_PACK_BYTES = 5_000_000_000
|
|
72
|
+
const renewalWindow = (state, grant) => state.sponsorship?.serviceOrders && grant.sponsorPeriods ? SPONSOR_ORDER_WINDOW : RENEW_WINDOW
|
|
73
|
+
const reserved = (row, now) => row.status === 'submitted' || row.status === 'draft' && row.reservedUntil > now
|
|
74
|
+
function holdsSlot(grant, now, window = RENEW_WINDOW) {
|
|
75
|
+
if (grant.revokedAt) return false
|
|
76
|
+
if (live(grant, now)) return true
|
|
77
|
+
const deadline = grant.expiresAt + window
|
|
78
|
+
return grant.plan === 'sponsor-basic' && (window === RENEW_WINDOW ? now <= deadline : now < deadline)
|
|
79
|
+
}
|
|
80
|
+
function currentGrant(grant, now) {
|
|
81
|
+
if (!grant?.sponsorPeriods) return grant
|
|
82
|
+
const period = grant.sponsorPeriods.findLast(period => period.startsAt <= now)
|
|
83
|
+
return { ...grant, periodStartsAt: period?.startsAt, expiresAt: period?.expiresAt ?? 0,
|
|
84
|
+
serviceExpiresAt: grant.expiresAt, packIds: period?.packIds || [] }
|
|
85
|
+
}
|
|
86
|
+
function occupiedSlots(state, now) {
|
|
87
|
+
const occupied = new Set(state.grants.filter(grant => holdsSlot(grant, now, renewalWindow(state, grant))).map(grant => grant.id))
|
|
88
|
+
let newDrafts = 0
|
|
89
|
+
for (const row of state.sponsorship?.applications || []) {
|
|
90
|
+
if (!reserved(row, now) || row.order?.kind === 'packs') continue
|
|
91
|
+
const grantId = row.orderGrantId || row.renewalGrantId
|
|
92
|
+
if (grantId) occupied.add(grantId)
|
|
93
|
+
else newDrafts++
|
|
94
|
+
}
|
|
95
|
+
return occupied.size + newDrafts
|
|
96
|
+
}
|
|
68
97
|
const signingText = (nonce, id, role, session = '', e2ee) => Buffer.from(JSON.stringify(
|
|
69
98
|
e2ee ? ['dsh-relay-e2ee-v1', nonce, id, role, session, e2ee.routeTokenHash, e2ee.policy, ...(e2ee.allowPlain === undefined ? [] : [e2ee.allowPlain]), ...(e2ee.devices === undefined ? [] : [e2ee.devices.map(d => [d.id, d.routeTokenHash, d.expiresAt])])] : ['dsh-relay-v1', nonce, id, role, session]))
|
|
70
|
-
function issueInState(state, { label = '', domain, expiresAt, plan } = {}) {
|
|
71
|
-
if (state.grants.filter(g => live(g)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
|
|
99
|
+
function issueInState(state, { label = '', domain, expiresAt, plan, now = Date.now() } = {}) {
|
|
100
|
+
if (state.grants.filter(g => live(g, now)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
|
|
72
101
|
const id = crypto.randomBytes(8).toString('hex')
|
|
73
102
|
const assigned = hostname(domain || `r-${id}.${state.baseDomain}`)
|
|
74
103
|
if (!assigned.endsWith('.' + state.baseDomain) || assigned === new URL(state.origin).hostname || assigned === state.tunnelHost) throw fault('INVALID_TENANT_DOMAIN')
|
|
75
104
|
if (state.grants.some(g => g.domain === assigned)) throw fault('DOMAIN_ALREADY_ASSIGNED', 409)
|
|
76
105
|
const code = `dsrp_${id}.${crypto.randomBytes(32).toString('base64url')}`
|
|
77
|
-
const grant = { id, label: String(label).slice(0, 80), domain: assigned, expiresAt, createdAt:
|
|
106
|
+
const grant = { id, label: String(label).slice(0, 80), domain: assigned, expiresAt, createdAt: now, codeHash: digest(code), publicKey: null, revokedAt: null, ...(plan ? { plan } : {}) }
|
|
78
107
|
state.grants.push(grant)
|
|
79
108
|
return { code, grant }
|
|
80
109
|
}
|
|
81
110
|
|
|
82
111
|
class Registry {
|
|
83
|
-
constructor(file) { this.file = path.resolve(file) }
|
|
112
|
+
constructor(file, now = Date.now) { this.file = path.resolve(file); this.now = now }
|
|
84
113
|
read() {
|
|
85
114
|
const state = JSON.parse(fs.readFileSync(this.file, 'utf8'))
|
|
86
115
|
if (state.version !== 1 || !Array.isArray(state.grants)) throw fault('INVALID_REGISTRY', 503)
|
|
@@ -119,13 +148,15 @@ class Registry {
|
|
|
119
148
|
const expires = Number(expiresAt)
|
|
120
149
|
if (!Number.isFinite(expires) || expires <= Date.now() || expires > Date.now() + 90 * 86400000) throw fault('INVALID_EXPIRY')
|
|
121
150
|
return this.change(state => {
|
|
122
|
-
|
|
123
|
-
if (state.grants.filter(g => live(g)).length + reserved >= state.maxUsers) throw fault('PILOT_FULL', 409)
|
|
151
|
+
if (occupiedSlots(state, Date.now()) >= state.maxUsers) throw fault('PILOT_FULL', 409)
|
|
124
152
|
const { code, grant } = issueInState(state, { label, domain, expiresAt: expires })
|
|
125
153
|
return { code, grant: this.view(grant) }
|
|
126
154
|
})
|
|
127
155
|
}
|
|
128
|
-
view(
|
|
156
|
+
view(grant) {
|
|
157
|
+
const now = this.now(), g = currentGrant(grant, now)
|
|
158
|
+
return { id: g.id, label: g.label, domain: g.domain, expiresAt: g.expiresAt, state: g.revokedAt ? 'revoked' : !live(g, now) ? 'expired' : g.publicKey ? 'bound' : 'invited', fingerprint: g.publicKey ? digest(g.publicKey) : null }
|
|
159
|
+
}
|
|
129
160
|
list() { return this.read().grants.map(g => this.view(g)) }
|
|
130
161
|
revoke(id) {
|
|
131
162
|
return this.change(state => {
|
|
@@ -136,21 +167,36 @@ class Registry {
|
|
|
136
167
|
})
|
|
137
168
|
}
|
|
138
169
|
enroll(code, key) {
|
|
139
|
-
const match = /^
|
|
170
|
+
const match = /^(dsrp|dsra)_([a-f0-9]{16})\.[A-Za-z0-9_-]{43}$/.exec(String(code || ''))
|
|
140
171
|
if (!match) throw fault('INVALID_AUTHORIZATION', 403)
|
|
141
172
|
const normalized = publicKey(key)
|
|
142
173
|
return this.change(state => {
|
|
143
|
-
const grant = state.grants.find(g => g.id === match[
|
|
144
|
-
|
|
174
|
+
const grant = state.grants.find(g => g.id === match[2])
|
|
175
|
+
const now = this.now()
|
|
176
|
+
const codeHash = digest(code)
|
|
177
|
+
const matchesHash = hash => /^[a-f0-9]{64}$/.test(hash || '') &&
|
|
178
|
+
crypto.timingSafeEqual(Buffer.from(hash, 'hex'), Buffer.from(codeHash, 'hex'))
|
|
179
|
+
const activation = match[1] === 'dsra' ? [grant?.activation, grant?.inboxActivation].find(item => matchesHash(item?.hash)) : null
|
|
180
|
+
const expected = match[1] === 'dsrp' ? grant?.codeHash : activation?.hash
|
|
181
|
+
const current = currentGrant(grant, now)
|
|
182
|
+
if (!live(current, now) || !matchesHash(expected)) throw fault('INVALID_AUTHORIZATION', 403)
|
|
183
|
+
if (activation && (activation.expiresAt <= now || activation.codeHash !== grant.codeHash)) throw fault('ACTIVATION_FILE_EXPIRED', 409)
|
|
145
184
|
if (grant.publicKey && grant.publicKey !== normalized) throw fault('HOST_ALREADY_BOUND', 409)
|
|
146
185
|
grant.publicKey = normalized
|
|
147
|
-
|
|
186
|
+
// The first bind consumes the grant for all other hosts. The same public
|
|
187
|
+
// key can recover a lost enrollment reply until the file expires.
|
|
188
|
+
const display = isEarlyTest(grant) ? { displayPlan: 'early-test' } : {}
|
|
189
|
+
const packs = current.packIds?.length || 0
|
|
190
|
+
// Older gateways use this enrollment flag to choose the signed tunnel
|
|
191
|
+
// policy. File access is instead enabled by authenticated live usage.
|
|
192
|
+
return { grantId: grant.id, domain: grant.domain, expiresAt: grant.expiresAt, publicUrl: `https://${grant.domain}`, ...display, ...(grant.plan === 'sponsor-basic' ? { quotaPeriod: 'month', monthlyLimitBytes: SPONSOR_PACK_BYTES * (1 + packs), fileTransfer: false } : { dailyLimitBytes: 5_000_000_000 }), timezone: 'Asia/Shanghai', transport: 'https-upgrade', tunnelOrigin: state.origin, tunnelHost: state.tunnelHost, tunnelPort: state.tunnelPort }
|
|
148
193
|
})
|
|
149
194
|
}
|
|
150
|
-
get(id) { return this.read().grants.find(g => g.id === id) }
|
|
195
|
+
get(id) { return currentGrant(this.read().grants.find(g => g.id === id), this.now()) }
|
|
196
|
+
byDomain(domain) { return currentGrant(this.read().grants.find(g => g.domain === domain), this.now()) }
|
|
151
197
|
}
|
|
152
198
|
|
|
153
|
-
module.exports = { Registry, fault, hostname, publicKey, digest, live, signingText, issueInState }
|
|
199
|
+
module.exports = { Registry, fault, hostname, publicKey, digest, live, currentGrant, isEarlyTest, signingText, issueInState, occupiedSlots, reserved, holdsSlot, renewalWindow, SPONSOR_ORDER_WINDOW, SPONSOR_PACK_BYTES, RENEW_WINDOW }
|
|
154
200
|
},
|
|
155
201
|
"./wire.cjs": function(require, module, exports) {
|
|
156
202
|
'use strict'
|
|
@@ -236,7 +282,7 @@ function enroll(origin, code, publicKey, ca) {
|
|
|
236
282
|
let code = 'ENROLLMENT_REJECTED'
|
|
237
283
|
try {
|
|
238
284
|
const candidate = JSON.parse(Buffer.concat(chunks).toString('utf8')).error
|
|
239
|
-
if (['INVALID_AUTHORIZATION', 'HOST_ALREADY_BOUND', 'REGISTRY_BUSY', 'TRY_LATER', 'INVALID_PUBLIC_KEY', 'INVALID_ENROLLMENT'].includes(candidate)) code = candidate
|
|
285
|
+
if (['INVALID_AUTHORIZATION', 'ACTIVATION_FILE_EXPIRED', 'HOST_ALREADY_BOUND', 'REGISTRY_BUSY', 'TRY_LATER', 'INVALID_PUBLIC_KEY', 'INVALID_ENROLLMENT'].includes(candidate)) code = candidate
|
|
240
286
|
} catch {}
|
|
241
287
|
return reject(fault(code, response.statusCode))
|
|
242
288
|
}
|
|
@@ -283,7 +329,7 @@ class RelayClient extends EventEmitter {
|
|
|
283
329
|
// waiting for a fresh host->relay handshake. DSH_REMOTE_RELAY_POOL overrides (1-6; the broker
|
|
284
330
|
// parks at most 8). Explicit poolSize from callers (and tests) still wins.
|
|
285
331
|
const configuredPool = Number.isInteger(poolSize) ? poolSize : Number(process.env.DSH_REMOTE_RELAY_POOL)
|
|
286
|
-
this.poolSize = Math.min(6, Math.max(1, Number.isInteger(configuredPool) ? configuredPool :
|
|
332
|
+
this.poolSize = Math.min(6, Math.max(1, Number.isInteger(configuredPool) ? configuredPool : 4)); this.reconnectMs = reconnectMs
|
|
287
333
|
this.context = null; this.running = false; this.timer = null; this.failures = 0; this.controlSocket = null; this.epoch = 0
|
|
288
334
|
}
|
|
289
335
|
async authenticate(role, session = '', context) {
|
|
@@ -298,7 +344,11 @@ class RelayClient extends EventEmitter {
|
|
|
298
344
|
const signature = crypto.sign(null, signingText(challenge.nonce, this.grantId, role, session, capability), this.privateKey).toString('base64url')
|
|
299
345
|
send(socket, { grantId: this.grantId, role, session, signature, ...(capability ? { e2ee: capability } : {}) })
|
|
300
346
|
const accepted = await line(socket)
|
|
301
|
-
if (accepted.type === 'rejected'
|
|
347
|
+
if (accepted.type === 'rejected') {
|
|
348
|
+
const error = fault(accepted.code || 'CONNECTION_NOT_ACCEPTED', accepted.code === 'AUTHORIZATION_INACTIVE' ? 403 : 409)
|
|
349
|
+
if (Number.isFinite(accepted.retryAfterMs)) error.retryAfterMs = Math.min(60000, Math.max(0, accepted.retryAfterMs))
|
|
350
|
+
throw error
|
|
351
|
+
}
|
|
302
352
|
if (!this.running || Date.now() >= this.expiresAt || accepted.type !== (role === 'control' ? 'accepted' : 'parked')) throw fault('CONNECTION_NOT_ACCEPTED')
|
|
303
353
|
return { socket, accepted }
|
|
304
354
|
} catch (error) { socket.destroy(); throw error }
|
|
@@ -308,6 +358,7 @@ class RelayClient extends EventEmitter {
|
|
|
308
358
|
if (!this.running) return
|
|
309
359
|
if (Date.now() >= this.expiresAt) { this.stop(); this.emit('status', 'expired'); return }
|
|
310
360
|
let context
|
|
361
|
+
let retryHint = 0
|
|
311
362
|
const epoch = this.epoch
|
|
312
363
|
try {
|
|
313
364
|
const { socket, accepted } = await this.authenticate('control')
|
|
@@ -315,18 +366,26 @@ class RelayClient extends EventEmitter {
|
|
|
315
366
|
context = { socket, session: accepted.session, sockets: new Set([socket]), pending: 0, closing: false, retryTimer: null }
|
|
316
367
|
this.context = context; this.failures = 0
|
|
317
368
|
if (this.e2ee && accepted.e2ee !== true) throw fault('E2EE_BROKER_UNSUPPORTED')
|
|
369
|
+
if (accepted.authorization) this.emit('authorization', accepted.authorization)
|
|
318
370
|
if (accepted.usage) this.emit('usage', accepted.usage)
|
|
319
371
|
this.emit('status', 'online'); this.refill(context)
|
|
320
372
|
while (this.running && !context.closing) {
|
|
321
373
|
const message = await line(socket, 65000)
|
|
322
|
-
if (message.type === 'usage') {
|
|
374
|
+
if (message.type === 'usage') {
|
|
375
|
+
if (message.authorization) this.emit('authorization', message.authorization)
|
|
376
|
+
this.emit('usage', message.usage); continue
|
|
377
|
+
}
|
|
323
378
|
if (message.type !== 'ping') throw fault('INVALID_CONTROL_MESSAGE')
|
|
379
|
+
if (message.authorization) this.emit('authorization', message.authorization)
|
|
324
380
|
if (message.usage) this.emit('usage', message.usage)
|
|
325
381
|
send(socket, { type: 'pong' })
|
|
326
382
|
}
|
|
327
383
|
} catch (error) {
|
|
328
384
|
if (error.code === 'AUTHORIZATION_INACTIVE') { this.stop(); this.emit('status', 'authorization-inactive') }
|
|
329
|
-
else if (this.running)
|
|
385
|
+
else if (this.running) {
|
|
386
|
+
this.emit('status', 'reconnecting')
|
|
387
|
+
retryHint = error.retryAfterMs || 0
|
|
388
|
+
}
|
|
330
389
|
}
|
|
331
390
|
finally {
|
|
332
391
|
if (context) this.dispose(context)
|
|
@@ -336,7 +395,8 @@ class RelayClient extends EventEmitter {
|
|
|
336
395
|
// socket. Retry quickly for the first minute so recovery does not inherit the
|
|
337
396
|
// exponential backoff of a stale registration.
|
|
338
397
|
const failures = this.failures++
|
|
339
|
-
const
|
|
398
|
+
const fast = retryHint > 0 && failures < 24 ? retryHint : 0
|
|
399
|
+
const wait = fast || Math.min(failures < 12 ? 5000 : 60000, this.reconnectMs * 2 ** Math.min(failures, 6))
|
|
340
400
|
this.timer = setTimeout(() => this.connect(), wait)
|
|
341
401
|
}
|
|
342
402
|
}
|
|
@@ -350,6 +410,7 @@ class RelayClient extends EventEmitter {
|
|
|
350
410
|
try {
|
|
351
411
|
const accepted = await this.authenticate('work', context.session, context)
|
|
352
412
|
remote = accepted.socket
|
|
413
|
+
// Older brokers park without a deadline; keep the legacy 60s wait in that case.
|
|
353
414
|
const start = await line(remote, 60000)
|
|
354
415
|
if (start.type !== 'start' || context.closing || this.context !== context) throw fault('STALE_WORK')
|
|
355
416
|
context.pending--; pending = false
|
|
@@ -720,7 +781,7 @@ module.exports = { track, contains }
|
|
|
720
781
|
const http = require('node:http')
|
|
721
782
|
const https = require('node:https')
|
|
722
783
|
const { headersOf } = require('./http-headers.cjs')
|
|
723
|
-
const { basicPolicy, basicBody, imageResponse } = require('./basic-policy.cjs')
|
|
784
|
+
const { basicPolicy, basicBody, imageResponse, relayFileRequest, rejectOverrides } = require('./basic-policy.cjs')
|
|
724
785
|
const { link } = require('./wire.cjs')
|
|
725
786
|
const { fault } = require('./registry.cjs')
|
|
726
787
|
const { FileRate } = require('./file-rate.cjs')
|
|
@@ -728,10 +789,11 @@ const { FileRate } = require('./file-rate.cjs')
|
|
|
728
789
|
// Attached only to authenticated reverse work streams, never a listening port.
|
|
729
790
|
// Access authentication remains owned by the real local gateway.
|
|
730
791
|
class E2eeEndpoint {
|
|
731
|
-
constructor({ identity, target, policy, expiresAt, devices }) {
|
|
792
|
+
constructor({ identity, target, policy, expiresAt, devices, allowFiles = () => false }) {
|
|
732
793
|
if (!['standard', 'sponsor-basic'].includes(policy) || !Number.isFinite(expiresAt)) throw fault('E2EE_POLICY_REQUIRED')
|
|
733
794
|
this.policy = policy; this.expiresAt = expiresAt; this.sockets = new Set(); this.active = 0; this.buffered = 0; this.files = 0
|
|
734
795
|
this.devices = devices
|
|
796
|
+
this.allowFiles = allowFiles
|
|
735
797
|
this.expiryTimer = setInterval(() => {
|
|
736
798
|
for (const socket of this.sockets) if (Date.now() >= this.expiresAt || socket.deviceId && !this.devices?.active(socket.deviceId)) socket.destroy()
|
|
737
799
|
}, 1000); this.expiryTimer.unref()
|
|
@@ -763,6 +825,10 @@ class E2eeEndpoint {
|
|
|
763
825
|
if (this.devices) req.socket.deviceId = this.devices.authorize(req.headers['x-dsh-relay-device'])
|
|
764
826
|
if (this.active >= 32) throw fault('HOST_BUSY', 503)
|
|
765
827
|
if (this.policy !== 'sponsor-basic') return null
|
|
828
|
+
if (!upgrade && this.allowFiles() && relayFileRequest(req)) {
|
|
829
|
+
rejectOverrides(req)
|
|
830
|
+
return 'file'
|
|
831
|
+
}
|
|
766
832
|
const mode = basicPolicy(req)
|
|
767
833
|
if (upgrade && (mode || req.method !== 'GET' || !/^\/api\/events\.(?:mux|host)(?:\?|$)/.test(req.url))) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
|
|
768
834
|
return mode
|
|
@@ -791,17 +857,17 @@ class E2eeEndpoint {
|
|
|
791
857
|
try {
|
|
792
858
|
const mode = this.check(req)
|
|
793
859
|
const pathname = new URL(req.url, 'http://relay.invalid').pathname
|
|
794
|
-
if (!mode && (pathname === '/fs' || pathname.startsWith('/fs/'))) {
|
|
860
|
+
if (mode === 'file' || !mode && (pathname === '/fs' || pathname.startsWith('/fs/'))) {
|
|
795
861
|
if (this.files >= 2) throw fault('FILE_TRANSFER_BUSY', 429)
|
|
796
862
|
this.files++; file = true
|
|
797
863
|
}
|
|
798
|
-
if (this.policy === 'sponsor-basic' && (mode || req.method === 'POST' && req.url.startsWith('/api/'))) {
|
|
864
|
+
if (this.policy === 'sponsor-basic' && !file && (mode || req.method === 'POST' && req.url.startsWith('/api/'))) {
|
|
799
865
|
if (this.buffered >= 4) throw fault('HOST_BUSY', 503)
|
|
800
866
|
this.buffered++; buffered = true
|
|
801
867
|
}
|
|
802
868
|
this.active++; counted = true
|
|
803
869
|
res.once('close', release); res.once('finish', release)
|
|
804
|
-
const body = this.policy === 'sponsor-basic' ? await basicBody(req) : null
|
|
870
|
+
const body = this.policy === 'sponsor-basic' && !file ? await basicBody(req) : null
|
|
805
871
|
if (res.destroyed || req.aborted) { release(); return }
|
|
806
872
|
request = this.request(req, false)
|
|
807
873
|
req.once('aborted', () => request.destroy())
|
|
@@ -813,7 +879,7 @@ class E2eeEndpoint {
|
|
|
813
879
|
// This is an authenticated public read. A metadata write failure must not interrupt it.
|
|
814
880
|
try { this.devices.rememberPublicAccess(req.socket.deviceId) } catch {}
|
|
815
881
|
}
|
|
816
|
-
if (mode) { void imageResponse(response, res, mode); return }
|
|
882
|
+
if (mode && !file) { void imageResponse(response, res, mode); return }
|
|
817
883
|
res.writeHead(response.statusCode, headersOf(response.headers))
|
|
818
884
|
response.on('error', () => res.destroy())
|
|
819
885
|
if (file) {
|
|
@@ -901,6 +967,19 @@ module.exports = { FileRate }
|
|
|
901
967
|
const { fault } = require('./registry.cjs')
|
|
902
968
|
const IMAGE = /^image\/(?:png|jpeg|gif|webp)$/
|
|
903
969
|
const IMAGE_MAX = 12 * 1024 * 1024
|
|
970
|
+
const ROUTING_OVERRIDES = ['x-http-method', 'x-http-method-override', 'x-method-override', 'x-original-url', 'x-rewrite-url', 'x-forwarded-uri', 'x-forwarded-prefix']
|
|
971
|
+
function rejectOverrides(req) {
|
|
972
|
+
if (ROUTING_OVERRIDES.some(name => Object.hasOwn(req.headers, name))) throw fault('RELAY_ROUTING_OVERRIDE_NOT_ALLOWED', 403)
|
|
973
|
+
}
|
|
974
|
+
const FILE_READS = new Set(['/fs/list', '/fs/file', '/fs/preview', '/fs/upload-probe', '/fs/inbox-file',
|
|
975
|
+
'/api/session-file', '/remote/api/session-file', '/api/file-inbox'])
|
|
976
|
+
const FILE_WRITES = new Set(['/fs/upload', '/fs/mkdir', '/fs/upload-control', '/api/file-inbox'])
|
|
977
|
+
function relayFileRequest(req) {
|
|
978
|
+
const route = req.url.split('?', 1)[0]
|
|
979
|
+
if (req.method === 'OPTIONS') return FILE_READS.has(route) || FILE_WRITES.has(route)
|
|
980
|
+
return (req.method === 'GET' || req.method === 'HEAD') && FILE_READS.has(route) ||
|
|
981
|
+
req.method === 'POST' && FILE_WRITES.has(route)
|
|
982
|
+
}
|
|
904
983
|
function basicPolicy(req) {
|
|
905
984
|
const url = new URL(req.url, 'http://relay.invalid')
|
|
906
985
|
let route
|
|
@@ -958,7 +1037,7 @@ async function basicBody(req) {
|
|
|
958
1037
|
if (url.pathname === '/api/operations' && /^(?:session[./](?:attachment|export)|files?[./])/.test(String(value?.method))) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
|
|
959
1038
|
return raw
|
|
960
1039
|
}
|
|
961
|
-
module.exports = { basicPolicy, imageResponse, basicBody }
|
|
1040
|
+
module.exports = { basicPolicy, imageResponse, basicBody, relayFileRequest, rejectOverrides }
|
|
962
1041
|
},
|
|
963
1042
|
"./host.cjs": function(require, module, exports) {
|
|
964
1043
|
'use strict'
|
|
@@ -995,20 +1074,29 @@ class RelayHost {
|
|
|
995
1074
|
finally { try { fs.unlinkSync(temp) } catch {} }
|
|
996
1075
|
this.config = config
|
|
997
1076
|
}
|
|
1077
|
+
e2eeAllowed(daily = this.daily) {
|
|
1078
|
+
if (!this.config) return false
|
|
1079
|
+
// Basic monthly relay has no encrypted entry. Data packs opt in explicitly.
|
|
1080
|
+
if (this.config.quotaPeriod !== 'month') return true
|
|
1081
|
+
return daily?.fileTransfer === true || this.config.dataPack === true
|
|
1082
|
+
}
|
|
998
1083
|
status() {
|
|
999
1084
|
const config = this.config
|
|
1000
1085
|
let phase = this.phase
|
|
1086
|
+
const e2eeAllowed = this.e2eeAllowed()
|
|
1001
1087
|
if (config && Date.now() >= config.expiresAt) phase = 'expired'
|
|
1002
|
-
else if (config?.enabled && this.daily?.exhausted) phase = 'quota-exceeded'
|
|
1088
|
+
else if (config?.enabled && this.daily?.exhausted && (this.e2eeEnabled || !this.daily.fallbackRemainingBytes)) phase = 'quota-exceeded'
|
|
1003
1089
|
else if (config?.enabled && this.daily?.unavailable) phase = 'quota-unavailable'
|
|
1004
1090
|
return { supported: true, enabled: !!config?.enabled, configured: !!config, phase,
|
|
1005
1091
|
publicUrl: config?.publicUrl || '', expiresAt: config?.expiresAt || null,
|
|
1092
|
+
...(config?.displayPlan === 'early-test' ? { displayPlan: 'early-test' } : {}),
|
|
1006
1093
|
fingerprint: config?.fingerprint || '', daily: this.daily, usageUpdatedAt: this.updatedAt,
|
|
1007
1094
|
quotaPending: !!config?.enabled && !this.daily, error: this.error,
|
|
1008
|
-
quotaPeriod: config?.quotaPeriod || 'day', fileTransfer: config?.fileTransfer !== false,
|
|
1009
|
-
monthlyLimitBytes: config?.
|
|
1010
|
-
e2ee: { enabled: this.e2eeEnabled, configured: !!this.endpoint, fingerprint: this.e2eeFingerprint, deviceCount: this.devices?.routes().length || 0 },
|
|
1011
|
-
server: this.origin, busy: this.busy, legacyAvailable: !config && !!this.legacy()
|
|
1095
|
+
quotaPeriod: config?.quotaPeriod || 'day', fileTransfer: config?.quotaPeriod === 'month' ? this.daily?.fileTransfer === true : config?.fileTransfer !== false,
|
|
1096
|
+
monthlyLimitBytes: config?.quotaPeriod === 'month' ? this.daily?.limitBytes || config.monthlyLimitBytes : null,
|
|
1097
|
+
e2ee: { allowed: e2eeAllowed, enabled: e2eeAllowed && this.e2eeEnabled, configured: e2eeAllowed && !!this.endpoint, fingerprint: e2eeAllowed ? this.e2eeFingerprint : '', deviceCount: e2eeAllowed ? this.devices?.routes().length || 0 : 0 },
|
|
1098
|
+
server: this.origin, busy: this.busy, legacyAvailable: !config && !!this.legacy(),
|
|
1099
|
+
activationImport: true, ...(config?.activationId ? { activationId: config.activationId } : {}) }
|
|
1012
1100
|
}
|
|
1013
1101
|
legacy() {
|
|
1014
1102
|
try {
|
|
@@ -1024,20 +1112,22 @@ class RelayHost {
|
|
|
1024
1112
|
}
|
|
1025
1113
|
start() {
|
|
1026
1114
|
this.stop()
|
|
1115
|
+
this.daily = null
|
|
1027
1116
|
if (!this.config || !fs.existsSync(this.keyFile)) throw fault('HOST_NOT_CONFIGURED', 409)
|
|
1028
1117
|
if (this.config.expiresAt <= Date.now()) { this.phase = 'expired'; return }
|
|
1029
1118
|
// Only the operator-configured service is allowed, never a target supplied by a browser.
|
|
1030
1119
|
if (this.config.tunnelOrigin !== this.origin) throw fault('RELAY_SERVER_MISMATCH', 409)
|
|
1031
|
-
this.e2eeEnabled = this.e2eeOverride ?? (this.config.e2eeEnabled === true)
|
|
1120
|
+
this.e2eeEnabled = this.e2eeAllowed() && (this.e2eeOverride ?? (this.config.e2eeEnabled === true))
|
|
1032
1121
|
let e2ee
|
|
1033
1122
|
if (this.e2eeEnabled) {
|
|
1034
1123
|
const identity = loadIdentity(this.root)
|
|
1035
1124
|
this.devices = new DeviceStore(this.root, identity)
|
|
1036
|
-
const policy = this.config.quotaPeriod === 'month'
|
|
1125
|
+
const policy = this.config.quotaPeriod === 'month' ? 'sponsor-basic'
|
|
1037
1126
|
: this.config.quotaPeriod !== 'month' && Number(this.config.dailyLimitBytes) > 0 ? 'standard' : null
|
|
1038
1127
|
if (!policy) throw fault('E2EE_POLICY_REQUIRED')
|
|
1039
1128
|
const { gatewayAddress } = require('./client.cjs')
|
|
1040
|
-
this.endpoint = new E2eeEndpoint({ identity, target: gatewayAddress(this.gateway), policy, expiresAt: this.config.expiresAt, devices: this.devices
|
|
1129
|
+
this.endpoint = new E2eeEndpoint({ identity, target: gatewayAddress(this.gateway), policy, expiresAt: this.config.expiresAt, devices: this.devices,
|
|
1130
|
+
allowFiles: () => this.daily?.fileTransfer === true && this.daily.resetsAt > Date.now() })
|
|
1041
1131
|
const endpoint = this.endpoint
|
|
1042
1132
|
e2ee = { routeTokenHash: crypto.createHash('sha256').update(identity.routeToken).digest('hex'), devices: this.devices.routes(), policy, allowPlain: true, accept: socket => endpoint.accept(socket), acceptPlain: socket => endpoint.acceptPlain(socket) }
|
|
1043
1133
|
const pairing = createPairing(identity.certificate, HOSTNAME)
|
|
@@ -1048,9 +1138,33 @@ class RelayHost {
|
|
|
1048
1138
|
const client = new RelayClient({ ...this.config, gateway: this.gateway, privateKey: fs.readFileSync(this.keyFile), ca: this.ca, e2ee })
|
|
1049
1139
|
this.client = client; this.phase = 'connecting'; this.error = ''
|
|
1050
1140
|
client.on('status', status => { if (this.client === client) this.phase = status })
|
|
1141
|
+
client.on('authorization', authorization => {
|
|
1142
|
+
if (this.client !== client) return
|
|
1143
|
+
const monthly = this.config?.quotaPeriod === 'month'
|
|
1144
|
+
if (!monthly && authorization.displayPlan !== 'early-test') return
|
|
1145
|
+
const { expiresAt } = authorization
|
|
1146
|
+
if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now() || expiresAt > 8.64e15) return
|
|
1147
|
+
if (!monthly && this.config.displayPlan !== 'early-test' || this.config.expiresAt !== expiresAt) {
|
|
1148
|
+
try { this.save({ ...this.config, ...(!monthly ? { displayPlan: 'early-test' } : {}), expiresAt }) }
|
|
1149
|
+
catch { this.error = 'LOCAL_STATE_WRITE_FAILED'; return }
|
|
1150
|
+
}
|
|
1151
|
+
client.expiresAt = expiresAt
|
|
1152
|
+
if (this.endpoint) this.endpoint.expiresAt = expiresAt
|
|
1153
|
+
})
|
|
1051
1154
|
client.on('usage', daily => {
|
|
1052
1155
|
if (this.client !== client) return
|
|
1053
1156
|
this.daily = daily; this.updatedAt = Date.now()
|
|
1157
|
+
if (this.config?.quotaPeriod === 'month' && typeof daily?.fileTransfer === 'boolean' && this.config.dataPack !== daily.fileTransfer) {
|
|
1158
|
+
try { this.save({ ...this.config, dataPack: daily.fileTransfer }) } catch {}
|
|
1159
|
+
}
|
|
1160
|
+
if (this.e2eeEnabled && !this.e2eeAllowed()) {
|
|
1161
|
+
this.e2eeEnabled = false
|
|
1162
|
+
queueMicrotask(() => {
|
|
1163
|
+
if (this.client === client && this.config?.enabled) {
|
|
1164
|
+
try { this.start() } catch { this.phase = 'error'; this.error = 'LOCAL_STATE_INVALID' }
|
|
1165
|
+
}
|
|
1166
|
+
})
|
|
1167
|
+
}
|
|
1054
1168
|
})
|
|
1055
1169
|
client.start()
|
|
1056
1170
|
}
|
|
@@ -1064,6 +1178,7 @@ class RelayHost {
|
|
|
1064
1178
|
async changeDevice(value) {
|
|
1065
1179
|
if (this.busy) throw fault('RELAY_OPERATION_BUSY',409)
|
|
1066
1180
|
if (!this.config) throw fault('HOST_NOT_CONFIGURED',409)
|
|
1181
|
+
if (!this.e2eeAllowed() && ['enable-encryption','rotate-identity','create-device'].includes(value.action)) throw fault('E2EE_PLAN_REQUIRED',409)
|
|
1067
1182
|
if (this.e2eeOverride === false && ['enable-encryption','rotate-identity'].includes(value.action)) throw fault('E2EE_DISABLED_BY_POLICY',409)
|
|
1068
1183
|
this.busy = true
|
|
1069
1184
|
try {
|
|
@@ -1096,7 +1211,7 @@ class RelayHost {
|
|
|
1096
1211
|
return this.deviceStatus()
|
|
1097
1212
|
} finally {this.busy=false}
|
|
1098
1213
|
}
|
|
1099
|
-
async change(action, key) {
|
|
1214
|
+
async change(action, key, activationId) {
|
|
1100
1215
|
if (this.busy) throw fault('RELAY_OPERATION_BUSY', 409)
|
|
1101
1216
|
this.busy = true
|
|
1102
1217
|
try {
|
|
@@ -1118,8 +1233,14 @@ class RelayHost {
|
|
|
1118
1233
|
fs.writeFileSync(path.join(this.legacyRoot,'stop.request'),'stop\n',{mode:0o600})
|
|
1119
1234
|
await new Promise(resolve=>setTimeout(resolve,700))
|
|
1120
1235
|
this.start()
|
|
1121
|
-
} else if (action === 'enroll') {
|
|
1122
|
-
|
|
1236
|
+
} else if (action === 'enroll' || action === 'activate-file') {
|
|
1237
|
+
const code = String(key || '').trim()
|
|
1238
|
+
const imported = action === 'activate-file'
|
|
1239
|
+
const match = (imported ? /^dsra_([a-f0-9]{16})\.[A-Za-z0-9_-]{43}$/ : /^dsrp_([a-f0-9]{16})\.[A-Za-z0-9_-]{43}$/).exec(code)
|
|
1240
|
+
if (!match) throw fault('INVALID_AUTHORIZATION', 400)
|
|
1241
|
+
if (imported && this.config && this.config.grantId !== match[1]) throw fault('HOST_ALREADY_CONFIGURED', 409)
|
|
1242
|
+
const activationHash = imported ? crypto.createHash('sha256').update(code).digest('hex') : null
|
|
1243
|
+
if (activationHash && this.config?.activationHash === activationHash && this.config.enabled) return this.status()
|
|
1123
1244
|
fs.mkdirSync(this.root, { recursive: true, mode: 0o700 })
|
|
1124
1245
|
if (!fs.existsSync(this.keyFile)) {
|
|
1125
1246
|
const pair = crypto.generateKeyPairSync('ed25519')
|
|
@@ -1127,12 +1248,13 @@ class RelayHost {
|
|
|
1127
1248
|
}
|
|
1128
1249
|
const privateKey = crypto.createPrivateKey(fs.readFileSync(this.keyFile))
|
|
1129
1250
|
const publicKey = crypto.createPublicKey(privateKey).export({ format: 'pem', type: 'spki' }).toString()
|
|
1130
|
-
const config = await enroll(this.origin,
|
|
1251
|
+
const config = await enroll(this.origin, code, publicKey, this.ca)
|
|
1131
1252
|
// Construct before replacing a working configuration; a malformed response cannot disable it.
|
|
1132
1253
|
new RelayClient({ ...config, gateway: this.gateway, privateKey: privateKey.export({ format: 'pem', type: 'pkcs8' }), ca: this.ca })
|
|
1133
1254
|
if (config.tunnelOrigin !== this.origin || new URL(config.publicUrl).protocol !== 'https:') throw fault('INVALID_SERVER_RESPONSE', 502)
|
|
1134
1255
|
this.save({ ...config, fingerprint: crypto.createHash('sha256').update(publicKey).digest('hex'), enabled: true,
|
|
1135
|
-
e2eeEnabled: this.e2eeOverride ?? (this.config ? this.e2eeEnabled :
|
|
1256
|
+
e2eeEnabled: this.e2eeOverride ?? (this.config ? this.e2eeEnabled : false),
|
|
1257
|
+
...(imported ? { activationId, activationHash } : {}) })
|
|
1136
1258
|
this.daily = null; this.updatedAt = null; this.start()
|
|
1137
1259
|
} else if (action === 'enable') {
|
|
1138
1260
|
if (!this.config) throw fault('HOST_NOT_CONFIGURED', 409)
|
|
@@ -1726,9 +1848,11 @@ const VERSION = gatewayVersion()
|
|
|
1726
1848
|
const PROTOCOL_VERSION = 1
|
|
1727
1849
|
const CAPABILITIES = Object.freeze({
|
|
1728
1850
|
wsTicket: 1,
|
|
1851
|
+
streamContinuity: 1,
|
|
1729
1852
|
eventPolling: 1,
|
|
1730
1853
|
eventEpoch: 1,
|
|
1731
1854
|
operations: 1,
|
|
1855
|
+
sessionContinuation: 1,
|
|
1732
1856
|
cloudRelay: 1,
|
|
1733
1857
|
workspaceFiles: 2,
|
|
1734
1858
|
fileInbox: 1,
|
|
@@ -2080,6 +2204,7 @@ function normalizeDeviceKey(value) {
|
|
|
2080
2204
|
return {
|
|
2081
2205
|
id,
|
|
2082
2206
|
note: String(value.note || '').trim().slice(0, 40),
|
|
2207
|
+
hostStateReadOnly: value.hostStateReadOnly === true,
|
|
2083
2208
|
token: accessToken,
|
|
2084
2209
|
createdAt: Number(value.createdAt) || Date.now(),
|
|
2085
2210
|
updatedAt: Number(value.updatedAt) || Number(value.createdAt) || Date.now(),
|
|
@@ -2125,11 +2250,12 @@ function scheduleDeviceKeysSave() {
|
|
|
2125
2250
|
deviceKeysSaveTimer.unref?.()
|
|
2126
2251
|
}
|
|
2127
2252
|
|
|
2128
|
-
function createDeviceKey(note = '') {
|
|
2253
|
+
function createDeviceKey(note = '', hostStateReadOnly = false) {
|
|
2129
2254
|
const now = Date.now()
|
|
2130
2255
|
const record = {
|
|
2131
2256
|
id: crypto.randomUUID?.() || crypto.randomBytes(16).toString('hex'),
|
|
2132
2257
|
note: String(note || '').trim().slice(0, 40) || '新设备',
|
|
2258
|
+
hostStateReadOnly,
|
|
2133
2259
|
token: newAccessToken(),
|
|
2134
2260
|
createdAt: now,
|
|
2135
2261
|
updatedAt: now,
|
|
@@ -2225,7 +2351,7 @@ function authorized(req, url, options = {}) {
|
|
|
2225
2351
|
if (deviceKeyState.enabled) {
|
|
2226
2352
|
const record = findDeviceKeyByToken(presented)
|
|
2227
2353
|
if (record) {
|
|
2228
|
-
req.dshRemoteAuth = { type: 'device', id: record.id }
|
|
2354
|
+
req.dshRemoteAuth = { type: 'device', id: record.id, hostStateReadOnly: record.hostStateReadOnly }
|
|
2229
2355
|
rememberDeviceKeyUse(record, req)
|
|
2230
2356
|
return true
|
|
2231
2357
|
}
|
|
@@ -3531,6 +3657,8 @@ const eventNextSeq = { mux: 1, host: 1 }
|
|
|
3531
3657
|
const EVENT_STREAM_EPOCH = crypto.randomUUID()
|
|
3532
3658
|
const WS_CLIENT_BUFFER_MAX = durationEnv('GATEWAY_WS_CLIENT_BUFFER_MAX', 2 * 1024 * 1024, 65536, 16 * 1024 * 1024)
|
|
3533
3659
|
const collectorClients = { mux: new Set(), host: new Set() }
|
|
3660
|
+
const continuitySockets = new Map()
|
|
3661
|
+
const continuityKey = (auth, id) => JSON.stringify([auth.type, auth.id, id])
|
|
3534
3662
|
const collectorReplay = { mux: new Map(), host: new Map() }
|
|
3535
3663
|
const eventPollWaiters = { mux: new Set(), host: new Set() }
|
|
3536
3664
|
const eventCollectorState = {
|
|
@@ -3603,7 +3731,7 @@ const modernState = {
|
|
|
3603
3731
|
eventClientId: '',
|
|
3604
3732
|
sessions: new Map(),
|
|
3605
3733
|
sessionCursors: new Map(),
|
|
3606
|
-
workspaces: { items: [], archivedSessionIds: [] },
|
|
3734
|
+
workspaces: { items: [], archivedSessionIds: [], pinnedSessionIds: [] },
|
|
3607
3735
|
pendingEvents: new Map(),
|
|
3608
3736
|
assistantStreams: new Map(),
|
|
3609
3737
|
sessionInterests: new Map(),
|
|
@@ -3724,6 +3852,72 @@ function legacyHistoryValue(value, summary) {
|
|
|
3724
3852
|
}
|
|
3725
3853
|
}
|
|
3726
3854
|
|
|
3855
|
+
async function readModernSessionPage(request, rpcId, signal) {
|
|
3856
|
+
const response = await callUpstreamRemote('session/events', { request }, rpcId, signal)
|
|
3857
|
+
if (response.status === 401 || response.status === 403) return response
|
|
3858
|
+
const missing = response.status === 404 && response.body?.result?.error?.code === 'gateway/method-unavailable'
|
|
3859
|
+
return missing || modernResponseNeedsLegacyFallback(response)
|
|
3860
|
+
? callUpstreamRemote('session/page', { request }, rpcId, signal)
|
|
3861
|
+
: response
|
|
3862
|
+
}
|
|
3863
|
+
|
|
3864
|
+
function sessionHistoryAddress({ sessionId, parentSessionId, subagentMode }) {
|
|
3865
|
+
return parentSessionId && typeof subagentMode === 'string'
|
|
3866
|
+
? { kind: 'subagent', parentSessionId, childSessionId: sessionId, mode: ['one-shot', 'continuable'].includes(subagentMode) ? subagentMode : 'unknown' }
|
|
3867
|
+
: { kind: 'session', sessionId }
|
|
3868
|
+
}
|
|
3869
|
+
|
|
3870
|
+
function imageReference(event, id) {
|
|
3871
|
+
const data = event?.data
|
|
3872
|
+
if (!data || !['user/message', 'assistant/message', 'tool/result'].includes(event.type)) return null
|
|
3873
|
+
const content = data.message?.content ?? data.content
|
|
3874
|
+
const image = block => block?.type === 'image' && block.attachment?.attachmentId === id
|
|
3875
|
+
const found = Array.isArray(content) && content.find(image)
|
|
3876
|
+
if (found) return found.attachment
|
|
3877
|
+
if (event.type === 'assistant/message' && Array.isArray(data.stream)) {
|
|
3878
|
+
return data.stream.find(record => record?.type === 'chunk' && record.chunk?.type === 'block-end' && image(record.chunk.block))?.chunk.block.attachment
|
|
3879
|
+
}
|
|
3880
|
+
return null
|
|
3881
|
+
}
|
|
3882
|
+
|
|
3883
|
+
async function readModernSessionImage(payload, rpcId) {
|
|
3884
|
+
const { sessionId } = payload
|
|
3885
|
+
const attachmentId = payload.attachment?.attachmentId ?? payload.attachmentId
|
|
3886
|
+
if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 256 || typeof attachmentId !== 'string' || !/^(?:sha256:)?[a-f0-9]{64}$/.test(attachmentId)) {
|
|
3887
|
+
return legacyEnvelope(rpcId, modernError('Invalid image reference.', 'session/attachment-invalid'))
|
|
3888
|
+
}
|
|
3889
|
+
// The new Host reads by store ID. Prove that this exact image occurs in the
|
|
3890
|
+
// addressed history before using the Host cookie, for every Remote credential.
|
|
3891
|
+
const signal = AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
|
|
3892
|
+
const upstream = UPSTREAM
|
|
3893
|
+
const projection = await callUpstreamRemote('session/projections', { request: { sessionId } }, rpcId, signal)
|
|
3894
|
+
const baseline = projection.body?.result?.ok && projection.body.result.value
|
|
3895
|
+
if (UPSTREAM !== upstream || !Number.isSafeInteger(baseline?.asOfSeq) || baseline.asOfSeq < 0 || baseline.kind === 'cached') {
|
|
3896
|
+
return legacyEnvelope(rpcId, modernError('The image could not be verified in this session.', 'session/attachment-not-in-history'))
|
|
3897
|
+
}
|
|
3898
|
+
const request = { address: sessionHistoryAddress(payload), throughSeq: baseline.asOfSeq, maxMessages: 100 }
|
|
3899
|
+
for (let page = 0; page < 100; page++) {
|
|
3900
|
+
const response = await readModernSessionPage(request, rpcId, signal)
|
|
3901
|
+
const value = response.body?.result?.ok && response.body.result.value
|
|
3902
|
+
if (UPSTREAM !== upstream || response.status !== 200 || !Array.isArray(value?.records)) break
|
|
3903
|
+
for (const record of value.records) {
|
|
3904
|
+
const attachment = imageReference(record?.event, attachmentId)
|
|
3905
|
+
if (!attachment) continue
|
|
3906
|
+
const endpoint = 'session/attachment'
|
|
3907
|
+
let image = await callUpstreamRemote(endpoint, { request: { sessionId, attachment } }, rpcId, signal)
|
|
3908
|
+
if (UPSTREAM === upstream && image.body?.result?.error?.code === 'gateway/input-invalid') {
|
|
3909
|
+
image = await callUpstreamRemote(endpoint, { request: { sessionId, attachmentId } }, rpcId, signal)
|
|
3910
|
+
}
|
|
3911
|
+
return UPSTREAM === upstream && image.body?.result ? legacyEnvelope(rpcId, image.body.result)
|
|
3912
|
+
: legacyEnvelope(rpcId, modernError('The Host could not read this image.', 'session/attachment-unavailable'))
|
|
3913
|
+
}
|
|
3914
|
+
const beforeSeq = value.records[0]?.event?.seq
|
|
3915
|
+
if (!value.hasMore || !Number.isSafeInteger(beforeSeq) || beforeSeq <= 0 || beforeSeq >= (request.beforeSeq ?? Infinity)) break
|
|
3916
|
+
request.beforeSeq = beforeSeq
|
|
3917
|
+
}
|
|
3918
|
+
return legacyEnvelope(rpcId, modernError('The image could not be verified in this session.', 'session/attachment-not-in-history'))
|
|
3919
|
+
}
|
|
3920
|
+
|
|
3727
3921
|
async function refreshModernSessions() {
|
|
3728
3922
|
const response = await callUpstreamRemote('session/list', { _request: {} })
|
|
3729
3923
|
if (response.status === 200 && response.body?.result?.ok) updateModernSessions(response.body.result.value?.items)
|
|
@@ -3752,6 +3946,71 @@ function modernPermissionCatalog(value) {
|
|
|
3752
3946
|
}
|
|
3753
3947
|
}
|
|
3754
3948
|
|
|
3949
|
+
function modernInboxItems(inbox) {
|
|
3950
|
+
return ['next-turn', 'next-step'].flatMap(target =>
|
|
3951
|
+
(Array.isArray(inbox?.[target]) ? inbox[target] : []).filter(message => message?.id).map(message => ({
|
|
3952
|
+
id: message.id,
|
|
3953
|
+
placement: target === 'next-turn' ? 'queued' : message.source?.kind === 'user' ? 'steering' : 'context',
|
|
3954
|
+
message,
|
|
3955
|
+
})))
|
|
3956
|
+
}
|
|
3957
|
+
|
|
3958
|
+
async function readModernQueue(sessionId, rpcId) {
|
|
3959
|
+
const request = { sessionId }
|
|
3960
|
+
const state = await callUpstreamRemote('session/state', { request }, rpcId)
|
|
3961
|
+
if (!modernResponseNeedsLegacyFallback(state)) {
|
|
3962
|
+
if (state.body?.result?.ok === true) {
|
|
3963
|
+
const { queue, cursor, running } = state.body.result.value || {}
|
|
3964
|
+
if (Array.isArray(queue)) return { items: queue, seq: cursor, running: running === true }
|
|
3965
|
+
if (queue === null) {
|
|
3966
|
+
const projections = await callUpstreamRemote('session/projections', { request }, rpcId)
|
|
3967
|
+
const value = projections.body?.result?.value
|
|
3968
|
+
if (projections.body?.result?.ok && value?.kind === 'sequenced') {
|
|
3969
|
+
return { items: modernInboxItems(value.values?.inbox), seq: value.asOfSeq, running: false }
|
|
3970
|
+
}
|
|
3971
|
+
return { failure: projections }
|
|
3972
|
+
}
|
|
3973
|
+
}
|
|
3974
|
+
return { failure: state }
|
|
3975
|
+
}
|
|
3976
|
+
const list = await callUpstreamRemote('session/list', { _request: {} }, rpcId)
|
|
3977
|
+
if (!list.body?.result?.ok) return { failure: list }
|
|
3978
|
+
const row = list.body.result.value?.items?.find(item => item.sessionId === sessionId)
|
|
3979
|
+
const projected = row?.projections
|
|
3980
|
+
if (projected?.kind === 'sequenced' && projected.values && Object.hasOwn(projected.values, 'inbox')) {
|
|
3981
|
+
return { items: modernInboxItems(projected.values.inbox), seq: projected.asOfSeq, running: row.running === true }
|
|
3982
|
+
}
|
|
3983
|
+
return { failure: { status: 404 } }
|
|
3984
|
+
}
|
|
3985
|
+
|
|
3986
|
+
function hostStateError(response, unavailableCode) {
|
|
3987
|
+
const error = response?.body?.result?.error
|
|
3988
|
+
if (response?.status === 403 || /(?:forbidden|permission.denied|access.denied)/i.test(error?.code || '')) {
|
|
3989
|
+
return modernError('This device cannot perform that Host operation.', 'host-state/access-denied')
|
|
3990
|
+
}
|
|
3991
|
+
if (modernResponseNeedsLegacyFallback(response)) return modernError('This Host does not expose the required API.', unavailableCode)
|
|
3992
|
+
return error ? { ok: false, error } : modernError('Host state could not be read.', 'host-state/unavailable')
|
|
3993
|
+
}
|
|
3994
|
+
|
|
3995
|
+
function scheduledExecution(records, messageId, running) {
|
|
3996
|
+
const events = records.map(record => record?.event).filter(Boolean)
|
|
3997
|
+
const entered = events.findIndex(event => event.type === 'user/message' && event.data?.id === messageId)
|
|
3998
|
+
if (entered < 0) return 'unverified'
|
|
3999
|
+
let stepped = false
|
|
4000
|
+
for (const event of events.slice(entered + 1)) {
|
|
4001
|
+
if (event.type === 'turn/start') return 'unverified'
|
|
4002
|
+
if (event.type === 'step/start') stepped = true
|
|
4003
|
+
if (event.type === 'turn/end') {
|
|
4004
|
+
const reason = event.data?.reason?.kind
|
|
4005
|
+
if (reason === 'completed') return 'completed'
|
|
4006
|
+
if (reason === 'aborted' || reason === 'interrupted') return 'aborted'
|
|
4007
|
+
if (['error', 'failed', 'blocked', 'max-tokens', 'rejected'].includes(reason)) return 'failed'
|
|
4008
|
+
return 'unverified'
|
|
4009
|
+
}
|
|
4010
|
+
}
|
|
4011
|
+
return running && stepped ? 'running' : 'unverified'
|
|
4012
|
+
}
|
|
4013
|
+
|
|
3755
4014
|
async function translateModernRpc(method, payload, rpcId, strictReceipt = false) {
|
|
3756
4015
|
const migrationFailure = response => method === 'session.history' && /cannot safely transform unclassified message source|migration-required|source v0 artifact remains unchanged/i.test(JSON.stringify(response.body?.result?.error || {}))
|
|
3757
4016
|
const migrationReply = () => legacyEnvelope(rpcId, modernError('The source session format cannot be migrated by DSH. Update DSH and open the original session there before retrying; Remote will not rewrite its log.', 'session/migration-required', { sessionId: payload.sessionId }))
|
|
@@ -3788,6 +4047,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
3788
4047
|
if (modernResponseNeedsLegacyFallback(response)) return legacyFallback('generated RPC session/list unavailable')
|
|
3789
4048
|
return response.body || legacyEnvelope(rpcId, modernError('DSH session/list returned no JSON response'))
|
|
3790
4049
|
}
|
|
4050
|
+
if (method === 'session.attachment') return readModernSessionImage(payload, rpcId)
|
|
3791
4051
|
if (method === 'session.history') {
|
|
3792
4052
|
let summary = modernState.sessions.get(payload.sessionId)
|
|
3793
4053
|
if (!summary) {
|
|
@@ -3795,7 +4055,8 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
3795
4055
|
summary = modernState.sessions.get(payload.sessionId)
|
|
3796
4056
|
}
|
|
3797
4057
|
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 }))
|
|
3798
|
-
const
|
|
4058
|
+
const address = sessionHistoryAddress(payload)
|
|
4059
|
+
const isChild = address.kind === 'subagent'
|
|
3799
4060
|
let throughSeq = modernState.sessionCursors.get(payload.sessionId) ?? Number(summary?.projections?.asOfSeq)
|
|
3800
4061
|
if (isChild || summary?.projections?.kind === 'cached' || !modernState.followedSessions?.has(payload.sessionId)) {
|
|
3801
4062
|
// Cached storage watermarks are not connected stream sequence numbers.
|
|
@@ -3809,11 +4070,8 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
3809
4070
|
if (!Number.isSafeInteger(throughSeq) || throughSeq < -1) {
|
|
3810
4071
|
return legacyEnvelope(rpcId, modernError('DSH did not expose a history cursor for this session', 'session-not-found'))
|
|
3811
4072
|
}
|
|
3812
|
-
endpoint = 'session/page'
|
|
3813
4073
|
args = { request: {
|
|
3814
|
-
address
|
|
3815
|
-
? { kind: 'subagent', parentSessionId: payload.parentSessionId, childSessionId: payload.sessionId, mode: ['one-shot', 'continuable'].includes(payload.subagentMode) ? payload.subagentMode : 'unknown' }
|
|
3816
|
-
: { kind: 'session', sessionId: payload.sessionId },
|
|
4074
|
+
address,
|
|
3817
4075
|
throughSeq,
|
|
3818
4076
|
...(payload.beforeSeq === undefined ? {} : { beforeSeq: payload.beforeSeq }),
|
|
3819
4077
|
...(payload.maxMessages === undefined ? {} : { maxMessages: payload.maxMessages }),
|
|
@@ -3822,6 +4080,20 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
3822
4080
|
if (!isChild) requestModernSessionStream(payload.sessionId)
|
|
3823
4081
|
return { ...legacyHistoryValue(value, summary), ...modernReasoningValue(payload.sessionId) }
|
|
3824
4082
|
}
|
|
4083
|
+
} else if (method === 'session.continue') {
|
|
4084
|
+
if (!strictReceipt) return legacyEnvelope(rpcId, modernError('Continuation requires an operation receipt.', 'session/continuation-unavailable'))
|
|
4085
|
+
const { sessionId, ending } = payload
|
|
4086
|
+
if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 256 || !Number.isSafeInteger(ending) || ending < 0) {
|
|
4087
|
+
return legacyEnvelope(rpcId, modernError('Invalid continuation request.', 'session/continuation-unavailable'))
|
|
4088
|
+
}
|
|
4089
|
+
const upstream = UPSTREAM
|
|
4090
|
+
const projection = await callUpstreamRemote('session/projections', { request: { sessionId } }, rpcId)
|
|
4091
|
+
const value = projection.body?.result?.ok && projection.body.result.value
|
|
4092
|
+
if (UPSTREAM !== upstream || value?.kind !== 'sequenced' || value.values?.conversationContinuation !== ending) {
|
|
4093
|
+
return legacyEnvelope(rpcId, modernError('This failed turn is no longer available to continue.', 'session/continuation-unavailable'))
|
|
4094
|
+
}
|
|
4095
|
+
endpoint = 'session/prompt'
|
|
4096
|
+
args = { request: { sessionId, requestId: rpcId, mode: 'queue', content: [] } }
|
|
3825
4097
|
} else if (method === 'session.models') {
|
|
3826
4098
|
endpoint = 'session/modelCatalog'
|
|
3827
4099
|
args = {}
|
|
@@ -3850,25 +4122,86 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
3850
4122
|
if (typeof skill?.name !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,199}$/.test(skill.name)) return []
|
|
3851
4123
|
return [{ name: skill.name, description: typeof skill.description === 'string' ? skill.description.slice(0, 500) : '' }]
|
|
3852
4124
|
}) })
|
|
4125
|
+
} else if (method === 'session.queueState') {
|
|
4126
|
+
const snapshot = await readModernQueue(payload.sessionId, rpcId)
|
|
4127
|
+
return legacyEnvelope(rpcId, snapshot.failure ? hostStateError(snapshot.failure, 'session/queue-state-unsupported') : { ok: true, value: snapshot })
|
|
4128
|
+
} else if (method === 'session.deliveryStatus') {
|
|
4129
|
+
const snapshot = await readModernQueue(payload.sessionId, rpcId)
|
|
4130
|
+
if (snapshot.failure) return legacyEnvelope(rpcId, hostStateError(snapshot.failure, 'session/queue-state-unsupported'))
|
|
4131
|
+
const request = { address: { kind: 'session', sessionId: payload.sessionId }, throughSeq: snapshot.seq, maxMessages: 32 }
|
|
4132
|
+
if (snapshot.items.some(item => item.id === payload.messageId)) return legacyEnvelope(rpcId, { ok: true, value: { status: 'pending' } })
|
|
4133
|
+
let records = []
|
|
4134
|
+
for (let page = 0; page < 4; page++) {
|
|
4135
|
+
const response = await readModernSessionPage(request, rpcId)
|
|
4136
|
+
if (!response.body?.result?.ok) return legacyEnvelope(rpcId, hostStateError(response, 'session/queue-state-unsupported'))
|
|
4137
|
+
const value = response.body.result.value
|
|
4138
|
+
const pageRecords = value?.records
|
|
4139
|
+
if (!Array.isArray(pageRecords) || !pageRecords.length) break
|
|
4140
|
+
records = [...pageRecords, ...records]
|
|
4141
|
+
const firstSeq = pageRecords[0]?.event?.seq
|
|
4142
|
+
if (pageRecords.some(record => record?.event?.type === 'user/message' && record.event.data?.id === payload.messageId)
|
|
4143
|
+
|| !value.hasMore || !Number.isSafeInteger(firstSeq) || (request.beforeSeq !== undefined && firstSeq >= request.beforeSeq)) break
|
|
4144
|
+
request.beforeSeq = firstSeq
|
|
4145
|
+
}
|
|
4146
|
+
return legacyEnvelope(rpcId, { ok: true, value: { status: scheduledExecution(records, payload.messageId, snapshot.running) } })
|
|
4147
|
+
} else if (['schedule.list', 'schedule.view', 'schedule.history', 'schedule.create', 'schedule.edit', 'schedule.run'].includes(method)) {
|
|
4148
|
+
endpoint = 'schedule/' + method.slice('schedule.'.length)
|
|
4149
|
+
args = { request: payload }
|
|
3853
4150
|
} else if (method.startsWith('session.')) {
|
|
3854
4151
|
const verb = method.slice('session.'.length)
|
|
3855
|
-
if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', '
|
|
4152
|
+
if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
|
|
3856
4153
|
endpoint = 'session/' + verb
|
|
3857
|
-
|
|
3858
|
-
? { ...payload, requestId:
|
|
4154
|
+
let request = verb === 'prompt' && !payload.requestId
|
|
4155
|
+
? { ...payload, requestId: rpcId }
|
|
3859
4156
|
: payload
|
|
3860
|
-
|
|
4157
|
+
if (verb === 'updateQueue' && payload.action?.kind === 'edit') {
|
|
4158
|
+
const snapshot = await readModernQueue(payload.sessionId, rpcId)
|
|
4159
|
+
if (snapshot.failure) return legacyEnvelope(rpcId, hostStateError(snapshot.failure, 'session/queue-state-unsupported'))
|
|
4160
|
+
const row = snapshot.items.find(item => item.id === payload.itemId && item.placement !== 'context')
|
|
4161
|
+
if (!row) return legacyEnvelope(rpcId, modernError('This item is no longer pending.', 'session/queue-item-not-found'))
|
|
4162
|
+
const content = row.message?.content ?? row.content
|
|
4163
|
+
if (!Array.isArray(content) || !content.length || content.some(block => block?.type !== 'text' || typeof block.text !== 'string')) {
|
|
4164
|
+
return legacyEnvelope(rpcId, modernError('The Host cannot preserve attachments during an edit.', 'session/queue-edit-attachments'))
|
|
4165
|
+
}
|
|
4166
|
+
if (!Object.hasOwn(payload, 'expectedContent') || operationJson(content) !== operationJson(payload.expectedContent)) {
|
|
4167
|
+
return legacyEnvelope(rpcId, modernError('The queue item changed; reopen the editor.', 'session/queue-conflict'))
|
|
4168
|
+
}
|
|
4169
|
+
request = { sessionId: payload.sessionId, itemId: payload.itemId, action: payload.action }
|
|
4170
|
+
}
|
|
4171
|
+
args = { request }
|
|
3861
4172
|
} else if (method.startsWith('workspace.')) {
|
|
3862
4173
|
const verb = method.slice('workspace.'.length)
|
|
3863
|
-
if (!['create', 'rename', 'delete', 'insertBefore', 'insertSessionBefore', 'archiveSession'
|
|
4174
|
+
if (!['create', 'rename', 'delete', 'insertBefore', 'insertSessionBefore', 'archiveSession',
|
|
4175
|
+
'unarchiveSession', 'pinSession', 'unpinSession'].includes(verb)) return legacyFallback('no generated RPC adapter')
|
|
3864
4176
|
endpoint = 'workspace/' + verb
|
|
3865
4177
|
args = { request: payload }
|
|
3866
|
-
|
|
4178
|
+
transform = value => {
|
|
3867
4179
|
// The HTTP receipt precedes workspace/follow on another connection.
|
|
3868
|
-
// Publish the committed
|
|
3869
|
-
if (
|
|
4180
|
+
// Publish the committed navigation change before a client's immediate refresh.
|
|
4181
|
+
if (verb === 'rename' && value?.workspace) applyModernWorkspaceFrame({ type: 'upsert', workspace: value.workspace })
|
|
4182
|
+
else if (verb === 'delete' && value?.deleted === true) applyModernWorkspaceFrame({ type: 'remove', workspaceId: payload.workspaceId })
|
|
4183
|
+
else if (verb === 'archiveSession' || verb === 'unarchiveSession') {
|
|
4184
|
+
if (Array.isArray(value?.archivedSessionIds)) applyModernWorkspaceFrame({ type: 'archived', ...value })
|
|
4185
|
+
} else if (verb === 'pinSession' || verb === 'unpinSession') {
|
|
4186
|
+
if (Array.isArray(value?.pinnedSessionIds)) applyModernWorkspaceFrame({ type: 'pinned', ...value })
|
|
4187
|
+
}
|
|
3870
4188
|
return value
|
|
3871
4189
|
}
|
|
4190
|
+
} else if (method === 'commands.list') {
|
|
4191
|
+
if (!payload?.sessionId) return legacyFallback('session id required for command catalog')
|
|
4192
|
+
endpoint = 'commands/list'
|
|
4193
|
+
args = { agentId: payload.sessionId }
|
|
4194
|
+
} else if (method === 'session.search') {
|
|
4195
|
+
endpoint = 'session/search'
|
|
4196
|
+
args = { request: { query: payload.query } }
|
|
4197
|
+
} else if (method === 'fileReferences.list') {
|
|
4198
|
+
if (!payload?.sessionId) return legacyFallback('session id required for file references')
|
|
4199
|
+
endpoint = 'fileReferences/list'
|
|
4200
|
+
args = { agentId: payload.sessionId, query: String(payload.query || '') }
|
|
4201
|
+
} else if (method === 'sessionReferenceResolver.candidates') {
|
|
4202
|
+
if (!payload?.sessionId) return legacyFallback('session id required for session references')
|
|
4203
|
+
endpoint = 'sessionReferenceResolver/candidates'
|
|
4204
|
+
args = { agentId: payload.sessionId, query: String(payload.query || '') }
|
|
3872
4205
|
} else if (method.startsWith('goal.')) {
|
|
3873
4206
|
const verb = method.slice('goal.'.length)
|
|
3874
4207
|
if (!['create', 'edit', 'pause', 'resume', 'complete', 'clear'].includes(verb)) return legacyFallback('no generated RPC adapter')
|
|
@@ -3927,8 +4260,19 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
3927
4260
|
return legacyFallback('no generated RPC adapter')
|
|
3928
4261
|
}
|
|
3929
4262
|
|
|
3930
|
-
let response = await callUpstreamRemote(endpoint, args, rpcId)
|
|
4263
|
+
let response = method === 'session.history' ? await readModernSessionPage(args.request, rpcId) : await callUpstreamRemote(endpoint, args, rpcId)
|
|
3931
4264
|
let receiptStage = 'modern-request'
|
|
4265
|
+
if (method.startsWith('schedule.')) {
|
|
4266
|
+
if (response.status === 403 || modernResponseNeedsLegacyFallback(response)) return legacyEnvelope(rpcId, hostStateError(response, 'schedule/unsupported'))
|
|
4267
|
+
if (method === 'schedule.list' && response.body?.result?.error?.code === 'gateway/input-invalid') {
|
|
4268
|
+
return legacyEnvelope(rpcId, modernError('This Host does not support the paginated Schedule contract.', 'schedule/unsupported'))
|
|
4269
|
+
}
|
|
4270
|
+
if (response.body?.result?.ok && (response.body.result.value?.code || (method === 'schedule.list' && !Array.isArray(response.body.result.value?.items)))) {
|
|
4271
|
+
const code = response.body.result.value?.code || 'schedule/unsupported'
|
|
4272
|
+
return legacyEnvelope(rpcId, modernError(code, code))
|
|
4273
|
+
}
|
|
4274
|
+
}
|
|
4275
|
+
if (method === 'session.updateQueue' && response.status === 403) return legacyEnvelope(rpcId, hostStateError(response))
|
|
3932
4276
|
if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (typeof response.body?.result?.ok !== 'boolean' && ![404,405,501].includes(response.status)))) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: response.status, receiptCategory: response.status >= 500 ? 'upstream-http' : 'invalid-response', receiptStage })
|
|
3933
4277
|
if (method === 'session.prompt' && imageAdmissionRejected(response.body)) {
|
|
3934
4278
|
let bridged
|
|
@@ -3983,14 +4327,19 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
3983
4327
|
hasChildren: Array.isArray(values.subagentCatalog) && values.subagentCatalog.length > 0 }
|
|
3984
4328
|
} catch { return { kind: 'diagnostic', id: child.id, reason: 'unavailable' } }
|
|
3985
4329
|
}))
|
|
3986
|
-
|
|
4330
|
+
const { values, asOfSeq } = parent.body.result.value
|
|
4331
|
+
return legacyEnvelope(rpcId, { ok: true, value: { entries, parentAvailable: !!modernState.sessions.get(payload.parentSessionId)?.agentAvailable,
|
|
4332
|
+
...(values?.agentTeam ? { agentTeam: values.agentTeam, teamSeq: asOfSeq } : {}) } })
|
|
3987
4333
|
}
|
|
3988
4334
|
if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (typeof response.body?.result?.ok !== 'boolean' && ![404,405,501].includes(response.status)))) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: response.status, receiptCategory: response.status >= 500 ? 'upstream-http' : 'invalid-response', receiptStage })
|
|
3989
|
-
if (modernResponseNeedsLegacyFallback(response))
|
|
4335
|
+
if (modernResponseNeedsLegacyFallback(response)) {
|
|
4336
|
+
if (method === 'session.continue') return legacyEnvelope(rpcId, modernError('This Host cannot continue generation.', 'session/continuation-unavailable'))
|
|
4337
|
+
return legacyFallback(`generated RPC ${endpoint || 'session/events'} unavailable`)
|
|
4338
|
+
}
|
|
3990
4339
|
if (!response.body?.result?.ok) {
|
|
3991
4340
|
if (migrationFailure(response)) return migrationReply()
|
|
3992
4341
|
recordCompatibility('generated-rpc-error', { method, status: response.status, detail: remoteFailureKind(response) })
|
|
3993
|
-
return response.body || legacyEnvelope(rpcId, modernError(`DSH ${endpoint} returned no JSON response`))
|
|
4342
|
+
return response.body || legacyEnvelope(rpcId, modernError(`DSH ${endpoint || 'session/events'} returned no JSON response`))
|
|
3994
4343
|
}
|
|
3995
4344
|
return legacyEnvelope(rpcId, { ok: true, value: transform(response.body.result.value) })
|
|
3996
4345
|
}
|
|
@@ -4161,6 +4510,18 @@ function serveEventPoll(req, res, url) {
|
|
|
4161
4510
|
}
|
|
4162
4511
|
touchDevice(req)
|
|
4163
4512
|
const kind = url.searchParams.get('kind')
|
|
4513
|
+
if (kind === 'mux' && url.searchParams.has('wsProbe')) {
|
|
4514
|
+
const id = url.searchParams.get('stream'), nonce = url.searchParams.get('wsProbe')
|
|
4515
|
+
const socket = /^[a-f0-9]{32}$/.test(id || '') && /^[a-f0-9]{32}$/.test(nonce || '')
|
|
4516
|
+
? continuitySockets.get(continuityKey(req.dshRemoteAuth, id)) : null
|
|
4517
|
+
const frame = socket && encodeWsText(JSON.stringify({ type: 'relay/ws-probe', nonce }))
|
|
4518
|
+
const available = socket?.writable && !socket.destroyed && socket.writableLength + frame.length <= WS_CLIENT_BUFFER_MAX
|
|
4519
|
+
if (available) socket.write(frame)
|
|
4520
|
+
cors(res)
|
|
4521
|
+
res.writeHead(available ? 204 : 404, { 'cache-control': 'no-store' })
|
|
4522
|
+
res.end()
|
|
4523
|
+
return
|
|
4524
|
+
}
|
|
4164
4525
|
if (kind !== 'mux' && kind !== 'host') {
|
|
4165
4526
|
cors(res)
|
|
4166
4527
|
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
@@ -4408,11 +4769,7 @@ function applyModernProjection(sessionId, key, value, seq) {
|
|
|
4408
4769
|
legacyPush('mux', { type: 'session/projection', sessionId, key, value, seq })
|
|
4409
4770
|
if (key === 'inbox') {
|
|
4410
4771
|
// DSH 0.2 stores queue/steer state in the durable Inbox projection.
|
|
4411
|
-
|
|
4412
|
-
(Array.isArray(value?.[target]) ? value[target] : []).filter(message => message?.id).map(message => ({
|
|
4413
|
-
id: message.id, placement: target === 'next-turn' ? 'queued' : 'context', message,
|
|
4414
|
-
})))
|
|
4415
|
-
legacyPush('mux', { type: 'session/queue', sessionId, items })
|
|
4772
|
+
legacyPush('mux', { type: 'session/queue', sessionId, items: modernInboxItems(value), seq })
|
|
4416
4773
|
}
|
|
4417
4774
|
}
|
|
4418
4775
|
|
|
@@ -4447,6 +4804,7 @@ function applyModernWorkspaceFrame(value) {
|
|
|
4447
4804
|
modernState.workspaces = {
|
|
4448
4805
|
items: Array.isArray(value.value?.items) ? value.value.items : [],
|
|
4449
4806
|
archivedSessionIds: Array.isArray(value.value?.archivedSessionIds) ? value.value.archivedSessionIds : [],
|
|
4807
|
+
pinnedSessionIds: Array.isArray(value.value?.pinnedSessionIds) ? value.value.pinnedSessionIds : [],
|
|
4450
4808
|
}
|
|
4451
4809
|
return
|
|
4452
4810
|
}
|
|
@@ -4470,6 +4828,9 @@ function applyModernWorkspaceFrame(value) {
|
|
|
4470
4828
|
} else if (value?.type === 'archived') {
|
|
4471
4829
|
modernState.workspaces = { ...modernState.workspaces, archivedSessionIds: value.archivedSessionIds || [] }
|
|
4472
4830
|
legacyPush('host', { type: 'host/archived-sessions-changed', archivedSessionIds: value.archivedSessionIds || [] })
|
|
4831
|
+
} else if (value?.type === 'pinned') {
|
|
4832
|
+
modernState.workspaces = { ...modernState.workspaces, pinnedSessionIds: value.pinnedSessionIds || [] }
|
|
4833
|
+
legacyPush('host', { type: 'host/pinned-sessions-changed', pinnedSessionIds: value.pinnedSessionIds || [] })
|
|
4473
4834
|
}
|
|
4474
4835
|
}
|
|
4475
4836
|
|
|
@@ -4629,6 +4990,8 @@ function applyModernRemoteEvent(ws, value) {
|
|
|
4629
4990
|
legacyPush('host', { type: 'host/session-activity', sessionId, updatedAt })
|
|
4630
4991
|
} else if (value.event === 'api-session/error') {
|
|
4631
4992
|
legacyPush('host', { type: 'host/agent-error', sessionId: args[0], message: String(args[1] || '') })
|
|
4993
|
+
} else if (value.event === 'schedule/changed') {
|
|
4994
|
+
legacyPush('host', { type: 'schedule/changed' })
|
|
4632
4995
|
} else {
|
|
4633
4996
|
legacyPush('host', { type: 'host/remote-event', event: value.event, args })
|
|
4634
4997
|
}
|
|
@@ -5628,7 +5991,7 @@ async function serveAdminApi(req, res, url) {
|
|
|
5628
5991
|
}
|
|
5629
5992
|
if (sub === '/device-keys/create') {
|
|
5630
5993
|
if (deviceKeyState.keys.length >= 100) return send(409, { error: 'too-many-device-keys', detail: '设备密钥数量已达到上限' })
|
|
5631
|
-
const record = createDeviceKey(payload.note)
|
|
5994
|
+
const record = createDeviceKey(payload.note, payload.hostStateReadOnly === true)
|
|
5632
5995
|
return record
|
|
5633
5996
|
? send(201, { ok: true, entry: { ...record }, deviceKeys: deviceKeysPayload() })
|
|
5634
5997
|
: send(500, { error: 'write-failed', detail: '无法保存设备密钥' })
|
|
@@ -5637,6 +6000,16 @@ async function serveAdminApi(req, res, url) {
|
|
|
5637
6000
|
const index = deviceKeyState.keys.findIndex(record => record.id === id)
|
|
5638
6001
|
if (index < 0) return send(404, { error: 'device-key-not-found', detail: '找不到该设备密钥' })
|
|
5639
6002
|
const record = deviceKeyState.keys[index]
|
|
6003
|
+
if (sub === '/device-keys/host-state-access') {
|
|
6004
|
+
if (typeof payload.readOnly !== 'boolean') return send(400, { error: 'bad-access' })
|
|
6005
|
+
const previous = record.hostStateReadOnly
|
|
6006
|
+
record.hostStateReadOnly = payload.readOnly
|
|
6007
|
+
if (!saveDeviceKeys()) {
|
|
6008
|
+
record.hostStateReadOnly = previous
|
|
6009
|
+
return send(500, { error: 'write-failed' })
|
|
6010
|
+
}
|
|
6011
|
+
return send(200, { ok: true, entry: { ...record } })
|
|
6012
|
+
}
|
|
5640
6013
|
if (sub === '/device-keys/note') {
|
|
5641
6014
|
const previous = { note: record.note, updatedAt: record.updatedAt }
|
|
5642
6015
|
record.note = String(payload.note || '').trim().slice(0, 40)
|
|
@@ -5779,6 +6152,70 @@ async function serveAdminApi(req, res, url) {
|
|
|
5779
6152
|
res.end(JSON.stringify({ error: 'not-found' }))
|
|
5780
6153
|
}
|
|
5781
6154
|
|
|
6155
|
+
let relayActivationRequest = null
|
|
6156
|
+
|
|
6157
|
+
function currentRelayActivation() {
|
|
6158
|
+
if (relayActivationRequest?.expiresAt <= Date.now() && relayActivationRequest.phase !== 'binding') relayActivationRequest = null
|
|
6159
|
+
return relayActivationRequest
|
|
6160
|
+
}
|
|
6161
|
+
|
|
6162
|
+
function relayActivationView(req, canManage, request = currentRelayActivation()) {
|
|
6163
|
+
if (!request || !(canManage && localRelayManagement(req)) && request.owner !== relayActivationOwner(req)) return {}
|
|
6164
|
+
const { id, phase, expiresAt, error } = request
|
|
6165
|
+
return { activationRequest: { id, phase, expiresAt, ...(error ? { error } : {}) } }
|
|
6166
|
+
}
|
|
6167
|
+
|
|
6168
|
+
function relayActivationOwner(req) {
|
|
6169
|
+
return JSON.stringify([req.dshRemoteAuth.type, req.dshRemoteAuth.id, String(req.headers['x-dsh-remote-client-id'] || '').slice(0, 96)])
|
|
6170
|
+
}
|
|
6171
|
+
|
|
6172
|
+
async function activateRelayFile(code, id) {
|
|
6173
|
+
const before = relayHost.status().activationId
|
|
6174
|
+
const status = await relayHost.change('activate-file', code, id)
|
|
6175
|
+
if (status.activationId !== before) legacyPush('host', { type: 'host/relay-activation', activationId: status.activationId })
|
|
6176
|
+
return status
|
|
6177
|
+
}
|
|
6178
|
+
|
|
6179
|
+
async function changeRelayActivation(req, canManage, value) {
|
|
6180
|
+
const fail = (code, status) => { throw Object.assign(new Error(code), { code, status }) }
|
|
6181
|
+
if (!localRelayPairing(req)) fail('LOCAL_PAIRING_REQUIRED', 403)
|
|
6182
|
+
if (value.action === 'activate-file') {
|
|
6183
|
+
const file = value.activation
|
|
6184
|
+
if (Object.keys(value).some(key => !['action', 'activation'].includes(key)) || !file ||
|
|
6185
|
+
Object.keys(file).some(key => !['type', 'version', 'code', 'expiresAt'].includes(key)) ||
|
|
6186
|
+
file.type !== 'dsh-remote-relay-activation' || file.version !== 1 || !Number.isSafeInteger(file.expiresAt) ||
|
|
6187
|
+
typeof file.code !== 'string' || !/^dsra_[a-f0-9]{16}\.[A-Za-z0-9_-]{43}$/.test(file.code)) fail('INVALID_ACTIVATION_FILE', 400)
|
|
6188
|
+
if (file.expiresAt <= Date.now()) fail('ACTIVATION_FILE_EXPIRED', 409)
|
|
6189
|
+
const pending = currentRelayActivation()
|
|
6190
|
+
if (pending?.phase === 'binding' || pending?.phase === 'pending' && (canManage || pending.code !== file.code || pending.owner !== relayActivationOwner(req))) {
|
|
6191
|
+
fail('RELAY_ACTIVATION_PENDING', 409)
|
|
6192
|
+
}
|
|
6193
|
+
if (canManage) return activateRelayFile(file.code, crypto.randomBytes(16).toString('hex'))
|
|
6194
|
+
if (!pending || pending.phase !== 'pending') relayActivationRequest = {
|
|
6195
|
+
id: crypto.randomBytes(16).toString('hex'), phase: 'pending', owner: relayActivationOwner(req), code: file.code,
|
|
6196
|
+
expiresAt: Math.min(file.expiresAt, Date.now() + 5 * 60 * 1000),
|
|
6197
|
+
}
|
|
6198
|
+
return { ...relayHost.status(), ...relayActivationView(req, canManage) }
|
|
6199
|
+
}
|
|
6200
|
+
if (!canManage || !localRelayManagement(req)) fail('RELAY_ADMIN_REQUIRED', 403)
|
|
6201
|
+
if (Object.keys(value).some(key => !['action', 'requestId'].includes(key))) fail('INVALID_RELAY_ACTION', 400)
|
|
6202
|
+
const pending = currentRelayActivation()
|
|
6203
|
+
if (pending?.phase !== 'pending' || pending.id !== value.requestId) fail('RELAY_ACTIVATION_NOT_PENDING', 409)
|
|
6204
|
+
const code = pending.code
|
|
6205
|
+
delete pending.code
|
|
6206
|
+
pending.phase = value.action === 'approve-activation' ? 'binding' : 'rejected'
|
|
6207
|
+
if (pending.phase === 'binding') {
|
|
6208
|
+
try {
|
|
6209
|
+
await activateRelayFile(code, pending.id)
|
|
6210
|
+
pending.phase = 'bound'
|
|
6211
|
+
} catch (error) {
|
|
6212
|
+
pending.phase = 'failed'
|
|
6213
|
+
pending.error = error.code || 'RELAY_OPERATION_FAILED'
|
|
6214
|
+
}
|
|
6215
|
+
}
|
|
6216
|
+
return { ...relayHost.status(), ...relayActivationView(req, canManage) }
|
|
6217
|
+
}
|
|
6218
|
+
|
|
5782
6219
|
async function serveRelaySettings(req, res, url) {
|
|
5783
6220
|
cors(res)
|
|
5784
6221
|
const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
|
|
@@ -5789,19 +6226,24 @@ async function serveRelaySettings(req, res, url) {
|
|
|
5789
6226
|
if (req.method === 'GET') {
|
|
5790
6227
|
const canManageDevices = canManage && localRelayManagement(req)
|
|
5791
6228
|
const pairingActivity = canManageDevices ? relayHost.pairingActivity() : undefined
|
|
5792
|
-
return reply(200, { ...relayHost.status(), canManage, canManageDevices, canPairLocally: localRelayPairing(req), pairingActivity })
|
|
6229
|
+
return reply(200, { ...relayHost.status(), canManage, canManageDevices, canPairLocally: localRelayPairing(req), pairingActivity, ...relayActivationView(req, canManage) })
|
|
5793
6230
|
}
|
|
5794
|
-
if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
|
|
5795
6231
|
try {
|
|
5796
6232
|
const chunks = []; let size = 0
|
|
5797
6233
|
for await (const chunk of req) { size += chunk.length; if (size > 4096) return reply(413, { error: 'BODY_TOO_LARGE' }); chunks.push(chunk) }
|
|
5798
6234
|
let value
|
|
5799
6235
|
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { return reply(400, { error: 'INVALID_JSON' }) }
|
|
5800
|
-
if (!value ||
|
|
6236
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return reply(400, { error: 'INVALID_RELAY_ACTION' })
|
|
6237
|
+
if (['activate-file', 'approve-activation', 'reject-activation'].includes(value.action)) {
|
|
6238
|
+
const result = await changeRelayActivation(req, canManage, value)
|
|
6239
|
+
return reply(200, { ...result, canManage, canManageDevices: canManage && localRelayManagement(req), canPairLocally: true })
|
|
6240
|
+
}
|
|
6241
|
+
if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
|
|
6242
|
+
if (Object.keys(value).some(key => !['action', 'key'].includes(key))) return reply(400, { error: 'INVALID_RELAY_ACTION' })
|
|
5801
6243
|
const result = await relayHost.change(value.action, value.key)
|
|
5802
6244
|
return reply(200, { ...result, canManage: true })
|
|
5803
6245
|
} catch (error) {
|
|
5804
|
-
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'])
|
|
6246
|
+
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', 'LOCAL_PAIRING_REQUIRED', 'INVALID_ACTIVATION_FILE', 'ACTIVATION_FILE_EXPIRED', 'RELAY_ACTIVATION_PENDING', 'RELAY_ACTIVATION_NOT_PENDING', 'RELAY_ADMIN_REQUIRED'])
|
|
5805
6247
|
return reply(error.status || 503, { error: known.has(error.code) ? error.code : 'RELAY_OPERATION_FAILED' })
|
|
5806
6248
|
}
|
|
5807
6249
|
}
|
|
@@ -7071,14 +7513,17 @@ function serveWorkbench(req, res, url) {
|
|
|
7071
7513
|
|
|
7072
7514
|
// ---------- /api 代理 ----------
|
|
7073
7515
|
const ADAPTIVE_RPC_METHODS = new Set([
|
|
7516
|
+
'session.queueState', 'session.deliveryStatus', 'schedule.list', 'schedule.view', 'schedule.history', 'schedule.create', 'schedule.edit', 'schedule.run',
|
|
7074
7517
|
'agentPresets.list', 'permissionPresets.catalog', 'skills.list',
|
|
7075
7518
|
'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
|
|
7076
7519
|
'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
|
|
7077
7520
|
'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
|
|
7078
7521
|
'workspace.create', 'workspace.rename', 'workspace.delete', 'workspace.insertBefore',
|
|
7079
|
-
'workspace.insertSessionBefore', 'workspace.archiveSession', '
|
|
7522
|
+
'workspace.insertSessionBefore', 'workspace.archiveSession', 'workspace.unarchiveSession',
|
|
7523
|
+
'workspace.pinSession', 'workspace.unpinSession', 'goal.create', 'goal.edit',
|
|
7080
7524
|
'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear', 'subagent.list',
|
|
7081
|
-
'subagent.interrupt', '
|
|
7525
|
+
'subagent.interrupt', 'commands.list', 'fileReferences.list',
|
|
7526
|
+
'sessionReferenceResolver.candidates', 'settings.describe', 'settings.mutate', 'settings.openDocument',
|
|
7082
7527
|
'credentials.describe', 'credentials.set', 'credentials.unset', 'llm.providers', 'llm.discoverModels',
|
|
7083
7528
|
])
|
|
7084
7529
|
|
|
@@ -7176,7 +7621,8 @@ function sendBufferedUpstreamResponse(res, response) {
|
|
|
7176
7621
|
// A durable receipt records intent before forwarding. Only a hash of the
|
|
7177
7622
|
// payload is stored. A crash/timeout is UNKNOWN, never permission to replay a
|
|
7178
7623
|
// potentially committed upstream write. Old DSH needs no invented RPC support.
|
|
7179
|
-
const OPERATION_METHODS = new Set(['session.fork', 'session.create', 'session.prompt', 'session.updateQueue',
|
|
7624
|
+
const OPERATION_METHODS = new Set(['session.fork', 'session.create', 'session.prompt', 'session.continue', 'session.updateQueue',
|
|
7625
|
+
'schedule.create', 'schedule.edit', 'schedule.run',
|
|
7180
7626
|
'session.selectModel', 'session.rename', 'session.cancel', 'workspace.create',
|
|
7181
7627
|
'workspace.archiveSession', 'goal.edit', 'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear'])
|
|
7182
7628
|
const OPERATION_DIR = path.join(path.dirname(TOKEN_FILE), 'operations')
|
|
@@ -7228,13 +7674,14 @@ function operationFailureFacts(error, stage, createdAt) {
|
|
|
7228
7674
|
...(Number.isInteger(httpStatus) && httpStatus >= 100 && httpStatus <= 599 ? { httpStatus } : {}),
|
|
7229
7675
|
durationMs: Math.max(0, Date.now() - createdAt) }
|
|
7230
7676
|
}
|
|
7231
|
-
function operationResult(body) {
|
|
7677
|
+
function operationResult(body, method) {
|
|
7232
7678
|
const guidance = {
|
|
7233
7679
|
'image-vision-failed': '图片处理未完成,消息尚未提交。请检查视觉辅助插件或切换支持图片的模型。',
|
|
7234
7680
|
'session/agent-busy': '当前会话正忙,请等待当前任务结束后再操作。',
|
|
7235
7681
|
'session/not-found': '会话不存在,请刷新列表后重新打开。',
|
|
7236
7682
|
'session/model-not-found': '所选模型不可用,请重新选择模型。',
|
|
7237
7683
|
'session/attachment-invalid': '图片或附件未被主机接受,请检查文件及所选模型的支持情况。',
|
|
7684
|
+
'schedule/input-invalid': '主机拒绝了任务设置。请核对时间、时区、重复规则和投递目标。',
|
|
7238
7685
|
}
|
|
7239
7686
|
const visionGuidance = {
|
|
7240
7687
|
VISION_PLUGIN_MISSING: '当前模型不支持图片,且未安装视觉辅助插件。请安装并启用 dsh-image-vision,或切换支持图片的模型。',
|
|
@@ -7246,7 +7693,9 @@ function operationResult(body) {
|
|
|
7246
7693
|
message: (code === 'image-vision-failed' && Object.hasOwn(visionGuidance, body.result.error?.details?.reason) && visionGuidance[body.result.error.details.reason]) || (Object.hasOwn(guidance, code) && guidance[code]) || '主机拒绝了操作,请核对会话和当前配置。'
|
|
7247
7694
|
} } }
|
|
7248
7695
|
const input = body.result.value || {}, value = {}
|
|
7249
|
-
|
|
7696
|
+
const fields = method?.startsWith('schedule.') ? ['id', 'deleted']
|
|
7697
|
+
: ['accepted', 'deleted', 'sessionId', 'workspaceId', 'archivedSessionIds', 'pinnedSessionIds', 'ref', 'selected', 'model', 'cleared', 'title', 'seq']
|
|
7698
|
+
for (const key of fields) {
|
|
7250
7699
|
if (input[key] !== undefined) value[key] = input[key]
|
|
7251
7700
|
}
|
|
7252
7701
|
if (input.workspace) value.workspace = Object.fromEntries(['workspaceId','path','title','sessionIds'].filter(key => input.workspace[key] !== undefined).map(key => [key,input.workspace[key]]))
|
|
@@ -7260,7 +7709,7 @@ async function executeOperation(key, job, payload) {
|
|
|
7260
7709
|
try {
|
|
7261
7710
|
let body
|
|
7262
7711
|
const url = new URL('/api/' + job.method, UPSTREAM)
|
|
7263
|
-
const modernFirst = await detectUpstreamApiFlavor() === 'modern'
|
|
7712
|
+
const modernFirst = job.method === 'session.continue' || await detectUpstreamApiFlavor() === 'modern'
|
|
7264
7713
|
if (modernFirst) {
|
|
7265
7714
|
stage = 'modern-request'
|
|
7266
7715
|
body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
|
|
@@ -7281,7 +7730,7 @@ async function executeOperation(key, job, payload) {
|
|
|
7281
7730
|
}
|
|
7282
7731
|
stage = 'response-validation'
|
|
7283
7732
|
if (typeof body?.result?.ok !== 'boolean' || Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) throw Object.assign(new Error('upstream-uncertain'), { receiptCategory: 'invalid-response', httpStatus: responseStatus })
|
|
7284
|
-
job.result = operationResult(body)
|
|
7733
|
+
job.result = operationResult(body, job.method)
|
|
7285
7734
|
job.phase = body.result.ok === true ? 'complete' : 'rejected'
|
|
7286
7735
|
} catch (error) {
|
|
7287
7736
|
job.phase = 'unknown'
|
|
@@ -7329,6 +7778,7 @@ async function serveOperations(req, res, url) {
|
|
|
7329
7778
|
if (!OPERATION_METHODS.has(body?.method) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) {
|
|
7330
7779
|
return reply(400, { error: 'unsupported-operation' })
|
|
7331
7780
|
}
|
|
7781
|
+
if (req.dshRemoteAuth?.hostStateReadOnly && hostStateWrite(body.method)) return reply(403, { error: 'host-state/access-denied' })
|
|
7332
7782
|
const fingerprint = operationHash(operationJson({ method: body.method, payload: body.payload }))
|
|
7333
7783
|
let old
|
|
7334
7784
|
try { old = loadOperation(key) } catch { return reply(503, { error: 'receipt-unavailable' }) }
|
|
@@ -7365,14 +7815,22 @@ async function serveOperations(req, res, url) {
|
|
|
7365
7815
|
|
|
7366
7816
|
async function proxyLegacyRpcWithModernFallback(req, res, url) {
|
|
7367
7817
|
const raw = await readApiRequest(req)
|
|
7818
|
+
let body
|
|
7819
|
+
try { body = JSON.parse(raw || '{}') } catch { body = null }
|
|
7820
|
+
if (decodeURIComponent(url.pathname) === '/api/session.attachment' && body?.method !== 'session.attachment') {
|
|
7821
|
+
cors(res)
|
|
7822
|
+
return sendHttpBody(res, 400, { 'content-type': 'application/json' }, JSON.stringify({ error: 'bad-request' }))
|
|
7823
|
+
}
|
|
7824
|
+
if (req.dshRemoteAuth?.hostStateReadOnly && hostStateWrite(body?.method)) {
|
|
7825
|
+
sendHttpBody(res, 403, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({ error: 'host-state/access-denied' }))
|
|
7826
|
+
return
|
|
7827
|
+
}
|
|
7368
7828
|
const legacy = await forwardLegacyRpc(url, raw)
|
|
7369
7829
|
if (!modernResponseNeedsLegacyFallback({ status: legacy.status, body: parseRpcJson(legacy.raw) })) {
|
|
7370
7830
|
if (legacy.status >= 400) recordCompatibility('legacy-rpc-error', { method: url.pathname.slice('/api/'.length), status: legacy.status })
|
|
7371
7831
|
sendBufferedUpstreamResponse(res, legacy)
|
|
7372
7832
|
return
|
|
7373
7833
|
}
|
|
7374
|
-
let body
|
|
7375
|
-
try { body = JSON.parse(raw || '{}') } catch { body = null }
|
|
7376
7834
|
if (body?.type !== 'client-request' || typeof body.rpcId !== 'string' || !ADAPTIVE_RPC_METHODS.has(body.method)) {
|
|
7377
7835
|
sendBufferedUpstreamResponse(res, legacy)
|
|
7378
7836
|
return
|
|
@@ -7385,7 +7843,7 @@ async function proxyLegacyRpcWithModernFallback(req, res, url) {
|
|
|
7385
7843
|
}
|
|
7386
7844
|
// A generated RPC completed, so subsequent requests and live collectors can use
|
|
7387
7845
|
// the modern contract immediately instead of waiting for the periodic probe.
|
|
7388
|
-
if (!['host.describe', 'workspace.list'].includes(body.method)) {
|
|
7846
|
+
if (!['host.describe', 'workspace.list'].includes(body.method) && !['schedule/unsupported', 'session/queue-state-unsupported'].includes(translated.result?.error?.code)) {
|
|
7389
7847
|
const previous = upstreamApiFlavor
|
|
7390
7848
|
upstreamApiFlavor = 'modern'
|
|
7391
7849
|
upstreamApiFlavorCheckedAt = Date.now()
|
|
@@ -7460,6 +7918,10 @@ async function proxyModernApi(req, res, url) {
|
|
|
7460
7918
|
res.end(JSON.stringify({ error: 'bad-request' }))
|
|
7461
7919
|
return true
|
|
7462
7920
|
}
|
|
7921
|
+
if (req.dshRemoteAuth?.hostStateReadOnly && hostStateWrite(body.method)) {
|
|
7922
|
+
sendHttpBody(res, 403, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({ error: 'host-state/access-denied' }))
|
|
7923
|
+
return true
|
|
7924
|
+
}
|
|
7463
7925
|
const translated = await translateModernRpc(body.method, body.payload || {}, body.rpcId)
|
|
7464
7926
|
if (translated?.__dshRemoteLegacyFallback) {
|
|
7465
7927
|
recordCompatibility('modern-legacy-fallback', { method: body.method, detail: translated.reason })
|
|
@@ -7595,6 +8057,11 @@ async function proxyLegacyApi(req, res, url) {
|
|
|
7595
8057
|
req.pipe(upstreamReq)
|
|
7596
8058
|
}
|
|
7597
8059
|
|
|
8060
|
+
function hostStateWrite(method) {
|
|
8061
|
+
const name = method.replace(/\//g, '.').replace(/\.+$/, '')
|
|
8062
|
+
return name === 'session.updateQueue' || (name.startsWith('schedule.') && !['schedule.list', 'schedule.history', 'schedule.catalog', 'schedule.view', 'schedule.deliveryLimits'].includes(name))
|
|
8063
|
+
}
|
|
8064
|
+
|
|
7598
8065
|
function proxyApi(req, res, url) {
|
|
7599
8066
|
if (req.method === 'OPTIONS') {
|
|
7600
8067
|
cors(res)
|
|
@@ -7624,6 +8091,20 @@ function proxyApi(req, res, url) {
|
|
|
7624
8091
|
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
7625
8092
|
return
|
|
7626
8093
|
}
|
|
8094
|
+
if (url.pathname === '/api/host-state-access' && req.method === 'GET') {
|
|
8095
|
+
cors(res)
|
|
8096
|
+
return sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify({ writable: req.dshRemoteAuth?.hostStateReadOnly !== true }))
|
|
8097
|
+
}
|
|
8098
|
+
let rpcRoute
|
|
8099
|
+
try { rpcRoute = decodeURIComponent(url.pathname).replace(/\/{2,}/g, '/').replace(/\/+$/, '') } catch { rpcRoute = '' }
|
|
8100
|
+
if (rpcRoute === '/api/session/attachment' || (rpcRoute === '/api/session.attachment' && (url.pathname !== '/api/session.attachment' || req.method !== 'POST')) || rpcRoute === '/api/session.continue') {
|
|
8101
|
+
cors(res)
|
|
8102
|
+
return sendHttpBody(res, 404, { 'content-type': 'application/json' }, JSON.stringify({ error: 'unsupported-endpoint' }))
|
|
8103
|
+
}
|
|
8104
|
+
if (req.dshRemoteAuth?.hostStateReadOnly && hostStateWrite(rpcRoute.slice('/api/'.length))) {
|
|
8105
|
+
cors(res)
|
|
8106
|
+
return sendHttpBody(res, 403, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({ error: 'host-state/access-denied' }))
|
|
8107
|
+
}
|
|
7627
8108
|
void proxyModernApi(req, res, url).then(handled => {
|
|
7628
8109
|
if (!handled) return proxyLegacyApi(req, res, url)
|
|
7629
8110
|
}).catch(error => {
|
|
@@ -7694,13 +8175,22 @@ function createFileInbox({ root, resolveSource, validAuth, now = Date.now, maxFi
|
|
|
7694
8175
|
return row
|
|
7695
8176
|
}
|
|
7696
8177
|
return {
|
|
7697
|
-
register: (auth, key, name) => lock(() => {
|
|
7698
|
-
if (!keyOk(key) || !validAuth(auth)) throw fail('invalid-receiver', 403)
|
|
7699
|
-
|
|
8178
|
+
register: (auth, key, name, legacyKey) => lock(() => {
|
|
8179
|
+
if (!keyOk(key) || !validAuth(auth) || (legacyKey !== undefined && !keyOk(legacyKey))) throw fail('invalid-receiver', 403)
|
|
8180
|
+
const keyHash = digest(key)
|
|
8181
|
+
const legacyHash = legacyKey ? digest(legacyKey) : keyHash
|
|
8182
|
+
let d = state.devices.find(row => row.auth === auth && row.keyHash === keyHash)
|
|
8183
|
+
const legacy = legacyHash === keyHash ? null : state.devices.find(row => row.auth === auth && row.keyHash === legacyHash)
|
|
8184
|
+
if (!d && legacy) {
|
|
8185
|
+
d = legacy; d.keyHash = keyHash
|
|
8186
|
+
} else if (d && legacy) {
|
|
8187
|
+
for (const row of state.transfers) if (row.deviceId === legacy.id && row.auth === auth) row.deviceId = d.id
|
|
8188
|
+
state.devices = state.devices.filter(row => row !== legacy)
|
|
8189
|
+
}
|
|
7700
8190
|
if (!d) {
|
|
7701
8191
|
state.devices = state.devices.filter(row => validAuth(row.auth) && row.lastSeenAt > now() - 30 * ttl)
|
|
7702
8192
|
if (state.devices.length >= 100) throw fail('too-many-receivers', 409)
|
|
7703
|
-
d = { id: crypto.randomUUID(), auth, keyHash
|
|
8193
|
+
d = { id: crypto.randomUUID(), auth, keyHash }; state.devices.push(d)
|
|
7704
8194
|
}
|
|
7705
8195
|
d.name = String(name || 'Remote 设备').replace(/[\x00-\x1f]/g, '').slice(0, 60)
|
|
7706
8196
|
d.lastSeenAt = now(); save()
|
|
@@ -7709,7 +8199,9 @@ function createFileInbox({ root, resolveSource, validAuth, now = Date.now, maxFi
|
|
|
7709
8199
|
devices: () => lock(() => state.devices.filter(d => validAuth(d.auth)).map(d => ({ id: d.id, name: d.name, lastSeenAt: d.lastSeenAt, online: now() - d.lastSeenAt < 45000 }))),
|
|
7710
8200
|
list: (auth, key) => lock(() => {
|
|
7711
8201
|
const d = device(auth, key)
|
|
7712
|
-
|
|
8202
|
+
const rows = state.transfers.filter(row => row.deviceId === d.id).reverse()
|
|
8203
|
+
let historyLimit = 50 - rows.filter(row => !terminal.has(row.phase)).length
|
|
8204
|
+
return rows.filter(row => !terminal.has(row.phase) || historyLimit-- > 0).map(view)
|
|
7713
8205
|
}),
|
|
7714
8206
|
send: body => lock(async () => {
|
|
7715
8207
|
if (!idOk(body.id) || typeof body.path !== 'string' || typeof body.workspaceRoot !== 'string' || typeof body.deviceId !== 'string' || typeof body.sessionId !== 'string') throw fail('invalid-delivery')
|
|
@@ -7835,6 +8327,7 @@ async function serveFileInbox(req, res, url) {
|
|
|
7835
8327
|
if (req.method === 'GET') return reply(200, { transfers: await fileInbox.list(auth, key) })
|
|
7836
8328
|
if (req.method !== 'POST') return reply(405, { error: 'method-not-allowed' })
|
|
7837
8329
|
if (body.action === 'register') return reply(200, await fileInbox.register(auth, key, body.name))
|
|
8330
|
+
if (body.action === 'register-device') return reply(200, await fileInbox.register(auth, key, body.name, body.legacyKey))
|
|
7838
8331
|
if (['accept', 'reject'].includes(body.action)) return reply(200, await fileInbox.decide(auth, key, body.id, body.action))
|
|
7839
8332
|
if (body.action === 'receipt') return reply(200, await fileInbox.acknowledge(auth, key, body.id, body.phase))
|
|
7840
8333
|
return reply(400, { error: 'invalid-action' })
|
|
@@ -8158,6 +8651,12 @@ function acceptCollectorClient(req, socket, head, kind, device) {
|
|
|
8158
8651
|
if (head?.length) socket.unshift(head)
|
|
8159
8652
|
socket.setNoDelay(true)
|
|
8160
8653
|
collectorClients[kind].add(socket)
|
|
8654
|
+
const streamId = new URL(req.url, 'http://dsh-remote.local').searchParams.get('stream')
|
|
8655
|
+
if (kind === 'mux' && /^[a-f0-9]{32}$/.test(streamId || '')) {
|
|
8656
|
+
const id = continuityKey(req.dshRemoteAuth, streamId)
|
|
8657
|
+
continuitySockets.set(id, socket)
|
|
8658
|
+
socket.once('close', () => { if (continuitySockets.get(id) === socket) continuitySockets.delete(id) })
|
|
8659
|
+
}
|
|
8161
8660
|
eventCollectorState[kind].clients = collectorClients[kind].size
|
|
8162
8661
|
// 客户端(鸿蒙 lws 等严格 RFC 实现)会发掩码 Ping 并等待 Pong;
|
|
8163
8662
|
// 网关必须按 RFC6455 回 Pong(0x8A),且服务端→客户端方向不带掩码位
|