-
Notifications
You must be signed in to change notification settings - Fork 8
fix: eliminate middleware bundle leak via lazy dynamic import #85
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,294 @@ | ||
| import { describe, it, expect, vi, beforeEach } from 'vitest'; | ||
|
|
||
| const mockAuthkit = { | ||
| withAuth: vi.fn(), | ||
| saveSession: vi.fn(), | ||
| }; | ||
|
|
||
| const mockGetConfig = vi.fn(); | ||
|
|
||
| vi.mock('./authkit-loader', () => ({ | ||
| getAuthkit: vi.fn(() => Promise.resolve(mockAuthkit)), | ||
| validateConfig: vi.fn(() => Promise.resolve()), | ||
| getConfig: () => mockGetConfig(), | ||
| })); | ||
|
|
||
| import { middlewareBody } from './middleware-body'; | ||
|
|
||
| describe('middlewareBody', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('header merging', () => { | ||
| it('uses Headers API for pendingHeaders', async () => { | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: null }, | ||
| refreshedSessionData: null, | ||
| }); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { | ||
| status: 200, | ||
| headers: { 'Content-Type': 'text/plain' }, | ||
| }); | ||
|
|
||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn().mockResolvedValue({ response: mockResponse }), | ||
| }; | ||
|
|
||
| const result = await middlewareBody(args); | ||
|
|
||
| expect(result.response).toBe(mockResponse); | ||
| }); | ||
|
|
||
| it('appends Set-Cookie headers correctly', async () => { | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: null }, | ||
| refreshedSessionData: null, | ||
| }); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { status: 200 }); | ||
|
|
||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async ({ context }: any) => { | ||
| context.__setPendingHeader('Set-Cookie', 'session=abc123; Path=/'); | ||
| return { response: mockResponse }; | ||
| }), | ||
| }; | ||
|
|
||
| const result = await middlewareBody(args); | ||
|
|
||
| expect(result.response.headers.get('Set-Cookie')).toBe('session=abc123; Path=/'); | ||
| }); | ||
|
|
||
| it('supports multiple Set-Cookie headers via append', async () => { | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: null }, | ||
| refreshedSessionData: null, | ||
| }); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { status: 200 }); | ||
|
|
||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async ({ context }: any) => { | ||
| context.__setPendingHeader('Set-Cookie', 'cookie1=value1; Path=/'); | ||
| context.__setPendingHeader('Set-Cookie', 'cookie2=value2; Path=/'); | ||
| return { response: mockResponse }; | ||
| }), | ||
| }; | ||
|
|
||
| const result = await middlewareBody(args); | ||
|
|
||
| const cookies = result.response.headers.get('Set-Cookie'); | ||
| expect(cookies).toContain('cookie1=value1'); | ||
| expect(cookies).toContain('cookie2=value2'); | ||
| }); | ||
|
|
||
| it('uses set() for non-cookie headers', async () => { | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: null }, | ||
| refreshedSessionData: null, | ||
| }); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { status: 200 }); | ||
|
|
||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async ({ context }: any) => { | ||
| context.__setPendingHeader('X-Custom', 'value1'); | ||
| context.__setPendingHeader('X-Custom', 'value2'); | ||
| return { response: mockResponse }; | ||
| }), | ||
| }; | ||
|
|
||
| const result = await middlewareBody(args); | ||
|
|
||
| expect(result.response.headers.get('X-Custom')).toBe('value2'); | ||
| }); | ||
|
|
||
| it('handles refreshed session data via storage context', async () => { | ||
| const refreshedData = 'encrypted_session_data'; | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: { id: 'user_123' } }, | ||
| refreshedSessionData: refreshedData, | ||
| }); | ||
| mockAuthkit.saveSession.mockResolvedValue({ | ||
| response: new Response('', { | ||
| headers: { 'Set-Cookie': 'wos-session=new_value; Path=/' }, | ||
| }), | ||
| }); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { status: 200 }); | ||
|
|
||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async () => ({ response: mockResponse })), | ||
| }; | ||
|
|
||
| const result = await middlewareBody(args); | ||
|
|
||
| expect(mockAuthkit.saveSession).toHaveBeenCalledWith(undefined, refreshedData); | ||
| expect(result.response.headers.get('Set-Cookie')).toContain('wos-session=new_value'); | ||
| }); | ||
|
|
||
| it('provides correct context shape to downstream handlers', async () => { | ||
| const mockAuth = { user: { id: 'user_123' }, sessionId: 'session_123' }; | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: mockAuth, | ||
| refreshedSessionData: null, | ||
| }); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { status: 200 }); | ||
|
|
||
| let capturedContext: any = null; | ||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async ({ context }: any) => { | ||
| capturedContext = context; | ||
| return { response: mockResponse }; | ||
| }), | ||
| }; | ||
|
|
||
| await middlewareBody(args); | ||
|
|
||
| expect(capturedContext.request).toBe(mockRequest); | ||
| expect(typeof capturedContext.auth).toBe('function'); | ||
| expect(capturedContext.auth()).toBe(mockAuth); | ||
| expect(typeof capturedContext.__setPendingHeader).toBe('function'); | ||
| }); | ||
|
|
||
| it('preserves existing response headers', async () => { | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: null }, | ||
| refreshedSessionData: null, | ||
| }); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { | ||
| status: 200, | ||
| headers: { 'X-Existing': 'preserved' }, | ||
| }); | ||
|
|
||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async ({ context }: any) => { | ||
| context.__setPendingHeader('X-New', 'added'); | ||
| return { response: mockResponse }; | ||
| }), | ||
| }; | ||
|
|
||
| const result = await middlewareBody(args); | ||
|
|
||
| expect(result.response.headers.get('X-Existing')).toBe('preserved'); | ||
| expect(result.response.headers.get('X-New')).toBe('added'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('redirectUri option', () => { | ||
| it('passes redirectUri to context when provided', async () => { | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: null }, | ||
| refreshedSessionData: null, | ||
| }); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { status: 200 }); | ||
|
|
||
| let capturedContext: any = null; | ||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async ({ context }: any) => { | ||
| capturedContext = context; | ||
| return { response: mockResponse }; | ||
| }), | ||
| }; | ||
|
|
||
| await middlewareBody(args, { redirectUri: 'https://custom.example.com/callback' }); | ||
|
|
||
| expect(capturedContext.redirectUri).toBe('https://custom.example.com/callback'); | ||
| }); | ||
|
|
||
| it('passes undefined redirectUri when not provided', async () => { | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: null }, | ||
| refreshedSessionData: null, | ||
| }); | ||
| mockGetConfig.mockResolvedValue(undefined); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { status: 200 }); | ||
|
|
||
| let capturedContext: any = null; | ||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async ({ context }: any) => { | ||
| capturedContext = context; | ||
| return { response: mockResponse }; | ||
| }), | ||
| }; | ||
|
|
||
| await middlewareBody(args); | ||
|
|
||
| expect(capturedContext.redirectUri).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('uses WORKOS_REDIRECT_URI from config when option not provided', async () => { | ||
| const envRedirectUri = 'https://env.example.com/callback'; | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: null }, | ||
| refreshedSessionData: null, | ||
| }); | ||
| mockGetConfig.mockResolvedValue(envRedirectUri); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { status: 200 }); | ||
|
|
||
| let capturedContext: any = null; | ||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async ({ context }: any) => { | ||
| capturedContext = context; | ||
| return { response: mockResponse }; | ||
| }), | ||
| }; | ||
|
|
||
| await middlewareBody(args); | ||
|
|
||
| expect(capturedContext.redirectUri).toBe(envRedirectUri); | ||
| }); | ||
|
|
||
| it('prioritizes explicit option over config', async () => { | ||
| const explicitRedirectUri = 'https://explicit.example.com/callback'; | ||
| mockAuthkit.withAuth.mockResolvedValue({ | ||
| auth: { user: null }, | ||
| refreshedSessionData: null, | ||
| }); | ||
| mockGetConfig.mockResolvedValue('https://env.example.com/callback'); | ||
|
|
||
| const mockRequest = new Request('http://test.local'); | ||
| const mockResponse = new Response('OK', { status: 200 }); | ||
|
|
||
| let capturedContext: any = null; | ||
| const args = { | ||
| request: mockRequest, | ||
| next: vi.fn(async ({ context }: any) => { | ||
| capturedContext = context; | ||
| return { response: mockResponse }; | ||
| }), | ||
| }; | ||
|
|
||
| await middlewareBody(args, { redirectUri: explicitRedirectUri }); | ||
|
|
||
| expect(capturedContext.redirectUri).toBe(explicitRedirectUri); | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import { getAuthkit, validateConfig, getConfig } from './authkit-loader.js'; | ||
| import type { AuthKitMiddlewareOptions } from './types.js'; | ||
|
|
||
| let configValidated = false; | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| export async function middlewareBody(args: any, options?: AuthKitMiddlewareOptions) { | ||
| const authkit = await getAuthkit(); | ||
|
|
||
| if (!configValidated) { | ||
| await validateConfig(); | ||
| configValidated = true; | ||
| } | ||
|
|
||
| const { auth, refreshedSessionData } = await authkit.withAuth(args.request); | ||
| const pendingHeaders = new Headers(); | ||
|
|
||
| const result = await args.next({ | ||
| context: { | ||
| auth: () => auth, | ||
| request: args.request, | ||
| redirectUri: options?.redirectUri ?? (await getConfig('redirectUri')), | ||
| __setPendingHeader: (key: string, value: string) => { | ||
| if (key.toLowerCase() === 'set-cookie') { | ||
| pendingHeaders.append(key, value); | ||
| } else { | ||
| pendingHeaders.set(key, value); | ||
| } | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| if (refreshedSessionData) { | ||
| const { response: sessionResponse } = await authkit.saveSession(undefined, refreshedSessionData); | ||
| for (const cookie of sessionResponse?.headers.getSetCookie() ?? []) { | ||
| pendingHeaders.append('Set-Cookie', cookie); | ||
| } | ||
| } | ||
|
|
||
| const headerEntries = [...pendingHeaders]; | ||
| if (headerEntries.length === 0) { | ||
| return result; | ||
| } | ||
|
|
||
| const newResponse = new Response(result.response.body, { | ||
| status: result.response.status, | ||
| statusText: result.response.statusText, | ||
| headers: result.response.headers, | ||
| }); | ||
|
|
||
| for (const [key, value] of headerEntries) { | ||
| if (key.toLowerCase() === 'set-cookie') { | ||
| newResponse.headers.append(key, value); | ||
| } else { | ||
| newResponse.headers.set(key, value); | ||
| } | ||
| } | ||
|
|
||
| return { ...result, response: newResponse }; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
saveSessionmock shape doesn't match what the production code readssaveSessionis mocked to resolve with{ headers: { 'Set-Cookie': '...' } }, butmiddlewareBodydestructures{ response: sessionResponse }from that return value (line 34 ofmiddleware-body.ts). Sinceresponseis absent from the mock,sessionResponseis alwaysundefined,sessionResponse?.headers.get('Set-Cookie')returnsundefined, and the cookie is never appended — so this test never actually verifies that the refreshed-sessionSet-Cookiereaches the final response. The mock should resolve with{ response: new Response('', { headers: { 'Set-Cookie': 'wos-session=new_value; Path=/' } }) }to exercise that path.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep. The mock here should be
and then later
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 3b923a1 — corrected the mock to return
{ response: new Response(...) }and added an assertion thatSet-Cookiereaches the final response.