Repository Public
1import crypto from "node:crypto"2import type { FastifyReply, FastifyRequest } from "fastify"3import { z } from "zod"4import { sql } from "./db.js"56export const b64 = (b: Uint8Array | Buffer) => Buffer.from(b).toString("base64")7export const unb64 = (s: string) => Buffer.from(s, "base64")8export const b64url = (b: Uint8Array | Buffer) => Buffer.from(b).toString("base64url")9export const sha256 = (s: string | Buffer) => crypto.createHash("sha256").update(s).digest()10export const randomToken = (bytes = 32) => crypto.randomBytes(bytes).toString("base64url")11export const uuidBytes = (u: string) => Buffer.from(u.replace(/-/g, ""), "hex")1213export class HttpError extends Error {14 constructor(public status: number, public code: string, message?: string) {15 super(message ?? code)16 }17}18export const bad = (code: string, status = 400, message?: string) => new HttpError(status, code, message)1920export function parse<T extends z.ZodTypeAny>(schema: T, data: unknown): z.infer<T> {21 const r = schema.safeParse(data)22 if (!r.success) throw new HttpError(400, "invalid_request", r.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "))23 return r.data24}2526export const zB64 = (max = 8 * 1024 * 1024) => z.string().max(Math.ceil((max * 4) / 3) + 4).regex(/^[A-Za-z0-9+/]*={0,2}$/)27export const zUuid = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)2829export async function audit(req: FastifyRequest | null, actor: string | null, action: string, target?: string | null, meta: Record<string, unknown> = {}) {30 await sql`insert into audit_log (actor, action, target, meta, ip) values (${actor}, ${action}, ${target ?? null}, ${sql.json(meta as never)}, ${req?.ip ?? null})`31}3233// Fixed-window in-memory rate limiter (single process).34const buckets = new Map<string, { n: number; reset: number }>()35const scale = Number(process.env.SPM_RATE_SCALE ?? 1) // raised only by the test harness, which runs every actor from one address36export function rateLimit(key: string, limit: number, windowMs: number) {37 limit *= scale38 const now = Date.now()39 let b = buckets.get(key)40 if (!b || b.reset < now) {41 b = { n: 0, reset: now + windowMs }42 buckets.set(key, b)43 }44 b.n++45 if (b.n > limit) throw new HttpError(429, "rate_limited", "Too many requests")46}47setInterval(() => {48 const now = Date.now()49 for (const [k, b] of buckets) if (b.reset < now) buckets.delete(k)50}, 60_000).unref()5152export function limitReq(req: FastifyRequest, group: string, limit: number, windowMs = 60_000) {53 rateLimit(`${group}:${req.ip}`, limit, windowMs)54}5556export function sendError(reply: FastifyReply, e: unknown) {57 if (e instanceof HttpError) return reply.status(e.status).send({ error: e.code, message: e.message })58 throw e59}60