franchising 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/cli/template-assets/api/src/main.ts +13 -11
  2. package/dist/cli/template-assets/api/src/modules/health/controller.ts +25 -4
  3. package/dist/cli/template-assets/api/src/shared/http/errors.ts +17 -0
  4. package/dist/cli/template-assets/cloudflare/cache.service.ts +1 -0
  5. package/dist/cli/template-assets/cloudflare/queue.service.ts +1 -0
  6. package/dist/cli/template-assets/cloudflare/worker.ts +4 -0
  7. package/dist/cli/template-assets/github/PULL_REQUEST_TEMPLATE.md +37 -0
  8. package/dist/cli/template-assets/observability/adapters.ts +37 -0
  9. package/dist/cli/template-assets/observability/bootstrap.ts +48 -0
  10. package/dist/cli/template-assets/observability/env.ts +21 -0
  11. package/dist/cli/template-assets/observability/index.ts +10 -0
  12. package/dist/cli/template-assets/observability/lifecycle.ts +97 -0
  13. package/dist/cli/template-assets/observability/local-index.ts +9 -0
  14. package/dist/cli/template-assets/observability/register.ts +12 -0
  15. package/dist/cli/template-assets/packages/jobs/src/index.ts +4 -40
  16. package/dist/cli/template-assets/packages/jobs/src/shared/queue/job-id.ts +9 -0
  17. package/dist/cli/template-assets/packages/jobs/src/shared/queue/options.ts +7 -0
  18. package/dist/cli/template-assets/packages/jobs/src/shared/queue/prefix.ts +18 -0
  19. package/dist/cli/template-assets/packages/queue/src/index.ts +4 -0
  20. package/dist/cli/template-assets/packages/queue/src/shared/errors/failure-reason.ts +7 -0
  21. package/dist/cli/template-assets/packages/{queue-runtime/src/index.ts → queue/src/shared/redis/connection.ts} +2 -15
  22. package/dist/cli/template-assets/packages/queue/src/types/redis/connection.ts +6 -0
  23. package/dist/cli/template-assets/packages/webhooks/src/index.ts +11 -0
  24. package/dist/cli/template-assets/packages/webhooks/src/shared/crypto/secret.ts +81 -0
  25. package/dist/cli/template-assets/packages/webhooks/src/shared/signing/headers.ts +43 -0
  26. package/dist/cli/template-assets/packages/webhooks/src/shared/url/deliverable.ts +58 -0
  27. package/dist/cli/template-assets/packages/webhooks/src/types/webhooks/job.ts +18 -0
  28. package/dist/cli/template-assets/packages/webhooks/test/webhooks.test.ts.tpl +69 -0
  29. package/dist/cli/template-assets/root/dot-dockerignore +88 -8
  30. package/dist/cli/template-assets/root/dot-oxlintrc.json +22 -0
  31. package/dist/cli/template-assets/root/lefthook.yml +32 -8
  32. package/dist/cli/template-assets/web/src/app/(app)/layout.tsx +2 -3
  33. package/dist/cli/template-assets/web/src/app/(auth)/login/page.tsx +1 -1
  34. package/dist/cli/template-assets/web/src/app/page.tsx +1 -0
  35. package/dist/cli/template-assets/web/src/{lib/api-client.ts → shared/api/client.ts} +11 -8
  36. package/dist/cli/template-assets/web/src/{lib/server-auth.ts → shared/auth/server.ts} +1 -2
  37. package/dist/cli/template-assets/web/src/types/api.ts +0 -15
  38. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/controller.ts +81 -0
  39. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/dto/create-endpoint.dto.ts +25 -0
  40. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/dto/endpoint.dto.ts +28 -0
  41. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/module.ts +27 -0
  42. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/repository.ts +147 -0
  43. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/service.ts +119 -0
  44. package/dist/cli/template-assets/webhooks/api/src/types/webhooks/endpoint.ts +26 -0
  45. package/dist/cli/template-assets/webhooks/worker/src/env.ts +18 -0
  46. package/dist/cli/template-assets/webhooks/worker/src/modules/queue/dispatcher.ts +119 -0
  47. package/dist/cli/template-assets/webhooks/worker/src/modules/queue/module.ts +16 -0
  48. package/dist/cli/template-assets/webhooks/worker/src/modules/queue/processor.ts +176 -0
  49. package/dist/cli/template-assets/webhooks/worker/src/modules/queue/repository.ts +187 -0
  50. package/dist/cli/template-assets/webhooks/worker/src/shared/http/deliver.ts +41 -0
  51. package/dist/cli/template-assets/webhooks/worker/src/types/webhooks/dispatch.ts +26 -0
  52. package/dist/cli/template-assets/worker/src/app.module.ts +14 -0
  53. package/dist/cli/template-assets/worker/src/main.ts +24 -0
  54. package/dist/cli/template-assets/worker/src/modules/queue/processor.ts +26 -3
  55. package/dist/cli/template-assets/worker/src/modules/queue/retry.ts +22 -7
  56. package/dist/cli/template-assets/worker/test/retry.test.ts.tpl +13 -1
  57. package/dist/cli/template-assets/worker-messaging/messaging-api-service.ts +6 -6
  58. package/dist/cli/template-assets/worker-messaging/src/env.ts +1 -1
  59. package/dist/cli/template-assets/worker-messaging/src/modules/messaging/service.ts +2 -4
  60. package/dist/cli/template-assets/worker-messaging/src/modules/queue/module.ts +1 -1
  61. package/dist/cli/template-assets/worker-messaging/src/modules/queue/processor.ts +32 -10
  62. package/dist/cli.js +631 -314
  63. package/dist/{index-BDYdEWl2.d.ts → index-B_byXBRW.d.cts} +10 -2
  64. package/dist/{index-BDYdEWl2.d.cts → index-B_byXBRW.d.ts} +10 -2
  65. package/dist/{index-u3ArUXO0.d.ts → index-CNlb6WNr.d.ts} +2 -2
  66. package/dist/{index--EJQTnHy.d.cts → index-I_Nx5SsQ.d.cts} +2 -2
  67. package/dist/index.cjs +1 -1
  68. package/dist/index.d.cts +1 -1
  69. package/dist/index.d.ts +1 -1
  70. package/dist/index.js +1 -1
  71. package/dist/messaging/index.cjs +1 -1
  72. package/dist/messaging/index.d.cts +1 -1
  73. package/dist/messaging/index.d.ts +1 -1
  74. package/dist/messaging/index.js +1 -1
  75. package/dist/sso/client.d.cts +7 -2
  76. package/dist/sso/client.d.ts +7 -2
  77. package/dist/sso/index.cjs +3 -1
  78. package/dist/sso/index.cjs.map +1 -1
  79. package/dist/sso/index.d.cts +1 -1
  80. package/dist/sso/index.d.ts +1 -1
  81. package/dist/sso/index.js +3 -1
  82. package/dist/sso/index.js.map +1 -1
  83. package/dist/sso/nestjs.d.cts +2 -2
  84. package/dist/sso/nestjs.d.ts +2 -2
  85. package/dist/sso/resource.d.cts +2 -2
  86. package/dist/sso/resource.d.ts +2 -2
  87. package/dist/version-Cm1EJ-YK.js +1 -0
  88. package/dist/{version-CrBclf1K.cjs → version-iERj9NJ6.cjs} +1 -1
  89. package/package.json +1 -1
  90. package/dist/cli/template-assets/api/src/errors/codes.ts +0 -17
  91. package/dist/cli/template-assets/api/src/errors/index.ts +0 -16
  92. package/dist/cli/template-assets/api/src/filters/exception.ts +0 -53
  93. package/dist/cli/template-assets/api/src/shared/exceptions.ts +0 -40
  94. package/dist/cli/template-assets/api/src/shared/response.ts +0 -31
  95. package/dist/cli/template-assets/api/src/telemetry.ts +0 -59
  96. package/dist/version-BhZpPjUh.js +0 -1
  97. /package/dist/cli/template-assets/web/src/{lib/auth-client.ts → shared/auth/client.ts} +0 -0
@@ -0,0 +1,81 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ randomBytes,
5
+ } from 'node:crypto';
6
+
7
+ const ALGORITHM = 'aes-256-gcm';
8
+
9
+ const VERSION = 'v1';
10
+
11
+ /**
12
+ * Chave de `WEBHOOK_SECRETS_KEY`: 32 bytes em base64.
13
+ *
14
+ * @remarks
15
+ * Gere com `openssl rand -base64 32`. Trocar a chave invalida todos os
16
+ * segredos ja gravados: quem rotacionar precisa decifrar com a velha e cifrar
17
+ * com a nova.
18
+ */
19
+ function keyFrom(base64: string): Buffer {
20
+ const key = Buffer.from(base64, 'base64');
21
+
22
+ if (key.length !== 32)
23
+ throw new Error('WEBHOOK_SECRETS_KEY precisa ter 32 bytes em base64.');
24
+
25
+ return key;
26
+ }
27
+
28
+ /**
29
+ * Segredo novo no formato do Standard Webhooks (`whsec_` + base64).
30
+ *
31
+ * @remarks
32
+ * 24 bytes aleatorios, dentro da faixa de 24 a 64 que a especificacao pede.
33
+ */
34
+ export function generateWebhookSecret(): string {
35
+ return `whsec_${randomBytes(24).toString('base64')}`;
36
+ }
37
+
38
+ /**
39
+ * Cifra o segredo para gravar no banco.
40
+ *
41
+ * @remarks
42
+ * AES-256-GCM com IV aleatorio por segredo; a tag de autenticacao impede que
43
+ * alguem com acesso ao banco troque o valor cifrado sem ser percebido.
44
+ */
45
+ export function sealWebhookSecret(secret: string, keyBase64: string): string {
46
+ const iv = randomBytes(12);
47
+ const cipher = createCipheriv(ALGORITHM, keyFrom(keyBase64), iv);
48
+
49
+ const encrypted = Buffer.concat([
50
+ cipher.update(secret, 'utf8'),
51
+ cipher.final(),
52
+ ]);
53
+
54
+ return [
55
+ VERSION,
56
+ iv.toString('base64'),
57
+ cipher.getAuthTag().toString('base64'),
58
+ encrypted.toString('base64'),
59
+ ].join(':');
60
+ }
61
+
62
+ /** Decifra o que `sealWebhookSecret` gravou. */
63
+ export function openWebhookSecret(sealed: string, keyBase64: string): string {
64
+ const [version, iv, tag, encrypted] = sealed.split(':');
65
+
66
+ if (version !== VERSION || !(iv && tag && encrypted))
67
+ throw new Error('WEBHOOK_SECRET_FORMAT_INVALID');
68
+
69
+ const decipher = createDecipheriv(
70
+ ALGORITHM,
71
+ keyFrom(keyBase64),
72
+ Buffer.from(iv, 'base64'),
73
+ );
74
+
75
+ decipher.setAuthTag(Buffer.from(tag, 'base64'));
76
+
77
+ return Buffer.concat([
78
+ decipher.update(Buffer.from(encrypted, 'base64')),
79
+ decipher.final(),
80
+ ]).toString('utf8');
81
+ }
@@ -0,0 +1,43 @@
1
+ import { Webhook } from 'standardwebhooks';
2
+ import type { WebhookHeaders } from '../../types/webhooks/job';
3
+
4
+ /**
5
+ * Corpo e cabecalhos assinados de uma entrega.
6
+ *
7
+ * @remarks
8
+ * Segue o Standard Webhooks (https://www.standardwebhooks.com): o corpo e
9
+ * `{ type, timestamp, data }`, e a assinatura cobre id, horario e corpo. O
10
+ * `webhook-timestamp` e o horario da tentativa, para o receptor recusar
11
+ * replay antigo; o `webhook-id` e o mesmo em toda tentativa, para ele
12
+ * descartar a entrega repetida.
13
+ */
14
+ export function signWebhook(input: {
15
+ secret: string;
16
+ messageId: string;
17
+ eventType: string;
18
+ payload: unknown;
19
+ occurredAt: string;
20
+ now?: Date | undefined;
21
+ }): { body: string; headers: WebhookHeaders } {
22
+ const now = input.now ?? new Date();
23
+
24
+ const body = JSON.stringify({
25
+ type: input.eventType,
26
+ timestamp: input.occurredAt,
27
+ data: input.payload,
28
+ });
29
+
30
+ return {
31
+ body,
32
+ headers: {
33
+ 'content-type': 'application/json',
34
+ 'webhook-id': input.messageId,
35
+ 'webhook-timestamp': Math.floor(now.getTime() / 1000).toString(),
36
+ 'webhook-signature': new Webhook(input.secret).sign(
37
+ input.messageId,
38
+ now,
39
+ body,
40
+ ),
41
+ },
42
+ };
43
+ }
@@ -0,0 +1,58 @@
1
+ import { isIP } from 'node:net';
2
+
3
+ /*
4
+ * Faixas que nunca recebem webhook em producao: loopback, rede privada,
5
+ * link-local (inclui o metadata da nuvem em 169.254.169.254) e CGNAT.
6
+ */
7
+ const PRIVATE_IPV4 = [
8
+ /^0\./,
9
+ /^10\./,
10
+ /^127\./,
11
+ /^169\.254\./,
12
+ /^172\.(?:1[6-9]|2\d|3[01])\./,
13
+ /^192\.168\./,
14
+ /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./,
15
+ ];
16
+
17
+ function isPrivateHost(hostname: string): boolean {
18
+ const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
19
+
20
+ if (host === 'localhost' || host.endsWith('.localhost')) return true;
21
+
22
+ if (isIP(host) === 4) return PRIVATE_IPV4.some((range) => range.test(host));
23
+
24
+ if (isIP(host) === 6)
25
+ return (
26
+ host === '::1' ||
27
+ host === '::' ||
28
+ host.startsWith('fc') ||
29
+ host.startsWith('fd') ||
30
+ host.startsWith('fe80')
31
+ );
32
+
33
+ return false;
34
+ }
35
+
36
+ /**
37
+ * URL que pode receber webhook.
38
+ *
39
+ * @remarks
40
+ * O endereco vem de quem cadastra o endpoint; sem esta checagem, o worker
41
+ * viraria um proxy para a rede interna (SSRF). Em producao so `https` e sem
42
+ * host privado; em desenvolvimento `http://localhost` passa, para testar com
43
+ * um receptor local. Nome de host que resolve para IP privado nao e pego
44
+ * aqui: para isso, restrinja a saida do worker na rede.
45
+ */
46
+ export function isDeliverableUrl(raw: string, production: boolean): boolean {
47
+ let url: URL;
48
+
49
+ try {
50
+ url = new URL(raw);
51
+ } catch {
52
+ return false;
53
+ }
54
+
55
+ if (!production) return url.protocol === 'https:' || url.protocol === 'http:';
56
+
57
+ return url.protocol === 'https:' && !isPrivateHost(url.hostname);
58
+ }
@@ -0,0 +1,18 @@
1
+ /** Job de entrega: um evento do outbox para um endpoint inscrito nele. */
2
+ export type WebhookDeliveryJob = {
3
+ /** Id do evento no outbox; vira o `webhook-id`, igual em toda tentativa. */
4
+ messageId: string;
5
+ endpointId: string;
6
+ eventType: string;
7
+ payload: unknown;
8
+ /** Quando o evento aconteceu (ISO 8601), e nao quando foi entregue. */
9
+ occurredAt: string;
10
+ };
11
+
12
+ /** Cabecalhos do Standard Webhooks. */
13
+ export type WebhookHeaders = {
14
+ 'content-type': 'application/json';
15
+ 'webhook-id': string;
16
+ 'webhook-timestamp': string;
17
+ 'webhook-signature': string;
18
+ };
@@ -0,0 +1,69 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { Webhook } from 'standardwebhooks';
3
+ import {
4
+ generateWebhookSecret,
5
+ isDeliverableUrl,
6
+ openWebhookSecret,
7
+ sealWebhookSecret,
8
+ signWebhook,
9
+ } from '../src';
10
+
11
+ const key = Buffer.alloc(32, 7).toString('base64');
12
+
13
+ describe('segredo', () => {
14
+ it('cifra e decifra', () => {
15
+ const secret = generateWebhookSecret();
16
+ const sealed = sealWebhookSecret(secret, key);
17
+
18
+ expect(sealed).not.toContain(secret);
19
+ expect(openWebhookSecret(sealed, key)).toBe(secret);
20
+ });
21
+
22
+ it('recusa valor adulterado', () => {
23
+ const sealed = sealWebhookSecret(generateWebhookSecret(), key);
24
+ const [version, iv, tag] = sealed.split(':');
25
+
26
+ expect(() =>
27
+ openWebhookSecret(`${version}:${iv}:${tag}:AAAA`, key),
28
+ ).toThrow();
29
+ });
30
+ });
31
+
32
+ describe('assinatura', () => {
33
+ it('sai no formato que o receptor do Standard Webhooks verifica', () => {
34
+ const secret = generateWebhookSecret();
35
+
36
+ const { body, headers } = signWebhook({
37
+ secret,
38
+ messageId: 'msg_1',
39
+ eventType: 'user.created',
40
+ payload: { id: 'u_1' },
41
+ occurredAt: new Date().toISOString(),
42
+ });
43
+
44
+ expect(new Webhook(secret).verify(body, headers)).toMatchObject({
45
+ type: 'user.created',
46
+ data: { id: 'u_1' },
47
+ });
48
+ });
49
+ });
50
+
51
+ describe('URL', () => {
52
+ it('em producao, so https publico', () => {
53
+ expect(isDeliverableUrl('https://exemplo.com/hook', true)).toBe(true);
54
+
55
+ for (const url of [
56
+ 'http://exemplo.com/hook',
57
+ 'https://localhost/hook',
58
+ 'https://127.0.0.1/hook',
59
+ 'https://10.0.0.5/hook',
60
+ 'https://169.254.169.254/latest',
61
+ 'https://[::1]/hook',
62
+ ])
63
+ expect(isDeliverableUrl(url, true)).toBe(false);
64
+ });
65
+
66
+ it('em desenvolvimento, aceita http local', () => {
67
+ expect(isDeliverableUrl('http://localhost:4000/hook', false)).toBe(true);
68
+ });
69
+ });
@@ -1,11 +1,91 @@
1
- .git
2
- .github
3
- .code-review-graph
4
- **/.env
5
- **/.env.*
1
+ # Contexto de build do Docker.
2
+ #
3
+ # O Dockerfile faz `COPY . .`: tudo que nao estiver aqui vai para dentro da
4
+ # imagem, deixa o build mais lento e invalida o cache a cada mudanca. Regra:
5
+ # so entra o que o install e o build precisam (package.json, lockfile,
6
+ # tsconfig, codigo de apps/ e packages/, configs de build e migrations).
7
+
8
+ # Dependencias: o install roda dentro da imagem, para a plataforma dela.
9
+ # Copiar o node_modules da maquina traria binarios nativos do sistema errado.
10
+ **/node_modules
11
+ **/.pnpm-store
12
+ **/.bun
13
+
14
+ # Saidas de build e caches: o build da imagem gera tudo de novo. Um dist velho
15
+ # copiado poderia sobreviver e rodar codigo que nao existe mais no fonte.
16
+ **/dist
17
+ **/build
18
+ **/out
6
19
  **/.next
20
+ **/.vinext
21
+ **/.open-next
22
+ **/.worker-build
7
23
  **/.turbo
24
+ **/.cache
25
+ **/*.tsbuildinfo
26
+
27
+ # Segredos: nunca podem parar numa camada da imagem, que qualquer um com acesso
28
+ # ao registry consegue ler. Em producao as variaveis vem da plataforma de deploy.
29
+ **/.env
30
+ **/.env.*
31
+ **/.dev.vars
32
+ **/.dev.vars.*
33
+ **/*.pem
34
+ **/*.key
35
+
36
+ # Git e CI: historico e workflows nao servem para rodar a app.
37
+ .git
38
+ .gitignore
39
+ .gitattributes
40
+ .github
41
+
42
+ # Testes e cobertura: o build usa o tsconfig.build.json, que nao compila testes.
8
43
  **/coverage
9
- **/dist
10
- **/node_modules
11
- *.log
44
+ **/.nyc_output
45
+ **/test
46
+ **/tests
47
+ **/__tests__
48
+ **/e2e
49
+ **/*.test.ts
50
+ **/*.test.tsx
51
+ **/*.spec.ts
52
+ **/*.spec.tsx
53
+
54
+ # Documentacao: nao e lida nem no build nem em runtime.
55
+ **/*.md
56
+ **/docs
57
+
58
+ # Ferramentas de desenvolvimento: lint, formatacao, hooks e editor rodam na
59
+ # maquina de quem programa e no CI, nunca na imagem.
60
+ lefthook.yml
61
+ commitlint.config.ts
62
+ **/.oxlintrc.json
63
+ **/.oxfmtrc.json
64
+ **/.editorconfig
65
+ **/.vscode
66
+ **/.idea
67
+ **/*.swp
68
+ **/.DS_Store
69
+
70
+ # Agentes e indices locais: contexto de IA e grafo de codigo, so para o editor.
71
+ **/.claude
72
+ **/.agents
73
+ **/.code-review-graph
74
+
75
+ # Docker e deploy: o proprio Dockerfile, o compose e as configs de plataforma
76
+ # sao lidos pela ferramenta de deploy, de fora do contexto.
77
+ **/Dockerfile
78
+ **/Dockerfile.*
79
+ **/docker-compose*.yml
80
+ **/compose*.yml
81
+ .dockerignore
82
+ **/railway.json
83
+ **/vercel.json
84
+ **/.vercel
85
+ **/.wrangler
86
+ infra
87
+
88
+ # Logs e temporarios.
89
+ **/*.log
90
+ **/tmp
91
+ **/.tmp
@@ -17,8 +17,30 @@
17
17
  "nextjs"
18
18
  // #endif
19
19
  ],
20
+ "jsPlugins": ["@stylistic/eslint-plugin"],
20
21
  "rules": {
21
22
  "typescript/consistent-type-imports": "off",
23
+ "curly": ["error", "multi"],
24
+ "@stylistic/padding-line-between-statements": [
25
+ "error",
26
+ { "blankLine": "always", "prev": "*", "next": "return" },
27
+ { "blankLine": "always", "prev": ["const", "let", "var"], "next": "*" },
28
+ {
29
+ "blankLine": "any",
30
+ "prev": ["const", "let", "var"],
31
+ "next": ["const", "let", "var"]
32
+ },
33
+ {
34
+ "blankLine": "always",
35
+ "prev": "*",
36
+ "next": ["multiline-expression", "multiline-const", "multiline-let", "multiline-var", "multiline-block-like"]
37
+ },
38
+ {
39
+ "blankLine": "always",
40
+ "prev": ["multiline-expression", "multiline-const", "multiline-let", "multiline-var", "multiline-block-like"],
41
+ "next": "*"
42
+ }
43
+ ],
22
44
  // #if hasWeb
23
45
  "react/react-in-jsx-scope": "off",
24
46
  // #endif
@@ -1,17 +1,41 @@
1
+ # Git hooks do projeto (https://lefthook.dev).
2
+ #
3
+ # O commit so olha os arquivos staged, para continuar rapido; typecheck e
4
+ # testes pegam o projeto inteiro e ficam no push. Build fica de fora: o CI ja
5
+ # roda, e esperar o build a cada push trava o fluxo sem pegar erro novo.
6
+ #
7
+ # Pular num caso pontual: LEFTHOOK=0 git commit ... (o CI continua valendo).
8
+
9
+ # #if ultracite
1
10
  pre-commit:
2
- parallel: false
11
+ # Em sequencia: o check precisa ver o arquivo que o fix ja corrigiu.
12
+ piped: true
3
13
  commands:
4
- format:
5
- glob: '*.{ts,tsx,js,jsx,json,jsonc,css,md}'
14
+ fix:
15
+ priority: 1
16
+ glob: '*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,json,jsonc,css,md}'
6
17
  run: __ROCK_PM_EXEC__ ultracite fix {staged_files}
7
18
  stage_fixed: true
8
- types:
9
- run: __ROCK_PM__ run typecheck
10
- test:
11
- run: __ROCK_PM__ run test
19
+ check:
20
+ priority: 2
21
+ glob: '*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}'
22
+ run: __ROCK_PM_EXEC__ ultracite check {staged_files}
23
+
24
+ # #endif
25
+ # #if commitlint
26
+ commit-msg:
27
+ commands:
28
+ commitlint:
29
+ run: __ROCK_PM_EXEC__ commitlint --edit {1}
30
+
31
+ # #endif
12
32
  pre-push:
13
- parallel: false
33
+ parallel: true
14
34
  commands:
35
+ # #if ultracite
36
+ lint:
37
+ run: __ROCK_PM__ run lint
38
+ # #endif
15
39
  types:
16
40
  run: __ROCK_PM__ run typecheck
17
41
  test:
@@ -1,7 +1,7 @@
1
1
  import { redirect } from 'next/navigation';
2
2
  import type { ReactNode } from 'react';
3
3
  import { AppShell } from '@/components/shell/app-shell';
4
- import { getSession } from '@/lib/server-auth';
4
+ import { getSession } from '@/shared/auth/server';
5
5
 
6
6
  /*
7
7
  * A sessao e lida no servidor e o redirecionamento acontece antes de qualquer
@@ -17,9 +17,8 @@ export default async function AppLayout({
17
17
  }) {
18
18
  const session = await getSession();
19
19
 
20
- if (!session) {
20
+ if (!session)
21
21
  redirect('/login');
22
- }
23
22
 
24
23
  return <AppShell>{children}</AppShell>;
25
24
  }
@@ -13,7 +13,7 @@ import Image from 'next/image';
13
13
  import Link from 'next/link';
14
14
  import { useRouter } from 'next/navigation';
15
15
  import { useState } from 'react';
16
- import { authClient } from '@/lib/auth-client';
16
+ import { authClient } from '@/shared/auth/client';
17
17
 
18
18
  export default function LoginPage() {
19
19
  const router = useRouter();
@@ -4,6 +4,7 @@ import { redirect } from 'next/navigation';
4
4
  export default function HomePage() {
5
5
  redirect('/dashboard');
6
6
  }
7
+
7
8
  // #else
8
9
  export default function HomePage() {
9
10
  return (
@@ -1,5 +1,9 @@
1
1
  import { env } from '@/env';
2
- import type { ApiEnvelope } from '@/types/api';
2
+ /*
3
+ * So o tipo: a entrada `franchising/http` tambem exporta o filtro NestJS, e um
4
+ * import de valor puxaria o `@nestjs/common` para o bundle do Next.
5
+ */
6
+ import type { APIResponse } from 'franchising/http';
3
7
 
4
8
  /**
5
9
  * Erro vindo da API, ja com o codigo estavel do contrato.
@@ -13,7 +17,7 @@ export class ApiClientError extends Error {
13
17
  readonly code: string,
14
18
  message: string,
15
19
  readonly status: number,
16
- readonly errors?: unknown,
20
+ readonly extra?: unknown,
17
21
  ) {
18
22
  super(message);
19
23
  this.name = 'ApiClientError';
@@ -42,16 +46,15 @@ export async function apiFetch<Data>(
42
46
 
43
47
  const payload = (await response
44
48
  .json()
45
- .catch(() => null)) as ApiEnvelope<Data> | null;
49
+ .catch(() => null)) as APIResponse<Data> | null;
46
50
 
47
- if (!response.ok || !payload?.ok) {
51
+ if (!response.ok || !payload?.ok)
48
52
  throw new ApiClientError(
49
- payload && !payload.ok ? payload.code : 'INTERNAL_ERROR',
50
- payload && !payload.ok ? payload.message : 'Request failed.',
53
+ payload && !payload.ok ? payload.error.code : 'InternalError',
54
+ payload && !payload.ok ? payload.error.message : 'Request failed.',
51
55
  response.status,
52
- payload && !payload.ok ? payload.errors : undefined,
56
+ payload && !payload.ok ? payload.error.extra : void 0,
53
57
  );
54
- }
55
58
 
56
59
  return payload.data;
57
60
  }
@@ -27,9 +27,8 @@ export async function getSession(): Promise<AuthSession | null> {
27
27
  },
28
28
  );
29
29
 
30
- if (!response.ok) {
30
+ if (!response.ok)
31
31
  return null;
32
- }
33
32
 
34
33
  return (await response.json()) as AuthSession | null;
35
34
  } catch {
@@ -1,18 +1,3 @@
1
- export type ApiSuccess<Data> = {
2
- ok: true;
3
- data: Data;
4
- };
5
-
6
- export type ApiFailure = {
7
- ok: false;
8
- code: string;
9
- message: string;
10
- errors?: unknown;
11
- };
12
-
13
- /** Envelope unico da API: o campo `ok` decide qual lado ler. */
14
- export type ApiEnvelope<Data> = ApiSuccess<Data> | ApiFailure;
15
-
16
1
  export type AuthSession = {
17
2
  user: { id: string; name: string; email: string };
18
3
  };
@@ -0,0 +1,81 @@
1
+ import {
2
+ Body,
3
+ Controller,
4
+ Delete,
5
+ Get,
6
+ Param,
7
+ ParseUUIDPipe,
8
+ Post,
9
+ } from '@nestjs/common';
10
+ import { ApiOperation, ApiTags } from '@nestjs/swagger';
11
+ import { Session, type UserSession } from '@thallesp/nestjs-better-auth';
12
+ import { CommonErrors, ok } from 'franchising/http';
13
+ import { APIEnvelope, APIErrors } from 'franchising/http/swagger';
14
+ import { Errors } from '../../shared/http/errors';
15
+ import { CreateWebhookEndpointDto } from './dto/create-endpoint.dto';
16
+ import { WebhookEndpointDto } from './dto/endpoint.dto';
17
+ import { WebhooksService } from './service';
18
+
19
+ /**
20
+ * Endpoints de webhook do usuario da sessao.
21
+ *
22
+ * @remarks
23
+ * O dono e sempre `session.user.id`: nenhuma rota aceita `ownerId` no corpo,
24
+ * entao ninguem cadastra nem altera endpoint em nome de outro usuario.
25
+ */
26
+ @ApiTags('Webhooks')
27
+ @Controller('webhooks/endpoints')
28
+ export class WebhooksController {
29
+ constructor(private readonly service: WebhooksService) {}
30
+
31
+ @Get()
32
+ @ApiOperation({ summary: 'Lista os endpoints do usuario' })
33
+ @APIEnvelope(WebhookEndpointDto, { isArray: true })
34
+ @APIErrors({ 401: [CommonErrors.Unauthorized] })
35
+ async list(@Session() session: UserSession) {
36
+ return ok(await this.service.list(session.user.id));
37
+ }
38
+
39
+ @Post()
40
+ @ApiOperation({ summary: 'Cadastra um endpoint e devolve o segredo' })
41
+ @APIEnvelope(WebhookEndpointDto)
42
+ @APIErrors({
43
+ 400: [Errors.WebhookUrlNotAllowed, CommonErrors.ValidationFailed],
44
+ 401: [CommonErrors.Unauthorized],
45
+ })
46
+ async create(
47
+ @Session() session: UserSession,
48
+ @Body() body: CreateWebhookEndpointDto,
49
+ ) {
50
+ return ok(await this.service.create(session.user.id, body));
51
+ }
52
+
53
+ @Post(':id/rotate-secret')
54
+ @ApiOperation({ summary: 'Troca o segredo de assinatura' })
55
+ @APIEnvelope(WebhookEndpointDto)
56
+ @APIErrors({
57
+ 401: [CommonErrors.Unauthorized],
58
+ 404: [Errors.WebhookEndpointNotFound],
59
+ })
60
+ async rotateSecret(
61
+ @Session() session: UserSession,
62
+ @Param('id', ParseUUIDPipe) id: string,
63
+ ) {
64
+ return ok(await this.service.rotateSecret(session.user.id, id));
65
+ }
66
+
67
+ /** Desativa, e nao apaga: o historico de entregas continua consultavel. */
68
+ @Delete(':id')
69
+ @ApiOperation({ summary: 'Desativa um endpoint' })
70
+ @APIEnvelope(WebhookEndpointDto)
71
+ @APIErrors({
72
+ 401: [CommonErrors.Unauthorized],
73
+ 404: [Errors.WebhookEndpointNotFound],
74
+ })
75
+ async disable(
76
+ @Session() session: UserSession,
77
+ @Param('id', ParseUUIDPipe) id: string,
78
+ ) {
79
+ return ok(await this.service.disable(session.user.id, id));
80
+ }
81
+ }
@@ -0,0 +1,25 @@
1
+ import { ApiProperty } from '@nestjs/swagger';
2
+ import {
3
+ ArrayMaxSize,
4
+ ArrayNotEmpty,
5
+ IsArray,
6
+ IsString,
7
+ IsUrl,
8
+ Matches,
9
+ MaxLength,
10
+ } from 'class-validator';
11
+
12
+ export class CreateWebhookEndpointDto {
13
+ @ApiProperty({ example: 'https://exemplo.com/webhooks' })
14
+ @IsUrl({ require_protocol: true, protocols: ['https', 'http'] })
15
+ @MaxLength(2048)
16
+ url!: string;
17
+
18
+ @ApiProperty({ example: ['user.created'], type: [String] })
19
+ @IsArray()
20
+ @ArrayNotEmpty()
21
+ @ArrayMaxSize(100)
22
+ @IsString({ each: true })
23
+ @Matches(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/, { each: true })
24
+ eventTypes!: string[];
25
+ }