@hed-hog/core 0.0.373 → 0.0.375

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.
Files changed (109) hide show
  1. package/README.md +954 -873
  2. package/dist/integration-profile/integration-profile.secrets.d.ts.map +1 -1
  3. package/dist/integration-profile/integration-profile.secrets.js +4 -0
  4. package/dist/integration-profile/integration-profile.secrets.js.map +1 -1
  5. package/dist/integration-profile/integration-profile.utils.d.ts +6 -0
  6. package/dist/integration-profile/integration-profile.utils.d.ts.map +1 -1
  7. package/dist/integration-profile/integration-profile.utils.js +1 -1
  8. package/dist/integration-profile/integration-profile.utils.js.map +1 -1
  9. package/dist/oauth/oauth.controller.d.ts +11 -3
  10. package/dist/oauth/oauth.controller.d.ts.map +1 -1
  11. package/dist/oauth/oauth.controller.js +52 -14
  12. package/dist/oauth/oauth.controller.js.map +1 -1
  13. package/dist/oauth/oauth.module.d.ts.map +1 -1
  14. package/dist/oauth/oauth.module.js +4 -0
  15. package/dist/oauth/oauth.module.js.map +1 -1
  16. package/dist/oauth/oauth.service.d.ts +38 -2
  17. package/dist/oauth/oauth.service.d.ts.map +1 -1
  18. package/dist/oauth/oauth.service.js +122 -5
  19. package/dist/oauth/oauth.service.js.map +1 -1
  20. package/dist/oauth/providers/apple.provider.d.ts +34 -0
  21. package/dist/oauth/providers/apple.provider.d.ts.map +1 -0
  22. package/dist/oauth/providers/apple.provider.js +197 -0
  23. package/dist/oauth/providers/apple.provider.js.map +1 -0
  24. package/dist/oauth/providers/facebook.provider.d.ts +1 -1
  25. package/dist/oauth/providers/facebook.provider.d.ts.map +1 -1
  26. package/dist/oauth/providers/facebook.provider.js +3 -2
  27. package/dist/oauth/providers/facebook.provider.js.map +1 -1
  28. package/dist/oauth/providers/google.provider.d.ts +1 -1
  29. package/dist/oauth/providers/google.provider.d.ts.map +1 -1
  30. package/dist/oauth/providers/google.provider.js +3 -2
  31. package/dist/oauth/providers/google.provider.js.map +1 -1
  32. package/dist/oauth/providers/linkedin.provider.d.ts +25 -0
  33. package/dist/oauth/providers/linkedin.provider.d.ts.map +1 -0
  34. package/dist/oauth/providers/linkedin.provider.js +99 -0
  35. package/dist/oauth/providers/linkedin.provider.js.map +1 -0
  36. package/dist/oauth/providers/microsoft-entra-id.provider.js +1 -1
  37. package/dist/oauth/providers/microsoft-entra-id.provider.js.map +1 -1
  38. package/dist/oauth/providers/microsoft.provider.d.ts +1 -1
  39. package/dist/oauth/providers/microsoft.provider.d.ts.map +1 -1
  40. package/dist/oauth/providers/microsoft.provider.js +3 -2
  41. package/dist/oauth/providers/microsoft.provider.js.map +1 -1
  42. package/dist/pdf/pdf.service.d.ts.map +1 -1
  43. package/dist/pdf/pdf.service.js +19 -2
  44. package/dist/pdf/pdf.service.js.map +1 -1
  45. package/dist/setting/setting.service.d.ts.map +1 -1
  46. package/dist/setting/setting.service.js +4 -1
  47. package/dist/setting/setting.service.js.map +1 -1
  48. package/hedhog/data/integration_provider.yaml +16 -0
  49. package/hedhog/data/setting_group.yaml +98 -0
  50. package/hedhog/data/setting_subgroup.yaml +16 -0
  51. package/hedhog/frontend/app/configurations/[slug]/components/setting-field.tsx.ejs +2 -0
  52. package/hedhog/frontend/app/dashboard/dashboard.css.ejs +11 -11
  53. package/hedhog/frontend/app/integration/profiles/page.tsx.ejs +42 -0
  54. package/hedhog/frontend/app/menu/page.tsx.ejs +1 -1
  55. package/hedhog/frontend/app/users/user-sheet.tsx.ejs +8 -0
  56. package/hedhog/frontend/e2e/core.spec.ts.ejs +28 -0
  57. package/hedhog/frontend/messages/en.json +35 -0
  58. package/hedhog/frontend/messages/pt.json +35 -0
  59. package/hedhog/table/user_account.yaml +1 -0
  60. package/package.json +3 -3
  61. package/src/access-log/access-log.service.spec.ts +235 -0
  62. package/src/ai-instruction/ai-prompt-builder.service.spec.ts +250 -0
  63. package/src/auth/auth.service.spec.ts +891 -0
  64. package/src/auth/guards/auth.guard.spec.ts +177 -0
  65. package/src/challenge/challenge.service.spec.ts +334 -0
  66. package/src/dashboard/dashboard-core/dashboard-core.service.spec.ts +193 -0
  67. package/src/file/image-optimization.service.spec.ts +283 -0
  68. package/src/file/provider/provider.factory.spec.ts +111 -0
  69. package/src/install/install.service.spec.ts +139 -0
  70. package/src/integration/README.md +2 -0
  71. package/src/integration/services/event-subscriber.registry.spec.ts +143 -0
  72. package/src/integration/services/inbox.service.spec.ts +183 -0
  73. package/src/integration/services/integration-link.service.spec.ts +217 -0
  74. package/src/integration/services/outbox.service.spec.ts +290 -0
  75. package/src/integration-profile/integration-credential-crypto.service.spec.ts +289 -0
  76. package/src/integration-profile/integration-profile.secrets.ts +4 -0
  77. package/src/integration-profile/integration-profile.utils.spec.ts +332 -0
  78. package/src/integration-profile/integration-profile.utils.ts +14 -1
  79. package/src/locale/locale.service.spec.ts +78 -0
  80. package/src/mail/mail.service.spec.ts +257 -0
  81. package/src/mcp/guards/mcp-auth.guard.spec.ts +87 -0
  82. package/src/mcp/guards/mcp-permission.guard.spec.ts +64 -0
  83. package/src/mcp/mcp-api-key.service.spec.ts +125 -0
  84. package/src/mcp/mcp-registry.service.spec.ts +96 -0
  85. package/src/mcp/mcp-server.service.spec.ts +187 -0
  86. package/src/menu/menu.service.spec.ts +76 -0
  87. package/src/notification/notification.service.spec.ts +297 -0
  88. package/src/oauth/oauth.controller.ts +53 -10
  89. package/src/oauth/oauth.module.ts +4 -0
  90. package/src/oauth/oauth.service.spec.ts +332 -0
  91. package/src/oauth/oauth.service.ts +156 -1
  92. package/src/oauth/providers/apple.provider.ts +175 -0
  93. package/src/oauth/providers/facebook.provider.ts +3 -2
  94. package/src/oauth/providers/google.provider.ts +3 -2
  95. package/src/oauth/providers/linkedin.provider.ts +96 -0
  96. package/src/oauth/providers/microsoft-entra-id.provider.ts +1 -1
  97. package/src/oauth/providers/microsoft.provider.ts +3 -2
  98. package/src/pdf/pdf.service.ts +20 -2
  99. package/src/role/guards/role.guard.spec.ts +157 -0
  100. package/src/role/role.service.spec.ts +179 -0
  101. package/src/session/session.service.spec.ts +376 -0
  102. package/src/setting/setting.service.spec.ts +316 -0
  103. package/src/setting/setting.service.ts +4 -1
  104. package/src/task/task.service.spec.ts +47 -0
  105. package/src/token/token.service.spec.ts +351 -0
  106. package/src/user/user.service.spec.ts +256 -0
  107. package/src/utils/locale-context.spec.ts +22 -0
  108. package/src/utils/webauthn-origin.spec.ts +73 -0
  109. package/src/webhook-integration/integration-event-catalog.service.spec.ts +149 -0
package/README.md CHANGED
@@ -1,873 +1,954 @@
1
- ```markdown
2
- # @hed-hog/core
3
-
4
- > **Licença**: MIT (Open Source) — o Core é o único módulo Open Source do HedHog Framework; os demais módulos são Enterprise e requerem licença comercial. Consulte [LICENSE.md](./LICENSE.md).
5
-
6
- ## 1. Visão geral do módulo
7
-
8
- O módulo `@hed-hog/core` é o núcleo do monorepo HedHog, responsável por fornecer funcionalidades centrais essenciais para o sistema, incluindo autenticação, inteligência artificial, dashboard, sistema e gerenciamento de usuários, roles, permissões e componentes de interface. Ele integra diversos submódulos que tratam desde a segurança e autenticação até a gestão de dashboards customizáveis e agentes de IA.
9
-
10
- ## 2. Escopo e responsabilidades
11
-
12
- - Gerenciamento de autenticação e autorização, incluindo MFA, WebAuthn, recuperação de senha e sessões.
13
- - Serviços de inteligência artificial para chat e agentes AI com suporte a OpenAI e Gemini.
14
- - Gestão de dashboards, componentes, roles e usuários associados.
15
- - Informações do sistema operacional, hardware, banco de dados e módulos instalados.
16
- - Validação e manipulação de dados via DTOs e integração com Prisma ORM.
17
- - Suporte a internacionalização e paginação.
18
-
19
- ## 3. Endpoints
20
-
21
- ### Módulo AI (`/ai`)
22
-
23
- | Método | Path | Autenticação | Descrição | Parâmetros / Query / Body | Resposta | Erros Comuns |
24
- |--------|-------------------------|--------------|--------------------------------------------------|-------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------------------------|
25
- | POST | `/ai/chat` | Autenticada | Realiza chat com IA, podendo enviar arquivo. | Body: `ChatDTO` (message: string, provider?: 'openai'|'gemini', model?: string, systemPrompt?: string, file_id?: number)<br>File: opcional | `{ provider: string, model: string, content: string }` | 400: Chave API não configurada |
26
- | POST | `/ai/agent` | Autenticada | Cria um agente AI. | Body: `CreateAgentDTO` (slug: string, provider?: 'openai'|'gemini', model?: string, instructions?: string) | Objeto agente criado ou existente | 400: Slug já existe |
27
- | GET | `/ai/agent` | Autenticada | Lista agentes AI com paginação. | Query: paginação (page?: number, pageSize?: number, search?: string) | Paginação com lista de agentes | - |
28
- | GET | `/ai/agent/id/:agentId` | Autenticada | Obtém agente AI por ID. | Path param: `agentId` (int) | Objeto agente | 404: Agente não encontrado |
29
- | GET | `/ai/agent/:slug` | Autenticada | Obtém agente AI por slug. | Path param: `slug` (string) | Objeto agente | 404: Agente não encontrado |
30
- | PATCH | `/ai/agent/:agentId` | Autenticada | Atualiza agente AI. | Path param: `agentId` (int)<br>Body: `UpdateAgentDTO` (slug?: string, provider?: 'openai'|'gemini', model?: string, instructions?: string) | Objeto agente atualizado | 404: Agente não encontrado<br>400: Slug duplicado |
31
- | DELETE | `/ai/agent` | Autenticada | Deleta agentes AI em lote. | Body: `DeleteDTO` (ids: number[]) | `{ count: number }` | 404: Um ou mais agentes não encontrados |
32
- | POST | `/ai/agent/:slug/chat` | Autenticada | Chat com agente AI específico, com arquivo opcional. | Path param: `slug` (string)<br>Body: `ChatAgentDTO` (message: string, file_id?: number)<br>File: opcional | `{ slug: string, provider: string, model: string, content: string }` | 404: Agente não encontrado |
33
-
34
- ### Módulo Auth (`/auth`)
35
-
36
- | Método | Path | Autenticação | Descrição | Parâmetros / Body | Resposta | Erros Comuns |
37
- |--------|-------------------------------------|--------------|--------------------------------------------------|--------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------------------------|
38
- | GET | `/auth/verify` | Autenticada | Verifica usuário autenticado. | - | Dados do usuário autenticado | - |
39
- | GET | `/auth/roles` | Pública | Retorna roles do usuário (se autenticado). | - | `{ roles: string[] }` | - |
40
- | POST | `/auth/refresh` | Pública | Atualiza token de acesso usando refresh token. | Body: `{ refreshToken?: string }`<br>Cookies: `rt` opcional | `{ accessToken: string, refreshToken?: string }` | 400: Refresh token não fornecido |
41
- | POST | `/auth/login` | Pública | Login com email e senha. | Body: `LoginDTO` (email: string, password: string, refreshToken?: boolean) | Tokens de acesso e refresh ou MFA requerida | 400: Acesso negado |
42
- | POST | `/auth/login-email-verification` | Pública | Login via verificação por email e código. | Body: `LoginEmailVerificationDTO` (token: string, code: string) | Tokens de acesso e refresh | 400: Código inválido ou desafio não encontrado |
43
- | POST | `/auth/login-email-verification-resend` | Pública | Reenvia código de verificação por email. | Body: `LoginEmailVerificationResendDTO` (token: string) | Novo token para verificação | 400: Token inválido ou expirado |
44
- | POST | `/auth/signup` | Pública | Cadastro com email e senha. | Body: `CreateWithEmailAndPasswordDTO` | Usuário criado | - |
45
- | POST | `/auth/login-code` | Pública | Login com código MFA. | Body: `LoginWithCodeDTO` (token: string, code: string, methodType?: 'totp'|'email'|'recovery') | Tokens de acesso e refresh | 400: Código MFA inválido |
46
- | POST | `/auth/login-recovery-code` | Pública | Login com código de recuperação MFA. | Body: `LoginWithRecoveryCodeDTO` (token: string, code: string) | Tokens de acesso e refresh | 400: Código de recuperação inválido|
47
- | POST | `/auth/resend-mfa-code` | Pública | Reenvia código MFA por email. | Body: `ResendMfaCodeDTO` (token: string) | `{ success: true, hasEmailMfa: true }` | 400: Nenhum método MFA por email |
48
- | POST | `/auth/webauthn/generate` | Pública | Gera opções para autenticação WebAuthn. | Body: `{ mfaToken: string }` | Opções WebAuthn | 400: WebAuthn não configurado |
49
- | POST | `/auth/webauthn/verify` | Pública | Verifica autenticação WebAuthn. | Body: `{ mfaToken: string, assertionResponse: any }` | Tokens de acesso e refresh | 400: Verificação falhou |
50
- | POST | `/auth/forgot` | Pública | Solicita recuperação de senha via email. | Body: `ForgetDTO` (email: string) | `{ success: true }` | - |
51
- | POST | `/auth/logout` | Pública | Logout e invalida refresh token. | Body: `{ refreshToken?: string }`<br>Cookies: `rt` opcional | `{ success: true }` | 400: Refresh token não fornecido |
52
- | POST | `/auth/forgot-reset` | Pública | Reseta senha via código de recuperação. | Body: `ResetDTO` (password: string, code: string) | Tokens de acesso e refresh | 400: Código inválido ou expirado |
53
-
54
- ### Módulo System (`/system`)
55
-
56
- | Método | Path | Autenticação | Descrição | Parâmetros / Body | Resposta | Erros Comuns |
57
- |--------|------------|--------------|---------------------------------|-------------------|------------------------------------------------------------------------------------------|--------------|
58
- | GET | `/system` | Autenticada | Retorna informações do sistema. | - | Informações detalhadas do sistema operacional, hardware, banco de dados, módulos e usuários | - |
59
-
60
- ### Módulo Dashboard Core (`/dashboard-core`)
61
-
62
- | Método | Path | Autenticação | Descrição | Parâmetros / Body | Resposta | Erros Comuns |
63
- |--------|---------------------------|--------------|--------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------------------------|
64
- | GET | `/dashboard-core/home` | Autenticada | Retorna dashboard home do usuário. | - | Objeto dashboard ou null | 400: Usuário não encontrado |
65
- | GET | `/dashboard-core/stats/overview/users` | Autenticada | Estatísticas de usuários. | - | Estatísticas agregadas de usuários e sessões | - |
66
- | GET | `/dashboard-core/stats/overview/mails` | Autenticada | Estatísticas de emails enviados. | - | Estatísticas agregadas de emails enviados | - |
67
- | GET | `/dashboard-core/stats/overview/system` | Autenticada | Estatísticas do sistema (menus e rotas). | - | Estatísticas agregadas do sistema | - |
68
- | GET | `/dashboard-core/config/overview` | Autenticada | Visão geral das configurações do sistema. | - | Objeto com configurações | - |
69
- | GET | `/dashboard-core/widgets/me` | Autenticada | Dados dos widgets para o usuário. | - | Dados agregados para widgets do usuário | - |
70
- | GET | `/dashboard-core/user-dashboards` | Autenticada | Lista dashboards do usuário. | - | Lista de dashboards associados ao usuário | - |
71
- | GET | `/dashboard-core/templates` | Autenticada | Lista templates disponíveis para dashboards. | - | Lista de templates | - |
72
- | POST | `/dashboard-core/dashboard` | Autenticada | Cria dashboard para usuário. | Body: `{ name?: string; slug?: string; icon?: string | null; templateSlug?: string }` | Dashboard criado | - |
73
- | PATCH | `/dashboard-core/dashboard/order` | Autenticada | Reordena dashboards do usuário. | Body: `{ slugs?: string[] }` | Dashboard reordenado | - |
74
- | PATCH | `/dashboard-core/dashboard/:slug` | Autenticada | Renomeia dashboard do usuário. | Path param: `slug` (string)<br>Body: `{ name?: string; icon?: string | null }` | Dashboard atualizado | - |
75
- | POST | `/dashboard-core/dashboard/:slug/home` | Autenticada | Define dashboard como home do usuário. | Path param: `slug` (string) | Sucesso | - |
76
- | GET | `/dashboard-core/dashboard/:slug/shares` | Autenticada | Lista compartilhamentos do dashboard. | Path param: `slug` (string) | Lista de usuários com acesso | - |
77
- | GET | `/dashboard-core/shareable-users/:slug` | Autenticada | Lista usuários para compartilhar dashboard. | Path param: `slug` (string)<br>Query: search?: string, page?: string, pageSize?: string | Paginação de usuários | - |
78
- | POST | `/dashboard-core/dashboard/:slug/share` | Autenticada | Compartilha dashboard com usuários. | Path param: `slug` (string)<br>Body: `{ userId?: number; userIds?: number[] }` | Sucesso | - |
79
- | DELETE | `/dashboard-core/dashboard/:slug/share/:sharedUserId` | Autenticada | Revoga compartilhamento de dashboard. | Path params: `slug` (string), `sharedUserId` (int) | Sucesso | - |
80
- | DELETE | `/dashboard-core/dashboard/:slug` | Autenticada | Remove dashboard do usuário. | Path param: `slug` (string) | Sucesso | - |
81
- | GET | `/dashboard-core/access/:slug` | Autenticada | Verifica acesso do usuário a dashboard. | Path param: `slug` (string) | `{ hasAccess: boolean, dashboard: object|null }` | - |
82
- | GET | `/dashboard-core/layout/:slug` | Autenticada | Obtém layout do usuário para dashboard. | Path param: `slug` (string) | Array de widgets com posições e dimensões | - |
83
- | POST | `/dashboard-core/layout/:slug` | Autenticada | Salva layout do usuário para dashboard. | Body: `{ layout: Array<{ i: string; x: number; y: number; w: number; h: number }> }` | `{ success: true }` | 403: Acesso negado |
84
- | POST | `/dashboard-core/widget/:slug` | Autenticada | Adiciona widget ao dashboard do usuário. | Body: `{ componentSlug: string }` | Dados do widget adicionado | 403: Acesso negado |
85
- | DELETE | `/dashboard-core/widget/:slug/:widgetId` | Autenticada | Remove widget do dashboard do usuário. | Path params: `slug` (string), `widgetId` (string) | Erro "Not implemented yet" | - |
86
- | GET | `/dashboard-core/:slug` | Autenticada | Obtém itens do dashboard por slug. | Path param: `slug` (string), Query param: `locale?: string` | Lista de itens do dashboard | - |
87
-
88
- ### Módulo Dashboard (`/dashboard`)
89
-
90
- | Método | Path | Autenticação | Descrição | Parâmetros / Body | Resposta | Erros Comuns |
91
- |--------|----------------|--------------|-------------------------------|-------------------------------------------------------|------------------------------|----------------------------|
92
- | GET | `/dashboard` | Autenticada | Lista dashboards com paginação | Query: paginação (page?: number, pageSize?: number, search?: string) | Paginação com dashboards | - |
93
- | GET | `/dashboard/:id` | Autenticada | Obtém dashboard por ID | Path param: `id` (int) | Objeto dashboard | 404: Dashboard não encontrado |
94
- | POST | `/dashboard` | Autenticada | Cria dashboard | Body: `CreateDashboardDTO` (slug: string, locale: Record<string, { name: string }>) | Dashboard criado | - |
95
- | PATCH | `/dashboard/:id` | Autenticada | Atualiza dashboard | Path param: `id` (int), Body: `UpdateDashboardDTO` | Dashboard atualizado | 404: Dashboard não encontrado |
96
- | DELETE | `/dashboard/:id` | Autenticada | Deleta dashboard | Path param: `id` (int) | `{ success: true }` | 404: Dashboard não encontrado |
97
-
98
- ### Módulo Dashboard Component (`/dashboard-component`)
99
-
100
- | Método | Path | Autenticação | Descrição | Parâmetros / Body | Resposta | Erros Comuns |
101
- |--------|------------------------|--------------|-------------------------------|----------------------------------------------------------------|------------------------------|-------------------------------|
102
- | GET | `/dashboard-component` | Autenticada | Lista componentes com paginação | Query: paginação (page?: number, pageSize?: number, search?: string) | Paginação com componentes | - |
103
- | GET | `/dashboard-component/user` | Autenticada | Lista componentes por roles do usuário | Query: paginação (page?: number, pageSize?: number, search?: string), User ID via token | Paginação com componentes | - |
104
- | GET | `/dashboard-component/:id` | Autenticada | Obtém componente por ID | Path param: `id` (int) | Objeto componente | 404: Componente não encontrado |
105
- | POST | `/dashboard-component` | Autenticada | Cria componente | Body: `CreateDashboardComponentDTO` | Componente criado | - |
106
- | PATCH | `/dashboard-component/:id` | Autenticada | Atualiza componente | Path param: `id` (int), Body: `UpdateDashboardComponentDTO` | Componente atualizado | 404: Componente não encontrado |
107
- | DELETE | `/dashboard-component/:id` | Autenticada | Deleta componente | Path param: `id` (int) | `{ success: true }` | 404: Componente não encontrado |
108
- | POST | `/dashboard-component/:id/preview` | Autenticada | Salva preview de componente (imagem) | Path param: `id` (int), File: imagem (image/*) | `{ success: true, componentId: number, slug: string, library_slug: string, fileName: string, relativeUrl: string }` | 400: Arquivo inválido<br>403: Apenas em dev |
109
-
110
- ### Módulo Dashboard Component Role (`/dashboard-component-role`)
111
-
112
- | Método | Path | Autenticação | Descrição | Parâmetros / Body | Resposta | Erros Comuns |
113
- |--------|-------------------------------|--------------|-----------------------------------|----------------------------------------------------------------|------------------------------|-------------------------------|
114
- | GET | `/dashboard-component-role` | Autenticada | Lista relações com paginação ou por componente | Query: paginação (page?: number, pageSize?: number), Query param: componentId?: number | Paginação ou lista de relações | - |
115
- | POST | `/dashboard-component-role` | Autenticada | Cria relação componente-role | Body: `CreateDashboardComponentRoleDTO` | Relação criada | Erro se relação já existe |
116
- | POST | `/dashboard-component-role/batch` | Autenticada | Cria relações em lote | Body: `CreateDashboardComponentRoleBatchDTO` | { success: boolean, created: number, skipped: number, message: string } | - |
117
- | DELETE | `/dashboard-component-role/:id` | Autenticada | Deleta relação por ID | Path param: `id` (int) | `{ success: true }` | 404: Relação não encontrada |
118
- | DELETE | `/dashboard-component-role/component/:componentId/role/:roleId` | Autenticada | Deleta relação por componente e role | Path params: `componentId` (int), `roleId` (int) | `{ success: true }` | 404: Relação não encontrada |
119
-
120
- ### Módulo Dashboard Item (`/dashboard-item`)
121
-
122
- | Método | Path | Autenticação | Descrição | Parâmetros / Body | Resposta | Erros Comuns |
123
- |--------|--------------------|--------------|-------------------------------|----------------------------------------------------------------|------------------------------|-------------------------------|
124
- | GET | `/dashboard-item` | Autenticada | Lista itens com paginação e filtro por dashboard | Query: paginação (page?: number, pageSize?: number), Query param: dashboardId?: number | Paginação com itens | - |
125
- | POST | `/dashboard-item` | Autenticada | Cria item | Body: `CreateDashboardItemDTO` | Item criado | - |
126
- | DELETE | `/dashboard-item/:id` | Autenticada | Deleta item por ID | Path param: `id` (int) | `{ success: true }` | 404: Item não encontrado |
127
-
128
- ### Módulo Dashboard Role (`/dashboard-role`)
129
-
130
- | Método | Path | Autenticação | Descrição | Parâmetros / Body | Resposta | Erros Comuns |
131
- |--------|--------------------|--------------|-----------------------------------|----------------------------------------------------------------|------------------------------|-------------------------------|
132
- | GET | `/dashboard-role` | Autenticada | Lista relações com paginação ou por dashboard | Query: paginação (page?: number, pageSize?: number), Query param: dashboardId?: number | Paginação ou lista de relações | - |
133
- | POST | `/dashboard-role` | Autenticada | Cria relação dashboard-role | Body: `CreateDashboardRoleDTO` | Relação criada | Erro se relação já existe |
134
- | POST | `/dashboard-role/batch` | Autenticada | Cria relações em lote | Body: `CreateDashboardRoleBatchDTO` | { success: boolean, created: number, skipped: number, message: string } | - |
135
- | DELETE | `/dashboard-role/:id` | Autenticada | Deleta relação por ID | Path param: `id` (int) | `{ success: true }` | 404: Relação não encontrada |
136
- | DELETE | `/dashboard-role/dashboard/:dashboardId/role/:roleId` | Autenticada | Deleta relação por dashboard e role | Path params: `dashboardId` (int), `roleId` (int) | `{ success: true }` | 404: Relação não encontrada |
137
-
138
- ### Módulo Dashboard User (`/dashboard-user`)
139
-
140
- | Método | Path | Autenticação | Descrição | Parâmetros / Body | Resposta | Erros Comuns |
141
- |--------|--------------------|--------------|-------------------------------|----------------------------------------------------------------|------------------------------|-------------------------------|
142
- | GET | `/dashboard-user` | Autenticada | Lista relações com paginação | Query: paginação (page?: number, pageSize?: number) | Paginação com relações | - |
143
- | GET | `/dashboard-user/:id` | Autenticada | Obtém relação por ID | Path param: `id` (int) | Objeto relação | - |
144
- | POST | `/dashboard-user` | Autenticada | Cria relação | Body: `CreateDTO` (dashboard_id: number, user_id: number) | Relação criada | - |
145
- | PATCH | `/dashboard-user/:id` | Autenticada | Atualiza relação | Path param: `id` (int), Body: `UpdateDTO` | Relação atualizada | - |
146
- | DELETE | `/dashboard-user` | Autenticada | Deleta relações em lote | Body: `DeleteDTO` (ids: number[]) | `{ count: number }` | 400: Nenhum id fornecido |
147
-
148
- ## 4. Regras de autenticação e autorização
149
-
150
- - A maioria dos endpoints requer autenticação via token JWT.
151
- - Endpoints públicos são indicados explicitamente.
152
- - Controle de acesso baseado em roles e permissões.
153
- - MFA (Multi-Factor Authentication) suportado via TOTP, email e códigos de recuperação.
154
- - WebAuthn suportado para autenticação forte.
155
- - Refresh tokens são gerenciados via cookies HTTP-only ou no corpo da requisição.
156
- - Operações sensíveis (criação, atualização, deleção) requerem autenticação e permissões adequadas.
157
-
158
- ## 5. Estruturas de request/response
159
-
160
- ### DTOs principais do módulo AI
161
-
162
- - **ChatDTO**
163
-
164
- ```ts
165
- {
166
- message: string; // obrigatório
167
- provider?: 'openai' | 'gemini'; // opcional, padrão 'openai'
168
- model?: string; // opcional
169
- systemPrompt?: string; // opcional
170
- file_id?: number; // opcional
171
- }
172
- ```
173
-
174
- - **ChatAgentDTO**
175
-
176
- ```ts
177
- {
178
- message: string; // obrigatório
179
- file_id?: number; // opcional
180
- }
181
- ```
182
-
183
- - **CreateAgentDTO**
184
-
185
- ```ts
186
- {
187
- slug: string; // obrigatório
188
- provider?: 'openai' | 'gemini'; // opcional, padrão 'openai'
189
- model?: string; // opcional
190
- instructions?: string; // opcional
191
- }
192
- ```
193
-
194
- - **UpdateAgentDTO**
195
-
196
- ```ts
197
- {
198
- slug?: string;
199
- provider?: 'openai' | 'gemini';
200
- model?: string;
201
- instructions?: string;
202
- }
203
- ```
204
-
205
- - **DeleteDTO**
206
-
207
- ```ts
208
- {
209
- ids: number[]; // array de IDs para deleção, mínimo 1 item
210
- }
211
- ```
212
-
213
- ### DTOs principais do módulo Auth
214
-
215
- - **LoginDTO**
216
-
217
- ```ts
218
- {
219
- email: string; // obrigatório, email válido
220
- password: string; // obrigatório, senha forte mínima 6 caracteres
221
- refreshToken?: boolean; // opcional, padrão false
222
- }
223
- ```
224
-
225
- - **LoginEmailVerificationDTO**
226
-
227
- ```ts
228
- {
229
- token: string; // obrigatório
230
- code: string; // obrigatório, código PIN
231
- }
232
- ```
233
-
234
- - **LoginEmailVerificationResendDTO**
235
-
236
- ```ts
237
- {
238
- token: string; // obrigatório
239
- }
240
- ```
241
-
242
- - **LoginWithCodeDTO**
243
-
244
- ```ts
245
- {
246
- code: string; // obrigatório
247
- token: string; // obrigatório, JWT
248
- methodType?: 'totp' | 'email' | 'recovery'; // opcional
249
- }
250
- ```
251
-
252
- - **LoginWithRecoveryCodeDTO**
253
-
254
- ```ts
255
- {
256
- code: string; // obrigatório
257
- token: string; // obrigatório, JWT
258
- }
259
- ```
260
-
261
- - **ForgetDTO**
262
-
263
- ```ts
264
- {
265
- email: string; // obrigatório, email válido
266
- }
267
- ```
268
-
269
- - **ResetDTO**
270
-
271
- ```ts
272
- {
273
- password: string; // obrigatório, mínimo 8 caracteres
274
- code: string; // obrigatório
275
- }
276
- ```
277
-
278
- ### DTOs principais do módulo Dashboard
279
-
280
- - **CreateDashboardDTO**
281
-
282
- ```ts
283
- {
284
- slug: string; // obrigatório
285
- locale: Record<string, { name: string }>; // obrigatório
286
- }
287
- ```
288
-
289
- - **UpdateDashboardDTO**
290
-
291
- ```ts
292
- {
293
- slug?: string;
294
- locale?: Record<string, { name: string }>;
295
- }
296
- ```
297
-
298
- - **CreateDashboardComponentDTO**
299
-
300
- ```ts
301
- {
302
- slug: string;
303
- library_slug?: string;
304
- min_width?: number;
305
- max_width?: number;
306
- min_height?: number;
307
- max_height?: number;
308
- width: number;
309
- height: number;
310
- is_resizable?: boolean;
311
- locale: Record<string, { name: string; description?: string }>;
312
- }
313
- ```
314
-
315
- - **UpdateDashboardComponentDTO**
316
-
317
- ```ts
318
- {
319
- slug?: string;
320
- library_slug?: string;
321
- min_width?: number;
322
- max_width?: number;
323
- min_height?: number;
324
- max_height?: number;
325
- width?: number;
326
- height?: number;
327
- is_resizable?: boolean;
328
- locale?: Record<string, { name: string; description?: string }>;
329
- }
330
- ```
331
-
332
- - **CreateDashboardRoleDTO**
333
-
334
- ```ts
335
- {
336
- dashboard_id: number;
337
- role_id: number;
338
- }
339
- ```
340
-
341
- - **CreateDashboardRoleBatchDTO**
342
-
343
- ```ts
344
- {
345
- dashboard_id: number;
346
- role_ids: number[];
347
- }
348
- ```
349
-
350
- - **CreateDashboardComponentRoleDTO**
351
-
352
- ```ts
353
- {
354
- component_id: number;
355
- role_id: number;
356
- }
357
- ```
358
-
359
- - **CreateDashboardComponentRoleBatchDTO**
360
-
361
- ```ts
362
- {
363
- component_id: number;
364
- role_ids: number[];
365
- }
366
- ```
367
-
368
- - **CreateDashboardItemDTO**
369
-
370
- ```ts
371
- {
372
- component_id: number;
373
- dashboard_id: number;
374
- width: number;
375
- height: number;
376
- x_axis: number;
377
- y_axis: number;
378
- }
379
- ```
380
-
381
- - **UpdateDashboardLayoutDTO**
382
-
383
- ```ts
384
- {
385
- dashboard_id: number;
386
- items: Array<{
387
- id: number;
388
- width: number;
389
- height: number;
390
- x_axis: number;
391
- y_axis: number;
392
- }>;
393
- }
394
- ```
395
-
396
- - **UpdateDashboardItemDTO**
397
-
398
- ```ts
399
- {
400
- component_id?: number;
401
- dashboard_id?: number;
402
- width?: number;
403
- height?: number;
404
- x_axis?: number;
405
- y_axis?: number;
406
- }
407
- ```
408
-
409
- - **CreateDTO (DashboardUser)**
410
-
411
- ```ts
412
- {
413
- dashboard_id: number;
414
- user_id: number;
415
- }
416
- ```
417
-
418
- - **UpdateDTO (DashboardUser)**
419
-
420
- ```ts
421
- {
422
- dashboard_id?: number;
423
- user_id?: number;
424
- }
425
- ```
426
-
427
- - **DeleteDTO**
428
-
429
- ```ts
430
- {
431
- ids: number[];
432
- }
433
- ```
434
-
435
- ## 6. Erros comuns
436
-
437
- - **400 Bad Request**
438
-
439
- - Chave API não configurada para OpenAI ou Gemini.
440
- - Slug de agente AI já existente.
441
- - Código de verificação inválido ou expirado.
442
- - Refresh token não fornecido.
443
- - Acesso negado por credenciais inválidas.
444
- - MFA não configurado ou código inválido.
445
- - Tentativa de deletar itens inexistentes.
446
- - Requisição inválida para criação de relações duplicadas.
447
- - Arquivo inválido para preview de componente.
448
- - Operação de preview disponível somente em ambiente de desenvolvimento.
449
-
450
- - **404 Not Found**
451
-
452
- - Agente AI não encontrado por ID ou slug.
453
- - Dashboard, componente ou relação não encontrada.
454
- - Desafio (challenge) para verificação não encontrado ou expirado.
455
-
456
- - **403 Forbidden**
457
-
458
- - Acesso negado a dashboards ou recursos protegidos.
459
- - Tentativa de salvar preview fora do ambiente de desenvolvimento.
460
-
461
- ## 7. Banco de dados (tabelas YAML)
462
-
463
- ### ai_agent
464
-
465
- ```yaml
466
- finalidade: Armazena agentes de inteligência artificial configurados no sistema.
467
- colunas:
468
- - id: integer, PK, auto-increment
469
- - slug: string, único, não nulo
470
- - provider: enum('openai', 'gemini'), não nulo
471
- - model: string, nullable
472
- - instructions: string, nullable
473
- - external_agent_id: string, nullable
474
- - created_at: timestamp, não nulo, default NOW()
475
- - updated_at: timestamp, não nulo, default NOW()
476
- defaults:
477
- - created_at: NOW()
478
- - updated_at: NOW()
479
- nulabilidade:
480
- - model: nullable
481
- - instructions: nullable
482
- - external_agent_id: nullable
483
- integridade:
484
- - slug único
485
- indices:
486
- - id (PK)
487
- - slug (único)
488
- enums:
489
- - provider: ['openai', 'gemini']
490
- ```
491
-
492
- ### user
493
-
494
- ```yaml
495
- finalidade: Armazena usuários do sistema.
496
- colunas:
497
- - id: integer, PK, auto-increment
498
- - name: string, não nulo
499
- - photo_id: integer, nullable
500
- - last_login_at: timestamp, nullable
501
- - created_at: timestamp, não nulo, default NOW()
502
- - updated_at: timestamp, não nulo, default NOW()
503
- integridade:
504
- - PK em id
505
- indices:
506
- - id (PK)
507
- ```
508
-
509
- ### user_mfa
510
-
511
- ```yaml
512
- finalidade: Armazena métodos de autenticação multifator dos usuários.
513
- colunas:
514
- - id: integer, PK, auto-increment
515
- - user_id: integer, FK para user.id, não nulo
516
- - name: string, não nulo
517
- - type: enum('totp', 'email', 'webauthn'), não nulo
518
- - verified_at: timestamp, nullable
519
- - suspended_until: timestamp, nullable
520
- - created_at: timestamp, não nulo, default NOW()
521
- - updated_at: timestamp, não nulo, default NOW()
522
- integridade:
523
- - FK user_id referencia user.id
524
- indices:
525
- - id (PK)
526
- enums:
527
- - type: ['totp', 'email', 'webauthn']
528
- ```
529
-
530
- ### user_identifier
531
-
532
- ```yaml
533
- finalidade: Identificadores do usuário, como emails.
534
- colunas:
535
- - id: integer, PK, auto-increment
536
- - user_id: integer, FK para user.id, não nulo
537
- - type: string, não nulo (ex: 'email')
538
- - value: string, não nulo
539
- - verified_at: timestamp, nullable
540
- - enabled: boolean, não nulo, default true
541
- - created_at: timestamp, não nulo, default NOW()
542
- - updated_at: timestamp, não nulo, default NOW()
543
- integridade:
544
- - FK user_id referencia user.id
545
- indices:
546
- - id (PK)
547
- ```
548
-
549
- ### user_session
550
-
551
- ```yaml
552
- finalidade: Sessões de usuários autenticados.
553
- colunas:
554
- - id: integer, PK, auto-increment
555
- - user_id: integer, FK para user.id, não nulo
556
- - token: string, não nulo
557
- - ip_address: string, nullable
558
- - user_agent: string, nullable
559
- - created_at: timestamp, não nulo, default NOW()
560
- - expires_at: timestamp, não nulo
561
- - revoked_at: timestamp, nullable
562
- integridade:
563
- - FK user_id referencia user.id
564
- indices:
565
- - id (PK)
566
- ```
567
-
568
- ### user_activity
569
-
570
- ```yaml
571
- finalidade: Registro de atividades dos usuários.
572
- colunas:
573
- - id: integer, PK, auto-increment
574
- - user_id: integer, FK para user.id, não nulo
575
- - action: string, não nulo
576
- - created_at: timestamp, não nulo, default NOW()
577
- integridade:
578
- - FK user_id referencia user.id
579
- indices:
580
- - id (PK)
581
- ```
582
-
583
- ### role
584
-
585
- ```yaml
586
- finalidade: Papéis (roles) do sistema para controle de acesso.
587
- colunas:
588
- - id: integer, PK, auto-increment
589
- - slug: string, único, não nulo
590
- - created_at: timestamp, não nulo, default NOW()
591
- - updated_at: timestamp, não nulo, default NOW()
592
- integridade:
593
- - slug único
594
- indices:
595
- - id (PK)
596
- - slug (único)
597
- ```
598
-
599
- ### role_user
600
-
601
- ```yaml
602
- finalidade: Relação muitos-para-muitos entre usuários e roles.
603
- colunas:
604
- - id: integer, PK, auto-increment
605
- - user_id: integer, FK para user.id, não nulo
606
- - role_id: integer, FK para role.id, não nulo
607
- integridade:
608
- - FK user_id referencia user.id
609
- - FK role_id referencia role.id
610
- indices:
611
- - id (PK)
612
- ```
613
-
614
- ### dashboard
615
-
616
- ```yaml
617
- finalidade: Dashboards configuráveis do sistema.
618
- colunas:
619
- - id: integer, PK, auto-increment
620
- - slug: string, único, não nulo
621
- - created_at: timestamp, não nulo, default NOW()
622
- - updated_at: timestamp, não nulo, default NOW()
623
- integridade:
624
- - slug único
625
- indices:
626
- - id (PK)
627
- - slug (único)
628
- ```
629
-
630
- ### dashboard_component
631
-
632
- ```yaml
633
- finalidade: Componentes que podem ser usados em dashboards.
634
- colunas:
635
- - id: integer, PK, auto-increment
636
- - slug: string, único, não nulo
637
- - library_slug: string, nullable
638
- - min_width: integer, nullable
639
- - max_width: integer, nullable
640
- - min_height: integer, nullable
641
- - max_height: integer, nullable
642
- - width: integer, não nulo
643
- - height: integer, não nulo
644
- - is_resizable: boolean, não nulo, default true
645
- - created_at: timestamp, não nulo, default NOW()
646
- - updated_at: timestamp, não nulo, default NOW()
647
- integridade:
648
- - slug único
649
- indices:
650
- - id (PK)
651
- - slug (único)
652
- ```
653
-
654
- ### dashboard_role
655
-
656
- ```yaml
657
- finalidade: Relação entre dashboards e roles para controle de acesso.
658
- colunas:
659
- - id: integer, PK, auto-increment
660
- - dashboard_id: integer, FK para dashboard.id, não nulo
661
- - role_id: integer, FK para role.id, não nulo
662
- integridade:
663
- - FK dashboard_id referencia dashboard.id
664
- - FK role_id referencia role.id
665
- indices:
666
- - id (PK)
667
- ```
668
-
669
- ### dashboard_user
670
-
671
- ```yaml
672
- finalidade: Relação entre dashboards e usuários.
673
- colunas:
674
- - id: integer, PK, auto-increment
675
- - dashboard_id: integer, FK para dashboard.id, não nulo
676
- - user_id: integer, FK para user.id, não nulo
677
- - is_home: boolean, não nulo, default false
678
- integridade:
679
- - FK dashboard_id referencia dashboard.id
680
- - FK user_id referencia user.id
681
- indices:
682
- - id (PK)
683
- ```
684
-
685
- ### dashboard_item
686
-
687
- ```yaml
688
- finalidade: Itens (widgets) dentro de dashboards.
689
- colunas:
690
- - id: integer, PK, auto-increment
691
- - dashboard_id: integer, FK para dashboard.id, não nulo
692
- - component_id: integer, FK para dashboard_component.id, não nulo
693
- - width: integer, não nulo
694
- - height: integer, não nulo
695
- - x_axis: integer, não nulo
696
- - y_axis: integer, não nulo
697
- integridade:
698
- - FK dashboard_id referencia dashboard.id
699
- - FK component_id referencia dashboard_component.id
700
- indices:
701
- - id (PK)
702
- ```
703
-
704
- ### dashboard_component_role
705
-
706
- ```yaml
707
- finalidade: Relação entre componentes de dashboard e roles.
708
- colunas:
709
- - id: integer, PK, auto-increment
710
- - component_id: integer, FK para dashboard_component.id, não nulo
711
- - role_id: integer, FK para role.id, não nulo
712
- integridade:
713
- - FK component_id referencia dashboard_component.id
714
- - FK role_id referencia role.id
715
- indices:
716
- - id (PK)
717
- ```
718
-
719
- ## 8. Regras de negócio relevantes
720
-
721
- - Agentes AI podem ser criados, atualizados e deletados, com integração direta com APIs OpenAI e Gemini.
722
- - Chat com IA suporta anexos de arquivos, com extração de texto para PDFs e arquivos de texto.
723
- - MFA obrigatório pode ser configurado, com suporte a email, TOTP e WebAuthn.
724
- - Tokens de acesso e refresh são gerenciados com segurança, incluindo cookies HTTP-only.
725
- - Dashboards são personalizados por usuário, com controle de acesso baseado em roles.
726
- - Layouts de dashboards e widgets podem ser salvos e recuperados por usuário.
727
- - Sistema coleta estatísticas de uso, sessões, emails enviados e segurança da conta.
728
- - Validações rigorosas são aplicadas via DTOs e classes de validação.
729
- - Operações de criação em batch evitam duplicações e retornam contagem de criados e ignorados.
730
- - A remoção de widgets do dashboard do usuário ainda não está implementada.
731
- - Preview de componentes de dashboard é permitido somente em ambiente de desenvolvimento e aceita apenas imagens.
732
- - MFA via email envia códigos para múltiplos emails associados ao usuário.
733
- - WebAuthn é suportado para autenticação forte com geração e verificação de desafios.
734
-
735
- ## 9. Guia rápido de uso (exemplos)
736
-
737
- ### Criar agente AI
738
-
739
- ```http
740
- POST /ai/agent
741
- Authorization: Bearer <token>
742
- Content-Type: application/json
743
-
744
- {
745
- "slug": "meu-agente",
746
- "provider": "openai",
747
- "model": "gpt-4o-mini",
748
- "instructions": "Seja um assistente amigável."
749
- }
750
- ```
751
-
752
- Resposta:
753
-
754
- ```json
755
- {
756
- "id": 1,
757
- "slug": "meu-agente",
758
- "provider": "openai",
759
- "model": "gpt-4o-mini",
760
- "instructions": "Seja um assistente amigável.",
761
- "external_agent_id": "abc123",
762
- "created_at": "2024-06-01T12:00:00Z",
763
- "updated_at": "2024-06-01T12:00:00Z"
764
- }
765
- ```
766
-
767
- ### Chat com agente AI
768
-
769
- ```http
770
- POST /ai/agent/meu-agente/chat
771
- Authorization: Bearer <token>
772
- Content-Type: multipart/form-data
773
-
774
- Form-data:
775
- - message: "Olá, como você está?"
776
- - file: (arquivo opcional)
777
- ```
778
-
779
- Resposta:
780
-
781
- ```json
782
- {
783
- "slug": "meu-agente",
784
- "provider": "openai",
785
- "model": "gpt-4o-mini",
786
- "content": "Olá! Estou bem, obrigado por perguntar."
787
- }
788
- ```
789
-
790
- ### Login com email e senha
791
-
792
- ```http
793
- POST /auth/login
794
- Content-Type: application/json
795
-
796
- {
797
- "email": "usuario@exemplo.com",
798
- "password": "senhaSegura123"
799
- }
800
- ```
801
-
802
- Resposta:
803
-
804
- ```json
805
- {
806
- "accessToken": "<jwt_access_token>",
807
- "refreshToken": "<jwt_refresh_token>"
808
- }
809
- ```
810
-
811
- ### Obter informações do sistema
812
-
813
- ```http
814
- GET /system
815
- Authorization: Bearer <token>
816
- ```
817
-
818
- Resposta (exemplo resumido):
819
-
820
- ```json
821
- {
822
- "os": {
823
- "name": "Linux",
824
- "platform": "linux",
825
- "version": "5.15.0",
826
- "architecture": "x64",
827
- "uptime": 123456,
828
- "cpu": {
829
- "model": "Intel(R) Xeon(R)",
830
- "speed": 2400,
831
- "physicalCores": 4,
832
- "virtualCores": 8
833
- },
834
- "memory": {
835
- "total": 17179869184,
836
- "free": 8589934592
837
- },
838
- "disk": [
839
- {
840
- "filesystem": "/dev/sda1",
841
- "size": 500107862016,
842
- "free": 250053931008,
843
- "mountpoint": "/"
844
- }
845
- ]
846
- },
847
- "modules": [
848
- {
849
- "name": "@hedhog/core",
850
- "version": "^1.0.0",
851
- "latestVersion": "1.0.1",
852
- "upToDate": false
853
- }
854
- ],
855
- "users": {
856
- "total": 100,
857
- "admin": 5,
858
- "active": 80,
859
- "activities": []
860
- },
861
- "database": {
862
- "connections": 10,
863
- "size": 104857600,
864
- "queriesPerSecond": 50
865
- }
866
- }
867
- ```
868
-
869
- ---
870
-
871
- Este README documenta o módulo `@hed-hog/core` com base no código-fonte e definições atuais, fornecendo uma visão técnica detalhada para desenvolvedores e integradores do sistema.
872
-
873
- ```
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.