-
Notifications
You must be signed in to change notification settings - Fork 307
Expand file tree
/
Copy pathauth.ts
More file actions
361 lines (327 loc) · 12.8 KB
/
Copy pathauth.ts
File metadata and controls
361 lines (327 loc) · 12.8 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
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 '@sourcebot/shared';
import { onCreateUser } from '@/lib/authUtils';
import { getAuditService } from '@/ee/features/audit/factory';
import { SINGLE_TENANT_ORG_ID } from './lib/constants';
import { EncryptedPrismaAdapter, encryptAccountData } from '@/lib/encryptedPrismaAdapter';
const auditService = getAuditService();
const eeIdentityProviders = hasEntitlement("sso") ? await getEEIdentityProviders() : [];
export const runtime = 'nodejs';
export type IdentityProvider = {
provider: Provider;
purpose: "sso" | "account_linking";
issuerUrl?: string;
required?: boolean;
}
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 = () => {
const providers: IdentityProvider[] = [...eeIdentityProviders];
const smtpConnectionUrl = getSMTPConnectionURL();
if (smtpConnectionUrl && env.EMAIL_FROM_ADDRESS && env.AUTH_EMAIL_CODE_LOGIN_ENABLED === 'true') {
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`);
}
}
}), purpose: "sso"
});
}
if (env.AUTH_CREDENTIALS_LOGIN_ENABLED === 'true') {
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,
};
}
}
}), purpose: "sso"
});
}
return providers;
}
const nextAuthResult = NextAuth({
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.provider &&
account.provider !== 'credentials' &&
account.providerAccountId
) {
const issuerUrl = await getIssuerUrlForAccount(account);
await __unsafePrisma.account.update({
where: {
provider_providerAccountId: {
provider: 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) {
await auditService.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) {
await auditService.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: {
// 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;
}
// @note The following performs a lazy migration of the issuerUrl
// in the user's accounts. The issuerUrl was introduced in v4.15.4
// and will not be present for accounts created prior to this version.
//
// @see https://github.com/sourcebot-dev/sourcebot/pull/993
if (token.userId) {
const accountsWithoutIssuerUrl = await __unsafePrisma.account.findMany({
where: {
userId: token.userId,
issuerUrl: null,
},
});
for (const account of accountsWithoutIssuerUrl) {
const issuerUrl = await getIssuerUrlForAccount(account);
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: getProviders().map((provider) => provider.provider),
pages: {
signIn: "/login",
// We set redirect to false in signInOptions so we can pass the email is as a param
// verifyRequest: "/login/verify",
}
});
export const { handlers, signIn, signOut } = nextAuthResult;
/**
* Wrapped session resolver that enforces JWT versioning at the auth layer.
*
* Every JWT cookie carries the `sessionVersion` it was minted with. This
* wrapper compares it against the user's current `sessionVersion` in the
* database; if the user's version has been bumped (e.g., they were removed
* from the org), we return null so every caller of `auth()` sees the
* session as logged out.
*/
export const auth = cache(async (): Promise<Session | null> => {
const session = await nextAuthResult.auth();
if (!session) {
return null;
}
const dbUser = await __unsafePrisma.user.findUnique({
where: { id: session.user.id },
select: { sessionVersion: true },
});
if (!dbUser) {
return null;
}
const tokenVersion = session.sessionVersion ?? 0;
if (tokenVersion !== dbUser.sessionVersion) {
return null;
}
return session;
});
/**
* Returns the issuer URL for a given auth.js account
*/
const getIssuerUrlForAccount = async (account: { provider: string; }) => {
const providers = getProviders();
const matchingProvider = providers.find((provider) => {
if (typeof provider.provider === "function") {
const providerInfo = provider.provider();
return providerInfo.id === account.provider;
} else {
return provider.provider.id === account.provider;
}
});
return matchingProvider?.issuerUrl;
}