@hed-hog/core 0.0.375 → 0.0.377

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,954 +1,954 @@
1
- # @hed-hog/core
2
-
3
- > **License**: MIT (Open Source) — Core is the only Open Source module of the HedHog Framework; the other modules are Enterprise and require a commercial license. See [LICENSE.md](./LICENSE.md).
4
-
5
- Learn more about the HedHog Framework at **[hedhog.com](https://hedhog.com)**.
6
-
7
- ## 1. Module overview
8
-
9
- The `@hed-hog/core` module is the core of the HedHog monorepo, responsible for providing essential core functionality for the system, including authentication, artificial intelligence, dashboard, system information, and management of users, roles, permissions and UI components. It integrates several submodules covering everything from security and authentication to management of customizable dashboards and AI agents.
10
-
11
- ## 2. Scope and responsibilities
12
-
13
- - Authentication and authorization management, including MFA, WebAuthn, password recovery, sessions, and social login via OAuth (Google, Facebook, GitHub, Microsoft, Microsoft Entra ID, Apple, LinkedIn) with a multi-app callback hub.
14
- - Artificial intelligence services for chat and AI agents with support for OpenAI and Gemini.
15
- - Management of dashboards, components, roles, and associated users.
16
- - Operating system, hardware, database, and installed-module information.
17
- - Data validation and handling via DTOs and integration with the Prisma ORM.
18
- - Internationalization and pagination support.
19
-
20
- ## 3. Endpoints
21
-
22
- ### AI Module (`/ai`)
23
-
24
- | Method | Path | Auth | Description | Parameters / Query / Body | Response | Common Errors |
25
- |--------|-------------------------|--------------|-----------------------------------------------------|-------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------------------------|
26
- | POST | `/ai/chat` | Authenticated | Chats with AI, optionally sending a file. | Body: `ChatDTO` (message: string, provider?: 'openai'|'gemini', model?: string, systemPrompt?: string, file_id?: number)<br>File: optional | `{ provider: string, model: string, content: string }` | 400: API key not configured |
27
- | POST | `/ai/agent` | Authenticated | Creates an AI agent. | Body: `CreateAgentDTO` (slug: string, provider?: 'openai'|'gemini', model?: string, instructions?: string) | Created or existing agent object | 400: Slug already exists |
28
- | GET | `/ai/agent` | Authenticated | Lists AI agents with pagination. | Query: pagination (page?: number, pageSize?: number, search?: string) | Paginated list of agents | - |
29
- | GET | `/ai/agent/id/:agentId` | Authenticated | Gets an AI agent by ID. | Path param: `agentId` (int) | Agent object | 404: Agent not found |
30
- | GET | `/ai/agent/:slug` | Authenticated | Gets an AI agent by slug. | Path param: `slug` (string) | Agent object | 404: Agent not found |
31
- | PATCH | `/ai/agent/:agentId` | Authenticated | Updates an AI agent. | Path param: `agentId` (int)<br>Body: `UpdateAgentDTO` (slug?: string, provider?: 'openai'|'gemini', model?: string, instructions?: string) | Updated agent object | 404: Agent not found<br>400: Duplicate slug |
32
- | DELETE | `/ai/agent` | Authenticated | Bulk-deletes AI agents. | Body: `DeleteDTO` (ids: number[]) | `{ count: number }` | 404: One or more agents not found |
33
- | POST | `/ai/agent/:slug/chat` | Authenticated | Chats with a specific AI agent, with an optional file. | Path param: `slug` (string)<br>Body: `ChatAgentDTO` (message: string, file_id?: number)<br>File: optional | `{ slug: string, provider: string, model: string, content: string }` | 404: Agent not found |
34
-
35
- ### Auth Module (`/auth`)
36
-
37
- | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
38
- |--------|-------------------------------------|--------------|-----------------------------------------------------|--------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------------------------|
39
- | GET | `/auth/verify` | Authenticated | Verifies the authenticated user. | - | Authenticated user data | - |
40
- | GET | `/auth/roles` | Public | Returns the user's roles (if authenticated). | - | `{ roles: string[] }` | - |
41
- | POST | `/auth/refresh` | Public | Refreshes the access token using the refresh token. | Body: `{ refreshToken?: string }`<br>Cookies: `rt` optional | `{ accessToken: string, refreshToken?: string }` | 400: Refresh token not provided |
42
- | POST | `/auth/login` | Public | Login with email and password. | Body: `LoginDTO` (email: string, password: string, refreshToken?: boolean) | Access and refresh tokens, or MFA required | 400: Access denied |
43
- | POST | `/auth/login-email-verification` | Public | Login via email verification and code. | Body: `LoginEmailVerificationDTO` (token: string, code: string) | Access and refresh tokens | 400: Invalid code or challenge not found |
44
- | POST | `/auth/login-email-verification-resend` | Public | Resends the email verification code. | Body: `LoginEmailVerificationResendDTO` (token: string) | New token for verification | 400: Invalid or expired token |
45
- | POST | `/auth/signup` | Public | Sign-up with email and password. | Body: `CreateWithEmailAndPasswordDTO` | User created | - |
46
- | POST | `/auth/login-code` | Public | Login with an MFA code. | Body: `LoginWithCodeDTO` (token: string, code: string, methodType?: 'totp'|'email'|'recovery') | Access and refresh tokens | 400: Invalid MFA code |
47
- | POST | `/auth/login-recovery-code` | Public | Login with an MFA recovery code. | Body: `LoginWithRecoveryCodeDTO` (token: string, code: string) | Access and refresh tokens | 400: Invalid recovery code|
48
- | POST | `/auth/resend-mfa-code` | Public | Resends the MFA code by email. | Body: `ResendMfaCodeDTO` (token: string) | `{ success: true, hasEmailMfa: true }` | 400: No email MFA method configured |
49
- | POST | `/auth/webauthn/generate` | Public | Generates options for WebAuthn authentication. | Body: `{ mfaToken: string }` | WebAuthn options | 400: WebAuthn not configured |
50
- | POST | `/auth/webauthn/verify` | Public | Verifies WebAuthn authentication. | Body: `{ mfaToken: string, assertionResponse: any }` | Access and refresh tokens | 400: Verification failed |
51
- | POST | `/auth/forgot` | Public | Requests password recovery via email. | Body: `ForgetDTO` (email: string) | `{ success: true }` | - |
52
- | POST | `/auth/logout` | Public | Logs out and invalidates the refresh token. | Body: `{ refreshToken?: string }`<br>Cookies: `rt` optional | `{ success: true }` | 400: Refresh token not provided |
53
- | POST | `/auth/forgot-reset` | Public | Resets the password using a recovery code. | Body: `ResetDTO` (password: string, code: string) | Access and refresh tokens | 400: Invalid or expired code |
54
-
55
- ### OAuth Module (`/oauth`)
56
-
57
- > **Multi-app hub pattern**: each provider only needs **one registered callback URL** (`${url}/callback/:provider`, with no flow suffix — GitHub uses `${api-url}/oauth/github/callback`, and Apple uses `${api-url}/oauth/apple/callback`, both because they only accept a single callback URL). The flow (`login`/`register`/`connect`) and the app that started the authentication (e.g. `training`) travel signed in the `state` parameter (`hhweb.<app>.<flow>.<signature>`, HMAC via `SecurityService`), never in the path. The app configured in the `url` setting acts as the **hub**: when it receives the callback from the provider, it either handles the flow locally or forwards the browser to the callback page of the app that started the flow, resolving the origin via the `app-urls` setting. Supported providers: Google, Facebook, GitHub, Microsoft, Microsoft Entra ID, Apple (Sign in with Apple), and LinkedIn.
58
-
59
- | Method | Path | Auth | Description | Parameters / Query / Body | Response | Common Errors |
60
- |--------|----------------------------------|--------------|--------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|------------------------------------------------------------------------|----------------------------------------------------------------------|
61
- | GET | `/oauth/github/callback` | Public | Exclusive GitHub bounce (the only callback URL accepted by the provider); forwards the `code` to the correct frontend. | Query: `code`, `state?` | 302 redirect to `${origin}/callback/github/<flow>?code=...&state=...` | - |
62
- | POST | `/oauth/apple/callback` | Public | Exclusive Apple bounce: Apple requires `response_mode=form_post` when `scope` is requested, so it POSTs `code`/`state` instead of a GET redirect. This is converted back to a GET redirect, the same as the GitHub bounce. | Body: `code`, `state?` | 302 redirect to `${origin}/callback/apple/<flow>?code=...&state=...` | - |
63
- | GET | `/oauth/:provider/login` | Public | Starts the login flow, redirecting to the provider's authorization screen. | Path: `provider`<br>Query: `redirectApp?` (key in the initiating app's `app-urls`) | 302 redirect to the provider's authorization URL | 400: provider not enabled or not supported |
64
- | GET | `/oauth/:provider/register` | Public | Starts the sign-up flow via OAuth. | Path: `provider`<br>Query: `redirectApp?` | 302 redirect to the provider's authorization URL | 400: provider not enabled or not supported |
65
- | GET | `/oauth/:provider/connect` | Public | Starts the flow to link an account to a user already authenticated in the target app. | Path: `provider`<br>Query: `redirectApp?` | 302 redirect to the provider's authorization URL | 400: provider not enabled or not supported |
66
- | GET | `/oauth/:provider/mobile/auth-url` | Public | Returns the authorization URL for native apps (Electron/React Native) to intercept the redirect. | Path: `provider`<br>Query: `redirectUri` (native app's custom scheme) | `{ authUrl: string }` | 400: invalid redirect URI or provider not enabled |
67
- | GET | `/oauth/:provider/callback/login` | Public | Exchanges the `code` for access tokens after the hub forwards to the app's login page. | Path: `provider`<br>Query: `code`, `state?`, `redirectUri?` | `{ accessToken: string, refreshToken?: string }` + `rt` cookie (httpOnly) | 400: missing code, invalid origin, or callback already processed<br>409: callback being processed<br>503: provider failure |
68
- | GET | `/oauth/:provider/callback/register` | Public | Exchanges the `code` for tokens after signing up via OAuth. | Path: `provider`<br>Query: `code` | `{ accessToken: string, refreshToken?: string }` + `rt` cookie | 400/409/503 — same cases as the login callback |
69
- | GET | `/oauth/:provider/callback/connect` | Authenticated | Links the provider account to the authenticated user. | Path: `provider`<br>Query: `code` | `{ accessToken: string, refreshToken?: string }` + `rt` cookie | 400/409/503 — same cases as the login callback |
70
- | DELETE | `/oauth/:provider` | Authenticated | Unlinks the provider account from the user. | Path: `provider`<br>Body: `{ email: string }` | Disconnection result | - |
71
-
72
- ### System Module (`/system`)
73
-
74
- | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
75
- |--------|------------|--------------|---------------------------------|-------------------|--------------------------------------------------------------------------------------------|--------------|
76
- | GET | `/system` | Authenticated | Returns system information. | - | Detailed information about the operating system, hardware, database, modules, and users | - |
77
-
78
- ### Dashboard Core Module (`/dashboard-core`)
79
-
80
- | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
81
- |--------|---------------------------|--------------|-----------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------------------------|
82
- | GET | `/dashboard-core/home` | Authenticated | Returns the user's home dashboard. | - | Dashboard object or null | 400: User not found |
83
- | GET | `/dashboard-core/stats/overview/users` | Authenticated | User statistics. | - | Aggregated user and session statistics | - |
84
- | GET | `/dashboard-core/stats/overview/mails` | Authenticated | Sent-email statistics. | - | Aggregated statistics on sent emails | - |
85
- | GET | `/dashboard-core/stats/overview/system` | Authenticated | System statistics (menus and routes). | - | Aggregated system statistics | - |
86
- | GET | `/dashboard-core/config/overview` | Authenticated | Overview of the system settings. | - | Object with configuration | - |
87
- | GET | `/dashboard-core/widgets/me` | Authenticated | Widget data for the user. | - | Aggregated data for the user's widgets | - |
88
- | GET | `/dashboard-core/user-dashboards` | Authenticated | Lists the user's dashboards. | - | List of dashboards associated with the user | - |
89
- | GET | `/dashboard-core/templates` | Authenticated | Lists templates available for dashboards. | - | List of templates | - |
90
- | POST | `/dashboard-core/dashboard` | Authenticated | Creates a dashboard for the user. | Body: `{ name?: string; slug?: string; icon?: string | null; templateSlug?: string }` | Created dashboard | - |
91
- | PATCH | `/dashboard-core/dashboard/order` | Authenticated | Reorders the user's dashboards. | Body: `{ slugs?: string[] }` | Reordered dashboard | - |
92
- | PATCH | `/dashboard-core/dashboard/:slug` | Authenticated | Renames the user's dashboard. | Path param: `slug` (string)<br>Body: `{ name?: string; icon?: string | null }` | Updated dashboard | - |
93
- | POST | `/dashboard-core/dashboard/:slug/home` | Authenticated | Sets the dashboard as the user's home dashboard. | Path param: `slug` (string) | Success | - |
94
- | GET | `/dashboard-core/dashboard/:slug/shares` | Authenticated | Lists the dashboard's shares. | Path param: `slug` (string) | List of users with access | - |
95
- | GET | `/dashboard-core/shareable-users/:slug` | Authenticated | Lists users the dashboard can be shared with. | Path param: `slug` (string)<br>Query: search?: string, page?: string, pageSize?: string | Paginated list of users | - |
96
- | POST | `/dashboard-core/dashboard/:slug/share` | Authenticated | Shares the dashboard with users. | Path param: `slug` (string)<br>Body: `{ userId?: number; userIds?: number[] }` | Success | - |
97
- | DELETE | `/dashboard-core/dashboard/:slug/share/:sharedUserId` | Authenticated | Revokes a dashboard share. | Path params: `slug` (string), `sharedUserId` (int) | Success | - |
98
- | DELETE | `/dashboard-core/dashboard/:slug` | Authenticated | Removes the dashboard from the user. | Path param: `slug` (string) | Success | - |
99
- | GET | `/dashboard-core/access/:slug` | Authenticated | Checks the user's access to the dashboard. | Path param: `slug` (string) | `{ hasAccess: boolean, dashboard: object|null }` | - |
100
- | GET | `/dashboard-core/layout/:slug` | Authenticated | Gets the user's layout for the dashboard. | Path param: `slug` (string) | Array of widgets with positions and sizes | - |
101
- | POST | `/dashboard-core/layout/:slug` | Authenticated | Saves the user's layout for the dashboard. | Body: `{ layout: Array<{ i: string; x: number; y: number; w: number; h: number }> }` | `{ success: true }` | 403: Access denied |
102
- | POST | `/dashboard-core/widget/:slug` | Authenticated | Adds a widget to the user's dashboard. | Body: `{ componentSlug: string }` | Data for the added widget | 403: Access denied |
103
- | DELETE | `/dashboard-core/widget/:slug/:widgetId` | Authenticated | Removes a widget from the user's dashboard. | Path params: `slug` (string), `widgetId` (string) | "Not implemented yet" error | - |
104
- | GET | `/dashboard-core/:slug` | Authenticated | Gets dashboard items by slug. | Path param: `slug` (string), Query param: `locale?: string` | List of dashboard items | - |
105
-
106
- ### Dashboard Module (`/dashboard`)
107
-
108
- | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
109
- |--------|----------------|--------------|------------------------------------|---------------------------------------------------------|------------------------------|----------------------------|
110
- | GET | `/dashboard` | Authenticated | Lists dashboards with pagination | Query: pagination (page?: number, pageSize?: number, search?: string) | Paginated list of dashboards | - |
111
- | GET | `/dashboard/:id` | Authenticated | Gets a dashboard by ID | Path param: `id` (int) | Dashboard object | 404: Dashboard not found |
112
- | POST | `/dashboard` | Authenticated | Creates a dashboard | Body: `CreateDashboardDTO` (slug: string, locale: Record<string, { name: string }>) | Created dashboard | - |
113
- | PATCH | `/dashboard/:id` | Authenticated | Updates a dashboard | Path param: `id` (int), Body: `UpdateDashboardDTO` | Updated dashboard | 404: Dashboard not found |
114
- | DELETE | `/dashboard/:id` | Authenticated | Deletes a dashboard | Path param: `id` (int) | `{ success: true }` | 404: Dashboard not found |
115
-
116
- ### Dashboard Component Module (`/dashboard-component`)
117
-
118
- | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
119
- |--------|------------------------|--------------|------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
120
- | GET | `/dashboard-component` | Authenticated | Lists components with pagination | Query: pagination (page?: number, pageSize?: number, search?: string) | Paginated list of components | - |
121
- | GET | `/dashboard-component/user` | Authenticated | Lists components by the user's roles | Query: pagination (page?: number, pageSize?: number, search?: string), User ID via token | Paginated list of components | - |
122
- | GET | `/dashboard-component/:id` | Authenticated | Gets a component by ID | Path param: `id` (int) | Component object | 404: Component not found |
123
- | POST | `/dashboard-component` | Authenticated | Creates a component | Body: `CreateDashboardComponentDTO` | Created component | - |
124
- | PATCH | `/dashboard-component/:id` | Authenticated | Updates a component | Path param: `id` (int), Body: `UpdateDashboardComponentDTO` | Updated component | 404: Component not found |
125
- | DELETE | `/dashboard-component/:id` | Authenticated | Deletes a component | Path param: `id` (int) | `{ success: true }` | 404: Component not found |
126
- | POST | `/dashboard-component/:id/preview` | Authenticated | Saves a component preview (image) | Path param: `id` (int), File: image (image/*) | `{ success: true, componentId: number, slug: string, library_slug: string, fileName: string, relativeUrl: string }` | 400: Invalid file<br>403: Dev environment only |
127
-
128
- ### Dashboard Component Role Module (`/dashboard-component-role`)
129
-
130
- | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
131
- |--------|-------------------------------|--------------|---------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
132
- | GET | `/dashboard-component-role` | Authenticated | Lists relations with pagination or by component | Query: pagination (page?: number, pageSize?: number), Query param: componentId?: number | Paginated or list of relations | - |
133
- | POST | `/dashboard-component-role` | Authenticated | Creates a component-role relation | Body: `CreateDashboardComponentRoleDTO` | Created relation | Error if the relation already exists |
134
- | POST | `/dashboard-component-role/batch` | Authenticated | Bulk-creates relations | Body: `CreateDashboardComponentRoleBatchDTO` | { success: boolean, created: number, skipped: number, message: string } | - |
135
- | DELETE | `/dashboard-component-role/:id` | Authenticated | Deletes a relation by ID | Path param: `id` (int) | `{ success: true }` | 404: Relation not found |
136
- | DELETE | `/dashboard-component-role/component/:componentId/role/:roleId` | Authenticated | Deletes a relation by component and role | Path params: `componentId` (int), `roleId` (int) | `{ success: true }` | 404: Relation not found |
137
-
138
- ### Dashboard Item Module (`/dashboard-item`)
139
-
140
- | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
141
- |--------|--------------------|--------------|------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
142
- | GET | `/dashboard-item` | Authenticated | Lists items with pagination and filter by dashboard | Query: pagination (page?: number, pageSize?: number), Query param: dashboardId?: number | Paginated list of items | - |
143
- | POST | `/dashboard-item` | Authenticated | Creates an item | Body: `CreateDashboardItemDTO` | Created item | - |
144
- | DELETE | `/dashboard-item/:id` | Authenticated | Deletes an item by ID | Path param: `id` (int) | `{ success: true }` | 404: Item not found |
145
-
146
- ### Dashboard Role Module (`/dashboard-role`)
147
-
148
- | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
149
- |--------|--------------------|--------------|---------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
150
- | GET | `/dashboard-role` | Authenticated | Lists relations with pagination or by dashboard | Query: pagination (page?: number, pageSize?: number), Query param: dashboardId?: number | Paginated or list of relations | - |
151
- | POST | `/dashboard-role` | Authenticated | Creates a dashboard-role relation | Body: `CreateDashboardRoleDTO` | Created relation | Error if the relation already exists |
152
- | POST | `/dashboard-role/batch` | Authenticated | Bulk-creates relations | Body: `CreateDashboardRoleBatchDTO` | { success: boolean, created: number, skipped: number, message: string } | - |
153
- | DELETE | `/dashboard-role/:id` | Authenticated | Deletes a relation by ID | Path param: `id` (int) | `{ success: true }` | 404: Relation not found |
154
- | DELETE | `/dashboard-role/dashboard/:dashboardId/role/:roleId` | Authenticated | Deletes a relation by dashboard and role | Path params: `dashboardId` (int), `roleId` (int) | `{ success: true }` | 404: Relation not found |
155
-
156
- ### Dashboard User Module (`/dashboard-user`)
157
-
158
- | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
159
- |--------|--------------------|--------------|------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
160
- | GET | `/dashboard-user` | Authenticated | Lists relations with pagination | Query: pagination (page?: number, pageSize?: number) | Paginated list of relations | - |
161
- | GET | `/dashboard-user/:id` | Authenticated | Gets a relation by ID | Path param: `id` (int) | Relation object | - |
162
- | POST | `/dashboard-user` | Authenticated | Creates a relation | Body: `CreateDTO` (dashboard_id: number, user_id: number) | Created relation | - |
163
- | PATCH | `/dashboard-user/:id` | Authenticated | Updates a relation | Path param: `id` (int), Body: `UpdateDTO` | Updated relation | - |
164
- | DELETE | `/dashboard-user` | Authenticated | Bulk-deletes relations | Body: `DeleteDTO` (ids: number[]) | `{ count: number }` | 400: No id provided |
165
-
166
- ## 4. Authentication and authorization rules
167
-
168
- - Most endpoints require authentication via a JWT token.
169
- - Public endpoints are explicitly marked.
170
- - Access control is based on roles and permissions.
171
- - MFA (Multi-Factor Authentication) is supported via TOTP, email, and recovery codes.
172
- - WebAuthn is supported for strong authentication.
173
- - Refresh tokens are managed via HTTP-only cookies or in the request body.
174
- - Sensitive operations (create, update, delete) require authentication and the appropriate permissions.
175
-
176
- ## 5. Request/response structures
177
-
178
- ### Main DTOs of the AI module
179
-
180
- - **ChatDTO**
181
-
182
- ```ts
183
- {
184
- message: string; // required
185
- provider?: 'openai' | 'gemini'; // optional, default 'openai'
186
- model?: string; // optional
187
- systemPrompt?: string; // optional
188
- file_id?: number; // optional
189
- }
190
- ```
191
-
192
- - **ChatAgentDTO**
193
-
194
- ```ts
195
- {
196
- message: string; // required
197
- file_id?: number; // optional
198
- }
199
- ```
200
-
201
- - **CreateAgentDTO**
202
-
203
- ```ts
204
- {
205
- slug: string; // required
206
- provider?: 'openai' | 'gemini'; // optional, default 'openai'
207
- model?: string; // optional
208
- instructions?: string; // optional
209
- }
210
- ```
211
-
212
- - **UpdateAgentDTO**
213
-
214
- ```ts
215
- {
216
- slug?: string;
217
- provider?: 'openai' | 'gemini';
218
- model?: string;
219
- instructions?: string;
220
- }
221
- ```
222
-
223
- - **DeleteDTO**
224
-
225
- ```ts
226
- {
227
- ids: number[]; // array of IDs to delete, minimum 1 item
228
- }
229
- ```
230
-
231
- ### Main DTOs of the Auth module
232
-
233
- - **LoginDTO**
234
-
235
- ```ts
236
- {
237
- email: string; // required, valid email
238
- password: string; // required, strong password, minimum 6 characters
239
- refreshToken?: boolean; // optional, default false
240
- }
241
- ```
242
-
243
- - **LoginEmailVerificationDTO**
244
-
245
- ```ts
246
- {
247
- token: string; // required
248
- code: string; // required, PIN code
249
- }
250
- ```
251
-
252
- - **LoginEmailVerificationResendDTO**
253
-
254
- ```ts
255
- {
256
- token: string; // required
257
- }
258
- ```
259
-
260
- - **LoginWithCodeDTO**
261
-
262
- ```ts
263
- {
264
- code: string; // required
265
- token: string; // required, JWT
266
- methodType?: 'totp' | 'email' | 'recovery'; // optional
267
- }
268
- ```
269
-
270
- - **LoginWithRecoveryCodeDTO**
271
-
272
- ```ts
273
- {
274
- code: string; // required
275
- token: string; // required, JWT
276
- }
277
- ```
278
-
279
- - **ForgetDTO**
280
-
281
- ```ts
282
- {
283
- email: string; // required, valid email
284
- }
285
- ```
286
-
287
- - **ResetDTO**
288
-
289
- ```ts
290
- {
291
- password: string; // required, minimum 8 characters
292
- code: string; // required
293
- }
294
- ```
295
-
296
- ### Main DTOs of the Dashboard module
297
-
298
- - **CreateDashboardDTO**
299
-
300
- ```ts
301
- {
302
- slug: string; // required
303
- locale: Record<string, { name: string }>; // required
304
- }
305
- ```
306
-
307
- - **UpdateDashboardDTO**
308
-
309
- ```ts
310
- {
311
- slug?: string;
312
- locale?: Record<string, { name: string }>;
313
- }
314
- ```
315
-
316
- - **CreateDashboardComponentDTO**
317
-
318
- ```ts
319
- {
320
- slug: string;
321
- library_slug?: string;
322
- min_width?: number;
323
- max_width?: number;
324
- min_height?: number;
325
- max_height?: number;
326
- width: number;
327
- height: number;
328
- is_resizable?: boolean;
329
- locale: Record<string, { name: string; description?: string }>;
330
- }
331
- ```
332
-
333
- - **UpdateDashboardComponentDTO**
334
-
335
- ```ts
336
- {
337
- slug?: string;
338
- library_slug?: string;
339
- min_width?: number;
340
- max_width?: number;
341
- min_height?: number;
342
- max_height?: number;
343
- width?: number;
344
- height?: number;
345
- is_resizable?: boolean;
346
- locale?: Record<string, { name: string; description?: string }>;
347
- }
348
- ```
349
-
350
- - **CreateDashboardRoleDTO**
351
-
352
- ```ts
353
- {
354
- dashboard_id: number;
355
- role_id: number;
356
- }
357
- ```
358
-
359
- - **CreateDashboardRoleBatchDTO**
360
-
361
- ```ts
362
- {
363
- dashboard_id: number;
364
- role_ids: number[];
365
- }
366
- ```
367
-
368
- - **CreateDashboardComponentRoleDTO**
369
-
370
- ```ts
371
- {
372
- component_id: number;
373
- role_id: number;
374
- }
375
- ```
376
-
377
- - **CreateDashboardComponentRoleBatchDTO**
378
-
379
- ```ts
380
- {
381
- component_id: number;
382
- role_ids: number[];
383
- }
384
- ```
385
-
386
- - **CreateDashboardItemDTO**
387
-
388
- ```ts
389
- {
390
- component_id: number;
391
- dashboard_id: number;
392
- width: number;
393
- height: number;
394
- x_axis: number;
395
- y_axis: number;
396
- }
397
- ```
398
-
399
- - **UpdateDashboardLayoutDTO**
400
-
401
- ```ts
402
- {
403
- dashboard_id: number;
404
- items: Array<{
405
- id: number;
406
- width: number;
407
- height: number;
408
- x_axis: number;
409
- y_axis: number;
410
- }>;
411
- }
412
- ```
413
-
414
- - **UpdateDashboardItemDTO**
415
-
416
- ```ts
417
- {
418
- component_id?: number;
419
- dashboard_id?: number;
420
- width?: number;
421
- height?: number;
422
- x_axis?: number;
423
- y_axis?: number;
424
- }
425
- ```
426
-
427
- - **CreateDTO (DashboardUser)**
428
-
429
- ```ts
430
- {
431
- dashboard_id: number;
432
- user_id: number;
433
- }
434
- ```
435
-
436
- - **UpdateDTO (DashboardUser)**
437
-
438
- ```ts
439
- {
440
- dashboard_id?: number;
441
- user_id?: number;
442
- }
443
- ```
444
-
445
- - **DeleteDTO**
446
-
447
- ```ts
448
- {
449
- ids: number[];
450
- }
451
- ```
452
-
453
- ## 6. Common errors
454
-
455
- - **400 Bad Request**
456
-
457
- - API key not configured for OpenAI or Gemini.
458
- - AI agent slug already exists.
459
- - Invalid or expired verification code.
460
- - Refresh token not provided.
461
- - Access denied due to invalid credentials.
462
- - MFA not configured or invalid code.
463
- - Attempt to delete non-existent items.
464
- - Invalid request to create duplicate relations.
465
- - Invalid file for component preview.
466
- - Preview operation available only in the development environment.
467
- - OAuth: provider not enabled (`oauth-<provider>-enabled` off) or not supported.
468
- - OAuth: integration profile not configured (`oauth-<provider>-profile-id` empty) or not found.
469
- - OAuth: missing authorization code, invalid mobile redirect URI, invalid callback origin (hub origin binding), or callback already processed.
470
-
471
- - **404 Not Found**
472
-
473
- - AI agent not found by ID or slug.
474
- - Dashboard, component, or relation not found.
475
- - Verification challenge not found or expired.
476
-
477
- - **403 Forbidden**
478
-
479
- - Access denied to dashboards or protected resources.
480
- - Attempt to save a preview outside the development environment.
481
-
482
- - **409 Conflict**
483
-
484
- - OAuth: callback already being processed (idempotency lock by code).
485
-
486
- - **503 Service Unavailable**
487
-
488
- - OAuth: failure communicating with the provider (upstream).
489
-
490
- ## 7. Database (YAML tables)
491
-
492
- ### ai_agent
493
-
494
- ```yaml
495
- purpose: Stores AI agents configured in the system.
496
- columns:
497
- - id: integer, PK, auto-increment
498
- - slug: string, unique, not null
499
- - provider: enum('openai', 'gemini'), not null
500
- - model: string, nullable
501
- - instructions: string, nullable
502
- - external_agent_id: string, nullable
503
- - created_at: timestamp, not null, default NOW()
504
- - updated_at: timestamp, not null, default NOW()
505
- defaults:
506
- - created_at: NOW()
507
- - updated_at: NOW()
508
- nullability:
509
- - model: nullable
510
- - instructions: nullable
511
- - external_agent_id: nullable
512
- integrity:
513
- - unique slug
514
- indexes:
515
- - id (PK)
516
- - slug (unique)
517
- enums:
518
- - provider: ['openai', 'gemini']
519
- ```
520
-
521
- ### user
522
-
523
- ```yaml
524
- purpose: Stores the system's users.
525
- columns:
526
- - id: integer, PK, auto-increment
527
- - name: string, not null
528
- - photo_id: integer, nullable
529
- - last_login_at: timestamp, nullable
530
- - created_at: timestamp, not null, default NOW()
531
- - updated_at: timestamp, not null, default NOW()
532
- integrity:
533
- - PK on id
534
- indexes:
535
- - id (PK)
536
- ```
537
-
538
- ### user_mfa
539
-
540
- ```yaml
541
- purpose: Stores users' multi-factor authentication methods.
542
- columns:
543
- - id: integer, PK, auto-increment
544
- - user_id: integer, FK to user.id, not null
545
- - name: string, not null
546
- - type: enum('totp', 'email', 'webauthn'), not null
547
- - verified_at: timestamp, nullable
548
- - suspended_until: timestamp, nullable
549
- - created_at: timestamp, not null, default NOW()
550
- - updated_at: timestamp, not null, default NOW()
551
- integrity:
552
- - FK user_id references user.id
553
- indexes:
554
- - id (PK)
555
- enums:
556
- - type: ['totp', 'email', 'webauthn']
557
- ```
558
-
559
- ### user_identifier
560
-
561
- ```yaml
562
- purpose: User identifiers, such as emails.
563
- columns:
564
- - id: integer, PK, auto-increment
565
- - user_id: integer, FK to user.id, not null
566
- - type: string, not null (e.g.: 'email')
567
- - value: string, not null
568
- - verified_at: timestamp, nullable
569
- - enabled: boolean, not null, default true
570
- - created_at: timestamp, not null, default NOW()
571
- - updated_at: timestamp, not null, default NOW()
572
- integrity:
573
- - FK user_id references user.id
574
- indexes:
575
- - id (PK)
576
- ```
577
-
578
- ### user_session
579
-
580
- ```yaml
581
- purpose: Sessions of authenticated users.
582
- columns:
583
- - id: integer, PK, auto-increment
584
- - user_id: integer, FK to user.id, not null
585
- - token: string, not null
586
- - ip_address: string, nullable
587
- - user_agent: string, nullable
588
- - created_at: timestamp, not null, default NOW()
589
- - expires_at: timestamp, not null
590
- - revoked_at: timestamp, nullable
591
- integrity:
592
- - FK user_id references user.id
593
- indexes:
594
- - id (PK)
595
- ```
596
-
597
- ### user_activity
598
-
599
- ```yaml
600
- purpose: Log of user activities.
601
- columns:
602
- - id: integer, PK, auto-increment
603
- - user_id: integer, FK to user.id, not null
604
- - action: string, not null
605
- - created_at: timestamp, not null, default NOW()
606
- integrity:
607
- - FK user_id references user.id
608
- indexes:
609
- - id (PK)
610
- ```
611
-
612
- ### role
613
-
614
- ```yaml
615
- purpose: System roles for access control.
616
- columns:
617
- - id: integer, PK, auto-increment
618
- - slug: string, unique, not null
619
- - created_at: timestamp, not null, default NOW()
620
- - updated_at: timestamp, not null, default NOW()
621
- integrity:
622
- - unique slug
623
- indexes:
624
- - id (PK)
625
- - slug (unique)
626
- ```
627
-
628
- ### role_user
629
-
630
- ```yaml
631
- purpose: Many-to-many relation between users and roles.
632
- columns:
633
- - id: integer, PK, auto-increment
634
- - user_id: integer, FK to user.id, not null
635
- - role_id: integer, FK to role.id, not null
636
- integrity:
637
- - FK user_id references user.id
638
- - FK role_id references role.id
639
- indexes:
640
- - id (PK)
641
- ```
642
-
643
- ### dashboard
644
-
645
- ```yaml
646
- purpose: The system's configurable dashboards.
647
- columns:
648
- - id: integer, PK, auto-increment
649
- - slug: string, unique, not null
650
- - created_at: timestamp, not null, default NOW()
651
- - updated_at: timestamp, not null, default NOW()
652
- integrity:
653
- - unique slug
654
- indexes:
655
- - id (PK)
656
- - slug (unique)
657
- ```
658
-
659
- ### dashboard_component
660
-
661
- ```yaml
662
- purpose: Components that can be used in dashboards.
663
- columns:
664
- - id: integer, PK, auto-increment
665
- - slug: string, unique, not null
666
- - library_slug: string, nullable
667
- - min_width: integer, nullable
668
- - max_width: integer, nullable
669
- - min_height: integer, nullable
670
- - max_height: integer, nullable
671
- - width: integer, not null
672
- - height: integer, not null
673
- - is_resizable: boolean, not null, default true
674
- - created_at: timestamp, not null, default NOW()
675
- - updated_at: timestamp, not null, default NOW()
676
- integrity:
677
- - unique slug
678
- indexes:
679
- - id (PK)
680
- - slug (unique)
681
- ```
682
-
683
- ### dashboard_role
684
-
685
- ```yaml
686
- purpose: Relation between dashboards and roles for access control.
687
- columns:
688
- - id: integer, PK, auto-increment
689
- - dashboard_id: integer, FK to dashboard.id, not null
690
- - role_id: integer, FK to role.id, not null
691
- integrity:
692
- - FK dashboard_id references dashboard.id
693
- - FK role_id references role.id
694
- indexes:
695
- - id (PK)
696
- ```
697
-
698
- ### dashboard_user
699
-
700
- ```yaml
701
- purpose: Relation between dashboards and users.
702
- columns:
703
- - id: integer, PK, auto-increment
704
- - dashboard_id: integer, FK to dashboard.id, not null
705
- - user_id: integer, FK to user.id, not null
706
- - is_home: boolean, not null, default false
707
- integrity:
708
- - FK dashboard_id references dashboard.id
709
- - FK user_id references user.id
710
- indexes:
711
- - id (PK)
712
- ```
713
-
714
- ### dashboard_item
715
-
716
- ```yaml
717
- purpose: Items (widgets) within dashboards.
718
- columns:
719
- - id: integer, PK, auto-increment
720
- - dashboard_id: integer, FK to dashboard.id, not null
721
- - component_id: integer, FK to dashboard_component.id, not null
722
- - width: integer, not null
723
- - height: integer, not null
724
- - x_axis: integer, not null
725
- - y_axis: integer, not null
726
- integrity:
727
- - FK dashboard_id references dashboard.id
728
- - FK component_id references dashboard_component.id
729
- indexes:
730
- - id (PK)
731
- ```
732
-
733
- ### dashboard_component_role
734
-
735
- ```yaml
736
- purpose: Relation between dashboard components and roles.
737
- columns:
738
- - id: integer, PK, auto-increment
739
- - component_id: integer, FK to dashboard_component.id, not null
740
- - role_id: integer, FK to role.id, not null
741
- integrity:
742
- - FK component_id references dashboard_component.id
743
- - FK role_id references role.id
744
- indexes:
745
- - id (PK)
746
- ```
747
-
748
- ### oauth_mobile_state_token
749
-
750
- ```yaml
751
- purpose: Single-use signed state for the OAuth flow started by native apps (mobile/desktop), binding the app's redirect URI to the provider and the flow.
752
- columns:
753
- - id: bigint, PK, auto-increment
754
- - token_hash: string, unique, not null
755
- - provider: string, not null
756
- - redirect_uri: string, not null (native app's custom scheme)
757
- - flow_type: string, not null ('login' | 'register' | 'connect')
758
- - expires_at: timestamptz, not null
759
- - consumed_at: timestamptz, nullable (marks single use)
760
- - created_at: timestamptz, not null, default NOW()
761
- integrity:
762
- - unique token_hash
763
- indexes:
764
- - id (PK)
765
- - expires_at
766
- - (provider, redirect_uri)
767
- ```
768
-
769
- > Used only by the mobile flow (`GET /oauth/:provider/mobile/auth-url`). The multi-app web hub (signed `state`, `hhweb.<app>.<flow>.<sig>`) is stateless — the HMAC signature is verified without database persistence.
770
-
771
- ## 8. Relevant business rules
772
-
773
- - AI agents can be created, updated, and deleted, with direct integration with the OpenAI and Gemini APIs.
774
- - AI chat supports file attachments, with text extraction for PDFs and text files.
775
- - Mandatory MFA can be configured, with support for email, TOTP, and WebAuthn.
776
- - Access and refresh tokens are managed securely, including HTTP-only cookies.
777
- - Dashboards are personalized per user, with role-based access control.
778
- - Dashboard and widget layouts can be saved and retrieved per user.
779
- - The system collects usage statistics, sessions, sent emails, and account security data.
780
- - Strict validations are applied via DTOs and validation classes.
781
- - Batch create operations avoid duplication and return counts of created and skipped items.
782
- - Removing widgets from a user's dashboard is not yet implemented.
783
- - Dashboard component previews are allowed only in the development environment and accept images only.
784
- - Email MFA sends codes to all email addresses associated with the user.
785
- - WebAuthn is supported for strong authentication with challenge generation and verification.
786
- - **OAuth — one callback URL per provider**: the flow (login/register/connect) and the initiating app travel signed in the `state`, never in the path; each provider is enabled/disabled individually via the `oauth-<provider>-enabled` setting, without removing the configured credentials (`oauth-<provider>-profile-id`, pointing to an `integration_profile`).
787
- - **OAuth — multi-app hub**: the app in the `url` setting (e.g. admin) receives the callback from the provider and, if the `state` indicates a different initiating app, forwards the browser to that app's corresponding callback page, resolving the origin via `app-urls`. Exchanging the `code` for tokens is only accepted when the request's `Origin`/`Referer` header matches the origin signed in the `state` (origin binding), preventing code interception between apps.
788
- - **OAuth — email auto-linking**: on login, if no `user_account` exists for the provider but an enabled email `user_identifier` matching the OAuth profile's email already exists, the flow becomes an automatic connection (`connect`) to the existing account instead of creating a new user; a new account (`register`) is only created when no user matches the email.
789
- - **OAuth — roles on sign-up**: new users registered via OAuth receive the roles configured in the `oauth-role-assignment` setting.
790
- - **OAuth — mobile**: native apps use `/oauth/:provider/mobile/auth-url` with a signed state persisted in `oauth_mobile_state_token` (10-minute TTL, single use).
791
- - **OAuth — Apple (Sign in with Apple)**: no static `client_secret` — the `private_key` (EC `.p8` key) signs a `client_secret` JWT (ES256, `iss`=team ID, `sub`=Services ID, `kid`=key ID, short TTL) on each code exchange. Since scopes require `response_mode=form_post`, the callback is `POST /oauth/apple/callback` (a single URL, on the backend), converted to the same GET redirect used by the other providers. Identity comes from the `id_token` (decoded JWT, without signature verification — delivered directly by Apple in the server-to-server exchange); the name is only sent by Apple on the first authorization and is not captured, so the user's name falls back to the local part of the email.
792
- - **OAuth — LinkedIn**: uses "Sign In with LinkedIn using OpenID Connect" (`scope=openid profile email`), with identity obtained in a single call to `GET /v2/userinfo` (standard OIDC claims), without the legacy pair of calls `/v2/me` + `/v2/emailAddress`.
793
-
794
- ## 9. Quick usage guide (examples)
795
-
796
- ### Create an AI agent
797
-
798
- ```http
799
- POST /ai/agent
800
- Authorization: Bearer <token>
801
- Content-Type: application/json
802
-
803
- {
804
- "slug": "my-agent",
805
- "provider": "openai",
806
- "model": "gpt-4o-mini",
807
- "instructions": "Be a friendly assistant."
808
- }
809
- ```
810
-
811
- Response:
812
-
813
- ```json
814
- {
815
- "id": 1,
816
- "slug": "my-agent",
817
- "provider": "openai",
818
- "model": "gpt-4o-mini",
819
- "instructions": "Be a friendly assistant.",
820
- "external_agent_id": "abc123",
821
- "created_at": "2024-06-01T12:00:00Z",
822
- "updated_at": "2024-06-01T12:00:00Z"
823
- }
824
- ```
825
-
826
- ### Chat with an AI agent
827
-
828
- ```http
829
- POST /ai/agent/my-agent/chat
830
- Authorization: Bearer <token>
831
- Content-Type: multipart/form-data
832
-
833
- Form-data:
834
- - message: "Hi, how are you?"
835
- - file: (optional file)
836
- ```
837
-
838
- Response:
839
-
840
- ```json
841
- {
842
- "slug": "my-agent",
843
- "provider": "openai",
844
- "model": "gpt-4o-mini",
845
- "content": "Hello! I'm doing well, thanks for asking."
846
- }
847
- ```
848
-
849
- ### Login with email and password
850
-
851
- ```http
852
- POST /auth/login
853
- Content-Type: application/json
854
-
855
- {
856
- "email": "user@example.com",
857
- "password": "strongPassword123"
858
- }
859
- ```
860
-
861
- Response:
862
-
863
- ```json
864
- {
865
- "accessToken": "<jwt_access_token>",
866
- "refreshToken": "<jwt_refresh_token>"
867
- }
868
- ```
869
-
870
- ### OAuth login started by another app (multi-app hub)
871
-
872
- An app other than the hub (e.g. `training`, key `training` in the `app-urls` setting) starts the login by redirecting the browser to:
873
-
874
- ```http
875
- GET /oauth/google/login?redirectApp=training
876
- ```
877
-
878
- The backend responds with a 302 `redirect` to Google's authorization URL, containing `state=hhweb.training.login.<signature>`. After consent, Google redirects to the single registered callback (`${url}/callback/google`, the hub). The hub reads the `state`, resolves `training` via `app-urls`, and forwards the browser to `${training-origin}/callback/google/login?code=...&state=...`. The `training` app then exchanges the code:
879
-
880
- ```http
881
- GET /oauth/google/callback/login?code=<code>&state=hhweb.training.login.<signature>
882
- ```
883
-
884
- Response:
885
-
886
- ```json
887
- {
888
- "accessToken": "<jwt_access_token>"
889
- }
890
- ```
891
-
892
- The `refreshToken` is set in the httpOnly `rt` cookie (it is not returned in the body, except when the call provides `redirectUri`, used by the mobile flow).
893
-
894
- ### Get system information
895
-
896
- ```http
897
- GET /system
898
- Authorization: Bearer <token>
899
- ```
900
-
901
- Response (abbreviated example):
902
-
903
- ```json
904
- {
905
- "os": {
906
- "name": "Linux",
907
- "platform": "linux",
908
- "version": "5.15.0",
909
- "architecture": "x64",
910
- "uptime": 123456,
911
- "cpu": {
912
- "model": "Intel(R) Xeon(R)",
913
- "speed": 2400,
914
- "physicalCores": 4,
915
- "virtualCores": 8
916
- },
917
- "memory": {
918
- "total": 17179869184,
919
- "free": 8589934592
920
- },
921
- "disk": [
922
- {
923
- "filesystem": "/dev/sda1",
924
- "size": 500107862016,
925
- "free": 250053931008,
926
- "mountpoint": "/"
927
- }
928
- ]
929
- },
930
- "modules": [
931
- {
932
- "name": "@hedhog/core",
933
- "version": "^1.0.0",
934
- "latestVersion": "1.0.1",
935
- "upToDate": false
936
- }
937
- ],
938
- "users": {
939
- "total": 100,
940
- "admin": 5,
941
- "active": 80,
942
- "activities": []
943
- },
944
- "database": {
945
- "connections": 10,
946
- "size": 104857600,
947
- "queriesPerSecond": 50
948
- }
949
- }
950
- ```
951
-
952
- ---
953
-
954
- This README documents the `@hed-hog/core` module based on the current source code and definitions, providing a detailed technical overview for developers and integrators of the system.
1
+ # @hed-hog/core
2
+
3
+ > **License**: MIT (Open Source) — Core is the only Open Source module of the HedHog Framework; the other modules are Enterprise and require a commercial license. See [LICENSE.md](./LICENSE.md).
4
+
5
+ Learn more about the HedHog Framework at **[hedhog.com](https://hedhog.com)**.
6
+
7
+ ## 1. Module overview
8
+
9
+ The `@hed-hog/core` module is the core of the HedHog monorepo, responsible for providing essential core functionality for the system, including authentication, artificial intelligence, dashboard, system information, and management of users, roles, permissions and UI components. It integrates several submodules covering everything from security and authentication to management of customizable dashboards and AI agents.
10
+
11
+ ## 2. Scope and responsibilities
12
+
13
+ - Authentication and authorization management, including MFA, WebAuthn, password recovery, sessions, and social login via OAuth (Google, Facebook, GitHub, Microsoft, Microsoft Entra ID, Apple, LinkedIn) with a multi-app callback hub.
14
+ - Artificial intelligence services for chat and AI agents with support for OpenAI and Gemini.
15
+ - Management of dashboards, components, roles, and associated users.
16
+ - Operating system, hardware, database, and installed-module information.
17
+ - Data validation and handling via DTOs and integration with the Prisma ORM.
18
+ - Internationalization and pagination support.
19
+
20
+ ## 3. Endpoints
21
+
22
+ ### AI Module (`/ai`)
23
+
24
+ | Method | Path | Auth | Description | Parameters / Query / Body | Response | Common Errors |
25
+ |--------|-------------------------|--------------|-----------------------------------------------------|-------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------------------------|
26
+ | POST | `/ai/chat` | Authenticated | Chats with AI, optionally sending a file. | Body: `ChatDTO` (message: string, provider?: 'openai'|'gemini', model?: string, systemPrompt?: string, file_id?: number)<br>File: optional | `{ provider: string, model: string, content: string }` | 400: API key not configured |
27
+ | POST | `/ai/agent` | Authenticated | Creates an AI agent. | Body: `CreateAgentDTO` (slug: string, provider?: 'openai'|'gemini', model?: string, instructions?: string) | Created or existing agent object | 400: Slug already exists |
28
+ | GET | `/ai/agent` | Authenticated | Lists AI agents with pagination. | Query: pagination (page?: number, pageSize?: number, search?: string) | Paginated list of agents | - |
29
+ | GET | `/ai/agent/id/:agentId` | Authenticated | Gets an AI agent by ID. | Path param: `agentId` (int) | Agent object | 404: Agent not found |
30
+ | GET | `/ai/agent/:slug` | Authenticated | Gets an AI agent by slug. | Path param: `slug` (string) | Agent object | 404: Agent not found |
31
+ | PATCH | `/ai/agent/:agentId` | Authenticated | Updates an AI agent. | Path param: `agentId` (int)<br>Body: `UpdateAgentDTO` (slug?: string, provider?: 'openai'|'gemini', model?: string, instructions?: string) | Updated agent object | 404: Agent not found<br>400: Duplicate slug |
32
+ | DELETE | `/ai/agent` | Authenticated | Bulk-deletes AI agents. | Body: `DeleteDTO` (ids: number[]) | `{ count: number }` | 404: One or more agents not found |
33
+ | POST | `/ai/agent/:slug/chat` | Authenticated | Chats with a specific AI agent, with an optional file. | Path param: `slug` (string)<br>Body: `ChatAgentDTO` (message: string, file_id?: number)<br>File: optional | `{ slug: string, provider: string, model: string, content: string }` | 404: Agent not found |
34
+
35
+ ### Auth Module (`/auth`)
36
+
37
+ | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
38
+ |--------|-------------------------------------|--------------|-----------------------------------------------------|--------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------------------------|
39
+ | GET | `/auth/verify` | Authenticated | Verifies the authenticated user. | - | Authenticated user data | - |
40
+ | GET | `/auth/roles` | Public | Returns the user's roles (if authenticated). | - | `{ roles: string[] }` | - |
41
+ | POST | `/auth/refresh` | Public | Refreshes the access token using the refresh token. | Body: `{ refreshToken?: string }`<br>Cookies: `rt` optional | `{ accessToken: string, refreshToken?: string }` | 400: Refresh token not provided |
42
+ | POST | `/auth/login` | Public | Login with email and password. | Body: `LoginDTO` (email: string, password: string, refreshToken?: boolean) | Access and refresh tokens, or MFA required | 400: Access denied |
43
+ | POST | `/auth/login-email-verification` | Public | Login via email verification and code. | Body: `LoginEmailVerificationDTO` (token: string, code: string) | Access and refresh tokens | 400: Invalid code or challenge not found |
44
+ | POST | `/auth/login-email-verification-resend` | Public | Resends the email verification code. | Body: `LoginEmailVerificationResendDTO` (token: string) | New token for verification | 400: Invalid or expired token |
45
+ | POST | `/auth/signup` | Public | Sign-up with email and password. | Body: `CreateWithEmailAndPasswordDTO` | User created | - |
46
+ | POST | `/auth/login-code` | Public | Login with an MFA code. | Body: `LoginWithCodeDTO` (token: string, code: string, methodType?: 'totp'|'email'|'recovery') | Access and refresh tokens | 400: Invalid MFA code |
47
+ | POST | `/auth/login-recovery-code` | Public | Login with an MFA recovery code. | Body: `LoginWithRecoveryCodeDTO` (token: string, code: string) | Access and refresh tokens | 400: Invalid recovery code|
48
+ | POST | `/auth/resend-mfa-code` | Public | Resends the MFA code by email. | Body: `ResendMfaCodeDTO` (token: string) | `{ success: true, hasEmailMfa: true }` | 400: No email MFA method configured |
49
+ | POST | `/auth/webauthn/generate` | Public | Generates options for WebAuthn authentication. | Body: `{ mfaToken: string }` | WebAuthn options | 400: WebAuthn not configured |
50
+ | POST | `/auth/webauthn/verify` | Public | Verifies WebAuthn authentication. | Body: `{ mfaToken: string, assertionResponse: any }` | Access and refresh tokens | 400: Verification failed |
51
+ | POST | `/auth/forgot` | Public | Requests password recovery via email. | Body: `ForgetDTO` (email: string) | `{ success: true }` | - |
52
+ | POST | `/auth/logout` | Public | Logs out and invalidates the refresh token. | Body: `{ refreshToken?: string }`<br>Cookies: `rt` optional | `{ success: true }` | 400: Refresh token not provided |
53
+ | POST | `/auth/forgot-reset` | Public | Resets the password using a recovery code. | Body: `ResetDTO` (password: string, code: string) | Access and refresh tokens | 400: Invalid or expired code |
54
+
55
+ ### OAuth Module (`/oauth`)
56
+
57
+ > **Multi-app hub pattern**: each provider only needs **one registered callback URL** (`${url}/callback/:provider`, with no flow suffix — GitHub uses `${api-url}/oauth/github/callback`, and Apple uses `${api-url}/oauth/apple/callback`, both because they only accept a single callback URL). The flow (`login`/`register`/`connect`) and the app that started the authentication (e.g. `training`) travel signed in the `state` parameter (`hhweb.<app>.<flow>.<signature>`, HMAC via `SecurityService`), never in the path. The app configured in the `url` setting acts as the **hub**: when it receives the callback from the provider, it either handles the flow locally or forwards the browser to the callback page of the app that started the flow, resolving the origin via the `app-urls` setting. Supported providers: Google, Facebook, GitHub, Microsoft, Microsoft Entra ID, Apple (Sign in with Apple), and LinkedIn.
58
+
59
+ | Method | Path | Auth | Description | Parameters / Query / Body | Response | Common Errors |
60
+ |--------|----------------------------------|--------------|--------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|------------------------------------------------------------------------|----------------------------------------------------------------------|
61
+ | GET | `/oauth/github/callback` | Public | Exclusive GitHub bounce (the only callback URL accepted by the provider); forwards the `code` to the correct frontend. | Query: `code`, `state?` | 302 redirect to `${origin}/callback/github/<flow>?code=...&state=...` | - |
62
+ | POST | `/oauth/apple/callback` | Public | Exclusive Apple bounce: Apple requires `response_mode=form_post` when `scope` is requested, so it POSTs `code`/`state` instead of a GET redirect. This is converted back to a GET redirect, the same as the GitHub bounce. | Body: `code`, `state?` | 302 redirect to `${origin}/callback/apple/<flow>?code=...&state=...` | - |
63
+ | GET | `/oauth/:provider/login` | Public | Starts the login flow, redirecting to the provider's authorization screen. | Path: `provider`<br>Query: `redirectApp?` (key in the initiating app's `app-urls`) | 302 redirect to the provider's authorization URL | 400: provider not enabled or not supported |
64
+ | GET | `/oauth/:provider/register` | Public | Starts the sign-up flow via OAuth. | Path: `provider`<br>Query: `redirectApp?` | 302 redirect to the provider's authorization URL | 400: provider not enabled or not supported |
65
+ | GET | `/oauth/:provider/connect` | Public | Starts the flow to link an account to a user already authenticated in the target app. | Path: `provider`<br>Query: `redirectApp?` | 302 redirect to the provider's authorization URL | 400: provider not enabled or not supported |
66
+ | GET | `/oauth/:provider/mobile/auth-url` | Public | Returns the authorization URL for native apps (Electron/React Native) to intercept the redirect. | Path: `provider`<br>Query: `redirectUri` (native app's custom scheme) | `{ authUrl: string }` | 400: invalid redirect URI or provider not enabled |
67
+ | GET | `/oauth/:provider/callback/login` | Public | Exchanges the `code` for access tokens after the hub forwards to the app's login page. | Path: `provider`<br>Query: `code`, `state?`, `redirectUri?` | `{ accessToken: string, refreshToken?: string }` + `rt` cookie (httpOnly) | 400: missing code, invalid origin, or callback already processed<br>409: callback being processed<br>503: provider failure |
68
+ | GET | `/oauth/:provider/callback/register` | Public | Exchanges the `code` for tokens after signing up via OAuth. | Path: `provider`<br>Query: `code` | `{ accessToken: string, refreshToken?: string }` + `rt` cookie | 400/409/503 — same cases as the login callback |
69
+ | GET | `/oauth/:provider/callback/connect` | Authenticated | Links the provider account to the authenticated user. | Path: `provider`<br>Query: `code` | `{ accessToken: string, refreshToken?: string }` + `rt` cookie | 400/409/503 — same cases as the login callback |
70
+ | DELETE | `/oauth/:provider` | Authenticated | Unlinks the provider account from the user. | Path: `provider`<br>Body: `{ email: string }` | Disconnection result | - |
71
+
72
+ ### System Module (`/system`)
73
+
74
+ | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
75
+ |--------|------------|--------------|---------------------------------|-------------------|--------------------------------------------------------------------------------------------|--------------|
76
+ | GET | `/system` | Authenticated | Returns system information. | - | Detailed information about the operating system, hardware, database, modules, and users | - |
77
+
78
+ ### Dashboard Core Module (`/dashboard-core`)
79
+
80
+ | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
81
+ |--------|---------------------------|--------------|-----------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------------------------|
82
+ | GET | `/dashboard-core/home` | Authenticated | Returns the user's home dashboard. | - | Dashboard object or null | 400: User not found |
83
+ | GET | `/dashboard-core/stats/overview/users` | Authenticated | User statistics. | - | Aggregated user and session statistics | - |
84
+ | GET | `/dashboard-core/stats/overview/mails` | Authenticated | Sent-email statistics. | - | Aggregated statistics on sent emails | - |
85
+ | GET | `/dashboard-core/stats/overview/system` | Authenticated | System statistics (menus and routes). | - | Aggregated system statistics | - |
86
+ | GET | `/dashboard-core/config/overview` | Authenticated | Overview of the system settings. | - | Object with configuration | - |
87
+ | GET | `/dashboard-core/widgets/me` | Authenticated | Widget data for the user. | - | Aggregated data for the user's widgets | - |
88
+ | GET | `/dashboard-core/user-dashboards` | Authenticated | Lists the user's dashboards. | - | List of dashboards associated with the user | - |
89
+ | GET | `/dashboard-core/templates` | Authenticated | Lists templates available for dashboards. | - | List of templates | - |
90
+ | POST | `/dashboard-core/dashboard` | Authenticated | Creates a dashboard for the user. | Body: `{ name?: string; slug?: string; icon?: string | null; templateSlug?: string }` | Created dashboard | - |
91
+ | PATCH | `/dashboard-core/dashboard/order` | Authenticated | Reorders the user's dashboards. | Body: `{ slugs?: string[] }` | Reordered dashboard | - |
92
+ | PATCH | `/dashboard-core/dashboard/:slug` | Authenticated | Renames the user's dashboard. | Path param: `slug` (string)<br>Body: `{ name?: string; icon?: string | null }` | Updated dashboard | - |
93
+ | POST | `/dashboard-core/dashboard/:slug/home` | Authenticated | Sets the dashboard as the user's home dashboard. | Path param: `slug` (string) | Success | - |
94
+ | GET | `/dashboard-core/dashboard/:slug/shares` | Authenticated | Lists the dashboard's shares. | Path param: `slug` (string) | List of users with access | - |
95
+ | GET | `/dashboard-core/shareable-users/:slug` | Authenticated | Lists users the dashboard can be shared with. | Path param: `slug` (string)<br>Query: search?: string, page?: string, pageSize?: string | Paginated list of users | - |
96
+ | POST | `/dashboard-core/dashboard/:slug/share` | Authenticated | Shares the dashboard with users. | Path param: `slug` (string)<br>Body: `{ userId?: number; userIds?: number[] }` | Success | - |
97
+ | DELETE | `/dashboard-core/dashboard/:slug/share/:sharedUserId` | Authenticated | Revokes a dashboard share. | Path params: `slug` (string), `sharedUserId` (int) | Success | - |
98
+ | DELETE | `/dashboard-core/dashboard/:slug` | Authenticated | Removes the dashboard from the user. | Path param: `slug` (string) | Success | - |
99
+ | GET | `/dashboard-core/access/:slug` | Authenticated | Checks the user's access to the dashboard. | Path param: `slug` (string) | `{ hasAccess: boolean, dashboard: object|null }` | - |
100
+ | GET | `/dashboard-core/layout/:slug` | Authenticated | Gets the user's layout for the dashboard. | Path param: `slug` (string) | Array of widgets with positions and sizes | - |
101
+ | POST | `/dashboard-core/layout/:slug` | Authenticated | Saves the user's layout for the dashboard. | Body: `{ layout: Array<{ i: string; x: number; y: number; w: number; h: number }> }` | `{ success: true }` | 403: Access denied |
102
+ | POST | `/dashboard-core/widget/:slug` | Authenticated | Adds a widget to the user's dashboard. | Body: `{ componentSlug: string }` | Data for the added widget | 403: Access denied |
103
+ | DELETE | `/dashboard-core/widget/:slug/:widgetId` | Authenticated | Removes a widget from the user's dashboard. | Path params: `slug` (string), `widgetId` (string) | "Not implemented yet" error | - |
104
+ | GET | `/dashboard-core/:slug` | Authenticated | Gets dashboard items by slug. | Path param: `slug` (string), Query param: `locale?: string` | List of dashboard items | - |
105
+
106
+ ### Dashboard Module (`/dashboard`)
107
+
108
+ | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
109
+ |--------|----------------|--------------|------------------------------------|---------------------------------------------------------|------------------------------|----------------------------|
110
+ | GET | `/dashboard` | Authenticated | Lists dashboards with pagination | Query: pagination (page?: number, pageSize?: number, search?: string) | Paginated list of dashboards | - |
111
+ | GET | `/dashboard/:id` | Authenticated | Gets a dashboard by ID | Path param: `id` (int) | Dashboard object | 404: Dashboard not found |
112
+ | POST | `/dashboard` | Authenticated | Creates a dashboard | Body: `CreateDashboardDTO` (slug: string, locale: Record<string, { name: string }>) | Created dashboard | - |
113
+ | PATCH | `/dashboard/:id` | Authenticated | Updates a dashboard | Path param: `id` (int), Body: `UpdateDashboardDTO` | Updated dashboard | 404: Dashboard not found |
114
+ | DELETE | `/dashboard/:id` | Authenticated | Deletes a dashboard | Path param: `id` (int) | `{ success: true }` | 404: Dashboard not found |
115
+
116
+ ### Dashboard Component Module (`/dashboard-component`)
117
+
118
+ | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
119
+ |--------|------------------------|--------------|------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
120
+ | GET | `/dashboard-component` | Authenticated | Lists components with pagination | Query: pagination (page?: number, pageSize?: number, search?: string) | Paginated list of components | - |
121
+ | GET | `/dashboard-component/user` | Authenticated | Lists components by the user's roles | Query: pagination (page?: number, pageSize?: number, search?: string), User ID via token | Paginated list of components | - |
122
+ | GET | `/dashboard-component/:id` | Authenticated | Gets a component by ID | Path param: `id` (int) | Component object | 404: Component not found |
123
+ | POST | `/dashboard-component` | Authenticated | Creates a component | Body: `CreateDashboardComponentDTO` | Created component | - |
124
+ | PATCH | `/dashboard-component/:id` | Authenticated | Updates a component | Path param: `id` (int), Body: `UpdateDashboardComponentDTO` | Updated component | 404: Component not found |
125
+ | DELETE | `/dashboard-component/:id` | Authenticated | Deletes a component | Path param: `id` (int) | `{ success: true }` | 404: Component not found |
126
+ | POST | `/dashboard-component/:id/preview` | Authenticated | Saves a component preview (image) | Path param: `id` (int), File: image (image/*) | `{ success: true, componentId: number, slug: string, library_slug: string, fileName: string, relativeUrl: string }` | 400: Invalid file<br>403: Dev environment only |
127
+
128
+ ### Dashboard Component Role Module (`/dashboard-component-role`)
129
+
130
+ | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
131
+ |--------|-------------------------------|--------------|---------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
132
+ | GET | `/dashboard-component-role` | Authenticated | Lists relations with pagination or by component | Query: pagination (page?: number, pageSize?: number), Query param: componentId?: number | Paginated or list of relations | - |
133
+ | POST | `/dashboard-component-role` | Authenticated | Creates a component-role relation | Body: `CreateDashboardComponentRoleDTO` | Created relation | Error if the relation already exists |
134
+ | POST | `/dashboard-component-role/batch` | Authenticated | Bulk-creates relations | Body: `CreateDashboardComponentRoleBatchDTO` | { success: boolean, created: number, skipped: number, message: string } | - |
135
+ | DELETE | `/dashboard-component-role/:id` | Authenticated | Deletes a relation by ID | Path param: `id` (int) | `{ success: true }` | 404: Relation not found |
136
+ | DELETE | `/dashboard-component-role/component/:componentId/role/:roleId` | Authenticated | Deletes a relation by component and role | Path params: `componentId` (int), `roleId` (int) | `{ success: true }` | 404: Relation not found |
137
+
138
+ ### Dashboard Item Module (`/dashboard-item`)
139
+
140
+ | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
141
+ |--------|--------------------|--------------|------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
142
+ | GET | `/dashboard-item` | Authenticated | Lists items with pagination and filter by dashboard | Query: pagination (page?: number, pageSize?: number), Query param: dashboardId?: number | Paginated list of items | - |
143
+ | POST | `/dashboard-item` | Authenticated | Creates an item | Body: `CreateDashboardItemDTO` | Created item | - |
144
+ | DELETE | `/dashboard-item/:id` | Authenticated | Deletes an item by ID | Path param: `id` (int) | `{ success: true }` | 404: Item not found |
145
+
146
+ ### Dashboard Role Module (`/dashboard-role`)
147
+
148
+ | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
149
+ |--------|--------------------|--------------|---------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
150
+ | GET | `/dashboard-role` | Authenticated | Lists relations with pagination or by dashboard | Query: pagination (page?: number, pageSize?: number), Query param: dashboardId?: number | Paginated or list of relations | - |
151
+ | POST | `/dashboard-role` | Authenticated | Creates a dashboard-role relation | Body: `CreateDashboardRoleDTO` | Created relation | Error if the relation already exists |
152
+ | POST | `/dashboard-role/batch` | Authenticated | Bulk-creates relations | Body: `CreateDashboardRoleBatchDTO` | { success: boolean, created: number, skipped: number, message: string } | - |
153
+ | DELETE | `/dashboard-role/:id` | Authenticated | Deletes a relation by ID | Path param: `id` (int) | `{ success: true }` | 404: Relation not found |
154
+ | DELETE | `/dashboard-role/dashboard/:dashboardId/role/:roleId` | Authenticated | Deletes a relation by dashboard and role | Path params: `dashboardId` (int), `roleId` (int) | `{ success: true }` | 404: Relation not found |
155
+
156
+ ### Dashboard User Module (`/dashboard-user`)
157
+
158
+ | Method | Path | Auth | Description | Parameters / Body | Response | Common Errors |
159
+ |--------|--------------------|--------------|------------------------------------|------------------------------------------------------------------|------------------------------|-------------------------------|
160
+ | GET | `/dashboard-user` | Authenticated | Lists relations with pagination | Query: pagination (page?: number, pageSize?: number) | Paginated list of relations | - |
161
+ | GET | `/dashboard-user/:id` | Authenticated | Gets a relation by ID | Path param: `id` (int) | Relation object | - |
162
+ | POST | `/dashboard-user` | Authenticated | Creates a relation | Body: `CreateDTO` (dashboard_id: number, user_id: number) | Created relation | - |
163
+ | PATCH | `/dashboard-user/:id` | Authenticated | Updates a relation | Path param: `id` (int), Body: `UpdateDTO` | Updated relation | - |
164
+ | DELETE | `/dashboard-user` | Authenticated | Bulk-deletes relations | Body: `DeleteDTO` (ids: number[]) | `{ count: number }` | 400: No id provided |
165
+
166
+ ## 4. Authentication and authorization rules
167
+
168
+ - Most endpoints require authentication via a JWT token.
169
+ - Public endpoints are explicitly marked.
170
+ - Access control is based on roles and permissions.
171
+ - MFA (Multi-Factor Authentication) is supported via TOTP, email, and recovery codes.
172
+ - WebAuthn is supported for strong authentication.
173
+ - Refresh tokens are managed via HTTP-only cookies or in the request body.
174
+ - Sensitive operations (create, update, delete) require authentication and the appropriate permissions.
175
+
176
+ ## 5. Request/response structures
177
+
178
+ ### Main DTOs of the AI module
179
+
180
+ - **ChatDTO**
181
+
182
+ ```ts
183
+ {
184
+ message: string; // required
185
+ provider?: 'openai' | 'gemini'; // optional, default 'openai'
186
+ model?: string; // optional
187
+ systemPrompt?: string; // optional
188
+ file_id?: number; // optional
189
+ }
190
+ ```
191
+
192
+ - **ChatAgentDTO**
193
+
194
+ ```ts
195
+ {
196
+ message: string; // required
197
+ file_id?: number; // optional
198
+ }
199
+ ```
200
+
201
+ - **CreateAgentDTO**
202
+
203
+ ```ts
204
+ {
205
+ slug: string; // required
206
+ provider?: 'openai' | 'gemini'; // optional, default 'openai'
207
+ model?: string; // optional
208
+ instructions?: string; // optional
209
+ }
210
+ ```
211
+
212
+ - **UpdateAgentDTO**
213
+
214
+ ```ts
215
+ {
216
+ slug?: string;
217
+ provider?: 'openai' | 'gemini';
218
+ model?: string;
219
+ instructions?: string;
220
+ }
221
+ ```
222
+
223
+ - **DeleteDTO**
224
+
225
+ ```ts
226
+ {
227
+ ids: number[]; // array of IDs to delete, minimum 1 item
228
+ }
229
+ ```
230
+
231
+ ### Main DTOs of the Auth module
232
+
233
+ - **LoginDTO**
234
+
235
+ ```ts
236
+ {
237
+ email: string; // required, valid email
238
+ password: string; // required, strong password, minimum 6 characters
239
+ refreshToken?: boolean; // optional, default false
240
+ }
241
+ ```
242
+
243
+ - **LoginEmailVerificationDTO**
244
+
245
+ ```ts
246
+ {
247
+ token: string; // required
248
+ code: string; // required, PIN code
249
+ }
250
+ ```
251
+
252
+ - **LoginEmailVerificationResendDTO**
253
+
254
+ ```ts
255
+ {
256
+ token: string; // required
257
+ }
258
+ ```
259
+
260
+ - **LoginWithCodeDTO**
261
+
262
+ ```ts
263
+ {
264
+ code: string; // required
265
+ token: string; // required, JWT
266
+ methodType?: 'totp' | 'email' | 'recovery'; // optional
267
+ }
268
+ ```
269
+
270
+ - **LoginWithRecoveryCodeDTO**
271
+
272
+ ```ts
273
+ {
274
+ code: string; // required
275
+ token: string; // required, JWT
276
+ }
277
+ ```
278
+
279
+ - **ForgetDTO**
280
+
281
+ ```ts
282
+ {
283
+ email: string; // required, valid email
284
+ }
285
+ ```
286
+
287
+ - **ResetDTO**
288
+
289
+ ```ts
290
+ {
291
+ password: string; // required, minimum 8 characters
292
+ code: string; // required
293
+ }
294
+ ```
295
+
296
+ ### Main DTOs of the Dashboard module
297
+
298
+ - **CreateDashboardDTO**
299
+
300
+ ```ts
301
+ {
302
+ slug: string; // required
303
+ locale: Record<string, { name: string }>; // required
304
+ }
305
+ ```
306
+
307
+ - **UpdateDashboardDTO**
308
+
309
+ ```ts
310
+ {
311
+ slug?: string;
312
+ locale?: Record<string, { name: string }>;
313
+ }
314
+ ```
315
+
316
+ - **CreateDashboardComponentDTO**
317
+
318
+ ```ts
319
+ {
320
+ slug: string;
321
+ library_slug?: string;
322
+ min_width?: number;
323
+ max_width?: number;
324
+ min_height?: number;
325
+ max_height?: number;
326
+ width: number;
327
+ height: number;
328
+ is_resizable?: boolean;
329
+ locale: Record<string, { name: string; description?: string }>;
330
+ }
331
+ ```
332
+
333
+ - **UpdateDashboardComponentDTO**
334
+
335
+ ```ts
336
+ {
337
+ slug?: string;
338
+ library_slug?: string;
339
+ min_width?: number;
340
+ max_width?: number;
341
+ min_height?: number;
342
+ max_height?: number;
343
+ width?: number;
344
+ height?: number;
345
+ is_resizable?: boolean;
346
+ locale?: Record<string, { name: string; description?: string }>;
347
+ }
348
+ ```
349
+
350
+ - **CreateDashboardRoleDTO**
351
+
352
+ ```ts
353
+ {
354
+ dashboard_id: number;
355
+ role_id: number;
356
+ }
357
+ ```
358
+
359
+ - **CreateDashboardRoleBatchDTO**
360
+
361
+ ```ts
362
+ {
363
+ dashboard_id: number;
364
+ role_ids: number[];
365
+ }
366
+ ```
367
+
368
+ - **CreateDashboardComponentRoleDTO**
369
+
370
+ ```ts
371
+ {
372
+ component_id: number;
373
+ role_id: number;
374
+ }
375
+ ```
376
+
377
+ - **CreateDashboardComponentRoleBatchDTO**
378
+
379
+ ```ts
380
+ {
381
+ component_id: number;
382
+ role_ids: number[];
383
+ }
384
+ ```
385
+
386
+ - **CreateDashboardItemDTO**
387
+
388
+ ```ts
389
+ {
390
+ component_id: number;
391
+ dashboard_id: number;
392
+ width: number;
393
+ height: number;
394
+ x_axis: number;
395
+ y_axis: number;
396
+ }
397
+ ```
398
+
399
+ - **UpdateDashboardLayoutDTO**
400
+
401
+ ```ts
402
+ {
403
+ dashboard_id: number;
404
+ items: Array<{
405
+ id: number;
406
+ width: number;
407
+ height: number;
408
+ x_axis: number;
409
+ y_axis: number;
410
+ }>;
411
+ }
412
+ ```
413
+
414
+ - **UpdateDashboardItemDTO**
415
+
416
+ ```ts
417
+ {
418
+ component_id?: number;
419
+ dashboard_id?: number;
420
+ width?: number;
421
+ height?: number;
422
+ x_axis?: number;
423
+ y_axis?: number;
424
+ }
425
+ ```
426
+
427
+ - **CreateDTO (DashboardUser)**
428
+
429
+ ```ts
430
+ {
431
+ dashboard_id: number;
432
+ user_id: number;
433
+ }
434
+ ```
435
+
436
+ - **UpdateDTO (DashboardUser)**
437
+
438
+ ```ts
439
+ {
440
+ dashboard_id?: number;
441
+ user_id?: number;
442
+ }
443
+ ```
444
+
445
+ - **DeleteDTO**
446
+
447
+ ```ts
448
+ {
449
+ ids: number[];
450
+ }
451
+ ```
452
+
453
+ ## 6. Common errors
454
+
455
+ - **400 Bad Request**
456
+
457
+ - API key not configured for OpenAI or Gemini.
458
+ - AI agent slug already exists.
459
+ - Invalid or expired verification code.
460
+ - Refresh token not provided.
461
+ - Access denied due to invalid credentials.
462
+ - MFA not configured or invalid code.
463
+ - Attempt to delete non-existent items.
464
+ - Invalid request to create duplicate relations.
465
+ - Invalid file for component preview.
466
+ - Preview operation available only in the development environment.
467
+ - OAuth: provider not enabled (`oauth-<provider>-enabled` off) or not supported.
468
+ - OAuth: integration profile not configured (`oauth-<provider>-profile-id` empty) or not found.
469
+ - OAuth: missing authorization code, invalid mobile redirect URI, invalid callback origin (hub origin binding), or callback already processed.
470
+
471
+ - **404 Not Found**
472
+
473
+ - AI agent not found by ID or slug.
474
+ - Dashboard, component, or relation not found.
475
+ - Verification challenge not found or expired.
476
+
477
+ - **403 Forbidden**
478
+
479
+ - Access denied to dashboards or protected resources.
480
+ - Attempt to save a preview outside the development environment.
481
+
482
+ - **409 Conflict**
483
+
484
+ - OAuth: callback already being processed (idempotency lock by code).
485
+
486
+ - **503 Service Unavailable**
487
+
488
+ - OAuth: failure communicating with the provider (upstream).
489
+
490
+ ## 7. Database (YAML tables)
491
+
492
+ ### ai_agent
493
+
494
+ ```yaml
495
+ purpose: Stores AI agents configured in the system.
496
+ columns:
497
+ - id: integer, PK, auto-increment
498
+ - slug: string, unique, not null
499
+ - provider: enum('openai', 'gemini'), not null
500
+ - model: string, nullable
501
+ - instructions: string, nullable
502
+ - external_agent_id: string, nullable
503
+ - created_at: timestamp, not null, default NOW()
504
+ - updated_at: timestamp, not null, default NOW()
505
+ defaults:
506
+ - created_at: NOW()
507
+ - updated_at: NOW()
508
+ nullability:
509
+ - model: nullable
510
+ - instructions: nullable
511
+ - external_agent_id: nullable
512
+ integrity:
513
+ - unique slug
514
+ indexes:
515
+ - id (PK)
516
+ - slug (unique)
517
+ enums:
518
+ - provider: ['openai', 'gemini']
519
+ ```
520
+
521
+ ### user
522
+
523
+ ```yaml
524
+ purpose: Stores the system's users.
525
+ columns:
526
+ - id: integer, PK, auto-increment
527
+ - name: string, not null
528
+ - photo_id: integer, nullable
529
+ - last_login_at: timestamp, nullable
530
+ - created_at: timestamp, not null, default NOW()
531
+ - updated_at: timestamp, not null, default NOW()
532
+ integrity:
533
+ - PK on id
534
+ indexes:
535
+ - id (PK)
536
+ ```
537
+
538
+ ### user_mfa
539
+
540
+ ```yaml
541
+ purpose: Stores users' multi-factor authentication methods.
542
+ columns:
543
+ - id: integer, PK, auto-increment
544
+ - user_id: integer, FK to user.id, not null
545
+ - name: string, not null
546
+ - type: enum('totp', 'email', 'webauthn'), not null
547
+ - verified_at: timestamp, nullable
548
+ - suspended_until: timestamp, nullable
549
+ - created_at: timestamp, not null, default NOW()
550
+ - updated_at: timestamp, not null, default NOW()
551
+ integrity:
552
+ - FK user_id references user.id
553
+ indexes:
554
+ - id (PK)
555
+ enums:
556
+ - type: ['totp', 'email', 'webauthn']
557
+ ```
558
+
559
+ ### user_identifier
560
+
561
+ ```yaml
562
+ purpose: User identifiers, such as emails.
563
+ columns:
564
+ - id: integer, PK, auto-increment
565
+ - user_id: integer, FK to user.id, not null
566
+ - type: string, not null (e.g.: 'email')
567
+ - value: string, not null
568
+ - verified_at: timestamp, nullable
569
+ - enabled: boolean, not null, default true
570
+ - created_at: timestamp, not null, default NOW()
571
+ - updated_at: timestamp, not null, default NOW()
572
+ integrity:
573
+ - FK user_id references user.id
574
+ indexes:
575
+ - id (PK)
576
+ ```
577
+
578
+ ### user_session
579
+
580
+ ```yaml
581
+ purpose: Sessions of authenticated users.
582
+ columns:
583
+ - id: integer, PK, auto-increment
584
+ - user_id: integer, FK to user.id, not null
585
+ - token: string, not null
586
+ - ip_address: string, nullable
587
+ - user_agent: string, nullable
588
+ - created_at: timestamp, not null, default NOW()
589
+ - expires_at: timestamp, not null
590
+ - revoked_at: timestamp, nullable
591
+ integrity:
592
+ - FK user_id references user.id
593
+ indexes:
594
+ - id (PK)
595
+ ```
596
+
597
+ ### user_activity
598
+
599
+ ```yaml
600
+ purpose: Log of user activities.
601
+ columns:
602
+ - id: integer, PK, auto-increment
603
+ - user_id: integer, FK to user.id, not null
604
+ - action: string, not null
605
+ - created_at: timestamp, not null, default NOW()
606
+ integrity:
607
+ - FK user_id references user.id
608
+ indexes:
609
+ - id (PK)
610
+ ```
611
+
612
+ ### role
613
+
614
+ ```yaml
615
+ purpose: System roles for access control.
616
+ columns:
617
+ - id: integer, PK, auto-increment
618
+ - slug: string, unique, not null
619
+ - created_at: timestamp, not null, default NOW()
620
+ - updated_at: timestamp, not null, default NOW()
621
+ integrity:
622
+ - unique slug
623
+ indexes:
624
+ - id (PK)
625
+ - slug (unique)
626
+ ```
627
+
628
+ ### role_user
629
+
630
+ ```yaml
631
+ purpose: Many-to-many relation between users and roles.
632
+ columns:
633
+ - id: integer, PK, auto-increment
634
+ - user_id: integer, FK to user.id, not null
635
+ - role_id: integer, FK to role.id, not null
636
+ integrity:
637
+ - FK user_id references user.id
638
+ - FK role_id references role.id
639
+ indexes:
640
+ - id (PK)
641
+ ```
642
+
643
+ ### dashboard
644
+
645
+ ```yaml
646
+ purpose: The system's configurable dashboards.
647
+ columns:
648
+ - id: integer, PK, auto-increment
649
+ - slug: string, unique, not null
650
+ - created_at: timestamp, not null, default NOW()
651
+ - updated_at: timestamp, not null, default NOW()
652
+ integrity:
653
+ - unique slug
654
+ indexes:
655
+ - id (PK)
656
+ - slug (unique)
657
+ ```
658
+
659
+ ### dashboard_component
660
+
661
+ ```yaml
662
+ purpose: Components that can be used in dashboards.
663
+ columns:
664
+ - id: integer, PK, auto-increment
665
+ - slug: string, unique, not null
666
+ - library_slug: string, nullable
667
+ - min_width: integer, nullable
668
+ - max_width: integer, nullable
669
+ - min_height: integer, nullable
670
+ - max_height: integer, nullable
671
+ - width: integer, not null
672
+ - height: integer, not null
673
+ - is_resizable: boolean, not null, default true
674
+ - created_at: timestamp, not null, default NOW()
675
+ - updated_at: timestamp, not null, default NOW()
676
+ integrity:
677
+ - unique slug
678
+ indexes:
679
+ - id (PK)
680
+ - slug (unique)
681
+ ```
682
+
683
+ ### dashboard_role
684
+
685
+ ```yaml
686
+ purpose: Relation between dashboards and roles for access control.
687
+ columns:
688
+ - id: integer, PK, auto-increment
689
+ - dashboard_id: integer, FK to dashboard.id, not null
690
+ - role_id: integer, FK to role.id, not null
691
+ integrity:
692
+ - FK dashboard_id references dashboard.id
693
+ - FK role_id references role.id
694
+ indexes:
695
+ - id (PK)
696
+ ```
697
+
698
+ ### dashboard_user
699
+
700
+ ```yaml
701
+ purpose: Relation between dashboards and users.
702
+ columns:
703
+ - id: integer, PK, auto-increment
704
+ - dashboard_id: integer, FK to dashboard.id, not null
705
+ - user_id: integer, FK to user.id, not null
706
+ - is_home: boolean, not null, default false
707
+ integrity:
708
+ - FK dashboard_id references dashboard.id
709
+ - FK user_id references user.id
710
+ indexes:
711
+ - id (PK)
712
+ ```
713
+
714
+ ### dashboard_item
715
+
716
+ ```yaml
717
+ purpose: Items (widgets) within dashboards.
718
+ columns:
719
+ - id: integer, PK, auto-increment
720
+ - dashboard_id: integer, FK to dashboard.id, not null
721
+ - component_id: integer, FK to dashboard_component.id, not null
722
+ - width: integer, not null
723
+ - height: integer, not null
724
+ - x_axis: integer, not null
725
+ - y_axis: integer, not null
726
+ integrity:
727
+ - FK dashboard_id references dashboard.id
728
+ - FK component_id references dashboard_component.id
729
+ indexes:
730
+ - id (PK)
731
+ ```
732
+
733
+ ### dashboard_component_role
734
+
735
+ ```yaml
736
+ purpose: Relation between dashboard components and roles.
737
+ columns:
738
+ - id: integer, PK, auto-increment
739
+ - component_id: integer, FK to dashboard_component.id, not null
740
+ - role_id: integer, FK to role.id, not null
741
+ integrity:
742
+ - FK component_id references dashboard_component.id
743
+ - FK role_id references role.id
744
+ indexes:
745
+ - id (PK)
746
+ ```
747
+
748
+ ### oauth_mobile_state_token
749
+
750
+ ```yaml
751
+ purpose: Single-use signed state for the OAuth flow started by native apps (mobile/desktop), binding the app's redirect URI to the provider and the flow.
752
+ columns:
753
+ - id: bigint, PK, auto-increment
754
+ - token_hash: string, unique, not null
755
+ - provider: string, not null
756
+ - redirect_uri: string, not null (native app's custom scheme)
757
+ - flow_type: string, not null ('login' | 'register' | 'connect')
758
+ - expires_at: timestamptz, not null
759
+ - consumed_at: timestamptz, nullable (marks single use)
760
+ - created_at: timestamptz, not null, default NOW()
761
+ integrity:
762
+ - unique token_hash
763
+ indexes:
764
+ - id (PK)
765
+ - expires_at
766
+ - (provider, redirect_uri)
767
+ ```
768
+
769
+ > Used only by the mobile flow (`GET /oauth/:provider/mobile/auth-url`). The multi-app web hub (signed `state`, `hhweb.<app>.<flow>.<sig>`) is stateless — the HMAC signature is verified without database persistence.
770
+
771
+ ## 8. Relevant business rules
772
+
773
+ - AI agents can be created, updated, and deleted, with direct integration with the OpenAI and Gemini APIs.
774
+ - AI chat supports file attachments, with text extraction for PDFs and text files.
775
+ - Mandatory MFA can be configured, with support for email, TOTP, and WebAuthn.
776
+ - Access and refresh tokens are managed securely, including HTTP-only cookies.
777
+ - Dashboards are personalized per user, with role-based access control.
778
+ - Dashboard and widget layouts can be saved and retrieved per user.
779
+ - The system collects usage statistics, sessions, sent emails, and account security data.
780
+ - Strict validations are applied via DTOs and validation classes.
781
+ - Batch create operations avoid duplication and return counts of created and skipped items.
782
+ - Removing widgets from a user's dashboard is not yet implemented.
783
+ - Dashboard component previews are allowed only in the development environment and accept images only.
784
+ - Email MFA sends codes to all email addresses associated with the user.
785
+ - WebAuthn is supported for strong authentication with challenge generation and verification.
786
+ - **OAuth — one callback URL per provider**: the flow (login/register/connect) and the initiating app travel signed in the `state`, never in the path; each provider is enabled/disabled individually via the `oauth-<provider>-enabled` setting, without removing the configured credentials (`oauth-<provider>-profile-id`, pointing to an `integration_profile`).
787
+ - **OAuth — multi-app hub**: the app in the `url` setting (e.g. admin) receives the callback from the provider and, if the `state` indicates a different initiating app, forwards the browser to that app's corresponding callback page, resolving the origin via `app-urls`. Exchanging the `code` for tokens is only accepted when the request's `Origin`/`Referer` header matches the origin signed in the `state` (origin binding), preventing code interception between apps.
788
+ - **OAuth — email auto-linking**: on login, if no `user_account` exists for the provider but an enabled email `user_identifier` matching the OAuth profile's email already exists, the flow becomes an automatic connection (`connect`) to the existing account instead of creating a new user; a new account (`register`) is only created when no user matches the email.
789
+ - **OAuth — roles on sign-up**: new users registered via OAuth receive the roles configured in the `oauth-role-assignment` setting.
790
+ - **OAuth — mobile**: native apps use `/oauth/:provider/mobile/auth-url` with a signed state persisted in `oauth_mobile_state_token` (10-minute TTL, single use).
791
+ - **OAuth — Apple (Sign in with Apple)**: no static `client_secret` — the `private_key` (EC `.p8` key) signs a `client_secret` JWT (ES256, `iss`=team ID, `sub`=Services ID, `kid`=key ID, short TTL) on each code exchange. Since scopes require `response_mode=form_post`, the callback is `POST /oauth/apple/callback` (a single URL, on the backend), converted to the same GET redirect used by the other providers. Identity comes from the `id_token` (decoded JWT, without signature verification — delivered directly by Apple in the server-to-server exchange); the name is only sent by Apple on the first authorization and is not captured, so the user's name falls back to the local part of the email.
792
+ - **OAuth — LinkedIn**: uses "Sign In with LinkedIn using OpenID Connect" (`scope=openid profile email`), with identity obtained in a single call to `GET /v2/userinfo` (standard OIDC claims), without the legacy pair of calls `/v2/me` + `/v2/emailAddress`.
793
+
794
+ ## 9. Quick usage guide (examples)
795
+
796
+ ### Create an AI agent
797
+
798
+ ```http
799
+ POST /ai/agent
800
+ Authorization: Bearer <token>
801
+ Content-Type: application/json
802
+
803
+ {
804
+ "slug": "my-agent",
805
+ "provider": "openai",
806
+ "model": "gpt-4o-mini",
807
+ "instructions": "Be a friendly assistant."
808
+ }
809
+ ```
810
+
811
+ Response:
812
+
813
+ ```json
814
+ {
815
+ "id": 1,
816
+ "slug": "my-agent",
817
+ "provider": "openai",
818
+ "model": "gpt-4o-mini",
819
+ "instructions": "Be a friendly assistant.",
820
+ "external_agent_id": "abc123",
821
+ "created_at": "2024-06-01T12:00:00Z",
822
+ "updated_at": "2024-06-01T12:00:00Z"
823
+ }
824
+ ```
825
+
826
+ ### Chat with an AI agent
827
+
828
+ ```http
829
+ POST /ai/agent/my-agent/chat
830
+ Authorization: Bearer <token>
831
+ Content-Type: multipart/form-data
832
+
833
+ Form-data:
834
+ - message: "Hi, how are you?"
835
+ - file: (optional file)
836
+ ```
837
+
838
+ Response:
839
+
840
+ ```json
841
+ {
842
+ "slug": "my-agent",
843
+ "provider": "openai",
844
+ "model": "gpt-4o-mini",
845
+ "content": "Hello! I'm doing well, thanks for asking."
846
+ }
847
+ ```
848
+
849
+ ### Login with email and password
850
+
851
+ ```http
852
+ POST /auth/login
853
+ Content-Type: application/json
854
+
855
+ {
856
+ "email": "user@example.com",
857
+ "password": "strongPassword123"
858
+ }
859
+ ```
860
+
861
+ Response:
862
+
863
+ ```json
864
+ {
865
+ "accessToken": "<jwt_access_token>",
866
+ "refreshToken": "<jwt_refresh_token>"
867
+ }
868
+ ```
869
+
870
+ ### OAuth login started by another app (multi-app hub)
871
+
872
+ An app other than the hub (e.g. `training`, key `training` in the `app-urls` setting) starts the login by redirecting the browser to:
873
+
874
+ ```http
875
+ GET /oauth/google/login?redirectApp=training
876
+ ```
877
+
878
+ The backend responds with a 302 `redirect` to Google's authorization URL, containing `state=hhweb.training.login.<signature>`. After consent, Google redirects to the single registered callback (`${url}/callback/google`, the hub). The hub reads the `state`, resolves `training` via `app-urls`, and forwards the browser to `${training-origin}/callback/google/login?code=...&state=...`. The `training` app then exchanges the code:
879
+
880
+ ```http
881
+ GET /oauth/google/callback/login?code=<code>&state=hhweb.training.login.<signature>
882
+ ```
883
+
884
+ Response:
885
+
886
+ ```json
887
+ {
888
+ "accessToken": "<jwt_access_token>"
889
+ }
890
+ ```
891
+
892
+ The `refreshToken` is set in the httpOnly `rt` cookie (it is not returned in the body, except when the call provides `redirectUri`, used by the mobile flow).
893
+
894
+ ### Get system information
895
+
896
+ ```http
897
+ GET /system
898
+ Authorization: Bearer <token>
899
+ ```
900
+
901
+ Response (abbreviated example):
902
+
903
+ ```json
904
+ {
905
+ "os": {
906
+ "name": "Linux",
907
+ "platform": "linux",
908
+ "version": "5.15.0",
909
+ "architecture": "x64",
910
+ "uptime": 123456,
911
+ "cpu": {
912
+ "model": "Intel(R) Xeon(R)",
913
+ "speed": 2400,
914
+ "physicalCores": 4,
915
+ "virtualCores": 8
916
+ },
917
+ "memory": {
918
+ "total": 17179869184,
919
+ "free": 8589934592
920
+ },
921
+ "disk": [
922
+ {
923
+ "filesystem": "/dev/sda1",
924
+ "size": 500107862016,
925
+ "free": 250053931008,
926
+ "mountpoint": "/"
927
+ }
928
+ ]
929
+ },
930
+ "modules": [
931
+ {
932
+ "name": "@hedhog/core",
933
+ "version": "^1.0.0",
934
+ "latestVersion": "1.0.1",
935
+ "upToDate": false
936
+ }
937
+ ],
938
+ "users": {
939
+ "total": 100,
940
+ "admin": 5,
941
+ "active": 80,
942
+ "activities": []
943
+ },
944
+ "database": {
945
+ "connections": 10,
946
+ "size": 104857600,
947
+ "queriesPerSecond": 50
948
+ }
949
+ }
950
+ ```
951
+
952
+ ---
953
+
954
+ This README documents the `@hed-hog/core` module based on the current source code and definitions, providing a detailed technical overview for developers and integrators of the system.