Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(auth): add user-triggered session revocation (#17255)

Mark Salpeterc12acd3c3ffc
diff --git a/packages/shared/prisma/migrations/20260909171000_add_sessions_expired_at/migration.sql b/packages/shared/prisma/migrations/20260909171000_add_sessions_expired_at/migration.sql
new file mode 100644
index 0000000000..55a1ce9462
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260909171000_add_sessions_expired_at/migration.sql
@@ -0,0 +1 @@
+ALTER TABLE "users" ADD COLUMN "sessions_expired_at" TIMESTAMP(3);
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 3ecdcc3445..3fae3c439b 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -51,6 +51,7 @@ model User {
email String? @unique
emailVerified DateTime? @map("email_verified")
password String?
+ sessionsExpiredAt DateTime? @map("sessions_expired_at")
image String?
admin Boolean @default(false)
v4BetaEnabled Boolean @default(false) @map("v4_beta_enabled")
diff --git a/web/src/__tests__/account-settings-sign-out-all-sessions.clienttest.tsx b/web/src/__tests__/account-settings-sign-out-all-sessions.clienttest.tsx
new file mode 100644
index 0000000000..3504a05445
--- /dev/null
+++ b/web/src/__tests__/account-settings-sign-out-all-sessions.clienttest.tsx
@@ -0,0 +1,158 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const {
+ mutateAsyncMock,
+ signOutCleanlyMock,
+ showSuccessToastMock,
+ showErrorToastMock,
+ reportNonTrpcErrorMock,
+} = vi.hoisted(() => ({
+ mutateAsyncMock: vi.fn(),
+ signOutCleanlyMock: vi.fn(),
+ showSuccessToastMock: vi.fn(),
+ showErrorToastMock: vi.fn(),
+ reportNonTrpcErrorMock: vi.fn(),
+}));
+
+vi.mock("next-auth/react", () => ({
+ useSession: () => ({
+ status: "authenticated",
+ data: {
+ user: {
+ email: "[email protected]",
+ name: "Test User",
+ hasPassword: true,
+ },
+ },
+ }),
+}));
+
+vi.mock("next/router", () => ({
+ useRouter: () => ({
+ query: {},
+ push: vi.fn(),
+ }),
+}));
+
+vi.mock("@/src/components/layouts/container-page", () => ({
+ default: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/src/components/PagedSettingsContainer", () => ({
+ PagedSettingsContainer: ({
+ pages,
+ }: {
+ pages: { content?: React.ReactNode }[];
+ }) => <>{pages[0]?.content}</>,
+}));
+
+vi.mock("@/src/features/auth/lib/signOut", () => ({
+ signOutCleanly: signOutCleanlyMock,
+}));
+
+vi.mock("@/src/features/notifications/showSuccessToast", () => ({
+ showSuccessToast: showSuccessToastMock,
+}));
+
+vi.mock("@/src/features/notifications/showErrorToast", () => ({
+ showErrorToast: showErrorToastMock,
+}));
+
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ useUtils: () => ({ invalidate: vi.fn() }),
+ userAccount: {
+ updateDisplayName: {
+ useMutation: () => ({
+ mutate: vi.fn(),
+ isPending: false,
+ }),
+ },
+ checkCanDelete: {
+ useQuery: () => ({
+ data: { canDelete: false, blockingOrganizations: [] },
+ }),
+ },
+ delete: {
+ useMutation: () => ({
+ mutateAsync: vi.fn(),
+ isPending: false,
+ }),
+ },
+ signOutAllSessions: {
+ useMutation: () => ({
+ mutateAsync: mutateAsyncMock,
+ isPending: false,
+ }),
+ },
+ },
+ },
+ reportNonTrpcError: reportNonTrpcErrorMock,
+}));
+
+vi.mock("@/src/features/v4-migration/useV4UpgradeUiEnabled", () => ({
+ useV4UpgradeUiFlag: () => false,
+}));
+
+import AccountSettingsPage from "@/src/pages/account/settings/index";
+
+describe("SignOutAllSessionsButton", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("keeps durable revocation success when local sign-out fails", async () => {
+ mutateAsyncMock.mockResolvedValue({ success: true });
+ signOutCleanlyMock.mockRejectedValue(
+ new Error("Network error during signOut"),
+ );
+
+ render(<AccountSettingsPage />);
+
+ const buttons = screen.getAllByRole("button", {
+ name: "Sign Out of All Sessions",
+ });
+ fireEvent.click(buttons[0]!);
+ fireEvent.click(
+ screen.getAllByRole("button", { name: "Sign Out of All Sessions" })[1] ??
+ screen.getByRole("button", { name: "Sign Out of All Sessions" }),
+ );
+
+ await waitFor(() => {
+ expect(showSuccessToastMock).toHaveBeenCalledWith({
+ title: "Signed Out of All Sessions",
+ description: "All sessions have been invalidated.",
+ });
+ });
+ expect(showErrorToastMock).not.toHaveBeenCalledWith(
+ "Failed to Sign Out of All Sessions",
+ expect.anything(),
+ );
+ expect(reportNonTrpcErrorMock).toHaveBeenCalled();
+ });
+
+ it("reports mutation failure without attempting local sign-out", async () => {
+ mutateAsyncMock.mockRejectedValue(new Error("UNAUTHORIZED"));
+
+ render(<AccountSettingsPage />);
+
+ const buttons = screen.getAllByRole("button", {
+ name: "Sign Out of All Sessions",
+ });
+ fireEvent.click(buttons[0]!);
+ fireEvent.click(
+ screen.getAllByRole("button", { name: "Sign Out of All Sessions" })[1] ??
+ screen.getByRole("button", { name: "Sign Out of All Sessions" }),
+ );
+
+ await waitFor(() => {
+ expect(showErrorToastMock).toHaveBeenCalledWith(
+ "Failed to Sign Out of All Sessions",
+ "UNAUTHORIZED",
+ );
+ });
+ expect(signOutCleanlyMock).not.toHaveBeenCalled();
+ expect(showSuccessToastMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/__tests__/server/credentials-reset-password.servertest.ts b/web/src/__tests__/server/credentials-reset-password.servertest.ts
index d6447eaf9a..97446d44b2 100644
--- a/web/src/__tests__/server/credentials-reset-password.servertest.ts
+++ b/web/src/__tests__/server/credentials-reset-password.servertest.ts
@@ -34,6 +34,7 @@ describe("credentials.resetPassword", () => {
const { caller, userId, email } = await createPasswordUser();
const token = uniqueOtp();
await insertOtp({ email, token });
+ const beforeReset = new Date();
await caller.credentials.resetPassword({
email,
@@ -42,6 +43,13 @@ describe("credentials.resetPassword", () => {
});
await expectPassword(userId, NEW_PASSWORD);
+ const user = await prisma.user.findUniqueOrThrow({
+ where: { id: userId },
+ select: { sessionsExpiredAt: true },
+ });
+ expect(user.sessionsExpiredAt?.getTime()).toBeGreaterThanOrEqual(
+ beforeReset.getTime(),
+ );
await expect(
caller.credentials.resetPassword({
email,
diff --git a/web/src/__tests__/server/sessionExpiration.servertest.ts b/web/src/__tests__/server/sessionExpiration.servertest.ts
new file mode 100644
index 0000000000..1ee4eb37b1
--- /dev/null
+++ b/web/src/__tests__/server/sessionExpiration.servertest.ts
@@ -0,0 +1,29 @@
+import { randomUUID } from "crypto";
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ advanceSessionsExpiredAtForUser,
+ getSessionLoginAt,
+} from "@/src/features/auth/lib/sessionExpiration";
+import { prisma } from "@langfuse/shared/src/db";
+
+describe("session expiration", () => {
+ const userIds: string[] = [];
+
+ afterEach(async () => {
+ await prisma.user.deleteMany({ where: { id: { in: userIds } } });
+ userIds.length = 0;
+ });
+
+ it("orders a new login strictly after the revocation boundary", async () => {
+ const id = randomUUID();
+ const email = `${id}@example.com`;
+ userIds.push(id);
+ await prisma.user.create({ data: { id, email } });
+
+ const sessionsExpiredAt = await advanceSessionsExpiredAtForUser(id, prisma);
+ const loginAt = await getSessionLoginAt(email, prisma);
+
+ expect(loginAt.getTime()).toBeGreaterThan(sessionsExpiredAt.getTime());
+ });
+});
diff --git a/web/src/__tests__/server/unit/getServerAuthSession-session-revocation.servertest.ts b/web/src/__tests__/server/unit/getServerAuthSession-session-revocation.servertest.ts
new file mode 100644
index 0000000000..6f483c7801
--- /dev/null
+++ b/web/src/__tests__/server/unit/getServerAuthSession-session-revocation.servertest.ts
@@ -0,0 +1,202 @@
+import type { Session } from "next-auth";
+import type { JWT } from "next-auth/jwt";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { mockFindUnique, mockQueryRaw, mockInstrumentAsync } = vi.hoisted(
+ () => ({
+ mockFindUnique: vi.fn(),
+ mockQueryRaw: vi.fn(),
+ mockInstrumentAsync: vi.fn(
+ async (
+ _options: unknown,
+ callback: (span: { setAttribute: ReturnType<typeof vi.fn> }) => unknown,
+ ) => callback({ setAttribute: vi.fn() }),
+ ),
+ }),
+);
+
+vi.mock("@langfuse/shared/src/db", async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ prisma: {
+ user: {
+ findUnique: mockFindUnique,
+ },
+ $queryRaw: mockQueryRaw,
+ },
+}));
+
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ instrumentAsync: mockInstrumentAsync,
+}));
+
+vi.mock("@/src/ee/features/multi-tenant-sso/utils", () => ({
+ findMultiTenantSsoConfig: vi.fn(),
+ getSsoAuthProviderIdForDomain: vi.fn(),
+ loadSsoProviders: vi.fn().mockResolvedValue([]),
+}));
+
+import { getAuthOptions } from "@/src/server/auth";
+
+const loginAt = new Date("2026-09-09T12:00:00.000Z").getTime();
+
+const dbUser = {
+ id: "user-1",
+ name: "Test User",
+ email: "[email protected]",
+ image: null,
+ emailVerified: new Date("2026-01-01T00:00:00.000Z"),
+ password: "hashed-password",
+ createdAt: new Date("2026-01-01T00:00:00.000Z"),
+ featureFlags: [],
+ admin: false,
+ v4BetaEnabled: false,
+ organizationMemberships: [],
+};
+
+const baseSession: Session = {
+ expires: "2026-09-23T12:00:00.000Z",
+ user: {
+ id: "user-1",
+ name: "Test User",
+ email: "[email protected]",
+ canCreateOrganizations: true,
+ organizations: [],
+ featureFlags: {
+ searchBar: false,
+ templateFlag: false,
+ excludeClickhouseRead: false,
+ observationEvals: false,
+ v4BetaToggleVisible: false,
+ experimentsV4Enabled: false,
+ },
+ admin: false,
+ },
+ environment: {
+ enableExperimentalFeatures: false,
+ selfHostedInstancePlan: null,
+ },
+};
+
+async function getCallbacks() {
+ const callbacks = (await getAuthOptions()).callbacks;
+ if (!callbacks?.jwt || !callbacks.session) {
+ throw new Error("Expected jwt and session callbacks");
+ }
+ return {
+ jwt: callbacks.jwt as (params: {
+ token: JWT;
+ user?: { id: string };
+ }) => JWT | Promise<JWT>,
+ session: callbacks.session as (params: {
+ session: Session;
+ token: JWT;
+ }) => Session | Promise<Session>,
+ };
+}
+
+describe("NextAuth JWT session revocation", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockQueryRaw.mockResolvedValue([
+ { loginAt: new Date("2026-09-09T12:00:00.000Z") },
+ ]);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("stamps loginAt from the database clock on initial sign-in and preserves it on refresh", async () => {
+ const { jwt } = await getCallbacks();
+ const dbNow = new Date("2026-09-09T12:00:00.123Z");
+ mockQueryRaw.mockResolvedValueOnce([{ loginAt: dbNow }]);
+
+ const initialToken = await jwt({
+ token: { email: "[email protected]" },
+ user: { id: "user-1" },
+ });
+ expect(initialToken.loginAt).toBe(dbNow.getTime());
+ expect(mockQueryRaw).toHaveBeenCalledTimes(1);
+
+ const refreshedToken = await jwt({
+ token: initialToken,
+ });
+ expect(refreshedToken.loginAt).toBe(dbNow.getTime());
+ expect(mockQueryRaw).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ {
+ name: "denies a token issued before the revocation timestamp",
+ token: { email: "[email protected]", loginAt },
+ sessionsExpiredAt: new Date(loginAt + 1),
+ isAllowed: false,
+ },
+ {
+ name: "allows a user who has never revoked sessions",
+ token: { email: "[email protected]", loginAt },
+ sessionsExpiredAt: null,
+ isAllowed: true,
+ },
+ {
+ name: "denies a token issued at the revocation timestamp",
+ token: { email: "[email protected]", loginAt },
+ sessionsExpiredAt: new Date(loginAt),
+ isAllowed: false,
+ },
+ {
+ name: "allows a token issued strictly after the revocation timestamp",
+ token: { email: "[email protected]", loginAt: loginAt + 1 },
+ sessionsExpiredAt: new Date(loginAt),
+ isAllowed: true,
+ },
+ {
+ name: "denies a legacy token after sessions have been revoked",
+ token: { email: "[email protected]" },
+ sessionsExpiredAt: new Date(loginAt),
+ isAllowed: false,
+ },
+ ])("$name", async ({ token, sessionsExpiredAt, isAllowed }) => {
+ mockFindUnique.mockImplementation(
+ ({
+ where,
+ }: {
+ where: {
+ OR: [
+ { sessionsExpiredAt: null },
+ { sessionsExpiredAt: { lt: Date } },
+ ];
+ };
+ }) => {
+ const tokenLoginAt = where.OR[1].sessionsExpiredAt.lt;
+ return sessionsExpiredAt === null || sessionsExpiredAt < tokenLoginAt
+ ? dbUser
+ : null;
+ },
+ );
+
+ const { session } = await getCallbacks();
+ const result = await session({
+ session: baseSession,
+ token: token as JWT,
+ });
+
+ expect(result.user !== null).toBe(isAllowed);
+ expect(mockFindUnique).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: {
+ email: "[email protected]",
+ OR: [
+ { sessionsExpiredAt: null },
+ {
+ sessionsExpiredAt: {
+ lt: new Date(token.loginAt ?? 0),
+ },
+ },
+ ],
+ },
+ }),
+ );
+ });
+});
diff --git a/web/src/__tests__/server/userAccount.servertest.ts b/web/src/__tests__/server/userAccount.servertest.ts
index d0513106b9..327d6f6f12 100644
--- a/web/src/__tests__/server/userAccount.servertest.ts
+++ b/web/src/__tests__/server/userAccount.servertest.ts
@@ -1,4 +1,5 @@
import type { Session } from "next-auth";
+import type { JWT } from "next-auth/jwt";
import { randomUUID } from "crypto";
import type { Plan } from "@langfuse/shared";
@@ -7,6 +8,8 @@ import { env } from "@/src/env.mjs";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import { getFeaturePreviewOptOutFlag } from "@/src/features/feature-flags/utils";
+import { getSessionLoginAt } from "@/src/features/auth/lib/sessionExpiration";
+import { getAuthOptions } from "@/src/server/auth";
describe("userAccountRouter.setFeaturePreviewEnabled", () => {
const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
@@ -81,6 +84,51 @@ describe("userAccountRouter.setFeaturePreviewEnabled", () => {
});
});
+describe("userAccountRouter.signOutAllSessions", () => {
+ it("advances the user's session revocation timestamp", async () => {
+ const { caller, userId } = await createCaller();
+ const beforeRevocation = new Date();
+
+ await expect(caller.userAccount.signOutAllSessions()).resolves.toEqual({
+ success: true,
+ });
+
+ const user = await prisma.user.findUniqueOrThrow({
+ where: { id: userId },
+ select: { sessionsExpiredAt: true },
+ });
+ expect(user.sessionsExpiredAt?.getTime()).toBeGreaterThanOrEqual(
+ beforeRevocation.getTime(),
+ );
+ });
+
+ it("evicts an older session and admits a later one", async () => {
+ const { caller, email, session } = await createCaller();
+ const revokedLoginAt = (await getSessionLoginAt(email, prisma)).getTime();
+
+ await caller.userAccount.signOutAllSessions();
+
+ const sessionCallback = (await getAuthOptions()).callbacks
+ ?.session as (params: {
+ session: Session;
+ token: JWT;
+ }) => Promise<Session>;
+
+ const revoked = await sessionCallback({
+ session,
+ token: { email, loginAt: revokedLoginAt },
+ });
+ expect(revoked.user).toBeNull();
+
+ const reLoginAt = (await getSessionLoginAt(email, prisma)).getTime();
+ const admitted = await sessionCallback({
+ session,
+ token: { email, loginAt: reLoginAt },
+ });
+ expect(admitted.user).not.toBeNull();
+ });
+});
+
async function createCaller({
plan = "cloud:hobby",
aiFeaturesEnabled = true,
@@ -180,6 +228,8 @@ async function createCaller({
orgId,
projectId,
userId,
+ email: user.email!,
+ session,
caller: appRouter.createCaller({ ...ctx, prisma }),
};
}
diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx
new file mode 100644
index 0000000000..810d6390ad
--- /dev/null
+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx
@@ -0,0 +1,166 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { mutateAsyncMock, signInMock, routerPushMock, useSessionMock } =
+ vi.hoisted(() => ({
+ mutateAsyncMock: vi.fn(),
+ signInMock: vi.fn(),
+ routerPushMock: vi.fn(),
+ useSessionMock: vi.fn(),
+ }));
+
+vi.mock("next-auth/react", () => ({
+ signIn: signInMock,
+ useSession: () => useSessionMock(),
+}));
+
+vi.mock("next/router", () => ({
+ useRouter: () => ({
+ push: routerPushMock,
+ query: {},
+ }),
+}));
+
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ credentials: {
+ resetPassword: {
+ useMutation: () => ({
+ mutateAsync: mutateAsyncMock,
+ isPending: false,
+ }),
+ },
+ },
+ },
+}));
+
+vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
+ usePostHogClientCapture: () => vi.fn(),
+}));
+
+vi.mock("@/src/features/organizations/hooks", () => ({
+ useLangfuseCloudRegion: () => ({
+ isLangfuseCloud: false,
+ region: undefined,
+ }),
+}));
+
+vi.mock(
+ "@/src/features/auth-credentials/components/ResetPasswordButton",
+ () => ({
+ RequestResetPasswordEmailButton: ({
+ onEmailSent,
+ label = "Send email",
+ }: {
+ onEmailSent?: () => void;
+ label?: string;
+ }) => (
+ <button type="button" onClick={() => onEmailSent?.()}>
+ {label}
+ </button>
+ ),
+ }),
+);
+
+import { ResetPasswordPage } from "@/src/features/auth-credentials/components/ResetPasswordPage";
+
+describe("ResetPasswordPage re-authentication", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mutateAsyncMock.mockResolvedValue({ success: true });
+ signInMock.mockResolvedValue({ ok: true });
+ });
+
+ it("re-authenticates after password update while already signed in", async () => {
+ useSessionMock.mockReturnValue({
+ status: "authenticated",
+ data: {
+ user: {
+ email: "[email protected]",
+ hasPassword: true,
+ },
+ },
+ });
+
+ render(
+ <ResetPasswordPage
+ passwordResetAvailable
+ initialEmail="[email protected]"
+ intent="reset"
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Send email" }));
+
+ await waitFor(() => {
+ expect(screen.getByLabelText("Verification code")).toBeTruthy();
+ });
+
+ fireEvent.change(screen.getByLabelText("Verification code"), {
+ target: { value: "123456" },
+ });
+ fireEvent.change(screen.getByLabelText("New Password"), {
+ target: { value: "Newpass1!" },
+ });
+ fireEvent.change(screen.getByLabelText("Confirm New Password"), {
+ target: { value: "Newpass1!" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Update Password" }));
+
+ await waitFor(() => {
+ expect(mutateAsyncMock).toHaveBeenCalledWith({
+ email: "[email protected]",
+ token: "123456",
+ password: "Newpass1!",
+ });
+ });
+ expect(signInMock).toHaveBeenCalledWith("credentials", {
+ email: "[email protected]",
+ password: "Newpass1!",
+ redirect: false,
+ });
+ });
+
+ it("re-authenticates after password setup while already signed in", async () => {
+ useSessionMock.mockReturnValue({
+ status: "authenticated",
+ data: {
+ user: {
+ email: "[email protected]",
+ hasPassword: false,
+ },
+ },
+ });
+
+ render(
+ <ResetPasswordPage
+ passwordResetAvailable
+ initialEmail="[email protected]"
+ intent="setup"
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByLabelText("Verification code")).toBeTruthy();
+ });
+
+ fireEvent.change(screen.getByLabelText("Verification code"), {
+ target: { value: "654321" },
+ });
+ fireEvent.change(screen.getByLabelText("Password"), {
+ target: { value: "Newpass1!" },
+ });
+ fireEvent.change(screen.getByLabelText("Confirm Password"), {
+ target: { value: "Newpass1!" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Set password" }));
+
+ await waitFor(() => {
+ expect(signInMock).toHaveBeenCalledWith("credentials", {
+ email: "[email protected]",
+ password: "Newpass1!",
+ redirect: false,
+ });
+ });
+ });
+});
diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
index 08a31f0822..0247cfd30a 100644
--- a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
@@ -114,15 +114,15 @@ export function ResetPasswordPage({
let target =
isSetMode && isLangfuseCloud && region !== "DEV" ? "/onboarding" : "/";
- if (session.status !== "authenticated") {
- const signInResult = await signIn("credentials", {
- email: effectiveEmail,
- password: values.password,
- redirect: false,
- });
- if (!signInResult?.ok) {
- target = "/auth/sign-in";
- }
+ // A password update revokes every existing JWT, including this
+ // browser's, so the current session always has to be re-established.
+ const signInResult = await signIn("credentials", {
+ email: effectiveEmail,
+ password: values.password,
+ redirect: false,
+ });
+ if (!signInResult?.ok) {
+ target = "/auth/sign-in";
}
setIsSuccess(true);
diff --git a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
index 50dc949b73..7ca39c709e 100644
--- a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
+++ b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
@@ -1,5 +1,6 @@
import { createHash } from "crypto";
import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/createProjectMembershipsOnSignup";
+import { advanceSessionsExpiredAtForEmail } from "@/src/features/auth/lib/sessionExpiration";
import type { AdClickIds } from "@/src/features/auth";
import { env } from "@/src/env.mjs";
import { prisma } from "@langfuse/shared/src/db";
@@ -113,6 +114,10 @@ export async function consumeEmailOtpAndUpdatePassword({
},
});
+ if (updated.count === 1) {
+ await advanceSessionsExpiredAtForEmail(identifier, tx);
+ }
+
return updated.count === 1;
});
diff --git a/web/src/features/auth/lib/sessionExpiration.ts b/web/src/features/auth/lib/sessionExpiration.ts
new file mode 100644
index 0000000000..49c63aca88
--- /dev/null
+++ b/web/src/features/auth/lib/sessionExpiration.ts
@@ -0,0 +1,64 @@
+import { prisma } from "@langfuse/shared/src/db";
+
+type PrismaQueryable = {
+ $queryRaw: (typeof prisma)["$queryRaw"];
+};
+
+/**
+ * Login and revocation timestamps are both read from the Postgres clock so
+ * they share one authoritative timeline across web replicas. A login is
+ * ordered strictly after any existing revocation boundary, which
+ * `sessions_expired_at` stores at millisecond precision.
+ */
+export async function getSessionLoginAt(
+ email: string,
+ db: PrismaQueryable = prisma,
+): Promise<Date> {
+ const [row] = await db.$queryRaw<{ loginAt: Date }[]>`
+ SELECT GREATEST(
+ timezone('UTC', clock_timestamp()),
+ COALESCE(
+ "sessions_expired_at" + INTERVAL '1 millisecond',
+ '-infinity'::timestamp
+ )
+ ) AS "loginAt"
+ FROM "users"
+ WHERE "email" = ${email.toLowerCase()}
+ `;
+ if (!row?.loginAt) {
+ throw new Error("Failed to read database login timestamp");
+ }
+ return row.loginAt;
+}
+
+export async function advanceSessionsExpiredAtForUser(
+ userId: string,
+ db: PrismaQueryable = prisma,
+): Promise<Date> {
+ const [row] = await db.$queryRaw<{ sessionsExpiredAt: Date }[]>`
+ UPDATE "users"
+ SET "sessions_expired_at" = timezone('UTC', clock_timestamp())
+ WHERE "id" = ${userId}
+ RETURNING "sessions_expired_at" AS "sessionsExpiredAt"
+ `;
+ if (!row?.sessionsExpiredAt) {
+ throw new Error("Failed to advance session revocation timestamp");
+ }
+ return row.sessionsExpiredAt;
+}
+
+export async function advanceSessionsExpiredAtForEmail(
+ email: string,
+ db: PrismaQueryable = prisma,
+): Promise<Date> {
+ const [row] = await db.$queryRaw<{ sessionsExpiredAt: Date }[]>`
+ UPDATE "users"
+ SET "sessions_expired_at" = timezone('UTC', clock_timestamp())
+ WHERE "email" = ${email.toLowerCase()}
+ RETURNING "sessions_expired_at" AS "sessionsExpiredAt"
+ `;
+ if (!row?.sessionsExpiredAt) {
+ throw new Error("Failed to advance session revocation timestamp");
+ }
+ return row.sessionsExpiredAt;
+}
diff --git a/web/src/pages/account/settings/index.tsx b/web/src/pages/account/settings/index.tsx
index 4235bca5c9..7ddf6b415a 100644
--- a/web/src/pages/account/settings/index.tsx
+++ b/web/src/pages/account/settings/index.tsx
@@ -240,6 +240,67 @@ function DeleteAccountButton() {
);
}
+function SignOutAllSessionsButton() {
+ const signOutAllSessions = api.userAccount.signOutAllSessions.useMutation();
+
+ const onConfirm = async () => {
+ try {
+ await signOutAllSessions.mutateAsync();
+ showSuccessToast({
+ title: "Signed Out of All Sessions",
+ description: "All sessions have been invalidated.",
+ });
+ } catch (error) {
+ reportNonTrpcError(error, "account");
+ showErrorToast(
+ "Failed to Sign Out of All Sessions",
+ error instanceof Error ? error.message : "An unexpected error occurred",
+ );
+ return;
+ }
+
+ // Sessions are already revoked server-side at this point, so a failure to
+ // clear local state must not be reported as a failed revocation.
+ try {
+ await signOutCleanly();
+ } catch (error) {
+ reportNonTrpcError(error, "account");
+ }
+ };
+
+ return (
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button variant="destructive-secondary">
+ Sign Out of All Sessions
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle className="text-lg font-bold">
+ Sign Out of All Sessions
+ </DialogTitle>
+ <DialogDescription>
+ This will sign you out on this device and every other device where
+ you are currently signed in. You will need to sign in again.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="destructive"
+ loading={signOutAllSessions.isPending}
+ onClick={onConfirm}
+ className="w-full"
+ >
+ Sign Out of All Sessions
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
type AccountSettingsPage = {
title: string;
slug: string;
@@ -301,6 +362,12 @@ const getAccountSettingsPages = ({
</div>
<SettingsDangerZone
items={[
+ {
+ title: "Sign out of all sessions",
+ description:
+ "Invalidate every active session for your account, including this device. You will need to sign in again.",
+ button: <SignOutAllSessionsButton />,
+ },
{
title: "Delete your account",
description:
diff --git a/web/src/server/api/routers/userAccount.ts b/web/src/server/api/routers/userAccount.ts
index 1cdc208024..943a0f341b 100644
--- a/web/src/server/api/routers/userAccount.ts
+++ b/web/src/server/api/routers/userAccount.ts
@@ -12,6 +12,7 @@ import { env } from "@/src/env.mjs";
import { getSfdcService } from "@/src/ee/features/sfdc-sync/server";
import { featurePreviewFlags } from "@/src/features/feature-flags/available-flags";
import { setUserFeaturePreview } from "@/src/features/feature-flags/server/organizationFeatureFlags";
+import { advanceSessionsExpiredAtForUser } from "@/src/features/auth/lib/sessionExpiration";
const updateDisplayNameSchema = z.object({
name: StringNoHTML.min(1, "Name cannot be empty").max(
@@ -98,6 +99,12 @@ export const userAccountRouter = createTRPCRouter({
};
}),
+ signOutAllSessions: authenticatedProcedure.mutation(async ({ ctx }) => {
+ await advanceSessionsExpiredAtForUser(ctx.session.user.id, ctx.prisma);
+
+ return { success: true };
+ }),
+
setFeaturePreviewEnabled: authenticatedProcedure
.input(
z.object({
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index dbd89586de..801498fc63 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -17,6 +17,7 @@ import {
} from "@/src/features/feature-flags/utils";
import { env } from "@/src/env.mjs";
import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/createProjectMembershipsOnSignup";
+import { getSessionLoginAt } from "@/src/features/auth/lib/sessionExpiration";
import { type AdClickIds } from "@/src/features/auth/lib/signupAttribution";
import {
type AdapterUser,
@@ -750,11 +751,28 @@ export async function getAuthOptions(signupAttribution?: {
}
return baseUrl;
},
+ async jwt({ token, user }) {
+ if (user) {
+ const loginAt = await getSessionLoginAt(token.email!);
+ token.loginAt = loginAt.getTime();
+ }
+ return token;
+ },
async session({ session, token }): Promise<Session> {
return instrumentAsync({ name: "next-auth-session" }, async (span) => {
const dbUser = await prisma.user.findUnique({
where: {
email: token.email!.toLowerCase(),
+ OR: [
+ { sessionsExpiredAt: null },
+ {
+ // Strict: a token issued in the same millisecond as revocation
+ // is treated as revoked.
+ sessionsExpiredAt: {
+ lt: new Date(token.loginAt ?? 0),
+ },
+ },
+ ],
},
select: {
id: true,
diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.ts
index 78c950a78a..604529573e 100644
--- a/web/types/next-auth.d.ts
+++ b/web/types/next-auth.d.ts
@@ -92,5 +92,6 @@ declare module "next-auth/jwt" {
name?: string | null;
email?: string | null;
image?: string | null;
+ loginAt?: number;
}
}