forjajs 5.0.0 → 5.1.0

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 (171) hide show
  1. package/CHANGELOG.md +68 -2
  2. package/README.md +4 -2
  3. package/README.pt-BR.md +4 -1
  4. package/boilerplates/02-saas-starter/README.md +58 -293
  5. package/boilerplates/02-saas-starter/backend/.env.example +13 -0
  6. package/boilerplates/02-saas-starter/backend/.oxlintrc.json +8 -0
  7. package/boilerplates/02-saas-starter/backend/nest-cli.json +6 -0
  8. package/boilerplates/02-saas-starter/backend/package.json +32 -73
  9. package/boilerplates/02-saas-starter/backend/src/app.module.ts +16 -16
  10. package/boilerplates/02-saas-starter/backend/src/billing/adapters/http/billing.controller.ts +55 -0
  11. package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/orm-entities.ts +28 -0
  12. package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/typeorm-billing.repository.ts +46 -0
  13. package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.spec.ts +58 -0
  14. package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.ts +68 -0
  15. package/boilerplates/02-saas-starter/backend/src/billing/billing.module.ts +11 -0
  16. package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.spec.ts +23 -0
  17. package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.ts +36 -0
  18. package/boilerplates/02-saas-starter/backend/src/billing/domain/ports.ts +27 -0
  19. package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.spec.ts +28 -0
  20. package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.ts +47 -0
  21. package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/auth.dto.ts +22 -0
  22. package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/identity.controller.ts +59 -0
  23. package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/orm-entities.ts +25 -0
  24. package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/typeorm-identity.repository.ts +47 -0
  25. package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.spec.ts +72 -0
  26. package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.ts +63 -0
  27. package/boilerplates/02-saas-starter/backend/src/identity/domain/model.spec.ts +19 -0
  28. package/boilerplates/02-saas-starter/backend/src/identity/domain/model.ts +42 -0
  29. package/boilerplates/02-saas-starter/backend/src/identity/domain/password.spec.ts +17 -0
  30. package/boilerplates/02-saas-starter/backend/src/identity/domain/password.ts +26 -0
  31. package/boilerplates/02-saas-starter/backend/src/identity/identity.module.ts +12 -0
  32. package/boilerplates/02-saas-starter/backend/src/main.ts +19 -19
  33. package/boilerplates/02-saas-starter/backend/src/platform/auth/jwt-auth.guard.ts +17 -0
  34. package/boilerplates/02-saas-starter/backend/src/platform/auth/principal.ts +22 -0
  35. package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.spec.ts +23 -0
  36. package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.ts +20 -0
  37. package/boilerplates/02-saas-starter/backend/src/platform/auth/token.service.ts +54 -0
  38. package/boilerplates/02-saas-starter/backend/src/platform/config.spec.ts +18 -0
  39. package/boilerplates/02-saas-starter/backend/src/platform/config.ts +33 -0
  40. package/boilerplates/02-saas-starter/backend/src/platform/platform.module.ts +14 -0
  41. package/boilerplates/02-saas-starter/backend/tsconfig.build.json +6 -0
  42. package/boilerplates/02-saas-starter/backend/tsconfig.json +16 -21
  43. package/boilerplates/02-saas-starter/backend/vitest.config.ts +7 -0
  44. package/boilerplates/02-saas-starter/boilerplate.manifest.json +19 -14
  45. package/boilerplates/02-saas-starter/docker-compose.yml +10 -24
  46. package/boilerplates/02-saas-starter/memory/30-domains/billing/context.md +15 -132
  47. package/boilerplates/02-saas-starter/memory/30-domains/identity/context.md +20 -0
  48. package/boilerplates/README.md +9 -10
  49. package/dist/bin/create-memory-nest-kit.js +0 -0
  50. package/dist/bin/forja.js +0 -0
  51. package/dist/bin/init-project.js +1 -0
  52. package/dist/lib/core/journey.js +10 -0
  53. package/dist/lib/generators/memory-generator.d.ts +0 -11
  54. package/dist/lib/generators/memory-generator.js +5 -161
  55. package/dist/lib/generators/readme-generator.js +1 -1
  56. package/dist/lib/llm/json-output.d.ts +14 -0
  57. package/dist/lib/llm/json-output.js +77 -0
  58. package/dist/lib/project-upgrade.d.ts +0 -4
  59. package/dist/lib/project-upgrade.js +19 -1
  60. package/dist/lib/project-wiring.d.ts +8 -0
  61. package/dist/lib/project-wiring.js +74 -2
  62. package/dist/lib/validators/structure-validator.js +0 -1
  63. package/dist/packages/llm/src/index.js +12 -2
  64. package/dist/scripts/llm-fit.js +23 -1
  65. package/dist/scripts/project-upgrade.js +9 -6
  66. package/docs/init-project.md +1 -1
  67. package/docs/llm-fit-loop.md +16 -0
  68. package/memory/90-decisions/0086-projeto-conectado-e-jornada-como-gate.md +1 -1
  69. package/memory/90-decisions/0088-templates-validados.md +3 -0
  70. package/memory/90-decisions/0089-skills-do-projeto.md +51 -0
  71. package/memory/90-decisions/0090-adapters-de-agente-somente-leitura.md +47 -0
  72. package/package.json +2 -2
  73. package/specs/skills-do-projeto/plan.md +40 -0
  74. package/specs/skills-do-projeto/spec.md +63 -0
  75. package/specs/skills-do-projeto/tasks.md +27 -0
  76. package/templates/project/AGENTS.md +9 -0
  77. package/templates/project/agents/context-engineer.md +3 -0
  78. package/templates/project/agents/governance.md +3 -0
  79. package/templates/project/agents/marketing.md +3 -0
  80. package/templates/project/agents/orchestrator.md +3 -0
  81. package/templates/project/agents/product.md +3 -0
  82. package/templates/project/agents/sdd-architect.md +3 -0
  83. package/templates/project/skills/README.md +14 -0
  84. package/templates/project/skills/accessibility-review/SKILL.md +89 -0
  85. package/templates/project/skills/api-design/SKILL.md +77 -0
  86. package/templates/project/skills/architecture-decision-record/SKILL.md +92 -0
  87. package/templates/project/skills/backlog-slicing/SKILL.md +82 -0
  88. package/templates/project/skills/bounded-context-mapping/SKILL.md +88 -0
  89. package/templates/project/skills/ci-pipeline-review/SKILL.md +83 -0
  90. package/templates/project/skills/commit-message/SKILL.md +143 -0
  91. package/templates/project/skills/data-migrations/SKILL.md +88 -0
  92. package/templates/project/skills/dependency-upgrade/SKILL.md +75 -0
  93. package/templates/project/skills/docker-compose-review/SKILL.md +85 -0
  94. package/templates/project/skills/domain-modeling/SKILL.md +120 -0
  95. package/templates/project/skills/event-storming/SKILL.md +95 -0
  96. package/templates/project/skills/executive-writing/SKILL.md +99 -0
  97. package/templates/project/skills/frontend-architecture/SKILL.md +97 -0
  98. package/templates/project/skills/incident-postmortem/SKILL.md +93 -0
  99. package/templates/project/skills/lgpd-compliance/SKILL.md +108 -0
  100. package/templates/project/skills/llm-provider-routing/SKILL.md +18 -0
  101. package/templates/project/skills/observability/SKILL.md +93 -0
  102. package/templates/project/skills/product-evaluation/SKILL.md +130 -0
  103. package/templates/project/skills/prompt-spec/SKILL.md +83 -0
  104. package/templates/project/skills/pull-request/SKILL.md +101 -0
  105. package/templates/project/skills/query-performance/SKILL.md +83 -0
  106. package/templates/project/skills/release-checklist/SKILL.md +106 -0
  107. package/templates/project/skills/release-notes/SKILL.md +87 -0
  108. package/templates/project/skills/requirements-elicitation/SKILL.md +127 -0
  109. package/templates/project/skills/requirements-gathering/SKILL.md +134 -0
  110. package/templates/project/skills/technical-spike/SKILL.md +101 -0
  111. package/templates/project/skills/testing/SKILL.md +109 -0
  112. package/templates/project/skills/threat-modeling/SKILL.md +87 -0
  113. package/templates/project/skills/ts-async-patterns/SKILL.md +101 -0
  114. package/templates/project/skills/ts-code-review/SKILL.md +121 -0
  115. package/templates/project/skills/ts-module-layout/SKILL.md +104 -0
  116. package/templates/project/skills/ts-testing/SKILL.md +89 -0
  117. package/templates/project/skills/web-performance/SKILL.md +72 -0
  118. package/boilerplates/02-saas-starter/.env.example +0 -25
  119. package/boilerplates/02-saas-starter/CHECKLIST-CRIACAO.md +0 -190
  120. package/boilerplates/02-saas-starter/INFO.md +0 -252
  121. package/boilerplates/02-saas-starter/QUICK_START.md +0 -194
  122. package/boilerplates/02-saas-starter/START-HERE.md +0 -259
  123. package/boilerplates/02-saas-starter/backend/src/common/decorators/roles.decorator.ts +0 -3
  124. package/boilerplates/02-saas-starter/backend/src/common/decorators/tenant.decorator.ts +0 -6
  125. package/boilerplates/02-saas-starter/backend/src/common/middleware/roles.guard.ts +0 -23
  126. package/boilerplates/02-saas-starter/backend/src/config/database.ts +0 -26
  127. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.controller.ts +0 -46
  128. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.module.ts +0 -25
  129. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.service.ts +0 -145
  130. package/boilerplates/02-saas-starter/backend/src/modules/auth/dto/auth.dto.ts +0 -30
  131. package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/jwt.strategy.ts +0 -24
  132. package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/local.strategy.ts +0 -19
  133. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.controller.ts +0 -42
  134. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.module.ts +0 -13
  135. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.service.ts +0 -67
  136. package/boilerplates/02-saas-starter/backend/src/modules/billing/entities/invoice.entity.ts +0 -52
  137. package/boilerplates/02-saas-starter/backend/src/modules/organizations/entities/organization.entity.ts +0 -36
  138. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.controller.ts +0 -16
  139. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.module.ts +0 -13
  140. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.service.ts +0 -34
  141. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/entities/subscription.entity.ts +0 -40
  142. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.controller.ts +0 -36
  143. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.module.ts +0 -13
  144. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.service.ts +0 -91
  145. package/boilerplates/02-saas-starter/backend/src/modules/users/entities/user.entity.ts +0 -42
  146. package/boilerplates/02-saas-starter/backend/src/modules/users/users.controller.ts +0 -14
  147. package/boilerplates/02-saas-starter/backend/src/modules/users/users.module.ts +0 -13
  148. package/boilerplates/02-saas-starter/backend/src/modules/users/users.service.ts +0 -48
  149. package/boilerplates/02-saas-starter/memory/00-global/agent-contract.md +0 -227
  150. package/boilerplates/02-saas-starter/memory/00-global/context-policy.md +0 -141
  151. package/boilerplates/02-saas-starter/memory/00-global/index.md +0 -133
  152. package/boilerplates/02-saas-starter/memory/00-global/mission.md +0 -45
  153. package/boilerplates/02-saas-starter/memory/00-global/patterns.md +0 -223
  154. package/boilerplates/02-saas-starter/memory/10-product/business-rules.md +0 -240
  155. package/boilerplates/02-saas-starter/memory/10-product/nfrs.md +0 -239
  156. package/boilerplates/02-saas-starter/memory/10-product/personas.md +0 -195
  157. package/boilerplates/02-saas-starter/memory/10-product/vision.md +0 -63
  158. package/boilerplates/02-saas-starter/memory/20-architecture/overview.md +0 -232
  159. package/boilerplates/02-saas-starter/memory/30-domains/auth/api.md +0 -186
  160. package/boilerplates/02-saas-starter/memory/30-domains/auth/context.md +0 -85
  161. package/boilerplates/02-saas-starter/memory/30-domains/billing/api.md +0 -262
  162. package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/api.md +0 -176
  163. package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/context.md +0 -100
  164. package/boilerplates/02-saas-starter/memory/40-delivery/backlog.md +0 -81
  165. package/boilerplates/02-saas-starter/memory/40-delivery/roadmap.md +0 -97
  166. package/boilerplates/02-saas-starter/memory/40-delivery/sprint-atual.md +0 -57
  167. package/boilerplates/02-saas-starter/memory/50-orchestration/topology.md +0 -90
  168. package/boilerplates/02-saas-starter/memory/60-runs/index.md +0 -54
  169. package/boilerplates/02-saas-starter/memory/70-summaries/global.md +0 -50
  170. package/boilerplates/02-saas-starter/memory/80-data/schema.md +0 -185
  171. package/boilerplates/02-saas-starter/memory/90-decisions/adr-template.md +0 -75
@@ -1,232 +0,0 @@
1
- # Visão Geral da Arquitetura
2
-
3
- ## Diagrama da Arquitetura
4
-
5
- ```
6
- ┌─────────────────────────────────────────────────────────────────┐
7
- │ Cliente Web/Mobile │
8
- └─────────────────────────────────────────────────────────────────┘
9
- │
10
- ↓
11
- ┌─────────────────────────────────────────────────────────────────┐
12
- │ API Gateway │
13
- │ (Rate Limiter, CORS, Request Logging) │
14
- └─────────────────────────────────────────────────────────────────┘
15
- │
16
- ↓
17
- ┌─────────────────────────────────────────────────────────────────┐
18
- │ NestJS Application │
19
- │ ┌──────────────────────────────────────────────────────────┐ │
20
- │ │ Controllers │ Services │ Middleware │ Guards │ │
21
- │ ├──────────────┴────────────┴──────────────┴──────────────┤ │
22
- │ │ Modules: │ │
23
- │ │ • Auth (JWT, Local strategy) │ │
24
- │ │ • Users (RBAC, invites) │ │
25
- │ │ • Organizations (Multi-tenant) │ │
26
- │ │ • Subscriptions (Plans, upgrades) │ │
27
- │ │ • Billing (Payments, invoices) │ │
28
- │ └──────────────────────────────────────────────────────────┘ │
29
- └─────────────────────────────────────────────────────────────────┘
30
- │ │
31
- ┌──────┴──────┬──────────────┬┴────────┐
32
- ↓ ↓ ↓ ↓
33
- ┌──────────┐ ┌─────────┐ ┌──────────┐ ┌────────┐
34
- │PostgreSQL│ │ Redis │ │ Payment │ │ Email │
35
- │ Database │ │ Cache │ │ Gateway │ │Service │
36
- │ │ │ │ │ (Mock) │ │(Hooks) │
37
- └──────────┘ └─────────┘ └──────────┘ └────────┘
38
- ```
39
-
40
- ## Stack Técnico
41
-
42
- | Camada | Tecnologia | Versão |
43
- |--------|-----------|--------|
44
- | **Backend** | NestJS | 10+ |
45
- | **Language** | TypeScript | 5.0+ |
46
- | **Database** | PostgreSQL | 15+ |
47
- | **Cache** | Redis | 7.0+ |
48
- | **ORM** | TypeORM | 0.3+ |
49
- | **Auth** | JWT | HS256 |
50
- | **Testing** | Jest | 29+ |
51
- | **API Docs** | Swagger/OpenAPI | 3.0 |
52
- | **Runtime** | Node.js | 18+ LTS |
53
-
54
- ## Módulos Principais
55
-
56
- ### 1. Auth Module
57
- - JWT strategy (access + refresh)
58
- - Local strategy (username/password)
59
- - Password hashing (bcrypt)
60
- - Token validation & expiry
61
-
62
- ### 2. Users Module
63
- - User CRUD (create, read, update, delete)
64
- - RBAC (role assignment, permission checking)
65
- - User invites (email link)
66
- - Profile management
67
-
68
- ### 3. Organizations Module
69
- - Org CRUD (create, read, update, delete)
70
- - Org settings
71
- - Multi-tenant isolation
72
- - Org-level permissions
73
-
74
- ### 4. Subscriptions Module
75
- - Subscription CRUD
76
- - Plan management (free, pro, enterprise)
77
- - Upgrade/downgrade logic
78
- - Billing integration
79
-
80
- ### 5. Billing Module
81
- - Payment processing (mock)
82
- - Invoice generation
83
- - Webhook handling
84
- - Transaction history
85
-
86
- ## Fluxos Principais
87
-
88
- ### Signup Flow
89
- ```
90
- 1. POST /api/auth/signup { email, password, org_name }
91
- 2. Validar email único + força de senha
92
- 3. Hash password com bcrypt
93
- 4. Criar org + user (owner role)
94
- 5. Gerar JWT access token
95
- 6. Enviar email de confirmação (async)
96
- 7. Retornar token + user data
97
- ```
98
-
99
- ### Subscription Upgrade Flow
100
- ```
101
- 1. GET /api/subscriptions (validar tenant, auth)
102
- 2. POST /api/subscriptions/:id/upgrade { plan_id }
103
- 3. Validar transição de plano
104
- 4. Charge payment (mock)
105
- 5. Atualizar subscription
106
- 6. Gerar invoice
107
- 7. Registrar audit log
108
- 8. Enviar email de confirmação
109
- ```
110
-
111
- ### Billing Flow
112
- ```
113
- 1. POST /api/billing/charge { amount, currency }
114
- 2. Chamar payment gateway (Stripe mock)
115
- 3. Registrar transação
116
- 4. Gerar invoice
117
- 5. Enviar email de receipt
118
- 6. Webhook callback (async)
119
- 7. Atualizar subscription status se necessário
120
- ```
121
-
122
- ## Padrões Arquiteturais
123
-
124
- ### 1. Dependency Injection
125
- - NestJS @Injectable()
126
- - Constructor injection (explícito, type-safe)
127
- - Service-to-service via providers
128
-
129
- ### 2. Middleware Pattern
130
- - Tenant context middleware (set tenantId no request)
131
- - Logging middleware
132
- - Error handling middleware
133
-
134
- ### 3. Guard Pattern
135
- - JwtAuthGuard (validar token)
136
- - RolesGuard (verificar RBAC)
137
- - TenantGuard (isolar tenant)
138
-
139
- ### 4. Service Pattern
140
- - Business logic separado de HTTP
141
- - Reutilizável por controllers/jobs
142
- - Testável isoladamente
143
-
144
- ### 5. Repository Pattern
145
- - Typeorm repositories para data access
146
- - Abstração de queries
147
- - Facilitado testes (mock repositories)
148
-
149
- ## Camadas
150
-
151
- ```
152
- ┌───────────────────────────────┐
153
- │ HTTP Controllers │ (Request/Response)
154
- ├───────────────────────────────┤
155
- │ Services │ (Business Logic)
156
- ├───────────────────────────────┤
157
- │ Repositories │ (Data Access)
158
- ├───────────────────────────────┤
159
- │ Database / Cache │ (Persistence)
160
- └───────────────────────────────┘
161
- ```
162
-
163
- ## Decisões Arquiteturais
164
-
165
- ### Por que PostgreSQL, não MongoDB?
166
- - Relational: Users ↔ Organizations ↔ Subscriptions ↔ Invoices
167
- - Transactions: ACID para billing (crítico)
168
- - Compliance: Melhor para GDPR + audit trails
169
- - Cost: Managed PostgreSQL (RDS, Heroku) é mais barato
170
-
171
- ### Por que Redis, não memcache?
172
- - Data structures: Listas, sets (cache invalidation mais fácil)
173
- - Persistence: Opcional, mas disponível
174
- - Pub/Sub: Para notificações em tempo real (futura)
175
- - Cost: Comparable, Redis tem mais features
176
-
177
- ### Por que TypeScript?
178
- - Type safety: Detectar bugs em compile-time
179
- - DX: Melhor IDE support, autocompletion
180
- - Refactoring: Renomear símbolos com confiança
181
- - Migration: JavaScript é subset de TypeScript
182
-
183
- ### Por que NestJS?
184
- - Convention over configuration: Setup rápido
185
- - Dependency injection: Integrado desde início
186
- - Modular: Escalável conforme projeto cresce
187
- - Testing: Built-in testing utilities
188
- - Community: Stack MEAN maduro em produção
189
-
190
- ## Próximas Fases
191
-
192
- ### Phase 2: Internacionalização
193
- - Multi-currency (USD, EUR, GBP, etc)
194
- - Stripe real integration
195
- - Webhooks para payment events
196
-
197
- ### Phase 3: Observability
198
- - Prometheus metrics
199
- - Grafana dashboards
200
- - OpenTelemetry tracing
201
- - Distributed logging (ELK stack)
202
-
203
- ### Phase 4: Compliance
204
- - SOC2 audit trail
205
- - GDPR data export
206
- - User audit logs
207
- - Rate limiting per endpoint
208
-
209
- ### Phase 5: Performance
210
- - Database indexes optimization
211
- - Query result caching
212
- - Bulk operations
213
- - Webhook batch processing
214
-
215
- ## Deployment Strategy
216
-
217
- ### Development Environment
218
- - docker-compose com PostgreSQL + Redis
219
- - Hot-reload NestJS
220
- - Seed data automático
221
-
222
- ### Staging Environment
223
- - AWS RDS PostgreSQL
224
- - AWS ElastiCache Redis
225
- - Docker containers em ECS
226
- - Blue-green deployment
227
-
228
- ### Production Environment
229
- - Multi-AZ RDS PostgreSQL
230
- - Read replicas para scaling
231
- - CloudFront para static assets (future)
232
- - Auto-scaling groups
@@ -1,186 +0,0 @@
1
- # Auth API Specification
2
-
3
- ## Endpoints
4
-
5
- ### 1. Signup
6
-
7
- **POST** `/api/auth/signup`
8
-
9
- ```json
10
- {
11
- "email": "founder@example.com",
12
- "password": "SecureP@ss123",
13
- "organizationName": "My Startup"
14
- }
15
- ```
16
-
17
- **Response 201**:
18
- ```json
19
- {
20
- "data": {
21
- "id": "user-uuid",
22
- "email": "founder@example.com",
23
- "organization": {
24
- "id": "org-uuid",
25
- "name": "My Startup",
26
- "plan": "free"
27
- },
28
- "accessToken": "eyJhbGc...",
29
- "refreshToken": "eyJhbGc..."
30
- }
31
- }
32
- ```
33
-
34
- **Error 400**: Email já existe
35
- **Error 422**: Senha fraca
36
-
37
- ---
38
-
39
- ### 2. Login
40
-
41
- **POST** `/api/auth/login`
42
-
43
- ```json
44
- {
45
- "email": "founder@example.com",
46
- "password": "SecureP@ss123"
47
- }
48
- ```
49
-
50
- **Response 200**:
51
- ```json
52
- {
53
- "data": {
54
- "user": { "id", "email", "roles": ["owner"] },
55
- "organization": { "id", "name", "plan" },
56
- "accessToken": "eyJhbGc...",
57
- "refreshToken": "eyJhbGc..."
58
- }
59
- }
60
- ```
61
-
62
- **Error 401**: Email ou senha inválida
63
- **Error 429**: Too many attempts (rate limited)
64
-
65
- ---
66
-
67
- ### 3. Refresh Token
68
-
69
- **POST** `/api/auth/refresh`
70
-
71
- ```json
72
- {
73
- "refreshToken": "eyJhbGc..."
74
- }
75
- ```
76
-
77
- **Response 200**:
78
- ```json
79
- {
80
- "data": {
81
- "accessToken": "eyJhbGc...",
82
- "refreshToken": "eyJhbGc..." // new if rotated
83
- }
84
- }
85
- ```
86
-
87
- **Error 401**: Refresh token inválido ou expirado
88
-
89
- ---
90
-
91
- ### 4. Logout
92
-
93
- **POST** `/api/auth/logout`
94
-
95
- Headers: `Authorization: Bearer {accessToken}`
96
-
97
- **Response 200**:
98
- ```json
99
- {
100
- "message": "Logged out successfully"
101
- }
102
- ```
103
-
104
- ---
105
-
106
- ### 5. Get Current User
107
-
108
- **GET** `/api/auth/me`
109
-
110
- Headers: `Authorization: Bearer {accessToken}`
111
-
112
- **Response 200**:
113
- ```json
114
- {
115
- "data": {
116
- "id": "user-uuid",
117
- "email": "founder@example.com",
118
- "roles": ["owner"],
119
- "organization": {
120
- "id": "org-uuid",
121
- "name": "My Startup",
122
- "plan": "free"
123
- }
124
- }
125
- }
126
- ```
127
-
128
- ---
129
-
130
- ## Error Codes
131
-
132
- | Code | Message | Meaning |
133
- |------|---------|---------|
134
- | AUTH_001 | Invalid credentials | Email ou senha incorreta |
135
- | AUTH_002 | Email already exists | Email já cadastrado neste tenant |
136
- | AUTH_003 | Weak password | Senha não atende requisitos |
137
- | AUTH_004 | Invalid token | JWT inválido ou expirado |
138
- | AUTH_005 | Token expired | Usar refresh endpoint |
139
- | AUTH_006 | Account locked | 5 failed attempts, tente em 15 min |
140
- | AUTH_007 | Email not verified | Confirmar email primeiro |
141
-
142
- ## Flow Examples
143
-
144
- ### Scenario: User Signup
145
- ```bash
146
- curl -X POST http://localhost:3000/api/auth/signup \
147
- -H "Content-Type: application/json" \
148
- -d '{
149
- "email": "founder@example.com",
150
- "password": "SecureP@ss123",
151
- "organizationName": "My Startup"
152
- }'
153
- ```
154
-
155
- ### Scenario: User Login
156
- ```bash
157
- curl -X POST http://localhost:3000/api/auth/login \
158
- -H "Content-Type: application/json" \
159
- -d '{
160
- "email": "founder@example.com",
161
- "password": "SecureP@ss123"
162
- }'
163
- ```
164
-
165
- ### Scenario: Access Protected Route
166
- ```bash
167
- curl -X GET http://localhost:3000/api/auth/me \
168
- -H "Authorization: Bearer eyJhbGc..."
169
- ```
170
-
171
- ### Scenario: Refresh Expired Token
172
- ```bash
173
- curl -X POST http://localhost:3000/api/auth/refresh \
174
- -H "Content-Type: application/json" \
175
- -d '{
176
- "refreshToken": "eyJhbGc..."
177
- }'
178
- ```
179
-
180
- ## Implementation Notes
181
-
182
- - Todos endpoints retornam `tenantId` no JWT payload
183
- - Todas operações são isoladas por tenant
184
- - Email é único por tenant, não globalmente
185
- - Passwords são hashed com bcrypt (cost=12)
186
- - Tokens são signed com HS256
@@ -1,85 +0,0 @@
1
- # Auth Domain Context
2
-
3
- ## O que é Auth neste SaaS?
4
-
5
- Autenticação & autorização stateless com JWT, permitindo:
6
- 1. Signup (criar org + user)
7
- 2. Login (JWT tokens)
8
- 3. Refresh (renovar access token)
9
- 4. Logout (invalidar token em Redis)
10
- 5. Password reset (email link)
11
-
12
- ## Fluxo de Autenticação
13
-
14
- ```
15
- User abre app
16
- ↓
17
- Frontend checa localStorage.accessToken
18
- ↓
19
- [Token válido?] → SIM → Mostrar dashboard
20
- ↓ NÃO
21
- [Token expirado?] → NÃO → Mostrar login
22
- ↓ SIM
23
- POST /api/auth/refresh com refreshToken
24
- ↓
25
- [Refresh válido?] → SIM → Novo accessToken
26
- ↓ NÃO
27
- Limpar tokens, mostrar login
28
- ```
29
-
30
- ## Conceitos
31
-
32
- ### JWT Structure
33
- ```
34
- Header.Payload.Signature
35
- eyJhbGciOiJIUzI1NiJ9.
36
- eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
37
- SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
38
- ```
39
-
40
- Payload contém:
41
- - `sub` (subject): user ID
42
- - `tenantId`: organization ID
43
- - `roles`: ['owner', 'admin'] etc
44
- - `iat`: issued at
45
- - `exp`: expiry timestamp
46
-
47
- ### Strategies
48
-
49
- **Local Strategy**:
50
- - Username/email + password
51
- - Usado em POST /api/auth/login
52
- - Retorna JWT
53
-
54
- **JWT Strategy**:
55
- - Valida token em Authorization header
56
- - Usado em @UseGuards(JwtAuthGuard)
57
- - Extrai dados do token payload
58
-
59
- ## Regras & Invariantes
60
-
61
- 1. **Password validation**: Min 12 chars, 1 uppercase, 1 lowercase, 1 number, 1 symbol
62
- 2. **Email validation**: RFC 5322
63
- 3. **Unique constraint**: Email único por tenant (não global)
64
- 4. **Token signing**: Secret from process.env.JWT_SECRET
65
- 5. **Token expiry**: Access 15 min, Refresh 7 days
66
- 6. **Rate limiting**: 5 failed login attempts = 15 min lockout
67
- 7. **Tenant isolation**: User pode pertencer a múltiplas orgs (multi-tenant)
68
-
69
- ## Status Atual
70
-
71
- - ✅ JWT strategy implementada
72
- - ✅ Local strategy implementada
73
- - ✅ User entity com password hash
74
- - ✅ Signup endpoint
75
- - ✅ Login endpoint
76
- - ✅ Refresh endpoint
77
- - 🚧 Password reset (future)
78
- - 🚧 MFA (future)
79
-
80
- ## Próximos Steps
81
-
82
- 1. Implementar password reset flow
83
- 2. Adicionar rate limiting
84
- 3. Webhook para email de confirmação
85
- 4. Audit logging de eventos de auth