| 373 | * @param {(message: string, error?: unknown) => void} [options.log] |
| 374 | */ |
| 375 | export function createMarsWebBridge({ |
| 376 | bridge: bridgeOverride, |
| 377 | env = process.env, |
| 378 | host = DEFAULT_BIND_HOST, |
| 379 | key = null, |
| 380 | stateDir = null, |
| 381 | log = (message, error) => console.warn(`[mars-web] ${message}`, error ?? ""), |
| 382 | } = {}) { |
| 383 | const dir = stateDir ? path.join(stateDir, STATE_SUBDIR) : null; |
| 384 | const bridge = |
| 385 | bridgeOverride ?? |
| 386 | createMarsTunnelBridge({ |
| 387 | userDataPath: dir, |
| 388 | secrets: openSecretStore({ env, dir }), |
| 389 | env, |
| 390 | }); |
| 391 | |
| 392 | /** Both ends of proxied WebSockets, so dispose() can close them. */ |
| 393 | const sockets = new Set(); |
| 394 | function track(socket) { |
| 395 | sockets.add(socket); |
| 396 | socket.once("close", () => sockets.delete(socket)); |
| 397 | } |
| 398 | // Its own proxy rather than the hosting server's: agent-server calls can |
| 399 | // stay silent far longer than a static backend's timeout, the session host |
| 400 | // has no use for X-Forwarded-* from the canvas, and errors answer in the |
| 401 | // same JSON shape as the rest of /mars/*. |
| 402 | const proxy = createProxyHandlers({ |
| 403 | label: "mars-web", |
| 404 | timeout: 0, |
| 405 | proxyTimeout: 0, |
| 406 | xfwd: false, |
| 407 | errorBody: (message) => ({ |
| 408 | contentType: "application/json", |
| 409 | body: JSON.stringify({ |
| 410 | error: { message: `upstream request failed: ${message}` }, |
| 411 | }), |
| 412 | }), |
| 413 | onProxySocket: track, |
| 414 | }); |
| 415 | /** Cookie value handed to requests that presented the key. */ |
| 416 | const cookieToken = key |
| 417 | ? deriveAuthCookieValue(key) |
| 418 | : randomBytes(32).toString("hex"); |
| 419 | |
| 420 | /** |
| 421 | * Whether the request may use the bridge. With no key configured every |
| 422 | * same-host request may. Otherwise it must carry the key (HTTP) or the |
| 423 | * cookie a keyed request earned (HTTP or WebSocket upgrade). Returns |
| 424 | * `"issue"` when the key was presented so the response can set the cookie. |
| 425 | */ |
| 426 | function authorize(req) { |
| 427 | if (!key) return "ok"; |
| 428 | const presented = req.headers[AUTH_HEADER]; |
| 429 | if (typeof presented === "string" && safeEqual(presented, key)) { |
| 430 | return "issue"; |
| 431 | } |
| 432 | const cookie = readCookie(req, AUTH_COOKIE); |