Skip to content

Commit f268f48

Browse files
committed
fix: pass auth token to browser WebSocket connection
When the server is started with --auth-token, the browser client now passes the token via query parameter (?token=...) when connecting to the ORPC WebSocket endpoint. The token is read from VITE_AUTH_TOKEN environment variable at build time. Change-Id: Ic0e253cf128cae361af5032b0dbc0decb92dbd5f Signed-off-by: Thomas Kosiewski <tk@coder.com>
1 parent 1531544 commit f268f48

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

index.html

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@
5151
</head>
5252
<body>
5353
<div id="root"></div>
54+
<!-- Load server-provided config (auth token) for browser mode. Fails silently in Electron/dev. -->
55+
<script src="/client-config.js" onerror="window.__MUX_AUTH_TOKEN__=null"></script>
5456
<script type="module" src="/src/browser/main.tsx"></script>
5557
</body>
5658
</html>

src/browser/orpc/react.tsx

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,19 @@ export const ORPCProvider = (props: ORPCProviderProps) => {
5757
const API_BASE = import.meta.env.VITE_BACKEND_URL ?? window.location.origin;
5858
const WS_BASE = API_BASE.replace("http://", "ws://").replace("https://", "wss://");
5959

60-
const ws = new WebSocket(`${WS_BASE}/orpc/ws`);
60+
// Auth token is injected by server via /client-config.js (loaded in index.html)
61+
// or can be passed as URL parameter for direct links
62+
const urlParams = new URLSearchParams(window.location.search);
63+
const authToken =
64+
urlParams.get("token") ??
65+
(window as unknown as { __MUX_AUTH_TOKEN__?: string }).__MUX_AUTH_TOKEN__ ??
66+
null;
67+
68+
const wsUrl = authToken
69+
? `${WS_BASE}/orpc/ws?token=${encodeURIComponent(authToken)}`
70+
: `${WS_BASE}/orpc/ws`;
71+
72+
const ws = new WebSocket(wsUrl);
6173
const link = new WebSocketLink({
6274
websocket: ws,
6375
});

src/cli/orpcServer.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,18 @@ export async function createOrpcServer({
9393
res.json({ ...VERSION, mode: "server" });
9494
});
9595

96+
// Client config endpoint - provides auth token for WebSocket connection
97+
// This is served without auth since the browser needs it to establish the authenticated connection
98+
// Security note: This endpoint should only be accessible to users who already have network access to the server
99+
app.get("/client-config.js", (_req, res) => {
100+
res.type("application/javascript");
101+
if (authToken) {
102+
res.send(`window.__MUX_AUTH_TOKEN__ = ${JSON.stringify(authToken)};`);
103+
} else {
104+
res.send(`window.__MUX_AUTH_TOKEN__ = null;`);
105+
}
106+
});
107+
96108
const orpcRouter = router(authToken);
97109

98110
// oRPC HTTP handler

0 commit comments

Comments
 (0)