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
Address feedback
PaulAsjes committed Dec 13, 2024
commit df7ced334624fbc807a483ca4322680b398c9340
62 changes: 61 additions & 1 deletion __tests__/auth.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,47 @@
import { describe, it, expect, beforeEach, jest } from '@jest/globals';

import { getSignInUrl, getSignUpUrl, signOut } from '../src/auth.js';
import { workos } from '../src/workos.js';

// These are mocked in jest.setup.ts
import { cookies, headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { sealData } from 'iron-session';
import { generateTestToken } from './test-helpers.js';
import { User } from '@workos-inc/node';

// jest.mock('../src/workos', () => ({
// workos: {
// userManagement: {
// getLogoutUrl: jest.fn().mockReturnValue('https://example.com/logout'),
// getJwksUrl: jest.fn().mockReturnValue('https://api.workos.com/sso/jwks/client_1234567890'),
// },
// },
// }));

describe('auth.ts', () => {
const mockSession = {
accessToken: 'access-token',
oauthTokens: undefined,
sessionId: 'session_123',
organizationId: 'org_123',
role: 'member',
permissions: ['posts:create', 'posts:delete'],
entitlements: ['audit-logs'],
impersonator: undefined,
user: {
object: 'user',
id: 'user_123',
email: '[email protected]',
emailVerified: true,
profilePictureUrl: null,
firstName: null,
lastName: null,
createdAt: '2024-01-01',
updatedAt: '2024-01-01',
} as User,
};

beforeEach(async () => {
// Clear all mocks between tests
jest.clearAllMocks();
@@ -45,7 +80,32 @@ describe('auth.ts', () => {
});

describe('signOut', () => {
it('should delete the cookie and redirect', async () => {
it('should delete the cookie and redirect to the logout url if there is a session', async () => {
const nextCookies = await cookies();
const nextHeaders = await headers();

mockSession.accessToken = await generateTestToken();

nextHeaders.set('x-workos-middleware', 'true');
nextHeaders.set(
'x-workos-session',
await sealData(mockSession, { password: process.env.WORKOS_COOKIE_PASSWORD as string }),
);

nextCookies.set('wos-session', 'foo');

jest.spyOn(workos.userManagement, 'getLogoutUrl').mockReturnValue('https://example.com/logout');

await signOut();

const sessionCookie = nextCookies.get('wos-session');

expect(sessionCookie).toBeUndefined();
expect(redirect).toHaveBeenCalledTimes(1);
expect(redirect).toHaveBeenCalledWith('https://example.com/logout');
});

it('should delete the cookie and redirect to the root path if there is no session', async () => {
const nextCookies = await cookies();
const nextHeaders = await headers();

3 changes: 1 addition & 2 deletions __tests__/cookie.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { describe, it, expect } from '@jest/globals';
import { getCookieOptions } from '../src/cookie.js';

// Mock at the top of the file
jest.mock('../src/env-variables');
@@ -13,8 +14,6 @@ describe('cookie.ts', () => {

describe('getCookieOptions', () => {
it('should return the default cookie options', async () => {
const { getCookieOptions } = await import('../src/cookie');

const options = getCookieOptions();
expect(options).toEqual(
expect.objectContaining({
4 changes: 3 additions & 1 deletion __tests__/get-authorization-url.spec.ts
Original file line number Diff line number Diff line change
@@ -18,7 +18,9 @@ describe('getAuthorizationUrl', () => {
// Mock workos.userManagement.getAuthorizationUrl
jest.mocked(workos.userManagement.getAuthorizationUrl).mockReturnValue('mock-url');

await getAuthorizationUrl({});
const url = await getAuthorizationUrl({});

expect(url).toBe('mock-url');

expect(workos.userManagement.getAuthorizationUrl).toHaveBeenCalledWith(
expect.objectContaining({
27 changes: 2 additions & 25 deletions __tests__/session.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
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 { workos } from '../src/workos.js';
import * as envVariables from '../src/env-variables.js';

import { jwtVerify, SignJWT } from 'jose';
import { jwtVerify } from 'jose';
import { sealData } from 'iron-session';
import { User } from '@workos-inc/node';

@@ -622,26 +622,3 @@ describe('session.ts', () => {
});
});
});

async function generateTestToken(payload = {}, expired = false) {
const defaultPayload = {
sid: 'session_123',
org_id: 'org_123',
role: 'member',
permissions: ['posts:create', 'posts:delete'],
entitlements: ['audit-logs'],
};

const mergedPayload = { ...defaultPayload, ...payload };

const secret = new TextEncoder().encode(process.env.WORKOS_COOKIE_PASSWORD as string);

const token = await new SignJWT(mergedPayload)
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setIssuer('urn:example:issuer')
.setExpirationTime(expired ? '0s' : '2h')
.sign(secret);

return token;
}
24 changes: 24 additions & 0 deletions __tests__/test-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { SignJWT } from 'jose';

export async function generateTestToken(payload = {}, expired = false) {
const defaultPayload = {
sid: 'session_123',
org_id: 'org_123',
role: 'member',
permissions: ['posts:create', 'posts:delete'],
entitlements: ['audit-logs'],
};

const mergedPayload = { ...defaultPayload, ...payload };

const secret = new TextEncoder().encode(process.env.WORKOS_COOKIE_PASSWORD as string);

const token = await new SignJWT(mergedPayload)
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setIssuer('urn:example:issuer')
.setExpirationTime(expired ? '0s' : '2h')
.sign(secret);

return token;
}