-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathws-server.ts
More file actions
1653 lines (1486 loc) · 58.1 KB
/
Copy pathws-server.ts
File metadata and controls
1653 lines (1486 loc) · 58.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2025 GoodRx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'module-alias/register';
import { join } from 'path';
import moduleAlias from 'module-alias';
// Register path aliases
moduleAlias.addAliases({
shared: join(__dirname, 'src/shared'),
server: join(__dirname, 'src/server'),
root: join(__dirname, '.'),
src: join(__dirname, 'src'),
scripts: join(__dirname, 'scripts'),
});
import { createServer, IncomingMessage, ServerResponse, request as httpRequest, STATUS_CODES } from 'http';
import { request as httpsRequest } from 'https';
import type { Socket } from 'net';
import { parse, URL } from 'url';
import next from 'next';
import { WebSocketServer, WebSocket } from 'ws';
import { rootLogger } from './src/server/lib/logger';
import { LIFECYCLE_MODE } from './src/shared/config';
import { isMcpServerEnabled, isAuthEnabled } from './src/server/mcp/config';
import { handleMcpHttpRequest as mcpHttpRequestHandler } from './src/server/mcp/handler';
import { streamK8sLogs, AbortHandle } from './src/server/lib/k8sStreamer';
import SitesService from './src/server/services/sites';
import {
serializeSocketHttpResponse,
EDITOR_PROXY_TIMEOUT_MS,
EDITOR_PROXY_PING_INTERVAL_MS,
EDITOR_PROXY_PONG_DEADLINE_MS,
editorProxyConnections,
classifyEditorProxyFailure,
resolveEditorProxyFailureMapping,
buildWorkspaceEditorErrorPage,
isEditorNavigationRequest,
type EditorProxyFailureContext,
} from './src/server/lib/agentSession/workspaceEditorProxy';
import {
buildChatPreviewAuthRedirectUrl,
buildChatPreviewCookie,
buildProxyHeaders,
buildRemoteTargetUrl,
appendForwardQuery,
CHAT_PREVIEW_COOKIE_NAME,
EDITOR_PROXY_BLOCKED_QUERY_PARAMS,
HOP_BY_HOP_HEADERS,
parseCookieHeader,
PREVIEW_PROXY_BLOCKED_QUERY_PARAMS,
rewritePreviewResponseHeader,
stripPreviewBootstrapParams,
stripQueryParamsFromRequestUrl,
type ChatPreviewPathMatch,
} from './src/server/lib/agentSession/chatPreviewProxy';
import { verifyChatPreviewGrant } from './src/server/lib/agentSession/chatPreviewGrant';
import { parseChatPreviewHost } from './src/server/lib/agentSession/chatPreviewFactory';
import { resolveChatPreviewSessionForHost } from './src/server/lib/agentSession/chatPreviewHostResolver';
const dev = process.env.NODE_ENV !== 'production';
const hostname = process.env.HOSTNAME || 'localhost';
const port = parseInt(process.env.PORT || '3000', 10);
// --- Initialize Next.js App ---
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
const LOG_STREAM_PATH = '/api/logs/stream'; // Path for WebSocket connections
const SESSION_WORKSPACE_EDITOR_PATH_PREFIX = '/api/agent-session/workspace-editor/';
const SESSION_WORKSPACE_EDITOR_COOKIE_NAME = 'lfc_session_workspace_editor_auth';
const SESSION_WORKSPACE_EDITOR_PORT = parseInt(process.env.AGENT_SESSION_WORKSPACE_EDITOR_PORT || '13337', 10);
const logger = rootLogger.child({ filename: __filename });
type McpHttpHandler = (
req: IncomingMessage,
res: ServerResponse,
pathname: string | null | undefined
) => Promise<boolean>;
// The MCP feature flag still gates whether the handler is *wired up*; the module
// itself is imported statically. (It was previously loaded via a deferred require to
// keep the ESM-only jose / MCP SDK off the boot path on Node < 20.19, but all deploys
// now run Node 22 — where require(esm) is supported — so the workaround is unnecessary.)
let handleMcpHttpRequest: McpHttpHandler | null = null;
if (isMcpServerEnabled()) {
if (isAuthEnabled() && !process.env.MCP_RESOURCE_URL) {
logger.warn(
'MCP: MCP_SERVER_ENABLED is true with auth on but MCP_RESOURCE_URL is unset; ' +
'token audiences will be validated against a localhost default and all real tokens will be rejected'
);
}
handleMcpHttpRequest = mcpHttpRequestHandler;
}
let sitesGatewayService: SitesService | null = null;
type SessionWorkspaceEditorPathMatch = { sessionId: string; forwardPath: string };
function getSitesGatewayService(): SitesService {
if (!sitesGatewayService) {
sitesGatewayService = new SitesService();
}
return sitesGatewayService;
}
// decodeURIComponent throws URIError on malformed escapes; a crash here would take down the server.
function safeDecodeURIComponent(value: string): string | null {
try {
return decodeURIComponent(value);
} catch {
return null;
}
}
function parseSessionWorkspaceEditorPath(pathname: string | null | undefined): SessionWorkspaceEditorPathMatch | null {
const safePathname = pathname || '';
if (safePathname.startsWith(SESSION_WORKSPACE_EDITOR_PATH_PREFIX)) {
const remainder = safePathname.slice(SESSION_WORKSPACE_EDITOR_PATH_PREFIX.length);
const slashIndex = remainder.indexOf('/');
const rawSessionId = slashIndex >= 0 ? remainder.slice(0, slashIndex) : remainder;
const sessionId = rawSessionId ? safeDecodeURIComponent(rawSessionId) : null;
if (!sessionId) {
return null;
}
const forwardPath = slashIndex >= 0 ? remainder.slice(slashIndex) : '/';
return {
sessionId,
forwardPath: forwardPath || '/',
};
}
return null;
}
async function resolveChatPreviewHostPathMatch(
request: IncomingMessage,
pathname: string | null | undefined
): Promise<ChatPreviewPathMatch | null> {
const hostMatch = parseChatPreviewHost(request.headers.host);
if (!hostMatch) {
return null;
}
const session = await resolveChatPreviewSessionForHost(hostMatch);
if (!session) {
return null;
}
return {
sessionId: session.sessionId,
port: hostMatch.port,
forwardPath: pathname || '/',
previewHost: hostMatch.host,
previewSlug: hostMatch.previewSlug,
};
}
// SECURITY: the preview proxies a workspace's own web app to the public ws-server origin;
// without this it would be reachable by anyone who learns the session uuid + port. Gated to
// the session owner with host-bound opaque preview grants.
async function resolveChatPreviewSessionUserId(sessionId: string): Promise<string | null> {
const { default: AgentSession } = await import('./src/server/models/AgentSession');
const session = await AgentSession.query().findOne({ uuid: sessionId });
return session?.userId ?? null;
}
async function isAuthorizedChatPreviewRequest(
request: IncomingMessage,
sessionUserId: string,
match: ChatPreviewPathMatch,
queryGrant?: string | null
): Promise<boolean> {
// Auth disabled (local dev) keeps the editor's behavior: open, same as that proxy.
if (process.env.ENABLE_AUTH !== 'true') {
return true;
}
const cookieGrant = parseCookieHeader(request.headers.cookie)[CHAT_PREVIEW_COOKIE_NAME];
const expectedGrant = {
sessionId: match.sessionId,
port: match.port,
userId: sessionUserId,
previewHost: match.previewHost,
};
return verifyChatPreviewGrant(cookieGrant, expectedGrant) || verifyChatPreviewGrant(queryGrant, expectedGrant);
}
function setNoReferrerPolicy(res: ServerResponse): void {
res.setHeader('Referrer-Policy', 'no-referrer');
}
function getSessionWorkspaceEditorCookiePath(sessionId: string): string {
return `${SESSION_WORKSPACE_EDITOR_PATH_PREFIX}${encodeURIComponent(sessionId)}`;
}
function decodeJwtPayload(token: string): Record<string, unknown> | null {
const payloadSegment = token.split('.')[1];
if (!payloadSegment) {
return null;
}
try {
const normalizedPayload = payloadSegment.replace(/-/g, '+').replace(/_/g, '/');
const paddedPayload = normalizedPayload.padEnd(
normalizedPayload.length + ((4 - (normalizedPayload.length % 4)) % 4),
'='
);
return JSON.parse(Buffer.from(paddedPayload, 'base64').toString('utf8')) as Record<string, unknown>;
} catch {
return null;
}
}
function getJwtCookieMaxAgeSeconds(token: string): number | null {
const exp = decodeJwtPayload(token)?.exp;
if (typeof exp !== 'number' || !Number.isFinite(exp)) {
return null;
}
return Math.max(Math.floor(exp - Date.now() / 1000), 0);
}
function isSendableCloseCode(code?: number): code is number {
if (typeof code !== 'number') {
return false;
}
if (code < 1000 || code >= 5000) {
return false;
}
return ![1004, 1005, 1006, 1015].includes(code);
}
function buildSessionWorkspaceEditorCookie(request: IncomingMessage, sessionId: string, token: string): string {
const isSecure =
request.headers['x-forwarded-proto'] === 'https' || (request.socket as { encrypted?: boolean }).encrypted === true;
const maxAgeSeconds = getJwtCookieMaxAgeSeconds(token);
const cookieParts = [
`${SESSION_WORKSPACE_EDITOR_COOKIE_NAME}=${encodeURIComponent(token)}`,
`Path=${getSessionWorkspaceEditorCookiePath(sessionId)}`,
...(maxAgeSeconds === null ? [] : [`Max-Age=${maxAgeSeconds}`]),
'HttpOnly',
'SameSite=Lax',
];
if (isSecure) {
cookieParts.push('Secure');
}
return cookieParts.join('; ');
}
function appendSetCookie(res: ServerResponse, value: string) {
const existing = res.getHeader('Set-Cookie');
if (!existing) {
res.setHeader('Set-Cookie', value);
return;
}
if (Array.isArray(existing)) {
res.setHeader('Set-Cookie', [...existing, value]);
return;
}
res.setHeader('Set-Cookie', [existing.toString(), value]);
}
function buildSessionWorkspaceEditorServiceUrl(
session: { id: string; podName: string; namespace: string },
forwardPath: string,
query: Record<string, string | string[] | undefined>,
isWebSocket = false
) {
const protocol = isWebSocket ? 'ws' : 'http';
const target = new URL(
`${protocol}://${session.podName}.${session.namespace}.svc.cluster.local:${SESSION_WORKSPACE_EDITOR_PORT}${forwardPath}`
);
appendForwardQuery(target, query, EDITOR_PROXY_BLOCKED_QUERY_PARAMS);
return target;
}
type SessionWorkspaceEditorTarget = {
url: URL;
headers?: Record<string, string>;
// SECURITY: remote (untrusted) editor backends must not receive Lifecycle credentials nor set cookies on our origin.
isRemote: boolean;
};
// Endpoint lookups run on every proxied request (browser previews fan out to dozens); cache the
// DB-backed resolution briefly so the hot path stays off the database.
const ENDPOINT_CACHE_TTL_MS = 5000;
const ENDPOINT_CACHE_NEGATIVE_TTL_MS = 1500;
const ENDPOINT_CACHE_MAX_ENTRIES = 1000;
type RemoteEndpointRef = { url: string; headers?: Record<string, string> } | null;
const endpointCache = new Map<string, { value: RemoteEndpointRef; expiresAt: number }>();
async function resolveCachedEndpoint(key: string, lookup: () => Promise<RemoteEndpointRef>) {
const cached = endpointCache.get(key);
if (cached && cached.expiresAt > Date.now()) {
return cached.value;
}
const value = await lookup();
if (endpointCache.size >= ENDPOINT_CACHE_MAX_ENTRIES) {
endpointCache.clear();
}
endpointCache.set(key, {
value,
expiresAt: Date.now() + (value ? ENDPOINT_CACHE_TTL_MS : ENDPOINT_CACHE_NEGATIVE_TTL_MS),
});
return value;
}
async function resolveSessionWorkspaceEditorTarget(
session: { id: string; uuid?: string; podName: string; namespace: string },
forwardPath: string,
query: Record<string, string | string[] | undefined>,
isWebSocket = false
): Promise<SessionWorkspaceEditorTarget> {
const endpoint = await resolveCachedEndpoint(`editor:${session.uuid || session.id}`, async () => {
const AgentSandboxService = (await import('./src/server/services/agent/SandboxService')).default;
return AgentSandboxService.resolveWorkspaceEditorEndpoint(session.uuid || session.id).catch(() => null);
});
if (endpoint) {
return {
url: buildRemoteTargetUrl(endpoint.url, forwardPath, query, {
isWebSocket,
blockedQueryParams: EDITOR_PROXY_BLOCKED_QUERY_PARAMS,
}),
isRemote: true,
...(endpoint.headers ? { headers: endpoint.headers } : {}),
};
}
return {
url: buildSessionWorkspaceEditorServiceUrl(session, forwardPath, query, isWebSocket),
isRemote: false,
};
}
// The exposure row intentionally holds no bearer token at rest; gateway auth headers are re-resolved
// per lookup from the exposure's own sandbox so URL and token never span generations.
async function resolvePreviewEndpointWithAuth(
providerState: unknown,
sandbox: import('./src/server/models/AgentSandbox').default,
session: import('./src/server/models/AgentSession').default
): Promise<RemoteEndpointRef> {
const { resolvePersistedPreviewEndpointWithAuth } = await import(
'./src/server/services/workspaceRuntime/gatewayPreview'
);
const { default: AgentSandboxService } = await import('./src/server/services/agent/SandboxService');
return resolvePersistedPreviewEndpointWithAuth(providerState || {}, () =>
AgentSandboxService.resolveGatewayEndpointForSandbox(sandbox, session).catch((error) => {
logger.warn({ error, sessionId: session.uuid }, 'ChatPreview: gateway auth resolution failed');
return null;
})
);
}
async function lookupChatPreviewEndpoint(match: ChatPreviewPathMatch): Promise<RemoteEndpointRef> {
const [{ default: AgentSession }, { default: AgentSandbox }, { default: AgentSandboxExposure }] = await Promise.all([
import('./src/server/models/AgentSession'),
import('./src/server/models/AgentSandbox'),
import('./src/server/models/AgentSandboxExposure'),
]);
if (match.previewSlug) {
let exposure = await AgentSandboxExposure.query()
.where({ kind: 'preview', targetPort: match.port })
.whereRaw('"metadata"->>? = ?', ['previewSlug', match.previewSlug])
.orderBy('id', 'desc')
.first();
if (!exposure) {
return null;
}
const exposureSandbox = await AgentSandbox.query().findById(exposure.sandboxId);
if (!exposureSandbox || exposureSandbox.status !== 'ready') {
return null;
}
const session = await AgentSession.query().findById(exposureSandbox.sessionId);
if (
!session ||
session.uuid !== match.sessionId ||
session.status !== 'active' ||
session.workspaceStatus !== 'ready'
) {
return null;
}
if (exposure.status !== 'ready' || exposure.endedAt) {
const AgentSandboxService = (await import('./src/server/services/agent/SandboxService')).default;
await AgentSandboxService.restorePreviewExposures(session);
exposure = await AgentSandboxExposure.query()
.where({ sandboxId: exposureSandbox.id, kind: 'preview', targetPort: match.port, status: 'ready' })
.whereRaw('"metadata"->>? = ?', ['previewSlug', match.previewSlug])
.whereNull('endedAt')
.first();
if (!exposure) {
return null;
}
}
return resolvePreviewEndpointWithAuth(exposure.providerState, exposureSandbox, session);
}
const session = await AgentSession.query().findOne({ uuid: match.sessionId });
if (!session || session.status !== 'active' || session.workspaceStatus !== 'ready') {
return null;
}
const sandbox = await AgentSandbox.query().where({ sessionId: session.id }).orderBy('generation', 'desc').first();
if (!sandbox || sandbox.status !== 'ready') {
return null;
}
let exposure = await AgentSandboxExposure.query()
.where({ sandboxId: sandbox.id, kind: 'preview', targetPort: match.port, status: 'ready' })
.whereNull('endedAt')
.first();
if (!exposure) {
const AgentSandboxService = (await import('./src/server/services/agent/SandboxService')).default;
await AgentSandboxService.restorePreviewExposures(session);
exposure = await AgentSandboxExposure.query()
.where({ sandboxId: sandbox.id, kind: 'preview', targetPort: match.port, status: 'ready' })
.whereNull('endedAt')
.first();
if (!exposure) {
return null;
}
}
return resolvePreviewEndpointWithAuth(exposure.providerState, sandbox, session);
}
async function resolveChatPreviewTarget(
match: ChatPreviewPathMatch,
query: Record<string, string | string[] | undefined>,
isWebSocket = false
): Promise<SessionWorkspaceEditorTarget | null> {
const cacheKey = match.previewSlug
? `preview:${match.sessionId}:${match.port}:${match.previewSlug}`
: `preview:${match.sessionId}:${match.port}`;
const endpoint = await resolveCachedEndpoint(cacheKey, () => lookupChatPreviewEndpoint(match));
if (!endpoint) {
return null;
}
return {
url: buildRemoteTargetUrl(endpoint.url, match.forwardPath, query, {
isWebSocket,
blockedQueryParams: PREVIEW_PROXY_BLOCKED_QUERY_PARAMS,
}),
isRemote: true,
...(endpoint.headers ? { headers: endpoint.headers } : {}),
};
}
function requestForTarget(target: URL): typeof httpRequest {
return target.protocol === 'https:' || target.protocol === 'wss:' ? httpsRequest : httpRequest;
}
// node's http/https.request reject ws:/wss: URLs. A proxied WebSocket is issued as a normal
// http/https request carrying Upgrade headers — the scheme, not the URL, makes it a WebSocket —
// so the upstream URL must be normalized back to http/https before the request is built.
function toUpgradeRequestUrl(target: URL): URL {
if (target.protocol !== 'ws:' && target.protocol !== 'wss:') {
return target;
}
const normalized = new URL(target.toString());
normalized.protocol = target.protocol === 'wss:' ? 'https:' : 'http:';
return normalized;
}
// SECURITY: untrusted preview responses must not set cookies on the Lifecycle origin.
function stripSetCookieHeaders(headers: IncomingMessage['headers']): IncomingMessage['headers'] {
const { 'set-cookie': _setCookie, ...rest } = headers;
return rest;
}
async function handleSessionWorkspaceEditorUpgrade(request: IncomingMessage, socket: Socket, head: Buffer) {
const parsedUrl = parse(request.url || '', true);
const match = parseSessionWorkspaceEditorPath(parsedUrl.pathname);
const editorLogCtx: Record<string, unknown> = {
remoteAddress: request.socket.remoteAddress,
path: parsedUrl.pathname,
};
if (!match) {
socket.end(
serializeSocketHttpResponse({ statusCode: 400, statusMessage: 'Bad Request', body: 'Invalid editor path' })
);
return;
}
let upstreamSocket: Socket | null = null;
let proxyReq: ReturnType<typeof httpRequest> | null = null;
// rh-2: track this socket pair as a live connection.
const registryToken = {};
let registered = false;
// Once the pipe is live, release-on-close owns the registry slot; finally must not release it.
let pipeEstablished = false;
let clientClosedEarly = false;
// rh-2: bind client close/error before the connect await so a disconnect aborts the pending proxyReq.
const onEarlyClientClose = () => {
clientClosedEarly = true;
if (proxyReq) {
proxyReq.destroy();
}
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy();
}
};
socket.on('close', onEarlyClientClose);
socket.on('error', onEarlyClientClose);
try {
const queryToken = typeof parsedUrl.query.token === 'string' ? parsedUrl.query.token : null;
const session = await resolveOwnedAgentSession(request, match.sessionId, queryToken);
if (clientClosedEarly) {
return;
}
if (!editorProxyConnections.tryRegister(match.sessionId, registryToken)) {
throw new EditorProxyError('editor-proxy-capacity');
}
registered = true;
const forwardedPrefix = getSessionWorkspaceEditorCookiePath(match.sessionId);
const target = await resolveSessionWorkspaceEditorTarget(
session,
match.forwardPath,
parsedUrl.query as Record<string, string | string[] | undefined>,
true
);
const targetUrl = target.url;
const proxyHeaders = buildProxyHeaders(request, targetUrl, forwardedPrefix, target.headers, true, target.isRemote);
const upstreamUrl = toUpgradeRequestUrl(targetUrl);
await new Promise<void>((resolve, reject) => {
proxyReq = requestForTarget(upstreamUrl)(upstreamUrl, {
method: request.method || 'GET',
headers: proxyHeaders,
});
// rh-2: bound the connect/upgrade phase so a half-open upstream can't hold it open indefinitely.
proxyReq.setTimeout(EDITOR_PROXY_TIMEOUT_MS, () => {
proxyReq?.destroy(new EditorProxyError('editor-proxy-timeout'));
});
proxyReq.on('upgrade', (upstreamRes, proxiedSocket, upstreamHead) => {
upstreamSocket = proxiedSocket as Socket;
// Hand off from the early connect-phase guards to steady-state pipe teardown.
socket.removeListener('close', onEarlyClientClose);
socket.removeListener('error', onEarlyClientClose);
if (clientClosedEarly || socket.destroyed) {
upstreamSocket.destroy();
resolve();
return;
}
socket.write(
serializeSocketHttpResponse({
statusCode: upstreamRes.statusCode || 101,
statusMessage: upstreamRes.statusMessage,
headers: target.isRemote ? stripSetCookieHeaders(upstreamRes.headers) : upstreamRes.headers,
})
);
if (upstreamHead.length > 0) {
socket.write(upstreamHead);
}
if (head.length > 0) {
upstreamSocket.write(head);
}
// rh-2: a byte-pipe can't parse WS frames, so enforce liveness via a bidirectional idle timeout (any traffic resets it).
const idleMs = EDITOR_PROXY_PING_INTERVAL_MS + EDITOR_PROXY_PONG_DEADLINE_MS;
const reapIdle = (source: 'client' | 'upstream') => {
logger.warn(
{ ...editorLogCtx, sessionId: match.sessionId, source, idleMs },
`SessionEditor: idle timeout source=${source} sessionId=${match.sessionId}`
);
if (!socket.destroyed) {
socket.destroy();
}
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy();
}
};
socket.setTimeout(idleMs, () => reapIdle('client'));
upstreamSocket.setTimeout(idleMs, () => reapIdle('upstream'));
socket.on('error', (error) => {
logger.warn(
{ ...editorLogCtx, error },
`SessionEditor: socket error source=client sessionId=${match.sessionId}`
);
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy(error as Error);
}
});
upstreamSocket.on('error', (error) => {
logger.warn(
{ ...editorLogCtx, error },
`SessionEditor: socket error source=upstream sessionId=${match.sessionId}`
);
if (!socket.destroyed) {
socket.destroy(error as Error);
}
});
socket.on('close', () => {
if (registered) {
registered = false;
editorProxyConnections.release(match.sessionId, registryToken);
}
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.end();
}
});
upstreamSocket.on('close', () => {
if (!socket.destroyed) {
socket.end();
}
});
pipeEstablished = true;
socket.pipe(upstreamSocket);
upstreamSocket.pipe(socket);
socket.resume();
upstreamSocket.resume();
resolve();
});
proxyReq.on('response', (upstreamRes) => {
const chunks: Buffer[] = [];
upstreamRes.on('data', (chunk) => {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
});
upstreamRes.on('end', () => {
if (!socket.destroyed) {
socket.end(
serializeSocketHttpResponse({
statusCode: upstreamRes.statusCode || 502,
statusMessage: upstreamRes.statusMessage,
headers: upstreamRes.headers,
body: Buffer.concat(chunks),
})
);
}
reject(new Error(`Editor upgrade rejected with status ${upstreamRes.statusCode || 502}`));
});
});
proxyReq.on('error', reject);
proxyReq.end();
});
} catch (error: any) {
const ctx = extractEditorFailureContext(error);
const reason = classifyEditorProxyFailure(error, ctx);
const mapping = resolveEditorProxyFailureMapping(reason);
logger.error(
{ ...editorLogCtx, error, sessionId: match.sessionId, reason, status: mapping.status },
`SessionEditor: websocket setup failed sessionId=${match.sessionId} reason=${reason}`
);
if (proxyReq) {
proxyReq.destroy();
}
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy();
}
// WS handshakes aren't browser navigations; reply with a coded status line on the raw socket, not HTML.
if (!socket.destroyed) {
socket.end(
serializeSocketHttpResponse({
statusCode: mapping.status,
statusMessage: STATUS_CODES[mapping.status] || 'Bad Gateway',
headers: { 'X-Editor-Proxy-Reason': reason },
body: mapping.message,
})
);
}
} finally {
socket.removeListener('close', onEarlyClientClose);
socket.removeListener('error', onEarlyClientClose);
// Release only when the pipe never went live; a live pipe's slot is released by its socket 'close' handler.
if (registered && !pipeEstablished) {
registered = false;
editorProxyConnections.release(match.sessionId, registryToken);
}
}
}
async function handleChatPreviewUpgrade(request: IncomingMessage, socket: Socket, head: Buffer) {
const parsedUrl = parse(request.url || '', true);
let match: ChatPreviewPathMatch | null = null;
try {
match = await resolveChatPreviewHostPathMatch(request, parsedUrl.pathname || '/');
if (!match) {
socket.end(
serializeSocketHttpResponse({ statusCode: 400, statusMessage: 'Bad Request', body: 'Invalid preview path' })
);
return;
}
const previewSessionUserId = await resolveChatPreviewSessionUserId(match.sessionId);
if (!previewSessionUserId || !(await isAuthorizedChatPreviewRequest(request, previewSessionUserId, match))) {
socket.end(serializeSocketHttpResponse({ statusCode: 401, statusMessage: 'Unauthorized', body: 'Unauthorized' }));
return;
}
} catch (error) {
logger.warn({ error, path: parsedUrl.pathname }, 'ChatPreview: websocket authorization failed');
socket.end(
serializeSocketHttpResponse({
statusCode: 502,
statusMessage: 'Bad Gateway',
headers: { 'X-Preview-Proxy-Reason': 'preview-unavailable' },
body: 'Preview is unavailable',
})
);
return;
}
if (!match) {
return;
}
let upstreamSocket: Socket | null = null;
let proxyReq: ReturnType<typeof httpRequest> | null = null;
let clientClosedEarly = false;
// Preview pipes share the editor's live-connection registry so they count toward caps/metrics.
const registryKey = `preview:${match.sessionId}`;
const registryToken = {};
let registered = false;
let pipeEstablished = false;
const onEarlyClientClose = () => {
clientClosedEarly = true;
proxyReq?.destroy();
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy();
}
};
socket.on('close', onEarlyClientClose);
socket.on('error', onEarlyClientClose);
try {
const target = await resolveChatPreviewTarget(
match,
parsedUrl.query as Record<string, string | string[] | undefined>,
true
);
if (!target) {
throw new Error('Preview target not found');
}
if (clientClosedEarly) {
return;
}
if (!editorProxyConnections.tryRegister(registryKey, registryToken)) {
throw new Error('preview-proxy-capacity');
}
registered = true;
const targetUrl = target.url;
const proxyHeaders = buildProxyHeaders(request, targetUrl, '', target.headers, true, true);
const upstreamUrl = toUpgradeRequestUrl(targetUrl);
await new Promise<void>((resolve, reject) => {
proxyReq = requestForTarget(upstreamUrl)(upstreamUrl, {
method: request.method || 'GET',
headers: proxyHeaders,
});
proxyReq.setTimeout(EDITOR_PROXY_TIMEOUT_MS, () => {
proxyReq?.destroy(new Error('preview-proxy-timeout'));
});
proxyReq.on('upgrade', (upstreamRes, proxiedSocket, upstreamHead) => {
upstreamSocket = proxiedSocket as Socket;
socket.removeListener('close', onEarlyClientClose);
socket.removeListener('error', onEarlyClientClose);
if (clientClosedEarly || socket.destroyed) {
upstreamSocket.destroy();
resolve();
return;
}
socket.write(
serializeSocketHttpResponse({
statusCode: upstreamRes.statusCode || 101,
statusMessage: upstreamRes.statusMessage,
headers: stripSetCookieHeaders(upstreamRes.headers),
})
);
if (upstreamHead.length > 0) {
socket.write(upstreamHead);
}
if (head.length > 0) {
upstreamSocket.write(head);
}
// A byte-pipe can't parse WS frames, so enforce liveness via a bidirectional idle timeout.
const idleMs = EDITOR_PROXY_PING_INTERVAL_MS + EDITOR_PROXY_PONG_DEADLINE_MS;
const reapIdle = (source: 'client' | 'upstream') => {
logger.warn(
{ sessionId: match.sessionId, port: match.port, source, idleMs },
`ChatPreview: idle timeout source=${source} sessionId=${match.sessionId}`
);
if (!socket.destroyed) {
socket.destroy();
}
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy();
}
};
socket.setTimeout(idleMs, () => reapIdle('client'));
upstreamSocket.setTimeout(idleMs, () => reapIdle('upstream'));
socket.on('error', (error) => {
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy(error as Error);
}
});
upstreamSocket.on('error', (error) => {
if (!socket.destroyed) {
socket.destroy(error as Error);
}
});
socket.on('close', () => {
if (registered) {
registered = false;
editorProxyConnections.release(registryKey, registryToken);
}
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.end();
}
});
upstreamSocket.on('close', () => {
if (!socket.destroyed) {
socket.end();
}
});
pipeEstablished = true;
socket.pipe(upstreamSocket);
upstreamSocket.pipe(socket);
socket.resume();
upstreamSocket.resume();
resolve();
});
proxyReq.on('response', (upstreamRes) => {
const chunks: Buffer[] = [];
upstreamRes.on('data', (chunk) => {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
});
upstreamRes.on('end', () => {
if (!socket.destroyed) {
socket.end(
serializeSocketHttpResponse({
statusCode: upstreamRes.statusCode || 502,
statusMessage: upstreamRes.statusMessage,
headers: stripSetCookieHeaders(upstreamRes.headers),
body: Buffer.concat(chunks),
})
);
}
reject(new Error(`Preview upgrade rejected with status ${upstreamRes.statusCode || 502}`));
});
});
proxyReq.on('error', reject);
proxyReq.end();
});
} catch (error) {
logger.warn(
{ error, path: parsedUrl.pathname, sessionId: match.sessionId, port: match.port },
'ChatPreview: websocket proxy failed'
);
proxyReq?.destroy();
if (upstreamSocket && !upstreamSocket.destroyed) {
upstreamSocket.destroy();
}
if (!socket.destroyed) {
socket.end(
serializeSocketHttpResponse({
statusCode: 502,
statusMessage: 'Bad Gateway',
headers: { 'X-Preview-Proxy-Reason': 'preview-unavailable' },
body: 'Preview is unavailable',
})
);
}
} finally {
socket.removeListener('close', onEarlyClientClose);
socket.removeListener('error', onEarlyClientClose);
// Release only when the pipe never went live; a live pipe's slot is released on socket close.
if (registered && !pipeEstablished) {
registered = false;
editorProxyConnections.release(registryKey, registryToken);
}
}
}
// err-4: coded error carrying failure context so callers can map suspended vs pod-gone vs auth.
class EditorProxyError extends Error {
failureContext: EditorProxyFailureContext;
constructor(message: string, failureContext: EditorProxyFailureContext = {}) {
super(message);
this.name = 'EditorProxyError';
this.failureContext = failureContext;
}
}
async function resolveOwnedAgentSession(
request: IncomingMessage,
sessionId: string,
queryToken?: string | null
): Promise<any> {
const AgentSessionService = (await import('./src/server/services/agentSession')).default;
const session = await AgentSessionService.getSession(sessionId);
if (!session || session.status !== 'active') {
throw new EditorProxyError('Session not found or not active', { podMissing: true });
}
// sr-3 guard: a crashed suspend can leave status=active over a dead pod; treat not-ready as unavailable to emit a coded page, not a 502.
if (session.workspaceStatus !== 'ready') {
throw new EditorProxyError('Workspace is not ready', { workspaceUnavailable: true });
}
if (!session.podName || !session.namespace) {
throw new EditorProxyError('Workspace runtime is gone', { podMissing: true });
}
if (process.env.ENABLE_AUTH === 'true') {
const headerToken = request.headers.authorization?.split(' ')[1];
const cookieToken = parseCookieHeader(request.headers.cookie)[SESSION_WORKSPACE_EDITOR_COOKIE_NAME];
const rawToken = headerToken || queryToken || cookieToken;
if (!rawToken) {
throw new Error('Authentication token is required');
}
const { verifyBearerToken } = await import('./src/server/lib/auth');
const authResult = await verifyBearerToken(rawToken);
if (!authResult.success || authResult.payload?.sub !== session.userId) {
throw new Error('Forbidden: you do not own this session');
}
}
return session;
}
function closeSocket(ws: WebSocket, code: number, reason: string) {
if (ws.readyState !== WebSocket.OPEN && ws.readyState !== WebSocket.CONNECTING) {
return;
}
const safeReason = Buffer.byteLength(reason, 'utf8') > 123 ? 'Connection error' : reason;
if (isSendableCloseCode(code)) {
ws.close(code, safeReason);
return;
}
ws.close(1000, safeReason);
}
// Same-origin deep-link back to the Lifecycle session for the branded error page CTA.
function buildEditorSessionDeepLink(request: IncomingMessage, sessionId: string): string {
const proto =
(typeof request.headers['x-forwarded-proto'] === 'string' && request.headers['x-forwarded-proto']) ||