termo_core 0.1.49 → 0.1.51
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 +0 -22
- package/dist/base/servicos.d.ts +0 -1
- package/dist/base/servicos.js +0 -9
- package/dist/index.d.ts +0 -1
- package/dist/index.js +0 -1
- package/dist/tracing/rotas.d.ts +66 -0
- package/dist/tracing/rotas.js +67 -0
- package/dist/tracing/tipos.d.ts +94 -0
- package/package.json +3 -3
- package/dist/webhook/assinatura.d.ts +0 -15
- package/dist/webhook/assinatura.js +0 -36
- package/dist/webhook/envelope.d.ts +0 -34
- package/dist/webhook/envelope.js +0 -16
- package/dist/webhook/eventos/index.d.ts +0 -1
- package/dist/webhook/eventos/index.js +0 -2
- package/dist/webhook/eventos/termo_auth.d.ts +0 -108
- package/dist/webhook/eventos/termo_auth.js +0 -37
- package/dist/webhook/index.d.ts +0 -11
- package/dist/webhook/index.js +0 -12
- package/dist/webhook/publicar.d.ts +0 -35
- package/dist/webhook/publicar.js +0 -143
- package/dist/webhook/receber.d.ts +0 -48
- package/dist/webhook/receber.js +0 -246
- package/dist/webhook/rotas.d.ts +0 -503
- package/dist/webhook/rotas.js +0 -709
- package/dist/webhook/tipos.d.ts +0 -487
- package/dist/webhook/tipos.js +0 -2
|
@@ -1,35 +0,0 @@
|
|
|
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>;
|
package/dist/webhook/publicar.js
DELETED
|
@@ -1,143 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,48 +0,0 @@
|
|
|
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 {};
|
package/dist/webhook/receber.js
DELETED
|
@@ -1,246 +0,0 @@
|
|
|
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
|
-
}
|