termo_core 0.1.28 → 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/flow/rotas.d.ts +6 -7
- package/dist/flow/rotas.js +5 -5
- package/dist/flow/tipos.d.ts +2 -1
- 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
|
@@ -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>",
|