Skip to content

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

50.2 KB
Raw Blame
/* eslint-disable no-nested-ternary, @typescript-eslint/no-use-before-define */
import { type GetServerSidePropsContext } from "next";
import { isTopicsProjectEnabled } from "@langfuse/shared/topics/server";
import {
  getServerSession,
  type NextAuthOptions,
  type Session,
} from "next-auth";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "@langfuse/shared/src/db";
import { isInAppAgentInstanceEnabled } from "@langfuse/shared/in-app-agent/server/modelProvider";
import {
  hashPassword,
  passwordRequiresReset,
  verifyPassword,
} from "@/src/features/auth-credentials/lib/passwordHash";
import {
  parseFlags,
  parseFlagsWithOrganizationDefaults,
} from "@/src/features/feature-flags/server/parseFlags";
import {
  isGatewayDeployedOnInstance,
  isGatewayEnabledForOrganization,
} from "@/src/features/ai-gateway/server/availability";
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,
  type Adapter,
  type AdapterAccount,
} from "next-auth/adapters";

// Providers
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider, { type GoogleProfile } from "next-auth/providers/google";
import GitHubProvider from "next-auth/providers/github";
import GitLabProvider from "next-auth/providers/gitlab";
import OktaProvider from "next-auth/providers/okta";
import AuthentikProvider from "next-auth/providers/authentik";
import OneLoginProvider from "next-auth/providers/onelogin";
import EmailProvider from "next-auth/providers/email";
import { randomInt } from "crypto";
import Auth0Provider from "next-auth/providers/auth0";
import CognitoProvider from "next-auth/providers/cognito";
import AzureADProvider from "next-auth/providers/azure-ad";
import KeycloakProvider from "next-auth/providers/keycloak";
import WorkOSProvider from "next-auth/providers/workos";
import WordPressProvider from "next-auth/providers/wordpress";
import { type Provider } from "next-auth/providers/index";
import { getCookieName, getCookieOptions } from "./utils/cookies";
import { nextAuthLogger } from "./utils/nextAuthLogger";
import {
  getRequestCookies,
  isValidCallbackUrl,
} from "./utils/nextAuthCallbackUrl";
import {
  findMultiTenantSsoConfig,
  getSsoAuthProviderIdForDomain,
  loadSsoProviders,
} from "@/src/ee/features/multi-tenant-sso/utils";
import { getSupportAccessMemberships } from "@/src/ee/features/support-access/server/supportAccess";
import {
  ENTERPRISE_SSO_REQUIRED_MESSAGE,
  MULTI_TENANT_SSO_DOMAIN_MISMATCH_MESSAGE,
  PASSWORD_RESET_REQUIRED_MESSAGE,
  TURNSTILE_ACTIONS,
  TURNSTILE_FAILED_MESSAGE,
} from "@/src/features/auth/constants";
import {
  getTurnstileRemoteIp,
  verifyTurnstileToken,
} from "@/src/features/auth/server/verifyTurnstile";
import { z } from "zod";
import { CloudConfigSchema, projectRoleAccessRights } from "@langfuse/shared";
import {
  CustomSSOProvider,
  GitHubEnterpriseProvider,
  JumpCloudProvider,
  traceException,
  sendResetPasswordVerificationRequest,
  instrumentAsync,
  logger,
  resolveProjectRole,
  isLangfuseAITracingConfigured,
  shouldSkipScoresDedup,
} from "@langfuse/shared/src/server";
import {
  getOrganizationPlanServerSide,
  getSelfHostedInstancePlanServerSide,
} from "@/src/features/entitlements/server/getPlan";
import { getSSOBlockedDomains } from "@/src/features/auth-credentials/server/signupApiHandler";
import { createSupportEmailHash } from "@/src/features/support-chat/createSupportEmailHash";
import {
  canToggleV4,
  isV4UpgradeUiAvailable,
} from "@/src/features/events/lib/v4Rollout";
import { canCreateOrganizations } from "@/src/features/organizations/server/canCreateOrganizations";
import { isSignupOnboardingEnabled } from "@/src/features/onboarding/server/onboardingService";

const staticProviders: Provider[] = [
  CredentialsProvider({
    name: "credentials",
    credentials: {
      email: {
        label: "Email",
        type: "email",
        placeholder: "[email protected]",
      },
      password: { label: "Password", type: "password" },
      turnstileToken: { label: "Turnstile token", type: "text" },
    },
    async authorize(credentials, req) {
      if (!credentials) throw new Error("No credentials");
      if (env.AUTH_DISABLE_USERNAME_PASSWORD === "true")
        throw new Error(
          "Sign in with email and password is disabled for this instance. Please use SSO.",
        );

      const turnstileValid = await verifyTurnstileToken({
        token: credentials.turnstileToken,
        action: TURNSTILE_ACTIONS.login,
        remoteIp: getTurnstileRemoteIp(req.headers),
      });
      if (!turnstileValid) throw new Error(TURNSTILE_FAILED_MESSAGE);

      const blockedDomains = getSSOBlockedDomains();
      const domain = credentials.email.split("@")[1]?.toLowerCase();
      if (domain && blockedDomains.includes(domain)) {
        throw new Error(
          "Sign in with email and password is disabled for this domain. Please use SSO.",
        );
      }

      // EE: Check custom SSO enforcement
      const multiTenantSsoProvider =
        await getSsoAuthProviderIdForDomain(domain);
      if (multiTenantSsoProvider) {
        throw new Error(ENTERPRISE_SSO_REQUIRED_MESSAGE);
      }

      const dbUser = await prisma.user.findUnique({
        where: {
          email: credentials.email.toLowerCase(),
        },
      });

      if (!dbUser) {
        // Keep hashing work comparable across failed login paths to reduce timing-based user enumeration.
        await hashPassword(credentials.password);
        throw new Error("Invalid credentials");
      }

      if (dbUser.password === null) {
        throw new Error(
          "Please sign in with the identity provider (e.g. Google, GitHub, Azure AD, etc.) that is linked to your account.",
        );
      }

      if (passwordRequiresReset(dbUser.password)) {
        throw new Error(PASSWORD_RESET_REQUIRED_MESSAGE);
      }

      const isValidPassword = await verifyPassword(
        credentials.password,
        dbUser.password,
      );
      if (!isValidPassword) throw new Error("Invalid credentials");

      const userObj = {
        id: dbUser.id,
        name: dbUser.name,
        email: dbUser.email,
        image: dbUser.image,
        emailVerified: dbUser.emailVerified?.toISOString(),
        featureFlags: parseFlags(dbUser.featureFlags, {
          email: dbUser.email,
          // The full session callback resolves deployment and rollout
          // availability before applying employee defaults.
          v4BetaEnabled: false,
        }),
        canCreateOrganizations: canCreateOrganizations(dbUser.email),
        organizations: [],
      };

      return userObj;
    },
  }),
];

// Password-reset for password reset of credentials provider
if (env.SMTP_CONNECTION_URL && env.EMAIL_FROM_ADDRESS) {
  staticProviders.push(
    EmailProvider({
      // SMTP vs SES dispatch happens inside sendVerificationRequest via
      // createMailTransport; NextAuth itself only forwards this string.
      server: env.SMTP_CONNECTION_URL,
      from: env.EMAIL_FROM_ADDRESS,
      maxAge: 3 * 60, // 3 minutes
      async generateVerificationToken() {
        return randomInt(100000, 1000000).toString();
      },
      sendVerificationRequest: sendResetPasswordVerificationRequest,
    }),
  );
}

if (
  env.AUTH_CUSTOM_CLIENT_ID &&
  env.AUTH_CUSTOM_CLIENT_SECRET &&
  env.AUTH_CUSTOM_ISSUER &&
  env.AUTH_CUSTOM_NAME // name required by front-end, ignored here
)
  staticProviders.push(
    CustomSSOProvider({
      clientId: env.AUTH_CUSTOM_CLIENT_ID,
      clientSecret: env.AUTH_CUSTOM_CLIENT_SECRET,
      issuer: env.AUTH_CUSTOM_ISSUER,
      idToken: env.AUTH_CUSTOM_ID_TOKEN === "true",
      fetchUserInfo: env.AUTH_CUSTOM_FETCH_USERINFO === "true",
      allowDangerousEmailAccountLinking:
        env.AUTH_CUSTOM_ALLOW_ACCOUNT_LINKING === "true",
      authorization: {
        params: { scope: env.AUTH_CUSTOM_SCOPE ?? "openid email profile" },
      },
      client: {
        token_endpoint_auth_method: env.AUTH_CUSTOM_CLIENT_AUTH_METHOD,
        ...(env.AUTH_CUSTOM_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_CUSTOM_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_CUSTOM_CHECKS ? { checks: env.AUTH_CUSTOM_CHECKS } : {}),
    }),
  );

if (env.AUTH_GOOGLE_CLIENT_ID && env.AUTH_GOOGLE_CLIENT_SECRET)
  staticProviders.push(
    GoogleProvider({
      clientId: env.AUTH_GOOGLE_CLIENT_ID,
      clientSecret: env.AUTH_GOOGLE_CLIENT_SECRET,
      allowDangerousEmailAccountLinking:
        env.AUTH_GOOGLE_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method: env.AUTH_GOOGLE_CLIENT_AUTH_METHOD,
        ...(env.AUTH_GOOGLE_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_GOOGLE_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_GOOGLE_CHECKS ? { checks: env.AUTH_GOOGLE_CHECKS } : {}),
    }),
  );

if (
  env.AUTH_OKTA_CLIENT_ID &&
  env.AUTH_OKTA_CLIENT_SECRET &&
  env.AUTH_OKTA_ISSUER
)
  staticProviders.push(
    OktaProvider({
      clientId: env.AUTH_OKTA_CLIENT_ID,
      clientSecret: env.AUTH_OKTA_CLIENT_SECRET,
      issuer: env.AUTH_OKTA_ISSUER,
      allowDangerousEmailAccountLinking:
        env.AUTH_OKTA_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method: env.AUTH_OKTA_CLIENT_AUTH_METHOD,
        ...(env.AUTH_OKTA_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_OKTA_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_OKTA_CHECKS ? { checks: env.AUTH_OKTA_CHECKS } : {}),
    }),
  );

if (
  env.AUTH_AUTHENTIK_CLIENT_ID &&
  env.AUTH_AUTHENTIK_CLIENT_SECRET &&
  env.AUTH_AUTHENTIK_ISSUER
) {
  const authentikProvider = AuthentikProvider({
    clientId: env.AUTH_AUTHENTIK_CLIENT_ID,
    clientSecret: env.AUTH_AUTHENTIK_CLIENT_SECRET,
    issuer: env.AUTH_AUTHENTIK_ISSUER,
    allowDangerousEmailAccountLinking:
      env.AUTH_AUTHENTIK_ALLOW_ACCOUNT_LINKING === "true",
    client: {
      token_endpoint_auth_method: env.AUTH_AUTHENTIK_CLIENT_AUTH_METHOD,
      ...(env.AUTH_AUTHENTIK_ID_TOKEN_SIGNED_RESPONSE_ALG
        ? {
            id_token_signed_response_alg:
              env.AUTH_AUTHENTIK_ID_TOKEN_SIGNED_RESPONSE_ALG,
          }
        : {}),
    },
    ...(env.AUTH_AUTHENTIK_CHECKS ? { checks: env.AUTH_AUTHENTIK_CHECKS } : {}),
  });

  if (env.AUTH_AUTHENTIK_AUTHORIZATION_URL) {
    // For reverse proxy setups where authentik's external URL differs from
    // the internal issuer, well-known discovery can't be used. We disable it
    // and derive token/userinfo/JWKS endpoints from the issuer, assuming
    // authentik's standard URL layout: <host>/application/o/<slug>.
    const authentikIssuer = env.AUTH_AUTHENTIK_ISSUER.replace(/\/$/, "");
    const authentikBase = authentikIssuer.replace(
      /\/application\/o\/[^/]+$/,
      "/application/o/",
    );
    const authentikJwksUrl = `${authentikIssuer}/jwks/`;

    authentikProvider.wellKnown = undefined;
    authentikProvider.authorization = {
      url: env.AUTH_AUTHENTIK_AUTHORIZATION_URL,
      params: { scope: "openid email profile" },
    };
    authentikProvider.token = {
      url: `${authentikBase}token/`,
    };
    authentikProvider.userinfo = {
      url: `${authentikBase}userinfo/`,
    };
    authentikProvider.jwks_endpoint = authentikJwksUrl;
  }

  staticProviders.push(authentikProvider);
}

if (
  env.AUTH_ONELOGIN_CLIENT_ID &&
  env.AUTH_ONELOGIN_CLIENT_SECRET &&
  env.AUTH_ONELOGIN_ISSUER
)
  staticProviders.push(
    OneLoginProvider({
      clientId: env.AUTH_ONELOGIN_CLIENT_ID,
      clientSecret: env.AUTH_ONELOGIN_CLIENT_SECRET,
      issuer: env.AUTH_ONELOGIN_ISSUER,
      allowDangerousEmailAccountLinking:
        env.AUTH_ONELOGIN_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method: env.AUTH_ONELOGIN_CLIENT_AUTH_METHOD,
        ...(env.AUTH_ONELOGIN_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_ONELOGIN_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_ONELOGIN_CHECKS ? { checks: env.AUTH_ONELOGIN_CHECKS } : {}),
    }),
  );

if (
  env.AUTH_AUTH0_CLIENT_ID &&
  env.AUTH_AUTH0_CLIENT_SECRET &&
  env.AUTH_AUTH0_ISSUER
)
  staticProviders.push(
    Auth0Provider({
      clientId: env.AUTH_AUTH0_CLIENT_ID,
      clientSecret: env.AUTH_AUTH0_CLIENT_SECRET,
      issuer: env.AUTH_AUTH0_ISSUER,
      allowDangerousEmailAccountLinking:
        env.AUTH_AUTH0_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method: env.AUTH_AUTH0_CLIENT_AUTH_METHOD,
        ...(env.AUTH_AUTH0_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_AUTH0_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_AUTH0_CHECKS ? { checks: env.AUTH_AUTH0_CHECKS } : {}),
    }),
  );

// Langfuse Cloud only: "Sign in with ClickHouse Cloud"
// Uses Auth0Provider with a custom provider ID so the callback URL becomes
// /api/auth/callback/clickhouse-cloud. NOT intended for self-hosted Langfuse.
if (
  env.AUTH_CLICKHOUSE_CLOUD_CLIENT_ID &&
  env.AUTH_CLICKHOUSE_CLOUD_CLIENT_SECRET &&
  env.AUTH_CLICKHOUSE_CLOUD_ISSUER &&
  env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
)
  staticProviders.push(
    Auth0Provider({
      id: "clickhouse-cloud",
      name: "ClickHouse Cloud",
      clientId: env.AUTH_CLICKHOUSE_CLOUD_CLIENT_ID,
      clientSecret: env.AUTH_CLICKHOUSE_CLOUD_CLIENT_SECRET,
      issuer: env.AUTH_CLICKHOUSE_CLOUD_ISSUER,
      authorization: {
        params: {
          scope: "openid email profile",
          // audience: "langfuse",
        },
      },
      allowDangerousEmailAccountLinking:
        env.AUTH_CLICKHOUSE_CLOUD_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method:
          env.AUTH_CLICKHOUSE_CLOUD_CLIENT_AUTH_METHOD,
        ...(env.AUTH_CLICKHOUSE_CLOUD_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_CLICKHOUSE_CLOUD_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_CLICKHOUSE_CLOUD_CHECKS
        ? { checks: env.AUTH_CLICKHOUSE_CLOUD_CHECKS }
        : {}),
    }),
  );

if (env.AUTH_GITHUB_CLIENT_ID && env.AUTH_GITHUB_CLIENT_SECRET)
  staticProviders.push(
    GitHubProvider({
      clientId: env.AUTH_GITHUB_CLIENT_ID,
      clientSecret: env.AUTH_GITHUB_CLIENT_SECRET,
      // Required for RFC 9207: GitHub now sends iss in OAuth callbacks
      // TODO perhaps add "https://github.com/login/oauth/.well-known/openid-configuration"
      // when github starts providing userinfo
      issuer: "https://github.com/login/oauth",
      allowDangerousEmailAccountLinking:
        env.AUTH_GITHUB_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method: env.AUTH_GITHUB_CLIENT_AUTH_METHOD,
      },
      ...(env.AUTH_GITHUB_CHECKS ? { checks: env.AUTH_GITHUB_CHECKS } : {}),
    }),
  );

if (
  env.AUTH_GITHUB_ENTERPRISE_CLIENT_ID &&
  env.AUTH_GITHUB_ENTERPRISE_CLIENT_SECRET &&
  env.AUTH_GITHUB_ENTERPRISE_BASE_URL
) {
  staticProviders.push(
    GitHubEnterpriseProvider({
      clientId: env.AUTH_GITHUB_ENTERPRISE_CLIENT_ID,
      clientSecret: env.AUTH_GITHUB_ENTERPRISE_CLIENT_SECRET,
      enterprise: { baseUrl: env.AUTH_GITHUB_ENTERPRISE_BASE_URL },
      issuer: new URL("/login/oauth", env.AUTH_GITHUB_ENTERPRISE_BASE_URL).href,
      allowDangerousEmailAccountLinking:
        env.AUTH_GITHUB_ENTERPRISE_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method:
          env.AUTH_GITHUB_ENTERPRISE_CLIENT_AUTH_METHOD,
      },
      ...(env.AUTH_GITHUB_ENTERPRISE_CHECKS
        ? { checks: env.AUTH_GITHUB_ENTERPRISE_CHECKS }
        : {}),
    }),
  );
}

if (env.AUTH_GITLAB_CLIENT_ID && env.AUTH_GITLAB_CLIENT_SECRET)
  staticProviders.push(
    GitLabProvider({
      clientId: env.AUTH_GITLAB_CLIENT_ID,
      clientSecret: env.AUTH_GITLAB_CLIENT_SECRET,
      allowDangerousEmailAccountLinking:
        env.AUTH_GITLAB_ALLOW_ACCOUNT_LINKING === "true",
      issuer: env.AUTH_GITLAB_ISSUER,
      client: {
        token_endpoint_auth_method: env.AUTH_GITLAB_CLIENT_AUTH_METHOD,
        ...(env.AUTH_GITLAB_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_GITLAB_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      authorization: {
        url: `${env.AUTH_GITLAB_URL}/oauth/authorize`,
        params: { scope: "read_user" },
      },
      token: `${env.AUTH_GITLAB_URL}/oauth/token`,
      userinfo: `${env.AUTH_GITLAB_URL}/api/v4/user`,
      ...(env.AUTH_GITLAB_CHECKS ? { checks: env.AUTH_GITLAB_CHECKS } : {}),
    }),
  );

if (
  env.AUTH_AZURE_AD_CLIENT_ID &&
  env.AUTH_AZURE_AD_CLIENT_SECRET &&
  env.AUTH_AZURE_AD_TENANT_ID
)
  staticProviders.push(
    AzureADProvider({
      clientId: env.AUTH_AZURE_AD_CLIENT_ID,
      clientSecret: env.AUTH_AZURE_AD_CLIENT_SECRET,
      tenantId: env.AUTH_AZURE_AD_TENANT_ID,
      allowDangerousEmailAccountLinking:
        env.AUTH_AZURE_AD_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method: env.AUTH_AZURE_AD_CLIENT_AUTH_METHOD,
        ...(env.AUTH_AZURE_AD_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_AZURE_AD_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_AZURE_AD_CHECKS ? { checks: env.AUTH_AZURE_AD_CHECKS } : {}),
    }),
  );

if (
  env.AUTH_COGNITO_CLIENT_ID &&
  env.AUTH_COGNITO_CLIENT_SECRET &&
  env.AUTH_COGNITO_ISSUER
)
  staticProviders.push(
    CognitoProvider({
      clientId: env.AUTH_COGNITO_CLIENT_ID,
      clientSecret: env.AUTH_COGNITO_CLIENT_SECRET,
      issuer: env.AUTH_COGNITO_ISSUER,
      allowDangerousEmailAccountLinking:
        env.AUTH_COGNITO_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method: env.AUTH_COGNITO_CLIENT_AUTH_METHOD,
        ...(env.AUTH_COGNITO_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_COGNITO_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_COGNITO_CHECKS
        ? { checks: env.AUTH_COGNITO_CHECKS }
        : { checks: "nonce" }),
    }),
  );

if (
  env.AUTH_KEYCLOAK_CLIENT_ID &&
  env.AUTH_KEYCLOAK_CLIENT_SECRET &&
  env.AUTH_KEYCLOAK_ISSUER
)
  staticProviders.push(
    KeycloakProvider({
      clientId: env.AUTH_KEYCLOAK_CLIENT_ID,
      clientSecret: env.AUTH_KEYCLOAK_CLIENT_SECRET,
      issuer: env.AUTH_KEYCLOAK_ISSUER,
      idToken: env.AUTH_KEYCLOAK_ID_TOKEN === "true",
      allowDangerousEmailAccountLinking:
        env.AUTH_KEYCLOAK_ALLOW_ACCOUNT_LINKING === "true",
      authorization: {
        params: { scope: env.AUTH_KEYCLOAK_SCOPE ?? "openid email profile" },
      },
      client: {
        token_endpoint_auth_method: env.AUTH_KEYCLOAK_CLIENT_AUTH_METHOD,
        ...(env.AUTH_KEYCLOAK_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_KEYCLOAK_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_KEYCLOAK_CHECKS ? { checks: env.AUTH_KEYCLOAK_CHECKS } : {}),
    }),
  );

if (
  env.AUTH_JUMPCLOUD_CLIENT_ID &&
  env.AUTH_JUMPCLOUD_CLIENT_SECRET &&
  env.AUTH_JUMPCLOUD_ISSUER
)
  staticProviders.push(
    JumpCloudProvider({
      clientId: env.AUTH_JUMPCLOUD_CLIENT_ID,
      clientSecret: env.AUTH_JUMPCLOUD_CLIENT_SECRET,
      issuer: env.AUTH_JUMPCLOUD_ISSUER,
      allowDangerousEmailAccountLinking:
        env.AUTH_JUMPCLOUD_ALLOW_ACCOUNT_LINKING === "true",
      authorization: {
        params: { scope: env.AUTH_JUMPCLOUD_SCOPE ?? "openid profile email" },
      },
      client: {
        token_endpoint_auth_method: env.AUTH_JUMPCLOUD_CLIENT_AUTH_METHOD,
        ...(env.AUTH_JUMPCLOUD_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_JUMPCLOUD_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_JUMPCLOUD_CHECKS
        ? { checks: env.AUTH_JUMPCLOUD_CHECKS }
        : {}),
    }),
  );

if (env.AUTH_WORKOS_CLIENT_ID && env.AUTH_WORKOS_CLIENT_SECRET)
  staticProviders.push(
    WorkOSProvider({
      clientId: env.AUTH_WORKOS_CLIENT_ID,
      clientSecret: env.AUTH_WORKOS_CLIENT_SECRET,
      allowDangerousEmailAccountLinking:
        env.AUTH_WORKOS_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method: "client_secret_post",
      },
    }),
  );

if (env.AUTH_WORDPRESS_CLIENT_ID && env.AUTH_WORDPRESS_CLIENT_SECRET)
  staticProviders.push(
    WordPressProvider({
      clientId: env.AUTH_WORDPRESS_CLIENT_ID,
      clientSecret: env.AUTH_WORDPRESS_CLIENT_SECRET,
      allowDangerousEmailAccountLinking:
        env.AUTH_WORDPRESS_ALLOW_ACCOUNT_LINKING === "true",
      client: {
        token_endpoint_auth_method: env.AUTH_WORDPRESS_CLIENT_AUTH_METHOD,
        ...(env.AUTH_WORDPRESS_ID_TOKEN_SIGNED_RESPONSE_ALG
          ? {
              id_token_signed_response_alg:
                env.AUTH_WORDPRESS_ID_TOKEN_SIGNED_RESPONSE_ALG,
            }
          : {}),
      },
      ...(env.AUTH_WORDPRESS_CHECKS
        ? { checks: env.AUTH_WORDPRESS_CHECKS }
        : {}),
    }),
  );

// Extend Prisma Adapter
const prismaAdapter = PrismaAdapter(prisma);
const ignoredAccountFields = env.AUTH_IGNORE_ACCOUNT_FIELDS?.split(",") ?? [];
// Factory instead of a static adapter so that per-request signup attribution
// (ad-platform click ids from first-party cookies) can reach the signup event
// captured for new SSO users.
const createExtendedPrismaAdapter = (signupAttribution?: {
  adClickIds?: AdClickIds;
}): Adapter => ({
  ...prismaAdapter,
  async createUser(profile: Omit<AdapterUser, "id">) {
    if (!prismaAdapter.createUser)
      throw new Error("createUser not implemented");
    if (
      env.NEXT_PUBLIC_SIGN_UP_DISABLED === "true" ||
      env.AUTH_DISABLE_SIGNUP === "true"
    ) {
      throw new Error("Sign up is disabled.");
    }
    if (!profile.email) {
      throw new Error(
        "Cannot create db user as login profile does not contain an email: " +
          JSON.stringify(profile),
      );
    }

    const user = await prismaAdapter.createUser(profile);

    await createProjectMembershipsOnSignup(user, {
      userWasJustCreated: true,
      adClickIds: signupAttribution?.adClickIds,
    });

    return user;
  },

  async linkAccount(data: AdapterAccount) {
    if (!prismaAdapter.linkAccount)
      throw new Error("NextAuth: prismaAdapter.linkAccount not implemented");

    // Keycloak returns incompatible data with the nextjs-auth schema
    // (refresh_expires_in and not-before-policy in).
    // So, we need to remove this data from the payload before linking an account.
    // https://github.com/nextauthjs/next-auth/issues/7655
    if (data.provider.endsWith("keycloak")) {
      // endsWith required as the multi-tenant cloud SSO providers are in the "domain.provider" format
      delete data["refresh_expires_in"];
      delete data["not-before-policy"];
    }

    // WorkOS returns profile data that doesn't match the schema
    if (data.provider.endsWith("workos")) {
      // endsWith required as the multi-tenant cloud SSO providers are in the "domain.provider" format
      delete data["profile"];
    }

    // Optionally, remove fields returned by the provider that cause issues with the adapter
    // Configure via AUTH_IGNORE_ACCOUNT_FIELDS
    for (const ignoredField of ignoredAccountFields) {
      if (ignoredField in data) {
        delete data[ignoredField];
      }
    }

    await prismaAdapter.linkAccount(data);

    // Assign default memberships for existing users logging in via SSO
    // This is idempotent - won't duplicate or overwrite existing memberships
    const user = await prisma.user.findUnique({
      where: { id: data.userId },
      select: { id: true, email: true, name: true },
    });
    if (user) {
      await createProjectMembershipsOnSignup(user, {
        adClickIds: signupAttribution?.adClickIds,
      });
    }
  },

  // Email one-time codes are consumed only by `credentials.resetPassword`
  // (consumeEmailOtpAndUpdatePassword), which validates the code and writes
  // the new password in one transaction. NextAuth calls this adapter method
  // from GET /api/auth/callback/email before it consults `callbacks.signIn`,
  // so returning null here is what keeps that route from logging a user in
  // without a password. It also leaves the stored code untouched, so a
  // prefetching mail scanner or a guessed request cannot burn a valid code.
  async useVerificationToken() {
    return null;
  },
});

/**
 * Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
 *
 * @param signupAttribution - per-request marketing attribution (ad-platform
 * click ids) attached to the signup analytics event if the request results
 * in a new user. Only passed by the NextAuth API route.
 * @param requestContext - captcha material for this request. The email
 * sign-in route passes the password-reset token; other callers omit it.
 *
 * @see https://next-auth.js.org/configuration/options
 */
export async function getAuthOptions(
  signupAttribution?: {
    adClickIds?: AdClickIds;
  },
  requestContext?: {
    turnstileToken?: unknown;
    turnstileRemoteIp?: string;
  },
): Promise<NextAuthOptions> {
  let dynamicSsoProviders: Provider[] = [];
  try {
    dynamicSsoProviders = await loadSsoProviders();
  } catch (e) {
    logger.error("Error loading dynamic SSO providers", e);
    traceException(e);
  }
  const providers = [...staticProviders, ...dynamicSsoProviders];

  const data: NextAuthOptions = {
    logger: nextAuthLogger,
    session: {
      strategy: "jwt",
      maxAge: env.AUTH_SESSION_MAX_AGE * 60, // minutes → seconds
    },
    callbacks: {
      // Harden the callback-URL redirect against malformed input. NextAuth's
      // default `redirect` callback calls `new URL(url)` on the caller-supplied
      // `callbackUrl`; for a non-relative, unparsable value (e.g. the
      // `.....///…/windows/win.ini` path-traversal payloads endpoint scanners
      // send) that throws an uncaught `TypeError: ERR_INVALID_URL`, which
      // escapes NextAuth's own error handling and surfaces as an HTTP 500 on
      // POST /api/auth/callback/* and /api/auth/signin/*. Guarding the parse
      // keeps the default same-origin semantics while turning malformed input
      // into a safe redirect to baseUrl instead of a 500.
      redirect({ url, baseUrl }) {
        if (!isValidCallbackUrl(url)) return baseUrl;

        try {
          // Relative callback URLs are always safe to resolve against baseUrl.
          if (url.startsWith("/")) return `${baseUrl}${url}`;
          // Absolute URLs are only honored when same-origin.
          if (new URL(url).origin === baseUrl) return url;
        } catch {
          // Malformed callbackUrl (e.g. scanner payload) — fall through.
        }
        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,
              name: true,
              email: true,
              image: true,
              emailVerified: true,
              password: true,
              createdAt: true,
              featureFlags: true,
              admin: true,
              v4BetaEnabled: true,
              supportAccess: true,
              organizationMemberships: {
                // Newest first so demo project is last for the `project/~/` sentinel
                orderBy: {
                  createdAt: "desc",
                },
                include: {
                  organization: {
                    include: {
                      projects: {
                        where: {
                          deletedAt: {
                            equals: null,
                          },
                        },
                        orderBy: {
                          createdAt: "desc",
                        },
                      },
                    },
                  },
                  ProjectMemberships: {
                    include: {
                      project: true,
                    },
                  },
                },
              },
            },
          });

          span.setAttribute("langfuse.user.id", dbUser?.id ?? "");
          // Support engineers with an unexpired ConductorOne grant see the
          // org as VIEWER.
          const organizationMemberships = [
            ...(dbUser?.organizationMemberships ?? []),
            ...(await getSupportAccessMemberships(dbUser)),
          ];
          // V4 preview availability is governed by the write mode:
          // - events_only: the legacy traces/observations tables are no longer
          //   written, so the events-aware UI is the only correct read path —
          //   force the preview on for everyone and hide the toggle.
          // - legacy: the events tables are not written, so the preview cannot
          //   read — keep it off and hide the toggle.
          // - dual: both table sets are written, so the preview is optional. On
          //   Cloud we keep the date-based rollout (new orgs are auto-enabled
          //   and locked on at signup/org-creation, older orgs may toggle).
          //   Self-hosted dual deployments are opt-in, but only once they have
          //   also set LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN=true —
          //   otherwise feature paths still gated on that flag would silently
          //   fall back to legacy tables while the core UI reads events.
          const v4WriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;
          const isLangfuseCloud = Boolean(
            env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
          );
          // In dual mode the preview is available on Cloud (governed by the
          // rollout below) or on self-hosted deployments that opted into the
          // preview read path via ALLOW_PREVIEW_OPT_IN.
          const dualPreviewAvailable =
            isLangfuseCloud ||
            env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";
          const v4BetaEnabled =
            v4WriteMode === "events_only" ||
            (v4WriteMode === "dual" &&
              dualPreviewAvailable &&
              dbUser?.v4BetaEnabled === true);
          // The migration/upgrade UI is a separate question from the preview
          // read path above: it guides users through work that is still
          // pending, so it does not require the user to have opted into v4
          // reads first — the migration panel is where that opt-in is offered.
          const v4UpgradeUiAvailable = isV4UpgradeUiAvailable({
            isLangfuseCloud,
            v4WriteMode,
            dualPreviewAvailable,
          });

          return {
            ...session,
            environment: {
              enableExperimentalFeatures:
                env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true",
              inAppAgentEnabled: isInAppAgentInstanceEnabled(),
              aiFeaturesTracingConfigured: isLangfuseAITracingConfigured(),
              aiGatewayDeployed: isGatewayDeployedOnInstance(),
              // Enables features that are only available under an enterprise license when self-hosting Langfuse
              // If you edit this line, you risk executing code that is not MIT licensed (self-contained in /ee folders otherwise)
              selfHostedInstancePlan: getSelfHostedInstancePlanServerSide(),
              v4WriteMode,
              apiKeyProjectRoleSelectionEnabled:
                env.API_AUTH_MIGRATION === "enforce" &&
                env.API_KEY_PROJECT_ROLES_ENABLE === "true",
              apiKeyOrgRoleSelectionEnabled:
                env.API_AUTH_MIGRATION === "enforce" &&
                env.API_KEY_ORG_ROLES_ENABLE === "true",
              accessAuditLogMode: env.LANGFUSE_AUDIT_LOG_ACCESS_EVENTS,
            },
            user:
              dbUser !== null
                ? {
                    ...session.user,
                    id: dbUser.id,
                    name: dbUser.name,
                    email: dbUser.email,
                    emailSupportHash: dbUser.email
                      ? createSupportEmailHash(dbUser.email)
                      : undefined,
                    image: dbUser.image,
                    admin: dbUser.admin,
                    v4BetaEnabled,
                    v4UpgradeUiAvailable,
                    canToggleV4:
                      v4WriteMode === "dual" && dualPreviewAvailable
                        ? isLangfuseCloud
                          ? canToggleV4(
                              {
                                userCreatedAt: dbUser.createdAt,
                                organizations:
                                  dbUser.organizationMemberships.map(
                                    (orgMembership) => ({
                                      id: orgMembership.organization.id,
                                      createdAt:
                                        orgMembership.organization.createdAt,
                                    }),
                                  ),
                                excludedOrganizationIds:
                                  env.NEXT_PUBLIC_DEMO_ORG_ID
                                    ? [env.NEXT_PUBLIC_DEMO_ORG_ID]
                                    : [],
                              },
                              { isLangfuseCloudAdmin: dbUser.admin },
                            )
                          : true
                        : false,
                    canCreateOrganizations: canCreateOrganizations(
                      dbUser.email,
                    ),
                    organizations: organizationMemberships.map(
                      (orgMembership) => {
                        const parsedCloudConfig = CloudConfigSchema.safeParse(
                          orgMembership.organization.cloudConfig,
                        );
                        return {
                          id: orgMembership.organization.id,
                          name: orgMembership.organization.name,
                          role: orgMembership.role,
                          supportAccess: "supportAccess" in orgMembership,
                          metadata:
                            (orgMembership.organization.metadata as Record<
                              string,
                              unknown
                            >) ?? {},
                          aiFeaturesEnabled:
                            orgMembership.organization.aiFeaturesEnabled,
                          aiTelemetryEnabled:
                            orgMembership.organization.aiTelemetryEnabled,
                          accessAuditLogEnabled:
                            orgMembership.organization.accessAuditLogEnabled,
                          featureFlags: parseFlagsWithOrganizationDefaults(
                            dbUser.featureFlags,
                            orgMembership.organization.featureFlagOrgDefaults,
                            {
                              email: dbUser.email,
                              v4BetaEnabled,
                              aiGatewayEnabled: isGatewayEnabledForOrganization(
                                orgMembership.organization.id,
                              ),
                            },
                          ),
                          cloudConfig: parsedCloudConfig.data,
                          projects: orgMembership.organization.projects
                            .map((project) => {
                              const projectRole = resolveProjectRole({
                                projectId: project.id,
                                projectMemberships:
                                  orgMembership.ProjectMemberships,
                                orgMembershipRole: orgMembership.role,
                              });
                              return {
                                id: project.id,
                                name: project.name,
                                role: projectRole,
                                retentionDays: project.retentionDays,
                                hasTraces: project.hasTraces,
                                topicsEnabled: isTopicsProjectEnabled(
                                  project.id,
                                ),
                                scoreEditsDisabled: shouldSkipScoresDedup(
                                  project.id,
                                ),
                                deletedAt: project.deletedAt,
                                metadata:
                                  (project.metadata as Record<
                                    string,
                                    unknown
                                  >) ?? {},
                                createdAt: project.createdAt.toISOString(),
                              };
                            })
                            // Only include projects where the user has the required role
                            .filter((project) =>
                              projectRoleAccessRights[project.role].includes(
                                "project:read",
                              ),
                            ),

                          // Enables features/entitlements based on the plan of the organization, either cloud or EE version when self-hosting
                          // If you edit this line, you risk executing code that is not MIT licensed (contained in /ee folders, see LICENSE)
                          plan: getOrganizationPlanServerSide(
                            parsedCloudConfig.data,
                          ),
                        };
                      },
                    ),
                    emailVerified: dbUser.emailVerified?.toISOString(),
                    featureFlags: parseFlags(dbUser.featureFlags, {
                      email: dbUser.email,
                      v4BetaEnabled,
                    }),
                    hasPassword: Boolean(dbUser.password),
                  }
                : null,
          };
        });
      },
      async signIn({ user, account, profile, email: emailFlow }) {
        return instrumentAsync({ name: "next-auth-sign-in" }, async () => {
          // Block sign in without valid user.email
          const email = user.email?.toLowerCase();
          if (!email) {
            logger.error("No email found in user object");
            throw new Error("No email found in user object");
          }
          if (z.email().safeParse(email).success === false) {
            logger.error("Invalid email found in user object");
            throw new Error("Invalid email found in user object");
          }

          // EE: Check custom SSO enforcement, enforce the specific SSO provider on email domain
          // This also blocks setting a password for an email that is enforced to use SSO via password reset flow
          const userDomain = email.split("@")[1].toLowerCase();
          const multiTenantSsoProvider =
            await getSsoAuthProviderIdForDomain(userDomain);
          if (
            multiTenantSsoProvider &&
            account?.provider !== multiTenantSsoProvider
          ) {
            logger.info(
              "Custom SSO provider enforced for domain, user signed in with other provider",
              { email, attemptedProvider: account?.provider },
            );
            const params = new URLSearchParams({
              reason: "sso_enforced_domain",
            });
            if (email) params.set("email", email);
            if (account?.provider)
              params.set("attemptedProvider", account.provider);
            return `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/enterprise-sso-required?${params.toString()}`;
          }

          // EE: Check that provider is only used for the associated domain
          if (account?.provider) {
            const { isMultiTenantSsoProvider, domain: ssoDomain } =
              await findMultiTenantSsoConfig({
                providerId: account.provider,
              });
            if (
              isMultiTenantSsoProvider &&
              ssoDomain.toLowerCase() !== userDomain.toLowerCase()
            ) {
              // warn: the ONLY server-side signal for this rejection — the
              // client render of the resulting /auth/error page is classified
              // as expected and not captured (expectedAuthErrors.ts), and
              // next-auth does not log signIn-callback throws itself.
              logger.warn(
                "Multi-tenant SSO provider used with a non-matching email domain",
                { email, attemptedProvider: account.provider },
              );
              throw new Error(MULTI_TENANT_SSO_DOMAIN_MISMATCH_MESSAGE);
            }
          }

          // The email provider only sends password-reset codes; it must never
          // complete a login. NextAuth sets `email.verificationRequest` on the
          // send request (POST /api/auth/signin/email) and omits it on the
          // consume request (GET /api/auth/callback/email).
          if (account?.provider === "email") {
            if (!emailFlow?.verificationRequest) {
              logger.warn(
                "Blocked email-OTP sign in via the NextAuth email callback",
                { email },
              );
              return false;
            }

            // Checked before the user lookup so a missing or rejected token
            // never sends a code, and does not reveal whether the account exists.
            const turnstileValid = await verifyTurnstileToken({
              token: requestContext?.turnstileToken,
              action: TURNSTILE_ACTIONS.passwordReset,
              remoteIp: requestContext?.turnstileRemoteIp,
            });
            if (!turnstileValid) throw new Error(TURNSTILE_FAILED_MESSAGE);

            // Codes only reset passwords, so there is nothing to send when
            // password login is disabled.
            if (env.AUTH_DISABLE_USERNAME_PASSWORD === "true") {
              logger.info(
                "Blocked email-OTP request because AUTH_DISABLE_USERNAME_PASSWORD is set",
                { email },
              );
              return false;
            }

            // Only send a code if the user already exists, as this is used for password reset
            const blockedDomains = getSSOBlockedDomains();
            if (userDomain && blockedDomains.includes(userDomain)) {
              logger.info(
                "Blocked email-OTP sign in for domain enforced via AUTH_DOMAINS_WITH_SSO_ENFORCEMENT",
                { email },
              );
              const params = new URLSearchParams({
                reason: "sso_enforced_domain",
              });
              if (email) params.set("email", email);
              params.set("attemptedProvider", "email");
              return `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/enterprise-sso-required?${params.toString()}`;
            }

            const user = await prisma.user.findUnique({
              where: {
                email: email,
              },
            });
            if (user) {
              // NextAuth stores the new code right after this callback. Codes
              // are hashed without the email and `token` is globally unique, so
              // rows left behind make new codes collide. Only the newest code
              // per account is needed, and expired codes can never be used.
              await prisma.verificationToken.deleteMany({
                where: {
                  OR: [{ identifier: email }, { expires: { lt: new Date() } }],
                },
              });
              return true;
            }
            // Add random delay to prevent leaking if user exists as otherwise it would be instant compared to sending an email
            await new Promise((resolve) =>
              setTimeout(resolve, Math.random() * 2000 + 200),
            );
            // Prevents sign in with email link if user does not exist
            return false;
          }

          // Optional configuration: validate authorised email domains for google provider
          // uses hd (hosted domain) claim from google profile as the domain
          // https://developers.google.com/identity/openid-connect/openid-connect#an-id-tokens-payload
          if (
            env.AUTH_GOOGLE_ALLOWED_DOMAINS &&
            account?.provider === "google"
          ) {
            const allowedDomains =
              env.AUTH_GOOGLE_ALLOWED_DOMAINS?.split(",").map((domain) =>
                domain.trim().toLowerCase(),
              ) ?? [];

            if (allowedDomains.length > 0) {
              return await Promise.resolve(
                allowedDomains.includes(
                  (profile as GoogleProfile).hd?.toLowerCase(),
                ),
              );
            }
          }

          return await Promise.resolve(true);
        });
      },
    },
    adapter: createExtendedPrismaAdapter(signupAttribution),
    providers,
    pages: {
      signIn: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/sign-in`,
      error: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/error`,
      ...(isSignupOnboardingEnabled()
        ? {
            newUser: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`,
          }
        : {}),
    },
    cookies: {
      sessionToken: {
        name: getCookieName("next-auth.session-token"),
        options: getCookieOptions(),
      },
      csrfToken: {
        name: getCookieName("next-auth.csrf-token"),
        options: getCookieOptions(),
      },
      callbackUrl: {
        name: getCookieName("next-auth.callback-url"),
        options: getCookieOptions(),
      },
      state: {
        name: getCookieName("next-auth.state"),
        options: getCookieOptions(),
      },
      nonce: {
        name: getCookieName("next-auth.nonce"),
        options: getCookieOptions(),
      },
      pkceCodeVerifier: {
        name: getCookieName("next-auth.pkce.code_verifier"),
        options: getCookieOptions(),
      },
    },
    events: {
      createUser: async ({ user }) => {
        if (
          env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK &&
          env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&
          env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== "STAGING" &&
          env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== "DEV"
        ) {
          await fetch(env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK, {
            method: "POST",
            body: JSON.stringify({
              name: user.name,
              email: user.email,
              cloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
              userId: user.id,
              // referralSource: ...
            }),
            headers: {
              "Content-Type": "application/json",
            },
          });
        }
      },
    },
  };
  return data;
}

/**
 * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file.
 *
 * @see https://next-auth.js.org/configuration/nextjs
 */
export const getServerAuthSession = async (ctx: {
  req: GetServerSidePropsContext["req"];
  res: GetServerSidePropsContext["res"];
}) => {
  const authOptions = await getAuthOptions();
  // https://github.com/nextauthjs/next-auth/issues/2408#issuecomment-1382629234
  // for api routes, we need to call the headers in the api route itself

  // disable caching for any api requiring server-side auth
  ctx.res.setHeader(
    "Cache-Control",
    "no-store, no-cache, must-revalidate, proxy-revalidate",
  );
  ctx.res.setHeader("Pragma", "no-cache");
  ctx.res.setHeader("Expires", "0");

  sanitizeServerSessionCallbackUrl(
    ctx.req,
    ctx.req.url?.split("?")[0]?.slice(0, 200),
  );

  return getServerSession(ctx.req, ctx.res, authOptions);
};

/**
 * App Router equivalent of getServerAuthSession. Passing the request and
 * response explicitly lets us sanitize the parsed cookies before next-auth's
 * config assertion runs.
 */
export const getServerAuthSessionForRequest = async (request: Request) => {
  const authOptions = await getAuthOptions();
  const cookies = getRequestCookies(request);
  const req = {
    headers: Object.fromEntries(request.headers.entries()),
    cookies,
  } as GetServerSidePropsContext["req"];

  sanitizeServerSessionCallbackUrl(
    req,
    new URL(request.url).pathname.slice(0, 200),
  );

  const res = {
    getHeader: () => undefined,
    setCookie: () => undefined,
    setHeader: () => undefined,
  } as unknown as GetServerSidePropsContext["res"];

  const session = await getServerSession(req, res, authOptions);

  // Match getServerSession's App Router behavior. The explicit request/response
  // form above selects its Pages Router branch, which otherwise keeps expires.
  if (!session) return session;

  const { expires: _expires, ...sessionWithoutExpires } = session;

  return sessionWithoutExpires as Session;
};

const sanitizeServerSessionCallbackUrl = (
  req: { cookies?: Partial<Record<string, string>> },
  path: string | undefined,
) => {
  const callbackUrlCookieName = getCookieName("next-auth.callback-url");
  const callbackUrlCookie = req.cookies?.[callbackUrlCookieName];

  if (!callbackUrlCookie || isValidCallbackUrl(callbackUrlCookie)) return;

  const { [callbackUrlCookieName]: _invalidCallbackUrl, ...sanitizedCookies } =
    req.cookies ?? {};
  req.cookies = sanitizedCookies;

  logger.warn(
    "[NEXT_AUTH] Ignored invalid callback URL for server-side session",
    {
      path,
    },
  );
};