@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.
@@ -0,0 +1,2019 @@
1
+ import { BetterFetchError, betterFetch } from "@better-fetch/fetch";
2
+ import {
3
+ type Account,
4
+ createAuthorizationURL,
5
+ generateState,
6
+ parseState,
7
+ type Session,
8
+ type User,
9
+ validateAuthorizationCode,
10
+ validateToken,
11
+ } from "better-auth";
12
+ import {
13
+ APIError,
14
+ createAuthEndpoint,
15
+ sessionMiddleware,
16
+ } from "better-auth/api";
17
+ import { setSessionCookie } from "better-auth/cookies";
18
+ import { handleOAuthUserInfo } from "better-auth/oauth2";
19
+ import { decodeJwt } from "jose";
20
+ import * as saml from "samlify";
21
+ import type { BindingContext } from "samlify/types/src/entity";
22
+ import type { IdentityProvider } from "samlify/types/src/entity-idp";
23
+ import type { FlowResult } from "samlify/types/src/flow";
24
+ import * as z from "zod/v4";
25
+ import type { OIDCConfig, SAMLConfig, SSOOptions, SSOProvider } from "../types";
26
+
27
+ /**
28
+ * Safely parses a value that might be a JSON string or already a parsed object
29
+ * This handles cases where ORMs like Drizzle might return already parsed objects
30
+ * instead of JSON strings from TEXT/JSON columns
31
+ */
32
+ function safeJsonParse<T>(value: string | T | null | undefined): T | null {
33
+ if (!value) return null;
34
+
35
+ // If it's already an object (not a string), return it as-is
36
+ if (typeof value === "object") {
37
+ return value as T;
38
+ }
39
+
40
+ // If it's a string, try to parse it
41
+ if (typeof value === "string") {
42
+ try {
43
+ return JSON.parse(value) as T;
44
+ } catch (error) {
45
+ // If parsing fails, this might indicate the string is not valid JSON
46
+ throw new Error(
47
+ `Failed to parse JSON: ${error instanceof Error ? error.message : "Unknown error"}`,
48
+ );
49
+ }
50
+ }
51
+
52
+ return null;
53
+ }
54
+
55
+ export const spMetadata = () => {
56
+ return createAuthEndpoint(
57
+ "/sso/saml2/sp/metadata",
58
+ {
59
+ method: "GET",
60
+ query: z.object({
61
+ providerId: z.string(),
62
+ format: z.enum(["xml", "json"]).default("xml"),
63
+ }),
64
+ metadata: {
65
+ openapi: {
66
+ summary: "Get Service Provider metadata",
67
+ description: "Returns the SAML metadata for the Service Provider",
68
+ responses: {
69
+ "200": {
70
+ description: "SAML metadata in XML format",
71
+ },
72
+ },
73
+ },
74
+ },
75
+ },
76
+ async (ctx) => {
77
+ const provider = await ctx.context.adapter.findOne<{
78
+ id: string;
79
+ samlConfig: string;
80
+ }>({
81
+ model: "ssoProvider",
82
+ where: [
83
+ {
84
+ field: "providerId",
85
+ value: ctx.query.providerId,
86
+ },
87
+ ],
88
+ });
89
+ if (!provider) {
90
+ throw new APIError("NOT_FOUND", {
91
+ message: "No provider found for the given providerId",
92
+ });
93
+ }
94
+
95
+ const parsedSamlConfig = safeJsonParse<SAMLConfig>(provider.samlConfig);
96
+ if (!parsedSamlConfig) {
97
+ throw new APIError("BAD_REQUEST", {
98
+ message: "Invalid SAML configuration",
99
+ });
100
+ }
101
+ const sp = parsedSamlConfig.spMetadata.metadata
102
+ ? saml.ServiceProvider({
103
+ metadata: parsedSamlConfig.spMetadata.metadata,
104
+ })
105
+ : saml.SPMetadata({
106
+ entityID:
107
+ parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
108
+ assertionConsumerService: [
109
+ {
110
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
111
+ Location:
112
+ parsedSamlConfig.callbackUrl ||
113
+ `${ctx.context.baseURL}/sso/saml2/sp/acs/${provider.id}`,
114
+ },
115
+ ],
116
+ wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
117
+ nameIDFormat: parsedSamlConfig.identifierFormat
118
+ ? [parsedSamlConfig.identifierFormat]
119
+ : undefined,
120
+ });
121
+ return new Response(sp.getMetadata(), {
122
+ headers: {
123
+ "Content-Type": "application/xml",
124
+ },
125
+ });
126
+ },
127
+ );
128
+ };
129
+
130
+ export const registerSSOProvider = (options?: SSOOptions) => {
131
+ return createAuthEndpoint(
132
+ "/sso/register",
133
+ {
134
+ method: "POST",
135
+ body: z.object({
136
+ providerId: z.string({}).meta({
137
+ description:
138
+ "The ID of the provider. This is used to identify the provider during login and callback",
139
+ }),
140
+ issuer: z.string({}).meta({
141
+ description: "The issuer of the provider",
142
+ }),
143
+ domain: z.string({}).meta({
144
+ description:
145
+ "The domain of the provider. This is used for email matching",
146
+ }),
147
+ oidcConfig: z
148
+ .object({
149
+ clientId: z.string({}).meta({
150
+ description: "The client ID",
151
+ }),
152
+ clientSecret: z.string({}).meta({
153
+ description: "The client secret",
154
+ }),
155
+ authorizationEndpoint: z
156
+ .string({})
157
+ .meta({
158
+ description: "The authorization endpoint",
159
+ })
160
+ .optional(),
161
+ tokenEndpoint: z
162
+ .string({})
163
+ .meta({
164
+ description: "The token endpoint",
165
+ })
166
+ .optional(),
167
+ userInfoEndpoint: z
168
+ .string({})
169
+ .meta({
170
+ description: "The user info endpoint",
171
+ })
172
+ .optional(),
173
+ tokenEndpointAuthentication: z
174
+ .enum(["client_secret_post", "client_secret_basic"])
175
+ .optional(),
176
+ jwksEndpoint: z
177
+ .string({})
178
+ .meta({
179
+ description: "The JWKS endpoint",
180
+ })
181
+ .optional(),
182
+ discoveryEndpoint: z.string().optional(),
183
+ scopes: z
184
+ .array(z.string(), {})
185
+ .meta({
186
+ description:
187
+ "The scopes to request. Defaults to ['openid', 'email', 'profile', 'offline_access']",
188
+ })
189
+ .optional(),
190
+ pkce: z
191
+ .boolean({})
192
+ .meta({
193
+ description: "Whether to use PKCE for the authorization flow",
194
+ })
195
+ .default(true)
196
+ .optional(),
197
+ mapping: z
198
+ .object({
199
+ id: z.string({}).meta({
200
+ description: "Field mapping for user ID (defaults to 'sub')",
201
+ }),
202
+ email: z.string({}).meta({
203
+ description: "Field mapping for email (defaults to 'email')",
204
+ }),
205
+ emailVerified: z
206
+ .string({})
207
+ .meta({
208
+ description:
209
+ "Field mapping for email verification (defaults to 'email_verified')",
210
+ })
211
+ .optional(),
212
+ name: z.string({}).meta({
213
+ description: "Field mapping for name (defaults to 'name')",
214
+ }),
215
+ image: z
216
+ .string({})
217
+ .meta({
218
+ description:
219
+ "Field mapping for image (defaults to 'picture')",
220
+ })
221
+ .optional(),
222
+ extraFields: z.record(z.string(), z.any()).optional(),
223
+ })
224
+ .optional(),
225
+ })
226
+ .optional(),
227
+ samlConfig: z
228
+ .object({
229
+ entryPoint: z.string({}).meta({
230
+ description: "The entry point of the provider",
231
+ }),
232
+ cert: z.string({}).meta({
233
+ description: "The certificate of the provider",
234
+ }),
235
+ callbackUrl: z.string({}).meta({
236
+ description: "The callback URL of the provider",
237
+ }),
238
+ audience: z.string().optional(),
239
+ idpMetadata: z
240
+ .object({
241
+ metadata: z.string().optional(),
242
+ entityID: z.string().optional(),
243
+ cert: z.string().optional(),
244
+ privateKey: z.string().optional(),
245
+ privateKeyPass: z.string().optional(),
246
+ isAssertionEncrypted: z.boolean().optional(),
247
+ encPrivateKey: z.string().optional(),
248
+ encPrivateKeyPass: z.string().optional(),
249
+ singleSignOnService: z
250
+ .array(
251
+ z.object({
252
+ Binding: z.string().meta({
253
+ description: "The binding type for the SSO service",
254
+ }),
255
+ Location: z.string().meta({
256
+ description: "The URL for the SSO service",
257
+ }),
258
+ }),
259
+ )
260
+ .optional()
261
+ .meta({
262
+ description: "Single Sign-On service configuration",
263
+ }),
264
+ })
265
+ .optional(),
266
+ spMetadata: z.object({
267
+ metadata: z.string().optional(),
268
+ entityID: z.string().optional(),
269
+ binding: z.string().optional(),
270
+ privateKey: z.string().optional(),
271
+ privateKeyPass: z.string().optional(),
272
+ isAssertionEncrypted: z.boolean().optional(),
273
+ encPrivateKey: z.string().optional(),
274
+ encPrivateKeyPass: z.string().optional(),
275
+ }),
276
+ wantAssertionsSigned: z.boolean().optional(),
277
+ signatureAlgorithm: z.string().optional(),
278
+ digestAlgorithm: z.string().optional(),
279
+ identifierFormat: z.string().optional(),
280
+ privateKey: z.string().optional(),
281
+ decryptionPvk: z.string().optional(),
282
+ additionalParams: z.record(z.string(), z.any()).optional(),
283
+ mapping: z
284
+ .object({
285
+ id: z.string({}).meta({
286
+ description:
287
+ "Field mapping for user ID (defaults to 'nameID')",
288
+ }),
289
+ email: z.string({}).meta({
290
+ description: "Field mapping for email (defaults to 'email')",
291
+ }),
292
+ emailVerified: z
293
+ .string({})
294
+ .meta({
295
+ description: "Field mapping for email verification",
296
+ })
297
+ .optional(),
298
+ name: z.string({}).meta({
299
+ description:
300
+ "Field mapping for name (defaults to 'displayName')",
301
+ }),
302
+ firstName: z
303
+ .string({})
304
+ .meta({
305
+ description:
306
+ "Field mapping for first name (defaults to 'givenName')",
307
+ })
308
+ .optional(),
309
+ lastName: z
310
+ .string({})
311
+ .meta({
312
+ description:
313
+ "Field mapping for last name (defaults to 'surname')",
314
+ })
315
+ .optional(),
316
+ extraFields: z.record(z.string(), z.any()).optional(),
317
+ })
318
+ .optional(),
319
+ })
320
+ .optional(),
321
+ organizationId: z
322
+ .string({})
323
+ .meta({
324
+ description:
325
+ "If organization plugin is enabled, the organization id to link the provider to",
326
+ })
327
+ .optional(),
328
+ overrideUserInfo: z
329
+ .boolean({})
330
+ .meta({
331
+ description:
332
+ "Override user info with the provider info. Defaults to false",
333
+ })
334
+ .default(false)
335
+ .optional(),
336
+ }),
337
+ use: [sessionMiddleware],
338
+ metadata: {
339
+ openapi: {
340
+ summary: "Register an OIDC provider",
341
+ description:
342
+ "This endpoint is used to register an OIDC provider. This is used to configure the provider and link it to an organization",
343
+ responses: {
344
+ "200": {
345
+ description: "OIDC provider created successfully",
346
+ content: {
347
+ "application/json": {
348
+ schema: {
349
+ type: "object",
350
+ properties: {
351
+ issuer: {
352
+ type: "string",
353
+ format: "uri",
354
+ description: "The issuer URL of the provider",
355
+ },
356
+ domain: {
357
+ type: "string",
358
+ description:
359
+ "The domain of the provider, used for email matching",
360
+ },
361
+ oidcConfig: {
362
+ type: "object",
363
+ properties: {
364
+ issuer: {
365
+ type: "string",
366
+ format: "uri",
367
+ description: "The issuer URL of the provider",
368
+ },
369
+ pkce: {
370
+ type: "boolean",
371
+ description:
372
+ "Whether PKCE is enabled for the authorization flow",
373
+ },
374
+ clientId: {
375
+ type: "string",
376
+ description: "The client ID for the provider",
377
+ },
378
+ clientSecret: {
379
+ type: "string",
380
+ description: "The client secret for the provider",
381
+ },
382
+ authorizationEndpoint: {
383
+ type: "string",
384
+ format: "uri",
385
+ nullable: true,
386
+ description: "The authorization endpoint URL",
387
+ },
388
+ discoveryEndpoint: {
389
+ type: "string",
390
+ format: "uri",
391
+ description: "The discovery endpoint URL",
392
+ },
393
+ userInfoEndpoint: {
394
+ type: "string",
395
+ format: "uri",
396
+ nullable: true,
397
+ description: "The user info endpoint URL",
398
+ },
399
+ scopes: {
400
+ type: "array",
401
+ items: { type: "string" },
402
+ nullable: true,
403
+ description:
404
+ "The scopes requested from the provider",
405
+ },
406
+ tokenEndpoint: {
407
+ type: "string",
408
+ format: "uri",
409
+ nullable: true,
410
+ description: "The token endpoint URL",
411
+ },
412
+ tokenEndpointAuthentication: {
413
+ type: "string",
414
+ enum: ["client_secret_post", "client_secret_basic"],
415
+ nullable: true,
416
+ description:
417
+ "Authentication method for the token endpoint",
418
+ },
419
+ jwksEndpoint: {
420
+ type: "string",
421
+ format: "uri",
422
+ nullable: true,
423
+ description: "The JWKS endpoint URL",
424
+ },
425
+ mapping: {
426
+ type: "object",
427
+ nullable: true,
428
+ properties: {
429
+ id: {
430
+ type: "string",
431
+ description:
432
+ "Field mapping for user ID (defaults to 'sub')",
433
+ },
434
+ email: {
435
+ type: "string",
436
+ description:
437
+ "Field mapping for email (defaults to 'email')",
438
+ },
439
+ emailVerified: {
440
+ type: "string",
441
+ nullable: true,
442
+ description:
443
+ "Field mapping for email verification (defaults to 'email_verified')",
444
+ },
445
+ name: {
446
+ type: "string",
447
+ description:
448
+ "Field mapping for name (defaults to 'name')",
449
+ },
450
+ image: {
451
+ type: "string",
452
+ nullable: true,
453
+ description:
454
+ "Field mapping for image (defaults to 'picture')",
455
+ },
456
+ extraFields: {
457
+ type: "object",
458
+ additionalProperties: { type: "string" },
459
+ nullable: true,
460
+ description: "Additional field mappings",
461
+ },
462
+ },
463
+ required: ["id", "email", "name"],
464
+ },
465
+ },
466
+ required: [
467
+ "issuer",
468
+ "pkce",
469
+ "clientId",
470
+ "clientSecret",
471
+ "discoveryEndpoint",
472
+ ],
473
+ description: "OIDC configuration for the provider",
474
+ },
475
+ organizationId: {
476
+ type: "string",
477
+ nullable: true,
478
+ description: "ID of the linked organization, if any",
479
+ },
480
+ userId: {
481
+ type: "string",
482
+ description:
483
+ "ID of the user who registered the provider",
484
+ },
485
+ providerId: {
486
+ type: "string",
487
+ description: "Unique identifier for the provider",
488
+ },
489
+ redirectURI: {
490
+ type: "string",
491
+ format: "uri",
492
+ description:
493
+ "The redirect URI for the provider callback",
494
+ },
495
+ },
496
+ required: [
497
+ "issuer",
498
+ "domain",
499
+ "oidcConfig",
500
+ "userId",
501
+ "providerId",
502
+ "redirectURI",
503
+ ],
504
+ },
505
+ },
506
+ },
507
+ },
508
+ },
509
+ },
510
+ },
511
+ },
512
+ async (ctx) => {
513
+ const user = ctx.context.session?.user;
514
+ if (!user) {
515
+ throw new APIError("UNAUTHORIZED");
516
+ }
517
+
518
+ const limit =
519
+ typeof options?.providersLimit === "function"
520
+ ? await options.providersLimit(user)
521
+ : (options?.providersLimit ?? 10);
522
+
523
+ if (!limit) {
524
+ throw new APIError("FORBIDDEN", {
525
+ message: "SSO provider registration is disabled",
526
+ });
527
+ }
528
+
529
+ const providers = await ctx.context.adapter.findMany({
530
+ model: "ssoProvider",
531
+ where: [{ field: "userId", value: user.id }],
532
+ });
533
+
534
+ if (providers.length >= limit) {
535
+ throw new APIError("FORBIDDEN", {
536
+ message: "You have reached the maximum number of SSO providers",
537
+ });
538
+ }
539
+
540
+ const body = ctx.body;
541
+ const issuerValidator = z.string().url();
542
+ if (issuerValidator.safeParse(body.issuer).error) {
543
+ throw new APIError("BAD_REQUEST", {
544
+ message: "Invalid issuer. Must be a valid URL",
545
+ });
546
+ }
547
+ if (ctx.body.organizationId) {
548
+ const organization = await ctx.context.adapter.findOne({
549
+ model: "member",
550
+ where: [
551
+ {
552
+ field: "userId",
553
+ value: user.id,
554
+ },
555
+ {
556
+ field: "organizationId",
557
+ value: ctx.body.organizationId,
558
+ },
559
+ ],
560
+ });
561
+ if (!organization) {
562
+ throw new APIError("BAD_REQUEST", {
563
+ message: "You are not a member of the organization",
564
+ });
565
+ }
566
+ }
567
+
568
+ const existingProvider = await ctx.context.adapter.findOne({
569
+ model: "ssoProvider",
570
+ where: [
571
+ {
572
+ field: "providerId",
573
+ value: body.providerId,
574
+ },
575
+ ],
576
+ });
577
+
578
+ if (existingProvider) {
579
+ ctx.context.logger.info(
580
+ `SSO provider creation attempt with existing providerId: ${body.providerId}`,
581
+ );
582
+ throw new APIError("UNPROCESSABLE_ENTITY", {
583
+ message: "SSO provider with this providerId already exists",
584
+ });
585
+ }
586
+
587
+ const provider = await ctx.context.adapter.create<
588
+ Record<string, any>,
589
+ SSOProvider
590
+ >({
591
+ model: "ssoProvider",
592
+ data: {
593
+ issuer: body.issuer,
594
+ domain: body.domain,
595
+ oidcConfig: body.oidcConfig
596
+ ? JSON.stringify({
597
+ issuer: body.issuer,
598
+ clientId: body.oidcConfig.clientId,
599
+ clientSecret: body.oidcConfig.clientSecret,
600
+ authorizationEndpoint: body.oidcConfig.authorizationEndpoint,
601
+ tokenEndpoint: body.oidcConfig.tokenEndpoint,
602
+ tokenEndpointAuthentication:
603
+ body.oidcConfig.tokenEndpointAuthentication,
604
+ jwksEndpoint: body.oidcConfig.jwksEndpoint,
605
+ pkce: body.oidcConfig.pkce,
606
+ discoveryEndpoint:
607
+ body.oidcConfig.discoveryEndpoint ||
608
+ `${body.issuer}/.well-known/openid-configuration`,
609
+ mapping: body.oidcConfig.mapping,
610
+ scopes: body.oidcConfig.scopes,
611
+ userInfoEndpoint: body.oidcConfig.userInfoEndpoint,
612
+ overrideUserInfo:
613
+ ctx.body.overrideUserInfo ||
614
+ options?.defaultOverrideUserInfo ||
615
+ false,
616
+ })
617
+ : null,
618
+ samlConfig: body.samlConfig
619
+ ? JSON.stringify({
620
+ issuer: body.issuer,
621
+ entryPoint: body.samlConfig.entryPoint,
622
+ cert: body.samlConfig.cert,
623
+ callbackUrl: body.samlConfig.callbackUrl,
624
+ audience: body.samlConfig.audience,
625
+ idpMetadata: body.samlConfig.idpMetadata,
626
+ spMetadata: body.samlConfig.spMetadata,
627
+ wantAssertionsSigned: body.samlConfig.wantAssertionsSigned,
628
+ signatureAlgorithm: body.samlConfig.signatureAlgorithm,
629
+ digestAlgorithm: body.samlConfig.digestAlgorithm,
630
+ identifierFormat: body.samlConfig.identifierFormat,
631
+ privateKey: body.samlConfig.privateKey,
632
+ decryptionPvk: body.samlConfig.decryptionPvk,
633
+ additionalParams: body.samlConfig.additionalParams,
634
+ mapping: body.samlConfig.mapping,
635
+ })
636
+ : null,
637
+ organizationId: body.organizationId,
638
+ userId: ctx.context.session.user.id,
639
+ providerId: body.providerId,
640
+ },
641
+ });
642
+
643
+ return ctx.json({
644
+ ...provider,
645
+ oidcConfig: JSON.parse(
646
+ provider.oidcConfig as unknown as string,
647
+ ) as OIDCConfig,
648
+ samlConfig: JSON.parse(
649
+ provider.samlConfig as unknown as string,
650
+ ) as SAMLConfig,
651
+ redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`,
652
+ });
653
+ },
654
+ );
655
+ };
656
+
657
+ export const signInSSO = (options?: SSOOptions) => {
658
+ return createAuthEndpoint(
659
+ "/sign-in/sso",
660
+ {
661
+ method: "POST",
662
+ body: z.object({
663
+ email: z
664
+ .string({})
665
+ .meta({
666
+ description:
667
+ "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",
668
+ })
669
+ .optional(),
670
+ organizationSlug: z
671
+ .string({})
672
+ .meta({
673
+ description: "The slug of the organization to sign in with",
674
+ })
675
+ .optional(),
676
+ providerId: z
677
+ .string({})
678
+ .meta({
679
+ description:
680
+ "The ID of the provider to sign in with. This can be provided instead of email or issuer",
681
+ })
682
+ .optional(),
683
+ domain: z
684
+ .string({})
685
+ .meta({
686
+ description: "The domain of the provider.",
687
+ })
688
+ .optional(),
689
+ callbackURL: z.string({}).meta({
690
+ description: "The URL to redirect to after login",
691
+ }),
692
+ errorCallbackURL: z
693
+ .string({})
694
+ .meta({
695
+ description: "The URL to redirect to after login",
696
+ })
697
+ .optional(),
698
+ newUserCallbackURL: z
699
+ .string({})
700
+ .meta({
701
+ description:
702
+ "The URL to redirect to after login if the user is new",
703
+ })
704
+ .optional(),
705
+ scopes: z
706
+ .array(z.string(), {})
707
+ .meta({
708
+ description: "Scopes to request from the provider.",
709
+ })
710
+ .optional(),
711
+ loginHint: z
712
+ .string({})
713
+ .meta({
714
+ description:
715
+ "Login hint to send to the identity provider (e.g., email or identifier). If supported, will be sent as 'login_hint'.",
716
+ })
717
+ .optional(),
718
+ requestSignUp: z
719
+ .boolean({})
720
+ .meta({
721
+ description:
722
+ "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider",
723
+ })
724
+ .optional(),
725
+ providerType: z.enum(["oidc", "saml"]).optional(),
726
+ }),
727
+ metadata: {
728
+ openapi: {
729
+ summary: "Sign in with SSO provider",
730
+ description:
731
+ "This endpoint is used to sign in with an SSO provider. It redirects to the provider's authorization URL",
732
+ requestBody: {
733
+ content: {
734
+ "application/json": {
735
+ schema: {
736
+ type: "object",
737
+ properties: {
738
+ email: {
739
+ type: "string",
740
+ description:
741
+ "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",
742
+ },
743
+ issuer: {
744
+ type: "string",
745
+ description:
746
+ "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",
747
+ },
748
+ providerId: {
749
+ type: "string",
750
+ description:
751
+ "The ID of the provider to sign in with. This can be provided instead of email or issuer",
752
+ },
753
+ callbackURL: {
754
+ type: "string",
755
+ description: "The URL to redirect to after login",
756
+ },
757
+ errorCallbackURL: {
758
+ type: "string",
759
+ description: "The URL to redirect to after login",
760
+ },
761
+ newUserCallbackURL: {
762
+ type: "string",
763
+ description:
764
+ "The URL to redirect to after login if the user is new",
765
+ },
766
+ loginHint: {
767
+ type: "string",
768
+ description:
769
+ "Login hint to send to the identity provider (e.g., email or identifier). If supported, sent as 'login_hint'.",
770
+ },
771
+ },
772
+ required: ["callbackURL"],
773
+ },
774
+ },
775
+ },
776
+ },
777
+ responses: {
778
+ "200": {
779
+ description:
780
+ "Authorization URL generated successfully for SSO sign-in",
781
+ content: {
782
+ "application/json": {
783
+ schema: {
784
+ type: "object",
785
+ properties: {
786
+ url: {
787
+ type: "string",
788
+ format: "uri",
789
+ description:
790
+ "The authorization URL to redirect the user to for SSO sign-in",
791
+ },
792
+ redirect: {
793
+ type: "boolean",
794
+ description:
795
+ "Indicates that the client should redirect to the provided URL",
796
+ enum: [true],
797
+ },
798
+ },
799
+ required: ["url", "redirect"],
800
+ },
801
+ },
802
+ },
803
+ },
804
+ },
805
+ },
806
+ },
807
+ },
808
+ async (ctx) => {
809
+ const body = ctx.body;
810
+ let { email, organizationSlug, providerId, domain } = body;
811
+ if (
812
+ !options?.defaultSSO?.length &&
813
+ !email &&
814
+ !organizationSlug &&
815
+ !domain &&
816
+ !providerId
817
+ ) {
818
+ throw new APIError("BAD_REQUEST", {
819
+ message: "email, organizationSlug, domain or providerId is required",
820
+ });
821
+ }
822
+ domain = body.domain || email?.split("@")[1];
823
+ let orgId = "";
824
+ if (organizationSlug) {
825
+ orgId = await ctx.context.adapter
826
+ .findOne<{ id: string }>({
827
+ model: "organization",
828
+ where: [
829
+ {
830
+ field: "slug",
831
+ value: organizationSlug,
832
+ },
833
+ ],
834
+ })
835
+ .then((res) => {
836
+ if (!res) {
837
+ return "";
838
+ }
839
+ return res.id;
840
+ });
841
+ }
842
+ let provider: SSOProvider | null = null;
843
+ if (options?.defaultSSO?.length) {
844
+ // Find matching default SSO provider by providerId
845
+ const matchingDefault = providerId
846
+ ? options.defaultSSO.find(
847
+ (defaultProvider) => defaultProvider.providerId === providerId,
848
+ )
849
+ : options.defaultSSO.find(
850
+ (defaultProvider) => defaultProvider.domain === domain,
851
+ );
852
+
853
+ if (matchingDefault) {
854
+ provider = {
855
+ issuer:
856
+ matchingDefault.samlConfig?.issuer ||
857
+ matchingDefault.oidcConfig?.issuer ||
858
+ "",
859
+ providerId: matchingDefault.providerId,
860
+ userId: "default",
861
+ oidcConfig: matchingDefault.oidcConfig,
862
+ samlConfig: matchingDefault.samlConfig,
863
+ domain: matchingDefault.domain,
864
+ };
865
+ }
866
+ }
867
+ if (!providerId && !orgId && !domain) {
868
+ throw new APIError("BAD_REQUEST", {
869
+ message: "providerId, orgId or domain is required",
870
+ });
871
+ }
872
+ // Try to find provider in database
873
+ if (!provider) {
874
+ provider = await ctx.context.adapter
875
+ .findOne<SSOProvider>({
876
+ model: "ssoProvider",
877
+ where: [
878
+ {
879
+ field: providerId
880
+ ? "providerId"
881
+ : orgId
882
+ ? "organizationId"
883
+ : "domain",
884
+ value: providerId || orgId || domain!,
885
+ },
886
+ ],
887
+ })
888
+ .then((res) => {
889
+ if (!res) {
890
+ return null;
891
+ }
892
+ return {
893
+ ...res,
894
+ oidcConfig: res.oidcConfig
895
+ ? safeJsonParse<OIDCConfig>(
896
+ res.oidcConfig as unknown as string,
897
+ ) || undefined
898
+ : undefined,
899
+ samlConfig: res.samlConfig
900
+ ? safeJsonParse<SAMLConfig>(
901
+ res.samlConfig as unknown as string,
902
+ ) || undefined
903
+ : undefined,
904
+ };
905
+ });
906
+ }
907
+
908
+ if (!provider) {
909
+ throw new APIError("NOT_FOUND", {
910
+ message: "No provider found for the issuer",
911
+ });
912
+ }
913
+
914
+ if (body.providerType) {
915
+ if (body.providerType === "oidc" && !provider.oidcConfig) {
916
+ throw new APIError("BAD_REQUEST", {
917
+ message: "OIDC provider is not configured",
918
+ });
919
+ }
920
+ if (body.providerType === "saml" && !provider.samlConfig) {
921
+ throw new APIError("BAD_REQUEST", {
922
+ message: "SAML provider is not configured",
923
+ });
924
+ }
925
+ }
926
+
927
+ if (provider.oidcConfig && body.providerType !== "saml") {
928
+ const state = await generateState(ctx, undefined, false);
929
+ const redirectURI = `${ctx.context.baseURL}/sso/callback/${provider.providerId}`;
930
+ const authorizationURL = await createAuthorizationURL({
931
+ id: provider.issuer,
932
+ options: {
933
+ clientId: provider.oidcConfig.clientId,
934
+ clientSecret: provider.oidcConfig.clientSecret,
935
+ },
936
+ redirectURI,
937
+ state: state.state,
938
+ codeVerifier: provider.oidcConfig.pkce
939
+ ? state.codeVerifier
940
+ : undefined,
941
+ scopes: ctx.body.scopes ||
942
+ provider.oidcConfig.scopes || [
943
+ "openid",
944
+ "email",
945
+ "profile",
946
+ "offline_access",
947
+ ],
948
+ loginHint: ctx.body.loginHint || email,
949
+ authorizationEndpoint: provider.oidcConfig.authorizationEndpoint!,
950
+ });
951
+ return ctx.json({
952
+ url: authorizationURL.toString(),
953
+ redirect: true,
954
+ });
955
+ }
956
+ if (provider.samlConfig) {
957
+ const parsedSamlConfig =
958
+ typeof provider.samlConfig === "object"
959
+ ? provider.samlConfig
960
+ : safeJsonParse<SAMLConfig>(
961
+ provider.samlConfig as unknown as string,
962
+ );
963
+ if (!parsedSamlConfig) {
964
+ throw new APIError("BAD_REQUEST", {
965
+ message: "Invalid SAML configuration",
966
+ });
967
+ }
968
+ const sp = saml.ServiceProvider({
969
+ metadata: parsedSamlConfig.spMetadata.metadata,
970
+ allowCreate: true,
971
+ });
972
+
973
+ const idp = saml.IdentityProvider({
974
+ metadata: parsedSamlConfig.idpMetadata?.metadata,
975
+ entityID: parsedSamlConfig.idpMetadata?.entityID,
976
+ encryptCert: parsedSamlConfig.idpMetadata?.cert,
977
+ singleSignOnService:
978
+ parsedSamlConfig.idpMetadata?.singleSignOnService,
979
+ });
980
+ const loginRequest = sp.createLoginRequest(
981
+ idp,
982
+ "redirect",
983
+ ) as BindingContext & { entityEndpoint: string; type: string };
984
+ if (!loginRequest) {
985
+ throw new APIError("BAD_REQUEST", {
986
+ message: "Invalid SAML request",
987
+ });
988
+ }
989
+ return ctx.json({
990
+ url: `${loginRequest.context}&RelayState=${encodeURIComponent(
991
+ body.callbackURL,
992
+ )}`,
993
+ redirect: true,
994
+ });
995
+ }
996
+ throw new APIError("BAD_REQUEST", {
997
+ message: "Invalid SSO provider",
998
+ });
999
+ },
1000
+ );
1001
+ };
1002
+
1003
+ export const callbackSSO = (options?: SSOOptions) => {
1004
+ return createAuthEndpoint(
1005
+ "/sso/callback/:providerId",
1006
+ {
1007
+ method: "GET",
1008
+ query: z.object({
1009
+ code: z.string().optional(),
1010
+ state: z.string(),
1011
+ error: z.string().optional(),
1012
+ error_description: z.string().optional(),
1013
+ }),
1014
+ metadata: {
1015
+ isAction: false,
1016
+ openapi: {
1017
+ summary: "Callback URL for SSO provider",
1018
+ description:
1019
+ "This endpoint is used as the callback URL for SSO providers. It handles the authorization code and exchanges it for an access token",
1020
+ responses: {
1021
+ "302": {
1022
+ description: "Redirects to the callback URL",
1023
+ },
1024
+ },
1025
+ },
1026
+ },
1027
+ },
1028
+ async (ctx) => {
1029
+ const { code, state, error, error_description } = ctx.query;
1030
+ const stateData = await parseState(ctx);
1031
+ if (!stateData) {
1032
+ const errorURL =
1033
+ ctx.context.options.onAPIError?.errorURL ||
1034
+ `${ctx.context.baseURL}/error`;
1035
+ throw ctx.redirect(`${errorURL}?error=invalid_state`);
1036
+ }
1037
+ const { callbackURL, errorURL, newUserURL, requestSignUp } = stateData;
1038
+ if (!code || error) {
1039
+ throw ctx.redirect(
1040
+ `${
1041
+ errorURL || callbackURL
1042
+ }?error=${error}&error_description=${error_description}`,
1043
+ );
1044
+ }
1045
+ let provider: SSOProvider | null = null;
1046
+ if (options?.defaultSSO?.length) {
1047
+ const matchingDefault = options.defaultSSO.find(
1048
+ (defaultProvider) =>
1049
+ defaultProvider.providerId === ctx.params.providerId,
1050
+ );
1051
+ if (matchingDefault) {
1052
+ provider = {
1053
+ ...matchingDefault,
1054
+ issuer: matchingDefault.oidcConfig?.issuer || "",
1055
+ userId: "default",
1056
+ };
1057
+ }
1058
+ }
1059
+ if (!provider) {
1060
+ provider = await ctx.context.adapter
1061
+ .findOne<{
1062
+ oidcConfig: string;
1063
+ }>({
1064
+ model: "ssoProvider",
1065
+ where: [
1066
+ {
1067
+ field: "providerId",
1068
+ value: ctx.params.providerId,
1069
+ },
1070
+ ],
1071
+ })
1072
+ .then((res) => {
1073
+ if (!res) {
1074
+ return null;
1075
+ }
1076
+ return {
1077
+ ...res,
1078
+ oidcConfig:
1079
+ safeJsonParse<OIDCConfig>(res.oidcConfig) || undefined,
1080
+ } as SSOProvider;
1081
+ });
1082
+ }
1083
+ if (!provider) {
1084
+ throw ctx.redirect(
1085
+ `${
1086
+ errorURL || callbackURL
1087
+ }/error?error=invalid_provider&error_description=provider not found`,
1088
+ );
1089
+ }
1090
+
1091
+ let config = provider.oidcConfig;
1092
+
1093
+ if (!config) {
1094
+ throw ctx.redirect(
1095
+ `${
1096
+ errorURL || callbackURL
1097
+ }/error?error=invalid_provider&error_description=provider not found`,
1098
+ );
1099
+ }
1100
+
1101
+ const discovery = await betterFetch<{
1102
+ token_endpoint: string;
1103
+ userinfo_endpoint: string;
1104
+ token_endpoint_auth_method:
1105
+ | "client_secret_basic"
1106
+ | "client_secret_post";
1107
+ }>(config.discoveryEndpoint);
1108
+
1109
+ if (discovery.data) {
1110
+ config = {
1111
+ tokenEndpoint: discovery.data.token_endpoint,
1112
+ tokenEndpointAuthentication:
1113
+ discovery.data.token_endpoint_auth_method,
1114
+ userInfoEndpoint: discovery.data.userinfo_endpoint,
1115
+ scopes: ["openid", "email", "profile", "offline_access"],
1116
+ ...config,
1117
+ };
1118
+ }
1119
+
1120
+ if (!config.tokenEndpoint) {
1121
+ throw ctx.redirect(
1122
+ `${
1123
+ errorURL || callbackURL
1124
+ }/error?error=invalid_provider&error_description=token_endpoint_not_found`,
1125
+ );
1126
+ }
1127
+
1128
+ const tokenResponse = await validateAuthorizationCode({
1129
+ code,
1130
+ codeVerifier: config.pkce ? stateData.codeVerifier : undefined,
1131
+ redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`,
1132
+ options: {
1133
+ clientId: config.clientId,
1134
+ clientSecret: config.clientSecret,
1135
+ },
1136
+ tokenEndpoint: config.tokenEndpoint,
1137
+ authentication:
1138
+ config.tokenEndpointAuthentication === "client_secret_post"
1139
+ ? "post"
1140
+ : "basic",
1141
+ }).catch((e) => {
1142
+ if (e instanceof BetterFetchError) {
1143
+ throw ctx.redirect(
1144
+ `${
1145
+ errorURL || callbackURL
1146
+ }?error=invalid_provider&error_description=${e.message}`,
1147
+ );
1148
+ }
1149
+ return null;
1150
+ });
1151
+ if (!tokenResponse) {
1152
+ throw ctx.redirect(
1153
+ `${
1154
+ errorURL || callbackURL
1155
+ }/error?error=invalid_provider&error_description=token_response_not_found`,
1156
+ );
1157
+ }
1158
+ let userInfo: {
1159
+ id?: string;
1160
+ email?: string;
1161
+ name?: string;
1162
+ image?: string;
1163
+ emailVerified?: boolean;
1164
+ [key: string]: any;
1165
+ } | null = null;
1166
+ if (tokenResponse.idToken) {
1167
+ const idToken = decodeJwt(tokenResponse.idToken);
1168
+ if (!config.jwksEndpoint) {
1169
+ throw ctx.redirect(
1170
+ `${
1171
+ errorURL || callbackURL
1172
+ }/error?error=invalid_provider&error_description=jwks_endpoint_not_found`,
1173
+ );
1174
+ }
1175
+ const verified = await validateToken(
1176
+ tokenResponse.idToken,
1177
+ config.jwksEndpoint,
1178
+ ).catch((e) => {
1179
+ ctx.context.logger.error(e);
1180
+ return null;
1181
+ });
1182
+ if (!verified) {
1183
+ throw ctx.redirect(
1184
+ `${
1185
+ errorURL || callbackURL
1186
+ }/error?error=invalid_provider&error_description=token_not_verified`,
1187
+ );
1188
+ }
1189
+ if (verified.payload.iss !== provider.issuer) {
1190
+ throw ctx.redirect(
1191
+ `${
1192
+ errorURL || callbackURL
1193
+ }/error?error=invalid_provider&error_description=issuer_mismatch`,
1194
+ );
1195
+ }
1196
+
1197
+ const mapping = config.mapping || {};
1198
+ userInfo = {
1199
+ ...Object.fromEntries(
1200
+ Object.entries(mapping.extraFields || {}).map(([key, value]) => [
1201
+ key,
1202
+ verified.payload[value],
1203
+ ]),
1204
+ ),
1205
+ id: idToken[mapping.id || "sub"],
1206
+ email: idToken[mapping.email || "email"],
1207
+ emailVerified: options?.trustEmailVerified
1208
+ ? idToken[mapping.emailVerified || "email_verified"]
1209
+ : false,
1210
+ name: idToken[mapping.name || "name"],
1211
+ image: idToken[mapping.image || "picture"],
1212
+ } as {
1213
+ id?: string;
1214
+ email?: string;
1215
+ name?: string;
1216
+ image?: string;
1217
+ emailVerified?: boolean;
1218
+ };
1219
+ }
1220
+
1221
+ if (!userInfo) {
1222
+ if (!config.userInfoEndpoint) {
1223
+ throw ctx.redirect(
1224
+ `${
1225
+ errorURL || callbackURL
1226
+ }/error?error=invalid_provider&error_description=user_info_endpoint_not_found`,
1227
+ );
1228
+ }
1229
+ const userInfoResponse = await betterFetch<{
1230
+ email?: string;
1231
+ name?: string;
1232
+ id?: string;
1233
+ image?: string;
1234
+ emailVerified?: boolean;
1235
+ }>(config.userInfoEndpoint, {
1236
+ headers: {
1237
+ Authorization: `Bearer ${tokenResponse.accessToken}`,
1238
+ },
1239
+ });
1240
+ if (userInfoResponse.error) {
1241
+ throw ctx.redirect(
1242
+ `${
1243
+ errorURL || callbackURL
1244
+ }/error?error=invalid_provider&error_description=${
1245
+ userInfoResponse.error.message
1246
+ }`,
1247
+ );
1248
+ }
1249
+ userInfo = userInfoResponse.data;
1250
+ }
1251
+
1252
+ if (!userInfo.email || !userInfo.id) {
1253
+ throw ctx.redirect(
1254
+ `${
1255
+ errorURL || callbackURL
1256
+ }/error?error=invalid_provider&error_description=missing_user_info`,
1257
+ );
1258
+ }
1259
+ const linked = await handleOAuthUserInfo(ctx, {
1260
+ userInfo: {
1261
+ email: userInfo.email,
1262
+ name: userInfo.name || userInfo.email,
1263
+ id: userInfo.id,
1264
+ image: userInfo.image,
1265
+ emailVerified: options?.trustEmailVerified
1266
+ ? userInfo.emailVerified || false
1267
+ : false,
1268
+ },
1269
+ account: {
1270
+ idToken: tokenResponse.idToken,
1271
+ accessToken: tokenResponse.accessToken,
1272
+ refreshToken: tokenResponse.refreshToken,
1273
+ accountId: userInfo.id,
1274
+ providerId: provider.providerId,
1275
+ accessTokenExpiresAt: tokenResponse.accessTokenExpiresAt,
1276
+ refreshTokenExpiresAt: tokenResponse.refreshTokenExpiresAt,
1277
+ scope: tokenResponse.scopes?.join(","),
1278
+ },
1279
+ callbackURL,
1280
+ disableSignUp: options?.disableImplicitSignUp && !requestSignUp,
1281
+ overrideUserInfo: config.overrideUserInfo,
1282
+ });
1283
+ if (linked.error) {
1284
+ throw ctx.redirect(
1285
+ `${errorURL || callbackURL}/error?error=${linked.error}`,
1286
+ );
1287
+ }
1288
+ const { session, user } = linked.data!;
1289
+
1290
+ if (options?.provisionUser) {
1291
+ await options.provisionUser({
1292
+ user,
1293
+ userInfo,
1294
+ token: tokenResponse,
1295
+ provider,
1296
+ });
1297
+ }
1298
+ if (
1299
+ provider.organizationId &&
1300
+ !options?.organizationProvisioning?.disabled
1301
+ ) {
1302
+ const isOrgPluginEnabled = ctx.context.options.plugins?.find(
1303
+ (plugin) => plugin.id === "organization",
1304
+ );
1305
+ if (isOrgPluginEnabled) {
1306
+ const isAlreadyMember = await ctx.context.adapter.findOne({
1307
+ model: "member",
1308
+ where: [
1309
+ { field: "organizationId", value: provider.organizationId },
1310
+ { field: "userId", value: user.id },
1311
+ ],
1312
+ });
1313
+ if (!isAlreadyMember) {
1314
+ const role = options?.organizationProvisioning?.getRole
1315
+ ? await options.organizationProvisioning.getRole({
1316
+ user,
1317
+ userInfo,
1318
+ token: tokenResponse,
1319
+ provider,
1320
+ })
1321
+ : options?.organizationProvisioning?.defaultRole || "member";
1322
+ await ctx.context.adapter.create({
1323
+ model: "member",
1324
+ data: {
1325
+ organizationId: provider.organizationId,
1326
+ userId: user.id,
1327
+ role,
1328
+ createdAt: new Date(),
1329
+ updatedAt: new Date(),
1330
+ },
1331
+ });
1332
+ }
1333
+ }
1334
+ }
1335
+ await setSessionCookie(ctx, {
1336
+ session,
1337
+ user,
1338
+ });
1339
+ let toRedirectTo: string;
1340
+ try {
1341
+ const url = linked.isRegister ? newUserURL || callbackURL : callbackURL;
1342
+ toRedirectTo = url.toString();
1343
+ } catch {
1344
+ toRedirectTo = linked.isRegister
1345
+ ? newUserURL || callbackURL
1346
+ : callbackURL;
1347
+ }
1348
+ throw ctx.redirect(toRedirectTo);
1349
+ },
1350
+ );
1351
+ };
1352
+
1353
+ export const callbackSSOSAML = (options?: SSOOptions) => {
1354
+ return createAuthEndpoint(
1355
+ "/sso/saml2/callback/:providerId",
1356
+ {
1357
+ method: "POST",
1358
+ body: z.object({
1359
+ SAMLResponse: z.string(),
1360
+ RelayState: z.string().optional(),
1361
+ }),
1362
+ metadata: {
1363
+ isAction: false,
1364
+ openapi: {
1365
+ summary: "Callback URL for SAML provider",
1366
+ description:
1367
+ "This endpoint is used as the callback URL for SAML providers.",
1368
+ responses: {
1369
+ "302": {
1370
+ description: "Redirects to the callback URL",
1371
+ },
1372
+ "400": {
1373
+ description: "Invalid SAML response",
1374
+ },
1375
+ "401": {
1376
+ description: "Unauthorized - SAML authentication failed",
1377
+ },
1378
+ },
1379
+ },
1380
+ },
1381
+ },
1382
+ async (ctx) => {
1383
+ const { SAMLResponse, RelayState } = ctx.body;
1384
+ const { providerId } = ctx.params;
1385
+ let provider: SSOProvider | null = null;
1386
+ if (options?.defaultSSO?.length) {
1387
+ const matchingDefault = options.defaultSSO.find(
1388
+ (defaultProvider) => defaultProvider.providerId === providerId,
1389
+ );
1390
+ if (matchingDefault) {
1391
+ provider = {
1392
+ ...matchingDefault,
1393
+ userId: "default",
1394
+ issuer: matchingDefault.samlConfig?.issuer || "",
1395
+ };
1396
+ }
1397
+ }
1398
+ if (!provider) {
1399
+ provider = await ctx.context.adapter
1400
+ .findOne<SSOProvider>({
1401
+ model: "ssoProvider",
1402
+ where: [{ field: "providerId", value: providerId }],
1403
+ })
1404
+ .then((res) => {
1405
+ if (!res) return null;
1406
+ return {
1407
+ ...res,
1408
+ samlConfig: res.samlConfig
1409
+ ? safeJsonParse<SAMLConfig>(
1410
+ res.samlConfig as unknown as string,
1411
+ ) || undefined
1412
+ : undefined,
1413
+ };
1414
+ });
1415
+ }
1416
+
1417
+ if (!provider) {
1418
+ throw new APIError("NOT_FOUND", {
1419
+ message: "No provider found for the given providerId",
1420
+ });
1421
+ }
1422
+
1423
+ const parsedSamlConfig = safeJsonParse<SAMLConfig>(
1424
+ provider.samlConfig as unknown as string,
1425
+ );
1426
+ if (!parsedSamlConfig) {
1427
+ throw new APIError("BAD_REQUEST", {
1428
+ message: "Invalid SAML configuration",
1429
+ });
1430
+ }
1431
+ const idpData = parsedSamlConfig.idpMetadata;
1432
+ let idp: IdentityProvider | null = null;
1433
+
1434
+ // Construct IDP with fallback to manual configuration
1435
+ if (!idpData?.metadata) {
1436
+ idp = saml.IdentityProvider({
1437
+ entityID: idpData?.entityID || parsedSamlConfig.issuer,
1438
+ singleSignOnService: [
1439
+ {
1440
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
1441
+ Location: parsedSamlConfig.entryPoint,
1442
+ },
1443
+ ],
1444
+ signingCert: idpData?.cert || parsedSamlConfig.cert,
1445
+ wantAuthnRequestsSigned:
1446
+ parsedSamlConfig.wantAssertionsSigned || false,
1447
+ isAssertionEncrypted: idpData?.isAssertionEncrypted || false,
1448
+ encPrivateKey: idpData?.encPrivateKey,
1449
+ encPrivateKeyPass: idpData?.encPrivateKeyPass,
1450
+ });
1451
+ } else {
1452
+ idp = saml.IdentityProvider({
1453
+ metadata: idpData.metadata,
1454
+ privateKey: idpData.privateKey,
1455
+ privateKeyPass: idpData.privateKeyPass,
1456
+ isAssertionEncrypted: idpData.isAssertionEncrypted,
1457
+ encPrivateKey: idpData.encPrivateKey,
1458
+ encPrivateKeyPass: idpData.encPrivateKeyPass,
1459
+ });
1460
+ }
1461
+
1462
+ // Construct SP with fallback to manual configuration
1463
+ const spData = parsedSamlConfig.spMetadata;
1464
+ const sp = saml.ServiceProvider({
1465
+ metadata: spData?.metadata,
1466
+ entityID: spData?.entityID || parsedSamlConfig.issuer,
1467
+ assertionConsumerService: spData?.metadata
1468
+ ? undefined
1469
+ : [
1470
+ {
1471
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
1472
+ Location: parsedSamlConfig.callbackUrl,
1473
+ },
1474
+ ],
1475
+ privateKey: spData?.privateKey || parsedSamlConfig.privateKey,
1476
+ privateKeyPass: spData?.privateKeyPass,
1477
+ isAssertionEncrypted: spData?.isAssertionEncrypted || false,
1478
+ encPrivateKey: spData?.encPrivateKey,
1479
+ encPrivateKeyPass: spData?.encPrivateKeyPass,
1480
+ wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
1481
+ nameIDFormat: parsedSamlConfig.identifierFormat
1482
+ ? [parsedSamlConfig.identifierFormat]
1483
+ : undefined,
1484
+ });
1485
+
1486
+ let parsedResponse: FlowResult;
1487
+ try {
1488
+ const decodedResponse = Buffer.from(SAMLResponse, "base64").toString(
1489
+ "utf-8",
1490
+ );
1491
+
1492
+ try {
1493
+ parsedResponse = await sp.parseLoginResponse(idp, "post", {
1494
+ body: {
1495
+ SAMLResponse,
1496
+ RelayState: RelayState || undefined,
1497
+ },
1498
+ });
1499
+ } catch (parseError) {
1500
+ const nameIDMatch = decodedResponse.match(
1501
+ /<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/,
1502
+ );
1503
+ if (!nameIDMatch) throw parseError;
1504
+ parsedResponse = {
1505
+ extract: {
1506
+ nameID: nameIDMatch[1],
1507
+ attributes: { nameID: nameIDMatch[1] },
1508
+ sessionIndex: {},
1509
+ conditions: {},
1510
+ },
1511
+ } as FlowResult;
1512
+ }
1513
+
1514
+ if (!parsedResponse?.extract) {
1515
+ throw new Error("Invalid SAML response structure");
1516
+ }
1517
+ } catch (error) {
1518
+ ctx.context.logger.error("SAML response validation failed", {
1519
+ error,
1520
+ decodedResponse: Buffer.from(SAMLResponse, "base64").toString(
1521
+ "utf-8",
1522
+ ),
1523
+ });
1524
+ throw new APIError("BAD_REQUEST", {
1525
+ message: "Invalid SAML response",
1526
+ details: error instanceof Error ? error.message : String(error),
1527
+ });
1528
+ }
1529
+
1530
+ const { extract } = parsedResponse!;
1531
+ const attributes = extract.attributes || {};
1532
+ const mapping = parsedSamlConfig.mapping ?? {};
1533
+
1534
+ const userInfo = {
1535
+ ...Object.fromEntries(
1536
+ Object.entries(mapping.extraFields || {}).map(([key, value]) => [
1537
+ key,
1538
+ attributes[value as string],
1539
+ ]),
1540
+ ),
1541
+ id: attributes[mapping.id || "nameID"] || extract.nameID,
1542
+ email: attributes[mapping.email || "email"] || extract.nameID,
1543
+ name:
1544
+ [
1545
+ attributes[mapping.firstName || "givenName"],
1546
+ attributes[mapping.lastName || "surname"],
1547
+ ]
1548
+ .filter(Boolean)
1549
+ .join(" ") ||
1550
+ attributes[mapping.name || "displayName"] ||
1551
+ extract.nameID,
1552
+ emailVerified:
1553
+ options?.trustEmailVerified && mapping.emailVerified
1554
+ ? ((attributes[mapping.emailVerified] || false) as boolean)
1555
+ : false,
1556
+ };
1557
+ if (!userInfo.id || !userInfo.email) {
1558
+ ctx.context.logger.error(
1559
+ "Missing essential user info from SAML response",
1560
+ {
1561
+ attributes: Object.keys(attributes),
1562
+ mapping,
1563
+ extractedId: userInfo.id,
1564
+ extractedEmail: userInfo.email,
1565
+ },
1566
+ );
1567
+ throw new APIError("BAD_REQUEST", {
1568
+ message: "Unable to extract user ID or email from SAML response",
1569
+ });
1570
+ }
1571
+
1572
+ // Find or create user
1573
+ let user: User;
1574
+ const existingUser = await ctx.context.adapter.findOne<User>({
1575
+ model: "user",
1576
+ where: [
1577
+ {
1578
+ field: "email",
1579
+ value: userInfo.email,
1580
+ },
1581
+ ],
1582
+ });
1583
+
1584
+ if (existingUser) {
1585
+ user = existingUser;
1586
+ } else {
1587
+ user = await ctx.context.internalAdapter.createUser({
1588
+ email: userInfo.email,
1589
+ name: userInfo.name,
1590
+ emailVerified: userInfo.emailVerified,
1591
+ });
1592
+ }
1593
+
1594
+ // Create or update account link
1595
+ const account = await ctx.context.adapter.findOne<Account>({
1596
+ model: "account",
1597
+ where: [
1598
+ { field: "userId", value: user.id },
1599
+ { field: "providerId", value: provider.providerId },
1600
+ { field: "accountId", value: userInfo.id },
1601
+ ],
1602
+ });
1603
+
1604
+ if (!account) {
1605
+ await ctx.context.internalAdapter.createAccount({
1606
+ userId: user.id,
1607
+ providerId: provider.providerId,
1608
+ accountId: userInfo.id,
1609
+ accessToken: "",
1610
+ refreshToken: "",
1611
+ });
1612
+ }
1613
+
1614
+ // Run provision hooks
1615
+ if (options?.provisionUser) {
1616
+ await options.provisionUser({
1617
+ user: user as User & Record<string, any>,
1618
+ userInfo,
1619
+ provider,
1620
+ });
1621
+ }
1622
+
1623
+ // Handle organization provisioning
1624
+ if (
1625
+ provider.organizationId &&
1626
+ !options?.organizationProvisioning?.disabled
1627
+ ) {
1628
+ const isOrgPluginEnabled = ctx.context.options.plugins?.find(
1629
+ (plugin) => plugin.id === "organization",
1630
+ );
1631
+ if (isOrgPluginEnabled) {
1632
+ const isAlreadyMember = await ctx.context.adapter.findOne({
1633
+ model: "member",
1634
+ where: [
1635
+ { field: "organizationId", value: provider.organizationId },
1636
+ { field: "userId", value: user.id },
1637
+ ],
1638
+ });
1639
+ if (!isAlreadyMember) {
1640
+ const role = options?.organizationProvisioning?.getRole
1641
+ ? await options.organizationProvisioning.getRole({
1642
+ user,
1643
+ userInfo,
1644
+ provider,
1645
+ })
1646
+ : options?.organizationProvisioning?.defaultRole || "member";
1647
+ await ctx.context.adapter.create({
1648
+ model: "member",
1649
+ data: {
1650
+ organizationId: provider.organizationId,
1651
+ userId: user.id,
1652
+ role,
1653
+ createdAt: new Date(),
1654
+ updatedAt: new Date(),
1655
+ },
1656
+ });
1657
+ }
1658
+ }
1659
+ }
1660
+
1661
+ // Create session and set cookie
1662
+ let session: Session = await ctx.context.internalAdapter.createSession(
1663
+ user.id,
1664
+ );
1665
+ await setSessionCookie(ctx, { session, user });
1666
+
1667
+ // Redirect to callback URL
1668
+ const callbackUrl =
1669
+ RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
1670
+ throw ctx.redirect(callbackUrl);
1671
+ },
1672
+ );
1673
+ };
1674
+
1675
+ export const acsEndpoint = (options?: SSOOptions) => {
1676
+ return createAuthEndpoint(
1677
+ "/sso/saml2/sp/acs/:providerId",
1678
+ {
1679
+ method: "POST",
1680
+ params: z.object({
1681
+ providerId: z.string().optional(),
1682
+ }),
1683
+ body: z.object({
1684
+ SAMLResponse: z.string(),
1685
+ RelayState: z.string().optional(),
1686
+ }),
1687
+ metadata: {
1688
+ isAction: false,
1689
+ openapi: {
1690
+ summary: "SAML Assertion Consumer Service",
1691
+ description:
1692
+ "Handles SAML responses from IdP after successful authentication",
1693
+ responses: {
1694
+ "302": {
1695
+ description:
1696
+ "Redirects to the callback URL after successful authentication",
1697
+ },
1698
+ },
1699
+ },
1700
+ },
1701
+ },
1702
+ async (ctx) => {
1703
+ const { SAMLResponse, RelayState = "" } = ctx.body;
1704
+ const { providerId } = ctx.params;
1705
+
1706
+ // If defaultSSO is configured, use it as the provider
1707
+ let provider: SSOProvider | null = null;
1708
+
1709
+ if (options?.defaultSSO?.length) {
1710
+ // For ACS endpoint, we can use the first default provider or try to match by providerId
1711
+ const matchingDefault = providerId
1712
+ ? options.defaultSSO.find(
1713
+ (defaultProvider) => defaultProvider.providerId === providerId,
1714
+ )
1715
+ : options.defaultSSO[0]; // Use first default provider if no specific providerId
1716
+
1717
+ if (matchingDefault) {
1718
+ provider = {
1719
+ issuer: matchingDefault.samlConfig?.issuer || "",
1720
+ providerId: matchingDefault.providerId,
1721
+ userId: "default",
1722
+ samlConfig: matchingDefault.samlConfig,
1723
+ domain: matchingDefault.domain,
1724
+ };
1725
+ }
1726
+ } else {
1727
+ provider = await ctx.context.adapter
1728
+ .findOne<SSOProvider>({
1729
+ model: "ssoProvider",
1730
+ where: [
1731
+ {
1732
+ field: "providerId",
1733
+ value: providerId ?? "sso",
1734
+ },
1735
+ ],
1736
+ })
1737
+ .then((res) => {
1738
+ if (!res) return null;
1739
+ return {
1740
+ ...res,
1741
+ samlConfig: res.samlConfig
1742
+ ? safeJsonParse<SAMLConfig>(
1743
+ res.samlConfig as unknown as string,
1744
+ ) || undefined
1745
+ : undefined,
1746
+ };
1747
+ });
1748
+ }
1749
+
1750
+ if (!provider?.samlConfig) {
1751
+ throw new APIError("NOT_FOUND", {
1752
+ message: "No SAML provider found",
1753
+ });
1754
+ }
1755
+
1756
+ const parsedSamlConfig = provider.samlConfig;
1757
+ // Configure SP and IdP
1758
+ const sp = saml.ServiceProvider({
1759
+ entityID:
1760
+ parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
1761
+ assertionConsumerService: [
1762
+ {
1763
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
1764
+ Location:
1765
+ parsedSamlConfig.callbackUrl ||
1766
+ `${ctx.context.baseURL}/sso/saml2/sp/acs/${providerId}`,
1767
+ },
1768
+ ],
1769
+ wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
1770
+ metadata: parsedSamlConfig.spMetadata?.metadata,
1771
+ privateKey:
1772
+ parsedSamlConfig.spMetadata?.privateKey ||
1773
+ parsedSamlConfig.privateKey,
1774
+ privateKeyPass: parsedSamlConfig.spMetadata?.privateKeyPass,
1775
+ nameIDFormat: parsedSamlConfig.identifierFormat
1776
+ ? [parsedSamlConfig.identifierFormat]
1777
+ : undefined,
1778
+ });
1779
+
1780
+ // Update where we construct the IdP
1781
+ const idpData = parsedSamlConfig.idpMetadata;
1782
+ const idp = !idpData?.metadata
1783
+ ? saml.IdentityProvider({
1784
+ entityID: idpData?.entityID || parsedSamlConfig.issuer,
1785
+ singleSignOnService: idpData?.singleSignOnService || [
1786
+ {
1787
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
1788
+ Location: parsedSamlConfig.entryPoint,
1789
+ },
1790
+ ],
1791
+ signingCert: idpData?.cert || parsedSamlConfig.cert,
1792
+ })
1793
+ : saml.IdentityProvider({
1794
+ metadata: idpData.metadata,
1795
+ });
1796
+
1797
+ // Parse and validate SAML response
1798
+ let parsedResponse: FlowResult;
1799
+ try {
1800
+ let decodedResponse = Buffer.from(SAMLResponse, "base64").toString(
1801
+ "utf-8",
1802
+ );
1803
+
1804
+ // Patch the SAML response if status is missing or not success
1805
+ if (!decodedResponse.includes("StatusCode")) {
1806
+ // Insert a success status if missing
1807
+ const insertPoint = decodedResponse.indexOf("</saml2:Issuer>");
1808
+ if (insertPoint !== -1) {
1809
+ decodedResponse =
1810
+ decodedResponse.slice(0, insertPoint + 14) +
1811
+ '<saml2:Status><saml2:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></saml2:Status>' +
1812
+ decodedResponse.slice(insertPoint + 14);
1813
+ }
1814
+ } else if (!decodedResponse.includes("saml2:Success")) {
1815
+ // Replace existing non-success status with success
1816
+ decodedResponse = decodedResponse.replace(
1817
+ /<saml2:StatusCode Value="[^"]+"/,
1818
+ '<saml2:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"',
1819
+ );
1820
+ }
1821
+
1822
+ try {
1823
+ parsedResponse = await sp.parseLoginResponse(idp, "post", {
1824
+ body: {
1825
+ SAMLResponse,
1826
+ RelayState: RelayState || undefined,
1827
+ },
1828
+ });
1829
+ } catch (parseError) {
1830
+ const nameIDMatch = decodedResponse.match(
1831
+ /<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/,
1832
+ );
1833
+ // due to different spec. we have to make sure to handle that.
1834
+ if (!nameIDMatch) throw parseError;
1835
+ parsedResponse = {
1836
+ extract: {
1837
+ nameID: nameIDMatch[1],
1838
+ attributes: { nameID: nameIDMatch[1] },
1839
+ sessionIndex: {},
1840
+ conditions: {},
1841
+ },
1842
+ } as FlowResult;
1843
+ }
1844
+
1845
+ if (!parsedResponse?.extract) {
1846
+ throw new Error("Invalid SAML response structure");
1847
+ }
1848
+ } catch (error) {
1849
+ ctx.context.logger.error("SAML response validation failed", {
1850
+ error,
1851
+ decodedResponse: Buffer.from(SAMLResponse, "base64").toString(
1852
+ "utf-8",
1853
+ ),
1854
+ });
1855
+ throw new APIError("BAD_REQUEST", {
1856
+ message: "Invalid SAML response",
1857
+ details: error instanceof Error ? error.message : String(error),
1858
+ });
1859
+ }
1860
+
1861
+ const { extract } = parsedResponse!;
1862
+ const attributes = extract.attributes || {};
1863
+ const mapping = parsedSamlConfig.mapping ?? {};
1864
+
1865
+ const userInfo = {
1866
+ ...Object.fromEntries(
1867
+ Object.entries(mapping.extraFields || {}).map(([key, value]) => [
1868
+ key,
1869
+ attributes[value as string],
1870
+ ]),
1871
+ ),
1872
+ id: attributes[mapping.id || "nameID"] || extract.nameID,
1873
+ email: attributes[mapping.email || "email"] || extract.nameID,
1874
+ name:
1875
+ [
1876
+ attributes[mapping.firstName || "givenName"],
1877
+ attributes[mapping.lastName || "surname"],
1878
+ ]
1879
+ .filter(Boolean)
1880
+ .join(" ") ||
1881
+ attributes[mapping.name || "displayName"] ||
1882
+ extract.nameID,
1883
+ emailVerified:
1884
+ options?.trustEmailVerified && mapping.emailVerified
1885
+ ? ((attributes[mapping.emailVerified] || false) as boolean)
1886
+ : false,
1887
+ };
1888
+
1889
+ if (!userInfo.id || !userInfo.email) {
1890
+ ctx.context.logger.error(
1891
+ "Missing essential user info from SAML response",
1892
+ {
1893
+ attributes: Object.keys(attributes),
1894
+ mapping,
1895
+ extractedId: userInfo.id,
1896
+ extractedEmail: userInfo.email,
1897
+ },
1898
+ );
1899
+ throw new APIError("BAD_REQUEST", {
1900
+ message: "Unable to extract user ID or email from SAML response",
1901
+ });
1902
+ }
1903
+
1904
+ // Find or create user
1905
+ let user: User;
1906
+ const existingUser = await ctx.context.adapter.findOne<User>({
1907
+ model: "user",
1908
+ where: [
1909
+ {
1910
+ field: "email",
1911
+ value: userInfo.email,
1912
+ },
1913
+ ],
1914
+ });
1915
+
1916
+ if (existingUser) {
1917
+ const account = await ctx.context.adapter.findOne<Account>({
1918
+ model: "account",
1919
+ where: [
1920
+ { field: "userId", value: existingUser.id },
1921
+ { field: "providerId", value: provider.providerId },
1922
+ { field: "accountId", value: userInfo.id },
1923
+ ],
1924
+ });
1925
+ if (!account) {
1926
+ const isTrustedProvider =
1927
+ ctx.context.options.account?.accountLinking?.trustedProviders?.includes(
1928
+ provider.providerId,
1929
+ );
1930
+ if (!isTrustedProvider) {
1931
+ throw ctx.redirect(
1932
+ `${parsedSamlConfig.callbackUrl}?error=account_not_found`,
1933
+ );
1934
+ }
1935
+ await ctx.context.internalAdapter.createAccount({
1936
+ userId: existingUser.id,
1937
+ providerId: provider.providerId,
1938
+ accountId: userInfo.id,
1939
+ accessToken: "",
1940
+ refreshToken: "",
1941
+ });
1942
+ }
1943
+ user = existingUser;
1944
+ } else {
1945
+ user = await ctx.context.internalAdapter.createUser({
1946
+ email: userInfo.email,
1947
+ name: userInfo.name,
1948
+ emailVerified: options?.trustEmailVerified
1949
+ ? userInfo.emailVerified || false
1950
+ : false,
1951
+ });
1952
+ await ctx.context.internalAdapter.createAccount({
1953
+ userId: user.id,
1954
+ providerId: provider.providerId,
1955
+ accountId: userInfo.id,
1956
+ accessToken: "",
1957
+ refreshToken: "",
1958
+ accessTokenExpiresAt: new Date(),
1959
+ refreshTokenExpiresAt: new Date(),
1960
+ scope: "",
1961
+ });
1962
+ }
1963
+
1964
+ if (options?.provisionUser) {
1965
+ await options.provisionUser({
1966
+ user: user as User & Record<string, any>,
1967
+ userInfo,
1968
+ provider,
1969
+ });
1970
+ }
1971
+
1972
+ if (
1973
+ provider.organizationId &&
1974
+ !options?.organizationProvisioning?.disabled
1975
+ ) {
1976
+ const isOrgPluginEnabled = ctx.context.options.plugins?.find(
1977
+ (plugin) => plugin.id === "organization",
1978
+ );
1979
+ if (isOrgPluginEnabled) {
1980
+ const isAlreadyMember = await ctx.context.adapter.findOne({
1981
+ model: "member",
1982
+ where: [
1983
+ { field: "organizationId", value: provider.organizationId },
1984
+ { field: "userId", value: user.id },
1985
+ ],
1986
+ });
1987
+ if (!isAlreadyMember) {
1988
+ const role = options?.organizationProvisioning?.getRole
1989
+ ? await options.organizationProvisioning.getRole({
1990
+ user,
1991
+ userInfo,
1992
+ provider,
1993
+ })
1994
+ : options?.organizationProvisioning?.defaultRole || "member";
1995
+ await ctx.context.adapter.create({
1996
+ model: "member",
1997
+ data: {
1998
+ organizationId: provider.organizationId,
1999
+ userId: user.id,
2000
+ role,
2001
+ createdAt: new Date(),
2002
+ updatedAt: new Date(),
2003
+ },
2004
+ });
2005
+ }
2006
+ }
2007
+ }
2008
+
2009
+ let session: Session = await ctx.context.internalAdapter.createSession(
2010
+ user.id,
2011
+ );
2012
+ await setSessionCookie(ctx, { session, user });
2013
+
2014
+ const callbackUrl =
2015
+ RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
2016
+ throw ctx.redirect(callbackUrl);
2017
+ },
2018
+ );
2019
+ };