pattern/messaging/content-filter
- Bun
- ElysiaJS
- TypeScript
- node:crypto
Remove campos sensíveis ou desnecessários antes de repassar a mensagem (minimização de dados da LGPD). Inverso do Content Enricher.
pattern/messaging/content-filter
Cenário
Evento de transação com CPF, nome e saldo sai para o scoring terceirizado só com valor, tipo e pseudônimo da conta.
Planta
Sequência4 passos — reproduza para seguir o fluxo
Como funciona
4passos
Remove campos sensíveis ou desnecessários antes de repassar a mensagem (minimização de dados da LGPD)
Esconde cada passo: lembre antes de tocar para revelar.
AllowlistSó os campos listados passam
Conta vira HMAC-SHA256 com CONTENT_FILTER_HMAC_KEY
O filtrado vai ao provedor por fetch()
O provedor usa schema estritoO evento cru, sem filtro, volta 422
Trade-offs
O que se ganha, o que se paga
Vantagens
Dado sensível não sai do perímetro
Pseudônimo permite correlacionar
Custos
Consumidor não recebe o imprevisto
Chave HMAC é segredo a guardar
Código
pattern/messaging/content-filter
5 arquivos./
src/
Executar só Bun
cp .env.example .env# variáveis de ambientebun install# dependênciasbun run demo# roda o cenárioSaída: evento filtrado sem CPF e com conta em hash: scoring 200 com score 21.5; evento cru recusado com 422.
Código
src/demo.ts// Demo: the raw ledger event is reduced to the minimum before it leaves the bank for a third-party scoring provider (LGPD).
import { createHmac } from "node:crypto";
import { Elysia, t } from "elysia";
// Secret: whoever holds it can link hashes back to accounts; the default is the example key, never a production one.
const CONTENT_FILTER_HMAC_KEY = Bun.env.CONTENT_FILTER_HMAC_KEY ?? "replace-with-a-random-key-of-at-least-32-chars";
const PROVIDER_PORT = Number(Bun.env.CONTENT_FILTER_PROVIDER_PORT ?? 8104);
const PROVIDER_SCORE_URL = `http://localhost:${PROVIDER_PORT}/score`;
const raw = {
transactionId: "TRX-0001",
accountId: "ACC-00421",
cpf: "123.456.789-00",
holderName: "Marina Albuquerque",
balanceFullCents: 1_843_055,
amountCents: 150_000,
type: "pix",
};
// Allowlist projection: only the listed fields pass, so a field added to the raw event later cannot leak.
// The account becomes a keyed HMAC: correlatable across events, but a plain hash would be reversed by brute force.
function eventTransactionFilter(event: typeof raw) {
return {
transactionId: event.transactionId,
accountIdHash: createHmac("sha256", CONTENT_FILTER_HMAC_KEY).update(event.accountId).digest("hex"),
amountCents: event.amountCents,
type: event.type,
};
}
// The provider's strict schema turns a filter bug into a 422 instead of a silent leak.
const provider = new Elysia()
.post("/score", ({ body }) => ({ transactionId: body.transactionId, score: 20 + Math.min(body.amountCents / 100_000, 60) }), {
body: t.Object(
{ transactionId: t.String(), accountIdHash: t.String({ pattern: "^[0-9a-f]{64}$" }), amountCents: t.Integer(), type: t.String() },
{ additionalProperties: false },
),
})
.listen(PROVIDER_PORT);
const filtered = eventTransactionFilter(raw);
console.log(` [RAW] ${JSON.stringify(raw)}`);
console.log(` [FILTERED] ${JSON.stringify(filtered)}`);
const scorePost = (event: object) => fetch(PROVIDER_SCORE_URL, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(event) });
const response = await scorePost(filtered);
console.log(` [SCORING] HTTP ${response.status} ${JSON.stringify(await response.json())}`);
// Without the filter: the strict schema refuses the raw event, so a filter bug fails loudly instead of silently.
console.log(` [UNFILTERED] HTTP ${(await scorePost(raw)).status}`);
await provider.stop();
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com Content Filter?
Limpa antes de padronizar. Abrir Normalizer
Seu progresso
0/157 estudados
Fica salvo só neste navegador.