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
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { Job, Worker } from 'bullmq';
|
|
2
|
+
import type { Telemetry } from 'franchising/telemetry';
|
|
3
|
+
|
|
4
|
+
function jobAttributes(job: Job | undefined) {
|
|
5
|
+
return {
|
|
6
|
+
queue: job?.queueName ?? 'unknown',
|
|
7
|
+
job: job?.name ?? 'unknown',
|
|
8
|
+
jobId: job?.id ?? 'unknown',
|
|
9
|
+
attempt: job?.attemptsMade ?? 0,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Tentativas que o job tem, contando a primeira. */
|
|
14
|
+
function maxAttempts(job: Job) {
|
|
15
|
+
return job.opts.attempts ?? 1;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Processa um job dentro do contexto da telemetria.
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* O `runJob` abre o span (continuando o trace do produtor quando o payload
|
|
23
|
+
* traz `traceparent`), conta sucesso e erro e mede a duracao por fila
|
|
24
|
+
* (`rock_dependency_*` com `dependency=queue.<fila>`), e reporta a excecao.
|
|
25
|
+
* Aqui entra so o que ele nao cobre: quanto tempo o job esperou na fila antes
|
|
26
|
+
* de um worker pegar, que e o primeiro sinal de fila acumulando.
|
|
27
|
+
*/
|
|
28
|
+
export function runObservedJob<Result>(
|
|
29
|
+
telemetry: Telemetry,
|
|
30
|
+
job: Job,
|
|
31
|
+
process: () => Promise<Result>,
|
|
32
|
+
): Promise<Result> {
|
|
33
|
+
const traceparent = (job.data as { traceparent?: unknown } | undefined)
|
|
34
|
+
?.traceparent;
|
|
35
|
+
|
|
36
|
+
telemetry.histogram(
|
|
37
|
+
'rock_job_wait_ms',
|
|
38
|
+
(job.processedOn ?? Date.now()) - job.timestamp,
|
|
39
|
+
{ queue: job.queueName },
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
return telemetry.runJob(
|
|
43
|
+
{
|
|
44
|
+
queue: job.queueName,
|
|
45
|
+
job: job.name,
|
|
46
|
+
...(job.id ? { jobId: job.id } : {}),
|
|
47
|
+
...(typeof traceparent === 'string' ? { traceparent } : {}),
|
|
48
|
+
},
|
|
49
|
+
process,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Liga os eventos do `Worker` do BullMQ a logs e metricas.
|
|
55
|
+
*
|
|
56
|
+
* @remarks
|
|
57
|
+
* Falha com retentativa pela frente vira `warn`; o `error` fica para o job
|
|
58
|
+
* que esgotou as tentativas (ou foi descartado com `UnrecoverableError`), que
|
|
59
|
+
* e o que precisa de alguem olhando. Job travado e erro da conexao tambem
|
|
60
|
+
* entram, porque nenhum dos dois passa pelo processador.
|
|
61
|
+
*/
|
|
62
|
+
export function observeWorker(worker: Worker, telemetry: Telemetry): void {
|
|
63
|
+
worker.on('failed', (job, error) => {
|
|
64
|
+
const attributes = { ...jobAttributes(job), reason: error.message };
|
|
65
|
+
|
|
66
|
+
const exhausted =
|
|
67
|
+
!job ||
|
|
68
|
+
error.name === 'UnrecoverableError' ||
|
|
69
|
+
job.attemptsMade >= maxAttempts(job);
|
|
70
|
+
|
|
71
|
+
if (!exhausted) {
|
|
72
|
+
telemetry.warn('job.retrying', attributes);
|
|
73
|
+
|
|
74
|
+
telemetry.increment('rock_job_retries_total', 1, {
|
|
75
|
+
queue: attributes.queue,
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
telemetry.error('job.exhausted', error, attributes);
|
|
82
|
+
|
|
83
|
+
telemetry.increment('rock_job_exhausted_total', 1, {
|
|
84
|
+
queue: attributes.queue,
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
worker.on('stalled', (jobId) => {
|
|
89
|
+
telemetry.warn('job.stalled', { queue: worker.name, jobId });
|
|
90
|
+
|
|
91
|
+
telemetry.increment('rock_job_stalled_total', 1, { queue: worker.name });
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
worker.on('error', (error) =>
|
|
95
|
+
telemetry.error('worker.error', error, { queue: worker.name }),
|
|
96
|
+
);
|
|
97
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Observabilidade da API.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* O registro do SDK fica em `./register`, importado primeiro no `main.ts`:
|
|
6
|
+
* aqui so entra o que roda depois do bootstrap.
|
|
7
|
+
*/
|
|
8
|
+
export { adapters } from './adapters';
|
|
9
|
+
export { bootstrapFailed, observeProcess } from './bootstrap';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { registerTelemetry } from 'franchising/telemetry/register';
|
|
2
|
+
import { env } from '../../env';
|
|
3
|
+
import { adapters } from './adapters';
|
|
4
|
+
|
|
5
|
+
/*
|
|
6
|
+
* Roda no import, e nao numa funcao chamada depois: a auto-instrumentacao so
|
|
7
|
+
* consegue interceptar o Nest, o driver do banco e os clients HTTP se for
|
|
8
|
+
* registrada antes de esses modulos serem avaliados. Por isso o `main.ts`
|
|
9
|
+
* importa este arquivo antes de qualquer `@nestjs/*`. No dev local a
|
|
10
|
+
* telemetria vem desligada e nada e registrado.
|
|
11
|
+
*/
|
|
12
|
+
if (env.TELEMETRY_ENABLED) registerTelemetry({ adapters });
|
|
@@ -7,43 +7,7 @@
|
|
|
7
7
|
* dos dois lados, um lado renomeia e o outro passa a consumir uma fila vazia
|
|
8
8
|
* sem erro nenhum.
|
|
9
9
|
*/
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
export
|
|
13
|
-
|
|
14
|
-
* O BullMQ recusa `:` em id customizado — justamente o separador obvio.
|
|
15
|
-
* Cada parte vai codificada para que um valor com ponto ou barra nao mude
|
|
16
|
-
* o significado do id.
|
|
17
|
-
*/
|
|
18
|
-
return parts.map((part) => encodeURIComponent(String(part))).join('.');
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Prefixo com hashtag por fila.
|
|
23
|
-
*
|
|
24
|
-
* @remarks
|
|
25
|
-
* Os scripts Lua do BullMQ tocam varias chaves de uma vez, e num Redis em modo
|
|
26
|
-
* cluster isso so e atomico se as chaves cairem no mesmo slot. A hashtag em
|
|
27
|
-
* volta do par prefixo/fila garante isso sem jogar todas as filas no mesmo
|
|
28
|
-
* shard.
|
|
29
|
-
*/
|
|
30
|
-
export function queuePrefix(prefix: string, queueName: string): string {
|
|
31
|
-
const normalizedPrefix = prefix.trim().replace(/:+$/, '');
|
|
32
|
-
const normalizedQueue = queueName.trim();
|
|
33
|
-
|
|
34
|
-
if (!(normalizedPrefix && normalizedQueue)) {
|
|
35
|
-
throw new Error('QUEUE_PREFIX_AND_NAME_REQUIRED');
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
return `{${normalizedPrefix}:${normalizedQueue}}`;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Politica padrao de retentativa das filas do projeto. */
|
|
42
|
-
export const DEFAULT_JOB_OPTIONS = {
|
|
43
|
-
attempts: 5,
|
|
44
|
-
backoff: { type: 'exponential', delay: 1000 },
|
|
45
|
-
removeOnComplete: { age: 3600, count: 1000 },
|
|
46
|
-
removeOnFail: { age: 86_400 },
|
|
47
|
-
} as const;
|
|
48
|
-
|
|
49
|
-
export * from './queues';
|
|
10
|
+
export * from './shared/queue/job-id';
|
|
11
|
+
export * from './shared/queue/names';
|
|
12
|
+
export * from './shared/queue/options';
|
|
13
|
+
export * from './shared/queue/prefix';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Identificador de job estavel, para o mesmo evento nao entrar duas vezes. */
|
|
2
|
+
export function jobId(parts: ReadonlyArray<string | number>): string {
|
|
3
|
+
/*
|
|
4
|
+
* O BullMQ recusa `:` em id customizado — justamente o separador obvio.
|
|
5
|
+
* Cada parte vai codificada para que um valor com ponto ou barra nao mude
|
|
6
|
+
* o significado do id.
|
|
7
|
+
*/
|
|
8
|
+
return parts.map((part) => encodeURIComponent(String(part))).join('.');
|
|
9
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prefixo com hashtag por fila.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Os scripts Lua do BullMQ tocam varias chaves de uma vez, e num Redis em modo
|
|
6
|
+
* cluster isso so e atomico se as chaves cairem no mesmo slot. A hashtag em
|
|
7
|
+
* volta do par prefixo/fila garante isso sem jogar todas as filas no mesmo
|
|
8
|
+
* shard.
|
|
9
|
+
*/
|
|
10
|
+
export function queuePrefix(prefix: string, queueName: string): string {
|
|
11
|
+
const normalizedPrefix = prefix.trim().replace(/:+$/, '');
|
|
12
|
+
const normalizedQueue = queueName.trim();
|
|
13
|
+
|
|
14
|
+
if (!(normalizedPrefix && normalizedQueue))
|
|
15
|
+
throw new Error('QUEUE_PREFIX_AND_NAME_REQUIRED');
|
|
16
|
+
|
|
17
|
+
return `{${normalizedPrefix}:${normalizedQueue}}`;
|
|
18
|
+
}
|
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
import IORedis
|
|
2
|
-
|
|
3
|
-
export type QueueRedisConnection = {
|
|
4
|
-
client: Redis;
|
|
5
|
-
close: () => Promise<void>;
|
|
6
|
-
};
|
|
1
|
+
import IORedis from 'ioredis';
|
|
2
|
+
import type { QueueRedisConnection } from '../../types/redis/connection';
|
|
7
3
|
|
|
8
4
|
/*
|
|
9
5
|
* `maxRetriesPerRequest: null` e exigencia do BullMQ para a conexao que fica
|
|
@@ -43,12 +39,3 @@ export function createWorkerRedisConnection(
|
|
|
43
39
|
): QueueRedisConnection {
|
|
44
40
|
return connect(url, WORKER_OPTIONS);
|
|
45
41
|
}
|
|
46
|
-
|
|
47
|
-
/** Motivo legivel da falha, para o log estruturado. */
|
|
48
|
-
export function failureReason(error: unknown): string {
|
|
49
|
-
if (error instanceof Error) {
|
|
50
|
-
return error.message;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
return typeof error === 'string' ? error : 'unknown';
|
|
54
|
-
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dominio de webhooks compartilhado entre a API e o worker `webhooks`.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* A API cifra o segredo ao cadastrar o endpoint e o worker decifra para
|
|
6
|
+
* assinar: os dois precisam do mesmo formato, entao ele mora num lugar so.
|
|
7
|
+
*/
|
|
8
|
+
export * from './shared/crypto/secret';
|
|
9
|
+
export * from './shared/signing/headers';
|
|
10
|
+
export * from './shared/url/deliverable';
|
|
11
|
+
export type * from './types/webhooks/job';
|
|
@@ -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
|
-
.
|
|
2
|
-
|
|
3
|
-
.
|
|
4
|
-
|
|
5
|
-
|
|
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
|
-
|
|
10
|
-
**/
|
|
11
|
-
|
|
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
|