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

Update library for latest version of remix / v3 features #45

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
159 changes: 86 additions & 73 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,17 @@
"format": "prettier --write \"{src,__tests__}/**/*.{js,ts,tsx}\""
},
"dependencies": {
"@workos-inc/node": "^7.31.0",
"@workos-inc/node": "^7.41.0",
"iron-session": "^8.0.1",
"jose": "^5.2.3"
},
"peerDependencies": {
"@remix-run/node": "^2.4.1",
"@remix-run/node": "^2.16.0",
"react": "^18.0 || ^19.0.0",
"react-dom": "^18.0 || ^19.0.0"
},
"devDependencies": {
"@remix-run/node": "^2.16.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
"@types/jest": "^29.5.14",
Expand Down
15 changes: 9 additions & 6 deletions src/authkit-callback-route.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { LoaderFunction } from '@remix-run/node';
import { getWorkOS } from './workos.js';
import { authLoader } from './authkit-callback-route.js';
import {
Expand All @@ -7,6 +6,8 @@ import {
assertIsResponse,
} from './test-utils/test-helpers.js';
import { configureSessionStorage } from './sessionStorage.js';
import { isDataWithResponseInit } from './utils.js';
import { DataWithResponseInit } from './interfaces.js';

// Mock dependencies
const fakeWorkosInstance = {
Expand All @@ -21,7 +22,7 @@ jest.mock('./workos.js', () => ({
}));

describe('authLoader', () => {
let loader: LoaderFunction;
let loader: ReturnType<typeof authLoader>;
let request: Request;
const workos = getWorkOS();
const authenticateWithCode = jest.mocked(workos.userManagement.authenticateWithCode);
Expand Down Expand Up @@ -58,17 +59,19 @@ describe('authLoader', () => {
it('should handle authentication failure', async () => {
authenticateWithCode.mockRejectedValue(new Error('Auth failed'));
request = createRequestWithSearchParams(request, { code: 'invalid-code' });
const response = (await loader({ request, params: {}, context: {} })) as Response;
const response = (await loader({ request, params: {}, context: {} })) as DataWithResponseInit<unknown>;
expect(isDataWithResponseInit(response)).toBeTruthy();

expect(response.status).toBe(500);
expect(response?.init?.status).toBe(500);
});

it('should handle authentication failure with string error', async () => {
authenticateWithCode.mockRejectedValue('Auth failed');
request = createRequestWithSearchParams(request, { code: 'invalid-code' });
const response = (await loader({ request, params: {}, context: {} })) as Response;
const response = (await loader({ request, params: {}, context: {} })) as DataWithResponseInit<unknown>;
expect(isDataWithResponseInit(response)).toBeTruthy();

expect(response.status).toBe(500);
expect(response?.init?.status).toBe(500);
});
});

Expand Down
4 changes: 2 additions & 2 deletions src/authkit-callback-route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { LoaderFunctionArgs, json, redirect } from '@remix-run/node';
import { LoaderFunctionArgs, data, redirect } from '@remix-run/node';
import { getConfig } from './config.js';
import { HandleAuthOptions } from './interfaces.js';
import { encryptSession } from './session.js';
Expand Down Expand Up @@ -86,7 +86,7 @@ export function authLoader(options: HandleAuthOptions = {}) {
}

function errorResponse() {
return json(
return data(
{
error: {
message: 'Something went wrong',
Expand Down
4 changes: 3 additions & 1 deletion src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { SessionStorage, SessionIdStorageStrategy } from '@remix-run/node';
import type { SessionStorage, SessionIdStorageStrategy, data } from '@remix-run/node';
import type { OauthTokens, User } from '@workos-inc/node';

export type DataWithResponseInit<T> = ReturnType<typeof data<T>>;

export interface HandleAuthOptions {
returnPathname?: string;
onSuccess?: (data: AuthLoaderSuccessData) => void | Promise<void>;
Expand Down
61 changes: 39 additions & 22 deletions src/session.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { LoaderFunctionArgs, Session as RemixSession, redirect } from '@remix-run/node';
import { LoaderFunctionArgs, Session as ReactRouterSession, redirect } from '@remix-run/node';
import { AuthenticationResponse } from '@workos-inc/node';
import * as ironSession from 'iron-session';
import * as jose from 'jose';
Expand Down Expand Up @@ -40,6 +40,23 @@ const getSessionStorage = jest.mocked(getSessionStorageMock);
const configureSessionStorage = jest.mocked(configureSessionStorageMock);
const jwtVerify = jest.mocked(jose.jwtVerify);

function getHeaderValue(headers: HeadersInit | undefined, name: string): string | null {
if (!headers) {
return null;
}

if (headers instanceof Headers) {
return headers.get(name);
}

if (Array.isArray(headers)) {
const pair = headers.find(([key]) => key.toLowerCase() === name.toLowerCase());
return pair?.[1] ?? null;
}

return headers[name] ?? null;
}

jest.mock('jose', () => ({
createRemoteJWKSet: jest.fn(),
jwtVerify: jest.fn(),
Expand All @@ -55,7 +72,7 @@ jest.mock('iron-session', () => ({

describe('session', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const createMockSession = (overrides?: Record<string, any>): RemixSession =>
const createMockSession = (overrides?: Record<string, any>): ReactRouterSession =>
({
has: jest.fn(),
get: jest.fn(),
Expand All @@ -65,7 +82,7 @@ describe('session', () => {
id: 'test-session-id',
data: {},
...overrides,
}) satisfies RemixSession;
}) satisfies ReactRouterSession;

const createMockRequest = (cookie = 'test-cookie', url = 'http://example.com./some-path') =>
new Request(url, {
Expand Down Expand Up @@ -111,8 +128,10 @@ describe('session', () => {
profilePictureUrl: 'https://example.com/avatar.jpg',
firstName: 'Test',
lastName: 'User',
externalId: null,
createdAt: '2021-01-01T00:00:00Z',
updatedAt: '2021-01-01T00:00:00Z',
lastSignInAt: '2021-01-01T00:00:00Z',
},
impersonator: undefined,
headers: {},
Expand Down Expand Up @@ -190,7 +209,7 @@ describe('session', () => {
// Execute
const response = await terminateSession(createMockRequest());

// Assert response is instance of Remix Response
// Assert response is instance of Response
expect(response instanceof Response).toBe(true);
expect(response.status).toBe(302);
expect(response.headers.get('Location')).toBe('https://auth.workos.com/logout/test-session-id');
Expand Down Expand Up @@ -222,8 +241,7 @@ describe('session', () => {
});

it('should return unauthorized data when no session exists', async () => {
const response = await authkitLoader(createLoaderArgs(createMockRequest()));
const data = await response.json();
const { data } = await authkitLoader(createLoaderArgs(createMockRequest()));

expect(data).toEqual({
user: null,
Expand Down Expand Up @@ -256,11 +274,14 @@ describe('session', () => {
});
const customLoader = jest.fn().mockReturnValue(redirectResponse);

const response = await authkitLoader(createLoaderArgs(createMockRequest()), customLoader);

expect(response.status).toBe(302);
expect(response.headers.get('Location')).toBe('/dashboard');
expect(response.headers.get('X-Redirect-Reason')).toBe('test');
try {
await authkitLoader(createLoaderArgs(createMockRequest()), customLoader);
} catch (response: unknown) {
assertIsResponse(response);
expect(response.status).toBe(302);
expect(response.headers.get('Location')).toEqual('/dashboard');
expect(response.headers.get('X-Redirect-Reason')).toEqual('test');
}
});
});

Expand Down Expand Up @@ -303,8 +324,7 @@ describe('session', () => {
});

it('should return authorized data with session claims', async () => {
const response = await authkitLoader(createLoaderArgs(createMockRequest()));
const data = await response.json();
const { data } = await authkitLoader(createLoaderArgs(createMockRequest()));

expect(data).toEqual({
user: mockSessionData.user,
Expand All @@ -325,8 +345,7 @@ describe('session', () => {
metadata: { key: 'value' },
});

const response = await authkitLoader(createLoaderArgs(createMockRequest()), customLoader);
const data = await response.json();
const { data } = await authkitLoader(createLoaderArgs(createMockRequest()), customLoader);

expect(data).toEqual(
expect.objectContaining({
Expand All @@ -349,12 +368,11 @@ describe('session', () => {
}),
);

const response = await authkitLoader(createLoaderArgs(createMockRequest()), customLoader);
const { data, init } = await authkitLoader(createLoaderArgs(createMockRequest()), customLoader);

expect(response.headers.get('Custom-Header')).toBe('test-header');
expect(response.headers.get('Content-Type')).toBe('application/json; charset=utf-8');
expect(getHeaderValue(init?.headers, 'Custom-Header')).toBe('test-header');
expect(getHeaderValue(init?.headers, 'Content-Type')).toBe('application/json; charset=utf-8');

const data = await response.json();
expect(data).toEqual(
expect.objectContaining({
customData: 'test-value',
Expand Down Expand Up @@ -437,8 +455,7 @@ describe('session', () => {
});

it('should refresh session when access token is invalid', async () => {
const response = await authkitLoader(createLoaderArgs(createMockRequest()));
const data = await response.json();
const { data, init } = await authkitLoader(createLoaderArgs(createMockRequest()));

// Verify the refresh token flow was triggered
expect(authenticateWithRefreshToken).toHaveBeenCalledWith({
Expand All @@ -459,7 +476,7 @@ describe('session', () => {
);

// Verify cookie was set
expect(response.headers.get('Set-Cookie')).toBe('new-session-cookie');
expect(getHeaderValue(init?.headers, 'Set-Cookie')).toBe('new-session-cookie');
});

it('should redirect to root when refresh fails', async () => {
Expand Down
Loading