termo_core 0.1.29 → 0.1.30
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 +26 -1
- package/dist/base/criptografia.d.ts +15 -0
- package/dist/base/criptografia.js +102 -0
- package/dist/base/index.d.ts +4 -2
- package/dist/base/index.js +4 -2
- package/dist/base/requisicao.d.ts +1 -1
- package/dist/base/requisicao.js +6 -4
- package/dist/base/segredo_de_app.d.ts +57 -0
- package/dist/base/segredo_de_app.js +203 -0
- package/dist/base/servico_termotubos.d.ts +8 -0
- package/dist/base/servico_termotubos.js +13 -0
- package/dist/base/token_do_aplicativo.js +46 -13
- package/dist/webhook/assinatura.d.ts +15 -0
- package/dist/webhook/assinatura.js +36 -0
- package/dist/webhook/envelope.d.ts +34 -0
- package/dist/webhook/envelope.js +16 -0
- package/dist/webhook/index.d.ts +4 -0
- package/dist/webhook/index.js +4 -0
- package/dist/webhook/publicar.d.ts +35 -0
- package/dist/webhook/publicar.js +143 -0
- package/dist/webhook/receber.d.ts +48 -0
- package/dist/webhook/receber.js +246 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -66,7 +66,32 @@ type Dados = webhook.eventos.termo_auth.ColaboradorCriadoV1; // dados do evento
|
|
|
66
66
|
const evento = webhook.eventos.termo_auth.ColaboradorCriadoV1; // { aplicativo, tipo, versao }
|
|
67
67
|
```
|
|
68
68
|
|
|
69
|
-
|
|
69
|
+
Publicar e receber também existem, como no crate (só back-end):
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
const envelope = webhook.novo_envelope(evento, "42", dados);
|
|
73
|
+
await webhook.publicar_evento_no_hub_agora(webhook.ConfiguracaoDoHub.carregar_do_ambiente_atual(), envelope);
|
|
74
|
+
|
|
75
|
+
// Na rota que recebe as entregas, com o corpo cru:
|
|
76
|
+
const entrega = await webhook.conferir_entrega_recebida_do_hub(request.headers, await request.arrayBuffer());
|
|
77
|
+
if (entrega.e(evento)) {
|
|
78
|
+
const recebido = entrega.ler<Dados>(evento);
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Busca automática do segredo do app
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { ativar_busca_automatica_do_segredo_do_app, sincronizar_segredo_do_app } from "termo_core";
|
|
86
|
+
|
|
87
|
+
ativar_busca_automatica_do_segredo_do_app("meu-app", global_secret_criptografia); // ao subir
|
|
88
|
+
const segredo_novo = await sincronizar_segredo_do_app(segredo_guardado); // ao subir e a cada 5 min
|
|
89
|
+
if (segredo_novo !== undefined) {
|
|
90
|
+
// grave cifrado no banco do app
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
A criptografia usa só WebCrypto: funciona em Node 20+, Bun, Deno e Cloudflare Workers, sem dependência.
|
|
70
95
|
|
|
71
96
|
## Gerado
|
|
72
97
|
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare function texto_em_bytes(texto: string): Uint8Array<ArrayBuffer>;
|
|
2
|
+
/** Lança erro quando os bytes não são UTF-8 válido. */
|
|
3
|
+
export declare function bytes_em_texto(bytes: Uint8Array): string;
|
|
4
|
+
export declare function juntar_bytes(...partes: Uint8Array[]): Uint8Array<ArrayBuffer>;
|
|
5
|
+
/** Base64 padrão ou base64url, com ou sem `=`; devolve `undefined` quando o texto não é base64. */
|
|
6
|
+
export declare function decodificar_base64(codificado: string): Uint8Array<ArrayBuffer> | undefined;
|
|
7
|
+
export declare function codificar_base64(bytes: Uint8Array): string;
|
|
8
|
+
export declare function codificar_base64url(bytes: Uint8Array): string;
|
|
9
|
+
export declare function sha256(bytes: Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer>>;
|
|
10
|
+
/** Confere uma assinatura Ed25519 com a chave pública crua de 32 bytes. Qualquer falha devolve `false`. */
|
|
11
|
+
export declare function assinatura_ed25519_confere(chave_publica: Uint8Array<ArrayBuffer>, mensagem: Uint8Array<ArrayBuffer>, assinatura: Uint8Array<ArrayBuffer>): Promise<boolean>;
|
|
12
|
+
/** Abre um AES-256-GCM (`nonce` de 12 bytes, tag de 16 bytes no final do cifrado); `undefined` se não abre. */
|
|
13
|
+
export declare function abrir_aes_256_gcm(chave: Uint8Array<ArrayBuffer>, nonce: Uint8Array<ArrayBuffer>, cifrado: Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer> | undefined>;
|
|
14
|
+
/** UUID v7 (ordenado pelo tempo), como o `Uuid::now_v7()` do crate. */
|
|
15
|
+
export declare function novo_uuid_v7(): string;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Criptografia só com WebCrypto (`globalThis.crypto`), sem `node:crypto`: roda igual no Node 20+, Bun, Deno e Cloudflare Workers.
|
|
2
|
+
const codificador_de_texto = new TextEncoder();
|
|
3
|
+
const decodificador_de_texto = new TextDecoder("utf-8", { fatal: true });
|
|
4
|
+
export function texto_em_bytes(texto) {
|
|
5
|
+
return codificador_de_texto.encode(texto);
|
|
6
|
+
}
|
|
7
|
+
/** Lança erro quando os bytes não são UTF-8 válido. */
|
|
8
|
+
export function bytes_em_texto(bytes) {
|
|
9
|
+
return decodificador_de_texto.decode(bytes);
|
|
10
|
+
}
|
|
11
|
+
export function juntar_bytes(...partes) {
|
|
12
|
+
const juntos = new Uint8Array(partes.reduce((total, parte) => total + parte.length, 0));
|
|
13
|
+
let posicao = 0;
|
|
14
|
+
for (const parte of partes) {
|
|
15
|
+
juntos.set(parte, posicao);
|
|
16
|
+
posicao += parte.length;
|
|
17
|
+
}
|
|
18
|
+
return juntos;
|
|
19
|
+
}
|
|
20
|
+
/** Base64 padrão ou base64url, com ou sem `=`; devolve `undefined` quando o texto não é base64. */
|
|
21
|
+
export function decodificar_base64(codificado) {
|
|
22
|
+
const padrao = codificado.trim().replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, "");
|
|
23
|
+
if (!/^[A-Za-z0-9+/]*$/.test(padrao) || padrao.length % 4 === 1) {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
const binario = atob(padrao + "=".repeat((4 - (padrao.length % 4)) % 4));
|
|
27
|
+
const bytes = new Uint8Array(binario.length);
|
|
28
|
+
for (let posicao = 0; posicao < binario.length; posicao += 1) {
|
|
29
|
+
bytes[posicao] = binario.charCodeAt(posicao);
|
|
30
|
+
}
|
|
31
|
+
return bytes;
|
|
32
|
+
}
|
|
33
|
+
export function codificar_base64(bytes) {
|
|
34
|
+
let binario = "";
|
|
35
|
+
for (const byte of bytes) {
|
|
36
|
+
binario += String.fromCharCode(byte);
|
|
37
|
+
}
|
|
38
|
+
return btoa(binario);
|
|
39
|
+
}
|
|
40
|
+
export function codificar_base64url(bytes) {
|
|
41
|
+
return codificar_base64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
42
|
+
}
|
|
43
|
+
function subtle() {
|
|
44
|
+
const criptografia = globalThis.crypto?.subtle;
|
|
45
|
+
if (!criptografia) {
|
|
46
|
+
throw new Error("termo_core: este runtime não tem WebCrypto (globalThis.crypto.subtle); use Node 20+, Bun, Deno ou Cloudflare Workers");
|
|
47
|
+
}
|
|
48
|
+
return criptografia;
|
|
49
|
+
}
|
|
50
|
+
export async function sha256(bytes) {
|
|
51
|
+
return new Uint8Array(await subtle().digest("SHA-256", bytes));
|
|
52
|
+
}
|
|
53
|
+
// Cloudflare Workers antigos só conhecem o Ed25519 pelo nome não padrão `NODE-ED25519`.
|
|
54
|
+
const ALGORITMOS_ED25519 = [
|
|
55
|
+
{ name: "Ed25519" },
|
|
56
|
+
{ name: "NODE-ED25519", namedCurve: "NODE-ED25519" },
|
|
57
|
+
];
|
|
58
|
+
/** Confere uma assinatura Ed25519 com a chave pública crua de 32 bytes. Qualquer falha devolve `false`. */
|
|
59
|
+
export async function assinatura_ed25519_confere(chave_publica, mensagem, assinatura) {
|
|
60
|
+
if (chave_publica.length !== 32 || assinatura.length !== 64) {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
for (const algoritmo of ALGORITMOS_ED25519) {
|
|
64
|
+
let chave;
|
|
65
|
+
try {
|
|
66
|
+
chave = await subtle().importKey("raw", chave_publica, algoritmo, false, ["verify"]);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return await subtle().verify(algoritmo, chave, assinatura, mensagem);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
throw new Error("termo_core: este runtime não tem Ed25519 no WebCrypto; use Node 20+, Bun, Deno ou Cloudflare Workers");
|
|
79
|
+
}
|
|
80
|
+
/** Abre um AES-256-GCM (`nonce` de 12 bytes, tag de 16 bytes no final do cifrado); `undefined` se não abre. */
|
|
81
|
+
export async function abrir_aes_256_gcm(chave, nonce, cifrado) {
|
|
82
|
+
try {
|
|
83
|
+
const chave_importada = await subtle().importKey("raw", chave, { name: "AES-GCM" }, false, ["decrypt"]);
|
|
84
|
+
return new Uint8Array(await subtle().decrypt({ name: "AES-GCM", iv: nonce }, chave_importada, cifrado));
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** UUID v7 (ordenado pelo tempo), como o `Uuid::now_v7()` do crate. */
|
|
91
|
+
export function novo_uuid_v7() {
|
|
92
|
+
const bytes = new Uint8Array(16);
|
|
93
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
94
|
+
const milissegundos = Date.now();
|
|
95
|
+
for (let posicao = 0; posicao < 6; posicao += 1) {
|
|
96
|
+
bytes[posicao] = Math.floor(milissegundos / 2 ** (8 * (5 - posicao))) & 0xff;
|
|
97
|
+
}
|
|
98
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x70;
|
|
99
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
100
|
+
const hexadecimal = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
101
|
+
return `${hexadecimal.slice(0, 8)}-${hexadecimal.slice(8, 12)}-${hexadecimal.slice(12, 16)}-${hexadecimal.slice(16, 20)}-${hexadecimal.slice(20)}`;
|
|
102
|
+
}
|
package/dist/base/index.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ export { ambiente_atual, definir_ambiente_atual_pelo_codigo, interpretar_nome_do
|
|
|
2
2
|
export { CredencialDeAcesso } from "./credencial.js";
|
|
3
3
|
export { ErroAoChamarServico, type DadosDoErroAoChamarServico, type TipoDoErroAoChamarServico } from "./erro.js";
|
|
4
4
|
export { chamar_servico, codificar_parametro_de_caminho, type FormatoDaResposta, type MetodoHttp, type OpcoesDaChamada, type RequisicaoAoServico, } from "./requisicao.js";
|
|
5
|
-
export {
|
|
5
|
+
export { ativar_busca_automatica_do_segredo_do_app, CAMINHO_DO_SEGREDO_DE_APP, INTERVALO_MINIMO_ENTRE_BUSCAS_EM_SEGUNDOS, sincronizar_segredo_do_app, } from "./segredo_de_app.js";
|
|
6
|
+
export { definir_tempo_limite_do_servico_neste_processo, endereco_do_servico_no_ambiente_atual, endereco_no_ambiente, substituir_endereco_do_servico_neste_processo, tempo_limite_do_servico_neste_processo, type ServicoTermotubos, } from "./servico_termotubos.js";
|
|
6
7
|
export * as servicos from "./servicos.js";
|
|
7
|
-
export { definir_segredo_do_app, identificador_do_aplicativo, segredo_do_app_configurado, token_do_aplicativo, VARIAVEL_DO_SEGREDO_DO_APP, type TokenDoAplicativoEmitido, } from "./token_do_aplicativo.js";
|
|
8
|
+
export { CAMINHO_DO_TOKEN_DE_APP, definir_segredo_do_app, identificador_do_aplicativo, MARGEM_PARA_RENOVAR_O_TOKEN_EM_SEGUNDOS, segredo_do_app_configurado, token_do_aplicativo, VARIAVEL_DO_SEGREDO_DO_APP, type TokenDoAplicativoEmitido, } from "./token_do_aplicativo.js";
|
|
9
|
+
export { TODOS_OS_SERVICOS } from "./servicos.js";
|
package/dist/base/index.js
CHANGED
|
@@ -2,6 +2,8 @@ export { ambiente_atual, definir_ambiente_atual_pelo_codigo, interpretar_nome_do
|
|
|
2
2
|
export { CredencialDeAcesso } from "./credencial.js";
|
|
3
3
|
export { ErroAoChamarServico } from "./erro.js";
|
|
4
4
|
export { chamar_servico, codificar_parametro_de_caminho, } from "./requisicao.js";
|
|
5
|
-
export {
|
|
5
|
+
export { ativar_busca_automatica_do_segredo_do_app, CAMINHO_DO_SEGREDO_DE_APP, INTERVALO_MINIMO_ENTRE_BUSCAS_EM_SEGUNDOS, sincronizar_segredo_do_app, } from "./segredo_de_app.js";
|
|
6
|
+
export { definir_tempo_limite_do_servico_neste_processo, endereco_do_servico_no_ambiente_atual, endereco_no_ambiente, substituir_endereco_do_servico_neste_processo, tempo_limite_do_servico_neste_processo, } from "./servico_termotubos.js";
|
|
6
7
|
export * as servicos from "./servicos.js";
|
|
7
|
-
export { definir_segredo_do_app, identificador_do_aplicativo, segredo_do_app_configurado, token_do_aplicativo, VARIAVEL_DO_SEGREDO_DO_APP, } from "./token_do_aplicativo.js";
|
|
8
|
+
export { CAMINHO_DO_TOKEN_DE_APP, definir_segredo_do_app, identificador_do_aplicativo, MARGEM_PARA_RENOVAR_O_TOKEN_EM_SEGUNDOS, segredo_do_app_configurado, token_do_aplicativo, VARIAVEL_DO_SEGREDO_DO_APP, } from "./token_do_aplicativo.js";
|
|
9
|
+
export { TODOS_OS_SERVICOS } from "./servicos.js";
|
|
@@ -6,7 +6,7 @@ export type FormatoDaResposta = "json" | "sem_conteudo" | "bytes";
|
|
|
6
6
|
export interface OpcoesDaChamada {
|
|
7
7
|
/** Cancela a chamada (ex.: o componente desmontou). O cancelamento chega como o `AbortError` do próprio `fetch`. */
|
|
8
8
|
sinal_de_cancelamento?: AbortSignal;
|
|
9
|
-
/** Padrão: 30 segundos. */
|
|
9
|
+
/** Padrão: o definido com `definir_tempo_limite_do_servico_neste_processo` ou 30 segundos. */
|
|
10
10
|
tempo_limite_em_milissegundos?: number;
|
|
11
11
|
}
|
|
12
12
|
/** Requisição a um serviço da Termotubos, montada pelo código gerado de cada módulo. */
|
package/dist/base/requisicao.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ErroAoChamarServico } from "./erro.js";
|
|
2
|
-
import { endereco_do_servico_no_ambiente_atual } from "./servico_termotubos.js";
|
|
2
|
+
import { endereco_do_servico_no_ambiente_atual, tempo_limite_do_servico_neste_processo, } from "./servico_termotubos.js";
|
|
3
3
|
const TEMPO_LIMITE_DA_REQUISICAO_EM_MILISSEGUNDOS = 30_000;
|
|
4
4
|
const TAMANHO_MAXIMO_DO_CORPO_GUARDADO_NO_ERRO = 2000;
|
|
5
5
|
/** Codifica um valor para entrar com segurança num segmento do caminho (`/usuario/{id}`). */
|
|
@@ -38,8 +38,10 @@ function ler_campo_erro_do_corpo(corpo_da_resposta) {
|
|
|
38
38
|
}
|
|
39
39
|
return undefined;
|
|
40
40
|
}
|
|
41
|
-
function montar_sinal_da_chamada(opcoes_da_chamada) {
|
|
42
|
-
const sinal_do_tempo_limite = AbortSignal.timeout(opcoes_da_chamada?.tempo_limite_em_milissegundos ??
|
|
41
|
+
function montar_sinal_da_chamada(servico, opcoes_da_chamada) {
|
|
42
|
+
const sinal_do_tempo_limite = AbortSignal.timeout(opcoes_da_chamada?.tempo_limite_em_milissegundos ??
|
|
43
|
+
tempo_limite_do_servico_neste_processo(servico) ??
|
|
44
|
+
TEMPO_LIMITE_DA_REQUISICAO_EM_MILISSEGUNDOS);
|
|
43
45
|
const sinal_de_cancelamento = opcoes_da_chamada?.sinal_de_cancelamento;
|
|
44
46
|
if (!sinal_de_cancelamento) {
|
|
45
47
|
return sinal_do_tempo_limite;
|
|
@@ -93,7 +95,7 @@ async function enviar_e_conferir_status_de_sucesso(requisicao, opcoes_da_chamada
|
|
|
93
95
|
method: requisicao.metodo_http,
|
|
94
96
|
headers: montar_cabecalhos(requisicao),
|
|
95
97
|
body: montar_corpo(requisicao),
|
|
96
|
-
signal: montar_sinal_da_chamada(opcoes_da_chamada),
|
|
98
|
+
signal: montar_sinal_da_chamada(requisicao.servico, opcoes_da_chamada),
|
|
97
99
|
});
|
|
98
100
|
}
|
|
99
101
|
catch (erro) {
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Busca automática do segredo do app no TermoAuth (só back-end), o mesmo da feature `segredo_de_app` do crate.
|
|
3
|
+
*
|
|
4
|
+
* O master gera o segredo em `/master/apps` do TermoAuth e o app o busca sozinho em
|
|
5
|
+
* `GET {TermoAuth}/segredo_de_app/{id do app}`, em vez de alguém colá-lo em `/painel/configuracoes/provedores`.
|
|
6
|
+
* O TermoAuth devolve um JWT EdDSA de 10 min (mesmo JWKS do token de usuário) com o segredo ainda cifrado
|
|
7
|
+
* com a `GLOBAL_SECRET_CRIPTOGRAFIA`; aqui ele é conferido e aberto. O `termo_core` não conhece o banco do app:
|
|
8
|
+
* `sincronizar_segredo_do_app` devolve o segredo novo e o próprio app grava.
|
|
9
|
+
*/
|
|
10
|
+
export declare const CAMINHO_DO_SEGREDO_DE_APP = "/segredo_de_app";
|
|
11
|
+
export declare const CAMINHO_DAS_CHAVES_PUBLICAS_DO_TERMO_AUTH = "/.well-known/jwks.json";
|
|
12
|
+
export declare const TIPO_DO_TOKEN_DO_SEGREDO_DE_APP = "segredo_de_app";
|
|
13
|
+
/** Entre duas buscas no TermoAuth passa pelo menos este tempo: um segredo recusado não vira enxurrada de chamadas. */
|
|
14
|
+
export declare const INTERVALO_MINIMO_ENTRE_BUSCAS_EM_SEGUNDOS = 60;
|
|
15
|
+
export interface ReivindicacoesDoSegredo {
|
|
16
|
+
aud: string;
|
|
17
|
+
sub: string;
|
|
18
|
+
exp: number;
|
|
19
|
+
tipo: string;
|
|
20
|
+
segredo: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ChavePublicaDoJwks {
|
|
23
|
+
kid: string;
|
|
24
|
+
x: string;
|
|
25
|
+
}
|
|
26
|
+
export interface ConjuntoDeChavesPublicas {
|
|
27
|
+
keys: ChavePublicaDoJwks[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Liga a busca automática: o id do app no TermoAuth (o slug cadastrado em `/master/apps`) e o valor da
|
|
31
|
+
* `GLOBAL_SECRET_CRIPTOGRAFIA` do app, a mesma com que o TermoAuth cifra o segredo. Chame uma vez, ao subir.
|
|
32
|
+
* Só back-end: a `GLOBAL_SECRET_CRIPTOGRAFIA` nunca vai para o navegador.
|
|
33
|
+
*/
|
|
34
|
+
export declare function ativar_busca_automatica_do_segredo_do_app(identificador_do_aplicativo: string, segredo_global_de_criptografia: string): void;
|
|
35
|
+
/**
|
|
36
|
+
* Chame ao subir e a cada 5 min com o segredo que o app tem no banco (`null`/`undefined` se não tem).
|
|
37
|
+
*
|
|
38
|
+
* - Devolve o segredo quando há segredo novo para o app gravar (cifrado) no banco: o banco estava vazio e
|
|
39
|
+
* ele foi buscado agora, ou o TermoAuth recusou o antigo e o `termo_core` já buscou o novo.
|
|
40
|
+
* - Devolve `undefined` quando o guardado continua valendo; ele é entregue com `definir_segredo_do_app`.
|
|
41
|
+
*/
|
|
42
|
+
export declare function sincronizar_segredo_do_app(segredo_guardado: string | null | undefined): Promise<string | undefined>;
|
|
43
|
+
/**
|
|
44
|
+
* Usado por `token_do_aplicativo()` quando não há segredo ou o TermoAuth recusou o atual: busca o novo, já o
|
|
45
|
+
* entrega neste processo e o deixa para a próxima `sincronizar_segredo_do_app` devolver ao app gravar.
|
|
46
|
+
*/
|
|
47
|
+
export declare function buscar_segredo_novo_para_o_token(): Promise<string | undefined>;
|
|
48
|
+
/** Confere o JWT do segredo pelo JWKS do TermoAuth; devolve as reivindicações ou o motivo da recusa. */
|
|
49
|
+
export declare function conferir_token_do_segredo(token: string, chaves: ConjuntoDeChavesPublicas, identificador_do_aplicativo: string, agora_em_segundos: number): Promise<ReivindicacoesDoSegredo | string>;
|
|
50
|
+
/** Abre o segredo `v1:` (AES-256-GCM, chave = SHA-256 da `GLOBAL_SECRET_CRIPTOGRAFIA`). */
|
|
51
|
+
export declare function decifrar_segredo(guardado: string, segredo_global_de_criptografia: string): Promise<{
|
|
52
|
+
segredo: string;
|
|
53
|
+
erro?: undefined;
|
|
54
|
+
} | {
|
|
55
|
+
segredo?: undefined;
|
|
56
|
+
erro: string;
|
|
57
|
+
}>;
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Busca automática do segredo do app no TermoAuth (só back-end), o mesmo da feature `segredo_de_app` do crate.
|
|
3
|
+
*
|
|
4
|
+
* O master gera o segredo em `/master/apps` do TermoAuth e o app o busca sozinho em
|
|
5
|
+
* `GET {TermoAuth}/segredo_de_app/{id do app}`, em vez de alguém colá-lo em `/painel/configuracoes/provedores`.
|
|
6
|
+
* O TermoAuth devolve um JWT EdDSA de 10 min (mesmo JWKS do token de usuário) com o segredo ainda cifrado
|
|
7
|
+
* com a `GLOBAL_SECRET_CRIPTOGRAFIA`; aqui ele é conferido e aberto. O `termo_core` não conhece o banco do app:
|
|
8
|
+
* `sincronizar_segredo_do_app` devolve o segredo novo e o próprio app grava.
|
|
9
|
+
*/
|
|
10
|
+
import { abrir_aes_256_gcm, assinatura_ed25519_confere, bytes_em_texto, decodificar_base64, sha256, texto_em_bytes, } from "./criptografia.js";
|
|
11
|
+
import { ErroAoChamarServico } from "./erro.js";
|
|
12
|
+
import { chamar_servico, codificar_parametro_de_caminho } from "./requisicao.js";
|
|
13
|
+
import { TERMO_AUTH } from "./servicos.js";
|
|
14
|
+
import { definir_segredo_do_app } from "./token_do_aplicativo.js";
|
|
15
|
+
export const CAMINHO_DO_SEGREDO_DE_APP = "/segredo_de_app";
|
|
16
|
+
export const CAMINHO_DAS_CHAVES_PUBLICAS_DO_TERMO_AUTH = "/.well-known/jwks.json";
|
|
17
|
+
export const TIPO_DO_TOKEN_DO_SEGREDO_DE_APP = "segredo_de_app";
|
|
18
|
+
/** Entre duas buscas no TermoAuth passa pelo menos este tempo: um segredo recusado não vira enxurrada de chamadas. */
|
|
19
|
+
export const INTERVALO_MINIMO_ENTRE_BUSCAS_EM_SEGUNDOS = 60;
|
|
20
|
+
const PREFIXO_DO_SEGREDO_CIFRADO = "v1:";
|
|
21
|
+
const TAMANHO_DO_NONCE = 12;
|
|
22
|
+
let busca_automatica;
|
|
23
|
+
let instante_da_ultima_busca_em_milissegundos;
|
|
24
|
+
let segredo_buscado_ainda_nao_guardado;
|
|
25
|
+
function erro_de_formato(detalhe) {
|
|
26
|
+
return new ErroAoChamarServico({
|
|
27
|
+
tipo: "resposta_do_servico_em_formato_inesperado",
|
|
28
|
+
nome_do_servico: TERMO_AUTH.nome_do_servico,
|
|
29
|
+
detalhe,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function erro_de_configuracao(detalhe) {
|
|
33
|
+
return new ErroAoChamarServico({ tipo: "falha_ao_montar_requisicao", nome_do_servico: TERMO_AUTH.nome_do_servico, detalhe });
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Liga a busca automática: o id do app no TermoAuth (o slug cadastrado em `/master/apps`) e o valor da
|
|
37
|
+
* `GLOBAL_SECRET_CRIPTOGRAFIA` do app, a mesma com que o TermoAuth cifra o segredo. Chame uma vez, ao subir.
|
|
38
|
+
* Só back-end: a `GLOBAL_SECRET_CRIPTOGRAFIA` nunca vai para o navegador.
|
|
39
|
+
*/
|
|
40
|
+
export function ativar_busca_automatica_do_segredo_do_app(identificador_do_aplicativo, segredo_global_de_criptografia) {
|
|
41
|
+
const identificador = identificador_do_aplicativo.trim();
|
|
42
|
+
const segredo_global = segredo_global_de_criptografia.trim();
|
|
43
|
+
busca_automatica =
|
|
44
|
+
identificador && segredo_global
|
|
45
|
+
? { identificador_do_aplicativo: identificador, segredo_global_de_criptografia: segredo_global }
|
|
46
|
+
: undefined;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Chame ao subir e a cada 5 min com o segredo que o app tem no banco (`null`/`undefined` se não tem).
|
|
50
|
+
*
|
|
51
|
+
* - Devolve o segredo quando há segredo novo para o app gravar (cifrado) no banco: o banco estava vazio e
|
|
52
|
+
* ele foi buscado agora, ou o TermoAuth recusou o antigo e o `termo_core` já buscou o novo.
|
|
53
|
+
* - Devolve `undefined` quando o guardado continua valendo; ele é entregue com `definir_segredo_do_app`.
|
|
54
|
+
*/
|
|
55
|
+
export async function sincronizar_segredo_do_app(segredo_guardado) {
|
|
56
|
+
const buscado = segredo_buscado_ainda_nao_guardado;
|
|
57
|
+
segredo_buscado_ainda_nao_guardado = undefined;
|
|
58
|
+
if (buscado !== undefined) {
|
|
59
|
+
return buscado;
|
|
60
|
+
}
|
|
61
|
+
const guardado = segredo_guardado?.trim() || undefined;
|
|
62
|
+
if (guardado !== undefined || busca_automatica === undefined) {
|
|
63
|
+
definir_segredo_do_app(guardado);
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
const novo = await buscar_segredo_respeitando_o_intervalo();
|
|
67
|
+
definir_segredo_do_app(novo);
|
|
68
|
+
return novo;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Usado por `token_do_aplicativo()` quando não há segredo ou o TermoAuth recusou o atual: busca o novo, já o
|
|
72
|
+
* entrega neste processo e o deixa para a próxima `sincronizar_segredo_do_app` devolver ao app gravar.
|
|
73
|
+
*/
|
|
74
|
+
export async function buscar_segredo_novo_para_o_token() {
|
|
75
|
+
if (busca_automatica === undefined) {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
const novo = await buscar_segredo_respeitando_o_intervalo();
|
|
80
|
+
definir_segredo_do_app(novo);
|
|
81
|
+
segredo_buscado_ainda_nao_guardado = novo;
|
|
82
|
+
return novo;
|
|
83
|
+
}
|
|
84
|
+
catch (erro) {
|
|
85
|
+
console.error(`termo_core: falha ao buscar o segredo do app no TermoAuth: ${erro instanceof Error ? erro.message : String(erro)}`);
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function buscar_segredo_respeitando_o_intervalo() {
|
|
90
|
+
const busca = busca_automatica;
|
|
91
|
+
if (busca === undefined) {
|
|
92
|
+
throw erro_de_configuracao("busca automática do segredo desligada: chame ativar_busca_automatica_do_segredo_do_app ao subir");
|
|
93
|
+
}
|
|
94
|
+
const agora = Date.now();
|
|
95
|
+
if (instante_da_ultima_busca_em_milissegundos !== undefined &&
|
|
96
|
+
agora - instante_da_ultima_busca_em_milissegundos < INTERVALO_MINIMO_ENTRE_BUSCAS_EM_SEGUNDOS * 1000) {
|
|
97
|
+
throw erro_de_configuracao(`o segredo do app foi buscado há menos de ${INTERVALO_MINIMO_ENTRE_BUSCAS_EM_SEGUNDOS} s; aguarde para buscar de novo`);
|
|
98
|
+
}
|
|
99
|
+
instante_da_ultima_busca_em_milissegundos = agora;
|
|
100
|
+
return buscar_segredo_do_app_no_termo_auth(busca);
|
|
101
|
+
}
|
|
102
|
+
async function buscar_segredo_do_app_no_termo_auth(busca) {
|
|
103
|
+
const emitido = await chamar_servico({
|
|
104
|
+
servico: TERMO_AUTH,
|
|
105
|
+
metodo_http: "GET",
|
|
106
|
+
caminho_da_rota: `${CAMINHO_DO_SEGREDO_DE_APP}/${codificar_parametro_de_caminho(busca.identificador_do_aplicativo)}`,
|
|
107
|
+
formato_da_resposta: "json",
|
|
108
|
+
});
|
|
109
|
+
const chaves = await chamar_servico({
|
|
110
|
+
servico: TERMO_AUTH,
|
|
111
|
+
metodo_http: "GET",
|
|
112
|
+
caminho_da_rota: CAMINHO_DAS_CHAVES_PUBLICAS_DO_TERMO_AUTH,
|
|
113
|
+
formato_da_resposta: "json",
|
|
114
|
+
});
|
|
115
|
+
const conferido = await conferir_token_do_segredo(emitido.token, chaves, busca.identificador_do_aplicativo, Math.floor(Date.now() / 1000));
|
|
116
|
+
if (typeof conferido === "string") {
|
|
117
|
+
throw erro_de_formato(conferido);
|
|
118
|
+
}
|
|
119
|
+
const aberto = await decifrar_segredo(conferido.segredo, busca.segredo_global_de_criptografia);
|
|
120
|
+
if (aberto.erro !== undefined) {
|
|
121
|
+
throw erro_de_formato(aberto.erro);
|
|
122
|
+
}
|
|
123
|
+
return aberto.segredo;
|
|
124
|
+
}
|
|
125
|
+
function decodificar_parte_do_token(parte) {
|
|
126
|
+
const bytes = decodificar_base64(parte);
|
|
127
|
+
if (!bytes) {
|
|
128
|
+
return "token do segredo ilegível";
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
const lido = JSON.parse(bytes_em_texto(bytes));
|
|
132
|
+
return lido && typeof lido === "object" && !Array.isArray(lido) ? lido : "token do segredo ilegível";
|
|
133
|
+
}
|
|
134
|
+
catch (erro) {
|
|
135
|
+
return `token do segredo ilegível: ${String(erro)}`;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** Confere o JWT do segredo pelo JWKS do TermoAuth; devolve as reivindicações ou o motivo da recusa. */
|
|
139
|
+
export async function conferir_token_do_segredo(token, chaves, identificador_do_aplicativo, agora_em_segundos) {
|
|
140
|
+
const partes = token.split(".");
|
|
141
|
+
if (partes.length !== 3) {
|
|
142
|
+
return "token do segredo fora do formato JWT";
|
|
143
|
+
}
|
|
144
|
+
const [parte_do_cabecalho, parte_do_corpo, parte_da_assinatura] = partes;
|
|
145
|
+
const cabecalho = decodificar_parte_do_token(parte_do_cabecalho);
|
|
146
|
+
if (typeof cabecalho === "string") {
|
|
147
|
+
return cabecalho;
|
|
148
|
+
}
|
|
149
|
+
if (cabecalho.alg !== "EdDSA") {
|
|
150
|
+
return `algoritmo do token do segredo não aceito: ${String(cabecalho.alg)}`;
|
|
151
|
+
}
|
|
152
|
+
const chave = chaves.keys.find((candidata) => candidata.kid === cabecalho.kid);
|
|
153
|
+
const chave_publica = chave ? decodificar_base64(chave.x) : undefined;
|
|
154
|
+
if (!chave_publica || chave_publica.length !== 32) {
|
|
155
|
+
return `chave ${String(cabecalho.kid)} do token do segredo não está no JWKS do TermoAuth`;
|
|
156
|
+
}
|
|
157
|
+
const assinatura = decodificar_base64(parte_da_assinatura);
|
|
158
|
+
if (!assinatura || assinatura.length !== 64) {
|
|
159
|
+
return "assinatura do token do segredo ilegível";
|
|
160
|
+
}
|
|
161
|
+
const mensagem = texto_em_bytes(`${parte_do_cabecalho}.${parte_do_corpo}`);
|
|
162
|
+
if (!(await assinatura_ed25519_confere(chave_publica, mensagem, assinatura))) {
|
|
163
|
+
return "assinatura do token do segredo não confere com o JWKS do TermoAuth";
|
|
164
|
+
}
|
|
165
|
+
const corpo = decodificar_parte_do_token(parte_do_corpo);
|
|
166
|
+
if (typeof corpo === "string") {
|
|
167
|
+
return corpo;
|
|
168
|
+
}
|
|
169
|
+
const { aud, sub, exp, tipo, segredo } = corpo;
|
|
170
|
+
if (typeof aud !== "string" || typeof sub !== "string" || typeof exp !== "number" || typeof tipo !== "string" || typeof segredo !== "string") {
|
|
171
|
+
return "token do segredo ilegível: faltam aud, sub, exp, tipo ou segredo";
|
|
172
|
+
}
|
|
173
|
+
if (tipo !== TIPO_DO_TOKEN_DO_SEGREDO_DE_APP) {
|
|
174
|
+
return `token do tipo ${tipo} não traz segredo de app`;
|
|
175
|
+
}
|
|
176
|
+
if (aud !== identificador_do_aplicativo || sub !== identificador_do_aplicativo) {
|
|
177
|
+
return `token do segredo emitido para outro app (${aud})`;
|
|
178
|
+
}
|
|
179
|
+
if (exp <= agora_em_segundos) {
|
|
180
|
+
return "token do segredo vencido";
|
|
181
|
+
}
|
|
182
|
+
return { aud, sub, exp, tipo, segredo };
|
|
183
|
+
}
|
|
184
|
+
/** Abre o segredo `v1:` (AES-256-GCM, chave = SHA-256 da `GLOBAL_SECRET_CRIPTOGRAFIA`). */
|
|
185
|
+
export async function decifrar_segredo(guardado, segredo_global_de_criptografia) {
|
|
186
|
+
const bytes = guardado.startsWith(PREFIXO_DO_SEGREDO_CIFRADO)
|
|
187
|
+
? decodificar_base64(guardado.slice(PREFIXO_DO_SEGREDO_CIFRADO.length))
|
|
188
|
+
: undefined;
|
|
189
|
+
if (!bytes || bytes.length <= TAMANHO_DO_NONCE) {
|
|
190
|
+
return { erro: "segredo cifrado em formato desconhecido" };
|
|
191
|
+
}
|
|
192
|
+
const chave = await sha256(texto_em_bytes(segredo_global_de_criptografia.trim()));
|
|
193
|
+
const aberto = await abrir_aes_256_gcm(chave, bytes.slice(0, TAMANHO_DO_NONCE), bytes.slice(TAMANHO_DO_NONCE));
|
|
194
|
+
if (!aberto) {
|
|
195
|
+
return { erro: "o segredo não abre com esta GLOBAL_SECRET_CRIPTOGRAFIA: confira se é a mesma do TermoAuth" };
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
return { segredo: bytes_em_texto(aberto) };
|
|
199
|
+
}
|
|
200
|
+
catch (erro) {
|
|
201
|
+
return { erro: String(erro) };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
@@ -16,5 +16,13 @@ export declare function endereco_no_ambiente(servico: ServicoTermotubos, ambient
|
|
|
16
16
|
* (ex.: apontar para um servidor de teste). O normal é não precisar chamar.
|
|
17
17
|
*/
|
|
18
18
|
export declare function substituir_endereco_do_servico_neste_processo(servico: ServicoTermotubos, novo_endereco: string): void;
|
|
19
|
+
/**
|
|
20
|
+
* Troca o tempo limite das requisições a um serviço só neste processo (ou nesta aba), por cima dos 30 s padrão
|
|
21
|
+
* (ex.: gerar imagem no gateway do TermoAI, que passa de 30 s). O `tempo_limite_em_milissegundos` de cada chamada
|
|
22
|
+
* ainda vale por cima deste. O normal é não precisar chamar.
|
|
23
|
+
*/
|
|
24
|
+
export declare function definir_tempo_limite_do_servico_neste_processo(servico: ServicoTermotubos, tempo_limite_em_milissegundos: number): void;
|
|
25
|
+
/** Tempo limite definido para o serviço com `definir_tempo_limite_do_servico_neste_processo`, se houver. */
|
|
26
|
+
export declare function tempo_limite_do_servico_neste_processo(servico: ServicoTermotubos): number | undefined;
|
|
19
27
|
/** Endereço da API do serviço no ambiente em que o código está rodando. */
|
|
20
28
|
export declare function endereco_do_servico_no_ambiente_atual(servico: ServicoTermotubos): string;
|
|
@@ -17,6 +17,19 @@ const enderecos_substituidos_pelo_codigo = new Map();
|
|
|
17
17
|
export function substituir_endereco_do_servico_neste_processo(servico, novo_endereco) {
|
|
18
18
|
enderecos_substituidos_pelo_codigo.set(servico.nome_do_modulo, novo_endereco.trim().replace(/\/+$/, ""));
|
|
19
19
|
}
|
|
20
|
+
const tempos_limite_definidos_pelo_codigo = new Map();
|
|
21
|
+
/**
|
|
22
|
+
* Troca o tempo limite das requisições a um serviço só neste processo (ou nesta aba), por cima dos 30 s padrão
|
|
23
|
+
* (ex.: gerar imagem no gateway do TermoAI, que passa de 30 s). O `tempo_limite_em_milissegundos` de cada chamada
|
|
24
|
+
* ainda vale por cima deste. O normal é não precisar chamar.
|
|
25
|
+
*/
|
|
26
|
+
export function definir_tempo_limite_do_servico_neste_processo(servico, tempo_limite_em_milissegundos) {
|
|
27
|
+
tempos_limite_definidos_pelo_codigo.set(servico.nome_do_modulo, tempo_limite_em_milissegundos);
|
|
28
|
+
}
|
|
29
|
+
/** Tempo limite definido para o serviço com `definir_tempo_limite_do_servico_neste_processo`, se houver. */
|
|
30
|
+
export function tempo_limite_do_servico_neste_processo(servico) {
|
|
31
|
+
return tempos_limite_definidos_pelo_codigo.get(servico.nome_do_modulo);
|
|
32
|
+
}
|
|
20
33
|
/** Endereço da API do serviço no ambiente em que o código está rodando. */
|
|
21
34
|
export function endereco_do_servico_no_ambiente_atual(servico) {
|
|
22
35
|
return enderecos_substituidos_pelo_codigo.get(servico.nome_do_modulo) ?? endereco_no_ambiente(servico, ambiente_atual());
|
|
@@ -2,6 +2,7 @@ import { ler_variavel_de_ambiente } from "./ambiente.js";
|
|
|
2
2
|
import { CredencialDeAcesso } from "./credencial.js";
|
|
3
3
|
import { ErroAoChamarServico } from "./erro.js";
|
|
4
4
|
import { chamar_servico } from "./requisicao.js";
|
|
5
|
+
import { buscar_segredo_novo_para_o_token } from "./segredo_de_app.js";
|
|
5
6
|
import { TERMO_AUTH } from "./servicos.js";
|
|
6
7
|
/** Só para back-end: o segredo nunca vai para o navegador. */
|
|
7
8
|
export const VARIAVEL_DO_SEGREDO_DO_APP = "SEGREDO_DO_APP_GERADO_NO_TERMO_AUTH";
|
|
@@ -40,33 +41,65 @@ export function segredo_do_app_configurado() {
|
|
|
40
41
|
return buscar_segredo_do_app() !== undefined;
|
|
41
42
|
}
|
|
42
43
|
async function pedir_token_do_aplicativo_ao_termo_auth(segredo) {
|
|
43
|
-
|
|
44
|
+
return chamar_servico({
|
|
44
45
|
servico: TERMO_AUTH,
|
|
45
46
|
metodo_http: "POST",
|
|
46
47
|
caminho_da_rota: CAMINHO_DO_TOKEN_DE_APP,
|
|
47
48
|
corpo_json: { segredo },
|
|
48
49
|
formato_da_resposta: "json",
|
|
49
50
|
});
|
|
50
|
-
|
|
51
|
-
|
|
51
|
+
}
|
|
52
|
+
function erro_sem_segredo_do_app() {
|
|
53
|
+
return new ErroAoChamarServico({
|
|
54
|
+
tipo: "falha_ao_montar_requisicao",
|
|
55
|
+
nome_do_servico: TERMO_AUTH.nome_do_servico,
|
|
56
|
+
detalhe: `cadastre o segredo do app gerado no TermoAuth (definir_segredo_do_app ou a variável ${VARIAVEL_DO_SEGREDO_DO_APP}) para pedir o token de aplicativo`,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
async function pedir_token_com_segredo_buscado_no_termo_auth(erro_original) {
|
|
60
|
+
const novo = await buscar_segredo_novo_para_o_token();
|
|
61
|
+
if (novo === undefined) {
|
|
62
|
+
throw erro_original;
|
|
63
|
+
}
|
|
64
|
+
return { emitido: await pedir_token_do_aplicativo_ao_termo_auth(novo), segredo_usado: novo };
|
|
65
|
+
}
|
|
66
|
+
async function pedir_token_ao_termo_auth_buscando_o_segredo_se_preciso() {
|
|
67
|
+
const segredo = buscar_segredo_do_app();
|
|
68
|
+
if (!segredo) {
|
|
69
|
+
return pedir_token_com_segredo_buscado_no_termo_auth(erro_sem_segredo_do_app());
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return { emitido: await pedir_token_do_aplicativo_ao_termo_auth(segredo), segredo_usado: segredo };
|
|
73
|
+
}
|
|
74
|
+
catch (erro) {
|
|
75
|
+
if (erro instanceof ErroAoChamarServico && erro.status_http_da_resposta() === 401) {
|
|
76
|
+
return pedir_token_com_segredo_buscado_no_termo_auth(erro);
|
|
77
|
+
}
|
|
78
|
+
throw erro;
|
|
79
|
+
}
|
|
52
80
|
}
|
|
53
81
|
async function token_do_aplicativo_emitido() {
|
|
54
82
|
const agora = Math.floor(Date.now() / 1000);
|
|
55
83
|
if (token_em_cache && token_ainda_vale_sem_renovar(token_em_cache.expira_em, agora)) {
|
|
56
84
|
return token_em_cache;
|
|
57
85
|
}
|
|
58
|
-
|
|
59
|
-
if (!
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
86
|
+
// Chamadas simultâneas esperam o mesmo pedido em vez de abrir um pedido cada.
|
|
87
|
+
if (!pedido_em_andamento) {
|
|
88
|
+
const pedido = pedir_token_ao_termo_auth_buscando_o_segredo_se_preciso()
|
|
89
|
+
.then(({ emitido, segredo_usado }) => {
|
|
90
|
+
// Só guarda se o segredo não foi trocado no meio do pedido (por definir_segredo_do_app).
|
|
91
|
+
if (buscar_segredo_do_app() === segredo_usado) {
|
|
92
|
+
token_em_cache = emitido;
|
|
93
|
+
}
|
|
94
|
+
return emitido;
|
|
95
|
+
})
|
|
96
|
+
.finally(() => {
|
|
97
|
+
if (pedido_em_andamento === pedido) {
|
|
98
|
+
pedido_em_andamento = undefined;
|
|
99
|
+
}
|
|
64
100
|
});
|
|
101
|
+
pedido_em_andamento = pedido;
|
|
65
102
|
}
|
|
66
|
-
// Chamadas simultâneas esperam o mesmo pedido em vez de abrir um pedido cada.
|
|
67
|
-
pedido_em_andamento ??= pedir_token_do_aplicativo_ao_termo_auth(segredo).finally(() => {
|
|
68
|
-
pedido_em_andamento = undefined;
|
|
69
|
-
});
|
|
70
103
|
return pedido_em_andamento;
|
|
71
104
|
}
|
|
72
105
|
/**
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare const CAMINHO_DAS_CHAVES_PUBLICAS = "/.well-known/jwks.json";
|
|
2
|
+
export declare const CABECALHO_DATA = "x-termowebhook-data";
|
|
3
|
+
export declare const CABECALHO_ASSINATURA = "x-termowebhook-assinatura";
|
|
4
|
+
export declare const CABECALHO_CHAVE = "x-termowebhook-chave";
|
|
5
|
+
export declare const CABECALHO_DESTINO = "x-termowebhook-destino";
|
|
6
|
+
export declare const CABECALHO_EVENTO = "x-termowebhook-evento";
|
|
7
|
+
export declare const CABECALHO_ENTREGA = "x-termowebhook-entrega";
|
|
8
|
+
export declare const CABECALHO_TENTATIVA = "x-termowebhook-tentativa";
|
|
9
|
+
export declare const TOLERANCIA_DO_RELOGIO_EM_SEGUNDOS = 300;
|
|
10
|
+
/** `"{data}.{destino}."` seguido dos bytes exatos do corpo. */
|
|
11
|
+
export declare function mensagem_da_entrega(data: number, destino: string, corpo: Uint8Array): Uint8Array<ArrayBuffer>;
|
|
12
|
+
export declare function assinatura_da_entrega_confere(chave_publica: Uint8Array<ArrayBuffer>, data: number, destino: string, corpo: Uint8Array, assinatura: string): Promise<boolean>;
|
|
13
|
+
export declare function data_dentro_da_janela(data: number, agora_em_segundos?: number): boolean;
|
|
14
|
+
/** Endereço do hub vem da configuração global por ambiente (variável `AMBIENTE`), nunca de `.env`. */
|
|
15
|
+
export declare function endereco_do_termo_webhook_no_ambiente_atual(): string;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Feito à mão (o gerador não sobrescreve): cabeçalhos e assinatura Ed25519 das entregas do hub, os mesmos do crate.
|
|
2
|
+
import { assinatura_ed25519_confere, decodificar_base64, juntar_bytes, texto_em_bytes } from "../base/criptografia.js";
|
|
3
|
+
import { endereco_do_servico_no_ambiente_atual } from "../base/servico_termotubos.js";
|
|
4
|
+
import { TERMO_WEBHOOK } from "../base/servicos.js";
|
|
5
|
+
export const CAMINHO_DAS_CHAVES_PUBLICAS = "/.well-known/jwks.json";
|
|
6
|
+
export const CABECALHO_DATA = "x-termowebhook-data";
|
|
7
|
+
export const CABECALHO_ASSINATURA = "x-termowebhook-assinatura";
|
|
8
|
+
export const CABECALHO_CHAVE = "x-termowebhook-chave";
|
|
9
|
+
export const CABECALHO_DESTINO = "x-termowebhook-destino";
|
|
10
|
+
export const CABECALHO_EVENTO = "x-termowebhook-evento";
|
|
11
|
+
export const CABECALHO_ENTREGA = "x-termowebhook-entrega";
|
|
12
|
+
export const CABECALHO_TENTATIVA = "x-termowebhook-tentativa";
|
|
13
|
+
export const TOLERANCIA_DO_RELOGIO_EM_SEGUNDOS = 300;
|
|
14
|
+
const PREFIXO_DA_ASSINATURA_DA_ENTREGA = "ed25519=";
|
|
15
|
+
/** `"{data}.{destino}."` seguido dos bytes exatos do corpo. */
|
|
16
|
+
export function mensagem_da_entrega(data, destino, corpo) {
|
|
17
|
+
return juntar_bytes(texto_em_bytes(`${data}.${destino}.`), corpo);
|
|
18
|
+
}
|
|
19
|
+
export async function assinatura_da_entrega_confere(chave_publica, data, destino, corpo, assinatura) {
|
|
20
|
+
const sem_espacos = assinatura.trim();
|
|
21
|
+
if (!sem_espacos.startsWith(PREFIXO_DA_ASSINATURA_DA_ENTREGA)) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
const bytes = decodificar_base64(sem_espacos.slice(PREFIXO_DA_ASSINATURA_DA_ENTREGA.length));
|
|
25
|
+
if (!bytes) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
return assinatura_ed25519_confere(chave_publica, mensagem_da_entrega(data, destino, corpo), bytes);
|
|
29
|
+
}
|
|
30
|
+
export function data_dentro_da_janela(data, agora_em_segundos = Math.floor(Date.now() / 1000)) {
|
|
31
|
+
return Math.abs(agora_em_segundos - data) <= TOLERANCIA_DO_RELOGIO_EM_SEGUNDOS;
|
|
32
|
+
}
|
|
33
|
+
/** Endereço do hub vem da configuração global por ambiente (variável `AMBIENTE`), nunca de `.env`. */
|
|
34
|
+
export function endereco_do_termo_webhook_no_ambiente_atual() {
|
|
35
|
+
return endereco_do_servico_no_ambiente_atual(TERMO_WEBHOOK);
|
|
36
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Como um evento é identificado no TermoWebhook: é a constante gerada com o mesmo nome do contrato
|
|
3
|
+
* (ex.: `eventos.termo_auth.ColaboradorCriadoV2`), equivalente ao trait `Evento` do crate.
|
|
4
|
+
*/
|
|
5
|
+
export interface Evento {
|
|
6
|
+
readonly aplicativo: string;
|
|
7
|
+
readonly tipo: string;
|
|
8
|
+
readonly versao: number;
|
|
9
|
+
}
|
|
10
|
+
/** O que o app publica no hub. `ocorrido_em` em RFC 3339. */
|
|
11
|
+
export interface Envelope<Dados> {
|
|
12
|
+
id: string;
|
|
13
|
+
tipo: string;
|
|
14
|
+
versao: number;
|
|
15
|
+
entidade_id: string;
|
|
16
|
+
ocorrido_em: string;
|
|
17
|
+
dados: Dados;
|
|
18
|
+
}
|
|
19
|
+
/** O que o hub entrega a quem assinou. Datas em RFC 3339. */
|
|
20
|
+
export interface EventoRecebido<Dados> {
|
|
21
|
+
id: string;
|
|
22
|
+
tipo: string;
|
|
23
|
+
versao: number;
|
|
24
|
+
entidade_id: string;
|
|
25
|
+
ocorrido_em: string;
|
|
26
|
+
recebido_em: string;
|
|
27
|
+
publicador: string;
|
|
28
|
+
dados: Dados;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Monta o envelope de um evento com id UUID v7 e `ocorrido_em` agora, como o `Envelope::novo` do crate:
|
|
32
|
+
* `novo_envelope(eventos.meu_app.PedidoFaturadoV1, String(pedido.id), dados)`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function novo_envelope<Dados>(evento: Evento, entidade_id: string, dados: Dados): Envelope<Dados>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Feito à mão (o gerador não sobrescreve): o envelope publicado e o evento recebido, os mesmos do crate.
|
|
2
|
+
import { novo_uuid_v7 } from "../base/criptografia.js";
|
|
3
|
+
/**
|
|
4
|
+
* Monta o envelope de um evento com id UUID v7 e `ocorrido_em` agora, como o `Envelope::novo` do crate:
|
|
5
|
+
* `novo_envelope(eventos.meu_app.PedidoFaturadoV1, String(pedido.id), dados)`.
|
|
6
|
+
*/
|
|
7
|
+
export function novo_envelope(evento, entidade_id, dados) {
|
|
8
|
+
return {
|
|
9
|
+
id: novo_uuid_v7(),
|
|
10
|
+
tipo: evento.tipo,
|
|
11
|
+
versao: evento.versao,
|
|
12
|
+
entidade_id,
|
|
13
|
+
ocorrido_em: new Date().toISOString(),
|
|
14
|
+
dados,
|
|
15
|
+
};
|
|
16
|
+
}
|
package/dist/webhook/index.d.ts
CHANGED
|
@@ -5,3 +5,7 @@ export * from "./tipos.js";
|
|
|
5
5
|
export * from "./rotas.js";
|
|
6
6
|
export { CredencialDeAcesso, ErroAoChamarServico } from "../base/index.js";
|
|
7
7
|
export * as eventos from "./eventos/index.js";
|
|
8
|
+
export { novo_envelope, type Envelope, type Evento, type EventoRecebido } from "./envelope.js";
|
|
9
|
+
export { assinatura_da_entrega_confere, CABECALHO_ASSINATURA, CABECALHO_CHAVE, CABECALHO_DATA, CABECALHO_DESTINO, CABECALHO_ENTREGA, CABECALHO_EVENTO, CABECALHO_TENTATIVA, CAMINHO_DAS_CHAVES_PUBLICAS, data_dentro_da_janela, endereco_do_termo_webhook_no_ambiente_atual, mensagem_da_entrega, TOLERANCIA_DO_RELOGIO_EM_SEGUNDOS, } from "./assinatura.js";
|
|
10
|
+
export { CAMINHO_DE_PUBLICACAO, ConfiguracaoDoHub, FalhaDePublicacao, publicar_evento_no_hub_agora, type Publicado, type TipoDaFalhaDePublicacao, } from "./publicar.js";
|
|
11
|
+
export { conferir_entrega_recebida_do_hub, conferir_entrega_recebida_do_hub_com_configuracao, ConfiguracaoDeRecebimento, Entrega, ErroDeRecebimento, receber_evento_conferido_do_hub, type CabecalhosDaEntrega, type CorpoDaEntrega, type TipoDoErroDeRecebimento, } from "./receber.js";
|
package/dist/webhook/index.js
CHANGED
|
@@ -6,3 +6,7 @@ export * from "./tipos.js";
|
|
|
6
6
|
export * from "./rotas.js";
|
|
7
7
|
export { CredencialDeAcesso, ErroAoChamarServico } from "../base/index.js";
|
|
8
8
|
export * as eventos from "./eventos/index.js";
|
|
9
|
+
export { novo_envelope } from "./envelope.js";
|
|
10
|
+
export { assinatura_da_entrega_confere, CABECALHO_ASSINATURA, CABECALHO_CHAVE, CABECALHO_DATA, CABECALHO_DESTINO, CABECALHO_ENTREGA, CABECALHO_EVENTO, CABECALHO_TENTATIVA, CAMINHO_DAS_CHAVES_PUBLICAS, data_dentro_da_janela, endereco_do_termo_webhook_no_ambiente_atual, mensagem_da_entrega, TOLERANCIA_DO_RELOGIO_EM_SEGUNDOS, } from "./assinatura.js";
|
|
11
|
+
export { CAMINHO_DE_PUBLICACAO, ConfiguracaoDoHub, FalhaDePublicacao, publicar_evento_no_hub_agora, } from "./publicar.js";
|
|
12
|
+
export { conferir_entrega_recebida_do_hub, conferir_entrega_recebida_do_hub_com_configuracao, ConfiguracaoDeRecebimento, Entrega, ErroDeRecebimento, receber_evento_conferido_do_hub, } from "./receber.js";
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Envelope } from "./envelope.js";
|
|
2
|
+
export declare const CAMINHO_DE_PUBLICACAO = "/eventos";
|
|
3
|
+
export declare class ConfiguracaoDoHub {
|
|
4
|
+
readonly url: string;
|
|
5
|
+
private constructor();
|
|
6
|
+
static nova(url: string): ConfiguracaoDoHub;
|
|
7
|
+
/**
|
|
8
|
+
* Sempre devolve o hub do ambiente atual. Enquanto o segredo do app não estiver configurado
|
|
9
|
+
* (`definir_segredo_do_app` ou `SEGREDO_DO_APP_GERADO_NO_TERMO_AUTH`), os eventos esperam na fila.
|
|
10
|
+
*/
|
|
11
|
+
static carregar_do_ambiente_atual(): ConfiguracaoDoHub;
|
|
12
|
+
endereco_de_publicacao(): string;
|
|
13
|
+
}
|
|
14
|
+
export interface Publicado {
|
|
15
|
+
repetido: boolean;
|
|
16
|
+
aviso: string | undefined;
|
|
17
|
+
}
|
|
18
|
+
export type TipoDaFalhaDePublicacao = "rede" | "sem_token_do_aplicativo" | "recusado" | "serializacao";
|
|
19
|
+
export declare class FalhaDePublicacao extends Error {
|
|
20
|
+
readonly tipo: TipoDaFalhaDePublicacao;
|
|
21
|
+
/** Só em `recusado`: o status HTTP do hub. */
|
|
22
|
+
readonly status: number | undefined;
|
|
23
|
+
/** Só em `recusado`: o campo `motivo` da resposta do hub. */
|
|
24
|
+
readonly motivo: string | undefined;
|
|
25
|
+
readonly mensagem: string;
|
|
26
|
+
constructor(dados: {
|
|
27
|
+
tipo: TipoDaFalhaDePublicacao;
|
|
28
|
+
mensagem: string;
|
|
29
|
+
status?: number;
|
|
30
|
+
motivo?: string;
|
|
31
|
+
});
|
|
32
|
+
private static descrever;
|
|
33
|
+
vale_tentar_de_novo(): boolean;
|
|
34
|
+
}
|
|
35
|
+
export declare function publicar_evento_no_hub_agora<Dados>(configuracao: ConfiguracaoDoHub, envelope: Envelope<Dados>): Promise<Publicado>;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Feito à mão (o gerador não sobrescreve): publicação no hub com o token do aplicativo, a mesma do crate.
|
|
2
|
+
// Só back-end: usa o segredo do app.
|
|
3
|
+
import { segredo_do_app_configurado, token_do_aplicativo, VARIAVEL_DO_SEGREDO_DO_APP } from "../base/token_do_aplicativo.js";
|
|
4
|
+
import { endereco_do_termo_webhook_no_ambiente_atual } from "./assinatura.js";
|
|
5
|
+
export const CAMINHO_DE_PUBLICACAO = "/eventos";
|
|
6
|
+
const TEMPO_LIMITE_EM_MILISSEGUNDOS = 10_000;
|
|
7
|
+
const TAMANHO_MAXIMO_DA_MENSAGEM = 500;
|
|
8
|
+
export class ConfiguracaoDoHub {
|
|
9
|
+
url;
|
|
10
|
+
constructor(url) {
|
|
11
|
+
this.url = url;
|
|
12
|
+
}
|
|
13
|
+
static nova(url) {
|
|
14
|
+
return new ConfiguracaoDoHub(url.trim().replace(/\/+$/, ""));
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Sempre devolve o hub do ambiente atual. Enquanto o segredo do app não estiver configurado
|
|
18
|
+
* (`definir_segredo_do_app` ou `SEGREDO_DO_APP_GERADO_NO_TERMO_AUTH`), os eventos esperam na fila.
|
|
19
|
+
*/
|
|
20
|
+
static carregar_do_ambiente_atual() {
|
|
21
|
+
if (!segredo_do_app_configurado()) {
|
|
22
|
+
console.error(`termo_webhook: segredo do app ainda não configurado (${VARIAVEL_DO_SEGREDO_DO_APP} ou definir_segredo_do_app); os eventos esperam na fila até ele ser cadastrado`);
|
|
23
|
+
}
|
|
24
|
+
return ConfiguracaoDoHub.nova(endereco_do_termo_webhook_no_ambiente_atual());
|
|
25
|
+
}
|
|
26
|
+
endereco_de_publicacao() {
|
|
27
|
+
return `${this.url}${CAMINHO_DE_PUBLICACAO}`;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export class FalhaDePublicacao extends Error {
|
|
31
|
+
tipo;
|
|
32
|
+
/** Só em `recusado`: o status HTTP do hub. */
|
|
33
|
+
status;
|
|
34
|
+
/** Só em `recusado`: o campo `motivo` da resposta do hub. */
|
|
35
|
+
motivo;
|
|
36
|
+
mensagem;
|
|
37
|
+
constructor(dados) {
|
|
38
|
+
super(FalhaDePublicacao.descrever(dados));
|
|
39
|
+
this.name = "FalhaDePublicacao";
|
|
40
|
+
this.tipo = dados.tipo;
|
|
41
|
+
this.status = dados.status;
|
|
42
|
+
this.motivo = dados.motivo;
|
|
43
|
+
this.mensagem = dados.mensagem;
|
|
44
|
+
}
|
|
45
|
+
static descrever(dados) {
|
|
46
|
+
switch (dados.tipo) {
|
|
47
|
+
case "rede":
|
|
48
|
+
return `falha de rede: ${dados.mensagem}`;
|
|
49
|
+
case "sem_token_do_aplicativo":
|
|
50
|
+
return `sem token do aplicativo: ${dados.mensagem}`;
|
|
51
|
+
case "serializacao":
|
|
52
|
+
return `envelope não serializa: ${dados.mensagem}`;
|
|
53
|
+
case "recusado":
|
|
54
|
+
return dados.motivo
|
|
55
|
+
? `hub respondeu ${dados.status} (${dados.motivo}): ${dados.mensagem}`
|
|
56
|
+
: `hub respondeu ${dados.status}: ${dados.mensagem}`;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
vale_tentar_de_novo() {
|
|
60
|
+
switch (this.tipo) {
|
|
61
|
+
case "rede":
|
|
62
|
+
case "sem_token_do_aplicativo":
|
|
63
|
+
return true;
|
|
64
|
+
case "serializacao":
|
|
65
|
+
return false;
|
|
66
|
+
case "recusado":
|
|
67
|
+
return this.status !== 400 && this.status !== 413 && this.status !== 422;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function ler_resposta_do_hub(texto) {
|
|
72
|
+
try {
|
|
73
|
+
const lida = JSON.parse(texto);
|
|
74
|
+
return lida && typeof lida === "object" && !Array.isArray(lida) ? lida : {};
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return {};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function texto_do_valor(valor) {
|
|
81
|
+
if (valor === undefined || valor === null) {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
return typeof valor === "string" ? valor : JSON.stringify(valor);
|
|
85
|
+
}
|
|
86
|
+
function descrever_falha_de_rede(erro) {
|
|
87
|
+
if (erro instanceof Error && (erro.name === "TimeoutError" || erro.name === "AbortError")) {
|
|
88
|
+
return "tempo limite esgotado";
|
|
89
|
+
}
|
|
90
|
+
return erro instanceof Error ? erro.message : String(erro);
|
|
91
|
+
}
|
|
92
|
+
export async function publicar_evento_no_hub_agora(configuracao, envelope) {
|
|
93
|
+
let corpo;
|
|
94
|
+
try {
|
|
95
|
+
corpo = JSON.stringify(envelope);
|
|
96
|
+
}
|
|
97
|
+
catch (erro) {
|
|
98
|
+
throw new FalhaDePublicacao({ tipo: "serializacao", mensagem: String(erro) });
|
|
99
|
+
}
|
|
100
|
+
return enviar_corpo(configuracao, corpo);
|
|
101
|
+
}
|
|
102
|
+
async function enviar_corpo(configuracao, corpo) {
|
|
103
|
+
let token_bearer;
|
|
104
|
+
try {
|
|
105
|
+
token_bearer = (await token_do_aplicativo()).token_bearer();
|
|
106
|
+
}
|
|
107
|
+
catch (erro) {
|
|
108
|
+
throw new FalhaDePublicacao({ tipo: "sem_token_do_aplicativo", mensagem: erro instanceof Error ? erro.message : String(erro) });
|
|
109
|
+
}
|
|
110
|
+
let resposta;
|
|
111
|
+
try {
|
|
112
|
+
resposta = await fetch(configuracao.endereco_de_publicacao(), {
|
|
113
|
+
method: "POST",
|
|
114
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token_bearer}` },
|
|
115
|
+
body: corpo,
|
|
116
|
+
redirect: "manual",
|
|
117
|
+
signal: AbortSignal.timeout(TEMPO_LIMITE_EM_MILISSEGUNDOS),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
catch (erro) {
|
|
121
|
+
throw new FalhaDePublicacao({ tipo: "rede", mensagem: descrever_falha_de_rede(erro) });
|
|
122
|
+
}
|
|
123
|
+
const texto = await resposta.text().catch(() => "");
|
|
124
|
+
const lida = ler_resposta_do_hub(texto);
|
|
125
|
+
if (resposta.status >= 200 && resposta.status <= 299) {
|
|
126
|
+
return { repetido: lida.situacao === "repetido", aviso: texto_do_valor(lida.aviso) };
|
|
127
|
+
}
|
|
128
|
+
const erro = typeof lida.erro === "string" ? lida.erro : undefined;
|
|
129
|
+
const erros = texto_do_valor(lida.erros);
|
|
130
|
+
let mensagem;
|
|
131
|
+
if (erro !== undefined) {
|
|
132
|
+
mensagem = erros !== undefined ? `${erro} ${erros}` : erro;
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
mensagem = texto.trim() ? texto : `${resposta.status} ${resposta.statusText}`.trim();
|
|
136
|
+
}
|
|
137
|
+
throw new FalhaDePublicacao({
|
|
138
|
+
tipo: "recusado",
|
|
139
|
+
status: resposta.status,
|
|
140
|
+
motivo: typeof lida.motivo === "string" ? lida.motivo : undefined,
|
|
141
|
+
mensagem: mensagem.slice(0, TAMANHO_MAXIMO_DA_MENSAGEM),
|
|
142
|
+
});
|
|
143
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Evento, EventoRecebido } from "./envelope.js";
|
|
2
|
+
export declare class ConfiguracaoDeRecebimento {
|
|
3
|
+
readonly url: string;
|
|
4
|
+
readonly aplicativo_id: string;
|
|
5
|
+
private constructor();
|
|
6
|
+
static nova(url: string, aplicativo_id: string): ConfiguracaoDeRecebimento;
|
|
7
|
+
static carregar_do_ambiente_atual(): Promise<ConfiguracaoDeRecebimento>;
|
|
8
|
+
endereco_das_chaves(): string;
|
|
9
|
+
}
|
|
10
|
+
export type TipoDoErroDeRecebimento = "sem_identificacao_do_aplicativo" | "sem_assinatura" | "fora_da_janela" | "chave_desconhecida" | "chaves_indisponiveis" | "assinatura_invalida" | "corpo_invalido" | "tipo_diferente";
|
|
11
|
+
interface DadosDoErroDeRecebimento {
|
|
12
|
+
tipo: TipoDoErroDeRecebimento;
|
|
13
|
+
detalhe?: string;
|
|
14
|
+
/** Só em `tipo_diferente`. */
|
|
15
|
+
tipo_do_evento?: string;
|
|
16
|
+
/** Só em `tipo_diferente`. */
|
|
17
|
+
versao_do_evento?: number;
|
|
18
|
+
}
|
|
19
|
+
export declare class ErroDeRecebimento extends Error {
|
|
20
|
+
readonly tipo: TipoDoErroDeRecebimento;
|
|
21
|
+
readonly detalhe: string | undefined;
|
|
22
|
+
readonly tipo_do_evento: string | undefined;
|
|
23
|
+
readonly versao_do_evento: number | undefined;
|
|
24
|
+
constructor(dados: DadosDoErroDeRecebimento);
|
|
25
|
+
/** O status HTTP para responder ao hub: 401 (assinatura), 503 (sem segredo: o hub reenvia), 400 ou 200 (tipo que o app não trata). */
|
|
26
|
+
status(): number;
|
|
27
|
+
}
|
|
28
|
+
/** Uma entrega com a assinatura já conferida; `ler` devolve o evento tipado. */
|
|
29
|
+
export declare class Entrega {
|
|
30
|
+
#private;
|
|
31
|
+
readonly id: string;
|
|
32
|
+
readonly tipo: string;
|
|
33
|
+
readonly versao: number;
|
|
34
|
+
constructor(corpo: Uint8Array, id: string, tipo: string, versao: number);
|
|
35
|
+
/** `entrega.e(eventos.termo_auth.ColaboradorCriadoV2)` */
|
|
36
|
+
e(evento: Evento): boolean;
|
|
37
|
+
/** `entrega.ler<eventos.termo_auth.ColaboradorCriadoV2>(eventos.termo_auth.ColaboradorCriadoV2)` */
|
|
38
|
+
ler<Dados>(evento: Evento): EventoRecebido<Dados>;
|
|
39
|
+
corpo(): Uint8Array;
|
|
40
|
+
}
|
|
41
|
+
/** `Headers` do `fetch` (Workers, Hono, Next) ou o objeto de cabeçalhos do Node (`req.headers` do http/Express/Fastify). */
|
|
42
|
+
export type CabecalhosDaEntrega = Headers | Record<string, string | string[] | undefined>;
|
|
43
|
+
/** O corpo cru, exatamente como chegou: a assinatura cobre os bytes. */
|
|
44
|
+
export type CorpoDaEntrega = Uint8Array | ArrayBuffer | string;
|
|
45
|
+
export declare function conferir_entrega_recebida_do_hub_com_configuracao(configuracao: ConfiguracaoDeRecebimento, cabecalhos: CabecalhosDaEntrega, corpo: CorpoDaEntrega): Promise<Entrega>;
|
|
46
|
+
export declare function conferir_entrega_recebida_do_hub(cabecalhos: CabecalhosDaEntrega, corpo: CorpoDaEntrega): Promise<Entrega>;
|
|
47
|
+
export declare function receber_evento_conferido_do_hub<Dados>(evento: Evento, cabecalhos: CabecalhosDaEntrega, corpo: CorpoDaEntrega): Promise<EventoRecebido<Dados>>;
|
|
48
|
+
export {};
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// Feito à mão (o gerador não sobrescreve): recebimento das entregas do hub, conferidas com a chave pública dele,
|
|
2
|
+
// o mesmo do crate. Só back-end: o destino assinado é o id do app, que vem do token de aplicativo.
|
|
3
|
+
import { bytes_em_texto, decodificar_base64, texto_em_bytes } from "../base/criptografia.js";
|
|
4
|
+
import { identificador_do_aplicativo } from "../base/token_do_aplicativo.js";
|
|
5
|
+
import { assinatura_da_entrega_confere, CABECALHO_ASSINATURA, CABECALHO_CHAVE, CABECALHO_DATA, CAMINHO_DAS_CHAVES_PUBLICAS, data_dentro_da_janela, endereco_do_termo_webhook_no_ambiente_atual, } from "./assinatura.js";
|
|
6
|
+
const TEMPO_LIMITE_EM_MILISSEGUNDOS = 10_000;
|
|
7
|
+
const INTERVALO_MINIMO_ENTRE_BUSCAS_EM_MILISSEGUNDOS = 30_000;
|
|
8
|
+
export class ConfiguracaoDeRecebimento {
|
|
9
|
+
url;
|
|
10
|
+
aplicativo_id;
|
|
11
|
+
constructor(url, aplicativo_id) {
|
|
12
|
+
this.url = url;
|
|
13
|
+
this.aplicativo_id = aplicativo_id;
|
|
14
|
+
}
|
|
15
|
+
static nova(url, aplicativo_id) {
|
|
16
|
+
return new ConfiguracaoDeRecebimento(url.trim().replace(/\/+$/, ""), aplicativo_id);
|
|
17
|
+
}
|
|
18
|
+
static async carregar_do_ambiente_atual() {
|
|
19
|
+
let aplicativo_id;
|
|
20
|
+
try {
|
|
21
|
+
aplicativo_id = await identificador_do_aplicativo();
|
|
22
|
+
}
|
|
23
|
+
catch (erro) {
|
|
24
|
+
throw new ErroDeRecebimento({ tipo: "sem_identificacao_do_aplicativo", detalhe: erro instanceof Error ? erro.message : String(erro) });
|
|
25
|
+
}
|
|
26
|
+
return ConfiguracaoDeRecebimento.nova(endereco_do_termo_webhook_no_ambiente_atual(), aplicativo_id);
|
|
27
|
+
}
|
|
28
|
+
endereco_das_chaves() {
|
|
29
|
+
return `${this.url}${CAMINHO_DAS_CHAVES_PUBLICAS}`;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function montar_mensagem_do_recebimento(dados) {
|
|
33
|
+
switch (dados.tipo) {
|
|
34
|
+
case "sem_identificacao_do_aplicativo":
|
|
35
|
+
return `não foi possível saber o id do app no TermoAuth pelo token de aplicativo: ${dados.detalhe ?? ""}`;
|
|
36
|
+
case "sem_assinatura":
|
|
37
|
+
return "entrega sem os cabeçalhos X-TermoWebhook-Data, X-TermoWebhook-Chave e X-TermoWebhook-Assinatura";
|
|
38
|
+
case "fora_da_janela":
|
|
39
|
+
return "X-TermoWebhook-Data fora da tolerância de 5 minutos";
|
|
40
|
+
case "chave_desconhecida":
|
|
41
|
+
return `chave ${dados.detalhe ?? ""} não está entre as chaves públicas do hub`;
|
|
42
|
+
case "chaves_indisponiveis":
|
|
43
|
+
return `não foi possível buscar as chaves públicas do hub: ${dados.detalhe ?? ""}`;
|
|
44
|
+
case "assinatura_invalida":
|
|
45
|
+
return "assinatura não confere com a chave do hub para este aplicativo";
|
|
46
|
+
case "corpo_invalido":
|
|
47
|
+
return `corpo da entrega inválido: ${dados.detalhe ?? ""}`;
|
|
48
|
+
case "tipo_diferente":
|
|
49
|
+
return `evento ${dados.tipo_do_evento ?? ""} v${dados.versao_do_evento ?? ""} não é o esperado`;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export class ErroDeRecebimento extends Error {
|
|
53
|
+
tipo;
|
|
54
|
+
detalhe;
|
|
55
|
+
tipo_do_evento;
|
|
56
|
+
versao_do_evento;
|
|
57
|
+
constructor(dados) {
|
|
58
|
+
super(montar_mensagem_do_recebimento(dados));
|
|
59
|
+
this.name = "ErroDeRecebimento";
|
|
60
|
+
this.tipo = dados.tipo;
|
|
61
|
+
this.detalhe = dados.detalhe;
|
|
62
|
+
this.tipo_do_evento = dados.tipo_do_evento;
|
|
63
|
+
this.versao_do_evento = dados.versao_do_evento;
|
|
64
|
+
}
|
|
65
|
+
/** O status HTTP para responder ao hub: 401 (assinatura), 503 (sem segredo: o hub reenvia), 400 ou 200 (tipo que o app não trata). */
|
|
66
|
+
status() {
|
|
67
|
+
switch (this.tipo) {
|
|
68
|
+
case "sem_assinatura":
|
|
69
|
+
case "fora_da_janela":
|
|
70
|
+
case "chave_desconhecida":
|
|
71
|
+
case "assinatura_invalida":
|
|
72
|
+
return 401;
|
|
73
|
+
case "sem_identificacao_do_aplicativo":
|
|
74
|
+
case "chaves_indisponiveis":
|
|
75
|
+
return 503;
|
|
76
|
+
case "corpo_invalido":
|
|
77
|
+
return 400;
|
|
78
|
+
case "tipo_diferente":
|
|
79
|
+
return 200;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** Uma entrega com a assinatura já conferida; `ler` devolve o evento tipado. */
|
|
84
|
+
export class Entrega {
|
|
85
|
+
#corpo;
|
|
86
|
+
id;
|
|
87
|
+
tipo;
|
|
88
|
+
versao;
|
|
89
|
+
constructor(corpo, id, tipo, versao) {
|
|
90
|
+
this.#corpo = corpo;
|
|
91
|
+
this.id = id;
|
|
92
|
+
this.tipo = tipo;
|
|
93
|
+
this.versao = versao;
|
|
94
|
+
}
|
|
95
|
+
/** `entrega.e(eventos.termo_auth.ColaboradorCriadoV2)` */
|
|
96
|
+
e(evento) {
|
|
97
|
+
return this.tipo === evento.tipo && this.versao === evento.versao;
|
|
98
|
+
}
|
|
99
|
+
/** `entrega.ler<eventos.termo_auth.ColaboradorCriadoV2>(eventos.termo_auth.ColaboradorCriadoV2)` */
|
|
100
|
+
ler(evento) {
|
|
101
|
+
if (!this.e(evento)) {
|
|
102
|
+
throw new ErroDeRecebimento({ tipo: "tipo_diferente", tipo_do_evento: this.tipo, versao_do_evento: this.versao });
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
return JSON.parse(bytes_em_texto(this.#corpo));
|
|
106
|
+
}
|
|
107
|
+
catch (erro) {
|
|
108
|
+
throw new ErroDeRecebimento({ tipo: "corpo_invalido", detalhe: String(erro) });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
corpo() {
|
|
112
|
+
return this.#corpo;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
let chaves_conhecidas = new Map();
|
|
116
|
+
let instante_da_ultima_busca_em_milissegundos;
|
|
117
|
+
let busca_em_andamento;
|
|
118
|
+
async function buscar_chaves(configuracao) {
|
|
119
|
+
let resposta;
|
|
120
|
+
try {
|
|
121
|
+
resposta = await fetch(configuracao.endereco_das_chaves(), {
|
|
122
|
+
redirect: "manual",
|
|
123
|
+
signal: AbortSignal.timeout(TEMPO_LIMITE_EM_MILISSEGUNDOS),
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
catch (erro) {
|
|
127
|
+
throw new ErroDeRecebimento({ tipo: "chaves_indisponiveis", detalhe: erro instanceof Error ? erro.message : String(erro) });
|
|
128
|
+
}
|
|
129
|
+
if (resposta.status < 200 || resposta.status > 299) {
|
|
130
|
+
throw new ErroDeRecebimento({ tipo: "chaves_indisponiveis", detalhe: `hub respondeu ${resposta.status}` });
|
|
131
|
+
}
|
|
132
|
+
let conjunto;
|
|
133
|
+
try {
|
|
134
|
+
conjunto = await resposta.json();
|
|
135
|
+
}
|
|
136
|
+
catch (erro) {
|
|
137
|
+
throw new ErroDeRecebimento({ tipo: "chaves_indisponiveis", detalhe: String(erro) });
|
|
138
|
+
}
|
|
139
|
+
const chaves = conjunto?.keys;
|
|
140
|
+
if (!Array.isArray(chaves)) {
|
|
141
|
+
throw new ErroDeRecebimento({ tipo: "chaves_indisponiveis", detalhe: "resposta sem a lista keys" });
|
|
142
|
+
}
|
|
143
|
+
const encontradas = new Map();
|
|
144
|
+
for (const chave of chaves) {
|
|
145
|
+
if (typeof chave?.kid !== "string" || typeof chave.x !== "string") {
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const bytes = decodificar_base64(chave.x);
|
|
149
|
+
if (bytes?.length === 32) {
|
|
150
|
+
encontradas.set(chave.kid, bytes);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return encontradas;
|
|
154
|
+
}
|
|
155
|
+
// Um kid desconhecido busca as chaves de novo (o hub pode ter trocado a dele), mas no máximo
|
|
156
|
+
// a cada 30 s: entrega forjada com kid inventado não vira enxurrada de chamadas ao hub.
|
|
157
|
+
async function chave_publica(configuracao, kid) {
|
|
158
|
+
const em_cache = chaves_conhecidas.get(kid);
|
|
159
|
+
if (em_cache) {
|
|
160
|
+
return em_cache;
|
|
161
|
+
}
|
|
162
|
+
if (busca_em_andamento) {
|
|
163
|
+
await busca_em_andamento.catch(() => undefined);
|
|
164
|
+
const buscada = chaves_conhecidas.get(kid);
|
|
165
|
+
if (buscada) {
|
|
166
|
+
return buscada;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (instante_da_ultima_busca_em_milissegundos !== undefined &&
|
|
170
|
+
Date.now() - instante_da_ultima_busca_em_milissegundos < INTERVALO_MINIMO_ENTRE_BUSCAS_EM_MILISSEGUNDOS) {
|
|
171
|
+
throw new ErroDeRecebimento({ tipo: "chave_desconhecida", detalhe: kid });
|
|
172
|
+
}
|
|
173
|
+
const busca = buscar_chaves(configuracao).then((chaves) => {
|
|
174
|
+
instante_da_ultima_busca_em_milissegundos = Date.now();
|
|
175
|
+
chaves_conhecidas = chaves;
|
|
176
|
+
});
|
|
177
|
+
busca_em_andamento = busca;
|
|
178
|
+
try {
|
|
179
|
+
await busca;
|
|
180
|
+
}
|
|
181
|
+
finally {
|
|
182
|
+
if (busca_em_andamento === busca) {
|
|
183
|
+
busca_em_andamento = undefined;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const encontrada = chaves_conhecidas.get(kid);
|
|
187
|
+
if (!encontrada) {
|
|
188
|
+
throw new ErroDeRecebimento({ tipo: "chave_desconhecida", detalhe: kid });
|
|
189
|
+
}
|
|
190
|
+
return encontrada;
|
|
191
|
+
}
|
|
192
|
+
function ler_cabecalho(cabecalhos, nome) {
|
|
193
|
+
if (typeof cabecalhos.get === "function") {
|
|
194
|
+
return cabecalhos.get(nome) ?? undefined;
|
|
195
|
+
}
|
|
196
|
+
const registro = cabecalhos;
|
|
197
|
+
const nome_encontrado = Object.keys(registro).find((chave) => chave.toLowerCase() === nome);
|
|
198
|
+
const valor = nome_encontrado === undefined ? undefined : registro[nome_encontrado];
|
|
199
|
+
return Array.isArray(valor) ? valor[0] : valor;
|
|
200
|
+
}
|
|
201
|
+
function corpo_em_bytes(corpo) {
|
|
202
|
+
if (typeof corpo === "string") {
|
|
203
|
+
return texto_em_bytes(corpo);
|
|
204
|
+
}
|
|
205
|
+
return corpo instanceof Uint8Array ? corpo : new Uint8Array(corpo);
|
|
206
|
+
}
|
|
207
|
+
function ler_identificacao(corpo) {
|
|
208
|
+
let lida;
|
|
209
|
+
try {
|
|
210
|
+
lida = JSON.parse(bytes_em_texto(corpo));
|
|
211
|
+
}
|
|
212
|
+
catch (erro) {
|
|
213
|
+
throw new ErroDeRecebimento({ tipo: "corpo_invalido", detalhe: String(erro) });
|
|
214
|
+
}
|
|
215
|
+
const { id, tipo, versao } = (lida ?? {});
|
|
216
|
+
if (typeof id !== "string" || typeof tipo !== "string" || typeof versao !== "number" || !Number.isInteger(versao)) {
|
|
217
|
+
throw new ErroDeRecebimento({ tipo: "corpo_invalido", detalhe: "faltam id, tipo ou versao" });
|
|
218
|
+
}
|
|
219
|
+
return { id, tipo, versao };
|
|
220
|
+
}
|
|
221
|
+
export async function conferir_entrega_recebida_do_hub_com_configuracao(configuracao, cabecalhos, corpo) {
|
|
222
|
+
const texto_da_data = ler_cabecalho(cabecalhos, CABECALHO_DATA)?.trim();
|
|
223
|
+
const data = texto_da_data && /^-?\d+$/.test(texto_da_data) ? Number(texto_da_data) : undefined;
|
|
224
|
+
const kid = ler_cabecalho(cabecalhos, CABECALHO_CHAVE);
|
|
225
|
+
const assinatura = ler_cabecalho(cabecalhos, CABECALHO_ASSINATURA);
|
|
226
|
+
if (data === undefined || kid === undefined || assinatura === undefined) {
|
|
227
|
+
throw new ErroDeRecebimento({ tipo: "sem_assinatura" });
|
|
228
|
+
}
|
|
229
|
+
if (!data_dentro_da_janela(data)) {
|
|
230
|
+
throw new ErroDeRecebimento({ tipo: "fora_da_janela" });
|
|
231
|
+
}
|
|
232
|
+
const chave = await chave_publica(configuracao, kid.trim());
|
|
233
|
+
const bytes_do_corpo = corpo_em_bytes(corpo);
|
|
234
|
+
if (!(await assinatura_da_entrega_confere(chave, data, configuracao.aplicativo_id, bytes_do_corpo, assinatura))) {
|
|
235
|
+
throw new ErroDeRecebimento({ tipo: "assinatura_invalida" });
|
|
236
|
+
}
|
|
237
|
+
const { id, tipo, versao } = ler_identificacao(bytes_do_corpo);
|
|
238
|
+
return new Entrega(bytes_do_corpo, id, tipo, versao);
|
|
239
|
+
}
|
|
240
|
+
export async function conferir_entrega_recebida_do_hub(cabecalhos, corpo) {
|
|
241
|
+
const configuracao = await ConfiguracaoDeRecebimento.carregar_do_ambiente_atual();
|
|
242
|
+
return conferir_entrega_recebida_do_hub_com_configuracao(configuracao, cabecalhos, corpo);
|
|
243
|
+
}
|
|
244
|
+
export async function receber_evento_conferido_do_hub(evento, cabecalhos, corpo) {
|
|
245
|
+
return (await conferir_entrega_recebida_do_hub(cabecalhos, corpo)).ler(evento);
|
|
246
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "termo_core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.30",
|
|
4
4
|
"description": "Todos os clientes da Termotubos num pacote só: um módulo por serviço e cada rota da API como uma função com fetch, com o endereço resolvido pelo ambiente atual.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "TI Termotubos <ti@termotubos.com.br>",
|