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

+3
View File
@@ -13,3 +13,6 @@ verify_jwt = false
[functions.ratings]
verify_jwt = false
[functions.admin]
verify_jwt = false
+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' })
}
})
@@ -0,0 +1,219 @@
-- Console d'administration séparée (30/11/2026). Voir docs/admin.md.
-- Tout vit dans le schéma « admin », qui n'est PAS exposé par l'API (PostgREST ne sert que public et graphql_public) :
-- ni l'app, ni un visiteur, ni un membre connecté ne peuvent l'appeler. Seule la fonction Edge « admin »
-- y accède, par une connexion directe à la base, après avoir vérifié le secret du VPS, le compte et son code (aal2).
-- Idempotent.
create schema if not exists admin;
revoke all on schema admin from public, anon, authenticated, service_role;
comment on schema admin is 'Console d''administration (docs/admin.md). Non exposé par l''API : seule la fonction Edge « admin » y accède, par connexion directe.';
-- ─── Qui est admin ───
create table if not exists admin.admins (
user_id uuid primary key references auth.users (id) on delete cascade,
added_at timestamptz not null default now()
);
comment on table admin.admins is 'Comptes autorisés dans la console (double authentification obligatoire en plus).';
-- ─── Journal : on peut y ajouter, jamais modifier ni effacer ───
create table if not exists admin.journal (
id bigint generated always as identity primary key,
at timestamptz not null default now(),
admin_id uuid,
action text not null check (char_length(action) <= 40),
target_user uuid,
target text check (char_length(target) <= 200),
details jsonb not null default '{}'::jsonb
);
create index if not exists journal_at_idx on admin.journal (at desc);
comment on table admin.journal is 'Journal de la console : connexions et actions. Ajout seulement (modification et suppression refusées).';
create or replace function admin.journal_locked()
returns trigger language plpgsql set search_path = '' as $$
begin
raise exception 'journal en ajout seulement';
end;
$$;
drop trigger if exists journal_locked on admin.journal;
create trigger journal_locked before update or delete on admin.journal
for each row execute function admin.journal_locked();
drop trigger if exists journal_no_truncate on admin.journal;
create trigger journal_no_truncate before truncate on admin.journal
for each statement execute function admin.journal_locked();
comment on function admin.journal_locked() is 'Trigger : refuse toute modification ou suppression du journal.';
create or replace function admin.log(p_admin uuid, p_action text, p_target_user uuid, p_target text, p_details jsonb)
returns void language sql set search_path = '' as $$
insert into admin.journal (admin_id, action, target_user, target, details)
values (p_admin, left(p_action, 40), p_target_user, left(p_target, 200), coalesce(p_details, '{}'::jsonb));
$$;
comment on function admin.log(uuid, text, uuid, text, jsonb) is 'Ajoute une ligne au journal.';
create or replace function admin.is_admin(p_user uuid)
returns boolean language sql stable set search_path = '' as $$
select exists (select 1 from admin.admins where user_id = p_user);
$$;
comment on function admin.is_admin(uuid) is 'Ce compte est-il dans la liste des admins ?';
-- Carte d'un membre (réutilisée par les listes)
create or replace function admin.card(p_user uuid)
returns jsonb language sql stable set search_path = '' as $$
select jsonb_build_object('id', p.id, 'username', p.username, 'display_name', p.display_name, 'avatar_url', p.avatar_url, 'suspended', p.suspended)
from public.profiles p where p.id = p_user;
$$;
comment on function admin.card(uuid) is 'Pseudo, nom, photo et état d''un membre.';
-- ─── Tableau de bord ───
create or replace function admin.overview()
returns jsonb language sql stable set search_path = '' as $$
select jsonb_build_object(
'members', (select count(*) from auth.users),
'members_week', (select count(*) from auth.users where created_at > now() - interval '7 days'),
'active_week', (select count(*) from auth.users where last_sign_in_at > now() - interval '7 days'),
'suspended', (select count(*) from public.profiles where suspended),
'private', (select count(*) from public.profiles where is_private),
'items', (select count(*) from public.items where not deleted),
'reviews', (select count(*) from public.items where not deleted and coalesce(data->>'notes', '') <> ''),
'comments', (select count(*) from public.review_comments),
'follows', (select count(*) from public.follows where status = 'accepted'),
'shared_lists', (select count(*) from public.shared_lists),
'latest', coalesce((
select jsonb_agg(admin.card(u.id) || jsonb_build_object('created_at', u.created_at) order by u.created_at desc)
from (select id, created_at from auth.users order by created_at desc limit 5) u
), '[]'::jsonb)
);
$$;
comment on function admin.overview() is 'Chiffres généraux et dernières inscriptions.';
-- ─── Membres ───
create or replace function admin.members(p_q text, p_offset integer)
returns jsonb language sql stable set search_path = '' as $$
select coalesce(jsonb_agg(m.row order by m.created_at desc), '[]'::jsonb) from (
select u.created_at, admin.card(u.id) || jsonb_build_object(
'email', u.email,
'created_at', u.created_at,
'last_sign_in_at', u.last_sign_in_at,
'items', (select count(*) from public.items i where i.user_id = u.id and not i.deleted),
'mfa', exists (select 1 from auth.mfa_factors f where f.user_id = u.id and f.status = 'verified'),
'is_admin', admin.is_admin(u.id)
) as row
from auth.users u join public.profiles p on p.id = u.id
where coalesce(p_q, '') = ''
or p.username ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%'
or p.display_name ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%'
or u.email ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%'
order by u.created_at desc
limit 50 offset greatest(coalesce(p_offset, 0), 0)
) m;
$$;
comment on function admin.members(text, integer) is 'Membres (recherche par pseudo, nom ou e-mail), 50 par page.';
create or replace function admin.set_suspended(p_admin uuid, p_user uuid, p_value boolean, p_reason text)
returns jsonb language plpgsql set search_path = '' as $$
begin
if p_user = p_admin then raise exception 'impossible sur son propre compte'; end if;
update public.profiles set suspended = p_value where id = p_user and suspended is distinct from p_value;
if not found then return jsonb_build_object('ok', false); end if;
perform admin.log(p_admin, case when p_value then 'suspendre' else 'réactiver' end, p_user,
(select username from public.profiles where id = p_user), jsonb_build_object('motif', left(p_reason, 500)));
return jsonb_build_object('ok', true);
end;
$$;
comment on function admin.set_suspended(uuid, uuid, boolean, text) is 'Suspendre ou réactiver un membre (inscrit au journal).';
-- ─── Avis ───
create or replace function admin.reviews(p_q text, p_offset integer)
returns jsonb language sql stable set search_path = '' as $$
select coalesce(jsonb_agg(r.row order by r.updated_at desc), '[]'::jsonb) from (
select i.updated_at, jsonb_build_object(
'user', admin.card(i.user_id),
'item_id', i.id,
'title', i.data->>'title',
'rating', i.data->'rating',
'spoiler', coalesce(i.data->'spoiler' = 'true'::jsonb, false),
'notes', left(i.data->>'notes', 2000),
'updated_at', i.updated_at,
'comments', (select count(*) from public.review_comments c where c.author_id = i.user_id and c.item_id = i.id)
) as row
from public.items i join public.profiles p on p.id = i.user_id
where not i.deleted and coalesce(i.data->>'notes', '') <> ''
and (coalesce(p_q, '') = '' or p.username ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%'
or i.data->>'title' ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%')
order by i.updated_at desc
limit 30 offset greatest(coalesce(p_offset, 0), 0)
) r;
$$;
comment on function admin.reviews(text, integer) is 'Avis (recherche par pseudo ou titre), les plus récents d''abord, 30 par page.';
create or replace function admin.clear_review(p_admin uuid, p_user uuid, p_item text, p_reason text)
returns jsonb language plpgsql set search_path = '' as $$
declare
now_iso text := to_char(now() at time zone 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"');
v_title text;
v_notes text;
begin
select data->>'title', data->>'notes' into v_title, v_notes from public.items
where user_id = p_user and id = p_item and not deleted and coalesce(data->>'notes', '') <> '';
if not found then return jsonb_build_object('ok', false); end if;
-- Date de modification avancée : l'appareil du membre reçoit la fiche sans l'avis à sa prochaine synchro
update public.items
set data = jsonb_set(data - 'notes', '{updatedAt}', to_jsonb(now_iso)), updated_at = now()
where user_id = p_user and id = p_item;
perform admin.log(p_admin, 'retirer un avis', p_user, v_title,
jsonb_build_object('motif', left(p_reason, 500), 'avis', left(v_notes, 1000)));
return jsonb_build_object('ok', true);
end;
$$;
comment on function admin.clear_review(uuid, uuid, text, text) is 'Retirer un avis (le texte retiré est gardé dans le journal).';
-- ─── Commentaires ───
create or replace function admin.comments(p_offset integer)
returns jsonb language sql stable set search_path = '' as $$
select coalesce(jsonb_agg(c.row order by c.created_at desc), '[]'::jsonb) from (
select rc.created_at, jsonb_build_object(
'id', rc.id, 'body', rc.body, 'created_at', rc.created_at,
'user', admin.card(rc.user_id), 'author', admin.card(rc.author_id),
'title', (select i.data->>'title' from public.items i where i.user_id = rc.author_id and i.id = rc.item_id)
) as row
from public.review_comments rc
order by rc.created_at desc
limit 30 offset greatest(coalesce(p_offset, 0), 0)
) c;
$$;
comment on function admin.comments(integer) is 'Derniers commentaires sur les avis, 30 par page.';
create or replace function admin.delete_comment(p_admin uuid, p_id bigint, p_reason text)
returns jsonb language plpgsql set search_path = '' as $$
declare r public.review_comments;
begin
delete from public.review_comments where id = p_id returning * into r;
if r.id is null then return jsonb_build_object('ok', false); end if;
perform admin.log(p_admin, 'supprimer un commentaire', r.user_id, (select username from public.profiles where id = r.user_id),
jsonb_build_object('motif', left(p_reason, 500), 'commentaire', left(r.body, 1000)));
return jsonb_build_object('ok', true);
end;
$$;
comment on function admin.delete_comment(uuid, bigint, text) is 'Supprimer un commentaire (le texte est gardé dans le journal).';
-- ─── Journal ───
create or replace function admin.journal_list(p_offset integer)
returns jsonb language sql stable set search_path = '' as $$
select coalesce(jsonb_agg(j.row order by j.id desc), '[]'::jsonb) from (
select j.id, jsonb_build_object('id', j.id, 'at', j.at, 'action', j.action, 'target', j.target, 'details', j.details,
'admin', (select username from public.profiles where id = j.admin_id)) as row
from admin.journal j order by j.id desc
limit 50 offset greatest(coalesce(p_offset, 0), 0)
) j;
$$;
comment on function admin.journal_list(integer) is 'Journal de la console, le plus récent d''abord, 50 par page.';
-- Personne d'autre que le propriétaire (postgres, utilisé par la fonction Edge) n'y touche
revoke all on all tables in schema admin from public, anon, authenticated, service_role;
revoke all on all functions in schema admin from public, anon, authenticated, service_role;
alter default privileges in schema admin revoke all on tables from public, anon, authenticated, service_role;
alter default privileges in schema admin revoke all on functions from public, anon, authenticated, service_role;
-- Premier admin : le compte de Romain (rx0m_dct)
insert into admin.admins (user_id)
select id from public.profiles where username = 'rx0m_dct'
on conflict do nothing;