fix: check url first for sso provider identification

This commit is contained in:
Nicolas Meienberger 2026-02-27 17:47:55 +01:00
parent 27ac83613d
commit 3e73b7cc8a
2 changed files with 14 additions and 12 deletions

View file

@ -2,14 +2,14 @@ import { APIError } from "better-auth/api";
import type { GenericEndpointContext } from "@better-auth/core";
import { db } from "~/server/db/db";
import { logger } from "~/server/utils/logger";
import { extractProviderIdFromContext, normalizeEmail } from "../utils/sso-context";
import { extractProviderIdFromContext, extractProviderIdFromUrl, normalizeEmail } from "../utils/sso-context";
export function isSsoCallbackRequest(ctx: GenericEndpointContext | null) {
if (!ctx) {
if (!ctx?.request?.url) {
return false;
}
return extractProviderIdFromContext(ctx) !== null;
return extractProviderIdFromUrl(ctx.request.url) !== null;
}
export const requireSsoInvitation = async (userEmail: string, ctx: GenericEndpointContext | null) => {

View file

@ -4,6 +4,16 @@ export function normalizeEmail(email: string): string {
return email.trim().toLowerCase();
}
export function extractProviderIdFromUrl(url: string): string | null {
try {
const pathname = new URL(url, "http://localhost").pathname;
const match = pathname.match(/\/sso\/(?:saml2\/)?callback\/([^/]+)$/);
return match?.[1] ?? null;
} catch {
return null;
}
}
export function extractProviderIdFromContext(ctx?: GenericEndpointContext | null) {
if (!ctx) {
return null;
@ -14,15 +24,7 @@ export function extractProviderIdFromContext(ctx?: GenericEndpointContext | null
}
if (ctx.request?.url) {
try {
const pathname = new URL(ctx.request.url, "http://localhost").pathname;
const ssoCallbackMatch = pathname.match(/\/sso\/(?:saml2\/)?callback\/([^/]+)$/);
if (ssoCallbackMatch) {
return ssoCallbackMatch[1];
}
} catch {
return null;
}
return extractProviderIdFromUrl(ctx.request.url);
}
return null;