@better-auth/sso 1.4.0-beta.19 → 1.4.0-beta.20

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