Skip to content

V2#43

Merged
dev-davexoyinbo merged 23 commits into
mainfrom
v2
May 25, 2026
Merged

V2#43
dev-davexoyinbo merged 23 commits into
mainfrom
v2

Conversation

@dev-davexoyinbo

Copy link
Copy Markdown
Contributor

No description provided.

@qodo-code-review

Copy link
Copy Markdown

Review Summary by Qodo

v2.0.0: Schema validation with Zod, refactored providers, and new composables

✨ Enhancement 🧪 Tests 📝 Documentation

Grey Divider

Walkthroughs

Description
• **Major version bump to v2.0.0** with comprehensive schema validation support using Zod
• **Schema validation pipeline**: Build-time conversion of Zod schemas to JSON Schema, runtime
  reconstruction via z.fromJSONSchema(), and per-provider schema configuration
• **LocalAuthProvider refactored**: Removed hardcoded principal/password field mapping; now
  accepts flexible Record with Zod schema validation via schemas.login and schemas.user
• **New composables**: useAuthLogin() for typed login methods, useAuthUser() for user state
  access, useAuthToken() for token management
• **Auth plugin property renamed**: loggedInisLoggedIn for consistency across plugin,
  middleware, and composables
• **Schema utilities module**: New schema-utils.ts with collectSchemas(),
  stripSchemasFromProviders(), renderAuthSchemasRuntime(), and renderAuthSchemasTypes() for
  build-time code generation
• **Runtime auth schemas store**: New auth-schemas.ts module providing authSchemas store and
  defineAuthSchemas() helper for runtime schema access
• **OAuth providers enhanced**: GoogleAuthProvider and GithubAuthProvider now support optional
  schemas.user validation
• **Error handling improvements**: Standardized error responses in login and refresh endpoints with
  proper HTTP status codes and field-level error reporting
• **Comprehensive test coverage**: 15+ new test files covering unit tests (auth provider methods,
  schema utilities, token utilities, helpers), E2E tests (local auth, schema validation, middleware,
  composables), and test fixtures with mock API endpoints
• **Documentation**: Complete README rewrite with schema validation guide, migration guide for
  v1→v2, and new AGENTS.md developer guide covering architecture and maintenance
• **Build-time schema generation**: Module now generates virtual #auth-schemas module and
  TypeScript definitions at build time
Diagram
flowchart LR
  A["Zod Schemas<br/>in Config"] -->|Build Time| B["collectSchemas()"]
  B -->|Convert| C["JSON Schema"]
  C -->|Generate| D["Virtual Module<br/>#auth-schemas"]
  D -->|Runtime| E["z.fromJSONSchema()"]
  E -->|Validate| F["Login/User Data"]
  
  G["LocalAuthProvider"] -->|Flexible Body| H["validateRequestBody()"]
  H -->|Zod Schema| I["Field Errors"]
  
  J["Auth Plugin"] -->|Renamed| K["isLoggedIn"]
  K -->|Used by| L["Composables<br/>useAuthUser"]
  L -->|Access| M["User State"]

Loading

File Changes

1. test/unit/auth-provider-methods.test.ts 🧪 Tests +286/-0

AuthProvider methods unit test suite

• New comprehensive unit tests for AuthProvider class methods (provider(), getUserFromEvent(),
 logoutFromEvent(), refreshTokensFromEvent())
• Tests cover token reading from cookies, provider lookup, error handling, and cookie clearing
• Uses Vitest with h3 mock handlers to simulate HTTP events

test/unit/auth-provider-methods.test.ts


2. test/unit/schema-utils.test.ts 🧪 Tests +323/-0

Schema utilities unit test suite

• New unit tests for schema collection and rendering utilities (collectSchemas,
 stripSchemasFromProviders, renderAuthSchemasRuntime, renderAuthSchemasTypes)
• Tests verify Zod schema conversion to JSON Schema, TypeScript type generation, and schema
 extraction from provider configs
• Covers edge cases like empty schemas, multiple providers, and type inference

test/unit/schema-utils.test.ts


3. test/local-auth.test.ts 🧪 Tests +182/-0

Local auth E2E integration tests

• E2E tests for local authentication API routes (login, logout, user, refresh)
• Tests schema validation, field errors, cookie management, and token refresh
• Uses Nuxt test utils to spin up a fixture server

test/local-auth.test.ts


View more (47)
4. src/runtime/plugin/auth.ts ✨ Enhancement +18/-18

Rename loggedIn to isLoggedIn, support flexible login data

• Renamed loggedIn property to isLoggedIn throughout the auth plugin for consistency
• Updated all state references and computed properties to use the new name
• Changed login data parameter type from Record to Record to support flexible schemas

src/runtime/plugin/auth.ts


5. test/token.test.ts 🧪 Tests +179/-0

Token utility methods unit tests

• New unit tests for token utility methods on AuthProvider (getTokensFromEvent,
 getProviderKeyFromEvent, setProviderTokensToCookies, deleteProviderTokensFromCookies, getTokenNames)
• Tests cookie reading/writing, expiry handling, and token name configuration

test/token.test.ts


6. src/runtime/providers/LocalAuthProvider.ts ✨ Enhancement +31/-38

LocalAuthProvider schema validation and flexible login fields

• Removed hardcoded principal and password field mapping from signIn.body config
• Added support for Zod schema validation via schemas.login and schemas.user
• Login method now accepts flexible Record and forwards body as-is to backend
• validateRequestBody() now uses Zod schema validation instead of hardcoded field checks
• fetchUserData() validates user response against schemas.user if configured

src/runtime/providers/LocalAuthProvider.ts


7. src/schema-utils.ts ✨ Enhancement +155/-0

Schema collection and code generation utilities

• New utility module for collecting Zod schemas from provider configs and converting to JSON Schema
• Exports collectSchemas() to extract login/user schemas from all providers
• Exports stripSchemasFromProviders() to remove schemas before serialization
• Exports renderAuthSchemasRuntime() to generate runtime schema module with z.fromJSONSchema()
• Exports renderAuthSchemasTypes() to generate TypeScript type definitions from JSON schemas

src/schema-utils.ts


8. test/unit/local-auth-provider.test.ts 🧪 Tests +139/-0

LocalAuthProvider validation unit tests

• New unit tests for LocalAuthProvider.validateRequestBody() with Zod schema validation
• Tests valid/invalid email, password length constraints, and field error reporting
• Tests provider construction and default options merging

test/unit/local-auth-provider.test.ts


9. test/unit/auth-schemas.test.ts 🧪 Tests +96/-0

Auth schemas store unit tests

• New unit tests for authSchemas store and defineAuthSchemas() helper
• Tests schema storage by provider and key, independent schema management, and overwriting

test/unit/auth-schemas.test.ts


10. test/unit/helpers.test.ts 🧪 Tests +95/-0

Helper function unit tests

• New unit tests for getRecursiveProperty() helper function
• Tests top-level access, nested dot-notation paths, array indexing, missing keys, and custom
 separators

test/unit/helpers.test.ts


11. test/schema.test.ts 🧪 Tests +113/-0

Schema validation E2E tests

• E2E tests for schema validation on login and user endpoints
• Tests valid/invalid email format, password length constraints, and field error responses
• Tests user schema validation on the /api/auth/user endpoint

test/schema.test.ts


12. src/module.ts ✨ Enhancement +37/-13

Module build-time schema generation and virtual module setup

• Added schema collection and code generation at build time via collectSchemas() and
 renderAuthSchemasRuntime()
• Generates virtual module #auth-schemas with runtime schema definitions
• Generates TypeScript definitions file for schema types
• Strips schemas from serialized config before storing in runtimeConfig
• Moved ModuleProvidersOptions type to schema-utils.ts

src/module.ts


13. test/middleware.test.ts 🧪 Tests +87/-0

Route middleware E2E tests

• E2E tests for auth and auth-guest route middlewares
• Tests redirect behavior for protected routes, guest-only routes, and public routes

test/middleware.test.ts


14. test/composables.test.ts 🧪 Tests +72/-0

Auth composables E2E tests

• E2E tests for useAuthUser() composable
• Tests isLoggedIn state before/after login and user data matching

test/composables.test.ts


15. src/runtime/providers/GoogleAuthProvider.ts ✨ Enhancement +19/-8

GoogleAuthProvider schema validation support

• Added schemas config option with optional user schema
• fetchUserData() now validates user response against schemas.user if configured
• Removed AuthLoginData interface extension; GoogleAuthLoginData now only has optional
 redirectUrl
• Added Zod error flattening for field-level error reporting

src/runtime/providers/GoogleAuthProvider.ts


16. playground/nuxt.config.ts ⚙️ Configuration changes +17/-3

Playground config updated with schema definitions

• Added Zod schema definitions for login and user data
• Removed signIn.body field mapping config
• Added schemas.login and schemas.user to local provider config
• Added schemas.user to github and google provider configs

playground/nuxt.config.ts


17. src/runtime/providers/GithubAuthProvider.ts ✨ Enhancement +19/-5

GithubAuthProvider schema validation support

• Added schemas config option with optional user schema
• fetchUserData() now validates user response against schemas.user if configured
• Removed AuthLoginData interface extension; GithubAuthLoginData now only has optional
 redirectUrl
• Added Zod error flattening for field-level error reporting

src/runtime/providers/GithubAuthProvider.ts


18. test/fixtures/auth/nuxt.config.ts 🧪 Tests +58/-0

Test fixture Nuxt configuration

• New test fixture Nuxt config with local auth provider configured
• Includes Zod schemas for login and user validation
• Points to mock API endpoints for testing

test/fixtures/auth/nuxt.config.ts


19. src/runtime/models.ts ✨ Enhancement +6/-6

Auth models updated for schema support

• Removed AuthLoginData interface; login methods now accept Record
• Changed AuthUser from empty interface to generic type inferred from Zod schema
• Updated AuthState to use isLoggedIn instead of loggedIn

src/runtime/models.ts


20. src/runtime/server/api/login.post.ts Error handling +11/-3

Login endpoint error handling improvements

• Destructured provider from request body for cleaner code
• Added try-catch around provider lookup with proper error response
• Returns 400 status with field error format when provider not found

src/runtime/server/api/login.post.ts


21. src/runtime/server/api/refresh.post.ts Error handling +11/-5

Refresh endpoint error handling standardization

• Changed error responses from Promise.reject to proper HTTP 401/400 responses
• Added ErrorResponse type for consistent error format
• Returns structured error with message and data fields

src/runtime/server/api/refresh.post.ts


22. src/runtime/plugin/auth-fetch.ts ✨ Enhancement +2/-2

Auth fetch plugin property rename

• Updated to use isLoggedIn instead of loggedIn from auth plugin

src/runtime/plugin/auth-fetch.ts


23. src/runtime/auth-schemas.ts ✨ Enhancement +27/-0

Runtime auth schemas store module

• New module providing authSchemas store for runtime schema access
• Exports defineAuthSchemas() helper to populate schemas from nested record
• Uses Map-based storage for provider/key schema lookup

src/runtime/auth-schemas.ts


24. src/runtime/composables/useAuthLogin.ts ✨ Enhancement +20/-0

useAuthLogin composable with typed login methods

• New composable providing typed login functions (localLogin, googleLogin, githubLogin)
• localLogin validates input against loginSchemas.local if available
• Returns promises from underlying auth.login() calls

src/runtime/composables/useAuthLogin.ts


25. vitest.config.ts ⚙️ Configuration changes +24/-0

Vitest configuration for unit tests

• New Vitest configuration with setup file and thread pool settings
• Provides alias for #auth-schemas virtual module stub for unit tests

vitest.config.ts


26. src/runtime/middleware/auth.ts ✨ Enhancement +2/-2

Auth middleware property rename

• Updated to use isLoggedIn instead of loggedIn from auth plugin

src/runtime/middleware/auth.ts


27. src/runtime/middleware/auth-guest.ts ✨ Enhancement +2/-2

Auth guest middleware property rename

• Updated to use isLoggedIn instead of loggedIn from auth plugin

src/runtime/middleware/auth-guest.ts


28. test/fixtures/auth/server/plugins/suppress-listening.ts 🧪 Tests +11/-0

Test fixture server plugin for output suppression

• New Nitro plugin to suppress "Listening on..." console output during tests

test/fixtures/auth/server/plugins/suppress-listening.ts


29. test/fixtures/basic/server/plugins/suppress-listening.ts 🧪 Tests +11/-0

Test fixture server plugin for output suppression

• New Nitro plugin to suppress "Listening on..." console output during tests

test/fixtures/basic/server/plugins/suppress-listening.ts


30. test/fixtures/auth/server/api/mock/user.get.ts 🧪 Tests +10/-0

Mock user API endpoint for tests

• New mock API endpoint returning authenticated user data
• Validates authorization header contains expected mock tokens

test/fixtures/auth/server/api/mock/user.get.ts


31. test/fixtures/auth/server/api/mock/refresh.post.ts 🧪 Tests +10/-0

Mock refresh token API endpoint for tests

• New mock API endpoint for token refresh
• Validates refresh token and returns new access/refresh tokens

test/fixtures/auth/server/api/mock/refresh.post.ts


32. test/fixtures/auth/server/api/mock/signin.post.ts 🧪 Tests +10/-0

Mock signin API endpoint for tests

• New mock API endpoint for local authentication
• Validates email_address and password fields, returns mock tokens

test/fixtures/auth/server/api/mock/signin.post.ts


33. test/setup.ts 🧪 Tests +8/-0

Vitest setup file for test output control

• New Vitest setup file to suppress "Listening on..." console output from test server

test/setup.ts


34. src/runtime/composables/useAuthToken.ts ✨ Enhancement +14/-0

useAuthToken composable for token access

• New composable providing access to token-related properties and methods
• Exports token, refreshToken, tokenType, provider, tokenNames, and refreshTokens

src/runtime/composables/useAuthToken.ts


35. src/runtime/composables/useAuthUser.ts ✨ Enhancement +11/-0

useAuthUser composable for user access

• New composable providing access to user-related properties and methods
• Exports user, isLoggedIn, and refreshUser

src/runtime/composables/useAuthUser.ts


36. test/unit/__mocks__/auth-schemas.ts 🧪 Tests +4/-0

Mock auth schemas module for unit tests

• New mock stub for #auth-schemas virtual module used in unit tests
• Provides empty loginSchemas and userSchemas objects

test/unit/mocks/auth-schemas.ts


37. test/fixtures/auth/server/api/mock/echo-headers.get.ts 🧪 Tests +5/-0

Mock echo headers API endpoint for tests

• New mock API endpoint echoing request authorization header

test/fixtures/auth/server/api/mock/echo-headers.get.ts


38. test/fixtures/auth/server/api/mock/logout.post.ts 🧪 Tests +3/-0

Mock logout API endpoint for tests

• New mock API endpoint for logout

test/fixtures/auth/server/api/mock/logout.post.ts


39. playground/components/TestNavigations.vue ✨ Enhancement +14/-34

Playground component updated for new login schema

• Updated login call to use email_address field instead of principal
• Minor formatting cleanup (self-closing tags, spacing)

playground/components/TestNavigations.vue


40. test/fixtures/auth/pages/status.vue 🧪 Tests +10/-0

Test fixture status page

• New test page displaying login status and user data
• Uses useAuthUser() composable with test IDs for assertions

test/fixtures/auth/pages/status.vue


41. test/fixtures/auth/pages/echo.vue 🧪 Tests +6/-0

Test fixture echo page

• New test page echoing authorization headers via mock API

test/fixtures/auth/pages/echo.vue


42. test/fixtures/auth/pages/login.vue 🧪 Tests +4/-0

Test fixture login page

• New test page with auth-guest middleware

test/fixtures/auth/pages/login.vue


43. test/fixtures/auth/pages/protected.vue 🧪 Tests +4/-0

Test fixture protected page

• New test page with auth middleware

test/fixtures/auth/pages/protected.vue


44. test/fixtures/auth/pages/index.vue 🧪 Tests +1/-0

Test fixture public page

• New test page for public route

test/fixtures/auth/pages/index.vue


45. README.md 📝 Documentation +370/-216

Comprehensive README rewrite with v2 documentation

• Complete rewrite with clearer structure and comprehensive documentation
• Added schema validation section explaining Zod integration
• Added migration guide for v1 → v2 breaking changes
• Documented all composables, server routes, plugins, and middleware
• Improved examples and configuration reference

README.md


46. playground/package.json Dependencies +2/-1

Add Zod dependency to playground

• Added zod@^4.4.3 as a dependency

playground/package.json


47. test/fixtures/auth/package.json 🧪 Tests +5/-0

Test fixture package configuration

• New package.json for test fixture

test/fixtures/auth/package.json


48. AGENTS.md 📝 Documentation +61/-0

Add comprehensive developer guide and architecture documentation

• New comprehensive developer guide documenting module architecture, layout, and key concepts
• Explains schema pipeline for Zod-to-JSON-Schema conversion and runtime reconstruction
• Details build commands, release workflow, and ESLint/code style conventions
• Lists important assumptions and gotchas for maintainers (stale docs, no formatter, Node version
 requirements)

AGENTS.md


49. package.json Dependencies +30/-52

Update version, dependencies, and package metadata for v2

• Version bumped from 1.0.2 to 2.0.0 with updated description emphasizing Zod schema validation and
 multi-provider support
• Keywords expanded and reorganized to include nuxt4, oauth, google-auth, zod,
 schema-validation, and composable names
• Added zod@4.4.3 as a direct dependency (required for z.toJSONSchema and z.fromJSONSchema)
• Added vitest configuration to disable concurrent test execution

package.json


50. CHANGELOG.md 📝 Documentation +20/-0

Document v2.0.0 release with breaking changes and features

• Added v2.0.0 release notes documenting breaking changes and new features
• Breaking changes: removed body: { principal, password } config in favor of schemas.login; Zod
 4 now required
• Features: open login body for local provider, per-provider Zod schema pipeline, build-time JSON
 Schema conversion, new composables (useAuthLogin, useAuthUser, useAuthToken), and server-side
 validation
• Added migration guide reference and marked v1.0.0 as initial release

CHANGELOG.md


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented May 25, 2026

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Weak OAuth state secret 🐞 Bug ⛨ Security
Description
GithubAuthProvider signs/verifies the OAuth state JWT with a hard-coded fallback "secret" when
HASHING_SECRET is falsy, so a missing/empty secret makes the state predictable and forgeable. This
can enable OAuth CSRF/state bypass and account takeover in real deployments.
Code

↗ src/runtime/providers/GithubAuthProvider.ts

Evidence
The provider explicitly uses || "secret" for both signing and verifying state, and the README
shows a configuration that can make HASHING_SECRET empty, triggering the fallback.

src/runtime/providers/GithubAuthProvider.ts[41-47]
src/runtime/providers/GithubAuthProvider.ts[88-93]
README.md[97-112]

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

## Issue description
`GithubAuthProvider` falls back to the literal string `"secret"` for signing/verifying OAuth `state` when `HASHING_SECRET` is empty. This makes the state token guessable/forgeable whenever users misconfigure or follow examples that default `HASHING_SECRET` to an empty string.

## Issue Context
The README example config sets `HASHING_SECRET: process.env.HASHING_SECRET || ""`, which is falsy and triggers the hard-coded fallback in the provider.

## Fix Focus Areas
- src/runtime/providers/GithubAuthProvider.ts[41-47]
- src/runtime/providers/GithubAuthProvider.ts[88-93]
- README.md[97-112]

## Proposed fix
1. Remove the `|| "secret"` fallback in both `jwt.sign` and `jwt.verify`.
2. Fail fast when GitHub provider is configured but `HASHING_SECRET` is missing/empty (throw a clear error at provider construction or module setup time).
3. Update README/playground examples to require an explicit secret (no empty-string fallback).

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


2. Refresh provider crash 🐞 Bug ☼ Reliability
Description
/api/auth/refresh calls authClient.provider(providerKey) directly; if the auth:provider cookie
is an unregistered key, AuthProvider.provider() throws and the route returns a 500. This is
inconsistent with /api/auth/login, which already catches unknown providers and returns a 400
ErrorResponse.
Code

src/runtime/server/api/refresh.post.ts[R20-26]

Evidence
refresh.post.ts calls provider() without guarding; provider() is implemented to throw when the key
is missing. login.post.ts demonstrates the intended guarded pattern for the same operation.

src/runtime/server/api/refresh.post.ts[20-26]
src/runtime/providers/AuthProvider.ts[61-67]
src/runtime/server/api/login.post.ts[33-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
`/api/auth/refresh` does an unconditional `authClient.provider(providerKey)` based on a client-controlled cookie value. When the cookie contains an unknown provider key, `AuthProvider.provider()` throws, producing a 500 instead of a controlled 4xx response.

## Issue Context
`/api/auth/login` already wraps `authClient.provider(...)` in try/catch and returns a 400 with a structured ErrorResponse; `/api/auth/refresh` should behave the same.

## Fix Focus Areas
- src/runtime/server/api/refresh.post.ts[20-26]
- src/runtime/providers/AuthProvider.ts[61-67]
- src/runtime/server/api/login.post.ts[33-42]

## Proposed fix
1. Wrap `authClient.provider(providerKey)` in try/catch.
2. On error: set an appropriate status (likely 400), return an `ErrorResponse` shaped like login.post.ts, and optionally clear auth cookies to self-heal corrupted state.

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



Remediation recommended

3. Single quotes, no semicolons 📘 Rule violation ⚙ Maintainability
Description
New/modified source files introduce single-quoted strings and omit trailing semicolons, diverging
from the repository’s documented formatting conventions. This creates inconsistent style and review
churn because stylistic ESLint rules are disabled.
Code

test/composables.test.ts[R1-7]

Evidence
PR Compliance ID 6 requires new/modified code to match the existing double-quote +
trailing-semicolon style. The added test/config files use single quotes (e.g., from 'vitest') and
omit semicolons across statements.

AGENTS.md: Match Existing Source Formatting: Double Quotes and Trailing Semicolons
test/composables.test.ts[1-20]
vitest.config.ts[1-24]
test/fixtures/auth/nuxt.config.ts[1-30]

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

## Issue description
Several newly added/modified files use single quotes and omit trailing semicolons, conflicting with the repo convention of double quotes + semicolons.

## Issue Context
Per the compliance checklist, formatting consistency is enforced by contributor discipline (stylistic ESLint rules are off).

## Fix Focus Areas
- test/composables.test.ts[1-72]
- test/local-auth.test.ts[1-182]
- test/middleware.test.ts[1-87]
- test/schema.test.ts[1-113]
- vitest.config.ts[1-24]
- test/fixtures/auth/nuxt.config.ts[1-58]
- test/fixtures/auth/server/api/mock/echo-headers.get.ts[1-5]
- test/fixtures/auth/server/api/mock/logout.post.ts[1-3]
- test/fixtures/auth/server/api/mock/refresh.post.ts[1-10]
- test/fixtures/auth/server/api/mock/signin.post.ts[1-10]
- test/fixtures/auth/server/api/mock/user.get.ts[1-10]
- test/fixtures/auth/server/plugins/suppress-listening.ts[1-11]
- test/fixtures/basic/server/plugins/suppress-listening.ts[1-11]
- test/setup.ts[1-8]

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


4. New tests boot Nuxt 📘 Rule violation ➹ Performance
Description
New tests import @nuxt/test-utils/e2e and spin up a Nuxt server fixture, which is discouraged for
unit tests and makes the suite heavier/slower. These should be rewritten as lightweight unit tests
or clearly segregated as e2e/integration tests.
Code

test/composables.test.ts[R1-4]

Evidence
PR Compliance ID 8 forbids using @nuxt/test-utils for new unit tests. The new test files import
@nuxt/test-utils/e2e and call setup(...), which boots Nuxt and violates the
lightweight-unit-test requirement.

AGENTS.md: New Unit Tests Should Avoid @nuxt/test-utils Imports (Keep Unit Tests Lightweight)
test/composables.test.ts[1-29]
test/local-auth.test.ts[1-29]
test/middleware.test.ts[1-29]
test/schema.test.ts[1-16]

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

## Issue description
Several new tests import `@nuxt/test-utils/e2e` and call `setup(...)`, which boots Nuxt for tests that appear to be validating composables/middleware behavior.

## Issue Context
The compliance checklist requires keeping unit tests lightweight and avoiding `@nuxt/test-utils` in unit tests to prevent slow suites.

## Fix Focus Areas
- test/composables.test.ts[1-30]
- test/local-auth.test.ts[1-30]
- test/middleware.test.ts[1-30]
- test/schema.test.ts[1-16]
- test/fixtures/auth/**[1-200]

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


5. Refresh errors become 500 🐞 Bug ☼ Reliability
Description
/api/auth/refresh awaits refreshTokensFromEvent() without a try/catch, so provider refresh
failures (including LocalAuthProvider rejecting when refreshToken is not configured) bubble up as
500s. This prevents clients from receiving a structured ErrorResponse and makes refresh failures
harder to handle reliably.
Code

src/runtime/server/api/refresh.post.ts[R28-40]

Evidence
The refresh handler has no error handling around refreshTokensFromEvent(), while
LocalAuthProvider.refreshTokens can explicitly reject when refresh is disabled, leading to an
uncaught exception path.

src/runtime/server/api/refresh.post.ts[28-40]
src/runtime/providers/LocalAuthProvider.ts[194-197]

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

## Issue description
`/api/auth/refresh` does not handle errors thrown/rejected by `authClient.refreshTokensFromEvent(event)`; errors bubble out and become 500 responses.

## Issue Context
At least one built-in provider can reject refresh when not configured (LocalAuthProvider). Other provider implementations can also throw for invalid/expired refresh tokens.

## Fix Focus Areas
- src/runtime/server/api/refresh.post.ts[28-40]
- src/runtime/providers/LocalAuthProvider.ts[194-197]

## Proposed fix
1. Wrap the `refreshTokensFromEvent` call in try/catch.
2. Map known error cases to controlled status codes and an `ErrorResponse` (e.g., 400 for "refreshToken not configured", 401 for invalid/expired refresh token, etc.).
3. Consider clearing cookies on auth-invalid refresh errors to avoid repeated failures.

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


Grey Divider

Qodo Logo

Comment on lines 20 to 26
const provider = authClient.provider(providerKey);
if (!provider || !provider.refreshTokens) {
return Promise.reject(
"refresh tokens is not implemented for this provider"
);
setResponseStatus(event, 400);
return {
message: "refresh tokens is not implemented for this provider",
} satisfies ErrorResponse;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

2. Refresh provider crash 🐞 Bug ☼ Reliability

/api/auth/refresh calls authClient.provider(providerKey) directly; if the auth:provider cookie
is an unregistered key, AuthProvider.provider() throws and the route returns a 500. This is
inconsistent with /api/auth/login, which already catches unknown providers and returns a 400
ErrorResponse.
Agent Prompt
## Issue description
`/api/auth/refresh` does an unconditional `authClient.provider(providerKey)` based on a client-controlled cookie value. When the cookie contains an unknown provider key, `AuthProvider.provider()` throws, producing a 500 instead of a controlled 4xx response.

## Issue Context
`/api/auth/login` already wraps `authClient.provider(...)` in try/catch and returns a 400 with a structured ErrorResponse; `/api/auth/refresh` should behave the same.

## Fix Focus Areas
- src/runtime/server/api/refresh.post.ts[20-26]
- src/runtime/providers/AuthProvider.ts[61-67]
- src/runtime/server/api/login.post.ts[33-42]

## Proposed fix
1. Wrap `authClient.provider(providerKey)` in try/catch.
2. On error: set an appropriate status (likely 400), return an `ErrorResponse` shaped like login.post.ts, and optionally clear auth cookies to self-heal corrupted state.

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

@dev-davexoyinbo
dev-davexoyinbo merged commit ff1cb1c into main May 25, 2026
6 checks passed
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 1.6.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant