@better-auth/sso 1.5.0-beta.18 → 1.5.0-beta.19

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