fix(login): show account selection after RP-initiated logout (#12638)

**Supersedes #12471** by @conblem — same fix, rebased onto current
`main` with conflicts resolved and review feedback applied. Original
commits are preserved, all credit to @conblem.

Closes #12252

### Problem

After an RP-initiated logout (`end_session` with `id_token_hint`), Login
V2 redirected straight to `/loginname` instead of showing the account
picker like Login V1. The `sessions` cookie still referenced the
previous accounts, but their server-side sessions had been terminated,
so `listSessions` returned nothing and the flow treated the browser as
having no accounts at all.

### Solution

- `handleOIDCFlowInitiation` now checks the `sessions` cookie
(`hasCookieAccount`) when no live session is eligible for the request's
organization. If the cookie still knows an account and the RP passed no
`login_hint`, the user is sent to `/accounts` instead of `/loginname`.
`prompt=none` is excluded since it must never render UI.
- `/accounts` synthesizes an (invalid) `Session` for each cookie entry
that has no live counterpart, so the account is still listed and a click
re-authenticates via `/loginname` → password in one step.
- `clearSession` prunes the cookie entry when the server reports the
session as already gone (`NotFound` / `PermissionDenied`), so stale
cards can be dismissed. Any other error is rethrown so a still-valid
server session is never silently orphaned.
- `getAllSessionCookieIds` is now a thin wrapper over `getAllSessions`;
`FlowInitiationParams.sessionCookies` is typed as `Cookie[]`.
- Tests: new `describe` block covering the cookie fallback, `login_hint`
precedence, `prompt=none`, org-scope matching/mismatch, and
`SELECT_ACCOUNT` / default prompt with live sessions filtered out by
org.
- Also adds `.claude/`, `.cursor/`, `.codex/`, `.windsurf/`,
`.copilot/`, `.aider*` to `.gitignore`.

---------

Co-authored-by: conblem <[email protected]>
This commit is contained in:
Max Peintner
2026-08-27 11:07:30 +00:00
committed by GitHub
co-authored by conblem
parent 6128aeaa89
commit 3c746281f1
25 changed files with 708 additions and 259 deletions
+200 -10
View File
@@ -1,3 +1,4 @@
import type { Cookie } from "@/lib/cookies";
import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { FlowInitiationParams, handleOIDCFlowInitiation } from "./flow-initiation";
@@ -51,6 +52,10 @@ function makeRequest(url = "https://example.com/login?requestId=oidc_abc123"): N
return new NextRequest(url);
}
function makeCookie(id: string, overrides?: Partial<Cookie>): Cookie {
return { id, token: "tok", loginName: "", creationTs: "", expirationTs: "", changeTs: "", ...overrides };
}
function makeBaseParams(overrides?: Partial<FlowInitiationParams>): FlowInitiationParams {
return {
serviceConfig: { baseUrl: "https://api.example.com" } as any,
@@ -243,7 +248,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [otherOrgSession] as any,
sessionCookies: [{ id: "session-other", token: "tok" }],
sessionCookies: [makeCookie("session-other")],
}),
);
@@ -270,7 +275,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [otherOrgSession] as any,
sessionCookies: [{ id: "session-other", token: "tok" }],
sessionCookies: [makeCookie("session-other")],
}),
);
@@ -296,7 +301,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [otherOrgSession] as any,
sessionCookies: [{ id: "session-other", token: "tok" }],
sessionCookies: [makeCookie("session-other")],
}),
);
@@ -321,7 +326,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [orgSession] as any,
sessionCookies: [{ id: "session-org", token: "tok" }],
sessionCookies: [makeCookie("session-org")],
}),
);
@@ -351,7 +356,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [otherOrgSession] as any,
sessionCookies: [{ id: "session-other", token: "tok" }],
sessionCookies: [makeCookie("session-other")],
}),
);
@@ -378,7 +383,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [otherOrgSession] as any,
sessionCookies: [{ id: "session-other", token: "tok" }],
sessionCookies: [makeCookie("session-other")],
}),
);
@@ -405,7 +410,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [otherOrgSession] as any,
sessionCookies: [{ id: "session-other", token: "tok" }],
sessionCookies: [makeCookie("session-other")],
}),
);
@@ -430,7 +435,7 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [orgSession] as any,
sessionCookies: [{ id: "session-org", token: "tok" }],
sessionCookies: [makeCookie("session-org")],
}),
);
@@ -646,6 +651,191 @@ describe("handleOIDCFlowInitiation — org-scoped session filtering", () => {
});
});
describe("handleOIDCFlowInitiation — stale session cookie fallback (#12252)", () => {
let mockGetAuthRequest: ReturnType<typeof vi.fn>;
let mockConstructUrl: ReturnType<typeof vi.fn>;
let mockFindValidSession: ReturnType<typeof vi.fn>;
let mockSendLoginname: ReturnType<typeof vi.fn>;
// Cookie entries left behind after an RP-initiated logout terminated the
// server-side sessions: no live Session objects, but loginName is still known.
const staleOrgCookie = makeCookie("session-stale-org", { loginName: "[email protected]", organization: "111111" });
const staleOtherOrgCookie = makeCookie("session-stale-other", { loginName: "[email protected]", organization: "999999" });
const otherOrgSession = {
id: "session-other",
factors: { user: { id: "user2", organizationId: "999999", loginName: "[email protected]" } },
};
function authRequestWith(overrides: Record<string, unknown>) {
mockGetAuthRequest.mockResolvedValue({
authRequest: {
id: "abc123",
uiLocales: [],
scope: [],
prompt: [],
loginHint: undefined,
...overrides,
},
});
}
beforeEach(async () => {
vi.clearAllMocks();
vi.unstubAllEnvs();
const zitadel = await import("@/lib/zitadel");
const serviceUrl = await import("@/lib/service-url");
const session = await import("@/lib/session");
const authUtils = await import("@/lib/auth-utils");
const loginname = await import("@/lib/server/loginname");
mockGetAuthRequest = vi.mocked(zitadel.getAuthRequest);
mockConstructUrl = vi.mocked(serviceUrl.constructUrl);
mockFindValidSession = vi.mocked(session.findValidSession);
mockSendLoginname = vi.mocked(loginname.sendLoginname);
vi.mocked(zitadel.getLoginSettings).mockResolvedValue(undefined);
vi.mocked(zitadel.getSecuritySettings).mockResolvedValue(undefined);
vi.mocked(authUtils.getValidLocaleFromUILocales).mockReturnValue(null);
mockConstructUrl.mockImplementation((_req: any, path: string) => {
return new URL(`https://example.com${path}`);
});
mockFindValidSession.mockResolvedValue(null);
mockSendLoginname.mockResolvedValue(undefined);
});
afterEach(() => {
vi.unstubAllEnvs();
});
test("should redirect to /accounts when there are no live sessions but the cookie references an account", async () => {
authRequestWith({});
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
const location = res.headers.get("location") ?? "";
expect(location).toContain("/accounts");
expect(location).not.toContain("/loginname");
});
test("should ignore cookie entries without a loginName", async () => {
authRequestWith({});
const res = await handleOIDCFlowInitiation(
makeBaseParams({ sessions: [], sessionCookies: [{ ...staleOrgCookie, loginName: "" }] }),
);
const location = res.headers.get("location") ?? "";
expect(location).toContain("/loginname");
});
test("should prefer login_hint over the cookie fallback when there are no live sessions", async () => {
authRequestWith({ loginHint: "[email protected]" });
mockSendLoginname.mockResolvedValue({ redirect: "/password?requestId=oidc_abc123" });
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
const location = res.headers.get("location") ?? "";
expect(location).toContain("/password");
expect(location).not.toContain("/accounts");
});
test("should not show the account picker for prompt=none even if the cookie references an account", async () => {
const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb");
authRequestWith({ prompt: [Prompt.NONE] });
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
const location = res.headers.get("location") ?? "";
expect(location).not.toContain("/accounts");
});
test("should redirect to /loginname when the cookie account belongs to a different org than the org scope", async () => {
authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"] });
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOtherOrgCookie] }));
const location = res.headers.get("location") ?? "";
expect(location).toContain("/loginname");
expect(location).not.toContain("/accounts");
});
test("should redirect to /accounts when the cookie account matches the org scope", async () => {
authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"] });
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
const location = res.headers.get("location") ?? "";
expect(location).toContain("/accounts");
expect(location).toContain("organization=111111");
});
test("should keep /accounts for SELECT_ACCOUNT when live sessions are filtered out by org but the cookie has a matching account", async () => {
const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb");
authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"], prompt: [Prompt.SELECT_ACCOUNT] });
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [otherOrgSession] as any,
sessionCookies: [{ ...staleOtherOrgCookie, id: "session-other" }, staleOrgCookie],
}),
);
const location = res.headers.get("location") ?? "";
expect(location).toContain("/accounts");
});
test("should not show the account picker for prompt=login even if the cookie references an account", async () => {
const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb");
authRequestWith({ prompt: [Prompt.LOGIN] });
const res = await handleOIDCFlowInitiation(makeBaseParams({ sessions: [], sessionCookies: [staleOrgCookie] }));
const location = res.headers.get("location") ?? "";
expect(location).toContain("/loginname");
expect(location).not.toContain("/accounts");
});
test("should let login_hint win over the cookie fallback for SELECT_ACCOUNT when no live session is eligible", async () => {
const { Prompt } = await import("@zitadel/proto/zitadel/oidc/v2/authorization_pb");
authRequestWith({
scope: ["urn:zitadel:iam:org:id:111111"],
prompt: [Prompt.SELECT_ACCOUNT],
loginHint: "[email protected]",
});
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [otherOrgSession] as any,
sessionCookies: [
makeCookie("session-other", { loginName: "[email protected]", organization: "999999" }),
staleOrgCookie,
],
}),
);
const location = res.headers.get("location") ?? "";
expect(location).toContain("/loginname");
expect(location).toContain("loginName=hinted%40org.com");
expect(location).not.toContain("/accounts");
});
test("should keep /accounts (default prompt) when live sessions are filtered out by org but the cookie has a matching account", async () => {
authRequestWith({ scope: ["urn:zitadel:iam:org:id:111111"] });
const res = await handleOIDCFlowInitiation(
makeBaseParams({
sessions: [otherOrgSession] as any,
sessionCookies: [{ ...staleOtherOrgCookie, id: "session-other" }, staleOrgCookie],
}),
);
const location = res.headers.get("location") ?? "";
expect(location).toContain("/accounts");
});
});
describe("handleOIDCFlowInitiation — Prompt.LOGIN + loginHint requestId prefix", () => {
let mockGetAuthRequest: ReturnType<typeof vi.fn>;
let mockConstructUrl: ReturnType<typeof vi.fn>;
@@ -700,7 +890,7 @@ describe("handleOIDCFlowInitiation — Prompt.LOGIN + loginHint requestId prefix
makeBaseParams({
requestId: "oidc_abc123",
sessions: [existingSession] as any,
sessionCookies: [{ id: "session-1", token: "tok" }],
sessionCookies: [makeCookie("session-1")],
}),
);
@@ -733,7 +923,7 @@ describe("handleOIDCFlowInitiation — Prompt.LOGIN + loginHint requestId prefix
makeBaseParams({
requestId: "oidc_abc123",
sessions: [existingSession] as any,
sessionCookies: [{ id: "session-1", token: "tok" }],
sessionCookies: [makeCookie("session-1")],
}),
);