SPB Git

Repository Public

service.ts 9.2 KB 144 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : backend/src/verify/service.ts9 * Module           : verify10 * 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 { randomInt } from "node:crypto"43import { config } from "../config.ts"44import { sql } from "../db.ts"45import { createOutbound, type AppCtx } from "../messages/service.ts"46import { hmacHex } from "../security/crypto.ts"47import { normalizeRecipient } from "../security/phone.ts"48import { ApiError, iso, newId, notFound, safeEqual } from "../util.ts"4950/**51 * Vérification d'un numéro par code à usage unique.52 * Règles : code aléatoire (CSPRNG), jamais stocké ni renvoyé par l'API (empreinte HMAC seulement), durée courte, 5 essais,53 * usage unique, un seul code valide à la fois par numéro, débit limité par numéro. Le SMS passe par les mêmes garde-fous que tout envoi54 * (arrêt d'urgence, liste autorisée, désinscription, quotas) et son texte est masqué puis effacé.55 */56const MAX_PER_HOUR = 5, MIN_INTERVAL_S = 30, SMS_TTL_S = 18057const hash = (id: string, code: string) => hmacHex(config.dataKey.toString("base64"), `verification:${id}:${code}`)58const TEXT = {59  fr: (b: string, c: string, m: number) => `${b} : votre code de vérification est ${c}. Il expire dans ${m} min. Ne le partagez avec personne.`,60  en: (b: string, c: string, m: number) => `${b}: your verification code is ${c}. It expires in ${m} min. Do not share it with anyone.`,61}62export interface StartInput { to: string; locale?: "fr" | "en" | null; brand?: string | null; ttl_seconds?: number | null; code_length?: number | null; sim_id?: string | null; from?: string | null }6364export const publicVerification = (v: any, messageStatus?: string | null) => ({65  id: v.id, to: v.to_number, status: v.status, attempts: v.attempts, attempts_remaining: Math.max(v.max_attempts - v.attempts, 0),66  created_at: iso(v.created_at), expires_at: iso(v.expires_at), approved_at: iso(v.approved_at), message_id: v.message_id,67  ...(messageStatus !== undefined ? { message_status: messageStatus ? messageStatus.toLowerCase() : null } : {}),68})6970export async function startVerification(input: StartInput, app: AppCtx, apiKeyId: string, idempotencyKey: string | null = null): Promise<{ verification: ReturnType<typeof publicVerification>; replayed: boolean }> {71  const to = normalizeRecipient(input.to)72  if (idempotencyKey != null) {73    if (!/^[\x21-\x7e]{1,128}$/.test(idempotencyKey)) throw new ApiError(400, "invalid_idempotency_key", "Idempotency-Key : 1 à 128 caractères ASCII imprimables")74    // Rejeu : même vérification, aucun second code. Vérifié AVANT les limites par numéro, pour qu'un réessai réseau ne soit pas refusé.75    const [prev] = await sql`select v.*, m.status as message_status from verifications v left join messages m on m.id = v.message_id where v.application_id = ${app.id} and v.idempotency_key = ${idempotencyKey}`76    if (prev) {77      if (prev.to_number !== to) throw new ApiError(409, "idempotency_conflict", "cette Idempotency-Key a déjà servi pour un autre numéro")78      return { verification: publicVerification(prev, prev.message_status), replayed: true }79    }80  }81  const ttl = Math.min(Math.max(Number(input.ttl_seconds ?? 600), 120), 900)82  const length = Math.min(Math.max(Number(input.code_length ?? 6), 6), 8)83  const brand = String(input.brand ?? app.name).replace(/[^\p{L}\p{N} .\-']/gu, "").trim().slice(0, 30) || "MacLustr"8485  // Limites par numéro (en base : elles survivent à un redémarrage et valent pour toutes les clés de l'application).86  const [r] = await sql`select count(*)::int as n, max(created_at) as last, min(created_at) as first from verifications87                        where application_id = ${app.id} and to_number = ${to} and created_at > now() - interval '1 hour'`88  if (r.last && Date.now() - new Date(r.last).getTime() < MIN_INTERVAL_S * 1000)89    throw new ApiError(429, "verification_too_soon", `un code vient d'être envoyé à ce numéro : attendre ${MIN_INTERVAL_S} s avant d'en demander un autre`, undefined, Math.ceil(MIN_INTERVAL_S - (Date.now() - new Date(r.last).getTime()) / 1000))90  if (r.n >= MAX_PER_HOUR)91    throw new ApiError(429, "verification_rate_limited", `trop de codes demandés pour ce numéro (${MAX_PER_HOUR} par heure)`, undefined, Math.max(1, Math.ceil((new Date(r.first).getTime() + 3600_000 - Date.now()) / 1000)))9293  let code = ""94  for (let i = 0; i < length; i++) code += randomInt(10)95  const id = newId("ver")96  // L'envoi passe d'abord : s'il est refusé (liste autorisée, quota, arrêt d'urgence…), aucune vérification n'est créée.97  const { message } = await createOutbound({ to, text: TEXT[input.locale === "en" ? "en" : "fr"](brand, code, Math.round(ttl / 60)), sim_id: input.sim_id, from: input.from, ttl_seconds: SMS_TTL_S, delivery_report: true, sensitive: true }, { app, apiKeyId }, idempotencyKey ? `verification:${idempotencyKey}` : null)98  const v = await sql.begin(async tx => {99    // Un seul code valide à la fois par numéro : le précédent est annulé.100    await tx`update verifications set status = 'cancelled' where application_id = ${app.id} and to_number = ${to} and status = 'pending'`101    const [v] = await tx`insert into verifications(id, application_id, to_number, code_hash, message_id, expires_at, idempotency_key)102                         values (${id}, ${app.id}, ${to}, ${hash(id, code)}, ${message.id}, now() + make_interval(secs => ${ttl}), ${idempotencyKey}) returning *`103    return v104  })105  return { verification: publicVerification(v, message.status), replayed: false }106}107108async function purgeText(tx: any, messageId: string | null) {109  if (messageId) await tx`update messages set text_enc = null where id = ${messageId} and status not in ('HELD','QUEUED','DISPATCHED','ACCEPTED','SUBMITTING')`110}111112export async function checkVerification(id: string, code: string, appId: string) {113  return sql.begin(async tx => {114    const [v] = await tx`select * from verifications where id = ${id} and application_id = ${appId} for update`115    if (!v) throw notFound("vérification")116    if (v.status === "pending" && new Date(v.expires_at) < new Date()) {117      const [e] = await tx`update verifications set status = 'expired' where id = ${id} returning *`118      await purgeText(tx, v.message_id)119      return { ...publicVerification(e), valid: false }120    }121    if (v.status !== "pending") return { ...publicVerification(v), valid: false }       // déjà approuvée, échouée, expirée ou annulée : usage unique122    const ok = safeEqual(hash(id, String(code).replace(/\D/g, "")), v.code_hash)123    const attempts = v.attempts + 1124    const status = ok ? "approved" : attempts >= v.max_attempts ? "failed" : "pending"125    const [n] = await tx`update verifications set attempts = ${attempts}, status = ${status}, approved_at = ${ok ? tx`now()` : null} where id = ${id} returning *`126    if (status !== "pending") await purgeText(tx, v.message_id)127    return { ...publicVerification(n), valid: ok }128  })129}130131export async function getVerification(id: string, appId: string) {132  const [v] = await sql`select v.*, m.status as message_status from verifications v left join messages m on m.id = v.message_id where v.id = ${id} and v.application_id = ${appId}`133  if (!v) throw notFound("vérification")134  const expired = v.status === "pending" && new Date(v.expires_at) < new Date()135  return publicVerification({ ...v, status: expired ? "expired" : v.status }, v.message_status)136}137138/** Balayage : expire les vérifications échues et efface le texte des SMS sensibles dont l'envoi est terminé depuis 15 minutes. */139export async function sweepVerifications() {140  await sql`update verifications set status = 'expired' where status = 'pending' and expires_at < now()`141  await sql`update messages set text_enc = null where sensitive and text_enc is not null and created_at < now() - interval '15 minutes'142            and status not in ('HELD','QUEUED','DISPATCHED','ACCEPTED','SUBMITTING')`143}144
Files main
Menu

Theme