@better-auth/sso 1.5.0-beta.8 → 1.5.0

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/routes/sso.ts DELETED
@@ -1,2710 +0,0 @@
1
- import { BetterFetchError, betterFetch } from "@better-fetch/fetch";
2
- import type { User, Verification } from "better-auth";
3
- import {
4
- createAuthorizationURL,
5
- generateState,
6
- HIDE_METADATA,
7
- parseState,
8
- validateAuthorizationCode,
9
- validateToken,
10
- } from "better-auth";
11
- import {
12
- APIError,
13
- createAuthEndpoint,
14
- getSessionFromCtx,
15
- sessionMiddleware,
16
- } from "better-auth/api";
17
- import { setSessionCookie } from "better-auth/cookies";
18
- import { generateRandomString } from "better-auth/crypto";
19
- import { handleOAuthUserInfo } from "better-auth/oauth2";
20
- import { XMLParser } from "fast-xml-parser";
21
- import { decodeJwt } from "jose";
22
- import * as saml from "samlify";
23
- import type { BindingContext } from "samlify/types/src/entity";
24
- import type { IdentityProvider } from "samlify/types/src/entity-idp";
25
- import type { FlowResult } from "samlify/types/src/flow";
26
- import z from "zod/v4";
27
-
28
- interface AuthnRequestRecord {
29
- id: string;
30
- providerId: string;
31
- createdAt: number;
32
- expiresAt: number;
33
- }
34
-
35
- import {
36
- AUTHN_REQUEST_KEY_PREFIX,
37
- DEFAULT_ASSERTION_TTL_MS,
38
- DEFAULT_AUTHN_REQUEST_TTL_MS,
39
- DEFAULT_CLOCK_SKEW_MS,
40
- DEFAULT_MAX_SAML_METADATA_SIZE,
41
- DEFAULT_MAX_SAML_RESPONSE_SIZE,
42
- USED_ASSERTION_KEY_PREFIX,
43
- } from "../constants";
44
- import { assignOrganizationFromProvider } from "../linking";
45
- import type { HydratedOIDCConfig } from "../oidc";
46
- import {
47
- DiscoveryError,
48
- discoverOIDCConfig,
49
- mapDiscoveryErrorToAPIError,
50
- } from "../oidc";
51
- import {
52
- validateConfigAlgorithms,
53
- validateSAMLAlgorithms,
54
- validateSingleAssertion,
55
- } from "../saml";
56
- import { generateRelayState, parseRelayState } from "../saml-state";
57
- import type { OIDCConfig, SAMLConfig, SSOOptions, SSOProvider } from "../types";
58
- import { safeJsonParse, validateEmailDomain } from "../utils";
59
-
60
- export interface TimestampValidationOptions {
61
- clockSkew?: number;
62
- requireTimestamps?: boolean;
63
- logger?: {
64
- warn: (message: string, data?: Record<string, unknown>) => void;
65
- };
66
- }
67
-
68
- /** Conditions extracted from SAML assertion */
69
- export interface SAMLConditions {
70
- notBefore?: string;
71
- notOnOrAfter?: string;
72
- }
73
-
74
- /**
75
- * Validates SAML assertion timestamp conditions (NotBefore/NotOnOrAfter).
76
- * Prevents acceptance of expired or future-dated assertions.
77
- * @throws {APIError} If timestamps are invalid, expired, or not yet valid
78
- */
79
- export function validateSAMLTimestamp(
80
- conditions: SAMLConditions | undefined,
81
- options: TimestampValidationOptions = {},
82
- ): void {
83
- const clockSkew = options.clockSkew ?? DEFAULT_CLOCK_SKEW_MS;
84
- const hasTimestamps = conditions?.notBefore || conditions?.notOnOrAfter;
85
-
86
- if (!hasTimestamps) {
87
- if (options.requireTimestamps) {
88
- throw new APIError("BAD_REQUEST", {
89
- message: "SAML assertion missing required timestamp conditions",
90
- details:
91
- "Assertions must include NotBefore and/or NotOnOrAfter conditions",
92
- });
93
- }
94
- // Log warning for missing timestamps when not required
95
- options.logger?.warn(
96
- "SAML assertion accepted without timestamp conditions",
97
- { hasConditions: !!conditions },
98
- );
99
- return;
100
- }
101
-
102
- const now = Date.now();
103
-
104
- if (conditions?.notBefore) {
105
- const notBeforeTime = new Date(conditions.notBefore).getTime();
106
- if (Number.isNaN(notBeforeTime)) {
107
- throw new APIError("BAD_REQUEST", {
108
- message: "SAML assertion has invalid NotBefore timestamp",
109
- details: `Unable to parse NotBefore value: ${conditions.notBefore}`,
110
- });
111
- }
112
- if (now < notBeforeTime - clockSkew) {
113
- throw new APIError("BAD_REQUEST", {
114
- message: "SAML assertion is not yet valid",
115
- details: `Current time is before NotBefore (with ${clockSkew}ms clock skew tolerance)`,
116
- });
117
- }
118
- }
119
-
120
- if (conditions?.notOnOrAfter) {
121
- const notOnOrAfterTime = new Date(conditions.notOnOrAfter).getTime();
122
- if (Number.isNaN(notOnOrAfterTime)) {
123
- throw new APIError("BAD_REQUEST", {
124
- message: "SAML assertion has invalid NotOnOrAfter timestamp",
125
- details: `Unable to parse NotOnOrAfter value: ${conditions.notOnOrAfter}`,
126
- });
127
- }
128
- if (now > notOnOrAfterTime + clockSkew) {
129
- throw new APIError("BAD_REQUEST", {
130
- message: "SAML assertion has expired",
131
- details: `Current time is after NotOnOrAfter (with ${clockSkew}ms clock skew tolerance)`,
132
- });
133
- }
134
- }
135
- }
136
-
137
- /**
138
- * Extracts the Assertion ID from a SAML response XML.
139
- * Returns null if the assertion ID cannot be found.
140
- */
141
- function extractAssertionId(samlContent: string): string | null {
142
- try {
143
- const parser = new XMLParser({
144
- ignoreAttributes: false,
145
- attributeNamePrefix: "@_",
146
- removeNSPrefix: true,
147
- });
148
- const parsed = parser.parse(samlContent);
149
-
150
- const response = parsed.Response || parsed["samlp:Response"];
151
- if (!response) return null;
152
-
153
- const rawAssertion = response.Assertion || response["saml:Assertion"];
154
- const assertion = Array.isArray(rawAssertion)
155
- ? rawAssertion[0]
156
- : rawAssertion;
157
- if (!assertion) return null;
158
-
159
- return assertion["@_ID"] || null;
160
- } catch {
161
- return null;
162
- }
163
- }
164
-
165
- const spMetadataQuerySchema = z.object({
166
- providerId: z.string(),
167
- format: z.enum(["xml", "json"]).default("xml"),
168
- });
169
-
170
- type RelayState = Awaited<ReturnType<typeof parseRelayState>>;
171
-
172
- export const spMetadata = () => {
173
- return createAuthEndpoint(
174
- "/sso/saml2/sp/metadata",
175
- {
176
- method: "GET",
177
- query: spMetadataQuerySchema,
178
- metadata: {
179
- openapi: {
180
- operationId: "getSSOServiceProviderMetadata",
181
- summary: "Get Service Provider metadata",
182
- description: "Returns the SAML metadata for the Service Provider",
183
- responses: {
184
- "200": {
185
- description: "SAML metadata in XML format",
186
- },
187
- },
188
- },
189
- },
190
- },
191
- async (ctx) => {
192
- const provider = await ctx.context.adapter.findOne<{
193
- id: string;
194
- samlConfig: string;
195
- }>({
196
- model: "ssoProvider",
197
- where: [
198
- {
199
- field: "providerId",
200
- value: ctx.query.providerId,
201
- },
202
- ],
203
- });
204
- if (!provider) {
205
- throw new APIError("NOT_FOUND", {
206
- message: "No provider found for the given providerId",
207
- });
208
- }
209
-
210
- const parsedSamlConfig = safeJsonParse<SAMLConfig>(provider.samlConfig);
211
- if (!parsedSamlConfig) {
212
- throw new APIError("BAD_REQUEST", {
213
- message: "Invalid SAML configuration",
214
- });
215
- }
216
- const sp = parsedSamlConfig.spMetadata.metadata
217
- ? saml.ServiceProvider({
218
- metadata: parsedSamlConfig.spMetadata.metadata,
219
- })
220
- : saml.SPMetadata({
221
- entityID:
222
- parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
223
- assertionConsumerService: [
224
- {
225
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
226
- Location:
227
- parsedSamlConfig.callbackUrl ||
228
- `${ctx.context.baseURL}/sso/saml2/sp/acs/${provider.id}`,
229
- },
230
- ],
231
- wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
232
- nameIDFormat: parsedSamlConfig.identifierFormat
233
- ? [parsedSamlConfig.identifierFormat]
234
- : undefined,
235
- });
236
- return new Response(sp.getMetadata(), {
237
- headers: {
238
- "Content-Type": "application/xml",
239
- },
240
- });
241
- },
242
- );
243
- };
244
-
245
- const ssoProviderBodySchema = z.object({
246
- providerId: z.string({}).meta({
247
- description:
248
- "The ID of the provider. This is used to identify the provider during login and callback",
249
- }),
250
- issuer: z.string({}).meta({
251
- description: "The issuer of the provider",
252
- }),
253
- domain: z.string({}).meta({
254
- description: "The domain of the provider. This is used for email matching",
255
- }),
256
- oidcConfig: z
257
- .object({
258
- clientId: z.string({}).meta({
259
- description: "The client ID",
260
- }),
261
- clientSecret: z.string({}).meta({
262
- description: "The client secret",
263
- }),
264
- authorizationEndpoint: z
265
- .string({})
266
- .meta({
267
- description: "The authorization endpoint",
268
- })
269
- .optional(),
270
- tokenEndpoint: z
271
- .string({})
272
- .meta({
273
- description: "The token endpoint",
274
- })
275
- .optional(),
276
- userInfoEndpoint: z
277
- .string({})
278
- .meta({
279
- description: "The user info endpoint",
280
- })
281
- .optional(),
282
- tokenEndpointAuthentication: z
283
- .enum(["client_secret_post", "client_secret_basic"])
284
- .optional(),
285
- jwksEndpoint: z
286
- .string({})
287
- .meta({
288
- description: "The JWKS endpoint",
289
- })
290
- .optional(),
291
- discoveryEndpoint: z.string().optional(),
292
- skipDiscovery: z
293
- .boolean()
294
- .meta({
295
- description:
296
- "Skip OIDC discovery during registration. When true, you must provide authorizationEndpoint, tokenEndpoint, and jwksEndpoint manually.",
297
- })
298
- .optional(),
299
- scopes: z
300
- .array(z.string(), {})
301
- .meta({
302
- description:
303
- "The scopes to request. Defaults to ['openid', 'email', 'profile', 'offline_access']",
304
- })
305
- .optional(),
306
- pkce: z
307
- .boolean({})
308
- .meta({
309
- description: "Whether to use PKCE for the authorization flow",
310
- })
311
- .default(true)
312
- .optional(),
313
- mapping: z
314
- .object({
315
- id: z.string({}).meta({
316
- description: "Field mapping for user ID (defaults to 'sub')",
317
- }),
318
- email: z.string({}).meta({
319
- description: "Field mapping for email (defaults to 'email')",
320
- }),
321
- emailVerified: z
322
- .string({})
323
- .meta({
324
- description:
325
- "Field mapping for email verification (defaults to 'email_verified')",
326
- })
327
- .optional(),
328
- name: z.string({}).meta({
329
- description: "Field mapping for name (defaults to 'name')",
330
- }),
331
- image: z
332
- .string({})
333
- .meta({
334
- description: "Field mapping for image (defaults to 'picture')",
335
- })
336
- .optional(),
337
- extraFields: z.record(z.string(), z.any()).optional(),
338
- })
339
- .optional(),
340
- })
341
- .optional(),
342
- samlConfig: z
343
- .object({
344
- entryPoint: z.string({}).meta({
345
- description: "The entry point of the provider",
346
- }),
347
- cert: z.string({}).meta({
348
- description: "The certificate of the provider",
349
- }),
350
- callbackUrl: z.string({}).meta({
351
- description: "The callback URL of the provider",
352
- }),
353
- audience: z.string().optional(),
354
- idpMetadata: z
355
- .object({
356
- metadata: z.string().optional(),
357
- entityID: z.string().optional(),
358
- cert: z.string().optional(),
359
- privateKey: z.string().optional(),
360
- privateKeyPass: z.string().optional(),
361
- isAssertionEncrypted: z.boolean().optional(),
362
- encPrivateKey: z.string().optional(),
363
- encPrivateKeyPass: z.string().optional(),
364
- singleSignOnService: z
365
- .array(
366
- z.object({
367
- Binding: z.string().meta({
368
- description: "The binding type for the SSO service",
369
- }),
370
- Location: z.string().meta({
371
- description: "The URL for the SSO service",
372
- }),
373
- }),
374
- )
375
- .optional()
376
- .meta({
377
- description: "Single Sign-On service configuration",
378
- }),
379
- })
380
- .optional(),
381
- spMetadata: z.object({
382
- metadata: z.string().optional(),
383
- entityID: z.string().optional(),
384
- binding: z.string().optional(),
385
- privateKey: z.string().optional(),
386
- privateKeyPass: z.string().optional(),
387
- isAssertionEncrypted: z.boolean().optional(),
388
- encPrivateKey: z.string().optional(),
389
- encPrivateKeyPass: z.string().optional(),
390
- }),
391
- wantAssertionsSigned: z.boolean().optional(),
392
- signatureAlgorithm: z.string().optional(),
393
- digestAlgorithm: z.string().optional(),
394
- identifierFormat: z.string().optional(),
395
- privateKey: z.string().optional(),
396
- decryptionPvk: z.string().optional(),
397
- additionalParams: z.record(z.string(), z.any()).optional(),
398
- mapping: z
399
- .object({
400
- id: z.string({}).meta({
401
- description: "Field mapping for user ID (defaults to 'nameID')",
402
- }),
403
- email: z.string({}).meta({
404
- description: "Field mapping for email (defaults to 'email')",
405
- }),
406
- emailVerified: z
407
- .string({})
408
- .meta({
409
- description: "Field mapping for email verification",
410
- })
411
- .optional(),
412
- name: z.string({}).meta({
413
- description: "Field mapping for name (defaults to 'displayName')",
414
- }),
415
- firstName: z
416
- .string({})
417
- .meta({
418
- description:
419
- "Field mapping for first name (defaults to 'givenName')",
420
- })
421
- .optional(),
422
- lastName: z
423
- .string({})
424
- .meta({
425
- description:
426
- "Field mapping for last name (defaults to 'surname')",
427
- })
428
- .optional(),
429
- extraFields: z.record(z.string(), z.any()).optional(),
430
- })
431
- .optional(),
432
- })
433
- .optional(),
434
- organizationId: z
435
- .string({})
436
- .meta({
437
- description:
438
- "If organization plugin is enabled, the organization id to link the provider to",
439
- })
440
- .optional(),
441
- overrideUserInfo: z
442
- .boolean({})
443
- .meta({
444
- description:
445
- "Override user info with the provider info. Defaults to false",
446
- })
447
- .default(false)
448
- .optional(),
449
- });
450
-
451
- export const registerSSOProvider = <O extends SSOOptions>(options: O) => {
452
- return createAuthEndpoint(
453
- "/sso/register",
454
- {
455
- method: "POST",
456
- body: ssoProviderBodySchema,
457
- use: [sessionMiddleware],
458
- metadata: {
459
- openapi: {
460
- operationId: "registerSSOProvider",
461
- summary: "Register an OIDC provider",
462
- description:
463
- "This endpoint is used to register an OIDC provider. This is used to configure the provider and link it to an organization",
464
- responses: {
465
- "200": {
466
- description: "OIDC provider created successfully",
467
- content: {
468
- "application/json": {
469
- schema: {
470
- type: "object",
471
- properties: {
472
- issuer: {
473
- type: "string",
474
- format: "uri",
475
- description: "The issuer URL of the provider",
476
- },
477
- domain: {
478
- type: "string",
479
- description:
480
- "The domain of the provider, used for email matching",
481
- },
482
- domainVerified: {
483
- type: "boolean",
484
- description:
485
- "A boolean indicating whether the domain has been verified or not",
486
- },
487
- domainVerificationToken: {
488
- type: "string",
489
- description:
490
- "Domain verification token. It can be used to prove ownership over the SSO domain",
491
- },
492
- oidcConfig: {
493
- type: "object",
494
- properties: {
495
- issuer: {
496
- type: "string",
497
- format: "uri",
498
- description: "The issuer URL of the provider",
499
- },
500
- pkce: {
501
- type: "boolean",
502
- description:
503
- "Whether PKCE is enabled for the authorization flow",
504
- },
505
- clientId: {
506
- type: "string",
507
- description: "The client ID for the provider",
508
- },
509
- clientSecret: {
510
- type: "string",
511
- description: "The client secret for the provider",
512
- },
513
- authorizationEndpoint: {
514
- type: "string",
515
- format: "uri",
516
- nullable: true,
517
- description: "The authorization endpoint URL",
518
- },
519
- discoveryEndpoint: {
520
- type: "string",
521
- format: "uri",
522
- description: "The discovery endpoint URL",
523
- },
524
- userInfoEndpoint: {
525
- type: "string",
526
- format: "uri",
527
- nullable: true,
528
- description: "The user info endpoint URL",
529
- },
530
- scopes: {
531
- type: "array",
532
- items: { type: "string" },
533
- nullable: true,
534
- description:
535
- "The scopes requested from the provider",
536
- },
537
- tokenEndpoint: {
538
- type: "string",
539
- format: "uri",
540
- nullable: true,
541
- description: "The token endpoint URL",
542
- },
543
- tokenEndpointAuthentication: {
544
- type: "string",
545
- enum: ["client_secret_post", "client_secret_basic"],
546
- nullable: true,
547
- description:
548
- "Authentication method for the token endpoint",
549
- },
550
- jwksEndpoint: {
551
- type: "string",
552
- format: "uri",
553
- nullable: true,
554
- description: "The JWKS endpoint URL",
555
- },
556
- mapping: {
557
- type: "object",
558
- nullable: true,
559
- properties: {
560
- id: {
561
- type: "string",
562
- description:
563
- "Field mapping for user ID (defaults to 'sub')",
564
- },
565
- email: {
566
- type: "string",
567
- description:
568
- "Field mapping for email (defaults to 'email')",
569
- },
570
- emailVerified: {
571
- type: "string",
572
- nullable: true,
573
- description:
574
- "Field mapping for email verification (defaults to 'email_verified')",
575
- },
576
- name: {
577
- type: "string",
578
- description:
579
- "Field mapping for name (defaults to 'name')",
580
- },
581
- image: {
582
- type: "string",
583
- nullable: true,
584
- description:
585
- "Field mapping for image (defaults to 'picture')",
586
- },
587
- extraFields: {
588
- type: "object",
589
- additionalProperties: { type: "string" },
590
- nullable: true,
591
- description: "Additional field mappings",
592
- },
593
- },
594
- required: ["id", "email", "name"],
595
- },
596
- },
597
- required: [
598
- "issuer",
599
- "pkce",
600
- "clientId",
601
- "clientSecret",
602
- "discoveryEndpoint",
603
- ],
604
- description: "OIDC configuration for the provider",
605
- },
606
- organizationId: {
607
- type: "string",
608
- nullable: true,
609
- description: "ID of the linked organization, if any",
610
- },
611
- userId: {
612
- type: "string",
613
- description:
614
- "ID of the user who registered the provider",
615
- },
616
- providerId: {
617
- type: "string",
618
- description: "Unique identifier for the provider",
619
- },
620
- redirectURI: {
621
- type: "string",
622
- format: "uri",
623
- description:
624
- "The redirect URI for the provider callback",
625
- },
626
- },
627
- required: [
628
- "issuer",
629
- "domain",
630
- "oidcConfig",
631
- "userId",
632
- "providerId",
633
- "redirectURI",
634
- ],
635
- },
636
- },
637
- },
638
- },
639
- },
640
- },
641
- },
642
- },
643
- async (ctx) => {
644
- const user = ctx.context.session?.user;
645
- if (!user) {
646
- throw new APIError("UNAUTHORIZED");
647
- }
648
-
649
- const limit =
650
- typeof options?.providersLimit === "function"
651
- ? await options.providersLimit(user)
652
- : (options?.providersLimit ?? 10);
653
-
654
- if (!limit) {
655
- throw new APIError("FORBIDDEN", {
656
- message: "SSO provider registration is disabled",
657
- });
658
- }
659
-
660
- const providers = await ctx.context.adapter.findMany({
661
- model: "ssoProvider",
662
- where: [{ field: "userId", value: user.id }],
663
- });
664
-
665
- if (providers.length >= limit) {
666
- throw new APIError("FORBIDDEN", {
667
- message: "You have reached the maximum number of SSO providers",
668
- });
669
- }
670
-
671
- const body = ctx.body;
672
- const issuerValidator = z.string().url();
673
- if (issuerValidator.safeParse(body.issuer).error) {
674
- throw new APIError("BAD_REQUEST", {
675
- message: "Invalid issuer. Must be a valid URL",
676
- });
677
- }
678
-
679
- if (body.samlConfig?.idpMetadata?.metadata) {
680
- const maxMetadataSize =
681
- options?.saml?.maxMetadataSize ?? DEFAULT_MAX_SAML_METADATA_SIZE;
682
- if (
683
- new TextEncoder().encode(body.samlConfig.idpMetadata.metadata)
684
- .length > maxMetadataSize
685
- ) {
686
- throw new APIError("BAD_REQUEST", {
687
- message: `IdP metadata exceeds maximum allowed size (${maxMetadataSize} bytes)`,
688
- });
689
- }
690
- }
691
-
692
- if (ctx.body.organizationId) {
693
- const organization = await ctx.context.adapter.findOne({
694
- model: "member",
695
- where: [
696
- {
697
- field: "userId",
698
- value: user.id,
699
- },
700
- {
701
- field: "organizationId",
702
- value: ctx.body.organizationId,
703
- },
704
- ],
705
- });
706
- if (!organization) {
707
- throw new APIError("BAD_REQUEST", {
708
- message: "You are not a member of the organization",
709
- });
710
- }
711
- }
712
-
713
- const existingProvider = await ctx.context.adapter.findOne({
714
- model: "ssoProvider",
715
- where: [
716
- {
717
- field: "providerId",
718
- value: body.providerId,
719
- },
720
- ],
721
- });
722
-
723
- if (existingProvider) {
724
- ctx.context.logger.info(
725
- `SSO provider creation attempt with existing providerId: ${body.providerId}`,
726
- );
727
- throw new APIError("UNPROCESSABLE_ENTITY", {
728
- message: "SSO provider with this providerId already exists",
729
- });
730
- }
731
-
732
- let hydratedOIDCConfig: HydratedOIDCConfig | null = null;
733
- if (body.oidcConfig && !body.oidcConfig.skipDiscovery) {
734
- try {
735
- hydratedOIDCConfig = await discoverOIDCConfig({
736
- issuer: body.issuer,
737
- existingConfig: {
738
- discoveryEndpoint: body.oidcConfig.discoveryEndpoint,
739
- authorizationEndpoint: body.oidcConfig.authorizationEndpoint,
740
- tokenEndpoint: body.oidcConfig.tokenEndpoint,
741
- jwksEndpoint: body.oidcConfig.jwksEndpoint,
742
- userInfoEndpoint: body.oidcConfig.userInfoEndpoint,
743
- tokenEndpointAuthentication:
744
- body.oidcConfig.tokenEndpointAuthentication,
745
- },
746
- isTrustedOrigin: (url: string) => ctx.context.isTrustedOrigin(url),
747
- });
748
- } catch (error) {
749
- if (error instanceof DiscoveryError) {
750
- throw mapDiscoveryErrorToAPIError(error);
751
- }
752
- throw error;
753
- }
754
- }
755
-
756
- const buildOIDCConfig = () => {
757
- if (!body.oidcConfig) return null;
758
-
759
- if (body.oidcConfig.skipDiscovery) {
760
- return JSON.stringify({
761
- issuer: body.issuer,
762
- clientId: body.oidcConfig.clientId,
763
- clientSecret: body.oidcConfig.clientSecret,
764
- authorizationEndpoint: body.oidcConfig.authorizationEndpoint,
765
- tokenEndpoint: body.oidcConfig.tokenEndpoint,
766
- tokenEndpointAuthentication:
767
- body.oidcConfig.tokenEndpointAuthentication ||
768
- "client_secret_basic",
769
- jwksEndpoint: body.oidcConfig.jwksEndpoint,
770
- pkce: body.oidcConfig.pkce,
771
- discoveryEndpoint:
772
- body.oidcConfig.discoveryEndpoint ||
773
- `${body.issuer}/.well-known/openid-configuration`,
774
- mapping: body.oidcConfig.mapping,
775
- scopes: body.oidcConfig.scopes,
776
- userInfoEndpoint: body.oidcConfig.userInfoEndpoint,
777
- overrideUserInfo:
778
- ctx.body.overrideUserInfo ||
779
- options?.defaultOverrideUserInfo ||
780
- false,
781
- });
782
- }
783
-
784
- if (!hydratedOIDCConfig) return null;
785
-
786
- return JSON.stringify({
787
- issuer: hydratedOIDCConfig.issuer,
788
- clientId: body.oidcConfig.clientId,
789
- clientSecret: body.oidcConfig.clientSecret,
790
- authorizationEndpoint: hydratedOIDCConfig.authorizationEndpoint,
791
- tokenEndpoint: hydratedOIDCConfig.tokenEndpoint,
792
- tokenEndpointAuthentication:
793
- hydratedOIDCConfig.tokenEndpointAuthentication,
794
- jwksEndpoint: hydratedOIDCConfig.jwksEndpoint,
795
- pkce: body.oidcConfig.pkce,
796
- discoveryEndpoint: hydratedOIDCConfig.discoveryEndpoint,
797
- mapping: body.oidcConfig.mapping,
798
- scopes: body.oidcConfig.scopes,
799
- userInfoEndpoint: hydratedOIDCConfig.userInfoEndpoint,
800
- overrideUserInfo:
801
- ctx.body.overrideUserInfo ||
802
- options?.defaultOverrideUserInfo ||
803
- false,
804
- });
805
- };
806
-
807
- if (body.samlConfig) {
808
- validateConfigAlgorithms(
809
- {
810
- signatureAlgorithm: body.samlConfig.signatureAlgorithm,
811
- digestAlgorithm: body.samlConfig.digestAlgorithm,
812
- },
813
- options?.saml?.algorithms,
814
- );
815
- }
816
-
817
- const provider = await ctx.context.adapter.create<
818
- Record<string, any>,
819
- SSOProvider<O>
820
- >({
821
- model: "ssoProvider",
822
- data: {
823
- issuer: body.issuer,
824
- domain: body.domain,
825
- domainVerified: false,
826
- oidcConfig: buildOIDCConfig(),
827
- samlConfig: body.samlConfig
828
- ? JSON.stringify({
829
- issuer: body.issuer,
830
- entryPoint: body.samlConfig.entryPoint,
831
- cert: body.samlConfig.cert,
832
- callbackUrl: body.samlConfig.callbackUrl,
833
- audience: body.samlConfig.audience,
834
- idpMetadata: body.samlConfig.idpMetadata,
835
- spMetadata: body.samlConfig.spMetadata,
836
- wantAssertionsSigned: body.samlConfig.wantAssertionsSigned,
837
- signatureAlgorithm: body.samlConfig.signatureAlgorithm,
838
- digestAlgorithm: body.samlConfig.digestAlgorithm,
839
- identifierFormat: body.samlConfig.identifierFormat,
840
- privateKey: body.samlConfig.privateKey,
841
- decryptionPvk: body.samlConfig.decryptionPvk,
842
- additionalParams: body.samlConfig.additionalParams,
843
- mapping: body.samlConfig.mapping,
844
- })
845
- : null,
846
- organizationId: body.organizationId,
847
- userId: ctx.context.session.user.id,
848
- providerId: body.providerId,
849
- },
850
- });
851
-
852
- let domainVerificationToken: string | undefined;
853
- let domainVerified: boolean | undefined;
854
-
855
- if (options?.domainVerification?.enabled) {
856
- domainVerified = false;
857
- domainVerificationToken = generateRandomString(24);
858
-
859
- await ctx.context.adapter.create<Verification>({
860
- model: "verification",
861
- data: {
862
- identifier: options.domainVerification?.tokenPrefix
863
- ? `${options.domainVerification?.tokenPrefix}-${provider.providerId}`
864
- : `better-auth-token-${provider.providerId}`,
865
- createdAt: new Date(),
866
- updatedAt: new Date(),
867
- value: domainVerificationToken as string,
868
- expiresAt: new Date(Date.now() + 3600 * 24 * 7 * 1000), // 1 week
869
- },
870
- });
871
- }
872
-
873
- type SSOProviderResponse = {
874
- redirectURI: string;
875
- oidcConfig: OIDCConfig | null;
876
- samlConfig: SAMLConfig | null;
877
- } & Omit<SSOProvider<O>, "oidcConfig" | "samlConfig">;
878
-
879
- type SSOProviderReturn = O["domainVerification"] extends { enabled: true }
880
- ? SSOProviderResponse & {
881
- domainVerified: boolean;
882
- domainVerificationToken: string;
883
- }
884
- : SSOProviderResponse;
885
-
886
- const result = {
887
- ...provider,
888
- oidcConfig: safeJsonParse<OIDCConfig>(
889
- provider.oidcConfig as unknown as string,
890
- ),
891
- samlConfig: safeJsonParse<SAMLConfig>(
892
- provider.samlConfig as unknown as string,
893
- ),
894
- redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`,
895
- ...(options?.domainVerification?.enabled ? { domainVerified } : {}),
896
- ...(options?.domainVerification?.enabled
897
- ? { domainVerificationToken }
898
- : {}),
899
- };
900
-
901
- return ctx.json(result as SSOProviderReturn);
902
- },
903
- );
904
- };
905
-
906
- const signInSSOBodySchema = z.object({
907
- email: z
908
- .string({})
909
- .meta({
910
- description:
911
- "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",
912
- })
913
- .optional(),
914
- organizationSlug: z
915
- .string({})
916
- .meta({
917
- description: "The slug of the organization to sign in with",
918
- })
919
- .optional(),
920
- providerId: z
921
- .string({})
922
- .meta({
923
- description:
924
- "The ID of the provider to sign in with. This can be provided instead of email or issuer",
925
- })
926
- .optional(),
927
- domain: z
928
- .string({})
929
- .meta({
930
- description: "The domain of the provider.",
931
- })
932
- .optional(),
933
- callbackURL: z.string({}).meta({
934
- description: "The URL to redirect to after login",
935
- }),
936
- errorCallbackURL: z
937
- .string({})
938
- .meta({
939
- description: "The URL to redirect to after login",
940
- })
941
- .optional(),
942
- newUserCallbackURL: z
943
- .string({})
944
- .meta({
945
- description: "The URL to redirect to after login if the user is new",
946
- })
947
- .optional(),
948
- scopes: z
949
- .array(z.string(), {})
950
- .meta({
951
- description: "Scopes to request from the provider.",
952
- })
953
- .optional(),
954
- loginHint: z
955
- .string({})
956
- .meta({
957
- description:
958
- "Login hint to send to the identity provider (e.g., email or identifier). If supported, will be sent as 'login_hint'.",
959
- })
960
- .optional(),
961
- requestSignUp: z
962
- .boolean({})
963
- .meta({
964
- description:
965
- "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider",
966
- })
967
- .optional(),
968
- providerType: z.enum(["oidc", "saml"]).optional(),
969
- });
970
-
971
- export const signInSSO = (options?: SSOOptions) => {
972
- return createAuthEndpoint(
973
- "/sign-in/sso",
974
- {
975
- method: "POST",
976
- body: signInSSOBodySchema,
977
- metadata: {
978
- openapi: {
979
- operationId: "signInWithSSO",
980
- summary: "Sign in with SSO provider",
981
- description:
982
- "This endpoint is used to sign in with an SSO provider. It redirects to the provider's authorization URL",
983
- requestBody: {
984
- content: {
985
- "application/json": {
986
- schema: {
987
- type: "object",
988
- properties: {
989
- email: {
990
- type: "string",
991
- description:
992
- "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",
993
- },
994
- issuer: {
995
- type: "string",
996
- description:
997
- "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",
998
- },
999
- providerId: {
1000
- type: "string",
1001
- description:
1002
- "The ID of the provider to sign in with. This can be provided instead of email or issuer",
1003
- },
1004
- callbackURL: {
1005
- type: "string",
1006
- description: "The URL to redirect to after login",
1007
- },
1008
- errorCallbackURL: {
1009
- type: "string",
1010
- description: "The URL to redirect to after login",
1011
- },
1012
- newUserCallbackURL: {
1013
- type: "string",
1014
- description:
1015
- "The URL to redirect to after login if the user is new",
1016
- },
1017
- loginHint: {
1018
- type: "string",
1019
- description:
1020
- "Login hint to send to the identity provider (e.g., email or identifier). If supported, sent as 'login_hint'.",
1021
- },
1022
- },
1023
- required: ["callbackURL"],
1024
- },
1025
- },
1026
- },
1027
- },
1028
- responses: {
1029
- "200": {
1030
- description:
1031
- "Authorization URL generated successfully for SSO sign-in",
1032
- content: {
1033
- "application/json": {
1034
- schema: {
1035
- type: "object",
1036
- properties: {
1037
- url: {
1038
- type: "string",
1039
- format: "uri",
1040
- description:
1041
- "The authorization URL to redirect the user to for SSO sign-in",
1042
- },
1043
- redirect: {
1044
- type: "boolean",
1045
- description:
1046
- "Indicates that the client should redirect to the provided URL",
1047
- enum: [true],
1048
- },
1049
- },
1050
- required: ["url", "redirect"],
1051
- },
1052
- },
1053
- },
1054
- },
1055
- },
1056
- },
1057
- },
1058
- },
1059
- async (ctx) => {
1060
- const body = ctx.body;
1061
- let { email, organizationSlug, providerId, domain } = body;
1062
- if (
1063
- !options?.defaultSSO?.length &&
1064
- !email &&
1065
- !organizationSlug &&
1066
- !domain &&
1067
- !providerId
1068
- ) {
1069
- throw new APIError("BAD_REQUEST", {
1070
- message: "email, organizationSlug, domain or providerId is required",
1071
- });
1072
- }
1073
- domain = body.domain || email?.split("@")[1];
1074
- let orgId = "";
1075
- if (organizationSlug) {
1076
- orgId = await ctx.context.adapter
1077
- .findOne<{ id: string }>({
1078
- model: "organization",
1079
- where: [
1080
- {
1081
- field: "slug",
1082
- value: organizationSlug,
1083
- },
1084
- ],
1085
- })
1086
- .then((res) => {
1087
- if (!res) {
1088
- return "";
1089
- }
1090
- return res.id;
1091
- });
1092
- }
1093
- let provider: SSOProvider<SSOOptions> | null = null;
1094
- if (options?.defaultSSO?.length) {
1095
- // Find matching default SSO provider by providerId
1096
- const matchingDefault = providerId
1097
- ? options.defaultSSO.find(
1098
- (defaultProvider) => defaultProvider.providerId === providerId,
1099
- )
1100
- : options.defaultSSO.find(
1101
- (defaultProvider) => defaultProvider.domain === domain,
1102
- );
1103
-
1104
- if (matchingDefault) {
1105
- provider = {
1106
- issuer:
1107
- matchingDefault.samlConfig?.issuer ||
1108
- matchingDefault.oidcConfig?.issuer ||
1109
- "",
1110
- providerId: matchingDefault.providerId,
1111
- userId: "default",
1112
- oidcConfig: matchingDefault.oidcConfig,
1113
- samlConfig: matchingDefault.samlConfig,
1114
- domain: matchingDefault.domain,
1115
- ...(options.domainVerification?.enabled
1116
- ? { domainVerified: true }
1117
- : {}),
1118
- } as SSOProvider<SSOOptions>;
1119
- }
1120
- }
1121
- if (!providerId && !orgId && !domain) {
1122
- throw new APIError("BAD_REQUEST", {
1123
- message: "providerId, orgId or domain is required",
1124
- });
1125
- }
1126
- // Try to find provider in database
1127
- if (!provider) {
1128
- provider = await ctx.context.adapter
1129
- .findOne<SSOProvider<SSOOptions>>({
1130
- model: "ssoProvider",
1131
- where: [
1132
- {
1133
- field: providerId
1134
- ? "providerId"
1135
- : orgId
1136
- ? "organizationId"
1137
- : "domain",
1138
- value: providerId || orgId || domain!,
1139
- },
1140
- ],
1141
- })
1142
- .then((res) => {
1143
- if (!res) {
1144
- return null;
1145
- }
1146
- return {
1147
- ...res,
1148
- oidcConfig: res.oidcConfig
1149
- ? safeJsonParse<OIDCConfig>(
1150
- res.oidcConfig as unknown as string,
1151
- ) || undefined
1152
- : undefined,
1153
- samlConfig: res.samlConfig
1154
- ? safeJsonParse<SAMLConfig>(
1155
- res.samlConfig as unknown as string,
1156
- ) || undefined
1157
- : undefined,
1158
- };
1159
- });
1160
- }
1161
-
1162
- if (!provider) {
1163
- throw new APIError("NOT_FOUND", {
1164
- message: "No provider found for the issuer",
1165
- });
1166
- }
1167
-
1168
- if (body.providerType) {
1169
- if (body.providerType === "oidc" && !provider.oidcConfig) {
1170
- throw new APIError("BAD_REQUEST", {
1171
- message: "OIDC provider is not configured",
1172
- });
1173
- }
1174
- if (body.providerType === "saml" && !provider.samlConfig) {
1175
- throw new APIError("BAD_REQUEST", {
1176
- message: "SAML provider is not configured",
1177
- });
1178
- }
1179
- }
1180
-
1181
- if (
1182
- options?.domainVerification?.enabled &&
1183
- !("domainVerified" in provider && provider.domainVerified)
1184
- ) {
1185
- throw new APIError("UNAUTHORIZED", {
1186
- message: "Provider domain has not been verified",
1187
- });
1188
- }
1189
-
1190
- if (provider.oidcConfig && body.providerType !== "saml") {
1191
- let finalAuthUrl = provider.oidcConfig.authorizationEndpoint;
1192
- if (!finalAuthUrl && provider.oidcConfig.discoveryEndpoint) {
1193
- const discovery = await betterFetch<{
1194
- authorization_endpoint: string;
1195
- }>(provider.oidcConfig.discoveryEndpoint, {
1196
- method: "GET",
1197
- });
1198
- if (discovery.data) {
1199
- finalAuthUrl = discovery.data.authorization_endpoint;
1200
- }
1201
- }
1202
- if (!finalAuthUrl) {
1203
- throw new APIError("BAD_REQUEST", {
1204
- message: "Invalid OIDC configuration. Authorization URL not found.",
1205
- });
1206
- }
1207
- const state = await generateState(ctx, undefined, false);
1208
- const redirectURI = `${ctx.context.baseURL}/sso/callback/${provider.providerId}`;
1209
- const authorizationURL = await createAuthorizationURL({
1210
- id: provider.issuer,
1211
- options: {
1212
- clientId: provider.oidcConfig.clientId,
1213
- clientSecret: provider.oidcConfig.clientSecret,
1214
- },
1215
- redirectURI,
1216
- state: state.state,
1217
- codeVerifier: provider.oidcConfig.pkce
1218
- ? state.codeVerifier
1219
- : undefined,
1220
- scopes: ctx.body.scopes ||
1221
- provider.oidcConfig.scopes || [
1222
- "openid",
1223
- "email",
1224
- "profile",
1225
- "offline_access",
1226
- ],
1227
- loginHint: ctx.body.loginHint || email,
1228
- authorizationEndpoint: finalAuthUrl,
1229
- });
1230
- return ctx.json({
1231
- url: authorizationURL.toString(),
1232
- redirect: true,
1233
- });
1234
- }
1235
- if (provider.samlConfig) {
1236
- const parsedSamlConfig =
1237
- typeof provider.samlConfig === "object"
1238
- ? provider.samlConfig
1239
- : safeJsonParse<SAMLConfig>(
1240
- provider.samlConfig as unknown as string,
1241
- );
1242
- if (!parsedSamlConfig) {
1243
- throw new APIError("BAD_REQUEST", {
1244
- message: "Invalid SAML configuration",
1245
- });
1246
- }
1247
-
1248
- let metadata = parsedSamlConfig.spMetadata.metadata;
1249
-
1250
- if (!metadata) {
1251
- metadata =
1252
- saml
1253
- .SPMetadata({
1254
- entityID:
1255
- parsedSamlConfig.spMetadata?.entityID ||
1256
- parsedSamlConfig.issuer,
1257
- assertionConsumerService: [
1258
- {
1259
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
1260
- Location:
1261
- parsedSamlConfig.callbackUrl ||
1262
- `${ctx.context.baseURL}/sso/saml2/sp/acs/${provider.providerId}`,
1263
- },
1264
- ],
1265
- wantMessageSigned:
1266
- parsedSamlConfig.wantAssertionsSigned || false,
1267
- nameIDFormat: parsedSamlConfig.identifierFormat
1268
- ? [parsedSamlConfig.identifierFormat]
1269
- : undefined,
1270
- })
1271
- .getMetadata() || "";
1272
- }
1273
-
1274
- const sp = saml.ServiceProvider({
1275
- metadata: metadata,
1276
- allowCreate: true,
1277
- });
1278
-
1279
- const idp = saml.IdentityProvider({
1280
- metadata: parsedSamlConfig.idpMetadata?.metadata,
1281
- entityID: parsedSamlConfig.idpMetadata?.entityID,
1282
- encryptCert: parsedSamlConfig.idpMetadata?.cert,
1283
- singleSignOnService:
1284
- parsedSamlConfig.idpMetadata?.singleSignOnService,
1285
- });
1286
- const loginRequest = sp.createLoginRequest(
1287
- idp,
1288
- "redirect",
1289
- ) as BindingContext & {
1290
- entityEndpoint: string;
1291
- type: string;
1292
- id: string;
1293
- };
1294
- if (!loginRequest) {
1295
- throw new APIError("BAD_REQUEST", {
1296
- message: "Invalid SAML request",
1297
- });
1298
- }
1299
-
1300
- const { state: relayState } = await generateRelayState(
1301
- ctx,
1302
- undefined,
1303
- false,
1304
- );
1305
-
1306
- const shouldSaveRequest =
1307
- loginRequest.id && options?.saml?.enableInResponseToValidation;
1308
- if (shouldSaveRequest) {
1309
- const ttl = options?.saml?.requestTTL ?? DEFAULT_AUTHN_REQUEST_TTL_MS;
1310
- const record: AuthnRequestRecord = {
1311
- id: loginRequest.id,
1312
- providerId: provider.providerId,
1313
- createdAt: Date.now(),
1314
- expiresAt: Date.now() + ttl,
1315
- };
1316
- await ctx.context.internalAdapter.createVerificationValue({
1317
- identifier: `${AUTHN_REQUEST_KEY_PREFIX}${record.id}`,
1318
- value: JSON.stringify(record),
1319
- expiresAt: new Date(record.expiresAt),
1320
- });
1321
- }
1322
-
1323
- return ctx.json({
1324
- url: `${loginRequest.context}&RelayState=${encodeURIComponent(relayState)}`,
1325
- redirect: true,
1326
- });
1327
- }
1328
- throw new APIError("BAD_REQUEST", {
1329
- message: "Invalid SSO provider",
1330
- });
1331
- },
1332
- );
1333
- };
1334
-
1335
- const callbackSSOQuerySchema = z.object({
1336
- code: z.string().optional(),
1337
- state: z.string(),
1338
- error: z.string().optional(),
1339
- error_description: z.string().optional(),
1340
- });
1341
-
1342
- export const callbackSSO = (options?: SSOOptions) => {
1343
- return createAuthEndpoint(
1344
- "/sso/callback/:providerId",
1345
- {
1346
- method: "GET",
1347
- query: callbackSSOQuerySchema,
1348
- allowedMediaTypes: [
1349
- "application/x-www-form-urlencoded",
1350
- "application/json",
1351
- ],
1352
- metadata: {
1353
- ...HIDE_METADATA,
1354
- openapi: {
1355
- operationId: "handleSSOCallback",
1356
- summary: "Callback URL for SSO provider",
1357
- description:
1358
- "This endpoint is used as the callback URL for SSO providers. It handles the authorization code and exchanges it for an access token",
1359
- responses: {
1360
- "302": {
1361
- description: "Redirects to the callback URL",
1362
- },
1363
- },
1364
- },
1365
- },
1366
- },
1367
- async (ctx) => {
1368
- const { code, error, error_description } = ctx.query;
1369
- const stateData = await parseState(ctx);
1370
- if (!stateData) {
1371
- const errorURL =
1372
- ctx.context.options.onAPIError?.errorURL ||
1373
- `${ctx.context.baseURL}/error`;
1374
- throw ctx.redirect(`${errorURL}?error=invalid_state`);
1375
- }
1376
- const { callbackURL, errorURL, newUserURL, requestSignUp } = stateData;
1377
- if (!code || error) {
1378
- throw ctx.redirect(
1379
- `${
1380
- errorURL || callbackURL
1381
- }?error=${error}&error_description=${error_description}`,
1382
- );
1383
- }
1384
- let provider: SSOProvider<SSOOptions> | null = null;
1385
- if (options?.defaultSSO?.length) {
1386
- const matchingDefault = options.defaultSSO.find(
1387
- (defaultProvider) =>
1388
- defaultProvider.providerId === ctx.params.providerId,
1389
- );
1390
- if (matchingDefault) {
1391
- provider = {
1392
- ...matchingDefault,
1393
- issuer: matchingDefault.oidcConfig?.issuer || "",
1394
- userId: "default",
1395
- ...(options.domainVerification?.enabled
1396
- ? { domainVerified: true }
1397
- : {}),
1398
- } as SSOProvider<SSOOptions>;
1399
- }
1400
- }
1401
- if (!provider) {
1402
- provider = await ctx.context.adapter
1403
- .findOne<{
1404
- oidcConfig: string;
1405
- }>({
1406
- model: "ssoProvider",
1407
- where: [
1408
- {
1409
- field: "providerId",
1410
- value: ctx.params.providerId,
1411
- },
1412
- ],
1413
- })
1414
- .then((res) => {
1415
- if (!res) {
1416
- return null;
1417
- }
1418
- return {
1419
- ...res,
1420
- oidcConfig:
1421
- safeJsonParse<OIDCConfig>(res.oidcConfig) || undefined,
1422
- } as SSOProvider<SSOOptions>;
1423
- });
1424
- }
1425
- if (!provider) {
1426
- throw ctx.redirect(
1427
- `${
1428
- errorURL || callbackURL
1429
- }/error?error=invalid_provider&error_description=provider not found`,
1430
- );
1431
- }
1432
-
1433
- if (
1434
- options?.domainVerification?.enabled &&
1435
- !("domainVerified" in provider && provider.domainVerified)
1436
- ) {
1437
- throw new APIError("UNAUTHORIZED", {
1438
- message: "Provider domain has not been verified",
1439
- });
1440
- }
1441
-
1442
- let config = provider.oidcConfig;
1443
-
1444
- if (!config) {
1445
- throw ctx.redirect(
1446
- `${
1447
- errorURL || callbackURL
1448
- }/error?error=invalid_provider&error_description=provider not found`,
1449
- );
1450
- }
1451
-
1452
- const discovery = await betterFetch<{
1453
- token_endpoint: string;
1454
- userinfo_endpoint: string;
1455
- token_endpoint_auth_method:
1456
- | "client_secret_basic"
1457
- | "client_secret_post";
1458
- }>(config.discoveryEndpoint);
1459
-
1460
- if (discovery.data) {
1461
- config = {
1462
- tokenEndpoint: discovery.data.token_endpoint,
1463
- tokenEndpointAuthentication:
1464
- discovery.data.token_endpoint_auth_method,
1465
- userInfoEndpoint: discovery.data.userinfo_endpoint,
1466
- scopes: ["openid", "email", "profile", "offline_access"],
1467
- ...config,
1468
- };
1469
- }
1470
-
1471
- if (!config.tokenEndpoint) {
1472
- throw ctx.redirect(
1473
- `${
1474
- errorURL || callbackURL
1475
- }/error?error=invalid_provider&error_description=token_endpoint_not_found`,
1476
- );
1477
- }
1478
-
1479
- const tokenResponse = await validateAuthorizationCode({
1480
- code,
1481
- codeVerifier: config.pkce ? stateData.codeVerifier : undefined,
1482
- redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`,
1483
- options: {
1484
- clientId: config.clientId,
1485
- clientSecret: config.clientSecret,
1486
- },
1487
- tokenEndpoint: config.tokenEndpoint,
1488
- authentication:
1489
- config.tokenEndpointAuthentication === "client_secret_post"
1490
- ? "post"
1491
- : "basic",
1492
- }).catch((e) => {
1493
- if (e instanceof BetterFetchError) {
1494
- throw ctx.redirect(
1495
- `${
1496
- errorURL || callbackURL
1497
- }?error=invalid_provider&error_description=${e.message}`,
1498
- );
1499
- }
1500
- return null;
1501
- });
1502
- if (!tokenResponse) {
1503
- throw ctx.redirect(
1504
- `${
1505
- errorURL || callbackURL
1506
- }/error?error=invalid_provider&error_description=token_response_not_found`,
1507
- );
1508
- }
1509
- let userInfo: {
1510
- id?: string;
1511
- email?: string;
1512
- name?: string;
1513
- image?: string;
1514
- emailVerified?: boolean;
1515
- [key: string]: any;
1516
- } | null = null;
1517
- if (tokenResponse.idToken) {
1518
- const idToken = decodeJwt(tokenResponse.idToken);
1519
- if (!config.jwksEndpoint) {
1520
- throw ctx.redirect(
1521
- `${
1522
- errorURL || callbackURL
1523
- }/error?error=invalid_provider&error_description=jwks_endpoint_not_found`,
1524
- );
1525
- }
1526
- const verified = await validateToken(
1527
- tokenResponse.idToken,
1528
- config.jwksEndpoint,
1529
- ).catch((e) => {
1530
- ctx.context.logger.error(e);
1531
- return null;
1532
- });
1533
- if (!verified) {
1534
- throw ctx.redirect(
1535
- `${
1536
- errorURL || callbackURL
1537
- }/error?error=invalid_provider&error_description=token_not_verified`,
1538
- );
1539
- }
1540
- if (verified.payload.iss !== provider.issuer) {
1541
- throw ctx.redirect(
1542
- `${
1543
- errorURL || callbackURL
1544
- }/error?error=invalid_provider&error_description=issuer_mismatch`,
1545
- );
1546
- }
1547
-
1548
- const mapping = config.mapping || {};
1549
- userInfo = {
1550
- ...Object.fromEntries(
1551
- Object.entries(mapping.extraFields || {}).map(([key, value]) => [
1552
- key,
1553
- verified.payload[value],
1554
- ]),
1555
- ),
1556
- id: idToken[mapping.id || "sub"],
1557
- email: idToken[mapping.email || "email"],
1558
- emailVerified: options?.trustEmailVerified
1559
- ? idToken[mapping.emailVerified || "email_verified"]
1560
- : false,
1561
- name: idToken[mapping.name || "name"],
1562
- image: idToken[mapping.image || "picture"],
1563
- } as {
1564
- id?: string;
1565
- email?: string;
1566
- name?: string;
1567
- image?: string;
1568
- emailVerified?: boolean;
1569
- };
1570
- }
1571
-
1572
- if (!userInfo) {
1573
- if (!config.userInfoEndpoint) {
1574
- throw ctx.redirect(
1575
- `${
1576
- errorURL || callbackURL
1577
- }/error?error=invalid_provider&error_description=user_info_endpoint_not_found`,
1578
- );
1579
- }
1580
- const userInfoResponse = await betterFetch<{
1581
- email?: string;
1582
- name?: string;
1583
- id?: string;
1584
- image?: string;
1585
- emailVerified?: boolean;
1586
- }>(config.userInfoEndpoint, {
1587
- headers: {
1588
- Authorization: `Bearer ${tokenResponse.accessToken}`,
1589
- },
1590
- });
1591
- if (userInfoResponse.error) {
1592
- throw ctx.redirect(
1593
- `${
1594
- errorURL || callbackURL
1595
- }/error?error=invalid_provider&error_description=${
1596
- userInfoResponse.error.message
1597
- }`,
1598
- );
1599
- }
1600
- userInfo = userInfoResponse.data;
1601
- }
1602
-
1603
- if (!userInfo.email || !userInfo.id) {
1604
- throw ctx.redirect(
1605
- `${
1606
- errorURL || callbackURL
1607
- }/error?error=invalid_provider&error_description=missing_user_info`,
1608
- );
1609
- }
1610
- const isTrustedProvider =
1611
- "domainVerified" in provider &&
1612
- (provider as { domainVerified?: boolean }).domainVerified === true &&
1613
- validateEmailDomain(userInfo.email, provider.domain);
1614
-
1615
- const linked = await handleOAuthUserInfo(ctx, {
1616
- userInfo: {
1617
- email: userInfo.email,
1618
- name: userInfo.name || userInfo.email,
1619
- id: userInfo.id,
1620
- image: userInfo.image,
1621
- emailVerified: options?.trustEmailVerified
1622
- ? userInfo.emailVerified || false
1623
- : false,
1624
- },
1625
- account: {
1626
- idToken: tokenResponse.idToken,
1627
- accessToken: tokenResponse.accessToken,
1628
- refreshToken: tokenResponse.refreshToken,
1629
- accountId: userInfo.id,
1630
- providerId: provider.providerId,
1631
- accessTokenExpiresAt: tokenResponse.accessTokenExpiresAt,
1632
- refreshTokenExpiresAt: tokenResponse.refreshTokenExpiresAt,
1633
- scope: tokenResponse.scopes?.join(","),
1634
- },
1635
- callbackURL,
1636
- disableSignUp: options?.disableImplicitSignUp && !requestSignUp,
1637
- overrideUserInfo: config.overrideUserInfo,
1638
- isTrustedProvider,
1639
- });
1640
- if (linked.error) {
1641
- throw ctx.redirect(
1642
- `${errorURL || callbackURL}/error?error=${linked.error}`,
1643
- );
1644
- }
1645
- const { session, user } = linked.data!;
1646
-
1647
- if (options?.provisionUser) {
1648
- await options.provisionUser({
1649
- user,
1650
- userInfo,
1651
- token: tokenResponse,
1652
- provider,
1653
- });
1654
- }
1655
-
1656
- await assignOrganizationFromProvider(ctx as any, {
1657
- user,
1658
- profile: {
1659
- providerType: "oidc",
1660
- providerId: provider.providerId,
1661
- accountId: userInfo.id,
1662
- email: userInfo.email,
1663
- emailVerified: Boolean(userInfo.emailVerified),
1664
- rawAttributes: userInfo,
1665
- },
1666
- provider,
1667
- token: tokenResponse,
1668
- provisioningOptions: options?.organizationProvisioning,
1669
- });
1670
-
1671
- await setSessionCookie(ctx, {
1672
- session,
1673
- user,
1674
- });
1675
- let toRedirectTo: string;
1676
- try {
1677
- const url = linked.isRegister ? newUserURL || callbackURL : callbackURL;
1678
- toRedirectTo = url.toString();
1679
- } catch {
1680
- toRedirectTo = linked.isRegister
1681
- ? newUserURL || callbackURL
1682
- : callbackURL;
1683
- }
1684
- throw ctx.redirect(toRedirectTo);
1685
- },
1686
- );
1687
- };
1688
-
1689
- const callbackSSOSAMLBodySchema = z.object({
1690
- SAMLResponse: z.string(),
1691
- RelayState: z.string().optional(),
1692
- });
1693
-
1694
- /**
1695
- * Validates and returns a safe redirect URL.
1696
- * - Prevents open redirect attacks by validating against trusted origins
1697
- * - Prevents redirect loops by checking if URL points to callback route
1698
- * - Falls back to appOrigin if URL is invalid or unsafe
1699
- */
1700
- const getSafeRedirectUrl = (
1701
- url: string | undefined,
1702
- callbackPath: string,
1703
- appOrigin: string,
1704
- isTrustedOrigin: (
1705
- url: string,
1706
- settings?: { allowRelativePaths: boolean },
1707
- ) => boolean,
1708
- ): string => {
1709
- if (!url) {
1710
- return appOrigin;
1711
- }
1712
-
1713
- if (url.startsWith("/") && !url.startsWith("//")) {
1714
- try {
1715
- const absoluteUrl = new URL(url, appOrigin);
1716
- if (absoluteUrl.origin !== appOrigin) {
1717
- return appOrigin;
1718
- }
1719
- const callbackPathname = new URL(callbackPath).pathname;
1720
- if (absoluteUrl.pathname === callbackPathname) {
1721
- return appOrigin;
1722
- }
1723
- } catch {
1724
- return appOrigin;
1725
- }
1726
- return url;
1727
- }
1728
-
1729
- if (!isTrustedOrigin(url, { allowRelativePaths: false })) {
1730
- return appOrigin;
1731
- }
1732
-
1733
- try {
1734
- const callbackPathname = new URL(callbackPath).pathname;
1735
- const urlPathname = new URL(url).pathname;
1736
- if (urlPathname === callbackPathname) {
1737
- return appOrigin;
1738
- }
1739
- } catch {
1740
- if (url === callbackPath || url.startsWith(`${callbackPath}?`)) {
1741
- return appOrigin;
1742
- }
1743
- }
1744
-
1745
- return url;
1746
- };
1747
-
1748
- export const callbackSSOSAML = (options?: SSOOptions) => {
1749
- return createAuthEndpoint(
1750
- "/sso/saml2/callback/:providerId",
1751
- {
1752
- method: ["GET", "POST"],
1753
- body: callbackSSOSAMLBodySchema.optional(),
1754
- query: z
1755
- .object({
1756
- RelayState: z.string().optional(),
1757
- })
1758
- .optional(),
1759
- metadata: {
1760
- ...HIDE_METADATA,
1761
- allowedMediaTypes: [
1762
- "application/x-www-form-urlencoded",
1763
- "application/json",
1764
- ],
1765
- openapi: {
1766
- operationId: "handleSAMLCallback",
1767
- summary: "Callback URL for SAML provider",
1768
- description:
1769
- "This endpoint is used as the callback URL for SAML providers. Supports both GET and POST methods for IdP-initiated and SP-initiated flows.",
1770
- responses: {
1771
- "302": {
1772
- description: "Redirects to the callback URL",
1773
- },
1774
- "400": {
1775
- description: "Invalid SAML response",
1776
- },
1777
- "401": {
1778
- description: "Unauthorized - SAML authentication failed",
1779
- },
1780
- },
1781
- },
1782
- },
1783
- },
1784
- async (ctx) => {
1785
- const { providerId } = ctx.params;
1786
- const appOrigin = new URL(ctx.context.baseURL).origin;
1787
- const errorURL =
1788
- ctx.context.options.onAPIError?.errorURL || `${appOrigin}/error`;
1789
- const currentCallbackPath = `${ctx.context.baseURL}/sso/saml2/callback/${providerId}`;
1790
-
1791
- // Determine if this is a GET request by checking both method AND body presence
1792
- // When called via auth.api.*, ctx.method may not be reliable, so we also check for body
1793
- const isGetRequest = ctx.method === "GET" && !ctx.body?.SAMLResponse;
1794
-
1795
- if (isGetRequest) {
1796
- const session = await getSessionFromCtx(ctx);
1797
-
1798
- if (!session?.session) {
1799
- throw ctx.redirect(`${errorURL}?error=invalid_request`);
1800
- }
1801
-
1802
- const relayState = ctx.query?.RelayState as string | undefined;
1803
- const safeRedirectUrl = getSafeRedirectUrl(
1804
- relayState,
1805
- currentCallbackPath,
1806
- appOrigin,
1807
- (url, settings) => ctx.context.isTrustedOrigin(url, settings),
1808
- );
1809
-
1810
- throw ctx.redirect(safeRedirectUrl);
1811
- }
1812
-
1813
- if (!ctx.body?.SAMLResponse) {
1814
- throw new APIError("BAD_REQUEST", {
1815
- message: "SAMLResponse is required for POST requests",
1816
- });
1817
- }
1818
-
1819
- const { SAMLResponse } = ctx.body;
1820
-
1821
- const maxResponseSize =
1822
- options?.saml?.maxResponseSize ?? DEFAULT_MAX_SAML_RESPONSE_SIZE;
1823
- if (new TextEncoder().encode(SAMLResponse).length > maxResponseSize) {
1824
- throw new APIError("BAD_REQUEST", {
1825
- message: `SAML response exceeds maximum allowed size (${maxResponseSize} bytes)`,
1826
- });
1827
- }
1828
-
1829
- let relayState: RelayState | null = null;
1830
- if (ctx.body.RelayState) {
1831
- try {
1832
- relayState = await parseRelayState(ctx);
1833
- } catch {
1834
- relayState = null;
1835
- }
1836
- }
1837
- let provider: SSOProvider<SSOOptions> | null = null;
1838
- if (options?.defaultSSO?.length) {
1839
- const matchingDefault = options.defaultSSO.find(
1840
- (defaultProvider) => defaultProvider.providerId === providerId,
1841
- );
1842
- if (matchingDefault) {
1843
- provider = {
1844
- ...matchingDefault,
1845
- userId: "default",
1846
- issuer: matchingDefault.samlConfig?.issuer || "",
1847
- ...(options.domainVerification?.enabled
1848
- ? { domainVerified: true }
1849
- : {}),
1850
- } as SSOProvider<SSOOptions>;
1851
- }
1852
- }
1853
- if (!provider) {
1854
- provider = await ctx.context.adapter
1855
- .findOne<SSOProvider<SSOOptions>>({
1856
- model: "ssoProvider",
1857
- where: [{ field: "providerId", value: providerId }],
1858
- })
1859
- .then((res) => {
1860
- if (!res) return null;
1861
- return {
1862
- ...res,
1863
- samlConfig: res.samlConfig
1864
- ? safeJsonParse<SAMLConfig>(
1865
- res.samlConfig as unknown as string,
1866
- ) || undefined
1867
- : undefined,
1868
- };
1869
- });
1870
- }
1871
-
1872
- if (!provider) {
1873
- throw new APIError("NOT_FOUND", {
1874
- message: "No provider found for the given providerId",
1875
- });
1876
- }
1877
-
1878
- if (
1879
- options?.domainVerification?.enabled &&
1880
- !("domainVerified" in provider && provider.domainVerified)
1881
- ) {
1882
- throw new APIError("UNAUTHORIZED", {
1883
- message: "Provider domain has not been verified",
1884
- });
1885
- }
1886
-
1887
- const parsedSamlConfig = safeJsonParse<SAMLConfig>(
1888
- provider.samlConfig as unknown as string,
1889
- );
1890
- if (!parsedSamlConfig) {
1891
- throw new APIError("BAD_REQUEST", {
1892
- message: "Invalid SAML configuration",
1893
- });
1894
- }
1895
- const idpData = parsedSamlConfig.idpMetadata;
1896
- let idp: IdentityProvider | null = null;
1897
-
1898
- // Construct IDP with fallback to manual configuration
1899
- if (!idpData?.metadata) {
1900
- idp = saml.IdentityProvider({
1901
- entityID: idpData?.entityID || parsedSamlConfig.issuer,
1902
- singleSignOnService: [
1903
- {
1904
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
1905
- Location: parsedSamlConfig.entryPoint,
1906
- },
1907
- ],
1908
- signingCert: idpData?.cert || parsedSamlConfig.cert,
1909
- wantAuthnRequestsSigned:
1910
- parsedSamlConfig.wantAssertionsSigned || false,
1911
- isAssertionEncrypted: idpData?.isAssertionEncrypted || false,
1912
- encPrivateKey: idpData?.encPrivateKey,
1913
- encPrivateKeyPass: idpData?.encPrivateKeyPass,
1914
- });
1915
- } else {
1916
- idp = saml.IdentityProvider({
1917
- metadata: idpData.metadata,
1918
- privateKey: idpData.privateKey,
1919
- privateKeyPass: idpData.privateKeyPass,
1920
- isAssertionEncrypted: idpData.isAssertionEncrypted,
1921
- encPrivateKey: idpData.encPrivateKey,
1922
- encPrivateKeyPass: idpData.encPrivateKeyPass,
1923
- });
1924
- }
1925
-
1926
- // Construct SP with fallback to manual configuration
1927
- const spData = parsedSamlConfig.spMetadata;
1928
- const sp = saml.ServiceProvider({
1929
- metadata: spData?.metadata,
1930
- entityID: spData?.entityID || parsedSamlConfig.issuer,
1931
- assertionConsumerService: spData?.metadata
1932
- ? undefined
1933
- : [
1934
- {
1935
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
1936
- Location: parsedSamlConfig.callbackUrl,
1937
- },
1938
- ],
1939
- privateKey: spData?.privateKey || parsedSamlConfig.privateKey,
1940
- privateKeyPass: spData?.privateKeyPass,
1941
- isAssertionEncrypted: spData?.isAssertionEncrypted || false,
1942
- encPrivateKey: spData?.encPrivateKey,
1943
- encPrivateKeyPass: spData?.encPrivateKeyPass,
1944
- wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
1945
- nameIDFormat: parsedSamlConfig.identifierFormat
1946
- ? [parsedSamlConfig.identifierFormat]
1947
- : undefined,
1948
- });
1949
-
1950
- validateSingleAssertion(SAMLResponse);
1951
-
1952
- let parsedResponse: FlowResult;
1953
- try {
1954
- parsedResponse = await sp.parseLoginResponse(idp, "post", {
1955
- body: {
1956
- SAMLResponse,
1957
- RelayState: ctx.body.RelayState || undefined,
1958
- },
1959
- });
1960
-
1961
- if (!parsedResponse?.extract) {
1962
- throw new Error("Invalid SAML response structure");
1963
- }
1964
- } catch (error) {
1965
- ctx.context.logger.error("SAML response validation failed", {
1966
- error,
1967
- decodedResponse: Buffer.from(SAMLResponse, "base64").toString(
1968
- "utf-8",
1969
- ),
1970
- });
1971
- throw new APIError("BAD_REQUEST", {
1972
- message: "Invalid SAML response",
1973
- details: error instanceof Error ? error.message : String(error),
1974
- });
1975
- }
1976
-
1977
- const { extract } = parsedResponse!;
1978
-
1979
- validateSAMLAlgorithms(parsedResponse, options?.saml?.algorithms);
1980
-
1981
- validateSAMLTimestamp((extract as any).conditions, {
1982
- clockSkew: options?.saml?.clockSkew,
1983
- requireTimestamps: options?.saml?.requireTimestamps,
1984
- logger: ctx.context.logger,
1985
- });
1986
-
1987
- const inResponseTo = (extract as any).inResponseTo as string | undefined;
1988
- const shouldValidateInResponseTo =
1989
- options?.saml?.enableInResponseToValidation;
1990
-
1991
- if (shouldValidateInResponseTo) {
1992
- const allowIdpInitiated = options?.saml?.allowIdpInitiated !== false;
1993
-
1994
- if (inResponseTo) {
1995
- let storedRequest: AuthnRequestRecord | null = null;
1996
-
1997
- const verification =
1998
- await ctx.context.internalAdapter.findVerificationValue(
1999
- `${AUTHN_REQUEST_KEY_PREFIX}${inResponseTo}`,
2000
- );
2001
- if (verification) {
2002
- try {
2003
- storedRequest = JSON.parse(
2004
- verification.value,
2005
- ) as AuthnRequestRecord;
2006
- if (storedRequest && storedRequest.expiresAt < Date.now()) {
2007
- storedRequest = null;
2008
- }
2009
- } catch {
2010
- storedRequest = null;
2011
- }
2012
- }
2013
-
2014
- if (!storedRequest) {
2015
- ctx.context.logger.error(
2016
- "SAML InResponseTo validation failed: unknown or expired request ID",
2017
- { inResponseTo, providerId: provider.providerId },
2018
- );
2019
- const redirectUrl =
2020
- relayState?.callbackURL ||
2021
- parsedSamlConfig.callbackUrl ||
2022
- ctx.context.baseURL;
2023
- throw ctx.redirect(
2024
- `${redirectUrl}?error=invalid_saml_response&error_description=Unknown+or+expired+request+ID`,
2025
- );
2026
- }
2027
-
2028
- if (storedRequest.providerId !== provider.providerId) {
2029
- ctx.context.logger.error(
2030
- "SAML InResponseTo validation failed: provider mismatch",
2031
- {
2032
- inResponseTo,
2033
- expectedProvider: storedRequest.providerId,
2034
- actualProvider: provider.providerId,
2035
- },
2036
- );
2037
-
2038
- await ctx.context.internalAdapter.deleteVerificationByIdentifier(
2039
- `${AUTHN_REQUEST_KEY_PREFIX}${inResponseTo}`,
2040
- );
2041
- const redirectUrl =
2042
- relayState?.callbackURL ||
2043
- parsedSamlConfig.callbackUrl ||
2044
- ctx.context.baseURL;
2045
- throw ctx.redirect(
2046
- `${redirectUrl}?error=invalid_saml_response&error_description=Provider+mismatch`,
2047
- );
2048
- }
2049
-
2050
- await ctx.context.internalAdapter.deleteVerificationByIdentifier(
2051
- `${AUTHN_REQUEST_KEY_PREFIX}${inResponseTo}`,
2052
- );
2053
- } else if (!allowIdpInitiated) {
2054
- ctx.context.logger.error(
2055
- "SAML IdP-initiated SSO rejected: InResponseTo missing and allowIdpInitiated is false",
2056
- { providerId: provider.providerId },
2057
- );
2058
- const redirectUrl =
2059
- relayState?.callbackURL ||
2060
- parsedSamlConfig.callbackUrl ||
2061
- ctx.context.baseURL;
2062
- throw ctx.redirect(
2063
- `${redirectUrl}?error=unsolicited_response&error_description=IdP-initiated+SSO+not+allowed`,
2064
- );
2065
- }
2066
- }
2067
-
2068
- // Assertion Replay Protection
2069
- const samlContent = (parsedResponse as any).samlContent as
2070
- | string
2071
- | undefined;
2072
- const assertionId = samlContent ? extractAssertionId(samlContent) : null;
2073
-
2074
- if (assertionId) {
2075
- const issuer = idp.entityMeta.getEntityID();
2076
- const conditions = (extract as any).conditions as
2077
- | SAMLConditions
2078
- | undefined;
2079
- const clockSkew = options?.saml?.clockSkew ?? DEFAULT_CLOCK_SKEW_MS;
2080
- const expiresAt = conditions?.notOnOrAfter
2081
- ? new Date(conditions.notOnOrAfter).getTime() + clockSkew
2082
- : Date.now() + DEFAULT_ASSERTION_TTL_MS;
2083
-
2084
- const existingAssertion =
2085
- await ctx.context.internalAdapter.findVerificationValue(
2086
- `${USED_ASSERTION_KEY_PREFIX}${assertionId}`,
2087
- );
2088
-
2089
- let isReplay = false;
2090
- if (existingAssertion) {
2091
- try {
2092
- const stored = JSON.parse(existingAssertion.value);
2093
- if (stored.expiresAt >= Date.now()) {
2094
- isReplay = true;
2095
- }
2096
- } catch (error) {
2097
- ctx.context.logger.warn("Failed to parse stored assertion record", {
2098
- assertionId,
2099
- error,
2100
- });
2101
- }
2102
- }
2103
-
2104
- if (isReplay) {
2105
- ctx.context.logger.error(
2106
- "SAML assertion replay detected: assertion ID already used",
2107
- {
2108
- assertionId,
2109
- issuer,
2110
- providerId: provider.providerId,
2111
- },
2112
- );
2113
- const redirectUrl =
2114
- relayState?.callbackURL ||
2115
- parsedSamlConfig.callbackUrl ||
2116
- ctx.context.baseURL;
2117
- throw ctx.redirect(
2118
- `${redirectUrl}?error=replay_detected&error_description=SAML+assertion+has+already+been+used`,
2119
- );
2120
- }
2121
-
2122
- await ctx.context.internalAdapter.createVerificationValue({
2123
- identifier: `${USED_ASSERTION_KEY_PREFIX}${assertionId}`,
2124
- value: JSON.stringify({
2125
- assertionId,
2126
- issuer,
2127
- providerId: provider.providerId,
2128
- usedAt: Date.now(),
2129
- expiresAt,
2130
- }),
2131
- expiresAt: new Date(expiresAt),
2132
- });
2133
- } else {
2134
- ctx.context.logger.warn(
2135
- "Could not extract assertion ID for replay protection",
2136
- { providerId: provider.providerId },
2137
- );
2138
- }
2139
-
2140
- const attributes = extract.attributes || {};
2141
- const mapping = parsedSamlConfig.mapping ?? {};
2142
-
2143
- const userInfo = {
2144
- ...Object.fromEntries(
2145
- Object.entries(mapping.extraFields || {}).map(([key, value]) => [
2146
- key,
2147
- attributes[value as string],
2148
- ]),
2149
- ),
2150
- id: attributes[mapping.id || "nameID"] || extract.nameID,
2151
- email: attributes[mapping.email || "email"] || extract.nameID,
2152
- name:
2153
- [
2154
- attributes[mapping.firstName || "givenName"],
2155
- attributes[mapping.lastName || "surname"],
2156
- ]
2157
- .filter(Boolean)
2158
- .join(" ") ||
2159
- attributes[mapping.name || "displayName"] ||
2160
- extract.nameID,
2161
- emailVerified:
2162
- options?.trustEmailVerified && mapping.emailVerified
2163
- ? ((attributes[mapping.emailVerified] || false) as boolean)
2164
- : false,
2165
- };
2166
- if (!userInfo.id || !userInfo.email) {
2167
- ctx.context.logger.error(
2168
- "Missing essential user info from SAML response",
2169
- {
2170
- attributes: Object.keys(attributes),
2171
- mapping,
2172
- extractedId: userInfo.id,
2173
- extractedEmail: userInfo.email,
2174
- },
2175
- );
2176
- throw new APIError("BAD_REQUEST", {
2177
- message: "Unable to extract user ID or email from SAML response",
2178
- });
2179
- }
2180
-
2181
- const isTrustedProvider: boolean =
2182
- !!ctx.context.options.account?.accountLinking?.trustedProviders?.includes(
2183
- provider.providerId,
2184
- ) ||
2185
- ("domainVerified" in provider &&
2186
- !!(provider as { domainVerified?: boolean }).domainVerified &&
2187
- validateEmailDomain(userInfo.email as string, provider.domain));
2188
-
2189
- const callbackUrl =
2190
- relayState?.callbackURL ||
2191
- parsedSamlConfig.callbackUrl ||
2192
- ctx.context.baseURL;
2193
-
2194
- const result = await handleOAuthUserInfo(ctx, {
2195
- userInfo: {
2196
- email: userInfo.email as string,
2197
- name: (userInfo.name || userInfo.email) as string,
2198
- id: userInfo.id as string,
2199
- emailVerified: Boolean(userInfo.emailVerified),
2200
- },
2201
- account: {
2202
- providerId: provider.providerId,
2203
- accountId: userInfo.id as string,
2204
- accessToken: "",
2205
- refreshToken: "",
2206
- },
2207
- callbackURL: callbackUrl,
2208
- disableSignUp: options?.disableImplicitSignUp,
2209
- isTrustedProvider,
2210
- });
2211
-
2212
- if (result.error) {
2213
- throw ctx.redirect(
2214
- `${callbackUrl}?error=${result.error.split(" ").join("_")}`,
2215
- );
2216
- }
2217
-
2218
- const { session, user } = result.data!;
2219
-
2220
- if (options?.provisionUser) {
2221
- await options.provisionUser({
2222
- user: user as User & Record<string, any>,
2223
- userInfo,
2224
- provider,
2225
- });
2226
- }
2227
-
2228
- await assignOrganizationFromProvider(ctx as any, {
2229
- user,
2230
- profile: {
2231
- providerType: "saml",
2232
- providerId: provider.providerId,
2233
- accountId: userInfo.id as string,
2234
- email: userInfo.email as string,
2235
- emailVerified: Boolean(userInfo.emailVerified),
2236
- rawAttributes: attributes,
2237
- },
2238
- provider,
2239
- provisioningOptions: options?.organizationProvisioning,
2240
- });
2241
-
2242
- await setSessionCookie(ctx, { session, user });
2243
-
2244
- const safeRedirectUrl = getSafeRedirectUrl(
2245
- relayState?.callbackURL || parsedSamlConfig.callbackUrl,
2246
- currentCallbackPath,
2247
- appOrigin,
2248
- (url, settings) => ctx.context.isTrustedOrigin(url, settings),
2249
- );
2250
- throw ctx.redirect(safeRedirectUrl);
2251
- },
2252
- );
2253
- };
2254
-
2255
- const acsEndpointParamsSchema = z.object({
2256
- providerId: z.string().optional(),
2257
- });
2258
-
2259
- const acsEndpointBodySchema = z.object({
2260
- SAMLResponse: z.string(),
2261
- RelayState: z.string().optional(),
2262
- });
2263
-
2264
- export const acsEndpoint = (options?: SSOOptions) => {
2265
- return createAuthEndpoint(
2266
- "/sso/saml2/sp/acs/:providerId",
2267
- {
2268
- method: "POST",
2269
- params: acsEndpointParamsSchema,
2270
- body: acsEndpointBodySchema,
2271
- metadata: {
2272
- ...HIDE_METADATA,
2273
- allowedMediaTypes: [
2274
- "application/x-www-form-urlencoded",
2275
- "application/json",
2276
- ],
2277
- openapi: {
2278
- operationId: "handleSAMLAssertionConsumerService",
2279
- summary: "SAML Assertion Consumer Service",
2280
- description:
2281
- "Handles SAML responses from IdP after successful authentication",
2282
- responses: {
2283
- "302": {
2284
- description:
2285
- "Redirects to the callback URL after successful authentication",
2286
- },
2287
- },
2288
- },
2289
- },
2290
- },
2291
- async (ctx) => {
2292
- const { SAMLResponse, RelayState = "" } = ctx.body;
2293
- const { providerId } = ctx.params;
2294
-
2295
- const maxResponseSize =
2296
- options?.saml?.maxResponseSize ?? DEFAULT_MAX_SAML_RESPONSE_SIZE;
2297
- if (new TextEncoder().encode(SAMLResponse).length > maxResponseSize) {
2298
- throw new APIError("BAD_REQUEST", {
2299
- message: `SAML response exceeds maximum allowed size (${maxResponseSize} bytes)`,
2300
- });
2301
- }
2302
-
2303
- // If defaultSSO is configured, use it as the provider
2304
- let provider: SSOProvider<SSOOptions> | null = null;
2305
-
2306
- if (options?.defaultSSO?.length) {
2307
- // For ACS endpoint, we can use the first default provider or try to match by providerId
2308
- const matchingDefault = providerId
2309
- ? options.defaultSSO.find(
2310
- (defaultProvider) => defaultProvider.providerId === providerId,
2311
- )
2312
- : options.defaultSSO[0]; // Use first default provider if no specific providerId
2313
-
2314
- if (matchingDefault) {
2315
- provider = {
2316
- issuer: matchingDefault.samlConfig?.issuer || "",
2317
- providerId: matchingDefault.providerId,
2318
- userId: "default",
2319
- samlConfig: matchingDefault.samlConfig,
2320
- domain: matchingDefault.domain,
2321
- ...(options.domainVerification?.enabled
2322
- ? { domainVerified: true }
2323
- : {}),
2324
- };
2325
- }
2326
- } else {
2327
- provider = await ctx.context.adapter
2328
- .findOne<SSOProvider<SSOOptions>>({
2329
- model: "ssoProvider",
2330
- where: [
2331
- {
2332
- field: "providerId",
2333
- value: providerId ?? "sso",
2334
- },
2335
- ],
2336
- })
2337
- .then((res) => {
2338
- if (!res) return null;
2339
- return {
2340
- ...res,
2341
- samlConfig: res.samlConfig
2342
- ? safeJsonParse<SAMLConfig>(
2343
- res.samlConfig as unknown as string,
2344
- ) || undefined
2345
- : undefined,
2346
- };
2347
- });
2348
- }
2349
-
2350
- if (!provider?.samlConfig) {
2351
- throw new APIError("NOT_FOUND", {
2352
- message: "No SAML provider found",
2353
- });
2354
- }
2355
-
2356
- if (
2357
- options?.domainVerification?.enabled &&
2358
- !("domainVerified" in provider && provider.domainVerified)
2359
- ) {
2360
- throw new APIError("UNAUTHORIZED", {
2361
- message: "Provider domain has not been verified",
2362
- });
2363
- }
2364
-
2365
- const parsedSamlConfig = provider.samlConfig;
2366
- // Configure SP and IdP
2367
- const sp = saml.ServiceProvider({
2368
- entityID:
2369
- parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
2370
- assertionConsumerService: [
2371
- {
2372
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
2373
- Location:
2374
- parsedSamlConfig.callbackUrl ||
2375
- `${ctx.context.baseURL}/sso/saml2/sp/acs/${providerId}`,
2376
- },
2377
- ],
2378
- wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
2379
- metadata: parsedSamlConfig.spMetadata?.metadata,
2380
- privateKey:
2381
- parsedSamlConfig.spMetadata?.privateKey ||
2382
- parsedSamlConfig.privateKey,
2383
- privateKeyPass: parsedSamlConfig.spMetadata?.privateKeyPass,
2384
- nameIDFormat: parsedSamlConfig.identifierFormat
2385
- ? [parsedSamlConfig.identifierFormat]
2386
- : undefined,
2387
- });
2388
-
2389
- // Update where we construct the IdP
2390
- const idpData = parsedSamlConfig.idpMetadata;
2391
- const idp = !idpData?.metadata
2392
- ? saml.IdentityProvider({
2393
- entityID: idpData?.entityID || parsedSamlConfig.issuer,
2394
- singleSignOnService: idpData?.singleSignOnService || [
2395
- {
2396
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
2397
- Location: parsedSamlConfig.entryPoint,
2398
- },
2399
- ],
2400
- signingCert: idpData?.cert || parsedSamlConfig.cert,
2401
- })
2402
- : saml.IdentityProvider({
2403
- metadata: idpData.metadata,
2404
- });
2405
-
2406
- try {
2407
- validateSingleAssertion(SAMLResponse);
2408
- } catch (error) {
2409
- if (error instanceof APIError) {
2410
- const redirectUrl =
2411
- RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
2412
- const errorCode =
2413
- error.body?.code === "SAML_MULTIPLE_ASSERTIONS"
2414
- ? "multiple_assertions"
2415
- : "no_assertion";
2416
- throw ctx.redirect(
2417
- `${redirectUrl}?error=${errorCode}&error_description=${encodeURIComponent(error.message)}`,
2418
- );
2419
- }
2420
- throw error;
2421
- }
2422
-
2423
- // Parse and validate SAML response
2424
- let parsedResponse: FlowResult;
2425
- try {
2426
- parsedResponse = await sp.parseLoginResponse(idp, "post", {
2427
- body: {
2428
- SAMLResponse,
2429
- RelayState: RelayState || undefined,
2430
- },
2431
- });
2432
-
2433
- if (!parsedResponse?.extract) {
2434
- throw new Error("Invalid SAML response structure");
2435
- }
2436
- } catch (error) {
2437
- ctx.context.logger.error("SAML response validation failed", {
2438
- error,
2439
- decodedResponse: Buffer.from(SAMLResponse, "base64").toString(
2440
- "utf-8",
2441
- ),
2442
- });
2443
- throw new APIError("BAD_REQUEST", {
2444
- message: "Invalid SAML response",
2445
- details: error instanceof Error ? error.message : String(error),
2446
- });
2447
- }
2448
-
2449
- const { extract } = parsedResponse!;
2450
-
2451
- validateSAMLAlgorithms(parsedResponse, options?.saml?.algorithms);
2452
-
2453
- validateSAMLTimestamp((extract as any).conditions, {
2454
- clockSkew: options?.saml?.clockSkew,
2455
- requireTimestamps: options?.saml?.requireTimestamps,
2456
- logger: ctx.context.logger,
2457
- });
2458
-
2459
- const inResponseToAcs = (extract as any).inResponseTo as
2460
- | string
2461
- | undefined;
2462
- const shouldValidateInResponseToAcs =
2463
- options?.saml?.enableInResponseToValidation;
2464
-
2465
- if (shouldValidateInResponseToAcs) {
2466
- const allowIdpInitiated = options?.saml?.allowIdpInitiated !== false;
2467
-
2468
- if (inResponseToAcs) {
2469
- let storedRequest: AuthnRequestRecord | null = null;
2470
-
2471
- const verification =
2472
- await ctx.context.internalAdapter.findVerificationValue(
2473
- `${AUTHN_REQUEST_KEY_PREFIX}${inResponseToAcs}`,
2474
- );
2475
- if (verification) {
2476
- try {
2477
- storedRequest = JSON.parse(
2478
- verification.value,
2479
- ) as AuthnRequestRecord;
2480
- if (storedRequest && storedRequest.expiresAt < Date.now()) {
2481
- storedRequest = null;
2482
- }
2483
- } catch {
2484
- storedRequest = null;
2485
- }
2486
- }
2487
-
2488
- if (!storedRequest) {
2489
- ctx.context.logger.error(
2490
- "SAML InResponseTo validation failed: unknown or expired request ID",
2491
- { inResponseTo: inResponseToAcs, providerId },
2492
- );
2493
- const redirectUrl =
2494
- RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
2495
- throw ctx.redirect(
2496
- `${redirectUrl}?error=invalid_saml_response&error_description=Unknown+or+expired+request+ID`,
2497
- );
2498
- }
2499
-
2500
- if (storedRequest.providerId !== providerId) {
2501
- ctx.context.logger.error(
2502
- "SAML InResponseTo validation failed: provider mismatch",
2503
- {
2504
- inResponseTo: inResponseToAcs,
2505
- expectedProvider: storedRequest.providerId,
2506
- actualProvider: providerId,
2507
- },
2508
- );
2509
- await ctx.context.internalAdapter.deleteVerificationByIdentifier(
2510
- `${AUTHN_REQUEST_KEY_PREFIX}${inResponseToAcs}`,
2511
- );
2512
- const redirectUrl =
2513
- RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
2514
- throw ctx.redirect(
2515
- `${redirectUrl}?error=invalid_saml_response&error_description=Provider+mismatch`,
2516
- );
2517
- }
2518
-
2519
- await ctx.context.internalAdapter.deleteVerificationByIdentifier(
2520
- `${AUTHN_REQUEST_KEY_PREFIX}${inResponseToAcs}`,
2521
- );
2522
- } else if (!allowIdpInitiated) {
2523
- ctx.context.logger.error(
2524
- "SAML IdP-initiated SSO rejected: InResponseTo missing and allowIdpInitiated is false",
2525
- { providerId },
2526
- );
2527
- const redirectUrl =
2528
- RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
2529
- throw ctx.redirect(
2530
- `${redirectUrl}?error=unsolicited_response&error_description=IdP-initiated+SSO+not+allowed`,
2531
- );
2532
- }
2533
- }
2534
-
2535
- // Assertion Replay Protection
2536
- const samlContentAcs = Buffer.from(SAMLResponse, "base64").toString(
2537
- "utf-8",
2538
- );
2539
- const assertionIdAcs = extractAssertionId(samlContentAcs);
2540
-
2541
- if (assertionIdAcs) {
2542
- const issuer = idp.entityMeta.getEntityID();
2543
- const conditions = (extract as any).conditions as
2544
- | SAMLConditions
2545
- | undefined;
2546
- const clockSkew = options?.saml?.clockSkew ?? DEFAULT_CLOCK_SKEW_MS;
2547
- const expiresAt = conditions?.notOnOrAfter
2548
- ? new Date(conditions.notOnOrAfter).getTime() + clockSkew
2549
- : Date.now() + DEFAULT_ASSERTION_TTL_MS;
2550
-
2551
- const existingAssertion =
2552
- await ctx.context.internalAdapter.findVerificationValue(
2553
- `${USED_ASSERTION_KEY_PREFIX}${assertionIdAcs}`,
2554
- );
2555
-
2556
- let isReplay = false;
2557
- if (existingAssertion) {
2558
- try {
2559
- const stored = JSON.parse(existingAssertion.value);
2560
- if (stored.expiresAt >= Date.now()) {
2561
- isReplay = true;
2562
- }
2563
- } catch (error) {
2564
- ctx.context.logger.warn("Failed to parse stored assertion record", {
2565
- assertionId: assertionIdAcs,
2566
- error,
2567
- });
2568
- }
2569
- }
2570
-
2571
- if (isReplay) {
2572
- ctx.context.logger.error(
2573
- "SAML assertion replay detected: assertion ID already used",
2574
- {
2575
- assertionId: assertionIdAcs,
2576
- issuer,
2577
- providerId,
2578
- },
2579
- );
2580
- const redirectUrl =
2581
- RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
2582
- throw ctx.redirect(
2583
- `${redirectUrl}?error=replay_detected&error_description=SAML+assertion+has+already+been+used`,
2584
- );
2585
- }
2586
-
2587
- await ctx.context.internalAdapter.createVerificationValue({
2588
- identifier: `${USED_ASSERTION_KEY_PREFIX}${assertionIdAcs}`,
2589
- value: JSON.stringify({
2590
- assertionId: assertionIdAcs,
2591
- issuer,
2592
- providerId,
2593
- usedAt: Date.now(),
2594
- expiresAt,
2595
- }),
2596
- expiresAt: new Date(expiresAt),
2597
- });
2598
- } else {
2599
- ctx.context.logger.warn(
2600
- "Could not extract assertion ID for replay protection",
2601
- { providerId },
2602
- );
2603
- }
2604
-
2605
- const attributes = extract.attributes || {};
2606
- const mapping = parsedSamlConfig.mapping ?? {};
2607
-
2608
- const userInfo = {
2609
- ...Object.fromEntries(
2610
- Object.entries(mapping.extraFields || {}).map(([key, value]) => [
2611
- key,
2612
- attributes[value as string],
2613
- ]),
2614
- ),
2615
- id: attributes[mapping.id || "nameID"] || extract.nameID,
2616
- email: attributes[mapping.email || "email"] || extract.nameID,
2617
- name:
2618
- [
2619
- attributes[mapping.firstName || "givenName"],
2620
- attributes[mapping.lastName || "surname"],
2621
- ]
2622
- .filter(Boolean)
2623
- .join(" ") ||
2624
- attributes[mapping.name || "displayName"] ||
2625
- extract.nameID,
2626
- emailVerified:
2627
- options?.trustEmailVerified && mapping.emailVerified
2628
- ? ((attributes[mapping.emailVerified] || false) as boolean)
2629
- : false,
2630
- };
2631
-
2632
- if (!userInfo.id || !userInfo.email) {
2633
- ctx.context.logger.error(
2634
- "Missing essential user info from SAML response",
2635
- {
2636
- attributes: Object.keys(attributes),
2637
- mapping,
2638
- extractedId: userInfo.id,
2639
- extractedEmail: userInfo.email,
2640
- },
2641
- );
2642
- throw new APIError("BAD_REQUEST", {
2643
- message: "Unable to extract user ID or email from SAML response",
2644
- });
2645
- }
2646
-
2647
- const isTrustedProvider: boolean =
2648
- !!ctx.context.options.account?.accountLinking?.trustedProviders?.includes(
2649
- provider.providerId,
2650
- ) ||
2651
- ("domainVerified" in provider &&
2652
- !!(provider as { domainVerified?: boolean }).domainVerified &&
2653
- validateEmailDomain(userInfo.email as string, provider.domain));
2654
-
2655
- const callbackUrl =
2656
- RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
2657
-
2658
- const result = await handleOAuthUserInfo(ctx, {
2659
- userInfo: {
2660
- email: userInfo.email as string,
2661
- name: (userInfo.name || userInfo.email) as string,
2662
- id: userInfo.id as string,
2663
- emailVerified: Boolean(userInfo.emailVerified),
2664
- },
2665
- account: {
2666
- providerId: provider.providerId,
2667
- accountId: userInfo.id as string,
2668
- accessToken: "",
2669
- refreshToken: "",
2670
- },
2671
- callbackURL: callbackUrl,
2672
- disableSignUp: options?.disableImplicitSignUp,
2673
- isTrustedProvider,
2674
- });
2675
-
2676
- if (result.error) {
2677
- throw ctx.redirect(
2678
- `${callbackUrl}?error=${result.error.split(" ").join("_")}`,
2679
- );
2680
- }
2681
-
2682
- const { session, user } = result.data!;
2683
-
2684
- if (options?.provisionUser) {
2685
- await options.provisionUser({
2686
- user: user as User & Record<string, any>,
2687
- userInfo,
2688
- provider,
2689
- });
2690
- }
2691
-
2692
- await assignOrganizationFromProvider(ctx as any, {
2693
- user,
2694
- profile: {
2695
- providerType: "saml",
2696
- providerId: provider.providerId,
2697
- accountId: userInfo.id as string,
2698
- email: userInfo.email as string,
2699
- emailVerified: Boolean(userInfo.emailVerified),
2700
- rawAttributes: attributes,
2701
- },
2702
- provider,
2703
- provisioningOptions: options?.organizationProvisioning,
2704
- });
2705
-
2706
- await setSessionCookie(ctx, { session, user });
2707
- throw ctx.redirect(callbackUrl);
2708
- },
2709
- );
2710
- };