API Authentication
Relevant source files
The following files were used as context for generating this wiki page:The MessageJS platform utilizes two primary authentication mechanisms to secure its API: API Key authentication for SDK-driven message sending and JWT-based authentication for user management via the dashboard. This separation ensures that client-side applications can send messages without exposing sensitive user credentials, while user-specific actions like project management remain protected.
API Key authentication is stateless and designed for public-facing clients like the @messagejs/client SDK. It uses a Bearer token in the Authorization header. User authentication, on the other hand, is stateful and used for the dashboard, involving user registration and login to obtain a JSON Web Token (JWT) for subsequent authenticated requests.
API Key Authentication
This is the primary mechanism for authenticating requests from the client SDK to the message sending endpoint (/api/v1/messages). It relies on a unique API key associated with a specific project.
Data Model & Relationships
The core data model for API key authentication involves the User and Project entities. A User can own multiple Projects, and each Project has a unique apiKey.
Sources: packages/core/prisma/schema.prisma:41-57
The following diagram illustrates the relationship between Users and Projects in the database.
The Project model in the Prisma schema defines the structure for projects, including the essential apiKey.
| Field | Type | Attributes | Description |
|---|---|---|---|
id | String | @id @default(cuid()) | Unique identifier for the project. |
name | String | The user-defined name of the project. | |
apiKey | String | @unique | The unique API key for this project. |
createdAt | DateTime | @default(now()) | Timestamp of project creation. |
userId | String | Foreign key linking to the User model. |
Sources: packages/core/prisma/schema.prisma:50-57
While the current schema.prisma stores the apiKey directly, the system's type definitions suggest a more detailed APIKey model for future implementation, which would include hashes, rate limits, and activity status.
Sources: packages/core/src/types/dataModels.ts:31-42
Request Authentication Flow
When the client SDK sends a message, it includes the API key in the Authorization header. The backend API uses the validateApiKey middleware to verify this key before allowing the request to proceed to the controller.
This sequence diagram shows the authentication flow for a POST /api/v1/messages request.
Middleware: validateApiKey
The validateApiKey middleware is responsible for protecting routes that require API key authentication. It is currently applied to the POST /api/v1/messages route.
Sources: packages/core/src/api/routes/messageRoutes.ts:17
The middleware's logic follows these steps:
- Check for the existence of the
Authorizationheader. - Verify that the header is formatted as
Bearer <api_key>. - Extract the API key from the header.
- Validate the key. Note: The current implementation uses a mock validation against a hardcoded key.
- If valid, attach key details to
req.apiKeyand pass control to the next middleware/controller. - If invalid, send an HTTP
401or403error response.
This flowchart illustrates the logic within the validateApiKey middleware.
Error Responses
If validation fails, the middleware returns a structured error object.
| Status Code | Error Code | Message |
|---|---|---|
401 | AUTH_MISSING_HEADER | Authorization header is missing or improperly formatted. |
401 | AUTH_MISSING_KEY | API key is missing from the Authorization header. |
403 | AUTH_INVALID_KEY | The provided API key is not valid. |
Sources: packages/core/src/api/middleware/authMiddleware.ts:30-36, packages/core/src/api/middleware/authMiddleware.ts:42-47, packages/core/src/api/middleware/authMiddleware.ts:74-79
Request Augmentation
Upon successful validation, the validateApiKey middleware augments the Express Request object by attaching an apiKey property. This makes the key's associated project information available to downstream controllers, such as sendMessage.
The Express.Request interface is extended to include this optional property.
// packages/core/src/types/security.ts
declare global {
namespace Express {
export interface Request {
// ...
apiKey?: {
id: string;
projectId: string;
};
}
}
}
Sources: packages/core/src/types/security.ts:17-23
In the middleware, this object is populated with mock data:
// packages/core/src/api/middleware/authMiddleware.ts
req.apiKey = {
id: MOCK_API_KEY_ID,
projectId: MOCK_PROJECT_ID,
};
Sources: packages/core/src/api/middleware/authMiddleware.ts:65-68
User (JWT) Authentication
User authentication is handled via JSON Web Tokens (JWT) and is primarily used for the dashboard API to manage resources like projects and API keys. This system is documented in the API reference and involves user registration and login endpoints.
Sources: API_REFERENCE.md:11-47
Endpoints
| Method | Endpoint | Description |
|---|---|---|
POST | /api/v1/auth/register | Creates a new user account. |
POST | /api/v1/auth/login | Authenticates a user and returns a JWT. |
GET | /api/v1/auth/me | Retrieves the current authenticated user's profile. |
Sources: API_REFERENCE.md:13-50
JWT Payload
When a user logs in, the server issues a JWT containing a specific payload. This payload is decoded by middleware on protected routes to identify the authenticated user.
The JWTPayload interface defines the structure of the data stored in the token.
| Field | Type | Description |
|---|---|---|
userId | string | The unique identifier of the user. |
email | string | The user's email address. |
iat | number | "Issued at" timestamp (seconds since epoch). |
exp | number | "Expiration time" timestamp (seconds since epoch). |
Sources: packages/core/src/types/security.ts:30-49
Summary
MessageJS employs a robust, dual-mechanism authentication strategy. API Key authentication provides a secure, stateless method for client SDKs to send messages, decoupling them from user credentials. Simultaneously, JWT-based user authentication secures the dashboard and management APIs, allowing users to safely manage their projects, connectors, and API keys. This layered approach is fundamental to the platform's security architecture.