Skip to content

An open-source, faster Devin alternative

TypeScript

fix(auth): end WorkOS session on logout at the edge; review fixups

Igor Zalutskib162475f9cfc
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index d8116e1c..9e877f15 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1160,8 +1160,10 @@ async function authCallback(req: Request, env: Env): Promise<Response> {
const errText = await tokenResp.text();
return json({ error: `workos exchange failed: ${tokenResp.status}: ${errText}` }, 401);
}
- const tokenBody = await tokenResp.json<{ user: WorkOSProfile; organization_id?: string }>();
+ const tokenBody = await tokenResp.json<{ user: WorkOSProfile; organization_id?: string; access_token?: string }>();
const profile = tokenBody.user;
+ // WorkOS session id (sid) for the hosted logout flow — carried in our session JWT.
+ const workosSessionID = workosSessionIdFromAccessToken(tokenBody.access_token);
// Upsert user + org. We share WorkOS with prod, so workos_user_id is the
// stable identity across both. Org auto-created on first sign-in with
@@ -1238,7 +1240,7 @@ async function authCallback(req: Request, env: Env): Promise<Response> {
// Mint session JWT — same signing secret as cap-token but a different
// Issuer so cell middleware can distinguish.
- const sessionJWT = await mintSessionJWT(env.SESSION_JWT_SECRET, orgID, userID, orgPlan);
+ const sessionJWT = await mintSessionJWT(env.SESSION_JWT_SECRET, orgID, userID, orgPlan, workosSessionID);
// Redirect to dashboard with the cookie set.
const dashURL = `${reqURL.origin}/dashboard`;
@@ -1251,12 +1253,47 @@ async function authCallback(req: Request, env: Env): Promise<Response> {
});
}
-async function authLogout(): Promise<Response> {
- return new Response(null, {
- status: 204,
- headers: {
- "set-cookie": `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`,
- },
+// Decode the WorkOS session id (`sid` claim) from a WorkOS access-token JWT
+// without verifying the signature. The token came straight from WorkOS's token
+// endpoint at callback; we only need the session id to build the hosted logout
+// URL, so an unverified parse is sufficient.
+function workosSessionIdFromAccessToken(accessToken?: string): string | undefined {
+ if (!accessToken) return undefined;
+ const parts = accessToken.split(".");
+ if (parts.length !== 3) return undefined;
+ try {
+ const payload = JSON.parse(atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))) as { sid?: string };
+ return payload.sid;
+ } catch {
+ return undefined;
+ }
+}
+
+async function authLogout(req: Request, env: Env): Promise<Response> {
+ const clearCookie = `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`;
+
+ // Clearing oc_session alone leaves the WorkOS SSO session alive, so the
+ // dashboard's /auth/login would silently re-authenticate the user. Hand back
+ // WorkOS's hosted logout URL (built from the sid captured into the session JWT
+ // at callback) so the browser also tears down the WorkOS session. No
+ // return_to: the post-logout destination is WorkOS dashboard config (Sign-out
+ // redirect), per environment. Old sessions without wsid fall back to a plain
+ // cookie clear; the client then routes to /auth/login.
+ let logoutUrl: string | undefined;
+ const cookie = req.headers.get("cookie") ?? "";
+ const m = cookie.match(new RegExp(`${SESSION_COOKIE}=([^;]+)`));
+ if (m) {
+ const claims = await verifySessionJWT(env.SESSION_JWT_SECRET, m[1]);
+ if (claims?.wsid) {
+ const u = new URL("https://api.workos.com/user_management/sessions/logout");
+ u.searchParams.set("session_id", claims.wsid);
+ logoutUrl = u.toString();
+ }
+ }
+
+ return new Response(JSON.stringify({ message: "logged out", ...(logoutUrl ? { logoutUrl } : {}) }), {
+ status: 200,
+ headers: { "content-type": "application/json", "set-cookie": clearCookie },
});
}
@@ -1335,9 +1372,13 @@ interface SessionClaims {
plan: string;
iat: number;
exp: number;
+ // WorkOS session id (sid). Carried so /auth/logout can build the WorkOS
+ // hosted logout URL and tear down the SSO session, not just our cookie.
+ // Optional: sessions minted before this existed won't have it.
+ wsid?: string;
}
-async function mintSessionJWT(secret: string, orgID: string, userID: string, plan: string): Promise<string> {
+async function mintSessionJWT(secret: string, orgID: string, userID: string, plan: string, wsid?: string): Promise<string> {
const now = Math.floor(Date.now() / 1000);
const header = { alg: "HS256", typ: "JWT" };
const payload = {
@@ -1348,6 +1389,7 @@ async function mintSessionJWT(secret: string, orgID: string, userID: string, pla
org_id: orgID,
user_id: userID,
plan,
+ ...(wsid ? { wsid } : {}),
};
const enc = new TextEncoder();
const signingInput =
@@ -1769,7 +1811,7 @@ export default {
// Auth flow (browser).
if (path === "/auth/login") { if (req.method === "GET") return authLogin(req, env); }
if (path === "/auth/callback") { if (req.method === "GET") return authCallback(req, env); }
- if (path === "/auth/logout") { if (req.method === "POST") return authLogout(); }
+ if (path === "/auth/logout") { if (req.method === "POST") return authLogout(req, env); }
if (path === "/auth/refresh") { if (req.method === "POST") return authRefresh(req, env); }
// Stripe webhook (test mode in app2, live in app).
diff --git a/internal/auth/oauth_handlers.go b/internal/auth/oauth_handlers.go
index 0e05f396..c77d8845 100644
--- a/internal/auth/oauth_handlers.go
+++ b/internal/auth/oauth_handlers.go
@@ -216,10 +216,11 @@ func (h *OAuthHandlers) HandleLogout(c echo.Context) error {
}
// sessionIDFromAccessToken extracts the WorkOS `sid` claim from an access-token
-// JWT without verifying its signature. The token was already validated for this
-// request by the auth middleware; here we only need the session id to build the
-// logout URL, so an unverified parse is sufficient (and avoids needing WorkOS's
-// JWKS at logout time).
+// JWT WITHOUT verifying its signature. Note /auth/logout is a public route (see
+// router.go), so this cookie is not validated by the auth middleware. That's
+// acceptable here: the worst a forged/garbage cookie can do is yield a session
+// id we put in a WorkOS logout URL, which only ends that session — no privilege
+// escalation and no data access. We never trust this value for anything else.
func sessionIDFromAccessToken(token string) string {
claims := jwt.MapClaims{}
if _, _, err := jwt.NewParser().ParseUnverified(token, claims); err != nil {
diff --git a/web/.gitignore b/web/.gitignore
index f06235c4..06e60381 100644
--- a/web/.gitignore
+++ b/web/.gitignore
@@ -1,2 +1,3 @@
node_modules
dist
+*.tsbuildinfo
diff --git a/web/tsconfig.tsbuildinfo b/web/tsconfig.tsbuildinfo
deleted file mode 100644
index b041e74d..00000000
--- a/web/tsconfig.tsbuildinfo
+++ /dev/null
@@ -1 +0,0 @@
-{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/client.ts","./src/components/layout.tsx","./src/components/logspanel.tsx","./src/components/protectedroute.tsx","./src/components/terminal.tsx","./src/hooks/useauth.tsx","./src/pages/apikeys.tsx","./src/pages/agentdetail.tsx","./src/pages/agents.tsx","./src/pages/billing.tsx","./src/pages/checkpoints.tsx","./src/pages/dashboard.tsx","./src/pages/login.tsx","./src/pages/sessiondetail.tsx","./src/pages/sessions.tsx","./src/pages/settings.tsx","./src/pages/templates.tsx"],"version":"5.6.3"}
\ No newline at end of file