Authentication API (/auth)
Relevant source files
The following files were used as context for generating this wiki page:
The Authentication API provides a complete JSON Web Token (JWT) based authentication and authorization system for the Kodus Runtime. It manages user registration, login, session renewal via refresh tokens, and secures critical API endpoints. The core logic is encapsulated within the @kodus/auth package, which is consumed by the Elysia-based API server.
This system is responsible for verifying user identity and controlling access to protected resources. It features role-based access control (RBAC) with predefined roles such as ADMIN, USER, and SERVICE. All critical routes, such as those for managing events and workflows, are protected by this authentication layer.
Sources: README.md:20-25, apps/api/src/routes/auth.ts, packages/auth/src/index.ts
Architecture Overview
The authentication system is composed of three main components: the API routes, the User Service, and the JWT Service. The API routes handle incoming HTTP requests, the User Service manages user data persistence and logic (currently in-memory), and the JWT Service is responsible for creating and verifying tokens.
The diagram below illustrates the high-level interaction between these components.
This diagram shows the flow of control from the API routes in auth.ts to the underlying UserService and JWTService for handling authentication logic.
Sources: apps/api/src/routes/auth.ts:8, apps/api/src/services/userService.ts:8, packages/auth/src/jwt.ts:4, packages/auth/src/middleware.ts:5
Core Components
User Service (UserService)
The UserService acts as the data access layer for user information. In the current implementation, it uses a simple in-memory Map to store user data and credentials, making it suitable for development but requiring a database backend for production.
Key Responsibilities:
- User Creation: Creates new users, hashes their passwords using
bcrypt, and assigns a defaultUSERrole. - Credential Validation: Compares a provided email and password against the stored hash to authenticate users.
- User Retrieval: Fetches user profiles by ID or email.
- Default User: Initializes a default administrator account (
admin@kodus.dev/admin123) on startup.
The diagram below shows the structure of the UserService and its main methods.
JWT Service (JWTService)
The JWTService encapsulates all logic related to JSON Web Tokens. It uses the jsonwebtoken library to generate and verify tokens. The service is configured via environment variables.
Key Responsibilities:
- Token Generation: Creates
accessTokenandrefreshTokenpairs for authenticated users. - Token Verification: Validates the signature and expiration of incoming access and refresh tokens.
- Token Extraction: Provides a utility to extract a bearer token from an
Authorizationheader. - Role Checking: A helper method to check if a user's role is in a list of required roles.
Sources: packages/auth/src/jwt.ts:4-124
Configuration
The JWTService is configured using the following environment variables. If not set, it falls back to default development values.
| Variable | Description | Default Value | Source File |
|---|---|---|---|
JWT_ACCESS_SECRET | Secret key for signing access tokens. | 'your-access-secret-key' | packages/auth/src/jwt.ts:10 |
JWT_REFRESH_SECRET | Secret key for signing refresh tokens. | 'your-refresh-secret-key' | packages/auth/src/jwt.ts:11 |
JWT_ACCESS_EXPIRY | Expiration time for access tokens. | '15m' | packages/auth/src/jwt.ts:12 |
JWT_REFRESH_EXPIRY | Expiration time for refresh tokens. | '7d' | packages/auth/src/jwt.ts:13 |
Authentication Middleware
Route protection is handled by a middleware function, authenticate, which can be configured to enforce different access policies. It checks for a valid JWT in the Authorization header, verifies it, and attaches the user object to the request context.
The following flowchart describes the logic of the authenticate middleware.
Sources: packages/auth/src/middleware.ts:5-64
The package also exports several pre-configured middleware helpers:
requireAdmin(): Requires an active user with theADMINrole.requireUser(): Requires an active user withUSERorADMINroles.requireService(): Requires an active user withSERVICEorADMINroles.
Sources: packages/auth/src/middleware.ts:70-87
API Endpoints
All authentication-related endpoints are grouped under the /auth prefix.
Sources: apps/api/src/routes/auth.ts:6
POST /auth/register
Registers a new user in the system. On success, it returns the new user object and a pair of JWT tokens.
Request Body:
{
"email": "new.user@example.com",
"password": "password123",
"name": "New User"
}
Responses:
201 Created: Registration successful.400 Bad Request: Missing required fields or password too short.409 Conflict: A user with the given email already exists.500 Internal Server Error: Generic registration failure.
The sequence diagram below shows the registration flow.
Sources: apps/api/src/routes/auth.ts:9-62
POST /auth/login
Authenticates a user with an email and password. On success, it returns the user object and a new set of JWT tokens.
Request Body:
{
"email": "admin@kodus.dev",
"password": "admin123"
}
Responses:
200 OK: Login successful.400 Bad Request: Missing email or password.401 Unauthorized: Invalid credentials.403 Forbidden: The user account is inactive.500 Internal Server Error: Generic login failure.
The sequence diagram below shows the login flow.
Sources: apps/api/src/routes/auth.ts:65-120
POST /auth/refresh
Generates a new set of tokens using a valid refreshToken. This allows clients to maintain a session without re-prompting for credentials.
Request Body:
{
"refreshToken": "a.valid.refreshtoken"
}
Responses:
200 OK: Token refresh successful.400 Bad Request: MissingrefreshToken.401 Unauthorized: Invalid or expired refresh token.403 Forbidden: The user account is inactive.
Sources: apps/api/src/routes/auth.ts:123-178
GET /auth/me
A protected route that returns information about the currently authenticated user. Requires a valid accessToken in the Authorization header.
Responses:
200 OK: Returns the full user object.401 Unauthorized: Not authenticated.
Sources: apps/api/src/routes/auth.ts:181-201
POST /auth/logout
A stateless endpoint that signals a successful logout. The client is responsible for discarding the stored JWT tokens. In the current implementation, this endpoint does not perform any server-side token invalidation.
Responses:
200 OK: Logout successful message.
Sources: apps/api/src/routes/auth.ts:204-212
Data Models
The authentication system relies on several key data structures defined in the @kodus/auth package.
Sources: packages/auth/src/types.ts
User
Represents a user in the system.
| Field | Type | Description |
|---|---|---|
id | string | Unique identifier for the user. |
email | string | User's email address (used for login). |
name | string | User's full name. |
role | UserRole | The role assigned to the user (ADMIN, USER, or SERVICE). |
isActive | boolean | Flag indicating if the user account is active. |
createdAt | Date | Timestamp of when the user was created. |
updatedAt | Date | Timestamp of the last update to the user. |
Sources: packages/auth/src/types.ts:1-9
UserRole
An enum defining the possible roles a user can have.
| Value | Description |
|---|---|
ADMIN | Administrator with full permissions. |
USER | Standard user with limited permissions. |
SERVICE | A role for service-to-service communication. |
Sources: packages/auth/src/types.ts:11-15
JWTPayload
The data encoded within the accessToken.
| Field | Type | Description |
|---|---|---|
userId | string | The ID of the user. |
email | string | The email of the user. |
role | UserRole | The role of the user at the time of token issuance. |
Sources: packages/auth/src/types.ts:17-23
AuthTokens
The object returned upon successful login or token refresh.
| Field | Type | Description |
|---|---|---|
accessToken | string | The JWT used to access protected resources. |
refreshToken | string | The JWT used to obtain a new accessToken. |
expiresIn | number | The lifetime of the accessToken in seconds. |
Sources: packages/auth/src/types.ts:25-29