luizomf/clean-architecture-api-boilerplate
47.5
Weak · 9 November 2026
2.1k
lines of production code
TypeScript
primary language
6
measurements over time
What this system is
This system is a Node.js API built on Clean Architecture principles, designed to manage user accounts and handle secure authentication flows. It provides capabilities for user registration, profile management, and role-based access control, supported by a PostgreSQL database via Knex. The system implements JWT-based sign-in and token refresh mechanisms, ensuring secure session management with configurable expiration policies.
Features
Add common utility helpers for dates, objects, and strings
This change introduces a new set of reusable helper functions in the common helpers library to standardize data manipulation across the application. It adds \createFutureDate\ and \formatDateTime\ for date arithmetic and formatting (including validation via \DateTimeError\), \zeroPadLeft\ for number padding, \objectKeyExists\ as a TypeScript type guard to safely check for key presence, \removeObjectEmptyKeys\ to clean up objects by deleting undefined values, and \isString\ for type narrowing. These utilities provide consistent, tested building blocks for date handling, object sanitization, and type checking.
src/common/helpers · high confidence
Add generic HTML string sanitizer adapter
A new GenericStringSanitizerAdapter has been introduced to handle HTML sanitization for string inputs. This adapter uses the sanitize-html library to strip unwanted tags (such as script tags) from provided strings. It returns an empty string for undefined inputs and throws a SanitizerError if the input is not a string or undefined, ensuring type safety during sanitization.
src/common/adapters/sanitizers · high confidence
Add token refresh controller with input validation and sanitization
A new RefreshTokenController has been introduced to handle token refresh requests. It validates that the incoming request contains a valid string token, sanitizes the input using a generic string sanitizer, and delegates the refresh logic to the RefreshTokenUseCase. The controller ensures that invalid or non-string tokens are rejected with a RequestValidationError before any business logic is executed.
src/presentation/controllers/token · high confidence
Added Insomnia workspace export for API testing
A new Insomnia workspace export file has been added to the misc directory, providing a pre-configured set of requests for the 'Clean Architecture' API. This file includes endpoints for user management (GET, POST, PUT, DELETE), sign-in, and token refresh, along with a base environment configuration pointing to localhost:3000, allowing users to easily import and test the API endpoints using the Insomnia client.
misc · high confidence
Added Refresh Token Use Case Interface
A new interface for the refresh token use case has been introduced in the domain layer. This defines the contract for refreshing authentication sessions, specifying that the \refresh\ method accepts a refresh token string and returns a promise resolving to a sign-in response model. This establishes the structural foundation for the token refresh capability within the application's domain logic.
src/domain/use-cases/token · high confidence
Added Sanitizer interface definition
A new \Sanitizer\ interface has been introduced in the application ports layer, defining a generic contract with a \sanitize\ method that accepts an input value and returns a sanitized output. This interface establishes the standard for input sanitization logic within the application architecture.
src/application/ports/sanitizers · high confidence
Added database seed scripts for initial admin user and roles
New Knex seed files (01\_users, 02\_roles, 03\_user\_roles) have been added to the infrastructure layer to populate the database with initial data. This includes creating an admin user with a hashed password, defining 'admin' and 'public' roles, and linking the admin user to the admin role, ensuring the application starts with a functional administrative account.
src/infrastructure/knex/seeds · high confidence
Added token refresh capability
Users can now refresh their authentication tokens without re-entering credentials. This change introduces the \RefreshToken\ use case and its corresponding tests in the application layer, which validates the existing refresh token, issues a new access token and refresh token pair, and persists the new refresh token.
src/application/use-cases/token · high confidence
Added token repository interfaces for CRUD operations
New interface definitions have been added to the application ports layer to support token management. These include \CreateTokenRepository\ for creating tokens, \DeleteTokenByUserIdRepository\ for removing tokens by user, and specific finders (\FindTokenByIdRepository\, \FindTokenByTokenRepository\, \FindTokenByUserIdRepository\) to retrieve tokens by ID, token string, or user ID. These interfaces define the contract for token persistence operations within the application layer.
src/application/ports/repositories/token · high confidence
Added validation for non-empty strings
A new validation rule, ValidateStringNotEmpty, has been introduced to ensure that string inputs are not empty. This rule throws a RequestValidationError with a 400 status code if the provided string is empty or not a string type, otherwise it allows the validation to pass. The implementation has been moved from the adapters layer to the application layer's common validation utilities.
src/application/validation/common · high confidence
Domain models updated to support refresh tokens and role-based access
The domain layer now includes new models for authentication flows, specifically adding a \SignInResponseModel\ that returns both an access token and a refresh token, alongside dedicated \Token\ and \SignedToken\ models to manage token lifecycle and expiration. Additionally, the \User\ model has been extended to include an optional \roles\ array, enabling role-based access control, while request models for sign-in and user creation have been reorganized into the domain layer for better separation of concerns.
src/domain · high confidence
Initial database schema for users, tokens, and roles
The application now includes the foundational database migrations to support user authentication and authorization. This introduces a 'users' table storing account details, a 'tokens' table for managing session refresh tokens with expiration, and a 'roles' system with a many-to-many relationship between users and roles to enable role-based access control.
src/infrastructure/knex/migrations · high confidence
Initial project structure and configuration
This change introduces the initial boilerplate for a Clean Architecture API using TypeScript and Node.js. It establishes the core folder structure (domain, application, presentation, infrastructure, main) and includes essential configuration files such as .env-example (defining database, JWT, and port settings), docker-compose.yml (for PostgreSQL), and Jest configuration (with specific test path ignore patterns). It also adds standard project files like README.md, LICENSE, and .gitignore, along with linting and pre-commit hook configurations.
(repo-wide) · high confidence
Introduction of JWT token signing and verification interface
A new \JwtToken\ interface has been added to the security ports layer, defining the contract for signing access and refresh tokens and verifying JWT strings. This establishes the foundational capability for the application to generate and validate JSON Web Tokens, supporting the introduction of refresh token functionality.
src/application/ports/security · high confidence
Introduction of Knex database connection and configuration
The application now uses Knex as the database query builder and connection manager. New files in the infrastructure layer establish a database connection instance (\connection.ts\) and a configuration file (\knexfile.ts\) that supports SQLite for test and development environments, and PostgreSQL for production. The configuration reads database credentials (host, name, user, password, port) from environment variables and sets up migration and seed directories.
src/infrastructure/knex · high confidence
Introduction of Middleware interface for request handling
A new Middleware interface has been added to the application ports, defining a standard contract for middleware components. This interface specifies a handleRequest method that accepts a MiddlewareRequestModel, enabling a consistent way to process incoming requests within the application layer.
src/application/ports/middlewares · high confidence
New SignInController with input validation and sanitization
A new SignInController has been introduced to handle user authentication requests. It validates that the request body contains non-empty string values for email and password, throwing an UnauthorizedError if they are missing or invalid. The controller also applies a generic string sanitizer to the input data before passing it to the underlying sign-in use case, and returns the resulting token and refresh token via a response presenter.
src/presentation/controllers/sign-in · high confidence
New application error classes and import path standardization
This change introduces four new specific error classes—DateTimeError, RepositoryError, SanitizerError, and UnauthorizedError—each extending the base DefaultApplicationError with appropriate HTTP status codes (500, 500, 400, and 401 respectively) and includes unit tests for them. Additionally, the import paths for DefaultApplicationError have been standardized to use the absolute path (\~/) across existing error files, and the import for ResponseModel has been updated to reflect a directory rename from 'response' to 'responses'.
src/application/errors · high confidence
New authentication, token refresh, and user management controller factories
This change introduces factory functions in src/main/factories to wire up new and refactored controllers for the application. A new refresh-token-controller-factory enables token refresh capabilities, while sign-in-controller-factory wires the sign-in flow with JWT and BCrypt adapters. Existing user management capabilities (create, find by ID, find all, update, delete) are now exposed via dedicated controller factories (create-user, find-user-by-id, find-all-users, update-user, delete-user-by-id) that utilize the new GenericSuccessResponse, GenericCreatedResponse, GenericUpdatedResponse, and GenericDeletedResponse presenters. Additionally, authentication middleware factories (is-authenticated-middleware-factory, logged-user-is-target-user-middleware-factory) are added to support route protection and target-user validation.
src/main · high confidence
New user management controllers with input sanitization
Added presentation-layer controllers for creating, finding, updating, and deleting users. These controllers enforce request validation (checking for required body or params), sanitize string inputs using a generic sanitizer adapter, and delegate to domain use cases while returning standardized HTTP responses.
src/presentation/controllers/user · high confidence
SQL repository now retrieves users with their associated roles
The SQL user repository has been extended to support fetching a user along with their assigned roles. This change introduces a new \findOneWithRoles\ method that joins the \users\, \user\_roles\, and \roles\ tables, and uses a new \mapUserFields\ helper to aggregate multiple role rows into a single user object with a \roles\ array. The repository now implements the \FindOneUserWithRoles\ port, and corresponding tests verify that users are correctly returned with their role details or null if not found.
src/infrastructure/repositories/user/sql · high confidence
SQL-based token persistence and repository implementation
The system now persists authentication tokens to a SQL database via a new \TokenSqlRepository\. This implementation supports creating, finding (by token, ID, or user ID), and deleting tokens, with logic that automatically filters out expired entries and ensures only one active token exists per user during creation. A default repository instance is exported to wire these capabilities into the application.
src/infrastructure/repositories/token · high confidence
Sign-in now returns both access and refresh tokens
The SignIn use case has been updated to issue a refresh token alongside the access token upon successful authentication. When a user logs in, the system now generates a refresh token, persists it to the database via the TokenSqlRepository, and returns both the access token and the refresh token in the response. This enables clients to implement token refresh flows without requiring the user to re-authenticate.
src/application/use-cases/sign-in · high confidence
User management use cases now enforce validation and support deletion and bulk retrieval
The user use cases in the application layer have been refactored to include input validation via a ValidationComposite for Create, Find, and Update operations, ensuring data integrity before repository interaction. A new DeleteUserById use case has been added, which validates the ID, checks for user existence, and returns the number of deleted rows. Additionally, a FindAllUsers use case now supports paginated retrieval with configurable order, limit, and offset. The UpdateUser use case has been enhanced to check for email uniqueness and hash passwords if provided. These changes also involve moving models and interfaces to the domain layer and restructuring repository ports.
src/application/use-cases/user · high confidence
User route authorization and new endpoints
The user management routes now require authentication and verify that the logged-in user is the target of the request for GET, PUT, and DELETE operations. Additionally, a new DELETE endpoint has been added to allow users to remove their own accounts, and a new GET endpoint allows listing all users (subject to the same authorization checks). The sign-in and refresh-token routes have also been introduced to handle authentication flows.
src/infrastructure/express/routes · high confidence
Removals
Removal of FindUserById controller factory and its tests
The factory responsible for wiring the FindUserById controller, use case, and validation logic has been removed, along with its associated unit tests. This eliminates the previous implementation that relied on an in-memory user repository, effectively removing the ability to instantiate this specific controller via the factory pattern in the current codebase.
src/infrastructure/factories · high confidence
Removal of in-memory user repository and related test artifacts
The in-memory implementation of the user repository, along with its factory and associated unit tests, has been removed from the codebase. This deletion eliminates the \InMemoryUserRepository\ class and the \inMemoryUserRepositoryFactory\ utility that previously provided a test-specific in-memory data store, effectively removing this local testing infrastructure from the project.
src/application/ports/user, src/infrastructure/repositories/testing-repository · high confidence
Removal of user controller and validation adapter layer
The user-facing adapter layer in \src/adapters\ has been removed, deleting the \CreateUserController\ and \FindUserByIdController\ implementations along with their associated test suites. This change also eliminates the concrete validation logic for user requests, including the \CreateUserRequestValidationComposite\ and \FindUserByIdValidationComposite\, as well as the \CreatedUserPresenter\ and \SuccessUserPresenter\ response formatters. Consequently, the specific request validation rules (such as checking for missing fields, email validity, and password matching) and the response formatting behavior (such as stripping password hashes) previously handled in this location are no longer present in the adapter layer.
src/adapters · high confidence
Removed console application simulation scripts
The console application entry-point scripts for creating and finding users by ID have been removed. These files previously served as simulation scripts to test controller factories directly in a console environment without Express; their removal indicates a shift away from this specific testing or demonstration pattern within the infrastructure layer.
src/infrastructure/console-application · high confidence
Architecture
Introduces a default user repository implementation
A new default repository file has been added to the user infrastructure layer, providing concrete instances of all user-related repository interfaces (create, find by ID/email, delete, update, find all, and find one with roles) by delegating to the existing SQL repository. This change centralizes the repository wiring for the user module, making it easier to swap or configure the underlying data access implementation during development.
src/infrastructure/repositories/user · high confidence
Use case interfaces moved to the domain layer
The interfaces for core user operations (sign-in, create, delete, find, and update) have been relocated from the application ports layer to the domain use-cases layer. This reorganization centralizes the contract definitions for user management within the domain, ensuring that the expected behavior for these operations is defined at the architectural boundary closest to the business logic.
src/domain/use-cases/sign-in, src/domain/use-cases/user · high confidence
Behavioural changes
Controller interface now defaults to unknown type parameter
The Controller interface in the application ports layer has been updated so that its generic type parameter defaults to 'unknown' if not explicitly specified. This change, along with path alias adjustments for request and response models, ensures that controllers without an explicit type definition handle data as generic unknown objects rather than requiring an explicit type annotation.
src/application/ports/controllers · high confidence
Enhanced security, error handling, and rate limiting for API endpoints
The Express application setup now includes several improvements to security and reliability. Global middleware now integrates Helmet to set secure HTTP headers and enforces JSON body parsing. A new rate-limiting middleware (express-rate-limit) is applied to the /users, /sign-in, and /refresh-token routes, restricting requests to 100 per 3 minutes. Error handling has been refined: generic errors now return a structured JSON response including error name, message, and status code, and detailed error logging is enabled when the DEBUG environment variable is set. Additionally, the 'trust proxy' setting is configured to support correct client IP detection behind proxies.
src/infrastructure/express/setup · high confidence
Express middleware and route adapters now pass request headers to application layer
The Express adapters have been refactored to explicitly include HTTP headers in the request data passed to the application layer. The new \expressMiddlewareAdapter\ and the updated \expressRouteAdapter\ now forward \request.headers\ alongside query, params, body, and method. Additionally, the route adapter's return behavior was corrected to explicitly return the \next()\ call, ensuring proper control flow in the middleware chain.
src/infrastructure/express/adapters · high confidence
Express server initialization refactored and test environment isolated
The Express application entry point has been restructured to support better testability and modularity. The server instance is now exported directly from \server.ts\ instead of being created and started immediately, allowing tests to import the app without triggering a network listener. A new \setupApp\ function is called during initialization, separating core app configuration from middleware and route setup. Additionally, the middleware adapter utility for converting async handlers has been removed, likely replaced by native Express error handling or a different pattern. The server only starts listening on the configured port when the environment is not set to 'test', preventing port conflicts during automated testing.
src/infrastructure/express · high confidence
JWT token adapter now supports configurable access and refresh token expiration
The security adapter for JWT tokens has been updated to support separate expiration settings for access and refresh tokens. The adapter now accepts distinct secrets and expiration durations (in seconds) for both token types, allowing for more granular control over session lifetimes. This change includes the introduction of a refresh token signing mechanism alongside the existing access token functionality, with default expiration times set to 10 minutes for access tokens and 8 days for refresh tokens. The adapter also provides a singleton instance that reads these configuration values from environment variables, enabling runtime customization of token validity periods.
src/common/adapters/security · high confidence
Refactored RequestModel interface and added MiddlewareRequestModel
The application's request handling interfaces have been restructured to support more granular data typing. The core RequestModel interface now accepts generic parameters for body, params, query, and headers, allowing consumers to define specific types for each section of the request. Additionally, a new MiddlewareRequestModel interface has been introduced, which extends RequestModel to optionally include an HTTP method, facilitating middleware that needs to inspect or modify request methods.
src/application/ports/requests · high confidence
Refactored authentication and authorization middleware logic
The authentication middleware now sanitizes the authorization token before verification and injects the extracted userId into the request headers. A new authorization middleware enforces that users can only access their own profile data, unless they hold the 'admin' role, by checking the logged-in user's ID against the target user ID in the request parameters.
src/presentation/middlewares · high confidence
Refactored user validation logic into a composable validation pipeline
The user validation logic has been restructured from a monolithic adapter into a composable pipeline of specific validation rules. This change introduces distinct leaf validators for required fields (with separate logic for create vs. update operations), email format, and password matching, which are orchestrated by a new composite validation class. Additionally, a new validator ensures that pagination parameters for finding users are valid. This modular approach allows for more precise error reporting and easier maintenance of validation rules across different user operations.
src/application/validation/user · high confidence
Refined sign-in validation to check email and password fields
The sign-in validation logic has been updated to explicitly verify that both the email and password fields are present and valid in the request body. Previously, validation focused primarily on email format; the new implementation now also rejects requests with missing passwords and provides specific error messages for missing or invalid email addresses, ensuring users receive clearer feedback during the sign-in process.
src/application/validation/sign-in · high confidence
Removal of CreateUserRepository interface
The \CreateUserRepository\ interface, previously defined in \src/application/ports/repositories/create-user-repository.ts\, has been removed from the codebase. This change eliminates the specific port contract for creating users, likely as part of a broader restructuring of user-related use-case interfaces.
src/application/ports/repositories · high confidence
Removal of generic RequestModel interface
The generic \RequestModel\ interface, which previously provided a unified structure for request \body\, \params\, and \query\ data, has been removed from the application ports. This change eliminates the abstraction layer for request modeling in this location, requiring consumers to handle request data structures directly or through other defined interfaces.
src/application/ports/request · high confidence
Rename presenters to responses and migrate to ResponseHandler port
The generic response classes (GenericCreated, GenericSuccess, GenericUpdated, GenericDeleted) have been renamed from 'Presenter' to 'Response' and moved from src/adapters/presenters/responses/generic to src/presentation/responses. These classes now implement the ResponseHandler\<T\> port instead of the Presenter\<T\> port, aligning the presentation layer with the updated application ports for response handling.
src/presentation/responses · high confidence
Renamed Presenter interface to ResponseHandler and reorganized response ports
The application's response handling interface has been renamed from \Presenter\ to \ResponseHandler\ to reduce confusion, and the related files have been moved from \src/application/ports/presenters\ and \src/application/ports/response\ into a unified \src/application/ports/responses\ directory. This change updates the import paths for \ResponseModel\ and reflects the new interface name in the code, clarifying the role of this port within the application layer.
src/application/ports/responses · high confidence
Reorganized user repository interfaces into a dedicated subdirectory
The user repository interfaces (Create, Delete, Find All, Find One with Roles, Update, Find By Email, and Find By Id) have been moved from the general \src/application/ports/repositories/\ directory into a new \src/application/ports/repositories/user/\ subdirectory. This change also updates the import paths for the \User\ model to reflect its relocation to the domain layer (\\~/domain/models/user/user\), ensuring the application layer correctly references the updated domain structure.
src/application/ports/repositories/user · high confidence
Reorganized validation ports and refined ValidationComposite typing
The validation port files have been moved from the validators directory to a new validation directory. Additionally, the ValidationComposite class now uses a generic type parameter for its input arguments and has been updated to correctly reflect that the validate method can either resolve to void or never return, improving type safety for validation logic.
src/application/ports/validation · high confidence
Reorganized validator adapter location and updated import path
The email validator adapter and its associated test file have been moved from src/common/validators to src/common/adapters/validators. Additionally, the adapter's import for the EmailValidator interface was updated to reflect a change in the interface's location from \~/application/ports/validators to \~/application/ports/validation.
src/common/adapters/validators · high confidence
Dependencies
Upgrade dependencies and add database and security packages
This update upgrades the Babel toolchain (cli, core, presets) to version 7.12.x and updates TypeScript, ESLint, Prettier, and Jest to their latest minor versions. It introduces several new runtime dependencies: Knex and PostgreSQL drivers (pg) for database access, Helmet and express-rate-limit for security and rate limiting, sanitize-html for input sanitization, and jsonwebtoken for authentication. Additionally, it adds SQLite3 and Supertest to devDependencies for testing, and includes new npm scripts for database migrations, Docker management, and linting.
(dependencies) · high confidence
Written by cca.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
How this codebase got here
This is the PUBLIC form of this artifact. Findings are listed in full, but the details of SECURITY findings — which rule fired, in which file, on which line, and how to fix it — are deliberately withheld, and any secret-scanner results are excluded entirely. Where detail is absent here it was REMOVED FOR PUBLICATION; it is not missing from the analysis. The complete artifact is available from the repository owner.
Score
- CAI 44 → 48 (+3.2)
- Rubric changed (rubric-2026.10.5 → rubric-2026.11.2) — scores are not directly comparable.
Lenses
- Code Health 94 → 94 (+0.0)
- Architecture 82 → 82 (+0.0)
- Maturity 61 → 61 (+0.0)
- Readiness 17 → 22 (+5.8)
- Security 57 → 60 (+2.4)
- Domain Modelling 100 → 100 (+0.0)
- Performance 100 → 100 (+0.0)
Resolved (22)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- Low coverage: src/application/use-cases/sign-in/sign-in.ts (src/application/use-cases/sign-in/sign-in.ts)
- Low coverage: src/common/adapters/security/bcrypt-adapter.ts (src/common/adapters/security/bcrypt-adapter.ts)
- Low coverage: src/infrastructure/express/adapters/express-middleware-adapter.ts (src/infrastructure/express/adapters/express-middleware-adapter.ts)
- Low coverage: src/infrastructure/express/adapters/express-route-adapter.ts (src/infrastructure/express/adapters/express-route-adapter.ts)
- Low coverage: src/infrastructure/express/middlewares/rate-limit.ts (src/infrastructure/express/middlewares/rate-limit.ts)
- Low coverage: src/infrastructure/express/routes/refresh-token.ts (src/infrastructure/express/routes/refresh-token.ts)
- Low coverage: src/infrastructure/express/routes/sign-in.ts (src/infrastructure/express/routes/sign-in.ts)
- Low coverage: src/infrastructure/express/routes/user.ts (src/infrastructure/express/routes/user.ts)
- Low coverage: src/infrastructure/express/setup/setup-app.ts (src/infrastructure/express/setup/setup-app.ts)
- Low coverage: src/infrastructure/express/setup/setup-async-errors.ts (src/infrastructure/express/setup/setup-async-errors.ts)
- Low coverage: src/infrastructure/express/setup/setup-global-middlewares.ts (src/infrastructure/express/setup/setup-global-middlewares.ts)
- Low coverage: src/infrastructure/express/setup/setup-routes.ts (src/infrastructure/express/setup/setup-routes.ts)
- Low coverage: src/infrastructure/repositories/token/sql/token-sql-repository.ts (src/infrastructure/repositories/token/sql/token-sql-repository.ts)
- Low coverage: src/infrastructure/repositories/user/sql/repositories/user-sql-repository.ts (src/infrastructure/repositories/user/sql/repositories/user-sql-repository.ts)
- …and 2 more
New (8)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- Low CVE: [GHSA redacted] (package-lock.json)
- Medium: security finding (details withheld)
Written by cca.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
Survey your own repository
luizomf/clean-architecture-api-boilerplate was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.
About this page
- The score is its most recent published measurement, taken on 9 November 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
- Measured at commit 7fb1ba431f8dd3d9f581798c072019eceb72d73e — the exact code this score is about.
- Scored under rubric-2026.11.2 — the same rubric and the same method as every other entry in this index.
- Measured by Canine Code Analyzer (cca.canine.dev) using cca measure-2026.11.3+preprod-bb0cb800cd0f.