import { randomUUID } from "node:crypto"; import { z } from "zod"; import { AppError, attachUser, branding, createMailer, currentUser, hashPassword, link, renderMail, requireAuth, type App, type Config, type Db, } from "../lib/index.js"; import { diskUsage } from "../storage.js"; const uuidParam = z .string() .regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide."); const createUserSchema = z.object({ email: z.string().trim().email().max(255), first_name: z.string().trim().min(1).max(50), last_name: z.string().trim().min(1).max(50), role_slug: z.enum(["admin", "user"]).default("user"), quota_bytes: z.number().int().positive().nullish(), max_file_bytes: z.number().int().positive().nullish(), password: z.string().min(8).max(1024).nullish(), }); const updateUserSchema = z.object({ first_name: z.string().trim().min(1).max(50).optional(), last_name: z.string().trim().min(1).max(50).optional(), role_slug: z.enum(["admin", "user"]).optional(), quota_bytes: z.number().int().positive().optional(), max_file_bytes: z.number().int().positive().optional(), is_active: z.boolean().optional(), }); const createLocationSchema = z.object({ name: z.string().trim().min(1).max(100), slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,99}$/, "Identifiant technique invalide."), mount_path: z.string().trim().min(1).max(255), quota_bytes: z.number().int().positive().nullish(), }); const updateLocationSchema = z.object({ name: z.string().trim().min(1).max(100).optional(), quota_bytes: z.number().int().positive().nullable().optional(), is_active: z.boolean().optional(), }); const parse = (schema: z.ZodType, body: unknown): T => { const result = schema.safeParse(body); if (!result.success) { const issue = result.error.issues[0]; throw AppError.badRequest( issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.", ); } return result.data; }; interface AdminUserRow { id: string; email: string; first_name: string; last_name: string; role_slug: string; quota_bytes: number; used_bytes: number; max_file_bytes: number; is_active: number; must_change_password: number; last_login_at: string | null; created_at: string; } const publicUser = (row: AdminUserRow) => ({ id: row.id, email: row.email, first_name: row.first_name, last_name: row.last_name, role_slug: row.role_slug, quota_bytes: row.quota_bytes, used_bytes: row.used_bytes, max_file_bytes: row.max_file_bytes, is_active: row.is_active === 1, must_change_password: row.must_change_password === 1, last_login_at: row.last_login_at, created_at: row.created_at, }); const SELECT_USER = ` SELECT u.id, u.email, u.first_name, u.last_name, r.slug AS role_slug, u.quota_bytes, u.used_bytes, u.max_file_bytes, u.is_active, u.must_change_password, u.last_login_at, u.created_at FROM users u JOIN roles r ON r.id = u.role_id`; const UNITS = ["o", "Ko", "Mo", "Go", "To", "Po"]; /** Taille lisible, pour les messages d'erreur destines a l'administrateur. */ const humanBytes = (bytes: number): string => { let value = bytes; let unit = 0; while (value >= 1024 && unit < UNITS.length - 1) { value /= 1024; unit += 1; } return `${value.toFixed(unit === 0 || value >= 10 ? 0 : 1)} ${UNITS[unit]}`; }; /** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */ const generatePasswordValue = (): string => { const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; const bytes = new Uint8Array(18); globalThis.crypto.getRandomValues(bytes); let out = ""; for (const byte of bytes) out += alphabet[byte % alphabet.length]; return out; }; export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { app.use("/api/cloud/admin/*", attachUser(db)); app.use("/api/cloud/admin", attachUser(db)); const mailer = createMailer(config); const brand = branding(config); const requireAdmin = (context: Parameters[0]): void => { if (currentUser(context).role_slug !== "admin") throw AppError.forbidden(); }; /** * Un quota ne peut depasser la capacite reelle du disque qui porte les * medias : au-dela, la limite est un chiffre mort que le support ne pourra * jamais honorer. Le controle est ignore si le support n'est pas lisible * (chemin absent dans le conteneur), pour ne pas bloquer la configuration. */ const assertQuotaFits = async (quota: number): Promise => { const disk = await diskUsage(config.MEDIA_DIR); if (disk !== null && quota > disk.total_bytes) { throw AppError.badRequest( `Le quota depasse la capacite du disque (${humanBytes(disk.total_bytes)}).`, ); } }; app.get("/api/cloud/admin/stats", requireAuth, async (context) => { requireAdmin(context); const [users] = await db.query<{ count: number }>( "SELECT COUNT(*) AS count FROM users WHERE deleted_at IS NULL", ); const [folders] = await db.query<{ count: number }>( "SELECT COUNT(*) AS count FROM folders WHERE deleted_at IS NULL", ); const [files] = await db.query<{ count: number; bytes: number }>( "SELECT COUNT(*) AS count, COALESCE(SUM(size_bytes), 0) AS bytes FROM files WHERE deleted_at IS NULL", ); const [trash] = await db.query<{ count: number }>( "SELECT COUNT(*) AS count FROM files WHERE deleted_at IS NOT NULL", ); const locations = await db.query<{ id: number; name: string; used_bytes: number; quota_bytes: number | null; }>( `SELECT id, name, used_bytes, quota_bytes FROM storage_locations WHERE deleted_at IS NULL ORDER BY id`, ); return context.json({ users: users?.count ?? 0, folders: folders?.count ?? 0, files: files?.count ?? 0, usedBytes: Number(files?.bytes ?? 0), trashFiles: trash?.count ?? 0, locations, disk: await diskUsage(config.MEDIA_DIR), }); }); app.get("/api/cloud/admin/users", requireAuth, async (context) => { requireAdmin(context); const query = (context.req.query("q") ?? "").trim(); const rows = query ? await db.query( `${SELECT_USER} WHERE u.deleted_at IS NULL AND (u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?) ORDER BY u.email LIMIT 500`, [`%${query}%`, `%${query}%`, `%${query}%`], ) : await db.query( `${SELECT_USER} WHERE u.deleted_at IS NULL ORDER BY u.email LIMIT 500`, ); return context.json({ users: rows.map(publicUser) }); }); app.post("/api/cloud/admin/users", requireAuth, async (context) => { requireAdmin(context); const data = parse(createUserSchema, await context.req.json().catch(() => null)); const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]); if (!role) throw AppError.badRequest("Role inconnu."); const existing = await db.one("SELECT id FROM users WHERE active_email = ?", [data.email]); if (existing) throw AppError.conflict("Ce compte existe deja."); const password = data.password ?? generatePasswordValue(); const hash = await hashPassword(password); const id = randomUUID(); await db.exec( `INSERT INTO users (id, email, first_name, last_name, password_hash, role_id, quota_bytes, max_file_bytes, must_change_password, password_changed_at) VALUES (?, ?, ?, ?, ?, ?, COALESCE(?, (SELECT CAST(setting_value AS UNSIGNED) FROM settings WHERE setting_key = 'default_quota_bytes'), 429496729600), COALESCE(?, 5368709120), 1, NULL)`, [id, data.email, data.first_name, data.last_name, hash, role.id, data.quota_bytes ?? null, data.max_file_bytes ?? null], ); const created = await db.required(`${SELECT_USER} WHERE u.id = ?`, [id]); const mail = renderMail(brand, { preview: "Votre acces CoHaiSe Cloud est pret.", heading: "Votre compte a ete cree", intro: `Un compte CoHaiSe Cloud vient d'etre ouvert pour ${data.first_name}. Connectez-vous avec les identifiants ci-dessous.`, credentials: { email: data.email, password }, cta: { label: "Se connecter", url: link(config, "/login") }, note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.", }); await mailer .send({ to: data.email, subject: "CoHaiSe Cloud — votre compte est pret", text: mail.text, html: mail.html, }) .catch(() => undefined); return context.json({ user: publicUser(created), password }, 201); }); app.patch("/api/cloud/admin/users/:id", requireAuth, async (context) => { const actor = currentUser(context); requireAdmin(context); const id = context.req.param("id") ?? ""; if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable."); const existing = await db.one(`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`, [id]); if (!existing) throw AppError.notFound("Compte introuvable."); const data = parse(updateUserSchema, await context.req.json().catch(() => null)); if (data.role_slug !== undefined && data.role_slug !== existing.role_slug) { const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]); if (!role) throw AppError.badRequest("Role inconnu."); if (id === actor.id) throw AppError.badRequest("Vous ne pouvez pas modifier votre propre role."); if (existing.role_slug === "admin") { const [count] = await db.query<{ count: number }>( `SELECT COUNT(*) AS count FROM users u JOIN roles r ON r.id = u.role_id WHERE r.slug = 'admin' AND u.is_active = 1 AND u.deleted_at IS NULL`, ); if ((count?.count ?? 0) <= 1) { throw AppError.badRequest("Impossible de retirer le dernier administrateur."); } } await db.exec("UPDATE users SET role_id = ? WHERE id = ?", [role.id, id]); } if (data.first_name !== undefined) { await db.exec("UPDATE users SET first_name = ? WHERE id = ?", [data.first_name, id]); } if (data.last_name !== undefined) { await db.exec("UPDATE users SET last_name = ? WHERE id = ?", [data.last_name, id]); } if (data.quota_bytes !== undefined) { if (data.quota_bytes < existing.used_bytes) { throw AppError.badRequest("Le quota ne peut pas etre inferieur a l'espace deja utilise."); } await db.exec("UPDATE users SET quota_bytes = ? WHERE id = ?", [data.quota_bytes, id]); } if (data.max_file_bytes !== undefined) { await db.exec("UPDATE users SET max_file_bytes = ? WHERE id = ?", [data.max_file_bytes, id]); } if (data.is_active !== undefined) { if (!data.is_active && id === actor.id) { throw AppError.badRequest("Vous ne pouvez pas desactiver votre propre compte."); } await db.exec("UPDATE users SET is_active = ? WHERE id = ?", [data.is_active ? 1 : 0, id]); if (!data.is_active) { await db.exec( "UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL", [id], ); } } const updated = await db.required(`${SELECT_USER} WHERE u.id = ?`, [id]); return context.json({ user: publicUser(updated) }); }); app.delete("/api/cloud/admin/users/:id", requireAuth, async (context) => { const actor = currentUser(context); requireAdmin(context); const id = context.req.param("id") ?? ""; if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable."); if (id === actor.id) throw AppError.badRequest("Vous ne pouvez pas supprimer votre propre compte."); const result = await db.exec( "UPDATE users SET deleted_at = UTC_TIMESTAMP(), is_active = 0 WHERE id = ? AND deleted_at IS NULL", [id], ); if (result.affectedRows === 0) throw AppError.notFound("Compte introuvable."); await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]); return context.json({ ok: true }); }); app.post("/api/cloud/admin/users/:id/reset-password", requireAuth, async (context) => { requireAdmin(context); const id = context.req.param("id") ?? ""; if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable."); const user = await db.one<{ email: string }>( "SELECT email FROM users WHERE id = ? AND deleted_at IS NULL", [id], ); if (!user) throw AppError.notFound("Compte introuvable."); const password = generatePasswordValue(); const hash = await hashPassword(password); await db.exec( "UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = NULL WHERE id = ?", [hash, id], ); await db.exec( "UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL", [id], ); // Le mot de passe est rendu une seule fois et envoye au compte. Un echec // d'envoi n'invalide pas la reinitialisation. const mail = renderMail(brand, { preview: "Un nouveau mot de passe a ete genere pour votre compte.", heading: "Mot de passe reinitialise", intro: "Un administrateur a reinitialise le mot de passe de votre compte CoHaiSe Cloud.", credentials: { email: user.email, password }, cta: { label: "Se connecter", url: link(config, "/login") }, note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.", }); await mailer .send({ to: user.email, subject: "CoHaiSe Cloud — mot de passe reinitialise", text: mail.text, html: mail.html, }) .catch(() => undefined); return context.json({ password }); }); app.get("/api/cloud/admin/storage-locations", requireAuth, async (context) => { requireAdmin(context); const rows = await db.query( `SELECT id, name, slug, mount_path, quota_bytes, used_bytes, is_active, created_at FROM storage_locations WHERE deleted_at IS NULL ORDER BY id`, ); return context.json({ locations: rows, disk: await diskUsage(config.MEDIA_DIR) }); }); app.post("/api/cloud/admin/storage-locations", requireAuth, async (context) => { requireAdmin(context); const data = parse(createLocationSchema, await context.req.json().catch(() => null)); if (data.quota_bytes !== undefined && data.quota_bytes !== null) { await assertQuotaFits(data.quota_bytes); } try { await db.exec( `INSERT INTO storage_locations (name, slug, mount_path, quota_bytes) VALUES (?, ?, ?, ?)`, [data.name, data.slug, data.mount_path, data.quota_bytes ?? null], ); } catch (error) { if ((error as { errno?: number }).errno === 1062) { throw AppError.conflict("Un emplacement porte deja ce nom ou ce chemin."); } throw error; } return context.json({ ok: true }, 201); }); app.patch("/api/cloud/admin/storage-locations/:id", requireAuth, async (context) => { requireAdmin(context); const id = Number(context.req.param("id")); if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Emplacement introuvable."); const data = parse(updateLocationSchema, await context.req.json().catch(() => null)); const row = await db.one<{ used_bytes: number }>( "SELECT used_bytes FROM storage_locations WHERE id = ? AND deleted_at IS NULL", [id], ); if (!row) throw AppError.notFound("Emplacement introuvable."); if (data.quota_bytes !== undefined && data.quota_bytes !== null && data.quota_bytes < row.used_bytes) { throw AppError.badRequest("Le quota est inferieur a l'espace deja utilise."); } if (data.quota_bytes !== undefined && data.quota_bytes !== null) { await assertQuotaFits(data.quota_bytes); } const fields: string[] = []; const values: unknown[] = []; if (data.name !== undefined) { fields.push("name = ?"); values.push(data.name); } if (data.quota_bytes !== undefined) { fields.push("quota_bytes = ?"); values.push(data.quota_bytes); } if (data.is_active !== undefined) { fields.push("is_active = ?"); values.push(data.is_active ? 1 : 0); } if (fields.length === 0) throw AppError.badRequest("Rien a modifier."); values.push(id); await db.exec(`UPDATE storage_locations SET ${fields.join(", ")} WHERE id = ?`, values); return context.json({ ok: true }); }); app.get("/api/cloud/admin/audit", requireAuth, async (context) => { requireAdmin(context); const limit = Math.min(500, Math.max(1, Number(context.req.query("limit")) || 100)); const offset = Math.max(0, Number(context.req.query("offset")) || 0); const action = context.req.query("action"); const rows = action ? await db.query( `SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at FROM audit_logs WHERE action = ? ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`, [action], ) : await db.query( `SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at FROM audit_logs ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`, ); return context.json({ entries: rows }); }); };