-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathsession.ts
456 lines (378 loc) · 13.1 KB
/
session.ts
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
'use server';
import { redirect } from 'next/navigation';
import { cookies, headers } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { jwtVerify, createRemoteJWKSet, decodeJwt } from 'jose';
import { sealData, unsealData } from 'iron-session';
import { getCookieOptions } from './cookie.js';
import { workos } from './workos.js';
import { WORKOS_CLIENT_ID, WORKOS_COOKIE_PASSWORD, WORKOS_COOKIE_NAME, WORKOS_REDIRECT_URI } from './env-variables.js';
import { getAuthorizationUrl } from './get-authorization-url.js';
import {
AccessToken,
AuthkitMiddlewareAuth,
AuthkitOptions,
AuthkitResponse,
CookieOptions,
NoUserInfo,
Session,
UserInfo,
} from './interfaces.js';
import { parse, tokensToRegexp } from 'path-to-regexp';
import { redirectWithFallback } from './utils.js';
const sessionHeaderName = 'x-workos-session';
const middlewareHeaderName = 'x-workos-middleware';
const signUpPathsHeaderName = 'x-sign-up-paths';
const JWKS = createRemoteJWKSet(new URL(workos.userManagement.getJwksUrl(WORKOS_CLIENT_ID)));
async function encryptSession(session: Session) {
return sealData(session, {
password: WORKOS_COOKIE_PASSWORD,
ttl: 0,
});
}
async function updateSessionMiddleware(
request: NextRequest,
debug: boolean,
middlewareAuth: AuthkitMiddlewareAuth,
redirectUri: string,
signUpPaths: string[],
) {
if (!redirectUri && !WORKOS_REDIRECT_URI) {
throw new Error('You must provide a redirect URI in the AuthKit middleware or in the environment variables.');
}
if (!WORKOS_COOKIE_PASSWORD || WORKOS_COOKIE_PASSWORD.length < 32) {
throw new Error(
'You must provide a valid cookie password that is at least 32 characters in the environment variables.',
);
}
let url;
if (redirectUri) {
url = new URL(redirectUri);
} else {
url = new URL(WORKOS_REDIRECT_URI);
}
if (
middlewareAuth.enabled &&
url.pathname === request.nextUrl.pathname &&
!middlewareAuth.unauthenticatedPaths.includes(url.pathname)
) {
// In the case where:
// - We're using middleware auth mode
// - The redirect URI is in the middleware matcher
// - The redirect URI isn't in the unauthenticatedPaths array
//
// then we would get stuck in a login loop due to the redirect happening before the session is set.
// It's likely that the user accidentally forgot to add the path to unauthenticatedPaths, so we add it here.
middlewareAuth.unauthenticatedPaths.push(url.pathname);
}
const matchedPaths: string[] = middlewareAuth.unauthenticatedPaths.filter((pathGlob) => {
const pathRegex = getMiddlewareAuthPathRegex(pathGlob);
return pathRegex.exec(request.nextUrl.pathname);
});
const { session, headers, authorizationUrl } = await updateSession(request, {
debug,
redirectUri,
screenHint: getScreenHint(signUpPaths, request.nextUrl.pathname),
});
// If the user is logged out and this path isn't on the allowlist for logged out paths, redirect to AuthKit.
if (middlewareAuth.enabled && matchedPaths.length === 0 && !session.user) {
if (debug) {
console.log(`Unauthenticated user on protected route ${request.url}, redirecting to AuthKit`);
}
return redirectWithFallback(authorizationUrl as string, headers);
}
// Record the sign up paths so we can use them later
if (signUpPaths.length > 0) {
headers.set(signUpPathsHeaderName, signUpPaths.join(','));
}
return NextResponse.next({
headers,
});
}
async function updateSession(
request: NextRequest,
options: AuthkitOptions = { debug: false },
): Promise<AuthkitResponse> {
const session = await getSessionFromCookie(request);
// Since we're setting the headers in the response, we need to create a new Headers object without copying
// the request headers.
// See https://github.com/vercel/next.js/issues/50659#issuecomment-2333990159
const newRequestHeaders = new Headers();
// Record that the request was routed through the middleware so we can check later for DX purposes
newRequestHeaders.set(middlewareHeaderName, 'true');
// We store the current request url in a custom header, so we can always have access to it
// This is because on hard navigations we don't have access to `next-url` but need to get the current
// `pathname` to be able to return the users where they came from before sign-in
newRequestHeaders.set('x-url', request.url);
newRequestHeaders.delete(sessionHeaderName);
if (!session) {
if (options.debug) {
console.log('No session found from cookie');
}
return {
session: { user: null },
headers: newRequestHeaders,
authorizationUrl: await getAuthorizationUrl({
returnPathname: getReturnPathname(request.url),
redirectUri: options.redirectUri || WORKOS_REDIRECT_URI,
screenHint: options.screenHint,
}),
};
}
const hasValidSession = await verifyAccessToken(session.accessToken);
const cookieName = WORKOS_COOKIE_NAME || 'wos-session';
if (hasValidSession) {
newRequestHeaders.set(sessionHeaderName, request.cookies.get(cookieName)!.value);
const {
sid: sessionId,
org_id: organizationId,
role,
permissions,
entitlements,
} = decodeJwt<AccessToken>(session.accessToken);
return {
session: {
sessionId,
user: session.user,
organizationId,
role,
permissions,
entitlements,
impersonator: session.impersonator,
accessToken: session.accessToken,
},
headers: newRequestHeaders,
};
}
if (options.debug) {
console.log(`Session invalid. Refreshing access token that ends in ${session.accessToken.slice(-10)}`);
}
try {
const { org_id: organizationIdFromAccessToken } = decodeJwt<AccessToken>(session.accessToken);
const { accessToken, refreshToken, user, impersonator } = await workos.userManagement.authenticateWithRefreshToken({
clientId: WORKOS_CLIENT_ID,
refreshToken: session.refreshToken,
organizationId: organizationIdFromAccessToken,
});
if (options.debug) {
console.log('Session successfully refreshed');
}
// Encrypt session with new access and refresh tokens
const encryptedSession = await encryptSession({
accessToken,
refreshToken,
user,
impersonator,
});
newRequestHeaders.append('Set-Cookie', `${cookieName}=${encryptedSession}; ${getCookieOptions(request.url, true)}`);
newRequestHeaders.set(sessionHeaderName, encryptedSession);
const {
sid: sessionId,
org_id: organizationId,
role,
permissions,
entitlements,
} = decodeJwt<AccessToken>(accessToken);
return {
session: {
sessionId,
user,
organizationId,
role,
permissions,
entitlements,
impersonator,
accessToken,
},
headers: newRequestHeaders,
};
} catch (e) {
if (options.debug) {
console.log('Failed to refresh. Deleting cookie.', e);
}
// When we need to delete a cookie, return it as a header as you can't delete cookies from edge middleware
const deleteCookie = `${cookieName}=; Expires=${new Date(0).toUTCString()}; ${getCookieOptions(request.url, true, true)}`;
newRequestHeaders.append('Set-Cookie', deleteCookie);
return {
session: { user: null },
headers: newRequestHeaders,
authorizationUrl: await getAuthorizationUrl({
returnPathname: getReturnPathname(request.url),
}),
};
}
}
async function refreshSession(options: {
organizationId?: string;
ensureSignedIn?: boolean;
}): Promise<UserInfo | NoUserInfo>;
/* istanbul ignore next */
async function refreshSession({
organizationId: nextOrganizationId,
ensureSignedIn = false,
}: {
organizationId?: string;
ensureSignedIn?: boolean;
} = {}) {
const session = await getSessionFromCookie();
if (!session) {
if (ensureSignedIn) {
await redirectToSignIn();
}
return { user: null };
}
const { org_id: organizationIdFromAccessToken } = decodeJwt<AccessToken>(session.accessToken);
let refreshResult;
try {
refreshResult = await workos.userManagement.authenticateWithRefreshToken({
clientId: WORKOS_CLIENT_ID,
refreshToken: session.refreshToken,
organizationId: nextOrganizationId ?? organizationIdFromAccessToken,
});
} catch (error) {
throw new Error(`Failed to refresh session: ${error instanceof Error ? error.message : String(error)}`, {
cause: error,
});
}
const { accessToken, refreshToken, user, impersonator } = refreshResult;
// Encrypt session with new access and refresh tokens
const encryptedSession = await encryptSession({
accessToken,
refreshToken,
user,
impersonator,
});
const cookieName = WORKOS_COOKIE_NAME || 'wos-session';
const headersList = await headers();
const url = headersList.get('x-url');
const nextCookies = await cookies();
nextCookies.set(cookieName, encryptedSession, getCookieOptions(url) as CookieOptions);
const {
sid: sessionId,
org_id: organizationId,
role,
permissions,
entitlements,
} = decodeJwt<AccessToken>(accessToken);
return {
sessionId,
user,
organizationId,
role,
permissions,
entitlements,
impersonator,
accessToken,
};
}
function getMiddlewareAuthPathRegex(pathGlob: string) {
try {
const url = new URL(pathGlob, 'https://example.com');
const path = `${url.pathname!}${url.hash || ''}`;
const tokens = parse(path);
const regex = tokensToRegexp(tokens).source;
return new RegExp(regex);
} catch (err) {
console.log('err', err);
const message = err instanceof Error ? err.message : String(err);
throw new Error(`Error parsing routes for middleware auth. Reason: ${message}`);
}
}
async function redirectToSignIn() {
const headersList = await headers();
const url = headersList.get('x-url');
if (!url) {
throw new Error('No URL found in the headers');
}
// Determine if the current route is in the sign up paths
const signUpPaths = headersList.get(signUpPathsHeaderName)?.split(',');
const pathname = new URL(url).pathname;
const screenHint = getScreenHint(signUpPaths, pathname);
const returnPathname = getReturnPathname(url);
redirect(await getAuthorizationUrl({ returnPathname, screenHint }));
}
async function withAuth(options: { ensureSignedIn: true }): Promise<UserInfo>;
async function withAuth(options?: { ensureSignedIn?: true | false }): Promise<UserInfo | NoUserInfo>;
async function withAuth(options?: { ensureSignedIn?: boolean }): Promise<UserInfo | NoUserInfo> {
const session = await getSessionFromHeader();
if (!session) {
if (options?.ensureSignedIn) {
await redirectToSignIn();
}
return { user: null };
}
const {
sid: sessionId,
org_id: organizationId,
role,
permissions,
entitlements,
} = decodeJwt<AccessToken>(session.accessToken);
return {
sessionId,
user: session.user,
organizationId,
role,
permissions,
entitlements,
impersonator: session.impersonator,
accessToken: session.accessToken,
};
}
async function terminateSession({ returnTo }: { returnTo?: string } = {}) {
const { sessionId } = await withAuth();
if (sessionId) {
redirect(workos.userManagement.getLogoutUrl({ sessionId, returnTo }));
} else {
redirect(returnTo ?? '/');
}
}
async function verifyAccessToken(accessToken: string) {
try {
await jwtVerify(accessToken, JWKS);
return true;
} catch {
return false;
}
}
async function getSessionFromCookie(request?: NextRequest) {
const cookieName = WORKOS_COOKIE_NAME || 'wos-session';
let cookie;
if (request) {
cookie = request.cookies.get(cookieName);
} else {
const nextCookies = await cookies();
cookie = nextCookies.get(cookieName);
}
if (cookie) {
return unsealData<Session>(cookie.value, {
password: WORKOS_COOKIE_PASSWORD,
});
}
}
async function getSessionFromHeader(): Promise<Session | undefined> {
const headersList = await headers();
const hasMiddleware = Boolean(headersList.get(middlewareHeaderName));
if (!hasMiddleware) {
const url = headersList.get('x-url');
throw new Error(
`You are calling 'withAuth' on ${url ?? 'a route'} that isn’t covered by the AuthKit middleware. Make sure it is running on all paths you are calling 'withAuth' from by updating your middleware config in 'middleware.(js|ts)'.`,
);
}
const authHeader = headersList.get(sessionHeaderName);
if (!authHeader) return;
return unsealData<Session>(authHeader, { password: WORKOS_COOKIE_PASSWORD });
}
function getReturnPathname(url: string): string {
const newUrl = new URL(url);
return `${newUrl.pathname}${newUrl.searchParams.size > 0 ? '?' + newUrl.searchParams.toString() : ''}`;
}
function getScreenHint(signUpPaths: string[] | undefined, pathname: string) {
if (!signUpPaths) return 'sign-in';
const screenHintPaths: string[] = signUpPaths.filter((pathGlob) => {
const pathRegex = getMiddlewareAuthPathRegex(pathGlob);
return pathRegex.exec(pathname);
});
return screenHintPaths.length > 0 ? 'sign-up' : 'sign-in';
}
export { encryptSession, withAuth, refreshSession, terminateSession, updateSessionMiddleware, updateSession };