Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/src/util.ts9 * Module : backend10 * Repository : https://git.spboucher.ai/maclustr-sms11 * Project Website : https://sms.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { createHash, randomBytes, timingSafeEqual } from "node:crypto"4344const B32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"45/** ULID : triable par date, 26 caractères. */46export function ulid(now = Date.now()): string {47 let t = now, time = ""48 for (let i = 0; i < 10; i++) { time = B32[t % 32] + time; t = Math.floor(t / 32) }49 const r = randomBytes(16)50 let rand = ""51 for (let i = 0; i < 16; i++) rand += B32[r[i] % 32]52 return time + rand53}54export const newId = (prefix: string) => `${prefix}_${ulid().toLowerCase()}`55export const sha256hex = (s: string | Buffer) => createHash("sha256").update(s).digest("hex")56export const randomToken = (bytes = 32) => randomBytes(bytes).toString("base64url")57export function safeEqual(a: string, b: string) {58 const x = Buffer.from(a), y = Buffer.from(b)59 return x.length === y.length && timingSafeEqual(x, y)60}61export const iso = (d: Date | string | null | undefined) => (d == null ? null : new Date(d).toISOString())6263/** Erreur d'API normalisée : { error: { code, message, details? } }. */64export class ApiError extends Error {65 constructor(public status: number, public code: string, message: string, public details?: unknown, public retryAfter?: number) { super(message) }66}67export const bad = (code: string, message: string, details?: unknown) => new ApiError(400, code, message, details)68export const notFound = (what = "ressource") => new ApiError(404, "not_found", `${what} introuvable`)69export const forbidden = (code: string, message: string) => new ApiError(403, code, message)70export const conflict = (code: string, message: string) => new ApiError(409, code, message)71export const unprocessable = (code: string, message: string, details?: unknown) => new ApiError(422, code, message, details)7273/** Pagination par curseur opaque (created_at, id). */74export function encodeCursor(createdAt: Date, id: string) { return Buffer.from(JSON.stringify([createdAt.toISOString(), id])).toString("base64url") }75export function decodeCursor(c: string | undefined): [string, string] | null {76 if (!c) return null77 try { const v = JSON.parse(Buffer.from(c, "base64url").toString()); if (Array.isArray(v) && typeof v[0] === "string" && typeof v[1] === "string") return [v[0], v[1]] } catch {}78 throw bad("invalid_cursor", "curseur de pagination invalide")79}80export const clampLimit = (v: unknown, def = 50, max = 200) => { const n = Number(v ?? def); return Number.isFinite(n) ? Math.min(Math.max(Math.trunc(n), 1), max) : def }81