SPB Git

Repository Public

apikeys.ts 5.2 KB 83 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr SMS Gateway8 * File             : backend/src/auth/apikeys.ts9 * Module           : auth10 * 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 type { FastifyRequest } from "fastify"43import { sql } from "../db.ts"44import type { AppCtx } from "../messages/service.ts"45import { enforce, enforceApp } from "../security/ratelimit.ts"46import { ApiError, iso, newId, randomToken, sha256hex } from "../util.ts"4748export const SCOPES = ["messages:send", "messages:read", "messages:cancel", "inbox:read", "devices:read", "numbers:read", "webhooks:manage", "usage:read", "queue:read", "verify:manage"] as const49export type Scope = (typeof SCOPES)[number]50export interface KeyCtx { keyId: string; scopes: string[]; app: AppCtx & { rate_per_minute: number } }51declare module "fastify" { interface FastifyRequest { key?: KeyCtx } }5253export async function createApiKey(applicationId: string, name: string, scopes: string[], expiresAt: Date | null = null, rotatedFrom: string | null = null) {54  const bad = scopes.filter(s => !SCOPES.includes(s as Scope))55  if (!scopes.length || bad.length) throw new ApiError(422, "invalid_scopes", `scopes acceptés : ${SCOPES.join(", ")}`)56  const secret = "mlsk_" + randomToken(32), id = newId("key")57  await sql`insert into api_keys(id, application_id, name, prefix, key_hash, scopes, expires_at, rotated_from)58            values (${id}, ${applicationId}, ${name}, ${secret.slice(0, 12)}, ${sha256hex(secret)}, ${[...new Set(scopes)]}, ${expiresAt}, ${rotatedFrom})`59  const [k] = await sql`select * from api_keys where id = ${id}`60  return { ...publicKey(k), key: secret } // la clé complète n'est montrée qu'une fois61}62export const publicKey = (k: any) => ({ id: k.id, application_id: k.application_id, name: k.name, prefix: k.prefix + "…", scopes: k.scopes, created_at: iso(k.created_at), last_used_at: iso(k.last_used_at), expires_at: iso(k.expires_at), revoked_at: iso(k.revoked_at) })6364const touched = new Map<string, number>()65/** Authentifie `Authorization: Bearer mlsk_…`, applique la limite de débit de l'application et vérifie le scope demandé. */66export async function requireKey(req: FastifyRequest, scope: Scope | Scope[]): Promise<KeyCtx> {67  const h = req.headers.authorization ?? ""68  const m = /^Bearer\s+(mlsk_[A-Za-z0-9_-]{20,80})$/.exec(h)69  if (!m) { enforce("badauth:" + req.ip, 30); throw new ApiError(401, "unauthenticated", "clé API manquante ou mal formée (Authorization: Bearer mlsk_…)") }70  const [r] = await sql`71    select k.id as key_id, k.scopes, k.expires_at, k.revoked_at, a.id, a.name, a.enabled, a.daily_quota, a.rate_per_minute, a.approval_required, a.require_consent, a.allowed_sim_ids72    from api_keys k join applications a on a.id = k.application_id where k.key_hash = ${sha256hex(m[1])}`73  if (!r || r.revoked_at || (r.expires_at && new Date(r.expires_at) < new Date())) { enforce("badauth:" + req.ip, 30); throw new ApiError(401, "invalid_api_key", "clé API invalide, expirée ou révoquée") }74  if (!r.enabled) throw new ApiError(403, "application_disabled", "cette application est désactivée")75  enforceApp("app:" + r.id, r.rate_per_minute)76  const wanted = Array.isArray(scope) ? scope : [scope]77  if (!wanted.some(w => r.scopes.includes(w))) throw new ApiError(403, "insufficient_scope", `cette clé n'a pas le scope ${wanted.join(" ou ")}`)78  if (Date.now() - (touched.get(r.key_id) ?? 0) > 60_000) { touched.set(r.key_id, Date.now()); void sql`update api_keys set last_used_at = now() where id = ${r.key_id}`.catch(() => {}) }79  const ctx: KeyCtx = { keyId: r.key_id, scopes: r.scopes, app: { id: r.id, name: r.name, enabled: r.enabled, daily_quota: r.daily_quota, rate_per_minute: r.rate_per_minute, approval_required: r.approval_required, require_consent: r.require_consent, allowed_sim_ids: r.allowed_sim_ids } }80  req.key = ctx81  return ctx82}83
Files main
Menu

Theme