Repository navigation
feat: extract business logic from controllers into core services - #2910
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughControllers were converted into thin HTTP adapters that build an ActorContext and delegate validation, policy checks, and CRUD to newly added per-entity services; many I*Service interfaces, service implementations, actor types, and DI/controller wiring were introduced across core and adapters. Changes
Sequence Diagram(s)mermaid Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Actionable comments posted: 13
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/adapters/http/controllers/entities/policy/module.ts (1)
67-74:⚠️ Potential issue | 🟠 MajorPreserve the
/expandedendpoint behavior.Line 73 still sets
{ expanded: true }, but Lines 84-89 ignoreoptions, so/policies/:id/expandednow returns the same payload as/policies/:id. Please thread that flag into the service call or keep a dedicated expanded-read path.Also applies to: 76-89
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/policy/module.ts` around lines 67 - 74, The /:id/expanded route currently calls getOne(id, req, res, { expanded: true }) but getOne (in this module) ignores the options and thus returns the same payload as the non-expanded endpoint; update getOne to accept and forward the options object (including the expanded flag) into the underlying service call (e.g., call policyService.getById(id, { expanded: true }) or equivalent) or restore a dedicated expanded-read path that calls the service method which returns expanded data; specifically modify the getOne handler (and any internal call sites that build the service request) to thread the options argument through to the service layer so getOneExpanded actually returns expanded results.
🧹 Nitpick comments (28)
apps/server-core/src/core/entities/role/types.ts (1)
17-21: AvoidRecord<string, any>in the public service interface.Using
anyhere weakens compile-time type guarantees. While the implementation validates data at runtime usingRoleValidator, this pattern is inconsistent with TypeScript best practices. PreferRecord<string, unknown>or typed DTOs forquery/datapayloads to improve type safety across the codebase.♻️ Proposed refactor
+export type RoleServiceQuery = Record<string, unknown>; +export type RoleServiceInput = Record<string, unknown>; + export interface IRoleService { - getMany(query: Record<string, any>, actor: ActorContext): Promise<EntityRepositoryFindManyResult<Role>>; + getMany(query: RoleServiceQuery, actor: ActorContext): Promise<EntityRepositoryFindManyResult<Role>>; getOne(idOrName: string, actor: ActorContext): Promise<Role>; - create(data: Record<string, any>, actor: ActorContext): Promise<Role>; - update(idOrName: string, data: Record<string, any>, actor: ActorContext): Promise<Role>; - save(idOrName: string | undefined, data: Record<string, any>, actor: ActorContext): Promise<{ entity: Role, created: boolean }>; + create(data: RoleServiceInput, actor: ActorContext): Promise<Role>; + update(idOrName: string, data: RoleServiceInput, actor: ActorContext): Promise<Role>; + save(idOrName: string | undefined, data: RoleServiceInput, actor: ActorContext): Promise<{ entity: Role, created: boolean }>; delete(id: string, actor: ActorContext): Promise<Role>; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/role/types.ts` around lines 17 - 21, The public Role service interface currently uses Record<string, any> for payloads in methods getMany, create, update, and save — replace those any types with Record<string, unknown> (or, better, explicit DTO types) so callers get stronger compile-time guarantees; update the signatures of getMany(query: Record<string, unknown>, actor: ActorContext), create(data: Record<string, unknown>, actor: ActorContext), update(idOrName: string, data: Record<string, unknown>, actor: ActorContext), and save(idOrName: string | undefined, data: Record<string, unknown>, actor: ActorContext) and adjust any callers or tests accordingly, keeping runtime validation with RoleValidator unchanged until you migrate to a typed DTO.apps/server-core/src/app/modules/database/repositories/user/repository.ts (1)
174-182: Consider consistency with otherfindOne*methods.Two observations:
Missing
extendOneWithEAcall: OtherfindOne*methods (e.g.,findOneById,findOneByName,findOne) callthis.repository.extendOneWithEA(entity)before returning. This method does not, which may cause inconsistent behavior if entity attributes are expected.Method naming:
findOneByWithEmailis grammatically awkward. ConsiderfindOneWithEmailorfindOneByIncludingEmailfor clarity.♻️ Proposed fix for consistency
async findOneByWithEmail(where: Record<string, any>): Promise<User | null> { const qb = this.repository.createQueryBuilder('user'); qb.addSelect('user.email'); const translated = translateWhereConditions(where); qb.where(translated); - return qb.getOne(); + const entity = await qb.getOne(); + if (entity) { + await this.repository.extendOneWithEA(entity); + } + return entity; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/modules/database/repositories/user/repository.ts` around lines 174 - 182, The method findOneByWithEmail lacks the same post-processing as other findOne* methods: call this.repository.extendOneWithEA(entity) on the returned entity before returning to ensure entity attributes are extended (mirror behavior in findOneById, findOneByName, findOne). Also rename the method to a clearer name (suggest findOneWithEmail or findOneByIncludingEmail) and update any callers to the new name to keep naming consistent across the repository.apps/server-core/src/adapters/http/request/helpers/actor.ts (1)
9-9: Prefer a narrowerActorContextimport to reduce barrel coupling.Importing from the root core barrel here is broader than needed; importing from the actor module keeps boundaries tighter.
♻️ Proposed refactor
-import type { ActorContext } from '../../../../core/index.ts'; +import type { ActorContext } from '../../../../core/entities/actor/index.ts';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/request/helpers/actor.ts` at line 9, The import currently pulls ActorContext from the root core barrel (import type { ActorContext } from '../../../../core/index.ts'); change it to import the narrower type directly from the actor module that actually exports it (e.g., '../../../../core/actor' or the module that defines ActorContext) to avoid barrel coupling—update the import for ActorContext in actor.ts to reference the actor-specific module instead of core/index.ts.apps/server-core/src/core/identity/password-recovery/types.ts (1)
31-34: Type the service inputs explicitly.These methods are the new handler/service boundary, and
Record<string, any>drops the compile-time guarantees the split is supposed to add. Please introduce dedicated forgot/reset request DTOs and expose them in this interface.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/types.ts` around lines 31 - 34, Replace the broad Record<string, any> inputs on IPasswordRecoveryService with explicit DTO types: introduce and export a ForgotPasswordRequest and ResetPasswordRequest (or similarly named) type/interface in this module and use them as the parameter types for forgotPassword and resetPassword while keeping the existing PasswordForgotResult and PasswordResetResult return types; update the IPasswordRecoveryService signature to accept these new DTOs and ensure the DTOs include the required fields (e.g., email, token, newPassword) used by the implementing handlers.apps/server-core/src/core/identity/password-recovery/service.ts (3)
64-67: Extract magic number for reset token expiry.The 30-minute expiry (
1000 * 60 * 30) is hardcoded. Consider extracting this to a named constant or making it configurable viaoptionsfor clarity and flexibility.✨ Suggested improvement
+const RESET_TOKEN_EXPIRY_MS = 1000 * 60 * 30; // 30 minutes + // In forgotPassword method: const merged = this.repository.merge(entity, { - reset_expires: new Date(Date.now() + (1000 * 60 * 30)).toISOString(), + reset_expires: new Date(Date.now() + RESET_TOKEN_EXPIRY_MS).toISOString(), reset_hash: randomBytes(32).toString('hex'), });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 64 - 67, The hardcoded 30-minute expiry used when creating the recovery token (in the repository.merge call that sets reset_expires and reset_hash) should be replaced with a named constant or configurable option; add a constant like PASSWORD_RESET_TTL_MS or accept an options parameter (e.g., passwordResetTtlMs) on the service, use that value instead of 1000 * 60 * 30 when computing reset_expires, and update any tests or callers to use the new constant/option; keep reset_hash generation (randomBytes(32).toString('hex')) unchanged.
121-161: Duplicate validator logic betweenrunForgotPasswordValidatorandrunResetPasswordValidator.Both validators share the same oneOf email/name container and realm_id validation. Consider extracting the shared validation logic into a reusable helper to reduce duplication.
Also applies to: 163-227
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 121 - 161, Extract the duplicated validation setup (the oneOf container that mounts 'email' and 'name' and the 'realm_id' optional UUID validator) into a reusable helper function (e.g., buildIdentitySelectorValidator or createForgotResetValidator). The helper should return a Container pre-mounted with the oneOf email/name validators and the optional 'realm_id' validator so both runForgotPasswordValidator and runResetPasswordValidator can call it and simply run(data) on the returned Container; update both functions to use this helper and remove the duplicated mounting logic.
104-105: Inconsistent dependency injection forUserCredentialsService.
UserCredentialsServiceis instantiated inline while other dependencies (repositories, mailClient) are injected via context. For consistency and testability, consider injecting this service through the context.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 104 - 105, The code instantiates UserCredentialsService inline (new UserCredentialsService()) which breaks DI consistency and testability; instead add UserCredentialsService to the existing context object used by the password recovery flow, retrieve it from context where the current instantiation occurs (e.g., use ctx.userCredentialsService or equivalent), and call its protect method (protect) from that injected instance; update the context/type declarations and any callers or tests to provide a mockable UserCredentialsService rather than creating it inline.apps/server-core/src/adapters/http/controllers/workflows/password-forgot/module.ts (1)
36-38: Consider resolving the type mismatch instead of suppressing the error.The
@ts-expect-errorcomment indicates a type incompatibility between thesendAcceptedreturn type andPasswordForgotResponse. This could mask future type errors or indicate an API contract issue.Consider either:
- Adjusting the return type annotation to match
sendAccepted's actual return- Wrapping the result appropriately so types align
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/workflows/password-forgot/module.ts` around lines 36 - 38, The ts-expect-error hides a type mismatch between sendAccepted(...) and the declared PasswordForgotResponse; remove the suppression and fix the types by either changing the controller/module function's return type to match sendAccepted's actual return type or by transforming/wrapping the result into the shape sendAccepted expects before calling it (refer to sendAccepted and PasswordForgotResponse symbols and the module's exported handler function where the call is made), so the call type-checks without `@ts-expect-error`.apps/server-core/src/adapters/http/controllers/entities/permission/module.ts (1)
84-145: Consider migratingcheck()to the service layer for consistency.The
check()endpoint performs permission verification using direct repository access and inlinePermissionCheckerinstantiation. While this is understandable for a specialized verification endpoint, it creates an inconsistency with the service-oriented architecture being established.Consider whether this logic should be encapsulated in a service method (e.g.,
service.checkPermission(id, data, actor)) to maintain a consistent abstraction layer.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/permission/module.ts` around lines 84 - 145, The check() controller method contains business logic and direct repository/policy-engine wiring; extract this into a service method (e.g., PermissionService.checkPermission) that accepts (id, data, actor, realmId) and returns a PermissionAPICheckResponse or throws; move entity resolution (realmRepository.resolve and repository.findOneBy) and the PermissionChecker instantiation (PermissionChecker, PermissionDatabaseRepository, PolicyEngine, PolicyData) into that service, update the controller to call service.checkPermission and simply sendAccepted(res, result); keep error translation in the service or let the controller map thrown errors into the same {status:'error', data:Error} shape.apps/server-core/src/adapters/http/controllers/entities/client/module.ts (2)
92-100: Inefficient secret retrieval inside attribute loop.The secret is fetched inside the loop iterating over attributes. If
'secret'appears in the attributes list, this triggers a database query. Consider fetching the secret once before the loop if the attribute is present:♻️ Proposed refactor
+ if (attributes.includes('secret')) { + const withSecret = await this.repository.findOneWithSecret({ id: entity.id }); + if (withSecret) { + entity.secret = withSecret.secret; + } + } - for (let i = 0; i < attributes.length; i++) { - const attr = attributes[i] as keyof Client; - if (attr === 'secret') { - const withSecret = await this.repository.findOneWithSecret({ id: entity.id }); - if (withSecret) { - entity.secret = withSecret.secret; - } - } - }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/client/module.ts` around lines 92 - 100, The loop in the module that iterates over attributes performs a DB call each time it hits 'secret' — move the repository.findOneWithSecret call out of the for-loop: first check if attributes includes 'secret', if so call this.repository.findOneWithSecret({ id: entity.id }) once and assign entity.secret from the result, then run the existing attributes loop (or filter out 'secret') to avoid repeated queries; refer to attributes, entity, and this.repository.findOneWithSecret in the current module to locate and update the logic.
79-103: Inconsistent data access pattern: repository used for "isMe" case vs. service for others.The
get()method uses direct repository access for the self-token case (lines 83-102) while delegating to the service for non-self requests (line 106). This bypasses the service layer's authorization and business logic for authenticated clients fetching their own data.Consider consolidating this logic into the service layer to maintain consistent authorization checks and reduce code duplication.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/client/module.ts` around lines 79 - 103, The current "isMe" branch in get() bypasses the service layer by calling repository.findOneByIdOrName and repository.findOneWithSecret directly; move this logic into the service (e.g., add or extend a method like ClientService.getByIdForSelf or ClientService.get with an isMe flag) so the service performs authorization, attribute resolution (use OAuth2ScopeAttributesResolver and useRequestScopes(req)), and secret inclusion as needed; replace the direct repository.findOneByIdOrName / findOneWithSecret and the send(res, entity) call with a single service call that returns the properly filtered Client entity, ensuring consistent business logic and avoiding duplicated access patterns.apps/server-core/src/core/entities/client/service.ts (2)
210-210:ClientCredentialsServiceinstantiated inline rather than injected.Creating a new instance of
ClientCredentialsServiceinside the method couples the service to a concrete implementation. Consider injecting it viaClientServiceContextfor better testability and consistency with the dependency injection pattern used elsewhere.♻️ Proposed refactor
export type ClientServiceContext = { repository: IClientRepository; realmRepository: IRealmRepository; + credentialsService?: ClientCredentialsService; }; // In constructor: +this.credentialsService = ctx.credentialsService ?? new ClientCredentialsService(); // In save method: -const credentialsService = new ClientCredentialsService(); +const credentialsService = this.credentialsService;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/client/service.ts` at line 210, Replace the inline instantiation "new ClientCredentialsService()" in the method with a dependency provided by ClientServiceContext: add a ClientCredentialsService (or an interface) property to the ClientServiceContext and read it inside the method (or accept it via the surrounding class constructor) so the service is injected rather than constructed inline; update the ClientService constructor or factory to supply the ClientCredentialsService implementation and adjust callers/tests to pass a mock or real instance, and add a defensive check that the injected ClientCredentialsService exists before use.
268-270: Inconsistent argument passed toprotect()between create and update paths.In the update path (line 238),
protect(validated.secret, entity)uses the mergedentity. In the create path (line 270),protect(validated.secret, validated)usesvalidatedinstead ofentity. Sinceentitywas just created fromvalidatedon line 263, they should be equivalent, but usingentityconsistently would be clearer.♻️ Proposed fix for consistency
- entity.secret = await credentialsService.protect(validated.secret, validated); + entity.secret = await credentialsService.protect(validated.secret, entity);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/client/service.ts` around lines 268 - 270, The create path is calling credentialsService.protect(validated.secret, validated) while the update path uses credentialsService.protect(validated.secret, entity); change the create-path call to credentialsService.protect(validated.secret, entity) so both create and update consistently pass the merged entity object (entity) to protect(), referencing the protect method on credentialsService and the local variables entity and validated.apps/server-core/src/adapters/http/controllers/entities/robot-role/module.ts (2)
27-31: Context still includesrepositorybut it appears unused.The
RobotRoleControllerContextincludes bothserviceandrepository, but after the refactor, onlyserviceis used ingetMany,getOne, anddelete. Consider whetherrepositoryandidentityPermissionServicecan be removed from the context or if the remaining logic inadd()(lines 70-82) should be moved to the service layer for consistency.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/robot-role/module.ts` around lines 27 - 31, RobotRoleControllerContext currently includes repository and identityPermissionService but repository is unused in getMany/getOne/delete; either remove repository (and identityPermissionService if it's unused elsewhere) from RobotRoleControllerContext to keep the controller context minimal, or move the logic inside add() (which references identityPermissionService/repository on lines ~70-82) into the IRobotRoleService (e.g., addRole or createRole) so the controller only calls service.add(...) and the context only needs service; update RobotRoleControllerContext and controller methods (getMany, getOne, delete, add) and the service interface/implementation accordingly to ensure callers compile.
70-84: Permission superset check remains in controller, breaking service delegation pattern.The
addmethod still performsvalidateJoinColumnsand identity permission checks directly in the controller (lines 70-82), while delegatingcreateto the service. This creates inconsistency with other controllers that fully delegate authorization to the service layer.Consider moving this logic into
RobotRoleService.create()to maintain a consistent architecture where all business logic and authorization reside in the service.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/robot-role/module.ts` around lines 70 - 84, The controller currently calls this.repository.validateJoinColumns(data) and performs an identity permission check using useRequestIdentityOrFail and this.identityPermissionService.isSuperset before calling this.service.create; move these responsibilities into RobotRoleService.create so the controller only forwards the request. Specifically, remove validateJoinColumns and the isSuperset block from the controller and implement equivalent logic inside RobotRoleService.create (or a private helper it calls): validateJoinColumns(data) (or delegate to the repository), resolve identity via useRequestIdentityOrFail (or accept identity as a parameter) and call identityPermissionService.isSuperset({ type: 'role', id: data.role_id, clientId: data.role.client_id }) to throw ForbiddenError when appropriate, then proceed with creation—ensuring RobotRoleService.create enforces both join-column validation and authorization.apps/server-core/src/adapters/http/controllers/entities/user-permission/module.ts (1)
64-74: Unusedidparameter from@DPathdecorator.The
idparameter extracted via@DPath('id')is declared but not used; instead,useRequestParamID(req)is called. This pattern is repeated indropas well. Consider using theidparameter directly or removing the@DPathdecorator parameter if the helper is preferred.♻️ Option 1: Use the extracted id parameter directly
`@DGet`('/:id', [ForceLoggedInMiddleware]) async getOne( `@DPath`('id') id: string, `@DRequest`() req: any, `@DResponse`() res: any, ): Promise<any> { const actor = buildActorContext(req); - const entity = await this.service.getOne(useRequestParamID(req), actor); + const entity = await this.service.getOne(id, actor); return send(res, entity); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/user-permission/module.ts` around lines 64 - 74, The `@DPath`('id') parameter in getOne (and similarly in drop) is extracted as id but never used—replace useRequestParamID(req) with the extracted id parameter or remove the unused `@DPath` and parameter; specifically, update the getOne method (and drop method) to call this.service.getOne(id, actor) (or this.service.drop(id, actor)) using the id argument from `@DPath`('id') so the decorator value is actually used, or remove the `@DPath`('id') and its id parameter if you prefer to keep useRequestParamID(req).apps/server-core/src/core/entities/permission/service.ts (1)
169-176: Duplicate policy realm validation logic.The same policy-realm consistency check appears twice: once in the update path (lines 169-176) and once in the create path (lines 199-206). Consider extracting this into a private helper method to reduce duplication.
♻️ Proposed refactor to extract helper
+ private validatePolicyRealmConsistency( + policy: { realm_id?: string } | undefined, + entityRealmId: string | undefined | null, + ): void { + if ( + policy?.realm_id && + entityRealmId && + policy.realm_id !== entityRealmId + ) { + throw new BadRequestError('Policy realm and permission realm must be equal.'); + } + } // In update path: - if ( - validated.policy && - validated.policy.realm_id && - entity.realm_id && - validated.policy.realm_id !== entity.realm_id - ) { - throw new BadRequestError('Policy realm and permission realm must be equal.'); - } + this.validatePolicyRealmConsistency(validated.policy, entity.realm_id); // In create path: - if ( - validated.policy && - validated.policy.realm_id && - validated.realm_id && - validated.policy.realm_id !== validated.realm_id - ) { - throw new BadRequestError('Policy realm and permission realm must be equal.'); - } + this.validatePolicyRealmConsistency(validated.policy, validated.realm_id);Also applies to: 199-206
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/permission/service.ts` around lines 169 - 176, Duplicate policy-realm consistency checks in PermissionService should be consolidated: add a private helper method on the PermissionService class (e.g., validatePolicyRealmConsistency(validated: PermissionInput, entity?: PermissionEntity)) that checks if validated.policy?.realm_id and entity?.realm_id both exist and are unequal and throws BadRequestError('Policy realm and permission realm must be equal.'), then replace the duplicated blocks inside the update path (the block that references validated.policy && validated.policy.realm_id && entity.realm_id ...) and the create path (the similar block at lines ~199-206) with a single call to that helper.apps/server-core/src/adapters/http/controllers/entities/client-permission/module.ts (1)
76-89: Unusedidparameter from@DPathdecorator indropmethod.Same pattern as other controllers - the
idparameter is declared butuseRequestParamID(req, { isUUID: false })is used instead.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/client-permission/module.ts` around lines 76 - 89, The drop method declares an unused parameter from the `@DPath`('id') decorator; remove the unused "id" parameter declaration from the drop method signature so the method becomes async drop(`@DRequest`() req: any, `@DResponse`() res: any) and keep using useRequestParamID(req, { isUUID: false }) when calling this.service.delete; update references to the parameter list in the drop function accordingly (function name: drop, decorator: `@DPath`('id'), helper: useRequestParamID).apps/server-core/src/core/entities/realm/service.ts (1)
38-53: Realm read operations are intentionally public; add a clarifying comment.The
getManyandgetOnemethods lackActorContextand permission checks by design—realms are infrastructure entities that must be publicly readable to support OAuth2/OpenID endpoints like JWKS and.well-known/openid-configuration. This differs from user/role/permission services where read access is permission-gated. Consider adding a comment in the class or interface explaining this design decision to prevent future confusion.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/realm/service.ts` around lines 38 - 53, Add a short clarifying comment in the Realm service explaining that getMany and getOne intentionally omit ActorContext and permission checks because realms are public infrastructure entities used by OAuth2/OpenID endpoints (e.g., JWKS and .well-known/openid-configuration); place this comment either at the top of the Realm service class or immediately above the getMany/getOne methods (symbols: getMany, getOne, Realm service) so future maintainers understand the design intent and do not add permission gating.apps/server-core/src/core/entities/robot/service.ts (2)
198-198: Consider reusing RobotCredentialsService instance.
RobotCredentialsServiceis instantiated insidesave()on every call. If this service is stateless, consider making it a class member initialized in the constructor for minor efficiency gains.💡 Suggested refactor
export class RobotService extends AbstractEntityService implements IRobotService { protected repository: IRobotRepository; protected realmRepository: IRealmRepository; protected validator: RobotValidator; + protected credentialsService: RobotCredentialsService; constructor(ctx: RobotServiceContext) { super(); this.repository = ctx.repository; this.realmRepository = ctx.realmRepository; this.validator = new RobotValidator(); + this.credentialsService = new RobotCredentialsService(); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/robot/service.ts` at line 198, The code currently creates a new RobotCredentialsService inside save() on every call; instead add a private readonly member (e.g. this.credentialsService) initialized in the RobotService constructor and replace the local instantiation in save() with this.credentialsService so the same instance is reused; update any references to the local variable in save() to use the class member and ensure the constructor imports/constructs RobotCredentialsService once.
60-88: Post-fetch permission filtering may have performance implications.The
getManymethod fetches all entities first, then iterates and checks permissions per-entity with try/catch. For large result sets, this creates N+1 permission checks. Consider:
- Documenting this behavior for operators
- If this becomes a bottleneck, exploring query-level filtering based on actor permissions
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/robot/service.ts` around lines 60 - 88, The current getMany loop performs per-entity permission checks (using actor.permissionChecker.checkOneOf with PermissionName.ROBOT_READ/UPDATE/DELETE and PolicyData/BuiltInPolicyType) which causes N+1 permission checks; update the code by adding a clear inline comment and/or method-level docstring on getMany documenting this behavior and its performance implications for operators, and, as a follow-up optimization, prepare the service to support query-level filtering (e.g., by augmenting the repository query with actor-scoped predicates) so callers can opt into DB-level filtering instead of per-entity checks; keep the existing identity shortcut (actor.identity.type === 'robot') but mark the per-entity try/catch block as a potential hotspot and add a TODO referencing actor.permissionChecker.checkOneOf to implement batched or query-level permission evaluation later.apps/server-core/src/core/entities/user/service.ts (1)
219-219: Same suggestion: consider reusing UserCredentialsService instance.Similar to
RobotService,UserCredentialsServiceis instantiated insidesave(). Consider making it a class member if it's stateless.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/user/service.ts` at line 219, The save() method currently constructs a new UserCredentialsService instance inline (const credentialsService = new UserCredentialsService()), which duplicates RobotService's pattern—if UserCredentialsService is stateless, make it a class-level member on the same class (initialize it in the constructor or as a private property) and replace the inline instantiation in save() with a reference to that member (e.g., this.userCredentialsService) to reuse the instance and keep behavior consistent with RobotService.apps/server-core/src/adapters/http/controllers/entities/user-role/module.ts (2)
27-31: Context still includes repository despite service migration.
UserRoleControllerContextincludes bothserviceandrepository. If the goal is full service delegation, the controller should ideally not require direct repository access. However, given the current validation logic inadd(), this may be intentional for now.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/user-role/module.ts` around lines 27 - 31, UserRoleControllerContext currently exposes IUserRoleRepository alongside IUserRoleService; remove IUserRoleRepository from the context type (UserRoleControllerContext) and update all places that construct/consume that context to stop passing the repository so the controller only depends on the service; then move any direct repository-based validation inside the service (adjust the add() handler to call service.validate/Add methods instead of accessing the repository) or, if you intentionally need repository access for now, add a clear TODO and narrow the exported type to reflect that temporary need (reference: UserRoleControllerContext, IUserRoleService, IUserRoleRepository, add()).
59-87: Consider moving validation and permission superset check into the service layer.The
addmethod performsrepository.validateJoinColumns(data)andidentityPermissionService.isSuperset()checks in the controller, while other operations delegate entirely to the service. For consistency with the service-oriented pattern introduced in this PR, consider encapsulating this logic inIUserRoleService.create().🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/user-role/module.ts` around lines 59 - 87, The controller's add method currently performs join-column validation and permission checks (repository.validateJoinColumns(data) and identityPermissionService.isSuperset(...)) which should be moved into the service layer for consistency; update IUserRoleService.create (and its implementation used by service.create) to accept the request data plus the caller identity or req (e.g., change signature to create(data, actor, identityOrReq)) and implement the logic there: run repository.validateJoinColumns(data) and call identityPermissionService.isSuperset(...) (using useRequestIdentityOrFail(req) or the passed identity) before creating the entity; then simplify the controller.add to build actor, validate input with UserRoleRequestValidator, and call service.create(data, actor[, identity]) and return sendCreated(res, entity). Ensure unique symbols touched: add (controller), repository.validateJoinColumns, identityPermissionService.isSuperset, useRequestIdentityOrFail, IUserRoleService.create / service.create.apps/server-core/src/adapters/http/controllers/workflows/password-reset/module.ts (1)
29-39: Consider addressing the type mismatch instead of suppressing it.The
@ts-expect-errorcomment suppresses a type error on line 38. This typically indicates a mismatch between the declared return type (PasswordResetResponse) and whatsendAcceptedreturns. Consider either adjusting the method signature to match the actual return type or ensuring the types align properly.💡 Suggested approach
If the method should return
PasswordResetResponsedirectly:- ): Promise<PasswordResetResponse> { + ): Promise<any> {Or ensure
sendAcceptedreturn type aligns withPasswordResetResponse.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/workflows/password-reset/module.ts` around lines 29 - 39, The `@ts-expect-error` hides a type mismatch between the declared return type of execute (Promise<PasswordResetResponse>) and the actual value returned by sendAccepted(res, result); fix by aligning types: either change execute's signature to return Promise<Response> (or Promise<void>) if you intend to return the Express response, or change sendAccepted's type to return PasswordResetResponse (or wrap/unwrap its result so execute returns a true PasswordResetResponse). Update the execute function (and/or sendAccepted declaration) and remove the ts-expect-error so the compiler enforces the correct type relationship between execute, sendAccepted, and PasswordResetResponse; use symbols: execute, this.service.resetPassword, useRequestBody, sendAccepted, PasswordResetResponse to locate the code to change.apps/server-core/src/core/entities/scope/service.ts (1)
156-161: Consider consistency with RobotService realm assignment logic.This block only assigns
realm_idwhen the actor is not a master realm member. TheRobotService.save(lines 225-230) unconditionally assignsrealm_idfrom the actor context when missing. Verify this difference is intentional—it may lead to inconsistent behavior where scopes created by master realm members have norealm_id, while robots always inherit one.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/scope/service.ts` around lines 156 - 161, The realm assignment for actors is inconsistent with RobotService.save: in the Scope service block (functions using isActorMasterRealmMember and getActorRealmId) only non-master actors get realm_id assigned, whereas RobotService.save unconditionally assigns realm_id when missing; update the Scope service logic to mirror RobotService.save by assigning validated.realm_id = this.getActorRealmId(actor) || null whenever validated.realm_id is falsy (remove the conditional check against isActorMasterRealmMember), or if the original behavior is intended add a clarifying comment and unit tests; reference isActorMasterRealmMember, getActorRealmId, and RobotService.save when making the change.apps/server-core/src/adapters/http/controllers/entities/robot/module.ts (1)
100-184: Mixed service/repository usage ingetOnecreates inconsistency.The
isMebranch (lines 143-167) bypasses the service layer entirely and accesses the repository directly, while the non-isMebranch (lines 168-176) uses the service. This creates:
- Inconsistent authorization semantics between paths
- Potential for drift as service logic evolves
Consider either:
- Adding a
getMemethod to the service that handles the scope-aware attribute resolution- Documenting why the
isMepath requires direct repository access🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/robot/module.ts` around lines 100 - 184, The controller's getOne mixes direct repository access (repository.findOneByIdOrName, dataSource.getRepository(RobotEntity), repository.findOneWithSecret) with service.getOne, causing inconsistent auth/logic; add a service method (e.g., service.getMe or service.findOneForIdentity) that encapsulates the OAuth2ScopeAttributesResolver logic, resolves attributes for OAuth2SubKind.ROBOT, fetches the robot (using repository.findOneByIdOrName), and conditionally loads the secret (using repository.findOneWithSecret and RobotEntity metadata) when scopes include 'secret'; then replace the in-controller repository logic in the isMe branch of getOne to call that new service method and return its result so both branches go through the service layer and share consistent authorization/attribute handling.apps/server-core/src/app/modules/http/modules/controller.ts (1)
374-392: Extract the shared user-lifecycle service wiring.These two helpers rebuild the same
Config/UserRepositoryAdapter/RealmRepositoryAdapter/IMailClientgraph. One constructor change now has to be kept in sync twice.♻️ Suggested refactor
+ createUserLifecycleDependencies(container: IDIContainer) { + const config = container.resolve<Config>(ConfigInjectionKey); + const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource); + const realmRepository = container.resolve<Repository<Realm>>(RealmEntity); + + return { + mailClient: container.resolve<IMailClient>(MailInjectionKey), + repository: new UserRepositoryAdapter({ + repository: new UserRepository(dataSource), + realmRepository, + }), + realmRepository: new RealmRepositoryAdapter(realmRepository), + options: { + registration: config.registration, + emailVerification: config.emailVerification, + }, + }; + } + createPasswordRecoveryService(container: IDIContainer) { - const config = container.resolve<Config>(ConfigInjectionKey); - const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource); - const realmRepository = container.resolve<Repository<Realm>>(RealmEntity); - const repository = new UserRepositoryAdapter({ - repository: new UserRepository(dataSource), - realmRepository, - }); - const mailClient = container.resolve<IMailClient>(MailInjectionKey); - - return new PasswordRecoveryService({ - mailClient, - repository, - realmRepository: new RealmRepositoryAdapter(realmRepository), - options: { - registration: config.registration, - emailVerification: config.emailVerification, - }, - }); + return new PasswordRecoveryService( + this.createUserLifecycleDependencies(container), + ); } createRegistrationService(container: IDIContainer) { - const config = container.resolve<Config>(ConfigInjectionKey); - const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource); - const realmRepository = container.resolve<Repository<Realm>>(RealmEntity); - const repository = new UserRepositoryAdapter({ - repository: new UserRepository(dataSource), - realmRepository, - }); - const mailClient = container.resolve<IMailClient>(MailInjectionKey); - - return new RegistrationService({ - mailClient, - repository, - realmRepository: new RealmRepositoryAdapter(realmRepository), - options: { - registration: config.registration, - emailVerification: config.emailVerification, - }, - }); + return new RegistrationService( + this.createUserLifecycleDependencies(container), + ); }Also applies to: 401-419
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 374 - 392, The code duplicates wiring for Config, DataSource, Realm repository, UserRepositoryAdapter, RealmRepositoryAdapter and IMailClient when constructing PasswordRecoveryService (and again at the other block around lines 401-419); extract that common graph into a single helper (e.g., buildUserLifecycleDeps or resolveUserLifecycleServices) that resolves Config via ConfigInjectionKey, DataSource via DatabaseInjectionKey.DataSource, realmRepository via RealmEntity, instantiates UserRepositoryAdapter with new UserRepository(dataSource) and the resolved realmRepository, wraps realmRepository with RealmRepositoryAdapter, and resolves IMailClient via MailInjectionKey, then return the bundled objects (config, repository, realmRepositoryAdapter, mailClient) and use that helper in createPasswordRecoveryService and the other duplicated constructor site so the PasswordRecoveryService({...}) calls only consume the shared bundle and stay in sync with constructor changes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 6c1cf854-503b-4076-9931-3106f9539ca0
📒 Files selected for processing (95)
apps/server-core/src/adapters/http/controllers/entities/client-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/client-role/module.tsapps/server-core/src/adapters/http/controllers/entities/client-scope/module.tsapps/server-core/src/adapters/http/controllers/entities/client/module.tsapps/server-core/src/adapters/http/controllers/entities/permission/module.tsapps/server-core/src/adapters/http/controllers/entities/policy/module.tsapps/server-core/src/adapters/http/controllers/entities/realm/module.tsapps/server-core/src/adapters/http/controllers/entities/robot-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/robot-role/module.tsapps/server-core/src/adapters/http/controllers/entities/robot/module.tsapps/server-core/src/adapters/http/controllers/entities/role-attribute/module.tsapps/server-core/src/adapters/http/controllers/entities/role-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/role/module.tsapps/server-core/src/adapters/http/controllers/entities/scope/module.tsapps/server-core/src/adapters/http/controllers/entities/user-attribute/module.tsapps/server-core/src/adapters/http/controllers/entities/user-attribute/utils/index.tsapps/server-core/src/adapters/http/controllers/entities/user-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/user-role/module.tsapps/server-core/src/adapters/http/controllers/entities/user/module.tsapps/server-core/src/adapters/http/controllers/workflows/activate/module.tsapps/server-core/src/adapters/http/controllers/workflows/password-forgot/module.tsapps/server-core/src/adapters/http/controllers/workflows/password-forgot/validator.tsapps/server-core/src/adapters/http/controllers/workflows/password-reset/module.tsapps/server-core/src/adapters/http/controllers/workflows/password-reset/validator.tsapps/server-core/src/adapters/http/controllers/workflows/register/module.tsapps/server-core/src/adapters/http/controllers/workflows/register/validator.tsapps/server-core/src/adapters/http/request/helpers/actor.tsapps/server-core/src/adapters/http/request/helpers/index.tsapps/server-core/src/app/modules/database/repositories/user/repository.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/core/entities/actor/index.tsapps/server-core/src/core/entities/actor/types.tsapps/server-core/src/core/entities/client-permission/index.tsapps/server-core/src/core/entities/client-permission/service.tsapps/server-core/src/core/entities/client-permission/types.tsapps/server-core/src/core/entities/client-role/index.tsapps/server-core/src/core/entities/client-role/service.tsapps/server-core/src/core/entities/client-role/types.tsapps/server-core/src/core/entities/client-scope/index.tsapps/server-core/src/core/entities/client-scope/service.tsapps/server-core/src/core/entities/client-scope/types.tsapps/server-core/src/core/entities/client/index.tsapps/server-core/src/core/entities/client/service.tsapps/server-core/src/core/entities/client/types.tsapps/server-core/src/core/entities/index.tsapps/server-core/src/core/entities/permission/index.tsapps/server-core/src/core/entities/permission/service.tsapps/server-core/src/core/entities/permission/types.tsapps/server-core/src/core/entities/policy/index.tsapps/server-core/src/core/entities/policy/service.tsapps/server-core/src/core/entities/policy/types.tsapps/server-core/src/core/entities/realm/index.tsapps/server-core/src/core/entities/realm/service.tsapps/server-core/src/core/entities/realm/types.tsapps/server-core/src/core/entities/robot-permission/index.tsapps/server-core/src/core/entities/robot-permission/service.tsapps/server-core/src/core/entities/robot-permission/types.tsapps/server-core/src/core/entities/robot-role/index.tsapps/server-core/src/core/entities/robot-role/service.tsapps/server-core/src/core/entities/robot-role/types.tsapps/server-core/src/core/entities/robot/index.tsapps/server-core/src/core/entities/robot/service.tsapps/server-core/src/core/entities/robot/types.tsapps/server-core/src/core/entities/role-attribute/index.tsapps/server-core/src/core/entities/role-attribute/service.tsapps/server-core/src/core/entities/role-attribute/types.tsapps/server-core/src/core/entities/role-permission/index.tsapps/server-core/src/core/entities/role-permission/service.tsapps/server-core/src/core/entities/role-permission/types.tsapps/server-core/src/core/entities/role/index.tsapps/server-core/src/core/entities/role/service.tsapps/server-core/src/core/entities/role/types.tsapps/server-core/src/core/entities/scope/index.tsapps/server-core/src/core/entities/scope/service.tsapps/server-core/src/core/entities/scope/types.tsapps/server-core/src/core/entities/service.tsapps/server-core/src/core/entities/user-attribute/index.tsapps/server-core/src/core/entities/user-attribute/service.tsapps/server-core/src/core/entities/user-attribute/types.tsapps/server-core/src/core/entities/user-permission/index.tsapps/server-core/src/core/entities/user-permission/service.tsapps/server-core/src/core/entities/user-permission/types.tsapps/server-core/src/core/entities/user-role/index.tsapps/server-core/src/core/entities/user-role/service.tsapps/server-core/src/core/entities/user-role/types.tsapps/server-core/src/core/entities/user/index.tsapps/server-core/src/core/entities/user/service.tsapps/server-core/src/core/entities/user/types.tsapps/server-core/src/core/identity/index.tsapps/server-core/src/core/identity/password-recovery/index.tsapps/server-core/src/core/identity/password-recovery/service.tsapps/server-core/src/core/identity/password-recovery/types.tsapps/server-core/src/core/identity/registration/index.tsapps/server-core/src/core/identity/registration/service.tsapps/server-core/src/core/identity/registration/types.ts
💤 Files with no reviewable changes (4)
- apps/server-core/src/adapters/http/controllers/entities/user-attribute/utils/index.ts
- apps/server-core/src/adapters/http/controllers/workflows/password-reset/validator.ts
- apps/server-core/src/adapters/http/controllers/workflows/register/validator.ts
- apps/server-core/src/adapters/http/controllers/workflows/password-forgot/validator.ts
| async create( | ||
| data: Record<string, any>, | ||
| actor: ActorContext, | ||
| ): Promise<ClientRole> { | ||
| await actor.permissionChecker.preCheck({ name: PermissionName.CLIENT_ROLE_CREATE }); | ||
|
|
||
| await this.repository.validateJoinColumns(data); | ||
|
|
||
| if (data.role) { | ||
| data.role_realm_id = data.role.realm_id; | ||
| } | ||
|
|
||
| if (data.client) { | ||
| data.client_realm_id = data.client.realm_id; | ||
| } | ||
|
|
||
| await actor.permissionChecker.check({ | ||
| name: PermissionName.CLIENT_ROLE_CREATE, | ||
| input: new PolicyData({ | ||
| [BuiltInPolicyType.ATTRIBUTES]: data, | ||
| }), | ||
| }); | ||
|
|
||
| let entity = this.repository.create(data); | ||
| entity = await this.repository.save(entity); | ||
|
|
||
| return entity; |
There was a problem hiding this comment.
Keep the role-superset guard inside ClientRoleService.create().
The HTTP controller still calls identityPermissionService.isSuperset(...) before invoking this method, but this new public service does not. That means any future caller using ClientRoleService.create() directly can assign a role whose permissions it does not own. Please move that guard into the service (or inject the required dependency here) so the invariant applies to every caller.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/entities/client-role/service.ts` around lines 64 -
90, ClientRoleService.create() currently lacks the role-superset guard, so
callers can assign roles whose permissions they don't own; move the check into
the service by invoking the same identityPermissionService.isSuperset(...) (or
inject identityPermissionService if not present) inside
ClientRoleService.create() before saving the entity, using the incoming
data.role (or data.role.id/realm) and the actor context to verify the actor is a
superset, and throw/reject when isSuperset returns false to preserve the
invariant for all callers.
| for (let i = 0; i < entities.length; i++) { | ||
| const entity = entities[i]; | ||
|
|
||
| if ( | ||
| entity.secret && | ||
| !entity.secret_encrypted && | ||
| !entity.secret_hashed | ||
| ) { | ||
| try { | ||
| await actor.permissionChecker.checkOneOf({ | ||
| name: [ | ||
| PermissionName.CLIENT_READ, | ||
| PermissionName.CLIENT_UPDATE, | ||
| PermissionName.CLIENT_DELETE, | ||
| ], | ||
| input: new PolicyData({ | ||
| [BuiltInPolicyType.ATTRIBUTES]: entity, | ||
| }), | ||
| }); | ||
| data.push(entity); | ||
| } catch (e) { | ||
| total -= 1; | ||
| } | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| data.push(entity); | ||
| } |
There was a problem hiding this comment.
Silent filtering in getMany may cause unexpected pagination issues.
The code catches permission errors and silently excludes entities from results while decrementing total. This could cause confusion for API consumers when data.length doesn't match expected page sizes, or when pagination metadata becomes inconsistent across pages.
Consider either:
- Returning a filtered query upfront based on actor permissions
- Documenting this behavior clearly in the API response
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/entities/client/service.ts` around lines 59 - 87,
The loop in getMany silently excludes entities when permission check fails
(actor.permissionChecker.checkOneOf) and decrements total, causing inconsistent
pagination; fix by pre-filtering entities by permission instead of mutating
total mid-iteration: iterate over entities, call
actor.permissionChecker.checkOneOf for each candidate, push allowed ones into a
new allowedEntities array (do not modify total on catch), then set total =
allowedEntities.length and proceed to build data/page from allowedEntities (or
alternatively expose an omittedCount in the response metadata if you want to
surface filtered-out items); update references to entities, data, total, and the
permission check logic in getMany accordingly.
| async getMany( | ||
| query: Record<string, any>, | ||
| actor: ActorContext, | ||
| ): Promise<EntityRepositoryFindManyResult<Policy>> { | ||
| await actor.permissionChecker.preCheckOneOf({ | ||
| name: [ | ||
| PermissionName.PERMISSION_READ, | ||
| PermissionName.PERMISSION_UPDATE, | ||
| PermissionName.PERMISSION_DELETE, | ||
| ], | ||
| }); | ||
|
|
||
| return this.repository.findMany(query); | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if POLICY_* permissions exist in the codebase
rg -n "POLICY_READ|POLICY_UPDATE|POLICY_DELETE|POLICY_CREATE" --type=tsRepository: authup/authup
Length of output: 39
🏁 Script executed:
# Find where PERMISSION_* constants are defined
rg -n "PERMISSION_READ|PERMISSION_UPDATE|PERMISSION_DELETE" --type=ts -A 2 | head -40Repository: authup/authup
Length of output: 3064
🏁 Script executed:
# Check the PermissionName enum definition
rg -n "enum PermissionName|export.*PERMISSION_" --type=ts | head -30Repository: authup/authup
Length of output: 141
🏁 Script executed:
# Look at the PolicyService file to understand the context better
cat -n apps/server-core/src/core/entities/policy/service.ts | head -60Repository: authup/authup
Length of output: 2529
🏁 Script executed:
# View the complete PermissionName enum
cat -n packages/core-kit/src/domains/permission/constants.tsRepository: authup/authup
Length of output: 3757
🏁 Script executed:
# Check another service (e.g., RoleService) to see permission pattern
rg -A 5 "async getMany" apps/server-core/src/core/entities/role/service.ts | head -20Repository: authup/authup
Length of output: 269
🏁 Script executed:
# Get RoleService permission usage in full context
rg -B 2 -A 8 "async getMany" apps/server-core/src/core/entities/role/service.ts | head -30Repository: authup/authup
Length of output: 406
🏁 Script executed:
# Check if there are any comments or patterns about policy permissions
rg -i "policy.*permission|permission.*policy" --type=ts -B 1 -A 1 | head -40Repository: authup/authup
Length of output: 3420
Add POLICY_ permissions to PolicyService or clarify if using PERMISSION_ is intentional.**
The service uses PermissionName.PERMISSION_READ, PERMISSION_UPDATE, PERMISSION_DELETE rather than POLICY_* permissions. All other entity services (Role, Client, Robot, User, etc.) follow an entity-specific naming pattern (e.g., ROLE_READ, CLIENT_UPDATE). Since no POLICY_* permissions exist in the PermissionName enum, either:
- Add
POLICY_READ,POLICY_UPDATE,POLICY_DELETEpermissions to the enum and use them here - Document if this is intentional because policies are managed under the permission domain
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/entities/policy/service.ts` around lines 35 - 48,
The getMany method is checking PermissionName.PERMISSION_READ/UPDATE/DELETE but
your project uses entity-scoped permissions; update the permission checks in
PolicyService.getMany to use POLICY_READ, POLICY_UPDATE, POLICY_DELETE (or add
those enum values to PermissionName if missing) so the service aligns with other
entity services; locate getMany in PolicyService and replace the
PermissionName.PERMISSION_* references with PermissionName.POLICY_* (or add the
POLICY_* entries to the PermissionName enum and import them) and run
tests/compile to ensure no missing-symbol errors.
| export interface IRealmService { | ||
| getMany(query: Record<string, any>): Promise<EntityRepositoryFindManyResult<Realm>>; | ||
| getOne(idOrName: string): Promise<Realm>; | ||
| create(data: Record<string, any>, actor: ActorContext): Promise<Realm>; | ||
| update(idOrName: string, data: Record<string, any>, actor: ActorContext): Promise<Realm>; | ||
| save(idOrName: string | undefined, data: Record<string, any>, actor: ActorContext): Promise<{ entity: Realm, created: boolean }>; | ||
| delete(id: string, actor: ActorContext): Promise<Realm>; | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check if other service interfaces follow the same pattern or if this is an intentional deviation
# Search for getMany/getOne method signatures in other service types to compare patterns
rg -n "getMany|getOne" --type ts -g "**/entities/**/types.ts" -A 1Repository: authup/authup
Length of output: 8034
Add ActorContext parameter to getMany and getOne methods.
The Realm service interface is the only one in the entities directory that omits ActorContext from its read methods. All 15+ comparable service interfaces (Scope, User, Role, Client, Permission, etc.) consistently require ActorContext for both read and write operations:
getMany(query: Record<string, any>, actor: ActorContext)getOne(idOrName: string, actor: ActorContext)
Without this parameter, realm visibility cannot be properly authorized or filtered based on the requesting actor, creating a security inconsistency with the rest of the codebase. Update the interface to match the established pattern.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/entities/realm/types.ts` around lines 17 - 24,
IRealmService's read methods currently lack the ActorContext parameter; update
the interface so getMany accepts (query: Record<string, any>, actor:
ActorContext): Promise<EntityRepositoryFindManyResult<Realm>> and getOne accepts
(idOrName: string, actor: ActorContext): Promise<Realm>, then update any
implementations and callers of IRealmService.getMany and IRealmService.getOne to
pass through the ActorContext (ensure references to IRealmService, getMany,
getOne, and any implementing classes are updated accordingly to maintain
compile-time consistency).
| const { data: entities, meta } = await this.repository.findMany(query); | ||
|
|
||
| const data: UserAttribute[] = []; | ||
| let { total } = meta; | ||
|
|
||
| for (let i = 0; i < entities.length; i++) { | ||
| const canManage = await this.canManageUserAttribute(actor, entities[i]); | ||
| if (canManage) { | ||
| data.push(entities[i]); | ||
| } else { | ||
| total--; | ||
| } | ||
| } | ||
|
|
||
| return { data, meta: { ...meta, total } }; |
There was a problem hiding this comment.
Don't paginate before the access filter.
Once findMany(query) runs on Line 41, paging has already happened. Filtering unauthorized rows at Lines 46-53 can return sparse pages and a meta.total that only reflects removals from the current page. USER_SELF_MANAGE callers can miss attributes they are allowed to see on later pages. Push the actor constraint into the repository query before fetching.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/entities/user-attribute/service.ts` around lines 41
- 55, The current implementation calls this.repository.findMany(query) then
filters results with canManageUserAttribute, which paginates before access
checks and breaks pagination; instead, push the actor constraint into the
repository query so only accessible rows are returned. Update the call site
around repository.findMany to augment the incoming query with the actor-based
access predicate (or use a repository method that applies access checks, e.g.,
add/findManyWithAccess), moving the logic inside the repository so
canManageUserAttribute is not used to filter post-fetch; ensure meta.total is
produced by the repository after applying the actor filter so pagination and
totals are correct.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
apps/server-core/src/adapters/http/controllers/entities/user-role/module.ts (1)
57-83: 🛠️ Refactor suggestion | 🟠 MajorKeep user-role assignment checks inside
IUserRoleService.create().
add()still reaches intorepositoryandidentityPermissionServicebefore calling the service, so the HTTP endpoint and any otherIUserRoleService.create()caller do not share the same create-time rules.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/user-role/module.ts` around lines 57 - 83, The controller method add() is performing repository.validateJoinColumns(...) and permission checks via identityPermissionService.isSuperset(...) before delegating to the service; move those creation-time validations into the IUserRoleService.create() implementation so all callers obey the same rules. Specifically: remove repository.validateJoinColumns(...) and the block that calls useRequestIdentityOrFail() + identityPermissionService.isSuperset(...) from the add() controller, and implement equivalent join-column validation and permission enforcement inside IUserRoleService.create(data, actor) (or the concrete UserRoleService.create) using the same logic and error types; keep buildActorContext(), useRequestBody() and sendCreated(res, entity) in add() but delegate all validation/permission checks to the service. Ensure the service still throws the same ForbiddenError when permissions fail.apps/server-core/src/adapters/http/controllers/entities/robot-role/module.ts (1)
57-83:⚠️ Potential issue | 🟠 MajorThe robot-role create path is still split across controller and service.
In
apps/server-core/src/core/entities/robot-role/service.ts:64-91,RobotRoleService.create()already callsrepository.validateJoinColumns(), so Line 67 is now a duplicate validation pass. TheisSuperset()check still lives only here, which means otherIRobotRoleService.create()callers will not share the same ownership guard.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/robot-role/module.ts` around lines 57 - 83, The controller's add method duplicates repository.validateJoinColumns (called again in RobotRoleService.create) and keeps the identity ownership guard (identityPermissionService.isSuperset) only in the controller; remove the duplicate validateJoinColumns call from the controller's add method and move the ownership check (the isSuperset logic that uses useRequestIdentityOrFail and identityPermissionService.isSuperset) into RobotRoleService.create (and the IRobotRoleService.create contract) so every caller of service.create enforces the same permission guard; ensure the service receives the request identity or actor context needed to perform the check and throw ForbiddenError from the service when the check fails.apps/server-core/src/adapters/http/controllers/entities/client-permission/module.ts (1)
59-66:⚠️ Potential issue | 🟠 MajorGET and DELETE disagree on the
:idformat.
getOne()uses the defaultuseRequestParamID(req)validation, butdrop()disables UUID validation for the same/:idroute. One of these handlers now has the wrong contract, so clients can see different 400/404 behavior depending on the verb.Also applies to: 71-81
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/client-permission/module.ts` around lines 59 - 66, GET and DELETE disagree on the :id validation: getOne uses useRequestParamID(req) while drop disables UUID validation; make them consistent by using the same ID validation helper in both handlers. Update the drop method (or getOne) to call the same helper signature (e.g., replace useRequestParamID(req, { disableUuidValidation: true }) with useRequestParamID(req) or conversely enable UUID validation in getOne) so both getOne and drop use the same contract for ID parsing/validation; locate references to getOne, drop, and useRequestParamID in this module to apply the change.
🧹 Nitpick comments (2)
apps/server-core/src/adapters/http/controllers/entities/policy/module.ts (2)
92-144: Inconsistent data access pattern incheckmethod.While all other CRUD methods now delegate to
this.service, thecheckmethod still usesthis.repository.findOneBy()directly (line 112). This bypasses any permission checks thatIPolicyService.getOne()enforces (see context snippet 2, which showsgetOneperformspermissionChecker.preCheckOneOf).If the intent is to allow any authenticated user to check policies without permission validation, this is fine but should be documented. Otherwise, consider delegating to the service to maintain consistency:
- const entity = await this.repository.findOneBy(criteria); - if (!entity) { - throw new NotFoundError(); - } + const actor = buildActorContext(req); + const entity = await this.service.getOne(paramId, actor, useRequestParam(req, 'realmId'));🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/policy/module.ts` around lines 92 - 144, The check method directly uses this.repository.findOneBy to load the policy, bypassing service-level permission checks; replace that direct repository call with the service method (e.g., this.service.getOne or the concrete IPolicyService.getOne used elsewhere) so the same permissionChecker.preCheckOneOf logic runs, or if intentional, add a clear comment explaining the bypass and why it’s safe; ensure you preserve the existing criteria resolution (isUUID + realmRepository.resolve) but pass the resolved id/name into the service call and handle the NotFoundError/response the same way.
74-90: Unusedidparameter from decorator.The
@DPath('id') id: stringdecorator parameter is never used in the method body; instead,useRequestParamID(req, { isUUID: false })extracts the same value. If the decorator is kept solely for OpenAPI documentation, consider adding an eslint-disable comment (similar tooptionson line 79-80) to suppress unused variable warnings, or remove the decorator if documentation is generated elsewhere.This pattern repeats in
update,replace, anddropmethods.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/policy/module.ts` around lines 74 - 90, The DPath('id') parameter is declared but unused in methods getOne, update, replace, and drop; either use the injected id (replace useRequestParamID calls) or suppress the lint warning if the decorator is kept for OpenAPI only—add an eslint-disable-next-line `@typescript-eslint/no-unused-vars` (matching the existing options pattern) before the unused parameter declarations (e.g., in getOne's "@DPath('id') id: string") or remove the `@DPath`('id') parameter entirely from those method signatures to eliminate the redundancy.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@apps/server-core/src/adapters/http/controllers/entities/client-role/module.ts`:
- Around line 57-83: The add() controller currently enforces create-time rules
by calling repository.validateJoinColumns and
identityPermissionService.isSuperset before delegating to this.service.create;
move those checks into the service (IClientRoleService.create) so the controller
only extracts input (useRequestBody), builds actor context, and calls
service.create(actor, data). Specifically, remove
repository.validateJoinColumns(...) and the
identityPermissionService.isSuperset(...) permission check (and related
useRequestIdentityOrFail() usage) from the add() method and implement equivalent
validation and ownership checks inside the service implementation invoked by
this.service.create so the service becomes the single enforcement boundary for
role-assignment rules.
---
Outside diff comments:
In
`@apps/server-core/src/adapters/http/controllers/entities/client-permission/module.ts`:
- Around line 59-66: GET and DELETE disagree on the :id validation: getOne uses
useRequestParamID(req) while drop disables UUID validation; make them consistent
by using the same ID validation helper in both handlers. Update the drop method
(or getOne) to call the same helper signature (e.g., replace
useRequestParamID(req, { disableUuidValidation: true }) with
useRequestParamID(req) or conversely enable UUID validation in getOne) so both
getOne and drop use the same contract for ID parsing/validation; locate
references to getOne, drop, and useRequestParamID in this module to apply the
change.
In
`@apps/server-core/src/adapters/http/controllers/entities/robot-role/module.ts`:
- Around line 57-83: The controller's add method duplicates
repository.validateJoinColumns (called again in RobotRoleService.create) and
keeps the identity ownership guard (identityPermissionService.isSuperset) only
in the controller; remove the duplicate validateJoinColumns call from the
controller's add method and move the ownership check (the isSuperset logic that
uses useRequestIdentityOrFail and identityPermissionService.isSuperset) into
RobotRoleService.create (and the IRobotRoleService.create contract) so every
caller of service.create enforces the same permission guard; ensure the service
receives the request identity or actor context needed to perform the check and
throw ForbiddenError from the service when the check fails.
In `@apps/server-core/src/adapters/http/controllers/entities/user-role/module.ts`:
- Around line 57-83: The controller method add() is performing
repository.validateJoinColumns(...) and permission checks via
identityPermissionService.isSuperset(...) before delegating to the service; move
those creation-time validations into the IUserRoleService.create()
implementation so all callers obey the same rules. Specifically: remove
repository.validateJoinColumns(...) and the block that calls
useRequestIdentityOrFail() + identityPermissionService.isSuperset(...) from the
add() controller, and implement equivalent join-column validation and permission
enforcement inside IUserRoleService.create(data, actor) (or the concrete
UserRoleService.create) using the same logic and error types; keep
buildActorContext(), useRequestBody() and sendCreated(res, entity) in add() but
delegate all validation/permission checks to the service. Ensure the service
still throws the same ForbiddenError when permissions fail.
---
Nitpick comments:
In `@apps/server-core/src/adapters/http/controllers/entities/policy/module.ts`:
- Around line 92-144: The check method directly uses this.repository.findOneBy
to load the policy, bypassing service-level permission checks; replace that
direct repository call with the service method (e.g., this.service.getOne or the
concrete IPolicyService.getOne used elsewhere) so the same
permissionChecker.preCheckOneOf logic runs, or if intentional, add a clear
comment explaining the bypass and why it’s safe; ensure you preserve the
existing criteria resolution (isUUID + realmRepository.resolve) but pass the
resolved id/name into the service call and handle the NotFoundError/response the
same way.
- Around line 74-90: The DPath('id') parameter is declared but unused in methods
getOne, update, replace, and drop; either use the injected id (replace
useRequestParamID calls) or suppress the lint warning if the decorator is kept
for OpenAPI only—add an eslint-disable-next-line
`@typescript-eslint/no-unused-vars` (matching the existing options pattern) before
the unused parameter declarations (e.g., in getOne's "@DPath('id') id: string")
or remove the `@DPath`('id') parameter entirely from those method signatures to
eliminate the redundancy.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 78cd2015-7924-4b8d-bcd9-a09bf7b2ef1e
📒 Files selected for processing (11)
apps/server-core/src/adapters/http/controllers/entities/client-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/client-role/module.tsapps/server-core/src/adapters/http/controllers/entities/client-scope/module.tsapps/server-core/src/adapters/http/controllers/entities/policy/module.tsapps/server-core/src/adapters/http/controllers/entities/robot-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/robot-role/module.tsapps/server-core/src/adapters/http/controllers/entities/role-attribute/module.tsapps/server-core/src/adapters/http/controllers/entities/role-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/user-attribute/module.tsapps/server-core/src/adapters/http/controllers/entities/user-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/user-role/module.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/server-core/src/adapters/http/controllers/entities/robot-permission/module.ts
| @DPost('', [ForceLoggedInMiddleware]) | ||
| async add( | ||
| @DBody() data: Pick<ClientRole, 'role_id' | 'client_id'>, | ||
| @DBody() _body: Pick<ClientRole, 'role_id' | 'client_id'>, | ||
| @DRequest() req: any, | ||
| @DResponse() res: any, | ||
| ): Promise<any> { | ||
| const permissionChecker = useRequestPermissionChecker(req); | ||
| await permissionChecker.preCheck({ name: PermissionName.CLIENT_ROLE_CREATE }); | ||
|
|
||
| const validator = new ClientRoleRequestValidator(); | ||
| const validatorAdapter = new RoutupContainerAdapter(validator); | ||
| const validatedData = await validatorAdapter.run(req, { | ||
| group: RequestHandlerOperation.CREATE, | ||
| }); | ||
| const actor = buildActorContext(req); | ||
|
|
||
| await this.repository.validateJoinColumns(validatedData); | ||
| const data = useRequestBody(req); | ||
|
|
||
| const policyData = new PolicyData(); | ||
| policyData.set(BuiltInPolicyType.ATTRIBUTES, validatedData); | ||
|
|
||
| if (validatedData.role) { | ||
| validatedData.role_realm_id = validatedData.role.realm_id; | ||
| await this.repository.validateJoinColumns(data); | ||
|
|
||
| if (data.role) { | ||
| const identity = useRequestIdentityOrFail(req); | ||
| const hasPermissions = await this.identityPermissionService.isSuperset(identity, { | ||
| type: 'role', | ||
| id: validatedData.role.id, | ||
| clientId: validatedData.role.client_id, | ||
| id: data.role.id, | ||
| clientId: data.role.client_id, | ||
| }); | ||
| if (!hasPermissions) { | ||
| throw new ForbiddenError('You don\'t own the required permissions.'); | ||
| } | ||
| } | ||
|
|
||
| if (validatedData.client) { | ||
| validatedData.client_realm_id = validatedData.client.realm_id; | ||
| } | ||
|
|
||
| await permissionChecker.check({ | ||
| name: PermissionName.CLIENT_ROLE_CREATE, | ||
| input: policyData, | ||
| }); | ||
|
|
||
| let entity = this.repository.create(validatedData); | ||
| entity = await this.repository.save(entity); | ||
| const entity = await this.service.create(data, actor); | ||
|
|
||
| return sendCreated(res, entity); |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
add() still keeps create-time rules in the controller.
This method still reaches into repository and identityPermissionService before calling IClientRoleService.create(). That leaves the HTTP path as a second place where role-assignment rules are enforced instead of making the service the single boundary for them.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@apps/server-core/src/adapters/http/controllers/entities/client-role/module.ts`
around lines 57 - 83, The add() controller currently enforces create-time rules
by calling repository.validateJoinColumns and
identityPermissionService.isSuperset before delegating to this.service.create;
move those checks into the service (IClientRoleService.create) so the controller
only extracts input (useRequestBody), builds actor context, and calls
service.create(actor, data). Specifically, remove
repository.validateJoinColumns(...) and the
identityPermissionService.isSuperset(...) permission check (and related
useRequestIdentityOrFail() usage) from the add() method and implement equivalent
validation and ownership checks inside the service implementation invoked by
this.service.create so the service becomes the single enforcement boundary for
role-assignment rules.
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (5)
apps/server-core/src/core/entities/role/service.ts (1)
58-76: Consider adding realm scoping for name-based lookups.The
getOnemethod usesfindOneByIdOrNamewithout realm scoping, while thesavemethod (lines 116-118) scopes entity lookups by realm when available. If role names are unique per-realm (rather than globally unique), a name-based lookup here could return an unintended role from a different realm.This may be intentional if IDs are always used in practice, but it's worth verifying the expected behavior.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/role/service.ts` around lines 58 - 76, The getOne method currently calls repository.findOneByIdOrName without realm scoping, which can return a role from the wrong realm when a name is passed; update getOne (the async getOne(idOrName: string, actor: ActorContext) method) to detect name-based lookups and query scoped to the actor's realm (similar to how save scopes lookups by realm) — e.g., if actor.realmId is present and idOrName is not a canonical ID, call a realm-scoped repository lookup (or add/use a findOneByNameInRealm/findOneByIdOrNameInRealm variant) so name resolution honors the actor.realmId before throwing NotFoundError.apps/server-core/src/core/identity/password-recovery/service.ts (3)
108-109: Consider injectingUserCredentialsServicevia context for consistency.
UserCredentialsServiceis instantiated directly here, while other dependencies (repository,realmRepository,mailClient) are injected via the context. For consistency and testability, consider addingcredentialsServicetoPasswordRecoveryServiceContext.This is optional if
UserCredentialsServiceis intentionally stateless and simple.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 108 - 109, The code instantiates UserCredentialsService directly in PasswordRecoveryService (see the lines creating new UserCredentialsService() and calling protect) which breaks the dependency-injection pattern used for repository, realmRepository and mailClient; update PasswordRecoveryServiceContext to accept a credentialsService (of type UserCredentialsService or its interface), add it to the context passed into PasswordRecoveryService, and replace the direct new UserCredentialsService() usage with context.credentialsService.protect(...) so tests and callers can inject a mock or alternative implementation.
219-228: Consider increasing minimum password length.A minimum password length of 5 characters is on the lower end by modern security standards. Many guidelines (e.g., NIST SP 800-63B) recommend a minimum of 8 characters. Consider increasing
min: 5tomin: 8for stronger security posture.🔒 Proposed change
validator.mount( 'password', createValidator(() => { const chain = createValidationChain(); return chain .exists() .notEmpty() - .isLength({ min: 5, max: 512 }); + .isLength({ min: 8, max: 512 }); }), );🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 219 - 228, The password validation currently sets a minimum length of 5 in the validator mounted for 'password' (see validator.mount, createValidator, createValidationChain, and the chain.isLength call); update the isLength constraint to use a stronger minimum (e.g., change min: 5 to min: 8) so passwords must be at least 8 characters long while keeping the existing max and other checks unchanged.
64-78: No rollback if email send fails after persisting reset token.The reset hash is persisted to the database (line 69) before the email is sent (lines 71-78). Per the
IMailClientinterface,send()throws on failure. If the email fails, the user won't receive the reset code, but thereset_hashandreset_expiresremain in the database.This is acceptable if subsequent forgot-password requests overwrite the token, but consider wrapping both operations in a try/catch to log the failure or clear the reset fields on email error if stricter consistency is required.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 64 - 78, The code persists reset_hash/reset_expires via this.repository.merge/save then calls this.mailClient.send which can throw, leaving tokens in DB on failure; wrap the save+send in a try/catch and on send failure either (A) clear the persisted fields (reload the entity or merge {reset_hash: null, reset_expires: null} and save) or (B) perform both operations inside a DB transaction if your repository supports it so the save is rolled back on error; update the function around repository.merge/repository.save and mailClient.send to catch errors, log them, and perform the chosen cleanup/rollback using the same entity/merged identifiers (reset_hash, reset_expires, repository.save, mailClient.send)..agents/architecture.md (1)
260-261: Document theidentityPermissionServicedependency.The architecture mentions
identityPermissionService.isSuperset()as a key component for superset junction controllers, but this service is not defined, explained, or documented anywhere in the file. Additionally, the distinction betweenRequestIdentity(adapter-level) and theIdentitytype inActorContextis unclear.Consider adding a subsection or note that:
- Explains what
identityPermissionServiceis and where it's instantiated- Clarifies the difference between
RequestIdentityandActorContext.identity- Documents why the superset check must remain at the controller (adapter) layer rather than in the service layer
This will help developers understand the complete pattern for implementing superset junction controllers.
Also applies to: 327-328
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.agents/architecture.md around lines 260 - 261, Add a short subsection documenting the identityPermissionService dependency: define what identityPermissionService is and where it’s instantiated, describe the isSuperset(contract) method used by superset junction controllers, and show the expected injection point (controller/adapter). Clarify the difference between adapter-level RequestIdentity and the Identity stored on ActorContext (ActorContext.identity) — e.g., RequestIdentity is the raw request principal with adapter-scoped metadata while ActorContext.identity is the normalized/propagated identity used in services. Finally, explain why the superset check must run in the controller/adapter (because it requires adapter-only RequestIdentity and request-context validation such as validateJoinColumns) rather than in the service layer which only receives ActorContext.identity.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/src/core/entities/realm/service.ts`:
- Around line 154-163: The built-in guard (throwing BadRequestError in the realm
deletion flow) is executed before the entity-level authorization check, leaking
a different error path; move the authorization call to
actor.permissionChecker.check (PermissionName.REALM_DELETE with new PolicyData({
[BuiltInPolicyType.ATTRIBUTES]: entity })) ahead of the built_in check so
permission is verified first, then after a successful check only enforce the
built_in guard and throw BadRequestError if appropriate.
In `@apps/server-core/src/core/entities/user/service.ts`:
- Around line 252-260: The code is reassigning plaintext passwords back onto
User entities after save (validated.password -> entity.password), exposing
secrets; remove any reassignment of validated.password to entity.password in the
save flow (references: validated.password, entity.password,
credentialsService.protect, this.repository.save) and ensure the returned entity
never contains the plaintext password (only store the hashed value returned by
credentialsService.protect and persist via this.repository.save); if callers
need confirmation of password set, return a boolean or a separate DTO that does
not include the password field.
- Around line 62-77: The catch in getMany is swallowing all exceptions from
actor.permissionChecker.checkOneOf and treating them as authorization denials;
change it to only suppress known authorization errors and rethrow any other
failures. Replace the broad catch around actor.permissionChecker.checkOneOf(...)
with logic that detects the auth error (e.g., instanceof/err.name check for your
permission/authorization error class from the permissionChecker or a
PermissionDenied/AuthorizationError type) — only then decrement total and skip
pushing the entity; otherwise rethrow the error so real failures surface;
reference actor.permissionChecker.checkOneOf, PermissionName, PolicyData and
BuiltInPolicyType to locate the code.
- Around line 156-173: After calling this.realmRepository.resolve for
data.realm_id, add a null-check and throw a NotFoundError when a string realm_id
was supplied but resolution returned null; specifically, after the line that
sets const realm = typeof data.realm_id === 'string' ? await
this.realmRepository.resolve(data.realm_id) : undefined; add: if (typeof
data.realm_id === 'string' && !realm) throw new NotFoundError('Realm not
found'); so subsequent lookups (e.g., repository.findOneBy) cannot proceed with
an unresolved realm_id.
In `@apps/server-core/src/core/identity/password-recovery/service.ts`:
- Around line 40-42: The password recovery flow currently gates on
this.options.registration which couples two unrelated features; change the guard
in the password recovery service to use a dedicated flag (e.g.
this.options.passwordRecovery) or remove the registration check entirely; if you
choose to add the flag, update the options/interface where options are defined
to include passwordRecovery:boolean and replace the existing check in the
password-recovery service (the if (!this.options.registration) { throw new
BadRequestError(...) } block) to check the new flag and throw a clearer error
message like "Password recovery is not enabled." instead of "User registration
is not enabled."; alternatively, if the coupling was intentional, only change
the thrown BadRequestError text to reflect password recovery rather than
registration.
---
Nitpick comments:
In @.agents/architecture.md:
- Around line 260-261: Add a short subsection documenting the
identityPermissionService dependency: define what identityPermissionService is
and where it’s instantiated, describe the isSuperset(contract) method used by
superset junction controllers, and show the expected injection point
(controller/adapter). Clarify the difference between adapter-level
RequestIdentity and the Identity stored on ActorContext (ActorContext.identity)
— e.g., RequestIdentity is the raw request principal with adapter-scoped
metadata while ActorContext.identity is the normalized/propagated identity used
in services. Finally, explain why the superset check must run in the
controller/adapter (because it requires adapter-only RequestIdentity and
request-context validation such as validateJoinColumns) rather than in the
service layer which only receives ActorContext.identity.
In `@apps/server-core/src/core/entities/role/service.ts`:
- Around line 58-76: The getOne method currently calls
repository.findOneByIdOrName without realm scoping, which can return a role from
the wrong realm when a name is passed; update getOne (the async getOne(idOrName:
string, actor: ActorContext) method) to detect name-based lookups and query
scoped to the actor's realm (similar to how save scopes lookups by realm) —
e.g., if actor.realmId is present and idOrName is not a canonical ID, call a
realm-scoped repository lookup (or add/use a
findOneByNameInRealm/findOneByIdOrNameInRealm variant) so name resolution honors
the actor.realmId before throwing NotFoundError.
In `@apps/server-core/src/core/identity/password-recovery/service.ts`:
- Around line 108-109: The code instantiates UserCredentialsService directly in
PasswordRecoveryService (see the lines creating new UserCredentialsService() and
calling protect) which breaks the dependency-injection pattern used for
repository, realmRepository and mailClient; update
PasswordRecoveryServiceContext to accept a credentialsService (of type
UserCredentialsService or its interface), add it to the context passed into
PasswordRecoveryService, and replace the direct new UserCredentialsService()
usage with context.credentialsService.protect(...) so tests and callers can
inject a mock or alternative implementation.
- Around line 219-228: The password validation currently sets a minimum length
of 5 in the validator mounted for 'password' (see validator.mount,
createValidator, createValidationChain, and the chain.isLength call); update the
isLength constraint to use a stronger minimum (e.g., change min: 5 to min: 8) so
passwords must be at least 8 characters long while keeping the existing max and
other checks unchanged.
- Around line 64-78: The code persists reset_hash/reset_expires via
this.repository.merge/save then calls this.mailClient.send which can throw,
leaving tokens in DB on failure; wrap the save+send in a try/catch and on send
failure either (A) clear the persisted fields (reload the entity or merge
{reset_hash: null, reset_expires: null} and save) or (B) perform both operations
inside a DB transaction if your repository supports it so the save is rolled
back on error; update the function around repository.merge/repository.save and
mailClient.send to catch errors, log them, and perform the chosen
cleanup/rollback using the same entity/merged identifiers (reset_hash,
reset_expires, repository.save, mailClient.send).
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 08c1c188-6442-495f-8cc8-6ca70c80b447
📒 Files selected for processing (7)
.agents/architecture.md.agents/conventions.mdapps/server-core/src/core/entities/realm/service.tsapps/server-core/src/core/entities/role/service.tsapps/server-core/src/core/entities/user-attribute/service.tsapps/server-core/src/core/entities/user/service.tsapps/server-core/src/core/identity/password-recovery/service.ts
✅ Files skipped from review due to trivial changes (1)
- .agents/conventions.md
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/server-core/src/core/entities/user-attribute/service.ts
| if (entity.built_in) { | ||
| throw new BadRequestError('A built-in realm can not be deleted.'); | ||
| } | ||
|
|
||
| await actor.permissionChecker.check({ | ||
| name: PermissionName.REALM_DELETE, | ||
| input: new PolicyData({ | ||
| [BuiltInPolicyType.ATTRIBUTES]: entity, | ||
| }), | ||
| }); |
There was a problem hiding this comment.
Run entity-level authorization before built-in guard
At Line 154, built_in is checked before permissionChecker.check (Line 158). This can disclose realm metadata (different error path) to callers who pass preCheck but are not authorized for that specific entity.
🔧 Proposed fix
- if (entity.built_in) {
- throw new BadRequestError('A built-in realm can not be deleted.');
- }
-
await actor.permissionChecker.check({
name: PermissionName.REALM_DELETE,
input: new PolicyData({
[BuiltInPolicyType.ATTRIBUTES]: entity,
}),
});
+
+ if (entity.built_in) {
+ throw new BadRequestError('A built-in realm can not be deleted.');
+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/entities/realm/service.ts` around lines 154 - 163,
The built-in guard (throwing BadRequestError in the realm deletion flow) is
executed before the entity-level authorization check, leaking a different error
path; move the authorization call to actor.permissionChecker.check
(PermissionName.REALM_DELETE with new PolicyData({
[BuiltInPolicyType.ATTRIBUTES]: entity })) ahead of the built_in check so
permission is verified first, then after a successful check only enforce the
built_in guard and throw BadRequestError if appropriate.
| try { | ||
| await actor.permissionChecker.checkOneOf({ | ||
| name: [ | ||
| PermissionName.USER_READ, | ||
| PermissionName.USER_UPDATE, | ||
| PermissionName.USER_DELETE, | ||
| ], | ||
| input: new PolicyData({ | ||
| [BuiltInPolicyType.ATTRIBUTES]: entities[i], | ||
| }), | ||
| }); | ||
|
|
||
| data.push(entities[i]); | ||
| } catch (e) { | ||
| total -= 1; | ||
| } |
There was a problem hiding this comment.
Don’t suppress non-authorization failures in getMany.
At Line 75, the broad catch treats every exception as “not allowed.” This can hide real failures and return silently truncated results.
Suggested fix
try {
await actor.permissionChecker.checkOneOf({
name: [
PermissionName.USER_READ,
PermissionName.USER_UPDATE,
PermissionName.USER_DELETE,
],
input: new PolicyData({
[BuiltInPolicyType.ATTRIBUTES]: entities[i],
}),
});
data.push(entities[i]);
} catch (e) {
- total -= 1;
+ // Only suppress explicit authorization denials.
+ if (!actor.permissionChecker.isPermissionError?.(e)) {
+ throw e;
+ }
+ total -= 1;
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/entities/user/service.ts` around lines 62 - 77, The
catch in getMany is swallowing all exceptions from
actor.permissionChecker.checkOneOf and treating them as authorization denials;
change it to only suppress known authorization errors and rethrow any other
failures. Replace the broad catch around actor.permissionChecker.checkOneOf(...)
with logic that detects the auth error (e.g., instanceof/err.name check for your
permission/authorization error class from the permissionChecker or a
PermissionDenied/AuthorizationError type) — only then decrement total and skip
pushing the entity; otherwise rethrow the error so real failures surface;
reference actor.permissionChecker.checkOneOf, PermissionName, PolicyData and
BuiltInPolicyType to locate the code.
| const realm = typeof data.realm_id === 'string' ? | ||
| await this.realmRepository.resolve(data.realm_id) : | ||
| undefined; | ||
|
|
||
| let entity: User | null | undefined; | ||
| if (idOrName) { | ||
| const where: Record<string, any> = {}; | ||
| if (isUUID(idOrName)) { | ||
| where.id = idOrName; | ||
| } else { | ||
| where.name = idOrName; | ||
| } | ||
|
|
||
| if (realm) { | ||
| where.realm_id = realm.id; | ||
| } | ||
|
|
||
| entity = await this.repository.findOneBy(where); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== IRealmRepository contract =="
fd 'types.ts' apps/server-core/src/core/entities/realm -t f -x sed -n '1,220p' {}
echo
echo "== resolve(...) implementations/usages in realm core =="
rg -n -C4 '\bresolve\s*\(' apps/server-core/src/core/entities/realm
echo
echo "== user service lookup path =="
sed -n '148,190p' apps/server-core/src/core/entities/user/service.tsRepository: authup/authup
Length of output: 3676
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Full save() method implementation =="
sed -n '148,230p' apps/server-core/src/core/entities/user/service.ts
echo
echo "== Check if data.realm_id is validated elsewhere =="
rg -n 'data\.realm_id' apps/server-core/src/core/entities/user/service.ts | head -20Repository: authup/authup
Length of output: 2853
Add null-check after realm resolution and throw if data.realm_id was provided but unresolved.
At lines 156–173, when data.realm_id is a string but resolve() returns null (unknown realm), the method silently proceeds with an unscoped name-based lookup. This can select a user from an unintended realm.
The IRealmRepository.resolve() signature allows null returns:
resolve(id, withFallback?: boolean): Promise<Realm | null>
After calling resolve(data.realm_id) at line 157, check that resolution succeeded if data.realm_id was provided, and throw an error otherwise:
const realm = typeof data.realm_id === 'string' ?
await this.realmRepository.resolve(data.realm_id) :
undefined;
if (typeof data.realm_id === 'string' && !realm) {
throw new NotFoundError('Realm not found');
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/entities/user/service.ts` around lines 156 - 173,
After calling this.realmRepository.resolve for data.realm_id, add a null-check
and throw a NotFoundError when a string realm_id was supplied but resolution
returned null; specifically, after the line that sets const realm = typeof
data.realm_id === 'string' ? await this.realmRepository.resolve(data.realm_id) :
undefined; add: if (typeof data.realm_id === 'string' && !realm) throw new
NotFoundError('Realm not found'); so subsequent lookups (e.g.,
repository.findOneBy) cannot proceed with an unresolved realm_id.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/src/core/entities/permission/service.ts`:
- Around line 171-178: The current realm-equality checks use truthy guards and
thus skip validation when one side is null; replace both occurrences so they
simply compare values and throw if unequal. Concretely, in the blocks that
reference validated.policy and entity.realm_id (the if that throws
BadRequestError('Policy realm and permission realm must be equal.')), change the
condition to check presence of validated.policy and then compare
validated.policy.realm_id !== entity.realm_id (i.e., if (validated.policy &&
validated.policy.realm_id !== entity.realm_id) { throw new BadRequestError(...)
}) and apply the same fix to the later check (lines 201-208) so null vs non-null
mismatches are caught.
In `@apps/server-core/src/core/entities/policy/attributes-validator.ts`:
- Line 24: The condition checking typeof this.attributeNames !== 'undefined' is
always true because the constructor assigns this.attributeNames =
options.attributeNames || []; update the logic in the constructor and the method
that contains the check (look for the attributeNames assignment in the
constructor and the conditional around attributeNames at the location with the
check) to distinguish "not provided" from "provided but empty": either store a
flag like options.attributeNames !== undefined when constructing, or change the
conditional to this.attributeNames.length > 0 so omission only happens when
attributeNames was explicitly provided and non-empty; adjust any related
branches that rely on the old undefined check accordingly.
In `@apps/server-core/src/core/entities/scope/service.ts`:
- Around line 94-99: The save method on ScopeService currently has a fourth
parameter options which makes its signature incompatible with the IScopeService
interface; update the IScopeService.save signature (in the scope types
declaration) to accept the options parameter (options?: { updateOnly?: boolean
}) and keep the existing return type Promise<{ entity: Scope, created: boolean
}>, so the concrete method save(idOrName, data, actor, options) matches the
interface; ensure the parameter is optional (no default) in the interface
declaration and the types (ActorContext, Scope) match existing symbols.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 67aa8fa9-bd0a-479c-b27d-4ada2b998b00
📒 Files selected for processing (6)
apps/server-core/src/core/entities/permission/service.tsapps/server-core/src/core/entities/policy/attributes-validator.tsapps/server-core/src/core/entities/policy/service.tsapps/server-core/src/core/entities/scope/service.tspackages/core-kit/src/domains/policy/index.tspackages/core-kit/src/domains/policy/validator.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/server-core/src/core/entities/policy/service.ts
| if ( | ||
| validated.policy && | ||
| validated.policy.realm_id && | ||
| entity.realm_id && | ||
| validated.policy.realm_id !== entity.realm_id | ||
| ) { | ||
| throw new BadRequestError('Policy realm and permission realm must be equal.'); | ||
| } |
There was a problem hiding this comment.
Enforce realm equality even when one side is null.
Line 171 and Line 201 use truthy guards for realm_id, so a policy with realm_id = "<uuid>" can slip through when permission realm_id is null. That contradicts the intended “must be equal” rule.
💡 Proposed fix
- if (
- validated.policy &&
- validated.policy.realm_id &&
- entity.realm_id &&
- validated.policy.realm_id !== entity.realm_id
- ) {
+ if (
+ validated.policy &&
+ (validated.policy.realm_id ?? null) !== (entity.realm_id ?? null)
+ ) {
throw new BadRequestError('Policy realm and permission realm must be equal.');
}
...
- if (
- validated.policy &&
- validated.policy.realm_id &&
- validated.realm_id &&
- validated.policy.realm_id !== validated.realm_id
- ) {
+ if (
+ validated.policy &&
+ (validated.policy.realm_id ?? null) !== (validated.realm_id ?? null)
+ ) {
throw new BadRequestError('Policy realm and permission realm must be equal.');
}Also applies to: 201-208
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/entities/permission/service.ts` around lines 171 -
178, The current realm-equality checks use truthy guards and thus skip
validation when one side is null; replace both occurrences so they simply
compare values and throw if unequal. Concretely, in the blocks that reference
validated.policy and entity.realm_id (the if that throws BadRequestError('Policy
realm and permission realm must be equal.')), change the condition to check
presence of validated.policy and then compare validated.policy.realm_id !==
entity.realm_id (i.e., if (validated.policy && validated.policy.realm_id !==
entity.realm_id) { throw new BadRequestError(...) }) and apply the same fix to
the later check (lines 201-208) so null vs non-null mismatches are caught.
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (1)
apps/server-core/src/core/identity/registration/service.ts (1)
68-79:⚠️ Potential issue | 🟠 MajorPersist-then-send still risks failing after a committed user write.
Line 68 commits the user, then Line 71 performs external mail delivery. A mail failure still turns the request into an error after persistence, which can leave inactive accounts and cause duplicate retry friction. Please move email dispatch intent to a transactional outbox/queue and return success after DB + outbox commit.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/registration/service.ts` around lines 68 - 79, Currently the code persists the user with repository.save and then calls this.mailClient.send, which can fail after commit; instead create and persist an Outbox entry (e.g., EmailOutbox entity containing to, subject, html, metadata like entity.activate_hash) within the same DB transaction as the user save so DB + outbox commit together; remove the direct this.mailClient.send call in create flow and, after transaction commits, let a background worker/process read unsent Outbox rows and invoke this.mailClient.send and mark the Outbox row as sent/failed; implement the outbox save via the same transaction/EntityManager used by repository.save and ensure this.options.emailVerificationEnabled gates creation of the Outbox entry rather than immediate sending.
🧹 Nitpick comments (3)
apps/server-core/src/app/modules/http/modules/controller.ts (3)
540-550: Avoid resolving the same dependency twice.
RealmEntityis resolved twice: once for theRealmRepositoryAdapter(line 542) and again for theRoleRepositoryAdapter(line 546). Consider reusing the resolved repository.♻️ Suggested fix
createRoleController(container: IDIContainer) { + const realmRepo = container.resolve<Repository<Realm>>(RealmEntity); const realmRepository = new RealmRepositoryAdapter( - container.resolve<Repository<Realm>>(RealmEntity), + realmRepo, ); const repository = new RoleRepositoryAdapter({ repository: container.resolve<Repository<Role>>(RoleEntity), - realmRepository: container.resolve<Repository<Realm>>(RealmEntity), + realmRepository: realmRepo, }); const service = new RoleService({ repository, realmRepository }); return new RoleController({ service }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 540 - 550, The createRoleController function resolves RealmEntity twice; instead resolve the Realm repository once into a variable (e.g. realmRepo) and reuse it when constructing RealmRepositoryAdapter and when passing realmRepository into RoleRepositoryAdapter so both adapters share the same resolved Repository<Realm> instance (update references to RealmRepositoryAdapter, RoleRepositoryAdapter, realmRepository and repository instantiation accordingly).
612-622: Avoid resolving the same dependency twice.Same pattern as
createRoleController:RealmEntityis resolved twice. Consider reusing the resolved repository.♻️ Suggested fix
createScopeController(container: IDIContainer) { + const realmRepo = container.resolve<Repository<Realm>>(RealmEntity); const realmRepository = new RealmRepositoryAdapter( - container.resolve<Repository<Realm>>(RealmEntity), + realmRepo, ); const repository = new ScopeRepositoryAdapter({ repository: container.resolve<Repository<Scope>>(ScopeEntity), - realmRepository: container.resolve<Repository<Realm>>(RealmEntity), + realmRepository: realmRepo, }); const service = new ScopeService({ repository, realmRepository }); return new ScopeController({ service }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 612 - 622, createScopeController resolves the Realm repository twice (used in RealmRepositoryAdapter and passed into ScopeRepositoryAdapter); instead resolve container.resolve<Repository<Realm>>(RealmEntity) once, store it in a single variable (e.g., realmRepo) and reuse it when constructing RealmRepositoryAdapter and when passing into ScopeRepositoryAdapter so RealmEntity is not resolved twice and both RealmRepositoryAdapter and ScopeRepositoryAdapter receive the same repository instance.
374-419: Consider extracting common setup logic to reduce duplication.
createPasswordRecoveryServiceandcreateRegistrationServiceshare nearly identical setup code: resolvingconfig,dataSource,realmRepository, creatingUserRepositoryAdapter, and resolvingmailClient. This repeated pattern could be extracted into a private helper method.♻️ Suggested refactor
+ private createUserServiceDependencies(container: IDIContainer) { + const config = container.resolve<Config>(ConfigInjectionKey); + const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource); + const realmRepository = container.resolve<Repository<Realm>>(RealmEntity); + const repository = new UserRepositoryAdapter({ + repository: new UserRepository(dataSource), + realmRepository, + }); + const mailClient = container.resolve<IMailClient>(MailInjectionKey); + return { config, repository, realmRepository, mailClient }; + } + createPasswordRecoveryService(container: IDIContainer) { - const config = container.resolve<Config>(ConfigInjectionKey); - const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource); - const realmRepository = container.resolve<Repository<Realm>>(RealmEntity); - const repository = new UserRepositoryAdapter({ - repository: new UserRepository(dataSource), - realmRepository, - }); - const mailClient = container.resolve<IMailClient>(MailInjectionKey); + const { config, repository, realmRepository, mailClient } = this.createUserServiceDependencies(container); return new PasswordRecoveryService({ mailClient, repository, realmRepository: new RealmRepositoryAdapter(realmRepository), options: { passwordRecoveryEnabled: config.forgotPassword, emailVerificationEnabled: config.emailVerification, }, }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 374 - 419, Both createPasswordRecoveryService and createRegistrationService duplicate the same setup steps (resolving Config, DataSource, Realm repository, creating UserRepositoryAdapter and resolving IMailClient); extract that into a private helper (e.g., a method like buildUserServiceDeps or resolveUserDependencies) that returns the shared pieces (config, repository adapter, realmRepositoryAdapter, mailClient) and use it from createPasswordRecoveryService and createRegistrationService to construct their specific service instances; reference the existing symbols createPasswordRecoveryService, createRegistrationService, UserRepositoryAdapter, UserRepository, RealmRepositoryAdapter, ConfigInjectionKey, DatabaseInjectionKey, and MailInjectionKey when implementing the helper so callers only handle service-specific options.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/src/core/identity/password-recovery/service.ts`:
- Line 10: The code currently persists raw reset tokens (generated via
randomBytes) which is unsafe; instead generate the token with randomBytes, send
the raw token to the user but persist only a secure hash (e.g., SHA-256 or HMAC)
of the token and an expiry in the database, and when verifying a submitted token
(in the password reset validate/consume function) hash the incoming token the
same way and compare against the stored hash using a constant-time comparison;
update the functions that generate/store tokens (references: randomBytes usage
and whatever functions/methods that save the token) to store tokenHash +
expiresAt rather than the raw token and update the verification code paths
(where tokens are looked up/consumed) to hash the provided token before matching
and to delete/expire the stored hash after use.
- Around line 58-62: Currently the forgot-password flow throws NotFoundError
when repository.findOneByWithEmail(where) returns no entity, which leaks account
existence; change the logic in the password recovery service so it does NOT
throw NotFoundError—always return the same generic success response and
continue: if entity is found (repository.findOneByWithEmail), generate the
recovery token and send the email as before, but if entity is null simply skip
token creation/email and still return the success result; remove the
NotFoundError throw and ensure any logging does not reveal whether the user
existed.
- Around line 104-106: The expiry check for password resets currently only tests
for past dates and lets invalid timestamps (NaN) pass; update the validation in
the password recovery service so that for entity.reset_expires you parse it into
a Date, verify it's a valid date (e.g., !isNaN(date.getTime())) and that date >=
new Date() and if either check fails throw the existing BadRequestError (or a
clear variant) to reject expired or malformed reset tokens; reference
entity.reset_expires and BadRequestError in your change.
- Around line 85-87: The resetPassword method lacks the same feature gate used
in forgotPassword; add a check for passwordRecoveryEnabled at the start of
resetPassword (before calling runResetPasswordValidator) and abort early when
disabled (e.g., throw the same error or return the same failure shape used by
forgotPassword). Update the resetPassword function to mirror the guard used in
forgotPassword so reset flows cannot proceed when passwordRecoveryEnabled is
false.
---
Duplicate comments:
In `@apps/server-core/src/core/identity/registration/service.ts`:
- Around line 68-79: Currently the code persists the user with repository.save
and then calls this.mailClient.send, which can fail after commit; instead create
and persist an Outbox entry (e.g., EmailOutbox entity containing to, subject,
html, metadata like entity.activate_hash) within the same DB transaction as the
user save so DB + outbox commit together; remove the direct this.mailClient.send
call in create flow and, after transaction commits, let a background
worker/process read unsent Outbox rows and invoke this.mailClient.send and mark
the Outbox row as sent/failed; implement the outbox save via the same
transaction/EntityManager used by repository.save and ensure
this.options.emailVerificationEnabled gates creation of the Outbox entry rather
than immediate sending.
---
Nitpick comments:
In `@apps/server-core/src/app/modules/http/modules/controller.ts`:
- Around line 540-550: The createRoleController function resolves RealmEntity
twice; instead resolve the Realm repository once into a variable (e.g.
realmRepo) and reuse it when constructing RealmRepositoryAdapter and when
passing realmRepository into RoleRepositoryAdapter so both adapters share the
same resolved Repository<Realm> instance (update references to
RealmRepositoryAdapter, RoleRepositoryAdapter, realmRepository and repository
instantiation accordingly).
- Around line 612-622: createScopeController resolves the Realm repository twice
(used in RealmRepositoryAdapter and passed into ScopeRepositoryAdapter); instead
resolve container.resolve<Repository<Realm>>(RealmEntity) once, store it in a
single variable (e.g., realmRepo) and reuse it when constructing
RealmRepositoryAdapter and when passing into ScopeRepositoryAdapter so
RealmEntity is not resolved twice and both RealmRepositoryAdapter and
ScopeRepositoryAdapter receive the same repository instance.
- Around line 374-419: Both createPasswordRecoveryService and
createRegistrationService duplicate the same setup steps (resolving Config,
DataSource, Realm repository, creating UserRepositoryAdapter and resolving
IMailClient); extract that into a private helper (e.g., a method like
buildUserServiceDeps or resolveUserDependencies) that returns the shared pieces
(config, repository adapter, realmRepositoryAdapter, mailClient) and use it from
createPasswordRecoveryService and createRegistrationService to construct their
specific service instances; reference the existing symbols
createPasswordRecoveryService, createRegistrationService, UserRepositoryAdapter,
UserRepository, RealmRepositoryAdapter, ConfigInjectionKey,
DatabaseInjectionKey, and MailInjectionKey when implementing the helper so
callers only handle service-specific options.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 6f2ae25e-423e-4b29-868c-eebe8f2edb66
📒 Files selected for processing (5)
apps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/core/identity/password-recovery/service.tsapps/server-core/src/core/identity/password-recovery/types.tsapps/server-core/src/core/identity/registration/service.tsapps/server-core/src/core/identity/registration/types.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/server-core/src/core/identity/registration/types.ts
- apps/server-core/src/core/identity/password-recovery/types.ts
|
|
||
| import { BadRequestError, NotFoundError } from '@ebec/http'; | ||
| import { createValidationChain, createValidator } from '@validup/adapter-validator'; | ||
| import { randomBytes } from 'node:crypto'; |
There was a problem hiding this comment.
Do not persist raw reset tokens.
The current flow stores the same token value that is sent to the user. If DB data is exposed, valid reset tokens are immediately usable.
Proposed fix
-import { randomBytes } from 'node:crypto';
+import { createHash, randomBytes } from 'node:crypto';
@@
- const merged = this.repository.merge(entity, {
+ const rawToken = randomBytes(32).toString('hex');
+ const tokenDigest = createHash('sha256').update(rawToken).digest('hex');
+
+ const merged = this.repository.merge(entity, {
reset_expires: new Date(Date.now() + (1000 * 60 * 30)).toISOString(),
- reset_hash: randomBytes(32).toString('hex'),
+ reset_hash: tokenDigest,
});
@@
- <p>${merged.reset_hash}</p>
+ <p>${rawToken}</p>
@@
- reset_hash: validated.token,
+ reset_hash: createHash('sha256').update(validated.token).digest('hex'),Also applies to: 64-67, 95-96
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/identity/password-recovery/service.ts` at line 10,
The code currently persists raw reset tokens (generated via randomBytes) which
is unsafe; instead generate the token with randomBytes, send the raw token to
the user but persist only a secure hash (e.g., SHA-256 or HMAC) of the token and
an expiry in the database, and when verifying a submitted token (in the password
reset validate/consume function) hash the incoming token the same way and
compare against the stored hash using a constant-time comparison; update the
functions that generate/store tokens (references: randomBytes usage and whatever
functions/methods that save the token) to store tokenHash + expiresAt rather
than the raw token and update the verification code paths (where tokens are
looked up/consumed) to hash the provided token before matching and to
delete/expire the stored hash after use.
| const entity = await this.repository.findOneByWithEmail(where); | ||
|
|
||
| if (!entity) { | ||
| throw new NotFoundError(); | ||
| } |
There was a problem hiding this comment.
Avoid account enumeration in forgot-password flow.
Line 61 returns NotFoundError when no user matches, which leaks whether an account exists for the provided identifier.
Proposed fix
- const entity = await this.repository.findOneByWithEmail(where);
-
- if (!entity) {
- throw new NotFoundError();
- }
+ const entity = await this.repository.findOneByWithEmail(where);
+ const resetExpires = new Date(Date.now() + (1000 * 60 * 30)).toISOString();
+
+ if (!entity) {
+ return { reset_expires: resetExpires };
+ }
const merged = this.repository.merge(entity, {
- reset_expires: new Date(Date.now() + (1000 * 60 * 30)).toISOString(),
+ reset_expires: resetExpires,
reset_hash: randomBytes(32).toString('hex'),
});🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines
58 - 62, Currently the forgot-password flow throws NotFoundError when
repository.findOneByWithEmail(where) returns no entity, which leaks account
existence; change the logic in the password recovery service so it does NOT
throw NotFoundError—always return the same generic success response and
continue: if entity is found (repository.findOneByWithEmail), generate the
recovery token and send the email as before, but if entity is null simply skip
token creation/email and still return the success result; remove the
NotFoundError throw and ensure any logging does not reveal whether the user
existed.
| if (!entity.reset_expires || new Date(entity.reset_expires) < new Date()) { | ||
| throw new BadRequestError('Reset token has expired.'); | ||
| } |
There was a problem hiding this comment.
Harden expiry validation for invalid timestamps.
Line 104 treats only “past date” as expired. Invalid date strings evaluate to NaN and can bypass this check.
Proposed fix
- if (!entity.reset_expires || new Date(entity.reset_expires) < new Date()) {
+ const expiresAt = entity.reset_expires ? new Date(entity.reset_expires) : null;
+ if (!expiresAt || Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() <= Date.now()) {
throw new BadRequestError('Reset token has expired.');
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines
104 - 106, The expiry check for password resets currently only tests for past
dates and lets invalid timestamps (NaN) pass; update the validation in the
password recovery service so that for entity.reset_expires you parse it into a
Date, verify it's a valid date (e.g., !isNaN(date.getTime())) and that date >=
new Date() and if either check fails throw the existing BadRequestError (or a
clear variant) to reject expired or malformed reset tokens; reference
entity.reset_expires and BadRequestError in your change.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (6)
apps/server-core/src/core/identity/password-recovery/service.ts (4)
85-86:⚠️ Potential issue | 🟠 MajorMissing
passwordRecoveryEnabledcheck inresetPassword.
forgotPasswordchecksthis.options.passwordRecoveryEnabled, butresetPassworddoes not. An attacker could still reset passwords if they obtained a valid token before the feature was disabled.🔒 Proposed fix
async resetPassword(data: Record<string, any>): Promise<PasswordResetResult> { + if (!this.options.passwordRecoveryEnabled) { + throw new BadRequestError('Password recovery is not enabled.'); + } + const validated = await this.runResetPasswordValidator(data);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 85 - 86, The resetPassword method (async resetPassword) is missing a guard for this.options.passwordRecoveryEnabled; add the same check used in forgotPassword to immediately reject/return a failed PasswordResetResult (or throw the same error) when passwordRecoveryEnabled is false so tokens cannot be used after feature is disabled — update resetPassword to check this.options.passwordRecoveryEnabled at the top and return/throw the appropriate error path consistent with forgotPassword and the PasswordResetResult contract.
104-106:⚠️ Potential issue | 🟡 MinorInvalid date strings bypass expiry check.
If
entity.reset_expirescontains a malformed string,new Date(...)yieldsInvalid Datewhose comparisons returnfalse, allowing the token to pass validation.🛡️ Proposed fix
- if (!entity.reset_expires || new Date(entity.reset_expires) < new Date()) { + const expiresAt = entity.reset_expires ? new Date(entity.reset_expires) : null; + if (!expiresAt || Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() <= Date.now()) { throw new BadRequestError('Reset token has expired.'); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 104 - 106, The expiry check using new Date(entity.reset_expires) can silently accept malformed strings because Invalid Date comparisons behave oddly; update the logic in the password recovery validation (the block referencing entity.reset_expires and throwing BadRequestError) to explicitly parse and validate the date (e.g., create a Date object and check !isNaN(date.getTime()) or use Date.parse) and then verify the parsed date is in the future; if parsing fails or the date is past, throw the same BadRequestError('Reset token has expired.') to reject malformed or expired tokens.
58-62:⚠️ Potential issue | 🟠 MajorAccount enumeration vulnerability persists.
Throwing
NotFoundErrorwhen no user matches reveals whether an account exists for the given identifier. Return a generic success response regardless of whether the user was found to prevent attackers from harvesting valid email addresses.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 58 - 62, The current early throw of NotFoundError after calling repository.findOneByWithEmail leaks account existence; instead, remove the NotFoundError path and always return the same generic success response to the caller. Keep calling repository.findOneByWithEmail to attempt to load the entity, but if it returns null simply skip any token generation/email send logic (or perform internal logging/auditing) and still return the identical success result; ensure symbols referenced are repository.findOneByWithEmail and the current password-recovery service method (the code that assigns const entity) so the change is localized and does not alter the public API behavior.
64-67:⚠️ Potential issue | 🟠 MajorStoring raw reset tokens is insecure.
The reset token is stored directly in the database. If the database is compromised, attackers can immediately use these tokens. Hash the token before storing (e.g., SHA-256) and send only the raw token to the user; on reset, hash the submitted token before lookup.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 64 - 67, The code currently stores the raw reset token (reset_hash) from randomBytes directly; instead generate a rawToken (e.g., const rawToken = randomBytes(32).toString('hex')), compute a SHA-256 hash of rawToken (e.g., createHash('sha256').update(rawToken).digest('hex')), store that hash in the merged entity under reset_hash and keep reset_expires as-is, and return/send the rawToken to the user; update the verification path to hash the submitted token with the same SHA-256 and look up/compare against reset_hash in the repository (functions to change: the service method that calls this.repository.merge and any verify/reset methods that currently compare raw tokens).apps/server-core/src/core/entities/user/service.ts (2)
156-173:⚠️ Potential issue | 🟠 MajorMissing null-check after realm resolution allows unintended cross-realm lookups.
When
data.realm_idis a string butthis.realmRepository.resolve()returnsnull(unknown realm), the code proceeds withrealmbeingundefined. At lines 169-171, this means norealm_idconstraint is added to the query, potentially matching a user from any realm.Add validation after resolution:
const realm = typeof data.realm_id === 'string' ? await this.realmRepository.resolve(data.realm_id) : undefined; + if (typeof data.realm_id === 'string' && !realm) { + throw new NotFoundError('Realm not found'); + } + let entity: User | null | undefined;,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/user/service.ts` around lines 156 - 173, After resolving data.realm_id with this.realmRepository.resolve(data.realm_id) ensure you validate the result (realm) is not null/undefined before proceeding: if data.realm_id is a string and realm resolution returns null, abort with a clear error or throw (preventing cross-realm queries). Update the logic around realm, idOrName, and the repository.findOneBy(where) path in the method (touching realmRepository.resolve, realm, data.realm_id, isUUID, idOrName, and repository.findOneBy) so that when a string realm_id is provided but resolve() returns no realm you do not omit where.realm_id — instead return/throw an appropriate error.
62-77:⚠️ Potential issue | 🟠 MajorBroad catch still swallows non-authorization failures.
The catch block at line 75 treats every exception as "not allowed," silently decrementing
totaland hiding real failures (database errors, network issues, etc.). This can return incorrect pagination metadata and mask operational issues.Consider checking for authorization-specific errors before suppressing:
} catch (e) { + // Only suppress explicit authorization denials + if ( + !(e instanceof Error) || + !e.name.includes('Permission') && !e.name.includes('Authorization') + ) { + throw e; + } total -= 1; }Alternatively, use a typed guard provided by the permission checker if available.
,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/entities/user/service.ts` around lines 62 - 77, The catch currently swallows all exceptions from actor.permissionChecker.checkOneOf (hiding DB/network errors) and always decrements total; change it to only suppress authorization errors: in the try/catch around actor.permissionChecker.checkOneOf({ ... }), detect authorization failures (e.g., instanceof AuthorizationError or check a permission-specific property like e.code === 'FORBIDDEN' or the permission checker's typed guard) and only decrement total and skip pushing the entity for those cases—rethrow any other errors so real failures bubble up; reference actor.permissionChecker.checkOneOf, PermissionName, PolicyData, and BuiltInPolicyType when locating the code to modify.
🧹 Nitpick comments (6)
docs/src/guide/deployment/configuration-server-core.md (1)
133-161: Add an explicit migration note for renamed variables to avoid silent misconfiguration.This is a breaking rename for existing deployments still using
REGISTRATION,EMAIL_VERIFICATION, orFORGOT_PASSWORD. Please add a short “renamed from → to” note in this page to make upgrades safer.Proposed doc patch
```dotenv [.env] PORT=3001 PUBLIC_URL=http://localhost:3001 REGISTRATION_ENABLED=false EMAIL_VERIFICATION_ENABLED=false PASSWORD_RECOVERY_ENABLED=false @@ PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT=true
+> Migration note:
+> -REGISTRATION→REGISTRATION_ENABLED
+> -EMAIL_VERIFICATION→EMAIL_VERIFICATION_ENABLED
+> -FORGOT_PASSWORD→PASSWORD_RECOVERY_ENABLED</details> <details> <summary>🤖 Prompt for AI Agents</summary>Verify each finding against the current code and only fix it if needed.
In
@docs/src/guide/deployment/configuration-server-core.mdaround lines 133 -
161, Add a clear migration note to the configuration docs explaining the renamed
environment variables so existing deployments don't silently misconfigure:
insert a short "Migration note" block near the .env examples listing the
mappingsREGISTRATION→REGISTRATION_ENABLED,EMAIL_VERIFICATION→
EMAIL_VERIFICATION_ENABLED, andFORGOT_PASSWORD→
PASSWORD_RECOVERY_ENABLED(referencing the .env keys shown like
PORT/PUBLIC_URL/REGISTRATION_ENABLED) so upgraders can update their environment
variables accordingly.</details> </blockquote></details> <details> <summary>apps/server-core/test/app/factory.ts (1)</summary><blockquote> `37-38`: **Consider explicitly setting `passwordRecoveryEnabled` for test completeness.** The `Config` type (see `apps/server-core/src/app/modules/config/types.ts:154-170`) includes `passwordRecoveryEnabled` alongside the two flags being set here. If any tests exercise password recovery flows, explicitly enabling this flag would ensure consistent test behavior. <details> <summary>💡 Optional addition</summary> ```diff config.registrationEnabled = true; config.emailVerificationEnabled = true; + config.passwordRecoveryEnabled = true;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/app/factory.ts` around lines 37 - 38, The test factory sets config.registrationEnabled and config.emailVerificationEnabled but omits passwordRecoveryEnabled; update the test setup to explicitly set config.passwordRecoveryEnabled (e.g., true) alongside the other flags so the Config used by tests (see the Config type with passwordRecoveryEnabled) has deterministic behavior for any password recovery flows.apps/server-core/src/core/identity/password-recovery/service.ts (2)
208-217: Token min length could be stricter.The generated token is 64 hex characters, but validation allows tokens as short as 3 characters. Consider raising the minimum to match the expected format (e.g., 64) to reject obviously invalid tokens early.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 208 - 217, The token validator registered via validator.mount('token', createValidator(...)) currently allows a minimum length of 3; tighten it to require the actual token length (e.g., change isLength({ min: 3, max: 256 }) to isLength({ min: 64, max: 256 })) so generated 64-hex-character tokens are enforced; update the validation in the createValidator / createValidationChain block referenced by validator.mount('token') to use min: 64 (and keep or adjust max as appropriate).
108-109: Consider injectingUserCredentialsServicevia context.Creating
UserCredentialsServiceinline makes the method harder to test and breaks the DI pattern established by the constructor. Consider adding it toPasswordRecoveryServiceContext.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 108 - 109, Replace the inline instantiation of UserCredentialsService with a dependency provided on the PasswordRecoveryServiceContext: add a userCredentialsService: UserCredentialsService (or factory) property to PasswordRecoveryServiceContext, accept and assign it in the PasswordRecoveryService constructor, and change the call site from "new UserCredentialsService()" to use the injected context property (e.g., this.context.userCredentialsService.protect(validated.password)); update any tests/consumers to supply a mock or real UserCredentialsService via the context.apps/server-core/src/core/identity/registration/types.ts (1)
28-28: Tightenregisterinput typing to avoidanyin a core public contract.The
registermethod signature usesRecord<string, any>, which bypasses compile-time type safety. Although the implementation validates input using aUserValidator(narrowing toname,password,realm_id), this narrowing happens at runtime. Replace withRecord<string, unknown>to enforce explicit narrowing by callers, or introduce a dedicated input DTO for better documentation of the public contract. Note thatactivateis already properly typed as{ token: string }, making this inconsistency more pronounced.Suggested change
+export type RegistrationInput = Record<string, unknown>; + export interface IRegistrationService { - register(data: Record<string, any>): Promise<RegistrationResult>; + register(data: RegistrationInput): Promise<RegistrationResult>; activate(data: { token: string }): Promise<void>; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/registration/types.ts` at line 28, The public method signature register currently accepts Record<string, any>, which weakens type safety; change it to Record<string, unknown> or define and use a dedicated DTO/interface (e.g., RegisterInput { email: string; name?: string; password: string; realm_id?: string }) in the same module and update the register declaration to return Promise<RegistrationResult> with that input type; then adjust implementations (functions named register and any places importing this type) to explicitly narrow/validate the unknown input (or accept the DTO) so callers must perform safe casting/validation and TypeScript will enforce the contract.apps/server-core/src/app/modules/http/modules/controller.ts (1)
374-420: Consider extracting shared dependency setup.Both
createPasswordRecoveryServiceandcreateRegistrationServiceresolve identical dependencies (dataSource,realmRepository,mailClient) and create the same adapters. Consider extracting a shared helper to reduce duplication:private createUserServiceDeps(container: IDIContainer) { const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource); const realmRepository = container.resolve<Repository<Realm>>(RealmEntity); return { dataSource, repository: new UserRepositoryAdapter({ repository: new UserRepository(dataSource), realmRepository, }), realmRepository: new RealmRepositoryAdapter(realmRepository), mailClient: container.resolve<IMailClient>(MailInjectionKey), }; }This is optional and can be deferred if the current pattern is preferred for explicitness.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 374 - 420, The two factory methods createPasswordRecoveryService and createRegistrationService duplicate resolving dataSource, realmRepository, mailClient and building UserRepositoryAdapter/RealmRepositoryAdapter; extract that shared setup into a private helper (e.g., createUserServiceDeps) that returns { repository, realmRepository, mailClient } (and dataSource if needed), then update both createPasswordRecoveryService and createRegistrationService to call this helper and pass its returned repository/realmRepository/mailClient into PasswordRecoveryService and RegistrationService, keeping each service-specific options logic intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.claude/skills/investigate-pr-comments/SKILL.md:
- Around line 19-28: Replace the placeholder node -e snippets with concrete JSON
parsing and filtering commands: capture the PR number and repo info into
variables (PR_NUM, OWNER, REPO) using gh pr view and gh repo view, then call gh
api "repos/$OWNER/$REPO/issues/$PR_NUM/comments" and parse the JSON to filter
out bot users (e.g., skip comments where c.user.login includes "bot") and print
trimmed summaries; do the same for gh api
"repos/$OWNER/$REPO/pulls/$PR_NUM/comments" to output file/line context (use
c.path and c.line) and user/body previews so the examples are fully runnable
without placeholders.
In `@apps/server-core/src/app/modules/config/read/env.ts`:
- Around line 97-110: When reading the new boolean env keys
(registrationEnabled, emailVerificationEnabled, passwordRecoveryEnabled via
readBool and ConfigEnvironmentVariableName.*) add a temporary fallback: if the
new key read returns undefined, call readBool again with the corresponding
legacy environment name and set options from that value; mark the legacy enum
entries as deprecated (e.g., add LEGACY_* entries to
ConfigEnvironmentVariableName or reference the old string names) and add a short
comment/log noting the migration fallback is temporary; update unit tests to
cover both new-key and legacy-key behavior so upgrades don't silently change
runtime defaults.
---
Duplicate comments:
In `@apps/server-core/src/core/entities/user/service.ts`:
- Around line 156-173: After resolving data.realm_id with
this.realmRepository.resolve(data.realm_id) ensure you validate the result
(realm) is not null/undefined before proceeding: if data.realm_id is a string
and realm resolution returns null, abort with a clear error or throw (preventing
cross-realm queries). Update the logic around realm, idOrName, and the
repository.findOneBy(where) path in the method (touching
realmRepository.resolve, realm, data.realm_id, isUUID, idOrName, and
repository.findOneBy) so that when a string realm_id is provided but resolve()
returns no realm you do not omit where.realm_id — instead return/throw an
appropriate error.
- Around line 62-77: The catch currently swallows all exceptions from
actor.permissionChecker.checkOneOf (hiding DB/network errors) and always
decrements total; change it to only suppress authorization errors: in the
try/catch around actor.permissionChecker.checkOneOf({ ... }), detect
authorization failures (e.g., instanceof AuthorizationError or check a
permission-specific property like e.code === 'FORBIDDEN' or the permission
checker's typed guard) and only decrement total and skip pushing the entity for
those cases—rethrow any other errors so real failures bubble up; reference
actor.permissionChecker.checkOneOf, PermissionName, PolicyData, and
BuiltInPolicyType when locating the code to modify.
In `@apps/server-core/src/core/identity/password-recovery/service.ts`:
- Around line 85-86: The resetPassword method (async resetPassword) is missing a
guard for this.options.passwordRecoveryEnabled; add the same check used in
forgotPassword to immediately reject/return a failed PasswordResetResult (or
throw the same error) when passwordRecoveryEnabled is false so tokens cannot be
used after feature is disabled — update resetPassword to check
this.options.passwordRecoveryEnabled at the top and return/throw the appropriate
error path consistent with forgotPassword and the PasswordResetResult contract.
- Around line 104-106: The expiry check using new Date(entity.reset_expires) can
silently accept malformed strings because Invalid Date comparisons behave oddly;
update the logic in the password recovery validation (the block referencing
entity.reset_expires and throwing BadRequestError) to explicitly parse and
validate the date (e.g., create a Date object and check !isNaN(date.getTime())
or use Date.parse) and then verify the parsed date is in the future; if parsing
fails or the date is past, throw the same BadRequestError('Reset token has
expired.') to reject malformed or expired tokens.
- Around line 58-62: The current early throw of NotFoundError after calling
repository.findOneByWithEmail leaks account existence; instead, remove the
NotFoundError path and always return the same generic success response to the
caller. Keep calling repository.findOneByWithEmail to attempt to load the
entity, but if it returns null simply skip any token generation/email send logic
(or perform internal logging/auditing) and still return the identical success
result; ensure symbols referenced are repository.findOneByWithEmail and the
current password-recovery service method (the code that assigns const entity) so
the change is localized and does not alter the public API behavior.
- Around line 64-67: The code currently stores the raw reset token (reset_hash)
from randomBytes directly; instead generate a rawToken (e.g., const rawToken =
randomBytes(32).toString('hex')), compute a SHA-256 hash of rawToken (e.g.,
createHash('sha256').update(rawToken).digest('hex')), store that hash in the
merged entity under reset_hash and keep reset_expires as-is, and return/send the
rawToken to the user; update the verification path to hash the submitted token
with the same SHA-256 and look up/compare against reset_hash in the repository
(functions to change: the service method that calls this.repository.merge and
any verify/reset methods that currently compare raw tokens).
---
Nitpick comments:
In `@apps/server-core/src/app/modules/http/modules/controller.ts`:
- Around line 374-420: The two factory methods createPasswordRecoveryService and
createRegistrationService duplicate resolving dataSource, realmRepository,
mailClient and building UserRepositoryAdapter/RealmRepositoryAdapter; extract
that shared setup into a private helper (e.g., createUserServiceDeps) that
returns { repository, realmRepository, mailClient } (and dataSource if needed),
then update both createPasswordRecoveryService and createRegistrationService to
call this helper and pass its returned repository/realmRepository/mailClient
into PasswordRecoveryService and RegistrationService, keeping each
service-specific options logic intact.
In `@apps/server-core/src/core/identity/password-recovery/service.ts`:
- Around line 208-217: The token validator registered via
validator.mount('token', createValidator(...)) currently allows a minimum length
of 3; tighten it to require the actual token length (e.g., change isLength({
min: 3, max: 256 }) to isLength({ min: 64, max: 256 })) so generated
64-hex-character tokens are enforced; update the validation in the
createValidator / createValidationChain block referenced by
validator.mount('token') to use min: 64 (and keep or adjust max as appropriate).
- Around line 108-109: Replace the inline instantiation of
UserCredentialsService with a dependency provided on the
PasswordRecoveryServiceContext: add a userCredentialsService:
UserCredentialsService (or factory) property to PasswordRecoveryServiceContext,
accept and assign it in the PasswordRecoveryService constructor, and change the
call site from "new UserCredentialsService()" to use the injected context
property (e.g.,
this.context.userCredentialsService.protect(validated.password)); update any
tests/consumers to supply a mock or real UserCredentialsService via the context.
In `@apps/server-core/src/core/identity/registration/types.ts`:
- Line 28: The public method signature register currently accepts Record<string,
any>, which weakens type safety; change it to Record<string, unknown> or define
and use a dedicated DTO/interface (e.g., RegisterInput { email: string; name?:
string; password: string; realm_id?: string }) in the same module and update the
register declaration to return Promise<RegistrationResult> with that input type;
then adjust implementations (functions named register and any places importing
this type) to explicitly narrow/validate the unknown input (or accept the DTO)
so callers must perform safe casting/validation and TypeScript will enforce the
contract.
In `@apps/server-core/test/app/factory.ts`:
- Around line 37-38: The test factory sets config.registrationEnabled and
config.emailVerificationEnabled but omits passwordRecoveryEnabled; update the
test setup to explicitly set config.passwordRecoveryEnabled (e.g., true)
alongside the other flags so the Config used by tests (see the Config type with
passwordRecoveryEnabled) has deterministic behavior for any password recovery
flows.
In `@docs/src/guide/deployment/configuration-server-core.md`:
- Around line 133-161: Add a clear migration note to the configuration docs
explaining the renamed environment variables so existing deployments don't
silently misconfigure: insert a short "Migration note" block near the .env
examples listing the mappings `REGISTRATION` → `REGISTRATION_ENABLED`,
`EMAIL_VERIFICATION` → `EMAIL_VERIFICATION_ENABLED`, and `FORGOT_PASSWORD` →
`PASSWORD_RECOVERY_ENABLED` (referencing the .env keys shown like
PORT/PUBLIC_URL/REGISTRATION_ENABLED) so upgraders can update their environment
variables accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 3de4021b-a2a1-4679-b01c-c1333768443c
📒 Files selected for processing (16)
.agents/architecture.md.agents/conventions.md.claude/skills/investigate-pr-comments/SKILL.mdapps/server-core/src/app/modules/config/constants.tsapps/server-core/src/app/modules/config/normalize.tsapps/server-core/src/app/modules/config/parse.tsapps/server-core/src/app/modules/config/read/env.tsapps/server-core/src/app/modules/config/types.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/core/entities/user/service.tsapps/server-core/src/core/identity/password-recovery/service.tsapps/server-core/src/core/identity/password-recovery/types.tsapps/server-core/src/core/identity/registration/service.tsapps/server-core/src/core/identity/registration/types.tsapps/server-core/test/app/factory.tsdocs/src/guide/deployment/configuration-server-core.md
✅ Files skipped from review due to trivial changes (2)
- .agents/architecture.md
- .agents/conventions.md
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/server-core/src/core/identity/registration/service.ts
| ```bash | ||
| # Get PR number | ||
| gh pr view --json number,headRepository | ||
|
|
||
| # Get PR-level comments (skip bot summaries) | ||
| gh api repos/{owner}/{repo}/issues/{number}/comments | node -e "..." | ||
|
|
||
| # Get review comments with file/line context | ||
| gh api repos/{owner}/{repo}/pulls/{number}/comments | node -e "..." | ||
| ``` |
There was a problem hiding this comment.
Provide complete, working examples for JSON parsing.
The example commands use node -e "..." placeholders without demonstrating the actual JSON parsing logic needed to extract and filter comments (e.g., "skip bot summaries" mentioned in line 32). Users cannot execute these commands as written.
📝 Suggested enhancement with concrete examples
Consider replacing the placeholders with working examples that demonstrate the actual filtering logic:
```bash
# Get PR number
gh pr view --json number,headRepository
-# Get PR-level comments (skip bot summaries)
-gh api repos/{owner}/{repo}/issues/{number}/comments | node -e "..."
+# Get PR-level comments (skip bot summaries)
+PR_NUM=$(gh pr view --json number -q .number)
+REPO_INFO=$(gh repo view --json owner,name -q '{owner: .owner.login, name: .name}')
+OWNER=$(echo "$REPO_INFO" | node -e "console.log(JSON.parse(require('fs').readFileSync(0, 'utf-8')).owner)")
+REPO=$(echo "$REPO_INFO" | node -e "console.log(JSON.parse(require('fs').readFileSync(0, 'utf-8')).name)")
+gh api "repos/$OWNER/$REPO/issues/$PR_NUM/comments" | node -e "
+ const comments = JSON.parse(require('fs').readFileSync(0, 'utf-8'));
+ comments.filter(c => !c.user.login.includes('bot')).forEach(c => {
+ console.log(\`[\${c.user.login}] \${c.body.substring(0, 100)}...\`);
+ });
+"
-# Get review comments with file/line context
-gh api repos/{owner}/{repo}/pulls/{number}/comments | node -e "..."
+# Get review comments with file/line context
+gh api "repos/$OWNER/$REPO/pulls/$PR_NUM/comments" | node -e "
+ const comments = JSON.parse(require('fs').readFileSync(0, 'utf-8'));
+ comments.forEach(c => {
+ console.log(\`\${c.path}#L\${c.line}: [\${c.user.login}] \${c.body.substring(0, 80)}...\`);
+ });
+"
</details>
<details>
<summary>🤖 Prompt for AI Agents</summary>
Verify each finding against the current code and only fix it if needed.
In @.claude/skills/investigate-pr-comments/SKILL.md around lines 19 - 28,
Replace the placeholder node -e snippets with concrete JSON parsing and
filtering commands: capture the PR number and repo info into variables (PR_NUM,
OWNER, REPO) using gh pr view and gh repo view, then call gh api
"repos/$OWNER/$REPO/issues/$PR_NUM/comments" and parse the JSON to filter out
bot users (e.g., skip comments where c.user.login includes "bot") and print
trimmed summaries; do the same for gh api
"repos/$OWNER/$REPO/pulls/$PR_NUM/comments" to output file/line context (use
c.path and c.line) and user/body previews so the examples are fully runnable
without placeholders.
</details>
<!-- fingerprinting:phantom:triton:puma -->
<!-- This is an auto-generated comment by CodeRabbit -->
The refactor in #2910 dropped the request query from ClientService.getOne, so applyQuery's field selection (allowed: ['secret']) was no longer reached and `?fields=+secret` silently returned no secret. - Add IClientRepository.findOne(id, query?, realm?) using applyQuery, mirroring the existing IUserRepository.findOne pattern; service's getOne now delegates to it - Align ClientService.getOne signature with IUserService.getOne: (idOrName, actor, query?, realmId?) - Mirror save()'s self-edit fallback: try CLIENT_READ/UPDATE/DELETE upfront, fall back to CLIENT_SELF_MANAGE when a client identity accesses its own record (verified against entity.id in the catch) - Skip the post-load ATTRIBUTES-based secret evaluation on self-access; CLIENT_SELF_MANAGE's ATTRIBUTE_NAMES denylist would otherwise reject the entity's own keys (active, realm_id, ...)
Same regression as #2910 introduced for clients: RobotService.getOne dropped the request query, so applyQuery's field selection was never reached and `?fields=+secret` returned no secret on GET /robots/:id. - Add IRobotRepository.findOne(id, query?, realm?) using applyQuery, matching the IUserRepository / IClientRepository pattern - Align RobotService.getOne signature with peers: (idOrName, actor, query?, realmId?) - Mirror save()'s self-edit fallback for ROBOT_SELF_MANAGE; getOne now lets a robot read its own record when it lacks ROBOT_READ etc. - Skip post-load ATTRIBUTES-based evaluation on self-access; the ATTRIBUTE_NAMES denylist on ROBOT_SELF_MANAGE would otherwise reject the entity's own keys
* fix: restore +secret field selection on GET /clients/:id The refactor in #2910 dropped the request query from ClientService.getOne, so applyQuery's field selection (allowed: ['secret']) was no longer reached and `?fields=+secret` silently returned no secret. - Add IClientRepository.findOne(id, query?, realm?) using applyQuery, mirroring the existing IUserRepository.findOne pattern; service's getOne now delegates to it - Align ClientService.getOne signature with IUserService.getOne: (idOrName, actor, query?, realmId?) - Mirror save()'s self-edit fallback: try CLIENT_READ/UPDATE/DELETE upfront, fall back to CLIENT_SELF_MANAGE when a client identity accesses its own record (verified against entity.id in the catch) - Skip the post-load ATTRIBUTES-based secret evaluation on self-access; CLIENT_SELF_MANAGE's ATTRIBUTE_NAMES denylist would otherwise reject the entity's own keys (active, realm_id, ...) * fix: restore +secret field selection on GET /robots/:id Same regression as #2910 introduced for clients: RobotService.getOne dropped the request query, so applyQuery's field selection was never reached and `?fields=+secret` returned no secret on GET /robots/:id. - Add IRobotRepository.findOne(id, query?, realm?) using applyQuery, matching the IUserRepository / IClientRepository pattern - Align RobotService.getOne signature with peers: (idOrName, actor, query?, realmId?) - Mirror save()'s self-edit fallback for ROBOT_SELF_MANAGE; getOne now lets a robot read its own record when it lacks ROBOT_READ etc. - Skip post-load ATTRIBUTES-based evaluation on self-access; the ATTRIBUTE_NAMES denylist on ROBOT_SELF_MANAGE would otherwise reject the entity's own keys * refactor: allow identities to read their own record without permission Align ClientService.getOne and RobotService.getOne with UserService.getOne: when the actor's identity matches the requested id-or-name, skip the upfront permission gate and the post-load ATTRIBUTES evaluation. *_SELF_MANAGE was always semantically a write permission (its ATTRIBUTE_NAMES denylist constrains editable fields, not readable ones), so requiring it for self-read was the wrong fit. Self-read now works the same across user, client, and robot — any authenticated identity can fetch its own record without holding any *_READ / *_SELF_MANAGE. The +secret / +email opt-in fields still require the explicit ?fields=+... query param. Non-self lookups continue to require *_READ / *_UPDATE / *_DELETE. * chore: updated agent files * fix: re-validate self-access after entity load Tentative self-detection (id-or-name match against actor identity) can falsely match when a name collides across realms — the loaded entity may belong to a different identity than the actor. Re-check after the lookup using the loaded entity's UUID against the actor's identity id; if they don't match, run the permission gate that was skipped pre-load. This mirrors the post-load self-edit verification already used in ClientService.save() / RobotService.save() / UserService.delete(), so read and write paths now share one self-detection idiom anchored on UUID equality. Applied to client, robot, and user getOne. Tests cover: - self-by-id and self-by-name (same entity) bypass permissions - self-by-name where the loaded entity's id differs from the actor's triggers the deferred preEvaluateOneOf and surfaces ForbiddenError
resolves #2909
Summary by CodeRabbit