forjajs 5.0.1 → 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.
- package/CHANGELOG.md +38 -2
- package/README.md +4 -2
- package/README.pt-BR.md +4 -1
- 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/bin/init-project.js +1 -0
- package/dist/lib/core/journey.js +10 -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 +74 -2
- package/dist/lib/validators/structure-validator.js +0 -1
- package/dist/packages/llm/src/index.js +12 -2
- package/dist/scripts/llm-fit.js +23 -1
- package/docs/llm-fit-loop.md +16 -0
- 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/package.json +1 -1
- 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/templates/project/AGENTS.md +9 -0
- 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,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
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { normalizeEmail, toSlug } from './model.js';
|
|
2
|
+
|
|
3
|
+
describe('identidade', () => {
|
|
4
|
+
it.each([
|
|
5
|
+
{ name: 'minúsculas e hífens', input: 'Minha Empresa', want: 'minha-empresa' },
|
|
6
|
+
{ name: 'remove acentos', input: 'Ação & Cia', want: 'acao-cia' },
|
|
7
|
+
{ name: 'apara separadores nas pontas', input: ' --Loja-- ', want: 'loja' },
|
|
8
|
+
])('slug: $name', ({ input, want }) => {
|
|
9
|
+
expect(toSlug(input)).toBe(want);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it('slug sem letras nem números é recusado', () => {
|
|
13
|
+
expect(() => toSlug('!!!')).toThrow();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('e-mail é comparado em minúsculas e sem espaços', () => {
|
|
17
|
+
expect(normalizeEmail(' Ana@Exemplo.COM ')).toBe('ana@exemplo.com');
|
|
18
|
+
});
|
|
19
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Role } from '../../platform/auth/principal.js';
|
|
2
|
+
|
|
3
|
+
export interface Organization {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly tenantId: string;
|
|
6
|
+
readonly name: string;
|
|
7
|
+
readonly slug: string;
|
|
8
|
+
readonly ownerId: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface User {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly tenantId: string;
|
|
14
|
+
readonly email: string;
|
|
15
|
+
readonly passwordHash: string;
|
|
16
|
+
readonly roles: readonly Role[];
|
|
17
|
+
readonly active: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** E-mail é a identidade de login: global (o login não sabe o tenant), comparado em minúsculas. */
|
|
21
|
+
export function normalizeEmail(email: string): string {
|
|
22
|
+
return email.trim().toLowerCase();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function toSlug(name: string): string {
|
|
26
|
+
const slug = name.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
|
27
|
+
if (!slug) throw new Error('Nome da organização precisa ter letras ou números');
|
|
28
|
+
return slug.slice(0, 60);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Portas de persistência: o domínio declara, os adaptadores TypeORM implementam. */
|
|
32
|
+
export interface IdentityRepository {
|
|
33
|
+
findUserByEmail(email: string): Promise<User | null>;
|
|
34
|
+
findUserById(id: string, tenantId: string): Promise<User | null>;
|
|
35
|
+
listUsers(tenantId: string): Promise<User[]>;
|
|
36
|
+
findOrganization(tenantId: string): Promise<Organization | null>;
|
|
37
|
+
slugTaken(slug: string): Promise<boolean>;
|
|
38
|
+
/** Cria a organização e o dono numa transação só: nunca um sem o outro. */
|
|
39
|
+
createTenant(org: Organization, owner: User): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const IDENTITY_REPOSITORY = Symbol('IDENTITY_REPOSITORY');
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { hashPassword, verifyPassword } from './password.js';
|
|
2
|
+
|
|
3
|
+
describe('senha (scrypt)', () => {
|
|
4
|
+
it('confere a senha certa e recusa a errada', async () => {
|
|
5
|
+
const hash = await hashPassword('Correta-Senha-123');
|
|
6
|
+
expect(await verifyPassword('Correta-Senha-123', hash)).toBe(true);
|
|
7
|
+
expect(await verifyPassword('correta-senha-123', hash)).toBe(false);
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
it('gera hashes diferentes para a mesma senha (salt)', async () => {
|
|
11
|
+
expect(await hashPassword('Igual-Senha-123')).not.toBe(await hashPassword('Igual-Senha-123'));
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('recusa hash malformado sem lançar', async () => {
|
|
15
|
+
expect(await verifyPassword('x', 'bcrypt$abc')).toBe(false);
|
|
16
|
+
});
|
|
17
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { randomBytes, scrypt, timingSafeEqual, type ScryptOptions } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Hash de senha com scrypt (node:crypto): sem dependência nativa para instalar. Formato:
|
|
5
|
+
* `scrypt$N$r$p$<salt base64>$<hash base64>`, para os parâmetros poderem subir sem invalidar hashes antigos.
|
|
6
|
+
*/
|
|
7
|
+
const PARAMS = { N: 2 ** 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 } as const;
|
|
8
|
+
const KEYLEN = 64;
|
|
9
|
+
|
|
10
|
+
function derive(password: string, salt: Buffer, options: ScryptOptions): Promise<Buffer> {
|
|
11
|
+
return new Promise((resolve, reject) => scrypt(password.normalize('NFKC'), salt, KEYLEN, options, (err, key) => (err ? reject(err) : resolve(key))));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function hashPassword(password: string): Promise<string> {
|
|
15
|
+
const salt = randomBytes(16);
|
|
16
|
+
const key = await derive(password, salt, PARAMS);
|
|
17
|
+
return ['scrypt', PARAMS.N, PARAMS.r, PARAMS.p, salt.toString('base64'), key.toString('base64')].join('$');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function verifyPassword(password: string, stored: string): Promise<boolean> {
|
|
21
|
+
const [scheme, n, r, p, salt, hash] = stored.split('$');
|
|
22
|
+
if (scheme !== 'scrypt' || !salt || !hash) return false;
|
|
23
|
+
const expected = Buffer.from(hash, 'base64');
|
|
24
|
+
const key = await derive(password, Buffer.from(salt, 'base64'), { N: Number(n), r: Number(r), p: Number(p), maxmem: PARAMS.maxmem });
|
|
25
|
+
return key.length === expected.length && timingSafeEqual(key, expected);
|
|
26
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
import { AuthService } from './application/auth.service.js';
|
|
3
|
+
import { IDENTITY_REPOSITORY } from './domain/model.js';
|
|
4
|
+
import { TypeOrmIdentityRepository } from './adapters/persistence/typeorm-identity.repository.js';
|
|
5
|
+
import { AuthController, IdentityController } from './adapters/http/identity.controller.js';
|
|
6
|
+
|
|
7
|
+
@Module({
|
|
8
|
+
controllers: [AuthController, IdentityController],
|
|
9
|
+
providers: [AuthService, { provide: IDENTITY_REPOSITORY, useClass: TypeOrmIdentityRepository }],
|
|
10
|
+
exports: [IDENTITY_REPOSITORY],
|
|
11
|
+
})
|
|
12
|
+
export class IdentityModule {}
|
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
import
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
2
3
|
import { ValidationPipe } from '@nestjs/common';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
4
|
+
import { NestFactory } from '@nestjs/core';
|
|
5
|
+
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
|
6
|
+
import { AppModule } from './app.module.js';
|
|
7
|
+
import { APP_CONFIG, type AppConfig } from './platform/config.js';
|
|
5
8
|
|
|
6
|
-
async function bootstrap() {
|
|
9
|
+
async function bootstrap(): Promise<void> {
|
|
10
|
+
// .env é opcional: em produção as variáveis vêm do ambiente.
|
|
11
|
+
if (existsSync('.env')) process.loadEnvFile('.env');
|
|
7
12
|
const app = await NestFactory.create(AppModule);
|
|
8
|
-
|
|
9
|
-
app.useGlobalPipes(new ValidationPipe({ transform: true }));
|
|
10
13
|
app.setGlobalPrefix('api');
|
|
14
|
+
// whitelist + forbidNonWhitelisted: campos fora do DTO são rejeitados (nada de atribuição em massa).
|
|
15
|
+
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
|
|
16
|
+
app.enableShutdownHooks();
|
|
11
17
|
|
|
12
|
-
const config =
|
|
13
|
-
|
|
14
|
-
.
|
|
15
|
-
.
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const document = SwaggerModule.createDocument(app, config);
|
|
20
|
-
SwaggerModule.setup('api/docs', app, document);
|
|
21
|
-
|
|
22
|
-
await app.listen(process.env.PORT || 3000);
|
|
23
|
-
console.log(`🚀 Server running on http://localhost:${process.env.PORT || 3000}`);
|
|
18
|
+
const config = app.get<AppConfig>(APP_CONFIG);
|
|
19
|
+
if (!config.production) {
|
|
20
|
+
const doc = new DocumentBuilder().setTitle('SaaS Starter API').setVersion('0.1.0').addBearerAuth().build();
|
|
21
|
+
SwaggerModule.setup('api/docs', app, SwaggerModule.createDocument(app, doc));
|
|
22
|
+
}
|
|
23
|
+
await app.listen(config.port);
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
bootstrap();
|
|
26
|
+
await bootstrap();
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Injectable, UnauthorizedException, type CanActivate, type ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import type { AuthenticatedRequest } from './principal.js';
|
|
3
|
+
import { TokenService } from './token.service.js';
|
|
4
|
+
|
|
5
|
+
@Injectable()
|
|
6
|
+
export class JwtAuthGuard implements CanActivate {
|
|
7
|
+
constructor(private readonly tokens: TokenService) {}
|
|
8
|
+
|
|
9
|
+
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
10
|
+
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
|
11
|
+
const header = request.headers.authorization;
|
|
12
|
+
const value = Array.isArray(header) ? header[0] : header;
|
|
13
|
+
if (!value?.startsWith('Bearer ')) throw new UnauthorizedException('Token ausente');
|
|
14
|
+
request.principal = await this.tokens.verifyAccess(value.slice('Bearer '.length));
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createParamDecorator, type ExecutionContext } from '@nestjs/common';
|
|
2
|
+
|
|
3
|
+
export const ROLES = ['owner', 'admin', 'member'] as const;
|
|
4
|
+
export type Role = (typeof ROLES)[number];
|
|
5
|
+
|
|
6
|
+
/** Quem está chamando: vem só do token verificado, nunca do corpo da requisição. */
|
|
7
|
+
export interface Principal {
|
|
8
|
+
readonly userId: string;
|
|
9
|
+
readonly tenantId: string;
|
|
10
|
+
readonly roles: readonly Role[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface AuthenticatedRequest {
|
|
14
|
+
principal?: Principal;
|
|
15
|
+
headers: Record<string, string | string[] | undefined>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const CurrentPrincipal = createParamDecorator((_: unknown, ctx: ExecutionContext): Principal => {
|
|
19
|
+
const principal = ctx.switchToHttp().getRequest<AuthenticatedRequest>().principal;
|
|
20
|
+
if (!principal) throw new Error('CurrentPrincipal usado em rota sem JwtAuthGuard');
|
|
21
|
+
return principal;
|
|
22
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ForbiddenException, type ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import { RolesGuard } from './roles.guard.js';
|
|
4
|
+
import type { Role } from './principal.js';
|
|
5
|
+
|
|
6
|
+
const ctx = (roles: Role[] | undefined): ExecutionContext => ({
|
|
7
|
+
getHandler: () => () => undefined,
|
|
8
|
+
getClass: () => class {},
|
|
9
|
+
switchToHttp: () => ({ getRequest: () => ({ principal: roles ? { userId: 'u', tenantId: 't', roles } : undefined }) }),
|
|
10
|
+
}) as unknown as ExecutionContext;
|
|
11
|
+
|
|
12
|
+
describe('RolesGuard', () => {
|
|
13
|
+
const guardFor = (required: Role[] | undefined) => new RolesGuard({ getAllAndOverride: () => required } as unknown as Reflector);
|
|
14
|
+
|
|
15
|
+
it('rota sem papéis exigidos libera qualquer autenticado', () => {
|
|
16
|
+
expect(guardFor(undefined).canActivate(ctx(['member']))).toBe(true);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('libera quem tem um dos papéis e barra quem não tem', () => {
|
|
20
|
+
expect(guardFor(['owner', 'admin']).canActivate(ctx(['admin']))).toBe(true);
|
|
21
|
+
expect(() => guardFor(['owner']).canActivate(ctx(['member']))).toThrow(ForbiddenException);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ForbiddenException, Injectable, SetMetadata, type CanActivate, type ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import type { AuthenticatedRequest, Role } from './principal.js';
|
|
4
|
+
|
|
5
|
+
const ROLES_KEY = 'roles';
|
|
6
|
+
export const RequireRoles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
|
|
7
|
+
|
|
8
|
+
/** Use depois do JwtAuthGuard. Sem @RequireRoles na rota, qualquer usuário autenticado passa. */
|
|
9
|
+
@Injectable()
|
|
10
|
+
export class RolesGuard implements CanActivate {
|
|
11
|
+
constructor(private readonly reflector: Reflector) {}
|
|
12
|
+
|
|
13
|
+
canActivate(context: ExecutionContext): boolean {
|
|
14
|
+
const required = this.reflector.getAllAndOverride<Role[] | undefined>(ROLES_KEY, [context.getHandler(), context.getClass()]);
|
|
15
|
+
if (!required?.length) return true;
|
|
16
|
+
const roles = context.switchToHttp().getRequest<AuthenticatedRequest>().principal?.roles ?? [];
|
|
17
|
+
if (!required.some((role) => roles.includes(role))) throw new ForbiddenException('Permissão insuficiente');
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
|
2
|
+
import { JwtService } from '@nestjs/jwt';
|
|
3
|
+
import { APP_CONFIG, type AppConfig } from '../config.js';
|
|
4
|
+
import { ROLES, type Principal, type Role } from './principal.js';
|
|
5
|
+
|
|
6
|
+
export interface TokenPair {
|
|
7
|
+
readonly accessToken: string;
|
|
8
|
+
readonly refreshToken: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface Claims {
|
|
12
|
+
sub: string;
|
|
13
|
+
tid: string;
|
|
14
|
+
roles: Role[];
|
|
15
|
+
typ: 'access' | 'refresh';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Tokens de acesso (15 min) e de renovação (7 dias) com segredos distintos e tipo explícito. */
|
|
19
|
+
@Injectable()
|
|
20
|
+
export class TokenService {
|
|
21
|
+
constructor(
|
|
22
|
+
private readonly jwt: JwtService,
|
|
23
|
+
@Inject(APP_CONFIG) private readonly config: AppConfig,
|
|
24
|
+
) {}
|
|
25
|
+
|
|
26
|
+
async issue(principal: Principal): Promise<TokenPair> {
|
|
27
|
+
const base = { sub: principal.userId, tid: principal.tenantId, roles: [...principal.roles] };
|
|
28
|
+
const [accessToken, refreshToken] = await Promise.all([
|
|
29
|
+
this.jwt.signAsync({ ...base, typ: 'access' }, { secret: this.config.jwtSecret, expiresIn: '15m' }),
|
|
30
|
+
this.jwt.signAsync({ ...base, typ: 'refresh' }, { secret: this.config.jwtRefreshSecret, expiresIn: '7d' }),
|
|
31
|
+
]);
|
|
32
|
+
return { accessToken, refreshToken };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
verifyAccess(token: string): Promise<Principal> {
|
|
36
|
+
return this.verify(token, this.config.jwtSecret, 'access');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
verifyRefresh(token: string): Promise<Principal> {
|
|
40
|
+
return this.verify(token, this.config.jwtRefreshSecret, 'refresh');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
private async verify(token: string, secret: string, typ: Claims['typ']): Promise<Principal> {
|
|
44
|
+
let claims: Claims;
|
|
45
|
+
try {
|
|
46
|
+
claims = await this.jwt.verifyAsync<Claims>(token, { secret });
|
|
47
|
+
} catch {
|
|
48
|
+
throw new UnauthorizedException('Token inválido ou expirado');
|
|
49
|
+
}
|
|
50
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.filter((r): r is Role => (ROLES as readonly string[]).includes(r)) : [];
|
|
51
|
+
if (claims.typ !== typ || !claims.sub || !claims.tid) throw new UnauthorizedException('Token inválido ou expirado');
|
|
52
|
+
return { userId: claims.sub, tenantId: claims.tid, roles };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { loadConfig } from './config.js';
|
|
2
|
+
|
|
3
|
+
const ok = { DATABASE_URL: 'postgres://x', JWT_SECRET: 'a'.repeat(32), JWT_REFRESH_SECRET: 'b'.repeat(32) };
|
|
4
|
+
|
|
5
|
+
describe('configuração', () => {
|
|
6
|
+
it('sem segredos a API não sobe (nada de segredo padrão)', () => {
|
|
7
|
+
expect(() => loadConfig({ DATABASE_URL: 'postgres://x' })).toThrow(/JWT_SECRET, JWT_REFRESH_SECRET/);
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
it('segredos curtos ou iguais são recusados', () => {
|
|
11
|
+
expect(() => loadConfig({ ...ok, JWT_SECRET: 'curto' })).toThrow(/32 caracteres/);
|
|
12
|
+
expect(() => loadConfig({ ...ok, JWT_REFRESH_SECRET: ok.JWT_SECRET })).toThrow(/diferentes/);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('valores padrão para porta e moeda', () => {
|
|
16
|
+
expect(loadConfig(ok)).toMatchObject({ port: 3000, currency: 'BRL', production: false });
|
|
17
|
+
});
|
|
18
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuração lida do ambiente uma vez, no boot. Segredos não têm valor padrão: sem eles a API não
|
|
3
|
+
* sobe, em vez de subir assinando tokens com um segredo conhecido.
|
|
4
|
+
*/
|
|
5
|
+
export interface AppConfig {
|
|
6
|
+
readonly port: number;
|
|
7
|
+
readonly databaseUrl: string;
|
|
8
|
+
readonly jwtSecret: string;
|
|
9
|
+
readonly jwtRefreshSecret: string;
|
|
10
|
+
readonly currency: string;
|
|
11
|
+
readonly production: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const APP_CONFIG = Symbol('APP_CONFIG');
|
|
15
|
+
|
|
16
|
+
export function loadConfig(env: Record<string, string | undefined> = process.env): AppConfig {
|
|
17
|
+
const missing = ['DATABASE_URL', 'JWT_SECRET', 'JWT_REFRESH_SECRET'].filter((k) => !env[k]);
|
|
18
|
+
if (missing.length) throw new Error(`Variáveis de ambiente obrigatórias ausentes: ${missing.join(', ')} (veja .env.example)`);
|
|
19
|
+
if (env.JWT_SECRET === env.JWT_REFRESH_SECRET) throw new Error('JWT_SECRET e JWT_REFRESH_SECRET precisam ser diferentes');
|
|
20
|
+
if ((env.JWT_SECRET ?? '').length < 32 || (env.JWT_REFRESH_SECRET ?? '').length < 32) {
|
|
21
|
+
throw new Error('JWT_SECRET e JWT_REFRESH_SECRET precisam ter pelo menos 32 caracteres');
|
|
22
|
+
}
|
|
23
|
+
const port = Number(env.PORT ?? 3000);
|
|
24
|
+
if (!Number.isInteger(port) || port <= 0) throw new Error(`PORT inválida: ${env.PORT}`);
|
|
25
|
+
return {
|
|
26
|
+
port,
|
|
27
|
+
databaseUrl: env.DATABASE_URL as string,
|
|
28
|
+
jwtSecret: env.JWT_SECRET as string,
|
|
29
|
+
jwtRefreshSecret: env.JWT_REFRESH_SECRET as string,
|
|
30
|
+
currency: env.BILLING_CURRENCY ?? 'BRL',
|
|
31
|
+
production: env.NODE_ENV === 'production',
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Global, Module } from '@nestjs/common';
|
|
2
|
+
import { JwtModule } from '@nestjs/jwt';
|
|
3
|
+
import { APP_CONFIG, loadConfig } from './config.js';
|
|
4
|
+
import { TokenService } from './auth/token.service.js';
|
|
5
|
+
import { JwtAuthGuard } from './auth/jwt-auth.guard.js';
|
|
6
|
+
import { RolesGuard } from './auth/roles.guard.js';
|
|
7
|
+
|
|
8
|
+
@Global()
|
|
9
|
+
@Module({
|
|
10
|
+
imports: [JwtModule.register({})],
|
|
11
|
+
providers: [{ provide: APP_CONFIG, useFactory: () => loadConfig() }, TokenService, JwtAuthGuard, RolesGuard],
|
|
12
|
+
exports: [APP_CONFIG, TokenService, JwtAuthGuard, RolesGuard],
|
|
13
|
+
})
|
|
14
|
+
export class PlatformModule {}
|
|
@@ -1,28 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"compilerOptions": {
|
|
3
|
-
"module": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
"
|
|
3
|
+
"module": "nodenext",
|
|
4
|
+
"moduleResolution": "nodenext",
|
|
5
|
+
"resolvePackageJsonExports": true,
|
|
6
|
+
"esModuleInterop": true,
|
|
7
|
+
"isolatedModules": true,
|
|
8
|
+
"declaration": false,
|
|
9
|
+
"removeComments": true,
|
|
10
|
+
"emitDecoratorMetadata": true,
|
|
11
|
+
"experimentalDecorators": true,
|
|
12
|
+
"allowSyntheticDefaultImports": true,
|
|
13
|
+
"target": "ES2023",
|
|
14
|
+
"sourceMap": true,
|
|
7
15
|
"outDir": "./dist",
|
|
8
|
-
"
|
|
16
|
+
"rootDir": ".",
|
|
9
17
|
"incremental": true,
|
|
10
18
|
"skipLibCheck": true,
|
|
11
|
-
"
|
|
19
|
+
"strict": true,
|
|
12
20
|
"strictPropertyInitialization": false,
|
|
13
|
-
"
|
|
14
|
-
|
|
15
|
-
"resolveJsonModule": true,
|
|
16
|
-
"declaration": true,
|
|
17
|
-
"declarationMap": true,
|
|
18
|
-
"sourceMap": true,
|
|
19
|
-
"paths": {
|
|
20
|
-
"@/*": ["src/*"],
|
|
21
|
-
"@modules/*": ["src/modules/*"],
|
|
22
|
-
"@common/*": ["src/common/*"],
|
|
23
|
-
"@config/*": ["src/config/*"]
|
|
24
|
-
}
|
|
25
|
-
},
|
|
26
|
-
"include": ["src/**/*"],
|
|
27
|
-
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
|
|
21
|
+
"types": ["vitest/globals", "node"]
|
|
22
|
+
}
|
|
28
23
|
}
|
|
@@ -2,41 +2,46 @@
|
|
|
2
2
|
"schemaVersion": "1.0",
|
|
3
3
|
"type": "boilerplate",
|
|
4
4
|
"name": "02-saas-starter",
|
|
5
|
-
"title": "SaaS Starter -
|
|
5
|
+
"title": "SaaS Starter - API multi-tenant com assinatura e faturamento",
|
|
6
6
|
"path": "boilerplates/02-saas-starter",
|
|
7
7
|
"readme": "boilerplates/02-saas-starter/README.md",
|
|
8
8
|
"stack": [
|
|
9
|
-
"NestJS",
|
|
10
|
-
"
|
|
9
|
+
"NestJS 12",
|
|
10
|
+
"TypeORM",
|
|
11
|
+
"Postgres",
|
|
11
12
|
"JWT",
|
|
12
|
-
"
|
|
13
|
+
"Vitest"
|
|
13
14
|
],
|
|
14
15
|
"useCases": [
|
|
15
|
-
"SaaS",
|
|
16
|
-
"
|
|
17
|
-
"
|
|
18
|
-
"
|
|
16
|
+
"SaaS B2B",
|
|
17
|
+
"Multi-tenant",
|
|
18
|
+
"Assinatura",
|
|
19
|
+
"Faturamento",
|
|
20
|
+
"Auth com papéis"
|
|
19
21
|
],
|
|
20
22
|
"commands": [
|
|
21
23
|
"npm install",
|
|
22
24
|
"npm run start:dev",
|
|
23
|
-
"
|
|
24
|
-
"npm
|
|
25
|
+
"npm test",
|
|
26
|
+
"npm run lint"
|
|
25
27
|
],
|
|
26
28
|
"gates": [
|
|
27
|
-
"npm run spec:check",
|
|
28
29
|
"npm test",
|
|
29
|
-
"npm run
|
|
30
|
+
"npm run lint",
|
|
31
|
+
"npm run build"
|
|
30
32
|
],
|
|
31
33
|
"tokenPolicy": {
|
|
32
34
|
"firstRead": [
|
|
33
35
|
"boilerplate.manifest.json",
|
|
34
|
-
"README.md"
|
|
36
|
+
"README.md",
|
|
37
|
+
"memory/30-domains/identity/context.md",
|
|
38
|
+
"memory/30-domains/billing/context.md"
|
|
35
39
|
],
|
|
36
40
|
"avoidLoadingByDefault": [
|
|
37
41
|
"node_modules",
|
|
38
42
|
"dist",
|
|
39
43
|
"coverage"
|
|
40
44
|
]
|
|
41
|
-
}
|
|
45
|
+
},
|
|
46
|
+
"template": true
|
|
42
47
|
}
|