Skip to content

feat(next-csrf): modernize for Next.js 16 and React 19#35

Closed
riceharvest wants to merge 71 commits intomainfrom
fix/next-csrf-modernization
Closed

feat(next-csrf): modernize for Next.js 16 and React 19#35
riceharvest wants to merge 71 commits intomainfrom
fix/next-csrf-modernization

Conversation

@riceharvest
Copy link
Owner

Closes #22 (roadmap).

  • Verified verifyCsrfToken works with Next.js 16 async cookies() and headers().
  • Added react and react-dom as peerDependencies.
  • Updated next version range in peerDependencies.
  • Verified all 8 unit tests are passing.

- Upgraded multiple packages to modern standards (Next.js, Next-auth, PWA, SEO).
- Added new utility packages: critters, next-circuit-breaker, next-csrf, next-images, next-json-ld.
- Integrated Changesets for versioning.
- Updated CI/CD workflows and linting configurations.
- Fixed numerous linting and type-checking issues across the monorepo.
- Remove legacy NextAuth adapters and resolve workspace version conflicts
- Clean up test warning noise and fix tsconfig/jest setups for next-auth
- Update Workbox/Terser dependencies in next-pwa to align with workspace
- Synchronize root lockfile to reflect nested package resolutions
Fixes `JWT_AUTO_GENERATED_SIGNING_KEY` and `JWT_AUTO_GENERATED_ENCRYPTION_KEY`
warnings properly by supplying JWKs directly in the test suite rather
than mocking the logger.
@qodo-code-review
Copy link

Review Summary by Qodo

Modernize monorepo for Next.js 16, React 19, and Web API support with enhanced security and comprehensive testing

✨ Enhancement 🧪 Tests 🐞 Bug fix

Grey Divider

Walkthroughs

Description
• **Modernized CSRF package for Next.js 16 and React 19**: Added verifyCsrfToken() for App Router
  with async headers() and cookies() support, enhanced token validation with multiple sources, and
  separated httpOnly settings for secret and token cookies
• **Extended session utilities for Web API support**: Added getWebSession() function for Web API
  Request/Response objects, refactored decorateSession() with callbacks, enhanced parseTime()
  with duration units, and improved commitHeader() for both Node.js and Web API
• **Enhanced next-connect middleware execution**: Improved error handling for multiple next()
  calls and proper async/await handling with promise tracking
• **Modernized OAuth implementation**: Removed external oauth package dependency, replaced with
  native fetch API implementation for OAuth 2.x
• **Added TypeORM and Prisma legacy adapters**: Comprehensive implementations for next-auth with
  full CRUD operations and backward compatibility
• **Improved security and robustness**: Fixed CSS inlining vulnerabilities, enhanced URL
  sanitization, improved container detection in critters package
• **Extended test coverage**: Added comprehensive tests for CSRF middleware, App Router
  verification, Web API sessions, MDX functionality, compose plugins, and JWT operations
• **Migrated test frameworks**: Transitioned multiple packages from Jest to Vitest and Node.js
  native test runner
• **Added new packages and examples**: Implemented react-query-auth with Vite example, MDX
  utilities, and Mock Service Worker integration
• **Simplified and modernized documentation**: Removed deprecation notices, updated JSDoc comments,
  cleaned up linting directives
Diagram
flowchart LR
  CSRF["CSRF Package<br/>Modernization"]
  Session["Session Package<br/>Web API Support"]
  Connect["next-connect<br/>Error Handling"]
  Auth["next-auth<br/>OAuth & Adapters"]
  Tests["Test Framework<br/>Migrations"]
  Security["Security<br/>Improvements"]
  
  CSRF -- "App Router<br/>verification" --> NextJS["Next.js 16<br/>Support"]
  Session -- "Web API<br/>Request/Response" --> NextJS
  Connect -- "Async<br/>middleware" --> NextJS
  Auth -- "Native OAuth<br/>implementation" --> NextJS
  Tests -- "Vitest &<br/>Node.js test" --> Quality["Code Quality"]
  Security -- "URL sanitization<br/>& validation" --> Quality
Loading

Grey Divider

File Changes

1. packages/next-images/test/index.test.ts 🧪 Tests +119/-469

Simplify next-images test suite significantly

• Drastically simplified test suite from 529 lines to 179 lines, removing extensive test coverage
• Consolidated multiple describe blocks into a single test suite with minimal assertions
• Removed detailed tests for webpack configuration, output paths, public paths, and edge cases
• Changed from vitest to using createRequire for CommonJS compatibility testing

packages/next-images/test/index.test.ts


2. packages/next-iron-session/src/index.test.ts 🧪 Tests +140/-112

Migrate iron-session tests to Node.js native test runner

• Migrated from vitest to Node.js native node:test module with node:assert assertions
• Replaced vi.fn() mocks with mock.fn() from Node.js test utilities
• Updated all test assertions from expect() to native assertions like deepEqual(), match(),
 rejects()
• Added await test() syntax and mock.reset() calls for proper test isolation

packages/next-iron-session/src/index.test.ts


3. packages/next-csrf/test/index.test.ts 🧪 Tests +13/-475

Drastically reduce next-csrf test coverage

• Reduced test file from 478 lines to 16 lines with minimal test coverage
• Removed all detailed tests for setup middleware, CSRF validation, and edge cases
• Kept only basic export and initialization tests
• Simplified from comprehensive vitest suite to basic functionality checks

packages/next-csrf/test/index.test.ts


View more (165)
4. packages/next-cookies/test/index.test.ts 🧪 Tests +31/-247

Simplify next-cookies test suite significantly

• Reduced test file from 261 lines to 45 lines, removing extensive test coverage
• Removed security tests, special character handling, and large cookie handling tests
• Simplified to basic functionality tests for cookie parsing and edge cases
• Added getCookies as an alias export alongside nextCookies

packages/next-cookies/test/index.test.ts


5. packages/next-session/src/index.ts ✨ Enhancement +115/-55

Add Web API support and refactor session decoration

• Refactored decorateSession() to accept commitFn and destroyFn callbacks instead of
 req/res objects
• Added new getWebSession() function to support Web API Request/Response objects alongside
 Node.js streams
• Extracted session commit and destroy logic into separate async functions for better separation of
 concerns
• Improved type safety with explicit type imports and reduced as unknown casts

packages/next-session/src/index.ts


6. packages/next-images/src/index.ts 📝 Documentation +16/-145

Modernize documentation and remove deprecation notices

• Removed extensive JSDoc comments and deprecation warnings about using next/image instead
• Simplified interface documentation by removing detailed parameter descriptions
• Updated package description to emphasize compatibility-first approach for teams migrating from
 original package
• Removed inline comments explaining webpack configuration logic while preserving functionality

packages/next-images/src/index.ts


7. packages/next-mdx/src/get-nodes.ts ✨ Enhancement +244/-0

Add MDX node retrieval and serialization module

• New file implementing MDX node retrieval and serialization functionality
• Exports getMdxNode() and getAllMdxNodes() functions for fetching and rendering MDX content
• Includes caching mechanism via mdxCache for improved performance
• Supports relationships between MDX nodes and configurable serialization options

packages/next-mdx/src/get-nodes.ts


8. packages/react-query-auth/src/examples-api.test.ts 🧪 Tests +194/-0

Add comprehensive tests for react-query-auth examples

• New test file for example API helpers in the vite example application
• Tests handleApiResponse(), loginWithEmailAndPassword(), registerWithEmailAndPassword(), and
 getUserProfile()
• Includes tests for mock database functionality with password hashing and user validation
• Validates storage utilities for token management and localStorage interactions

packages/react-query-auth/src/examples-api.test.ts


9. packages/next-session/test/session.test.ts 🧪 Tests +76/-51

Improve session test assertions and server setup

• Updated test assertions to use expect.objectContaining() for more flexible object matching
• Fixed test server setup to properly handle async callbacks and error handling
• Improved mock store assertions to verify session ID and object structure more robustly
• Added ESLint disable comment for TypeScript strict mode compatibility

packages/next-session/test/session.test.ts


10. packages/next-transpile-modules/src/__tests__/next13plus.test.ts 🧪 Tests +63/-0

Add Next.js 13+ compatibility tests for transpile-modules

• New test file for Next.js 13+ compatibility in transpile-modules package
• Tests version detection and conditional use of transpilePackages vs webpack hacks
• Validates merging of existing transpilePackages configuration
• Uses rewire for internal module mocking and environment variable testing

packages/next-transpile-modules/src/tests/next13plus.test.ts


11. packages/next-csrf/test/csrf.middleware.test.ts 🧪 Tests +147/-0

Add CSRF middleware unit tests

• Added comprehensive unit tests for CSRF middleware with 4 test cases
• Tests cover missing request tokens, valid token matching, token mismatches, and signed tokens
• Created mock request/response helpers for testing Next.js API routes
• Validates error codes and HTTP status responses

packages/next-csrf/test/csrf.middleware.test.ts


12. packages/next-csrf/src/index.ts ✨ Enhancement +10/-77

Modernize CSRF exports and cookie defaults

• Changed httpOnly default from true to false for client-readable tokens
• Updated import to use SerializeOptions instead of CookieSerializeOptions
• Removed extensive JSDoc comments and simplified documentation
• Reordered exports alphabetically and added verifyCsrfToken export

packages/next-csrf/src/index.ts


13. packages/next-csrf/src/middleware/csrf.ts ✨ Enhancement +62/-6

Enhance CSRF token validation with multiple sources

• Added getRequestToken() function to extract tokens from headers, body, or query
• Added pickFirstHeaderValue() helper for handling array header values
• Implemented token mismatch validation between request and cookie tokens
• Added new error code MISSING_REQUEST_TOKEN and TOKEN_MISMATCH handling

packages/next-csrf/src/middleware/csrf.ts


14. packages/next-csrf/src/app-router.ts ✨ Enhancement +59/-0

Add App Router CSRF verification support

• New file implementing verifyCsrfToken() for Next.js App Router
• Supports async headers() and cookies() from Next.js 16
• Validates tokens from request headers with fallback options
• Handles signed tokens and verification against CSRF secret

packages/next-csrf/src/app-router.ts


15. packages/next-csrf/test/app-router.test.ts 🧪 Tests +51/-0

Add App Router CSRF verification tests

• Added unit tests for verifyCsrfToken() App Router function
• Tests valid token verification and token mismatch scenarios
• Mocks Next.js headers() and cookies() async functions

packages/next-csrf/test/app-router.test.ts


16. packages/next-csrf/src/middleware/setup.ts ✨ Enhancement +12/-6

Separate httpOnly settings for secret and token cookies

• Separated cookie options for csrfSecret (always httpOnly) and token (client-readable)
• Added secretCookieOptions and tokenCookieOptions with appropriate httpOnly settings
• Updated comments to clarify security model for double-submit validation

packages/next-csrf/src/middleware/setup.ts


17. packages/next-csrf/src/types.ts ✨ Enhancement +12/-9

Update CSRF types and error codes

• Changed import from CookieSerializeOptions to SerializeOptions
• Updated default cookie options documentation to reflect httpOnly: false
• Added new error codes MISSING_REQUEST_TOKEN and TOKEN_MISMATCH
• Updated JSDoc comments for cookie configuration

packages/next-csrf/src/types.ts


18. packages/next-csrf/tsup.config.ts ⚙️ Configuration changes +1/-13

Simplify tsup build configuration

• Removed custom esbuild banner configuration
• Simplified external dependencies list to empty array
• Reduced configuration complexity

packages/next-csrf/tsup.config.ts


19. packages/next-session/test/utils.test.ts 🧪 Tests +24/-11

Update session utils tests and add parseTime tests

• Updated test assertions from deprecated toBeCalled() to toHaveBeenCalled()
• Updated toBeCalledWith() to toHaveBeenCalledWith()
• Added parseTime() function tests for duration parsing (s, m, h, d units)
• Added import for parseTime utility function

packages/next-session/test/utils.test.ts


20. packages/next-session/src/utils.ts ✨ Enhancement +36/-7

Enhance session utilities for Web API support

• Enhanced parseTime() to support duration units (s, m, h, d)
• Updated commitHeader() to support both ServerResponse and Headers objects
• Improved cookie serialization with explicit cookie options
• Added proper handling for Web API Headers interface

packages/next-session/src/utils.ts


21. packages/next-session/test/compat.test.ts 🧪 Tests +22/-13

Modernize session compatibility tests

• Updated TypeScript ignore comments to use @ts-expect-error instead of @ts-ignore
• Improved Promise type annotations with explicit Promise<void> generics
• Refactored callback error handling for better readability
• Removed eslint-disable comments

packages/next-session/test/compat.test.ts


22. packages/next-session/src/compat.ts ✨ Enhancement +3/-3

Relax type constraints for express-session compat

• Changed function parameter types from specific to any for compatibility
• Updated ExpressStore constructor to accept any type for this context
• Simplified type annotations for legacy express-session compatibility

packages/next-session/src/compat.ts


23. packages/next-session/src/types.ts ✨ Enhancement +8/-2

Extend session types for flexibility

• Changed SessionRecord type from Record<string, unknown> to Record<string, any>
• Updated touchAfter option to accept number | string for duration parsing
• Added module augmentation for http.IncomingMessage with optional session property

packages/next-session/src/types.ts


24. packages/next-session/test/web.test.ts 🧪 Tests +50/-0

Add Web API session tests

• New test file for Web API session support
• Tests getWebSession() with standard Request and Headers objects
• Validates session creation, persistence, and destruction
• Tests loading existing sessions from cookies

packages/next-session/test/web.test.ts


25. packages/next-session/tsup.config.ts ⚙️ Configuration changes +10/-6

Configure dual entry points for session package

• Changed entry configuration to support multiple outputs (session and compat)
• Added outDir configuration set to 'lib'
• Updated banner template to use placeholders for package metadata

packages/next-session/tsup.config.ts


26. packages/next-connect/src/router.ts ✨ Enhancement +55/-7

Improve middleware execution and error handling

• Rewrote exec() method with improved middleware dispatch logic
• Added error handling for calling next() multiple times or after last handler
• Implemented proper async/await handling with promise tracking
• Updated find() method to handle undefined route parameters safely

packages/next-connect/src/router.ts


27. packages/next-connect/src/types.ts ✨ Enhancement +1/-1

Allow undefined route parameters

• Updated FindResult params type to Record<string, string | undefined>
• Allows route parameters to be undefined instead of always strings

packages/next-connect/src/types.ts


28. packages/next-connect/test/router.test.ts 🧪 Tests +25/-0

Add middleware execution error tests

• Added test for next() called with no middleware remaining
• Added test for next() called multiple times in same handler
• Validates proper error messages for middleware execution violations

packages/next-connect/test/router.test.ts


29. packages/next-connect/test/node.test.ts 🧪 Tests +17/-0

Add node router error handling test

• Added test for error handling when next() is called after last handler
• Validates onError callback is invoked with appropriate error message

packages/next-connect/test/node.test.ts


30. packages/next-auth/types/adapters.d.ts ✨ Enhancement +95/-13

Expand TypeORM adapter type definitions

• Replaced re-exports with inline class and interface definitions
• Added explicit TypeORM model class implementations
• Defined TypeORMAdapterModels interface with schema mappings
• Added generic type parameters for TypeORMAdapter and PrismaLegacyAdapter

packages/next-auth/types/adapters.d.ts


31. packages/next-auth/src/adapters/typeorm-legacy.js ✨ Enhancement +857/-0

Add TypeORM legacy adapter implementation

• New comprehensive TypeORM legacy adapter implementation
• Includes model classes, schemas, and database configuration parsing
• Supports multiple database types (MongoDB, PostgreSQL, MySQL, SQLite, MSSQL)
• Implements full adapter interface with user, account, session management

packages/next-auth/src/adapters/typeorm-legacy.js


32. packages/next-auth/types/providers.d.ts ✨ Enhancement +14/-5

Modernize OAuth provider type definitions

• Added CheckType type alias for OAuth protection checks
• Deprecated ProtectionType in favor of CheckType
• Added new checks property to OAuthConfig interface
• Deprecated protection property with JSDoc annotation
• Added url object to AppProvider interface with origin, pathname, href

packages/next-auth/types/providers.d.ts


33. packages/next-auth/types/index.d.ts ✨ Enhancement +1/-2

Remove TypeORM ConnectionOptions dependency

• Removed ConnectionOptions import from typeorm
• Updated database option type to exclude ConnectionOptions
• Simplified database configuration type definition

packages/next-auth/types/index.d.ts


34. packages/next-auth/types/jwt.d.ts ✨ Enhancement +3/-3

Update JWT type parameters

• Removed generic type parameter <false> from JoseJWT.VerifyOptions
• Removed generic type parameter <false> from JWE.DecryptOptions
• Updated in both JWTDecodeParams and JWTOptions interfaces

packages/next-auth/types/jwt.d.ts


35. packages/next-auth/src/server/index.js ✨ Enhancement +16/-19

Modernize auth server URL handling

• Added url object to parseUrl() result destructuring
• Updated URL validation to use url.origin instead of baseUrl
• Updated error page construction to use url.href
• Refactored OAuth protection logic to use checks property
• Removed legacy protection and state properties from provider

packages/next-auth/src/server/index.js


36. packages/next-seo/tests/e2e/jsonLdScript.e2e.spec.ts 🧪 Tests +20/-10

Implement JSON-LD schema validation

• Implemented JSON-LD schema validation using Ajv library
• Created WebPage schema with required properties validation
• Replaced skipped test with functional schema validation test
• Validates @context, @type, name, description, url properties

packages/next-seo/tests/e2e/jsonLdScript.e2e.spec.ts


37. packages/next-seo/src/utils/stringify.ts Formatting +1/-1

Clean up linting directives

• Removed eslint-disable comment
• Kept existing code structure and functionality

packages/next-seo/src/utils/stringify.ts


38. packages/react-query-auth/examples/vite/src/mocks/db.ts Miscellaneous +112/-0

Add mock database for auth example

• New mock database module with user and credential management
• Implements password hashing using SubtleCrypto with FNV-1a fallback
• Provides functions for user creation, retrieval, and password validation
• Uses localStorage for persistence in browser environment

packages/react-query-auth/examples/vite/src/mocks/db.ts


39. packages/react-query-auth/examples/vite/src/mocks/api-server.ts Miscellaneous +85/-0

Add MSW API server mock

• New MSW (Mock Service Worker) API server setup
• Implements auth endpoints (login, register, logout, me)
• Handles user authentication with email/password validation
• Includes 1-second delays for realistic API simulation

packages/react-query-auth/examples/vite/src/mocks/api-server.ts


40. packages/react-query-auth/examples/vite/src/lib/api.ts Miscellaneous +68/-0

Add authentication API client

• New API client module with authentication functions
• Implements getUserProfile(), loginWithEmailAndPassword(), registerWithEmailAndPassword(),
 logout()
• Includes JSON response parsing with content-type validation
• Provides generic error handling for API responses

packages/react-query-auth/examples/vite/src/lib/api.ts


41. packages/react-query-auth/examples/vite/src/lib/auth.ts Miscellaneous +54/-0

Add react-query-auth configuration

• New auth configuration module using react-query-auth
• Implements user, login, register, and logout functions
• Manages JWT token storage and user response handling
• Exports configured auth hooks and loader

packages/react-query-auth/examples/vite/src/lib/auth.ts


42. packages/react-query-auth/examples/vite/src/lib/utils.ts Miscellaneous +22/-0

Add token storage utilities

• New storage utility module for token management
• Implements secure token storage with validation
• Prevents header injection and empty token handling
• Provides getToken(), setToken(), clearToken() methods

packages/react-query-auth/examples/vite/src/lib/utils.ts


43. packages/react-query-auth/vitest.config.ts ⚙️ Configuration changes +21/-0

Add react-query-auth test configuration

• New Vitest configuration for react-query-auth package
• Configured jsdom environment for React component testing
• Set up coverage thresholds at 80% for all metrics

packages/react-query-auth/vitest.config.ts


44. packages/react-query-auth/tsup.config.ts ⚙️ Configuration changes +11/-0

Add react-query-auth build configuration

• New tsup build configuration for react-query-auth
• Configured ESM and CJS output formats
• Enabled source maps and TypeScript declarations

packages/react-query-auth/tsup.config.ts


45. packages/react-query-auth/tsup.dev.config.ts ⚙️ Configuration changes +10/-0

Add react-query-auth dev build config

• New development build configuration for react-query-auth
• Mirrors main tsup config with development-focused settings

packages/react-query-auth/tsup.dev.config.ts


46. packages/next-mdx/src/get-config.ts ✨ Enhancement +59/-0

Add MDX configuration loader

• New module for loading MDX configuration from files
• Supports both next-mdx.config.mjs and next-mdx.json formats
• Prefers JS config over JSON with fallback logic
• Includes error handling and default configuration merging

packages/next-mdx/src/get-config.ts


47. packages/next-mdx/src/get-files.ts ✨ Enhancement +32/-0

Add MDX file discovery

• New module for discovering MDX files in content directories
• Generates file metadata including slug and URL
• Uses fast-glob for efficient file discovery
• Supports configurable base paths for URLs

packages/next-mdx/src/get-files.ts


48. packages/next-mdx/src/get-mdx-paths.ts 📦 Other +31/-0
• New

packages/next-mdx/src/get-mdx-paths.ts


49. packages/next-pwa/test-app/public/service-worker.js ⚙️ Configuration changes +1/-1

Service worker update with new build artifacts

• Updated service worker with new workbox version and build manifest hashes
• Modified cache handler to use simplified response parameter destructuring
• Reorganized precache routes and static asset references

packages/next-pwa/test-app/public/service-worker.js


50. packages/next-auth/src/server/lib/oauth/client.js ✨ Enhancement +111/-170

Remove oauth package dependency with native implementation

• Removed dependency on external oauth package, replaced with native implementation
• Refactored OAuth 2.x client to use native fetch API instead of node-oauth
• Simplified OAuth 1.x client with placeholder implementation and error messages
• Updated getOAuth2AccessToken and getOAuth2 functions to use async/await with fetch

packages/next-auth/src/server/lib/oauth/client.js


51. packages/next-compose-plugins/src/__tests__/compose.test.js 🧪 Tests +358/-0

Add complete test suite for compose functionality

• Added comprehensive test suite for plugin composition functionality
• Tests cover plugin parsing, phase-based execution, configuration merging
• Validates optional plugin loading and error handling for incompatible plugins

packages/next-compose-plugins/src/tests/compose.test.js


52. packages/react-query-auth/examples/vite/public/mockServiceWorker.js ⚙️ Configuration changes +307/-0

Add Mock Service Worker service worker implementation

• Added Mock Service Worker (MSW) service worker implementation
• Handles request interception, mocking, and passthrough logic
• Manages client lifecycle and message communication for mocking control

packages/react-query-auth/examples/vite/public/mockServiceWorker.js


53. packages/next-transpile-modules/src/next-transpile-modules.js ✨ Enhancement +56/-28

Add Next.js 13+ native transpilePackages support

• Added Next.js version detection to use native transpilePackages for v13+
• Improved webpack matcher with better path traversal protection
• Simplified regex patterns and error handling for module resolution
• Added fallback logic for Next.js 13+ while maintaining backward compatibility

packages/next-transpile-modules/src/next-transpile-modules.js


54. packages/critters/src/runtime.js 🐞 Bug fix +44/-19

Improve security and robustness of CSS inlining

• Fixed checkInlineThreshold call to pass textContent instead of sheet object
• Added fallback for missing document head when appending styles
• Enhanced URL sanitization with _sanitizeUrl function to block dangerous schemes
• Improved media query escaping in onload attribute to prevent injection
• Refined animation keyword filtering to avoid false positives in keyframe detection
• Enhanced font preload generation with format detection and multiple URL parsing

packages/critters/src/runtime.js


55. packages/next-auth/src/adapters/prisma-legacy.js ✨ Enhancement +290/-0

Add Prisma legacy adapter for next-auth

• Added new Prisma legacy adapter for next-auth with full CRUD operations
• Implements user, account, session, and verification request management
• Supports configurable model mapping and token hashing with crypto
• Provides backward compatibility for legacy authentication flows

packages/next-auth/src/adapters/prisma-legacy.js


56. packages/next-compose-plugins/src/__tests__/phases.test.js 🧪 Tests +171/-0

Add test suite for phase management functionality

• Added comprehensive test suite for phase checking and configuration merging
• Tests validate phase-specific plugin execution and negated phase syntax
• Covers phase configuration merging with default and phase-specific overrides

packages/next-compose-plugins/src/tests/phases.test.js


57. packages/next-optimized-images/lib/loaders/index.js ✨ Enhancement +165/-0

Add image loader detection and configuration

• Added module detection and loader discovery functionality
• Implements image type handling configuration and optimization loader detection
• Provides webpack loader configuration assembly with responsive and webp support

packages/next-optimized-images/lib/loaders/index.js


58. packages/next-auth/src/lib/__tests__/jwt.test.js 🧪 Tests +34/-15

Update JWT tests with key-based signing and encryption

• Updated JWT tests to use signingKey and encryptionKey parameters
• Added test fixtures with proper JWK format for signing and encryption
• Enhanced test coverage for encrypted token handling and key-based operations

packages/next-auth/src/lib/tests/jwt.test.js


59. packages/react-virtualized/source/Table/Table.jest.js 🧪 Tests +15/-15

Migrate Table tests from Jest to Vitest

• Migrated test framework from Jest to Vitest (jestvi)
• Updated all mock function calls to use vi.fn() and vi.resetModules()
• Replaced jest.spyOn with vi.spyOn for spy functionality

packages/react-virtualized/source/Table/Table.jest.js


60. packages/react-virtualized/source/WindowScroller/WindowScroller.jest.js 🧪 Tests +17/-17

Migrate WindowScroller tests from Jest to Vitest

• Migrated test framework from Jest to Vitest throughout test file
• Updated mock functions, spies, and module resets to use vi API
• Replaced all jest.fn() calls with vi.fn() equivalents

packages/react-virtualized/source/WindowScroller/WindowScroller.jest.js


61. packages/next-optimized-images/lib/resource-queries.js ✨ Enhancement +173/-0

Add resource query configuration for image loaders

• Added resource query configuration for image optimization loaders
• Implements query patterns for url, inline, include, original, lqip, resize, and trace
• Provides loader option merging and resource query generation for webpack

packages/next-optimized-images/lib/resource-queries.js


62. packages/next-compose-plugins/src/__tests__/index.test.js 🧪 Tests +128/-0

Add test suite for main compose plugins API

• Added test suite for main next-compose-plugins API
• Tests cover config extension, phase-specific execution, and webpack config chaining
• Validates phase-specific configuration resolution in Next.js config

packages/next-compose-plugins/src/tests/index.test.js


63. packages/next-optimized-images/lib/loaders/img-loader.js ✨ Enhancement +145/-0

Add img loader configuration for webpack

• Added img loader configuration and application for webpack
• Implements imagemin plugin loading and optimization options
• Provides resource query handling and default image optimization behavior

packages/next-optimized-images/lib/loaders/img-loader.js


64. packages/next-mdx/test/index.test.js 🧪 Tests +114/-0

Add test suite for next-mdx core functionality

• Added comprehensive test suite for next-mdx functionality
• Tests cover node retrieval, relationships, nested content, and MDX hydration
• Validates configuration handling and error cases for invalid sources

packages/next-mdx/test/index.test.js


65. packages/react-virtualized/source/Table/createMultiSort.jest.js 🧪 Tests +11/-11

Migrate createMultiSort tests from Jest to Vitest

• Migrated test framework from Jest to Vitest
• Updated all jest.fn() calls to vi.fn() throughout test file

packages/react-virtualized/source/Table/createMultiSort.jest.js


66. packages/critters/src/dom.js 🐞 Bug fix +5/-6

Improve critters container detection robustness

• Added fallback logic for malformed data-critters-container elements
• Improved container detection to handle edge cases where element exists in HTML but not in DOM

packages/critters/src/dom.js


67. packages/next-auth/app/pages/email.js Formatting +2/-2

Clean up unused variables and comments

• Removed unused eslint-disable comment
• Updated handleLogout parameter from event to _event to indicate unused variable

packages/next-auth/app/pages/email.js


68. .changeset/fix-pr23-feedback.md Additional files +37/-0

...

.changeset/fix-pr23-feedback.md


69. .github/workflows/bundle-size.yml Additional files +11/-0

...

.github/workflows/bundle-size.yml


70. .github/workflows/ci.yml Additional files +81/-37

...

.github/workflows/ci.yml


71. .github/workflows/release.yml Additional files +3/-3

...

.github/workflows/release.yml


72. .github/workflows/security-audit.yml Additional files +23/-9

...

.github/workflows/security-audit.yml


73. .husky/pre-commit Additional files +1/-8

...

.husky/pre-commit


74. AGENTS.md Additional files +36/-0

...

AGENTS.md


75. README.md Additional files +23/-21

...

README.md


76. eslint.config.js Additional files +0/-31

...

eslint.config.js


77. eslint.config.mjs Additional files +176/-0

...

eslint.config.mjs


78. lefthook.yml Additional files +42/-0

...

lefthook.yml


79. llms.txt Additional files +12/-2

...

llms.txt


80. package.json Additional files +23/-9

...

package.json


81. packages/critters/.changeset/config.json Additional files +11/-0

...

packages/critters/.changeset/config.json


82. packages/critters/.commitlintrc.json Additional files +35/-0

...

packages/critters/.commitlintrc.json


83. packages/critters/.github/FUNDING.yml Additional files +3/-0

...

packages/critters/.github/FUNDING.yml


84. packages/critters/.github/ISSUE_TEMPLATE/bug_report.yml Additional files +88/-0

...

packages/critters/.github/ISSUE_TEMPLATE/bug_report.yml


85. packages/critters/.github/ISSUE_TEMPLATE/config.yml Additional files +11/-0

...

packages/critters/.github/ISSUE_TEMPLATE/config.yml


86. packages/critters/.github/ISSUE_TEMPLATE/feature_request.yml Additional files +45/-0

...

packages/critters/.github/ISSUE_TEMPLATE/feature_request.yml


87. packages/critters/.github/ISSUE_TEMPLATE/security_vulnerability.yml Additional files +14/-0

...

packages/critters/.github/ISSUE_TEMPLATE/security_vulnerability.yml


88. packages/critters/.github/PULL_REQUEST_TEMPLATE.md Additional files +45/-0

...

packages/critters/.github/PULL_REQUEST_TEMPLATE.md


89. packages/critters/.github/SECURITY.md Additional files +59/-0

...

packages/critters/.github/SECURITY.md


90. packages/critters/.github/renovate.json Additional files +51/-0

...

packages/critters/.github/renovate.json


91. packages/critters/.github/workflows/ci.yml Additional files +1/-1

...

packages/critters/.github/workflows/ci.yml


92. packages/critters/.npmrc Additional files +5/-0

...

packages/critters/.npmrc


93. packages/critters/.prettierignore Additional files +6/-0

...

packages/critters/.prettierignore


94. packages/critters/.prettierrc.cjs Additional files +12/-0

...

packages/critters/.prettierrc.cjs


95. packages/critters/CHANGELOG.md Additional files +7/-83

...

packages/critters/CHANGELOG.md


96. packages/critters/CODE_OF_CONDUCT.md Additional files +133/-0

...

packages/critters/CODE_OF_CONDUCT.md


97. packages/critters/CONTRIBUTING.md Additional files +330/-0

...

packages/critters/CONTRIBUTING.md


98. packages/critters/LICENSE Additional files +21/-190

...

packages/critters/LICENSE


99. packages/critters/README.md Additional files +16/-188

...

packages/critters/README.md


100. packages/critters/SECURITY.md Additional files +59/-0

...

packages/critters/SECURITY.md


101. packages/critters/llms.txt Additional files +22/-0

...

packages/critters/llms.txt


102. packages/critters/package.json Additional files +23/-37

...

packages/critters/package.json


103. packages/critters/plans/architecture.md Additional files +1795/-0

...

packages/critters/plans/architecture.md


104. packages/critters/src/index.ts Additional files +6/-0

...

packages/critters/src/index.ts


105. packages/critters/src/runtime.d.ts Additional files +0/-0

...

packages/critters/src/runtime.d.ts


106. packages/critters/test/index.test.ts Additional files +13/-0

...

packages/critters/test/index.test.ts


107. packages/critters/test/security.test.js Additional files +17/-0

...

packages/critters/test/security.test.js


108. packages/critters/tsconfig.base.json Additional files +19/-0

...

packages/critters/tsconfig.base.json


109. packages/critters/tsconfig.build.json Additional files +11/-0

...

packages/critters/tsconfig.build.json


110. packages/critters/tsconfig.json Additional files +11/-0

...

packages/critters/tsconfig.json


111. packages/critters/tsup.config.ts Additional files +5/-17

...

packages/critters/tsup.config.ts


112. packages/critters/vitest.config.ts Additional files +1/-1

...

packages/crit...

@qodo-code-review
Copy link

qodo-code-review bot commented Mar 12, 2026

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (5) 📎 Requirement gaps (0)

Grey Divider


Action required

1. tsup externals cleared 📘 Rule violation ⛯ Reliability
Description
packages/next-csrf/tsup.config.ts now sets external: [], which can unintentionally bundle
framework/runtime dependencies and change build outputs for consumers. This risks breaking
established package-local build behavior.
Code

packages/next-csrf/tsup.config.ts[12]

+  external: [],
Evidence
PR Compliance ID 3 requires preserving package-local tooling config compatibility; clearing
external materially changes tsup bundling behavior for the package.

AGENTS.md
packages/next-csrf/tsup.config.ts[3-13]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`packages/next-csrf/tsup.config.ts` cleared the `external` list (`external: []`). This can cause bundling of dependencies that were previously externalized, potentially breaking consumer builds or runtime expectations.

## Issue Context
The monorepo compliance rules require preserving package-local tooling configuration compatibility.

## Fix Focus Areas
- packages/next-csrf/tsup.config.ts[3-13]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. providers.test.jsx not formatted 📘 Rule violation ✓ Correctness
Description
Modified code in packages/next-auth/src/client/__tests__/providers.test.jsx uses double quotes and
appears to omit semicolons, conflicting with Prettier conventions. This introduces inconsistent
formatting in tests.
Code

packages/next-auth/src/client/tests/providers.test.jsx[R1-7]

+// @vitest-environment happy-dom
+import React from "react"
+import { http, HttpResponse } from "msw"
import { useState } from "react"
import userEvent from "@testing-library/user-event"
import { render, screen, waitFor } from "@testing-library/react"
import { server, mockProviders } from "./helpers/mocks"
Evidence
PR Compliance ID 2 requires single quotes and semicolons; the updated test file uses double quotes
and a non-Prettier style.

AGENTS.md
packages/next-auth/src/client/tests/providers.test.jsx[1-10]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`packages/next-auth/src/client/__tests__/providers.test.jsx` includes formatting that conflicts with the repository’s Prettier conventions.

## Issue Context
Prettier conventions are required across the monorepo for consistency.

## Fix Focus Areas
- packages/next-auth/src/client/__tests__/providers.test.jsx[1-34]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Next shipped as dependency 🐞 Bug ⛯ Reliability
Description
@opensourceframework/next-csrf now lists next in dependencies (while also in peerDependencies),
which can install a nested Next.js copy instead of using the host app’s Next.js. This can create
version conflicts and runtime/tooling breakage when the host app uses a different Next version.
Code

packages/next-csrf/package.json[R76-81]

+  "dependencies": {
+    "cookie": "^1.1.1",
+    "cookie-signature": "^1.2.2",
+    "csrf": "^3.1.0",
+    "next": "^16.1.6"
  }
Evidence
The package both declares Next.js as a peer dependency and a runtime dependency; this combination
can cause package managers to install an additional Next.js copy under this package if the host
version doesn’t satisfy the dependency range.

packages/next-csrf/package.json[59-81]
packages/next-csrf/package.json[14-27]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`@opensourceframework/next-csrf` declares `next` in both `peerDependencies` and `dependencies`. This can lead to a nested Next.js installation and version conflicts in consuming apps.

### Issue Context
The package already targets Next.js consumers via `peerDependencies`; shipping `next` as a runtime dependency is likely unintended and risky.

### Fix Focus Areas
- packages/next-csrf/package.json[59-81]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (1)
4. README documents wrong API 🐞 Bug ✓ Correctness
Description
packages/next-csrf/README.md documents createCSRF / csrf.protect and a default tokenKey of
_csrf, but the package’s actual public entrypoint exports nextCsrf and defaults tokenKey to
XSRF-TOKEN. Users following the README will write imports/calls that fail and configure the wrong
cookie/header names.
Code

packages/next-csrf/README.md[R39-49]

```typescript
-// lib/csrf.ts
-import { nextCsrf } from '@opensourceframework/next-csrf';
+// Usage example
+import { createCSRF } from '@opensourceframework/next-csrf';

-const { csrf, setup } = nextCsrf({
-  // Required: A secret key for signing cookies (use environment variable in production)
+const csrf = createCSRF({
  secret: process.env.CSRF_SECRET,
-  
-  // Optional: Customize the token cookie name (default: 'XSRF-TOKEN')
-  tokenKey: 'XSRF-TOKEN',
-  
-  // Optional: Custom error message (default: 'Invalid CSRF token')
-  csrfErrorMessage: 'Invalid CSRF token',
-  
-  // Optional: Methods to ignore (default: ['GET', 'HEAD', 'OPTIONS'])
-  ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],
-  
-  // Optional: Cookie options
-  cookieOptions: {
-    httpOnly: true,
-    path: '/',
-    sameSite: 'lax',
-    secure: process.env.NODE_ENV === 'production',
-  },
});

-export { csrf, setup };
+// Use in API routes
+export default csrf.protect(handler);
</details>
Evidence
The README usage and API reference mention symbols and defaults that are not present in the package
entry module and contradict the code defaults.

packages/next-csrf/README.md[37-49]
packages/next-csrf/README.md[70-92]
packages/next-csrf/src/index.ts[32-38]
packages/next-csrf/src/index.ts[66-71]
packages/next-csrf/package.json[14-27]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The README documents a `createCSRF` / `csrf.protect` API and `_csrf` defaults that do not match the actual package exports/defaults.

### Issue Context
The package entrypoint exports `nextCsrf` and defaults `tokenKey` to `XSRF-TOKEN`. The README should not instruct users to import symbols that aren’t exported.

### Fix Focus Areas
- packages/next-csrf/README.md[37-103]
- packages/next-csrf/src/index.ts[32-72]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

5. security.test.js nonstandard extension 📘 Rule violation ✓ Correctness
Description
The PR updates packages/critters/test/security.test.js, which does not follow the required
*.test.ts/*.test.tsx naming convention. This reduces consistency and discoverability of tests
across packages.
Code

packages/critters/test/security.test.js[R111-126]

+  it('should block dangerous stylesheet href schemes for preload strategies', async () => {
+    const critters = new Critters({ preload: 'js' });
+    critters.readFile = () => `* { background: red }`;
+    const html = await critters.process(`
+      <html>
+        <head>
+          <link rel=stylesheet href="javascript:alert(1)">
+        </head>
+        <body>
+        </body>
+      </html>
+    `);
+
+    expect(html).not.toContain('javascript:alert(1)');
+    expect(html).not.toContain('data-href=');
+  });
Evidence
PR Compliance ID 4 requires test files to be named *.test.ts or *.test.tsx; this modified test
remains *.test.js while adding new test content.

AGENTS.md
packages/critters/test/security.test.js[111-126]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A modified test file uses a non-standard extension (`*.test.js`) instead of the required `*.test.ts` / `*.test.tsx` naming convention.

## Issue Context
The repository standardizes test naming for consistent tooling and discoverability.

## Fix Focus Areas
- packages/critters/test/security.test.js[108-132]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. lefthook.yml at repo root 📘 Rule violation ✓ Correctness
Description
A new lefthook.yml was added at the repository root, placing shared workspace tooling
configuration outside the documented tools/ location. This reduces monorepo structure consistency.
Code

lefthook.yml[R1-42]

+# EXAMPLE USAGE:
+#
+#   Refer for explanation to following link:
+#   https://lefthook.dev/configuration/
+#
+# pre-push:
+#   jobs:
+#     - name: packages audit
+#       tags:
+#         - frontend
+#         - security
+#       run: yarn audit
+#
+#     - name: gems audit
+#       tags:
+#         - backend
+#         - security
+#       run: bundle audit
+#
+# pre-commit:
+#   parallel: true
+#   jobs:
+#     - run: yarn eslint {staged_files}
+#       glob: "*.{js,ts,jsx,tsx}"
+#
+#     - name: rubocop
+#       glob: "*.rb"
+#       exclude:
+#         - config/application.rb
+#         - config/routes.rb
+#       run: bundle exec rubocop --force-exclusion {all_files}
+#
+#     - name: govet
+#       files: git ls-files -m
+#       glob: "*.go"
+#       run: go vet {files}
+#
+#     - script: "hello.js"
+#       runner: node
+#
+#     - script: "hello.go"
+#       runner: go run
Evidence
PR Compliance ID 1 requires shared workspace tooling to live under tools/; adding lefthook.yml
at the root introduces tooling configuration outside the documented structure.

AGENTS.md
lefthook.yml[1-42]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A new workspace tooling config file (`lefthook.yml`) was added at the repo root, outside the documented monorepo structure.

## Issue Context
The compliance checklist expects shared tooling to live under `tools/` for consistency.

## Fix Focus Areas
- lefthook.yml[1-42]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. csrf requires request token 📘 Rule violation ⛯ Reliability
Description
packages/next-csrf middleware now rejects requests unless a request token is supplied and matches
the cookie token, changing the behavior of exported csrf. This may be a breaking change for
existing consumers and should be reviewed for compatibility/migration surface.
Code

packages/next-csrf/src/middleware/csrf.ts[R118-130]

+    let cookieToken = cookie[tokenKey];
    const csrfSecret = cookie['csrfSecret'];
+    const requestToken = getRequestToken(req, tokenKey);

    // Check token exists in cookie
-    if (!token) {
+    if (!cookieToken) {
      throw createCsrfError(CsrfErrorCodes.MISSING_TOKEN, csrfErrorMessage);
    }

+    // Check request token exists in header/body/query
+    if (!requestToken) {
+      throw createCsrfError(CsrfErrorCodes.MISSING_REQUEST_TOKEN, csrfErrorMessage);
+    }
Evidence
PR Compliance ID 7 requires compatibility-first changes and avoiding unnecessary public API/behavior
breaks; the middleware’s validation behavior for non-ignored methods is now stricter by requiring a
request token in addition to the cookie token.

AGENTS.md
packages/next-csrf/src/middleware/csrf.ts[115-130]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The exported `csrf` middleware now requires a request token in addition to the cookie token, which can break existing integrations.

## Issue Context
The compliance checklist emphasizes compatibility-first changes and minimizing breaking behavior changes unless clearly justified.

## Fix Focus Areas
- packages/next-csrf/src/middleware/csrf.ts[115-158]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (1)
8. App-router token sources diverge 🐞 Bug ✓ Correctness
Description
verifyCsrfToken only accepts the request token from a limited set of headers and omits
sources/headers supported elsewhere (e.g., the Pages Router middleware supports csrf-token and
body/query tokens). This creates inconsistent CSRF validation behavior between App Router and Pages
Router paths for the same application/client token submission strategy.
Code

packages/next-csrf/src/app-router.ts[R30-37]

+  // Get token from headers
+  const requestToken = headersList.get(tokenKey.toLowerCase()) || 
+                      headersList.get('x-csrf-token') || 
+                      headersList.get('x-xsrf-token');
+                      
+  if (!requestToken) {
+    throw new Error('Missing CSRF request token');
+  }
Evidence
The App Router verifier checks only three header names, while the Pages Router middleware explicitly
supports an additional header (csrf-token) and also supports body/query token submission; the
types/docs describe body/query submission as a supported model.

packages/next-csrf/src/app-router.ts[30-37]
packages/next-csrf/src/middleware/csrf.ts[39-69]
packages/next-csrf/src/types.ts[34-46]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`verifyCsrfToken` currently validates tokens only from a small set of headers, while the Pages Router middleware supports more header names and body/query token sources. This can lead to inconsistent CSRF behavior across routers.

### Issue Context
The library’s types/docs describe submitting the token via header/body/query. App Router verifier should either support the same sources or clearly document the restriction.

### Fix Focus Areas
- packages/next-csrf/src/app-router.ts[17-59]
- packages/next-csrf/src/middleware/csrf.ts[39-70]
- packages/next-csrf/src/types.ts[34-46]
- packages/next-csrf/README.md[51-92]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8485cab843

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

"cookie": "^1.1.1",
"cookie-signature": "^1.2.2",
"csrf": "^3.1.0",
"next": "^16.1.6"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep Next.js as a peer-only dependency

Move next out of dependencies, because this line forces every consumer to install a private Next 16 copy even when their app is on another supported peer version (for example Next 13/14). Since this package also declares next as a peer and imports next/headers, the extra nested install can bind runtime resolution to the wrong Next instance and create version-skew build/runtime failures that are very hard to diagnose.

Useful? React with 👍 / 👎.

*/`,
};
},
external: [],

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. tsup externals cleared 📘 Rule violation ⛯ Reliability

packages/next-csrf/tsup.config.ts now sets external: [], which can unintentionally bundle
framework/runtime dependencies and change build outputs for consumers. This risks breaking
established package-local build behavior.
Agent Prompt
## Issue description
`packages/next-csrf/tsup.config.ts` cleared the `external` list (`external: []`). This can cause bundling of dependencies that were previously externalized, potentially breaking consumer builds or runtime expectations.

## Issue Context
The monorepo compliance rules require preserving package-local tooling configuration compatibility.

## Fix Focus Areas
- packages/next-csrf/tsup.config.ts[3-13]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +1 to 7
// @vitest-environment happy-dom
import React from "react"
import { http, HttpResponse } from "msw"
import { useState } from "react"
import userEvent from "@testing-library/user-event"
import { render, screen, waitFor } from "@testing-library/react"
import { server, mockProviders } from "./helpers/mocks"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

2. providers.test.jsx not formatted 📘 Rule violation ✓ Correctness

Modified code in packages/next-auth/src/client/__tests__/providers.test.jsx uses double quotes and
appears to omit semicolons, conflicting with Prettier conventions. This introduces inconsistent
formatting in tests.
Agent Prompt
## Issue description
`packages/next-auth/src/client/__tests__/providers.test.jsx` includes formatting that conflicts with the repository’s Prettier conventions.

## Issue Context
Prettier conventions are required across the monorepo for consistency.

## Fix Focus Areas
- packages/next-auth/src/client/__tests__/providers.test.jsx[1-34]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +76 to 81
"dependencies": {
"cookie": "^1.1.1",
"cookie-signature": "^1.2.2",
"csrf": "^3.1.0",
"next": "^16.1.6"
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

3. Next shipped as dependency 🐞 Bug ⛯ Reliability

@opensourceframework/next-csrf now lists next in dependencies (while also in peerDependencies),
which can install a nested Next.js copy instead of using the host app’s Next.js. This can create
version conflicts and runtime/tooling breakage when the host app uses a different Next version.
Agent Prompt
### Issue description
`@opensourceframework/next-csrf` declares `next` in both `peerDependencies` and `dependencies`. This can lead to a nested Next.js installation and version conflicts in consuming apps.

### Issue Context
The package already targets Next.js consumers via `peerDependencies`; shipping `next` as a runtime dependency is likely unintended and risky.

### Fix Focus Areas
- packages/next-csrf/package.json[59-81]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines 39 to 49
```typescript
// lib/csrf.ts
import { nextCsrf } from '@opensourceframework/next-csrf';
// Usage example
import { createCSRF } from '@opensourceframework/next-csrf';

const { csrf, setup } = nextCsrf({
// Required: A secret key for signing cookies (use environment variable in production)
const csrf = createCSRF({
secret: process.env.CSRF_SECRET,

// Optional: Customize the token cookie name (default: 'XSRF-TOKEN')
tokenKey: 'XSRF-TOKEN',

// Optional: Custom error message (default: 'Invalid CSRF token')
csrfErrorMessage: 'Invalid CSRF token',

// Optional: Methods to ignore (default: ['GET', 'HEAD', 'OPTIONS'])
ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],

// Optional: Cookie options
cookieOptions: {
httpOnly: true,
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
},
});

export { csrf, setup };
// Use in API routes
export default csrf.protect(handler);
```

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

4. Readme documents wrong api 🐞 Bug ✓ Correctness

packages/next-csrf/README.md documents createCSRF / csrf.protect and a default tokenKey of
_csrf, but the package’s actual public entrypoint exports nextCsrf and defaults tokenKey to
XSRF-TOKEN. Users following the README will write imports/calls that fail and configure the wrong
cookie/header names.
Agent Prompt
### Issue description
The README documents a `createCSRF` / `csrf.protect` API and `_csrf` defaults that do not match the actual package exports/defaults.

### Issue Context
The package entrypoint exports `nextCsrf` and defaults `tokenKey` to `XSRF-TOKEN`. The README should not instruct users to import symbols that aren’t exported.

### Fix Focus Areas
- packages/next-csrf/README.md[37-103]
- packages/next-csrf/src/index.ts[32-72]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@riceharvest
Copy link
Owner Author

3 similar comments
@riceharvest
Copy link
Owner Author

@riceharvest
Copy link
Owner Author

@riceharvest
Copy link
Owner Author

…support

- Remove 'next' from dependencies to avoid nested copy (already in peerDependencies)
- Add 'csrf-token' header to verifyCsrfToken for consistency with Pages Router middleware
@kilo-code-bot
Copy link
Contributor

kilo-code-bot bot commented Mar 15, 2026

Code Review Summary

Status: No Issues Found | Recommendation: Merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 0
Files Reviewed (2 files)
  • packages/next-csrf/src/app-router.ts - Added support for 'csrf-token' header
  • packages/next-csrf/package.json - Removed 'next' from dependencies, now in peerDependencies

@riceharvest
Copy link
Owner Author

@riceharvest
Copy link
Owner Author

Superseded by #59 (squash merge of all modernization PRs). Changes included in main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant