From 142251e47563e8c863b71c987a6aea599aac03ae Mon Sep 17 00:00:00 2001 From: Ernest Bursa <260287277+ebursa91@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:08:15 +0100 Subject: [PATCH 1/4] fix: bind browser credential approval to the current session --- .../__tests__/unit/agent-key-tor-exit.test.ts | 32 ++-- apps/web/__tests__/unit/auth-options.test.ts | 8 +- .../unit/extension-auth-consent.test.ts | 138 ++++++++++++++++++ apps/web/__tests__/unit/mcp-authorize.test.ts | 39 ++++- .../dashboard/settings/account/server.ts | 21 ++- apps/web/app/cli/authorize/page.tsx | 57 +++----- apps/web/app/mcp/authorize/actions.ts | 13 +- apps/web/app/mcp/authorize/page.tsx | 5 +- packages/database/auth/auth-options.ts | 6 + packages/database/auth/session.ts | 17 ++- .../web-backend/src/Extension/Extensions.ts | 73 ++++----- packages/web-backend/src/Extension/Http.ts | 35 ++++- packages/web-domain/src/Extension.ts | 7 +- 13 files changed, 348 insertions(+), 103 deletions(-) create mode 100644 apps/web/__tests__/unit/extension-auth-consent.test.ts diff --git a/apps/web/__tests__/unit/agent-key-tor-exit.test.ts b/apps/web/__tests__/unit/agent-key-tor-exit.test.ts index 4247fd275fa..1671f5097a1 100644 --- a/apps/web/__tests__/unit/agent-key-tor-exit.test.ts +++ b/apps/web/__tests__/unit/agent-key-tor-exit.test.ts @@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({ headers: new Headers(), limitChecks: [] as string[], writes: 0, + browserAccountId: "user-1", })); class Redirected extends Error { @@ -44,6 +45,10 @@ vi.mock("@cap/database", () => { }; }); vi.mock("@cap/database/auth/session", () => ({ + getBrowserCredentialSession: async () => ({ + id: mocks.browserAccountId, + authSessionVersion: 0, + }), getCurrentUser: async () => ({ id: "user-1", email: "person@example.com", @@ -143,13 +148,7 @@ async function cliApprove() { }); const approve = findFormAction(page); if (!approve) throw new Error("approve action not rendered"); - const form = new FormData(); - form.set("clientId", cliRequest.client_id); - form.set("redirectUri", cliRequest.redirect_uri); - form.set("state", cliRequest.state); - form.set("codeChallenge", cliRequest.code_challenge); - form.set("scope", cliRequest.scope); - return approve(form); + return approve(new FormData()); } async function mcpApprove() { @@ -157,7 +156,7 @@ async function mcpApprove() { const form = new FormData(); form.set("client_id", "client"); form.set("decision", "approve"); - return authorizeMcpClient(form); + return authorizeMcpClient("user-1", form); } async function mcpCancel() { @@ -165,7 +164,7 @@ async function mcpCancel() { const form = new FormData(); form.set("client_id", "client"); form.set("decision", "deny"); - return authorizeMcpClient(form); + return authorizeMcpClient("user-1", form); } async function createCliKey() { @@ -192,6 +191,7 @@ beforeEach(() => { resetTorExitListCache(); mocks.limitChecks = []; mocks.writes = 0; + mocks.browserAccountId = "user-1"; vi.stubEnv("VERCEL", "1"); vi.stubGlobal( "fetch", @@ -248,6 +248,20 @@ describe("credential creation from a Tor exit in deny mode", () => { describe("credential creation from other addresses", () => { beforeEach(() => fromAddress(UNLISTED)); + it("redraws CLI consent for a different browser account before minting", async () => { + mocks.browserAccountId = "user-2"; + const error = await rejection(cliApprove); + const continuation = new URL( + (error as Redirected).location, + "https://cap.example", + ); + + expect(continuation.pathname).toBe("/cli/authorize"); + expect(Object.fromEntries(continuation.searchParams)).toEqual(cliRequest); + expect(mocks.limitChecks).toEqual([]); + expect(mocks.writes).toBe(0); + }); + it("reaches the usual limits for every surface", async () => { expect((await rejection(createCliKey)) as Error).toMatchObject({ message: "Too many API key requests. Try again later.", diff --git a/apps/web/__tests__/unit/auth-options.test.ts b/apps/web/__tests__/unit/auth-options.test.ts index d8be7e5d3af..7df735314e2 100644 --- a/apps/web/__tests__/unit/auth-options.test.ts +++ b/apps/web/__tests__/unit/auth-options.test.ts @@ -801,10 +801,16 @@ describe("authOptions", () => { const session = await options.callbacks?.session?.({ session: { user: {}, expires: "" }, - token: { id: AUTHENTICATED_USER.id, authTime: 1234, authMethod: "email" }, + token: { + id: AUTHENTICATED_USER.id, + authTime: 1234, + authMethod: "email", + sessionVersion: 7, + }, } as never); expect((session as { authTime?: number }).authTime).toBe(1234); expect((session as { authMethod?: string }).authMethod).toBe("email"); + expect(session).toMatchObject({ authSessionVersion: 7 }); }); it.each(["workos", "google", "apple"])( diff --git a/apps/web/__tests__/unit/extension-auth-consent.test.ts b/apps/web/__tests__/unit/extension-auth-consent.test.ts new file mode 100644 index 00000000000..d29bd456bcb --- /dev/null +++ b/apps/web/__tests__/unit/extension-auth-consent.test.ts @@ -0,0 +1,138 @@ +import { Database, Videos } from "@cap/web-backend"; +import { ExtensionHttpLive, Extensions } from "@cap/web-backend/src/Extension"; +import { Http, HttpAuthMiddleware } from "@cap/web-domain"; +import { HttpApiBuilder, HttpServer } from "@effect/platform"; +import { type Context, Effect, Layer } from "effect"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + browserAccountId: "account-1", + mintAuthKey: vi.fn<(id: string, version: number) => string>( + () => "synthetic-key", + ), +})); + +vi.mock("server-only", () => ({})); +vi.mock("@cap/env", async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + serverEnv: () => ({ + WEB_URL: "https://cap.example", + CAP_CHROME_EXTENSION_ID: "abcdefghijklmnopabcdefghijklmnop", + }), + }; +}); +vi.mock("@cap/database/auth/session", async (importOriginal) => ({ + ...(await importOriginal()), + getBrowserCredentialSession: async () => ({ + id: mocks.browserAccountId, + authSessionVersion: 3, + }), +})); +vi.mock("@cap/database/auth/auth-options", async (importOriginal) => ({ + ...(await importOriginal()), + getServerSession: async () => ({ user: { id: "account-1" } }), +})); + +const { handler, dispose } = HttpApiBuilder.api(Http.ApiContract).pipe( + Layer.provide(ExtensionHttpLive), + Layer.provideMerge( + Layer.succeed( + Database, + Database.make({ + use: () => + Effect.succeed([ + { id: "account-1", email: "user@example.com" }, + ] as never), + }), + ), + ), + Layer.provideMerge( + Layer.succeed(Videos, {} as Context.Tag.Service), + ), + Layer.provideMerge( + Layer.succeed( + Extensions, + Extensions.make({ + isUserPro: () => Effect.die("unused"), + mintAuthKey: (id, version) => + Effect.sync(() => mocks.mintAuthKey(id, version)), + revokeAuthKey: () => Effect.die("unused"), + resolveBootstrapOrganization: () => Effect.die("unused"), + }), + ), + ), + Layer.provideMerge(Layer.succeed(HttpAuthMiddleware, Effect.die("unused"))), + Layer.merge(HttpServer.layerContext), + HttpApiBuilder.toWebHandler, +); + +const authEndpoint = "https://cap.example/api/extension/auth"; +const redirectUri = "https://abcdefghijklmnopabcdefghijklmnop.chromiumapp.org/"; +const state = "extension-state"; +const approve = () => + handler( + new Request(`${authEndpoint}/approve`, { + method: "POST", + headers: { "sec-fetch-site": "same-origin" }, + body: new URLSearchParams({ accountId: "account-1", redirectUri, state }), + }), + ); + +beforeEach(() => { + mocks.browserAccountId = "account-1"; + mocks.mintAuthKey.mockClear(); +}); +afterAll(dispose); + +describe("extension browser consent", () => { + it("renders the approval form with the shown account and denies framing", async () => { + const response = await handler( + new Request( + `${authEndpoint}/start?${new URLSearchParams({ redirectUri, state })}`, + ), + ); + const html = await response.text(); + + expect(response.status).toBe(200); + expect(response.headers.get("x-frame-options")).toBe("DENY"); + expect(response.headers.get("content-security-policy")).toContain( + "frame-ancestors 'none'", + ); + expect(html).toContain('name="accountId" value="account-1"'); + expect(html).toContain( + `${redirectUri}#error=access_denied&state=${state}`, + ); + }); + + it("redraws consent when the browser changed accounts", async () => { + mocks.browserAccountId = "account-2"; + const response = await approve(); + const next = new URL(response.headers.get("location") ?? ""); + + expect(response.status).toBe(303); + expect(next.origin + next.pathname).toBe(`${authEndpoint}/start`); + expect(Object.fromEntries(next.searchParams)).toEqual({ + redirectUri, + state, + }); + expect(mocks.mintAuthKey).not.toHaveBeenCalled(); + }); + + it("returns the approved matching account to the original Chrome callback", async () => { + const response = await approve(); + const callback = new URL(response.headers.get("location") ?? ""); + + expect(response.status).toBe(302); + expect(callback.origin + callback.pathname).toBe(redirectUri); + expect( + Object.fromEntries(new URLSearchParams(callback.hash.slice(1))), + ).toEqual({ + authApiKey: "synthetic-key", + userId: "account-1", + state, + }); + expect(mocks.mintAuthKey).toHaveBeenCalledExactlyOnceWith("account-1", 3); + }); +}); diff --git a/apps/web/__tests__/unit/mcp-authorize.test.ts b/apps/web/__tests__/unit/mcp-authorize.test.ts index 3e6a1c5a3b5..8590eb0d4b4 100644 --- a/apps/web/__tests__/unit/mcp-authorize.test.ts +++ b/apps/web/__tests__/unit/mcp-authorize.test.ts @@ -5,6 +5,7 @@ const mocks = vi.hoisted(() => ({ validate: vi.fn(), createCode: vi.fn(), isRateLimited: vi.fn(), + getBrowserCredentialSession: vi.fn(), })); vi.mock("server-only", () => ({})); @@ -12,6 +13,7 @@ vi.mock("@cap/database", () => ({ db: () => ({}) })); vi.mock("@cap/ui", () => ({ Logo: () => null })); vi.mock("@cap/database/auth/session", () => ({ getCurrentUser: async () => ({ id: "user-1", email: "owner@example.com" }), + getBrowserCredentialSession: mocks.getBrowserCredentialSession, })); vi.mock("next/navigation", () => ({ redirect: (url: string) => { @@ -48,11 +50,13 @@ const submit = async (decisions: string[]) => { for (const [key, value] of Object.entries(oauthParams)) form.append(key, value); for (const decision of decisions) form.append("decision", decision); - const outcome = await authorizeMcpClient(form).catch((error: Error) => error); + const outcome = await authorizeMcpClient("user-1", form).catch( + (error: Error) => error, + ); expect(outcome).toBeInstanceOf(Error); const message = (outcome as Error).message; expect(message.startsWith("REDIRECT:")).toBe(true); - return new URL(message.slice("REDIRECT:".length)); + return new URL(message.slice("REDIRECT:".length), "https://cap.so"); }; beforeEach(() => { @@ -69,6 +73,11 @@ beforeEach(() => { mocks.createCode.mockResolvedValue("cap_mcp_code_test"); mocks.isRateLimited.mockReset(); mocks.isRateLimited.mockResolvedValue(false); + mocks.getBrowserCredentialSession.mockReset(); + mocks.getBrowserCredentialSession.mockResolvedValue({ + id: "user-1", + authSessionVersion: 3, + }); }); describe("MCP authorize page", () => { @@ -107,6 +116,32 @@ describe("authorizeMcpClient", () => { expect(callback.searchParams.get("state")).toBe("state-value"); }); + it("redraws consent without issuing a code if the browser changed accounts", async () => { + mocks.getBrowserCredentialSession.mockResolvedValue({ + id: "user-2", + authSessionVersion: 3, + }); + const continuation = await submit(["approve"]); + + expect(continuation.origin).toBe("https://cap.so"); + expect(continuation.pathname).toBe("/mcp/authorize"); + expect(Object.fromEntries(continuation.searchParams)).toEqual(oauthParams); + expect(mocks.createCode).not.toHaveBeenCalled(); + }); + + it("preserves the denial callback if the browser changed accounts", async () => { + mocks.getBrowserCredentialSession.mockResolvedValue({ + id: "user-2", + authSessionVersion: 3, + }); + const callback = await submit(["deny"]); + + expect(callback.origin + callback.pathname).toBe(oauthParams.redirect_uri); + expect(callback.searchParams.get("error")).toBe("access_denied"); + expect(callback.searchParams.get("state")).toBe(oauthParams.state); + expect(mocks.createCode).not.toHaveBeenCalled(); + }); + it.each([ [["deny"]], [["approve", "deny"]], diff --git a/apps/web/app/(org)/dashboard/settings/account/server.ts b/apps/web/app/(org)/dashboard/settings/account/server.ts index 6c88d1b269d..f19c3a0888e 100644 --- a/apps/web/app/(org)/dashboard/settings/account/server.ts +++ b/apps/web/app/(org)/dashboard/settings/account/server.ts @@ -2,7 +2,10 @@ import { db } from "@cap/database"; import { revokeAllCredentials } from "@cap/database/auth/revoke-credentials"; -import { getCurrentUser } from "@cap/database/auth/session"; +import { + getBrowserCredentialSession, + getCurrentUser, +} from "@cap/database/auth/session"; import { nanoId } from "@cap/database/helpers"; import { agentApiKeys, @@ -129,7 +132,7 @@ export async function createCliApiKey(input: { profile: string; expiresInDays: number; }): Promise<{ token: string; key: CliApiKeySummary }> { - const currentUser = await getCurrentUser(); + const currentUser = await getBrowserCredentialSession(); if (!currentUser) throw new Error("Unauthorized"); const name = input.name.trim(); @@ -163,9 +166,16 @@ export async function createCliApiKey(input: { ); const scopes = agentScopeProfiles[input.profile]; const id = nanoId(); - await db() - .insert(agentApiKeys) - .values({ + await db().transaction(async (tx) => { + const [account] = await tx + .select({ authSessionVersion: users.authSessionVersion }) + .from(users) + .where(eq(users.id, currentUser.id)) + .limit(1) + .for("update"); + if (account?.authSessionVersion !== currentUser.authSessionVersion) + throw new Error("Session expired"); + await tx.insert(agentApiKeys).values({ id, userId: currentUser.id, tokenHash: hashAgentSecret(token), @@ -173,6 +183,7 @@ export async function createCliApiKey(input: { scopes, expiresAt, }); + }); revalidatePath("/dashboard/settings/account"); return { diff --git a/apps/web/app/cli/authorize/page.tsx b/apps/web/app/cli/authorize/page.tsx index c78e645190a..824f701150b 100644 --- a/apps/web/app/cli/authorize/page.tsx +++ b/apps/web/app/cli/authorize/page.tsx @@ -1,5 +1,8 @@ import { db } from "@cap/database"; -import { getCurrentUser } from "@cap/database/auth/session"; +import { + getBrowserCredentialSession, + getCurrentUser, +} from "@cap/database/auth/session"; import { nanoId } from "@cap/database/helpers"; import { agentApiAuthorizationCodes, users } from "@cap/database/schema"; import { Logo } from "@cap/ui"; @@ -56,8 +59,8 @@ export default async function CliAuthorizePage(props: { searchParams: Promise; }) { const searchParams = await props.searchParams; - const request = parseAgentAuthorizationRequest(searchParams); - if (!request) { + const authorizationRequest = parseAgentAuthorizationRequest(searchParams); + if (!authorizationRequest) { return (
@@ -73,29 +76,18 @@ export default async function CliAuthorizePage(props: { ); } + const request = authorizationRequest; + const consentPath = authorizationPath(searchParams); + const loginPath = `/login?next=${encodeURIComponent(consentPath)}`; const user = await getCurrentUser(); - if (!user) { - redirect( - `/login?next=${encodeURIComponent(authorizationPath(searchParams))}`, - ); - } + if (!user) redirect(loginPath); + const expectedAccountId = user.id; - async function approve(formData: FormData) { + async function approve() { "use server"; - const submitted = parseAgentAuthorizationRequest({ - client_id: formData.get("clientId")?.toString(), - redirect_uri: formData.get("redirectUri")?.toString(), - response_type: "code", - state: formData.get("state")?.toString(), - code_challenge: formData.get("codeChallenge")?.toString(), - code_challenge_method: "S256", - scope: formData.get("scope")?.toString(), - }); - if (!submitted) throw new Error("Invalid authorization request"); - const currentUser = await getCurrentUser(); - if (!currentUser) { - redirect("/login"); - } + const currentUser = await getBrowserCredentialSession(); + if (!currentUser) redirect(loginPath); + if (currentUser.id !== expectedAccountId) redirect(consentPath); if (await shouldRefuseTorExit("cli-authorize")) { redirect("/login?error=SignupBlocked"); } @@ -122,14 +114,14 @@ export default async function CliAuthorizePage(props: { id: nanoId(), userId: currentUser.id, codeHash: hashAgentSecret(code), - codeChallenge: submitted.codeChallenge, - redirectUri: submitted.redirectUri, - scopes: submitted.scopes, + codeChallenge: request.codeChallenge, + redirectUri: request.redirectUri, + scopes: request.scopes, expiresAt: new Date(Date.now() + 5 * 60 * 1000), }); }); - const callback = buildAgentCallbackUrl(submitted.redirectUri, { - state: submitted.state, + const callback = buildAgentCallbackUrl(request.redirectUri, { + state: request.state, code, }); if (!callback) throw new Error("Invalid callback URL"); @@ -160,15 +152,6 @@ export default async function CliAuthorizePage(props: { ))}
- - - - -
-`); +`).pipe( + HttpServerResponse.setHeaders({ + "Cache-Control": "private, no-store", + "Content-Security-Policy": + "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'", + "Referrer-Policy": "same-origin", + "X-Frame-Options": "DENY", + }), + ); }; const redirectWithAuthKey = ({ @@ -235,6 +247,7 @@ export const ExtensionHttpLive = HttpApiBuilder.group( } return renderConsentPage({ + accountId: currentUser.value.id, email: currentUser.value.email, redirectUri, state: urlParams.state, @@ -272,9 +285,11 @@ export const ExtensionHttpLive = HttpApiBuilder.group( const redirectUri = yield* validateExtensionRedirectUri( payload.redirectUri, ); - const currentUser = yield* getCurrentUser; + const session = yield* Effect.tryPromise( + getBrowserCredentialSession, + ); - if (Option.isNone(currentUser)) { + if (!session) { // The session expired between rendering the consent page // and approving it; restart the flow at the consent page. return redirectToLogin( @@ -284,21 +299,31 @@ export const ExtensionHttpLive = HttpApiBuilder.group( }), ); } + if (session.id !== payload.accountId) { + return HttpServerResponse.redirect( + consentPageUrl(request.url, payload), + { status: 303 }, + ); + } const authApiKey = yield* extensions.mintAuthKey( - currentUser.value.id, + session.id, + session.authSessionVersion, ); return redirectWithAuthKey({ redirectUri, authApiKey, - userId: currentUser.value.id, + userId: session.id, state: payload.state, }); }).pipe( Effect.catchTag("AuthKeyMintRateLimited", () => Effect.fail(new HttpApiError.BadRequest()), ), + Effect.catchTag("AuthKeySessionExpired", () => + Effect.succeed(HttpServerResponse.empty({ status: 401 })), + ), Effect.catchTag("UnknownException", () => Effect.fail(new Http.InternalServerError({ cause: "unknown" })), ), diff --git a/packages/web-domain/src/Extension.ts b/packages/web-domain/src/Extension.ts index d3ef6d393c5..60efbfdcead 100644 --- a/packages/web-domain/src/Extension.ts +++ b/packages/web-domain/src/Extension.ts @@ -74,9 +74,10 @@ export class ExtensionHttpApi extends HttpApiGroup.make("extension") .add( HttpApiEndpoint.post("approveAuth", ExtensionApiPaths.approveAuth) .setPayload( - ExtensionAuthStartParams.pipe( - HttpApiSchema.withEncoding({ kind: "UrlParams" }), - ), + Schema.Struct({ + ...ExtensionAuthStartParams.fields, + accountId: UserId, + }).pipe(HttpApiSchema.withEncoding({ kind: "UrlParams" })), ) .addError(HttpApiError.BadRequest) .addError(InternalServerError), From cd12d5c6cce8f51a26e22969562de9a055543770 Mon Sep 17 00:00:00 2001 From: Ernest Bursa <260287277+ebursa91@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:08:15 +0100 Subject: [PATCH 2/4] fix: require browser approval for desktop sign-in --- apps/desktop-gpui/README.md | 6 + apps/desktop-gpui/src/auth.rs | 260 +----------------- apps/desktop-gpui/src/sign_in.rs | 18 +- .../unit/desktop-session-api-key.test.ts | 190 +++++++++++-- .../unit/desktop-session-state-probe.test.ts | 94 +++---- .../unit/desktop-session-tor-exit.test.ts | 60 +++- .../web/app/api/desktop/[...route]/session.ts | 146 +++++++--- apps/web/lib/desktop-session.ts | 63 +++++ 8 files changed, 449 insertions(+), 388 deletions(-) diff --git a/apps/desktop-gpui/README.md b/apps/desktop-gpui/README.md index d13e0114602..da5e459971a 100644 --- a/apps/desktop-gpui/README.md +++ b/apps/desktop-gpui/README.md @@ -37,6 +37,12 @@ generic dependency calls over large data — `imageops::resize`, image encoders, that instantiates it, at that crate's opt-level. Put the call in `kernels/` behind a plain-slice function and call that from the app. +### Signing in to a self-hosted server + +Desktop browser sign-in requires the server to return the sign-in state in its +callback. If a self-hosted deployment cannot complete browser sign-in, upgrade +its Cap web server and start a new sign-in from the desktop app. + ### The dev loop ```sh diff --git a/apps/desktop-gpui/src/auth.rs b/apps/desktop-gpui/src/auth.rs index fed12912d4b..72f694b653f 100644 --- a/apps/desktop-gpui/src/auth.rs +++ b/apps/desktop-gpui/src/auth.rs @@ -78,7 +78,6 @@ pub struct SignInSession { pub url: String, id: u64, state: String, - custom_server: Option, local: Option>, deep: flume::Receiver, callback: Arc, @@ -88,7 +87,6 @@ pub struct SignInSession { struct CallbackControl { stop: AtomicBool, completed: AtomicBool, - state_optional: AtomicBool, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -109,7 +107,6 @@ pub fn begin_sign_in() -> Result { // Without a port the server redirects straight to the `cap-desktop://` // deep link, so a failed bind degrades to the deep-link path instead of // failing sign-in outright. - let custom_server = (!has_same_origin(&server, DEFAULT_SERVER_URL)).then(|| server.clone()); let local = match start_local_callback(callback.clone(), state.clone()) { Ok(local) => Some(local), Err(error) => { @@ -137,7 +134,6 @@ pub fn begin_sign_in() -> Result { ), id, state, - custom_server, local: local.map(|local| local.complete), deep: deep_rx, callback, @@ -185,11 +181,7 @@ impl SignInSession { loop { match self.deep.recv_async().await { Ok(url) => { - if let Some(params) = parse_auth_callback( - &url, - &self.state, - self.callback.state_optional.load(Ordering::Acquire), - ) { + if let Some(params) = parse_auth_callback(&url, &self.state) { break params; } } @@ -206,19 +198,6 @@ impl SignInSession { } } - /// The server this attempt signs in to, when it is not the official one. - pub fn custom_server(&self) -> Option<&str> { - self.custom_server.as_deref() - } - - /// Accepts callbacks without `state` for this attempt, for a server that - /// does not return it. Never applies to the official server. - pub fn accept_callbacks_without_state(&self) { - if self.custom_server.is_some() { - self.callback.state_optional.store(true, Ordering::Release); - } - } - pub fn mark_completed(&self) { self.callback.completed.store(true, Ordering::Release); } @@ -662,7 +641,7 @@ fn serve_local_callback( listener: TcpListener, port: u16, state: &str, - control: &Arc, + control: &CallbackControl, tx: &flume::Sender, ) { let started = Instant::now(); @@ -691,12 +670,11 @@ fn serve_local_callback( active.fetch_add(1, Ordering::AcqRel); let tx = tx.clone(); let state = state.to_string(); - let connection_control = control.clone(); let connection_active = active.clone(); let spawned = std::thread::Builder::new() .name("cap-sign-in-request".into()) .spawn(move || { - handle_callback_connection(stream, port, &state, &connection_control, &tx); + handle_callback_connection(stream, port, &state, &tx); connection_active.fetch_sub(1, Ordering::AcqRel); }); if let Err(error) = spawned { @@ -719,7 +697,6 @@ fn handle_callback_connection( mut stream: TcpStream, port: u16, state: &str, - control: &CallbackControl, tx: &flume::Sender, ) { // BSD sockets inherit O_NONBLOCK from the listener, so on macOS a stream @@ -740,11 +717,7 @@ fn handle_callback_connection( let Some(target) = read_request_target(&mut stream, deadline) else { return; }; - let params = parse_auth_callback( - &format!("http://127.0.0.1:{port}{target}"), - state, - control.state_optional.load(Ordering::Acquire), - ); + let params = parse_auth_callback(&format!("http://127.0.0.1:{port}{target}"), state); let (status, body) = if params.is_some() { ("200 OK", crate::local_page::signed_in()) } else { @@ -810,105 +783,18 @@ fn origin_of(value: &str) -> Option { Some(url.origin().ascii_serialization()) } -fn parse_auth_callback( - url: &str, - expected_state: &str, - state_optional: bool, -) -> Option { +fn parse_auth_callback(url: &str, expected_state: &str) -> Option { let parsed = reqwest::Url::parse(url).ok()?; - let states = parsed + let mut states = parsed .query_pairs() - .filter(|(key, _)| key == "state") - .map(|(_, value)| value) - .collect::>(); - match states.as_slice() { - [] if state_optional => {} - [state] if constant_time_eq(state.as_bytes(), expected_state.as_bytes()) => {} - _ => return None, + .filter_map(|(key, value)| (key == "state").then_some(value)); + let state = states.next()?; + if states.next().is_some() || !constant_time_eq(state.as_bytes(), expected_state.as_bytes()) { + return None; } parse_auth_params(url) } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SignInStateSupport { - Supported, - Unsupported, - Unknown, -} - -const SIGN_IN_STATE_SERVERS: &str = "signInStateServers"; - -/// Asks a server other than the official one whether it returns `state` on -/// its sign-in callbacks: a current server rejects a malformed `state` with -/// 400 and accepts a well-formed one. Sent by the app before the browser -/// opens. -pub async fn probe_sign_in_state(server: &str) -> SignInStateSupport { - let Ok(client) = reqwest::Client::builder() - .redirect(reqwest::redirect::Policy::none()) - .connect_timeout(Duration::from_secs(5)) - .timeout(Duration::from_secs(5)) - .build() - else { - return SignInStateSupport::Unknown; - }; - let status = |state: &'static str| { - let request = apply_desktop_headers(client.get(format!( - "{server}/api/desktop/session/request?type=api_key&state={state}" - ))); - async move { request.send().await.ok().map(|response| response.status()) } - }; - let malformed = status("x").await; - let well_formed = status("abcdefghijklmnopqrstuvwxyz012345").await; - sign_in_state_support(malformed, well_formed) -} - -fn sign_in_state_support( - malformed: Option, - well_formed: Option, -) -> SignInStateSupport { - let bad_request = reqwest::StatusCode::BAD_REQUEST; - match (malformed, well_formed) { - (Some(malformed), Some(well_formed)) - if malformed.is_server_error() || well_formed.is_server_error() => - { - SignInStateSupport::Unknown - } - (Some(malformed), Some(well_formed)) - if malformed == bad_request && well_formed != bad_request => - { - SignInStateSupport::Supported - } - (Some(malformed), Some(_)) if malformed != bad_request => SignInStateSupport::Unsupported, - _ => SignInStateSupport::Unknown, - } -} - -/// Whether sign-in to this server must return `state`. A server that has -/// confirmed support once stays required when a later check fails. -pub fn sign_in_state_required(server: &str, support: SignInStateSupport) -> bool { - let Some(origin) = origin_of(server) else { - return false; - }; - if support == SignInStateSupport::Supported - && !store::set_store_setting(SIGN_IN_STATE_SERVERS, &origin, Value::Bool(true)) - { - tracing::warn!("saving sign-in state support failed"); - } - let confirmed_before = store::store_section(SIGN_IN_STATE_SERVERS) - .get(&origin) - .and_then(Value::as_bool) - .unwrap_or(false); - state_required(support, confirmed_before) -} - -fn state_required(support: SignInStateSupport, confirmed_before: bool) -> bool { - match support { - SignInStateSupport::Supported => true, - SignInStateSupport::Unsupported => false, - SignInStateSupport::Unknown => confirmed_before, - } -} - fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { left.len() == right.len() && left @@ -1166,13 +1052,14 @@ mod tests { "cap-desktop://signin?state=abc123&api_key=k&user_id=u", ] { assert_eq!( - parse_auth_callback(url, "abc123", false), + parse_auth_callback(url, "abc123"), Some(expected.clone()), "{url}" ); } for url in [ "cap-desktop://signin?type=api_key&api_key=k&user_id=u", + "http://127.0.0.1:4280/?type=api_key&api_key=k&user_id=u", "cap-desktop://signin?api_key=k&user_id=u&state=", "cap-desktop://signin?api_key=k&user_id=u&state=abc12", "cap-desktop://signin?api_key=k&user_id=u&state=abc1234", @@ -1182,130 +1069,10 @@ mod tests { "cap-desktop://auth?token=t&user_id=u&expires=9&state=wrong", "cap-desktop://signin?state=abc123", ] { - assert_eq!(parse_auth_callback(url, "abc123", false), None, "{url}"); - } - } - - #[test] - fn a_server_without_state_support_accepts_only_stateless_or_matching_callbacks() { - let expected = Some(AuthParams::ApiKey { - api_key: "k".into(), - user_id: "u".into(), - }); - assert_eq!( - parse_auth_callback("cap-desktop://signin?api_key=k&user_id=u", "abc123", true), - expected - ); - assert_eq!( - parse_auth_callback( - "http://127.0.0.1:1/?api_key=k&user_id=u&state=abc123", - "abc123", - true - ), - expected - ); - for url in [ - "cap-desktop://signin?api_key=k&user_id=u&state=wrong", - "cap-desktop://signin?api_key=k&user_id=u&state=abc123&state=abc123", - "cap-desktop://signin?api_key=k&user_id=u&state=", - ] { - assert_eq!(parse_auth_callback(url, "abc123", true), None, "{url}"); + assert_eq!(parse_auth_callback(url, "abc123"), None, "{url}"); } } - #[test] - fn state_support_needs_a_400_for_malformed_and_not_for_well_formed_state() { - use SignInStateSupport::*; - use reqwest::StatusCode; - let found = Some(StatusCode::FOUND); - let bad = Some(StatusCode::BAD_REQUEST); - assert_eq!(sign_in_state_support(bad, found), Supported); - assert_eq!(sign_in_state_support(bad, Some(StatusCode::OK)), Supported); - assert_eq!(sign_in_state_support(found, found), Unsupported); - assert_eq!( - sign_in_state_support(Some(StatusCode::MOVED_PERMANENTLY), found), - Unsupported - ); - assert_eq!( - sign_in_state_support(Some(StatusCode::NOT_FOUND), Some(StatusCode::NOT_FOUND)), - Unsupported - ); - assert_eq!(sign_in_state_support(bad, bad), Unknown); - assert_eq!(sign_in_state_support(None, found), Unknown); - assert_eq!(sign_in_state_support(bad, None), Unknown); - assert_eq!(sign_in_state_support(None, None), Unknown); - assert_eq!( - sign_in_state_support(bad, Some(StatusCode::BAD_GATEWAY)), - Unknown - ); - assert_eq!( - sign_in_state_support(Some(StatusCode::SERVICE_UNAVAILABLE), found), - Unknown - ); - } - - #[test] - fn a_server_that_confirmed_state_stays_required_when_a_check_fails() { - use SignInStateSupport::*; - assert!(state_required(Supported, false)); - assert!(state_required(Supported, true)); - assert!(state_required(Unknown, true)); - assert!(!state_required(Unknown, false)); - assert!(!state_required(Unsupported, true)); - assert!(!state_required(Unsupported, false)); - } - - #[tokio::test] - async fn state_support_probe_reads_real_responses() { - use SignInStateSupport::*; - let serve = |respond: fn(&str) -> &'static str| { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - std::thread::spawn(move || { - for mut stream in listener.incoming().flatten().take(2) { - let target = read_request_target(&mut stream, far_future()).unwrap_or_default(); - let status = respond(&target); - let _ = stream.write_all( - format!("HTTP/1.1 {status}\r\nLocation: /login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").as_bytes(), - ); - } - }); - format!("http://127.0.0.1:{port}") - }; - let current = serve(|target| { - if target.contains("state=x") { - "400 Bad Request" - } else { - "302 Found" - } - }); - assert_eq!(probe_sign_in_state(¤t).await, Supported); - let older = serve(|_| "302 Found"); - assert_eq!(probe_sign_in_state(&older).await, Unsupported); - let failing = serve(|_| "503 Service Unavailable"); - assert_eq!(probe_sign_in_state(&failing).await, Unknown); - assert_eq!(probe_sign_in_state("http://127.0.0.1:9").await, Unknown); - } - - #[test] - fn only_a_custom_server_can_accept_callbacks_without_state() { - let session = |custom_server: Option| SignInSession { - url: String::new(), - id: u64::MAX - 2, - state: "abc123".into(), - custom_server, - local: None, - deep: flume::bounded(1).1, - callback: Arc::new(CallbackControl::default()), - }; - let official = session(None); - official.accept_callbacks_without_state(); - assert!(!official.callback.state_optional.load(Ordering::Acquire)); - let custom = session(Some("http://localhost:3000".into())); - custom.accept_callbacks_without_state(); - assert!(custom.callback.state_optional.load(Ordering::Acquire)); - } - #[test] fn a_finished_session_only_clears_its_own_deep_link_slot() { let (old_tx, old_rx) = flume::bounded(1); @@ -1313,7 +1080,6 @@ mod tests { url: String::new(), id: u64::MAX - 1, state: String::new(), - custom_server: None, local: None, deep: old_rx, callback: Arc::new(CallbackControl::default()), diff --git a/apps/desktop-gpui/src/sign_in.rs b/apps/desktop-gpui/src/sign_in.rs index 2fe5c979a2c..7c6206dc906 100644 --- a/apps/desktop-gpui/src/sign_in.rs +++ b/apps/desktop-gpui/src/sign_in.rs @@ -71,7 +71,8 @@ impl SignIn { } pub fn try_global(cx: &App) -> Option> { - cx.try_global::().map(|global| global.0.clone()) + cx.try_global::() + .map(|global| global.0.clone()) } pub fn is_pending(&self) -> bool { @@ -111,21 +112,6 @@ impl SignIn { let timeout = cx.background_executor().timer(auth::SIGN_IN_TIMEOUT); let browser_url = url.clone(); let task = cx.spawn(async move |this, cx| { - if let Some(server) = session.custom_server().map(str::to_string) { - let probe_server = server.clone(); - let support = gpui_tokio::Tokio::spawn(cx, async move { - auth::probe_sign_in_state(&probe_server).await - }) - .await - .unwrap_or(auth::SignInStateSupport::Unknown); - if !auth::sign_in_state_required(&server, support) { - tracing::warn!( - ?support, - "sign-in server did not confirm state support; accepting callbacks without state for this attempt" - ); - session.accept_callbacks_without_state(); - } - } cx.update(|cx| cx.open_url(&browser_url)); let outcome = match session.wait(timeout).await { Ok(params) => match auth::process_auth_data(params) { diff --git a/apps/web/__tests__/unit/desktop-session-api-key.test.ts b/apps/web/__tests__/unit/desktop-session-api-key.test.ts index e8876395776..c54bb374679 100644 --- a/apps/web/__tests__/unit/desktop-session-api-key.test.ts +++ b/apps/web/__tests__/unit/desktop-session-api-key.test.ts @@ -1,5 +1,6 @@ import type { SQL } from "drizzle-orm"; import { MySqlDialect } from "drizzle-orm/mysql-core"; +import { Hono } from "hono"; import { beforeEach, describe, expect, it, vi } from "vitest"; type KeyRow = { @@ -14,6 +15,9 @@ const state = vi.hoisted(() => ({ clock: 0, base: 0, userId: "user-1", + browserVersion: 2, + databaseVersion: 2, + signedIn: true, events: [] as string[], mints: new Map(), limiterCalls: [] as [string, string | undefined][], @@ -63,7 +67,7 @@ function keysTable() { state.events.push( `lock:${strength}:${params(condition).join(",")}`, ); - return [{ id: params(condition)[0] }]; + return [{ authSessionVersion: state.databaseVersion }]; }, orderBy: (ordering: SQL) => ({ limit: (limit: number) => ({ @@ -111,10 +115,15 @@ vi.mock("@cap/database", () => ({ }, })); vi.mock("@cap/database/auth/session", () => ({ - getCurrentUser: async () => ({ id: state.userId }), + getBrowserCredentialSession: async () => + state.signedIn + ? { id: state.userId, authSessionVersion: state.browserVersion } + : null, + getCurrentUser: async () => + state.signedIn ? { id: state.userId, email: "account@example.test" } : null, })); vi.mock("@cap/database/auth/auth-options", () => ({ - decodeSessionToken: vi.fn(), + decodeSessionToken: async () => ({ id: state.userId, exp: 1234 }), })); vi.mock("@/lib/rate-limit", async (importOriginal) => ({ ...(await importOriginal()), @@ -133,11 +142,32 @@ vi.mock("@cap/env", () => ({ }), })); +const browserState = "S0fJzqKxpsugWDC3ExLQ1Q"; +const desktopSessionUrl = "https://cap.example/api/desktop/session"; +const { app: sessionApp } = await import( + "@/app/api/desktop/[...route]/session" +); +const app = new Hono().basePath("/api/desktop").route("/session", sessionApp); + +const requestApproval = async ( + body = new URLSearchParams({ + type: "api_key", + platform: "web", + port: "49152", + state: browserState, + accountId: "user-1", + }), + headers: HeadersInit = { "Sec-Fetch-Site": "same-origin" }, +) => { + return app.request(`${desktopSessionUrl}/approve`, { + method: "POST", + headers, + body, + }); +}; + const requestApiKey = async () => { - const { app } = await import("@/app/api/desktop/[...route]/session"); - const response = await app.request( - "https://cap.example/request?type=api_key&platform=web&port=49152", - ); + const response = await requestApproval(); const location = response.headers.get("location"); if (!location) throw new Error("expected a loopback redirect"); return new URL(location).searchParams.get("api_key"); @@ -152,11 +182,146 @@ describe("desktop api key sign-in", () => { state.clock = 0; state.base = Date.now(); state.userId = "user-1"; + state.browserVersion = 2; + state.databaseVersion = 2; + state.signedIn = true; state.events = []; state.mints.clear(); state.limiterCalls = []; }); + it("renders a private consent page before creating a credential", async () => { + const response = await app.request( + `${desktopSessionUrl}/request?type=api_key&platform=web&port=49152&state=${browserState}`, + ); + const page = await response.text(); + + expect(response.status).toBe(200); + expect(response.headers.get("cache-control")).toBe("private, no-store"); + expect(response.headers.get("x-frame-options")).toBe("DENY"); + expect(page).toContain('method="post" action="approve"'); + expect(page).toContain(`name="state" value="${browserState}"`); + expect(page).toContain('name="accountId" value="user-1"'); + expect(page).toContain("account@example.test"); + expect(response.headers.get("location")).toBeNull(); + expect(state.events).toEqual([]); + expect(state.limiterCalls).toEqual([]); + }); + + it("accepts a same-origin native handoff in browsers without fetch metadata", async () => { + const response = await requestApproval(undefined, { + Origin: "https://cap.example", + }); + const location = response.headers.get("location") ?? ""; + const callback = new URL(location); + + expect(response.status).toBe(303); + expect(response.headers.get("cache-control")).toBe("private, no-store"); + expect(callback.origin).toBe("http://127.0.0.1:49152"); + expect(callback.searchParams.get("state")).toBe(browserState); + expect(callback.searchParams.get("user_id")).toBe("user-1"); + expect(desktopKeys("user-1")).toHaveLength(1); + }); + + it.each([{}, { "Sec-Fetch-Site": "same-site" }])( + "requires a same-origin signal before processing approval (%j)", + async (headers) => { + const response = await requestApproval(undefined, headers); + + expect(response.status).toBe(403); + expect(state.events).toEqual([]); + expect(state.limiterCalls).toEqual([]); + }, + ); + + it("asks for consent again if the signed-in browser account has changed", async () => { + state.userId = "user-2"; + const response = await requestApproval(); + const continuation = new URL(response.headers.get("location") ?? ""); + + expect(response.status).toBe(303); + expect(continuation.pathname).toBe("/api/desktop/session/request"); + expect(continuation.searchParams.get("state")).toBe(browserState); + expect(state.events).toEqual([]); + expect(state.limiterCalls).toEqual([]); + }); + + it("returns an expired credential session to login without minting", async () => { + state.databaseVersion = 3; + const response = await requestApproval(); + const location = new URL(response.headers.get("location") ?? ""); + + expect(response.status).toBe(303); + expect(location.pathname).toBe("/login"); + const continuation = new URL(location.searchParams.get("next") ?? ""); + expect(continuation.pathname).toBe("/api/desktop/session/request"); + expect(continuation.searchParams.get("state")).toBe(browserState); + expect(state.events).toEqual(["lock:update:user-1"]); + expect(desktopKeys("user-1")).toEqual([]); + }); + + it("preserves an approved legacy token callback", async () => { + const response = await requestApproval( + new URLSearchParams({ + type: "session", + platform: "web", + port: "49152", + accountId: "user-1", + }), + { + "Sec-Fetch-Site": "same-origin", + Cookie: "next-auth.session-token=test-session", + }, + ); + const callback = new URL(response.headers.get("location") ?? ""); + + expect(response.status).toBe(303); + expect(callback.origin).toBe("http://127.0.0.1:49152"); + expect(callback.searchParams.get("token")).toBe("test-session"); + expect(callback.searchParams.get("expires")).toBe("1234"); + expect(state.events).toEqual([]); + }); + + it("continues through the native app when no loopback listener is available", async () => { + const response = await requestApproval( + new URLSearchParams({ + type: "api_key", + platform: "web", + state: browserState, + accountId: "user-1", + }), + ); + const callback = new URL(response.headers.get("location") ?? ""); + + expect(response.status).toBe(303); + expect(callback.protocol).toBe("cap-desktop:"); + expect(callback.hostname).toBe("signin"); + expect(callback.searchParams.get("state")).toBe(browserState); + expect(desktopKeys("user-1").map((row) => row.id)).toEqual([ + callback.searchParams.get("api_key"), + ]); + }); + + it("preserves the browser fallback on an approved desktop handoff", async () => { + const response = await requestApproval( + new URLSearchParams({ + type: "api_key", + platform: "desktop", + port: "49152", + state: browserState, + accountId: "user-1", + }), + ); + const page = await response.text(); + + expect(response.status).toBe(200); + expect(response.headers.get("cache-control")).toBe("private, no-store"); + expect(page).toContain("cap-desktop://signin?"); + expect(page).toContain('href="http://127.0.0.1:49152/?'); + expect(page).toContain(`state=${browserState}`); + expect(desktopKeys("user-1")).toHaveLength(1); + }); + it("returns a new key that stays stored for the signed-in user", async () => { const apiKey = await requestApiKey(); @@ -230,13 +395,6 @@ describe("desktop api key sign-in", () => { expect(state.events).toEqual(["lock:update:user-1", "count", "insert"]); }); - const request = async () => { - const { app } = await import("@/app/api/desktop/[...route]/session"); - return app.request( - "https://cap.example/request?type=api_key&platform=web&port=49152", - ); - }; - it("issues no key once 20 desktop keys were made in the last hour", async () => { state.rows.push({ id: "hour-old", @@ -250,7 +408,7 @@ describe("desktop api key sign-in", () => { state.mints.clear(); state.events = []; - const refused = await request(); + const refused = await requestApproval(); expect(refused.status).toBe(429); expect(refused.headers.get("location")).toBeNull(); @@ -263,7 +421,7 @@ describe("desktop api key sign-in", () => { state.rows = []; state.events = []; - const refused = await request(); + const refused = await requestApproval(); expect(refused.status).toBe(429); expect(state.events).toEqual([]); diff --git a/apps/web/__tests__/unit/desktop-session-state-probe.test.ts b/apps/web/__tests__/unit/desktop-session-state-probe.test.ts index 3873144629b..d6fbcf1c4e4 100644 --- a/apps/web/__tests__/unit/desktop-session-state-probe.test.ts +++ b/apps/web/__tests__/unit/desktop-session-state-probe.test.ts @@ -1,42 +1,19 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -const state = vi.hoisted(() => ({ - inserted: 0, - user: null as null | { id: string }, +const mocks = vi.hoisted(() => ({ + db: vi.fn(), + getBrowserCredentialSession: vi.fn(), + getCurrentUser: vi.fn(), })); -vi.mock("@cap/database", () => { - const tx = { - select: () => ({ - from: () => ({ - where: () => - Object.assign(Promise.resolve([{ total: 0 }]), { - for: async () => [], - orderBy: () => ({ limit: () => ({ offset: async () => [] }) }), - }), - }), - }), - insert: () => ({ - values: async () => { - state.inserted += 1; - }, - }), - delete: () => ({ where: async () => {} }), - }; - return { - db: () => ({ - ...tx, - transaction: async (callback: (value: typeof tx) => Promise) => - callback(tx), - }), - }; -}); +vi.mock("@cap/database", () => ({ db: mocks.db })); vi.mock("@/lib/rate-limit", async (importOriginal) => ({ ...(await importOriginal()), isRateLimited: async () => false, })); vi.mock("@cap/database/auth/session", () => ({ - getCurrentUser: async () => state.user, + getBrowserCredentialSession: mocks.getBrowserCredentialSession, + getCurrentUser: mocks.getCurrentUser, })); vi.mock("@cap/database/auth/auth-options", () => ({ decodeSessionToken: vi.fn(), @@ -49,38 +26,53 @@ vi.mock("@cap/env", () => ({ })); const WELL_FORMED = "abcdefghijklmnopqrstuvwxyz012345"; +const { app } = await import("@/app/api/desktop/[...route]/session"); -const request = async (query: string) => { - const { app } = await import("@/app/api/desktop/[...route]/session"); - return app.request(`https://cap.example/request?${query}`); -}; +const request = (query: string) => + app.request(`https://cap.example/request?${query}`); beforeEach(() => { - state.inserted = 0; - state.user = null; + vi.clearAllMocks(); + mocks.getCurrentUser.mockResolvedValue(null); }); -describe("desktop sign-in state support, as the desktop app checks it", () => { - it("rejects a malformed state with 400 before signing anyone in", async () => { +describe("desktop sign-in state across browser requests", () => { + it("rejects a malformed state before looking up the consent account", async () => { const res = await request("type=api_key&state=x"); expect(res.status).toBe(400); - expect(state.inserted).toBe(0); - }); - - it("does not reject a well-formed state", async () => { - const res = await request(`type=api_key&state=${WELL_FORMED}`); - expect(res.status).toBe(302); - expect(res.headers.get("location")).toContain("/login"); + expect(mocks.getCurrentUser).not.toHaveBeenCalled(); + expect(mocks.db).not.toHaveBeenCalled(); }); - it("returns the state on the loopback callback for a signed-in user", async () => { - state.user = { id: "user-1" }; + it("carries valid state through the login continuation", async () => { const res = await request( `type=api_key&platform=web&port=49152&state=${WELL_FORMED}`, ); - const location = new URL(res.headers.get("location") ?? ""); - expect(location.hostname).toBe("127.0.0.1"); - expect(location.searchParams.get("state")).toBe(WELL_FORMED); - expect(location.searchParams.get("user_id")).toBe("user-1"); + const login = new URL(res.headers.get("location") ?? ""); + const continuation = new URL(login.searchParams.get("next") ?? ""); + + expect(res.status).toBe(302); + expect(login.pathname).toBe("/login"); + expect(continuation.pathname).toBe("/request"); + expect(continuation.searchParams.get("state")).toBe(WELL_FORMED); + expect(continuation.searchParams.get("port")).toBe("49152"); + }); + + it("validates state again at approval before issuing credentials", async () => { + const res = await app.request("https://cap.example/approve", { + method: "POST", + headers: { "Sec-Fetch-Site": "same-origin" }, + body: new URLSearchParams({ + type: "api_key", + platform: "web", + port: "49152", + accountId: "user-1", + state: "x", + }), + }); + + expect(res.status).toBe(400); + expect(mocks.getBrowserCredentialSession).not.toHaveBeenCalled(); + expect(mocks.db).not.toHaveBeenCalled(); }); }); diff --git a/apps/web/__tests__/unit/desktop-session-tor-exit.test.ts b/apps/web/__tests__/unit/desktop-session-tor-exit.test.ts index a6b5027c389..12a9644b83b 100644 --- a/apps/web/__tests__/unit/desktop-session-tor-exit.test.ts +++ b/apps/web/__tests__/unit/desktop-session-tor-exit.test.ts @@ -9,7 +9,7 @@ vi.mock("@cap/database", () => { from: () => ({ where: () => Object.assign(Promise.resolve([{ total: 0 }]), { - for: async () => [], + for: async () => [{ authSessionVersion: 1 }], orderBy: () => ({ limit: () => ({ offset: async () => [] }) }), }), }), @@ -34,7 +34,14 @@ vi.mock("@/lib/rate-limit", async (importOriginal) => ({ isRateLimited: async () => false, })); vi.mock("@cap/database/auth/session", () => ({ - getCurrentUser: async () => ({ id: "user-1" }), + getBrowserCredentialSession: async () => ({ + id: "user-1", + authSessionVersion: 1, + }), + getCurrentUser: async () => ({ + id: "user-1", + email: "person@example.test", + }), })); vi.mock("@cap/database/auth/auth-options", () => ({ decodeSessionToken: vi.fn(), @@ -54,13 +61,25 @@ const list = [ LISTED, ].join("\n"); -const requestApiKey = async (address: string) => { - const { app } = await import("@/app/api/desktop/[...route]/session"); - return app.request( +const { app } = await import("@/app/api/desktop/[...route]/session"); + +const requestConsent = (address: string) => + app.request( "https://cap.example/request?type=api_key&platform=web&port=49152", { headers: { "x-real-ip": address } }, ); -}; + +const approveSignIn = (address: string) => + app.request("https://cap.example/approve", { + method: "POST", + headers: { "x-real-ip": address, "Sec-Fetch-Site": "same-origin" }, + body: new URLSearchParams({ + type: "api_key", + platform: "web", + port: "49152", + accountId: "user-1", + }), + }); beforeEach(() => { state.inserted = 0; @@ -79,19 +98,30 @@ afterEach(() => { }); describe("desktop session request", () => { - it("refuses a Tor exit with the blocked notice and creates no key", async () => { - const response = await requestApiKey(LISTED); + it.each([ + ["consent", requestConsent, 302], + ["approval", approveSignIn, 303], + ] as const)( + "shows the blocked notice and creates no key from a Tor exit during %s", + async (_phase, request, status) => { + const response = await request(LISTED); - expect(response.status).toBe(302); - const location = new URL(response.headers.get("location") ?? ""); - expect(location.pathname).toBe("/login"); - expect(location.searchParams.get("error")).toBe("SignupBlocked"); + expect(response.status).toBe(status); + const location = new URL(response.headers.get("location") ?? ""); + expect(location.pathname).toBe("/login"); + expect(location.searchParams.get("error")).toBe("SignupBlocked"); + expect(state.inserted).toBe(0); + }, + ); + + it("issues a key after approval from another address", async () => { + const consent = await requestConsent(UNLISTED); + expect(consent.status).toBe(200); expect(state.inserted).toBe(0); - }); - it("issues a key to other addresses", async () => { - const response = await requestApiKey(UNLISTED); + const response = await approveSignIn(UNLISTED); + expect(response.status).toBe(303); const location = new URL(response.headers.get("location") ?? ""); expect(location.hostname).toBe("127.0.0.1"); expect(location.searchParams.get("api_key")).toMatch(/^[0-9a-f-]{36}$/); diff --git a/apps/web/app/api/desktop/[...route]/session.ts b/apps/web/app/api/desktop/[...route]/session.ts index 811e98da9ec..7d30eb84803 100644 --- a/apps/web/app/api/desktop/[...route]/session.ts +++ b/apps/web/app/api/desktop/[...route]/session.ts @@ -1,6 +1,9 @@ import { db } from "@cap/database"; import { decodeSessionToken } from "@cap/database/auth/auth-options"; -import { getCurrentUser } from "@cap/database/auth/session"; +import { + getBrowserCredentialSession, + getCurrentUser, +} from "@cap/database/auth/session"; import { authApiKeys, users } from "@cap/database/schema"; import { serverEnv } from "@cap/env"; import type { User } from "@cap/web-domain"; @@ -10,7 +13,11 @@ import { getCookie } from "hono/cookie"; import { buildDesktopCallbackParams, buildLoopbackCallbackUrl, + createDesktopConsentPage, createDesktopRedirectPage, + type DesktopSessionRequest, + desktopSessionApprovalFormSchema, + desktopSessionRequestParams, desktopSessionRequestQuerySchema, } from "@/lib/desktop-session"; import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit"; @@ -19,32 +26,69 @@ import { zValidator } from "@/utils/zod-validator"; export const app = new Hono(); +app.use("*", async (c, next) => { + c.header("Cache-Control", "private, no-store"); + c.header("Content-Security-Policy", "frame-ancestors 'none'"); + c.header("Referrer-Policy", "no-referrer"); + c.header("X-Frame-Options", "DENY"); + await next(); +}); + app.get( "/request", zValidator("query", desktopSessionRequestQuerySchema), async (c) => { - const { port, platform, type, state } = c.req.valid("query"); + const redirectOrigin = getDeploymentOrigin(); + if (await shouldRefuseTorExit("desktop-session", c.req.raw.headers)) { + const blockedUrl = new URL("/login", redirectOrigin); + blockedUrl.searchParams.set("error", "SignupBlocked"); + return c.redirect(blockedUrl); + } - const secret = serverEnv().NEXTAUTH_SECRET; + const request = c.req.valid("query"); + const user = await getCurrentUser(); + if (!user) + return c.redirect( + loginRedirectUrl(consentUrl(redirectOrigin, c.req.path, request)), + ); - const url = new URL(c.req.url); + c.header( + "Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'", + ); + c.header("Referrer-Policy", "same-origin"); + return c.html(createDesktopConsentPage(user, request)); + }, +); +app.post( + "/approve", + async (c, next) => { + const fetchSite = c.req.header("Sec-Fetch-Site"); + const sameOrigin = + fetchSite === undefined + ? c.req.header("Origin") === new URL(getDeploymentOrigin()).origin + : fetchSite === "same-origin"; + if (!sameOrigin) return c.text("Forbidden", 403); + await next(); + }, + zValidator("form", desktopSessionApprovalFormSchema), + async (c) => { const redirectOrigin = getDeploymentOrigin(); - - const loginRedirectUrl = new URL(`${redirectOrigin}/login`); - loginRedirectUrl.searchParams.set( - "next", - new URL(`${redirectOrigin}${url.pathname}${url.search}`).toString(), - ); + const request = c.req.valid("form"); + const { port, platform, type, state, accountId } = request; + const consent = consentUrl(redirectOrigin, c.req.path, request); + const reauthenticate = () => c.redirect(loginRedirectUrl(consent), 303); if (await shouldRefuseTorExit("desktop-session", c.req.raw.headers)) { - const blockedUrl = new URL(`${redirectOrigin}/login`); + const blockedUrl = new URL("/login", redirectOrigin); blockedUrl.searchParams.set("error", "SignupBlocked"); - return c.redirect(blockedUrl); + return c.redirect(blockedUrl, 303); } - const user = await getCurrentUser(); - if (!user) return c.redirect(loginRedirectUrl); + const session = await getBrowserCredentialSession(); + if (!session) return reauthenticate(); + if (session.id !== accountId) return c.redirect(consent, 303); let data: | { type: "token"; token: string; expires: string } @@ -52,11 +96,14 @@ app.get( if (type === "session") { const token = getCookie(c, "next-auth.session-token"); - if (token === undefined) return c.redirect(loginRedirectUrl); + if (token === undefined) return reauthenticate(); - const decodedToken = await decodeSessionToken({ token, secret }); + const decodedToken = await decodeSessionToken({ + token, + secret: serverEnv().NEXTAUTH_SECRET, + }); - if (!decodedToken) return c.redirect(loginRedirectUrl); + if (decodedToken?.id !== session.id) return reauthenticate(); data = { type: "token", @@ -64,13 +111,14 @@ app.get( expires: String(decodedToken.exp), }; } else { - const apiKey = (await isRateLimited(RATE_LIMIT_IDS.DESKTOP_KEY_MINT, { - key: `desktop-key-mint:${user.id}`, + const result = (await isRateLimited(RATE_LIMIT_IDS.DESKTOP_KEY_MINT, { + key: `desktop-key-mint:${session.id}`, headers: c.req.raw.headers, })) - ? null - : await createDesktopApiKey(user.id); - if (!apiKey) { + ? ({ status: "limited" } as const) + : await createDesktopApiKey(session.id, session.authSessionVersion); + if (result.status === "expired") return reauthenticate(); + if (result.status === "limited") { return c.text( "Too many sign-ins in the last hour. Try again later.", 429, @@ -79,48 +127,60 @@ app.get( }, ); } - data = { type: "api_key", api_key: apiKey }; + data = { type: "api_key", api_key: result.apiKey }; } - const params = buildDesktopCallbackParams(data, user.id, state); + const params = buildDesktopCallbackParams(data, session.id, state); const localhostUrl = port !== undefined ? buildLoopbackCallbackUrl(port, params) : undefined; const deepLinkUrl = `cap-desktop://signin?${params}`; if (platform === "web" && localhostUrl) { - return Response.redirect(localhostUrl); + return c.redirect(localhostUrl, 303); } if (platform === "desktop" && localhostUrl) { - return new Response( - createDesktopRedirectPage(deepLinkUrl, localhostUrl), - { - headers: { - "Content-Type": "text/html; charset=utf-8", - "Cache-Control": "no-store, no-cache, must-revalidate", - Pragma: "no-cache", - }, - }, - ); + return c.html(createDesktopRedirectPage(deepLinkUrl, localhostUrl)); } - return Response.redirect(deepLinkUrl); + return c.redirect(deepLinkUrl, 303); }, ); +function consentUrl( + origin: string, + path: string, + request: DesktopSessionRequest, +) { + const continuation = new URL("request", new URL(path, origin)); + continuation.search = desktopSessionRequestParams(request).toString(); + return continuation; +} + +function loginRedirectUrl(consent: URL) { + const login = new URL("/login", consent); + login.searchParams.set("next", consent.toString()); + return login; +} + const MAX_DESKTOP_API_KEYS_PER_USER = 20; const DESKTOP_API_KEYS_PER_HOUR = 20; const DESKTOP_API_KEY_WINDOW_MS = 60 * 60 * 1000; const STALE_DESKTOP_API_KEY_BATCH = 1000; -async function createDesktopApiKey(userId: User.UserId) { +async function createDesktopApiKey( + userId: User.UserId, + authSessionVersion: number, +) { const id = crypto.randomUUID(); - const minted = await db().transaction(async (tx) => { - await tx - .select({ id: users.id }) + return db().transaction(async (tx) => { + const [user] = await tx + .select({ authSessionVersion: users.authSessionVersion }) .from(users) .where(eq(users.id, userId)) .for("update"); + if (user?.authSessionVersion !== authSessionVersion) + return { status: "expired" } as const; const [recent] = await tx .select({ total: count() }) .from(authApiKeys) @@ -134,7 +194,8 @@ async function createDesktopApiKey(userId: User.UserId) { ), ), ); - if (Number(recent?.total ?? 0) >= DESKTOP_API_KEYS_PER_HOUR) return false; + if (Number(recent?.total ?? 0) >= DESKTOP_API_KEYS_PER_HOUR) + return { status: "limited" } as const; await tx.insert(authApiKeys).values({ id, userId, source: "desktop" }); for (;;) { const staleKeys = await tx @@ -159,9 +220,8 @@ async function createDesktopApiKey(userId: User.UserId) { ); if (staleKeys.length < STALE_DESKTOP_API_KEY_BATCH) break; } - return true; + return { status: "minted", apiKey: id } as const; }); - return minted ? id : null; } function getDeploymentOrigin() { diff --git a/apps/web/lib/desktop-session.ts b/apps/web/lib/desktop-session.ts index 3b1a2843809..1d475c7f564 100644 --- a/apps/web/lib/desktop-session.ts +++ b/apps/web/lib/desktop-session.ts @@ -19,6 +19,29 @@ export const desktopSessionRequestQuerySchema = z.object({ .optional(), }); +export type DesktopSessionRequest = z.infer< + typeof desktopSessionRequestQuerySchema +>; + +export const desktopSessionApprovalFormSchema = + desktopSessionRequestQuerySchema.extend({ + platform: desktopSessionRequestQuerySchema.shape.platform.removeDefault(), + type: desktopSessionRequestQuerySchema.shape.type.removeDefault(), + accountId: z.string().min(1).max(255), + }); + +export function desktopSessionRequestParams({ + port, + platform, + type, + state, +}: DesktopSessionRequest) { + const params = new URLSearchParams({ platform, type }); + if (port !== undefined) params.set("port", String(port)); + if (state !== undefined) params.set("state", state); + return params; +} + export function buildDesktopCallbackParams( data: Record, userId: string, @@ -53,6 +76,46 @@ export function escapeHtmlAttribute(value: string) { .replace(/'/g, "'"); } +export function createDesktopConsentPage( + account: { id: string; email: string }, + request: DesktopSessionRequest, +) { + const fields = Array.from( + desktopSessionRequestParams(request), + ([name, value]) => + ``, + ).join(""); + + return ` + + + + + + Connect Cap Desktop + + + +
+

Connect Cap Desktop

+

Sign in to Cap Desktop as ${escapeHtmlAttribute(account.email)}.

+

Only continue if you opened this window from Cap Desktop.

+
+ + ${fields} + +
+
+ +`; +} + export function serializeStateForScript(value: unknown) { // Escape characters that could break out of an inline