termo_core 0.1.29 → 0.1.31
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/flow/rotas.d.ts +78 -2
- package/dist/flow/rotas.js +103 -2
- package/dist/flow/tipos.d.ts +159 -0
- package/dist/portal/rotas.d.ts +3 -2
- package/dist/portal/rotas.js +2 -2
- package/dist/portal/tipos.d.ts +1 -0
- 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/dist/portal/tipos.d.ts
CHANGED
|
@@ -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.31",
|
|
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>",
|