Console d'administration séparée, joignable seulement par Tailscale
deploy / deploy (push) Successful in 48s

- Site à part (admin/, build:admin → dist-admin/), jamais dans l'app publique : tableau de bord, membres
  (suspendre / réactiver), avis (retirer), commentaires (supprimer), journal. Motif obligatoire.
  Session en mémoire seulement, 1 h maximum, déconnexion après 15 min d'inactivité.
- Connexion : mot de passe + code de double authentification obligatoire (jeton aal2).
- Fonction Edge « admin » : secret X-Admin-Gate (ajouté par nginx sur le VPS, sinon 404), jeton aal2,
  liste admin.admins ; accès à la base par connexion directe. Alertes e-mail si SMTP_PASSWORD est configuré.
- Schéma « admin » (20261130150000, appliqué) non exposé par l'API : admins, journal en ajout seulement
  (modification, suppression et vidage refusés), fonctions de la console.
- nginx : admin.conf sur 127.0.0.1:8081 (CSP stricte, sans cache, noindex), relais vers la fonction avec le
  secret lu dans /etc/nginx/bobinoo-admin-gate.conf (hors dépôt). Publié par « tailscale serve ».
- Déploiement : build de la console et copie dans chaque release. Guide : docs/admin.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-11-30 20:26:58 +00:00
1 parent 0daee3eddf
commit 361ea66a32
21 files changed
+1372 -8

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
// Console d'administration (docs/admin.md) : seule porte d'entrée vers le schéma « admin » de la base.
//
// Une requête n'est traitée que si les trois verrous passent, dans cet ordre :
// 1. le secret du VPS (en-tête X-Admin-Gate, ajouté par nginx sur le serveur de la console, joignable
// seulement par le VPN Tailscale). Sans lui : 404, comme si la fonction n'existait pas ;
// 2. un compte connecté AVEC son code de double authentification (jeton « aal2 ») ;
// 3. ce compte est dans admin.admins.
// Chaque connexion, refus et action est inscrit dans admin.journal (ajout seulement). Les actions
// sensibles envoient en plus un e-mail d'alerte à contact@bobinoo.org (si SMTP_PASSWORD est configuré).
import postgres from 'npm:postgres@3.4.5'
const GATE = Deno.env.get('ADMIN_GATE_SECRET') ?? ''
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? ''
const ANON_KEY = Deno.env.get('SUPABASE_ANON_KEY') ?? ''
const DB_URL = Deno.env.get('SUPABASE_DB_URL') ?? ''
const SMTP_USER = Deno.env.get('SMTP_USER') ?? 'contact@bobinoo.org'
const SMTP_PASSWORD = Deno.env.get('SMTP_PASSWORD') ?? ''
const ALERT_TO = Deno.env.get('ADMIN_ALERT_TO') ?? 'contact@bobinoo.org'
const sql = DB_URL ? postgres(DB_URL, { prepare: false, max: 2, idle_timeout: 20, connect_timeout: 10 }) : null
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const ITEM_ID = /^[A-Za-z0-9_-]{1,64}$/
/** Laisse une tâche finir après la réponse (e-mail d'alerte). */
const inBackground = (p: Promise<unknown>) => (globalThis as { EdgeRuntime?: { waitUntil?: (p: Promise<unknown>) => void } }).EdgeRuntime?.waitUntil?.(p)
const enc = new TextEncoder()
/** Comparaison en temps constant (empreintes SHA-256 : même longueur quelle que soit l'entrée). */
async function sameSecret(a: string, b: string): Promise<boolean> {
const [x, y] = await Promise.all([crypto.subtle.digest('SHA-256', enc.encode(a)), crypto.subtle.digest('SHA-256', enc.encode(b))])
const u = new Uint8Array(x)
const v = new Uint8Array(y)
let diff = 0
for (let i = 0; i < u.length; i++) diff |= u[i] ^ v[i]
return diff === 0
}
const notFound = () => new Response('Not found', { status: 404 })
const json = (status: number, body: unknown) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' } })
function tokenClaims(token: string): { aal?: string } {
try {
const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
return JSON.parse(atob(part.padEnd(part.length + ((4 - (part.length % 4)) % 4), '='))) as { aal?: string }
} catch {
return {}
}
}
/** Compte du jeton, vérifié par Supabase Auth, avec son niveau (aal2 = code de double authentification validé). */
async function verifiedUser(req: Request): Promise<{ id: string; email: string; aal2: boolean; totp: boolean } | null> {
const auth = req.headers.get('Authorization') ?? ''
const token = auth.startsWith('Bearer ') ? auth.slice(7).trim() : ''
if (!token || token.length > 4096) return null
const res = await fetch(`${SUPABASE_URL}/auth/v1/user`, { headers: { apikey: ANON_KEY, Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) })
if (!res.ok) {
await res.body?.cancel()
return null
}
const u = (await res.json()) as { id?: string; email?: string; factors?: { status?: string; factor_type?: string }[] }
if (typeof u.id !== 'string' || !UUID.test(u.id)) return null
const totp = Array.isArray(u.factors) && u.factors.some((f) => f?.status === 'verified' && f?.factor_type === 'totp')
return { id: u.id, email: u.email ?? '', aal2: tokenClaims(token).aal === 'aal2', totp }
}
// Limite par compte : 120 requêtes par minute (par instance)
const hits = new Map<string, number[]>()
function limited(key: string): boolean {
const now = Date.now()
const list = (hits.get(key) ?? []).filter((t) => now - t < 60_000)
list.push(now)
hits.set(key, list)
if (hits.size > 1000) hits.clear()
return list.length > 120
}
async function log(adminId: string | null, action: string, targetUser: string | null, target: string | null, details: Record<string, unknown>) {
await sql!`select admin.log(${adminId}::uuid, ${action}::text, ${targetUser}::uuid, ${target}::text, ${JSON.stringify(details)}::jsonb)`
}
/** E-mail d'alerte (action sensible ou connexion). Sans mot de passe SMTP configuré : rien. */
function alert(subject: string, lines: string[]) {
if (!SMTP_PASSWORD) return
inBackground(
(async () => {
// Chargé seulement pour envoyer : un souci d'envoi ne peut pas bloquer la console
const { default: nodemailer } = await import('npm:nodemailer@6.9.16')
const transport = nodemailer.createTransport({ host: 'ssl0.ovh.net', port: 465, secure: true, auth: { user: SMTP_USER, pass: SMTP_PASSWORD } })
await transport.sendMail({
from: `Bobinoo (console) <${SMTP_USER}>`,
to: ALERT_TO,
subject: `[Console Bobinoo] ${subject}`,
text: [...lines, '', `Le ${new Date().toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })} (heure de Paris).`, "Si ce n'est pas toi : change ton mot de passe et retire ce compte de admin.admins dans Supabase."].join('\n'),
})
})().catch((e) => console.error('alerte e-mail non envoyée', (e as Error)?.message)),
)
}
const str = (v: unknown, max: number) => (typeof v === 'string' ? v.trim().slice(0, max) : '')
const int = (v: unknown) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 100_000 ? v : 0)
const reasonOf = (v: unknown) => {
const r = str(v, 500)
if (r.length < 3) throw new Error('motif requis (3 caractères minimum)')
return r
}
Deno.serve(async (req) => {
// 1. Secret du VPS : sans lui, la fonction n'existe pas
if (GATE.length < 32 || !sql) return notFound()
if (!(await sameSecret(req.headers.get('X-Admin-Gate') ?? '', GATE))) return notFound()
if (req.method !== 'POST') return notFound()
// 2. Compte + code de double authentification
const user = await verifiedUser(req).catch(() => null)
if (!user) return json(401, { error: 'session' })
if (limited(user.id)) return json(429, { error: 'trop de requêtes' })
if (!user.totp || !user.aal2) return json(403, { error: 'mfa' })
// 3. Liste des admins
const [{ ok: isAdmin }] = await sql`select admin.is_admin(${user.id}::uuid) as ok`
if (!isAdmin) {
await log(user.id, 'accès refusé', user.id, user.email, {})
alert('Accès refusé', [`Un compte qui n'est pas admin a tenté d'utiliser la console : ${user.email}.`])
return json(403, { error: 'interdit' })
}
const text = await req.text()
if (text.length > 10_000) return json(413, { error: 'trop long' })
let body: Record<string, unknown>
try {
body = JSON.parse(text) as Record<string, unknown>
} catch {
return json(400, { error: 'json' })
}
const action = str(body.action, 30)
try {
switch (action) {
case 'hello': {
const ua = str(req.headers.get('User-Agent'), 200)
await log(user.id, 'connexion', user.id, user.email, { appareil: ua })
alert('Connexion à la console', [`Connexion de ${user.email}.`, `Appareil : ${ua}`])
const [{ r }] = await sql`select admin.card(${user.id}::uuid) as r`
return json(200, r)
}
case 'overview': {
const [{ r }] = await sql`select admin.overview() as r`
return json(200, r)
}
case 'members': {
const [{ r }] = await sql`select admin.members(${str(body.q, 60)}::text, ${int(body.offset)}::int) as r`
return json(200, r)
}
case 'suspend': {
const target = str(body.user, 36)
if (!UUID.test(target) || typeof body.value !== 'boolean') return json(400, { error: 'paramètres' })
const reason = reasonOf(body.reason)
const [{ r }] = await sql`select admin.set_suspended(${user.id}::uuid, ${target}::uuid, ${body.value}::boolean, ${reason}::text) as r`
if (r?.ok) alert(body.value ? 'Compte suspendu' : 'Compte réactivé', [`Par ${user.email}.`, `Compte : ${target}`, `Motif : ${reason}`])
return json(200, r)
}
case 'reviews': {
const [{ r }] = await sql`select admin.reviews(${str(body.q, 60)}::text, ${int(body.offset)}::int) as r`
return json(200, r)
}
case 'clear_review': {
const target = str(body.user, 36)
const item = str(body.item, 64)
if (!UUID.test(target) || !ITEM_ID.test(item)) return json(400, { error: 'paramètres' })
const reason = reasonOf(body.reason)
const [{ r }] = await sql`select admin.clear_review(${user.id}::uuid, ${target}::uuid, ${item}::text, ${reason}::text) as r`
if (r?.ok) alert('Avis retiré', [`Par ${user.email}.`, `Compte : ${target}, fiche ${item}`, `Motif : ${reason}`])
return json(200, r)
}
case 'comments': {
const [{ r }] = await sql`select admin.comments(${int(body.offset)}::int) as r`
return json(200, r)
}
case 'delete_comment': {
const id = typeof body.id === 'number' && Number.isInteger(body.id) && body.id > 0 ? body.id : 0
if (!id) return json(400, { error: 'paramètres' })
const reason = reasonOf(body.reason)
const [{ r }] = await sql`select admin.delete_comment(${user.id}::uuid, ${id}::bigint, ${reason}::text) as r`
if (r?.ok) alert('Commentaire supprimé', [`Par ${user.email}.`, `Commentaire n° ${id}`, `Motif : ${reason}`])
return json(200, r)
}
case 'journal': {
const [{ r }] = await sql`select admin.journal_list(${int(body.offset)}::int) as r`
return json(200, r)
}
default:
return json(400, { error: 'action inconnue' })
}
} catch (e) {
const msg = (e as Error)?.message ?? 'erreur'
// Messages volontaires (motif manquant, action sur son propre compte) renvoyés tels quels, le reste masqué
if (/motif requis|impossible sur son propre compte/.test(msg)) return json(400, { error: msg.replace(/^.*?(motif requis.*|impossible sur son propre compte).*$/, '$1') })
console.error('admin', action, msg)
return json(500, { error: 'erreur serveur' })
}
})