pattern/security/gatekeeper
- AbortSignal
- Bun
- ElysiaJS
- PostgreSQL
- TypeScript
- node-postgres
- node:crypto
- Docker
Processo dedicado entre a internet e o core: única porta pública, autentica, limita, valida e limpa o payload e repassa com segredo compartilhado. O core recusa qualquer chamada sem o segredo.
pattern/security/gatekeeper
Cenário
Transferência com campo injetado (isAdmin) é limpa e repassada; chamada direta ao core recebe 403.
Planta
Fluxo4 passos — reproduza para seguir o fluxo
Como funciona
4passos
Processo dedicado entre a internet e o core que autentica, limita, valida e repassa com segredo compartilhado
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
onRequest confere o token do canal em tempo constante; maxRequestBodySize limita o corpo
Schema valida e remove campos não declarados
Repasse com x-gatekeeper-secret e timeout; erro do core → 502 genérico
Core em 127.0.0.1, timingSafeEqual e schema validado de novo
Trade-offs
O que se ganha, o que se paga
Vantagens
Core nunca exposto
Rede e segredo se cobrem
Custos
Um salto a mais
Ponto crítico; segredo exige rotação
Código
pattern/security/gatekeeper
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec gatekeeper-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f gatekeeper-dbSaída: pelo gatekeeper, 201 com a transferência gravada sem o isAdmin; direto no core, 403 calls must come through the gatekeeper.
Código
src/demo.ts// Demo: the gatekeeper is the only entry — it checks the channel, validates and strips the transfer, and forwards it to
// the core with a shared secret; the core refuses anything that did not come through it.
import { timingSafeEqual } from "node:crypto";
import { Elysia, t } from "elysia";
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.GATEKEEPER_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/core_bank_db" });
const SHARED_SECRET = Bun.env.GATEKEEPER_SHARED_SECRET ?? "change-me-internal-only-secret-32b";
const CHANNEL_TOKEN = Bun.env.GATEKEEPER_CHANNEL_TOKEN ?? "mobile-app-token-change-me-2026";
const CORE_URL = "http://127.0.0.1:8705";
const CORE_TIMEOUT_MS = 3_000;
const BODY_MAX_BYTES = 2_048;
// Constant time; the length is checked first because timingSafeEqual throws on a size mismatch.
const secretMatches = (received: string | null | undefined, expected: string) => Buffer.from(received ?? "").length === Buffer.from(expected).length && timingSafeEqual(Buffer.from(received ?? ""), Buffer.from(expected));
// Undeclared fields are dropped by Elysia before the handler sees the body.
const schemaTransfer = t.Object({
fromAccount: t.String({ pattern: "^[0-9]{4}-[0-9]{4,10}$" }),
toAccount: t.String({ pattern: "^[0-9]{4}-[0-9]{4,10}$" }),
amountCents: t.Integer({ minimum: 1, maximum: 100_000_000 }),
});
// The core: the only writer of the database, bound to 127.0.0.1, and still refusing calls without the secret.
const core = new Elysia()
.onBeforeHandle(({ headers, status }) => (secretMatches(headers["x-gatekeeper-secret"], SHARED_SECRET) ? undefined : status(403, "calls must come through the gatekeeper")))
.post("/transfers", async ({ body, status }) => {
const { rows: [transfer] } = await pool.query<{ id: string }>("INSERT INTO transfers (from_account, to_account, amount_cents) VALUES ($1, $2, $3) RETURNING id", [body.fromAccount, body.toAccount, body.amountCents]);
return status(201, { id: transfer?.id, status: "completed", stored: body });
}, { body: schemaTransfer })
.listen({ hostname: "127.0.0.1", port: new URL(CORE_URL).port });
// The gatekeeper: unknown channel and oversized body are refused before any parse; the schema validates and strips.
const gatekeeper = new Elysia({ serve: { maxRequestBodySize: BODY_MAX_BYTES } })
.onRequest(({ request, status }) => (secretMatches(request.headers.get("x-channel-token"), CHANNEL_TOKEN) ? undefined : status(401, "unknown channel")))
.post("/transfers", async ({ body }) => {
const response = await fetch(`${CORE_URL}/transfers`, { method: "POST", headers: { "content-type": "application/json", "x-gatekeeper-secret": SHARED_SECRET }, body: JSON.stringify(body), signal: AbortSignal.timeout(CORE_TIMEOUT_MS) });
// The core's own errors are not relayed as they are: the internet gets a generic 502.
return response.status >= 500 ? new Response("core unavailable", { status: 502 }) : new Response(await response.text(), { status: response.status });
}, { body: schemaTransfer });
const injected = { fromAccount: "0001-11112222", toAccount: "0002-33334444", amountCents: 250_000, isAdmin: true };
const viaGatekeeper = await gatekeeper.handle(new Request("http://bank/transfers", { method: "POST", headers: { "content-type": "application/json", "x-channel-token": CHANNEL_TOKEN }, body: JSON.stringify(injected) }));
console.log(` [GATEKEEPER] transfer with injected isAdmin → ${viaGatekeeper.status} ${await viaGatekeeper.text()}`);
const direct = await fetch(`${CORE_URL}/transfers`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(injected) });
console.log(` [DIRECT] straight to the core → ${direct.status} ${await direct.text()}`);
await core.stop(true);
await pool.end();
Nível
intermediário
4/13
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Por que se relacionam
Teste rápido
Qual destes combina com Gatekeeper?
Valida antes de assinar o acesso. Abrir Valet Key
Seu progresso
0/157 estudados
Fica salvo só neste navegador.