-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathauth.ts
More file actions
3355 lines (3117 loc) · 128 KB
/
Copy pathauth.ts
File metadata and controls
3355 lines (3117 loc) · 128 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createHash } from 'crypto'
import { cache } from 'react'
import { sso } from '@better-auth/sso'
import { stripe } from '@better-auth/stripe'
import { db } from '@sim/db'
import * as schema from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { betterAuth, type User } from 'better-auth'
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
import { APIError, createAuthMiddleware } from 'better-auth/api'
import { nextCookies } from 'better-auth/next-js'
import {
admin,
captcha,
customSession,
emailOTP,
genericOAuth,
oneTimeToken,
organization,
} from 'better-auth/plugins'
import { and, count, eq, inArray, sql } from 'drizzle-orm'
import { headers } from 'next/headers'
import Stripe from 'stripe'
import {
getEmailSubject,
renderExistingAccountEmail,
renderOTPEmail,
renderPasswordResetEmail,
renderWelcomeEmail,
} from '@/components/emails'
import { getAccessControlConfig, isEmailBlockedByAccessControl } from '@/lib/auth/access-control'
import { sendPlanWelcomeEmail } from '@/lib/billing'
import { authorizeSubscriptionReference } from '@/lib/billing/authorization'
import {
getOrganizationIdForSubscriptionReference,
syncSubscriptionPlan,
writeBillingInterval,
} from '@/lib/billing/core/subscription'
import { handleNewUser } from '@/lib/billing/core/usage'
import {
ensureOrganizationForTeamSubscription,
syncSubscriptionUsageLimits,
} from '@/lib/billing/organization'
import { isTeam } from '@/lib/billing/plan-helpers'
import { getPlans, resolvePlanFromStripeSubscription } from '@/lib/billing/plans'
import { syncSeatsFromStripeQuantity } from '@/lib/billing/validation/seat-management'
import { handleAbandonedCheckout } from '@/lib/billing/webhooks/checkout'
import { handleChargeDispute, handleDisputeClosed } from '@/lib/billing/webhooks/disputes'
import { handleManualEnterpriseSubscription } from '@/lib/billing/webhooks/enterprise'
import {
handleInvoiceFinalized,
handleInvoicePaymentFailed,
handleInvoicePaymentSucceeded,
} from '@/lib/billing/webhooks/invoices'
import {
handleOrganizationPlanDowngrade,
handleSubscriptionCreated,
handleSubscriptionDeleted,
} from '@/lib/billing/webhooks/subscription'
import { env } from '@/lib/core/config/env'
import {
isAuthDisabled,
isBillingEnabled,
isEmailPasswordEnabled,
isEmailSignupDisabled,
isEmailVerificationEnabled,
isGithubAuthDisabled,
isGoogleAuthDisabled,
isHosted,
isMicrosoftAuthDisabled,
isOrganizationsEnabled,
isRegistrationDisabled,
isSignupMxValidationEnabled,
isSsoEnabled,
} from '@/lib/core/config/env-flags'
import { PlatformEvents } from '@/lib/core/telemetry'
import { getBaseUrl, isLocalhostUrl, parseOriginList } from '@/lib/core/utils/urls'
import { processCredentialDraft } from '@/lib/credentials/draft-processor'
import { sendEmail } from '@/lib/messaging/email/mailer'
import { getFromEmailAddress, getPersonalEmailFrom } from '@/lib/messaging/email/utils'
import { quickValidateEmail } from '@/lib/messaging/email/validation'
import { validateSignupEmailMx } from '@/lib/messaging/email/validation.server'
import { scheduleLifecycleEmail } from '@/lib/messaging/lifecycle'
import { captureServerEvent, getPostHogClient } from '@/lib/posthog/server'
import { syncAllWebhooksForCredentialSet } from '@/lib/webhooks/utils.server'
import { disableUserResources } from '@/lib/workflows/lifecycle'
import { SSO_TRUSTED_PROVIDERS } from '@/ee/sso/constants'
import { createAnonymousSession, ensureAnonymousUserExists } from './anonymous'
import { getRequestedSignInProviderId, isSignInProviderAllowed } from './constants'
const logger = createLogger('Auth')
import {
deriveMicrosoftEmailVerified,
getMicrosoftRefreshTokenExpiry,
isMicrosoftProvider,
} from '@/lib/oauth/microsoft'
import { getCanonicalScopesForProvider } from '@/lib/oauth/utils'
/**
* Extracts user info from a Microsoft ID token JWT instead of calling Graph API /me.
* This avoids 403 errors for external tenant users whose admin hasn't consented to Graph API scopes.
* The ID token is always returned when the openid scope is requested.
*/
function getMicrosoftUserInfoFromIdToken(tokens: { accessToken?: string }, providerId: string) {
const idToken = (tokens as Record<string, unknown>).idToken as string | undefined
if (!idToken) {
logger.error(
`Microsoft ${providerId} OAuth: no ID token received. Ensure openid scope is requested.`
)
throw new Error(`Microsoft ${providerId} OAuth requires an ID token (openid scope)`)
}
const parts = idToken.split('.')
if (parts.length !== 3) {
throw new Error(`Microsoft ${providerId} OAuth: malformed ID token`)
}
let payload: Record<string, unknown>
try {
payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf-8'))
} catch {
throw new Error(`Microsoft ${providerId} OAuth: failed to decode ID token payload`)
}
const email =
(payload.email as string) || (payload.preferred_username as string) || (payload.upn as string)
if (!email) {
throw new Error(
`Microsoft ${providerId} OAuth: ID token contains no email, preferred_username, or upn claim`
)
}
const emailVerified = deriveMicrosoftEmailVerified(payload, email)
const now = new Date()
return {
id: `${payload.oid || payload.sub}-${generateId()}`,
name: (payload.name as string) || 'Microsoft User',
email,
emailVerified,
createdAt: now,
updatedAt: now,
}
}
const additionalTrustedOrigins = parseOriginList(env.TRUSTED_ORIGINS, (value) =>
logger.warn('Ignoring invalid entry in TRUSTED_ORIGINS', { value })
)
/**
* SSO provider IDs to trust for automatic account linking when an SSO sign-in
* matches an existing account's email. Includes `SSO_PROVIDER_ID` when it is set
* in the app environment, plus any IDs from `SSO_TRUSTED_PROVIDER_IDS`. Empty when
* SSO is disabled, so `trustedProviders` is unchanged for non-SSO deployments.
* Resolved once at startup; `trustEmailVerified` on the SSO plugin handles IdPs
* that assert `email_verified` live, so this is only needed for IdPs that omit it.
*/
const additionalTrustedSsoProviders = isSsoEnabled
? [env.SSO_PROVIDER_ID, ...(env.SSO_TRUSTED_PROVIDER_IDS?.split(',') ?? [])]
.map((id) => id?.trim())
.filter((id): id is string => Boolean(id))
: []
if (env.NODE_ENV === 'production') {
const baseUrl = getBaseUrl()
if (isLocalhostUrl(baseUrl)) {
logger.warn(
'NEXT_PUBLIC_APP_URL points to localhost in production. Self-hosted deployments must set NEXT_PUBLIC_APP_URL to the public URL users access (e.g. https://sim.example.com), otherwise auth POST requests from any non-localhost origin will be rejected by trustedOrigins. Set TRUSTED_ORIGINS to allow additional public origins.',
{ baseUrl }
)
}
}
const validStripeKey = env.STRIPE_SECRET_KEY
let stripeClient = null
if (validStripeKey) {
stripeClient = new Stripe(env.STRIPE_SECRET_KEY || '', {
apiVersion: '2025-08-27.basil',
})
}
export const auth = betterAuth({
baseURL: getBaseUrl(),
trustedOrigins: [
getBaseUrl(),
...(env.NEXT_PUBLIC_SOCKET_URL ? [env.NEXT_PUBLIC_SOCKET_URL] : []),
...additionalTrustedOrigins,
].filter(Boolean),
database: drizzleAdapter(db, {
provider: 'pg',
schema,
}),
session: {
cookieCache: {
enabled: true,
maxAge: 24 * 60 * 60, // 24 hours in seconds
},
expiresIn: 30 * 24 * 60 * 60, // 30 days (how long a session can last overall)
updateAge: 24 * 60 * 60, // 24 hours (how often to refresh the expiry)
freshAge: 0,
},
user: {
deleteUser: {
enabled: false,
beforeDelete: async (deletingUser) => {
const { isSoleOwnerOfPaidOrganization } = await import(
'@/lib/billing/organizations/membership'
)
const check = await isSoleOwnerOfPaidOrganization(deletingUser.id)
if (check.isBlocker) {
throw new Error(
`You are the owner of ${check.organizationName ?? 'an active paid organization'}. Transfer ownership before deleting your account.`
)
}
const { reassignBilledAccountForUser, reassignOwnedWorkspacesForUser } = await import(
'@/lib/workspaces/utils'
)
const { unresolved } = await reassignBilledAccountForUser(deletingUser.id)
if (unresolved.length > 0) {
throw new Error(
`Your account is the billing account for ${unresolved.length} workspace${unresolved.length === 1 ? '' : 's'} with no other admin to take it over. Add another admin to ${unresolved.length === 1 ? 'that workspace' : 'those workspaces'} or delete ${unresolved.length === 1 ? 'it' : 'them'} before deleting your account.`
)
}
// Reassign workspace ownership BEFORE deletion so the `workspace.owner_id`
// ON DELETE CASCADE can never silently nuke workspaces this user owns
// (e.g. org workspaces they created but are billed to the org owner).
const { unresolved: ownedUnresolved } = await reassignOwnedWorkspacesForUser(
deletingUser.id
)
if (ownedUnresolved.length > 0) {
throw new Error(
`Your account owns ${ownedUnresolved.length} workspace${ownedUnresolved.length === 1 ? '' : 's'} with no other admin to take over ownership. Add another admin to ${ownedUnresolved.length === 1 ? 'that workspace' : 'those workspaces'} or delete ${ownedUnresolved.length === 1 ? 'it' : 'them'} before deleting your account.`
)
}
},
},
},
databaseHooks: {
user: {
create: {
before: async (user) => {
const accessControl = await getAccessControlConfig()
if (isEmailBlockedByAccessControl(user.email, accessControl)) {
throw new Error('Sign-ups from this email are not allowed.')
}
return { data: user }
},
after: async (user) => {
logger.info('[databaseHooks.user.create.after] User created, initializing stats', {
userId: user.id,
})
try {
PlatformEvents.userSignedUp({
userId: user.id,
authMethod: 'email',
})
} catch {
// Telemetry should not fail the operation
}
try {
const client = getPostHogClient()
if (client) {
client.identify({
distinctId: user.id,
properties: {
...(user.email ? { email: user.email } : {}),
...(user.name ? { name: user.name } : {}),
},
})
}
} catch {
// Telemetry should not fail the operation
}
try {
await handleNewUser(user.id)
} catch (error) {
logger.error('[databaseHooks.user.create.after] Failed to initialize user stats', {
userId: user.id,
error,
})
}
if (isHosted && user.email && user.emailVerified) {
try {
const html = await renderWelcomeEmail(user.name || undefined)
const { from, replyTo } = getPersonalEmailFrom()
await sendEmail({
to: user.email,
subject: getEmailSubject('welcome'),
html,
from,
replyTo,
emailType: 'transactional',
})
logger.info('[databaseHooks.user.create.after] Welcome email sent to OAuth user', {
userId: user.id,
})
} catch (error) {
logger.error('[databaseHooks.user.create.after] Failed to send welcome email', {
userId: user.id,
error,
})
}
try {
await scheduleLifecycleEmail({
userId: user.id,
type: 'onboarding-followup',
delayDays: 5,
})
} catch (error) {
logger.error(
'[databaseHooks.user.create.after] Failed to schedule onboarding followup email',
{ userId: user.id, error }
)
}
}
},
},
update: {
after: async (user) => {
if (user.banned) {
await disableUserResources(user.id)
}
},
},
},
account: {
create: {
before: async (account) => {
const modifiedAccount = { ...account }
if (account.providerId === 'salesforce' && account.accessToken) {
try {
const response = await fetch(
'https://login.salesforce.com/services/oauth2/userinfo',
{
headers: {
Authorization: `Bearer ${account.accessToken}`,
},
}
)
if (response.ok) {
const data = await response.json()
if (data.profile) {
const match = data.profile.match(/^(https:\/\/[^/]+)/)
if (match && match[1] !== 'https://login.salesforce.com') {
const instanceUrl = match[1]
modifiedAccount.scope = `__sf_instance__:${instanceUrl} ${account.scope}`
}
}
}
} catch (error) {
logger.error('Failed to fetch Salesforce instance URL', { error })
}
}
if (isMicrosoftProvider(account.providerId)) {
modifiedAccount.refreshTokenExpiresAt = getMicrosoftRefreshTokenExpiry()
}
// Box token response does not include a scope field, so Better Auth
// stores nothing. Populate it from the requested scopes so the
// credential-selector can verify permissions.
if (account.providerId === 'box' && !account.scope) {
const requestedScopes = getCanonicalScopesForProvider('box')
if (requestedScopes.length > 0) {
modifiedAccount.scope = requestedScopes.join(' ')
}
}
return { data: modifiedAccount }
},
after: async (account) => {
/**
* Migrate credentials from stale account rows to the newly created one.
*
* Each getUserInfo appends a random UUID to the stable external ID so
* that Better Auth never blocks cross-user connections. This means
* re-connecting the same external identity creates a new row. We detect
* the stale siblings here by comparing the stable prefix (everything
* before the trailing UUID), migrate any credential FKs to the new row,
* then delete the stale rows.
*/
try {
const UUID_SUFFIX_RE = /-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
const stablePrefix = account.accountId.replace(UUID_SUFFIX_RE, '')
if (stablePrefix && stablePrefix !== account.accountId) {
const siblings = await db
.select({ id: schema.account.id, accountId: schema.account.accountId })
.from(schema.account)
.where(
and(
eq(schema.account.userId, account.userId),
eq(schema.account.providerId, account.providerId),
sql`${schema.account.id} != ${account.id}`
)
)
const staleRows = siblings.filter(
(row) => row.accountId.replace(UUID_SUFFIX_RE, '') === stablePrefix
)
if (staleRows.length > 0) {
const staleIds = staleRows.map((row) => row.id)
await db
.update(schema.credential)
.set({ accountId: account.id })
.where(inArray(schema.credential.accountId, staleIds))
await db.delete(schema.account).where(inArray(schema.account.id, staleIds))
logger.info('[account.create.after] Migrated credentials from stale accounts', {
userId: account.userId,
providerId: account.providerId,
newAccountId: account.id,
migratedFrom: staleIds,
})
}
}
} catch (error) {
logger.error('[account.create.after] Failed to clean up stale accounts', {
userId: account.userId,
providerId: account.providerId,
error,
})
}
try {
await processCredentialDraft({
userId: account.userId,
providerId: account.providerId,
accountId: account.id,
})
} catch (error) {
logger.error('[account.create.after] Failed to process credential draft', {
userId: account.userId,
providerId: account.providerId,
error,
})
}
try {
const { ensureUserStatsExists } = await import('@/lib/billing/core/usage')
await ensureUserStatsExists(account.userId)
} catch (error) {
logger.error('[databaseHooks.account.create.after] Failed to ensure user stats', {
userId: account.userId,
accountId: account.id,
error,
})
}
try {
const [{ value: accountCount }] = await db
.select({ value: count() })
.from(schema.account)
.where(eq(schema.account.userId, account.userId))
if (accountCount === 1) {
const { providerId } = account
const authMethod =
providerId === 'credential'
? 'email'
: SSO_TRUSTED_PROVIDERS.includes(providerId)
? 'sso'
: 'oauth'
captureServerEvent(
account.userId,
'user_created',
{
auth_method: authMethod,
...(providerId !== 'credential' ? { provider: providerId } : {}),
},
{ setOnce: { signup_at: new Date().toISOString() } }
)
}
} catch (error) {
logger.error(
'[databaseHooks.account.create.after] Failed to capture user_created event',
{
userId: account.userId,
error,
}
)
}
if (account.providerId === 'salesforce') {
const updates: {
accessTokenExpiresAt?: Date
scope?: string
} = {}
if (!account.accessTokenExpiresAt) {
updates.accessTokenExpiresAt = new Date(Date.now() + 2 * 60 * 60 * 1000)
}
if (account.accessToken) {
try {
const response = await fetch(
'https://login.salesforce.com/services/oauth2/userinfo',
{
headers: {
Authorization: `Bearer ${account.accessToken}`,
},
}
)
if (response.ok) {
const data = await response.json()
if (data.profile) {
const match = data.profile.match(/^(https:\/\/[^/]+)/)
if (match && match[1] !== 'https://login.salesforce.com') {
const instanceUrl = match[1]
updates.scope = `__sf_instance__:${instanceUrl} ${account.scope}`
}
}
}
} catch (error) {
logger.error('Failed to fetch Salesforce instance URL', { error })
}
}
if (Object.keys(updates).length > 0) {
await db.update(schema.account).set(updates).where(eq(schema.account.id, account.id))
}
}
if (isMicrosoftProvider(account.providerId)) {
await db
.update(schema.account)
.set({ refreshTokenExpiresAt: getMicrosoftRefreshTokenExpiry() })
.where(eq(schema.account.id, account.id))
}
// Sync webhooks for credential sets after connecting a new credential
const requestId = generateId().slice(0, 8)
const userMemberships = await db
.select({
credentialSetId: schema.credentialSetMember.credentialSetId,
providerId: schema.credentialSet.providerId,
})
.from(schema.credentialSetMember)
.innerJoin(
schema.credentialSet,
eq(schema.credentialSetMember.credentialSetId, schema.credentialSet.id)
)
.where(
and(
eq(schema.credentialSetMember.userId, account.userId),
eq(schema.credentialSetMember.status, 'active')
)
)
for (const membership of userMemberships) {
if (membership.providerId === account.providerId) {
try {
await syncAllWebhooksForCredentialSet(membership.credentialSetId, requestId)
logger.info('[account.create.after] Synced webhooks after credential connect', {
credentialSetId: membership.credentialSetId,
providerId: account.providerId,
})
} catch (error) {
logger.error(
'[account.create.after] Failed to sync webhooks after credential connect',
{
credentialSetId: membership.credentialSetId,
providerId: account.providerId,
error,
}
)
}
}
}
try {
PlatformEvents.oauthConnected({
userId: account.userId,
provider: account.providerId,
})
} catch {
// Telemetry should not fail the operation
}
},
},
},
session: {
create: {
before: async (session) => {
// Blocked emails/domains must not establish sessions, regardless of
// provider (email/password, OAuth, SSO). Deliberately outside the
// try below — a thrown APIError must propagate, not be swallowed.
const accessControl = await getAccessControlConfig()
if (
accessControl.blockedSignupDomains.length > 0 ||
accessControl.blockedEmails.length > 0
) {
const [sessionUser] = await db
.select({ email: schema.user.email })
.from(schema.user)
.where(eq(schema.user.id, session.userId))
.limit(1)
if (isEmailBlockedByAccessControl(sessionUser?.email, accessControl)) {
logger.warn('Blocking session creation for blocked account', {
userId: session.userId,
})
throw new APIError('FORBIDDEN', {
message: 'Access restricted. Please contact your administrator.',
})
}
}
try {
// Find the first organization this user is a member of
const members = await db
.select()
.from(schema.member)
.where(eq(schema.member.userId, session.userId))
.limit(1)
if (members.length > 0) {
logger.info('Found organization for user', {
userId: session.userId,
organizationId: members[0].organizationId,
})
return {
data: {
...session,
activeOrganizationId: members[0].organizationId,
},
}
}
logger.info('No organizations found for user', {
userId: session.userId,
})
return { data: session }
} catch (error) {
logger.error('Error setting active organization', {
error,
userId: session.userId,
})
return { data: session }
}
},
},
},
},
account: {
accountLinking: {
enabled: true,
allowDifferentEmails: true,
requireLocalEmailVerified: false,
/**
* Only providers that verify email ownership may auto-link to an existing
* account during sign-in. Integration connectors are deliberately absent:
* they connect through the authenticated `/oauth2/link` flow, which binds
* to the current session user and never consults this list. `microsoft` is
* also excluded because it authenticates against the multi-tenant
* `/common/` endpoint where the email claim is attacker-controllable;
* leaving it trusted would bypass the email-verified check and allow
* nOAuth account takeover. Microsoft sign-in still works — it just links
* to an existing account only when the IdP asserts a verified email.
*/
trustedProviders: [
'google',
'github',
'email-password',
...SSO_TRUSTED_PROVIDERS,
...additionalTrustedSsoProviders,
],
},
},
socialProviders: {
...(!isGithubAuthDisabled && {
github: {
clientId: env.GITHUB_CLIENT_ID as string,
clientSecret: env.GITHUB_CLIENT_SECRET as string,
scope: ['user:email', 'repo'],
},
}),
...(!isGoogleAuthDisabled && {
google: {
clientId: env.GOOGLE_CLIENT_ID as string,
clientSecret: env.GOOGLE_CLIENT_SECRET as string,
scope: [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
],
},
}),
...(!isMicrosoftAuthDisabled &&
env.MICROSOFT_CLIENT_ID &&
env.MICROSOFT_CLIENT_SECRET && {
microsoft: {
clientId: env.MICROSOFT_CLIENT_ID,
clientSecret: env.MICROSOFT_CLIENT_SECRET,
scope: ['openid', 'profile', 'email'],
},
}),
},
emailVerification: {
autoSignInAfterVerification: true,
afterEmailVerification: async (user) => {
if (isHosted && user.email) {
try {
const html = await renderWelcomeEmail(user.name || undefined)
const { from, replyTo } = getPersonalEmailFrom()
await sendEmail({
to: user.email,
subject: getEmailSubject('welcome'),
html,
from,
replyTo,
emailType: 'transactional',
})
logger.info('[emailVerification.afterEmailVerification] Welcome email sent', {
userId: user.id,
})
} catch (error) {
logger.error('[emailVerification.afterEmailVerification] Failed to send welcome email', {
userId: user.id,
error,
})
}
try {
await scheduleLifecycleEmail({
userId: user.id,
type: 'onboarding-followup',
delayDays: 5,
})
} catch (error) {
logger.error(
'[emailVerification.afterEmailVerification] Failed to schedule onboarding followup email',
{ userId: user.id, error }
)
}
}
},
},
emailAndPassword: {
enabled: true,
requireEmailVerification: isEmailVerificationEnabled,
/**
* When someone signs up with an already-registered email, better-auth returns a
* generic success response (OWASP enumeration protection) instead of leaking that
* the account exists. This callback notifies the real account owner out-of-band,
* mirroring the privacy-preserving forget-password flow. Errors are swallowed so the
* response is indistinguishable from a genuine new sign-up.
*/
onExistingUserSignUp: async ({ user }: { user: User }) => {
try {
const html = await renderExistingAccountEmail(user.name || '')
const result = await sendEmail({
to: user.email,
subject: getEmailSubject('existing-account'),
html,
from: getFromEmailAddress(),
emailType: 'transactional',
})
if (!result.success) {
logger.warn('[onExistingUserSignUp] Failed to send existing-account email', {
message: result.message,
})
}
} catch (error) {
logger.error('[onExistingUserSignUp] Error sending existing-account email', { error })
}
},
/**
* The synthetic user returned for the generic duplicate-sign-up response must carry
* the exact same set of returned fields a real freshly-created user would, otherwise
* the differing response shape re-opens the enumeration oracle. The admin plugin
* (always loaded) adds role/banned/banReason/banExpires, and the Stripe plugin — loaded
* only when billing is enabled — adds stripeCustomerId (null on a new user).
*/
customSyntheticUser: ({
coreFields,
additionalFields,
id,
}: {
coreFields: {
name: string
email: string
emailVerified: boolean
image: string | null
createdAt: Date
updatedAt: Date
}
additionalFields: Record<string, unknown>
id: string
}) => ({
...coreFields,
role: 'user',
banned: false,
banReason: null,
banExpires: null,
...(isBillingEnabled && stripeClient ? { stripeCustomerId: null } : {}),
...additionalFields,
id,
}),
sendResetPassword: async ({ user, url, token }, request) => {
const username = user.name || ''
const html = await renderPasswordResetEmail(username, url)
const result = await sendEmail({
to: user.email,
subject: getEmailSubject('reset-password'),
html,
from: getFromEmailAddress(),
emailType: 'transactional',
})
if (!result.success) {
throw new Error(`Failed to send reset password email: ${result.message}`)
}
},
onPasswordReset: async ({ user: resetUser }) => {
const { AuditAction, AuditResourceType, recordAudit } = await import('@sim/audit')
recordAudit({
actorId: resetUser.id,
actorName: resetUser.name,
actorEmail: resetUser.email,
action: AuditAction.PASSWORD_RESET,
resourceType: AuditResourceType.PASSWORD,
resourceId: resetUser.id,
description: `Password reset completed for ${resetUser.email}`,
})
},
},
hooks: {
before: createAuthMiddleware(async (ctx) => {
/**
* Restrict the unauthenticated sign-in endpoints to first-party login
* providers. Better Auth registers every generic-OAuth integration
* connector as a social provider, so without this guard `microsoft-ad`,
* `salesforce`, `jira`, and the rest are reachable through
* `/sign-in/social` and `/sign-in/oauth2` and can mint a session for any
* user by email (nOAuth account takeover). Connectors are connected only
* through the authenticated `/oauth2/link` flow, which is unaffected.
*/
if (ctx.path === '/sign-in/social' || ctx.path === '/sign-in/oauth2') {
const requestedProviderId = getRequestedSignInProviderId(ctx.path, ctx.body)
if (!isSignInProviderAllowed(requestedProviderId)) {
throw new APIError('FORBIDDEN', {
message:
'This provider can only be connected from a signed-in account and cannot be used to sign in.',
})
}
}
if (ctx.path.startsWith('/sign-up') && isRegistrationDisabled)
throw new APIError('FORBIDDEN', {
message: 'Registration is disabled, please contact your admin.',
})
if (!isEmailPasswordEnabled) {
const emailPasswordPaths = ['/sign-in/email', '/sign-up/email', '/email-otp']
if (emailPasswordPaths.some((path) => ctx.path.startsWith(path)))
throw new APIError('FORBIDDEN', {
message: 'Email/password authentication is disabled. Please use SSO to sign in.',
})
}
if (isEmailSignupDisabled && ctx.path.startsWith('/sign-up/email'))
throw new APIError('FORBIDDEN', {
message: 'Email sign-up is disabled. Please use Google, Microsoft, or GitHub.',
})
const isSignIn = ctx.path.startsWith('/sign-in')
const isSignUp = ctx.path.startsWith('/sign-up')
if (isSignIn || isSignUp) {
const accessControl = await getAccessControlConfig()
const requestEmail = ctx.body?.email?.toLowerCase()
// Banning an existing account is owned by better-auth's admin plugin (a
// `session.create.before` hook that blocks banned users at sign-in across
// all providers), so it is not re-checked here.
const hasAllowlist =
accessControl.allowedLoginEmails.length > 0 ||
accessControl.allowedLoginDomains.length > 0
if (hasAllowlist && requestEmail) {
const emailDomain = requestEmail.split('@')[1]
const isAllowed =
accessControl.allowedLoginEmails.includes(requestEmail) ||
(!!emailDomain && accessControl.allowedLoginDomains.includes(emailDomain))
if (!isAllowed) {
throw new APIError('FORBIDDEN', {
message: 'Access restricted. Please contact your administrator.',
})
}
}
// Blocked emails/domains gate both signup and sign-in. OAuth/SSO sign-ins
// have no email in the body here; the session.create.before hook covers them.
if (isEmailBlockedByAccessControl(requestEmail, accessControl)) {
throw new APIError('FORBIDDEN', {
message: isSignUp
? 'Sign-ups from this email are not allowed.'
: 'Access restricted. Please contact your administrator.',
})
}
if (
isSignupMxValidationEnabled &&
ctx.path.startsWith('/sign-up/email') &&
ctx.body?.email
) {
const mxCheck = await validateSignupEmailMx(
ctx.body.email,
accessControl.blockedEmailMxHosts
)
if (!mxCheck.allowed) {
throw new APIError('FORBIDDEN', {
message: 'Sign-ups from this email domain are not allowed.',
})
}
}
}
return
}),
},
plugins: [
...(env.TURNSTILE_SECRET_KEY
? [
captcha({
provider: 'cloudflare-turnstile',
secretKey: env.TURNSTILE_SECRET_KEY,
endpoints: ['/sign-up/email'],
}),
]
: []),
admin(),
oneTimeToken({
expiresIn: 24 * 60, // 24 hours in minutes (better-auth's expiresIn unit)
}),
customSession(async ({ user, session }) => ({
user,
session,
})),
emailOTP({
sendVerificationOTP: async (data) => {
if (!isEmailVerificationEnabled) {
logger.info('Skipping email verification')
return
}
try {
if (!data.email) {
throw new Error('Email is required')
}
const validation = quickValidateEmail(data.email)
if (!validation.isValid) {
logger.warn('Email validation failed', {
email: data.email,
reason: validation.reason,
checks: validation.checks,
})
throw new Error(
validation.reason ||
"We are unable to deliver the verification email to that address. Please make sure it's valid and able to receive emails."
)
}
const html = await renderOTPEmail(data.otp, data.email, data.type)
const result = await sendEmail({
to: data.email,
subject: getEmailSubject(data.type),
html,
from: getFromEmailAddress(),
emailType: 'transactional',
})
if (!result.success && result.message.includes('no email service configured')) {
logger.info('🔑 VERIFICATION CODE FOR LOGIN/SIGNUP', {
email: data.email,