import { randomUUID } from "node:crypto"; import { z } from "zod"; import { AppError, attachUser, currentUser, requireAuth, requireRole, type App, type Config, type Db, } from "../lib/index.js"; import { audit, canManageFolder, canRead, canWrite } from "../access.js"; const uuid = 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 createFolder = z.object({ name: z.string().trim().min(1).max(255), parentId: uuid.nullish(), }); const updateFolder = z.object({ name: z.string().trim().min(1).max(255), }); const moveFolder = z.object({ parentId: uuid.nullish(), }); const permissionInput = z.object({ email: z.string().trim().min(3).max(255), level: z.enum(["read", "write", "admin"]), expiresAt: z.string().datetime().nullish(), }); interface FolderRow { id: string; parent_id: string | null; name: string; owner_id: string | null; access_type: string; is_system: number; storage_location_id: number; created_at: string; updated_at: string; } const SELECT_FOLDER = `SELECT f.id, f.parent_id, f.name, f.owner_id, f.access_type, f.is_system, f.storage_location_id, f.created_at, f.updated_at FROM folders f`; const publicFolder = (row: FolderRow) => ({ id: row.id, parent_id: row.parent_id, name: row.name, owner_id: row.owner_id, access_type: row.access_type, is_system: row.is_system === 1, created_at: row.created_at, updated_at: row.updated_at, }); const assertName = (raw: string): string => { const name = raw.trim(); if (!name || name.length > 255) { throw AppError.badRequest("Le nom du dossier doit contenir entre 1 et 255 caracteres."); } if (name === "." || name === ".." || /[/\\\0-\x1f]/.test(name)) { throw AppError.badRequest("Le nom du dossier ne peut pas contenir de separateur."); } return name; }; 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; }; /** Id du dossier et de tous ses descendants, y compris lui-meme. */ const subtreeIds = async (db: Db, rootId: string): Promise => { const rows = await db.query<{ id: string }>( `WITH RECURSIVE subtree AS ( SELECT id FROM folders WHERE id = ? UNION ALL SELECT f.id FROM folders f JOIN subtree s ON f.parent_id = s.id ) SELECT id FROM subtree`, [rootId], ); return rows.map((row) => row.id); }; export const registerFolderRoutes = (app: App, db: Db, config: Config): void => { app.use("/api/cloud/folders/*", attachUser(db)); app.use("/api/cloud/folders", attachUser(db)); app.get("/api/cloud/folders", requireAuth, async (context) => { const user = currentUser(context); const rawParent = context.req.query("parentId"); const parentId = rawParent === undefined || rawParent === "" ? null : rawParent; if (parentId !== null && !uuid.safeParse(parentId).success) { throw AppError.badRequest("Identifiant de dossier invalide."); } if (parentId !== null) { // Contre l'IDOR : on ne liste un dossier que si la session y a acces. if (!(await canRead(db, user, parentId))) { throw AppError.notFound("Dossier introuvable."); } } const rows = await db.query( `${SELECT_FOLDER} WHERE f.deleted_at IS NULL AND (f.parent_id <=> ?) AND ( ? = 1 OR f.owner_id = ? OR f.access_type = 'public' OR EXISTS ( SELECT 1 FROM folder_permissions fp WHERE fp.folder_id = f.id AND fp.user_id = ? AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) ORDER BY f.name`, [parentId, 0, user.id, user.id], ); return context.json({ parentId, folders: rows.map(publicFolder) }); }); app.post( "/api/cloud/folders", requireAuth, requireRole("admin", "user"), async (context) => { const user = currentUser(context); const { name: rawName, parentId } = parse( createFolder, await context.req.json().catch(() => null), ); const name = assertName(rawName); if (parentId) { if (!(await canWrite(db, user, parentId))) { throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier."); } } const duplicate = await db.one( `SELECT 1 AS taken FROM folders WHERE parent_id <=> ? AND active_name = ? AND deleted_at IS NULL LIMIT 1`, [parentId ?? null, name], ); if (duplicate) throw AppError.conflict("Ce nom existe deja ici."); const parent = parentId ? await db.one<{ id: string; storage_location_id: number }>( "SELECT id, storage_location_id FROM folders WHERE id = ? AND deleted_at IS NULL", [parentId], ) : null; if (parentId && !parent) throw AppError.notFound("Dossier parent introuvable."); const locationId = parent?.storage_location_id ?? ( await db.one<{ id: number }>( `SELECT id FROM storage_locations WHERE is_active = 1 AND deleted_at IS NULL ORDER BY id LIMIT 1`, ) )?.id; if (locationId === undefined) { throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible."); } const id = randomUUID(); try { await db.exec( `INSERT INTO folders (id, storage_location_id, parent_id, name, owner_id, created_by) VALUES (?, ?, ?, ?, ?, ?)`, [id, locationId, parentId ?? null, name, user.id, user.id], ); } catch (error) { if ((error as { errno?: number }).errno === 1062) { throw AppError.conflict("Ce nom existe deja ici."); } throw error; } const created = await db.required(`${SELECT_FOLDER} WHERE f.id = ?`, [id]); await audit(db, context, user, "folder.create", "folder", id, { name }, config.TRUST_PROXY); return context.json({ folder: publicFolder(created) }, 201); }, ); app.patch("/api/cloud/folders/:id", requireAuth, async (context) => { const user = currentUser(context); const id = context.req.param("id") ?? ""; if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable."); const existing = await db.one(`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`, [id]); if (!existing) throw AppError.notFound("Dossier introuvable."); if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable."); const data = parse(updateFolder, await context.req.json().catch(() => null)); const name = assertName(data.name); try { await db.exec("UPDATE folders SET name = ? WHERE id = ?", [name, id]); } catch (error) { if ((error as { errno?: number }).errno === 1062) { throw AppError.conflict("Ce nom existe deja ici."); } throw error; } const updated = await db.required(`${SELECT_FOLDER} WHERE f.id = ?`, [id]); await audit(db, context, user, "folder.update", "folder", id, { name }, config.TRUST_PROXY); return context.json({ folder: publicFolder(updated) }); }); app.post("/api/cloud/folders/:id/move", requireAuth, async (context) => { const user = currentUser(context); const id = context.req.param("id") ?? ""; if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable."); const existing = await db.one(`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`, [id]); if (!existing) throw AppError.notFound("Dossier introuvable."); if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre deplace."); if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable."); const { parentId } = parse(moveFolder, await context.req.json().catch(() => null)); if (parentId !== null && parentId !== undefined) { if (!(await canWrite(db, user, parentId))) { throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier de destination."); } // Refuse un deplacement dans soi-meme ou dans un descendant : sans cela, // l'arborescence se detache du graphe et devient inaccessible. const descendants = await subtreeIds(db, id); if (descendants.includes(parentId)) { throw AppError.badRequest("Impossible de deplacer un dossier dans lui-meme."); } } try { await db.exec("UPDATE folders SET parent_id = ? WHERE id = ?", [parentId ?? null, id]); } catch (error) { if ((error as { errno?: number }).errno === 1062) { throw AppError.conflict("Ce nom existe deja dans la destination."); } throw error; } const updated = await db.required(`${SELECT_FOLDER} WHERE f.id = ?`, [id]); await audit(db, context, user, "folder.move", "folder", id, { parentId: parentId ?? null }, config.TRUST_PROXY); return context.json({ folder: publicFolder(updated) }); }); /** Suppression logique recursive : le dossier, ses descendants et leurs fichiers. */ app.delete("/api/cloud/folders/:id", requireAuth, async (context) => { const user = currentUser(context); const id = context.req.param("id") ?? ""; if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable."); const existing = await db.one(`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`, [id]); if (!existing) throw AppError.notFound("Dossier introuvable."); if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre supprime."); if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable."); const ids = await subtreeIds(db, id); const placeholders = ids.map(() => "?").join(","); await db.transaction(async (connection) => { await connection.execute( `UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${placeholders}) AND deleted_at IS NULL`, ids, ); await connection.execute( `UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${placeholders}) AND deleted_at IS NULL`, ids, ); }); await audit(db, context, user, "folder.delete", "folder", id, { name: existing.name }, config.TRUST_PROXY); return context.json({ ok: true }); }); // --- Permissions nominatives ------------------------------------------- app.get("/api/cloud/folders/:id/permissions", requireAuth, async (context) => { const user = currentUser(context); const id = context.req.param("id") ?? ""; if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable."); if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable."); const rows = await db.query<{ user_id: string; email: string; first_name: string; last_name: string; level: string; expires_at: string | null; created_at: string; }>( `SELECT fp.user_id, u.email, u.first_name, u.last_name, fp.level, fp.expires_at, fp.created_at FROM folder_permissions fp JOIN users u ON u.id = fp.user_id WHERE fp.folder_id = ? ORDER BY u.email`, [id], ); return context.json({ permissions: rows.map((row) => ({ user_id: row.user_id, email: row.email, first_name: row.first_name, last_name: row.last_name, level: row.level, expires_at: row.expires_at, created_at: row.created_at, })), }); }); app.post("/api/cloud/folders/:id/permissions", requireAuth, async (context) => { const user = currentUser(context); const id = context.req.param("id") ?? ""; if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable."); if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable."); const { email, level, expiresAt } = parse( permissionInput, await context.req.json().catch(() => null), ); const target = await db.one<{ id: string }>( "SELECT id FROM users WHERE active_email = ? AND deleted_at IS NULL", [email], ); if (!target) throw AppError.notFound("Aucun compte ne correspond a cette adresse."); if (target.id === user.id) { throw AppError.badRequest("Vous etes deja proprietaire de ce dossier."); } const expires = expiresAt ? new Date(expiresAt) : null; await db.exec( `INSERT INTO folder_permissions (id, folder_id, user_id, level, expires_at, granted_by) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE level = VALUES(level), expires_at = VALUES(expires_at), granted_by = VALUES(granted_by)`, [randomUUID(), id, target.id, level, expires, user.id], ); await audit(db, context, user, "folder.share", "folder", id, { email, level }, config.TRUST_PROXY); return context.json({ ok: true }, 201); }); app.delete("/api/cloud/folders/:id/permissions/:userId", requireAuth, async (context) => { const user = currentUser(context); const id = context.req.param("id") ?? ""; const userId = context.req.param("userId") ?? ""; if (!uuid.safeParse(id).success || !uuid.safeParse(userId).success) { throw AppError.notFound("Dossier introuvable."); } if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable."); const result = await db.exec( "DELETE FROM folder_permissions WHERE folder_id = ? AND user_id = ?", [id, userId], ); if (result.affectedRows === 0) throw AppError.notFound("Partage introuvable."); await audit(db, context, user, "folder.unshare", "folder", id, { userId }, config.TRUST_PROXY); return context.json({ ok: true }); }); };