Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/api/migrations/0107_browser_session_revocations.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- A browser sign-out revokes only that cookie, without changing the
-- membership version used to invalidate credentials after security events.
CREATE TABLE app.revoked_browser_sessions (
digest text PRIMARY KEY,
expires_at timestamptz NOT NULL
);
CREATE INDEX revoked_browser_sessions_expiry_idx ON app.revoked_browser_sessions (expires_at);
23 changes: 12 additions & 11 deletions packages/api/src/auth-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import { z } from "zod";
import { AuthRepository } from "./postgres/auth-repository";
import { IdentityRepository } from "./postgres/identity-repository";
import { databaseFor } from "./postgres/database";
import { readSession, requestCookie, signSession, type Session } from "./session";
import { requestCookie, signSession, type Session } from "./session";
import { readBrowserSession, revokeBrowserSession } from "./browser-session";
import type { Env } from "./types";

export const SESSION_SCOPES = [...ACCESS_SCOPES, "apps:manage"] as const;
Expand Down Expand Up @@ -93,7 +94,7 @@ async function limitGoogleStart(request: Request, env: Env) {
return response;
}
async function currentSession(request: Request, env: Env): Promise<Session | null> {
const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET);
const session = await readBrowserSession(request, env);
if (!session) return null;
const member = await new IdentityRepository(databaseFor(env), session.tenantId).member(session.userId);
return member?.role === "owner" && member.sessionVersion === session.sessionVersion ? { ...session, email: member.email } : null;
Expand Down Expand Up @@ -249,7 +250,14 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env
const pending = await connectionFor(env, String(input.connection));
if (!pending || !await originalBrowser(request, env, pending)) return failure(400, "Invalid or expired connection. Restart connecting from your MCP client.");
}
if (action === "profile" || action === "profile-update" || action === "session" || action === "logout" || action === "password" || action === "consent-preview" || action === "consent-decision" || action === "device-preview" || action === "device-decision") {
if (action === "logout") {
await revokeBrowserSession(request, env);
const response = authJson({ ok: true });
response.headers.append("Set-Cookie", clearTotpLoginCookie(env));
response.headers.append("Set-Cookie", sessionCookie(env, "", 0));
return response;
}
if (action === "profile" || action === "profile-update" || action === "session" || action === "password" || action === "consent-preview" || action === "consent-decision" || action === "device-preview" || action === "device-decision") {
const session = await currentSession(request, env);
if (action === "profile" || action === "profile-update") {
if (!session) return failure(401, "Sign in to manage your profile.");
Expand Down Expand Up @@ -290,13 +298,6 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env
return failure(400, "Factorize couldn't validate this connection. Start Reconnect in your MCP client and use the fresh authorization link.");
}
}
if (action === "logout") {
if (session) await new IdentityRepository(databaseFor(env), session.tenantId).revoke(session.userId);
const response = authJson({ ok: true });
response.headers.append("Set-Cookie", clearTotpLoginCookie(env));
response.headers.append("Set-Cookie", sessionCookie(env, "", 0));
return response;
}
if (!session) return failure(401, "The request is not authorized.");
const result = await new AuthRepository(databaseFor(env), env).changePassword(session.userId, input);
if (result.status !== 200) return failure(result.status, "error" in result.body ? result.body.error : "Password change failed.");
Expand Down Expand Up @@ -406,6 +407,6 @@ async function signedIn(env: Env, identity: GoogleIdentity, body: { ok?: boolean
async function issueSession(env: Env, identity: GoogleIdentity, body: unknown) {
const lifetime = 7 * 24 * 60 * 60;
const response = authJson(body);
response.headers.append("Set-Cookie", sessionCookie(env, await signSession({ tenantId: identity.tenantId, userId: identity.userId, email: identity.email, sessionVersion: identity.sessionVersion, exp: Math.floor(Date.now() / 1000) + lifetime }, env.SESSION_SIGNING_SECRET), lifetime));
response.headers.append("Set-Cookie", sessionCookie(env, await signSession({ tenantId: identity.tenantId, userId: identity.userId, email: identity.email, sessionVersion: identity.sessionVersion, browserNonce: crypto.randomUUID(), exp: Math.floor(Date.now() / 1000) + lifetime }, env.SESSION_SIGNING_SECRET), lifetime));
return response;
}
33 changes: 33 additions & 0 deletions packages/api/src/browser-session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { databaseFor } from "./postgres/database";
import { readSession, requestCookie, type Session } from "./session";
import type { Env } from "./types";

async function browserCredential(request: Request, env: Env) {
const value = requestCookie(request, "factorize_session");
const session = await readSession(value, env.SESSION_SIGNING_SECRET);
if (!session || !value || typeof session.tenantId !== "string" || typeof session.userId !== "string"
|| typeof session.email !== "string" || !Number.isSafeInteger(session.exp)
|| !Number.isSafeInteger(session.sessionVersion)) return null;
// Key the revocation by the signed payload, not the cookie encoding or
// signature. Old cookies without a nonce keep working until expiry/logout.
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value.split(".", 1)[0]));
return { session, digest: btoa(String.fromCharCode(...new Uint8Array(digest))) };
}

export async function readBrowserSession(request: Request, env: Env): Promise<Session | null> {
const credential = await browserCredential(request, env);
if (!credential) return null;
const revoked = await databaseFor(env).pool.query(
"SELECT 1 FROM app.revoked_browser_sessions WHERE digest=$1", [credential.digest],
);
return revoked.rows.length ? null : credential.session;
}

export async function revokeBrowserSession(request: Request, env: Env): Promise<void> {
const credential = await browserCredential(request, env);
if (!credential) return;
await databaseFor(env).pool.query(
"INSERT INTO app.revoked_browser_sessions(digest,expires_at) VALUES ($1,$2) ON CONFLICT (digest) DO NOTHING",
[credential.digest, new Date(credential.session.exp * 1000)],
);
}
18 changes: 10 additions & 8 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { executeAuth } from "./auth-api";
import { STATIC_CSP, staticApp } from "./static-app";
import { Hono } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import { readSession, signSession, type Session } from "./session";
import type { Session } from "./session";
import { readBrowserSession } from "./browser-session";
export { readSession, signSession, requestCookie, type Session } from "./session";
import { equalHmac, hmac } from "./crypto";
import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./github";
Expand Down Expand Up @@ -44,11 +45,10 @@ app.onError((error, c) => {
return c.text("Internal Server Error", 500);
});

async function authed(c: any): Promise<Session | null> { return readSession(getCookie(c, "factorize_session"), c.env.SESSION_SIGNING_SECRET); }
async function owner(c: any): Promise<Session | null> {
const started = performance.now();
try {
const session = await authed(c); if (!session) return null;
const session = await readBrowserSession(c.req.raw, c.env); if (!session) return null;
const member = await new IdentityRepository(databaseFor(c.env), session.tenantId).member(session.userId);
return member?.role === "owner" && member.sessionVersion === session.sessionVersion ? session : null;
} finally { c.set("authorizationDuration", (c.get("authorizationDuration") ?? 0) + performance.now() - started); }
Expand Down Expand Up @@ -88,10 +88,12 @@ app.get("/auth/linear/callback", async (c) => {
});

app.post("/auth/logout", async (c) => {
const session = await owner(c);
if (session) await new IdentityRepository(databaseFor(c.env), session.tenantId).revoke(session.userId);
deleteCookie(c, "factorize_session", { path: "/" });
return c.redirect("/");
const response = await executeAuth("logout", c.req.raw, c.env);
if (!response.ok) return response;
const headers = new Headers(response.headers);
headers.set("Location", "/");
headers.delete("Content-Type");
return new Response(null, { status: 302, headers });
});

// Form compatibility uses the same continuation and session rules as the JSON API.
Expand Down Expand Up @@ -121,7 +123,7 @@ app.post("/auth/password-change", async (c) => {
app.get("/auth/clickup", async (c) => {
const session = await owner(c); if (!session) return c.redirect("/auth/login");
if (!c.env.CLICKUP_CLIENT_ID) return c.text("ClickUp OAuth is not configured", 503);
const state = await signSession({ ...session, exp: Math.floor(Date.now() / 1000) + 600 }, c.env.SESSION_SIGNING_SECRET);
const state = await signSetupState({ tenantId: session.tenantId, userId: session.userId, nonce: crypto.randomUUID(), exp: Math.floor(Date.now() / 1000) + 600 }, c.env.SESSION_SIGNING_SECRET);
setCookie(c, "clickup_oauth_state", state, { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/auth/clickup", maxAge: 600 });
const redirect = new URL("https://app.clickup.com/api");
redirect.searchParams.set("client_id", c.env.CLICKUP_CLIENT_ID);
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/session.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { parse } from "hono/utils/cookie";
import { hmac } from "./crypto";

export type Session = { tenantId: string; userId: string; email: string; exp: number; sessionVersion: number };
export type Session = { tenantId: string; userId: string; email: string; exp: number; sessionVersion: number; browserNonce?: string };
const textEncoder = new TextEncoder();

function b64(value: string): string { return btoa(String.fromCharCode(...textEncoder.encode(value))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); }
Expand Down
10 changes: 6 additions & 4 deletions packages/api/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { wakeMcpDeliveries } from "./postgres/event-match-repository";
import { staticApp, securityHeaders } from "./static-app";
import { OAuthProvider, AuthorizationError, getOAuthApi, type AuthRequest, type OAuthProviderOptions } from "@cloudflare/workers-oauth-provider";
import app from "./index";
import { readSession, requestCookie } from "./session";
import { readBrowserSession } from "./browser-session";
import { isBrowserAuthOperation } from "./api-contract";
import { ProtectedApiHandler, protectedApiFetch } from "./protected-api";
import { startConnection, connectionFor } from "./oauth-continuation";
Expand All @@ -27,7 +27,7 @@ const scopes = [...ACCESS_SCOPES, "apps:manage"];
// consent screens and metadata advertise only the canonical scopes above.
const oauthScopes = [...AGENT_SCOPES];
async function currentOwner(request: Request, env: Env) {
const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET);
const session = await readBrowserSession(request, env);
if (!session) return null;
const member = await new IdentityRepository(databaseFor(env), session.tenantId).member(session.userId);
return member?.role === "owner" && member.sessionVersion === session.sessionVersion ? session : null;
Expand Down Expand Up @@ -136,9 +136,9 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext)
}
if (isBrowserAuthOperation(request.method, url.pathname)) return protectedApiFetch(request, apiEnv, null, ctx);
if (url.pathname.startsWith("/api/v1") && !request.headers.has("Authorization")) {
// Signature and expiry here; the service performs the authoritative owner,
// Validate the browser cookie and its revocation here; the service performs the authoritative owner,
// verified-email and session-version lookup once for this API request.
const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET);
const session = await readBrowserSession(request, env);
if (!session) return Response.json({ error: { code: "invalid_token", message: "Unauthorized" } }, { status: 401 });
return protectedApiFetch(request, apiEnv, { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes, authMethod: "session" }, ctx);
}
Expand Down Expand Up @@ -177,6 +177,8 @@ export default {
const db = databaseFor(env);
await clearExpiredGoogleSignIns(db.pool);
await pruneTotp(db.pool);
await db.pool.query(`DELETE FROM app.revoked_browser_sessions WHERE digest IN
(SELECT digest FROM app.revoked_browser_sessions WHERE expires_at<now()-interval '1 day' ORDER BY expires_at LIMIT 5000)`);
await db.pool.query(`DELETE FROM app.vm_permission_proofs WHERE (tenant_id,grant_id,proof_id) IN
(SELECT tenant_id,grant_id,proof_id FROM app.vm_permission_proofs WHERE expires_at<now() ORDER BY expires_at LIMIT 5000)`);
await db.pool.query(`UPDATE app.vm_permission_grants SET revoked_at=now(),updated_at=now(),updated_by='system:enrollment-timeout',
Expand Down
5 changes: 3 additions & 2 deletions packages/api/src/x-oauth-callback.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { requestCookie, readSession } from "./session";
import { requestCookie } from "./session";
import { readBrowserSession } from "./browser-session";
import { databaseFor } from "./postgres/database";
import { IdentityRepository } from "./postgres/identity-repository";
import { XAccountMismatchError, XConnectionRepository } from "./postgres/x-connection-repository";
Expand All @@ -20,7 +21,7 @@ export async function xOAuthCallback(request: Request, env: Env): Promise<Respon
const fail = (result: string) => {
return new Response(null, { status: 303, headers: { Location: settings(env, result), ...clear } });
};
const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET);
const session = await readBrowserSession(request, env);
if (!session) return fail("session_required");
const database = databaseFor(env), identities = new IdentityRepository(database, session.tenantId);
const member = await identities.member(session.userId);
Expand Down
15 changes: 8 additions & 7 deletions packages/api/test/auth-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ vi.mock("@cloudflare/workers-oauth-provider", () => ({
AuthorizationError: class extends Error {},
getOAuthApi: vi.fn(),
}));
const env = { APP_ORIGIN: "https://app.test", SESSION_SIGNING_SECRET: "test-only-secret", DATABASE: { pool: { query: vi.fn() } } } as unknown as Env;
const env = { APP_ORIGIN: "https://app.test", SESSION_SIGNING_SECRET: "test-only-secret", DATABASE: { pool: { query: vi.fn(async () => ({ rows: [] })) } } } as unknown as Env;
const ctx = {} as ExecutionContext;
const identity = { tenantId: "tenant-a", userId: "user-a", email: "owner@test.com", sessionVersion: 4 };
const member = { ...identity, role: "owner" as const };
const auth: OAuthProps = { ...identity, scopes: ["team:read", "triggers:read", "integrations:read", "team:write", "triggers:write", "integrations:write", "triggers:read", "triggers:write", "triggers:write", "triggers:write"], authMethod: "session" };
const openapi = parse(readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"));
afterEach(() => vi.restoreAllMocks());
afterEach(() => { vi.mocked(env.DATABASE!.pool.query).mockReset().mockResolvedValue({ rows: [] } as never); vi.restoreAllMocks(); });

async function call(path: string, body?: unknown, headers: Record<string, string> = {}) {
return worker.fetch(new Request(env.APP_ORIGIN + path, {
Expand Down Expand Up @@ -122,7 +122,7 @@ describe("public auth API and cookie security", () => {
it("maps current authoritative identity and selected workspace without secrets", async () => {
const cookie = await signSession({ ...identity, email: "stale@test.com", exp: Math.floor(Date.now() / 1000) + 100 }, env.SESSION_SIGNING_SECRET);
vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue(member);
vi.mocked(env.DATABASE!.pool.query).mockResolvedValue({ rows: [{ name: "Workspace A", has_password: true }] } as never);
vi.mocked(env.DATABASE!.pool.query).mockResolvedValueOnce({ rows: [] } as never).mockResolvedValueOnce({ rows: [{ name: "Workspace A", has_password: true }] } as never);
const response = await call("/api/v1/session", undefined, { Cookie: "factorize_session=" + cookie });
expect(await contract(response, "/api/v1/session", "GET")).toMatchObject({ authenticated: true, user: { id: identity.userId, email: identity.email }, team: { id: identity.tenantId, name: "Workspace A", role: "owner" }, hasPassword: true, capabilities: expect.arrayContaining(["triggers:read", "triggers:write"]) });
const query = vi.mocked(env.DATABASE!.pool.query).mock.calls.at(-1)!;
Expand Down Expand Up @@ -186,15 +186,16 @@ describe("public auth API and cookie security", () => {
});

it("revokes logout sessions and safely clears absent/expired sessions too", async () => {
vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue(member);
const revoke = vi.spyOn(IdentityRepository.prototype, "revoke").mockResolvedValue(true);
const revoke = vi.spyOn(IdentityRepository.prototype, "revoke");
vi.mocked(env.DATABASE!.pool.query).mockClear();
const cookie = await signSession({ ...identity, exp: Math.floor(Date.now() / 1000) + 100 }, env.SESSION_SIGNING_SECRET);
const response = await call("/api/v1/auth/logout", {}, { Cookie: "factorize_session=" + cookie });
expect(response.status).toBe(200);
expect(revoke).toHaveBeenCalledWith(identity.userId);
expect(revoke).not.toHaveBeenCalled();
expect(env.DATABASE!.pool.query).toHaveBeenCalledWith(expect.stringContaining("INSERT INTO app.revoked_browser_sessions"), [expect.any(String), expect.any(Date)]);
expect(response.headers.get("Set-Cookie")).toContain("Max-Age=0");
expect((await call("/api/v1/auth/logout", {})).status).toBe(200);
expect(revoke).toHaveBeenCalledTimes(1);
expect(env.DATABASE!.pool.query).toHaveBeenCalledTimes(1);
});

it("rejects bearer credentials for browser identity and auth operations", async () => {
Expand Down
Loading
Loading