From ae66dcf7074d654b7545c3f89a9065864ceceedb Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:49:35 +0000 Subject: [PATCH 1/2] feat(auth): verify founder sessions through WorkOS AuthKit Model: gpt-6.2-sol Task: implementation Agent: Codex Lane: codex --- .../test-t3-app/references/feature-map.md | 4 +- .../DesktopLocalEnvironmentAuth.test.ts | 36 ++ .../backend/DesktopLocalEnvironmentAuth.ts | 141 ++++++- apps/desktop/src/ipc/DesktopIpcHandlers.ts | 2 + apps/desktop/src/ipc/channels.ts | 1 + apps/desktop/src/ipc/methods/window.ts | 13 +- apps/desktop/src/preload.ts | 1 + apps/server/package.json | 1 + apps/server/src/auth/EnvironmentAuth.ts | 53 ++- apps/server/src/auth/SessionStore.ts | 12 +- apps/server/src/auth/WorkOsAuth.test.ts | 317 +++++++++++++++ apps/server/src/auth/WorkOsAuth.ts | 363 ++++++++++++++++++ apps/server/src/auth/WorkOsConfig.ts | 93 +++++ apps/server/src/auth/workOsHttp.ts | 169 ++++++++ apps/server/src/http.ts | 2 + apps/server/src/persistence/AuthSessions.ts | 15 +- apps/server/src/server.ts | 4 + .../components/auth/PairingRouteSurface.tsx | 7 + apps/web/src/components/auth/WorkOsSignIn.tsx | 66 ++++ .../settings/ConnectionsSettings.tsx | 8 + apps/web/src/environments/primary/auth.ts | 4 +- docs/operations/workos-authkit.md | 41 ++ packages/contracts/src/auth.ts | 2 + packages/contracts/src/ipc.ts | 1 + pnpm-lock.yaml | 5 +- 25 files changed, 1335 insertions(+), 26 deletions(-) create mode 100644 apps/server/src/auth/WorkOsAuth.test.ts create mode 100644 apps/server/src/auth/WorkOsAuth.ts create mode 100644 apps/server/src/auth/WorkOsConfig.ts create mode 100644 apps/server/src/auth/workOsHttp.ts create mode 100644 apps/web/src/components/auth/WorkOsSignIn.tsx create mode 100644 docs/operations/workos-authkit.md diff --git a/.agents/skills/test-t3-app/references/feature-map.md b/.agents/skills/test-t3-app/references/feature-map.md index 106a343211f2c..d2466d94b6979 100644 --- a/.agents/skills/test-t3-app/references/feature-map.md +++ b/.agents/skills/test-t3-app/references/feature-map.md @@ -208,7 +208,7 @@ Code: Connections: -- **settings.connections** — `/settings/connections`, "Environments": "This machine", "Linked environments", "Network access", "Tailscale HTTPS", "T3 Connect", "Load balancing". +- **settings.connections** — `/settings/connections`, "Environments": "This machine", "Linked environments", "Network access", "Tailscale HTTPS", "T3 Connect", "Load balancing", "Google sign-in" (when configured). - **settings.access** — `/settings/access`, "Sharing & access": paired devices, "Guest links", "Require approval for new devices". - **settings.secrets** — `/settings/secrets`, "Secrets" (only when secrets are enabled). @@ -230,7 +230,7 @@ Old links that redirect: ## Onboarding, pairing and connect pages - **onboard.welcome** — `/welcome`, "Welcome": "Set up an agent" (Codex, Claude Code), "Import projects and their threads", "Set up T3 Connect", mobile app pointer. -- **onboard.pair** — `/pair`, "Pair with this environment": "Paste a one-time token or pairing secret". +- **onboard.pair** — `/pair`, "Pair with this environment": "Paste a one-time token or pairing secret", "Sign in with Google" (when configured). - **onboard.connect** — `/connect`, "Authorization request", "Connecting your terminal": approves a `t3` CLI sign-in through T3 Connect. - **onboard.connect-agent** — `/connect-agent`, "Agent sign-in", "Connect ": lets an outside agent connect. Reached from the code made by "Use T3 Code in another app (MCP)". - **onboard.approve-agent** — `/approve-agent`, "Agent sign-in": "Choose what it may do", "Read only", "Continue", "Deny". diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts index c15ce3932bb80..e7726052ce715 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts @@ -193,6 +193,42 @@ describe("DesktopLocalEnvironmentAuth", () => { }, ]), } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]); + + it.effect("uses the WorkOS session only after the browser handoff completes", () => + Effect.gen(function* () { + const authorizationUrl = "https://t3.example.test/api/auth/workos/start?desktop=handoff"; + const opened = yield* Ref.make(null); + const layerHttpClient = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => { + const path = new URL(request.url).pathname; + if (path === "/oauth/token") return Effect.succeed(tokenResponse(request)); + const response = path.endsWith("/start") + ? Response.json({ id: "handoff", authorizationUrl }) + : path.endsWith("/finish") + ? Response.json({ token: "verified-session", expiresAt: 120_000 }) + : new Response(null, { status: 204 }); + return Effect.succeed(HttpClientResponse.fromWeb(request, response)); + }), + ); + const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe( + Effect.provide( + DesktopLocalEnvironmentAuth.layer.pipe( + Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)), + ), + ), + ); + const open = (url: unknown) => Ref.set(opened, url).pipe(Effect.as(true)); + yield* auth.workOsAction("start", open); + assert.strictEqual(yield* Ref.get(opened), authorizationUrl); + assert.strictEqual(yield* auth.getRendererBearerToken, "desktop-bearer-token"); + yield* auth.workOsAction("finish", open); + assert.strictEqual(yield* auth.getRendererBearerToken, "verified-session"); + yield* auth.workOsAction("logout", open); + assert.strictEqual(yield* auth.getRendererBearerToken, "desktop-bearer-token"); + }), + ); + const makeExchange = (failures: number, failure: () => Response) => Effect.gen(function* () { const requestCount = yield* Ref.make(0); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts index 89aa3cd2a678c..a91ea29d8a84c 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics nodeBuiltinImport:off - PKCE is generated in the Electron main process. +import * as NodeCrypto from "node:crypto"; import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization"; import type { RemoteEnvironmentRequestError } from "@t3tools/client-runtime/rpc"; import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts"; @@ -13,8 +15,9 @@ import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; -import * as HttpClient from "effect/http/HttpClient"; +import { HttpClient, HttpClientRequest } from "effect/http"; +import * as ElectronShell from "../electron/ElectronShell.ts"; import * as DesktopBackendPool from "./DesktopBackendPool.ts"; // Each /oauth/token attempt may take 10 s, so a backend busy after ready needs several attempts. @@ -58,10 +61,25 @@ export const DesktopLocalEnvironmentAuthError = Schema.Union([ ]); export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type; +const DesktopStart = Schema.Struct({ id: Schema.String, authorizationUrl: Schema.String }); +const DesktopFinish = Schema.Struct({ token: Schema.String, expiresAt: Schema.Number }); +const decodeWorkOsStart = Schema.decodeUnknownEffect(DesktopStart); +const decodeWorkOsFinish = Schema.decodeUnknownEffect(DesktopFinish); + +export class DesktopWorkOsRequestError extends Schema.TaggedError()( + "DesktopWorkOsRequestError", + { message: Schema.String }, +) {} + export class DesktopLocalEnvironmentAuth extends Context.Service< DesktopLocalEnvironmentAuth, { readonly getBearerToken: Effect.Effect; + readonly getRendererBearerToken: Effect.Effect; + readonly workOsAction: ( + action: "start" | "finish" | "logout", + openExternal: ElectronShell.ElectronShell["Service"]["openExternal"], + ) => Effect.Effect; } >()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {} @@ -72,6 +90,25 @@ export const make = Effect.gen(function* () { const mac = yield* Mac.Mac; const tokenRef = yield* Ref.make(Option.none()); const mutex = yield* Semaphore.make(1); + const workOsMutex = yield* Semaphore.make(1); + let pending: + | { readonly base: string; readonly id: string; readonly verifier: string } + | undefined; + let verified: + | { readonly base: string; readonly token: string; readonly expiresAt: number } + | undefined; + + const primaryConfig = Effect.fn("DesktopLocalEnvironmentAuth.primaryConfig")(function* () { + const instances = yield* pool.list; + const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID); + if (primary === undefined || !(yield* primary.waitForReady(Duration.infinity))) { + return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); + } + const config = yield* primary.currentConfig; + if (Option.isNone(config)) + return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); + return config.value; + }); const getBearerToken = mutex .withPermits(1)( @@ -81,16 +118,7 @@ export const make = Effect.gen(function* () { return cached.value; } - const instances = yield* pool.list; - const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID); - if (primary === undefined || !(yield* primary.waitForReady(Duration.infinity))) { - return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); - } - const configOption = yield* primary.currentConfig; - if (Option.isNone(configOption)) { - return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); - } - const config = configOption.value; + const config = yield* primaryConfig(); // Secret-authenticated backends accept the current window token; the launch token may be stale. const secret = config.bootstrap.desktopBootstrapSecret; const credential = @@ -129,7 +157,96 @@ export const make = Effect.gen(function* () { ) .pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken")); - return DesktopLocalEnvironmentAuth.of({ getBearerToken }); + const getRendererBearerToken = Effect.gen(function* () { + if (verified && verified.expiresAt > (yield* Clock.currentTimeMillis)) { + const current = yield* primaryConfig(); + if (current.httpBaseUrl.href === verified.base) return verified.token; + } + return yield* getBearerToken; + }); + + const requestWorkOs = Effect.fn("DesktopLocalEnvironmentAuth.requestWorkOs")(function* ( + base: string, + path: "desktop/start" | "desktop/finish" | "logout", + token: string, + body?: object, + ) { + const unavailable = () => + new DesktopWorkOsRequestError({ message: "Could not reach the local T3 Code server." }); + const request = HttpClientRequest.post(new URL(`/api/auth/workos/${path}`, base)).pipe( + HttpClientRequest.bearerToken(token), + ); + const prepared = body + ? yield* HttpClientRequest.bodyJson(request, body).pipe(Effect.mapError(unavailable)) + : request; + const response = yield* httpClient + .execute(prepared) + .pipe(Effect.timeout("10 seconds"), Effect.mapError(unavailable)); + if (response.status < 200 || response.status >= 300) { + return yield* new DesktopWorkOsRequestError({ + message: + response.status === 409 + ? "Finish Google sign-in in your browser first." + : "Google sign-in could not be completed. Start again.", + }); + } + if (response.status === 204) return undefined; + return yield* response.json.pipe(Effect.mapError(unavailable)); + }); + + const workOsAction: DesktopLocalEnvironmentAuth["Service"]["workOsAction"] = Effect.fn( + "DesktopLocalEnvironmentAuth.workOsAction", + )(function* (action, openExternal) { + const base = (yield* primaryConfig()).httpBaseUrl.href; + const invalidResponse = () => + new DesktopWorkOsRequestError({ + message: "The local server returned an invalid sign-in response.", + }); + if (action === "logout") { + if (verified?.base === base && verified.expiresAt > (yield* Clock.currentTimeMillis)) { + yield* requestWorkOs(base, "logout", verified.token); + } + verified = undefined; + pending = undefined; + return; + } + const token = yield* getBearerToken; + if (action === "start") { + const verifier = NodeCrypto.randomBytes(32).toString("base64url"); + const challenge = NodeCrypto.createHash("sha256").update(verifier).digest("base64url"); + const result = yield* requestWorkOs(base, "desktop/start", token, { challenge }); + const { id, authorizationUrl } = yield* decodeWorkOsStart(result).pipe( + Effect.mapError(invalidResponse), + ); + const url = URL.parse(authorizationUrl); + if ( + url?.protocol !== "https:" || + url.username || + url.password || + url.pathname !== "/api/auth/workos/start" || + url.searchParams.get("desktop") !== id + ) { + return yield* invalidResponse(); + } + if (!(yield* openExternal(url.href))) { + return yield* new DesktopWorkOsRequestError({ + message: "Could not open your system browser.", + }); + } + pending = { base, id, verifier }; + return; + } + if (!pending || pending.base !== base) { + return yield* new DesktopWorkOsRequestError({ message: "Start Google sign-in again." }); + } + const { id, verifier } = pending; + const result = yield* requestWorkOs(base, "desktop/finish", token, { id, verifier }); + const session = yield* decodeWorkOsFinish(result).pipe(Effect.mapError(invalidResponse)); + verified = { base, ...session }; + pending = undefined; + }, workOsMutex.withPermits(1)); + + return DesktopLocalEnvironmentAuth.of({ getBearerToken, getRendererBearerToken, workOsAction }); }); export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 60b72deb293a5..6396942fcd751 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -37,6 +37,7 @@ import { getAppBranding, getLocalEnvironmentBootstraps, getLocalEnvironmentBearerToken, + workOsSignIn, installRelayTelemetryEnabled, getSystemLocale, getPreferredSystemLanguages, @@ -109,6 +110,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(setLocalEnvironmentEnabled); yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); + yield* ipc.handle(workOsSignIn); yield* ipc.handle(restartAudioService); yield* ipc.handle(getClientSettings); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 9e5c7296a3a03..671b3ab416ecb 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -45,6 +45,7 @@ export const SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:set-local-environm export const GET_HOST_ENVIRONMENT_ID_CHANNEL = "desktop:get-host-environment-id"; export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL = "desktop:get-local-environment-bearer-token"; +export const WORKOS_SIGN_IN_CHANNEL = "desktop:workos-sign-in"; export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings"; export const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings"; export const SETUP_SNAP_SHOT_CHANNEL = "desktop:setup-snap-shot"; diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 38887ec71d906..acdc2b5956dfb 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -205,7 +205,18 @@ export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({ result: Schema.String, handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () { const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth; - return yield* localAuth.getBearerToken; + return yield* localAuth.getRendererBearerToken; + }), +}); + +export const workOsSignIn = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WORKOS_SIGN_IN_CHANNEL, + payload: Schema.Literals(["start", "finish", "logout"]), + result: Schema.Void, + handler: Effect.fn("desktop.ipc.window.workOsSignIn")(function* (action) { + const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth; + const shell = yield* ElectronShell.ElectronShell; + yield* localAuth.workOsAction(action, shell.openExternal); }), }); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ba9c17aae2695..b894275541567 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -154,6 +154,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { }, getLocalEnvironmentBearerToken: () => ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL), + workOsSignIn: (action) => ipcRenderer.invoke(IpcChannels.WORKOS_SIGN_IN_CHANNEL, action), getLocalEnvironmentEnabled: () => ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false, setLocalEnvironmentEnabled: (enabled) => diff --git a/apps/server/package.json b/apps/server/package.json index d3765b52c5d27..01cea663f7f88 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -66,6 +66,7 @@ "diff": "8.0.3", "effect": "catalog:", "ffi-rs": "1.3.2", + "jose": "6.2.17", "jsonc-parser": "3.3.1", "node-pty": "^1.2.0-beta.15", "playwright-core": "1.64.1", diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 5798cd3076924..3b73c4e44a24c 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -55,6 +55,7 @@ import * as ManagedLimits from "../policy/managedLimits.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { MCP_APPROVAL_SUBJECT_PREFIX } from "../persistence/AuthPairingLinks.ts"; import { requestUrl } from "../requestUrl.ts"; +import { readConfig, subjectFor, WORKOS_SUBJECT_PREFIX } from "./WorkOsConfig.ts"; const DEFAULT_SESSION_SUBJECT = "cli-issued-session"; export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap"; @@ -826,7 +827,51 @@ export const make = Effect.gen(function* () { const sessions = yield* SessionStore.SessionStore; const secretStore = yield* ServerSecretStore.ServerSecretStore; const digest = yield* Digest.Digest; - const descriptor = yield* policy.getDescriptor(); + const authDescriptor = yield* policy.getDescriptor(); + const workOs = yield* readConfig; + const descriptor = workOs ? { ...authDescriptor, workOsGoogleSignIn: true } : authDescriptor; + const workOsSubjects = workOs + ? new Set([subjectFor(workOs, "kameron"), subjectFor(workOs, "jeff")]) + : new Set(); + const assertWorkOsSession = Effect.fn("EnvironmentAuth.assertWorkOsSession")(( + session: Pick, + request: HttpServerRequest.HttpServerRequest, + socket: boolean, + ): Effect.Effect => { + if (workOs && session.subject === "desktop-bootstrap") { + return Effect.fail( + new ServerAuthInvalidCredentialError({ + diagnostic: "Sign in with Google on this desktop.", + }), + ); + } + if (!session.subject.startsWith(WORKOS_SUBJECT_PREFIX)) return Effect.void; + if (!workOs || !workOsSubjects.has(session.subject)) { + return Effect.fail( + new ServerAuthInvalidCredentialError({ + diagnostic: "WorkOS enrollment no longer applies to this session.", + }), + ); + } + if (session.method !== "browser-session-cookie") return Effect.void; + const requestOrigin = Option.map(requestUrl(request), (url) => url.origin); + const origin = request.headers.origin; + const write = request.method !== "GET" && request.method !== "HEAD"; + if ( + Option.getOrUndefined(requestOrigin) !== workOs.origin || + (socket || write || origin !== undefined + ? origin !== workOs.origin + : request.headers["sec-fetch-site"] !== undefined && + request.headers["sec-fetch-site"] !== "same-origin") + ) { + return Effect.fail( + new ServerAuthInvalidCredentialError({ + diagnostic: "WorkOS browser sessions require the configured HTTPS origin.", + }), + ); + } + return Effect.void; + }); const config = yield* ServerConfig.ServerConfig; const managedPolicy = yield* ManagedPolicy.ManagedPolicy; const devAuth = resolveReusableDevAuth(config); @@ -884,6 +929,7 @@ export const make = Effect.gen(function* () { const authenticateRequest = ( request: HttpServerRequest.HttpServerRequest, + socket = false, ): Effect.Effect => { const dpopToken = parseDpopToken(request); const credential = resolveRequestCredential(request); @@ -901,6 +947,7 @@ export const make = Effect.gen(function* () { ); } return authenticateToken(credential.token).pipe( + Effect.tap((session) => assertWorkOsSession(session, request, socket)), Effect.flatMap((session) => { if (session.proofKeyThumbprint) { if (!dpopToken || dpopToken !== credential.token) { @@ -940,6 +987,7 @@ export const make = Effect.gen(function* () { (session) => ({ authenticated: true, + ...(workOsSubjects.has(session.subject) ? { workOsSession: true } : {}), auth: descriptor, ...authScopeResponse(session.scopes), sessionMethod: session.method, @@ -1576,6 +1624,7 @@ export const make = Effect.gen(function* () { const session = yield* sessions .verifyWebSocketToken(websocketTicket) .pipe(mapSessionVerificationErrors, Effect.flatMap(rejectMcpClientAudience)); + yield* assertWorkOsSession(session, request, true); if (session.audience !== undefined && session.audience !== use) { return yield* new ServerAuthInvalidCredentialError({ diagnostic: `WebSocket ticket was issued for the ${session.audience} route.`, @@ -1615,7 +1664,7 @@ export const make = Effect.gen(function* () { } } - return yield* authenticateRequest(request); + return yield* authenticateRequest(request, true); }); const authenticateMcpClient: EnvironmentAuth["Service"]["authenticateMcpClient"] = (request) => { diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index c03d4c686a1a5..1e06fdfec0a4f 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -408,6 +408,8 @@ export class SessionStore extends Context.Service< readonly legacyCookieName: string | undefined; readonly issue: (input?: { readonly ttl?: Duration.Duration; + readonly expiresAt?: DateTime.Utc; + readonly founder?: Founder; readonly subject?: string; readonly method?: ServerAuthSessionMethod; readonly scopes?: ReadonlyArray; @@ -713,9 +715,11 @@ const make = Effect.gen(function* () { .pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ cause }))), ); const issuedAt = yield* DateTime.now; - const expiresAt = DateTime.add(issuedAt, { - milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL), - }); + const expiresAt = + input?.expiresAt ?? + DateTime.add(issuedAt, { + milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL), + }); const claims: SessionClaims = { v: 1, kind: "session", @@ -761,6 +765,7 @@ const make = Effect.gen(function* () { }, issuedAt, expiresAt, + ...(input?.founder ? { founder: input.founder } : {}), ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}), } satisfies AuthSessions.CreateAuthSessionInput; const replacedSessionIds = yield* ( @@ -799,6 +804,7 @@ const make = Effect.gen(function* () { expiresAt, lastConnectedAt: null, connected: false, + ...(input?.founder ? { founder: input.founder } : {}), }), ); diff --git a/apps/server/src/auth/WorkOsAuth.test.ts b/apps/server/src/auth/WorkOsAuth.test.ts new file mode 100644 index 0000000000000..86ea0f87473d5 --- /dev/null +++ b/apps/server/src/auth/WorkOsAuth.test.ts @@ -0,0 +1,317 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import * as Clock from "effect/Clock"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { FetchHttpClient, HttpRouter, HttpServerRequest } from "effect/http"; +import { createLocalJWKSet, exportJWK, generateKeyPair, SignJWT, base64url } from "jose"; +import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import * as ServerSecretStore from "./ServerSecretStore.ts"; +import * as SessionStore from "./SessionStore.ts"; +import { verifyCodeResponse, WorkOsAuth, layer as workOsLayer } from "./WorkOsAuth.ts"; +import { readConfig, WORKOS_PATH } from "./WorkOsConfig.ts"; +import * as WorkOsHttp from "./workOsHttp.ts"; + +const origin = "https://t3.example.test"; +const issuer = "https://api.workos.com/"; +const clientId = "client_fixture"; +const email = "founder@example.test"; +const userId = "user_fixture"; +const env = { + T3CODE_WORKOS_AUTH_ENABLED: "true", + T3CODE_WORKOS_API_KEY: "test-only", + T3CODE_WORKOS_CLIENT_ID: clientId, + T3CODE_WORKOS_ISSUER: issuer, + T3CODE_WORKOS_ORIGIN: origin, + T3CODE_WORKOS_ORGANIZATION_ID: "org_fixture", + T3CODE_WORKOS_KAMERON_USER_ID: userId, + T3CODE_WORKOS_KAMERON_EMAIL: email, + T3CODE_WORKOS_JEFF_USER_ID: "user_second", + T3CODE_WORKOS_JEFF_EMAIL: "second@example.test", +}; + +const withEnv = (values: Record) => + ConfigProvider.layer(ConfigProvider.fromUnknown(values)); + +const makeSigner = Effect.fn("WorkOsFixture.makeSigner")(function* () { + const now = Math.floor((yield* Clock.currentTimeMillis) / 1000); + const { publicKey, privateKey } = yield* Effect.promise(() => generateKeyPair("RS256")); + const key = yield* Effect.promise(async () => ({ + ...(await exportJWK(publicKey)), + kid: "fixture", + })); + const jwks = { keys: [key] }; + const makeBody = async ( + input: { + readonly jwt?: Record; + readonly user?: Record; + readonly response?: Record; + readonly signingKey?: Awaited>["privateKey"]; + } = {}, + ) => ({ + access_token: await new SignJWT({ + sub: userId, + sid: "session_fixture", + client_id: clientId, + org_id: "org_fixture", + iss: issuer, + iat: now, + exp: now + 120, + ...input.jwt, + }) + .setProtectedHeader({ alg: "RS256", kid: "fixture" }) + .sign(input.signingKey ?? privateKey), + user: { id: userId, email, email_verified: true, ...input.user }, + authentication_method: "GoogleOAuth", + ...input.response, + }); + return { jwks, makeBody }; +}); + +it.effect("keeps WorkOS disabled without a complete, unambiguous enrollment configuration", () => + Effect.gen(function* () { + expect(yield* readConfig.pipe(Effect.provide(withEnv({})))).toBeNull(); + expect( + yield* readConfig.pipe(Effect.provide(withEnv({ T3CODE_WORKOS_AUTH_ENABLED: "true" }))), + ).toBeNull(); + expect( + yield* readConfig.pipe( + Effect.provide(withEnv({ ...env, T3CODE_WORKOS_JEFF_USER_ID: userId })), + ), + ).toBeNull(); + }), +); + +it.effect("verifies issuer, app, time, organization, and both founder identity fields", () => + Effect.gen(function* () { + const config = yield* readConfig.pipe(Effect.provide(withEnv(env))); + if (!config) return yield* Effect.die("Fixture config did not load"); + const { jwks, makeBody } = yield* makeSigner(); + const key = createLocalJWKSet(jwks); + const otherKey = yield* Effect.promise(() => generateKeyPair("RS256")); + const verify = (input?: Parameters[0]) => + Effect.promise(() => makeBody(input)).pipe( + Effect.flatMap((body) => verifyCodeResponse(config, key, body)), + ); + expect((yield* verify()).founder).toBe("kameron"); + expect( + (yield* verify({ + jwt: { sub: "user_second" }, + user: { id: "user_second", email: "SECOND@example.test" }, + })).founder, + ).toBe("jeff"); + for (const [input, status] of [ + [{ signingKey: otherKey.privateKey }, 401], + [{ jwt: { iss: "https://wrong.example.test/" } }, 401], + [{ jwt: { exp: -1 } }, 401], + [{ jwt: { iat: 120 } }, 401], + [{ jwt: { nbf: 120 } }, 401], + [{ jwt: { sid: undefined } }, 401], + [{ jwt: { client_id: "client_other" } }, 401], + [{ jwt: { aud: "client_other" } }, 401], + [{ jwt: { org_id: "org_other" } }, 403], + [{ user: { id: "user_other" } }, 401], + [{ user: { email: "unlisted@example.test" } }, 403], + [{ user: { email_verified: false } }, 403], + [{ response: { impersonator: { email } } }, 403], + [{ response: { authentication_method: "Password" } }, 403], + [{ jwt: { sub: "user_unlisted" }, user: { id: "user_unlisted" } }, 403], + ] as const) { + expect((yield* verify(input).pipe(Effect.flip)).status).toBe(status); + } + expect((yield* verify({ jwt: { client_id: undefined } })).founder).toBe("kameron"); + }), +); + +it.effect( + "exchanges PKCE once, persists attribution, and revokes the scoped WebSocket session", + () => + Effect.gen(function* () { + const { jwks, makeBody } = yield* makeSigner(); + const valid = yield* Effect.promise(() => makeBody()); + const invalid = yield* Effect.promise(() => makeBody({ jwt: { exp: -1 } })); + const unlisted = yield* Effect.promise(() => + makeBody({ user: { email: "unlisted@example.test" } }), + ); + let exchange: { code: string; code_verifier: string } | undefined; + const mockWorkOs: typeof fetch = async (input, init) => { + const path = new URL(String(input)).pathname; + if (path === `/sso/jwks/${clientId}`) return Response.json(jwks); + if (path !== "/user_management/authenticate") return new Response(null, { status: 404 }); + exchange = JSON.parse(String(init?.body)) as typeof exchange; + return Response.json( + exchange?.code === "expired" ? invalid : exchange?.code === "unlisted" ? unlisted : valid, + ); + }; + const node = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer); + const serverAuthLayer = EnvironmentAuth.layer.pipe( + Layer.provide(SqlitePersistence.layerMemory), + Layer.provide(ServerSecretStore.layer), + Layer.provide(ServerEnvironment.layerIdentity), + Layer.provide(ManagedPolicy.layerTest()), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-workos-test-" })), + ); + const authServices = workOsLayer.pipe( + Layer.provideMerge(serverAuthLayer), + Layer.provide(node), + Layer.provide(withEnv(env)), + Layer.provide(Layer.succeed(FetchHttpClient.Fetch, mockWorkOs)), + ); + const services = yield* Layer.build(authServices); + const requestServices = Context.add(services, Clock.Clock, yield* Clock.Clock); + const sessions = Context.get(services, SessionStore.SessionStore); + const serverAuth = Context.get(services, EnvironmentAuth.EnvironmentAuth); + const routes = HttpRouter.toWebHandler( + WorkOsHttp.layer.pipe( + Layer.provide(Layer.succeed(WorkOsAuth, Context.get(services, WorkOsAuth))), + ), + { disableLogger: true }, + ); + yield* Effect.addFinalizer(() => Effect.promise(routes.dispose)); + const request = (path: string, init?: RequestInit) => { + const headers = new Headers(init?.headers); + headers.set("host", new URL(origin).host); + return new Request(new URL(path, origin), { ...init, headers }); + }; + const send = (path: string, init?: RequestInit) => + Effect.promise(() => routes.handler(request(path, init), requestServices)); + const open = (desktop?: string) => + send( + `${WORKOS_PATH}/start${desktop ? `?desktop=${desktop}` : ""}`, + desktop ? {} : { method: "POST", headers: { origin } }, + ); + const finish = (start: Response, code: string, cookie?: string) => { + const location = new URL(start.headers.get("location")!); + const state = location.searchParams.get("state")!; + return send( + `${WORKOS_PATH}/callback?state=${state}&code=${code}&returnTo=https://other.example.test`, + { + headers: { cookie: cookie ?? start.headers.getSetCookie()[0]!.split(";")[0]! }, + }, + ); + }; + expect( + (yield* send(`${WORKOS_PATH}/start`, { + method: "POST", + headers: { origin: "https://other.example.test" }, + })).status, + ).toBe(403); + const start = yield* open(); + expect(start.status).toBe(303); + const authorization = new URL(start.headers.get("location")!); + expect(authorization.searchParams.get("code_challenge_method")).toBe("S256"); + expect(authorization.searchParams.get("redirect_uri")).toBe( + `${origin}${WORKOS_PATH}/callback`, + ); + expect((yield* finish(start, "valid", "wrong=1")).status).toBe(401); + const complete = yield* finish(start, "valid"); + expect(complete.status).toBe(303); + expect(complete.headers.get("location")).toBe(`${origin}/`); + expect(exchange?.code).toBe("valid"); + const verifierDigest = yield* Effect.promise(() => + crypto.subtle.digest("SHA-256", new TextEncoder().encode(exchange?.code_verifier)), + ); + expect(base64url.encode(new Uint8Array(verifierDigest))).toBe( + authorization.searchParams.get("code_challenge"), + ); + expect((yield* finish(start, "valid")).status).toBe(401); + expect((yield* finish(yield* open(), "expired")).status).toBe(401); + expect((yield* finish(yield* open(), "unlisted")).status).toBe(403); + const sessionCookie = complete.headers + .getSetCookie() + .find((cookie) => cookie.startsWith(`${sessions.cookieName}=`))!; + expect(sessionCookie).toMatch(/HttpOnly/i); + expect(sessionCookie).toMatch(/Secure/i); + expect(sessionCookie).toMatch(/SameSite=Lax/i); + const cookie = sessionCookie.split(";")[0]!; + const upgrade = HttpServerRequest.fromWeb(request("/ws", { headers: { origin, cookie } })); + const session = yield* serverAuth.authenticateWebSocketUpgrade(upgrade, "rpc"); + expect(yield* serverAuth.messageSenderOf(session.sessionId)).toMatchObject({ + founder: "kameron", + sessionId: session.sessionId, + }); + expect(yield* sessions.setFounder(session.sessionId, "jeff")).toBe(false); + const crossOrigin = HttpServerRequest.fromWeb( + request("/ws", { headers: { origin: "https://other.example.test", cookie } }), + ); + expect( + yield* serverAuth.authenticateWebSocketUpgrade(crossOrigin, "rpc").pipe(Effect.exit), + ).toMatchObject({ _tag: "Failure" }); + expect( + (yield* send(`${WORKOS_PATH}/logout`, { method: "POST", headers: { origin, cookie } })) + .status, + ).toBe(303); + yield* sessions.awaitInvalidation(session.sessionId); + expect( + yield* serverAuth.authenticateWebSocketUpgrade(upgrade, "rpc").pipe(Effect.exit), + ).toMatchObject({ _tag: "Failure" }); + + const mobileGrant = yield* serverAuth.issuePairingCredential({ + scopes: ["orchestration:read"], + }); + const mobile = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( + mobileGrant.credential, + ["orchestration:read"], + { deviceType: "mobile" }, + ); + const mobileSession = yield* serverAuth.authenticateHttpRequest( + HttpServerRequest.fromWeb( + request("/api/auth/session", { + headers: { authorization: `Bearer ${mobile.access_token}` }, + }), + ), + ); + expect(yield* sessions.setFounder(mobileSession.sessionId, "jeff")).toBe(true); + expect( + Option.getOrUndefined(yield* sessions.senderOf(mobileSession.sessionId))?.founder, + ).toBe("jeff"); + + const bootstrap = yield* sessions.issue({ + method: "bearer-access-token", + subject: "desktop-bootstrap", + }); + const desktopAuth = { + authorization: `Bearer ${bootstrap.token}`, + "content-type": "application/json", + }; + const verifier = "a".repeat(43); + const desktopDigest = yield* Effect.promise(() => + crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)), + ); + const desktopStart = yield* send(`${WORKOS_PATH}/desktop/start`, { + method: "POST", + headers: desktopAuth, + body: JSON.stringify({ challenge: base64url.encode(new Uint8Array(desktopDigest)) }), + }); + expect(desktopStart.status).toBe(200); + const { id } = (yield* Effect.promise(() => desktopStart.json())) as { id: string }; + const redeem = (value: string) => + send(`${WORKOS_PATH}/desktop/finish`, { + method: "POST", + headers: desktopAuth, + body: JSON.stringify({ id, verifier: value }), + }); + expect((yield* redeem(verifier)).status).toBe(409); + const desktopAuthorize = yield* open(id); + const desktopCallback = yield* finish(desktopAuthorize, "valid"); + expect(desktopCallback.status).toBe(303); + expect(desktopCallback.headers.getSetCookie()).toHaveLength(1); + expect((yield* redeem("b".repeat(43))).status).toBe(401); + const desktopFinish = yield* redeem(verifier); + expect(desktopFinish.status).toBe(200); + const { token } = (yield* Effect.promise(() => desktopFinish.json())) as { token: string }; + expect((yield* sessions.verify(token)).method).toBe("bearer-access-token"); + expect( + (yield* serverAuth.messageSenderOf((yield* sessions.verify(token)).sessionId)).founder, + ).toBe("kameron"); + expect((yield* redeem(verifier)).status).toBe(401); + }), +); diff --git a/apps/server/src/auth/WorkOsAuth.ts b/apps/server/src/auth/WorkOsAuth.ts new file mode 100644 index 0000000000000..0468356be4f42 --- /dev/null +++ b/apps/server/src/auth/WorkOsAuth.ts @@ -0,0 +1,363 @@ +// @effect-diagnostics nodeBuiltinImport:off - PKCE and state use the same synchronous generation as the transaction maps. +import * as NodeCrypto from "node:crypto"; +import { + AuthFilesystemReadScope, + AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, + type AuthClientMetadata, + type Founder, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; +import { createRemoteJWKSet, customFetch, jwtVerify, type JWTVerifyGetKey } from "jose"; +import * as SessionStore from "./SessionStore.ts"; +import { readConfig, subjectFor, WORKOS_PATH, type WorkOsConfig } from "./WorkOsConfig.ts"; + +const transactionLifetimeMs = 5 * 60_000; +const sessionLifetimeMs = 15 * 60_000; +const maxPending = 512; +const workOsApi = "https://api.workos.com"; +export const transactionCookie = "__Host-t3-workos-state"; +const opaque = () => NodeCrypto.randomBytes(32).toString("base64url"); +const challenge = (verifier: string) => + NodeCrypto.createHash("sha256").update(verifier).digest("base64url"); +const isOpaque = (value: string) => /^[A-Za-z0-9_-]{43}$/.test(value); + +export class WorkOsError extends Schema.TaggedError()("WorkOsError", { + status: Schema.Literals([401, 403, 404, 409, 429, 502, 503]), + message: Schema.String, +}) {} + +const invalid = () => + new WorkOsError({ status: 401, message: "Google sign-in could not be verified. Start again." }); +const denied = () => + new WorkOsError({ + status: 403, + message: "This Google account is not enrolled for this environment.", + }); +const unavailable = () => + new WorkOsError({ status: 503, message: "Could not establish a T3 Code session." }); +const upstreamUnavailable = () => + new WorkOsError({ status: 502, message: "WorkOS is unavailable. Start again." }); + +const responseSchema = Schema.Struct({ + access_token: Schema.String, + authentication_method: Schema.optionalKey(Schema.String), + impersonator: Schema.optionalKey(Schema.Unknown), + user: Schema.Struct({ id: Schema.String, email: Schema.String, email_verified: Schema.Boolean }), +}); +const decodeResponse = Schema.decodeUnknownEffect(responseSchema); + +interface Identity { + readonly founder: Founder; + readonly expiresAt: number; +} + +/** @public Test seam for signed WorkOS code-exchange responses. */ +export const verifyCodeResponse = Effect.fn("WorkOsAuth.verifyCodeResponse")(function* ( + config: WorkOsConfig, + key: JWTVerifyGetKey, + body: unknown, +) { + const response = yield* decodeResponse(body).pipe(Effect.mapError(invalid)); + const now = yield* DateTime.now; + const { payload } = yield* Effect.tryPromise({ + try: () => + jwtVerify(response.access_token, key, { + algorithms: ["RS256"], + issuer: config.issuer, + requiredClaims: ["sub", "sid", "iat", "exp"], + currentDate: DateTime.toDate(now), + }), + catch: invalid, + }); + if ( + !payload.sub || + typeof payload.sid !== "string" || + !payload.sid || + payload.sub !== response.user.id || + typeof payload.iat !== "number" || + payload.iat > now.epochMilliseconds / 1000 || + typeof payload.exp !== "number" || + (payload.client_id !== undefined && payload.client_id !== config.clientId) || + (payload.aud !== undefined && + payload.aud !== config.clientId && + !(Array.isArray(payload.aud) && payload.aud.includes(config.clientId))) + ) + return yield* invalid(); + + if ( + response.impersonator != null || + payload.impersonator != null || + response.authentication_method !== "GoogleOAuth" || + !response.user.email_verified || + (config.organizationId !== undefined && payload.org_id !== config.organizationId) + ) + return yield* denied(); + + for (const founder of ["kameron", "jeff"] as const) { + const allow = config.founders[founder]; + if (allow.id === payload.sub && allow.email === response.user.email.trim().toLowerCase()) { + return { + founder, + expiresAt: Math.min(payload.exp * 1000, now.epochMilliseconds + sessionLifetimeMs), + } satisfies Identity; + } + } + return yield* denied(); +}); + +interface DesktopTransaction { + readonly challenge: string; + readonly expiresAt: number; + started: boolean; + identity?: Identity; +} + +interface BrowserTransaction { + readonly verifier: string; + readonly expiresAt: number; + readonly desktop?: DesktopTransaction; +} + +export class WorkOsAuth extends Context.Service< + WorkOsAuth, + { + readonly config: WorkOsConfig | null; + readonly startDesktop: ( + accessToken: string, + verifierChallenge: string, + ) => Effect.Effect; + readonly begin: ( + desktop: string | null, + ) => Effect.Effect<{ state: string; location: URL }, WorkOsError>; + readonly callback: (input: { + state: string; + challengeCookie: string; + code: string; + client: AuthClientMetadata; + previousCookie?: string; + }) => Effect.Effect; + readonly finishDesktop: ( + accessToken: string, + id: string, + verifier: string, + ) => Effect.Effect; + readonly signOut: (token: string) => Effect.Effect; + } +>()("t3/auth/WorkOsAuth") {} + +const make = Effect.gen(function* () { + const config = yield* readConfig; + const sessions = yield* SessionStore.SessionStore; + const http = yield* HttpClient.HttpClient; + const fetchJwks = yield* FetchHttpClient.Fetch; + const browser = new Map(); + const desktop = new Map(); + const key = + config && + createRemoteJWKSet(new URL(`/sso/jwks/${config.clientId}`, workOsApi), { + timeoutDuration: 5_000, + cooldownDuration: 30_000, + [customFetch]: fetchJwks, + }); + + const requireDesktopBootstrap = Effect.fn("WorkOsAuth.requireDesktopBootstrap")(function* ( + token: string, + ) { + const session = yield* sessions.verify(token).pipe(Effect.mapError(invalid)); + if (session.subject !== "desktop-bootstrap" || session.method !== "bearer-access-token") { + return yield* denied(); + } + }); + + const issue = Effect.fn("WorkOsAuth.issue")(function* ( + configured: WorkOsConfig, + identity: Identity, + client: AuthClientMetadata, + method: "browser-session-cookie" | "bearer-access-token", + previousCookie?: string, + ) { + const now = yield* DateTime.now; + if (identity.expiresAt <= now.epochMilliseconds) return yield* invalid(); + const previous = previousCookie + ? yield* sessions.verify(previousCookie).pipe(Effect.option) + : undefined; + return yield* sessions + .issue({ + method, + client, + founder: identity.founder, + subject: subjectFor(configured, identity.founder), + expiresAt: DateTime.makeUnsafe(identity.expiresAt), + scopes: [ + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + AuthFilesystemReadScope, + ], + ...(previous?._tag === "Some" && previous.value.method === "browser-session-cookie" + ? { replaceSessionId: previous.value.sessionId } + : {}), + }) + .pipe(Effect.mapError(unavailable)); + }); + + const startDesktop = Effect.fn("WorkOsAuth.startDesktop")(function* ( + token: string, + verifierChallenge: string, + ) { + if (!config) + return yield* new WorkOsError({ status: 404, message: "WorkOS sign-in is disabled." }); + yield* requireDesktopBootstrap(token); + if (!isOpaque(verifierChallenge)) return yield* invalid(); + const now = (yield* DateTime.now).epochMilliseconds; + for (const [id, transaction] of desktop) if (transaction.expiresAt <= now) desktop.delete(id); + if (desktop.size >= maxPending) + return yield* new WorkOsError({ status: 429, message: "Too many pending sign-ins." }); + const id = opaque(); + desktop.set(id, { + challenge: verifierChallenge, + expiresAt: now + transactionLifetimeMs, + started: false, + }); + return id; + }); + + const begin = Effect.fn("WorkOsAuth.begin")(function* (desktopId: string | null) { + if (!config) + return yield* new WorkOsError({ status: 404, message: "WorkOS sign-in is disabled." }); + const now = (yield* DateTime.now).epochMilliseconds; + const pending = desktopId ? desktop.get(desktopId) : undefined; + if (desktopId && (!pending || pending.expiresAt <= now || pending.started)) + return yield* invalid(); + for (const [state, transaction] of browser) + if (transaction.expiresAt <= now) browser.delete(state); + if (browser.size >= maxPending) + return yield* new WorkOsError({ status: 429, message: "Too many pending sign-ins." }); + if (pending) pending.started = true; + const state = opaque(); + const verifier = opaque(); + browser.set(state, { + verifier, + expiresAt: now + transactionLifetimeMs, + ...(pending ? { desktop: pending } : {}), + }); + const location = new URL("/user_management/authorize", workOsApi); + location.search = new URLSearchParams({ + provider: "authkit", + client_id: config.clientId, + redirect_uri: `${config.origin}${WORKOS_PATH}/callback`, + response_type: "code", + state, + code_challenge: challenge(verifier), + code_challenge_method: "S256", + ...(config.organizationId ? { organization_id: config.organizationId } : {}), + }).toString(); + return { state, location }; + }); + + const callback: WorkOsAuth["Service"]["callback"] = Effect.fn("WorkOsAuth.callback")( + function* (input) { + if (!config || !key) + return yield* new WorkOsError({ status: 404, message: "WorkOS sign-in is disabled." }); + const transaction = browser.get(input.state); + const now = (yield* DateTime.now).epochMilliseconds; + if (!transaction || transaction.expiresAt <= now || input.state !== input.challengeCookie) + return yield* invalid(); + browser.delete(input.state); + if (!input.code || input.code.length > 2048) return yield* invalid(); + const request = yield* HttpClientRequest.post( + `${workOsApi}/user_management/authenticate`, + ).pipe( + HttpClientRequest.bodyJson({ + grant_type: "authorization_code", + client_id: config.clientId, + client_secret: Redacted.value(config.apiKey), + code: input.code, + code_verifier: transaction.verifier, + }), + Effect.mapError(upstreamUnavailable), + ); + const response = yield* http + .execute(request) + .pipe( + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), + Effect.timeout("10 seconds"), + Effect.mapError(upstreamUnavailable), + ); + if (response.status < 200 || response.status >= 300) { + return yield* response.status >= 500 || response.status === 429 + ? upstreamUnavailable() + : invalid(); + } + const body: unknown = yield* response.json.pipe(Effect.mapError(upstreamUnavailable)); + const identity = yield* verifyCodeResponse(config, key, body); + if (transaction.desktop) { + transaction.desktop.identity = identity; + return null; + } + return yield* issue( + config, + identity, + input.client, + "browser-session-cookie", + input.previousCookie, + ); + }, + ); + + const finishDesktop = Effect.fn("WorkOsAuth.finishDesktop")(function* ( + token: string, + id: string, + verifier: string, + ) { + if (!config) + return yield* new WorkOsError({ status: 404, message: "WorkOS sign-in is disabled." }); + yield* requireDesktopBootstrap(token); + const pending = desktop.get(id); + const now = (yield* DateTime.now).epochMilliseconds; + if ( + !pending || + pending.expiresAt <= now || + !isOpaque(verifier) || + challenge(verifier) !== pending.challenge + ) { + return yield* invalid(); + } + if (!pending.identity) + return yield* new WorkOsError({ + status: 409, + message: "Finish Google sign-in in your browser first.", + }); + desktop.delete(id); + return yield* issue( + config, + pending.identity, + { label: "T3 Code Desktop", deviceType: "desktop" }, + "bearer-access-token", + ); + }); + + const signOut = Effect.fn("WorkOsAuth.signOut")(function* (token: string) { + const session = yield* sessions.verify(token).pipe(Effect.mapError(invalid)); + if ( + !config || + !( + session.subject === subjectFor(config, "kameron") || + session.subject === subjectFor(config, "jeff") + ) + ) { + return yield* denied(); + } + yield* sessions.revoke(session.sessionId).pipe(Effect.mapError(unavailable)); + }); + + return WorkOsAuth.of({ config, startDesktop, begin, callback, finishDesktop, signOut }); +}); + +export const layer = Layer.effect(WorkOsAuth, make).pipe(Layer.provide(FetchHttpClient.layer)); diff --git a/apps/server/src/auth/WorkOsConfig.ts b/apps/server/src/auth/WorkOsConfig.ts new file mode 100644 index 0000000000000..4f5ea953f1027 --- /dev/null +++ b/apps/server/src/auth/WorkOsConfig.ts @@ -0,0 +1,93 @@ +// @effect-diagnostics nodeBuiltinImport:off - The session subject is computed synchronously from immutable configuration. +import * as NodeCrypto from "node:crypto"; +import type { Founder } from "@t3tools/contracts"; +import * as Config from "effect/Config"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; + +export const WORKOS_PATH = "/api/auth/workos"; +export const WORKOS_SUBJECT_PREFIX = "workos:"; +const userIdPattern = /^user_[A-Za-z0-9]+$/; + +export interface WorkOsConfig { + readonly clientId: string; + readonly apiKey: Redacted.Redacted; + readonly origin: string; + readonly issuer: string; + readonly organizationId: string | undefined; + readonly founders: Readonly>; +} + +const isHttpsUrl = (value: string) => { + const url = URL.parse(value); + return url?.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash; +}; + +const fromEnv = Config.all({ + clientId: Config.String("T3CODE_WORKOS_CLIENT_ID"), + apiKey: Config.Redacted("T3CODE_WORKOS_API_KEY"), + origin: Config.String("T3CODE_WORKOS_ORIGIN"), + issuer: Config.String("T3CODE_WORKOS_ISSUER"), + organizationId: Config.String("T3CODE_WORKOS_ORGANIZATION_ID").pipe(Config.option), + kameronId: Config.String("T3CODE_WORKOS_KAMERON_USER_ID"), + jeffId: Config.String("T3CODE_WORKOS_JEFF_USER_ID"), + kameronEmail: Config.String("T3CODE_WORKOS_KAMERON_EMAIL"), + jeffEmail: Config.String("T3CODE_WORKOS_JEFF_EMAIL"), +}); + +export const readConfig = Effect.gen(function* () { + const enabled = yield* Config.Boolean("T3CODE_WORKOS_AUTH_ENABLED").pipe( + Config.withDefault(false), + Effect.orElseSucceed(() => false), + ); + if (!enabled) return null; + const raw = yield* fromEnv.pipe(Effect.option); + if (Option.isSome(raw)) { + const { clientId, apiKey, origin, issuer, organizationId, kameronId, jeffId } = raw.value; + const kameronEmail = raw.value.kameronEmail.trim().toLowerCase(); + const jeffEmail = raw.value.jeffEmail.trim().toLowerCase(); + if ( + /^client_[A-Za-z0-9]+$/.test(clientId) && + Redacted.value(apiKey).trim() && + isHttpsUrl(origin) && + new URL(origin).origin === origin && + isHttpsUrl(issuer) && + userIdPattern.test(kameronId) && + userIdPattern.test(jeffId) && + kameronId !== jeffId && + kameronEmail.includes("@") && + jeffEmail.includes("@") && + kameronEmail !== jeffEmail && + (Option.isNone(organizationId) || /^org_[A-Za-z0-9]+$/.test(organizationId.value)) + ) { + return { + clientId, + apiKey, + origin, + issuer, + organizationId: Option.getOrUndefined(organizationId), + founders: { + kameron: { id: kameronId, email: kameronEmail }, + jeff: { id: jeffId, email: jeffEmail }, + }, + } satisfies WorkOsConfig; + } + } + yield* Effect.logWarning( + "WorkOS sign-in is disabled because its server configuration is incomplete or invalid.", + ); + return null; +}); + +export function subjectFor(config: WorkOsConfig, founder: Founder): string { + const { id, email } = config.founders[founder]; + return ( + WORKOS_SUBJECT_PREFIX + + NodeCrypto.createHash("sha256") + .update( + JSON.stringify([config.issuer, config.clientId, config.organizationId, founder, id, email]), + ) + .digest("base64url") + ); +} diff --git a/apps/server/src/auth/workOsHttp.ts b/apps/server/src/auth/workOsHttp.ts new file mode 100644 index 0000000000000..448bd1d8880c7 --- /dev/null +++ b/apps/server/src/auth/workOsHttp.ts @@ -0,0 +1,169 @@ +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { HttpMiddleware, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { requestUrl } from "../requestUrl.ts"; +import { parseBearerToken } from "./EnvironmentAuth.ts"; +import * as SessionStore from "./SessionStore.ts"; +import { deriveAuthClientMetadata } from "./utils.ts"; +import * as WorkOsAuth from "./WorkOsAuth.ts"; +import { WORKOS_PATH } from "./WorkOsConfig.ts"; + +const cookieOptions = { httpOnly: true, secure: true, sameSite: "lax", path: "/" } as const; +const headers = { "cache-control": "no-store", "referrer-policy": "no-referrer" } as const; + +const route = ( + method: "GET" | "POST", + path: string, + handle: (input: { + request: HttpServerRequest.HttpServerRequest; + auth: WorkOsAuth.WorkOsAuth["Service"]; + origin: string; + url: URL; + }) => Effect.Effect, +) => + HttpRouter.add( + method, + `${WORKOS_PATH}/${path}`, + HttpMiddleware.withLoggerDisabled( + Effect.gen(function* () { + const auth = yield* WorkOsAuth.WorkOsAuth; + const request = yield* HttpServerRequest.HttpServerRequest; + const url = requestUrl(request); + if (!auth.config) return HttpServerResponse.empty({ status: 404 }); + if (Option.isNone(url)) return HttpServerResponse.empty({ status: 403 }); + return yield* handle({ request, auth, origin: auth.config.origin, url: url.value }); + }).pipe( + Effect.catchIf(Schema.is(WorkOsAuth.WorkOsError), (error) => + Effect.succeed(HttpServerResponse.text(error.message, { status: error.status })), + ), + Effect.orElseSucceed(() => + HttpServerResponse.text("Could not complete Google sign-in.", { status: 500 }), + ), + Effect.map(HttpServerResponse.setHeaders(headers)), + ), + ), + ); + +const browserStart = (method: "GET" | "POST") => + route(method, "start", ({ auth, request, origin, url }) => + Effect.gen(function* () { + const desktop = url.searchParams.get("desktop"); + if ( + url.origin !== origin || + (method === "POST" ? request.headers.origin !== origin || desktop !== null : !desktop) + ) { + return HttpServerResponse.empty({ status: 403 }); + } + const { state, location } = yield* auth.begin(desktop); + return yield* HttpServerResponse.redirect(location, { status: 303 }).pipe( + HttpServerResponse.setCookie(WorkOsAuth.transactionCookie, state, { + ...cookieOptions, + maxAge: 300, + }), + ); + }), + ); + +const callback = route("GET", "callback", ({ request, auth, origin, url }) => + Effect.gen(function* () { + if (url.origin !== origin) return HttpServerResponse.empty({ status: 403 }); + const sessions = yield* SessionStore.SessionStore; + const previousCookie = request.cookies[sessions.cookieName]; + const result = yield* auth.callback({ + state: url.searchParams.get("state") ?? "", + challengeCookie: request.cookies[WorkOsAuth.transactionCookie] ?? "", + code: url.searchParams.get("code") ?? "", + client: deriveAuthClientMetadata({ request }), + ...(previousCookie ? { previousCookie } : {}), + }); + const response = result + ? yield* HttpServerResponse.redirect(`${origin}/`, { status: 303 }).pipe( + HttpServerResponse.setCookie(sessions.cookieName, result.token, { + ...cookieOptions, + expires: DateTime.toDate(result.expiresAt), + }), + ) + : HttpServerResponse.redirect(`${origin}${WORKOS_PATH}/desktop-complete`, { status: 303 }); + return yield* response.pipe( + HttpServerResponse.setCookie(WorkOsAuth.transactionCookie, "", { + ...cookieOptions, + maxAge: 0, + }), + ); + }), +); + +const desktopComplete = route("GET", "desktop-complete", ({ origin, url }) => + Effect.succeed( + url.origin === origin + ? HttpServerResponse.text( + "Google verified your account. Return to T3 Code and choose Finish sign-in.", + ) + : HttpServerResponse.empty({ status: 403 }), + ), +); + +const desktopStartBody = HttpServerRequest.schemaBodyJson( + Schema.Struct({ challenge: Schema.String }), +); +const desktopFinishBody = HttpServerRequest.schemaBodyJson( + Schema.Struct({ id: Schema.String, verifier: Schema.String }), +); +const desktopStart = route("POST", "desktop/start", ({ auth, request, origin }) => + Effect.gen(function* () { + const token = parseBearerToken(request); + if (!token || request.headers.origin !== undefined) + return HttpServerResponse.empty({ status: 403 }); + const { challenge } = yield* desktopStartBody; + const id = yield* auth.startDesktop(token, challenge); + return HttpServerResponse.jsonUnsafe({ + id, + authorizationUrl: `${origin}${WORKOS_PATH}/start?desktop=${id}`, + }); + }), +); + +const desktopFinish = route("POST", "desktop/finish", ({ auth, request }) => + Effect.gen(function* () { + const token = parseBearerToken(request); + if (!token || request.headers.origin !== undefined) + return HttpServerResponse.empty({ status: 403 }); + const { id, verifier } = yield* desktopFinishBody; + const session = yield* auth.finishDesktop(token, id, verifier); + return HttpServerResponse.jsonUnsafe({ + token: session.token, + expiresAt: session.expiresAt.epochMilliseconds, + }); + }), +); + +const logout = route("POST", "logout", ({ auth, request, origin, url }) => + Effect.gen(function* () { + const bearer = parseBearerToken(request); + if (bearer && request.headers.origin === undefined) { + yield* auth.signOut(bearer); + return HttpServerResponse.empty({ status: 204 }); + } + if (request.headers.origin !== origin || url.origin !== origin) + return HttpServerResponse.empty({ status: 403 }); + const sessions = yield* SessionStore.SessionStore; + const token = request.cookies[sessions.cookieName]; + if (token) yield* auth.signOut(token); + return yield* HttpServerResponse.redirect(`${origin}/pair`, { status: 303 }).pipe( + HttpServerResponse.setCookie(sessions.cookieName, "", { ...cookieOptions, maxAge: 0 }), + ); + }), +); + +export const layer = Layer.mergeAll( + browserStart("GET"), + browserStart("POST"), + callback, + desktopComplete, + desktopStart, + desktopFinish, + logout, +); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 8a4bebbec83c4..f8db65fdf6d43 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -1,3 +1,4 @@ +import { WORKOS_PATH } from "./auth/WorkOsConfig.ts"; import * as Mime from "effect/http/Mime"; import { AuthOrchestrationOperateScope, @@ -405,6 +406,7 @@ const layerUntracedRequests = Layer.succeed(HttpMiddleware.TracerDisabledWhen)(( // Signed URLs carry bearer tokens in the path, so they never reach a trace. return ( UNTRACED_REQUEST_PATHS.has(path) || + path.startsWith(`${WORKOS_PATH}/`) || path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`) || path.startsWith(`${ASSET_ROUTE_PREFIX}/`) || path.startsWith(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`) diff --git a/apps/server/src/persistence/AuthSessions.ts b/apps/server/src/persistence/AuthSessions.ts index 7ef35c10e433c..73d6ff1740d9b 100644 --- a/apps/server/src/persistence/AuthSessions.ts +++ b/apps/server/src/persistence/AuthSessions.ts @@ -15,6 +15,7 @@ import { ServerAuthSessionMethod, } from "@t3tools/contracts"; +import { WORKOS_SUBJECT_PREFIX } from "../auth/WorkOsConfig.ts"; import { type AuthSessionRepositoryError, PersistenceDecodeError, @@ -56,6 +57,7 @@ export const CreateAuthSessionInput = Schema.Struct({ issuedAt: Schema.DateTimeUtcFromString, expiresAt: Schema.DateTimeUtcFromString, proofKeyThumbprint: Schema.optionalKey(Schema.String), + founder: Schema.optionalKey(Founder), }); export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type; @@ -261,7 +263,8 @@ export const make = Effect.gen(function* () { issued_at, expires_at, revoked_at, - proof_key_thumbprint + proof_key_thumbprint, + founder ) VALUES ( ${input.sessionId}, @@ -277,7 +280,8 @@ export const make = Effect.gen(function* () { ${input.issuedAt}, ${input.expiresAt}, NULL, - ${input.proofKeyThumbprint ?? null} + ${input.proofKeyThumbprint ?? null}, + ${input.founder ?? null} ) ${ignoreExisting ? sql`ON CONFLICT(session_id) DO NOTHING` : sql``} `, @@ -326,7 +330,8 @@ export const make = Effect.gen(function* () { AND method = ${session.method} AND revoked_at IS NULL AND expires_at > ${revokedAt} - RETURNING session_id AS "sessionId", founder AS "founder" + RETURNING session_id AS "sessionId", + CASE WHEN subject GLOB ${WORKOS_SUBJECT_PREFIX + "*"} THEN NULL ELSE founder END AS "founder" `, }); @@ -380,6 +385,7 @@ export const make = Effect.gen(function* () { AND revoked_at IS NULL AND expires_at > ${now} AND client_device_type IS NOT 'bot' + AND subject NOT GLOB ${WORKOS_SUBJECT_PREFIX + "*"} RETURNING session_id AS "sessionId" `, }); @@ -507,7 +513,8 @@ export const make = Effect.gen(function* () { // subject could span several devices, so that never carries a person over. const founders = new Set(revokedRows.map((row) => row.founder)); const [founder] = founders; - return input.replaceSessionId !== undefined && + return input.session.founder === undefined && + input.replaceSessionId !== undefined && founders.size === 1 && founder !== null && founder !== undefined diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d8cf2f4a8c7dd..1dbadbc949cd1 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -154,6 +154,8 @@ import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as DirectEndpoints from "./environment/DirectEndpoints.ts"; import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; import * as AuthHttp from "./auth/http.ts"; +import * as WorkOsAuth from "./auth/WorkOsAuth.ts"; +import * as WorkOsHttp from "./auth/workOsHttp.ts"; import * as ReplayMarkers from "./auth/replayMarkers.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as CodexManagedTokenBroker from "./provider/CodexManagedTokenBroker.ts"; @@ -820,6 +822,7 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe( Layer.provideMerge(layerRepositoryIdentityResolver), Layer.provideMerge(CodexManagedTokenBroker.layer), Layer.provideMerge(layerServerEnvironment), + Layer.provideMerge(WorkOsAuth.layer), Layer.provideMerge(layerAuth), Layer.provideMerge(Layer.mergeAll(AssetSigner.layer, EnvironmentKeys.layer)), Layer.provideMerge(ServerSecretStore.layer), @@ -874,6 +877,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(WebhookRoute.layer.pipe(Layer.provide(RelayDeliveryProof.layer))), Layer.provide(AuthHttp.layerAuthenticatedAuth), ), + WorkOsHttp.layer, ServerHttp.layerOtlpTracesProxyRoute, ServerHttp.layerAssetRoute, ServerHttp.layerAttachmentUploadRoute, diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx index 8bedc8b2e7117..6d00ef14f34f6 100644 --- a/apps/web/src/components/auth/PairingRouteSurface.tsx +++ b/apps/web/src/components/auth/PairingRouteSurface.tsx @@ -11,6 +11,7 @@ import { } from "../../environments/primary"; import { readHostedPairingRequest } from "../../hostedPairing"; import { Button } from "../ui/button"; +import { WorkOsSignIn } from "./WorkOsSignIn"; import { Input } from "../ui/input"; import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -89,6 +90,12 @@ export function PairingRouteSurface({ description={describeAuthGate(auth.bootstrapMethods)} /> + {auth.workOsGoogleSignIn && ( +
+ +
+ )} +
void handleSubmit(event)}>