@better-auth/sso 1.4.0-beta.14 → 1.4.0-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1256 +0,0 @@
1
- //#region rolldown:runtime
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
- key = keys[i];
11
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
- get: ((k) => from[k]).bind(null, key),
13
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
- });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
- value: mod,
20
- enumerable: true
21
- }) : target, mod));
22
-
23
- //#endregion
24
- let __better_fetch_fetch = require("@better-fetch/fetch");
25
- __better_fetch_fetch = __toESM(__better_fetch_fetch);
26
- let better_auth = require("better-auth");
27
- better_auth = __toESM(better_auth);
28
- let better_auth_api = require("better-auth/api");
29
- better_auth_api = __toESM(better_auth_api);
30
- let better_auth_cookies = require("better-auth/cookies");
31
- better_auth_cookies = __toESM(better_auth_cookies);
32
- let better_auth_oauth2 = require("better-auth/oauth2");
33
- better_auth_oauth2 = __toESM(better_auth_oauth2);
34
- let better_auth_plugins = require("better-auth/plugins");
35
- better_auth_plugins = __toESM(better_auth_plugins);
36
- let fast_xml_parser = require("fast-xml-parser");
37
- fast_xml_parser = __toESM(fast_xml_parser);
38
- let jose = require("jose");
39
- jose = __toESM(jose);
40
- let samlify = require("samlify");
41
- samlify = __toESM(samlify);
42
- let zod_v4 = require("zod/v4");
43
- zod_v4 = __toESM(zod_v4);
44
-
45
- //#region src/index.ts
46
- samlify.setSchemaValidator({ async validate(xml) {
47
- if (fast_xml_parser.XMLValidator.validate(xml, { allowBooleanAttributes: true }) === true) return "SUCCESS_VALIDATE_XML";
48
- throw "ERR_INVALID_XML";
49
- } });
50
- /**
51
- * Safely parses a value that might be a JSON string or already a parsed object
52
- * This handles cases where ORMs like Drizzle might return already parsed objects
53
- * instead of JSON strings from TEXT/JSON columns
54
- */
55
- function safeJsonParse(value) {
56
- if (!value) return null;
57
- if (typeof value === "object") return value;
58
- if (typeof value === "string") try {
59
- return JSON.parse(value);
60
- } catch (error) {
61
- throw new Error(`Failed to parse JSON: ${error instanceof Error ? error.message : "Unknown error"}`);
62
- }
63
- return null;
64
- }
65
- const sso = (options) => {
66
- return {
67
- id: "sso",
68
- endpoints: {
69
- spMetadata: (0, better_auth_plugins.createAuthEndpoint)("/sso/saml2/sp/metadata", {
70
- method: "GET",
71
- query: zod_v4.object({
72
- providerId: zod_v4.string(),
73
- format: zod_v4.enum(["xml", "json"]).default("xml")
74
- }),
75
- metadata: { openapi: {
76
- summary: "Get Service Provider metadata",
77
- description: "Returns the SAML metadata for the Service Provider",
78
- responses: { "200": { description: "SAML metadata in XML format" } }
79
- } }
80
- }, async (ctx) => {
81
- const provider = await ctx.context.adapter.findOne({
82
- model: "ssoProvider",
83
- where: [{
84
- field: "providerId",
85
- value: ctx.query.providerId
86
- }]
87
- });
88
- if (!provider) throw new better_auth_api.APIError("NOT_FOUND", { message: "No provider found for the given providerId" });
89
- const parsedSamlConfig = safeJsonParse(provider.samlConfig);
90
- if (!parsedSamlConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SAML configuration" });
91
- const sp = parsedSamlConfig.spMetadata.metadata ? samlify.ServiceProvider({ metadata: parsedSamlConfig.spMetadata.metadata }) : samlify.SPMetadata({
92
- entityID: parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
93
- assertionConsumerService: [{
94
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
95
- Location: parsedSamlConfig.callbackUrl || `${ctx.context.baseURL}/sso/saml2/sp/acs/${provider.id}`
96
- }],
97
- wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
98
- nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : void 0
99
- });
100
- return new Response(sp.getMetadata(), { headers: { "Content-Type": "application/xml" } });
101
- }),
102
- registerSSOProvider: (0, better_auth_plugins.createAuthEndpoint)("/sso/register", {
103
- method: "POST",
104
- body: zod_v4.object({
105
- providerId: zod_v4.string({}).meta({ description: "The ID of the provider. This is used to identify the provider during login and callback" }),
106
- issuer: zod_v4.string({}).meta({ description: "The issuer of the provider" }),
107
- domain: zod_v4.string({}).meta({ description: "The domain of the provider. This is used for email matching" }),
108
- oidcConfig: zod_v4.object({
109
- clientId: zod_v4.string({}).meta({ description: "The client ID" }),
110
- clientSecret: zod_v4.string({}).meta({ description: "The client secret" }),
111
- authorizationEndpoint: zod_v4.string({}).meta({ description: "The authorization endpoint" }).optional(),
112
- tokenEndpoint: zod_v4.string({}).meta({ description: "The token endpoint" }).optional(),
113
- userInfoEndpoint: zod_v4.string({}).meta({ description: "The user info endpoint" }).optional(),
114
- tokenEndpointAuthentication: zod_v4.enum(["client_secret_post", "client_secret_basic"]).optional(),
115
- jwksEndpoint: zod_v4.string({}).meta({ description: "The JWKS endpoint" }).optional(),
116
- discoveryEndpoint: zod_v4.string().optional(),
117
- scopes: zod_v4.array(zod_v4.string(), {}).meta({ description: "The scopes to request. Defaults to ['openid', 'email', 'profile', 'offline_access']" }).optional(),
118
- pkce: zod_v4.boolean({}).meta({ description: "Whether to use PKCE for the authorization flow" }).default(true).optional(),
119
- mapping: zod_v4.object({
120
- id: zod_v4.string({}).meta({ description: "Field mapping for user ID (defaults to 'sub')" }),
121
- email: zod_v4.string({}).meta({ description: "Field mapping for email (defaults to 'email')" }),
122
- emailVerified: zod_v4.string({}).meta({ description: "Field mapping for email verification (defaults to 'email_verified')" }).optional(),
123
- name: zod_v4.string({}).meta({ description: "Field mapping for name (defaults to 'name')" }),
124
- image: zod_v4.string({}).meta({ description: "Field mapping for image (defaults to 'picture')" }).optional(),
125
- extraFields: zod_v4.record(zod_v4.string(), zod_v4.any()).optional()
126
- }).optional()
127
- }).optional(),
128
- samlConfig: zod_v4.object({
129
- entryPoint: zod_v4.string({}).meta({ description: "The entry point of the provider" }),
130
- cert: zod_v4.string({}).meta({ description: "The certificate of the provider" }),
131
- callbackUrl: zod_v4.string({}).meta({ description: "The callback URL of the provider" }),
132
- audience: zod_v4.string().optional(),
133
- idpMetadata: zod_v4.object({
134
- metadata: zod_v4.string().optional(),
135
- entityID: zod_v4.string().optional(),
136
- cert: zod_v4.string().optional(),
137
- privateKey: zod_v4.string().optional(),
138
- privateKeyPass: zod_v4.string().optional(),
139
- isAssertionEncrypted: zod_v4.boolean().optional(),
140
- encPrivateKey: zod_v4.string().optional(),
141
- encPrivateKeyPass: zod_v4.string().optional(),
142
- singleSignOnService: zod_v4.array(zod_v4.object({
143
- Binding: zod_v4.string().meta({ description: "The binding type for the SSO service" }),
144
- Location: zod_v4.string().meta({ description: "The URL for the SSO service" })
145
- })).optional().meta({ description: "Single Sign-On service configuration" })
146
- }).optional(),
147
- spMetadata: zod_v4.object({
148
- metadata: zod_v4.string().optional(),
149
- entityID: zod_v4.string().optional(),
150
- binding: zod_v4.string().optional(),
151
- privateKey: zod_v4.string().optional(),
152
- privateKeyPass: zod_v4.string().optional(),
153
- isAssertionEncrypted: zod_v4.boolean().optional(),
154
- encPrivateKey: zod_v4.string().optional(),
155
- encPrivateKeyPass: zod_v4.string().optional()
156
- }),
157
- wantAssertionsSigned: zod_v4.boolean().optional(),
158
- signatureAlgorithm: zod_v4.string().optional(),
159
- digestAlgorithm: zod_v4.string().optional(),
160
- identifierFormat: zod_v4.string().optional(),
161
- privateKey: zod_v4.string().optional(),
162
- decryptionPvk: zod_v4.string().optional(),
163
- additionalParams: zod_v4.record(zod_v4.string(), zod_v4.any()).optional(),
164
- mapping: zod_v4.object({
165
- id: zod_v4.string({}).meta({ description: "Field mapping for user ID (defaults to 'nameID')" }),
166
- email: zod_v4.string({}).meta({ description: "Field mapping for email (defaults to 'email')" }),
167
- emailVerified: zod_v4.string({}).meta({ description: "Field mapping for email verification" }).optional(),
168
- name: zod_v4.string({}).meta({ description: "Field mapping for name (defaults to 'displayName')" }),
169
- firstName: zod_v4.string({}).meta({ description: "Field mapping for first name (defaults to 'givenName')" }).optional(),
170
- lastName: zod_v4.string({}).meta({ description: "Field mapping for last name (defaults to 'surname')" }).optional(),
171
- extraFields: zod_v4.record(zod_v4.string(), zod_v4.any()).optional()
172
- }).optional()
173
- }).optional(),
174
- organizationId: zod_v4.string({}).meta({ description: "If organization plugin is enabled, the organization id to link the provider to" }).optional(),
175
- overrideUserInfo: zod_v4.boolean({}).meta({ description: "Override user info with the provider info. Defaults to false" }).default(false).optional()
176
- }),
177
- use: [better_auth_api.sessionMiddleware],
178
- metadata: { openapi: {
179
- summary: "Register an OIDC provider",
180
- description: "This endpoint is used to register an OIDC provider. This is used to configure the provider and link it to an organization",
181
- responses: { "200": {
182
- description: "OIDC provider created successfully",
183
- content: { "application/json": { schema: {
184
- type: "object",
185
- properties: {
186
- issuer: {
187
- type: "string",
188
- format: "uri",
189
- description: "The issuer URL of the provider"
190
- },
191
- domain: {
192
- type: "string",
193
- description: "The domain of the provider, used for email matching"
194
- },
195
- oidcConfig: {
196
- type: "object",
197
- properties: {
198
- issuer: {
199
- type: "string",
200
- format: "uri",
201
- description: "The issuer URL of the provider"
202
- },
203
- pkce: {
204
- type: "boolean",
205
- description: "Whether PKCE is enabled for the authorization flow"
206
- },
207
- clientId: {
208
- type: "string",
209
- description: "The client ID for the provider"
210
- },
211
- clientSecret: {
212
- type: "string",
213
- description: "The client secret for the provider"
214
- },
215
- authorizationEndpoint: {
216
- type: "string",
217
- format: "uri",
218
- nullable: true,
219
- description: "The authorization endpoint URL"
220
- },
221
- discoveryEndpoint: {
222
- type: "string",
223
- format: "uri",
224
- description: "The discovery endpoint URL"
225
- },
226
- userInfoEndpoint: {
227
- type: "string",
228
- format: "uri",
229
- nullable: true,
230
- description: "The user info endpoint URL"
231
- },
232
- scopes: {
233
- type: "array",
234
- items: { type: "string" },
235
- nullable: true,
236
- description: "The scopes requested from the provider"
237
- },
238
- tokenEndpoint: {
239
- type: "string",
240
- format: "uri",
241
- nullable: true,
242
- description: "The token endpoint URL"
243
- },
244
- tokenEndpointAuthentication: {
245
- type: "string",
246
- enum: ["client_secret_post", "client_secret_basic"],
247
- nullable: true,
248
- description: "Authentication method for the token endpoint"
249
- },
250
- jwksEndpoint: {
251
- type: "string",
252
- format: "uri",
253
- nullable: true,
254
- description: "The JWKS endpoint URL"
255
- },
256
- mapping: {
257
- type: "object",
258
- nullable: true,
259
- properties: {
260
- id: {
261
- type: "string",
262
- description: "Field mapping for user ID (defaults to 'sub')"
263
- },
264
- email: {
265
- type: "string",
266
- description: "Field mapping for email (defaults to 'email')"
267
- },
268
- emailVerified: {
269
- type: "string",
270
- nullable: true,
271
- description: "Field mapping for email verification (defaults to 'email_verified')"
272
- },
273
- name: {
274
- type: "string",
275
- description: "Field mapping for name (defaults to 'name')"
276
- },
277
- image: {
278
- type: "string",
279
- nullable: true,
280
- description: "Field mapping for image (defaults to 'picture')"
281
- },
282
- extraFields: {
283
- type: "object",
284
- additionalProperties: { type: "string" },
285
- nullable: true,
286
- description: "Additional field mappings"
287
- }
288
- },
289
- required: [
290
- "id",
291
- "email",
292
- "name"
293
- ]
294
- }
295
- },
296
- required: [
297
- "issuer",
298
- "pkce",
299
- "clientId",
300
- "clientSecret",
301
- "discoveryEndpoint"
302
- ],
303
- description: "OIDC configuration for the provider"
304
- },
305
- organizationId: {
306
- type: "string",
307
- nullable: true,
308
- description: "ID of the linked organization, if any"
309
- },
310
- userId: {
311
- type: "string",
312
- description: "ID of the user who registered the provider"
313
- },
314
- providerId: {
315
- type: "string",
316
- description: "Unique identifier for the provider"
317
- },
318
- redirectURI: {
319
- type: "string",
320
- format: "uri",
321
- description: "The redirect URI for the provider callback"
322
- }
323
- },
324
- required: [
325
- "issuer",
326
- "domain",
327
- "oidcConfig",
328
- "userId",
329
- "providerId",
330
- "redirectURI"
331
- ]
332
- } } }
333
- } }
334
- } }
335
- }, async (ctx) => {
336
- const user = ctx.context.session?.user;
337
- if (!user) throw new better_auth_api.APIError("UNAUTHORIZED");
338
- const limit = typeof options?.providersLimit === "function" ? await options.providersLimit(user) : options?.providersLimit ?? 10;
339
- if (!limit) throw new better_auth_api.APIError("FORBIDDEN", { message: "SSO provider registration is disabled" });
340
- if ((await ctx.context.adapter.findMany({
341
- model: "ssoProvider",
342
- where: [{
343
- field: "userId",
344
- value: user.id
345
- }]
346
- })).length >= limit) throw new better_auth_api.APIError("FORBIDDEN", { message: "You have reached the maximum number of SSO providers" });
347
- const body = ctx.body;
348
- if (zod_v4.string().url().safeParse(body.issuer).error) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid issuer. Must be a valid URL" });
349
- if (ctx.body.organizationId) {
350
- if (!await ctx.context.adapter.findOne({
351
- model: "member",
352
- where: [{
353
- field: "userId",
354
- value: user.id
355
- }, {
356
- field: "organizationId",
357
- value: ctx.body.organizationId
358
- }]
359
- })) throw new better_auth_api.APIError("BAD_REQUEST", { message: "You are not a member of the organization" });
360
- }
361
- if (await ctx.context.adapter.findOne({
362
- model: "ssoProvider",
363
- where: [{
364
- field: "providerId",
365
- value: body.providerId
366
- }]
367
- })) {
368
- ctx.context.logger.info(`SSO provider creation attempt with existing providerId: ${body.providerId}`);
369
- throw new better_auth_api.APIError("UNPROCESSABLE_ENTITY", { message: "SSO provider with this providerId already exists" });
370
- }
371
- const provider = await ctx.context.adapter.create({
372
- model: "ssoProvider",
373
- data: {
374
- issuer: body.issuer,
375
- domain: body.domain,
376
- oidcConfig: body.oidcConfig ? JSON.stringify({
377
- issuer: body.issuer,
378
- clientId: body.oidcConfig.clientId,
379
- clientSecret: body.oidcConfig.clientSecret,
380
- authorizationEndpoint: body.oidcConfig.authorizationEndpoint,
381
- tokenEndpoint: body.oidcConfig.tokenEndpoint,
382
- tokenEndpointAuthentication: body.oidcConfig.tokenEndpointAuthentication,
383
- jwksEndpoint: body.oidcConfig.jwksEndpoint,
384
- pkce: body.oidcConfig.pkce,
385
- discoveryEndpoint: body.oidcConfig.discoveryEndpoint || `${body.issuer}/.well-known/openid-configuration`,
386
- mapping: body.oidcConfig.mapping,
387
- scopes: body.oidcConfig.scopes,
388
- userInfoEndpoint: body.oidcConfig.userInfoEndpoint,
389
- overrideUserInfo: ctx.body.overrideUserInfo || options?.defaultOverrideUserInfo || false
390
- }) : null,
391
- samlConfig: body.samlConfig ? JSON.stringify({
392
- issuer: body.issuer,
393
- entryPoint: body.samlConfig.entryPoint,
394
- cert: body.samlConfig.cert,
395
- callbackUrl: body.samlConfig.callbackUrl,
396
- audience: body.samlConfig.audience,
397
- idpMetadata: body.samlConfig.idpMetadata,
398
- spMetadata: body.samlConfig.spMetadata,
399
- wantAssertionsSigned: body.samlConfig.wantAssertionsSigned,
400
- signatureAlgorithm: body.samlConfig.signatureAlgorithm,
401
- digestAlgorithm: body.samlConfig.digestAlgorithm,
402
- identifierFormat: body.samlConfig.identifierFormat,
403
- privateKey: body.samlConfig.privateKey,
404
- decryptionPvk: body.samlConfig.decryptionPvk,
405
- additionalParams: body.samlConfig.additionalParams,
406
- mapping: body.samlConfig.mapping
407
- }) : null,
408
- organizationId: body.organizationId,
409
- userId: ctx.context.session.user.id,
410
- providerId: body.providerId
411
- }
412
- });
413
- return ctx.json({
414
- ...provider,
415
- oidcConfig: JSON.parse(provider.oidcConfig),
416
- samlConfig: JSON.parse(provider.samlConfig),
417
- redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`
418
- });
419
- }),
420
- signInSSO: (0, better_auth_plugins.createAuthEndpoint)("/sign-in/sso", {
421
- method: "POST",
422
- body: zod_v4.object({
423
- email: zod_v4.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(),
424
- organizationSlug: zod_v4.string({}).meta({ description: "The slug of the organization to sign in with" }).optional(),
425
- providerId: zod_v4.string({}).meta({ description: "The ID of the provider to sign in with. This can be provided instead of email or issuer" }).optional(),
426
- domain: zod_v4.string({}).meta({ description: "The domain of the provider." }).optional(),
427
- callbackURL: zod_v4.string({}).meta({ description: "The URL to redirect to after login" }),
428
- errorCallbackURL: zod_v4.string({}).meta({ description: "The URL to redirect to after login" }).optional(),
429
- newUserCallbackURL: zod_v4.string({}).meta({ description: "The URL to redirect to after login if the user is new" }).optional(),
430
- scopes: zod_v4.array(zod_v4.string(), {}).meta({ description: "Scopes to request from the provider." }).optional(),
431
- loginHint: zod_v4.string({}).meta({ description: "Login hint to send to the identity provider (e.g., email or identifier). If supported, will be sent as 'login_hint'." }).optional(),
432
- requestSignUp: zod_v4.boolean({}).meta({ description: "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider" }).optional(),
433
- providerType: zod_v4.enum(["oidc", "saml"]).optional()
434
- }),
435
- metadata: { openapi: {
436
- summary: "Sign in with SSO provider",
437
- description: "This endpoint is used to sign in with an SSO provider. It redirects to the provider's authorization URL",
438
- requestBody: { content: { "application/json": { schema: {
439
- type: "object",
440
- properties: {
441
- email: {
442
- type: "string",
443
- 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"
444
- },
445
- issuer: {
446
- type: "string",
447
- 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"
448
- },
449
- providerId: {
450
- type: "string",
451
- description: "The ID of the provider to sign in with. This can be provided instead of email or issuer"
452
- },
453
- callbackURL: {
454
- type: "string",
455
- description: "The URL to redirect to after login"
456
- },
457
- errorCallbackURL: {
458
- type: "string",
459
- description: "The URL to redirect to after login"
460
- },
461
- newUserCallbackURL: {
462
- type: "string",
463
- description: "The URL to redirect to after login if the user is new"
464
- },
465
- loginHint: {
466
- type: "string",
467
- description: "Login hint to send to the identity provider (e.g., email or identifier). If supported, sent as 'login_hint'."
468
- }
469
- },
470
- required: ["callbackURL"]
471
- } } } },
472
- responses: { "200": {
473
- description: "Authorization URL generated successfully for SSO sign-in",
474
- content: { "application/json": { schema: {
475
- type: "object",
476
- properties: {
477
- url: {
478
- type: "string",
479
- format: "uri",
480
- description: "The authorization URL to redirect the user to for SSO sign-in"
481
- },
482
- redirect: {
483
- type: "boolean",
484
- description: "Indicates that the client should redirect to the provided URL",
485
- enum: [true]
486
- }
487
- },
488
- required: ["url", "redirect"]
489
- } } }
490
- } }
491
- } }
492
- }, async (ctx) => {
493
- const body = ctx.body;
494
- let { email, organizationSlug, providerId, domain } = body;
495
- if (!options?.defaultSSO?.length && !email && !organizationSlug && !domain && !providerId) throw new better_auth_api.APIError("BAD_REQUEST", { message: "email, organizationSlug, domain or providerId is required" });
496
- domain = body.domain || email?.split("@")[1];
497
- let orgId = "";
498
- if (organizationSlug) orgId = await ctx.context.adapter.findOne({
499
- model: "organization",
500
- where: [{
501
- field: "slug",
502
- value: organizationSlug
503
- }]
504
- }).then((res) => {
505
- if (!res) return "";
506
- return res.id;
507
- });
508
- let provider = null;
509
- if (options?.defaultSSO?.length) {
510
- const matchingDefault = providerId ? options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === providerId) : options.defaultSSO.find((defaultProvider) => defaultProvider.domain === domain);
511
- if (matchingDefault) provider = {
512
- issuer: matchingDefault.samlConfig?.issuer || matchingDefault.oidcConfig?.issuer || "",
513
- providerId: matchingDefault.providerId,
514
- userId: "default",
515
- oidcConfig: matchingDefault.oidcConfig,
516
- samlConfig: matchingDefault.samlConfig
517
- };
518
- }
519
- if (!providerId && !orgId && !domain) throw new better_auth_api.APIError("BAD_REQUEST", { message: "providerId, orgId or domain is required" });
520
- if (!provider) provider = await ctx.context.adapter.findOne({
521
- model: "ssoProvider",
522
- where: [{
523
- field: providerId ? "providerId" : orgId ? "organizationId" : "domain",
524
- value: providerId || orgId || domain
525
- }]
526
- }).then((res) => {
527
- if (!res) return null;
528
- return {
529
- ...res,
530
- oidcConfig: res.oidcConfig ? safeJsonParse(res.oidcConfig) || void 0 : void 0,
531
- samlConfig: res.samlConfig ? safeJsonParse(res.samlConfig) || void 0 : void 0
532
- };
533
- });
534
- if (!provider) throw new better_auth_api.APIError("NOT_FOUND", { message: "No provider found for the issuer" });
535
- if (body.providerType) {
536
- if (body.providerType === "oidc" && !provider.oidcConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "OIDC provider is not configured" });
537
- if (body.providerType === "saml" && !provider.samlConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "SAML provider is not configured" });
538
- }
539
- if (provider.oidcConfig && body.providerType !== "saml") {
540
- const state = await (0, better_auth.generateState)(ctx);
541
- const redirectURI = `${ctx.context.baseURL}/sso/callback/${provider.providerId}`;
542
- const authorizationURL = await (0, better_auth_oauth2.createAuthorizationURL)({
543
- id: provider.issuer,
544
- options: {
545
- clientId: provider.oidcConfig.clientId,
546
- clientSecret: provider.oidcConfig.clientSecret
547
- },
548
- redirectURI,
549
- state: state.state,
550
- codeVerifier: provider.oidcConfig.pkce ? state.codeVerifier : void 0,
551
- scopes: ctx.body.scopes || provider.oidcConfig.scopes || [
552
- "openid",
553
- "email",
554
- "profile",
555
- "offline_access"
556
- ],
557
- loginHint: ctx.body.loginHint || email,
558
- authorizationEndpoint: provider.oidcConfig.authorizationEndpoint
559
- });
560
- return ctx.json({
561
- url: authorizationURL.toString(),
562
- redirect: true
563
- });
564
- }
565
- if (provider.samlConfig) {
566
- const parsedSamlConfig = typeof provider.samlConfig === "object" ? provider.samlConfig : safeJsonParse(provider.samlConfig);
567
- if (!parsedSamlConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SAML configuration" });
568
- const sp = samlify.ServiceProvider({
569
- metadata: parsedSamlConfig.spMetadata.metadata,
570
- allowCreate: true
571
- });
572
- const idp = samlify.IdentityProvider({
573
- metadata: parsedSamlConfig.idpMetadata?.metadata,
574
- entityID: parsedSamlConfig.idpMetadata?.entityID,
575
- encryptCert: parsedSamlConfig.idpMetadata?.cert,
576
- singleSignOnService: parsedSamlConfig.idpMetadata?.singleSignOnService
577
- });
578
- const loginRequest = sp.createLoginRequest(idp, "redirect");
579
- if (!loginRequest) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SAML request" });
580
- return ctx.json({
581
- url: `${loginRequest.context}&RelayState=${encodeURIComponent(body.callbackURL)}`,
582
- redirect: true
583
- });
584
- }
585
- throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SSO provider" });
586
- }),
587
- callbackSSO: (0, better_auth_plugins.createAuthEndpoint)("/sso/callback/:providerId", {
588
- method: "GET",
589
- query: zod_v4.object({
590
- code: zod_v4.string().optional(),
591
- state: zod_v4.string(),
592
- error: zod_v4.string().optional(),
593
- error_description: zod_v4.string().optional()
594
- }),
595
- metadata: {
596
- isAction: false,
597
- openapi: {
598
- summary: "Callback URL for SSO provider",
599
- description: "This endpoint is used as the callback URL for SSO providers. It handles the authorization code and exchanges it for an access token",
600
- responses: { "302": { description: "Redirects to the callback URL" } }
601
- }
602
- }
603
- }, async (ctx) => {
604
- const { code, state, error, error_description } = ctx.query;
605
- const stateData = await (0, better_auth_oauth2.parseState)(ctx);
606
- if (!stateData) {
607
- const errorURL$1 = ctx.context.options.onAPIError?.errorURL || `${ctx.context.baseURL}/error`;
608
- throw ctx.redirect(`${errorURL$1}?error=invalid_state`);
609
- }
610
- const { callbackURL, errorURL, newUserURL, requestSignUp } = stateData;
611
- if (!code || error) throw ctx.redirect(`${errorURL || callbackURL}?error=${error}&error_description=${error_description}`);
612
- let provider = null;
613
- if (options?.defaultSSO?.length) {
614
- const matchingDefault = options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === ctx.params.providerId);
615
- if (matchingDefault) provider = {
616
- ...matchingDefault,
617
- issuer: matchingDefault.oidcConfig?.issuer || "",
618
- userId: "default"
619
- };
620
- }
621
- if (!provider) provider = await ctx.context.adapter.findOne({
622
- model: "ssoProvider",
623
- where: [{
624
- field: "providerId",
625
- value: ctx.params.providerId
626
- }]
627
- }).then((res) => {
628
- if (!res) return null;
629
- return {
630
- ...res,
631
- oidcConfig: safeJsonParse(res.oidcConfig) || void 0
632
- };
633
- });
634
- if (!provider) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=provider not found`);
635
- let config = provider.oidcConfig;
636
- if (!config) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=provider not found`);
637
- const discovery = await (0, __better_fetch_fetch.betterFetch)(config.discoveryEndpoint);
638
- if (discovery.data) config = {
639
- tokenEndpoint: discovery.data.token_endpoint,
640
- tokenEndpointAuthentication: discovery.data.token_endpoint_auth_method,
641
- userInfoEndpoint: discovery.data.userinfo_endpoint,
642
- scopes: [
643
- "openid",
644
- "email",
645
- "profile",
646
- "offline_access"
647
- ],
648
- ...config
649
- };
650
- if (!config.tokenEndpoint) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=token_endpoint_not_found`);
651
- const tokenResponse = await (0, better_auth_oauth2.validateAuthorizationCode)({
652
- code,
653
- codeVerifier: config.pkce ? stateData.codeVerifier : void 0,
654
- redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`,
655
- options: {
656
- clientId: config.clientId,
657
- clientSecret: config.clientSecret
658
- },
659
- tokenEndpoint: config.tokenEndpoint,
660
- authentication: config.tokenEndpointAuthentication === "client_secret_post" ? "post" : "basic"
661
- }).catch((e) => {
662
- if (e instanceof __better_fetch_fetch.BetterFetchError) throw ctx.redirect(`${errorURL || callbackURL}?error=invalid_provider&error_description=${e.message}`);
663
- return null;
664
- });
665
- if (!tokenResponse) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=token_response_not_found`);
666
- let userInfo = null;
667
- if (tokenResponse.idToken) {
668
- const idToken = (0, jose.decodeJwt)(tokenResponse.idToken);
669
- if (!config.jwksEndpoint) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=jwks_endpoint_not_found`);
670
- const verified = await (0, better_auth_oauth2.validateToken)(tokenResponse.idToken, config.jwksEndpoint).catch((e) => {
671
- ctx.context.logger.error(e);
672
- return null;
673
- });
674
- if (!verified) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=token_not_verified`);
675
- if (verified.payload.iss !== provider.issuer) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=issuer_mismatch`);
676
- const mapping = config.mapping || {};
677
- userInfo = {
678
- ...Object.fromEntries(Object.entries(mapping.extraFields || {}).map(([key, value]) => [key, verified.payload[value]])),
679
- id: idToken[mapping.id || "sub"],
680
- email: idToken[mapping.email || "email"],
681
- emailVerified: options?.trustEmailVerified ? idToken[mapping.emailVerified || "email_verified"] : false,
682
- name: idToken[mapping.name || "name"],
683
- image: idToken[mapping.image || "picture"]
684
- };
685
- }
686
- if (!userInfo) {
687
- if (!config.userInfoEndpoint) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=user_info_endpoint_not_found`);
688
- const userInfoResponse = await (0, __better_fetch_fetch.betterFetch)(config.userInfoEndpoint, { headers: { Authorization: `Bearer ${tokenResponse.accessToken}` } });
689
- if (userInfoResponse.error) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=${userInfoResponse.error.message}`);
690
- userInfo = userInfoResponse.data;
691
- }
692
- if (!userInfo.email || !userInfo.id) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=missing_user_info`);
693
- const linked = await (0, better_auth_oauth2.handleOAuthUserInfo)(ctx, {
694
- userInfo: {
695
- email: userInfo.email,
696
- name: userInfo.name || userInfo.email,
697
- id: userInfo.id,
698
- image: userInfo.image,
699
- emailVerified: options?.trustEmailVerified ? userInfo.emailVerified || false : false
700
- },
701
- account: {
702
- idToken: tokenResponse.idToken,
703
- accessToken: tokenResponse.accessToken,
704
- refreshToken: tokenResponse.refreshToken,
705
- accountId: userInfo.id,
706
- providerId: provider.providerId,
707
- accessTokenExpiresAt: tokenResponse.accessTokenExpiresAt,
708
- refreshTokenExpiresAt: tokenResponse.refreshTokenExpiresAt,
709
- scope: tokenResponse.scopes?.join(",")
710
- },
711
- callbackURL,
712
- disableSignUp: options?.disableImplicitSignUp && !requestSignUp,
713
- overrideUserInfo: config.overrideUserInfo
714
- });
715
- if (linked.error) throw ctx.redirect(`${errorURL || callbackURL}/error?error=${linked.error}`);
716
- const { session, user } = linked.data;
717
- if (options?.provisionUser) await options.provisionUser({
718
- user,
719
- userInfo,
720
- token: tokenResponse,
721
- provider
722
- });
723
- if (provider.organizationId && !options?.organizationProvisioning?.disabled) {
724
- if (ctx.context.options.plugins?.find((plugin) => plugin.id === "organization")) {
725
- if (!await ctx.context.adapter.findOne({
726
- model: "member",
727
- where: [{
728
- field: "organizationId",
729
- value: provider.organizationId
730
- }, {
731
- field: "userId",
732
- value: user.id
733
- }]
734
- })) {
735
- const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({
736
- user,
737
- userInfo,
738
- token: tokenResponse,
739
- provider
740
- }) : options?.organizationProvisioning?.defaultRole || "member";
741
- await ctx.context.adapter.create({
742
- model: "member",
743
- data: {
744
- organizationId: provider.organizationId,
745
- userId: user.id,
746
- role,
747
- createdAt: /* @__PURE__ */ new Date(),
748
- updatedAt: /* @__PURE__ */ new Date()
749
- }
750
- });
751
- }
752
- }
753
- }
754
- await (0, better_auth_cookies.setSessionCookie)(ctx, {
755
- session,
756
- user
757
- });
758
- let toRedirectTo;
759
- try {
760
- toRedirectTo = (linked.isRegister ? newUserURL || callbackURL : callbackURL).toString();
761
- } catch {
762
- toRedirectTo = linked.isRegister ? newUserURL || callbackURL : callbackURL;
763
- }
764
- throw ctx.redirect(toRedirectTo);
765
- }),
766
- callbackSSOSAML: (0, better_auth_plugins.createAuthEndpoint)("/sso/saml2/callback/:providerId", {
767
- method: "POST",
768
- body: zod_v4.object({
769
- SAMLResponse: zod_v4.string(),
770
- RelayState: zod_v4.string().optional()
771
- }),
772
- metadata: {
773
- isAction: false,
774
- openapi: {
775
- summary: "Callback URL for SAML provider",
776
- description: "This endpoint is used as the callback URL for SAML providers.",
777
- responses: {
778
- "302": { description: "Redirects to the callback URL" },
779
- "400": { description: "Invalid SAML response" },
780
- "401": { description: "Unauthorized - SAML authentication failed" }
781
- }
782
- }
783
- }
784
- }, async (ctx) => {
785
- const { SAMLResponse, RelayState } = ctx.body;
786
- const { providerId } = ctx.params;
787
- let provider = null;
788
- if (options?.defaultSSO?.length) {
789
- const matchingDefault = options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === providerId);
790
- if (matchingDefault) provider = {
791
- ...matchingDefault,
792
- userId: "default",
793
- issuer: matchingDefault.samlConfig?.issuer || ""
794
- };
795
- }
796
- if (!provider) provider = await ctx.context.adapter.findOne({
797
- model: "ssoProvider",
798
- where: [{
799
- field: "providerId",
800
- value: providerId
801
- }]
802
- }).then((res) => {
803
- if (!res) return null;
804
- return {
805
- ...res,
806
- samlConfig: res.samlConfig ? safeJsonParse(res.samlConfig) || void 0 : void 0
807
- };
808
- });
809
- if (!provider) throw new better_auth_api.APIError("NOT_FOUND", { message: "No provider found for the given providerId" });
810
- const parsedSamlConfig = safeJsonParse(provider.samlConfig);
811
- if (!parsedSamlConfig) throw new better_auth_api.APIError("BAD_REQUEST", { message: "Invalid SAML configuration" });
812
- const idpData = parsedSamlConfig.idpMetadata;
813
- let idp = null;
814
- if (!idpData?.metadata) idp = samlify.IdentityProvider({
815
- entityID: idpData?.entityID || parsedSamlConfig.issuer,
816
- singleSignOnService: [{
817
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
818
- Location: parsedSamlConfig.entryPoint
819
- }],
820
- signingCert: idpData?.cert || parsedSamlConfig.cert,
821
- wantAuthnRequestsSigned: parsedSamlConfig.wantAssertionsSigned || false,
822
- isAssertionEncrypted: idpData?.isAssertionEncrypted || false,
823
- encPrivateKey: idpData?.encPrivateKey,
824
- encPrivateKeyPass: idpData?.encPrivateKeyPass
825
- });
826
- else idp = samlify.IdentityProvider({
827
- metadata: idpData.metadata,
828
- privateKey: idpData.privateKey,
829
- privateKeyPass: idpData.privateKeyPass,
830
- isAssertionEncrypted: idpData.isAssertionEncrypted,
831
- encPrivateKey: idpData.encPrivateKey,
832
- encPrivateKeyPass: idpData.encPrivateKeyPass
833
- });
834
- const spData = parsedSamlConfig.spMetadata;
835
- const sp = samlify.ServiceProvider({
836
- metadata: spData?.metadata,
837
- entityID: spData?.entityID || parsedSamlConfig.issuer,
838
- assertionConsumerService: spData?.metadata ? void 0 : [{
839
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
840
- Location: parsedSamlConfig.callbackUrl
841
- }],
842
- privateKey: spData?.privateKey || parsedSamlConfig.privateKey,
843
- privateKeyPass: spData?.privateKeyPass,
844
- isAssertionEncrypted: spData?.isAssertionEncrypted || false,
845
- encPrivateKey: spData?.encPrivateKey,
846
- encPrivateKeyPass: spData?.encPrivateKeyPass,
847
- wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
848
- nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : void 0
849
- });
850
- let parsedResponse;
851
- try {
852
- const decodedResponse = Buffer.from(SAMLResponse, "base64").toString("utf-8");
853
- try {
854
- parsedResponse = await sp.parseLoginResponse(idp, "post", { body: {
855
- SAMLResponse,
856
- RelayState: RelayState || void 0
857
- } });
858
- } catch (parseError) {
859
- const nameIDMatch = decodedResponse.match(/<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/);
860
- if (!nameIDMatch) throw parseError;
861
- parsedResponse = { extract: {
862
- nameID: nameIDMatch[1],
863
- attributes: { nameID: nameIDMatch[1] },
864
- sessionIndex: {},
865
- conditions: {}
866
- } };
867
- }
868
- if (!parsedResponse?.extract) throw new Error("Invalid SAML response structure");
869
- } catch (error) {
870
- ctx.context.logger.error("SAML response validation failed", {
871
- error,
872
- decodedResponse: Buffer.from(SAMLResponse, "base64").toString("utf-8")
873
- });
874
- throw new better_auth_api.APIError("BAD_REQUEST", {
875
- message: "Invalid SAML response",
876
- details: error instanceof Error ? error.message : String(error)
877
- });
878
- }
879
- const { extract } = parsedResponse;
880
- const attributes = extract.attributes || {};
881
- const mapping = parsedSamlConfig.mapping ?? {};
882
- const userInfo = {
883
- ...Object.fromEntries(Object.entries(mapping.extraFields || {}).map(([key, value]) => [key, attributes[value]])),
884
- id: attributes[mapping.id || "nameID"] || extract.nameID,
885
- email: attributes[mapping.email || "email"] || extract.nameID,
886
- name: [attributes[mapping.firstName || "givenName"], attributes[mapping.lastName || "surname"]].filter(Boolean).join(" ") || attributes[mapping.name || "displayName"] || extract.nameID,
887
- emailVerified: options?.trustEmailVerified && mapping.emailVerified ? attributes[mapping.emailVerified] || false : false
888
- };
889
- if (!userInfo.id || !userInfo.email) {
890
- ctx.context.logger.error("Missing essential user info from SAML response", {
891
- attributes: Object.keys(attributes),
892
- mapping,
893
- extractedId: userInfo.id,
894
- extractedEmail: userInfo.email
895
- });
896
- throw new better_auth_api.APIError("BAD_REQUEST", { message: "Unable to extract user ID or email from SAML response" });
897
- }
898
- let user;
899
- const existingUser = await ctx.context.adapter.findOne({
900
- model: "user",
901
- where: [{
902
- field: "email",
903
- value: userInfo.email
904
- }]
905
- });
906
- if (existingUser) user = existingUser;
907
- else user = await ctx.context.adapter.create({
908
- model: "user",
909
- data: {
910
- email: userInfo.email,
911
- name: userInfo.name,
912
- emailVerified: userInfo.emailVerified,
913
- createdAt: /* @__PURE__ */ new Date(),
914
- updatedAt: /* @__PURE__ */ new Date()
915
- }
916
- });
917
- if (!await ctx.context.adapter.findOne({
918
- model: "account",
919
- where: [
920
- {
921
- field: "userId",
922
- value: user.id
923
- },
924
- {
925
- field: "providerId",
926
- value: provider.providerId
927
- },
928
- {
929
- field: "accountId",
930
- value: userInfo.id
931
- }
932
- ]
933
- })) await ctx.context.adapter.create({
934
- model: "account",
935
- data: {
936
- userId: user.id,
937
- providerId: provider.providerId,
938
- accountId: userInfo.id,
939
- createdAt: /* @__PURE__ */ new Date(),
940
- updatedAt: /* @__PURE__ */ new Date(),
941
- accessToken: "",
942
- refreshToken: ""
943
- }
944
- });
945
- if (options?.provisionUser) await options.provisionUser({
946
- user,
947
- userInfo,
948
- provider
949
- });
950
- if (provider.organizationId && !options?.organizationProvisioning?.disabled) {
951
- if (ctx.context.options.plugins?.find((plugin) => plugin.id === "organization")) {
952
- if (!await ctx.context.adapter.findOne({
953
- model: "member",
954
- where: [{
955
- field: "organizationId",
956
- value: provider.organizationId
957
- }, {
958
- field: "userId",
959
- value: user.id
960
- }]
961
- })) {
962
- const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({
963
- user,
964
- userInfo,
965
- provider
966
- }) : options?.organizationProvisioning?.defaultRole || "member";
967
- await ctx.context.adapter.create({
968
- model: "member",
969
- data: {
970
- organizationId: provider.organizationId,
971
- userId: user.id,
972
- role,
973
- createdAt: /* @__PURE__ */ new Date(),
974
- updatedAt: /* @__PURE__ */ new Date()
975
- }
976
- });
977
- }
978
- }
979
- }
980
- await (0, better_auth_cookies.setSessionCookie)(ctx, {
981
- session: await ctx.context.internalAdapter.createSession(user.id),
982
- user
983
- });
984
- const callbackUrl = RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
985
- throw ctx.redirect(callbackUrl);
986
- }),
987
- acsEndpoint: (0, better_auth_plugins.createAuthEndpoint)("/sso/saml2/sp/acs/:providerId", {
988
- method: "POST",
989
- params: zod_v4.object({ providerId: zod_v4.string().optional() }),
990
- body: zod_v4.object({
991
- SAMLResponse: zod_v4.string(),
992
- RelayState: zod_v4.string().optional()
993
- }),
994
- metadata: {
995
- isAction: false,
996
- openapi: {
997
- summary: "SAML Assertion Consumer Service",
998
- description: "Handles SAML responses from IdP after successful authentication",
999
- responses: { "302": { description: "Redirects to the callback URL after successful authentication" } }
1000
- }
1001
- }
1002
- }, async (ctx) => {
1003
- const { SAMLResponse, RelayState = "" } = ctx.body;
1004
- const { providerId } = ctx.params;
1005
- let provider = null;
1006
- if (options?.defaultSSO?.length) {
1007
- const matchingDefault = providerId ? options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === providerId) : options.defaultSSO[0];
1008
- if (matchingDefault) provider = {
1009
- issuer: matchingDefault.samlConfig?.issuer || "",
1010
- providerId: matchingDefault.providerId,
1011
- userId: "default",
1012
- samlConfig: matchingDefault.samlConfig
1013
- };
1014
- } else provider = await ctx.context.adapter.findOne({
1015
- model: "ssoProvider",
1016
- where: [{
1017
- field: "providerId",
1018
- value: providerId ?? "sso"
1019
- }]
1020
- }).then((res) => {
1021
- if (!res) return null;
1022
- return {
1023
- ...res,
1024
- samlConfig: res.samlConfig ? safeJsonParse(res.samlConfig) || void 0 : void 0
1025
- };
1026
- });
1027
- if (!provider?.samlConfig) throw new better_auth_api.APIError("NOT_FOUND", { message: "No SAML provider found" });
1028
- const parsedSamlConfig = provider.samlConfig;
1029
- const sp = samlify.ServiceProvider({
1030
- entityID: parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
1031
- assertionConsumerService: [{
1032
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
1033
- Location: parsedSamlConfig.callbackUrl || `${ctx.context.baseURL}/sso/saml2/sp/acs/${providerId}`
1034
- }],
1035
- wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
1036
- metadata: parsedSamlConfig.spMetadata?.metadata,
1037
- privateKey: parsedSamlConfig.spMetadata?.privateKey || parsedSamlConfig.privateKey,
1038
- privateKeyPass: parsedSamlConfig.spMetadata?.privateKeyPass,
1039
- nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : void 0
1040
- });
1041
- const idpData = parsedSamlConfig.idpMetadata;
1042
- const idp = !idpData?.metadata ? samlify.IdentityProvider({
1043
- entityID: idpData?.entityID || parsedSamlConfig.issuer,
1044
- singleSignOnService: idpData?.singleSignOnService || [{
1045
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
1046
- Location: parsedSamlConfig.entryPoint
1047
- }],
1048
- signingCert: idpData?.cert || parsedSamlConfig.cert
1049
- }) : samlify.IdentityProvider({ metadata: idpData.metadata });
1050
- let parsedResponse;
1051
- try {
1052
- let decodedResponse = Buffer.from(SAMLResponse, "base64").toString("utf-8");
1053
- if (!decodedResponse.includes("StatusCode")) {
1054
- const insertPoint = decodedResponse.indexOf("</saml2:Issuer>");
1055
- 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);
1056
- } else if (!decodedResponse.includes("saml2:Success")) decodedResponse = decodedResponse.replace(/<saml2:StatusCode Value="[^"]+"/, "<saml2:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"");
1057
- try {
1058
- parsedResponse = await sp.parseLoginResponse(idp, "post", { body: {
1059
- SAMLResponse,
1060
- RelayState: RelayState || void 0
1061
- } });
1062
- } catch (parseError) {
1063
- const nameIDMatch = decodedResponse.match(/<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/);
1064
- if (!nameIDMatch) throw parseError;
1065
- parsedResponse = { extract: {
1066
- nameID: nameIDMatch[1],
1067
- attributes: { nameID: nameIDMatch[1] },
1068
- sessionIndex: {},
1069
- conditions: {}
1070
- } };
1071
- }
1072
- if (!parsedResponse?.extract) throw new Error("Invalid SAML response structure");
1073
- } catch (error) {
1074
- ctx.context.logger.error("SAML response validation failed", {
1075
- error,
1076
- decodedResponse: Buffer.from(SAMLResponse, "base64").toString("utf-8")
1077
- });
1078
- throw new better_auth_api.APIError("BAD_REQUEST", {
1079
- message: "Invalid SAML response",
1080
- details: error instanceof Error ? error.message : String(error)
1081
- });
1082
- }
1083
- const { extract } = parsedResponse;
1084
- const attributes = extract.attributes || {};
1085
- const mapping = parsedSamlConfig.mapping ?? {};
1086
- const userInfo = {
1087
- ...Object.fromEntries(Object.entries(mapping.extraFields || {}).map(([key, value]) => [key, attributes[value]])),
1088
- id: attributes[mapping.id || "nameID"] || extract.nameID,
1089
- email: attributes[mapping.email || "email"] || extract.nameID,
1090
- name: [attributes[mapping.firstName || "givenName"], attributes[mapping.lastName || "surname"]].filter(Boolean).join(" ") || attributes[mapping.name || "displayName"] || extract.nameID,
1091
- emailVerified: options?.trustEmailVerified && mapping.emailVerified ? attributes[mapping.emailVerified] || false : false
1092
- };
1093
- if (!userInfo.id || !userInfo.email) {
1094
- ctx.context.logger.error("Missing essential user info from SAML response", {
1095
- attributes: Object.keys(attributes),
1096
- mapping,
1097
- extractedId: userInfo.id,
1098
- extractedEmail: userInfo.email
1099
- });
1100
- throw new better_auth_api.APIError("BAD_REQUEST", { message: "Unable to extract user ID or email from SAML response" });
1101
- }
1102
- let user;
1103
- const existingUser = await ctx.context.adapter.findOne({
1104
- model: "user",
1105
- where: [{
1106
- field: "email",
1107
- value: userInfo.email
1108
- }]
1109
- });
1110
- if (existingUser) {
1111
- if (!await ctx.context.adapter.findOne({
1112
- model: "account",
1113
- where: [
1114
- {
1115
- field: "userId",
1116
- value: existingUser.id
1117
- },
1118
- {
1119
- field: "providerId",
1120
- value: provider.providerId
1121
- },
1122
- {
1123
- field: "accountId",
1124
- value: userInfo.id
1125
- }
1126
- ]
1127
- })) {
1128
- if (!ctx.context.options.account?.accountLinking?.trustedProviders?.includes(provider.providerId)) throw ctx.redirect(`${parsedSamlConfig.callbackUrl}?error=account_not_found`);
1129
- await ctx.context.adapter.create({
1130
- model: "account",
1131
- data: {
1132
- userId: existingUser.id,
1133
- providerId: provider.providerId,
1134
- accountId: userInfo.id,
1135
- createdAt: /* @__PURE__ */ new Date(),
1136
- updatedAt: /* @__PURE__ */ new Date(),
1137
- accessToken: "",
1138
- refreshToken: ""
1139
- }
1140
- });
1141
- }
1142
- user = existingUser;
1143
- } else {
1144
- user = await ctx.context.adapter.create({
1145
- model: "user",
1146
- data: {
1147
- email: userInfo.email,
1148
- name: userInfo.name,
1149
- emailVerified: options?.trustEmailVerified ? userInfo.emailVerified || false : false,
1150
- createdAt: /* @__PURE__ */ new Date(),
1151
- updatedAt: /* @__PURE__ */ new Date()
1152
- }
1153
- });
1154
- await ctx.context.adapter.create({
1155
- model: "account",
1156
- data: {
1157
- userId: user.id,
1158
- providerId: provider.providerId,
1159
- accountId: userInfo.id,
1160
- accessToken: "",
1161
- refreshToken: "",
1162
- accessTokenExpiresAt: /* @__PURE__ */ new Date(),
1163
- refreshTokenExpiresAt: /* @__PURE__ */ new Date(),
1164
- scope: "",
1165
- createdAt: /* @__PURE__ */ new Date(),
1166
- updatedAt: /* @__PURE__ */ new Date()
1167
- }
1168
- });
1169
- }
1170
- if (options?.provisionUser) await options.provisionUser({
1171
- user,
1172
- userInfo,
1173
- provider
1174
- });
1175
- if (provider.organizationId && !options?.organizationProvisioning?.disabled) {
1176
- if (ctx.context.options.plugins?.find((plugin) => plugin.id === "organization")) {
1177
- if (!await ctx.context.adapter.findOne({
1178
- model: "member",
1179
- where: [{
1180
- field: "organizationId",
1181
- value: provider.organizationId
1182
- }, {
1183
- field: "userId",
1184
- value: user.id
1185
- }]
1186
- })) {
1187
- const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({
1188
- user,
1189
- userInfo,
1190
- provider
1191
- }) : options?.organizationProvisioning?.defaultRole || "member";
1192
- await ctx.context.adapter.create({
1193
- model: "member",
1194
- data: {
1195
- organizationId: provider.organizationId,
1196
- userId: user.id,
1197
- role,
1198
- createdAt: /* @__PURE__ */ new Date(),
1199
- updatedAt: /* @__PURE__ */ new Date()
1200
- }
1201
- });
1202
- }
1203
- }
1204
- }
1205
- await (0, better_auth_cookies.setSessionCookie)(ctx, {
1206
- session: await ctx.context.internalAdapter.createSession(user.id),
1207
- user
1208
- });
1209
- const callbackUrl = RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
1210
- throw ctx.redirect(callbackUrl);
1211
- })
1212
- },
1213
- schema: { ssoProvider: { fields: {
1214
- issuer: {
1215
- type: "string",
1216
- required: true
1217
- },
1218
- oidcConfig: {
1219
- type: "string",
1220
- required: false
1221
- },
1222
- samlConfig: {
1223
- type: "string",
1224
- required: false
1225
- },
1226
- userId: {
1227
- type: "string",
1228
- references: {
1229
- model: "user",
1230
- field: "id"
1231
- }
1232
- },
1233
- providerId: {
1234
- type: "string",
1235
- required: true,
1236
- unique: true
1237
- },
1238
- organizationId: {
1239
- type: "string",
1240
- required: false
1241
- },
1242
- domain: {
1243
- type: "string",
1244
- required: true
1245
- }
1246
- } } }
1247
- };
1248
- };
1249
-
1250
- //#endregion
1251
- Object.defineProperty(exports, 'sso', {
1252
- enumerable: true,
1253
- get: function () {
1254
- return sso;
1255
- }
1256
- });