Skip to content

refactor(oauth2)!: split OAuth2Error into spec-aligned subclasses - #3054

Merged
tada5hi merged 2 commits into
masterfrom
refactor/oauth2-error-split
May 14, 2026
Merged

tada5hi merged 2 commits into
masterfrom
refactor/oauth2-error-split

Conversation

@tada5hi

@tada5hi tada5hi commented May 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Split the monolithic OAuth2Error into seven spec-aligned subclasses, each in its own file under packages/specs/src/oauth2/error/. Each carries a Symbol.for(...) marker via markInstanceof, with a matching duck-type guard in oauth2/check.ts so cross-realm/bundler-boundary instanceof-style checks work without instanceof.
  • Migrated all 44 throw sites across 14 files in apps/server-core/src to the new subclasses' factories. OAuth2Error.clientInvalid() → OAuth2ClientError.invalid(), OAuth2Error.grantInvalid() → OAuth2GrantError.invalid(), etc.
  • Removed the legacy static factories from OAuth2Error; it remains as the shared tagged base so existing isOAuth2Error() checks (and downstream instanceof OAuth2Error if any) still match every variant.
  • Replaced the stray instanceof JWTError in packages/server-adapter-kit/test/utils/response-error.ts with isJWTError, and routed status resolution through httpStatusFromCode(code) — the prior code read a non-existent statusCode field that had been silently defaulting to 400.

This closes out Phase 4 of plan 013 (error-handling refactor). Pre-1.0 breaking rename (! marker is for release-please changelog signaling; no semver-load-bearing change).

Subclass mapping

Subclass RFC 6749 code HTTP status
OAuth2RequestError invalid_request 400
OAuth2ClientError invalid_client 401 (via ERROR_CODE_TO_STATUS)
OAuth2GrantError invalid_grant 400
OAuth2ScopeError invalid_scope / insufficient_scope 400
OAuth2GrantTypeError unsupported_grant_type 400
OAuth2ResponseTypeError unsupported_response_type 400
OAuth2ServerError server_error 500

Test plan

  • npm run build -w packages/specs
  • npm run build -w packages/server-adapter-kit
  • npm run build -w apps/server-core
  • npm run test --workspace=apps/server-core — 799/799 passing
  • npm run test --workspace=packages/server-adapter-kit — 11/11 passing
  • ESLint clean on every changed file

Summary by CodeRabbit

Refactor

  • OAuth2 Error Handling: Enhanced error categorization by replacing generic error types with specific, purpose-built OAuth2 error classes. Errors are now properly classified as request, client, grant, scope, response-type, grant-type, or server errors, providing clearer error differentiation and more accurate error reporting in OAuth2 flows.

Word count: 44

Split the monolithic OAuth2Error class into seven spec-aligned subclasses
so consumers can pattern-match on RFC 6749 categories without inspecting
both `code` and `data.error`. Each subclass owns its `Symbol.for(...)`
marker and a duck-type guard for cross-realm `instanceof`-style checks.

- OAuth2RequestError    (invalid_request)
- OAuth2ClientError     (invalid_client)
- OAuth2GrantError      (invalid_grant)
- OAuth2ScopeError      (invalid_scope, insufficient_scope)
- OAuth2GrantTypeError  (unsupported_grant_type)
- OAuth2ResponseTypeError (unsupported_response_type)
- OAuth2ServerError     (server_error)

Static factories move from the base class to the appropriate subclass:
`OAuth2Error.clientInvalid()` → `OAuth2ClientError.invalid()`,
`OAuth2Error.grantInvalid()` → `OAuth2GrantError.invalid()`,
`OAuth2Error.requestInvalid()` → `OAuth2RequestError.malformed()`, etc.
All 44 throw sites in apps/server-core migrated. OAuth2Error remains as
the shared tagged base so existing `isOAuth2Error()` checks still match
every variant.

Also replace the stray `instanceof JWTError` in server-adapter-kit's
test helper with `isJWTError` and route status resolution through
`httpStatusFromCode(code)` (previously read a non-existent
`statusCode` field that had defaulted to 400 by accident).
Copilot AI review requested due to automatic review settings May 14, 2026 19:26
@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@tada5hi has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 36 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e0aed301-3a0d-44e2-8f78-06b075d297fb

📥 Commits

Reviewing files that changed from the base of the PR and between 3ca3549 and dc31d46.

📒 Files selected for processing (4)
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • packages/specs/src/oauth2/constants.ts
  • packages/specs/src/oauth2/error/grant.ts
  • packages/specs/src/oauth2/error/scope.ts
📝 Walkthrough

Walkthrough

This PR refactors OAuth2 error handling throughout the codebase by replacing a single generic OAuth2Error class with a more granular error hierarchy. Specific error types (OAuth2RequestError, OAuth2ClientError, OAuth2GrantError, OAuth2ScopeError, OAuth2ResponseTypeError, OAuth2GrantTypeError, OAuth2ServerError) are now thrown at appropriate validation and authentication points, improving error categorization and client-side error handling.

Changes

OAuth2 Error Type Hierarchy & Type Guards

Layer / File(s) Summary
Error type class hierarchy
packages/specs/src/oauth2/error/module.ts, packages/specs/src/oauth2/error/client.ts, packages/specs/src/oauth2/error/grant.ts, packages/specs/src/oauth2/error/grant-type.ts, packages/specs/src/oauth2/error/request.ts, packages/specs/src/oauth2/error/response-type.ts, packages/specs/src/oauth2/error/scope.ts, packages/specs/src/oauth2/error/server.ts
Seven new OAuth2 error subclasses, each with instance markers and static factory methods, replace the removed monolithic OAuth2Error class. Each subclass maps to specific error codes and OAuth2 error semantics (e.g., OAuth2ClientError for auth failures, OAuth2GrantError for grant mismatches, OAuth2RequestError for malformed requests).
Error barrel exports & type guards
packages/specs/src/oauth2/error/index.ts, packages/specs/src/oauth2/check.ts
error/index.ts barrel-re-exports all new error types; check.ts adds seven new type-guard functions (isOAuth2RequestError, isOAuth2ClientError, etc.) that detect specific error instances via symbol markers with fallback code checks.
Removed monolithic error class
(deleted) packages/specs/src/oauth2/error.ts
The generic OAuth2Error base factory and its static methods (requestInvalid, grantInvalid, etc.) are removed; logic is distributed into specialized subclasses.

OAuth2 Grant Type Handlers

Layer / File(s) Summary
Authorize & Refresh-Token grant errors
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.ts, apps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.ts
Malformed/missing code and refresh-token parameters now throw OAuth2RequestError.malformed() instead of generic invalid-request. Client-binding failures in refresh-token flow use OAuth2ClientError.invalid() and OAuth2GrantError.invalid().
Client credential extraction
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts
Credential validation (dual submission, missing client_id, malformed Authorization header) now throws OAuth2RequestError.malformed(...) instead of generic request-invalid errors.

OAuth2 Authorization & Code Flow Verification

Layer / File(s) Summary
Code request validation
apps/server-core/src/core/oauth2/authorization/code-request/validator.ts
Unsupported response_type now throws OAuth2ResponseTypeError.unsupported() instead of generic response-type-unsupported.
Code request & authorization code verification
apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts, apps/server-core/src/core/oauth2/authorization/code/verifier/module.ts
Client validation uses OAuth2ClientError.invalid()/inactive(). PKCE/state/redirect-URI failures throw OAuth2RequestError.malformed(...) or OAuth2GrantError variants. Scope insufficiency throws OAuth2ScopeError.insufficient(); PKCE mismatches throw OAuth2GrantError.invalid(...).
Authorization module & state validation
apps/server-core/src/core/oauth2/authorization/module.ts, apps/server-core/src/core/oauth2/authorization/state/module.ts
Invalid response_type uses OAuth2ResponseTypeError.unsupported(), missing redirect_uri uses OAuth2GrantError.redirectUriMismatch(), invalid identity uses OAuth2RequestError.identityInvalid(). State validation failures throw OAuth2RequestError.stateInvalid().

OAuth2 Client & Token Operations

Layer / File(s) Summary
Client & identity provider authentication
apps/server-core/src/core/authentication/entities/client/module.ts, apps/server-core/src/core/oauth2/client/authenticator.ts
Client authentication failures now throw OAuth2ClientError.invalid() and OAuth2ClientError.inactive() instead of generic client-invalid/inactive.
Identity provider controller & token controller
apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts, apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
JSON parsing and realm mismatches in identity-provider controller throw OAuth2RequestError.malformed(). Token introspection and creation failures use OAuth2RequestError.identityInvalid() and OAuth2GrantError.invalid().

Tests & Utilities

Layer / File(s) Summary
Error helper tests & response error utility
apps/server-core/test/unit/core/oauth2/helpers/error.spec.ts, packages/server-adapter-kit/test/utils/response-error.ts
OAuth2 error helper tests updated to use OAuth2GrantError.invalid(). Response-error utility refactored to use isJWTError predicate and derive HTTP status from error code via httpStatusFromCode.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • authup/authup#3041: Introduces the foundational @authup/specs OAuth2 error/check infrastructure (instance markers, base classes) that this PR applies throughout the server-core codebase.
  • authup/authup#2937: Overlaps at apps/server-core/src/adapters/http/controllers/workflows/token/module.ts with separate changes to token creation side-effects; this PR refines the error types thrown in the same controller routes.

Poem

🐰 Hop, hop—errors now grow clear!
Specific types for client fear,
Grants, requests, and scopes defined,
OAuth flows refined in mind. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: refactoring the monolithic OAuth2Error into seven RFC-6749-aligned subclasses. It is concise, specific, and clearly summarizes the primary objective.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/oauth2-error-split

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.

Copilot AI 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.

Pull request overview

Splits the monolithic OAuth2Error (in packages/specs) into seven spec-aligned subclasses—one per RFC 6749 error code—each marked with its own Symbol.for(...) and accompanied by a duck-type guard in oauth2/check.ts. All 44 throw sites in apps/server-core/src are migrated to the new factory methods, and a stray instanceof JWTError/non-existent statusCode access in server-adapter-kit test util is corrected to use isJWTError/httpStatusFromCode.

Changes:

  • New packages/specs/src/oauth2/error/{module,client,grant,grant-type,request,response-type,scope,server}.ts subclasses + index.ts barrel; old oauth2/error.ts removed.
  • Added isOAuth2{Request,Client,Grant,Scope,GrantType,ResponseType,Server}Error guards combining symbol-tag check with ErrorCode duck-type fallback.
  • Migrated server-core throw sites to the new subclass factories and fixed server-adapter-kit test util to use isJWTError + httpStatusFromCode.

Reviewed changes

Copilot reviewed 25 out of 25 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/specs/src/oauth2/error/module.ts Base OAuth2Error + shared normalizeOAuth2ErrorInput helper
packages/specs/src/oauth2/error/client.ts OAuth2ClientError with invalid() / inactive() factories
packages/specs/src/oauth2/error/grant.ts OAuth2GrantError with invalid() / redirectUriMismatch()
packages/specs/src/oauth2/error/grant-type.ts OAuth2GrantTypeError with unsupported()
packages/specs/src/oauth2/error/request.ts OAuth2RequestError with malformed/stateInvalid/identityInvalid/codeRequestInvalid
packages/specs/src/oauth2/error/response-type.ts OAuth2ResponseTypeError with unsupported()
packages/specs/src/oauth2/error/scope.ts OAuth2ScopeError with invalid() / insufficient()
packages/specs/src/oauth2/error/server.ts OAuth2ServerError with signingKeyMissing()
packages/specs/src/oauth2/error/index.ts Barrel re-exports new subclass files
packages/specs/src/oauth2/error.ts Deleted (monolithic class removed)
packages/specs/src/oauth2/check.ts Adds per-subclass type guards combining symbol tag + code duck-type fallback
packages/server-adapter-kit/test/utils/response-error.ts Switches to isJWTError and httpStatusFromCode
apps/server-core/test/unit/core/oauth2/helpers/error.spec.ts Updates test to use OAuth2GrantError.invalid()
apps/server-core/src/core/oauth2/client/authenticator.ts Migrates throws to OAuth2ClientError.invalid()/inactive()
apps/server-core/src/core/oauth2/authorization/state/module.ts Migrates to OAuth2RequestError.stateInvalid()
apps/server-core/src/core/oauth2/authorization/module.ts Splits throws across OAuth2{ResponseType,Grant,Request}Error
apps/server-core/src/core/oauth2/authorization/code/verifier/module.ts Switches PKCE/redirect/grant throws to OAuth2GrantError
apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts Splits throws across OAuth2{Client,Request,Scope,Grant}Error
apps/server-core/src/core/oauth2/authorization/code-request/validator.ts Uses OAuth2ResponseTypeError.unsupported() in zod issue
apps/server-core/src/core/authentication/entities/client/module.ts Switches to OAuth2ClientError.invalid()
apps/server-core/src/adapters/http/controllers/workflows/token/module.ts Migrates to OAuth2{Grant,Request}Error factories
apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts Migrates to OAuth2RequestError.malformed()/stateInvalid()
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts Migrates to OAuth2RequestError.malformed()
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.ts Splits throws across OAuth2{Request,Grant,Client}Error
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.ts Migrates to OAuth2RequestError.malformed()

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@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: 3

🤖 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 `@apps/server-core/src/adapters/http/controllers/workflows/token/module.ts`:
- Around line 196-201: The grant-type selection currently throws
OAuth2GrantError.invalid() in the token controller; replace those calls with
OAuth2GrantTypeError.unsupported() so unknown/missing grant types return the
unsupported_grant_type error; update both occurrences around the grant lookup
(the throw after checking for missing grantType and the throw when the grant is
not found in this.tokenGrants) to use OAuth2GrantTypeError.unsupported().

In `@packages/specs/src/oauth2/error/grant.ts`:
- Around line 38-43: Update the error message in the static method
redirectUriMismatch of OAuth2GrantError: change "The redirect URI is missing or
do not match" to grammatically correct singular form, e.g. "The redirect URI is
missing or does not match", keeping the ErrorCode.OAUTH_REDIRECT_URI_MISMATCH
and the OAuth2GrantError constructor usage unchanged.

In `@packages/specs/src/oauth2/error/scope.ts`:
- Around line 34-38: The insufficent-scope factory sets the ErrorCode but
doesn't update the OAuth2 `error` field; in OAuth2ScopeError.insufficient()
ensure the created OAuth2ScopeError includes data.error = 'insufficient_scope'
(or sets the constructor payload's data.error) so the returned instance has
ErrorCode.OAUTH_SCOPE_INSUFFICIENT and data.error === 'insufficient_scope',
keeping fields consistent with OAuth2 semantics.
🪄 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: 630d9f3d-687a-499b-9bdd-abeb1310a4fb

📥 Commits

Reviewing files that changed from the base of the PR and between 2524876 and 3ca3549.

📒 Files selected for processing (25)
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts
  • apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/core/authentication/entities/client/module.ts
  • apps/server-core/src/core/oauth2/authorization/code-request/validator.ts
  • apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts
  • apps/server-core/src/core/oauth2/authorization/code/verifier/module.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/src/core/oauth2/authorization/state/module.ts
  • apps/server-core/src/core/oauth2/client/authenticator.ts
  • apps/server-core/test/unit/core/oauth2/helpers/error.spec.ts
  • packages/server-adapter-kit/test/utils/response-error.ts
  • packages/specs/src/oauth2/check.ts
  • packages/specs/src/oauth2/error.ts
  • packages/specs/src/oauth2/error/client.ts
  • packages/specs/src/oauth2/error/grant-type.ts
  • packages/specs/src/oauth2/error/grant.ts
  • packages/specs/src/oauth2/error/index.ts
  • packages/specs/src/oauth2/error/module.ts
  • packages/specs/src/oauth2/error/request.ts
  • packages/specs/src/oauth2/error/response-type.ts
  • packages/specs/src/oauth2/error/scope.ts
  • packages/specs/src/oauth2/error/server.ts
💤 Files with no reviewable changes (1)
  • packages/specs/src/oauth2/error.ts

Three pre-existing semantic issues surfaced during PR review (all live in
code paths the OAuth2Error split refactor touched):

- `POST /token` was throwing `invalid_grant` when the grant_type was
  missing or unknown. Per RFC 6749 §5.2 those situations are
  `unsupported_grant_type`. Switch both throws to
  `OAuth2GrantTypeError.unsupported()`.
- Fix subject-verb agreement in `OAuth2GrantError.redirectUriMismatch()`:
  "is missing or do not match" → "is missing or does not match".
- `OAuth2ScopeError.insufficient()` was setting `code:
  OAUTH_SCOPE_INSUFFICIENT` but leaving `data.error` at the constructor
  default (`invalid_scope`). Add `OAuth2ErrorCode.INSUFFICIENT_SCOPE` and
  thread it through so the wire response is internally consistent and
  matches RFC 6750 §3.1.
@tada5hi
tada5hi merged commit c40a37b into master May 14, 2026
8 checks passed
@tada5hi
tada5hi deleted the refactor/oauth2-error-split branch May 14, 2026 21:13
This was referenced May 14, 2026
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.

2 participants