franchising 0.6.0 → 0.8.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/README.md +13 -72
- package/dist/{accounts-TyMPSHM0.cjs → accounts-BscmRiXc.cjs} +26 -1
- package/dist/{accounts-TyMPSHM0.cjs.map → accounts-BscmRiXc.cjs.map} +1 -1
- package/dist/{accounts-B4bnTXUd.js → accounts-DJRg4gXj.js} +26 -1
- package/dist/{accounts-B4bnTXUd.js.map → accounts-DJRg4gXj.js.map} +1 -1
- package/dist/cli/template-assets/api/src/main.ts +13 -11
- package/dist/cli/template-assets/api/src/modules/health/controller.ts +25 -4
- package/dist/cli/template-assets/api/src/shared/http/errors.ts +17 -0
- package/dist/cli/template-assets/cloudflare/cache.service.ts +1 -0
- package/dist/cli/template-assets/cloudflare/queue.service.ts +1 -0
- package/dist/cli/template-assets/cloudflare/worker.ts +4 -0
- package/dist/cli/template-assets/github/PULL_REQUEST_TEMPLATE.md +37 -0
- package/dist/cli/template-assets/observability/adapters.ts +37 -0
- package/dist/cli/template-assets/observability/bootstrap.ts +48 -0
- package/dist/cli/template-assets/observability/env.ts +21 -0
- package/dist/cli/template-assets/observability/index.ts +10 -0
- package/dist/cli/template-assets/observability/lifecycle.ts +97 -0
- package/dist/cli/template-assets/observability/local-index.ts +9 -0
- package/dist/cli/template-assets/observability/register.ts +12 -0
- package/dist/cli/template-assets/packages/jobs/src/index.ts +4 -40
- package/dist/cli/template-assets/packages/jobs/src/shared/queue/job-id.ts +9 -0
- package/dist/cli/template-assets/packages/jobs/src/shared/queue/options.ts +7 -0
- package/dist/cli/template-assets/packages/jobs/src/shared/queue/prefix.ts +18 -0
- package/dist/cli/template-assets/packages/queue/src/index.ts +4 -0
- package/dist/cli/template-assets/packages/queue/src/shared/errors/failure-reason.ts +7 -0
- package/dist/cli/template-assets/packages/{queue-runtime/src/index.ts → queue/src/shared/redis/connection.ts} +2 -15
- package/dist/cli/template-assets/packages/queue/src/types/redis/connection.ts +6 -0
- package/dist/cli/template-assets/packages/webhooks/src/index.ts +11 -0
- package/dist/cli/template-assets/packages/webhooks/src/shared/crypto/secret.ts +81 -0
- package/dist/cli/template-assets/packages/webhooks/src/shared/signing/headers.ts +43 -0
- package/dist/cli/template-assets/packages/webhooks/src/shared/url/deliverable.ts +58 -0
- package/dist/cli/template-assets/packages/webhooks/src/types/webhooks/job.ts +18 -0
- package/dist/cli/template-assets/packages/webhooks/test/webhooks.test.ts.tpl +69 -0
- package/dist/cli/template-assets/root/dot-dockerignore +88 -8
- package/dist/cli/template-assets/root/dot-oxlintrc.json +22 -0
- package/dist/cli/template-assets/root/lefthook.yml +32 -8
- package/dist/cli/template-assets/web/src/app/(app)/layout.tsx +2 -3
- package/dist/cli/template-assets/web/src/app/(auth)/login/page.tsx +1 -1
- package/dist/cli/template-assets/web/src/app/page.tsx +1 -0
- package/dist/cli/template-assets/web/src/{lib/api-client.ts → shared/api/client.ts} +11 -8
- package/dist/cli/template-assets/web/src/{lib/server-auth.ts → shared/auth/server.ts} +1 -2
- package/dist/cli/template-assets/web/src/types/api.ts +0 -15
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/controller.ts +81 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/dto/create-endpoint.dto.ts +25 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/dto/endpoint.dto.ts +28 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/module.ts +27 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/repository.ts +147 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/service.ts +119 -0
- package/dist/cli/template-assets/webhooks/api/src/types/webhooks/endpoint.ts +26 -0
- package/dist/cli/template-assets/webhooks/worker/src/env.ts +18 -0
- package/dist/cli/template-assets/webhooks/worker/src/modules/queue/dispatcher.ts +119 -0
- package/dist/cli/template-assets/webhooks/worker/src/modules/queue/module.ts +16 -0
- package/dist/cli/template-assets/webhooks/worker/src/modules/queue/processor.ts +176 -0
- package/dist/cli/template-assets/webhooks/worker/src/modules/queue/repository.ts +187 -0
- package/dist/cli/template-assets/webhooks/worker/src/shared/http/deliver.ts +41 -0
- package/dist/cli/template-assets/webhooks/worker/src/types/webhooks/dispatch.ts +26 -0
- package/dist/cli/template-assets/worker/src/app.module.ts +14 -0
- package/dist/cli/template-assets/worker/src/main.ts +24 -0
- package/dist/cli/template-assets/worker/src/modules/queue/processor.ts +26 -3
- package/dist/cli/template-assets/worker/src/modules/queue/retry.ts +22 -7
- package/dist/cli/template-assets/worker/test/retry.test.ts.tpl +13 -1
- package/dist/cli/template-assets/worker-messaging/messaging-api-service.ts +6 -6
- package/dist/cli/template-assets/worker-messaging/src/env.ts +1 -1
- package/dist/cli/template-assets/worker-messaging/src/modules/messaging/service.ts +2 -4
- package/dist/cli/template-assets/worker-messaging/src/modules/queue/module.ts +1 -1
- package/dist/cli/template-assets/worker-messaging/src/modules/queue/processor.ts +32 -10
- package/dist/cli.js +631 -314
- package/dist/{index-CNlb6WNr.d.ts → index-Bl4Ka1Wr.d.ts} +2 -2
- package/dist/{index-I_Nx5SsQ.d.cts → index-CBue43h0.d.cts} +2 -2
- package/dist/{index-B_byXBRW.d.ts → index-cKCKFKLi.d.cts} +181 -5
- package/dist/{index-B_byXBRW.d.cts → index-cKCKFKLi.d.ts} +181 -5
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/messaging/index.cjs +1 -1
- package/dist/messaging/index.d.cts +1 -1
- package/dist/messaging/index.d.ts +1 -1
- package/dist/messaging/index.js +1 -1
- package/dist/sso/client.d.cts +2 -2
- package/dist/sso/client.d.ts +2 -2
- package/dist/sso/index.cjs +72 -1
- package/dist/sso/index.cjs.map +1 -1
- package/dist/sso/index.d.cts +2 -2
- package/dist/sso/index.d.ts +2 -2
- package/dist/sso/index.js +72 -1
- package/dist/sso/index.js.map +1 -1
- package/dist/sso/nestjs.cjs +2 -2
- package/dist/sso/nestjs.d.cts +2 -2
- package/dist/sso/nestjs.d.ts +2 -2
- package/dist/sso/nestjs.js +2 -2
- package/dist/sso/resource.cjs +2 -2
- package/dist/sso/resource.d.cts +3 -3
- package/dist/sso/resource.d.ts +3 -3
- package/dist/sso/resource.js +2 -2
- package/dist/{verifier-BIBtPCVi.cjs → verifier-BYrFb8tg.cjs} +2 -2
- package/dist/{verifier-BIBtPCVi.cjs.map → verifier-BYrFb8tg.cjs.map} +1 -1
- package/dist/{verifier-DNdy5Ynw.js → verifier-DSvtdWuY.js} +2 -2
- package/dist/{verifier-DNdy5Ynw.js.map → verifier-DSvtdWuY.js.map} +1 -1
- package/dist/version-8Zc_uUvG.js +1 -0
- package/dist/{version-DDLRsahz.cjs → version-BMXokpna.cjs} +1 -1
- package/package.json +1 -1
- package/dist/cli/template-assets/api/src/errors/codes.ts +0 -17
- package/dist/cli/template-assets/api/src/errors/index.ts +0 -16
- package/dist/cli/template-assets/api/src/filters/exception.ts +0 -53
- package/dist/cli/template-assets/api/src/shared/exceptions.ts +0 -40
- package/dist/cli/template-assets/api/src/shared/response.ts +0 -31
- package/dist/cli/template-assets/api/src/telemetry.ts +0 -59
- package/dist/version-DHlIo_M1.js +0 -1
- /package/dist/cli/template-assets/web/src/{lib/auth-client.ts → shared/auth/client.ts} +0 -0
|
@@ -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
|
-
|
|
11
|
+
# Em sequencia: o check precisa ver o arquivo que o fix ja corrigiu.
|
|
12
|
+
piped: true
|
|
3
13
|
commands:
|
|
4
|
-
|
|
5
|
-
|
|
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
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
run:
|
|
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:
|
|
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 '@/
|
|
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 '@/
|
|
16
|
+
import { authClient } from '@/shared/auth/client';
|
|
17
17
|
|
|
18
18
|
export default function LoginPage() {
|
|
19
19
|
const router = useRouter();
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { env } from '@/env';
|
|
2
|
-
|
|
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
|
|
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
|
|
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 : '
|
|
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.
|
|
56
|
+
payload && !payload.ok ? payload.error.extra : void 0,
|
|
53
57
|
);
|
|
54
|
-
}
|
|
55
58
|
|
|
56
59
|
return payload.data;
|
|
57
60
|
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
|
2
|
+
|
|
3
|
+
export class WebhookEndpointDto {
|
|
4
|
+
@ApiProperty({ format: 'uuid' })
|
|
5
|
+
id!: string;
|
|
6
|
+
|
|
7
|
+
@ApiProperty({ example: 'https://exemplo.com/webhooks' })
|
|
8
|
+
url!: string;
|
|
9
|
+
|
|
10
|
+
@ApiProperty({ example: ['user.created'], type: [String] })
|
|
11
|
+
eventTypes!: string[];
|
|
12
|
+
|
|
13
|
+
@ApiProperty({ example: true })
|
|
14
|
+
enabled!: boolean;
|
|
15
|
+
|
|
16
|
+
@ApiProperty({ type: String, format: 'date-time' })
|
|
17
|
+
createdAt!: Date;
|
|
18
|
+
|
|
19
|
+
@ApiProperty({ type: String, format: 'date-time' })
|
|
20
|
+
updatedAt!: Date;
|
|
21
|
+
|
|
22
|
+
@ApiPropertyOptional({
|
|
23
|
+
example: 'whsec_...',
|
|
24
|
+
description:
|
|
25
|
+
'Segredo de assinatura (Standard Webhooks). Vem so na criacao e na rotacao: guarde na hora.',
|
|
26
|
+
})
|
|
27
|
+
secret?: string;
|
|
28
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
// #if routes
|
|
3
|
+
import { WebhooksController } from './controller';
|
|
4
|
+
// #endif
|
|
5
|
+
import { WebhooksRepository } from './repository';
|
|
6
|
+
import { WebhooksService } from './service';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Webhooks de saida.
|
|
10
|
+
*
|
|
11
|
+
* @remarks
|
|
12
|
+
* Exporta o `WebhooksService` para os outros modulos publicarem eventos com
|
|
13
|
+
* `publish`. A entrega roda no worker `apps/workers/webhooks`.
|
|
14
|
+
*/
|
|
15
|
+
// #if routes
|
|
16
|
+
@Module({
|
|
17
|
+
controllers: [WebhooksController],
|
|
18
|
+
providers: [WebhooksRepository, WebhooksService],
|
|
19
|
+
exports: [WebhooksService],
|
|
20
|
+
})
|
|
21
|
+
// #else
|
|
22
|
+
@Module({
|
|
23
|
+
providers: [WebhooksRepository, WebhooksService],
|
|
24
|
+
exports: [WebhooksService],
|
|
25
|
+
})
|
|
26
|
+
// #endif
|
|
27
|
+
export class WebhooksModule {}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
// #if drizzle
|
|
3
|
+
import { and, desc, eq } from 'drizzle-orm';
|
|
4
|
+
import {
|
|
5
|
+
type DatabaseTransaction,
|
|
6
|
+
webhookEndpoints,
|
|
7
|
+
webhookOutbox,
|
|
8
|
+
} from '__ROCK_SCOPE__/database';
|
|
9
|
+
// #else
|
|
10
|
+
import type { DatabaseTransaction } from '__ROCK_SCOPE__/database';
|
|
11
|
+
// #endif
|
|
12
|
+
import type {
|
|
13
|
+
NewWebhookEndpoint,
|
|
14
|
+
WebhookEndpointChanges,
|
|
15
|
+
WebhookEndpointRecord,
|
|
16
|
+
} from '../../types/webhooks/endpoint';
|
|
17
|
+
import { DatabaseService } from '../database/database.service';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Acesso a `webhook_endpoints` e `webhook_outbox`.
|
|
21
|
+
*
|
|
22
|
+
* @remarks
|
|
23
|
+
* Toda leitura e escrita de endpoint filtra por `ownerId`: o id do endpoint
|
|
24
|
+
* sozinho nao autoriza nada, entao um usuario nunca alcanca o endpoint de
|
|
25
|
+
* outro, nem adivinhando o id.
|
|
26
|
+
*/
|
|
27
|
+
@Injectable()
|
|
28
|
+
export class WebhooksRepository {
|
|
29
|
+
constructor(private readonly database: DatabaseService) {}
|
|
30
|
+
|
|
31
|
+
// #if drizzle
|
|
32
|
+
async create(input: NewWebhookEndpoint): Promise<WebhookEndpointRecord> {
|
|
33
|
+
const [row] = await this.database.client
|
|
34
|
+
.insert(webhookEndpoints)
|
|
35
|
+
.values(input)
|
|
36
|
+
.returning();
|
|
37
|
+
|
|
38
|
+
if (!row) throw new Error('WEBHOOK_ENDPOINT_NOT_CREATED');
|
|
39
|
+
|
|
40
|
+
return row;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
listByOwner(ownerId: string): Promise<WebhookEndpointRecord[]> {
|
|
44
|
+
return this.database.client
|
|
45
|
+
.select()
|
|
46
|
+
.from(webhookEndpoints)
|
|
47
|
+
.where(eq(webhookEndpoints.ownerId, ownerId))
|
|
48
|
+
.orderBy(desc(webhookEndpoints.createdAt));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async update(
|
|
52
|
+
ownerId: string,
|
|
53
|
+
id: string,
|
|
54
|
+
changes: WebhookEndpointChanges,
|
|
55
|
+
): Promise<WebhookEndpointRecord | undefined> {
|
|
56
|
+
const [row] = await this.database.client
|
|
57
|
+
.update(webhookEndpoints)
|
|
58
|
+
.set(changes)
|
|
59
|
+
.where(
|
|
60
|
+
and(
|
|
61
|
+
eq(webhookEndpoints.id, id),
|
|
62
|
+
eq(webhookEndpoints.ownerId, ownerId),
|
|
63
|
+
),
|
|
64
|
+
)
|
|
65
|
+
.returning();
|
|
66
|
+
|
|
67
|
+
return row;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Grava o evento no outbox, dentro da transacao de quem publica. */
|
|
71
|
+
async enqueue(
|
|
72
|
+
tx: DatabaseTransaction,
|
|
73
|
+
event: { ownerId: string; eventType: string; payload: unknown },
|
|
74
|
+
): Promise<string> {
|
|
75
|
+
const [row] = await tx
|
|
76
|
+
.insert(webhookOutbox)
|
|
77
|
+
.values(event)
|
|
78
|
+
.returning({ id: webhookOutbox.id });
|
|
79
|
+
|
|
80
|
+
if (!row) throw new Error('WEBHOOK_EVENT_NOT_CREATED');
|
|
81
|
+
|
|
82
|
+
return row.id;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Abre uma transacao so para o evento, quando quem publica nao tem uma. */
|
|
86
|
+
transaction<T>(fn: (tx: DatabaseTransaction) => Promise<T>): Promise<T> {
|
|
87
|
+
return this.database.client.transaction(fn);
|
|
88
|
+
}
|
|
89
|
+
// #else
|
|
90
|
+
create(input: NewWebhookEndpoint): Promise<WebhookEndpointRecord> {
|
|
91
|
+
return this.database.client.webhookEndpoint.create({ data: input });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
listByOwner(ownerId: string): Promise<WebhookEndpointRecord[]> {
|
|
95
|
+
return this.database.client.webhookEndpoint.findMany({
|
|
96
|
+
where: { ownerId },
|
|
97
|
+
orderBy: { createdAt: 'desc' },
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async update(
|
|
102
|
+
ownerId: string,
|
|
103
|
+
id: string,
|
|
104
|
+
changes: WebhookEndpointChanges,
|
|
105
|
+
): Promise<WebhookEndpointRecord | undefined> {
|
|
106
|
+
const { count } = await this.database.client.webhookEndpoint.updateMany({
|
|
107
|
+
where: { id, ownerId },
|
|
108
|
+
data: changes,
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
if (count === 0) return void 0;
|
|
112
|
+
|
|
113
|
+
return (
|
|
114
|
+
(await this.database.client.webhookEndpoint.findUnique({
|
|
115
|
+
where: { id },
|
|
116
|
+
})) ?? void 0
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Grava o evento no outbox, dentro da transacao de quem publica. */
|
|
121
|
+
async enqueue(
|
|
122
|
+
tx: DatabaseTransaction,
|
|
123
|
+
event: { ownerId: string; eventType: string; payload: unknown },
|
|
124
|
+
): Promise<string> {
|
|
125
|
+
const row = await tx.webhookOutbox.create({
|
|
126
|
+
data: {
|
|
127
|
+
ownerId: event.ownerId,
|
|
128
|
+
eventType: event.eventType,
|
|
129
|
+
/*
|
|
130
|
+
* Ida e volta pelo JSON: garante que o payload gravado e
|
|
131
|
+
* exatamente o que o receptor vai ler (sem `Date`, `undefined`
|
|
132
|
+
* ou classe), e satisfaz o tipo de coluna JSON do Prisma.
|
|
133
|
+
*/
|
|
134
|
+
payload: JSON.parse(JSON.stringify(event.payload ?? null)),
|
|
135
|
+
},
|
|
136
|
+
select: { id: true },
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
return row.id;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Abre uma transacao so para o evento, quando quem publica nao tem uma. */
|
|
143
|
+
transaction<T>(fn: (tx: DatabaseTransaction) => Promise<T>): Promise<T> {
|
|
144
|
+
return this.database.client.$transaction(fn);
|
|
145
|
+
}
|
|
146
|
+
// #endif
|
|
147
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { badRequest, notFound } from 'franchising/http';
|
|
3
|
+
import type { DatabaseTransaction } from '__ROCK_SCOPE__/database';
|
|
4
|
+
import {
|
|
5
|
+
generateWebhookSecret,
|
|
6
|
+
isDeliverableUrl,
|
|
7
|
+
sealWebhookSecret,
|
|
8
|
+
} from '__ROCK_SCOPE__/webhooks';
|
|
9
|
+
import { env } from '../../env';
|
|
10
|
+
import { Errors } from '../../shared/http/errors';
|
|
11
|
+
import type {
|
|
12
|
+
WebhookEndpointRecord,
|
|
13
|
+
WebhookEndpointView,
|
|
14
|
+
WebhookEndpointWithSecret,
|
|
15
|
+
} from '../../types/webhooks/endpoint';
|
|
16
|
+
import { WebhooksRepository } from './repository';
|
|
17
|
+
|
|
18
|
+
function toView({
|
|
19
|
+
secret: _secret,
|
|
20
|
+
ownerId: _ownerId,
|
|
21
|
+
...view
|
|
22
|
+
}: WebhookEndpointRecord): WebhookEndpointView {
|
|
23
|
+
return view;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Endpoints de webhook de cada usuario e publicacao de eventos.
|
|
28
|
+
*
|
|
29
|
+
* @remarks
|
|
30
|
+
* O segredo sai em texto so na criacao e na rotacao; no banco ele fica
|
|
31
|
+
* cifrado com `WEBHOOK_SECRETS_KEY`, e quem le o banco nao consegue assinar
|
|
32
|
+
* em nome da API.
|
|
33
|
+
*/
|
|
34
|
+
@Injectable()
|
|
35
|
+
export class WebhooksService {
|
|
36
|
+
constructor(private readonly repository: WebhooksRepository) {}
|
|
37
|
+
|
|
38
|
+
async create(
|
|
39
|
+
ownerId: string,
|
|
40
|
+
input: { url: string; eventTypes: string[] },
|
|
41
|
+
): Promise<WebhookEndpointWithSecret> {
|
|
42
|
+
if (!isDeliverableUrl(input.url, env.isProduction))
|
|
43
|
+
throw badRequest(Errors.WebhookUrlNotAllowed);
|
|
44
|
+
|
|
45
|
+
const secret = generateWebhookSecret();
|
|
46
|
+
|
|
47
|
+
const endpoint = await this.repository.create({
|
|
48
|
+
ownerId,
|
|
49
|
+
url: input.url,
|
|
50
|
+
eventTypes: [...new Set(input.eventTypes)],
|
|
51
|
+
secret: sealWebhookSecret(secret, env.WEBHOOK_SECRETS_KEY),
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
return { ...toView(endpoint), secret };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async list(ownerId: string): Promise<WebhookEndpointView[]> {
|
|
58
|
+
const endpoints = await this.repository.listByOwner(ownerId);
|
|
59
|
+
|
|
60
|
+
return endpoints.map((endpoint) => toView(endpoint));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Troca o segredo na hora.
|
|
65
|
+
*
|
|
66
|
+
* @remarks
|
|
67
|
+
* Entregas ja enfileiradas assinam com o segredo novo, porque o worker le
|
|
68
|
+
* o endpoint a cada tentativa: o receptor precisa trocar o dele junto.
|
|
69
|
+
*/
|
|
70
|
+
async rotateSecret(
|
|
71
|
+
ownerId: string,
|
|
72
|
+
id: string,
|
|
73
|
+
): Promise<WebhookEndpointWithSecret> {
|
|
74
|
+
const secret = generateWebhookSecret();
|
|
75
|
+
|
|
76
|
+
const endpoint = await this.repository.update(ownerId, id, {
|
|
77
|
+
secret: sealWebhookSecret(secret, env.WEBHOOK_SECRETS_KEY),
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
if (!endpoint) throw notFound(Errors.WebhookEndpointNotFound);
|
|
81
|
+
|
|
82
|
+
return { ...toView(endpoint), secret };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Para de entregar; as tentativas em andamento desistem na proxima. */
|
|
86
|
+
async disable(ownerId: string, id: string): Promise<WebhookEndpointView> {
|
|
87
|
+
const endpoint = await this.repository.update(ownerId, id, {
|
|
88
|
+
enabled: false,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
if (!endpoint) throw notFound(Errors.WebhookEndpointNotFound);
|
|
92
|
+
|
|
93
|
+
return toView(endpoint);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Publica um evento para os endpoints do dono.
|
|
98
|
+
*
|
|
99
|
+
* @remarks
|
|
100
|
+
* So grava no outbox. Passe a transacao da mudanca de negocio em `tx`: o
|
|
101
|
+
* evento existe se e somente se a mudanca foi gravada, e o worker
|
|
102
|
+
* `webhooks` entrega depois, mesmo que o Redis esteja fora agora. Devolve
|
|
103
|
+
* o id do evento, que vira o `webhook-id` de todas as entregas dele.
|
|
104
|
+
*/
|
|
105
|
+
publish(
|
|
106
|
+
eventType: string,
|
|
107
|
+
payload: unknown,
|
|
108
|
+
ownerId: string,
|
|
109
|
+
tx?: DatabaseTransaction,
|
|
110
|
+
): Promise<string> {
|
|
111
|
+
const event = { ownerId, eventType, payload };
|
|
112
|
+
|
|
113
|
+
if (tx) return this.repository.enqueue(tx, event);
|
|
114
|
+
|
|
115
|
+
return this.repository.transaction((transaction) =>
|
|
116
|
+
this.repository.enqueue(transaction, event),
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Linha de `webhook_endpoints`, com o segredo ainda cifrado. */
|
|
2
|
+
export type WebhookEndpointRecord = {
|
|
3
|
+
id: string;
|
|
4
|
+
ownerId: string;
|
|
5
|
+
url: string;
|
|
6
|
+
secret: string;
|
|
7
|
+
eventTypes: string[];
|
|
8
|
+
enabled: boolean;
|
|
9
|
+
createdAt: Date;
|
|
10
|
+
updatedAt: Date;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/** O que a API devolve: nunca o segredo, nem cifrado. */
|
|
14
|
+
export type WebhookEndpointView = Omit<WebhookEndpointRecord, 'secret' | 'ownerId'>;
|
|
15
|
+
|
|
16
|
+
/** Resposta de criacao e de rotacao: a unica vez que o segredo aparece. */
|
|
17
|
+
export type WebhookEndpointWithSecret = WebhookEndpointView & { secret: string };
|
|
18
|
+
|
|
19
|
+
export type NewWebhookEndpoint = Pick<
|
|
20
|
+
WebhookEndpointRecord,
|
|
21
|
+
'ownerId' | 'url' | 'secret' | 'eventTypes'
|
|
22
|
+
>;
|
|
23
|
+
|
|
24
|
+
export type WebhookEndpointChanges = Partial<
|
|
25
|
+
Pick<WebhookEndpointRecord, 'secret' | 'enabled'>
|
|
26
|
+
>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import 'dotenv/config';
|
|
2
|
+
import { cleanEnv, num, str } from 'envalid';
|
|
3
|
+
|
|
4
|
+
export const env = cleanEnv(process.env, {
|
|
5
|
+
NODE_ENV: str({
|
|
6
|
+
choices: ['development', 'test', 'production'],
|
|
7
|
+
default: 'development',
|
|
8
|
+
}),
|
|
9
|
+
QUEUE_REDIS_URL: str({ default: 'redis://localhost:6379' }),
|
|
10
|
+
QUEUE_PREFIX: str({ default: '__ROCK_PROJECT_SLUG__' }),
|
|
11
|
+
__ROCK_WORKER_CONCURRENCY_ENV__: num({ default: 10 }),
|
|
12
|
+
WEBHOOK_SECRETS_KEY: str({
|
|
13
|
+
desc: 'Chave AES-256 dos segredos (openssl rand -base64 32), a mesma da API.',
|
|
14
|
+
}),
|
|
15
|
+
WEBHOOKS_DISPATCH_INTERVAL_MS: num({ default: 1000 }),
|
|
16
|
+
WEBHOOKS_DISPATCH_BATCH_SIZE: num({ default: 100 }),
|
|
17
|
+
WEBHOOKS_TIMEOUT_MS: num({ default: 10_000 }),
|
|
18
|
+
});
|