Pular para o conteúdo

Content Filter

Remove campos sensíveis ou desnecessários antes de repassar a mensagem (minimização de dados da LGPD). Inverso do Content Enricher.

passos
4
arquivos
5
testes
0
tecnologias
4

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ência
4/4
evento cru (cpf, nome, saldo, valor, tipo)1allowlist + HMAC da conta2POST /score (só o mínimo)3200 com o score4Core bancárioContent FilterProvedor de scoring
4

4 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.

  1. 1

    AllowlistSó os campos listados passam

  2. 2

    Conta vira HMAC-SHA256 com CONTENT_FILTER_HMAC_KEY

  3. 3

    O filtrado vai ao provedor por fetch()

  4. 4

    O provedor usa schema estritoO evento cru, sem filtro, volta 422

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar só Bun

  1. cp .env.example .env# variáveis de ambiente
  2. bun install# dependências
  3. bun run demo# roda o cenário

Saída: evento filtrado sem CPF e com conta em hash: scoring 200 com score 21.5; evento cru recusado com 422.

Requisitos
Bun

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

Linhas de TypeScript
44
Tipo
A — código puro

Domínio financeiro

  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

  • Content Filter

Variáveis de ambiente

CONTENT_FILTER_HMAC_KEY
replace-with-a-random-key-of-at-least-32-chars
HMAC key that pseudonymizes the account before the event leaves the bank. Secret: no default in the code; generate your own.
CONTENT_FILTER_PROVIDER_PORT
8104
Port of the third-party scoring provider (POST /score).

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Content Filter?

Próximo projeto, Mensageria & EventosControl Bus
Esc

↑ ↓ navegarEnter abrir239 resultados