forjajs 5.0.1 → 5.3.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.
- package/CHANGELOG.md +114 -2
- package/README.md +40 -5
- package/README.pt-BR.md +42 -4
- package/boilerplates/02-saas-starter/README.md +58 -293
- package/boilerplates/02-saas-starter/backend/.env.example +13 -0
- package/boilerplates/02-saas-starter/backend/.oxlintrc.json +8 -0
- package/boilerplates/02-saas-starter/backend/nest-cli.json +6 -0
- package/boilerplates/02-saas-starter/backend/package.json +32 -73
- package/boilerplates/02-saas-starter/backend/src/app.module.ts +16 -16
- package/boilerplates/02-saas-starter/backend/src/billing/adapters/http/billing.controller.ts +55 -0
- package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/orm-entities.ts +28 -0
- package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/typeorm-billing.repository.ts +46 -0
- package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.spec.ts +58 -0
- package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.ts +68 -0
- package/boilerplates/02-saas-starter/backend/src/billing/billing.module.ts +11 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.spec.ts +23 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.ts +36 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/ports.ts +27 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.spec.ts +28 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.ts +47 -0
- package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/auth.dto.ts +22 -0
- package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/identity.controller.ts +59 -0
- package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/orm-entities.ts +25 -0
- package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/typeorm-identity.repository.ts +47 -0
- package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.spec.ts +72 -0
- package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.ts +63 -0
- package/boilerplates/02-saas-starter/backend/src/identity/domain/model.spec.ts +19 -0
- package/boilerplates/02-saas-starter/backend/src/identity/domain/model.ts +42 -0
- package/boilerplates/02-saas-starter/backend/src/identity/domain/password.spec.ts +17 -0
- package/boilerplates/02-saas-starter/backend/src/identity/domain/password.ts +26 -0
- package/boilerplates/02-saas-starter/backend/src/identity/identity.module.ts +12 -0
- package/boilerplates/02-saas-starter/backend/src/main.ts +19 -19
- package/boilerplates/02-saas-starter/backend/src/platform/auth/jwt-auth.guard.ts +17 -0
- package/boilerplates/02-saas-starter/backend/src/platform/auth/principal.ts +22 -0
- package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.spec.ts +23 -0
- package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.ts +20 -0
- package/boilerplates/02-saas-starter/backend/src/platform/auth/token.service.ts +54 -0
- package/boilerplates/02-saas-starter/backend/src/platform/config.spec.ts +18 -0
- package/boilerplates/02-saas-starter/backend/src/platform/config.ts +33 -0
- package/boilerplates/02-saas-starter/backend/src/platform/platform.module.ts +14 -0
- package/boilerplates/02-saas-starter/backend/tsconfig.build.json +6 -0
- package/boilerplates/02-saas-starter/backend/tsconfig.json +16 -21
- package/boilerplates/02-saas-starter/backend/vitest.config.ts +7 -0
- package/boilerplates/02-saas-starter/boilerplate.manifest.json +19 -14
- package/boilerplates/02-saas-starter/docker-compose.yml +10 -24
- package/boilerplates/02-saas-starter/memory/30-domains/billing/context.md +15 -132
- package/boilerplates/02-saas-starter/memory/30-domains/identity/context.md +20 -0
- package/boilerplates/README.md +9 -10
- package/dist/apps/cli/src/index.d.ts +0 -1
- package/dist/apps/cli/src/index.js +43 -32
- package/dist/apps/dashboard/app/api/forja/[...path]/route.js +34 -1
- package/dist/apps/dashboard/app/api/forja/capabilities.d.ts +26 -0
- package/dist/apps/dashboard/app/api/forja/capabilities.js +39 -0
- package/dist/apps/dashboard/app/dashboard-client.jsx +607 -42
- package/dist/apps/server/src/forja-nest.module.d.ts +6 -0
- package/dist/apps/server/src/forja-nest.module.js +55 -0
- package/dist/apps/server/src/main.d.ts +21 -4
- package/dist/apps/server/src/main.js +79 -57
- package/dist/apps/server/src/task-planning-service.d.ts +29 -0
- package/dist/apps/server/src/task-planning-service.js +195 -0
- package/dist/apps/server/src/task-runtime-coordinator.d.ts +57 -0
- package/dist/apps/server/src/task-runtime-coordinator.js +229 -0
- package/dist/bin/forja.js +3 -2
- package/dist/bin/init-project.js +1 -0
- package/dist/lib/agent-evals.d.ts +138 -0
- package/dist/lib/agent-evals.js +349 -0
- package/dist/lib/cli-output.js +14 -2
- package/dist/lib/code-context.d.ts +33 -5
- package/dist/lib/code-context.js +70 -5
- package/dist/lib/context-builder.d.ts +49 -4
- package/dist/lib/context-builder.js +114 -47
- package/dist/lib/core/coverage-gate.d.ts +59 -0
- package/dist/lib/core/coverage-gate.js +58 -0
- package/dist/lib/core/doc-graph.d.ts +38 -0
- package/dist/lib/core/doc-graph.js +83 -0
- package/dist/lib/core/health.js +286 -5
- package/dist/lib/core/journey.js +36 -0
- package/dist/lib/core/registry.js +81 -6
- package/dist/lib/docs-reference.d.ts +35 -0
- package/dist/lib/docs-reference.js +57 -0
- package/dist/lib/generators/memory-generator.d.ts +0 -11
- package/dist/lib/generators/memory-generator.js +5 -161
- package/dist/lib/generators/readme-generator.js +1 -1
- package/dist/lib/llm/json-output.d.ts +14 -0
- package/dist/lib/llm/json-output.js +77 -0
- package/dist/lib/project-wiring.d.ts +8 -0
- package/dist/lib/project-wiring.js +79 -3
- package/dist/lib/session-memory.d.ts +38 -0
- package/dist/lib/session-memory.js +206 -0
- package/dist/lib/spec-trace.d.ts +46 -0
- package/dist/lib/spec-trace.js +184 -0
- package/dist/lib/validators/structure-validator.js +0 -1
- package/dist/packages/adapter-nest/src/index.d.ts +2 -1
- package/dist/packages/adapter-nest/src/index.js +59 -1
- package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
- package/dist/packages/adapter-sqlite/src/index.js +61 -1
- package/dist/packages/context/src/index.d.ts +2 -0
- package/dist/packages/context/src/index.js +36 -15
- package/dist/packages/contracts/src/index.d.ts +64 -0
- package/dist/packages/core/src/index.d.ts +9 -1
- package/dist/packages/core/src/index.js +28 -3
- package/dist/packages/graph/src/index.js +14 -5
- package/dist/packages/llm/src/index.js +12 -2
- package/dist/packages/mcp/src/index.d.ts +8 -0
- package/dist/packages/mcp/src/index.js +12 -1
- package/dist/packages/observability/src/index.d.ts +11 -0
- package/dist/packages/observability/src/index.js +3 -0
- package/dist/packages/orchestration/src/index.d.ts +15 -1
- package/dist/packages/orchestration/src/index.js +127 -21
- package/dist/packages/planner/src/index.d.ts +7 -1
- package/dist/packages/planner/src/index.js +67 -10
- package/dist/packages/planner/src/proposal-store.d.ts +30 -0
- package/dist/packages/planner/src/proposal-store.js +109 -0
- package/dist/packages/policy/src/index.d.ts +9 -16
- package/dist/packages/policy/src/index.js +114 -31
- package/dist/packages/runtime/src/index.d.ts +16 -2
- package/dist/packages/runtime/src/index.js +176 -61
- package/dist/scripts/build-smart-context.d.ts +2 -0
- package/dist/scripts/build-smart-context.js +12 -3
- package/dist/scripts/code-context.d.ts +3 -1
- package/dist/scripts/code-context.js +13 -3
- package/dist/scripts/coverage-gate.d.ts +2 -0
- package/dist/scripts/coverage-gate.js +101 -0
- package/dist/scripts/eval-agents.d.ts +11 -0
- package/dist/scripts/eval-agents.js +96 -0
- package/dist/scripts/gen-commands-doc.d.ts +2 -0
- package/dist/scripts/gen-commands-doc.js +18 -0
- package/dist/scripts/hook-session-memory.d.ts +9 -0
- package/dist/scripts/hook-session-memory.js +20 -0
- package/dist/scripts/hook-session-start.js +34 -0
- package/dist/scripts/llm-fit.js +23 -1
- package/dist/scripts/spec-trace.d.ts +10 -0
- package/dist/scripts/spec-trace.js +73 -0
- package/dist/scripts/sync-universal-memory.js +69 -4
- package/dist/scripts/token-benchmark.d.ts +33 -1
- package/dist/scripts/token-benchmark.js +179 -5
- package/dist/scripts/token-economy.js +3 -1
- package/dist/scripts/tools-doctor.d.ts +16 -1
- package/dist/scripts/tools-doctor.js +58 -17
- package/docs/commands.md +155 -0
- package/docs/fluxo.md +11 -7
- package/docs/init-project.md +3 -1
- package/docs/llm-fit-loop.md +36 -0
- package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
- package/docs/produto/factsheet-marketing.md +7 -5
- package/docs/produto/roteiro-demo.md +14 -5
- package/docs/quick-reference.md +3 -3
- package/docs/token-optimization.md +10 -6
- package/memory/90-decisions/0088-templates-validados.md +3 -0
- package/memory/90-decisions/0089-skills-do-projeto.md +51 -0
- package/memory/90-decisions/0090-adapters-de-agente-somente-leitura.md +47 -0
- package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
- package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
- package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
- package/package.json +4 -2
- package/specs/avaliacoes-de-agentes/spec.md +52 -0
- package/specs/criterios-ligados-a-testes/spec.md +42 -0
- package/specs/memoria-de-sessao/spec.md +48 -0
- package/specs/skills-do-projeto/plan.md +40 -0
- package/specs/skills-do-projeto/spec.md +63 -0
- package/specs/skills-do-projeto/tasks.md +27 -0
- package/specs/v6-agent-runtime-portable/spec.md +83 -0
- package/specs/v6-core-consolidation/spec.md +70 -0
- package/specs/v6-docs-drift/spec.md +85 -0
- package/specs/v6-quality-gates/spec.md +99 -0
- package/specs/v6-token-economy/spec.md +84 -0
- package/templates/evals/agents/adr.json +25 -0
- package/templates/evals/agents/memoria.json +32 -0
- package/templates/evals/agents/proxima-acao.json +29 -0
- package/templates/evals/agents/spec-nova.json +26 -0
- package/templates/evals/agents/teste-do-criterio.json +29 -0
- package/templates/project/AGENTS.md +16 -0
- package/templates/project/CLAUDE.md +3 -2
- package/templates/project/agents/context-engineer.md +3 -0
- package/templates/project/agents/governance.md +3 -0
- package/templates/project/agents/marketing.md +3 -0
- package/templates/project/agents/orchestrator.md +3 -0
- package/templates/project/agents/product.md +3 -0
- package/templates/project/agents/sdd-architect.md +3 -0
- package/templates/project/skills/README.md +14 -0
- package/templates/project/skills/accessibility-review/SKILL.md +89 -0
- package/templates/project/skills/api-design/SKILL.md +77 -0
- package/templates/project/skills/architecture-decision-record/SKILL.md +92 -0
- package/templates/project/skills/backlog-slicing/SKILL.md +82 -0
- package/templates/project/skills/bounded-context-mapping/SKILL.md +88 -0
- package/templates/project/skills/ci-pipeline-review/SKILL.md +83 -0
- package/templates/project/skills/commit-message/SKILL.md +143 -0
- package/templates/project/skills/data-migrations/SKILL.md +88 -0
- package/templates/project/skills/dependency-upgrade/SKILL.md +75 -0
- package/templates/project/skills/docker-compose-review/SKILL.md +85 -0
- package/templates/project/skills/domain-modeling/SKILL.md +120 -0
- package/templates/project/skills/event-storming/SKILL.md +95 -0
- package/templates/project/skills/executive-writing/SKILL.md +99 -0
- package/templates/project/skills/frontend-architecture/SKILL.md +97 -0
- package/templates/project/skills/incident-postmortem/SKILL.md +93 -0
- package/templates/project/skills/lgpd-compliance/SKILL.md +108 -0
- package/templates/project/skills/llm-provider-routing/SKILL.md +18 -0
- package/templates/project/skills/observability/SKILL.md +93 -0
- package/templates/project/skills/product-evaluation/SKILL.md +130 -0
- package/templates/project/skills/prompt-spec/SKILL.md +83 -0
- package/templates/project/skills/pull-request/SKILL.md +101 -0
- package/templates/project/skills/query-performance/SKILL.md +83 -0
- package/templates/project/skills/release-checklist/SKILL.md +106 -0
- package/templates/project/skills/release-notes/SKILL.md +87 -0
- package/templates/project/skills/requirements-elicitation/SKILL.md +127 -0
- package/templates/project/skills/requirements-gathering/SKILL.md +134 -0
- package/templates/project/skills/technical-spike/SKILL.md +101 -0
- package/templates/project/skills/testing/SKILL.md +109 -0
- package/templates/project/skills/threat-modeling/SKILL.md +87 -0
- package/templates/project/skills/ts-async-patterns/SKILL.md +101 -0
- package/templates/project/skills/ts-code-review/SKILL.md +121 -0
- package/templates/project/skills/ts-module-layout/SKILL.md +104 -0
- package/templates/project/skills/ts-testing/SKILL.md +89 -0
- package/templates/project/skills/web-performance/SKILL.md +72 -0
- package/boilerplates/02-saas-starter/.env.example +0 -25
- package/boilerplates/02-saas-starter/CHECKLIST-CRIACAO.md +0 -190
- package/boilerplates/02-saas-starter/INFO.md +0 -252
- package/boilerplates/02-saas-starter/QUICK_START.md +0 -194
- package/boilerplates/02-saas-starter/START-HERE.md +0 -259
- package/boilerplates/02-saas-starter/backend/src/common/decorators/roles.decorator.ts +0 -3
- package/boilerplates/02-saas-starter/backend/src/common/decorators/tenant.decorator.ts +0 -6
- package/boilerplates/02-saas-starter/backend/src/common/middleware/roles.guard.ts +0 -23
- package/boilerplates/02-saas-starter/backend/src/config/database.ts +0 -26
- package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.controller.ts +0 -46
- package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.module.ts +0 -25
- package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.service.ts +0 -145
- package/boilerplates/02-saas-starter/backend/src/modules/auth/dto/auth.dto.ts +0 -30
- package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/jwt.strategy.ts +0 -24
- package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/local.strategy.ts +0 -19
- package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.controller.ts +0 -42
- package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.module.ts +0 -13
- package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.service.ts +0 -67
- package/boilerplates/02-saas-starter/backend/src/modules/billing/entities/invoice.entity.ts +0 -52
- package/boilerplates/02-saas-starter/backend/src/modules/organizations/entities/organization.entity.ts +0 -36
- package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.controller.ts +0 -16
- package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.module.ts +0 -13
- package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.service.ts +0 -34
- package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/entities/subscription.entity.ts +0 -40
- package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.controller.ts +0 -36
- package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.module.ts +0 -13
- package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.service.ts +0 -91
- package/boilerplates/02-saas-starter/backend/src/modules/users/entities/user.entity.ts +0 -42
- package/boilerplates/02-saas-starter/backend/src/modules/users/users.controller.ts +0 -14
- package/boilerplates/02-saas-starter/backend/src/modules/users/users.module.ts +0 -13
- package/boilerplates/02-saas-starter/backend/src/modules/users/users.service.ts +0 -48
- package/boilerplates/02-saas-starter/memory/00-global/agent-contract.md +0 -227
- package/boilerplates/02-saas-starter/memory/00-global/context-policy.md +0 -141
- package/boilerplates/02-saas-starter/memory/00-global/index.md +0 -133
- package/boilerplates/02-saas-starter/memory/00-global/mission.md +0 -45
- package/boilerplates/02-saas-starter/memory/00-global/patterns.md +0 -223
- package/boilerplates/02-saas-starter/memory/10-product/business-rules.md +0 -240
- package/boilerplates/02-saas-starter/memory/10-product/nfrs.md +0 -239
- package/boilerplates/02-saas-starter/memory/10-product/personas.md +0 -195
- package/boilerplates/02-saas-starter/memory/10-product/vision.md +0 -63
- package/boilerplates/02-saas-starter/memory/20-architecture/overview.md +0 -232
- package/boilerplates/02-saas-starter/memory/30-domains/auth/api.md +0 -186
- package/boilerplates/02-saas-starter/memory/30-domains/auth/context.md +0 -85
- package/boilerplates/02-saas-starter/memory/30-domains/billing/api.md +0 -262
- package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/api.md +0 -176
- package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/context.md +0 -100
- package/boilerplates/02-saas-starter/memory/40-delivery/backlog.md +0 -81
- package/boilerplates/02-saas-starter/memory/40-delivery/roadmap.md +0 -97
- package/boilerplates/02-saas-starter/memory/40-delivery/sprint-atual.md +0 -57
- package/boilerplates/02-saas-starter/memory/50-orchestration/topology.md +0 -90
- package/boilerplates/02-saas-starter/memory/60-runs/index.md +0 -54
- package/boilerplates/02-saas-starter/memory/70-summaries/global.md +0 -50
- package/boilerplates/02-saas-starter/memory/80-data/schema.md +0 -185
- package/boilerplates/02-saas-starter/memory/90-decisions/adr-template.md +0 -75
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { InjectDataSource } from '@nestjs/typeorm';
|
|
3
|
+
import { DataSource } from 'typeorm';
|
|
4
|
+
import { isPlanId } from '../../domain/plan.js';
|
|
5
|
+
import type { SubscriptionState } from '../../domain/subscription.js';
|
|
6
|
+
import type { BillingRepository, Invoice } from '../../domain/ports.js';
|
|
7
|
+
import { InvoiceOrm, SubscriptionOrm } from './orm-entities.js';
|
|
8
|
+
|
|
9
|
+
const toInvoice = (r: InvoiceOrm): Invoice => ({
|
|
10
|
+
id: r.id, tenantId: r.tenantId, number: r.number, plan: r.plan, amountCents: r.amountCents, currency: r.currency,
|
|
11
|
+
periodStart: r.periodStart, periodEnd: r.periodEnd, status: r.status, issuedAt: r.issuedAt,
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
@Injectable()
|
|
15
|
+
export class TypeOrmBillingRepository implements BillingRepository {
|
|
16
|
+
constructor(@InjectDataSource() private readonly ds: DataSource) {}
|
|
17
|
+
|
|
18
|
+
async findSubscription(tenantId: string): Promise<SubscriptionState | null> {
|
|
19
|
+
const r = await this.ds.getRepository(SubscriptionOrm).findOneBy({ tenantId });
|
|
20
|
+
if (!r) return null;
|
|
21
|
+
if (!isPlanId(r.plan)) throw new Error(`Plano inválido no banco: ${r.plan}`);
|
|
22
|
+
return { id: r.id, tenantId: r.tenantId, plan: r.plan, periodStart: r.periodStart, periodEnd: r.periodEnd };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async saveSubscription(state: SubscriptionState): Promise<void> {
|
|
26
|
+
await this.ds.getRepository(SubscriptionOrm).save({ ...state });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async findInvoiceForPeriod(tenantId: string, periodStart: Date): Promise<Invoice | null> {
|
|
30
|
+
const r = await this.ds.getRepository(InvoiceOrm).findOneBy({ tenantId, periodStart });
|
|
31
|
+
return r ? toInvoice(r) : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async insertInvoice(invoice: Invoice): Promise<void> {
|
|
35
|
+
await this.ds.getRepository(InvoiceOrm).insert({ ...invoice });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async listInvoices(tenantId: string): Promise<Invoice[]> {
|
|
39
|
+
return (await this.ds.getRepository(InvoiceOrm).find({ where: { tenantId }, order: { periodStart: 'DESC' } })).map(toInvoice);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async findInvoice(id: string, tenantId: string): Promise<Invoice | null> {
|
|
43
|
+
const r = await this.ds.getRepository(InvoiceOrm).findOneBy({ id, tenantId });
|
|
44
|
+
return r ? toInvoice(r) : null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { BadRequestException, NotFoundException, UnprocessableEntityException } from '@nestjs/common';
|
|
2
|
+
import type { SubscriptionState } from '../domain/subscription.js';
|
|
3
|
+
import type { BillingRepository, Invoice } from '../domain/ports.js';
|
|
4
|
+
import { BillingService } from './billing.service.js';
|
|
5
|
+
|
|
6
|
+
class InMemoryBilling implements BillingRepository {
|
|
7
|
+
subs = new Map<string, SubscriptionState>();
|
|
8
|
+
invoices: Invoice[] = [];
|
|
9
|
+
async findSubscription(t: string) { return this.subs.get(t) ?? null; }
|
|
10
|
+
async saveSubscription(s: SubscriptionState) { this.subs.set(s.tenantId, s); }
|
|
11
|
+
async findInvoiceForPeriod(t: string, start: Date) { return this.invoices.find((i) => i.tenantId === t && i.periodStart.getTime() === start.getTime()) ?? null; }
|
|
12
|
+
async insertInvoice(i: Invoice) { this.invoices.push(i); }
|
|
13
|
+
async listInvoices(t: string) { return this.invoices.filter((i) => i.tenantId === t); }
|
|
14
|
+
async findInvoice(id: string, t: string) { return this.invoices.find((i) => i.id === id && i.tenantId === t) ?? null; }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const setup = (at = new Date('2026-05-10T12:00:00Z')) => {
|
|
18
|
+
const repo = new InMemoryBilling();
|
|
19
|
+
return { repo, billing: new BillingService(repo, () => at, { currency: 'BRL' }) };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
describe('BillingService', () => {
|
|
23
|
+
it('cria a assinatura free na primeira consulta e devolve a mesma depois', async () => {
|
|
24
|
+
const { billing } = setup();
|
|
25
|
+
const a = await billing.subscription('t1');
|
|
26
|
+
expect(a.plan).toBe('free');
|
|
27
|
+
expect((await billing.subscription('t1')).id).toBe(a.id);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('plano desconhecido → 400; transição proibida → 422', async () => {
|
|
31
|
+
const { billing } = setup();
|
|
32
|
+
await expect(billing.changePlan('t1', 'gold')).rejects.toBeInstanceOf(BadRequestException);
|
|
33
|
+
await billing.changePlan('t1', 'enterprise');
|
|
34
|
+
await expect(billing.changePlan('t1', 'free')).rejects.toBeInstanceOf(UnprocessableEntityException);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('fatura usa o preço do plano em centavos e é idempotente no período', async () => {
|
|
38
|
+
const { billing, repo } = setup();
|
|
39
|
+
await billing.changePlan('t1', 'pro');
|
|
40
|
+
const first = await billing.issueCurrentInvoice('t1');
|
|
41
|
+
const again = await billing.issueCurrentInvoice('t1');
|
|
42
|
+
expect(first).toMatchObject({ amountCents: 9900, currency: 'BRL', status: 'open', plan: 'pro' });
|
|
43
|
+
expect(again.id).toBe(first.id);
|
|
44
|
+
expect(repo.invoices).toHaveLength(1);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('fatura do plano free nasce paga, com valor zero', async () => {
|
|
48
|
+
const { billing } = setup();
|
|
49
|
+
expect(await billing.issueCurrentInvoice('t1')).toMatchObject({ amountCents: 0, status: 'paid' });
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('isolamento: fatura de outro tenant responde 404 e não aparece na lista', async () => {
|
|
53
|
+
const { billing } = setup();
|
|
54
|
+
const inv = await billing.issueCurrentInvoice('t1');
|
|
55
|
+
await expect(billing.invoice(inv.id, 't2')).rejects.toBeInstanceOf(NotFoundException);
|
|
56
|
+
expect(await billing.listInvoices('t2')).toEqual([]);
|
|
57
|
+
});
|
|
58
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { BadRequestException, Inject, Injectable, NotFoundException, UnprocessableEntityException } from '@nestjs/common';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { APP_CONFIG, type AppConfig } from '../../platform/config.js';
|
|
4
|
+
import { isPlanId, PLANS } from '../domain/plan.js';
|
|
5
|
+
import { InvalidPlanChange, Subscription, monthlyPeriod, type SubscriptionState } from '../domain/subscription.js';
|
|
6
|
+
import { BILLING_REPOSITORY, CLOCK, type BillingRepository, type Clock, type Invoice } from '../domain/ports.js';
|
|
7
|
+
|
|
8
|
+
@Injectable()
|
|
9
|
+
export class BillingService {
|
|
10
|
+
constructor(
|
|
11
|
+
@Inject(BILLING_REPOSITORY) private readonly repo: BillingRepository,
|
|
12
|
+
@Inject(CLOCK) private readonly now: Clock,
|
|
13
|
+
@Inject(APP_CONFIG) private readonly config: Pick<AppConfig, 'currency'>,
|
|
14
|
+
) {}
|
|
15
|
+
|
|
16
|
+
/** A assinatura do tenant; criada no plano free na primeira consulta. */
|
|
17
|
+
async subscription(tenantId: string): Promise<SubscriptionState> {
|
|
18
|
+
const existing = await this.repo.findSubscription(tenantId);
|
|
19
|
+
if (existing) return existing;
|
|
20
|
+
const created = Subscription.start(randomUUID(), tenantId, this.now()).snapshot;
|
|
21
|
+
await this.repo.saveSubscription(created);
|
|
22
|
+
return created;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async changePlan(tenantId: string, plan: string): Promise<SubscriptionState> {
|
|
26
|
+
if (!isPlanId(plan)) throw new BadRequestException(`Plano desconhecido: ${plan}`);
|
|
27
|
+
const sub = Subscription.restore(await this.subscription(tenantId));
|
|
28
|
+
try {
|
|
29
|
+
sub.changePlan(plan);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (error instanceof InvalidPlanChange) throw new UnprocessableEntityException(error.message);
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
await this.repo.saveSubscription(sub.snapshot);
|
|
35
|
+
return sub.snapshot;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Emite a fatura do período atual a partir do plano. Idempotente por período: chamar de novo devolve
|
|
40
|
+
* a mesma fatura. O valor vem da tabela de planos, nunca do cliente.
|
|
41
|
+
*/
|
|
42
|
+
async issueCurrentInvoice(tenantId: string): Promise<Invoice> {
|
|
43
|
+
const sub = await this.subscription(tenantId);
|
|
44
|
+
const { start, end } = monthlyPeriod(this.now());
|
|
45
|
+
const existing = await this.repo.findInvoiceForPeriod(tenantId, start);
|
|
46
|
+
if (existing) return existing;
|
|
47
|
+
const plan = PLANS[sub.plan];
|
|
48
|
+
const issuedAt = this.now();
|
|
49
|
+
const invoice: Invoice = {
|
|
50
|
+
id: randomUUID(), tenantId, plan: plan.id, amountCents: plan.monthlyPriceCents, currency: this.config.currency,
|
|
51
|
+
number: `INV-${start.toISOString().slice(0, 7)}-${tenantId.slice(0, 8)}`,
|
|
52
|
+
periodStart: start, periodEnd: end, status: plan.monthlyPriceCents === 0 ? 'paid' : 'open', issuedAt,
|
|
53
|
+
};
|
|
54
|
+
await this.repo.insertInvoice(invoice);
|
|
55
|
+
return invoice;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
listInvoices(tenantId: string): Promise<Invoice[]> {
|
|
59
|
+
return this.repo.listInvoices(tenantId);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Fatura de outro tenant responde 404, como se não existisse. */
|
|
63
|
+
async invoice(id: string, tenantId: string): Promise<Invoice> {
|
|
64
|
+
const found = await this.repo.findInvoice(id, tenantId);
|
|
65
|
+
if (!found) throw new NotFoundException('Fatura não encontrada');
|
|
66
|
+
return found;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
import { BillingService } from './application/billing.service.js';
|
|
3
|
+
import { BILLING_REPOSITORY, CLOCK } from './domain/ports.js';
|
|
4
|
+
import { TypeOrmBillingRepository } from './adapters/persistence/typeorm-billing.repository.js';
|
|
5
|
+
import { BillingController } from './adapters/http/billing.controller.js';
|
|
6
|
+
|
|
7
|
+
@Module({
|
|
8
|
+
controllers: [BillingController],
|
|
9
|
+
providers: [BillingService, { provide: BILLING_REPOSITORY, useClass: TypeOrmBillingRepository }, { provide: CLOCK, useValue: () => new Date() }],
|
|
10
|
+
})
|
|
11
|
+
export class BillingModule {}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { canChangePlan, isPlanId, PLANS } from './plan.js';
|
|
2
|
+
|
|
3
|
+
describe('política de planos', () => {
|
|
4
|
+
it.each([
|
|
5
|
+
{ from: 'free', to: 'pro', ok: true },
|
|
6
|
+
{ from: 'free', to: 'enterprise', ok: true },
|
|
7
|
+
{ from: 'pro', to: 'free', ok: true },
|
|
8
|
+
{ from: 'pro', to: 'enterprise', ok: true },
|
|
9
|
+
{ from: 'enterprise', to: 'pro', ok: false },
|
|
10
|
+
{ from: 'enterprise', to: 'free', ok: false },
|
|
11
|
+
] as const)('$from → $to: $ok', ({ from, to, ok }) => {
|
|
12
|
+
expect(canChangePlan(from, to)).toBe(ok);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('preços são centavos inteiros', () => {
|
|
16
|
+
for (const plan of Object.values(PLANS)) expect(Number.isSafeInteger(plan.monthlyPriceCents)).toBe(true);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('reconhece só os planos da tabela', () => {
|
|
20
|
+
expect(isPlanId('pro')).toBe(true);
|
|
21
|
+
expect(isPlanId('gold')).toBe(false);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Política de planos: preço em centavos (inteiro, nunca float), limites e transições permitidas.
|
|
3
|
+
* Mudar um preço ou uma regra de transição é mudar este arquivo, e os testes dizem o que quebrou.
|
|
4
|
+
*/
|
|
5
|
+
export const PLAN_IDS = ['free', 'pro', 'enterprise'] as const;
|
|
6
|
+
export type PlanId = (typeof PLAN_IDS)[number];
|
|
7
|
+
|
|
8
|
+
export interface Plan {
|
|
9
|
+
readonly id: PlanId;
|
|
10
|
+
readonly monthlyPriceCents: number;
|
|
11
|
+
/** null = sem limite. */
|
|
12
|
+
readonly apiCallsPerMonth: number | null;
|
|
13
|
+
readonly seats: number | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const PLANS: Readonly<Record<PlanId, Plan>> = {
|
|
17
|
+
free: { id: 'free', monthlyPriceCents: 0, apiCallsPerMonth: 1_000, seats: 3 },
|
|
18
|
+
pro: { id: 'pro', monthlyPriceCents: 9_900, apiCallsPerMonth: 100_000, seats: 25 },
|
|
19
|
+
// Enterprise é negociado: preço por contrato, não por tabela.
|
|
20
|
+
enterprise: { id: 'enterprise', monthlyPriceCents: 0, apiCallsPerMonth: null, seats: null },
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const TRANSITIONS: Readonly<Record<PlanId, readonly PlanId[]>> = {
|
|
24
|
+
free: ['pro', 'enterprise'],
|
|
25
|
+
pro: ['free', 'enterprise'],
|
|
26
|
+
// Sair do enterprise passa por contrato, não por autoatendimento.
|
|
27
|
+
enterprise: [],
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export function isPlanId(value: string): value is PlanId {
|
|
31
|
+
return (PLAN_IDS as readonly string[]).includes(value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function canChangePlan(from: PlanId, to: PlanId): boolean {
|
|
35
|
+
return TRANSITIONS[from].includes(to);
|
|
36
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { SubscriptionState } from './subscription.js';
|
|
2
|
+
|
|
3
|
+
export interface Invoice {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly tenantId: string;
|
|
6
|
+
readonly number: string;
|
|
7
|
+
readonly plan: string;
|
|
8
|
+
readonly amountCents: number;
|
|
9
|
+
readonly currency: string;
|
|
10
|
+
readonly periodStart: Date;
|
|
11
|
+
readonly periodEnd: Date;
|
|
12
|
+
readonly status: 'open' | 'paid' | 'void';
|
|
13
|
+
readonly issuedAt: Date;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface BillingRepository {
|
|
17
|
+
findSubscription(tenantId: string): Promise<SubscriptionState | null>;
|
|
18
|
+
saveSubscription(state: SubscriptionState): Promise<void>;
|
|
19
|
+
findInvoiceForPeriod(tenantId: string, periodStart: Date): Promise<Invoice | null>;
|
|
20
|
+
insertInvoice(invoice: Invoice): Promise<void>;
|
|
21
|
+
listInvoices(tenantId: string): Promise<Invoice[]>;
|
|
22
|
+
findInvoice(id: string, tenantId: string): Promise<Invoice | null>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const BILLING_REPOSITORY = Symbol('BILLING_REPOSITORY');
|
|
26
|
+
export const CLOCK = Symbol('CLOCK');
|
|
27
|
+
export type Clock = () => Date;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { InvalidPlanChange, monthlyPeriod, Subscription } from './subscription.js';
|
|
2
|
+
|
|
3
|
+
describe('Assinatura', () => {
|
|
4
|
+
it('começa no plano free, no período mensal em UTC do momento', () => {
|
|
5
|
+
const s = Subscription.start('s1', 't1', new Date('2026-03-15T23:30:00-03:00')).snapshot;
|
|
6
|
+
expect(s.plan).toBe('free');
|
|
7
|
+
expect(s.periodStart.toISOString()).toBe('2026-03-01T00:00:00.000Z');
|
|
8
|
+
expect(s.periodEnd.toISOString()).toBe('2026-04-01T00:00:00.000Z');
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it('virada de ano no período mensal', () => {
|
|
12
|
+
const { start, end } = monthlyPeriod(new Date('2026-12-31T12:00:00Z'));
|
|
13
|
+
expect([start.toISOString(), end.toISOString()]).toEqual(['2026-12-01T00:00:00.000Z', '2027-01-01T00:00:00.000Z']);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('transição inválida lança e deixa a assinatura como estava', () => {
|
|
17
|
+
const sub = Subscription.start('s1', 't1', new Date());
|
|
18
|
+
sub.changePlan('enterprise');
|
|
19
|
+
expect(() => sub.changePlan('free')).toThrow(InvalidPlanChange);
|
|
20
|
+
expect(sub.snapshot.plan).toBe('enterprise');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('mudar para o mesmo plano não é erro', () => {
|
|
24
|
+
const sub = Subscription.start('s1', 't1', new Date());
|
|
25
|
+
sub.changePlan('free');
|
|
26
|
+
expect(sub.snapshot.plan).toBe('free');
|
|
27
|
+
});
|
|
28
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { canChangePlan, type PlanId } from './plan.js';
|
|
2
|
+
|
|
3
|
+
export class InvalidPlanChange extends Error {
|
|
4
|
+
constructor(readonly from: PlanId, readonly to: PlanId) {
|
|
5
|
+
super(`Mudança de plano não permitida: ${from} → ${to}`);
|
|
6
|
+
this.name = 'InvalidPlanChange';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface SubscriptionState {
|
|
11
|
+
readonly id: string;
|
|
12
|
+
readonly tenantId: string;
|
|
13
|
+
readonly plan: PlanId;
|
|
14
|
+
readonly periodStart: Date;
|
|
15
|
+
readonly periodEnd: Date;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Período mensal em UTC que contém `at`: [primeiro dia do mês, primeiro dia do mês seguinte). */
|
|
19
|
+
export function monthlyPeriod(at: Date): { start: Date; end: Date } {
|
|
20
|
+
const start = new Date(Date.UTC(at.getUTCFullYear(), at.getUTCMonth(), 1));
|
|
21
|
+
const end = new Date(Date.UTC(at.getUTCFullYear(), at.getUTCMonth() + 1, 1));
|
|
22
|
+
return { start, end };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Agregado Assinatura: um por tenant; a mudança de plano respeita a política de transições. */
|
|
26
|
+
export class Subscription {
|
|
27
|
+
private constructor(private state: SubscriptionState) {}
|
|
28
|
+
|
|
29
|
+
static start(id: string, tenantId: string, at: Date): Subscription {
|
|
30
|
+
const { start, end } = monthlyPeriod(at);
|
|
31
|
+
return new Subscription({ id, tenantId, plan: 'free', periodStart: start, periodEnd: end });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
static restore(state: SubscriptionState): Subscription {
|
|
35
|
+
return new Subscription(state);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
get snapshot(): SubscriptionState {
|
|
39
|
+
return this.state;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
changePlan(to: PlanId): void {
|
|
43
|
+
if (to === this.state.plan) return;
|
|
44
|
+
if (!canChangePlan(this.state.plan, to)) throw new InvalidPlanChange(this.state.plan, to);
|
|
45
|
+
this.state = { ...this.state, plan: to };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { ApiProperty } from '@nestjs/swagger';
|
|
2
|
+
import { IsEmail, IsNotEmpty, IsString, Matches, MaxLength, MinLength } from 'class-validator';
|
|
3
|
+
|
|
4
|
+
export class SignupDto {
|
|
5
|
+
@ApiProperty() @IsEmail() @MaxLength(254) email: string;
|
|
6
|
+
|
|
7
|
+
@ApiProperty({ minLength: 12 })
|
|
8
|
+
@IsString() @MinLength(12) @MaxLength(128)
|
|
9
|
+
@Matches(/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, { message: 'A senha precisa ter minúscula, maiúscula e número' })
|
|
10
|
+
password: string;
|
|
11
|
+
|
|
12
|
+
@ApiProperty() @IsString() @IsNotEmpty() @MaxLength(120) organizationName: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class LoginDto {
|
|
16
|
+
@ApiProperty() @IsEmail() email: string;
|
|
17
|
+
@ApiProperty() @IsString() @IsNotEmpty() @MaxLength(128) password: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class RefreshDto {
|
|
21
|
+
@ApiProperty() @IsString() @IsNotEmpty() refreshToken: string;
|
|
22
|
+
}
|
package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/identity.controller.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Body, Controller, Get, HttpCode, Inject, NotFoundException, Post, UseGuards } from '@nestjs/common';
|
|
2
|
+
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
|
3
|
+
import { CurrentPrincipal, type Principal } from '../../../platform/auth/principal.js';
|
|
4
|
+
import { JwtAuthGuard } from '../../../platform/auth/jwt-auth.guard.js';
|
|
5
|
+
import { RequireRoles, RolesGuard } from '../../../platform/auth/roles.guard.js';
|
|
6
|
+
import { AuthService } from '../../application/auth.service.js';
|
|
7
|
+
import { IDENTITY_REPOSITORY, type IdentityRepository } from '../../domain/model.js';
|
|
8
|
+
import { LoginDto, RefreshDto, SignupDto } from './auth.dto.js';
|
|
9
|
+
|
|
10
|
+
@ApiTags('auth')
|
|
11
|
+
@Controller('auth')
|
|
12
|
+
export class AuthController {
|
|
13
|
+
constructor(private readonly auth: AuthService) {}
|
|
14
|
+
|
|
15
|
+
@Post('signup')
|
|
16
|
+
signup(@Body() dto: SignupDto) {
|
|
17
|
+
return this.auth.signup(dto);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
@Post('login')
|
|
21
|
+
@HttpCode(200)
|
|
22
|
+
login(@Body() dto: LoginDto) {
|
|
23
|
+
return this.auth.login(dto.email, dto.password);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
@Post('refresh')
|
|
27
|
+
@HttpCode(200)
|
|
28
|
+
refresh(@Body() dto: RefreshDto) {
|
|
29
|
+
return this.auth.refresh(dto.refreshToken);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
@ApiTags('identity')
|
|
34
|
+
@ApiBearerAuth()
|
|
35
|
+
@Controller()
|
|
36
|
+
@UseGuards(JwtAuthGuard, RolesGuard)
|
|
37
|
+
export class IdentityController {
|
|
38
|
+
constructor(@Inject(IDENTITY_REPOSITORY) private readonly repo: IdentityRepository) {}
|
|
39
|
+
|
|
40
|
+
@Get('me')
|
|
41
|
+
async me(@CurrentPrincipal() principal: Principal) {
|
|
42
|
+
const user = await this.repo.findUserById(principal.userId, principal.tenantId);
|
|
43
|
+
if (!user) throw new NotFoundException();
|
|
44
|
+
return { id: user.id, email: user.email, roles: user.roles };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
@Get('organization')
|
|
48
|
+
async organization(@CurrentPrincipal() principal: Principal) {
|
|
49
|
+
const org = await this.repo.findOrganization(principal.tenantId);
|
|
50
|
+
if (!org) throw new NotFoundException();
|
|
51
|
+
return org;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
@Get('users')
|
|
55
|
+
@RequireRoles('owner', 'admin')
|
|
56
|
+
async users(@CurrentPrincipal() principal: Principal) {
|
|
57
|
+
return (await this.repo.listUsers(principal.tenantId)).map((u) => ({ id: u.id, email: u.email, roles: u.roles, active: u.active }));
|
|
58
|
+
}
|
|
59
|
+
}
|
package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/orm-entities.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Column, CreateDateColumn, Entity, Index, PrimaryColumn, UpdateDateColumn } from 'typeorm';
|
|
2
|
+
|
|
3
|
+
@Entity('organizations')
|
|
4
|
+
export class OrganizationOrm {
|
|
5
|
+
@PrimaryColumn('uuid') id: string;
|
|
6
|
+
@Column('uuid', { unique: true }) tenantId: string;
|
|
7
|
+
@Column('varchar', { length: 120 }) name: string;
|
|
8
|
+
@Column('varchar', { length: 64, unique: true }) slug: string;
|
|
9
|
+
@Column('uuid') ownerId: string;
|
|
10
|
+
@CreateDateColumn({ type: 'timestamptz' }) createdAt: Date;
|
|
11
|
+
@UpdateDateColumn({ type: 'timestamptz' }) updatedAt: Date;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
@Entity('users')
|
|
15
|
+
@Index(['tenantId'])
|
|
16
|
+
export class UserOrm {
|
|
17
|
+
@PrimaryColumn('uuid') id: string;
|
|
18
|
+
@Column('uuid') tenantId: string;
|
|
19
|
+
@Column('varchar', { length: 254, unique: true }) email: string;
|
|
20
|
+
@Column('varchar', { length: 255 }) passwordHash: string;
|
|
21
|
+
@Column('simple-array') roles: string[];
|
|
22
|
+
@Column('boolean', { default: true }) active: boolean;
|
|
23
|
+
@CreateDateColumn({ type: 'timestamptz' }) createdAt: Date;
|
|
24
|
+
@UpdateDateColumn({ type: 'timestamptz' }) updatedAt: Date;
|
|
25
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { InjectDataSource } from '@nestjs/typeorm';
|
|
3
|
+
import { DataSource } from 'typeorm';
|
|
4
|
+
import { ROLES, type Role } from '../../../platform/auth/principal.js';
|
|
5
|
+
import type { IdentityRepository, Organization, User } from '../../domain/model.js';
|
|
6
|
+
import { OrganizationOrm, UserOrm } from './orm-entities.js';
|
|
7
|
+
|
|
8
|
+
const toUser = (row: UserOrm): User => ({
|
|
9
|
+
id: row.id, tenantId: row.tenantId, email: row.email, passwordHash: row.passwordHash, active: row.active,
|
|
10
|
+
roles: row.roles.filter((r): r is Role => (ROLES as readonly string[]).includes(r)),
|
|
11
|
+
});
|
|
12
|
+
const toOrg = (row: OrganizationOrm): Organization => ({ id: row.id, tenantId: row.tenantId, name: row.name, slug: row.slug, ownerId: row.ownerId });
|
|
13
|
+
|
|
14
|
+
@Injectable()
|
|
15
|
+
export class TypeOrmIdentityRepository implements IdentityRepository {
|
|
16
|
+
constructor(@InjectDataSource() private readonly ds: DataSource) {}
|
|
17
|
+
|
|
18
|
+
async findUserByEmail(email: string): Promise<User | null> {
|
|
19
|
+
const row = await this.ds.getRepository(UserOrm).findOneBy({ email });
|
|
20
|
+
return row ? toUser(row) : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async findUserById(id: string, tenantId: string): Promise<User | null> {
|
|
24
|
+
const row = await this.ds.getRepository(UserOrm).findOneBy({ id, tenantId });
|
|
25
|
+
return row ? toUser(row) : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async listUsers(tenantId: string): Promise<User[]> {
|
|
29
|
+
return (await this.ds.getRepository(UserOrm).find({ where: { tenantId }, order: { createdAt: 'ASC' } })).map(toUser);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async findOrganization(tenantId: string): Promise<Organization | null> {
|
|
33
|
+
const row = await this.ds.getRepository(OrganizationOrm).findOneBy({ tenantId });
|
|
34
|
+
return row ? toOrg(row) : null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async slugTaken(slug: string): Promise<boolean> {
|
|
38
|
+
return (await this.ds.getRepository(OrganizationOrm).countBy({ slug })) > 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async createTenant(org: Organization, owner: User): Promise<void> {
|
|
42
|
+
await this.ds.transaction(async (tx) => {
|
|
43
|
+
await tx.getRepository(OrganizationOrm).insert({ ...org });
|
|
44
|
+
await tx.getRepository(UserOrm).insert({ ...owner, roles: [...owner.roles] });
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { ConflictException, UnauthorizedException } from '@nestjs/common';
|
|
2
|
+
import { JwtService } from '@nestjs/jwt';
|
|
3
|
+
import { TokenService } from '../../platform/auth/token.service.js';
|
|
4
|
+
import type { IdentityRepository, Organization, User } from '../domain/model.js';
|
|
5
|
+
import { AuthService } from './auth.service.js';
|
|
6
|
+
|
|
7
|
+
class InMemoryIdentity implements IdentityRepository {
|
|
8
|
+
users: User[] = [];
|
|
9
|
+
orgs: Organization[] = [];
|
|
10
|
+
async findUserByEmail(email: string) { return this.users.find((u) => u.email === email) ?? null; }
|
|
11
|
+
async findUserById(id: string, tenantId: string) { return this.users.find((u) => u.id === id && u.tenantId === tenantId) ?? null; }
|
|
12
|
+
async listUsers(tenantId: string) { return this.users.filter((u) => u.tenantId === tenantId); }
|
|
13
|
+
async findOrganization(tenantId: string) { return this.orgs.find((o) => o.tenantId === tenantId) ?? null; }
|
|
14
|
+
async slugTaken(slug: string) { return this.orgs.some((o) => o.slug === slug); }
|
|
15
|
+
async createTenant(org: Organization, owner: User) { this.orgs.push(org); this.users.push(owner); }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const config = { jwtSecret: 'a'.repeat(40), jwtRefreshSecret: 'b'.repeat(40) } as never;
|
|
19
|
+
const setup = () => {
|
|
20
|
+
const repo = new InMemoryIdentity();
|
|
21
|
+
const tokens = new TokenService(new JwtService({}), config);
|
|
22
|
+
return { repo, tokens, auth: new AuthService(repo, tokens) };
|
|
23
|
+
};
|
|
24
|
+
const signup = { email: 'Dona@Empresa.com', password: 'Senha-Forte-123', organizationName: 'Empresa X' };
|
|
25
|
+
|
|
26
|
+
describe('AuthService', () => {
|
|
27
|
+
it('cadastro cria tenant, organização e dona, e devolve tokens', async () => {
|
|
28
|
+
const { repo, auth, tokens } = setup();
|
|
29
|
+
const session = await auth.signup(signup);
|
|
30
|
+
expect(repo.orgs).toHaveLength(1);
|
|
31
|
+
expect(repo.users[0]).toMatchObject({ email: 'dona@empresa.com', roles: ['owner'], tenantId: repo.orgs[0].tenantId });
|
|
32
|
+
const principal = await tokens.verifyAccess(session.accessToken);
|
|
33
|
+
expect(principal).toEqual({ userId: repo.users[0].id, tenantId: repo.orgs[0].tenantId, roles: ['owner'] });
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('e-mail repetido (qualquer caixa) é recusado', async () => {
|
|
37
|
+
const { auth } = setup();
|
|
38
|
+
await auth.signup(signup);
|
|
39
|
+
await expect(auth.signup({ ...signup, email: 'DONA@empresa.com' })).rejects.toBeInstanceOf(ConflictException);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('slug em uso ganha sufixo em vez de colidir', async () => {
|
|
43
|
+
const { auth, repo } = setup();
|
|
44
|
+
await auth.signup(signup);
|
|
45
|
+
await auth.signup({ ...signup, email: 'outra@empresa.com' });
|
|
46
|
+
expect(repo.orgs[0].slug).toBe('empresa-x');
|
|
47
|
+
expect(repo.orgs[1].slug).toMatch(/^empresa-x-[0-9a-f]{6}$/);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('login com senha errada ou e-mail inexistente dá a mesma resposta', async () => {
|
|
51
|
+
const { auth } = setup();
|
|
52
|
+
await auth.signup(signup);
|
|
53
|
+
await expect(auth.login('dona@empresa.com', 'errada')).rejects.toThrow('E-mail ou senha inválidos');
|
|
54
|
+
await expect(auth.login('ninguem@empresa.com', 'errada')).rejects.toThrow('E-mail ou senha inválidos');
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('refresh token não serve como access token, e vice-versa', async () => {
|
|
58
|
+
const { auth, tokens } = setup();
|
|
59
|
+
const session = await auth.signup(signup);
|
|
60
|
+
await expect(tokens.verifyAccess(session.refreshToken)).rejects.toBeInstanceOf(UnauthorizedException);
|
|
61
|
+
await expect(auth.refresh(session.accessToken)).rejects.toBeInstanceOf(UnauthorizedException);
|
|
62
|
+
const renewed = await auth.refresh(session.refreshToken);
|
|
63
|
+
expect(renewed.accessToken).toBeTypeOf('string');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('refresh de usuário desativado é recusado', async () => {
|
|
67
|
+
const { auth, repo } = setup();
|
|
68
|
+
const session = await auth.signup(signup);
|
|
69
|
+
repo.users[0] = { ...repo.users[0], active: false };
|
|
70
|
+
await expect(auth.refresh(session.refreshToken)).rejects.toBeInstanceOf(UnauthorizedException);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { ConflictException, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { TokenService, type TokenPair } from '../../platform/auth/token.service.js';
|
|
4
|
+
import { hashPassword, verifyPassword } from '../domain/password.js';
|
|
5
|
+
import { IDENTITY_REPOSITORY, normalizeEmail, toSlug, type IdentityRepository } from '../domain/model.js';
|
|
6
|
+
|
|
7
|
+
export interface SignupInput {
|
|
8
|
+
readonly email: string;
|
|
9
|
+
readonly password: string;
|
|
10
|
+
readonly organizationName: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface Session extends TokenPair {
|
|
14
|
+
readonly user: { readonly id: string; readonly email: string; readonly roles: readonly string[] };
|
|
15
|
+
readonly organization: { readonly id: string; readonly name: string; readonly slug: string };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Hash usado quando o e-mail não existe, para o tempo de resposta não revelar quem tem conta. */
|
|
19
|
+
const DUMMY_HASH = 'scrypt$32768$8$1$AAAAAAAAAAAAAAAAAAAAAA==$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==';
|
|
20
|
+
|
|
21
|
+
@Injectable()
|
|
22
|
+
export class AuthService {
|
|
23
|
+
constructor(
|
|
24
|
+
@Inject(IDENTITY_REPOSITORY) private readonly repo: IdentityRepository,
|
|
25
|
+
private readonly tokens: TokenService,
|
|
26
|
+
) {}
|
|
27
|
+
|
|
28
|
+
async signup(input: SignupInput): Promise<Session> {
|
|
29
|
+
const email = normalizeEmail(input.email);
|
|
30
|
+
if (await this.repo.findUserByEmail(email)) throw new ConflictException('E-mail já cadastrado');
|
|
31
|
+
|
|
32
|
+
let slug = toSlug(input.organizationName);
|
|
33
|
+
if (await this.repo.slugTaken(slug)) slug = `${slug}-${randomUUID().slice(0, 6)}`;
|
|
34
|
+
|
|
35
|
+
const tenantId = randomUUID();
|
|
36
|
+
const owner = { id: randomUUID(), tenantId, email, passwordHash: await hashPassword(input.password), roles: ['owner' as const], active: true };
|
|
37
|
+
const org = { id: randomUUID(), tenantId, name: input.organizationName.trim(), slug, ownerId: owner.id };
|
|
38
|
+
await this.repo.createTenant(org, owner);
|
|
39
|
+
return this.session(owner, org);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async login(emailInput: string, password: string): Promise<Session> {
|
|
43
|
+
const user = await this.repo.findUserByEmail(normalizeEmail(emailInput));
|
|
44
|
+
const valid = await verifyPassword(password, user?.passwordHash ?? DUMMY_HASH);
|
|
45
|
+
if (!user || !valid || !user.active) throw new UnauthorizedException('E-mail ou senha inválidos');
|
|
46
|
+
const org = await this.repo.findOrganization(user.tenantId);
|
|
47
|
+
if (!org) throw new UnauthorizedException('E-mail ou senha inválidos');
|
|
48
|
+
return this.session(user, org);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Renova o par a partir de um refresh token válido, relendo papéis e status atuais do usuário. */
|
|
52
|
+
async refresh(refreshToken: string): Promise<TokenPair> {
|
|
53
|
+
const principal = await this.tokens.verifyRefresh(refreshToken);
|
|
54
|
+
const user = await this.repo.findUserById(principal.userId, principal.tenantId);
|
|
55
|
+
if (!user?.active) throw new UnauthorizedException('Sessão inválida');
|
|
56
|
+
return this.tokens.issue({ userId: user.id, tenantId: user.tenantId, roles: user.roles });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private async session(user: { id: string; tenantId: string; email: string; roles: readonly ('owner' | 'admin' | 'member')[] }, org: { id: string; name: string; slug: string }): Promise<Session> {
|
|
60
|
+
const pair = await this.tokens.issue({ userId: user.id, tenantId: user.tenantId, roles: user.roles });
|
|
61
|
+
return { ...pair, user: { id: user.id, email: user.email, roles: user.roles }, organization: { id: org.id, name: org.name, slug: org.slug } };
|
|
62
|
+
}
|
|
63
|
+
}
|