Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add composable middleware #164

Merged
merged 28 commits into from
Jan 13, 2025
Merged
Changes from 1 commit
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
a8503dc
Added tests and made a start to auth.ts
PaulAsjes Nov 26, 2024
ecd3173
Add tests for cookie and callback route
PaulAsjes Nov 26, 2024
60f70f8
Tests for session and actions
PaulAsjes Dec 2, 2024
0c55d70
Add jsdom tests for tsx files
PaulAsjes Dec 3, 2024
47aee50
Add new workflow
PaulAsjes Dec 3, 2024
10d2004
Clean up jest config file
PaulAsjes Dec 3, 2024
ff50e18
Didn't mean to add this
PaulAsjes Dec 3, 2024
77393b9
Add jest config and setup scripts to ts exclude
PaulAsjes Dec 3, 2024
33559b0
Impersonation shouldn't be a client component for now
PaulAsjes Dec 3, 2024
72f1c2e
100% test coverage
PaulAsjes Dec 4, 2024
27a5a1e
Add debug flag
PaulAsjes Dec 4, 2024
3b568af
Add another test and change coverage engine to have local and github …
PaulAsjes Dec 4, 2024
05abae4
Should actually add the test
PaulAsjes Dec 4, 2024
df7ced3
Address feedback
PaulAsjes Dec 13, 2024
2656a76
Also run prettier on test files
PaulAsjes Dec 13, 2024
3e6968f
Merge remote-tracking branch 'origin/main' into pma/composable-middle…
PaulAsjes Jan 2, 2025
0399fcc
wip
PaulAsjes Jan 3, 2025
851ac7a
wip
PaulAsjes Jan 7, 2025
142ecca
Merge remote-tracking branch 'origin/main' into pma/composable-middle…
PaulAsjes Jan 7, 2025
f05af89
Add tests
PaulAsjes Jan 8, 2025
a42594c
Delete getSession in favor of authkit method
PaulAsjes Jan 8, 2025
bae11b8
Restore package-lock.json
PaulAsjes Jan 8, 2025
61f9127
Flip debug back to false
PaulAsjes Jan 8, 2025
cfacbcc
Remove deprecated tests and update readme
PaulAsjes Jan 8, 2025
7b27eb5
Make options object optional and fix tests
PaulAsjes Jan 8, 2025
46a857d
Merge remote-tracking branch 'origin/main' into pma/composable-middle…
PaulAsjes Jan 10, 2025
159f118
Update tests
PaulAsjes Jan 10, 2025
dd9143e
Merge remote-tracking branch 'origin/main' into pma/composable-middle…
PaulAsjes Jan 13, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add tests
PaulAsjes committed Jan 8, 2025
commit f05af89e44ddc203675a73072622151d523504d3
133 changes: 113 additions & 20 deletions __tests__/session.spec.ts
Original file line number Diff line number Diff line change
@@ -2,7 +2,14 @@ import { NextRequest, NextResponse } from 'next/server';
import { cookies, headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { generateTestToken } from './test-helpers.js';
import { withAuth, updateSession, refreshSession, getSession, terminateSession } from '../src/session.js';
import {
withAuth,
updateSession,
refreshSession,
getSession,
terminateSession,
updateSessionMiddleware,
} from '../src/session.js';
import { workos } from '../src/workos.js';
import * as envVariables from '../src/env-variables.js';

@@ -18,7 +25,7 @@ jest.mock('jose', () => ({
}));

// logging is disabled by default, flip this to true to still have logs in the console
const DEBUG = false;
const DEBUG = true;

describe('session.ts', () => {
const mockSession = {
@@ -137,14 +144,14 @@ describe('session.ts', () => {
});
});

describe('updateSession', () => {
describe('updateSessionMiddleware', () => {
it('should throw an error if the redirect URI is not set', async () => {
const originalWorkosRedirectUri = envVariables.WORKOS_REDIRECT_URI;

jest.replaceProperty(envVariables, 'WORKOS_REDIRECT_URI', '');

await expect(async () => {
await updateSession(
await updateSessionMiddleware(
new NextRequest(new URL('http://example.com')),
false,
{
@@ -165,7 +172,7 @@ describe('session.ts', () => {
jest.replaceProperty(envVariables, 'WORKOS_COOKIE_PASSWORD', '');

await expect(async () => {
await updateSession(
await updateSessionMiddleware(
new NextRequest(new URL('http://example.com')),
false,
{
@@ -188,7 +195,7 @@ describe('session.ts', () => {
jest.replaceProperty(envVariables, 'WORKOS_COOKIE_PASSWORD', 'short');

await expect(async () => {
await updateSession(
await updateSessionMiddleware(
new NextRequest(new URL('http://example.com')),
false,
{
@@ -207,7 +214,7 @@ describe('session.ts', () => {

it('should return early if there is no session', async () => {
const request = new NextRequest(new URL('http://example.com'));
const result = await updateSession(
const result = await updateSessionMiddleware(
request,
false,
{
@@ -236,7 +243,7 @@ describe('session.ts', () => {
});

const request = new NextRequest(new URL('http://example.com'));
const result = await updateSession(
const result = await updateSessionMiddleware(
request,
true,
{
@@ -273,7 +280,7 @@ describe('session.ts', () => {

const request = new NextRequest(new URL('http://example.com'));

const result = await updateSession(
const result = await updateSessionMiddleware(
request,
true,
{
@@ -312,7 +319,7 @@ describe('session.ts', () => {

const request = new NextRequest(new URL('http://example.com'));

const result = await updateSession(
const result = await updateSessionMiddleware(
request,
true,
{
@@ -342,7 +349,7 @@ describe('session.ts', () => {
jest.spyOn(console, 'log').mockImplementation(() => {});

const request = new NextRequest(new URL('http://example.com/protected'));
const result = await updateSession(
const result = await updateSessionMiddleware(
request,
true,
{
@@ -364,7 +371,7 @@ describe('session.ts', () => {
(NextResponse as Partial<typeof NextResponse>).redirect = undefined;

const request = new NextRequest(new URL('http://example.com/protected'));
const result = await updateSession(
const result = await updateSessionMiddleware(
request,
false,
{
@@ -383,7 +390,7 @@ describe('session.ts', () => {

it('should automatically add the redirect URI to unauthenticatedPaths when middleware is enabled', async () => {
const request = new NextRequest(new URL('http://example.com/protected'));
const result = await updateSession(
const result = await updateSessionMiddleware(
request,
false,
{
@@ -399,7 +406,7 @@ describe('session.ts', () => {

it('should redirect unauthenticated users to sign up page on protected routes included in signUpPaths', async () => {
const request = new NextRequest(new URL('http://example.com/protected-signup'));
const result = await updateSession(
const result = await updateSessionMiddleware(
request,
false,
{
@@ -416,7 +423,7 @@ describe('session.ts', () => {

it('should allow logged out users on unauthenticated paths', async () => {
const request = new NextRequest(new URL('http://example.com/unauthenticated'));
const result = await updateSession(
const result = await updateSessionMiddleware(
request,
false,
{
@@ -433,7 +440,7 @@ describe('session.ts', () => {
it('should throw an error if the provided regex is invalid', async () => {
const request = new NextRequest(new URL('http://example.com/invalid-regex'));
await expect(async () => {
await updateSession(
await updateSessionMiddleware(
request,
false,
{
@@ -457,12 +464,12 @@ describe('session.ts', () => {
});

// Import session after setting up the spy
const { updateSession } = await import('../src/session.js');
const { updateSessionMiddleware } = await import('../src/session.js');

const request = new NextRequest(new URL('http://example.com/invalid-regex'));

await expect(async () => {
await updateSession(
await updateSessionMiddleware(
request,
false,
{
@@ -480,7 +487,7 @@ describe('session.ts', () => {

it('should default to the WORKOS_REDIRECT_URI environment variable if no redirect URI is provided', async () => {
const request = new NextRequest(new URL('http://example.com/protected'));
const result = await updateSession(
const result = await updateSessionMiddleware(
request,
false,
{
@@ -498,7 +505,7 @@ describe('session.ts', () => {
it('should redirect to sign up when unauthenticated user is on a sign up path', async () => {
const request = new NextRequest(new URL('http://example.com/signup'));

const result = await updateSession(
const result = await updateSessionMiddleware(
request,
false,
{
@@ -526,6 +533,92 @@ describe('session.ts', () => {
});
});

describe('updateSession', () => {
it('should return an authorization url if the session is invalid', async () => {
const result = await updateSession(new NextRequest(new URL('http://example.com/protected')), {
debug: true,
});

expect(result.authorizationUrl).toBeDefined();
expect(result.session.user).toBeNull();
});

it('should return a session if the session is valid', async () => {
const nextCookies = await cookies();
nextCookies.set(
'wos-session',
await sealData(mockSession, { password: process.env.WORKOS_COOKIE_PASSWORD as string }),
);

const result = await updateSession(new NextRequest(new URL('http://example.com/protected')), {
debug: true,
});
console.log('result', result);

expect(result.session).toBeDefined();
});

it('should attempt to refresh an invalid session', async () => {
// Setup invalid session
mockSession.accessToken = await generateTestToken({}, true);

const nextCookies = await cookies();
nextCookies.set(
'wos-session',
await sealData(mockSession, { password: process.env.WORKOS_COOKIE_PASSWORD as string }),
);

// Mock token verification to fail
(jwtVerify as jest.Mock).mockImplementation(() => {
throw new Error('Invalid token');
});

// Mock successful refresh
jest.spyOn(workos.userManagement, 'authenticateWithRefreshToken').mockResolvedValue({
accessToken: await generateTestToken(),
refreshToken: 'new-refresh-token',
user: mockSession.user,
});

const result = await updateSession(new NextRequest(new URL('http://example.com/protected')), {
debug: true,
});

expect(result.session).toBeDefined();
expect(result.session.user).toBeDefined();
expect(console.log).toHaveBeenCalledWith(
expect.stringContaining('Session invalid. Refreshing access token that ends in'),
);
});

it('should handle refresh failure by returning auth URL', async () => {
// Setup invalid session
mockSession.accessToken = await generateTestToken({}, true);

const nextCookies = await cookies();
nextCookies.set(
'wos-session',
await sealData(mockSession, { password: process.env.WORKOS_COOKIE_PASSWORD as string }),
);

// Mock token verification to fail
(jwtVerify as jest.Mock).mockImplementation(() => {
throw new Error('Invalid token');
});

// Mock refresh failure
jest.spyOn(workos.userManagement, 'authenticateWithRefreshToken').mockRejectedValue(new Error('Refresh failed'));

const result = await updateSession(new NextRequest(new URL('http://example.com/protected')), {
debug: true,
});

expect(result.session.user).toBeNull();
expect(result.authorizationUrl).toBeDefined();
expect(console.log).toHaveBeenCalledWith('Failed to refresh. Deleting cookie.', expect.any(Error));
});
});

describe('refreshSession', () => {
it('should refresh session successfully', async () => {
jest.spyOn(workos.userManagement, 'authenticateWithRefreshToken').mockResolvedValue({
3 changes: 2 additions & 1 deletion src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -74,7 +74,8 @@ export interface AuthkitOptions {

export interface AuthkitResponse {
session: UserInfo | NoUserInfo;
redirectUri: string;
headers: Headers;
authorizationUrl?: string;
}

export interface CookieOptions {
9 changes: 1 addition & 8 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -15,12 +15,5 @@ export function authkitMiddleware({
}

export async function authkit(request: NextRequest, options: AuthkitOptions = {}): Promise<AuthkitResponse> {
const session = await updateSession(request, options);

const response = {
session,
redirectUri: WORKOS_REDIRECT_URI,
};

return response;
return await updateSession(request, options);
}
80 changes: 61 additions & 19 deletions src/session.ts
Original file line number Diff line number Diff line change
@@ -9,7 +9,15 @@ 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, NoUserInfo, Session, UserInfo } from './interfaces.js';
import {
AccessToken,
AuthkitMiddlewareAuth,
AuthkitOptions,
AuthkitResponse,
NoUserInfo,
Session,
UserInfo,
} from './interfaces.js';

import { parse, tokensToRegexp } from 'path-to-regexp';
import { redirectWithFallback } from './utils.js';
@@ -171,39 +179,70 @@ async function updateSessionMiddleware(
return redirectWithFallback(request.url);
}

async function updateSession(request: NextRequest, options: AuthkitOptions): Promise<UserInfo | NoUserInfo> {
async function updateSession(request: NextRequest, options: AuthkitOptions): Promise<AuthkitResponse> {
const session = await getSessionFromCookie();
if (!session) {
if (options.debug) console.log('No session found from cookie');
return { user: null };
}

const newRequestHeaders = new Headers(request.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),
}),
};
}

const hasValidSession = await verifyAccessToken(session.accessToken);

const cookieName = WORKOS_COOKIE_NAME || 'wos-session';
const nextCookies = await cookies();

if (!hasValidSession) {
if (options.debug)
if (options.debug) {
console.log(`Session invalid. Refreshing access token that ends in ${session.accessToken.slice(-10)}`);
}

try {
const newSession = await refreshSession({
ensureSignedIn: false,
});

return newSession;
newRequestHeaders.set(sessionHeaderName, nextCookies.get(cookieName)!.value);

return {
session: newSession,
headers: newRequestHeaders,
};
} catch (e) {
if (options.debug) console.log('Failed to refresh. Deleting cookie.', e);
const nextCookies = await cookies();
nextCookies.delete(WORKOS_COOKIE_NAME || 'wos-session');

return { user: null };
nextCookies.delete(cookieName);

return {
session: { user: null },
headers: newRequestHeaders,
authorizationUrl: await getAuthorizationUrl({
returnPathname: getReturnPathname(request.url),
}),
};
}
}

newRequestHeaders.set(sessionHeaderName, nextCookies.get(cookieName)!.value);

const {
sid: sessionId,
org_id: organizationId,
@@ -213,14 +252,17 @@ async function updateSession(request: NextRequest, options: AuthkitOptions): Pro
} = decodeJwt<AccessToken>(session.accessToken);

return {
sessionId,
user: session.user,
organizationId,
role,
permissions,
entitlements,
impersonator: session.impersonator,
accessToken: session.accessToken,
session: {
sessionId,
user: session.user,
organizationId,
role,
permissions,
entitlements,
impersonator: session.impersonator,
accessToken: session.accessToken,
},
headers: newRequestHeaders,
};
}