const require_rolldown_runtime = require('../../../../_virtual/rolldown_runtime.cjs');
const require_schemas = require('../../../zod/v4/classic/schemas.cjs');
const require_index = require('../../../samlify/build/index.cjs');
const require_index$1 = require('../../../@better-fetch/fetch/dist/index.cjs');
const require_decode_jwt = require('../../../jose/dist/webapi/util/decode_jwt.cjs');
const require_fxp = require('../../../fast-xml-parser/src/fxp.cjs');
let better_auth = require("better-auth");
let better_auth_api = require("better-auth/api");
let better_auth_oauth2 = require("better-auth/oauth2");
let better_auth_plugins = require("better-auth/plugins");
let better_auth_cookies = require("better-auth/cookies");

//#region ../../node_modules/@better-auth/sso/dist/index.mjs
var import_build = /* @__PURE__ */ require_rolldown_runtime.__toESM(require_index.default, 1);
import_build.setSchemaValidator({ async validate(xml) {
	if (require_fxp.XMLValidator.validate(xml, { allowBooleanAttributes: true }) === true) return "SUCCESS_VALIDATE_XML";
	throw "ERR_INVALID_XML";
} });
function safeJsonParse(value) {
	if (!value) return null;
	if (typeof value === "object") return value;
	if (typeof value === "string") try {
		return JSON.parse(value);
	} catch (error) {
		throw new Error(`Failed to parse JSON: ${error instanceof Error ? error.message : "Unknown error"}`);
	}
	return null;
}
const sso = (options) => {
	return {
		id: "sso",
		endpoints: {
			spMetadata: (0, better_auth_plugins.createAuthEndpoint)("/sso/saml2/sp/metadata", {
				method: "GET",
				query: require_schemas.object({
					providerId: require_schemas.string(),
					format: require_schemas._enum(["xml", "json"]).default("xml")
				}),
				metadata: { openapi: {
					summary: "Get Service Provider metadata",
					description: "Returns the SAML metadata for the Service Provider",
					responses: { "200": { description: "SAML metadata in XML format" } }
				} }
			}, async (ctx) => {
				const provider = await ctx.context.adapter.findOne({
					model: "ssoProvider",
					where: [{
						field: "providerId",
						value: ctx.query.providerId
					}]
				});
				if (!provider) throw new better_auth_api.APIError("NOT_FOUND", { message: "No provider found for the given providerId" });
				const parsedSamlConfig = safeJsonParse(provider.samlConfig);
				if (!parsedSamlConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SAML configuration" });
				const sp = parsedSamlConfig.spMetadata.metadata ? import_build.ServiceProvider({ metadata: parsedSamlConfig.spMetadata.metadata }) : import_build.SPMetadata({
					entityID: parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
					assertionConsumerService: [{
						Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
						Location: parsedSamlConfig.callbackUrl || `${ctx.context.baseURL}/sso/saml2/sp/acs/${provider.id}`
					}],
					wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
					nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : void 0
				});
				return new Response(sp.getMetadata(), { headers: { "Content-Type": "application/xml" } });
			}),
			registerSSOProvider: (0, better_auth_plugins.createAuthEndpoint)("/sso/register", {
				method: "POST",
				body: require_schemas.object({
					providerId: require_schemas.string({}).meta({ description: "The ID of the provider. This is used to identify the provider during login and callback" }),
					issuer: require_schemas.string({}).meta({ description: "The issuer of the provider" }),
					domain: require_schemas.string({}).meta({ description: "The domain of the provider. This is used for email matching" }),
					oidcConfig: require_schemas.object({
						clientId: require_schemas.string({}).meta({ description: "The client ID" }),
						clientSecret: require_schemas.string({}).meta({ description: "The client secret" }),
						authorizationEndpoint: require_schemas.string({}).meta({ description: "The authorization endpoint" }).optional(),
						tokenEndpoint: require_schemas.string({}).meta({ description: "The token endpoint" }).optional(),
						userInfoEndpoint: require_schemas.string({}).meta({ description: "The user info endpoint" }).optional(),
						tokenEndpointAuthentication: require_schemas._enum(["client_secret_post", "client_secret_basic"]).optional(),
						jwksEndpoint: require_schemas.string({}).meta({ description: "The JWKS endpoint" }).optional(),
						discoveryEndpoint: require_schemas.string().optional(),
						scopes: require_schemas.array(require_schemas.string(), {}).meta({ description: "The scopes to request. Defaults to ['openid', 'email', 'profile', 'offline_access']" }).optional(),
						pkce: require_schemas.boolean({}).meta({ description: "Whether to use PKCE for the authorization flow" }).default(true).optional(),
						mapping: require_schemas.object({
							id: require_schemas.string({}).meta({ description: "Field mapping for user ID (defaults to 'sub')" }),
							email: require_schemas.string({}).meta({ description: "Field mapping for email (defaults to 'email')" }),
							emailVerified: require_schemas.string({}).meta({ description: "Field mapping for email verification (defaults to 'email_verified')" }).optional(),
							name: require_schemas.string({}).meta({ description: "Field mapping for name (defaults to 'name')" }),
							image: require_schemas.string({}).meta({ description: "Field mapping for image (defaults to 'picture')" }).optional(),
							extraFields: require_schemas.record(require_schemas.string(), require_schemas.any()).optional()
						}).optional()
					}).optional(),
					samlConfig: require_schemas.object({
						entryPoint: require_schemas.string({}).meta({ description: "The entry point of the provider" }),
						cert: require_schemas.string({}).meta({ description: "The certificate of the provider" }),
						callbackUrl: require_schemas.string({}).meta({ description: "The callback URL of the provider" }),
						audience: require_schemas.string().optional(),
						idpMetadata: require_schemas.object({
							metadata: require_schemas.string().optional(),
							entityID: require_schemas.string().optional(),
							cert: require_schemas.string().optional(),
							privateKey: require_schemas.string().optional(),
							privateKeyPass: require_schemas.string().optional(),
							isAssertionEncrypted: require_schemas.boolean().optional(),
							encPrivateKey: require_schemas.string().optional(),
							encPrivateKeyPass: require_schemas.string().optional(),
							singleSignOnService: require_schemas.array(require_schemas.object({
								Binding: require_schemas.string().meta({ description: "The binding type for the SSO service" }),
								Location: require_schemas.string().meta({ description: "The URL for the SSO service" })
							})).optional().meta({ description: "Single Sign-On service configuration" })
						}).optional(),
						spMetadata: require_schemas.object({
							metadata: require_schemas.string().optional(),
							entityID: require_schemas.string().optional(),
							binding: require_schemas.string().optional(),
							privateKey: require_schemas.string().optional(),
							privateKeyPass: require_schemas.string().optional(),
							isAssertionEncrypted: require_schemas.boolean().optional(),
							encPrivateKey: require_schemas.string().optional(),
							encPrivateKeyPass: require_schemas.string().optional()
						}),
						wantAssertionsSigned: require_schemas.boolean().optional(),
						signatureAlgorithm: require_schemas.string().optional(),
						digestAlgorithm: require_schemas.string().optional(),
						identifierFormat: require_schemas.string().optional(),
						privateKey: require_schemas.string().optional(),
						decryptionPvk: require_schemas.string().optional(),
						additionalParams: require_schemas.record(require_schemas.string(), require_schemas.any()).optional(),
						mapping: require_schemas.object({
							id: require_schemas.string({}).meta({ description: "Field mapping for user ID (defaults to 'nameID')" }),
							email: require_schemas.string({}).meta({ description: "Field mapping for email (defaults to 'email')" }),
							emailVerified: require_schemas.string({}).meta({ description: "Field mapping for email verification" }).optional(),
							name: require_schemas.string({}).meta({ description: "Field mapping for name (defaults to 'displayName')" }),
							firstName: require_schemas.string({}).meta({ description: "Field mapping for first name (defaults to 'givenName')" }).optional(),
							lastName: require_schemas.string({}).meta({ description: "Field mapping for last name (defaults to 'surname')" }).optional(),
							extraFields: require_schemas.record(require_schemas.string(), require_schemas.any()).optional()
						}).optional()
					}).optional(),
					organizationId: require_schemas.string({}).meta({ description: "If organization plugin is enabled, the organization id to link the provider to" }).optional(),
					overrideUserInfo: require_schemas.boolean({}).meta({ description: "Override user info with the provider info. Defaults to false" }).default(false).optional()
				}),
				use: [better_auth_api.sessionMiddleware],
				metadata: { openapi: {
					summary: "Register an OIDC provider",
					description: "This endpoint is used to register an OIDC provider. This is used to configure the provider and link it to an organization",
					responses: { "200": {
						description: "OIDC provider created successfully",
						content: { "application/json": { schema: {
							type: "object",
							properties: {
								issuer: {
									type: "string",
									format: "uri",
									description: "The issuer URL of the provider"
								},
								domain: {
									type: "string",
									description: "The domain of the provider, used for email matching"
								},
								oidcConfig: {
									type: "object",
									properties: {
										issuer: {
											type: "string",
											format: "uri",
											description: "The issuer URL of the provider"
										},
										pkce: {
											type: "boolean",
											description: "Whether PKCE is enabled for the authorization flow"
										},
										clientId: {
											type: "string",
											description: "The client ID for the provider"
										},
										clientSecret: {
											type: "string",
											description: "The client secret for the provider"
										},
										authorizationEndpoint: {
											type: "string",
											format: "uri",
											nullable: true,
											description: "The authorization endpoint URL"
										},
										discoveryEndpoint: {
											type: "string",
											format: "uri",
											description: "The discovery endpoint URL"
										},
										userInfoEndpoint: {
											type: "string",
											format: "uri",
											nullable: true,
											description: "The user info endpoint URL"
										},
										scopes: {
											type: "array",
											items: { type: "string" },
											nullable: true,
											description: "The scopes requested from the provider"
										},
										tokenEndpoint: {
											type: "string",
											format: "uri",
											nullable: true,
											description: "The token endpoint URL"
										},
										tokenEndpointAuthentication: {
											type: "string",
											enum: ["client_secret_post", "client_secret_basic"],
											nullable: true,
											description: "Authentication method for the token endpoint"
										},
										jwksEndpoint: {
											type: "string",
											format: "uri",
											nullable: true,
											description: "The JWKS endpoint URL"
										},
										mapping: {
											type: "object",
											nullable: true,
											properties: {
												id: {
													type: "string",
													description: "Field mapping for user ID (defaults to 'sub')"
												},
												email: {
													type: "string",
													description: "Field mapping for email (defaults to 'email')"
												},
												emailVerified: {
													type: "string",
													nullable: true,
													description: "Field mapping for email verification (defaults to 'email_verified')"
												},
												name: {
													type: "string",
													description: "Field mapping for name (defaults to 'name')"
												},
												image: {
													type: "string",
													nullable: true,
													description: "Field mapping for image (defaults to 'picture')"
												},
												extraFields: {
													type: "object",
													additionalProperties: { type: "string" },
													nullable: true,
													description: "Additional field mappings"
												}
											},
											required: [
												"id",
												"email",
												"name"
											]
										}
									},
									required: [
										"issuer",
										"pkce",
										"clientId",
										"clientSecret",
										"discoveryEndpoint"
									],
									description: "OIDC configuration for the provider"
								},
								organizationId: {
									type: "string",
									nullable: true,
									description: "ID of the linked organization, if any"
								},
								userId: {
									type: "string",
									description: "ID of the user who registered the provider"
								},
								providerId: {
									type: "string",
									description: "Unique identifier for the provider"
								},
								redirectURI: {
									type: "string",
									format: "uri",
									description: "The redirect URI for the provider callback"
								}
							},
							required: [
								"issuer",
								"domain",
								"oidcConfig",
								"userId",
								"providerId",
								"redirectURI"
							]
						} } }
					} }
				} }
			}, async (ctx) => {
				const user = ctx.context.session?.user;
				if (!user) throw new better_auth_api.APIError("UNAUTHORIZED");
				const limit = typeof options?.providersLimit === "function" ? await options.providersLimit(user) : options?.providersLimit ?? 10;
				if (!limit) throw new better_auth_api.APIError("FORBIDDEN", { message: "SSO provider registration is disabled" });
				if ((await ctx.context.adapter.findMany({
					model: "ssoProvider",
					where: [{
						field: "userId",
						value: user.id
					}]
				})).length >= limit) throw new better_auth_api.APIError("FORBIDDEN", { message: "You have reached the maximum number of SSO providers" });
				const body = ctx.body;
				if (require_schemas.string().url().safeParse(body.issuer).error) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid issuer. Must be a valid URL" });
				if (ctx.body.organizationId) {
					if (!await ctx.context.adapter.findOne({
						model: "member",
						where: [{
							field: "userId",
							value: user.id
						}, {
							field: "organizationId",
							value: ctx.body.organizationId
						}]
					})) throw new better_auth_api.APIError("BAD_REQUEST", { message: "You are not a member of the organization" });
				}
				if (await ctx.context.adapter.findOne({
					model: "ssoProvider",
					where: [{
						field: "providerId",
						value: body.providerId
					}]
				})) {
					ctx.context.logger.info(`SSO provider creation attempt with existing providerId: ${body.providerId}`);
					throw new better_auth_api.APIError("UNPROCESSABLE_ENTITY", { message: "SSO provider with this providerId already exists" });
				}
				const provider = await ctx.context.adapter.create({
					model: "ssoProvider",
					data: {
						issuer: body.issuer,
						domain: body.domain,
						oidcConfig: body.oidcConfig ? JSON.stringify({
							issuer: body.issuer,
							clientId: body.oidcConfig.clientId,
							clientSecret: body.oidcConfig.clientSecret,
							authorizationEndpoint: body.oidcConfig.authorizationEndpoint,
							tokenEndpoint: body.oidcConfig.tokenEndpoint,
							tokenEndpointAuthentication: body.oidcConfig.tokenEndpointAuthentication,
							jwksEndpoint: body.oidcConfig.jwksEndpoint,
							pkce: body.oidcConfig.pkce,
							discoveryEndpoint: body.oidcConfig.discoveryEndpoint || `${body.issuer}/.well-known/openid-configuration`,
							mapping: body.oidcConfig.mapping,
							scopes: body.oidcConfig.scopes,
							userInfoEndpoint: body.oidcConfig.userInfoEndpoint,
							overrideUserInfo: ctx.body.overrideUserInfo || options?.defaultOverrideUserInfo || false
						}) : null,
						samlConfig: body.samlConfig ? JSON.stringify({
							issuer: body.issuer,
							entryPoint: body.samlConfig.entryPoint,
							cert: body.samlConfig.cert,
							callbackUrl: body.samlConfig.callbackUrl,
							audience: body.samlConfig.audience,
							idpMetadata: body.samlConfig.idpMetadata,
							spMetadata: body.samlConfig.spMetadata,
							wantAssertionsSigned: body.samlConfig.wantAssertionsSigned,
							signatureAlgorithm: body.samlConfig.signatureAlgorithm,
							digestAlgorithm: body.samlConfig.digestAlgorithm,
							identifierFormat: body.samlConfig.identifierFormat,
							privateKey: body.samlConfig.privateKey,
							decryptionPvk: body.samlConfig.decryptionPvk,
							additionalParams: body.samlConfig.additionalParams,
							mapping: body.samlConfig.mapping
						}) : null,
						organizationId: body.organizationId,
						userId: ctx.context.session.user.id,
						providerId: body.providerId
					}
				});
				return ctx.json({
					...provider,
					oidcConfig: JSON.parse(provider.oidcConfig),
					samlConfig: JSON.parse(provider.samlConfig),
					redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`
				});
			}),
			signInSSO: (0, better_auth_plugins.createAuthEndpoint)("/sign-in/sso", {
				method: "POST",
				body: require_schemas.object({
					email: require_schemas.string({}).meta({ description: "The email address to sign in with. This is used to identify the issuer to sign in with. It's optional if the issuer is provided" }).optional(),
					organizationSlug: require_schemas.string({}).meta({ description: "The slug of the organization to sign in with" }).optional(),
					providerId: require_schemas.string({}).meta({ description: "The ID of the provider to sign in with. This can be provided instead of email or issuer" }).optional(),
					domain: require_schemas.string({}).meta({ description: "The domain of the provider." }).optional(),
					callbackURL: require_schemas.string({}).meta({ description: "The URL to redirect to after login" }),
					errorCallbackURL: require_schemas.string({}).meta({ description: "The URL to redirect to after login" }).optional(),
					newUserCallbackURL: require_schemas.string({}).meta({ description: "The URL to redirect to after login if the user is new" }).optional(),
					scopes: require_schemas.array(require_schemas.string(), {}).meta({ description: "Scopes to request from the provider." }).optional(),
					requestSignUp: require_schemas.boolean({}).meta({ description: "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider" }).optional(),
					providerType: require_schemas._enum(["oidc", "saml"]).optional()
				}),
				metadata: { openapi: {
					summary: "Sign in with SSO provider",
					description: "This endpoint is used to sign in with an SSO provider. It redirects to the provider's authorization URL",
					requestBody: { content: { "application/json": { schema: {
						type: "object",
						properties: {
							email: {
								type: "string",
								description: "The email address to sign in with. This is used to identify the issuer to sign in with. It's optional if the issuer is provided"
							},
							issuer: {
								type: "string",
								description: "The issuer identifier, this is the URL of the provider and can be used to verify the provider and identify the provider during login. It's optional if the email is provided"
							},
							providerId: {
								type: "string",
								description: "The ID of the provider to sign in with. This can be provided instead of email or issuer"
							},
							callbackURL: {
								type: "string",
								description: "The URL to redirect to after login"
							},
							errorCallbackURL: {
								type: "string",
								description: "The URL to redirect to after login"
							},
							newUserCallbackURL: {
								type: "string",
								description: "The URL to redirect to after login if the user is new"
							}
						},
						required: ["callbackURL"]
					} } } },
					responses: { "200": {
						description: "Authorization URL generated successfully for SSO sign-in",
						content: { "application/json": { schema: {
							type: "object",
							properties: {
								url: {
									type: "string",
									format: "uri",
									description: "The authorization URL to redirect the user to for SSO sign-in"
								},
								redirect: {
									type: "boolean",
									description: "Indicates that the client should redirect to the provided URL",
									enum: [true]
								}
							},
							required: ["url", "redirect"]
						} } }
					} }
				} }
			}, async (ctx) => {
				const body = ctx.body;
				let { email, organizationSlug, providerId, domain } = body;
				if (!options?.defaultSSO?.length && !email && !organizationSlug && !domain && !providerId) throw new better_auth_api.APIError("BAD_REQUEST", { message: "email, organizationSlug, domain or providerId is required" });
				domain = body.domain || email?.split("@")[1];
				let orgId = "";
				if (organizationSlug) orgId = await ctx.context.adapter.findOne({
					model: "organization",
					where: [{
						field: "slug",
						value: organizationSlug
					}]
				}).then((res) => {
					if (!res) return "";
					return res.id;
				});
				let provider = null;
				if (options?.defaultSSO?.length) {
					const matchingDefault = providerId ? options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === providerId) : options.defaultSSO.find((defaultProvider) => defaultProvider.domain === domain);
					if (matchingDefault) provider = {
						issuer: matchingDefault.samlConfig?.issuer || matchingDefault.oidcConfig?.issuer || "",
						providerId: matchingDefault.providerId,
						userId: "default",
						oidcConfig: matchingDefault.oidcConfig,
						samlConfig: matchingDefault.samlConfig
					};
				}
				if (!providerId && !orgId && !domain) throw new better_auth_api.APIError("BAD_REQUEST", { message: "providerId, orgId or domain is required" });
				if (!provider) provider = await ctx.context.adapter.findOne({
					model: "ssoProvider",
					where: [{
						field: providerId ? "providerId" : orgId ? "organizationId" : "domain",
						value: providerId || orgId || domain
					}]
				}).then((res) => {
					if (!res) return null;
					return {
						...res,
						oidcConfig: res.oidcConfig ? safeJsonParse(res.oidcConfig) || void 0 : void 0,
						samlConfig: res.samlConfig ? safeJsonParse(res.samlConfig) || void 0 : void 0
					};
				});
				if (!provider) throw new better_auth_api.APIError("NOT_FOUND", { message: "No provider found for the issuer" });
				if (body.providerType) {
					if (body.providerType === "oidc" && !provider.oidcConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "OIDC provider is not configured" });
					if (body.providerType === "saml" && !provider.samlConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "SAML provider is not configured" });
				}
				if (provider.oidcConfig && body.providerType !== "saml") {
					const state = await (0, better_auth.generateState)(ctx);
					const redirectURI = `${ctx.context.baseURL}/sso/callback/${provider.providerId}`;
					const authorizationURL = await (0, better_auth_oauth2.createAuthorizationURL)({
						id: provider.issuer,
						options: {
							clientId: provider.oidcConfig.clientId,
							clientSecret: provider.oidcConfig.clientSecret
						},
						redirectURI,
						state: state.state,
						codeVerifier: provider.oidcConfig.pkce ? state.codeVerifier : void 0,
						scopes: ctx.body.scopes || provider.oidcConfig.scopes || [
							"openid",
							"email",
							"profile",
							"offline_access"
						],
						authorizationEndpoint: provider.oidcConfig.authorizationEndpoint
					});
					return ctx.json({
						url: authorizationURL.toString(),
						redirect: true
					});
				}
				if (provider.samlConfig) {
					const parsedSamlConfig = typeof provider.samlConfig === "object" ? provider.samlConfig : safeJsonParse(provider.samlConfig);
					if (!parsedSamlConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SAML configuration" });
					const sp = import_build.ServiceProvider({
						metadata: parsedSamlConfig.spMetadata.metadata,
						allowCreate: true
					});
					const idp = import_build.IdentityProvider({
						metadata: parsedSamlConfig.idpMetadata?.metadata,
						entityID: parsedSamlConfig.idpMetadata?.entityID,
						encryptCert: parsedSamlConfig.idpMetadata?.cert,
						singleSignOnService: parsedSamlConfig.idpMetadata?.singleSignOnService
					});
					const loginRequest = sp.createLoginRequest(idp, "redirect");
					if (!loginRequest) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SAML request" });
					return ctx.json({
						url: `${loginRequest.context}&RelayState=${encodeURIComponent(body.callbackURL)}`,
						redirect: true
					});
				}
				throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SSO provider" });
			}),
			callbackSSO: (0, better_auth_plugins.createAuthEndpoint)("/sso/callback/:providerId", {
				method: "GET",
				query: require_schemas.object({
					code: require_schemas.string().optional(),
					state: require_schemas.string(),
					error: require_schemas.string().optional(),
					error_description: require_schemas.string().optional()
				}),
				metadata: {
					isAction: false,
					openapi: {
						summary: "Callback URL for SSO provider",
						description: "This endpoint is used as the callback URL for SSO providers. It handles the authorization code and exchanges it for an access token",
						responses: { "302": { description: "Redirects to the callback URL" } }
					}
				}
			}, async (ctx) => {
				const { code, state, error, error_description } = ctx.query;
				const stateData = await (0, better_auth_oauth2.parseState)(ctx);
				if (!stateData) {
					const errorURL2 = ctx.context.options.onAPIError?.errorURL || `${ctx.context.baseURL}/error`;
					throw ctx.redirect(`${errorURL2}?error=invalid_state`);
				}
				const { callbackURL, errorURL, newUserURL, requestSignUp } = stateData;
				if (!code || error) throw ctx.redirect(`${errorURL || callbackURL}?error=${error}&error_description=${error_description}`);
				let provider = null;
				if (options?.defaultSSO?.length) {
					const matchingDefault = options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === ctx.params.providerId);
					if (matchingDefault) provider = {
						...matchingDefault,
						issuer: matchingDefault.oidcConfig?.issuer || "",
						userId: "default"
					};
				}
				if (!provider) provider = await ctx.context.adapter.findOne({
					model: "ssoProvider",
					where: [{
						field: "providerId",
						value: ctx.params.providerId
					}]
				}).then((res) => {
					if (!res) return null;
					return {
						...res,
						oidcConfig: safeJsonParse(res.oidcConfig) || void 0
					};
				});
				if (!provider) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=provider not found`);
				let config = provider.oidcConfig;
				if (!config) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=provider not found`);
				const discovery = await require_index$1.betterFetch(config.discoveryEndpoint);
				if (discovery.data) config = {
					tokenEndpoint: discovery.data.token_endpoint,
					tokenEndpointAuthentication: discovery.data.token_endpoint_auth_method,
					userInfoEndpoint: discovery.data.userinfo_endpoint,
					scopes: [
						"openid",
						"email",
						"profile",
						"offline_access"
					],
					...config
				};
				if (!config.tokenEndpoint) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=token_endpoint_not_found`);
				const tokenResponse = await (0, better_auth_oauth2.validateAuthorizationCode)({
					code,
					codeVerifier: config.pkce ? stateData.codeVerifier : void 0,
					redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`,
					options: {
						clientId: config.clientId,
						clientSecret: config.clientSecret
					},
					tokenEndpoint: config.tokenEndpoint,
					authentication: config.tokenEndpointAuthentication === "client_secret_post" ? "post" : "basic"
				}).catch((e) => {
					if (e instanceof require_index$1.BetterFetchError) throw ctx.redirect(`${errorURL || callbackURL}?error=invalid_provider&error_description=${e.message}`);
					return null;
				});
				if (!tokenResponse) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=token_response_not_found`);
				let userInfo = null;
				if (tokenResponse.idToken) {
					const idToken = require_decode_jwt.decodeJwt(tokenResponse.idToken);
					if (!config.jwksEndpoint) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=jwks_endpoint_not_found`);
					const verified = await (0, better_auth_oauth2.validateToken)(tokenResponse.idToken, config.jwksEndpoint).catch((e) => {
						ctx.context.logger.error(e);
						return null;
					});
					if (!verified) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=token_not_verified`);
					if (verified.payload.iss !== provider.issuer) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=issuer_mismatch`);
					const mapping = config.mapping || {};
					userInfo = {
						...Object.fromEntries(Object.entries(mapping.extraFields || {}).map(([key, value]) => [key, verified.payload[value]])),
						id: idToken[mapping.id || "sub"],
						email: idToken[mapping.email || "email"],
						emailVerified: options?.trustEmailVerified ? idToken[mapping.emailVerified || "email_verified"] : false,
						name: idToken[mapping.name || "name"],
						image: idToken[mapping.image || "picture"]
					};
				}
				if (!userInfo) {
					if (!config.userInfoEndpoint) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=user_info_endpoint_not_found`);
					const userInfoResponse = await require_index$1.betterFetch(config.userInfoEndpoint, { headers: { Authorization: `Bearer ${tokenResponse.accessToken}` } });
					if (userInfoResponse.error) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=${userInfoResponse.error.message}`);
					userInfo = userInfoResponse.data;
				}
				if (!userInfo.email || !userInfo.id) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=missing_user_info`);
				const linked = await (0, better_auth_oauth2.handleOAuthUserInfo)(ctx, {
					userInfo: {
						email: userInfo.email,
						name: userInfo.name || userInfo.email,
						id: userInfo.id,
						image: userInfo.image,
						emailVerified: options?.trustEmailVerified ? userInfo.emailVerified || false : false
					},
					account: {
						idToken: tokenResponse.idToken,
						accessToken: tokenResponse.accessToken,
						refreshToken: tokenResponse.refreshToken,
						accountId: userInfo.id,
						providerId: provider.providerId,
						accessTokenExpiresAt: tokenResponse.accessTokenExpiresAt,
						refreshTokenExpiresAt: tokenResponse.refreshTokenExpiresAt,
						scope: tokenResponse.scopes?.join(",")
					},
					callbackURL,
					disableSignUp: options?.disableImplicitSignUp && !requestSignUp,
					overrideUserInfo: config.overrideUserInfo
				});
				if (linked.error) throw ctx.redirect(`${errorURL || callbackURL}/error?error=${linked.error}`);
				const { session, user } = linked.data;
				if (options?.provisionUser) await options.provisionUser({
					user,
					userInfo,
					token: tokenResponse,
					provider
				});
				if (provider.organizationId && !options?.organizationProvisioning?.disabled) {
					if (ctx.context.options.plugins?.find((plugin) => plugin.id === "organization")) {
						if (!await ctx.context.adapter.findOne({
							model: "member",
							where: [{
								field: "organizationId",
								value: provider.organizationId
							}, {
								field: "userId",
								value: user.id
							}]
						})) {
							const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({
								user,
								userInfo,
								token: tokenResponse,
								provider
							}) : options?.organizationProvisioning?.defaultRole || "member";
							await ctx.context.adapter.create({
								model: "member",
								data: {
									organizationId: provider.organizationId,
									userId: user.id,
									role,
									createdAt: /* @__PURE__ */ new Date(),
									updatedAt: /* @__PURE__ */ new Date()
								}
							});
						}
					}
				}
				await (0, better_auth_cookies.setSessionCookie)(ctx, {
					session,
					user
				});
				let toRedirectTo;
				try {
					toRedirectTo = (linked.isRegister ? newUserURL || callbackURL : callbackURL).toString();
				} catch {
					toRedirectTo = linked.isRegister ? newUserURL || callbackURL : callbackURL;
				}
				throw ctx.redirect(toRedirectTo);
			}),
			callbackSSOSAML: (0, better_auth_plugins.createAuthEndpoint)("/sso/saml2/callback/:providerId", {
				method: "POST",
				body: require_schemas.object({
					SAMLResponse: require_schemas.string(),
					RelayState: require_schemas.string().optional()
				}),
				metadata: {
					isAction: false,
					openapi: {
						summary: "Callback URL for SAML provider",
						description: "This endpoint is used as the callback URL for SAML providers.",
						responses: {
							"302": { description: "Redirects to the callback URL" },
							"400": { description: "Invalid SAML response" },
							"401": { description: "Unauthorized - SAML authentication failed" }
						}
					}
				}
			}, async (ctx) => {
				const { SAMLResponse, RelayState } = ctx.body;
				const { providerId } = ctx.params;
				let provider = null;
				if (options?.defaultSSO?.length) {
					const matchingDefault = options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === providerId);
					if (matchingDefault) provider = {
						...matchingDefault,
						userId: "default",
						issuer: matchingDefault.samlConfig?.issuer || ""
					};
				}
				if (!provider) provider = await ctx.context.adapter.findOne({
					model: "ssoProvider",
					where: [{
						field: "providerId",
						value: providerId
					}]
				}).then((res) => {
					if (!res) return null;
					return {
						...res,
						samlConfig: res.samlConfig ? safeJsonParse(res.samlConfig) || void 0 : void 0
					};
				});
				if (!provider) throw new better_auth_api.APIError("NOT_FOUND", { message: "No provider found for the given providerId" });
				const parsedSamlConfig = safeJsonParse(provider.samlConfig);
				if (!parsedSamlConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SAML configuration" });
				const idpData = parsedSamlConfig.idpMetadata;
				let idp = null;
				if (!idpData?.metadata) idp = import_build.IdentityProvider({
					entityID: idpData?.entityID || parsedSamlConfig.issuer,
					singleSignOnService: [{
						Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
						Location: parsedSamlConfig.entryPoint
					}],
					signingCert: idpData?.cert || parsedSamlConfig.cert,
					wantAuthnRequestsSigned: parsedSamlConfig.wantAssertionsSigned || false,
					isAssertionEncrypted: idpData?.isAssertionEncrypted || false,
					encPrivateKey: idpData?.encPrivateKey,
					encPrivateKeyPass: idpData?.encPrivateKeyPass
				});
				else idp = import_build.IdentityProvider({
					metadata: idpData.metadata,
					privateKey: idpData.privateKey,
					privateKeyPass: idpData.privateKeyPass,
					isAssertionEncrypted: idpData.isAssertionEncrypted,
					encPrivateKey: idpData.encPrivateKey,
					encPrivateKeyPass: idpData.encPrivateKeyPass
				});
				const spData = parsedSamlConfig.spMetadata;
				const sp = import_build.ServiceProvider({
					metadata: spData?.metadata,
					entityID: spData?.entityID || parsedSamlConfig.issuer,
					assertionConsumerService: spData?.metadata ? void 0 : [{
						Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
						Location: parsedSamlConfig.callbackUrl
					}],
					privateKey: spData?.privateKey || parsedSamlConfig.privateKey,
					privateKeyPass: spData?.privateKeyPass,
					isAssertionEncrypted: spData?.isAssertionEncrypted || false,
					encPrivateKey: spData?.encPrivateKey,
					encPrivateKeyPass: spData?.encPrivateKeyPass,
					wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
					nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : void 0
				});
				let parsedResponse;
				try {
					const decodedResponse = Buffer.from(SAMLResponse, "base64").toString("utf-8");
					try {
						parsedResponse = await sp.parseLoginResponse(idp, "post", { body: {
							SAMLResponse,
							RelayState: RelayState || void 0
						} });
					} catch (parseError) {
						const nameIDMatch = decodedResponse.match(/<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/);
						if (!nameIDMatch) throw parseError;
						parsedResponse = { extract: {
							nameID: nameIDMatch[1],
							attributes: { nameID: nameIDMatch[1] },
							sessionIndex: {},
							conditions: {}
						} };
					}
					if (!parsedResponse?.extract) throw new Error("Invalid SAML response structure");
				} catch (error) {
					ctx.context.logger.error("SAML response validation failed", {
						error,
						decodedResponse: Buffer.from(SAMLResponse, "base64").toString("utf-8")
					});
					throw new better_auth_api.APIError("BAD_REQUEST", {
						message: "Invalid SAML response",
						details: error instanceof Error ? error.message : String(error)
					});
				}
				const { extract } = parsedResponse;
				const attributes = extract.attributes || {};
				const mapping = parsedSamlConfig.mapping ?? {};
				const userInfo = {
					...Object.fromEntries(Object.entries(mapping.extraFields || {}).map(([key, value]) => [key, attributes[value]])),
					id: attributes[mapping.id || "nameID"] || extract.nameID,
					email: attributes[mapping.email || "email"] || extract.nameID,
					name: [attributes[mapping.firstName || "givenName"], attributes[mapping.lastName || "surname"]].filter(Boolean).join(" ") || attributes[mapping.name || "displayName"] || extract.nameID,
					emailVerified: options?.trustEmailVerified && mapping.emailVerified ? attributes[mapping.emailVerified] || false : false
				};
				if (!userInfo.id || !userInfo.email) {
					ctx.context.logger.error("Missing essential user info from SAML response", {
						attributes: Object.keys(attributes),
						mapping,
						extractedId: userInfo.id,
						extractedEmail: userInfo.email
					});
					throw new better_auth_api.APIError("BAD_REQUEST", { message: "Unable to extract user ID or email from SAML response" });
				}
				let user;
				const existingUser = await ctx.context.adapter.findOne({
					model: "user",
					where: [{
						field: "email",
						value: userInfo.email
					}]
				});
				if (existingUser) user = existingUser;
				else user = await ctx.context.adapter.create({
					model: "user",
					data: {
						email: userInfo.email,
						name: userInfo.name,
						emailVerified: userInfo.emailVerified,
						createdAt: /* @__PURE__ */ new Date(),
						updatedAt: /* @__PURE__ */ new Date()
					}
				});
				if (!await ctx.context.adapter.findOne({
					model: "account",
					where: [
						{
							field: "userId",
							value: user.id
						},
						{
							field: "providerId",
							value: provider.providerId
						},
						{
							field: "accountId",
							value: userInfo.id
						}
					]
				})) await ctx.context.adapter.create({
					model: "account",
					data: {
						userId: user.id,
						providerId: provider.providerId,
						accountId: userInfo.id,
						createdAt: /* @__PURE__ */ new Date(),
						updatedAt: /* @__PURE__ */ new Date(),
						accessToken: "",
						refreshToken: ""
					}
				});
				if (options?.provisionUser) await options.provisionUser({
					user,
					userInfo,
					provider
				});
				if (provider.organizationId && !options?.organizationProvisioning?.disabled) {
					if (ctx.context.options.plugins?.find((plugin) => plugin.id === "organization")) {
						if (!await ctx.context.adapter.findOne({
							model: "member",
							where: [{
								field: "organizationId",
								value: provider.organizationId
							}, {
								field: "userId",
								value: user.id
							}]
						})) {
							const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({
								user,
								userInfo,
								provider
							}) : options?.organizationProvisioning?.defaultRole || "member";
							await ctx.context.adapter.create({
								model: "member",
								data: {
									organizationId: provider.organizationId,
									userId: user.id,
									role,
									createdAt: /* @__PURE__ */ new Date(),
									updatedAt: /* @__PURE__ */ new Date()
								}
							});
						}
					}
				}
				await (0, better_auth_cookies.setSessionCookie)(ctx, {
					session: await ctx.context.internalAdapter.createSession(user.id, ctx),
					user
				});
				const callbackUrl = RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
				throw ctx.redirect(callbackUrl);
			}),
			acsEndpoint: (0, better_auth_plugins.createAuthEndpoint)("/sso/saml2/sp/acs/:providerId", {
				method: "POST",
				params: require_schemas.object({ providerId: require_schemas.string().optional() }),
				body: require_schemas.object({
					SAMLResponse: require_schemas.string(),
					RelayState: require_schemas.string().optional()
				}),
				metadata: {
					isAction: false,
					openapi: {
						summary: "SAML Assertion Consumer Service",
						description: "Handles SAML responses from IdP after successful authentication",
						responses: { "302": { description: "Redirects to the callback URL after successful authentication" } }
					}
				}
			}, async (ctx) => {
				const { SAMLResponse, RelayState = "" } = ctx.body;
				const { providerId } = ctx.params;
				let provider = null;
				if (options?.defaultSSO?.length) {
					const matchingDefault = providerId ? options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === providerId) : options.defaultSSO[0];
					if (matchingDefault) provider = {
						issuer: matchingDefault.samlConfig?.issuer || "",
						providerId: matchingDefault.providerId,
						userId: "default",
						samlConfig: matchingDefault.samlConfig
					};
				} else provider = await ctx.context.adapter.findOne({
					model: "ssoProvider",
					where: [{
						field: "providerId",
						value: providerId ?? "sso"
					}]
				}).then((res) => {
					if (!res) return null;
					return {
						...res,
						samlConfig: res.samlConfig ? safeJsonParse(res.samlConfig) || void 0 : void 0
					};
				});
				if (!provider?.samlConfig) throw new better_auth_api.APIError("NOT_FOUND", { message: "No SAML provider found" });
				const parsedSamlConfig = provider.samlConfig;
				const sp = import_build.ServiceProvider({
					entityID: parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
					assertionConsumerService: [{
						Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
						Location: parsedSamlConfig.callbackUrl || `${ctx.context.baseURL}/sso/saml2/sp/acs/${providerId}`
					}],
					wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
					metadata: parsedSamlConfig.spMetadata?.metadata,
					privateKey: parsedSamlConfig.spMetadata?.privateKey || parsedSamlConfig.privateKey,
					privateKeyPass: parsedSamlConfig.spMetadata?.privateKeyPass,
					nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : void 0
				});
				const idpData = parsedSamlConfig.idpMetadata;
				const idp = !idpData?.metadata ? import_build.IdentityProvider({
					entityID: idpData?.entityID || parsedSamlConfig.issuer,
					singleSignOnService: idpData?.singleSignOnService || [{
						Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
						Location: parsedSamlConfig.entryPoint
					}],
					signingCert: idpData?.cert || parsedSamlConfig.cert
				}) : import_build.IdentityProvider({ metadata: idpData.metadata });
				let parsedResponse;
				try {
					let decodedResponse = Buffer.from(SAMLResponse, "base64").toString("utf-8");
					if (!decodedResponse.includes("StatusCode")) {
						const insertPoint = decodedResponse.indexOf("</saml2:Issuer>");
						if (insertPoint !== -1) decodedResponse = decodedResponse.slice(0, insertPoint + 14) + "<saml2:Status><saml2:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/></saml2:Status>" + decodedResponse.slice(insertPoint + 14);
					} else if (!decodedResponse.includes("saml2:Success")) decodedResponse = decodedResponse.replace(/<saml2:StatusCode Value="[^"]+"/, "<saml2:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"");
					try {
						parsedResponse = await sp.parseLoginResponse(idp, "post", { body: {
							SAMLResponse,
							RelayState: RelayState || void 0
						} });
					} catch (parseError) {
						const nameIDMatch = decodedResponse.match(/<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/);
						if (!nameIDMatch) throw parseError;
						parsedResponse = { extract: {
							nameID: nameIDMatch[1],
							attributes: { nameID: nameIDMatch[1] },
							sessionIndex: {},
							conditions: {}
						} };
					}
					if (!parsedResponse?.extract) throw new Error("Invalid SAML response structure");
				} catch (error) {
					ctx.context.logger.error("SAML response validation failed", {
						error,
						decodedResponse: Buffer.from(SAMLResponse, "base64").toString("utf-8")
					});
					throw new better_auth_api.APIError("BAD_REQUEST", {
						message: "Invalid SAML response",
						details: error instanceof Error ? error.message : String(error)
					});
				}
				const { extract } = parsedResponse;
				const attributes = extract.attributes || {};
				const mapping = parsedSamlConfig.mapping ?? {};
				const userInfo = {
					...Object.fromEntries(Object.entries(mapping.extraFields || {}).map(([key, value]) => [key, attributes[value]])),
					id: attributes[mapping.id || "nameID"] || extract.nameID,
					email: attributes[mapping.email || "email"] || extract.nameID,
					name: [attributes[mapping.firstName || "givenName"], attributes[mapping.lastName || "surname"]].filter(Boolean).join(" ") || attributes[mapping.name || "displayName"] || extract.nameID,
					emailVerified: options?.trustEmailVerified && mapping.emailVerified ? attributes[mapping.emailVerified] || false : false
				};
				if (!userInfo.id || !userInfo.email) {
					ctx.context.logger.error("Missing essential user info from SAML response", {
						attributes: Object.keys(attributes),
						mapping,
						extractedId: userInfo.id,
						extractedEmail: userInfo.email
					});
					throw new better_auth_api.APIError("BAD_REQUEST", { message: "Unable to extract user ID or email from SAML response" });
				}
				let user;
				const existingUser = await ctx.context.adapter.findOne({
					model: "user",
					where: [{
						field: "email",
						value: userInfo.email
					}]
				});
				if (existingUser) {
					if (!await ctx.context.adapter.findOne({
						model: "account",
						where: [
							{
								field: "userId",
								value: existingUser.id
							},
							{
								field: "providerId",
								value: provider.providerId
							},
							{
								field: "accountId",
								value: userInfo.id
							}
						]
					})) {
						if (!ctx.context.options.account?.accountLinking?.trustedProviders?.includes(provider.providerId)) throw ctx.redirect(`${parsedSamlConfig.callbackUrl}?error=account_not_found`);
						await ctx.context.adapter.create({
							model: "account",
							data: {
								userId: existingUser.id,
								providerId: provider.providerId,
								accountId: userInfo.id,
								createdAt: /* @__PURE__ */ new Date(),
								updatedAt: /* @__PURE__ */ new Date(),
								accessToken: "",
								refreshToken: ""
							}
						});
					}
					user = existingUser;
				} else {
					user = await ctx.context.adapter.create({
						model: "user",
						data: {
							email: userInfo.email,
							name: userInfo.name,
							emailVerified: options?.trustEmailVerified ? userInfo.emailVerified || false : false,
							createdAt: /* @__PURE__ */ new Date(),
							updatedAt: /* @__PURE__ */ new Date()
						}
					});
					await ctx.context.adapter.create({
						model: "account",
						data: {
							userId: user.id,
							providerId: provider.providerId,
							accountId: userInfo.id,
							accessToken: "",
							refreshToken: "",
							accessTokenExpiresAt: /* @__PURE__ */ new Date(),
							refreshTokenExpiresAt: /* @__PURE__ */ new Date(),
							scope: "",
							createdAt: /* @__PURE__ */ new Date(),
							updatedAt: /* @__PURE__ */ new Date()
						}
					});
				}
				if (options?.provisionUser) await options.provisionUser({
					user,
					userInfo,
					provider
				});
				if (provider.organizationId && !options?.organizationProvisioning?.disabled) {
					if (ctx.context.options.plugins?.find((plugin) => plugin.id === "organization")) {
						if (!await ctx.context.adapter.findOne({
							model: "member",
							where: [{
								field: "organizationId",
								value: provider.organizationId
							}, {
								field: "userId",
								value: user.id
							}]
						})) {
							const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({
								user,
								userInfo,
								provider
							}) : options?.organizationProvisioning?.defaultRole || "member";
							await ctx.context.adapter.create({
								model: "member",
								data: {
									organizationId: provider.organizationId,
									userId: user.id,
									role,
									createdAt: /* @__PURE__ */ new Date(),
									updatedAt: /* @__PURE__ */ new Date()
								}
							});
						}
					}
				}
				await (0, better_auth_cookies.setSessionCookie)(ctx, {
					session: await ctx.context.internalAdapter.createSession(user.id, ctx),
					user
				});
				const callbackUrl = RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
				throw ctx.redirect(callbackUrl);
			})
		},
		schema: { ssoProvider: { fields: {
			issuer: {
				type: "string",
				required: true
			},
			oidcConfig: {
				type: "string",
				required: false
			},
			samlConfig: {
				type: "string",
				required: false
			},
			userId: {
				type: "string",
				references: {
					model: "user",
					field: "id"
				}
			},
			providerId: {
				type: "string",
				required: true,
				unique: true
			},
			organizationId: {
				type: "string",
				required: false
			},
			domain: {
				type: "string",
				required: true
			}
		} } }
	};
};

//#endregion
exports.sso = sso;
//# sourceMappingURL=index.cjs.map