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