SPB Git

Repository Public

util.ts 3.2 KB 81 lines typescript

1import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";23export const now = (): number => Date.now();4export const sha256 = (value: string | Uint8Array): string => createHash("sha256").update(value).digest("hex");5export const hmac = (secret: string, value: string): string => createHmac("sha256", secret).update(value).digest("hex");6export const randomId = (bytes = 16): string => randomBytes(bytes).toString("base64url");7export const utcDay = (ms = Date.now()): string => new Date(ms).toISOString().slice(0, 10);89export function safeEqual(a: string, b: string): boolean {10  const x = Buffer.from(a), y = Buffer.from(b);11  return x.length === y.length && timingSafeEqual(x, y);12}1314export class HttpError extends Error {15  status: number;16  code: string;17  extra?: Record<string, unknown>;18  constructor(status: number, code: string, message: string, extra?: Record<string, unknown>) {19    super(message);20    this.status = status;21    this.code = code;22    this.extra = extra;23  }24}2526/** Sliding-window rate limiter kept in memory (per process). Keys are already hashed by callers. */27export class RateLimiter {28  private hits = new Map<string, number[]>();29  constructor() {30    setInterval(() => this.sweep(), 60_000).unref();31  }32  /** Returns seconds to wait when over the limit, otherwise 0 (and records the hit). */33  check(key: string, limit: number, windowMs: number): number {34    const t = Date.now();35    const list = (this.hits.get(key) ?? []).filter((x) => t - x < windowMs);36    if (list.length >= limit) {37      this.hits.set(key, list);38      return Math.max(1, Math.ceil((windowMs - (t - list[0])) / 1000));39    }40    list.push(t);41    this.hits.set(key, list);42    return 0;43  }44  private sweep(): void {45    const t = Date.now();46    for (const [key, list] of this.hits) {47      const kept = list.filter((x) => t - x < 3_600_000);48      if (kept.length) this.hits.set(key, kept); else this.hits.delete(key);49    }50  }51}5253/** Bounded in-memory operational log. Messages are written by the code only: never queries, URLs or tokens. */54export class OpsLog {55  private entries: { at: number; level: string; area: string; message: string }[] = [];56  add(level: "info" | "warn" | "error", area: string, message: string): void {57    this.entries.push({ at: Date.now(), level, area, message: message.slice(0, 300) });58    if (this.entries.length > 400) this.entries.splice(0, this.entries.length - 400);59  }60  recent(limit = 100) {61    return this.entries.slice(-limit).reverse();62  }63  countSince(level: string, sinceMs: number): number {64    return this.entries.filter((e) => e.level === level && e.at >= sinceMs).length;65  }66}6768export async function fetchJSON(url: string, init: RequestInit & { timeoutMs?: number } = {}): Promise<{ status: number; body: any; headers: Headers }> {69  const controller = new AbortController();70  const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 12_000);71  try {72    const response = await fetch(url, { ...init, signal: controller.signal });73    const text = await response.text();74    let body: any = null;75    try { body = text ? JSON.parse(text) : null; } catch { body = null; }76    return { status: response.status, body, headers: response.headers };77  } finally {78    clearTimeout(timer);79  }80}81
Files main
Menu

Theme