import { authenticatedProxyOptionsFromEnv, startAuthenticatedInspectorProxy, } from "../src/web/authenticated-proxy.js"; import { createInspectorOAuthAuth, oauthConfigurationFromEnv, } from "../src/web/oauth-auth.js"; import { configureCoChat } from "../src/web/co-chat-config.js"; const options = authenticatedProxyOptionsFromEnv(); const oauthConfiguration = oauthConfigurationFromEnv(); if (process.env.THOUGHTSTREAM_CO_CHAT_ENABLED !== undefined && !["true", "false"].includes(process.env.THOUGHTSTREAM_CO_CHAT_ENABLED)) throw new Error("Invalid Co chat enablement"); const oauth = oauthConfiguration.enabled ? await createInspectorOAuthAuth({ publicOrigin: oauthConfiguration.publicOrigin!, allowedDid: oauthConfiguration.allowedDid!, expectedHandle: oauthConfiguration.expectedHandle!, storeDirectory: oauthConfiguration.storeDirectory!, storeKey: oauthConfiguration.storeKey!, privateJwk: oauthConfiguration.privateJwk!, ...(oauthConfiguration.sessionTtlMs ? { sessionTtlMs: oauthConfiguration.sessionTtlMs } : {}), }) : undefined; let server: Awaited>; let coChat: Awaited>; try { if (process.env.THOUGHTSTREAM_CO_CHAT_ENABLED === "true" && !oauth) throw new Error("Co chat requires OAuth"); if (oauth) coChat = await configureCoChat({ origin: oauthConfiguration.publicOrigin!, directory: oauthConfiguration.storeDirectory!, key: oauthConfiguration.storeKey!, projectRoot: options.projectRoot ?? process.cwd() }); server = await startAuthenticatedInspectorProxy({ ...options, ...(oauth ? { oauth } : {}), ...(coChat ? { coChat } : {}) }); } catch (error) { await coChat?.chat.close(); await oauth?.close(); throw error; } process.stdout.write(`thought stream web proxy: http://${options.host}:${options.port} oauth=${oauth ? "enabled" : "disabled"} basicFallback=${options.basicFallbackEnabled ? "enabled" : "disabled"}\n`); for (const signal of ["SIGINT", "SIGTERM"] as const) { process.once(signal, () => { const chatClosed = coChat?.chat.close() ?? Promise.resolve(); server.closeAllConnections(); server.close(() => { void chatClosed.then(() => oauth?.close()).then(() => process.exit(0), () => process.exit(1)); }); setTimeout(() => process.exit(1), 2_000).unref(); }); }