-
Notifications
You must be signed in to change notification settings - Fork 307
Expand file tree
/
Copy pathauth.ts
More file actions
473 lines (436 loc) · 19.2 KB
/
Copy pathauth.ts
File metadata and controls
473 lines (436 loc) · 19.2 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
import 'next-auth/jwt';
import { cache } from "react";
import NextAuth, { DefaultSession, Session, User as AuthJsUser } from "next-auth"
import Credentials from "next-auth/providers/credentials"
import EmailProvider from "next-auth/providers/nodemailer";
import { __unsafePrisma } from "@/prisma";
import { env, getSMTPConnectionURL } from "@sourcebot/shared";
import { User } from '@sourcebot/db';
import 'next-auth/jwt';
import type { Provider } from "next-auth/providers";
import { verifyCredentialsRequestSchema } from './lib/schemas';
import { createTransport } from 'nodemailer';
import { render } from '@react-email/render';
import MagicLinkEmail from './emails/magicLinkEmail';
import bcrypt from 'bcryptjs';
import { getEEIdentityProviders } from '@/ee/features/sso/sso';
import { hasEntitlement } from '@/lib/entitlements';
import { onCreateUser } from '@/lib/authUtils';
import { createAudit } from '@/ee/features/audit/audit';
import { SINGLE_TENANT_ORG_ID } from './lib/constants';
import { EncryptedPrismaAdapter, encryptAccountData } from '@/lib/encryptedPrismaAdapter';
import { getAnonymousId } from '@/lib/anonymousId';
import { captureEvent } from '@/lib/posthog';
import { isEmailCodeLoginEnabled, isCredentialsLoginEnabled } from '@sourcebot/shared'
export const runtime = 'nodejs';
export type IdentityProvider = {
/** Provider type (e.g., 'github', 'gitlab') — used to pick icon / display defaults. */
type: string;
/** Provider instance id (e.g., 'github', 'gitlab-corp') — used for `signIn(provider)`. */
id: string;
/** Optional admin-supplied display name from config; overrides type-derived defaults in the UI. */
displayName?: string;
purpose: "sso" | "account_linking";
issuerUrl?: string;
required?: boolean;
/**
* @warning don't use this field directly - this is meant to be
* passed directly to auth.js. Use the fields directly on the
* IdentityProvider type (i.e., `type`, `id`, etc.)
*
* @deprecated this field isn't actually deprected, but adding
* this tag to dissuade usage.
*/
__provider: Provider;
}
export type SessionUser = {
id: string;
} & DefaultSession['user'];
declare module 'next-auth' {
interface Session {
user: SessionUser;
sessionVersion?: number;
}
interface User {
sessionVersion?: number;
}
}
declare module 'next-auth/jwt' {
interface JWT {
userId: string;
sessionVersion?: number;
}
}
export const getProviders = async () => {
const hasSSOEntitlement = await hasEntitlement("sso");
const providers: IdentityProvider[] = [
...(hasSSOEntitlement ? await getEEIdentityProviders() : []),
];
const org = await __unsafePrisma.org.findUnique({ where: { id: SINGLE_TENANT_ORG_ID } });
const smtpConnectionUrl = getSMTPConnectionURL();
if (smtpConnectionUrl && env.EMAIL_FROM_ADDRESS && isEmailCodeLoginEnabled(org!)) {
providers.push({
__provider: EmailProvider({
server: smtpConnectionUrl,
from: env.EMAIL_FROM_ADDRESS,
maxAge: 60 * 10,
generateVerificationToken: async () => {
const token = String(Math.floor(100000 + Math.random() * 900000));
return token;
},
sendVerificationRequest: async ({ identifier, provider, token }) => {
const transport = createTransport(provider.server);
const html = await render(MagicLinkEmail({ token: token }));
const result = await transport.sendMail({
to: identifier,
from: provider.from,
subject: 'Log in to Sourcebot',
html,
text: `Log in to Sourcebot using this code: ${token}`
});
const failed = result.rejected.concat(result.pending).filter(Boolean);
if (failed.length) {
throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`);
}
},
}),
type: "nodemailer",
id: "nodemailer",
purpose: "sso",
});
}
if (isCredentialsLoginEnabled(org!)) {
providers.push({
__provider: Credentials({
credentials: {
email: {},
password: {}
},
type: "credentials",
authorize: async (credentials) => {
const body = verifyCredentialsRequestSchema.safeParse(credentials);
if (!body.success) {
return null;
}
const { email, password } = body.data;
const user = await __unsafePrisma.user.findUnique({
where: { email }
});
// The user doesn't exist, so create a new one.
if (!user) {
const hashedPassword = bcrypt.hashSync(password, 10);
const newUser = await __unsafePrisma.user.create({
data: {
email,
hashedPassword,
}
});
const authJsUser: AuthJsUser = {
id: newUser.id,
email: newUser.email,
sessionVersion: newUser.sessionVersion,
}
onCreateUser({ user: authJsUser });
return authJsUser;
// Otherwise, the user exists, so verify the password.
} else {
if (!user.hashedPassword) {
return null;
}
if (!bcrypt.compareSync(password, user.hashedPassword)) {
return null;
}
return {
id: user.id,
email: user.email,
name: user.name ?? undefined,
image: user.image ?? undefined,
sessionVersion: user.sessionVersion,
};
}
}
}),
type: "credentials",
id: "credentials",
purpose: "sso"
});
}
return providers;
}
// @note we use lazy initialization here to ensure that the
// `providers` property is upto date with any config changes.
// @see https://authjs.dev/reference/nextjs#lazy-initialization
const nextAuthResult = NextAuth(async () => ({
secret: env.AUTH_SECRET,
adapter: EncryptedPrismaAdapter(__unsafePrisma),
session: {
strategy: "jwt",
maxAge: env.AUTH_SESSION_MAX_AGE_SECONDS,
updateAge: env.AUTH_SESSION_UPDATE_AGE_SECONDS,
},
trustHost: true,
events: {
createUser: onCreateUser,
signIn: async ({ user, account }) => {
// Explicitly update the Account record with the OAuth token details.
// This is necessary to update the access token when the user
// re-authenticates.
// NOTE: Tokens are encrypted before storage for security
if (
account &&
(account.type === 'oauth' || account.type === 'oidc') &&
account.provider &&
account.providerAccountId
) {
const issuerUrl = await getIssuerUrlForProviderId(account.provider);
await __unsafePrisma.account.update({
where: {
providerId_providerAccountId: {
providerId: account.provider,
providerAccountId: account.providerAccountId,
},
},
data: encryptAccountData({
refresh_token: account.refresh_token,
access_token: account.access_token,
expires_at: account.expires_at,
token_type: account.token_type,
scope: account.scope,
id_token: account.id_token,
issuerUrl,
// Clear any token refresh error since the user has successfully re-authenticated.
tokenRefreshErrorMessage: null,
})
})
}
if (user.id) {
// Claim any anonymous chats created before sign-in.
const anonymousId = await getAnonymousId();
if (anonymousId) {
const result = await __unsafePrisma.chat.updateMany({
where: {
orgId: SINGLE_TENANT_ORG_ID,
anonymousCreatorId: anonymousId,
createdById: null,
},
data: {
createdById: user.id,
anonymousCreatorId: null,
},
});
if (result.count > 0) {
await captureEvent('wa_anonymous_chats_claimed', {
claimedCount: result.count,
});
}
}
await createAudit({
action: "user.signed_in",
actor: {
id: user.id,
type: "user"
},
orgId: SINGLE_TENANT_ORG_ID, // TODO(mt)
target: {
id: user.id,
type: "user"
}
});
}
},
signOut: async (message) => {
const token = message as { token: { userId: string } | null };
if (token?.token?.userId) {
// Bump sessionVersion so any JWT minted before this signout
// is treated as invalid by the jwt callback's DB cross-check
// on its next request, even if the cookie value was captured
// and is being replayed.
await __unsafePrisma.user.update({
where: { id: token.token.userId },
data: { sessionVersion: { increment: 1 } },
});
await createAudit({
action: "user.signed_out",
actor: {
id: token.token.userId,
type: "user"
},
orgId: SINGLE_TENANT_ORG_ID, // TODO(mt)
target: {
id: token.token.userId,
type: "user"
}
});
}
}
},
callbacks: {
async signIn({ account, user }) {
const matchingProvider = account
? (await getProviders()).find((p) => p.id === account.provider)
: undefined;
// Refuse OAuth signin for providers configured purely for account
// linking when no authenticated user is present on the request.
//
// Background: @auth/core's handleLoginOrRegister (callback/handle-login.js)
// reads the session token from the request and, if it can't decode it
// (e.g., the session cookie expired browser-side mid auth flow, or it
// never made it across the cross-site redirect),
// falls through to `createUser({ ...profile })`, silently spawning a
// new orphan User row from the OAuth profile. That's correct behavior
// for `purpose: "sso"` providers (an unauthenticated user logging in
// via SSO should become a new Sourcebot user). It's wrong for
// `purpose: "account_linking"` providers: by definition, those should
// only ever attach an upstream identity to an *existing* signed-in
// user, never mint a new Sourcebot user.
//
// Returning `false` here short-circuits the callback action with an
// `AccessDenied` before handleLoginOrRegister can run, redirecting
// the user to the error page instead of leaving them stranded as a
// new orphan identity with no UserToOrg row.
const isAccountLinkingAttempt = matchingProvider?.purpose === 'account_linking';
const session = await auth();
if (isAccountLinkingAttempt && session === null) {
return false;
}
// Reject any sign-in that arrives without an email. `email` is a required
// column, so a null would otherwise fail the `createUser` insert at the
// database; historically these rows also crashed the members list and other
// surfaces that assume an email is present. Returning false surfaces the auth
// error page instead. In practice only OAuth/OIDC profiles can lack an email
// (credentials and email providers always carry one), but the check is left
// unconditional so any future provider or edge case is covered too. `user` is
// always defined in the signIn callback, so it needs no guard.
// @see 20260616000000_make_user_email_required/migration.sql
if (!user.email) {
return false;
}
return true;
},
// Restrict post-auth redirects (sign-in / sign-out, `callbackUrl`,
// `redirectTo`) to the same origin as the application. This mirrors
// Auth.js's documented default; we set it explicitly so the protection
// is visible in code and not dependent on upstream defaults.
// @see https://authjs.dev/reference/core#redirect
async redirect({ url, baseUrl }) {
if (url.startsWith("/")) {
return `${baseUrl}${url}`;
}
try {
if (new URL(url).origin === baseUrl) {
return url;
}
} catch {
// Malformed URL — fall through to baseUrl.
}
return baseUrl;
},
async jwt({ token, user: _user }) {
const user = _user as User | undefined;
// @note: `user` will be available on signUp or signIn triggers.
// Cache the userId in the JWT for later use.
if (user) {
token.userId = user.id;
token.sessionVersion = user.sessionVersion ?? 0;
}
if (token.userId) {
// Single query: fetch the user's current sessionVersion for
// the cross-check below, plus any accounts that still need
// the issuerUrl lazy migration.
//
// @see https://github.com/sourcebot-dev/sourcebot/pull/993
const dbUser = await __unsafePrisma.user.findUnique({
where: {
id: token.userId as string,
},
select: {
sessionVersion: true,
accounts: {
where: {
issuerUrl: null,
},
},
},
});
// The user row was removed (e.g., deleted via /api/ee/user
// or org-removal cascade). Treat the JWT as invalid so
// /api/auth/session reports logged-out and @auth/core clears
// the cookie from the browser.
if (!dbUser) {
return null;
}
// On every non-login request, cross-check the JWT's
// sessionVersion against the user's current sessionVersion in
// the database. A mismatch means the user signed out, was
// removed from the org, or their sessions were otherwise
// invalidated since the JWT was minted. Returning null here
// is what makes invalidation visible at /api/auth/session,
// not just at withAuth-gated endpoints.
const tokenSessionVersion = token.sessionVersion ?? 0;
if (!user && tokenSessionVersion !== dbUser.sessionVersion) {
return null;
}
// Lazy migration of issuerUrl on accounts created before
// the column was introduced in v4.15.4. The where clause
// above scopes this to only accounts that still need it,
// so the loop is a no-op once everyone is backfilled.
for (const account of dbUser.accounts) {
const issuerUrl = await getIssuerUrlForProviderId(account.providerId);
if (issuerUrl) {
await __unsafePrisma.account.update({
where: {
id: account.id,
},
data: {
issuerUrl,
},
});
}
}
}
return token;
},
async session({ session, token }) {
// @WARNING: Anything stored in the session will be sent over
// to the client.
session.user = {
...session.user,
// Propagate the userId to the session.
id: token.userId,
}
session.sessionVersion = token.sessionVersion;
return session;
},
},
providers: (await getProviders()).map((provider) => provider.__provider),
pages: {
signIn: "/login",
error: "/login/error",
// We set redirect to false in signInOptions so we can pass the email in as a param
// verifyRequest: "/login/verify",
}
}));
export const { handlers, signIn, signOut } = nextAuthResult;
/**
* Per-request memoized session resolver.
*
* JWT validity (including the `sessionVersion` cross-check against the
* database and the existence of the underlying `User` row) is enforced in
* the `jwt` callback above. If that callback returns `null`, NextAuth's
* core resolves the session to `null` here and also clears the cookie on
* the response. We therefore only need to memoize the result within a
* single request so that multiple `auth()` callers share the same answer
* without re-running the upstream resolver.
*/
export const auth = cache(async (): Promise<Session | null> => {
return nextAuthResult.auth();
});
/**
* Returns the issuer URL for a given identity provider id (i.e., the auth.js
* provider id, which is also what we store in `Account.providerId`).
*/
const getIssuerUrlForProviderId = async (providerId: string) => {
const providers = await getProviders();
const matchingProvider = providers.find((provider) => provider.id === providerId);
return matchingProvider?.issuerUrl;
}