.ts
TypeScript
(application/typescript)
// std
import { createHash } from "node:crypto";
// 3rd-party
import fp from "fastify-plugin";
import { FastifyPluginAsync } from "fastify";
// app
import { makeCryptoService } from "../services/crypto";

export const cryptoPlugin: FastifyPluginAsync<{ serverSecret: string }> = fp(
  async (server, { serverSecret }) => {
    const cryptoServiceKey = "cryptoService";
    const cryptoService = makeCryptoService({
      compare: (a, b) => a === b,
      hash: (str, salt) =>
        createHash("sha512")
          .update(`${salt}.${str}.${serverSecret}`)
          .digest("hex"),
    });
    server.decorate(cryptoServiceKey, {
      getter: () => cryptoService,
    });
    server.decorateRequest(cryptoServiceKey, {
      getter: () => cryptoService,
    });
  }
);