SPB Git

Repository Public

keys.ts 9.1 KB 143 lines typescript

1// Clés d'API (/api/v1) : jeton spm_<prefix>_<secret>, seul le SHA-256 du secret est en base ; jetons d'exploration spx_… (10 min).2import crypto from "node:crypto"3import type { FastifyRequest } from "fastify"4import { sql } from "./db.js"5import { bearerOf, requireUser, type Auth } from "./session.js"6import { bad, sha256 } from "./util.js"78export const SCOPES = [9  "mail.send", "mail.read", "mail.search", "mail.modify", "mail.delete", "mail.drafts", "mail.attachments.read", "mail.attachments.write",10  "mail.addresses.read", "mail.addresses.manage", "mail.aliases.manage", "mail.webhooks.manage", "mail.admin",11] as const12export type Scope = (typeof SCOPES)[number]1314export type KeyPrincipal = {15  type: "key"; keyId: string; name: string; scopes: Set<string>; addressIds: string[]; allAddresses: boolean; ratePerMinute: number16  dailySendLimit: number; externalPolicy: "allow" | "approval" | "deny"; allowedDomains: string[]; explorer: boolean; createdBy: string | null17}18export type UserPrincipal = { type: "user"; userId: string; role: "admin" | "member"; sessionId: string; auth: Auth }19export type Principal = KeyPrincipal | UserPrincipal20export const principalId = (p: Principal) => (p.type === "key" ? `key:${p.keyId}` : `user:${p.userId}`)2122export type KeyRow = {23  id: string; name: string; description: string; prefix: string; secret_hash: Buffer; scopes: string[]; address_ids: string[]; all_addresses: boolean24  rate_per_minute: number; daily_send_limit: number; external_send_policy: "allow" | "approval" | "deny"; allowed_recipient_domains: string[]25  expires_at: Date | null; revoked_at: Date | null; last_used_at: Date | null; created_by: string | null; rotated_from: string | null; created_at: Date; updated_at: Date26}2728const TOKEN_RE = /^spm_([a-z0-9]{10})_([A-Za-z0-9_-]{43})$/29export const looksLikeApiToken = (s: string | undefined) => !!s && /^sp[mx]_/.test(s)30export function parseToken(token: string): { prefix: string; secret: string } | null {31  const m = TOKEN_RE.exec(token)32  return m ? { prefix: m[1], secret: m[2] } : null33}34/** Secret de 256 bits ; le jeton complet n'existe que dans la valeur rendue ici, une seule fois. */35export function newKeyMaterial() {36  const prefix = crypto.randomBytes(5).toString("hex")37  const secret = crypto.randomBytes(32).toString("base64url")38  return { prefix, hash: sha256(secret), token: `spm_${prefix}_${secret}` }39}40const constEq = (a: Buffer, b: Buffer) => a.length === b.length && crypto.timingSafeEqual(a, b)4142export function presentKey(k: KeyRow) {43  const now = Date.now()44  return {45    id: k.id, name: k.name, description: k.description, prefix: `spm_${k.prefix}`, scopes: k.scopes, address_ids: k.address_ids, all_addresses: k.all_addresses,46    rate_per_minute: k.rate_per_minute, daily_send_limit: k.daily_send_limit, external_send_policy: k.external_send_policy,47    allowed_recipient_domains: k.allowed_recipient_domains, expires_at: k.expires_at ? new Date(k.expires_at).toISOString() : null,48    revoked_at: k.revoked_at ? new Date(k.revoked_at).toISOString() : null, last_used_at: k.last_used_at ? new Date(k.last_used_at).toISOString() : null,49    created_by: k.created_by, rotated_from: k.rotated_from, created_at: new Date(k.created_at).toISOString(),50    state: k.revoked_at && new Date(k.revoked_at).getTime() <= now ? "revoked" : k.expires_at && new Date(k.expires_at).getTime() <= now ? "expired" : "active",51  }52}5354export type KeyInput = {55  name: string; description?: string; scopes: string[]; address_ids?: string[]; all_addresses?: boolean; rate_per_minute?: number; daily_send_limit?: number56  external_send_policy?: "allow" | "approval" | "deny"; allowed_recipient_domains?: string[]; expires_at?: string | null57}58export async function validateKeyInput(i: Partial<KeyInput>) {59  if (i.scopes) for (const s of i.scopes) if (!(SCOPES as readonly string[]).includes(s)) throw bad("invalid_scope", 400, `Unknown scope ${s}`)60  if (i.all_addresses && i.scopes && !i.scopes.includes("mail.admin")) throw bad("all_addresses_requires_admin", 400, "all_addresses is only available to keys holding the mail.admin scope")61  if (i.address_ids?.length) {62    const found = await sql`select id from addresses where id = any(${i.address_ids}::uuid[])`63    if (found.length !== new Set(i.address_ids).size) throw bad("unknown_address", 400, "address_ids contains an unknown address")64  }65}66export async function createKey(i: KeyInput, createdBy: string | null, rotatedFrom: string | null = null): Promise<{ row: KeyRow; token: string }> {67  await validateKeyInput(i)68  const m = newKeyMaterial()69  const [row] = await sql`insert into api_keys (name, description, prefix, secret_hash, scopes, address_ids, all_addresses, rate_per_minute, daily_send_limit,70      external_send_policy, allowed_recipient_domains, expires_at, created_by, rotated_from)71    values (${i.name}, ${i.description ?? ""}, ${m.prefix}, ${m.hash}, ${[...new Set(i.scopes)]}, ${[...new Set(i.address_ids ?? [])]}::uuid[], ${!!i.all_addresses},72      ${i.rate_per_minute ?? 60}, ${i.daily_send_limit ?? 200}, ${i.external_send_policy ?? "approval"}, ${(i.allowed_recipient_domains ?? []).map((d) => d.toLowerCase())},73      ${i.expires_at ? new Date(i.expires_at) : null}, ${createdBy}, ${rotatedFrom}) returning *`74  return { row: row as KeyRow, token: m.token }75}7677function toPrincipal(k: KeyRow, explorer: boolean): KeyPrincipal {78  return {79    type: "key", keyId: k.id, name: k.name, scopes: new Set(k.scopes), addressIds: k.address_ids, allAddresses: k.all_addresses && k.scopes.includes("mail.admin"),80    ratePerMinute: k.rate_per_minute, dailySendLimit: k.daily_send_limit, externalPolicy: k.external_send_policy, allowedDomains: k.allowed_recipient_domains,81    explorer, createdBy: k.created_by,82  }83}84function assertUsable(k: KeyRow) {85  if (k.revoked_at && new Date(k.revoked_at).getTime() <= Date.now()) throw bad("key_revoked", 401, "This API key has been revoked")86  if (k.expires_at && new Date(k.expires_at).getTime() <= Date.now()) throw bad("key_expired", 401, "This API key has expired")87}8889/** Vérifie un jeton à CHAQUE requête (aucun cache) : une clé révoquée ou expirée échoue immédiatement. */90export async function authenticateToken(token: string): Promise<KeyPrincipal> {91  if (token.startsWith("spx_")) {92    const [t] = await sql`select key_id from explorer_tokens where token_hash = ${sha256(token)} and expires_at > now()`93    if (!t) throw bad("invalid_api_key", 401, "Invalid or expired explorer token")94    const [k] = await sql`select * from api_keys where id = ${t.key_id}`95    if (!k) throw bad("invalid_api_key", 401)96    assertUsable(k as KeyRow)97    return toPrincipal(k as KeyRow, true)98  }99  const parsed = parseToken(token)100  if (!parsed) throw bad("invalid_api_key", 401, "Malformed API key")101  const [k] = await sql`select * from api_keys where prefix = ${parsed.prefix}`102  // comparaison en temps constant, y compris quand le préfixe est inconnu103  const ok = constEq(sha256(parsed.secret), k ? Buffer.from(k.secret_hash) : crypto.randomBytes(32))104  if (!k || !ok) throw bad("invalid_api_key", 401, "Invalid API key")105  assertUsable(k as KeyRow)106  if (!k.last_used_at || Date.now() - new Date(k.last_used_at).getTime() > 60_000) await sql`update api_keys set last_used_at = now() where id = ${k.id}`107  return toPrincipal(k as KeyRow, false)108}109110export async function mintExplorerToken(keyId: string, userId: string): Promise<{ token: string; expires_at: string }> {111  const token = `spx_${crypto.randomBytes(32).toString("base64url")}`112  const expires = new Date(Date.now() + 10 * 60_000)113  await sql`insert into explorer_tokens (token_hash, key_id, created_by, expires_at) values (${sha256(token)}, ${keyId}, ${userId}, ${expires})`114  return { token, expires_at: expires.toISOString() }115}116117/** Appelant d'une route /api/v1 : clé d'API (porteur spm_/spx_) ou session web/native du propriétaire. */118export async function principalOf(req: FastifyRequest): Promise<Principal> {119  const bearer = bearerOf(req)120  if (looksLikeApiToken(bearer)) return authenticateToken(bearer!)121  const a = await requireUser(req)122  return { type: "user", userId: a.userId, role: a.role, sessionId: a.sessionId, auth: a }123}124125export function hasScope(p: Principal, scope: Scope): boolean {126  if (p.type === "user") return scope === "mail.admin" ? p.role === "admin" : true127  return p.scopes.has(scope) || p.scopes.has("mail.admin")128}129export function requireScope(p: Principal, ...anyOf: Scope[]) {130  if (!anyOf.some((s) => hasScope(p, s))) throw bad("insufficient_scope", 403, `This operation requires the scope ${anyOf.join(" or ")}`, { required: anyOf })131}132133// Limite de débit par clé : fenêtre fixe d'une minute, en mémoire (processus unique).134const windows = new Map<string, { n: number; reset: number }>()135export function keyRate(p: KeyPrincipal): { limit: number; remaining: number; reset: number; exceeded: boolean } {136  const now = Date.now()137  let w = windows.get(p.keyId)138  if (!w || w.reset <= now) { w = { n: 0, reset: now + 60_000 }; windows.set(p.keyId, w) }139  w.n++140  return { limit: p.ratePerMinute, remaining: Math.max(0, p.ratePerMinute - w.n), reset: Math.ceil(w.reset / 1000), exceeded: w.n > p.ratePerMinute }141}142setInterval(() => { const now = Date.now(); for (const [k, w] of windows) if (w.reset < now) windows.delete(k) }, 60_000).unref()143
Files main
Menu

Theme