@tianacloud/dsh-remote 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1412 @@
1
+ import { RTCPeerConnection } from 'werift';
2
+ import { MultipathSession, createPath, LEASE_MS, relayPacer, RELAY_GRACE_MS } from '../web-src/multipath.js';
3
+ import { PeerPath, localAddress, normalizeP2pEnabled, normalizeStun } from '../web-src/peer-path.js';
4
+ import { FragmentReader, sendFragments } from '../web-src/ws-fragments.js';
5
+ import { base64UrlEncode, MSG_E2EE_CTRL, MULTIPATH_CAPABILITIES, respondHostHandshake } from '../web-src/e2ee.js';
6
+ import { FrontendAssets } from './frontend-assets.js';
7
+ import { openPinnedWebSocket, pinnedFetch, resolvePinnedEndpoint, resolvePinnedTarget } from './local-transport.js';
8
+ import {
9
+ decodeClientFrame,
10
+ decodeHostFrame,
11
+ decodeJSON,
12
+ decodeWindowUpdate,
13
+ encodeClientFrame,
14
+ encodeHostFrame,
15
+ encodeJSON,
16
+ MSG_CONTROL_JSON,
17
+ MSG_E2EE_BOX,
18
+ MSG_E2EE_CLIENT_HELLO,
19
+ MSG_E2EE_ERROR,
20
+ MSG_E2EE_HOST_HELLO,
21
+ MSG_HTTP_ABORT,
22
+ MSG_HTTP_REQ_BODY,
23
+ MSG_HTTP_REQ_END,
24
+ MSG_HTTP_REQ_HEAD,
25
+ MSG_HTTP_RES_BODY,
26
+ MSG_HTTP_RES_END,
27
+ MSG_HTTP_RES_HEAD,
28
+ MSG_HTTP_RES_WINDOW,
29
+ MSG_WS_CLOSE,
30
+ MSG_WS_DATA_BIN,
31
+ MSG_WS_DATA_TEXT,
32
+ MSG_WS_OPEN,
33
+ MSG_WS_OPENED,
34
+ } from './protocol.js';
35
+
36
+ const CHUNK_SIZE = 32 * 1024;
37
+ const MAX_REQUEST_BYTES = 16 * 1024 * 1024;
38
+ const MAX_REQUEST_CHUNKS = 1024;
39
+ const MAX_HOST_REQUEST_BYTES = 32 * 1024 * 1024;
40
+ export const MAX_STREAMS = 64;
41
+ const MIN_WINDOW_BYTES = 64 * 1024;
42
+ const MAX_WINDOW_BYTES = 8 * 1024 * 1024;
43
+ const MAX_BUFFERED_BYTES = 4 * 1024 * 1024;
44
+ const REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
45
+ const DEFAULT_SSE_KEEPALIVE_MS = 25_000;
46
+ const DEFAULT_AUTH_TIMEOUT_MS = 30_000;
47
+ const SSE_KEEPALIVE_BYTES = Buffer.from(': keepalive\n', 'utf8');
48
+
49
+ const SHARED_HOP_BY_HOP_HEADERS = new Set([
50
+ 'connection',
51
+ 'keep-alive',
52
+ 'proxy-authenticate',
53
+ 'proxy-authorization',
54
+ 'te',
55
+ 'trailer',
56
+ 'transfer-encoding',
57
+ 'upgrade',
58
+ ]);
59
+ const REQUEST_STRIPPED_HEADERS = new Set([
60
+ ...SHARED_HOP_BY_HOP_HEADERS,
61
+ 'host',
62
+ 'origin',
63
+ 'referer',
64
+ 'content-length',
65
+ 'cookie',
66
+ 'authorization',
67
+ 'forwarded',
68
+ 'x-real-ip',
69
+ 'x-dsh-remote-tunnel',
70
+ ]);
71
+
72
+ function nominatedConnectionHeaders(headers) {
73
+ const nominated = new Set();
74
+ for (const part of (headers.get('connection') || '').toLowerCase().split(',')) {
75
+ const name = part.trim();
76
+ if (name) nominated.add(name);
77
+ }
78
+ return nominated;
79
+ }
80
+
81
+ const ALLOWED_HTTP_METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']);
82
+ const RESERVED_HTTP_EXACT_PATHS = new Set([
83
+ '/',
84
+ '/index.html',
85
+ ]);
86
+ const RESERVED_HTTP_PREFIX_SEGMENTS = new Set([
87
+ '__dsh_remote__',
88
+ '_tiana',
89
+ 'connect',
90
+ 'plugins',
91
+ 'oauth',
92
+ 'inspector',
93
+ 'open-in-app',
94
+ ]);
95
+
96
+ /**
97
+ * Validate and classify a tunneled HTTP target.
98
+ * - Blocks malformed/traversal paths and reserved DSH core or shell routes (returns null -> 404).
99
+ * - Blocks `/api/tiana-remote/admin` and `/api/tiana-remote/admin/*` (returns `{ kind: 'forbidden' }` -> 403).
100
+ * - Allows `/api/*` (including `/api/tiana-remote/status` & `/api/tiana-remote/public-status`)
101
+ * and third-party plugin HTTP routes.
102
+ */
103
+ export function classifyHttpRoute(pathAndQuery) {
104
+ if (typeof pathAndQuery !== 'string' || !pathAndQuery.startsWith('/') ||
105
+ pathAndQuery.startsWith('//') || /[\\#\u0000-\u0020\u007f]/u.test(pathAndQuery)) {
106
+ return null;
107
+ }
108
+ let parsed;
109
+ try {
110
+ parsed = new URL(pathAndQuery, 'http://route.invalid');
111
+ } catch {
112
+ return null;
113
+ }
114
+ const rawPathname = pathAndQuery.split('?', 1)[0];
115
+ if (parsed.origin !== 'http://route.invalid' || parsed.username || parsed.password ||
116
+ parsed.pathname !== rawPathname) {
117
+ return null;
118
+ }
119
+ if (parsed.pathname === '/__dsh_remote__/bootstrap.json' || parsed.pathname === '/__dsh_remote__/asset') {
120
+ return { kind: 'internal', parsed };
121
+ }
122
+ if (/%(?:2f|5c|2e|25)/iu.test(parsed.pathname) || parsed.pathname.includes('//')) {
123
+ return null;
124
+ }
125
+ let decodedPathname;
126
+ try {
127
+ decodedPathname = decodeURIComponent(parsed.pathname);
128
+ } catch {
129
+ return null;
130
+ }
131
+ if (/[\u0000-\u001f\u007f\\]/u.test(decodedPathname)) {
132
+ return null;
133
+ }
134
+ const segments = decodedPathname.slice(1).split('/');
135
+ for (let i = 0; i < segments.length; i++) {
136
+ const seg = segments[i];
137
+ if (seg === '.' || seg === '..') return null;
138
+ if (seg === '' && decodedPathname !== '/' && i < segments.length - 1) return null;
139
+ }
140
+ const trimmedLower = decodedPathname === '/' ? '/' : decodedPathname.replace(/\/+$/u, '').toLowerCase() || '/';
141
+ if (RESERVED_HTTP_EXACT_PATHS.has(trimmedLower)) {
142
+ return null;
143
+ }
144
+ if (RESERVED_HTTP_PREFIX_SEGMENTS.has(segments[0].toLowerCase())) {
145
+ return null;
146
+ }
147
+ if (/^\/api\/tiana-remote\/admin(?:\/|$)/iu.test(trimmedLower)) {
148
+ return { kind: 'forbidden', parsed };
149
+ }
150
+ return { kind: 'forward', parsed };
151
+ }
152
+
153
+ function parseFirstCookiePair(setCookieHeader) {
154
+ if (!setCookieHeader) return '';
155
+ const first = Array.isArray(setCookieHeader) ? setCookieHeader[0] : setCookieHeader;
156
+ if (!first) return '';
157
+ return String(first).split(';', 1)[0].trim();
158
+ }
159
+
160
+ function getSetCookieHeaders(headers) {
161
+ if (typeof headers.getSetCookie === 'function') {
162
+ return headers.getSetCookie();
163
+ }
164
+ const single = headers.get('set-cookie');
165
+ return single ? [single] : [];
166
+ }
167
+
168
+ function extractThemeFromInjections(rows) {
169
+ const theme = {
170
+ preference: 'system',
171
+ cssVars: {},
172
+ };
173
+ for (const row of rows || []) {
174
+ if (row?.kind !== 'script' || typeof row.text !== 'string') continue;
175
+ if (!row.text.includes('dsThemeSource') && !row.text.includes('data-ds-dark-theme')) continue;
176
+ const prefMatch = /const preference = ("[^"]+"|'[^']+')/.exec(row.text);
177
+ if (prefMatch) {
178
+ try {
179
+ theme.preference = JSON.parse(prefMatch[1].replace(/^'|'$/g, '"'));
180
+ } catch {
181
+ // ignore
182
+ }
183
+ }
184
+ for (const m of row.text.matchAll(/setProperty\(("[^"]+"),\s*("[^"]*")\)/g)) {
185
+ try {
186
+ const key = JSON.parse(m[1]);
187
+ const val = JSON.parse(m[2]);
188
+ theme.cssVars[key] = val;
189
+ } catch {
190
+ // ignore
191
+ }
192
+ }
193
+ }
194
+ return theme;
195
+ }
196
+
197
+ function isEventStreamContentType(contentType) {
198
+ if (typeof contentType !== 'string') return false;
199
+ return contentType.split(';', 1)[0].trim().toLowerCase() === 'text/event-stream';
200
+ }
201
+
202
+ export class HostBridge {
203
+ constructor(options) {
204
+ this.relayUrl = options.relayUrl;
205
+ this.relayToken = options.relayToken || '';
206
+ this.e2eeSecret = options.e2eeSecret || '';
207
+ this.hostId = options.hostId;
208
+ this.hostName = options.hostName || options.hostId;
209
+ this.getLocalOrigin = typeof options.localOrigin === 'function'
210
+ ? options.localOrigin
211
+ : () => options.localOrigin;
212
+ this.inProcessEndpoint = options.inProcessEndpoint || null;
213
+ this.getLaunchToken = options.getLaunchToken || null;
214
+ this.collectIndexInjections = options.collectIndexInjections || this.collectBrowserBoot.bind(this);
215
+ this.frontend = new FrontendAssets({
216
+ allowlist: process.env.DSH_REMOTE_WEB_PLUGINS,
217
+ activeClientPath: options.activeClientPath,
218
+ ...options.frontendOptions,
219
+ });
220
+ this.ownerUserId = options.ownerUserId || '';
221
+ this.webId = options.webId || '';
222
+ this.ownerTenantId = options.ownerTenantId || '';
223
+ this.registrationKey = options.registrationKey || '';
224
+ this.allowInsecureLoopback = options.allowInsecureLoopback === true;
225
+ this.registered = false;
226
+ if (!this.ownerUserId || !this.ownerTenantId || !this.webId || !this.registrationKey || !this.e2eeSecret) {
227
+ throw new Error('Remote owner and host registration are required. Run dsh-remote setup with the updated plugin.');
228
+ }
229
+ this.log = options.log || console.log;
230
+
231
+ this.ws = null;
232
+ this.stopped = false;
233
+ this.reconnectAttempts = 0;
234
+ this.reconnectTimer = null;
235
+ this.connectedPromise = null;
236
+ this.browserCookie = null;
237
+ this.browserCookieGeneration = 0;
238
+
239
+ this.sessions = new Map();
240
+ this.relayLegs = new Map();
241
+ this.leaseMs = options.leaseMs ?? LEASE_MS;
242
+ this.authTimeoutMs = options.authTimeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS;
243
+ this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
244
+ this.sseKeepaliveMs = options.sseKeepaliveMs ?? DEFAULT_SSE_KEEPALIVE_MS;
245
+ this.p2pEnabled = normalizeP2pEnabled(options.p2p ?? process.env.DSH_REMOTE_P2P);
246
+ this.iceServers = this.p2pEnabled ? normalizeStun(options.stun ?? process.env.DSH_REMOTE_STUN) : [];
247
+ this.createPeer = options.createPeer ?? ((config) => {
248
+ const pc = new RTCPeerConnection({
249
+ ...config, iceUseDefaultStunServer: false, iceUseTcp: false, maxMessageSize: 65536,
250
+ });
251
+ if (this.iceServers.length === 0) {
252
+ const guardIce = () => {
253
+ const iceConn = pc.sctp?.dtlsTransport?.iceTransport?.connection ?? pc.dtlsTransports?.[0]?.iceTransport?.connection;
254
+ if (iceConn && typeof iceConn.checkIncoming === 'function' && !iceConn.__dshPrivateOnly) {
255
+ const orig = iceConn.checkIncoming.bind(iceConn);
256
+ iceConn.__dshPrivateOnly = true;
257
+ iceConn.checkIncoming = (msg, addr, proto) => {
258
+ if (!Array.isArray(addr) || !localAddress(String(addr[0] ?? ''))) return;
259
+ return orig(msg, addr, proto);
260
+ };
261
+ }
262
+ };
263
+ const origSetRemote = pc.setRemoteDescription.bind(pc);
264
+ pc.setRemoteDescription = async (...args) => {
265
+ const res = await origSetRemote(...args);
266
+ guardIce();
267
+ return res;
268
+ };
269
+ const origSetLocal = pc.setLocalDescription.bind(pc);
270
+ pc.setLocalDescription = async (...args) => {
271
+ const res = await origSetLocal(...args);
272
+ guardIce();
273
+ return res;
274
+ };
275
+ }
276
+ return pc;
277
+ });
278
+ // `${sessionId}:${streamId}` -> HTTP stream state
279
+ this.httpStreams = new Map();
280
+ this.httpRequestBytes = 0;
281
+ // `${sessionId}:${streamId}` -> WebSocket stream state
282
+ this.wsStreams = new Map();
283
+ }
284
+
285
+ getStatusSnapshot() {
286
+ const now = Date.now();
287
+ const sessions = [];
288
+ for (const [id, session] of this.sessions.entries()) {
289
+ const isP2p = Boolean(session.peer?.current?.promoted);
290
+ sessions.push({
291
+ id,
292
+ sessionId: `${id.slice(0, 8)}…`,
293
+ transport: isP2p ? 'p2p' : 'relay',
294
+ path: isP2p ? 'p2p' : 'relay',
295
+ rttMs: session.rttMs ?? null,
296
+ admittedAt: session.admittedAt,
297
+ connectedDurationMs: Math.max(0, now - (session.admittedAt || now)),
298
+ expiresAt: session.transport?.expiresAt ?? null,
299
+ });
300
+ }
301
+ return {
302
+ running: !this.stopped,
303
+ relayConnected: this.registered,
304
+ hostId: this.hostId,
305
+ hostName: this.hostName,
306
+ p2pEnabled: this.p2pEnabled,
307
+ stunUrls: [...this.iceServers],
308
+ activeStreams: this.httpStreams.size + this.wsStreams.size,
309
+ sessions,
310
+ };
311
+ }
312
+
313
+ async disconnectSession(sessionId, { code = 1000, reason = 'disconnected_by_host' } = {}) {
314
+ const session = this.sessions.get(sessionId);
315
+ if (!session) return false;
316
+ try {
317
+ await session.transport?.control({ type: 'session_closed', code, reason }).catch(() => {});
318
+ } catch {
319
+ // ignore
320
+ }
321
+ this.closeSessionResources(sessionId);
322
+ return true;
323
+ }
324
+
325
+ async disconnectAllSessions({ code = 1000, reason = 'disconnected_by_host' } = {}) {
326
+ const ids = [...this.sessions.keys()];
327
+ await Promise.all(ids.map((id) => this.disconnectSession(id, { code, reason })));
328
+ return ids.length;
329
+ }
330
+
331
+ async rotateE2eeSecret(newSecret) {
332
+ if (!newSecret || typeof newSecret !== 'string') {
333
+ throw new Error('New E2EE secret is required');
334
+ }
335
+ this.e2eeSecret = newSecret;
336
+ const kicked = await this.disconnectAllSessions({ code: 4001, reason: 'key_rotated' });
337
+ return { kicked };
338
+ }
339
+
340
+ updateSettings({ hostName, p2pEnabled, stunUrls, allowedWebPlugins, relayToken } = {}) {
341
+ if (typeof hostName === 'string' && hostName.trim()) {
342
+ this.hostName = hostName.trim().slice(0, 128);
343
+ }
344
+ if (p2pEnabled !== undefined) {
345
+ this.p2pEnabled = normalizeP2pEnabled(p2pEnabled);
346
+ }
347
+ if (stunUrls !== undefined || p2pEnabled !== undefined) {
348
+ this.iceServers = this.p2pEnabled ? normalizeStun(stunUrls ?? this.iceServers) : [];
349
+ }
350
+ if (allowedWebPlugins !== undefined) {
351
+ this.frontend.setAllowlist(allowedWebPlugins);
352
+ }
353
+ if (typeof relayToken === 'string' && relayToken) {
354
+ this.relayToken = relayToken;
355
+ }
356
+ }
357
+
358
+ buildRelayHostWsUrl() {
359
+ const url = new URL('/host', this.relayUrl);
360
+ if (url.protocol === 'https:') url.protocol = 'wss:';
361
+ if (this.allowInsecureLoopback && url.protocol === 'http:' &&
362
+ ['127.0.0.1', '[::1]'].includes(url.hostname)) url.protocol = 'ws:';
363
+ if (url.protocol !== 'wss:' && !(this.allowInsecureLoopback && url.protocol === 'ws:' &&
364
+ ['127.0.0.1', '[::1]'].includes(url.hostname))) {
365
+ throw new Error('A WSS relay is required');
366
+ }
367
+ if (url.username || url.password) throw new Error('Invalid relay origin');
368
+ url.searchParams.set('host_id', this.hostId);
369
+ url.searchParams.set('name', this.hostName);
370
+ return url.href;
371
+ }
372
+
373
+ start() {
374
+ this.stopped = false;
375
+ return this.connectOnce();
376
+ }
377
+
378
+ stop() {
379
+ this.stopped = true;
380
+ if (this.reconnectTimer) {
381
+ clearTimeout(this.reconnectTimer);
382
+ this.reconnectTimer = null;
383
+ }
384
+ this.cleanupActiveStreams();
385
+ if (this.ws) {
386
+ try {
387
+ this.ws.close(1000, 'host shutdown');
388
+ } catch {
389
+ // ignore
390
+ }
391
+ this.ws = null;
392
+ }
393
+ this.registered = false;
394
+ }
395
+
396
+ cleanupActiveStreams() {
397
+ for (const [key, req] of this.httpStreams) this.cancelHttpStream(key, req);
398
+ for (const { socket } of this.wsStreams.values()) socket?.close(1000, 'host shutdown');
399
+ this.wsStreams.clear();
400
+ for (const [id] of this.sessions) this.closeSessionResources(id);
401
+ for (const leg of this.relayLegs.values()) clearTimeout(leg.unauthTimer);
402
+ this.relayLegs.clear();
403
+ }
404
+
405
+ scheduleReconnect() {
406
+ if (this.stopped || this.reconnectTimer) return;
407
+ const delayMs = Math.min(30_000, 1000 * Math.pow(2, Math.min(this.reconnectAttempts, 5)));
408
+ this.reconnectAttempts += 1;
409
+ this.log(`[dsh-remote] Relay disconnected; reconnecting in ${Math.round(delayMs / 1000)}s...`);
410
+ this.reconnectTimer = setTimeout(() => {
411
+ this.reconnectTimer = null;
412
+ if (!this.stopped) {
413
+ this.connectOnce().catch((err) => {
414
+ this.log(`[dsh-remote] Reconnect attempt failed: ${err.message}`);
415
+ });
416
+ }
417
+ }, delayMs);
418
+ }
419
+
420
+ connectOnce() {
421
+ if (this.stopped) return Promise.resolve();
422
+ const wsUrl = this.buildRelayHostWsUrl();
423
+ const headers = { 'Dsh-Host-Registration': this.registrationKey };
424
+ if (this.relayToken) {
425
+ headers.Authorization = `Bearer ${this.relayToken}`;
426
+ }
427
+
428
+ return new Promise((resolve, reject) => {
429
+ let settled = false;
430
+ const ws = new WebSocket(wsUrl, { headers });
431
+ const registrationTimeout = setTimeout(() => ws.close(), 10_000);
432
+ this.registered = false;
433
+ ws.binaryType = 'arraybuffer';
434
+ this.ws = ws;
435
+ this.paceRelay = relayPacer();
436
+
437
+ ws.addEventListener('message', (event) => {
438
+ if (this.ws !== ws || !(event.data instanceof ArrayBuffer)) return;
439
+ let frame;
440
+ try {
441
+ frame = decodeHostFrame(event.data);
442
+ } catch {
443
+ return;
444
+ }
445
+ if (!this.registered) {
446
+ if (frame.sessionId !== 0 || frame.msgType !== MSG_CONTROL_JSON) return;
447
+ let reply;
448
+ try { reply = decodeJSON(frame.payload); } catch { ws.close(); return; }
449
+ if (reply?.type !== 'host_registered' || reply.hostId !== this.hostId || reply.version !== 2) {
450
+ ws.close();
451
+ return;
452
+ }
453
+ clearTimeout(registrationTimeout);
454
+ this.registered = true;
455
+ this.reconnectAttempts = 0;
456
+ this.log(`[dsh-remote] Registered host "${this.hostId}"`);
457
+ settled = true;
458
+ resolve();
459
+ return;
460
+ }
461
+ this.handleFrame(frame).catch((err) => {
462
+ this.log(`[dsh-remote] Frame handler error: ${err.message}`);
463
+ });
464
+ });
465
+
466
+ ws.addEventListener('close', () => {
467
+ clearTimeout(registrationTimeout);
468
+ if (this.ws === ws) {
469
+ this.registered = false;
470
+ this.ws = null;
471
+ for (const [id] of this.relayLegs) this.detachRelay(id);
472
+ if (!this.stopped) {
473
+ this.scheduleReconnect();
474
+ }
475
+ }
476
+ if (!settled) {
477
+ settled = true;
478
+ reject(new Error('Relay closed before secure host registration'));
479
+ }
480
+ });
481
+
482
+ ws.addEventListener('error', () => {
483
+ // close event will trigger reconnect / rejection
484
+ });
485
+ });
486
+ }
487
+
488
+ sendRawFrame(sessionId, streamId, msgType, payload) {
489
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN || !this.registered) return false;
490
+ if (this.ws.bufferedAmount > MAX_BUFFERED_BYTES) {
491
+ this.ws.close(4008);
492
+ return false;
493
+ }
494
+ this.ws.send(encodeHostFrame(sessionId, streamId, msgType, payload));
495
+ return true;
496
+ }
497
+
498
+ sendStreamFrame(sessionId, streamId, msgType, payload, session = this.sessions.get(sessionId), signal) {
499
+ if (!session?.transport || this.sessions.get(sessionId) !== session) {
500
+ return Promise.reject(new Error('DSH session is closed'));
501
+ }
502
+ return session.transport.send(encodeClientFrame(streamId, msgType, payload), signal);
503
+ }
504
+
505
+ detachRelay(id) {
506
+ const leg = this.relayLegs.get(id);
507
+ if (!leg) return;
508
+ clearTimeout(leg.unauthTimer);
509
+ leg.unauthTimer = null;
510
+ this.relayLegs.delete(id);
511
+ const session = leg.session;
512
+ if (session?.leg === leg) {
513
+ session.leg = null;
514
+ session.transport.setRelay(null);
515
+ this.armGrace(session);
516
+ }
517
+ }
518
+
519
+ markLegAuthenticated(leg) {
520
+ clearTimeout(leg.unauthTimer);
521
+ leg.unauthTimer = null;
522
+ if (!leg.relayAuthed) {
523
+ leg.relayAuthed = true;
524
+ this.sendRawFrame(0, 0, MSG_CONTROL_JSON, encodeJSON({ type: 'session_authenticated', sessionId: leg.id }));
525
+ }
526
+ }
527
+
528
+ armGrace(session) {
529
+ clearTimeout(session.grace);
530
+ if (session.leg || session.peer?.current?.promoted || session.transport.closed) return;
531
+ session.grace = setTimeout(() => this.closeSessionResources(session.id), RELAY_GRACE_MS);
532
+ }
533
+
534
+ async bindRelay(session, leg, challenge, renew) {
535
+ const now = Date.now();
536
+ if (challenge !== leg.challenge || (leg.session && leg.session !== session) ||
537
+ !leg.path.ready() || now >= session.transport.expiresAt || now >= leg.expiresAt) return;
538
+ let renewed = false;
539
+ let grantedLeaseMs = Math.max(1, session.transport.expiresAt - now);
540
+ if (renew) {
541
+ if (leg.leaseGranted || leg.session === session) return;
542
+ leg.leaseGranted = true;
543
+ renewed = true;
544
+ grantedLeaseMs = Math.max(1, Math.min(this.leaseMs, leg.expiresAt - now));
545
+ session.transport.renewLease(grantedLeaseMs);
546
+ }
547
+ this.markLegAuthenticated(leg);
548
+ leg.session = session;
549
+ session.leg = leg;
550
+ clearTimeout(session.grace);
551
+ const sent = await session.transport.control({
552
+ type: 'bound_relay_leg', challenge, renewed, leaseMs: grantedLeaseMs,
553
+ }, leg.path);
554
+ if (sent && session.leg === leg && leg.path.ready()) session.transport.setRelay(leg.path);
555
+ }
556
+
557
+ authorizeSession(msg) {
558
+ return msg.userId === this.ownerUserId &&
559
+ msg.tenantId === this.ownerTenantId && msg.webId === this.webId;
560
+ }
561
+
562
+ resolveLocalEndpoint() {
563
+ const inProcess = typeof this.inProcessEndpoint === 'function'
564
+ ? this.inProcessEndpoint()
565
+ : this.inProcessEndpoint;
566
+ return resolvePinnedEndpoint(this.getLocalOrigin(), inProcess);
567
+ }
568
+
569
+ async ensureBrowserCookieEntry(endpoint, forceRefresh) {
570
+ if (!this.getLaunchToken) return null;
571
+ const cacheKey = `${endpoint.connectHost}:${endpoint.connectPort}:${endpoint.authorityOrigin}`;
572
+ const cached = this.browserCookie;
573
+ if (cached?.key === cacheKey && !forceRefresh) return cached;
574
+ const token = this.getLaunchToken();
575
+ if (!token) return null;
576
+ const path = '/?' + new URLSearchParams({ token }).toString();
577
+ const resp = await pinnedFetch(endpoint, path, {
578
+ method: 'GET',
579
+ signal: AbortSignal.timeout(10_000),
580
+ headers: { Origin: endpoint.authorityOrigin, 'accept-encoding': 'identity' },
581
+ });
582
+ const cookie = parseFirstCookiePair(getSetCookieHeaders(resp.headers));
583
+ if (!cookie) {
584
+ throw new Error(`Failed to obtain local DSH browser cookie (HTTP ${resp.status})`);
585
+ }
586
+ const entry = Object.freeze({
587
+ key: cacheKey,
588
+ value: cookie,
589
+ generation: ++this.browserCookieGeneration,
590
+ });
591
+ this.browserCookie = entry;
592
+ return entry;
593
+ }
594
+
595
+ async ensureBrowserCookie(endpoint, forceRefresh) {
596
+ return (await this.ensureBrowserCookieEntry(endpoint, forceRefresh))?.value || '';
597
+ }
598
+
599
+ invalidateBrowserCookie(entryOrGeneration) {
600
+ if (entryOrGeneration === undefined || entryOrGeneration === null) return;
601
+ if (typeof entryOrGeneration === 'object') {
602
+ if (this.browserCookie === entryOrGeneration) {
603
+ this.browserCookie = null;
604
+ }
605
+ return;
606
+ }
607
+ if (this.browserCookie?.generation === entryOrGeneration) {
608
+ this.browserCookie = null;
609
+ }
610
+ }
611
+
612
+ async collectBrowserBoot() {
613
+ const endpoint = this.resolveLocalEndpoint();
614
+ const cookie = await this.ensureBrowserCookie(endpoint, false);
615
+ const response = await pinnedFetch(endpoint, '/', {
616
+ headers: { 'accept-encoding': 'identity', ...(cookie ? { cookie } : {}) },
617
+ signal: AbortSignal.timeout(10_000),
618
+ });
619
+ if (!response.ok) throw new Error('DSH could not supply the active browser profile');
620
+ const html = await response.text();
621
+ const match = /globalThis\["__DSH_BOOT__"\]\s*=\s*([\s\S]*?)<\/script>/u.exec(html);
622
+ return match ? [{ kind: 'global', name: '__DSH_BOOT__', value: JSON.parse(match[1]) }] : [];
623
+ }
624
+
625
+ async mintOperatorCookie(endpoint) {
626
+ if (!this.getLaunchToken) return '';
627
+ const token = this.getLaunchToken();
628
+ if (!token) return '';
629
+ const path = '/connect?' + new URLSearchParams({ interactions: 'answer', token }).toString();
630
+ const resp = await pinnedFetch(endpoint, path, {
631
+ method: 'GET',
632
+ signal: AbortSignal.timeout(10_000),
633
+ headers: { Origin: endpoint.authorityOrigin, 'accept-encoding': 'identity' },
634
+ });
635
+ const cookie = parseFirstCookiePair(getSetCookieHeaders(resp.headers));
636
+ if (!cookie) {
637
+ throw new Error(`Failed to obtain local DSH operator cookie (HTTP ${resp.status})`);
638
+ }
639
+ return cookie;
640
+ }
641
+
642
+ async handleE2eeClientHello(leg, payload) {
643
+ if (!leg?.allowed || leg.session || leg.leaseGranted || leg.handshaking ||
644
+ Date.now() >= leg.expiresAt || payload.length > 1024 || ++leg.attempts > 4) return;
645
+ leg.handshaking = true;
646
+ try {
647
+ const hello = decodeJSON(payload);
648
+ if (!/^[A-Za-z0-9_-]{22}$/u.test(hello.logicalSessionId) ||
649
+ hello.capabilities !== MULTIPATH_CAPABILITIES || this.sessions.has(hello.logicalSessionId)) {
650
+ const error = new Error('Unsupported DSH Remote protocol; update the app and host together');
651
+ error.code = 'INCOMPATIBLE';
652
+ throw error;
653
+ }
654
+ if (this.sessions.size >= MAX_STREAMS) throw new Error('DSH remote session limit');
655
+ const id = hello.logicalSessionId;
656
+ const { hostHelloPayload, cipher } = await respondHostHandshake(this.e2eeSecret, payload, {
657
+ hostId: this.hostId, webId: this.webId, tenantId: this.ownerTenantId, ownerUserId: this.ownerUserId,
658
+ logicalSessionId: id,
659
+ });
660
+ const initialLeaseMs = leg.expiresAt - Date.now();
661
+ if (!leg.path.ready() || this.sessions.has(id) || initialLeaseMs <= 0) return;
662
+ leg.leaseGranted = true;
663
+ this.markLegAuthenticated(leg);
664
+ const session = { id, userId: this.ownerUserId, allowed: true, leg, admittedAt: Date.now(), rttMs: null };
665
+ session.transport = new MultipathSession({
666
+ cipher,
667
+ leaseMs: this.leaseMs,
668
+ initialLeaseMs,
669
+ onData: (bytes) => this.dispatchInnerFrame(id, session, decodeClientFrame(bytes)),
670
+ onControl: (message, path) => this.handleSessionControl(session, message, path),
671
+ onClose: () => this.closeSessionResources(id),
672
+ onStall: (path) => path?.close(),
673
+ });
674
+ session.peer = this.p2pEnabled ? new PeerPath(session.transport, {
675
+ createPeer: this.createPeer,
676
+ sendChannel: (channel, bytes) => channel.send(Buffer.from(bytes)),
677
+ initiator: false,
678
+ urls: this.iceServers,
679
+ signalPath: () => session.leg?.path,
680
+ onPath: () => this.armGrace(session),
681
+ }) : null;
682
+ this.sessions.set(id, session);
683
+ leg.session = session;
684
+ session.transport.setRelay(leg.path);
685
+ this.sendRawFrame(leg.id, 0, MSG_E2EE_HOST_HELLO, hostHelloPayload);
686
+ void session.transport.control({ type: 'lease_sync', leaseMs: initialLeaseMs }, leg.path).catch(() => {});
687
+ } catch (err) {
688
+ this.sendRawFrame(leg.id, 0, MSG_E2EE_ERROR, encodeJSON({
689
+ code: err.code === 'AUTH_FAILED' ? 'AUTH_FAILED' : err.code === 'INCOMPATIBLE' ? 'INCOMPATIBLE' : 'HANDSHAKE_FAILED',
690
+ message: err.code === 'INCOMPATIBLE' ? 'Host and app versions must match' : 'E2EE handshake rejected',
691
+ }));
692
+ } finally {
693
+ leg.handshaking = false;
694
+ }
695
+ }
696
+
697
+ async handleSessionControl(session, message, path) {
698
+ if (message?.type === 'bind_relay_leg') {
699
+ const leg = path.leg;
700
+ if (leg?.allowed) await this.bindRelay(session, leg, message.challenge, false);
701
+ } else if (message?.type === 'lease_renew') {
702
+ const leg = path.leg;
703
+ if (leg?.allowed) await this.bindRelay(session, leg, message.challenge, true);
704
+ } else if (message?.type === 'rtt_ping' && Number.isFinite(message.ts)) {
705
+ await session.transport?.control({ type: 'rtt_pong', ts: message.ts }, path).catch(() => {});
706
+ if (Number.isFinite(message.lastRttMs) && message.lastRttMs >= 0) {
707
+ session.rttMs = Math.round(message.lastRttMs);
708
+ }
709
+ } else if (message?.type === 'close_session') {
710
+ this.closeSessionResources(session.id);
711
+ } else if (session.peer) {
712
+ await session.peer.handle(message, path);
713
+ }
714
+ }
715
+
716
+ async handleFrame({ sessionId, streamId, msgType, payload }) {
717
+ if (sessionId === 0 && msgType === MSG_CONTROL_JSON) {
718
+ const message = decodeJSON(payload);
719
+ if (!Number.isInteger(message?.sessionId) || message.sessionId <= 0 || message.sessionId > 0xffffffff) return;
720
+ const id = message.sessionId;
721
+ if (message.type === 'close_session') {
722
+ this.detachRelay(id);
723
+ return;
724
+ }
725
+ if (message.type !== 'open_session' || message.hostId !== this.hostId ||
726
+ this.relayLegs.has(id) || this.relayLegs.size >= MAX_STREAMS ||
727
+ !/^[A-Za-z0-9_-]{22}$/u.test(message.challenge)) return;
728
+ const now = Date.now();
729
+ const relayRemaining = Number.isSafeInteger(message.remainingMs) && message.remainingMs >= 0
730
+ ? Math.min(this.leaseMs, message.remainingMs)
731
+ : this.leaseMs;
732
+ if (relayRemaining <= 0) return;
733
+ const socket = this.ws;
734
+ const leg = {
735
+ id,
736
+ challenge: message.challenge,
737
+ allowed: this.authorizeSession(message),
738
+ attempts: 0,
739
+ expiresAt: now + relayRemaining,
740
+ leaseGranted: false,
741
+ relayAuthed: false,
742
+ unauthTimer: this.authTimeoutMs > 0 ? setTimeout(() => this.detachRelay(id), this.authTimeoutMs) : null,
743
+ };
744
+ leg.path = createPath({
745
+ send: (type, bytes) => {
746
+ if (!this.paceRelay(type)) return false;
747
+ if (!this.sendRawFrame(id, 0, type, bytes)) throw new Error('Relay unavailable');
748
+ return true;
749
+ },
750
+ ready: () => this.ws === socket && socket?.readyState === WebSocket.OPEN && this.relayLegs.get(id) === leg,
751
+ bufferedAmount: () => socket?.bufferedAmount ?? 0,
752
+ close: () => this.detachRelay(id),
753
+ });
754
+ leg.path.leg = leg;
755
+ this.relayLegs.set(id, leg);
756
+ return;
757
+ }
758
+ const leg = this.relayLegs.get(sessionId);
759
+ if (!leg?.allowed) return;
760
+ if (streamId !== 0) {
761
+ if (msgType === MSG_HTTP_REQ_HEAD && !leg.session) {
762
+ this.sendRawFrame(leg.id, streamId, MSG_HTTP_RES_HEAD, encodeJSON({ status: 403 }));
763
+ this.sendRawFrame(leg.id, streamId, MSG_HTTP_RES_BODY, 'E2EE handshake required');
764
+ this.sendRawFrame(leg.id, streamId, MSG_HTTP_RES_END);
765
+ }
766
+ return;
767
+ }
768
+ if (msgType === MSG_E2EE_CLIENT_HELLO) return this.handleE2eeClientHello(leg, payload);
769
+ if (msgType === MSG_E2EE_CTRL && payload.length >= 40) {
770
+ const id = base64UrlEncode(payload.subarray(0, 16));
771
+ const session = this.sessions.get(id);
772
+ if (!session && !leg.session) {
773
+ this.sendRawFrame(leg.id, 0, MSG_E2EE_ERROR, encodeJSON({ code: 'GENERATION_UNKNOWN' }));
774
+ } else {
775
+ session?.transport.receive(msgType, payload, leg.path);
776
+ }
777
+ } else if (msgType === MSG_E2EE_BOX) {
778
+ leg.session?.transport.receive(msgType, payload, leg.path);
779
+ }
780
+ }
781
+
782
+ dispatchInnerFrame(sessionId, session, { streamId, msgType, payload }) {
783
+ if (!session.allowed || streamId === 0) throw new Error('Invalid application stream');
784
+ const key = `${sessionId}:${streamId}`;
785
+
786
+ if (msgType === MSG_HTTP_REQ_HEAD) {
787
+ if (this.httpStreams.has(key) || this.wsStreams.has(key)) throw new Error('Duplicate stream');
788
+ if (this.httpStreams.size + this.wsStreams.size >= MAX_STREAMS) {
789
+ this.sendHttpError(sessionId, streamId, 429, 'Remote stream limit reached');
790
+ return;
791
+ }
792
+ let head;
793
+ try {
794
+ head = decodeJSON(payload);
795
+ } catch {
796
+ this.sendHttpError(sessionId, streamId, 400, 'Invalid HTTP head JSON');
797
+ return;
798
+ }
799
+ const hasWindow = Number.isInteger(head.windowBytes) && head.windowBytes > 0;
800
+ const initialWindow = hasWindow
801
+ ? Math.min(MAX_WINDOW_BYTES, Math.max(MIN_WINDOW_BYTES, head.windowBytes))
802
+ : 0;
803
+
804
+ const entry = {
805
+ head,
806
+ chunks: [],
807
+ chunkCount: 0,
808
+ totalBytes: 0,
809
+ executing: false,
810
+ aborted: false,
811
+ flowControl: hasWindow,
812
+ initialWindowBytes: initialWindow,
813
+ sendWindowBytes: initialWindow,
814
+ windowPaused: false,
815
+ windowWaiter: null,
816
+ windowMinBytes: 1,
817
+ sseKeepaliveTimer: null,
818
+ abortController: new AbortController(),
819
+ timer: null,
820
+ refreshTimer: null,
821
+ };
822
+ entry.refreshTimer = () => {
823
+ clearTimeout(entry.timer);
824
+ if (entry.aborted) return;
825
+ // Exempt backpressure-paused streams from idle timeout while the underlying session is alive
826
+ if (entry.windowPaused && this.sessions.get(sessionId) === session && !session.transport?.closed) {
827
+ return;
828
+ }
829
+ entry.timer = setTimeout(() => {
830
+ const cur = this.httpStreams.get(key);
831
+ if (cur !== entry) return;
832
+ if (entry.windowPaused && this.sessions.get(sessionId) === session && !session.transport?.closed) {
833
+ return;
834
+ }
835
+ this.cancelHttpStream(key, entry);
836
+ if (entry.executing) {
837
+ void this.sendStreamFrame(sessionId, streamId, MSG_HTTP_ABORT, 'DSH request timed out', session).catch(() => {});
838
+ } else {
839
+ this.sendHttpError(sessionId, streamId, 504, 'DSH request timed out');
840
+ }
841
+ }, this.requestTimeoutMs);
842
+ };
843
+ entry.refreshTimer();
844
+ this.httpStreams.set(key, entry);
845
+ return;
846
+ }
847
+
848
+ if (msgType === MSG_HTTP_REQ_BODY) {
849
+ const entry = this.httpStreams.get(key);
850
+ if (!entry) return;
851
+ if (entry.executing) throw new Error('Body after request end');
852
+ if (payload.byteLength === 0) return;
853
+ entry.refreshTimer();
854
+ const totalBytes = entry.totalBytes + payload.byteLength;
855
+ if (++entry.chunkCount > MAX_REQUEST_CHUNKS || totalBytes > MAX_REQUEST_BYTES ||
856
+ this.httpRequestBytes + payload.byteLength > MAX_HOST_REQUEST_BYTES) {
857
+ this.cancelHttpStream(key, entry);
858
+ this.sendHttpError(sessionId, streamId, 413, 'DSH request body is too large');
859
+ return;
860
+ }
861
+ this.httpRequestBytes += payload.byteLength;
862
+ entry.totalBytes = totalBytes;
863
+ entry.chunks.push(Buffer.from(payload));
864
+ return;
865
+ }
866
+
867
+ if (msgType === MSG_HTTP_REQ_END) {
868
+ const entry = this.httpStreams.get(key);
869
+ if (!entry || entry.aborted) return;
870
+ if (entry.executing) throw new Error('Duplicate request end');
871
+ entry.executing = true;
872
+ entry.refreshTimer();
873
+ void this.executeHttpStream(sessionId, streamId, session, entry).catch(() => {
874
+ if (!entry.aborted) this.sendHttpError(sessionId, streamId, 502, 'Local DSH request failed');
875
+ }).finally(() => {
876
+ clearTimeout(entry.timer);
877
+ clearTimeout(entry.sseKeepaliveTimer);
878
+ if (entry.windowWaiter) {
879
+ const w = entry.windowWaiter;
880
+ entry.windowWaiter = null;
881
+ w();
882
+ }
883
+ if (this.httpStreams.get(key) === entry) {
884
+ this.httpStreams.delete(key);
885
+ this.httpRequestBytes -= entry.totalBytes;
886
+ }
887
+ });
888
+ return;
889
+ }
890
+
891
+ if (msgType === MSG_HTTP_RES_WINDOW) {
892
+ const entry = this.httpStreams.get(key);
893
+ if (!entry || !entry.flowControl || entry.aborted) return;
894
+ let credit;
895
+ try {
896
+ credit = decodeWindowUpdate(payload);
897
+ } catch {
898
+ return;
899
+ }
900
+ if (credit <= 0) return;
901
+ const room = Math.max(0, entry.initialWindowBytes - entry.sendWindowBytes);
902
+ if (room > 0) {
903
+ entry.sendWindowBytes += Math.min(credit, room);
904
+ }
905
+ entry.refreshTimer();
906
+ if (entry.windowWaiter && entry.sendWindowBytes >= (entry.windowMinBytes || 1)) {
907
+ const wake = entry.windowWaiter;
908
+ entry.windowWaiter = null;
909
+ wake();
910
+ }
911
+ return;
912
+ }
913
+
914
+ if (msgType === MSG_HTTP_ABORT) {
915
+ const entry = this.httpStreams.get(key);
916
+ if (entry) this.cancelHttpStream(key, entry);
917
+ return;
918
+ }
919
+
920
+ if (msgType === MSG_WS_OPEN) {
921
+ if (this.wsStreams.has(key) || this.httpStreams.has(key)) throw new Error('Duplicate stream');
922
+ if (this.httpStreams.size + this.wsStreams.size >= MAX_STREAMS) {
923
+ void this.sendStreamFrame(sessionId, streamId, MSG_WS_CLOSE, encodeJSON({ code: 1008, reason: 'Remote stream limit reached', wasClean: false }), session).catch(() => {});
924
+ return;
925
+ }
926
+ let info;
927
+ try {
928
+ info = decodeJSON(payload);
929
+ } catch {
930
+ void this.sendStreamFrame(sessionId, streamId, MSG_WS_CLOSE, encodeJSON({ code: 1002, reason: 'Invalid WS open frame', wasClean: false })).catch(() => {});
931
+ return;
932
+ }
933
+ const entry = { socket: null, fragments: new FragmentReader(), sendQueue: Promise.resolve() };
934
+ this.wsStreams.set(key, entry);
935
+ void this.openLocalWebSocket(sessionId, streamId, session, key, entry, info.path || '/api/remote.mux').catch(() => {
936
+ if (this.wsStreams.get(key) !== entry) return;
937
+ this.wsStreams.delete(key);
938
+ void this.sendStreamFrame(sessionId, streamId, MSG_WS_CLOSE, encodeJSON({
939
+ code: 1008, reason: 'Local DSH WebSocket rejected', wasClean: false,
940
+ }), session).catch(() => {});
941
+ });
942
+ return;
943
+ }
944
+
945
+ if (msgType === MSG_WS_DATA_TEXT || msgType === MSG_WS_DATA_BIN) {
946
+ const entry = this.wsStreams.get(key);
947
+ const sock = entry?.socket;
948
+ if (!sock || sock.readyState !== WebSocket.OPEN) return;
949
+ const bytes = entry.fragments.push(msgType, payload);
950
+ if (!bytes) return;
951
+ if (sock.bufferedAmount + bytes.length > MAX_BUFFERED_BYTES * 4) {
952
+ sock.close(4008, 'Remote receive queue exceeded');
953
+ return;
954
+ }
955
+ sock.send(msgType === MSG_WS_DATA_TEXT ? new TextDecoder().decode(bytes) : bytes);
956
+ return;
957
+ }
958
+
959
+ if (msgType === MSG_WS_CLOSE) {
960
+ const entry = this.wsStreams.get(key);
961
+ if (entry) {
962
+ this.wsStreams.delete(key);
963
+ let code = 1000;
964
+ let reason = '';
965
+ if (payload.byteLength > 0) {
966
+ try {
967
+ const parsed = decodeJSON(payload);
968
+ if (typeof parsed.code === 'number') code = parsed.code;
969
+ if (typeof parsed.reason === 'string') reason = parsed.reason;
970
+ } catch {
971
+ // ignore
972
+ }
973
+ }
974
+ try { entry.socket?.close(code, reason); }
975
+ catch { entry.socket?.close(1000); }
976
+ }
977
+ }
978
+ }
979
+
980
+ cancelHttpStream(key, entry) {
981
+ if (this.httpStreams.get(key) !== entry) return;
982
+ this.httpStreams.delete(key);
983
+ this.httpRequestBytes -= entry.totalBytes;
984
+ clearTimeout(entry.timer);
985
+ clearTimeout(entry.sseKeepaliveTimer);
986
+ entry.aborted = true;
987
+ entry.abortController.abort();
988
+ if (entry.windowWaiter) {
989
+ const wake = entry.windowWaiter;
990
+ entry.windowWaiter = null;
991
+ wake();
992
+ }
993
+ }
994
+
995
+ closeSessionStreamsOnly(sessionId) {
996
+ const prefix = `${sessionId}:`;
997
+ for (const [k, req] of this.httpStreams.entries()) {
998
+ if (k.startsWith(prefix)) {
999
+ this.cancelHttpStream(k, req);
1000
+ }
1001
+ }
1002
+ for (const [k, sock] of this.wsStreams.entries()) {
1003
+ if (k.startsWith(prefix)) {
1004
+ this.wsStreams.delete(k);
1005
+ sock.socket?.close(1000, 'session closed');
1006
+ }
1007
+ }
1008
+ }
1009
+
1010
+ closeSessionResources(sessionId) {
1011
+ const session = this.sessions.get(sessionId);
1012
+ if (!session) return;
1013
+ this.sessions.delete(sessionId);
1014
+ clearTimeout(session.grace);
1015
+ session.transport.close();
1016
+ if (session.peer) void session.peer.stop().catch(() => {});
1017
+ for (const [id, leg] of this.relayLegs) {
1018
+ if (leg.session === session) this.detachRelay(id);
1019
+ }
1020
+ this.closeSessionStreamsOnly(sessionId);
1021
+ }
1022
+
1023
+ sendHttpError(sessionId, streamId, status, message, { forcePlaintext = false } = {}) {
1024
+ const send = forcePlaintext
1025
+ ? (msgType, payload) => this.sendRawFrame(sessionId, streamId, msgType, payload)
1026
+ : (msgType, payload) => { void this.sendStreamFrame(sessionId, streamId, msgType, payload).catch(() => {}); };
1027
+ send(MSG_HTTP_RES_HEAD, encodeJSON({
1028
+ status,
1029
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
1030
+ }));
1031
+ send(MSG_HTTP_RES_BODY, message);
1032
+ send(MSG_HTTP_RES_END);
1033
+ }
1034
+
1035
+ async rejectRoute(send) {
1036
+ await send(MSG_HTTP_RES_HEAD, encodeJSON({ status: 404, headers: {} }));
1037
+ await send(MSG_HTTP_RES_END);
1038
+ }
1039
+
1040
+ async rejectForbiddenRoute(send) {
1041
+ await send(MSG_HTTP_RES_HEAD, encodeJSON({
1042
+ status: 403,
1043
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
1044
+ }));
1045
+ await send(MSG_HTTP_RES_BODY, JSON.stringify({ ok: false, error: 'Admin routes are forbidden over remote tunnel' }));
1046
+ await send(MSG_HTTP_RES_END);
1047
+ }
1048
+
1049
+ async sendAsset(send, method, asset, wire, signal) {
1050
+ signal.throwIfAborted();
1051
+ await send(MSG_HTTP_RES_HEAD, encodeJSON({
1052
+ status: 200,
1053
+ headers: {
1054
+ 'content-type': asset.meta.mimeType,
1055
+ 'content-encoding': wire.encoding,
1056
+ 'content-length': String(wire.bytes.length),
1057
+ 'cache-control': 'no-store',
1058
+ },
1059
+ }), signal);
1060
+ if (method !== 'HEAD') {
1061
+ for (let offset = 0; offset < wire.bytes.length; offset += CHUNK_SIZE) {
1062
+ signal.throwIfAborted();
1063
+ await send(MSG_HTTP_RES_BODY, wire.bytes.subarray(offset, offset + CHUNK_SIZE), signal);
1064
+ }
1065
+ }
1066
+ await send(MSG_HTTP_RES_END, undefined, signal);
1067
+ }
1068
+
1069
+ async executeHttpStream(sessionId, streamId, session, entry) {
1070
+ const { head, chunks, abortController } = entry;
1071
+ const method = String(head.method || 'GET').toUpperCase();
1072
+ const send = (type, payload, signal = abortController.signal) =>
1073
+ this.sendStreamFrame(sessionId, streamId, type, payload, session, signal);
1074
+
1075
+ if (head.path !== undefined && typeof head.path !== 'string') {
1076
+ await this.rejectRoute(send);
1077
+ return;
1078
+ }
1079
+ const pathAndQuery = head.path ?? '/';
1080
+ const route = classifyHttpRoute(pathAndQuery);
1081
+ if (!route) {
1082
+ await this.rejectRoute(send);
1083
+ return;
1084
+ }
1085
+ if (route.kind === 'forbidden') {
1086
+ await this.rejectForbiddenRoute(send);
1087
+ return;
1088
+ }
1089
+ if (route.kind === 'internal') {
1090
+ const { parsed } = route;
1091
+ if (!['GET', 'HEAD'].includes(method)) return this.rejectRoute(send);
1092
+ const signal = AbortSignal.any([abortController.signal, AbortSignal.timeout(15_000)]);
1093
+ if (parsed.pathname.endsWith('bootstrap.json') && !parsed.search) {
1094
+ const rows = await this.collectIndexInjections();
1095
+ const snapshot = await this.frontend.prepare(rows);
1096
+ signal.throwIfAborted();
1097
+ session.assetManifest = snapshot;
1098
+ const bytes = Buffer.from(JSON.stringify({
1099
+ ...snapshot.manifest,
1100
+ p2pEnabled: this.p2pEnabled,
1101
+ iceServers: this.iceServers,
1102
+ theme: extractThemeFromInjections(rows),
1103
+ host: { hostId: this.hostId, hostName: this.hostName },
1104
+ session: { role: 'owner', userId: this.ownerUserId, tenantId: this.ownerTenantId },
1105
+ }));
1106
+ const asset = { bytes, meta: { mimeType: 'application/json' } };
1107
+ const wire = await this.frontend.representation(asset, head.headers?.['x-dsh-encoding'] === 'gzip', signal);
1108
+ return this.sendAsset(send, method, asset, wire, signal).catch(() =>
1109
+ send(MSG_HTTP_ABORT, 'Frontend transfer failed'));
1110
+ }
1111
+ if (parsed.pathname.endsWith('/asset') && parsed.searchParams.size === 2 &&
1112
+ parsed.searchParams.getAll('key').length === 1 && parsed.searchParams.getAll('rev').length === 1) {
1113
+ const asset = session.assetManifest?.resources.get(parsed.searchParams.get('key'));
1114
+ if (asset?.meta.rev === parsed.searchParams.get('rev') && session.assetManifest === this.frontend.snapshot) {
1115
+ const wire = await this.frontend.representation(asset, head.headers?.['x-dsh-encoding'] === 'gzip', signal);
1116
+ return this.sendAsset(send, method, asset, wire, signal).catch(() =>
1117
+ send(MSG_HTTP_ABORT, 'Frontend transfer failed'));
1118
+ }
1119
+ }
1120
+ return this.rejectRoute(send);
1121
+ }
1122
+ if (!ALLOWED_HTTP_METHODS.has(method)) {
1123
+ return this.rejectRoute(send);
1124
+ }
1125
+
1126
+ let endpoint;
1127
+ let targetUrl;
1128
+ try {
1129
+ endpoint = this.resolveLocalEndpoint();
1130
+ targetUrl = resolvePinnedTarget(endpoint, pathAndQuery);
1131
+ } catch {
1132
+ await send(MSG_HTTP_RES_HEAD, encodeJSON({ status: 400, headers: {} }));
1133
+ await send(MSG_HTTP_RES_END);
1134
+ return;
1135
+ }
1136
+ const reqBody = chunks.length > 0 ? Buffer.concat(chunks) : undefined;
1137
+ chunks.length = 0;
1138
+ const incoming = new Headers(head.headers || {});
1139
+ const nominated = nominatedConnectionHeaders(incoming);
1140
+ const headers = new Headers();
1141
+ for (const [name, value] of incoming) {
1142
+ if (REQUEST_STRIPPED_HEADERS.has(name) || nominated.has(name) ||
1143
+ name.startsWith('x-forwarded-') || name.startsWith('tiana-caller-') || name.startsWith('x-tiana-')) continue;
1144
+ headers.set(name, value);
1145
+ }
1146
+ headers.set('origin', targetUrl.origin);
1147
+ headers.set('x-dsh-remote-tunnel', '1');
1148
+ if (String(headers.get('accept') || '').toLowerCase().includes('text/event-stream')) {
1149
+ headers.set('accept-encoding', 'identity');
1150
+ }
1151
+
1152
+ const doFetch = async (forceCookieRefresh) => {
1153
+ const cookieEntry = await this.ensureBrowserCookieEntry(endpoint, forceCookieRefresh);
1154
+ abortController.signal.throwIfAborted();
1155
+ if (cookieEntry?.value) headers.set('cookie', cookieEntry.value);
1156
+ const resp = await pinnedFetch(endpoint, pathAndQuery, {
1157
+ method,
1158
+ headers,
1159
+ body: method === 'GET' || method === 'HEAD' ? undefined : reqBody,
1160
+ signal: abortController.signal,
1161
+ });
1162
+ return { resp, cookieEntry };
1163
+ };
1164
+
1165
+ const waitForWindow = async (minBytes = 1) => {
1166
+ while (entry.flowControl && entry.sendWindowBytes < minBytes) {
1167
+ abortController.signal.throwIfAborted();
1168
+ entry.windowPaused = true;
1169
+ entry.windowMinBytes = minBytes;
1170
+ clearTimeout(entry.timer);
1171
+ await new Promise((resolve) => {
1172
+ const onAbort = () => {
1173
+ if (entry.windowWaiter === wake) entry.windowWaiter = null;
1174
+ resolve();
1175
+ };
1176
+ const wake = () => {
1177
+ abortController.signal.removeEventListener('abort', onAbort);
1178
+ resolve();
1179
+ };
1180
+ entry.windowWaiter = wake;
1181
+ abortController.signal.addEventListener('abort', onAbort, { once: true });
1182
+ });
1183
+ entry.windowPaused = false;
1184
+ entry.windowMinBytes = 1;
1185
+ entry.refreshTimer();
1186
+ abortController.signal.throwIfAborted();
1187
+ }
1188
+ };
1189
+
1190
+ try {
1191
+ let { resp, cookieEntry } = await doFetch(false);
1192
+ if (resp.status === 401 && this.getLaunchToken) {
1193
+ if (method === 'GET' || method === 'HEAD') {
1194
+ await resp.body?.cancel().catch(() => {});
1195
+ ({ resp, cookieEntry } = await doFetch(true));
1196
+ } else {
1197
+ this.invalidateBrowserCookie(cookieEntry);
1198
+ }
1199
+ }
1200
+
1201
+ entry.refreshTimer();
1202
+
1203
+ const resNominated = nominatedConnectionHeaders(resp.headers);
1204
+ const resHeaders = {};
1205
+ resp.headers.forEach((value, key) => {
1206
+ const lower = key.toLowerCase();
1207
+ if (lower === 'set-cookie' || SHARED_HOP_BY_HOP_HEADERS.has(lower) || resNominated.has(lower)) return;
1208
+ resHeaders[lower] = value;
1209
+ });
1210
+
1211
+ const isSse = resp.status === 200 && isEventStreamContentType(resHeaders['content-type']);
1212
+ if (isSse) {
1213
+ // Stripping Content-Length because keepalive comments may be injected at line boundaries
1214
+ delete resHeaders['content-length'];
1215
+ }
1216
+ let reader;
1217
+ let streamDone = false;
1218
+ let writeChain = Promise.resolve();
1219
+
1220
+ // Track SSE UTF-8 multi-byte boundaries & line boundaries so keepalive NEVER splits a line or UTF-8 char
1221
+ let sseAtLineBoundary = true;
1222
+ let sseUtf8Pending = 0;
1223
+ let ssePendingKeepalive = false;
1224
+
1225
+ const advanceSseBoundary = (bytes) => {
1226
+ for (let i = 0; i < bytes.byteLength; i += 1) {
1227
+ const b = bytes[i];
1228
+ if (sseUtf8Pending > 0) {
1229
+ if ((b & 0xc0) === 0x80) {
1230
+ sseUtf8Pending -= 1;
1231
+ continue;
1232
+ }
1233
+ sseUtf8Pending = 0;
1234
+ }
1235
+ if (b < 0x80) {
1236
+ sseUtf8Pending = 0;
1237
+ } else if ((b & 0xe0) === 0xc0) {
1238
+ sseUtf8Pending = 1;
1239
+ } else if ((b & 0xf0) === 0xe0) {
1240
+ sseUtf8Pending = 2;
1241
+ } else if ((b & 0xf8) === 0xf0) {
1242
+ sseUtf8Pending = 3;
1243
+ } else {
1244
+ sseUtf8Pending = 0;
1245
+ }
1246
+ }
1247
+ if (bytes.byteLength > 0) {
1248
+ sseAtLineBoundary = sseUtf8Pending === 0 && bytes[bytes.byteLength - 1] === 0x0a;
1249
+ }
1250
+ };
1251
+
1252
+ const sendKeepaliveNow = async () => {
1253
+ if (streamDone || entry.aborted) return;
1254
+ await waitForWindow(SSE_KEEPALIVE_BYTES.byteLength);
1255
+ if (streamDone || entry.aborted) return;
1256
+ if (entry.flowControl) {
1257
+ entry.sendWindowBytes -= SSE_KEEPALIVE_BYTES.byteLength;
1258
+ }
1259
+ entry.refreshTimer();
1260
+ await send(MSG_HTTP_RES_BODY, SSE_KEEPALIVE_BYTES);
1261
+ sseAtLineBoundary = true;
1262
+ sseUtf8Pending = 0;
1263
+ ssePendingKeepalive = false;
1264
+ };
1265
+
1266
+ const scheduleKeepalive = () => {
1267
+ clearTimeout(entry.sseKeepaliveTimer);
1268
+ if (!isSse || streamDone || entry.aborted || this.sseKeepaliveMs <= 0) return;
1269
+ entry.sseKeepaliveTimer = setTimeout(() => {
1270
+ if (streamDone || entry.aborted) return;
1271
+ writeChain = writeChain.then(async () => {
1272
+ if (streamDone || entry.aborted) return;
1273
+ if (!sseAtLineBoundary || sseUtf8Pending > 0) {
1274
+ // Defer keepalive until upstream finishes the current line / UTF-8 sequence
1275
+ ssePendingKeepalive = true;
1276
+ entry.refreshTimer();
1277
+ return;
1278
+ }
1279
+ await sendKeepaliveNow();
1280
+ scheduleKeepalive();
1281
+ }).catch(() => {});
1282
+ }, this.sseKeepaliveMs);
1283
+ };
1284
+
1285
+ try {
1286
+ const resHeadObj = {
1287
+ status: resp.status,
1288
+ statusText: resp.statusText,
1289
+ headers: resHeaders,
1290
+ ...(entry.flowControl ? { flowControl: true } : {}),
1291
+ };
1292
+ await send(MSG_HTTP_RES_HEAD, encodeJSON(resHeadObj));
1293
+
1294
+ if (resp.body && method !== 'HEAD') {
1295
+ reader = resp.body.getReader();
1296
+ scheduleKeepalive();
1297
+ while (true) {
1298
+ abortController.signal.throwIfAborted();
1299
+ await waitForWindow(1);
1300
+ const { done, value } = await reader.read();
1301
+ if (done) {
1302
+ streamDone = true;
1303
+ break;
1304
+ }
1305
+ scheduleKeepalive();
1306
+ let offset = 0;
1307
+ while (offset < value.byteLength) {
1308
+ await waitForWindow(1);
1309
+ abortController.signal.throwIfAborted();
1310
+ const maxChunk = entry.flowControl
1311
+ ? Math.min(CHUNK_SIZE, entry.sendWindowBytes)
1312
+ : CHUNK_SIZE;
1313
+ if (entry.flowControl && maxChunk <= 0) continue;
1314
+ const end = Math.min(value.byteLength, offset + maxChunk);
1315
+ const slice = value.subarray(offset, end);
1316
+ offset = end;
1317
+ if (entry.flowControl) {
1318
+ entry.sendWindowBytes -= slice.byteLength;
1319
+ }
1320
+ entry.refreshTimer();
1321
+ const writeOp = writeChain.then(async () => {
1322
+ if (entry.aborted) return;
1323
+ await send(MSG_HTTP_RES_BODY, slice);
1324
+ if (isSse) {
1325
+ advanceSseBoundary(slice);
1326
+ if (ssePendingKeepalive && sseAtLineBoundary && sseUtf8Pending === 0) {
1327
+ await sendKeepaliveNow();
1328
+ scheduleKeepalive();
1329
+ }
1330
+ }
1331
+ });
1332
+ writeChain = writeOp.catch(() => {});
1333
+ await writeOp;
1334
+ }
1335
+ }
1336
+ await writeChain;
1337
+ }
1338
+ } finally {
1339
+ clearTimeout(entry.sseKeepaliveTimer);
1340
+ entry.sseKeepaliveTimer = null;
1341
+ if (reader) {
1342
+ if (!streamDone) await reader.cancel().catch(() => {});
1343
+ reader.releaseLock();
1344
+ } else if (resp.body && !resp.body.locked) {
1345
+ await resp.body.cancel().catch(() => {});
1346
+ }
1347
+ }
1348
+ await send(MSG_HTTP_RES_END);
1349
+ } catch {
1350
+ if (abortController.signal.aborted) return;
1351
+ await send(MSG_HTTP_ABORT, 'Local DSH request failed');
1352
+ }
1353
+ }
1354
+
1355
+ async openLocalWebSocket(sessionId, streamId, session, key, entry, pathAndQuery) {
1356
+ const endpoint = this.resolveLocalEndpoint();
1357
+ const wsUrl = resolvePinnedTarget(endpoint, pathAndQuery);
1358
+ if (wsUrl.pathname !== '/api/remote.mux' || !pathAndQuery.match(/^\/api\/remote\.mux(?:\?|$)/u)) {
1359
+ throw new Error('Invalid DSH WebSocket route');
1360
+ }
1361
+ const origin = endpoint.authorityOrigin;
1362
+
1363
+ const cookie = await this.mintOperatorCookie(endpoint);
1364
+ if (this.sessions.get(sessionId) !== session || this.wsStreams.get(key) !== entry) return;
1365
+ const headers = { Origin: origin };
1366
+ if (cookie) headers.Cookie = cookie;
1367
+
1368
+ const sock = openPinnedWebSocket(endpoint, pathAndQuery, { headers });
1369
+ sock.binaryType = 'arraybuffer';
1370
+ entry.socket = sock;
1371
+ const connectTimer = setTimeout(() => sock.close(), 10_000);
1372
+ const send = (type, payload) => {
1373
+ if (this.wsStreams.get(key) !== entry) return;
1374
+ void this.sendStreamFrame(sessionId, streamId, type, payload, session).catch(() => {});
1375
+ };
1376
+
1377
+ sock.addEventListener('open', () => {
1378
+ clearTimeout(connectTimer);
1379
+ send(MSG_WS_OPENED, encodeJSON({ protocol: sock.protocol || '' }));
1380
+ });
1381
+
1382
+ sock.addEventListener('message', (event) => {
1383
+ const binary = typeof event.data !== 'string';
1384
+ const value = event.data;
1385
+ if (binary && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)) return;
1386
+ const size = binary ? value.byteLength : Buffer.byteLength(value);
1387
+ entry.queued = (entry.queued ?? 0) + size;
1388
+ if (entry.queued > 16 * 1024 * 1024) {
1389
+ sock.close(4008, 'Remote WebSocket queue exceeded');
1390
+ return;
1391
+ }
1392
+ entry.sendQueue = entry.sendQueue.then(async () => {
1393
+ if (this.wsStreams.get(key) !== entry) return;
1394
+ const type = binary ? MSG_WS_DATA_BIN : MSG_WS_DATA_TEXT;
1395
+ await sendFragments(value, (part) => this.sendStreamFrame(sessionId, streamId, type, part, session));
1396
+ }).catch(() => sock.close(4008, 'Remote WebSocket send failed')).finally(() => { entry.queued -= size; });
1397
+ });
1398
+
1399
+ sock.addEventListener('close', (ev) => {
1400
+ clearTimeout(connectTimer);
1401
+ void entry.sendQueue.finally(() => {
1402
+ if (this.wsStreams.get(key) !== entry) return;
1403
+ send(MSG_WS_CLOSE, encodeJSON({ code: ev.code || 1000, reason: ev.reason || '', wasClean: ev.wasClean }));
1404
+ this.wsStreams.delete(key);
1405
+ });
1406
+ });
1407
+
1408
+ sock.addEventListener('error', () => {
1409
+ // close event handles cleanup
1410
+ });
1411
+ }
1412
+ }