Skip to content

refactor(core): improve user messages with clearer context#189

Merged
halvaradop merged 6 commits into
masterfrom
feat/improve-error-ctx
Jun 17, 2026
Merged

refactor(core): improve user messages with clearer context#189
halvaradop merged 6 commits into
masterfrom
feat/improve-error-ctx

Conversation

@halvaradop

@halvaradop halvaradop commented Jun 13, 2026

Copy link
Copy Markdown
Member

Description

This pull request refactors and standardizes error handling across the authentication flows in @aura-stack/auth.

The changes improve error reporting by providing clearer user-facing messages and more structured diagnostic information for developers. All authentication errors now extend the AuraAuthError base class, creating a consistent error model throughout the library.

The new error system includes structured metadata such as:

  • type
  • code
  • message
  • userMessage

This information enables applications to present meaningful messages to end users while also providing developers with the context needed to diagnose and resolve issues.

As part of this work, @aura-stack/router has been upgraded to v0.9.0, which provides the underlying error-handling infrastructure required for this refactor.

Key Changes

  • Standardized error handling across authentication flows.
  • Introduced the AuraAuthError base class.
  • Added structured error metadata (type, code, message, and userMessage).
  • Improved error consistency throughout the library.
  • Enhanced user-facing messages with clearer guidance for configuration and validation issues.
  • Upgraded @aura-stack/router to v0.9.0 to support the new error architecture.

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Standardized error handling across OAuth, sign-in, sign-up, and session management flows with consistent error codes and messages.
    • Improved error response structure with specific, actionable error codes for better debugging and error handling in client applications.
  • Chores

    • Updated @aura-stack/router dependency to ^0.9.0.
    • Updated authentication version to 0.7.2.

@vercel

vercel Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
auth Skipped Skipped Jun 17, 2026 6:06pm

@coderabbitai

coderabbitai Bot commented Jun 13, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Replaces all legacy error classes (OAuthProtocolError, AuthInternalError, AuthSecurityError, AuthValidationError, AuthClientError, AuthInvalidConfigurationError, AuthJoseInitializationError) with a unified AuraAuthError backed by an ERROR_CATALOG of 60+ structured error codes. Every module that threw or detected the old types is updated to use AuraAuthError and isAuraAuthError, the router error handler is simplified to delegate to error.toResponse(), and all tests are updated to assert the new error codes, types, and HTTP statuses.

Changes

Aura Error System Refactor

Layer / File(s) Summary
New AuraAuthError System Definition
packages/core/src/shared/errors.ts, packages/core/src/shared/utils.ts, packages/core/deno.json, packages/core/package.json
errors.ts is replaced wholesale with AuraErrorCode catalog, ERROR_CATALOG record, AuraAuthError class with toResponse(), and isAuraAuthError guard. formatZodError is removed from utils.ts, AURA_AUTH_VERSION bumped to 0.7.2, and @aura-stack/router dependency bumped to ^0.9.0.
Router Error Handler Simplification
packages/core/src/router/errorHandler.ts
Replaces ~55 lines of bespoke error-branch response shaping with a single isAuraAuthError check that calls error.toResponse(), plus unchanged generic SERVER_ERROR fallback.
Session, CSRF, Cookie, and Security Token Handling
packages/core/src/session/stateless.ts, packages/core/src/session/strategy.ts, packages/core/src/session/jose-manager.ts, packages/core/src/shared/crypto.ts, packages/core/src/cookie.ts
All CSRF/session/cookie error paths switch from AuthSecurityError/AuthInvalidConfigurationError to AuraAuthError with structured codes (SESSION_NOT_FOUND, CSRF_TOKEN_MISSING, CSRF_DOUBLE_SUBMIT_FAILED, CSRF_TOKEN_MISMATCH, JWT_INVALID_MODE, PKCE_VERIFIER_INVALID, COOKIE_NOT_FOUND, etc.).
JOSE and Cryptographic Initialization
packages/core/src/jose.ts
JWT expiration, PEM key mode mismatches, missing secrets, and salt validation failures now throw AuraAuthError with distinct codes and cause chains.
OAuth Callback Flow Error Handling
packages/core/src/actions/callback/access-token.ts, packages/core/src/actions/callback/callback.ts, packages/core/src/actions/callback/userinfo.ts
Token exchange, state mismatch, open-redirect, and userinfo request failures all replaced with AuraAuthError specific codes. The callbackConfig OAuthAuthorizationErrorResponse pre-handler middleware is removed.
Sign-In Authorization and OAuth Provider Error Handling
packages/core/src/actions/signIn/authorization-url.ts, packages/core/src/actions/signIn/authorization.ts, packages/core/src/oauth/index.ts
Authorization URL construction, trusted-origin validation, and OAuth provider config/schema failures now throw AuraAuthError with INVALID_OAUTH_PROVIDER_URL_CONFIG, INVALID_OAUTH_PROVIDER_SCHEMA_CONFIG, INVALID_AUTH_CONFIGURATION, INVALID_TRUSTED_ORIGIN, INVALID_ENVIRONMENT_CONFIGURATION, and DUPLICATED_OAUTH_PROVIDER_ID.
Validator and Schema Registry Error Handling
packages/core/src/validator/registry.ts, packages/core/src/validator/validator.ts, packages/core/src/actions/signUp/signUp.ts
Schema derivation and parse failures use AuraAuthError (SCHEMA_UNSUPPORTED, SCHEMA_PARSER_FAILED with cause). Internal throwValidationError helper removed. signUp.ts drops the z.object({}) default body schema fallback.
API Endpoints Error Handling Migration
packages/core/src/api/credentials.ts, packages/core/src/api/signIn.ts, packages/core/src/api/signOut.ts, packages/core/src/api/signUp.ts, packages/core/src/api/updateSession.ts, packages/core/src/client/client.ts
All API handlers switch from isAuthErrorWithCode/instanceof AuthValidationError to isAuraAuthError, extract code/userMessage, and throw typed AuraAuthError codes. signOut failure response adds redirectURL: null.
Test Assertion Updates
packages/core/test/actions/callback/*, packages/core/test/actions/signIn/*, packages/core/test/actions/signOut/*, packages/core/test/actions/signUp/*, packages/core/test/api/*, packages/core/test/instance.test.ts, packages/core/test/jose.test.ts, packages/core/test/oauth.test.ts
All test assertions updated to expect new AuraAuthError codes, type fields (AUTH_FLOW, PROTOCOL, VALIDATION), updated HTTP statuses (401/403/500), and new catalog-sourced userMessage strings.
Package and Config Updates
apps/nuxt/package.json
Removes postinstall and prepare scripts from the Nuxt app.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • aura-stack-ts/auth#130: Both PRs modify packages/core/src/router/errorHandler.ts's auth/validation error branching — the retrieved PR adds an AuthValidationError/IDENTITY_VALIDATION_FAILED 422 branch that this PR replaces with the unified isAuraAuthError delegation.
  • aura-stack-ts/auth#162: Both PRs touch packages/core/src/validator/registry.ts — the retrieved PR adds full schema validation/parse variants while this PR migrates those same schema-validation failures to AuraAuthError codes and removes the throwValidationError helper.
  • aura-stack-ts/auth#170: Both PRs modify credentials sign-in error handling in packages/core/src/api/credentials.ts, switching toward Aura-style error type detection and response shaping.

Suggested labels

refactor

🐇 Seven old error types, now just one!
A catalog of codes, all neatly spun.
AuraAuthError hops through every file,
With toResponse() serialized in style. 🎉
No more instanceof — just isAuraAuthError,
The warren of errors is tidy at last!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'refactor(core): improve user messages with clearer context' accurately summarizes the main objective: enhancing error handling to provide clearer user-facing messages and better context throughout the authentication flows.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/improve-error-ctx

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
packages/core/src/shared/utils.ts (1)

93-98: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Unresolved provider env placeholders still become a live Basic header.

Lines 94-95 fall back to the raw arguments when the env lookup misses. In packages/core/src/oauth/notion.ts, Lines 56-61, that turns absent NOTION_CLIENT_ID / NOTION_CLIENT_SECRET vars into literal credentials, so Line 97 never throws and the misconfiguration is only discovered after an outbound token request. This helper needs an explicit “resolve env key” vs “use literal credential” contract, and the fail-fast path should use a configuration-oriented Aura code instead of AUTH_BASIC_CREDENTIALS_INVALID.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/shared/utils.ts` around lines 93 - 98, The helper
createBasicAuthHeader currently falls back to the raw username/password when
getEnv returns undefined (getEnv(username) ?? username), which lets unresolved
env placeholders become live credentials; change the contract to require
resolved env values: call getEnv(username) and getEnv(password) and if either
returns undefined/null, do NOT use the literal argument — throw a
configuration-oriented error (replace AuraAuthError with a config error class
such as AuraConfigError) with a clear config-missing code (e.g.,
"CONFIG_ENV_VAR_MISSING") and message identifying which env key failed; ensure
createBasicAuthHeader, getEnv usage, and the thrown error class/name are updated
so callers like oauth/notion.ts fail fast on missing envs.
packages/core/src/api/signOut.ts (1)

60-64: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix failure response contract (redirectURL) and return an error status.

Line 63 uses redirectsURL (typo), and this failure toResponse currently returns default 200. That breaks response shape consistency and can mask failures at HTTP level.

Suggested fix
             toResponse: () => {
-                return Response.json({
-                    success: false,
-                    redirect: false,
-                    redirectsURL: null,
-                })
+                return Response.json(
+                    {
+                        success: false,
+                        redirect: false,
+                        redirectURL: null,
+                        error: { code, message },
+                    },
+                    { headers, status: 400 }
+                )
             },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/api/signOut.ts` around lines 60 - 64, The failure response
in signOut.ts returns the wrong field name and a 200 status; update the
Response.json call in the signOut (or its toResponse) failure branch to use the
correct redirectURL property (not redirectsURL) and return a non-200 HTTP status
(e.g., status: 500 or other appropriate error code) so the response shape and
status indicate failure; ensure the payload still contains success: false and
include an error message or null redirectURL as before.
packages/core/src/api/credentials.ts (1)

80-85: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Narrow the invalid-credentials branch to the explicit credentials error code.

Line 80 currently treats any AuraAuthError as invalid credentials. That mislabels unrelated auth/config/origin errors as INVALID_CREDENTIALS and returns the same 401 path.

Suggested fix
-        if (isAuraAuthError(error)) {
+        if (isAuraAuthError(error) && error.code === "AUTH_CREDENTIALS_INVALID") {
             logger?.log("INVALID_CREDENTIALS", {
                 severity: "warning",
                 structuredData: { path: "/signIn/credentials" },
             })
             return invalidCredentials
         }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/api/credentials.ts` around lines 80 - 85, The code
currently treats any AuraAuthError as invalid credentials; change the condition
so the invalid-credentials branch only triggers for the explicit credential
error code (e.g., check error.code or error.errorCode equals the project's
credential error constant) instead of any AuraAuthError. Concretely, update the
if around isAuraAuthError(error) to something like isAuraAuthError(error) &&
error.code === <CREDENTIALS_ERROR_CODE>, then call
logger?.log("INVALID_CREDENTIALS", ...) and return invalidCredentials; otherwise
let other AuraAuthError cases fall through or be handled separately.
packages/core/src/actions/callback/callback.ts (1)

41-53: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Don't report provider-declared OAuth errors as "missing parameters".

This branch runs when the callback contains an OAuth error payload from the provider, e.g. access_denied or server_error. Throwing AUTH_CALLBACK_MISSING_PARAMETERS turns an explicit upstream denial/failure into the wrong message and removes the distinction between "provider rejected the flow" and "the callback was malformed." Use a dedicated AuraAuthError code for authorization error responses instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/actions/callback/callback.ts` around lines 41 - 53, The
code currently detects an OAuth provider error via
OAuthAuthorizationErrorResponse.safeParse and then throws AuraAuthError with
code "AUTH_CALLBACK_MISSING_PARAMETERS"; change this to throw a distinct
authorization error that preserves provider details (e.g., throw new
AuraAuthError({ code: "AUTH_CALLBACK_AUTHORIZATION_ERROR", meta: { error,
error_description } })) so provider-declared errors (access_denied,
server_error) are not misreported as missing parameters; update the thrown error
in the same branch where OAuthAuthorizationErrorResponse, criticalAuthErrors,
and logger are used and ensure the logger still records severity and
structuredData.
packages/core/src/actions/callback/access-token.ts (1)

25-36: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't collapse every missing precondition into INVALID_OAUTH_PROVIDER_URL_CONFIG.

This guard also fires when clientSecret, code, or codeVerifier is missing, so callers will get a provider-URL error for failures that are unrelated to the provider URL. Split the URL-only validation from the general callback/config preconditions and map them to different catalog codes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/actions/callback/access-token.ts` around lines 25 - 36,
Split the single guard into two checks: first validate the provider-URL related
fields (e.g., redirectURI and any provider URL-specific input) and if those are
missing log structuredData and throw AuraAuthError with code
"INVALID_OAUTH_PROVIDER_URL_CONFIG"; then validate the remaining callback/config
preconditions (clientId, clientSecret, code, codeVerifier, accessToken) and if
any are missing log structuredData and throw a different AuraAuthError code such
as "INVALID_OAUTH_CONFIGURATION". Keep the same logger structuredData keys
(has_client_id, has_client_secret, has_access_token, has_redirect_uri, has_code,
has_code_verifier) and apply them to both checks so the logs show which specific
fields are absent; update the throw sites in access-token.ts accordingly.
🧹 Nitpick comments (1)
packages/core/test/actions/callback/access-token.test.ts (1)

66-68: ⚡ Quick win

These tests are over-coupled to mutable internal prose; assert stable error contract fields instead.

  • packages/core/test/actions/callback/access-token.test.ts#L66-L68: assert error code/type (or status+payload) rather than long internal message text.
  • packages/core/test/actions/callback/access-token.test.ts#L97-L99: same refactor—prefer contract fields over prose.
  • packages/core/test/actions/callback/access-token.test.ts#L135-L137: same refactor—replace exact full sentence assertion with stable identifiers.
  • packages/core/test/actions/callback/userinfo.test.ts#L117-L119: switch to checking stable error identifiers.
  • packages/core/test/actions/callback/userinfo.test.ts#L150-L152: switch to checking stable error identifiers.
  • packages/core/test/actions/callback/userinfo.test.ts#L177-L179: switch to checking stable error identifiers.
  • packages/core/test/actions/callback/userinfo.test.ts#L258-L260: switch to checking stable error identifiers.
  • packages/core/test/actions/signIn/authorization.test.ts#L110-L112: prefer code/type assertions for rejection paths.
  • packages/core/test/actions/signIn/authorization.test.ts#L151-L153: same refactor to stable contract assertions.
  • packages/core/test/actions/signIn/authorization.test.ts#L165-L167: same refactor to stable contract assertions.
  • packages/core/test/oauth.test.ts#L27-L29: assert stable structured error attributes instead of exact message.
  • packages/core/test/oauth.test.ts#L54-L56: assert stable structured error attributes instead of exact message.
  • packages/core/test/api/signOut.test.ts#L22-L24: assert stable error code/type for missing session token path.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/test/actions/callback/access-token.test.ts` around lines 66 -
68, Replace fragile assertions that match full error message prose with
assertions on stable error contract fields (e.g., error.code, error.type, or
status+payload) in the listed tests:
packages/core/test/actions/callback/access-token.test.ts (the rejects.toThrow at
L66-L68, and similar at L97-L99 and L135-L137),
packages/core/test/actions/callback/userinfo.test.ts (L117-L119, L150-L152,
L177-L179, L258-L260), packages/core/test/actions/signIn/authorization.test.ts
(L110-L112, L151-L153, L165-L167), packages/core/test/oauth.test.ts (L27-L29,
L54-L56), and packages/core/test/api/signOut.test.ts (L22-L24); locate the
Promise rejection checks (e.g., the .rejects.toThrow calls) and change them to
assert the error object has the expected stable fields (like
expect(err.code).toBe(...) or expect(err.type).toBe(...) or
expect(err.status).toBe(...) and/or inspect err.payload) instead of matching the
full human-readable message.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/actions/callback/access-token.ts`:
- Around line 70-94: The JSON.parse step (response.json()) needs its own
try/catch so parse failures are classified as response-format errors rather than
generic transport errors: wrap the response.json() call in a small try block and
if it throws, log via logger and throw an AuraAuthError with code
"INVALID_OAUTH_ACCESS_TOKEN_RES_FORMAT" in access-token.ts (affecting the logic
around OAuthAccessTokenResponse/OAuthAccessTokenErrorResponse handling), and
similarly throw "INVALID_OAUTH_USER_INFO_RES_FORMAT" in userinfo.ts (around the
OAuth user info response validation). Keep the outer try to handle
transport/network failures and preserve existing isAuraAuthError rethrows and
other error codes; only reclassify JSON parse exceptions to the new *_RES_FORMAT
codes and include the original parse error as the cause when creating the
AuraAuthError.

In `@packages/core/src/actions/signIn/authorization-url.ts`:
- Around line 23-27: The code currently constructs the provider URL with new
URL(baseURL) which can throw a native TypeError for malformed strings; wrap the
URL construction in a try/catch around the new URL(baseURL) call in the
authorization URL logic (the spot using authorizeConfig/baseURL and creating
url) and on any exception rethrow an AuraAuthError with code
"INVALID_OAUTH_PROVIDER_URL_CONFIG" (include the original error message/details
in the AuraAuthError payload or log) so malformed provider URLs surface as the
standardized AuraAuthError instead of leaking a native TypeError.

In `@packages/core/src/actions/signUp/signUp.ts`:
- Line 10: The fallback empty Zod schema uses z.object() which is not the
intended API in Zod v4; update the fallback in the sign-up action so that body:
config?.schema ?? z.object({}) uses an explicit empty shape. Locate the
occurrence of config?.schema and replace the z.object() fallback with
z.object({}) (e.g., in the signUp handler where body is assigned) to ensure a
proper empty-object schema.

In `@packages/core/src/api/signIn.ts`:
- Around line 77-80: When projecting AuraAuthError into API payloads, replace
uses of the internal error.message with the user-facing error.userMessage:
inside the isAuraAuthError(error) branches (e.g., in signIn.ts where code =
error.code and message = error.message), set message = error.userMessage; make
the same change in the corresponding Aura error branches in credentials.ts,
signOut.ts, signUp.ts, and updateSession.ts so each branch uses
error.userMessage when building the response object (preserve existing code =
error.code behavior and only swap the message source).

In `@packages/core/src/cookie.ts`:
- Around line 104-106: The current check in cookie handling only tests `if
(!cookies)` which misses empty arrays; update the condition where `cookies` is
validated (refer to the `cookies` variable and the throw of `AuraAuthError` with
code `"SET_COOKIE_NOT_FOUND"`) to treat an empty collection as "not found" as
well (e.g., check for `cookies` falsy OR `cookies.length === 0`) so that empty
responses trigger the `SET_COOKIE_NOT_FOUND` error instead of
`SET_COOKIE_INVALID_VALUE`.

In `@packages/core/src/shared/crypto.ts`:
- Around line 83-85: In verifyCSRF, the catch currently replaces every error
with AuraAuthError({ code: "CSRF_TOKEN_MISSING", cause: error }), which hides
explicit CSRF_TOKEN_MISMATCH errors; change the catch to rethrow the original
error when it's already an AuraAuthError (or when error.code ===
"CSRF_TOKEN_MISMATCH"), and only wrap/throw a new AuraAuthError with code
"CSRF_TOKEN_MISSING" for other unexpected failures—refer to the verifyCSRF
function and AuraAuthError usage to implement this conditional rethrowing logic
so mismatch errors are preserved.

In `@packages/core/src/shared/unstable_error.ts`:
- Around line 407-413: The CONFIG_BASE_URL_MISSING catalog entry currently has
empty message and userMessage which causes AuraAuthError.message to be blank and
toResponse() to emit an invalid empty-message response; update the
CONFIG_BASE_URL_MISSING object (the constant with key CONFIG_BASE_URL_MISSING)
to provide non-empty defaults for both message and userMessage (e.g. a concise
internal message and a user-facing string), keeping the type, statusCode, and
name unchanged so that AuraAuthError.message, toResponse(), and errorHandler.ts
produce a valid response (this same change should also be applied at the other
occurrence referenced around lines 729-733).

In `@packages/core/src/validator/registry.ts`:
- Around line 61-62: The three schema-type fallback throws that currently use
throw new AuraAuthError({ code: "SCHEMA_INVALID_MODE" }) are misclassifying
unsupported schema fallthroughs; replace those error instances so they throw
AuraAuthError with code "SCHEMA_UNSUPPORTED" instead (or alternatively add an
explicit runtime mode guard earlier if you intend to validate mode), i.e.,
locate each occurrence of throw new AuraAuthError({ code: "SCHEMA_INVALID_MODE"
}) in registry.ts (the schema-type fallback branches) and change the code value
to "SCHEMA_UNSUPPORTED".

---

Outside diff comments:
In `@packages/core/src/actions/callback/access-token.ts`:
- Around line 25-36: Split the single guard into two checks: first validate the
provider-URL related fields (e.g., redirectURI and any provider URL-specific
input) and if those are missing log structuredData and throw AuraAuthError with
code "INVALID_OAUTH_PROVIDER_URL_CONFIG"; then validate the remaining
callback/config preconditions (clientId, clientSecret, code, codeVerifier,
accessToken) and if any are missing log structuredData and throw a different
AuraAuthError code such as "INVALID_OAUTH_CONFIGURATION". Keep the same logger
structuredData keys (has_client_id, has_client_secret, has_access_token,
has_redirect_uri, has_code, has_code_verifier) and apply them to both checks so
the logs show which specific fields are absent; update the throw sites in
access-token.ts accordingly.

In `@packages/core/src/actions/callback/callback.ts`:
- Around line 41-53: The code currently detects an OAuth provider error via
OAuthAuthorizationErrorResponse.safeParse and then throws AuraAuthError with
code "AUTH_CALLBACK_MISSING_PARAMETERS"; change this to throw a distinct
authorization error that preserves provider details (e.g., throw new
AuraAuthError({ code: "AUTH_CALLBACK_AUTHORIZATION_ERROR", meta: { error,
error_description } })) so provider-declared errors (access_denied,
server_error) are not misreported as missing parameters; update the thrown error
in the same branch where OAuthAuthorizationErrorResponse, criticalAuthErrors,
and logger are used and ensure the logger still records severity and
structuredData.

In `@packages/core/src/api/credentials.ts`:
- Around line 80-85: The code currently treats any AuraAuthError as invalid
credentials; change the condition so the invalid-credentials branch only
triggers for the explicit credential error code (e.g., check error.code or
error.errorCode equals the project's credential error constant) instead of any
AuraAuthError. Concretely, update the if around isAuraAuthError(error) to
something like isAuraAuthError(error) && error.code ===
<CREDENTIALS_ERROR_CODE>, then call logger?.log("INVALID_CREDENTIALS", ...) and
return invalidCredentials; otherwise let other AuraAuthError cases fall through
or be handled separately.

In `@packages/core/src/api/signOut.ts`:
- Around line 60-64: The failure response in signOut.ts returns the wrong field
name and a 200 status; update the Response.json call in the signOut (or its
toResponse) failure branch to use the correct redirectURL property (not
redirectsURL) and return a non-200 HTTP status (e.g., status: 500 or other
appropriate error code) so the response shape and status indicate failure;
ensure the payload still contains success: false and include an error message or
null redirectURL as before.

In `@packages/core/src/shared/utils.ts`:
- Around line 93-98: The helper createBasicAuthHeader currently falls back to
the raw username/password when getEnv returns undefined (getEnv(username) ??
username), which lets unresolved env placeholders become live credentials;
change the contract to require resolved env values: call getEnv(username) and
getEnv(password) and if either returns undefined/null, do NOT use the literal
argument — throw a configuration-oriented error (replace AuraAuthError with a
config error class such as AuraConfigError) with a clear config-missing code
(e.g., "CONFIG_ENV_VAR_MISSING") and message identifying which env key failed;
ensure createBasicAuthHeader, getEnv usage, and the thrown error class/name are
updated so callers like oauth/notion.ts fail fast on missing envs.

---

Nitpick comments:
In `@packages/core/test/actions/callback/access-token.test.ts`:
- Around line 66-68: Replace fragile assertions that match full error message
prose with assertions on stable error contract fields (e.g., error.code,
error.type, or status+payload) in the listed tests:
packages/core/test/actions/callback/access-token.test.ts (the rejects.toThrow at
L66-L68, and similar at L97-L99 and L135-L137),
packages/core/test/actions/callback/userinfo.test.ts (L117-L119, L150-L152,
L177-L179, L258-L260), packages/core/test/actions/signIn/authorization.test.ts
(L110-L112, L151-L153, L165-L167), packages/core/test/oauth.test.ts (L27-L29,
L54-L56), and packages/core/test/api/signOut.test.ts (L22-L24); locate the
Promise rejection checks (e.g., the .rejects.toThrow calls) and change them to
assert the error object has the expected stable fields (like
expect(err.code).toBe(...) or expect(err.type).toBe(...) or
expect(err.status).toBe(...) and/or inspect err.payload) instead of matching the
full human-readable message.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 070c010d-9450-450a-bd03-d54f09121a37

📥 Commits

Reviewing files that changed from the base of the PR and between 6314709 and a053364.

📒 Files selected for processing (46)
  • packages/core/deno.json
  • packages/core/src/actions/callback/access-token.ts
  • packages/core/src/actions/callback/callback.ts
  • packages/core/src/actions/callback/userinfo.ts
  • packages/core/src/actions/signIn/authorization-url.ts
  • packages/core/src/actions/signIn/authorization.ts
  • packages/core/src/actions/signUp/signUp.ts
  • packages/core/src/api/credentials.ts
  • packages/core/src/api/signIn.ts
  • packages/core/src/api/signOut.ts
  • packages/core/src/api/signUp.ts
  • packages/core/src/api/updateSession.ts
  • packages/core/src/client/client.ts
  • packages/core/src/cookie.ts
  • packages/core/src/jose.ts
  • packages/core/src/oauth/index.ts
  • packages/core/src/router/errorHandler.ts
  • packages/core/src/session/jose-manager.ts
  • packages/core/src/session/stateless.ts
  • packages/core/src/session/strategy.ts
  • packages/core/src/shared/crypto.ts
  • packages/core/src/shared/errors.ts
  • packages/core/src/shared/unstable_error.ts
  • packages/core/src/shared/utils.ts
  • packages/core/src/validator/registry.ts
  • packages/core/src/validator/validator.ts
  • packages/core/test/actions/callback/access-token.test.ts
  • packages/core/test/actions/callback/callback.test.ts
  • packages/core/test/actions/callback/userinfo.test.ts
  • packages/core/test/actions/signIn/authorization.test.ts
  • packages/core/test/actions/signIn/signIn.test.ts
  • packages/core/test/actions/signOut/signOut.test.ts
  • packages/core/test/api/signIn.test.ts
  • packages/core/test/api/signInCredentials.test.ts
  • packages/core/test/api/signOut.test.ts
  • packages/core/test/api/signUp.test.ts
  • packages/core/test/api/updateSession.test.ts
  • packages/core/test/instance.test.ts
  • packages/core/test/jose.test.ts
  • packages/core/test/oauth.test.ts
  • packages/elysia/package.json
  • packages/express/package.json
  • packages/hono/package.json
  • packages/next/package.json
  • packages/react-router/package.json
  • packages/react/package.json
💤 Files with no reviewable changes (1)
  • packages/core/src/shared/errors.ts

Comment thread packages/core/src/actions/callback/access-token.ts
Comment thread packages/core/src/actions/signIn/authorization-url.ts Outdated
Comment thread packages/core/src/actions/signUp/signUp.ts Outdated
Comment thread packages/core/src/api/signIn.ts
Comment thread packages/core/src/cookie.ts
Comment thread packages/core/src/shared/crypto.ts
Comment thread packages/core/src/shared/unstable_error.ts Outdated
Comment thread packages/core/src/validator/registry.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/api/signOut.ts`:
- Around line 60-65: In the error response payload returned by the toResponse()
method in the signOut.ts file, change the key name from `redirectsURL` to
`redirectURL` to maintain consistency with the API contract used elsewhere in
the file. This single character fix (removing the 's' from 'redirects') ensures
the response structure matches the expected contract.

In `@packages/core/test/actions/signUp/signUp.test.ts`:
- Around line 93-95: Remove the debug artifacts from the test code in the
signUp.test.ts file. The temporary variable named `idk` and the associated
`console.log("idk: ", idk)` statement should be removed. Instead, directly parse
and assert on the response JSON by replacing the `idk` variable reference with
the actual `response.json()` call in the expect assertion to clean up the test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c0875489-b70f-4828-a017-f0a8c2c9a394

📥 Commits

Reviewing files that changed from the base of the PR and between a053364 and d5d5dee.

📒 Files selected for processing (20)
  • packages/core/src/actions/callback/access-token.ts
  • packages/core/src/actions/signIn/authorization-url.ts
  • packages/core/src/actions/signUp/signUp.ts
  • packages/core/src/api/credentials.ts
  • packages/core/src/api/signIn.ts
  • packages/core/src/api/signOut.ts
  • packages/core/src/api/signUp.ts
  • packages/core/src/api/updateSession.ts
  • packages/core/src/cookie.ts
  • packages/core/src/router/errorHandler.ts
  • packages/core/src/shared/crypto.ts
  • packages/core/src/shared/unstable_error.ts
  • packages/core/src/validator/registry.ts
  • packages/core/test/actions/callback/access-token.test.ts
  • packages/core/test/actions/signIn/signIn.test.ts
  • packages/core/test/actions/signUp/signUp.test.ts
  • packages/core/test/api/signIn.test.ts
  • packages/core/test/api/signInCredentials.test.ts
  • packages/core/test/api/signUp.test.ts
  • packages/core/test/api/updateSession.test.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/core/test/api/signUp.test.ts
🚧 Files skipped from review as they are similar to previous changes (11)
  • packages/core/test/api/signIn.test.ts
  • packages/core/src/api/signIn.ts
  • packages/core/src/api/updateSession.ts
  • packages/core/src/actions/signIn/authorization-url.ts
  • packages/core/src/shared/crypto.ts
  • packages/core/src/api/signUp.ts
  • packages/core/src/cookie.ts
  • packages/core/src/router/errorHandler.ts
  • packages/core/src/api/credentials.ts
  • packages/core/test/api/signInCredentials.test.ts
  • packages/core/src/shared/unstable_error.ts

Comment thread packages/core/src/api/signOut.ts
Comment thread packages/core/test/actions/signUp/signUp.test.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/core/src/actions/callback/callback.ts (1)

22-32: ⚠️ Potential issue | 🟠 Major

Fix Zod v4 error message API usage.

In Zod v4, error messages must be passed via a configuration object with an error property, not as positional arguments. Update:

  • z.string("message")z.string({ error: "message" })
  • z.enum(array, "message")z.enum(array, { error: "message" })

The current code at lines 23-25 and lines 30-31 uses the deprecated v3 API and will not produce the intended error messages in Zod v4.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/actions/callback/callback.ts` around lines 22 - 32, Update
the Zod schema definitions in the callback validation to use Zod v4's error
message API. In the params object, change the z.enum call to pass the error
message via a configuration object with an error property instead of as a
positional argument. Similarly, update both z.string calls in the searchParams
object to use the new syntax by passing an object with an error property
containing the message instead of passing the message as a positional argument.
This ensures the error messages are properly recognized in Zod v4.
🧹 Nitpick comments (1)
packages/core/src/actions/callback/callback.ts (1)

62-76: 💤 Low value

State mismatch returns JSON instead of throwing AuraAuthError.

This block returns Response.json(...) directly rather than throwing AuraAuthError({ code: "AUTH_MISMATCHING_STATE" }). This is inconsistent with the rest of the error system refactor where security/protocol errors throw AuraAuthError and let the error handler serialize the response.

Consider throwing AuraAuthError for consistency, though this approach works since the response needs custom headers to clear cookies.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/actions/callback/callback.ts` around lines 62 - 76, The
state mismatch check in the timingSafeEqual block is returning Response.json
directly instead of throwing AuraAuthError, which is inconsistent with the error
refactor pattern. Replace the Response.json return statement with throwing
AuraAuthError using code "AUTH_MISMATCHING_STATE". Since the error also needs to
clear cookies via clearCookieHeaders, attach the headers to the thrown
AuraAuthError instance so the error handler can properly serialize the response
with the required headers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@packages/core/src/actions/callback/callback.ts`:
- Around line 22-32: Update the Zod schema definitions in the callback
validation to use Zod v4's error message API. In the params object, change the
z.enum call to pass the error message via a configuration object with an error
property instead of as a positional argument. Similarly, update both z.string
calls in the searchParams object to use the new syntax by passing an object with
an error property containing the message instead of passing the message as a
positional argument. This ensures the error messages are properly recognized in
Zod v4.

---

Nitpick comments:
In `@packages/core/src/actions/callback/callback.ts`:
- Around line 62-76: The state mismatch check in the timingSafeEqual block is
returning Response.json directly instead of throwing AuraAuthError, which is
inconsistent with the error refactor pattern. Replace the Response.json return
statement with throwing AuraAuthError using code "AUTH_MISMATCHING_STATE". Since
the error also needs to clear cookies via clearCookieHeaders, attach the headers
to the thrown AuraAuthError instance so the error handler can properly serialize
the response with the required headers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d3ff6d87-c26f-4bc2-80ea-a24fa2f63f2d

📥 Commits

Reviewing files that changed from the base of the PR and between d5d5dee and 124c241.

⛔ Files ignored due to path filters (3)
  • bun.lock is excluded by !**/*.lock
  • deno.lock is excluded by !**/*.lock
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (29)
  • apps/nuxt/package.json
  • packages/core/deno.json
  • packages/core/package.json
  • packages/core/src/actions/callback/access-token.ts
  • packages/core/src/actions/callback/callback.ts
  • packages/core/src/actions/callback/userinfo.ts
  • packages/core/src/actions/signIn/authorization-url.ts
  • packages/core/src/actions/signIn/authorization.ts
  • packages/core/src/api/credentials.ts
  • packages/core/src/api/signIn.ts
  • packages/core/src/api/signOut.ts
  • packages/core/src/api/signUp.ts
  • packages/core/src/api/updateSession.ts
  • packages/core/src/client/client.ts
  • packages/core/src/cookie.ts
  • packages/core/src/jose.ts
  • packages/core/src/oauth/index.ts
  • packages/core/src/router/errorHandler.ts
  • packages/core/src/session/jose-manager.ts
  • packages/core/src/session/stateless.ts
  • packages/core/src/session/strategy.ts
  • packages/core/src/shared/crypto.ts
  • packages/core/src/shared/errors.ts
  • packages/core/src/shared/utils.ts
  • packages/core/src/validator/registry.ts
  • packages/core/src/validator/validator.ts
  • packages/core/test/actions/callback/callback.test.ts
  • packages/core/test/actions/signIn/signIn.test.ts
  • packages/core/test/actions/signUp/signUp.test.ts
💤 Files with no reviewable changes (3)
  • apps/nuxt/package.json
  • packages/core/src/shared/errors.ts
  • packages/core/src/validator/validator.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/core/package.json
🚧 Files skipped from review as they are similar to previous changes (18)
  • packages/core/src/session/jose-manager.ts
  • packages/core/src/api/signOut.ts
  • packages/core/src/api/signIn.ts
  • packages/core/src/session/strategy.ts
  • packages/core/src/api/updateSession.ts
  • packages/core/src/actions/signIn/authorization-url.ts
  • packages/core/src/api/signUp.ts
  • packages/core/src/client/client.ts
  • packages/core/src/shared/crypto.ts
  • packages/core/src/session/stateless.ts
  • packages/core/src/actions/callback/userinfo.ts
  • packages/core/src/actions/signIn/authorization.ts
  • packages/core/src/shared/utils.ts
  • packages/core/src/oauth/index.ts
  • packages/core/src/actions/callback/access-token.ts
  • packages/core/src/api/credentials.ts
  • packages/core/src/validator/registry.ts
  • packages/core/src/jose.ts

@halvaradop halvaradop merged commit b99786d into master Jun 17, 2026
7 checks passed
@halvaradop halvaradop deleted the feat/improve-error-ctx branch June 17, 2026 18:31
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