-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathserver.ts
More file actions
1819 lines (1561 loc) · 55.3 KB
/
server.ts
File metadata and controls
1819 lines (1561 loc) · 55.3 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
/**
* oRPC Server factory for mux.
* Serves oRPC router over HTTP and WebSocket.
*
* This module exports the server creation logic so it can be tested.
* The CLI entry point (server.ts) uses this to start the server.
*/
import express, { type Express } from "express";
import * as fs from "fs/promises";
import * as http from "http";
import * as path from "path";
import { WebSocketServer, type WebSocket } from "ws";
import { RPCHandler } from "@orpc/server/node";
import { RPCHandler as ORPCWebSocketServerHandler } from "@orpc/server/ws";
import { ORPCError, onError } from "@orpc/server";
import { OpenAPIGenerator } from "@orpc/openapi";
import { OpenAPIHandler } from "@orpc/openapi/node";
import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4";
import { router, type AppRouter } from "@/node/orpc/router";
import type { ORPCContext } from "@/node/orpc/context";
import { extractCookieValues, extractWsHeaders, safeEq } from "@/node/orpc/authMiddleware";
import { VERSION } from "@/version";
import { formatOrpcError } from "@/node/orpc/formatOrpcError";
import { BROWSER_BRIDGE_WS_PATH, DESKTOP_WS_PATH, ORPC_WS_PATH } from "@/node/orpc/wsPaths";
import { log } from "@/node/services/log";
import {
SERVER_AUTH_SESSION_COOKIE_NAME,
SERVER_AUTH_SESSION_MAX_AGE_SECONDS,
} from "@/node/services/serverAuthService";
import { attachStreamErrorHandler, isIgnorableStreamError } from "@/node/utils/streamErrors";
import { getErrorMessage } from "@/common/utils/errors";
import { escapeHtml } from "@/node/utils/oauthUtils";
import { assert } from "@/common/utils/assert";
import { getAppProxyBasePathFromPathname, stripAppProxyBasePath } from "@/common/appProxyBasePath";
type AliveWebSocket = WebSocket & { isAlive?: boolean };
export { BROWSER_BRIDGE_WS_PATH, DESKTOP_WS_PATH, ORPC_WS_PATH };
const WS_HEARTBEAT_INTERVAL_MS = 30_000;
// --- Types ---
export interface OrpcServerOptions {
/** Host to bind to (default: "127.0.0.1") */
host?: string;
/** Port to bind to (default: 0 for random available port) */
port?: number;
/** oRPC context with services */
context: ORPCContext;
/** Whether to serve static files and SPA fallback (default: false) */
serveStatic?: boolean;
/** Directory to serve static files from (default: dist/ relative to dist/node/orpc/) */
staticDir?: string;
/** Custom error handler for oRPC errors */
onOrpcError?: (error: unknown, options: unknown) => void;
/** Optional bearer token for HTTP auth (used if router not provided) */
authToken?: string;
/** Optional pre-created router (if not provided, creates router(authToken)) */
router?: AppRouter;
/** Desktop bridge upgrade/shutdown hooks for /desktop/ws */
desktopBridgeServer?: Pick<ORPCContext["desktopBridgeServer"], "handleUpgrade" | "stop">;
/** Browser bridge upgrade/shutdown hooks for /browser/ws */
browserBridgeServer?: Pick<ORPCContext["browserBridgeServer"], "handleUpgrade" | "stop">;
/**
* Allow HTTPS browser origins when reverse proxies forward X-Forwarded-Proto=http.
* Keep disabled by default and only enable when TLS is terminated before mux.
*/
allowHttpOrigin?: boolean;
}
export interface OrpcServer {
/** The HTTP server instance */
httpServer: http.Server;
/** The WebSocket server instance */
wsServer: WebSocketServer;
/** The Express app instance */
app: Express;
/** The port the server is listening on */
port: number;
/** Base URL for HTTP requests */
baseUrl: string;
/** WebSocket URL for WS connections */
wsUrl: string;
/** URL for OpenAPI spec JSON */
specUrl: string;
/** URL for Scalar API docs */
docsUrl: string;
/** Close the server and cleanup resources */
close: () => Promise<void>;
}
// --- Server Factory ---
function formatHostForUrl(host: string): string {
const trimmed = host.trim();
// IPv6 URLs must be bracketed: http://[::1]:1234
if (trimmed.includes(":")) {
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
return trimmed;
}
// If the host contains a zone index (e.g. fe80::1%en0), percent must be encoded.
const escaped = trimmed.replaceAll("%", "%25");
return `[${escaped}]`;
}
return trimmed;
}
function extractBearerToken(header: string | undefined): string | null {
if (!header?.toLowerCase().startsWith("bearer ")) return null;
const token = header.slice(7).trim();
return token.length ? token : null;
}
function escapeHtmlAttribute(value: string): string {
return value
.replaceAll("&", "&")
.replaceAll('"', """)
.replaceAll("'", "'")
.replaceAll("<", "<")
.replaceAll(">", ">");
}
const SLASHLESS_ROOT_REDIRECT_SCRIPT =
'<script>(()=>{const pathname=location.pathname;if(pathname.startsWith("//")||pathname.endsWith("/"))return;location.replace(location.origin+pathname+"/"+location.search+location.hash);})();</script>';
function injectBaseHref(
indexHtml: string,
baseHref: string,
options: { includeSlashlessRootRedirect?: boolean } = {}
): string {
// Avoid double-injecting if the HTML already has a base tag.
if (/<base\b/i.test(indexHtml)) {
return indexHtml;
}
// The redirect must precede the base tag so slashless app-root URLs become
// directory URLs before the browser resolves relative assets.
const slashlessRootRedirect = options.includeSlashlessRootRedirect
? `\n ${SLASHLESS_ROOT_REDIRECT_SCRIPT}`
: "";
// Insert immediately after the opening <head> tag (supports <head> and <head ...attrs>).
const escapedBaseHref = escapeHtmlAttribute(baseHref);
return indexHtml.replace(
/<head[^>]*>/i,
(match) => `${match}${slashlessRootRedirect}\n <base href="${escapedBaseHref}" />`
);
}
function escapeJsonForHtmlScript(value: unknown): string {
// Prevent `</script>` injection when embedding untrusted strings in an inline <script>.
return JSON.stringify(value).replaceAll("<", "\\u003c");
}
function getBrowserProxyUriTemplate(): string | null {
const muxProxyUri = process.env.MUX_PROXY_URI?.trim();
if (muxProxyUri) {
return muxProxyUri;
}
const vscodeProxyUri = process.env.VSCODE_PROXY_URI?.trim();
return vscodeProxyUri?.length ? vscodeProxyUri : null;
}
function injectProxyUriTemplate(indexHtml: string, proxyUriTemplate: string | null): string {
const templateJson = escapeJsonForHtmlScript(proxyUriTemplate);
return indexHtml.replace(
/<head[^>]*>/i,
(match) => `${match}\n <script>window.__MUX_PROXY_URI_TEMPLATE__ = ${templateJson};</script>`
);
}
type OriginValidationRequest = Pick<http.IncomingMessage, "headers" | "socket"> & {
protocol?: string;
};
function getFirstHeaderValue(
req: Pick<http.IncomingMessage, "headers">,
headerName: string
): string | null {
const rawValue = req.headers[headerName.toLowerCase()];
const value = Array.isArray(rawValue) ? rawValue[0] : rawValue;
if (typeof value !== "string") {
return null;
}
const firstValue = value.split(",")[0]?.trim();
return firstValue?.length ? firstValue : null;
}
function normalizeProtocol(rawProtocol: string): "http" | "https" | null {
const normalized = rawProtocol.trim().toLowerCase().replace(/:$/, "");
if (normalized === "http" || normalized === "https") {
return normalized;
}
return null;
}
function buildOrigin(protocol: string, host: string): string | null {
const normalizedProtocol = normalizeProtocol(protocol);
const normalizedHost = host.trim();
if (!normalizedProtocol || normalizedHost.length === 0) {
return null;
}
try {
return new URL(`${normalizedProtocol}://${normalizedHost}`).origin;
} catch {
return null;
}
}
function normalizeHostForProtocol(host: string, protocol: "http" | "https"): string | null {
const trimmedHost = host.trim();
if (!trimmedHost) {
return null;
}
try {
return new URL(`${protocol}://${trimmedHost}`).host.toLowerCase();
} catch {
return null;
}
}
function inferProtocol(req: OriginValidationRequest): "http" | "https" {
if (typeof req.protocol === "string") {
const normalized = normalizeProtocol(req.protocol);
if (normalized) {
return normalized;
}
}
return (req.socket as { encrypted?: boolean }).encrypted ? "https" : "http";
}
function getExpectedHosts(req: OriginValidationRequest): string[] {
return [getFirstHeaderValue(req, "x-forwarded-host"), getFirstHeaderValue(req, "host")].filter(
(value, index, values): value is string => value !== null && values.indexOf(value) === index
);
}
function getFirstForwardedProtocol(req: OriginValidationRequest): "http" | "https" | null {
const forwardedProtoHeader = getFirstHeaderValue(req, "x-forwarded-proto");
if (!forwardedProtoHeader) {
return null;
}
// Trust the client-facing hop. Additional values come from downstream/internal hops.
const firstHop = forwardedProtoHeader.split(",")[0] ?? "";
return normalizeProtocol(firstHop);
}
function getOriginProtocolOnExpectedHost(req: OriginValidationRequest): "http" | "https" | null {
const normalizedOrigin = normalizeOrigin(getFirstHeaderValue(req, "origin"));
if (!normalizedOrigin) {
return null;
}
try {
const parsedOrigin = new URL(normalizedOrigin);
const originProtocol = normalizeProtocol(parsedOrigin.protocol);
if (!originProtocol) {
return null;
}
const originHost = parsedOrigin.host.toLowerCase();
const hasExpectedHost = getExpectedHosts(req).some((host) => {
const normalizedHost = normalizeHostForProtocol(host, originProtocol);
return normalizedHost !== null && normalizedHost === originHost;
});
return hasExpectedHost ? originProtocol : null;
} catch {
return null;
}
}
function getClientFacingProtocol(req: OriginValidationRequest): "http" | "https" {
return getFirstForwardedProtocol(req) ?? inferProtocol(req);
}
function getExpectedProtocols(
req: OriginValidationRequest,
allowHttpOrigin = false
): Array<"http" | "https"> {
const clientFacingProtocol = getClientFacingProtocol(req);
const originProtocol = getOriginProtocolOnExpectedHost(req);
// Compatibility path: some reverse proxies overwrite X-Forwarded-Proto to http
// even when the browser-facing request is https. In that specific case, trust the
// validated origin protocol for host-matched requests only when explicitly enabled.
if (allowHttpOrigin && clientFacingProtocol === "http" && originProtocol === "https") {
return ["https"];
}
return [clientFacingProtocol];
}
function getPreferredPublicProtocol(
req: OriginValidationRequest,
allowHttpOrigin = false
): "http" | "https" {
const clientFacingProtocol = getClientFacingProtocol(req);
const originProtocol = getOriginProtocolOnExpectedHost(req);
if (allowHttpOrigin && clientFacingProtocol === "http" && originProtocol === "https") {
return "https";
}
return clientFacingProtocol;
}
function getExpectedOrigins(req: OriginValidationRequest, allowHttpOrigin = false): string[] {
const hosts = getExpectedHosts(req);
if (hosts.length === 0) {
return [];
}
const protocols = getExpectedProtocols(req, allowHttpOrigin);
const expectedOrigins: string[] = [];
for (const protocol of protocols) {
for (const host of hosts) {
const origin = buildOrigin(protocol, host);
if (!origin || expectedOrigins.includes(origin)) {
continue;
}
expectedOrigins.push(origin);
}
}
return expectedOrigins;
}
function normalizeOrigin(raw: string | null | undefined): string | null {
if (!raw) {
return null;
}
try {
const parsed = new URL(raw);
const normalizedProtocol = normalizeProtocol(parsed.protocol);
if (!normalizedProtocol) {
return null;
}
return `${normalizedProtocol}://${parsed.host}`;
} catch {
return null;
}
}
interface OriginIdentity {
protocol: "http:" | "https:";
port: string;
hostname: string;
isLoopback: boolean;
}
function normalizeHostnameForOriginCheck(hostname: string): string {
const normalized = hostname.trim().toLowerCase();
// URL.hostname may include brackets for IPv6 literals in some runtimes.
if (normalized.startsWith("[") && normalized.endsWith("]")) {
return normalized.slice(1, -1);
}
return normalized;
}
function isLoopbackHostname(hostname: string): boolean {
const normalized = normalizeHostnameForOriginCheck(hostname);
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
}
function parseOriginIdentity(rawOrigin: string): OriginIdentity | null {
try {
const parsed = new URL(rawOrigin);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
return null;
}
const hostname = normalizeHostnameForOriginCheck(parsed.hostname);
return {
protocol: parsed.protocol,
port: parsed.port,
hostname,
isLoopback: isLoopbackHostname(hostname),
};
} catch {
return null;
}
}
// In local development, the browser and proxy may use loopback aliases interchangeably.
// Treat loopback host aliases as equivalent origins when protocol+port match.
function areEquivalentLoopbackOrigins(originA: string, originB: string): boolean {
const identityA = parseOriginIdentity(originA);
const identityB = parseOriginIdentity(originB);
if (!identityA || !identityB) {
return false;
}
return (
identityA.protocol === identityB.protocol &&
identityA.port === identityB.port &&
identityA.isLoopback &&
identityB.isLoopback
);
}
function isOriginAllowed(
req: OriginValidationRequest,
expectedOrigins: readonly string[] = getExpectedOrigins(req)
): boolean {
const origin = getFirstHeaderValue(req, "origin");
if (!origin) {
return true;
}
const normalizedOrigin = normalizeOrigin(origin);
if (!normalizedOrigin || expectedOrigins.length === 0) {
return false;
}
return expectedOrigins.some(
(expectedOrigin) =>
normalizedOrigin === expectedOrigin ||
areEquivalentLoopbackOrigins(normalizedOrigin, expectedOrigin)
);
}
const URL_PATHNAME_RE = /^[A-Za-z0-9._~!$&'()*+,;=:@%/-]+$/;
const PUBLIC_BASE_PATH_VARY_HEADERS = [
"X-Forwarded-Prefix",
"X-Forwarded-Uri",
"X-Original-Uri",
"X-Original-Url",
"Referer",
] as const;
interface PublicBasePathLocals {
publicBasePath?: string;
}
type PublicBasePathRequest = Pick<http.IncomingMessage, "headers" | "url"> & {
originalUrl?: string;
};
function isValidUrlPathname(value: string): boolean {
return (
value.length > 0 &&
value.startsWith("/") &&
!value.startsWith("//") &&
URL_PATHNAME_RE.test(value)
);
}
function normalizePublicBasePath(value: string | null | undefined): string | null {
if (!value) {
return null;
}
const trimmed = value.trim();
if (!trimmed || trimmed.startsWith("//")) {
return null;
}
const withLeadingSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
const withoutTrailingSlash =
withLeadingSlash === "/" ? withLeadingSlash : withLeadingSlash.replace(/\/+$/, "");
return isValidUrlPathname(withoutTrailingSlash) ? withoutTrailingSlash : null;
}
function parsePathnameFromRequestValue(value: string | null | undefined): string | null {
if (!value) {
return null;
}
const trimmed = value.trim();
if (!trimmed || trimmed.startsWith("//")) {
return null;
}
try {
const pathname = trimmed.startsWith("/")
? new URL(trimmed, "http://localhost").pathname
: new URL(trimmed).pathname;
return isValidUrlPathname(pathname) ? pathname : null;
} catch {
return null;
}
}
function getPathnameFromRequestUrl(requestUrl: string | undefined): string | null {
return parsePathnameFromRequestValue(requestUrl);
}
function getRequestPublicBasePath(
req: PublicBasePathRequest,
options: { allowReferer?: boolean } = {}
): string {
const forwardedPrefix = normalizePublicBasePath(getFirstHeaderValue(req, "x-forwarded-prefix"));
if (forwardedPrefix) {
return forwardedPrefix;
}
for (const headerName of ["x-forwarded-uri", "x-original-uri", "x-original-url"] as const) {
const headerPathname = parsePathnameFromRequestValue(getFirstHeaderValue(req, headerName));
const headerBasePath = headerPathname ? getAppProxyBasePathFromPathname(headerPathname) : null;
if (headerBasePath) {
return headerBasePath;
}
}
for (const requestValue of [req.originalUrl, req.url]) {
const requestPathname = parsePathnameFromRequestValue(requestValue);
const requestBasePath = requestPathname
? getAppProxyBasePathFromPathname(requestPathname)
: null;
if (requestBasePath) {
return requestBasePath;
}
}
// Browser mode requests include Referer by default, so this keeps cookie scope
// and generated app links aligned when a proxy strips the public prefix.
if (options.allowReferer) {
const refererPathname = parsePathnameFromRequestValue(getFirstHeaderValue(req, "referer"));
const refererBasePath = refererPathname
? getAppProxyBasePathFromPathname(refererPathname)
: null;
if (refererBasePath) {
return refererBasePath;
}
}
return "/";
}
function setResponsePublicBasePath(res: express.Response, publicBasePath: string): void {
(res.locals as PublicBasePathLocals).publicBasePath = publicBasePath;
}
function getResponsePublicBasePath(res: express.Response): string | null {
const publicBasePath = (res.locals as PublicBasePathLocals).publicBasePath;
return typeof publicBasePath === "string" ? publicBasePath : null;
}
function getPublicBasePathForRequest(
req: express.Request,
res: express.Response,
options: { allowReferer?: boolean } = {}
): string {
return getResponsePublicBasePath(res) ?? getRequestPublicBasePath(req, options);
}
function joinPublicBasePath(publicBasePath: string, routePathname: string): string {
const normalizedBasePath = normalizePublicBasePath(publicBasePath) ?? "/";
const normalizedRoutePathname = routePathname.startsWith("/")
? routePathname
: `/${routePathname}`;
return normalizedBasePath === "/"
? normalizedRoutePathname
: `${normalizedBasePath}${normalizedRoutePathname}`;
}
function getDirectAppProxyHandlerPrefix(
req: express.Request,
routePrefix: `/${string}`
): `/${string}` {
const originalPathname = parsePathnameFromRequestValue(req.originalUrl);
const directBasePath = originalPathname
? getAppProxyBasePathFromPathname(originalPathname)
: null;
return directBasePath
? (joinPublicBasePath(directBasePath, routePrefix) as `/${string}`)
: routePrefix;
}
function getRoutePathnameForBaseHref(req: express.Request): string | null {
return getPathnameFromRequestUrl(req.url);
}
function getRelativeBaseHrefFromRoutePathname(routePathname: string): string {
const pathname = routePathname.startsWith("/") ? routePathname : `/${routePathname}`;
const segments = pathname.split("/").slice(1);
const depth = Math.max(0, segments.length - 1);
return depth === 0 ? "./" : `./${"../".repeat(depth)}`;
}
function shouldInjectSlashlessRootRedirect(req: express.Request): boolean {
return getRoutePathnameForBaseHref(req) === "/";
}
function getPublicBaseHref(req: express.Request, res: express.Response): string {
const publicBasePath = getPublicBasePathForRequest(req, res, { allowReferer: true });
if (publicBasePath !== "/") {
return `${publicBasePath}/`;
}
// User rationale: when a reverse proxy strips the app prefix without forwarding
// headers, a relative climb still lets the browser resolve assets from the
// public app root. Root-hosted deep links resolve correctly too.
return getRelativeBaseHrefFromRoutePathname(getRoutePathnameForBaseHref(req) ?? "/");
}
function getPublicAppRootPath(req: express.Request, res: express.Response): string {
return joinPublicBasePath(getPublicBasePathForRequest(req, res, { allowReferer: true }), "/");
}
function varyPublicBasePathHeaders(res: express.Response): void {
for (const header of PUBLIC_BASE_PATH_VARY_HEADERS) {
res.vary(header);
}
}
function splitRequestUrlPathAndQuery(
requestUrl: string | undefined
): { pathname: string; querySuffix: string } | null {
if (!requestUrl) {
return null;
}
const queryStart = requestUrl.indexOf("?");
if (queryStart === -1) {
return { pathname: requestUrl, querySuffix: "" };
}
return {
pathname: requestUrl.slice(0, queryStart),
querySuffix: requestUrl.slice(queryStart),
};
}
function getNormalizedUpgradeRoute(
requestUrl: string | undefined
): { routePathname: string; routeUrl: string } | null {
const publicPathname = getPathnameFromRequestUrl(requestUrl);
if (!publicPathname) {
return null;
}
const { routePathname } = stripAppProxyBasePath(publicPathname);
const querySuffix = splitRequestUrlPathAndQuery(requestUrl)?.querySuffix ?? "";
return { routePathname, routeUrl: `${routePathname}${querySuffix}` };
}
function isSafeHttpHostHeader(host: string): boolean {
if (host.trim().length === 0 || host.includes("/") || host.includes("\\")) {
return false;
}
for (const character of host) {
const codePoint = character.codePointAt(0);
if (codePoint !== undefined && (codePoint < 0x20 || codePoint === 0x7f)) {
return false;
}
}
return true;
}
function getValidatedPublicHost(req: express.Request, protocol: "http" | "https"): string | null {
for (const headerName of ["x-forwarded-host", "host"] as const) {
const host = getFirstHeaderValue(req, headerName);
if (!host || !isSafeHttpHostHeader(host)) {
continue;
}
const normalizedHost = normalizeHostForProtocol(host, protocol);
if (normalizedHost) {
return normalizedHost;
}
}
return null;
}
function buildPublicAbsoluteUrl(
req: express.Request,
routePathname: string,
allowHttpOrigin: boolean
): string | null {
const protocol = getPreferredPublicProtocol(req, allowHttpOrigin);
const host = getValidatedPublicHost(req, protocol);
if (!host) {
return null;
}
const publicRoutePathname = joinPublicBasePath(
getRequestPublicBasePath(req, { allowReferer: true }),
routePathname
);
return `${protocol}://${host}${publicRoutePathname}`;
}
const OAUTH_CALLBACK_ORIGIN_BYPASS_PATHS = new Set<string>([
"/auth/mux-gateway/callback",
"/auth/mux-governor/callback",
"/auth/mcp-oauth/callback",
]);
function isOAuthCallbackNavigationRequest(req: Pick<express.Request, "method" | "path">): boolean {
return (
(req.method === "GET" || req.method === "POST") &&
OAUTH_CALLBACK_ORIGIN_BYPASS_PATHS.has(req.path)
);
}
function shouldEnforceOriginValidation(req: Pick<express.Request, "path">): boolean {
// User rationale: static HTML/CSS/JS must keep loading even when intermediaries rewrite
// Origin/forwarded headers, while API and auth endpoints retain strict same-origin checks.
return (
req.path.startsWith("/orpc") || req.path.startsWith("/api") || req.path.startsWith("/auth/")
);
}
/**
* Create an oRPC server with HTTP and WebSocket endpoints.
*
* HTTP endpoint: /orpc
* WebSocket endpoint: /orpc/ws
* Desktop relay WebSocket endpoint: /desktop/ws
* Browser relay WebSocket endpoint: /browser/ws
* Health check: /health
* Version: /version
*/
export async function createOrpcServer({
host = "127.0.0.1",
port = 0,
authToken,
context,
serveStatic = false,
allowHttpOrigin = false,
// Default for non-bundled mode: from dist/node/orpc/, go up 2 levels to dist/.
// In bundled mode (dist/runtime/), serverService computes the static dir.
staticDir = path.join(__dirname, "../.."),
onOrpcError = (error, options) => {
// Auth failures are expected in browser mode while the user enters the token.
// Avoid spamming error logs with stack traces on every unauthenticated request.
if (error instanceof ORPCError && error.code === "UNAUTHORIZED") {
log.debug("ORPC unauthorized request");
return;
}
const formatted = formatOrpcError(error, options);
log.error(formatted.message);
if (log.isDebugMode()) {
const suffix = Math.random().toString(16).slice(2);
log.debug_obj(`orpc/${Date.now()}_${suffix}.json`, formatted.debugDump);
}
},
router: existingRouter,
desktopBridgeServer = context.desktopBridgeServer,
browserBridgeServer = context.browserBridgeServer,
}: OrpcServerOptions): Promise<OrpcServer> {
// Express app setup
const app = express();
app.use((req, res, next) => {
const requestPath = splitRequestUrlPathAndQuery(req.url);
if (requestPath && isValidUrlPathname(requestPath.pathname)) {
const { basePath, routePathname } = stripAppProxyBasePath(requestPath.pathname);
if (basePath) {
setResponsePublicBasePath(res, basePath);
req.url = `${routePathname}${requestPath.querySuffix}`;
next();
return;
}
}
const publicBasePath = getRequestPublicBasePath(req);
if (publicBasePath !== "/") {
setResponsePublicBasePath(res, publicBasePath);
}
next();
});
app.use((req, res, next) => {
if (!shouldEnforceOriginValidation(req)) {
next();
return;
}
const originHeader = getFirstHeaderValue(req, "origin");
if (!originHeader) {
next();
return;
}
const normalizedOrigin = normalizeOrigin(originHeader);
const expectedOrigins = getExpectedOrigins(req, allowHttpOrigin);
const allowedOrigin = isOriginAllowed(req, expectedOrigins) ? normalizedOrigin : null;
const oauthCallbackNavigationRequest = isOAuthCallbackNavigationRequest(req);
if (req.method === "OPTIONS") {
if (!allowedOrigin) {
log.warn("Blocked cross-origin CORS preflight request", {
method: req.method,
path: req.path,
origin: originHeader,
expectedOrigins,
});
res.sendStatus(403);
return;
}
res.setHeader("Vary", "Origin");
res.setHeader("Access-Control-Allow-Origin", allowedOrigin);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Max-Age", "86400");
res.sendStatus(204);
return;
}
if (!allowedOrigin) {
// OAuth redirects can legitimately arrive from a different origin (including
// response_mode=form_post). These callback handlers validate OAuth state
// before exchanging codes, so allowing navigation requests here is safe.
if (oauthCallbackNavigationRequest) {
next();
return;
}
log.warn("Blocked cross-origin HTTP request", {
method: req.method,
path: req.path,
origin: originHeader,
expectedOrigins,
});
res.sendStatus(403);
return;
}
res.setHeader("Vary", "Origin");
res.setHeader("Access-Control-Allow-Origin", allowedOrigin);
res.setHeader("Access-Control-Allow-Credentials", "true");
next();
});
// OAuth providers may use POST redirects (307/308) or response_mode=form_post.
// Support both JSON API requests and form-encoded callback payloads.
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ extended: false }));
let rawSpaIndexHtml: string | null = null;
// Static file serving (optional)
if (serveStatic) {
try {
const indexHtmlPath = path.join(staticDir, "index.html");
rawSpaIndexHtml = await fs.readFile(indexHtmlPath, "utf8");
} catch (error) {
log.error("Failed to read index.html for SPA fallback:", error);
}
// Serve JS/CSS/assets from disk, but never serve index.html — the SPA fallback
// (below all API routes) serves the injected version with base href + proxy template.
const serveStaticAssets = express.static(staticDir, { index: false });
app.use((req, res, next) => {
if (req.path === "/index.html") return next();
serveStaticAssets(req, res, next);
});
}
// Health check endpoint
app.get("/health", (_req, res) => {
res.json({ status: "ok" });
});
// Version endpoint
app.get("/version", (_req, res) => {
res.json({ ...VERSION, mode: "server" });
});
function getRequestIpAddress(
req: Pick<express.Request, "headers" | "socket">
): string | undefined {
const forwardedFor = getFirstHeaderValue(req, "x-forwarded-for");
if (forwardedFor) {
const first = forwardedFor.split(",")[0]?.trim();
if (first) {
return first;
}
}
const remoteAddress = req.socket.remoteAddress?.trim();
return remoteAddress?.length ? remoteAddress : undefined;
}
function isSecureRequest(req: OriginValidationRequest): boolean {
return getPreferredPublicProtocol(req, allowHttpOrigin) === "https";
}
function getServerSessionCookiePath(req: express.Request): string {
return getRequestPublicBasePath(req, { allowReferer: true });
}
function buildServerSessionCookie(
sessionToken: string,
secure: boolean,
cookiePath: string
): string {
const encoded = encodeURIComponent(sessionToken);
return `${SERVER_AUTH_SESSION_COOKIE_NAME}=${encoded}; Path=${cookiePath}; HttpOnly; SameSite=Strict; Max-Age=${SERVER_AUTH_SESSION_MAX_AGE_SECONDS}${secure ? "; Secure" : ""}`;
}
async function isHttpRequestAuthenticated(req: express.Request): Promise<boolean> {
if (!authToken?.trim()) {
return true;
}
const expectedToken = authToken.trim();
const presentedToken = extractBearerToken(req.header("authorization"));
if (presentedToken && safeEq(presentedToken, expectedToken)) {
return true;
}
const sessionTokens = extractCookieValues(req.headers.cookie, SERVER_AUTH_SESSION_COOKIE_NAME);
if (sessionTokens.length === 0) {
return false;
}
for (const sessionToken of sessionTokens) {
const validation = await context.serverAuthService.validateSessionToken(sessionToken, {
userAgent: req.header("user-agent") ?? undefined,
ipAddress: getRequestIpAddress(req),
});
if (validation != null) {
return true;
}
}
return false;
}
function getStringParamFromQueryOrBody(req: express.Request, key: string): string | null {
const queryValue = req.query[key];
if (typeof queryValue === "string") return queryValue;
const bodyRecord = req.body as Record<string, unknown> | undefined;
const bodyValue = bodyRecord?.[key];
return typeof bodyValue === "string" ? bodyValue : null;
}
app.get("/auth/server-login/options", (_req, res) => {
res.json({ githubDeviceFlowEnabled: context.serverAuthService.isGithubDeviceFlowEnabled() });
});
app.post("/auth/server-login/github/start", async (_req, res) => {
const startResult = await context.serverAuthService.startGithubDeviceFlow();
if (!startResult.success) {
const status = startResult.error.includes("Too many concurrent GitHub login attempts")
? 429
: 400;
res.status(status).json({ error: startResult.error });
return;
}
res.json(startResult.data);
});
app.post("/auth/server-login/github/wait", async (req, res) => {
const flowId = getStringParamFromQueryOrBody(req, "flowId");
if (!flowId) {
res.status(400).json({ error: "Missing flowId" });
return;
}
let canceledByDisconnect = false;
const cancelFlowForDisconnect = () => {
if (canceledByDisconnect) {
return;
}
canceledByDisconnect = true;
context.serverAuthService.cancelGithubDeviceFlow(flowId);
};
const handleRequestAborted = () => {
cancelFlowForDisconnect();