Aller au contenu
ZarexDocs

Fastify

Protégez une application Fastify (ou NestJS sur Fastify) avec le hook @zarex/fastify.

Installation

npm install @zarex/fastify
.env
ZAREX_KEY=zarex_test_...

Protéger l'application

server.ts
import Fastify from "fastify";
import { zarexFastify, shield, rateLimit } from "@zarex/fastify";

const app = Fastify();

app.addHook(
  "onRequest",
  zarexFastify({
    key: process.env.ZAREX_KEY!,
    rules: [shield(), rateLimit({ max: 100, window: "1m" })],
  })
);

app.get("/", async () => ({ ok: true }));
app.listen({ port: 3000 });

Une requête refusée reçoit automatiquement 403, ou 429 avec retry-after.

Avec NestJS

main.ts
import type { FastifyInstance } from "fastify";

(app.getHttpAdapter().getInstance() as FastifyInstance).addHook(
  "onRequest",
  zarexFastify({ key: process.env.ZAREX_KEY!, rules: [shield()] })
);

L'adresse IP du visiteur

Zarex utilise request.ip, calculé par Fastify selon l'option trustProxy de votre serveur. Derrière un proxy, réglez-la selon votre infrastructure réelle : sinon tous vos visiteurs semblent venir de la même adresse.

Analyser le corps des requêtes

Choisissez le bon hook

En onRequest, Fastify n'a pas encore lu le corps : inspectBody ne verrait rien. Pour analyser le corps, enregistrez le hook en preHandler.

app.addHook(
  "preHandler",
  zarexFastify({ key: process.env.ZAREX_KEY!, inspectBody: true, rules: [shield()] })
);

Identifiants et données de formulaire

app.addHook(
  "preHandler",
  zarexFastify({
    key: process.env.ZAREX_KEY!,
    rules: [rateLimit({ max: 100, window: "1m", characteristics: ["userId"] })],
    call: (req) => ({ characteristics: { userId: req.user?.id } }),
  })
);

call peut aussi fournir email, phone, text et tokensRequested. Les identifiants sont hachés (SHA-256) avant l'envoi.

Lire la décision

app.get("/", async (req) => {
  console.log(req.zarex?.verdict); // "ALLOW" | "DENY"
  return { ok: true };
});

Personnaliser le refus

zarexFastify({
  key: process.env.ZAREX_KEY!,
  rules: [shield()],
  onDeny: (req, reply, decision) => {
    reply.code(403).send({ erreur: "Requête refusée", id: decision.id });
  },
});

En-têtes de sécurité et réponses

secureHeaders: true ajoute les en-têtes de sécurité à toutes les réponses. Pour surveiller les réponses de votre application, Fastify demande un second hook :

import { zarexFastifyOnSend } from "@zarex/fastify";

app.addHook("onSend", zarexFastifyOnSend({ responseGuard: true }));

Sur cette page