Repository navigation
refactor(oauth2)!: split OAuth2Error into spec-aligned subclasses - #3054
Conversation
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).
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThis PR refactors OAuth2 error handling throughout the codebase by replacing a single generic ChangesOAuth2 Error Type Hierarchy & Type Guards
OAuth2 Grant Type Handlers
OAuth2 Authorization & Code Flow Verification
OAuth2 Client & Token Operations
Tests & Utilities
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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}.tssubclasses +index.tsbarrel; oldoauth2/error.tsremoved. - Added
isOAuth2{Request,Client,Grant,Scope,GrantType,ResponseType,Server}Errorguards combining symbol-tag check withErrorCodeduck-type fallback. - Migrated server-core throw sites to the new subclass factories and fixed
server-adapter-kittest util to useisJWTError+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.
There was a problem hiding this comment.
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
📒 Files selected for processing (25)
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.tsapps/server-core/src/adapters/http/controllers/entities/identity-provider/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/core/authentication/entities/client/module.tsapps/server-core/src/core/oauth2/authorization/code-request/validator.tsapps/server-core/src/core/oauth2/authorization/code-request/verifier/module.tsapps/server-core/src/core/oauth2/authorization/code/verifier/module.tsapps/server-core/src/core/oauth2/authorization/module.tsapps/server-core/src/core/oauth2/authorization/state/module.tsapps/server-core/src/core/oauth2/client/authenticator.tsapps/server-core/test/unit/core/oauth2/helpers/error.spec.tspackages/server-adapter-kit/test/utils/response-error.tspackages/specs/src/oauth2/check.tspackages/specs/src/oauth2/error.tspackages/specs/src/oauth2/error/client.tspackages/specs/src/oauth2/error/grant-type.tspackages/specs/src/oauth2/error/grant.tspackages/specs/src/oauth2/error/index.tspackages/specs/src/oauth2/error/module.tspackages/specs/src/oauth2/error/request.tspackages/specs/src/oauth2/error/response-type.tspackages/specs/src/oauth2/error/scope.tspackages/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.
Summary
OAuth2Errorinto seven spec-aligned subclasses, each in its own file underpackages/specs/src/oauth2/error/. Each carries aSymbol.for(...)marker viamarkInstanceof, with a matching duck-type guard inoauth2/check.tsso cross-realm/bundler-boundaryinstanceof-style checks work withoutinstanceof.apps/server-core/srcto the new subclasses' factories.OAuth2Error.clientInvalid()→OAuth2ClientError.invalid(),OAuth2Error.grantInvalid()→OAuth2GrantError.invalid(), etc.OAuth2Error; it remains as the shared tagged base so existingisOAuth2Error()checks (and downstreaminstanceof OAuth2Errorif any) still match every variant.instanceof JWTErrorinpackages/server-adapter-kit/test/utils/response-error.tswithisJWTError, and routed status resolution throughhttpStatusFromCode(code)— the prior code read a non-existentstatusCodefield 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
OAuth2RequestErrorinvalid_requestOAuth2ClientErrorinvalid_clientERROR_CODE_TO_STATUS)OAuth2GrantErrorinvalid_grantOAuth2ScopeErrorinvalid_scope/insufficient_scopeOAuth2GrantTypeErrorunsupported_grant_typeOAuth2ResponseTypeErrorunsupported_response_typeOAuth2ServerErrorserver_errorTest plan
npm run build -w packages/specsnpm run build -w packages/server-adapter-kitnpm run build -w apps/server-corenpm run test --workspace=apps/server-core— 799/799 passingnpm run test --workspace=packages/server-adapter-kit— 11/11 passingSummary by CodeRabbit
Refactor
Word count: 44