Skip to content

refactor(errors)!: decouple AuthupError from @ebec/http, add inheritance-aware duck guards - #3041

Merged
tada5hi merged 11 commits into
masterfrom
refactor/error-handling
May 11, 2026
Merged

tada5hi merged 11 commits into
masterfrom
refactor/error-handling

Conversation

@tada5hi

@tada5hi tada5hi commented May 11, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Rebases the error hierarchy so domain code only throws AuthupError-derived classes; @ebec/http is confined to the HTTP middleware for foreign-error translation. HTTP status is derived from a semantic-code mapping in the adapter rather than from the error's class inheritance.

Plan reference: .agents/plans/013-error-handling-refactor.md

Architectural rule

Every error thrown by Authup code extends AuthupError (which extends @ebec/core's BaseError). @ebec/http errors are confined to the HTTP adapter, and even there only the middleware handles them — Authup code does not throw them. The HTTP-status concern is owned by a single code→status mapping in the HTTP adapter; domain code throws errors with semantic codes and never sets status.

Key changes

@authup/errors

  • AuthupError now extends @ebec/core's BaseError (was BadRequestError). The package drops its @ebec/http dependency.
  • New @instanceof chain convention: markInstanceof(this, MARKER) in each constructor; hasInstanceof(input, MARKER) for the guards. Subclass instances accumulate markers from every ancestor, so a parent-class guard fast-path-matches a subclass instance. Works cross-realm via Symbol.for(...). (Upstream proposal: feat(core): cross-realm @instanceof chain convention (markInstanceof / hasInstanceof) tada5hi/ebec#429)
  • New built-in classes: BadRequestError, UnauthorizedError, EntityNotFoundError, EntityConflictError, InternalError.
  • BearerTokenMalformedError and AuthHeaderError rebased onto UnauthorizedError (their semantic family).
  • ERROR_CODE_TO_STATUS + httpStatusFromCode() co-located with the ErrorCode enum.
  • Sibling check.ts files hold the duck-type guards (isAuthupError, isBadRequestError, etc.).

@authup/specs, @authup/access, @authup/core-kit

  • OAuth2Error, JWTError, JWKError, PolicyError, PermissionError, ClientError, RobotError each export their Symbol.for(...) marker; guards in sibling check.ts files.

apps/server-core

  • HTTP error middleware uses httpStatusFromCode(next.code) instead of next.status.
  • sanitizeError keeps isHTTPError from @ebec/http for routup-thrown framework errors only.
  • ~30 throw sites migrated from new BadRequestError/NotFoundError/ConflictError (from @ebec/http) to new AuthupError-derived classes.
  • Identity workflow errors (RegistrationDisabledError, PasswordRecoveryDisabledError, EmailVerificationRequiredError, ResetTokenExpiredError) in their domain folders, each extending BadRequestError.
  • JWKS endpoints now throw JWKError.notFound() / JWKError.encryptionKeyMissing() — the missing-encryption-key case is semantically a 404, not a 400.

Behaviour changes (HTTP status)

Code Before After Reason
OAUTH_CLIENT_INVALID 400 401 RFC 6749 §5.2 compliance
HTTP_HEADER_AUTH_TYPE_UNSUPPORTED 400 401 Aligns with UnauthorizedError family
JWK_NOT_FOUND 400 404 Semantic: JWK not publishable

All other codes preserve their pre-refactor HTTP status. The HTTP-level test suite (Docker-gated) still asserts the old statuses for the four OAUTH_CLIENT_INVALID sites and will need updates when next run.

Inheritance verified

RegistrationDisabledError -> [AuthupError, BadRequestError, RegistrationDisabledError]
isAuthupError(regErr)     -> true
isBadRequestError(regErr) -> true

BearerTokenMalformedError       -> [AuthupError, UnauthorizedError, BearerTokenMalformedError]
isAuthupError(bearerErr)        -> true
isUnauthorizedError(bearerErr)  -> true

Test plan

  • npm run build — 18/18 projects green
  • Service-level tests: 582/582 pass (apps/server-core/test/unit/core/)
  • Package tests: 79/79 pass (errors, specs, access, core-kit, server-adapter-kit)
  • HTTP-level integration tests (Docker-gated) — pending; will need assertion updates for the three documented status changes
  • Live inheritance-chain verification via node -e

Deferred to follow-up PRs

  • Phase 4 of plan 013: split OAuth2Error into spec-aligned subclasses (OAuth2RequestError, OAuth2ClientError, etc.) — now cheap thanks to the @instanceof chain
  • Phase 5 of plan 013: rename core-kit ClientError/RobotError → ClientEntityError/RobotEntityError to resolve the hapic/@ebec/http name collision
  • HTTP-test assertion updates for the documented status changes

Summary by CodeRabbit

Release Notes

  • Refactor

    • Unified error handling architecture with semantic error codes replacing HTTP-specific exceptions
    • Improved error specificity for authentication, authorization, and entity operations
    • Centralized HTTP status mapping in adapter layer while core systems use standardized error codes
  • New Features

    • Added specialized error types for better error identification and handling

Review Change Stack

…nce-aware duck guards

Rebases the error hierarchy so that domain code only throws AuthupError-derived
classes; @ebec/http is confined to the HTTP middleware for translating foreign
framework errors. HTTP status is now derived from a semantic-code mapping in
the adapter rather than from the error's class inheritance.

Key changes
-----------

- AuthupError now extends @ebec/core's BaseError (was BadRequestError). The
  package drops its @ebec/http dependency in favour of @ebec/core.
- New @instanceof chain convention with markInstanceof / hasInstanceof helpers
  in @authup/errors. Each error class's constructor appends its own
  Symbol.for(...) marker; subclass instances accumulate markers from every
  ancestor, so a parent-class guard fast-path-matches a subclass instance.
  Works cross-realm / cross-bundle via the global Symbol.for registry.
- Sibling check.ts files for every error class hold the duck-type guards
  (isAuthupError, isOAuth2Error, isJWTError, isJWKError, isPolicyError,
  isPermissionError, isClientError, isRobotError, etc.).
- New built-in classes in @authup/errors: BadRequestError, UnauthorizedError,
  EntityNotFoundError, EntityConflictError, InternalError. BearerTokenMalformed
  and AuthHeaderError rebased onto UnauthorizedError; identity workflow errors
  (RegistrationDisabledError, PasswordRecoveryDisabledError,
  EmailVerificationRequiredError, ResetTokenExpiredError) onto BadRequestError.
- ERROR_CODE_TO_STATUS table + httpStatusFromCode() in @authup/errors,
  co-located with the ErrorCode enum. HTTP middleware uses this instead of
  reading .status off the error class.
- JWKS endpoints now throw JWKError.notFound / JWKError.encryptionKeyMissing
  instead of the generic helpers — the missing-encryption-key case is
  semantically a 404, not a 400.

Behaviour changes (HTTP status)
-------------------------------

- OAUTH_CLIENT_INVALID: 400 -> 401  (RFC 6749 §5.2 compliance)
- HTTP_HEADER_AUTH_TYPE_UNSUPPORTED: 400 -> 401  (aligns with UnauthorizedError)
- JWK_NOT_FOUND: 400 -> 404  (semantic: JWK not publishable)

All other codes preserve their pre-refactor HTTP status.

The HTTP-level test suite (Docker-gated) still asserts the old statuses for
the four OAUTH_CLIENT_INVALID sites and will require updates when next run.
Copilot AI review requested due to automatic review settings May 11, 2026 08:38
@coderabbitai

coderabbitai Bot commented May 11, 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 35 minutes and 33 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: c60d6d26-cb67-401f-add0-8d9e96ec4d19

📥 Commits

Reviewing files that changed from the base of the PR and between 2fedbe6 and 8711abd.

📒 Files selected for processing (3)
  • apps/server-core/src/core/identity/provider/authentication/protocols/ldap/module.ts
  • apps/server-core/src/utils/error.ts
  • packages/errors/src/status.ts
📝 Walkthrough

Walkthrough

Migrates error handling across the repository to @authup/errors: adds/brands error classes and guards, centralizes code→HTTP mapping, updates services/controllers/middleware/auth flows to throw code-based errors, introduces identity workflow errors, adjusts JWKS/JWT/OAuth2 errors, refactors tests to assert ErrorCode, and updates docs/configs.

Changes

Authup error unification across layers

Layer / File(s) Summary
Errors library foundation (types, codes, built-ins, mapping)
packages/errors/*
AuthupError rebased on BaseError; adds built-ins, guards, ErrorCode additions, and ERROR_CODE_TO_STATUS; replaces @ebec/http with @ebec/core.
Access package permission/policy errors and guards
packages/access/src/permission/*, packages/access/src/policy/*
Adds instance markers and type guards; updates re-exports.
Specs: JWT/JWK/OAuth2 errors and guards
packages/specs/src/json-web-*/*, packages/specs/src/oauth2/*
Adds error instance markers/guards; removes fixed HTTP statuses; extends OAuth2 error codes.
Core-kit domain error branding and barrel changes
packages/core-kit/src/domains/*
Brands ClientError/RobotError; removes UserError and barrels.
Server-core: error middleware, header handling, identity helper, sanitizer
apps/server-core/src/adapters/http/middleware/*, .../request/helpers/*, .../utils/error.ts
Maps code→status in middleware; uses AuthHeaderError; switches UnauthorizedError source; refactors sanitizeError.
HTTP controllers: switch to domain errors; JWKS uses JWKError
apps/server-core/src/adapters/http/controllers/*
Controllers replace @ebec/http errors with @authup/errors; JWKS handlers/controllers throw JWKError.
Authentication flows and OAuth2 helpers/grants
apps/server-core/src/core/authentication/*, .../oauth2/helpers/*, .../adapters/oauth2/*, packages/server-adapter-kit/*
Authenticators use EntityCredentialsInvalidError/EntityInactiveError; OAuth2 helper uses guards; grant throws credentials-invalid entity error; verifier drops upstream status.
Domain services: replace HTTP errors with Authup errors
apps/server-core/src/core/entities/*/service.ts
All services now throw EntityNotFoundError/EntityConflictError/PermissionError for not-found/conflict/denied.
Identity workflows: password recovery and registration errors
apps/server-core/src/core/identity/*
Adds recovery/registration error classes and guards; services updated to throw specific errors.
DB adapter error and server-adapter-kit verifier
apps/server-core/src/adapters/database/errors/*, packages/server-adapter-kit/*
DatabaseConflictError extends AuthupError; verifier drops statusCode on JWTError.
HTTP token workflow tests (status changes)
apps/server-core/test/unit/http/controllers/workflows/token/*
Invalid confidential client auth now returns 401; assertions updated.
Unit tests: assert by ErrorCode and new errors
apps/server-core/test/unit/**/*
Refactors tests to match ErrorCode and new PermissionError behavior.
Docs and dependency bumps
.agents/*, apps/server-core/package.json
Docs updated to new error model; bumps @ebec/http and routup versions.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120+ minutes

Poem

In burrows deep, I map each code,
From 404s to conflicts showed.
I twitch an ear—no throws of yore,
Just symbols marked and guards galore.
Now errors hop with tidy grace—
One status finds its proper place. 🐇✨

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/error-handling

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

This PR refactors Authup’s error hierarchy to remove domain-level coupling to @ebec/http, standardize on AuthupError (now extending @ebec/core’s BaseError), and centralize HTTP status derivation via an error-code → status mapping plus inheritance-aware duck-type guards.

Changes:

  • Rebase @authup/errors on @ebec/core (BaseError), introduce @instanceof marker chains (markInstanceof/hasInstanceof), and add code→status mapping (httpStatusFromCode).
  • Add per-domain/spec error markers + check.ts guard modules (OAuth2/JWT/JWK, policy/permission, client/robot, identity workflow errors).
  • Migrate server-core throw sites + middleware to rely on semantic code (not class inheritance/status) and update unit tests to assert codes.

Reviewed changes

Copilot reviewed 107 out of 108 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
packages/specs/src/oauth2/index.ts Re-export OAuth2 duck-type guards.
packages/specs/src/oauth2/error.ts Add @instanceof marker + remove direct status usage; adjust internal-error code.
packages/specs/src/oauth2/check.ts Introduce isOAuth2Error guard (marker + shape fallback).
packages/specs/src/json-web-token/error.ts Add JWT marker + remove status usage.
packages/specs/src/json-web-token/check.ts Add isJWTError guard.
packages/specs/src/json-web-key/error.ts Add JWK marker + remove status usage; minor formatting.
packages/specs/src/json-web-key/check.ts Add isJWKError guard.
packages/server-adapter-kit/src/verifier/module.ts Stop passing statusCode when wrapping remote JWT errors.
packages/errors/src/types.ts Rebase AuthupErrorOptions onto @ebec/core ErrorOptions.
packages/errors/src/status.ts Add central ERROR_CODE_TO_STATUS mapping + httpStatusFromCode.
packages/errors/src/module.ts Rebase AuthupError onto BaseError + add marker chain.
packages/errors/src/instanceof.ts Add marker-chain implementation (@instanceof array).
packages/errors/src/index.ts Export new guards/instanceof/status utilities.
packages/errors/src/constants.ts Extend ErrorCode enum for new semantic codes used by the refactor.
packages/errors/src/check.ts Add isAuthupError duck-type guard (marker fast-path + shape fallback).
packages/errors/src/built-in/unauthorized.ts Add UnauthorizedError built-in class + marker.
packages/errors/src/built-in/internal.ts Add InternalError built-in class + marker.
packages/errors/src/built-in/index.ts Rework exports to new built-in error set + guard exports.
packages/errors/src/built-in/http.ts Remove HTTPError helper tied to old design.
packages/errors/src/built-in/entity-not-found.ts Add EntityNotFoundError built-in class + marker.
packages/errors/src/built-in/entity-conflict.ts Add EntityConflictError built-in class + marker.
packages/errors/src/built-in/check.ts Add built-in error duck guards (marker + code fallback).
packages/errors/src/built-in/bearer-token.ts Rebase bearer token error onto new UnauthorizedError + marker.
packages/errors/src/built-in/bad-request.ts Add BadRequestError built-in class + marker.
packages/errors/src/built-in/auth-header.ts Add auth-header error as UnauthorizedError subclass + marker.
packages/errors/package.json Drop @ebec/http dependency; add @ebec/core.
packages/core-kit/src/domains/robot/index.ts Re-export robot guards.
packages/core-kit/src/domains/robot/error.ts Add robot error marker + constructor marker call.
packages/core-kit/src/domains/robot/check.ts Add isRobotError guard.
packages/core-kit/src/domains/client/index.ts Re-export client guards.
packages/core-kit/src/domains/client/error.ts Add client error marker + constructor marker call.
packages/core-kit/src/domains/client/check.ts Add isClientError guard.
packages/access/src/policy/error/module.ts Move to marker-chain convention; export marker constant.
packages/access/src/policy/error/index.ts Re-export policy guard module.
packages/access/src/policy/error/check.ts Add isPolicyError guard (marker + code fallback).
packages/access/src/permission/error/module.ts Switch to semantic-code-based defaults + marker-chain.
packages/access/src/permission/error/index.ts Re-export permission guard module.
packages/access/src/permission/error/check.ts Add isPermissionError guard.
package-lock.json Update lockfile for dependency changes (@ebec/core).
apps/server-core/test/unit/core/identity/registration/service.spec.ts Update assertions to semantic ErrorCode values.
apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts Update assertions to semantic ErrorCode values.
apps/server-core/test/unit/core/helpers/fake-permission-evaluator.ts Use PermissionError instead of @ebec/http forbidden errors in fakes.
apps/server-core/test/unit/core/entities/user/service.spec.ts Update service tests to assert code instead of @ebec/http classes.
apps/server-core/test/unit/core/entities/user-role/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/user-permission/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts Update service tests to assert code; use PermissionError in fakes.
apps/server-core/test/unit/core/entities/scope/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/role/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/role-permission/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/role-attribute/service.spec.ts Update service tests to assert code; use PermissionError in fakes.
apps/server-core/test/unit/core/entities/robot/service.spec.ts Update service tests to assert code; use PermissionError in fakes.
apps/server-core/test/unit/core/entities/robot-role/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/realm/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/permission/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/permission-policy/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/identity-provider-role-mapping/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/client/service.spec.ts Update service tests to assert code; use PermissionError in fakes.
apps/server-core/test/unit/core/entities/client-scope/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/client-role/service.spec.ts Update service tests to assert code.
apps/server-core/test/unit/core/entities/client-permission/service.spec.ts Update service tests to assert code.
apps/server-core/src/utils/error.ts Refactor sanitizeError to produce semantic codes + translate foreign @ebec/http errors.
apps/server-core/src/core/oauth2/helpers/erorr.ts Switch OAuth2 error conversion to use new guards + avoid instanceof.
apps/server-core/src/core/identity/registration/service.ts Throw domain-specific AuthupError subclasses instead of @ebec/http.
apps/server-core/src/core/identity/registration/error.ts Add RegistrationDisabledError (BadRequest subclass) + marker.
apps/server-core/src/core/identity/registration/check.ts Add guard for RegistrationDisabledError.
apps/server-core/src/core/identity/password-recovery/token-expired.ts Add ResetTokenExpiredError + marker.
apps/server-core/src/core/identity/password-recovery/service.ts Replace @ebec/http errors with AuthupError subclasses.
apps/server-core/src/core/identity/password-recovery/email-verification-required.ts Add EmailVerificationRequiredError + marker.
apps/server-core/src/core/identity/password-recovery/disabled.ts Add PasswordRecoveryDisabledError + marker.
apps/server-core/src/core/identity/password-recovery/check.ts Add guards for password-recovery domain errors.
apps/server-core/src/core/entities/user/service.ts Replace @ebec/http not-found errors with EntityNotFoundError.
apps/server-core/src/core/entities/user-role/service.ts Replace conflict/not-found/forbidden errors with semantic Authup errors.
apps/server-core/src/core/entities/user-permission/service.ts Replace conflict/not-found errors with semantic Authup errors.
apps/server-core/src/core/entities/user-attribute/service.ts Replace not-found/forbidden errors with semantic Authup errors.
apps/server-core/src/core/entities/scope/service.ts Replace not-found errors with EntityNotFoundError.
apps/server-core/src/core/entities/role/service.ts Replace not-found errors with EntityNotFoundError.
apps/server-core/src/core/entities/role-permission/service.ts Replace conflict/not-found errors with semantic Authup errors.
apps/server-core/src/core/entities/role-attribute/service.ts Replace not-found errors with EntityNotFoundError.
apps/server-core/src/core/entities/robot/service.ts Replace not-found errors with EntityNotFoundError.
apps/server-core/src/core/entities/robot-role/service.ts Replace conflict/not-found/forbidden errors with semantic Authup errors.
apps/server-core/src/core/entities/robot-permission/service.ts Replace conflict/not-found errors with semantic Authup errors.
apps/server-core/src/core/entities/realm/service.ts Replace not-found errors with EntityNotFoundError.
apps/server-core/src/core/entities/policy/service.ts Replace not-found errors with EntityNotFoundError.
apps/server-core/src/core/entities/permission/service.ts Replace not-found errors with EntityNotFoundError; adjust imports.
apps/server-core/src/core/entities/permission-policy/service.ts Replace conflict/not-found errors with semantic Authup errors.
apps/server-core/src/core/entities/identity-provider-role-mapping/service.ts Replace conflict/not-found/forbidden errors with semantic Authup errors.
apps/server-core/src/core/entities/client/service.ts Replace not-found errors with EntityNotFoundError.
apps/server-core/src/core/entities/client-scope/service.ts Replace conflict/not-found errors with semantic Authup errors.
apps/server-core/src/core/entities/client-role/service.ts Replace conflict/not-found/forbidden errors with semantic Authup errors.
apps/server-core/src/core/entities/client-permission/service.ts Replace conflict/not-found errors with semantic Authup errors.
apps/server-core/src/adapters/http/request/helpers/identity.ts Use @authup/errors UnauthorizedError in HTTP adapter.
apps/server-core/src/adapters/http/middleware/built-in/loggedin/user.ts Use @authup/errors UnauthorizedError in middleware.
apps/server-core/src/adapters/http/middleware/built-in/error.ts Derive HTTP status via httpStatusFromCode(next.code) instead of next.status.
apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts Replace removed HTTPError helper with AuthHeaderError.
apps/server-core/src/adapters/http/controllers/workflows/jwks/module.ts Use JWKError semantic factories for JWKS endpoints (404 vs 400).
apps/server-core/src/adapters/http/controllers/workflows/jwks/handlers/read.ts Use JWKError semantic factories for JWKS endpoints (404 vs 400).
apps/server-core/src/adapters/http/controllers/workflows/authorize/module.ts Minor import re-ordering (no behavior change).
apps/server-core/src/adapters/http/controllers/entities/user/module.ts Minor import re-ordering (no behavior change).
apps/server-core/src/adapters/http/controllers/entities/robot/module.ts Replace NotFoundError with EntityNotFoundError; reorder imports.
apps/server-core/src/adapters/http/controllers/entities/realm/module.ts Minor import re-ordering (no behavior change).
apps/server-core/src/adapters/http/controllers/entities/policy/module.ts Replace NotFoundError with EntityNotFoundError.
apps/server-core/src/adapters/http/controllers/entities/permission/module.ts Replace NotFoundError with EntityNotFoundError.
apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts Replace NotFoundError with EntityNotFoundError; reorder imports.
apps/server-core/src/adapters/http/controllers/entities/client/module.ts Replace NotFoundError with EntityNotFoundError; reorder imports.
apps/server-core/src/adapters/database/errors/conflict.ts Rebase DB conflict error to semantic AuthupError/ErrorCode.
.agents/conventions.md Update error-handling conventions to new architecture.
.agents/architecture.md Update architecture docs for semantic-code errors (vs HTTP-class errors).

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

Comment thread apps/server-core/src/utils/error.ts Resolved
Comment thread apps/server-core/src/utils/error.ts Resolved
Comment thread .agents/conventions.md Resolved
Comment thread .agents/architecture.md Resolved

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

Caution

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

⚠️ Outside diff range comments (1)
apps/server-core/src/core/entities/user-role/service.ts (1)

82-88: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Authorize the binding before surfacing ENTITY_CONFLICT.

The duplicate lookup runs before the superset check and USER_ROLE_CREATE policy evaluation. A caller that passes the coarse pre-check can distinguish “assignment exists” from “I’m not allowed to create it,” which leaks membership information. Move the conflict check behind the authorization path.

Suggested ordering
-        const existing = await this.repository.findOneBy({
-            role_id: validated.role_id,
-            user_id: validated.user_id,
-        });
-        if (existing) {
-            throw new EntityConflictError('The user-role assignment already exists.');
-        }
-
         if (validated.role) {
             validated.role_realm_id = validated.role.realm_id;
         }
@@
         await actor.permissionEvaluator.evaluate({
             name: PermissionName.USER_ROLE_CREATE,
             input: new PolicyData({ [BuiltInPolicyType.ATTRIBUTES]: validated }),
         });
+
+        const existing = await this.repository.findOneBy({
+            role_id: validated.role_id,
+            user_id: validated.user_id,
+        });
+        if (existing) {
+            throw new EntityConflictError('The user-role assignment already exists.');
+        }

Also applies to: 98-118

🤖 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 `@apps/server-core/src/core/entities/user-role/service.ts` around lines 82 -
88, The duplicate-record check using this.repository.findOneBy and throwing
EntityConflictError should be moved to occur only after the
authorization/superset verification and the USER_ROLE_CREATE policy evaluation
have completed; update the method(s) containing the existing check so that you
first run the superset check and call the policy evaluation for
USER_ROLE_CREATE, and only then perform the repository.findOneBy duplicate
lookup and throw EntityConflictError if found. Apply the same reorder/fix to the
other similar block around the code referenced in the 98-118 region to avoid
leaking membership information before authorization.
🧹 Nitpick comments (10)
packages/core-kit/src/domains/client/error.ts (1)

8-16: ⚡ Quick win

Keep ClientError's constructor aligned with AuthupErrorInput.

This override narrows a public API from string | options to options only, so new ClientError('...') becomes a TypeScript break even though AuthupError still supports it.

Proposed change
-import type { AuthupErrorOptions } from '@authup/errors';
+import type { AuthupErrorInput } from '@authup/errors';
 import { AuthupError, ErrorCode, markInstanceof } from '@authup/errors';

 export const CLIENT_ERROR_INSTANCE = Symbol.for('@authup/core-kit/ClientError');

 export class ClientError extends AuthupError {
-    constructor(options: AuthupErrorOptions = {}) {
-        super(options);
+    constructor(input: AuthupErrorInput = {}) {
+        super(input);
         markInstanceof(this, CLIENT_ERROR_INSTANCE);
     }
🤖 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-kit/src/domains/client/error.ts` around lines 8 - 16, The
ClientError constructor currently narrows the public API by accepting only
AuthupErrorOptions; change its signature to accept the same union type as the
base (string | AuthupErrorOptions / AuthupErrorInput) so callers can still do
new ClientError('message') as with AuthupError, and update the constructor body
in class ClientError to detect a string vs options and pass the correct value to
super; reference ClientError, AuthupError, and AuthupErrorOptions (or the
AuthupErrorInput type) when making the change.
apps/server-core/src/adapters/database/errors/conflict.ts (1)

10-15: ⚡ Quick win

Prefer extending EntityConflictError here.

Using the built-in class keeps marker inheritance consistent and removes duplicated conflict wiring.

Suggested refactor
-import { AuthupError, ErrorCode } from '@authup/errors';
+import { EntityConflictError } from '@authup/errors';

-export class DatabaseConflictError extends AuthupError {
+export class DatabaseConflictError extends EntityConflictError {
     constructor() {
-        super({
-            code: ErrorCode.ENTITY_CONFLICT,
-            message: 'A db entry with some unique attributes already exist.',
-        });
+        super('A db entry with some unique attributes already exists.');
     }
 }
🤖 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 `@apps/server-core/src/adapters/database/errors/conflict.ts` around lines 10 -
15, The DatabaseConflictError class currently extends AuthupError and manually
sets ErrorCode.ENTITY_CONFLICT; change it to extend the built-in
EntityConflictError so it inherits the standard conflict wiring and marker
types. Update the class declaration for DatabaseConflictError to extend
EntityConflictError and remove or simplify the custom super payload (ensure any
needed message is passed through EntityConflictError's constructor rather than
re-implementing the conflict code), keeping ErrorCode.ENTITY_CONFLICT semantics
consistent.
apps/server-core/src/core/entities/permission/service.ts (1)

134-134: 💤 Low value

Consider adding descriptive messages to EntityNotFoundError instances.

Adding context like "Permission not found" would improve debuggability and align with the pattern used for BadRequestError in this service.

💬 Suggested improvements
 // Line 134 in getOne
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Permission not found.');

 // Line 187 in save (updateOnly with idOrName)
-                throw new EntityNotFoundError();
+                throw new EntityNotFoundError('Permission not found.');

 // Line 190 in save (updateOnly without idOrName)
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Permission entity required for update operation.');

 // Line 268 in delete
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Permission not found.');

Also applies to: 187-187, 190-190, 268-268

🤖 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 `@apps/server-core/src/core/entities/permission/service.ts` at line 134, The
EntityNotFoundError throws in this permission service lack descriptive messages;
update each throw of EntityNotFoundError in this file (including the occurrences
around lines 134, 187, 190, 268) to include a clear message like "Permission not
found" and, where available, append the relevant identifier (e.g., permissionId
or id) for context; ensure you modify the throws inside the Permission service
methods (the functions that load/update/delete permissions) so they mirror the
BadRequestError pattern and provide the entity name and id in the error message.
apps/server-core/src/core/entities/robot/service.ts (1)

123-123: 💤 Low value

Consider adding descriptive messages to EntityNotFoundError instances.

Adding context like "Robot not found" or "Robot entity required for update" improves log clarity and debugging experience.

💬 Suggested improvements
 // Line 123 in getOne
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Robot not found.');

 // Line 188 in save (updateOnly with idOrName)
-                throw new EntityNotFoundError();
+                throw new EntityNotFoundError('Robot not found.');

 // Line 191 in save (updateOnly without idOrName)
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Robot entity required for update operation.');

 // Line 291 in delete
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Robot not found.');

Also applies to: 188-188, 191-191, 291-291

🤖 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 `@apps/server-core/src/core/entities/robot/service.ts` at line 123, Replace
bare throws of EntityNotFoundError with descriptive messages to clarify intent
and context; e.g., in apps/server-core/src/core/entities/robot/service.ts update
the throw new EntityNotFoundError() occurrences (including those around the
update/delete/get flows at the noted spots) to throw new
EntityNotFoundError("Robot not found") or a context-specific message such as
"Robot entity required for update" or "Robot not found for deletion" so logs and
stack traces carry meaningful information; locate the throws by searching for
EntityNotFoundError within the Robot service functions (methods handling
fetch/update/delete) and update each instantiation accordingly.
apps/server-core/src/core/identity/registration/service.ts (1)

92-92: 💤 Low value

Consider adding a descriptive message to EntityNotFoundError.

While the error code conveys the issue, adding a message like "Activation token not found" would improve debuggability and developer experience when reviewing logs.

💬 Suggested improvement
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Activation token not found.');
🤖 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 `@apps/server-core/src/core/identity/registration/service.ts` at line 92,
Replace the bare throw new EntityNotFoundError() with a descriptive instance
message (e.g., throw new EntityNotFoundError("Activation token not found")) so
logs and stack traces include context; locate the throw in the registration
service where EntityNotFoundError is raised (the existing throw new
EntityNotFoundError() line) and update it to pass a clear, specific message
about the missing activation token.
apps/server-core/src/core/entities/policy/service.ts (1)

82-82: 💤 Low value

Consider adding descriptive messages to EntityNotFoundError instances.

While error codes provide semantic meaning, adding context like "Policy not found" would improve debuggability and align with the messaging pattern used for BadRequestError in this service.

💬 Suggested improvements
 // Line 82 in getOne
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Policy not found.');

 // Line 135 in save (updateOnly with idOrName)
-                throw new EntityNotFoundError();
+                throw new EntityNotFoundError('Policy not found.');

 // Line 138 in save (updateOnly without idOrName)
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Policy entity required for update operation.');

 // Line 236 in delete
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Policy not found.');

Also applies to: 135-135, 138-138, 236-236

🤖 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 `@apps/server-core/src/core/entities/policy/service.ts` at line 82, Replace
bare EntityNotFoundError() throws with descriptive messages (e.g., "Policy not
found" or "Policy not found: <id>") so they mirror the BadRequestError pattern
and improve debuggability; update each instantiation found in this file — for
example in the methods that currently throw in the Policy service (the throws
inside the functions handling get/fetch/update/delete of Policy entities) to
pass a clear message string to new EntityNotFoundError(...) and include
identifying context (policy id or query info) where available.
apps/server-core/src/core/entities/role-permission/service.ts (1)

69-69: 💤 Low value

Consider adding context to EntityNotFoundError instances.

While error codes provide semantic meaning, descriptive messages improve the developer experience when debugging. Consider adding entity-specific context.

💬 Suggested improvements
 // Line 69 in getOne
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Role-permission assignment not found.');

 // Line 150 in update
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Role-permission assignment not found.');

 // Line 178 in delete
-            throw new EntityNotFoundError();
+            throw new EntityNotFoundError('Role-permission assignment not found.');

Also applies to: 150-150, 178-178

🤖 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 `@apps/server-core/src/core/entities/role-permission/service.ts` at line 69,
Replace bare throws of EntityNotFoundError in this service with contextual
messages: wherever the code currently does throw new EntityNotFoundError() (the
instances in service.ts), change to throw new
EntityNotFoundError('RolePermission not found' + contextualInfo) and include
relevant identifiers/params available in that scope (e.g., id, roleId,
permissionId). Locate the throws by the symbol EntityNotFoundError in the
RolePermission service methods (e.g., the get/update/delete/find methods) and
construct messages like "RolePermission not found: id=<id>" or include
roleId/permissionId as appropriate so the error carries actionable context.
packages/errors/src/status.ts (1)

23-55: ⚡ Quick win

Add focused tests for httpStatusFromCode to lock intended status behavior.

This mapping is now the single source for HTTP translation; a small test suite would protect intentional changes (e.g., OAUTH_CLIENT_INVALID → 401, JWK_NOT_FOUND → 404) from accidental regressions.

Suggested test shape
describe('httpStatusFromCode', () => {
    it('maps explicit codes', () => {
        expect(httpStatusFromCode(ErrorCode.OAUTH_CLIENT_INVALID)).toBe(401);
        expect(httpStatusFromCode(ErrorCode.JWK_NOT_FOUND)).toBe(404);
        expect(httpStatusFromCode(ErrorCode.ENTITY_CONFLICT)).toBe(409);
    });

    it('falls back for unknown codes', () => {
        expect(httpStatusFromCode('UNKNOWN')).toBe(400);
        expect(httpStatusFromCode('UNKNOWN', 500)).toBe(500);
    });
});
🤖 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/errors/src/status.ts` around lines 23 - 55, Add a focused test suite
for httpStatusFromCode that asserts the explicit mappings in
ERROR_CODE_TO_STATUS (e.g., ErrorCode.OAUTH_CLIENT_INVALID -> 401,
ErrorCode.JWK_NOT_FOUND -> 404, ErrorCode.ENTITY_CONFLICT -> 409) and verifies
fallback behavior for unknown codes (default 400 and custom fallback like 500);
place tests near other errors tests and call httpStatusFromCode with both known
ErrorCode values and a bogus string to lock intended status behavior.
apps/server-core/src/core/identity/password-recovery/service.ts (1)

84-91: 💤 Low value

Consider a more specific error for mail delivery failures.

The mail-send failure path throws a generic BadRequestError with a literal message. While functional, a dedicated error class (e.g., MailDeliveryError) would:

  • Provide a distinct ErrorCode for monitoring/alerting
  • Enable specific retry logic in middleware
  • Clarify that this is an infrastructure issue, not a client validation failure
💡 Optional: Introduce MailDeliveryError

Define a new error class:

export class MailDeliveryError extends InternalError {
    constructor(message?: string) {
        super({
            code: ErrorCode.MAIL_DELIVERY_FAILED,
            message: message || 'Failed to send email.',
        });
        markInstanceof(this, MAIL_DELIVERY_ERROR_INSTANCE);
    }
}

Then replace line 90:

-throw new BadRequestError('Password recovery failed. Could not send reset email.');
+throw new MailDeliveryError('Password recovery failed. Could not send reset email.');
🤖 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 `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines
84 - 91, The code currently throws a generic BadRequestError when email sending
fails in the password recovery flow; create a specific MailDeliveryError class
(extending InternalError) that sets code to ErrorCode.MAIL_DELIVERY_FAILED and
marks the instance with MAIL_DELIVERY_ERROR_INSTANCE, then replace the thrown
BadRequestError in the password-recovery service (the block using
this.repository.merge(...) and this.repository.save(...)) with a throw new
MailDeliveryError(...) so mail failures are distinguishable for monitoring and
retry logic.
apps/server-core/src/utils/error.ts (1)

76-77: 💤 Low value

Consider validating property types before casting.

Lines 76-77, 83-84, and 89-91 cast input.stack and input.message to string | undefined without runtime validation. Since we've only confirmed isObject(input), these properties could be numbers, objects, or other non-string types.

While unlikely to cause crashes (the values are just passed along), unexpected types could leak into error logs or responses.

🛡️ Proposed defensive casting
 case 'ER_DUP_ENTRY':
 case 'SQLITE_CONSTRAINT_UNIQUE': {
     return new AuthupError({
         code: ErrorCode.ENTITY_CONFLICT,
         message: 'An entry with some unique attributes already exist.',
-        stack: input.stack as string | undefined,
+        stack: typeof input.stack === 'string' ? input.stack : undefined,
     });
 }

Apply similar checks for lines 83-84 and 89-91.

Also applies to: 83-84, 89-91

🤖 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 `@apps/server-core/src/utils/error.ts` around lines 76 - 77, Validate that
input.stack and input.message are strings before casting them: replace direct
casts like input.stack as string | undefined and input.message as string |
undefined with runtime checks (e.g., typeof input.stack === "string" ?
input.stack : undefined or safely coerce via String(input.message) when
appropriate), and apply the same pattern to the other occurrences that cast
these properties so non-string values (numbers/objects) are not leaked into
logs/responses.
🤖 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 @.agents/architecture.md:
- Line 599: Update the note to reference the actual exception thrown by the
validator: replace mention of the helper badRequest(...) with the
BadRequestError from `@authup/errors` (and retain reference to
ErrorCode.BAD_REQUEST if present); specifically call out that
UserAttributeService.create and UserAttributeService.update throw new
BadRequestError(...) rather than invoking the apps/server-core helper, so change
the wording to point readers at BadRequestError/@authup/errors and remove the
incorrect helper reference.

In `@packages/core-kit/src/domains/robot/check.ts`:
- Around line 19-21: The guard is currently treating generic ErrorCode values
(ErrorCode.ENTITY_NOT_FOUND, ENTITY_INACTIVE, ENTITY_CREDENTIALS_INVALID) as
robot-specific, which conflicts with the client guard; update the fallback to
require a domain discriminator so the check is unambiguous — e.g., instead of
returning true when input.code matches those ErrorCode values, require that
input.domain === Domain.ROBOT (or another domain-specific field such as
input.resourceType === 'robot') AND the code matches; change the return
expression that reads input.code === ErrorCode... to include that domain check
(use the existing input and ErrorCode symbols so only robot-domain errors are
accepted).

In `@packages/errors/src/built-in/entity-conflict.ts`:
- Around line 18-21: The constructor currently passes code:
ErrorCode.ENTITY_CONFLICT before spreading options which allows callers to
override it; change the object passed to super so the ErrorCode.ENTITY_CONFLICT
value cannot be overridden (e.g., spread options first then set code to
ErrorCode.ENTITY_CONFLICT, or explicitly delete/ignore options.code before
calling super) so the class invariant is preserved; refer to the super call and
ErrorCode.ENTITY_CONFLICT in entity-conflict.ts to locate and update the call.

In `@packages/errors/src/built-in/entity-not-found.ts`:
- Around line 18-22: The constructor for EntityNotFoundError currently spreads
options after setting code, allowing options.code to override
ErrorCode.ENTITY_NOT_FOUND; fix this by applying the spread first and then
setting code to ErrorCode.ENTITY_NOT_FOUND so the canonical code cannot be
overridden (i.e., change the object to { ..., ...options, code:
ErrorCode.ENTITY_NOT_FOUND } or explicitly delete options.code before calling
super in the EntityNotFoundError constructor).

In `@packages/errors/src/constants.ts`:
- Around line 24-25: The ERROR_CODE_TO_STATUS map is missing an explicit entry
for ENTITY_RELATION_INVALID so it falls back to 400; update the map to include
ENTITY_RELATION_INVALID with the intended HTTP status (e.g., 409 to match
ENTITY_CONFLICT). Locate ERROR_CODE_TO_STATUS and add a key for
ENTITY_RELATION_INVALID mapped to the correct numeric status code so
apps/server-core's error handling returns the intended status.

In `@packages/specs/src/oauth2/error.ts`:
- Around line 143-147: The signingKeyMissing() factory currently returns an
OAuth2Error that defaults data.error to "invalid_request"; update
signingKeyMissing() to create the OAuth2Error with the OAuth2 server-side error
type by setting data.error to "server_error" (i.e., call new OAuth2Error({... ,
data: { error: 'server_error' } })), keeping the existing message and
ErrorCode.INTERNAL_ERROR so the failure is reported as a server_error rather
than an invalid_request.

---

Outside diff comments:
In `@apps/server-core/src/core/entities/user-role/service.ts`:
- Around line 82-88: The duplicate-record check using this.repository.findOneBy
and throwing EntityConflictError should be moved to occur only after the
authorization/superset verification and the USER_ROLE_CREATE policy evaluation
have completed; update the method(s) containing the existing check so that you
first run the superset check and call the policy evaluation for
USER_ROLE_CREATE, and only then perform the repository.findOneBy duplicate
lookup and throw EntityConflictError if found. Apply the same reorder/fix to the
other similar block around the code referenced in the 98-118 region to avoid
leaking membership information before authorization.

---

Nitpick comments:
In `@apps/server-core/src/adapters/database/errors/conflict.ts`:
- Around line 10-15: The DatabaseConflictError class currently extends
AuthupError and manually sets ErrorCode.ENTITY_CONFLICT; change it to extend the
built-in EntityConflictError so it inherits the standard conflict wiring and
marker types. Update the class declaration for DatabaseConflictError to extend
EntityConflictError and remove or simplify the custom super payload (ensure any
needed message is passed through EntityConflictError's constructor rather than
re-implementing the conflict code), keeping ErrorCode.ENTITY_CONFLICT semantics
consistent.

In `@apps/server-core/src/core/entities/permission/service.ts`:
- Line 134: The EntityNotFoundError throws in this permission service lack
descriptive messages; update each throw of EntityNotFoundError in this file
(including the occurrences around lines 134, 187, 190, 268) to include a clear
message like "Permission not found" and, where available, append the relevant
identifier (e.g., permissionId or id) for context; ensure you modify the throws
inside the Permission service methods (the functions that load/update/delete
permissions) so they mirror the BadRequestError pattern and provide the entity
name and id in the error message.

In `@apps/server-core/src/core/entities/policy/service.ts`:
- Line 82: Replace bare EntityNotFoundError() throws with descriptive messages
(e.g., "Policy not found" or "Policy not found: <id>") so they mirror the
BadRequestError pattern and improve debuggability; update each instantiation
found in this file — for example in the methods that currently throw in the
Policy service (the throws inside the functions handling get/fetch/update/delete
of Policy entities) to pass a clear message string to new
EntityNotFoundError(...) and include identifying context (policy id or query
info) where available.

In `@apps/server-core/src/core/entities/robot/service.ts`:
- Line 123: Replace bare throws of EntityNotFoundError with descriptive messages
to clarify intent and context; e.g., in
apps/server-core/src/core/entities/robot/service.ts update the throw new
EntityNotFoundError() occurrences (including those around the update/delete/get
flows at the noted spots) to throw new EntityNotFoundError("Robot not found") or
a context-specific message such as "Robot entity required for update" or "Robot
not found for deletion" so logs and stack traces carry meaningful information;
locate the throws by searching for EntityNotFoundError within the Robot service
functions (methods handling fetch/update/delete) and update each instantiation
accordingly.

In `@apps/server-core/src/core/entities/role-permission/service.ts`:
- Line 69: Replace bare throws of EntityNotFoundError in this service with
contextual messages: wherever the code currently does throw new
EntityNotFoundError() (the instances in service.ts), change to throw new
EntityNotFoundError('RolePermission not found' + contextualInfo) and include
relevant identifiers/params available in that scope (e.g., id, roleId,
permissionId). Locate the throws by the symbol EntityNotFoundError in the
RolePermission service methods (e.g., the get/update/delete/find methods) and
construct messages like "RolePermission not found: id=<id>" or include
roleId/permissionId as appropriate so the error carries actionable context.

In `@apps/server-core/src/core/identity/password-recovery/service.ts`:
- Around line 84-91: The code currently throws a generic BadRequestError when
email sending fails in the password recovery flow; create a specific
MailDeliveryError class (extending InternalError) that sets code to
ErrorCode.MAIL_DELIVERY_FAILED and marks the instance with
MAIL_DELIVERY_ERROR_INSTANCE, then replace the thrown BadRequestError in the
password-recovery service (the block using this.repository.merge(...) and
this.repository.save(...)) with a throw new MailDeliveryError(...) so mail
failures are distinguishable for monitoring and retry logic.

In `@apps/server-core/src/core/identity/registration/service.ts`:
- Line 92: Replace the bare throw new EntityNotFoundError() with a descriptive
instance message (e.g., throw new EntityNotFoundError("Activation token not
found")) so logs and stack traces include context; locate the throw in the
registration service where EntityNotFoundError is raised (the existing throw new
EntityNotFoundError() line) and update it to pass a clear, specific message
about the missing activation token.

In `@apps/server-core/src/utils/error.ts`:
- Around line 76-77: Validate that input.stack and input.message are strings
before casting them: replace direct casts like input.stack as string | undefined
and input.message as string | undefined with runtime checks (e.g., typeof
input.stack === "string" ? input.stack : undefined or safely coerce via
String(input.message) when appropriate), and apply the same pattern to the other
occurrences that cast these properties so non-string values (numbers/objects)
are not leaked into logs/responses.

In `@packages/core-kit/src/domains/client/error.ts`:
- Around line 8-16: The ClientError constructor currently narrows the public API
by accepting only AuthupErrorOptions; change its signature to accept the same
union type as the base (string | AuthupErrorOptions / AuthupErrorInput) so
callers can still do new ClientError('message') as with AuthupError, and update
the constructor body in class ClientError to detect a string vs options and pass
the correct value to super; reference ClientError, AuthupError, and
AuthupErrorOptions (or the AuthupErrorInput type) when making the change.

In `@packages/errors/src/status.ts`:
- Around line 23-55: Add a focused test suite for httpStatusFromCode that
asserts the explicit mappings in ERROR_CODE_TO_STATUS (e.g.,
ErrorCode.OAUTH_CLIENT_INVALID -> 401, ErrorCode.JWK_NOT_FOUND -> 404,
ErrorCode.ENTITY_CONFLICT -> 409) and verifies fallback behavior for unknown
codes (default 400 and custom fallback like 500); place tests near other errors
tests and call httpStatusFromCode with both known ErrorCode values and a bogus
string to lock intended status behavior.
🪄 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: 2a4744bb-7a35-40ee-acbd-60b51fb9803d

📥 Commits

Reviewing files that changed from the base of the PR and between 1adf08e and eab7d8b.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (107)
  • .agents/architecture.md
  • .agents/conventions.md
  • apps/server-core/src/adapters/database/errors/conflict.ts
  • apps/server-core/src/adapters/http/controllers/entities/client/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/policy/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/realm/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/robot/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/user/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/authorize/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/jwks/handlers/read.ts
  • apps/server-core/src/adapters/http/controllers/workflows/jwks/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/error.ts
  • apps/server-core/src/adapters/http/middleware/built-in/loggedin/user.ts
  • apps/server-core/src/adapters/http/request/helpers/identity.ts
  • apps/server-core/src/core/entities/client-permission/service.ts
  • apps/server-core/src/core/entities/client-role/service.ts
  • apps/server-core/src/core/entities/client-scope/service.ts
  • apps/server-core/src/core/entities/client/service.ts
  • apps/server-core/src/core/entities/identity-provider-role-mapping/service.ts
  • apps/server-core/src/core/entities/permission-policy/service.ts
  • apps/server-core/src/core/entities/permission/service.ts
  • apps/server-core/src/core/entities/policy/service.ts
  • apps/server-core/src/core/entities/realm/service.ts
  • apps/server-core/src/core/entities/robot-permission/service.ts
  • apps/server-core/src/core/entities/robot-role/service.ts
  • apps/server-core/src/core/entities/robot/service.ts
  • apps/server-core/src/core/entities/role-attribute/service.ts
  • apps/server-core/src/core/entities/role-permission/service.ts
  • apps/server-core/src/core/entities/role/service.ts
  • apps/server-core/src/core/entities/scope/service.ts
  • apps/server-core/src/core/entities/user-attribute/service.ts
  • apps/server-core/src/core/entities/user-permission/service.ts
  • apps/server-core/src/core/entities/user-role/service.ts
  • apps/server-core/src/core/entities/user/service.ts
  • apps/server-core/src/core/identity/password-recovery/check.ts
  • apps/server-core/src/core/identity/password-recovery/disabled.ts
  • apps/server-core/src/core/identity/password-recovery/email-verification-required.ts
  • apps/server-core/src/core/identity/password-recovery/service.ts
  • apps/server-core/src/core/identity/password-recovery/token-expired.ts
  • apps/server-core/src/core/identity/registration/check.ts
  • apps/server-core/src/core/identity/registration/error.ts
  • apps/server-core/src/core/identity/registration/service.ts
  • apps/server-core/src/core/oauth2/helpers/erorr.ts
  • apps/server-core/src/utils/error.ts
  • apps/server-core/test/unit/core/entities/client-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/client-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/client-scope/service.spec.ts
  • apps/server-core/test/unit/core/entities/client/service.spec.ts
  • apps/server-core/test/unit/core/entities/identity-provider-role-mapping/service.spec.ts
  • apps/server-core/test/unit/core/entities/permission-policy/service.spec.ts
  • apps/server-core/test/unit/core/entities/permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/realm/service.spec.ts
  • apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/robot-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/robot/service.spec.ts
  • apps/server-core/test/unit/core/entities/role-attribute/service.spec.ts
  • apps/server-core/test/unit/core/entities/role-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/role/service.spec.ts
  • apps/server-core/test/unit/core/entities/scope/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/user/service.spec.ts
  • apps/server-core/test/unit/core/helpers/fake-permission-evaluator.ts
  • apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts
  • apps/server-core/test/unit/core/identity/registration/service.spec.ts
  • packages/access/src/permission/error/check.ts
  • packages/access/src/permission/error/index.ts
  • packages/access/src/permission/error/module.ts
  • packages/access/src/policy/error/check.ts
  • packages/access/src/policy/error/index.ts
  • packages/access/src/policy/error/module.ts
  • packages/core-kit/src/domains/client/check.ts
  • packages/core-kit/src/domains/client/error.ts
  • packages/core-kit/src/domains/client/index.ts
  • packages/core-kit/src/domains/robot/check.ts
  • packages/core-kit/src/domains/robot/error.ts
  • packages/core-kit/src/domains/robot/index.ts
  • packages/errors/package.json
  • packages/errors/src/built-in/auth-header.ts
  • packages/errors/src/built-in/bad-request.ts
  • packages/errors/src/built-in/bearer-token.ts
  • packages/errors/src/built-in/check.ts
  • packages/errors/src/built-in/entity-conflict.ts
  • packages/errors/src/built-in/entity-not-found.ts
  • packages/errors/src/built-in/http.ts
  • packages/errors/src/built-in/index.ts
  • packages/errors/src/built-in/internal.ts
  • packages/errors/src/built-in/unauthorized.ts
  • packages/errors/src/check.ts
  • packages/errors/src/constants.ts
  • packages/errors/src/index.ts
  • packages/errors/src/instanceof.ts
  • packages/errors/src/module.ts
  • packages/errors/src/status.ts
  • packages/errors/src/types.ts
  • packages/server-adapter-kit/src/verifier/module.ts
  • packages/specs/src/json-web-key/check.ts
  • packages/specs/src/json-web-key/error.ts
  • packages/specs/src/json-web-token/check.ts
  • packages/specs/src/json-web-token/error.ts
  • packages/specs/src/oauth2/check.ts
  • packages/specs/src/oauth2/error.ts
  • packages/specs/src/oauth2/index.ts
💤 Files with no reviewable changes (2)
  • packages/server-adapter-kit/src/verifier/module.ts
  • packages/errors/src/built-in/http.ts

Comment thread .agents/architecture.md Resolved
Comment on lines +18 to +21
super({
code: ErrorCode.ENTITY_CONFLICT,
...options,
});

@coderabbitai coderabbitai Bot May 11, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Prevent overriding the built-in error code.

...options after code allows callers to replace ErrorCode.ENTITY_CONFLICT, which weakens class invariants and can produce wrong HTTP mapping.

Suggested fix
         super({
-            code: ErrorCode.ENTITY_CONFLICT,
             ...options,
+            code: ErrorCode.ENTITY_CONFLICT,
         });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
super({
code: ErrorCode.ENTITY_CONFLICT,
...options,
});
super({
...options,
code: ErrorCode.ENTITY_CONFLICT,
});
🤖 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/errors/src/built-in/entity-conflict.ts` around lines 18 - 21, The
constructor currently passes code: ErrorCode.ENTITY_CONFLICT before spreading
options which allows callers to override it; change the object passed to super
so the ErrorCode.ENTITY_CONFLICT value cannot be overridden (e.g., spread
options first then set code to ErrorCode.ENTITY_CONFLICT, or explicitly
delete/ignore options.code before calling super) so the class invariant is
preserved; refer to the super call and ErrorCode.ENTITY_CONFLICT in
entity-conflict.ts to locate and update the call.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Declining — the spread order is intentional. Subclasses depend on overriding the canonical code: e.g. RegistrationDisabledError extends BadRequestError calls super({ code: REGISTRATION_DISABLED, message: ... }), and PasswordRecoveryDisabledError / EmailVerificationRequiredError / ResetTokenExpiredError do the same. Locking the code here would either force Object.defineProperty-via-options or block subclass-based code refinement, both of which are bigger losses than the theoretical new EntityConflictError({ code: 'foo' }) foot-gun (which still has the @instanceof marker pinning the class identity).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@tada5hi, understood — that's a clear and well-reasoned design. Spreading options after the default code is the deliberate mechanism that lets subclasses (e.g. RegistrationDisabledError, ResetTokenExpiredError) supply a more specific ErrorCode via super({ code: ..., message: ... }), while @instanceof markers independently preserve class identity. I'll drop this suggestion.


✏️ Learnings added
Learnt from: tada5hi
Repo: authup/authup PR: 3041
File: packages/errors/src/built-in/entity-conflict.ts:18-21
Timestamp: 2026-05-11T09:10:51.769Z
Learning: In the `authup/errors` package (TypeScript), the spread order in `AuthupError` subclass constructors is intentional: the default `code` (e.g. `ErrorCode.ENTITY_CONFLICT`) is placed *before* `...options` in the `super({})` call so that subclasses can override it by passing `{ code: MORE_SPECIFIC_CODE, ... }` to their own `super(...)`. Examples include `RegistrationDisabledError`, `PasswordRecoveryDisabledError`, `EmailVerificationRequiredError`, and `ResetTokenExpiredError`, which all extend a built-in base error and supply their own `ErrorCode`. Class identity is still reliably pinned by the `instanceof` marker written via `markInstanceof`. Do not flag this spread order as a bug.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines +18 to +22
super({
code: ErrorCode.ENTITY_NOT_FOUND,
message: 'Entity not found.',
...options,
});

@coderabbitai coderabbitai Bot May 11, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Lock EntityNotFoundError to its canonical code.

Current spread order lets options.code override ErrorCode.ENTITY_NOT_FOUND, which can break code-based handling guarantees.

Suggested fix
         super({
-            code: ErrorCode.ENTITY_NOT_FOUND,
             message: 'Entity not found.',
             ...options,
+            code: ErrorCode.ENTITY_NOT_FOUND,
         });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
super({
code: ErrorCode.ENTITY_NOT_FOUND,
message: 'Entity not found.',
...options,
});
super({
message: 'Entity not found.',
...options,
code: ErrorCode.ENTITY_NOT_FOUND,
});
🤖 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/errors/src/built-in/entity-not-found.ts` around lines 18 - 22, The
constructor for EntityNotFoundError currently spreads options after setting
code, allowing options.code to override ErrorCode.ENTITY_NOT_FOUND; fix this by
applying the spread first and then setting code to ErrorCode.ENTITY_NOT_FOUND so
the canonical code cannot be overridden (i.e., change the object to { ...,
...options, code: ErrorCode.ENTITY_NOT_FOUND } or explicitly delete options.code
before calling super in the EntityNotFoundError constructor).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Same rationale as the EntityConflictError thread — the spread order is intentional for subclass code refinement. The @instanceof marker pins class identity even if a caller passes a custom code.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@tada5hi, understood — the @instanceof marker is the canonical identity anchor here, so allowing options.code to be overridden via the spread is a safe and intentional mechanism for subclass code refinement. I'll withdraw this concern.


✏️ Learnings added
Learnt from: tada5hi
Repo: authup/authup PR: 3041
File: packages/errors/src/built-in/entity-not-found.ts:18-22
Timestamp: 2026-05-11T09:10:53.368Z
Learning: In `packages/errors/src/built-in/` (e.g., `entity-not-found.ts`, `entity-conflict.ts`, `bad-request.ts`, etc.), the constructor spread order `{ code: ErrorCode.X, message: '...', ...options }` is intentional: it allows subclasses or callers to pass a more specific `code` via `options` for refinement. Class identity is guaranteed by the `instanceof` marker set via `markInstanceof(this, <CLASS_ERROR_INSTANCE>)`, not by the `code` field. Do not flag this spread order as a bug.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines +24 to +25
ENTITY_CONFLICT = 'entity_conflict',
ENTITY_RELATION_INVALID = 'entity_relation_invalid',

@coderabbitai coderabbitai Bot May 11, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C2 'ERROR_CODE_TO_STATUS|httpStatusFromCode|ENTITY_CONFLICT|ENTITY_RELATION_INVALID'

Repository: authup/authup

Length of output: 13554


Add HTTP status mapping for ENTITY_RELATION_INVALID to ERROR_CODE_TO_STATUS.

ENTITY_CONFLICT is correctly mapped to 409, but ENTITY_RELATION_INVALID (actively used in apps/server-core/src/utils/error.ts:34) lacks an explicit entry in the status map. Without it, the error will fall back to 400 instead of an intentional status.

🤖 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/errors/src/constants.ts` around lines 24 - 25, The
ERROR_CODE_TO_STATUS map is missing an explicit entry for
ENTITY_RELATION_INVALID so it falls back to 400; update the map to include
ENTITY_RELATION_INVALID with the intended HTTP status (e.g., 409 to match
ENTITY_CONFLICT). Locate ERROR_CODE_TO_STATUS and add a key for
ENTITY_RELATION_INVALID mapped to the correct numeric status code so
apps/server-core's error handling returns the intended status.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Declining — ENTITY_RELATION_INVALID is intentionally not in the status table. It's thrown when a TypeORM EntityRelationLookupError propagates through sanitizeError (client provided a join column referencing a non-existent entity). That's a 400 (Bad Request) case, which is exactly what the fallback gives. Mapping it to 409 (suggested in the bot's prompt) would be wrong — there's no conflict, the request is malformed.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@tada5hi, understood — that's a clear semantic distinction. ENTITY_RELATION_INVALID signals a malformed request (referencing a non-existent related entity), so the 400 fallback is exactly right and an explicit mapping would add noise without changing behavior. I've noted this for future reviews.


✏️ Learnings added
Learnt from: tada5hi
Repo: authup/authup PR: 3041
File: packages/errors/src/constants.ts:24-25
Timestamp: 2026-05-11T09:10:54.618Z
Learning: In `packages/errors/src/constants.ts` and `packages/errors/src/status.ts` (authup/authup, TypeScript), `ErrorCode.ENTITY_RELATION_INVALID` is intentionally absent from the `ERROR_CODE_TO_STATUS` map. It is thrown when a TypeORM `EntityRelationLookupError` propagates through `sanitizeError` — the client referenced a non-existent entity in a join column (malformed request). The 400 Bad Request fallback is the correct HTTP status for this case; do not suggest mapping it to 409 (Conflict) or any other status.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment thread packages/specs/src/oauth2/error.ts Resolved
tada5hi added 4 commits May 11, 2026 11:09
…rror, file rename

- Fix grammar in conflict / disk-full messages ("already exist" -> "already exists",
  "due the leak" -> "due to the lack")
- Update .agents docs to reference the new AuthupError classes instead of the
  removed apps/server-core/src/utils/errors.ts helpers
- Remove stray double-space in permission/service.ts import
- OAuth2Error.signingKeyMissing() now sets data.error = "server_error" instead
  of inheriting the "invalid_request" default; adds SERVER_ERROR to OAuth2ErrorCode
  per RFC 6749 §5.2
- Rename apps/server-core/src/core/oauth2/helpers/erorr.ts -> error.ts (pre-existing
  typo, only two import sites)
…e 1.1.0

The convention proposed in tada5hi/ebec#429 shipped in @ebec/core 1.1.0
(plus per-class marker symbols in @ebec/http 4.1.0). Replace our local
packages/errors/src/instanceof.ts with the upstream helpers:

- Bump @ebec/core to ^1.1.0 in @authup/errors
- Bump @ebec/http to ^4.1.0 in apps/server-core
- Delete packages/errors/src/instanceof.ts
- Re-export markInstanceof / hasInstanceof / INSTANCEOF_PROPERTY from the
  @authup/errors barrel so downstream consumers don't need to change imports
- Internal @authup/errors source now imports the helpers directly from @ebec/core

BaseError 1.1.0 also self-marks with BASE_ERROR_INSTANCE in its constructor,
so every AuthupError instance now has an extra '@ebec/core/BaseError' entry
at the start of its @instanceof chain — no behaviour change for our guards
(they key on the Authup-specific markers further up the chain).
The status-table fix in this PR maps OAUTH_CLIENT_INVALID to 401 per
RFC 6749 §5.2 (was 400 via OAuth2Error's BadRequestError inheritance).
Five HTTP-level integration assertions across grant-authorize,
grant-password and grant-refresh-token still asserted the old 400.
Updating them to 401 — no production code change.

Full test suite green: 78 files, 783 tests.
tada5hi added 3 commits May 11, 2026 12:14
…utup to 5.1.1

Retries the upgrade reverted in d042d86. routup 5.1.1 migrated
RoutupError from the old class-field '@instanceof' = SYMBOL convention
to markInstanceof(this, ErrorSymbol), so the new BaseError 1.1.0
self-marker no longer collides.

- @ebec/core: ^1.0.1 -> ^1.1.0
- @ebec/http: ^4.0.0 -> ^4.1.0
- routup: ^5.0.1 -> ^5.1.1
- Delete packages/errors/src/instanceof.ts; re-export markInstanceof /
  hasInstanceof / INSTANCEOF_PROPERTY / BASE_ERROR_INSTANCE from the
  @authup/errors barrel
- Internal @authup/errors source pulls the helpers from @ebec/core

Full test suite: 78 files, 783 tests passing.
…ure-mode classes

The domain error classes in @authup/core-kit (ClientError, RobotError, UserError)
existed purely as factory namespaces — their isClientError / isRobotError guards
were exported but never consumed (the only `isClientError` reference in the
codebase imports from hapic, unrelated). The factories all produced shared
codes (ENTITY_NOT_FOUND, ENTITY_INACTIVE, ENTITY_CREDENTIALS_INVALID), creating
the slow-path ambiguity CodeRabbit flagged in the PR review.

Switching to failure-mode classes: one class per code, domain identity in the
message.

- New in @authup/errors: EntityInactiveError, EntityCredentialsInvalidError
  (alongside existing EntityNotFoundError), with sibling guards in built-in/check.ts
- ClientError.invalid() (the only OAUTH_CLIENT_INVALID factory) folds into
  the existing OAuth2Error.clientInvalid() in @authup/specs
- Delete packages/core-kit/src/domains/{client,robot,user}/error.ts and
  the two unused check.ts files; update barrels

Migrated throw sites:
- core/authentication/entities/{client,robot,user}/module.ts
- core/identity/provider/authentication/protocols/ldap/{module,collection}.ts
- adapters/http/adapters/oauth2/grant-types/client-credentials.ts

Full test suite: 78 files, 783 tests passing.

BREAKING: @authup/core-kit no longer exports ClientError, RobotError, UserError,
isClientError, isRobotError. Consumers should use EntityNotFoundError,
EntityInactiveError, EntityCredentialsInvalidError from @authup/errors and
OAuth2Error.clientInvalid() from @authup/specs.
Stale reference to @ebec/http — the package now extends @ebec/core's BaseError
and exposes built-in subclasses, code -> status mapping, and Symbol.for guards.

Audit-only — no source changes.
Adds an `entity` option on EntityCredentialsInvalidError, EntityInactiveError,
EntityNotFoundError, and EntityConflictError so callers can pass an entity name
and have the message auto-generated from a per-class template. Migrates 17
throw sites from hardcoded strings to the shorthand. Junction sites lose the
word "assignment" in the conflict message (e.g. "The role-permission already
exists.") — the entity name carries that meaning by itself.

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

🧹 Nitpick comments (1)
packages/errors/src/built-in/entity-credentials-invalid.ts (1)

15-26: 💤 Low value

Minor: Consider aligning fallback message with EntityInactiveError pattern.

The fallback message reads "Credentials are invalid." whereas EntityInactiveError uses "Entity is inactive." When an entity is provided both classes use the consistent "The ${entity} ..." form, but the fallback differs. For consistency, consider:

-            message: entity ? `The ${entity} credentials are invalid.` : 'Credentials are invalid.',
+            message: entity ? `The ${entity} credentials are invalid.` : 'Entity credentials are 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/errors/src/built-in/entity-credentials-invalid.ts` around lines 15 -
26, The fallback message in EntityCredentialsInvalidError is inconsistent with
EntityInactiveError; update the fallback string in the constructor of
EntityCredentialsInvalidError (where it builds the super call) from 'Credentials
are invalid.' to 'Entity credentials are invalid.' so it matches the "Entity
..." pattern used when entity is present and aligns with EntityInactiveError's
fallback style.
🤖 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/core/identity/provider/authentication/protocols/ldap/module.ts`:
- Around line 51-54: The code throws EntityCredentialsInvalidError after a
successful LDAP bind but does not unbind the LDAP client first; update the
function in module.ts so that before throwing when this.findOneByName(name)
returns falsy you call the LDAP client's unbind/close method (the same client
used to bind earlier, e.g., client or ldapClient) and await/handle it as needed,
then throw EntityCredentialsInvalidError; ensure the client is also properly
closed in the other error/exit paths to avoid leaking the LDAP session.

---

Nitpick comments:
In `@packages/errors/src/built-in/entity-credentials-invalid.ts`:
- Around line 15-26: The fallback message in EntityCredentialsInvalidError is
inconsistent with EntityInactiveError; update the fallback string in the
constructor of EntityCredentialsInvalidError (where it builds the super call)
from 'Credentials are invalid.' to 'Entity credentials are invalid.' so it
matches the "Entity ..." pattern used when entity is present and aligns with
EntityInactiveError's fallback style.
🪄 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: 322ece82-7505-4df1-b313-4114d3865b91

📥 Commits

Reviewing files that changed from the base of the PR and between 4fc5078 and 2fedbe6.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (34)
  • .agents/structure.md
  • apps/server-core/package.json
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/client-credentials.ts
  • apps/server-core/src/core/authentication/entities/client/module.ts
  • apps/server-core/src/core/authentication/entities/robot/module.ts
  • apps/server-core/src/core/authentication/entities/user/module.ts
  • apps/server-core/src/core/entities/client-permission/service.ts
  • apps/server-core/src/core/entities/client-role/service.ts
  • apps/server-core/src/core/entities/client-scope/service.ts
  • apps/server-core/src/core/entities/identity-provider-role-mapping/service.ts
  • apps/server-core/src/core/entities/permission-policy/service.ts
  • apps/server-core/src/core/entities/robot-permission/service.ts
  • apps/server-core/src/core/entities/robot-role/service.ts
  • apps/server-core/src/core/entities/role-permission/service.ts
  • apps/server-core/src/core/entities/user-permission/service.ts
  • apps/server-core/src/core/entities/user-role/service.ts
  • apps/server-core/src/core/identity/provider/authentication/protocols/ldap/collection.ts
  • apps/server-core/src/core/identity/provider/authentication/protocols/ldap/module.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts
  • packages/core-kit/src/domains/client/error.ts
  • packages/core-kit/src/domains/client/index.ts
  • packages/core-kit/src/domains/robot/error.ts
  • packages/core-kit/src/domains/robot/index.ts
  • packages/core-kit/src/domains/user/error.ts
  • packages/core-kit/src/domains/user/index.ts
  • packages/errors/src/built-in/check.ts
  • packages/errors/src/built-in/entity-conflict.ts
  • packages/errors/src/built-in/entity-credentials-invalid.ts
  • packages/errors/src/built-in/entity-inactive.ts
  • packages/errors/src/built-in/entity-not-found.ts
  • packages/errors/src/built-in/index.ts
  • packages/errors/src/types.ts
💤 Files with no reviewable changes (6)
  • packages/core-kit/src/domains/user/index.ts
  • packages/core-kit/src/domains/robot/index.ts
  • packages/core-kit/src/domains/client/error.ts
  • packages/core-kit/src/domains/user/error.ts
  • packages/core-kit/src/domains/client/index.ts
  • packages/core-kit/src/domains/robot/error.ts
✅ Files skipped from review due to trivial changes (1)
  • .agents/structure.md
🚧 Files skipped from review as they are similar to previous changes (12)
  • apps/server-core/src/core/entities/robot-role/service.ts
  • apps/server-core/src/core/entities/client-scope/service.ts
  • apps/server-core/src/core/entities/robot-permission/service.ts
  • apps/server-core/src/core/entities/permission-policy/service.ts
  • packages/errors/src/built-in/entity-not-found.ts
  • packages/errors/src/built-in/index.ts
  • apps/server-core/src/core/entities/user-role/service.ts
  • apps/server-core/package.json
  • apps/server-core/src/core/entities/client-permission/service.ts
  • apps/server-core/src/core/entities/identity-provider-role-mapping/service.ts
  • apps/server-core/src/core/entities/user-permission/service.ts
  • packages/errors/src/types.ts

tada5hi added 2 commits May 11, 2026 13:45
The initial service-account bind at the top of LDAP authenticate() is
followed by a directory lookup. When the user does not exist, the
function previously threw without unbinding the LDAP client, leaving the
session uncleared. Other failure branches in this function already
unbind first; align this path with the same pattern. Reported by
coderabbitai on PR #3041.
Promotes the foreign-HTTP-status → semantic-ErrorCode translation from
the server-core local helper to a public @authup/errors export, mirroring
the existing httpStatusFromCode (the inverse direction). Any adapter that
sanitizes a foreign HTTPError into an AuthupError needs this — status is
the only stable handshake across @ebec/http and @authup/errors code
vocabularies. Useful for hub once it adopts the same pattern.
@tada5hi
tada5hi merged commit 058c503 into master May 11, 2026
8 checks passed
@tada5hi
tada5hi deleted the refactor/error-handling branch May 11, 2026 12:03
@github-actions github-actions Bot mentioned this pull request May 11, 2026
@github-actions github-actions Bot mentioned this pull request May 15, 2026
tada5hi added a commit to PrivateAIM/hub that referenced this pull request May 19, 2026
…1607)

* feat(errors)!: introduce @privateaim/errors package

Adds a new foundational @privateaim/errors package mirroring the
architecture used in @authup/errors:

- HubError extends BaseError from @ebec/core (no @ebec/http coupling)
- Per-failure-mode classes: BadRequestError, UnauthorizedError,
  InternalError, EntityNotFoundError, EntityConflictError,
  EntityRelationInvalidError, PermissionDeniedError,
  StorageInsufficientError — all extend HubError
- Symbol.for-keyed @instanceof markers (markInstanceof from @ebec/core)
  + sibling check.ts duck-type guards for cross-realm safety
- ErrorCode enum with hub-specific codes (analysis flow + storage)
- ERROR_CODE_TO_STATUS table + httpStatusFromCode + codeFromHttpStatus
  helpers — HTTP-status concern lives in the adapter, not on the class
- EntityNotFoundError / EntityConflictError support { entity: 'X' }
  shorthand for templated messages

Drops the old HubError-extends-BadRequestError shape from
@privateaim/kit. Updates server-http-kit/sanitize.ts and the error
middleware to use httpStatusFromCode (status no longer read off the
class), and rewires AnalysisError to extend the new HubError.

Throw-site sweep across 65 remaining @ebec/http consumers follows in
subsequent commits.

Refs: #1603 (modeled on authup/authup#3041).

* refactor: sweep @ebec/http throw sites to @privateaim/errors

Replaces all @ebec/http class throws with @privateaim/errors equivalents
across 65 source files spanning all apps and packages:

- NotFoundError       → EntityNotFoundError
- ConflictError       → EntityConflictError
- ForbiddenError      → PermissionDeniedError
- ServerError         → InternalError
- BadRequestError     → BadRequestError (just import path change)
- UnauthorizedError   → UnauthorizedError (just import path change)

Updates DatabaseConflictError to extend EntityConflictError. Adds
@privateaim/errors as a dep where needed; drops @ebec/http from every
package.json except server-http-kit (which still uses isHTTPError in
sanitize.ts to translate foreign HTTPError instances).

All package and app builds clean; core-kit unit tests pass (51/51).
Server-core tests fail on an unrelated better-sqlite3 native binding
issue (ERR_DLOPEN_FAILED, environmental).

Refs: #1603.

* chore(errors): adopt entity shorthand, bump routup 5.1.1, lint sweep

- EntityNotFoundError throw sites now use { entity: 'X' } shorthand
  instead of bare/string-message variants. Messages auto-template
  via the class (e.g. "The analysis was not found.").
- Bump routup ^5.1.0 -> ^5.1.1 across all packages. routup 5.1.0
  declared @instanceof as a non-configurable class field, which
  conflicted with @ebec/core 1.1.0's markInstanceof helper and caused
  TypeError: Cannot redefine property: @instanceof at construction.
  5.1.1 migrated to markInstanceof internally.
- Run eslint --fix across all touched files.

All test suites pass: core-kit 51/51, server-core 318/318,
server-storage 65/65, server-telemetry 62/62.

Refs: #1603.

* refactor(errors): address PR review feedback

- lock built-in error code/message invariants against options override
- fix grammar and entity wording in error messages (node, registry-project)
- scope authup master-realm lookup catch to 404 (rethrow other failures)
- guard driver-error code lookup with hasOwnProperty in sanitizeError
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