refactor: restructure frontend and backend by domain services
PR — Ouverture automatique / create-pr (push) Successful in 3s

Split the monolithic backend (lib/, routes/, access.ts, storage.ts, media.ts)
into a layered structure inspired by JeanXXIII-CRM:
- config/: appConfig, db
- middleware/: auth (session, roles, cookies)
- models/: shared types
- routes/: *Routes.ts (thin HTTP handlers)
- services/: *Service.ts (business logic, one per domain)
- utils/: errors, http, migrate, ratelimit, validators, service bootstrap

Frontend likewise: services/*Service.ts + apiClient, contexts/, types/, utils/format.
Route files now carry the "Routes" suffix; service files are named
authService.ts, ratelimit.ts, etc. and live in their own files, frontend and
backend separated.

Updated docs and READMEs to reflect the new layout. Typecheck and builds pass.
This commit is contained in:
2026-11-13 09:45:21 +01:00
parent d837817bcb
commit 68d4d5dea0
103 changed files with 5415 additions and 4711 deletions
+373
View File
@@ -0,0 +1,373 @@
import { randomBytes, randomUUID } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { hashPassword, sessionTokenHash, sha256, verifyPassword } from "./authService.js";
import { branding, getMailer, link, renderMail } from "./mailService.js";
import { absolutePath, diskUsage, fileExists } from "./storageService.js";
const AVATAR_PX = 512;
const HOUR_MS = 3600_000;
const avatarRelativePath = (userId: string): string => path.posix.join("avatars", `${userId}.webp`);
const newToken = (): string => randomBytes(32).toString("base64url");
export const updateProfile = async (
db: Db,
user: SessionUser,
first_name: string,
last_name: string,
): Promise<{ first_name: string; last_name: string }> => {
await db.exec("UPDATE users SET first_name = ?, last_name = ? WHERE id = ?", [
first_name,
last_name,
user.id,
]);
return { first_name, last_name };
};
export const getPreferences = async (
db: Db,
user: SessionUser,
): Promise<{ theme: string; language: string }> => {
const row = await db.one<{ theme: string; language: string }>(
"SELECT theme, language FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!row) throw AppError.notFound("Compte introuvable.");
return { theme: row.theme, language: row.language };
};
export const updatePreferences = async (
db: Db,
user: SessionUser,
theme: string,
language: string,
): Promise<{ theme: string; language: string }> => {
await db.exec("UPDATE users SET theme = ?, language = ? WHERE id = ?", [
theme,
language,
user.id,
]);
return { theme, language };
};
export interface SessionInfo {
id: string;
ip_address: string | null;
user_agent: string | null;
created_at: string;
last_seen_at: string;
expires_at: string;
current: boolean;
}
/** Sessions actives de l'utilisateur, la session courante marquee. */
export const listSessions = async (
db: Db,
config: Config,
user: SessionUser,
currentToken: string,
): Promise<SessionInfo[]> => {
const current = sessionTokenHash(currentToken, config.SESSION_SECRET);
const rows = await db.query<{
id: string;
token_hash: string;
ip_address: string | null;
user_agent: string | null;
created_at: string;
last_seen_at: string;
expires_at: string;
}>(
`SELECT id, token_hash, ip_address, user_agent, created_at, last_seen_at, expires_at
FROM user_sessions
WHERE user_id = ? AND revoked_at IS NULL AND expires_at > UTC_TIMESTAMP()
ORDER BY last_seen_at DESC`,
[user.id],
);
return rows.map((row) => ({
id: row.id,
ip_address: row.ip_address,
user_agent: row.user_agent,
created_at: row.created_at,
last_seen_at: row.last_seen_at,
expires_at: row.expires_at,
current: row.token_hash === current,
}));
};
export const revokeSessionById = async (db: Db, user: SessionUser, id: string): Promise<void> => {
const result = await db.exec(
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE id = ? AND user_id = ? AND revoked_at IS NULL",
[id, user.id],
);
if (result.affectedRows === 0) throw AppError.notFound("Session introuvable.");
};
export const revokeOtherSessions = async (
db: Db,
config: Config,
user: SessionUser,
currentToken: string,
): Promise<void> => {
const current = sessionTokenHash(currentToken, config.SESSION_SECRET);
await db.exec(
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND token_hash <> ? AND revoked_at IS NULL",
[user.id, current],
);
};
/** Traite l'image recue (recadrage, webp) et met a jour l'avatar + le quota. */
export const uploadAvatar = async (
db: Db,
config: Config,
user: SessionUser,
source: Buffer,
): Promise<void> => {
let processed: Buffer;
try {
processed = await sharp(source, { failOn: "none" })
.rotate()
.resize(AVATAR_PX, AVATAR_PX, { fit: "cover" })
.webp({ quality: 82 })
.toBuffer();
} catch {
throw AppError.badRequest("Le fichier n'est pas une image exploitable.");
}
const location = await db.one<{ id: number }>(
`SELECT id FROM storage_locations
WHERE is_active = 1 AND deleted_at IS NULL ORDER BY id LIMIT 1`,
);
if (!location) throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible.");
const disk = await diskUsage(config.VARIANT_DIR);
if (disk !== null && processed.byteLength > disk.available_bytes) {
throw AppError.insufficientStorage("Espace disque insuffisant sur le serveur.");
}
const relative = avatarRelativePath(user.id);
const destination = absolutePath(config.VARIANT_DIR, relative);
await mkdir(path.dirname(destination), { recursive: true });
await writeFile(destination, processed);
const size = processed.byteLength;
const previous = await db.one<{ storage_location_id: number; size_bytes: number }>(
"SELECT storage_location_id, size_bytes FROM user_avatars WHERE user_id = ?",
[user.id],
);
await db.transaction(async (connection) => {
if (previous) {
await connection.execute(
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
[previous.size_bytes, previous.storage_location_id],
);
}
await connection.execute(
`UPDATE storage_locations SET used_bytes = used_bytes + ? WHERE id = ?`,
[size, location.id],
);
await connection.execute(
`INSERT INTO user_avatars (user_id, storage_location_id, original_path, mime_type, size_bytes, width, height)
VALUES (?, ?, ?, 'image/webp', ?, ?, ?)
ON DUPLICATE KEY UPDATE storage_location_id = VALUES(storage_location_id),
original_path = VALUES(original_path), mime_type = VALUES(mime_type),
size_bytes = VALUES(size_bytes), width = VALUES(width), height = VALUES(height)`,
[user.id, location.id, relative, processed.byteLength, AVATAR_PX, AVATAR_PX],
);
});
};
/** Chemin et taille de l'avatar d'un utilisateur (null si absent). */
export const getAvatar = async (
db: Db,
config: Config,
userId: string,
): Promise<{ absolute: string; size: number } | null> => {
const row = await db.one<{ original_path: string; size_bytes: number }>(
"SELECT original_path, size_bytes FROM user_avatars WHERE user_id = ?",
[userId],
);
if (!row) return null;
const absolute = absolutePath(config.VARIANT_DIR, row.original_path);
if (!(await fileExists(absolute))) return null;
return { absolute, size: row.size_bytes };
};
export const deleteAvatar = async (db: Db, user: SessionUser): Promise<void> => {
const row = await db.one<{ storage_location_id: number; size_bytes: number }>(
"SELECT storage_location_id, size_bytes FROM user_avatars WHERE user_id = ?",
[user.id],
);
if (!row) throw AppError.notFound("Avatar introuvable.");
await db.transaction(async (connection) => {
await connection.execute("DELETE FROM user_avatars WHERE user_id = ?", [user.id]);
await connection.execute(
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
[row.size_bytes, row.storage_location_id],
);
});
};
/** Cree un jeton de reinitialisation et envoie le lien (silencieux si compte absent). */
export const forgotPassword = async (db: Db, config: Config, email: string): Promise<void> => {
const user = await db.one<{ id: string; email: string }>(
"SELECT id, email FROM users WHERE active_email = ? AND is_active = 1",
[email],
);
if (!user) return;
const token = newToken();
await db.exec(
"INSERT INTO password_reset_tokens (id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)",
[randomUUID(), user.id, sha256(token), new Date(Date.now() + HOUR_MS)],
);
const url = link(config, `/reset-password?token=${encodeURIComponent(token)}`);
const mail = renderMail(branding(config), {
preview: "Reinitialisez le mot de passe de votre compte.",
heading: "Reinitialisation du mot de passe",
intro:
"Une reinitialisation de mot de passe a ete demandee pour votre compte CoHaiSe Cloud. Choisissez un nouveau mot de passe en suivant le lien ci-dessous.",
cta: { label: "Choisir un mot de passe", url },
note: "Ce lien expire dans une heure. Si vous n'etes pas a l'origine de cette demande, ignorez ce message : votre mot de passe reste inchange.",
});
await getMailer(config)
.send({
to: user.email,
subject: "CoHaiSe Cloud — reinitialisation du mot de passe",
...mail,
})
.catch(() => undefined);
};
export interface ResetActor {
userId: string;
email: string;
first_name: string;
last_name: string;
}
/** Applique la reinitialisation du mot de passe. Renvoie l'acteur pour l'audit. */
export const resetPassword = async (
db: Db,
token: string,
password: string,
): Promise<ResetActor | null> => {
const row = await db.one<{ id: string; user_id: string }>(
`SELECT id, user_id FROM password_reset_tokens
WHERE token_hash = ? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP()`,
[sha256(token)],
);
if (!row) throw AppError.badRequest("Lien invalide ou expire.");
const hash = await hashPassword(password);
const account = await db.one<{ email: string; first_name: string; last_name: string }>(
"SELECT email, first_name, last_name FROM users WHERE id = ?",
[row.user_id],
);
await db.transaction(async (connection) => {
await connection.execute(
"UPDATE users SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP() WHERE id = ?",
[hash, row.user_id],
);
await connection.execute(
"UPDATE password_reset_tokens SET used_at = UTC_TIMESTAMP() WHERE id = ?",
[row.id],
);
await connection.execute(
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL",
[row.user_id],
);
});
if (!account) return null;
return {
userId: row.user_id,
email: account.email,
first_name: account.first_name,
last_name: account.last_name,
};
};
/** Demande un changement d'adresse : verifie le mot de passe puis envoie le lien. */
export const requestEmailChange = async (
db: Db,
config: Config,
user: SessionUser,
password: string,
newEmail: string,
): Promise<void> => {
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!row || !(await verifyPassword(password, row.password_hash))) {
throw AppError.unauthorized("Mot de passe incorrect.");
}
if (newEmail.toLowerCase() === user.email.toLowerCase()) {
throw AppError.badRequest("La nouvelle adresse est identique a l'actuelle.");
}
const taken = await db.one("SELECT id FROM users WHERE active_email = ?", [newEmail]);
if (taken) throw AppError.conflict("Cette adresse est deja utilisee.");
const token = newToken();
await db.exec(
`INSERT INTO email_change_requests (id, user_id, new_email, token_hash, expires_at)
VALUES (?, ?, ?, ?, ?)`,
[randomUUID(), user.id, newEmail, sha256(token), new Date(Date.now() + HOUR_MS)],
);
const url = link(config, `/confirm-email?token=${encodeURIComponent(token)}`);
const mail = renderMail(branding(config), {
preview: "Confirmez votre nouvelle adresse e-mail.",
heading: "Confirmez votre nouvelle adresse",
intro:
"Une demande de changement d'adresse a ete faite pour votre compte CoHaiSe Cloud. Confirmez la nouvelle adresse en suivant le lien ci-dessous.",
cta: { label: "Confirmer l'adresse", url },
note: "Ce lien expire dans une heure. Sans confirmation, l'adresse reste inchangee.",
});
await getMailer(config)
.send({
to: newEmail,
subject: "CoHaiSe Cloud — confirmez votre nouvelle adresse",
text: mail.text,
html: mail.html,
})
.catch(() => undefined);
};
/** Confirme le changement d'adresse. Renvoie la nouvelle adresse. */
export const confirmEmailChange = async (db: Db, token: string): Promise<string> => {
const row = await db.one<{ id: string; user_id: string; new_email: string }>(
`SELECT id, user_id, new_email FROM email_change_requests
WHERE token_hash = ? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP()`,
[sha256(token)],
);
if (!row) throw AppError.badRequest("Lien invalide ou expire.");
const taken = await db.one("SELECT id FROM users WHERE active_email = ? AND id <> ?", [
row.new_email,
row.user_id,
]);
if (taken) throw AppError.conflict("Cette adresse est deja utilisee.");
await db.transaction(async (connection) => {
await connection.execute("UPDATE users SET email = ? WHERE id = ?", [
row.new_email,
row.user_id,
]);
await connection.execute(
"UPDATE email_change_requests SET used_at = UTC_TIMESTAMP() WHERE id = ?",
[row.id],
);
});
return row.new_email;
};
+494
View File
@@ -0,0 +1,494 @@
import { randomInt, randomUUID } from "node:crypto";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { AppError } from "../utils/errors.js";
import { hashPassword } from "./authService.js";
import { branding, getMailer, link, renderMail } from "./mailService.js";
import { diskUsage } from "./storageService.js";
export 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;
}
export 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"];
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]}`;
};
const generatePasswordValue = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let out = "";
for (let index = 0; index < 18; index += 1) out += alphabet[randomInt(alphabet.length)];
return out;
};
/** Reaffecte ou supprime les dossiers d'un compte supprime. */
const rehomeUserFolders = async (
db: Db,
userId: string,
): Promise<{ kept: number; deleted: number }> => {
const folders = await db.query<{ id: string; parent_id: string | null }>(
"SELECT id, parent_id FROM folders WHERE owner_id = ? AND deleted_at IS NULL AND is_system = 0",
[userId],
);
if (folders.length === 0) return { kept: 0, deleted: 0 };
const ids = folders.map((folder) => folder.id);
const placeholders = ids.map(() => "?").join(",");
const candidates = await db.query<{
folder_id: string;
user_id: string;
level: string;
created_at: string;
}>(
`SELECT fp.folder_id, fp.user_id, fp.level, fp.created_at
FROM folder_permissions fp
JOIN users u ON u.id = fp.user_id AND u.deleted_at IS NULL AND u.is_active = 1
WHERE fp.folder_id IN (${placeholders})
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() )
ORDER BY FIELD(fp.level, 'admin', 'write', 'read'), fp.created_at ASC`,
[...ids],
);
const newOwner = new Map<string, string>();
for (const row of candidates) {
if (!newOwner.has(row.folder_id)) newOwner.set(row.folder_id, row.user_id);
}
const owned = new Map(folders.map((folder) => [folder.id, folder.parent_id]));
const keepIds = [...newOwner.keys()];
const deleteIds = ids.filter((id) => !newOwner.has(id));
await db.transaction(async (connection) => {
for (const [id, owner] of newOwner) {
const parentId = owned.get(id) ?? null;
const parentGone = parentId !== null && owned.has(parentId) && !newOwner.has(parentId);
await connection.execute(
"UPDATE folders SET owner_id = ?, parent_id = ? WHERE id = ?",
[owner, parentGone ? null : parentId, id],
);
}
if (deleteIds.length > 0) {
const delPh = deleteIds.map(() => "?").join(",");
await connection.execute(
`UPDATE folders SET parent_id = NULL
WHERE parent_id IN (${delPh}) AND deleted_at IS NULL
AND owner_id <> ? AND id NOT IN (${keepIds.map(() => "?").join(",") || "''"})`,
[...deleteIds, userId, ...(keepIds.length > 0 ? keepIds : [])],
);
await connection.execute(
`UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${delPh}) AND deleted_at IS NULL`,
deleteIds,
);
await connection.execute(
`UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${delPh}) AND deleted_at IS NULL`,
deleteIds,
);
}
await connection.execute("DELETE FROM folder_permissions WHERE user_id = ?", [userId]);
await connection.execute("DELETE FROM user_file_stars WHERE user_id = ?", [userId]);
});
return { kept: keepIds.length, deleted: deleteIds.length };
};
const assertQuotaFits = async (config: Config, quota: number): Promise<void> => {
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)}).`,
);
}
};
export const getStats = async (db: Db, config: Config) => {
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 {
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),
};
};
export const listUsers = async (db: Db, q: string): Promise<AdminUserRow[]> => {
const query = q.trim();
if (query) {
return db.query<AdminUserRow>(
`${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}%`],
);
}
return db.query<AdminUserRow>(
`${SELECT_USER} WHERE u.deleted_at IS NULL ORDER BY u.email LIMIT 500`,
);
};
export interface CreateUserInput {
email: string;
first_name: string;
last_name: string;
role_slug: string;
quota_bytes?: number | null | undefined;
max_file_bytes?: number | null | undefined;
password?: string | null | undefined;
}
export const createUser = async (
db: Db,
config: Config,
data: CreateUserInput,
): Promise<AdminUserRow> => {
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<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
const mail = renderMail(branding(config), {
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 getMailer(config)
.send({
to: data.email,
subject: "CoHaiSe Cloud — votre compte est pret",
text: mail.text,
html: mail.html,
})
.catch(() => undefined);
return created;
};
export interface UpdateUserInput {
first_name?: string | undefined;
last_name?: string | undefined;
role_slug?: string | undefined;
quota_bytes?: number | undefined;
max_file_bytes?: number | undefined;
is_active?: boolean | undefined;
}
export const updateUser = async (
db: Db,
actorId: string,
id: string,
data: UpdateUserInput,
): Promise<AdminUserRow> => {
const existing = await db.one<AdminUserRow>(
`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`,
[id],
);
if (!existing) throw AppError.notFound("Compte introuvable.");
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 === actorId) 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 === actorId) {
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],
);
}
}
return db.required<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
};
/** Supprime (logiquement) un compte et reattribue ses dossiers. */
export const deleteUser = async (
db: Db,
actorId: string,
id: string,
): Promise<{ kept: number; deleted: number }> => {
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.");
if (id === actorId) throw AppError.badRequest("Vous ne pouvez pas supprimer votre propre compte.");
const rehomed = await rehomeUserFolders(db, id);
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]);
return rehomed;
};
/** Reinitialise le mot de passe d'un compte et envoie les identifiants. */
export const resetUserPassword = async (db: Db, config: Config, id: string): Promise<void> => {
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],
);
const mail = renderMail(branding(config), {
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 getMailer(config)
.send({
to: user.email,
subject: "CoHaiSe Cloud — mot de passe reinitialise",
text: mail.text,
html: mail.html,
})
.catch(() => undefined);
};
export interface StorageLocationRow {
id: number;
name: string;
slug: string;
mount_path: string;
quota_bytes: number | null;
used_bytes: number;
is_active: number;
created_at: string;
}
export const listStorageLocations = async (db: Db, config: Config) => ({
locations: await db.query<StorageLocationRow>(
`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`,
),
disk: await diskUsage(config.MEDIA_DIR),
});
export const createStorageLocation = async (
db: Db,
config: Config,
data: { name: string; slug: string; mount_path: string; quota_bytes?: number | null | undefined },
): Promise<void> => {
if (data.quota_bytes !== undefined && data.quota_bytes !== null) {
await assertQuotaFits(config, 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;
}
};
export const updateStorageLocation = async (
db: Db,
config: Config,
id: number,
data: { name?: string | undefined; quota_bytes?: number | null | undefined; is_active?: boolean | undefined },
): Promise<void> => {
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(config, 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);
};
export const auditFilters = async (db: Db) => {
const actions = await db.query<{ action: string }>(
"SELECT DISTINCT action FROM audit_logs ORDER BY action ASC",
);
const users = await db.query<{ user_id: string; user_email: string | null }>(
`SELECT user_id, MAX(user_email) AS user_email
FROM audit_logs
WHERE user_id IS NOT NULL
GROUP BY user_id
ORDER BY user_email ASC`,
);
return {
actions: actions.map((row) => row.action),
users: users.map((row) => ({ id: row.user_id, email: row.user_email })),
};
};
export const auditEntries = async (
db: Db,
options: { limit: number; offset: number; action?: string | null; userId?: string | null },
) => {
const conditions: string[] = [];
const params: unknown[] = [];
if (options.action) {
conditions.push("action = ?");
params.push(options.action);
}
if (options.userId) {
conditions.push("user_id = ?");
params.push(options.userId);
}
const where = conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "";
return db.query(
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
FROM audit_logs${where} ORDER BY created_at DESC LIMIT ${options.limit} OFFSET ${options.offset}`,
params,
);
};
+152
View File
@@ -0,0 +1,152 @@
import type { Context } from "hono";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { clientIp } from "../utils/http.js";
/** Fragment SQL de lisibilite d'un dossier, partage par les requetes du chat. */
export const READ_SQL = `( 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.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )`;
export const canWrite = async (db: Db, user: SessionUser, folderId: string): Promise<boolean> => {
const row = await db.one(
`SELECT 1 AS granted
FROM folders f
WHERE f.id = ? AND f.deleted_at IS NULL
AND ( 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.level IN ('write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
LIMIT 1`,
[folderId, user.id, user.id],
);
return row !== null;
};
export const canRead = async (db: Db, user: SessionUser, folderId: string): Promise<boolean> => {
const row = await db.one(
`SELECT 1 AS granted
FROM folders f
WHERE f.id = ? AND f.deleted_at IS NULL
AND ( 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.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
LIMIT 1`,
[folderId, user.id, user.id],
);
return row !== null;
};
export const canWriteExplicit = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<boolean> => {
const row = await db.one(
`SELECT 1 AS granted
FROM folders f
WHERE f.id = ? AND f.deleted_at IS NULL
AND ( f.owner_id = ?
OR EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = f.id AND fp.user_id = ?
AND fp.level IN ('write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
LIMIT 1`,
[folderId, user.id, user.id],
);
return row !== null;
};
export const canManageFolder = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<boolean> => {
const row = await db.one(
`SELECT 1 AS granted FROM folders
WHERE id = ? AND deleted_at IS NULL AND owner_id = ? LIMIT 1`,
[folderId, user.id],
);
return row !== null;
};
export const canTraverse = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<boolean> => {
const direct = await db.one(
`SELECT 1 AS granted
FROM folders f
WHERE f.id = ? AND f.deleted_at IS NULL
AND ( 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.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
LIMIT 1`,
[folderId, user.id, user.id],
);
if (direct !== null) return true;
const descendant = await db.one(
`WITH RECURSIVE descendants AS (
SELECT id, parent_id FROM folders WHERE parent_id = ? AND deleted_at IS NULL
UNION ALL
SELECT f.id, f.parent_id FROM folders f
JOIN descendants d ON f.parent_id = d.id
WHERE f.deleted_at IS NULL
)
SELECT 1 AS granted
FROM descendants d
JOIN folders f2 ON f2.id = d.id AND f2.deleted_at IS NULL
WHERE f2.owner_id = ?
OR f2.access_type = 'public'
OR EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = f2.id AND fp.user_id = ?
AND fp.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) )
LIMIT 1`,
[folderId, user.id, user.id],
);
return descendant !== null;
};
/** Consigne une action dans le journal d'audit (silencieux en cas d'echec). */
export const audit = async (
db: Db,
context: Context,
user: SessionUser,
action: string,
resource: string,
resourceId: string | null,
details: Record<string, unknown> | null,
trustProxy: boolean,
): Promise<void> => {
await db
.exec(
`INSERT INTO audit_logs
(user_id, user_email, action, resource, resource_id, details, ip_address, user_agent)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[
user.id,
user.email,
action,
resource,
resourceId,
details ? JSON.stringify(details) : null,
clientIp(context, trustProxy),
(context.req.header("user-agent") ?? "").slice(0, 255) || null,
],
)
.catch(() => undefined);
};
+241
View File
@@ -0,0 +1,241 @@
import {
createHash,
createHmac,
randomBytes,
randomUUID,
scrypt as scryptCallback,
timingSafeEqual,
} from "node:crypto";
import { promisify } from "node:util";
import type { Db } from "../config/db.js";
import type { Config } from "../config/appConfig.js";
import type { SessionMeta, SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
const scrypt = promisify(scryptCallback) as (
password: string | Buffer,
salt: Buffer,
keylen: number,
options: { N: number; r: number; p: number; maxmem?: number },
) => Promise<Buffer>;
const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 64, maxmem: 32 * 1024 * 1024 };
export const hashPassword = async (password: string): Promise<string> => {
if (Buffer.byteLength(password) < 8) {
throw AppError.badRequest("Le mot de passe doit contenir au moins 8 caracteres.");
}
const salt = randomBytes(16);
const derived = await scrypt(password, salt, SCRYPT.keylen, SCRYPT);
return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${salt.toString("base64")}$${derived.toString("base64")}`;
};
export const verifyPassword = async (password: string, stored: string): Promise<boolean> => {
const parts = stored.split("$");
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
const [, n, r, p, saltB64, hashB64] = parts;
const salt = Buffer.from(saltB64 ?? "", "base64");
const expected = Buffer.from(hashB64 ?? "", "base64");
if (expected.length === 0) return false;
const derived = await scrypt(password, salt, expected.length, {
N: Number(n),
r: Number(r),
p: Number(p),
maxmem: SCRYPT.maxmem,
});
return derived.length === expected.length && timingSafeEqual(derived, expected);
};
export const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex");
export const sessionTokenHash = (token: string, secret: string): string =>
createHmac("sha256", secret).update(token).digest("hex");
export const SESSION_COOKIE = "cohaise_session";
export const createSession = async (
db: Db,
userId: string,
meta: SessionMeta,
ttlHours: number,
secret: string,
): Promise<{ token: string; expiresAt: Date }> => {
const token = randomBytes(32).toString("base64url");
const expiresAt = new Date(Date.now() + ttlHours * 3600_000);
await db.exec(
`INSERT INTO user_sessions (id, user_id, token_hash, ip_address, user_agent, expires_at)
VALUES (?, ?, ?, ?, ?, ?)`,
[
randomUUID(),
userId,
sessionTokenHash(token, secret),
meta.ipAddress ?? null,
meta.userAgent?.slice(0, 255) ?? null,
expiresAt,
],
);
return { token, expiresAt };
};
export const resolveSession = async (
db: Db,
token: string,
secret: string,
): Promise<SessionUser | null> => {
const row = await db.one<SessionUser & { last_seen_at: string }>(
`SELECT u.id, u.email, u.first_name, u.last_name,
r.slug AS role_slug, r.name AS role_name,
u.is_active, u.must_change_password,
s.last_seen_at
FROM user_sessions s
JOIN users u ON u.id = s.user_id
JOIN roles r ON r.id = u.role_id
WHERE s.token_hash = ?
AND s.revoked_at IS NULL
AND s.expires_at > UTC_TIMESTAMP()
AND u.deleted_at IS NULL
AND u.is_active = 1`,
[sessionTokenHash(token, secret)],
);
if (!row) return null;
await db.exec(
"UPDATE user_sessions SET last_seen_at = UTC_TIMESTAMP() WHERE token_hash = ? AND last_seen_at < UTC_TIMESTAMP(3) - INTERVAL 60 SECOND",
[sessionTokenHash(token, secret)],
);
return row;
};
export const revokeSession = async (db: Db, token: string, secret: string): Promise<void> => {
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE token_hash = ?", [
sessionTokenHash(token, secret),
]);
};
export const purgeExpiredSessions = async (db: Db): Promise<number> => {
const result = await db.exec("DELETE FROM user_sessions WHERE expires_at < UTC_TIMESTAMP()");
return result.affectedRows;
};
export interface UserRow {
id: string;
email: string;
first_name: string;
last_name: string;
password_hash: string;
role_slug: string;
role_name: string;
quota_bytes: number;
used_bytes: number;
max_file_bytes: number;
must_change_password: number;
is_active: number;
theme: string;
language: string;
avatar_updated_at: Date | null;
}
export const SELECT_USER = `
SELECT u.id, u.email, u.first_name, u.last_name, u.password_hash,
r.slug AS role_slug, r.name AS role_name,
u.quota_bytes, u.used_bytes, u.max_file_bytes, u.must_change_password, u.is_active,
u.theme, u.language,
ua.updated_at AS avatar_updated_at
FROM users u
JOIN roles r ON r.id = u.role_id
LEFT JOIN user_avatars ua ON ua.user_id = u.id`;
export const publicUser = (row: UserRow) => ({
id: row.id,
email: row.email,
first_name: row.first_name,
last_name: row.last_name,
role_slug: row.role_slug,
role_name: row.role_name,
quota_bytes: row.quota_bytes,
used_bytes: row.used_bytes,
max_file_bytes: row.max_file_bytes,
must_change_password: row.must_change_password,
theme: row.theme,
language: row.language,
has_avatar: row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
});
export type PublicUser = ReturnType<typeof publicUser>;
let dummyHash: Promise<string> | undefined;
const decoyHash = (): Promise<string> => (dummyHash ??= hashPassword("aucun-compte-ne-correspond"));
/** Verifie les identifiants, cree la session et marque la derniere connexion. */
export const login = async (
db: Db,
config: Config,
email: string,
password: string,
meta: SessionMeta,
): Promise<{ user: PublicUser; token: string; expiresAt: Date }> => {
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.active_email = ?`, [email]);
const stored = row && row.is_active === 1 ? row.password_hash : await decoyHash();
if (!row || row.is_active !== 1 || !(await verifyPassword(password, stored))) {
throw AppError.unauthorized("Identifiants invalides.");
}
const { token, expiresAt } = await createSession(
db,
row.id,
meta,
config.SESSION_TTL_HOURS,
config.SESSION_SECRET,
);
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP() WHERE id = ?", [row.id]);
return { user: publicUser(row), token, expiresAt };
};
/** Renvoie le profil public de l'utilisateur courant. */
export const me = async (db: Db, userId: string): Promise<PublicUser> => {
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ?`, [userId]);
if (!row) throw AppError.unauthorized();
return publicUser(row);
};
/** Change le mot de passe et revoque toutes les autres sessions. */
export const changePassword = async (
db: Db,
config: Config,
userId: string,
currentToken: string,
currentPassword: string,
nextPassword: string,
): Promise<void> => {
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[userId],
);
if (!row) throw AppError.unauthorized();
if (!(await verifyPassword(currentPassword, row.password_hash))) {
throw AppError.unauthorized("Mot de passe actuel incorrect.");
}
if (currentPassword === nextPassword) {
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
}
const hash = await hashPassword(nextPassword);
await db.exec(
`UPDATE users
SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP()
WHERE id = ?`,
[hash, userId],
);
await db.exec(
`UPDATE user_sessions
SET revoked_at = UTC_TIMESTAMP()
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
[userId, sessionTokenHash(currentToken, config.SESSION_SECRET)],
);
};
+278
View File
@@ -0,0 +1,278 @@
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { canManageFolder, canRead, READ_SQL } from "./auditService.js";
const DATETIME_CURSOR = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?$/;
export interface MessageRow {
id: number;
user_id: string | null;
body: string;
created_at: string;
edited_at: string | null;
is_pinned: number;
first_name: string | null;
last_name: string | null;
avatar_updated_at: Date | null;
}
const SELECT_MESSAGE = `
SELECT m.id, m.user_id, m.body, m.created_at, m.edited_at, m.is_pinned,
u.first_name, u.last_name, ua.updated_at AS avatar_updated_at
FROM chat_messages m
LEFT JOIN users u ON u.id = m.user_id
LEFT JOIN user_avatars ua ON ua.user_id = m.user_id`;
export const publicMessage = (row: MessageRow) => ({
id: row.id,
user_id: row.user_id,
first_name: row.first_name,
last_name: row.last_name,
body: row.body,
created_at: row.created_at,
edited_at: row.edited_at,
is_pinned: row.is_pinned === 1,
has_avatar: row.user_id !== null && row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
});
const assertFolder = async (
db: Db,
folderId: string,
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
const folder = await db.one<{ id: string; owner_id: string | null; access_type: string }>(
"SELECT id, owner_id, access_type FROM folders WHERE id = ? AND deleted_at IS NULL",
[folderId],
);
if (!folder) throw AppError.notFound("Dossier introuvable.");
return folder;
};
const assertReadableFolder = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
const folder = await assertFolder(db, folderId);
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
return folder;
};
const markRead = async (db: Db, folderId: string, userId: string, messageId: number): Promise<void> => {
if (messageId <= 0) return;
await db
.exec(
`INSERT INTO chat_reads (folder_id, user_id, last_read_message_id)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
last_read_message_id = GREATEST(last_read_message_id, ?),
updated_at = UTC_TIMESTAMP(3)`,
[folderId, userId, messageId, messageId],
)
.catch(() => undefined);
};
/** Nombre de messages non lus par dossier. */
export const unreadCounts = async (db: Db, user: SessionUser): Promise<Record<string, number>> => {
const rows = await db.query<{ folder_id: string; unread: number }>(
`SELECT f.id AS folder_id, COUNT(m.id) AS unread
FROM folders f
JOIN chat_messages m
ON m.folder_id = f.id
AND m.deleted_at IS NULL
AND m.user_id <> ?
WHERE f.deleted_at IS NULL
AND m.id > COALESCE (
( SELECT cr.last_read_message_id
FROM chat_reads cr
WHERE cr.folder_id = f.id AND cr.user_id = ? ), 0 )
AND ${READ_SQL}
GROUP BY f.id
HAVING unread > 0`,
[user.id, user.id, user.id, user.id],
);
const unread: Record<string, number> = {};
for (const row of rows) unread[row.folder_id] = Number(row.unread);
return unread;
};
export interface ChatMember {
id: string;
first_name: string;
last_name: string;
role_slug: string;
avatar_updated_at: Date | null;
last_login_at: string | null;
is_self: boolean;
}
export const members = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<ChatMember[]> => {
const folder = await assertReadableFolder(db, user, folderId);
const rows = await db.query<Omit<ChatMember, "is_self">>(
`SELECT u.id, u.first_name, u.last_name, r.slug AS role_slug,
ua.updated_at AS avatar_updated_at, u.last_login_at
FROM users u
JOIN roles r ON r.id = u.role_id
LEFT JOIN user_avatars ua ON ua.user_id = u.id
WHERE u.deleted_at IS NULL AND u.is_active = 1
AND ( u.id = ?
OR ? = 1
OR EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = ? AND fp.user_id = u.id
AND fp.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
ORDER BY u.first_name ASC, u.last_name ASC`,
[folder.owner_id, folder.access_type === "public" ? 1 : 0, folderId],
);
return rows.map((row) => ({ ...row, is_self: row.id === user.id }));
};
export const messages = async (
db: Db,
user: SessionUser,
folderId: string,
options: { after?: number; limit?: number; editedAfter?: string | null },
): Promise<{ messages: MessageRow[]; cursor: string }> => {
await assertReadableFolder(db, user, folderId);
const limit = Math.min(200, Math.max(1, options.limit ?? 50));
const after = Math.max(0, options.after ?? 0);
const cursorRow = await db.one<{ chat_cursor: string }>(
"SELECT DATE_FORMAT(CURRENT_TIMESTAMP(3), '%Y-%m-%dT%H:%i:%s.%f') AS chat_cursor",
);
const serverCursor = cursorRow?.chat_cursor ?? "1970-01-01T00:00:00.000000";
const editedAfterRaw = options.editedAfter;
const editedSince =
typeof editedAfterRaw === "string" && DATETIME_CURSOR.test(editedAfterRaw)
? editedAfterRaw
: serverCursor;
const rows =
after > 0
? await db.query<MessageRow>(
`${SELECT_MESSAGE}
WHERE m.folder_id = ? AND m.deleted_at IS NULL
AND ( m.id > ?
OR ( m.edited_at IS NOT NULL AND m.edited_at >= ? ) )
ORDER BY m.id ASC
LIMIT ${limit}`,
[folderId, after, editedSince],
)
: (
await db.query<MessageRow>(
`${SELECT_MESSAGE}
WHERE m.folder_id = ? AND m.deleted_at IS NULL
ORDER BY m.id DESC
LIMIT ${limit}`,
[folderId],
)
).reverse();
const newest = rows.reduce((max, row) => Math.max(max, row.id), 0);
await markRead(db, folderId, user.id, newest);
return { messages: rows, cursor: serverCursor };
};
export const sendMessage = async (
db: Db,
user: SessionUser,
folderId: string,
body: string,
): Promise<MessageRow> => {
await assertReadableFolder(db, user, folderId);
const result = await db.exec(
"INSERT INTO chat_messages (folder_id, user_id, body) VALUES (?, ?, ?)",
[folderId, user.id, body],
);
return db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [result.insertId]);
};
export const editMessage = async (
db: Db,
user: SessionUser,
folderId: string,
id: number,
body: string,
): Promise<MessageRow> => {
await assertReadableFolder(db, user, folderId);
const result = await db.exec(
`UPDATE chat_messages
SET body = ?, edited_at = CURRENT_TIMESTAMP(3)
WHERE id = ? AND folder_id = ? AND user_id = ? AND deleted_at IS NULL`,
[body, id, folderId, user.id],
);
if (result.affectedRows === 0) throw AppError.notFound("Message introuvable.");
return db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [id]);
};
export const togglePin = async (
db: Db,
user: SessionUser,
folderId: string,
id: number,
): Promise<boolean> => {
await assertReadableFolder(db, user, folderId);
const result = await db.exec(
"UPDATE chat_messages SET is_pinned = 1 - is_pinned WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
[id, folderId],
);
if (result.affectedRows === 0) throw AppError.notFound("Message introuvable.");
const row = await db.required<{ is_pinned: number }>(
"SELECT is_pinned FROM chat_messages WHERE id = ?",
[id],
);
return row.is_pinned === 1;
};
export const pins = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<MessageRow[]> => {
await assertReadableFolder(db, user, folderId);
return db.query<MessageRow>(
`${SELECT_MESSAGE}
WHERE m.folder_id = ? AND m.is_pinned = 1 AND m.deleted_at IS NULL
ORDER BY m.id DESC
LIMIT 50`,
[folderId],
);
};
export const deleteMessage = async (
db: Db,
user: SessionUser,
folderId: string,
id: number,
): Promise<void> => {
await assertReadableFolder(db, user, folderId);
const row = await db.one<{ user_id: string | null }>(
"SELECT user_id FROM chat_messages WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
[id, folderId],
);
if (!row || (row.user_id !== user.id && !(await canManageFolder(db, user, folderId)))) {
throw AppError.notFound("Message introuvable.");
}
await db.exec(
"UPDATE chat_messages SET deleted_at = CURRENT_TIMESTAMP(3), is_pinned = 0 WHERE id = ?",
[id],
);
};
+40
View File
@@ -0,0 +1,40 @@
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
export interface DirectoryUser {
id: string;
first_name: string;
last_name: string;
email: string;
has_avatar: boolean;
avatar_updated_at: Date | null;
}
/** Annuaire des comptes actifs (hors soi-meme). */
export const listUsers = async (db: Db, user: SessionUser): Promise<DirectoryUser[]> => {
const rows = await db.query<{
id: string;
first_name: string;
last_name: string;
email: string;
avatar_updated_at: Date | null;
}>(
`SELECT u.id, u.first_name, u.last_name, u.email,
ua.updated_at AS avatar_updated_at
FROM users u
LEFT JOIN user_avatars ua ON ua.user_id = u.id
WHERE u.deleted_at IS NULL AND u.is_active = 1 AND u.id <> ?
ORDER BY u.first_name ASC, u.last_name ASC
LIMIT 1000`,
[user.id],
);
return rows.map((row) => ({
id: row.id,
first_name: row.first_name,
last_name: row.last_name,
email: row.email,
has_avatar: row.avatar_updated_at !== null,
avatar_updated_at: row.avatar_updated_at,
}));
};
+364
View File
@@ -0,0 +1,364 @@
import { randomUUID } from "node:crypto";
import path from "node:path";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { FileRow, SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { canRead, canWrite, canWriteExplicit } from "./auditService.js";
import { indexMedia } from "./mediaService.js";
import {
absolutePath,
chooseLocation,
discard,
diskUsage,
ensureDir,
publish,
relativePathFor,
temporaryPath,
writeBody,
} from "./storageService.js";
export const SELECT_FILE = `SELECT f.id, f.folder_id, f.name, f.mime_type, f.size_bytes, f.checksum_sha256,
f.relative_path, f.owner_id,
EXISTS (SELECT 1 FROM user_file_stars s WHERE s.file_id = f.id AND s.user_id = ?) AS is_starred,
f.download_count, f.created_at, f.updated_at
FROM files f`;
export const publicFile = (row: FileRow) => ({
id: row.id,
folder_id: row.folder_id,
name: row.name,
mime_type: row.mime_type,
size_bytes: row.size_bytes,
checksum_sha256: row.checksum_sha256,
owner_id: row.owner_id,
is_starred: row.is_starred === 1,
download_count: row.download_count,
created_at: row.created_at,
updated_at: row.updated_at,
});
export const assertNameFree = async (
db: Db,
user: { id: string },
folderId: string | null,
name: string,
): Promise<void> => {
const duplicate = await db.one(
`SELECT 1 AS taken FROM files
WHERE folder_id <=> ? AND active_name = ? AND deleted_at IS NULL
AND ( folder_id IS NOT NULL OR owner_id = ? )
LIMIT 1`,
[folderId, name, user.id],
);
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
};
export interface UploadInput {
name: string;
folderId: string | null;
declared: number;
mimeType: string;
body: ReadableStream<Uint8Array> | null;
}
/** Envoi direct (petits fichiers) : controle, ecriture disque et enregistrement. */
export const uploadFile = async (
db: Db,
config: Config,
user: SessionUser,
input: UploadInput,
): Promise<FileRow> => {
const { name, folderId, declared, mimeType, body } = input;
if (folderId !== null) {
const folder = await db.one(
"SELECT 1 AS present FROM folders WHERE id = ? AND deleted_at IS NULL",
[folderId],
);
if (!folder) throw AppError.notFound("Dossier introuvable.");
if (!(await canWrite(db, user, folderId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
}
const budget = await db.one<{
used_bytes: number;
quota_bytes: number;
max_file_bytes: number;
}>(
"SELECT used_bytes, quota_bytes, max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!budget) throw AppError.unauthorized();
if (declared > budget.max_file_bytes) {
throw AppError.payloadTooLarge(
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
);
}
if (BigInt(budget.used_bytes) + BigInt(declared) > BigInt(budget.quota_bytes)) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
await assertNameFree(db, user, folderId, name);
const disk = await diskUsage(config.MEDIA_DIR);
if (disk !== null && declared > disk.available_bytes) {
throw AppError.insufficientStorage(
"Espace disque insuffisant sur le serveur pour ce fichier.",
);
}
const location = await chooseLocation(db, BigInt(declared));
const id = randomUUID();
const relative = relativePathFor(location.slug, id, name);
const destination = absolutePath(config.MEDIA_DIR, relative);
const temporary = temporaryPath(config.MEDIA_DIR, location.slug);
await ensureDir(path.dirname(destination));
if (!body) throw AppError.badRequest("Corps de requete vide.");
let written;
try {
written = await writeBody(temporary, body, declared, budget.max_file_bytes);
} catch (error) {
await discard(temporary);
throw error;
}
await publish(temporary, destination);
try {
await db.transaction(async (connection) => {
const [quota] = await connection.execute(
`UPDATE users SET used_bytes = used_bytes + ?
WHERE id = ? AND used_bytes + ? <= quota_bytes`,
[written.size, user.id, written.size],
);
if ((quota as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
const [inserted] = await connection.execute(
`INSERT INTO files
(id, storage_location_id, folder_id, name, mime_type, size_bytes,
checksum_sha256, relative_path, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
location.id,
folderId,
name,
mimeType,
written.size,
written.checksum,
relative,
user.id,
user.id,
],
);
const [support] = await connection.execute(
`UPDATE storage_locations
SET used_bytes = used_bytes + ?
WHERE id = ? AND (quota_bytes IS NULL OR used_bytes + ? <= quota_bytes)`,
[written.size, location.id, written.size],
);
if ((support as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
}
void inserted;
});
} catch (error) {
await discard(destination);
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
await indexMedia(db, config, id, mimeType, destination).catch(() => undefined);
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, id]);
};
/** Liste les fichiers d'un dossier (ou de la racine). */
export const listFiles = async (
db: Db,
user: SessionUser,
folderId: string | null,
): Promise<FileRow[]> => {
if (folderId !== null && !(await canRead(db, user, folderId))) {
const readable = await db.one(
`SELECT 1 AS granted FROM folders f
WHERE f.id = ? AND f.deleted_at IS NULL AND f.owner_id = ? LIMIT 1`,
[folderId, user.id],
);
if (!readable) throw AppError.notFound("Dossier introuvable.");
}
return db.query<FileRow>(
`${SELECT_FILE}
WHERE f.deleted_at IS NULL
AND (f.folder_id <=> ?)
AND ( ? = 1
OR f.owner_id = ?
OR ( f.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f2
WHERE f2.id = f.folder_id AND f2.access_type = 'public' ) )
OR ( f.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f3
WHERE f3.id = f.folder_id
AND f3.owner_id = ? ) )
OR ( f.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = f.folder_id
AND fp.user_id = ?
AND fp.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
ORDER BY is_starred DESC, f.name`,
[user.id, folderId, 0, user.id, user.id, user.id],
);
};
/** Liste les fichiers etoiles de l'utilisateur. */
export const listFavorites = async (
db: Db,
user: SessionUser,
): Promise<(FileRow & { folder_name: string | null })[]> =>
db.query<FileRow & { folder_name: string | null }>(
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.checksum_sha256,
fi.relative_path, fi.owner_id, 1 AS is_starred, fi.download_count,
fi.created_at, fi.updated_at, fo.name AS folder_name
FROM files fi
JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
LEFT JOIN folders fo ON fo.id = fi.folder_id
WHERE fi.deleted_at IS NULL
AND ( fi.owner_id = ?
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = fi.folder_id AND f.deleted_at IS NULL
AND f.access_type = 'public' ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = fi.folder_id AND f.deleted_at IS NULL
AND f.owner_id = ? ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
AND fp.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
ORDER BY ufs.created_at DESC`,
[user.id, user.id, user.id, user.id],
);
/** Charge un fichier en verifiant la lisibilite (ou la gestion) de l'utilisateur. */
export const getFile = async (
db: Db,
user: SessionUser,
id: string,
options: { manage?: boolean } = {},
): Promise<FileRow> => {
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE f.id = ? AND f.deleted_at IS NULL`, [
user.id,
id,
]);
if (!row) throw AppError.notFound("Fichier introuvable.");
if (options.manage) {
const owner = row.owner_id !== null && row.owner_id === user.id;
const permitted =
owner || (row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!permitted) throw AppError.notFound("Fichier introuvable.");
return row;
}
const allowed =
(row.owner_id !== null && row.owner_id === user.id) ||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
if (!allowed) throw AppError.notFound("Fichier introuvable.");
return row;
};
export const renameFile = async (
db: Db,
user: SessionUser,
id: string,
name: string,
): Promise<FileRow> => {
const row = await getFile(db, user, id, { manage: true });
try {
await db.exec("UPDATE files SET name = ? WHERE id = ? AND deleted_at IS NULL", [name, row.id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
};
export const moveFile = async (
db: Db,
user: SessionUser,
id: string,
folderId: string | null,
): Promise<FileRow> => {
const row = await getFile(db, user, id, { manage: true });
if (folderId !== null && !(await canWrite(db, user, folderId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
try {
await db.exec("UPDATE files SET folder_id = ? WHERE id = ?", [folderId, row.id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un fichier du meme nom existe deja dans la destination.");
}
throw error;
}
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
};
export const toggleStar = async (db: Db, user: SessionUser, id: string): Promise<FileRow> => {
const row = await getFile(db, user, id);
const starred = await db.one(
"SELECT 1 AS mark FROM user_file_stars WHERE user_id = ? AND file_id = ?",
[user.id, row.id],
);
if (starred) {
await db.exec("DELETE FROM user_file_stars WHERE user_id = ? AND file_id = ?", [
user.id,
row.id,
]);
} else {
await db.exec("INSERT INTO user_file_stars (user_id, file_id) VALUES (?, ?)", [
user.id,
row.id,
]);
}
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
};
/** Deplace le fichier vers la corbeille (suppression logique). */
export const deleteFile = async (db: Db, user: SessionUser, id: string): Promise<FileRow> => {
const row = await getFile(db, user, id, { manage: true });
const result = await db.exec(
"UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
[row.id],
);
if (result.affectedRows === 0) throw AppError.notFound("Fichier introuvable.");
return row;
};
+290
View File
@@ -0,0 +1,290 @@
import { randomUUID } from "node:crypto";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { canManageFolder, canTraverse, canWrite } from "./auditService.js";
export 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`;
export 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 subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
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);
};
/** Liste les dossiers visibles sous un parent (racine si null). */
export const listFolders = async (
db: Db,
user: SessionUser,
parentId: string | null,
): Promise<FolderRow[]> => {
if (parentId !== null && !(await canTraverse(db, user, parentId))) {
throw AppError.notFound("Dossier introuvable.");
}
const rows = await db.query<FolderRow>(
`${SELECT_FOLDER}
WHERE f.deleted_at IS NULL
AND (f.parent_id <=> ?)
ORDER BY f.name`,
[parentId],
);
const visible: FolderRow[] = [];
for (const row of rows) {
if (row.owner_id === user.id || (await canTraverse(db, user, row.id))) {
visible.push(row);
}
}
return visible;
};
export const createFolder = async (
db: Db,
user: SessionUser,
name: string,
parentId: string | null,
): Promise<FolderRow> => {
if (parentId && !(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
AND ( parent_id IS NOT NULL OR owner_id = ? )
LIMIT 1`,
[parentId ?? null, name, user.id],
);
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;
}
return db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
};
export const renameFolder = async (
db: Db,
user: SessionUser,
id: string,
name: string,
): Promise<FolderRow> => {
const existing = await db.one<FolderRow>(
`${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.");
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;
}
return db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
};
export const moveFolder = async (
db: Db,
user: SessionUser,
id: string,
parentId: string | null,
): Promise<FolderRow> => {
const existing = await db.one<FolderRow>(
`${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.");
if (parentId !== null) {
if (!(await canWrite(db, user, parentId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier de destination.");
}
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, id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja dans la destination.");
}
throw error;
}
return db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
};
/** Deplace le dossier et son arborescence vers la corbeille. */
export const deleteFolder = async (
db: Db,
user: SessionUser,
id: string,
): Promise<FolderRow> => {
const existing = await db.one<FolderRow>(
`${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,
);
});
return existing;
};
export interface FolderPermissionRow {
user_id: string;
email: string;
first_name: string;
last_name: string;
level: string;
expires_at: string | null;
created_at: string;
}
export const listPermissions = async (
db: Db,
user: SessionUser,
id: string,
): Promise<FolderPermissionRow[]> => {
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const rows = await db.query<FolderPermissionRow>(
`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 rows;
};
export const grantPermission = async (
db: Db,
user: SessionUser,
id: string,
input: { email: string; level: string; expiresAt: string | null },
): Promise<{ email: string; level: string }> => {
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const target = await db.one<{ id: string }>(
"SELECT id FROM users WHERE active_email = ? AND deleted_at IS NULL",
[input.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 = input.expiresAt ? new Date(input.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, input.level, expires, user.id],
);
return { email: input.email, level: input.level };
};
export const revokePermission = async (
db: Db,
user: SessionUser,
id: string,
userId: string,
): Promise<void> => {
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.");
};
+201
View File
@@ -0,0 +1,201 @@
import { readFileSync } from "node:fs";
import { createTransport, type Transporter } from "nodemailer";
import type { Config } from "../config/appConfig.js";
export interface MailMessage {
to: string;
subject: string;
text: string;
html?: string;
}
export interface Mailer {
send: (message: MailMessage) => Promise<void>;
}
export interface Branding {
appName: string;
origin: string;
logoUrl: string;
color: string;
footer: string;
}
export interface MailContent {
preview: string;
heading: string;
intro: string;
paragraphs?: string[];
credentials?: { email: string; password: string };
cta?: { label: string; url: string };
note?: string;
}
export interface RenderedMail {
html: string;
text: string;
}
export const LOGO_CID = "cohaise-logo";
const LOGO_PATH = new URL("../../src/assets/logo.png", import.meta.url);
const loadLogo = (): Buffer | null => {
try {
return readFileSync(LOGO_PATH);
} catch {
return null;
}
};
const mailers = new WeakMap<Config, Mailer>();
/** Transport SMTP partage (un par configuration). */
export const getMailer = (config: Config): Mailer => {
const existing = mailers.get(config);
if (existing) return existing;
const mailer = createMailer(config);
mailers.set(config, mailer);
return mailer;
};
export const createMailer = (config: Config): Mailer => {
const transport: Transporter = createTransport({
host: config.SMTP_HOST,
port: config.SMTP_PORT,
secure: config.SMTP_SECURE,
...(config.SMTP_USER
? { auth: { user: config.SMTP_USER, pass: config.SMTP_PASSWORD ?? "" } }
: {}),
disableFileAccess: true,
disableUrlAccess: true,
});
const logo = config.MAIL_LOGO_URL ? null : loadLogo();
return {
send: async (message) => {
const inlineLogo = logo !== null && message.html?.includes(`cid:${LOGO_CID}`) === true;
await transport.sendMail({
from: config.SMTP_FROM,
to: message.to,
subject: message.subject,
text: message.text,
...(message.html ? { html: message.html } : {}),
...(inlineLogo
? { attachments: [{ filename: "logo.png", content: logo, cid: LOGO_CID }] }
: {}),
});
},
};
};
export const link = (config: Config, path: string): string =>
new URL(path, config.PUBLIC_ORIGIN).toString();
export const branding = (config: Config): Branding => ({
appName: "CoHaiSe Cloud",
origin: config.PUBLIC_ORIGIN,
logoUrl: config.MAIL_LOGO_URL ?? `cid:${LOGO_CID}`,
color: "#b71c1c",
footer: config.SMTP_FROM,
});
const escapeHtml = (value: string): string =>
value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
const FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif";
export const renderMail = (brand: Branding, content: MailContent): RenderedMail => {
const paragraphs = (content.paragraphs ?? [])
.map(
(paragraph) =>
`<p style="margin:0 0 16px;font-size:15px;line-height:1.6;color:#c9c2c2;text-align:center;">${escapeHtml(paragraph)}</p>`,
)
.join("");
const credentials = content.credentials
? `
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 auto 26px;max-width:420px;background:#1b1212;border:1px solid #332222;border-radius:10px;">
<tr><td style="padding:16px 18px;font-family:${FONT};text-align:left;">
<p style="margin:0 0 10px;font:600 12px ${FONT};letter-spacing:.04em;text-transform:uppercase;color:#9c9292;">Vos identifiants</p>
<p style="margin:0 0 6px;font:400 14px ${FONT};color:#c9c2c2;">Adresse : <strong style="color:#f7f5f5;">${escapeHtml(content.credentials.email)}</strong></p>
<p style="margin:0;font:400 14px ${FONT};color:#c9c2c2;">Mot de passe temporaire :
<span style="font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:14px;background:#241818;border:1px solid #3a2828;border-radius:6px;padding:2px 8px;color:#f7f5f5;">${escapeHtml(content.credentials.password)}</span>
</p>
</td></tr>
</table>`
: "";
const cta = content.cta
? `
<table role="presentation" cellpadding="0" cellspacing="0" align="center" style="margin:0 auto 26px;">
<tr><td align="center" style="background:${brand.color};border-radius:10px;">
<a href="${escapeHtml(content.cta.url)}" style="display:inline-block;padding:14px 32px;font:600 15px ${FONT};color:#ffffff;text-decoration:none;">${escapeHtml(content.cta.label)}</a>
</td></tr>
</table>`
: "";
const note = content.note
? `
<p style="margin:0;font:400 13px ${FONT};line-height:1.6;color:#8a8282;text-align:center;">${escapeHtml(content.note)}</p>`
: "";
const html = `<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="color-scheme" content="dark only">
<meta name="supported-color-schemes" content="dark only">
<title>${escapeHtml(content.heading)}</title>
</head>
<body style="margin:0;padding:0;background:#050000;">
<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:#050000;">${escapeHtml(content.preview)}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#050000;padding:32px 12px;">
<tr><td align="center">
<table role="presentation" width="560" cellpadding="0" cellspacing="0" style="width:100%;max-width:560px;background:#140d0d;border:1px solid #2a1c1c;border-radius:14px;overflow:hidden;">
<tr><td style="background:${brand.color};padding:17px 28px;text-align:center;">
<span style="font:700 14px ${FONT};letter-spacing:.18em;text-transform:uppercase;color:#ffffff;">${escapeHtml(brand.appName)}</span>
</td></tr>
<tr><td style="padding:40px 30px 6px;font-family:${FONT};text-align:center;">
<h1 style="margin:0 0 18px;font:700 28px ${FONT};line-height:1.25;color:#f7f5f5;">${escapeHtml(content.heading)}</h1>
<p style="margin:0 0 28px;font:400 15px ${FONT};line-height:1.65;color:#c9c2c2;">${escapeHtml(content.intro)}</p>
</td></tr>
<tr><td style="padding:0 30px 14px;font-family:${FONT};text-align:center;">
${paragraphs}${credentials}${cta}${note}
</td></tr>
<tr><td style="padding:20px 28px 24px;background:#0d0808;border-top:1px solid #2a1c1c;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0">
<tr>
<td style="vertical-align:middle;font-family:${FONT};">
<p style="margin:0 0 4px;font:400 12px ${FONT};line-height:1.6;color:#8a8282;">Message automatique : merci de ne pas repondre a cet e-mail.</p>
<p style="margin:0;font:400 12px ${FONT};line-height:1.6;color:#8a8282;">${escapeHtml(brand.footer)}</p>
</td>
<td align="right" style="vertical-align:middle;padding-left:16px;">
<img src="${escapeHtml(brand.logoUrl)}" width="44" height="44" alt="" style="display:block;border:0;border-radius:10px;background:#ffffff;">
</td>
</tr>
</table>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`;
const lines = [content.intro, ...(content.paragraphs ?? [])];
if (content.credentials) {
lines.push(`Adresse : ${content.credentials.email}`, `Mot de passe temporaire : ${content.credentials.password}`);
}
if (content.cta) lines.push(`${content.cta.label} : ${content.cta.url}`);
if (content.note) lines.push(content.note);
lines.push("", "Message automatique : merci de ne pas repondre a cet e-mail.", brand.footer);
return { html, text: lines.join("\n") };
};
+217
View File
@@ -0,0 +1,217 @@
import { randomUUID } from "node:crypto";
import { mkdir, stat } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { absolutePath } from "./storageService.js";
export type MediaKind = "image" | "video" | "audio" | "document" | "archive" | "other";
const THUMBNAIL_PX = 480;
export const classify = (mime: string | null): MediaKind => {
const value = (mime ?? "").toLowerCase();
if (value.startsWith("image/")) return "image";
if (value.startsWith("video/")) return "video";
if (value.startsWith("audio/")) return "audio";
if (
value === "application/pdf" ||
value.startsWith("text/") ||
value.includes("word") ||
value.includes("excel") ||
value.includes("presentation") ||
value.includes("opendocument")
) {
return "document";
}
if (
value.includes("zip") ||
value.includes("tar") ||
value.includes("gzip") ||
value.includes("rar") ||
value.includes("7z") ||
value.includes("compressed")
) {
return "archive";
}
return "other";
};
export const isImage = (mime: string | null): boolean =>
(mime ?? "").toLowerCase().startsWith("image/");
const isRasterImage = (mime: string | null): boolean => {
const value = (mime ?? "").toLowerCase();
return value.startsWith("image/") && value !== "image/svg+xml";
};
export const thumbnailRelativePath = (fileId: string): string =>
path.posix.join("thumbnails", `${fileId}.webp`);
interface ImageProbe {
width: number | null;
height: number | null;
orientation: number | null;
}
const probeImage = async (source: string): Promise<ImageProbe> => {
const meta = await sharp(source, { failOn: "none" }).metadata();
return {
width: meta.width ?? null,
height: meta.height ?? null,
orientation: meta.orientation ?? null,
};
};
interface ThumbnailResult {
width: number;
height: number;
size: number;
}
const writeThumbnail = async (source: string, destination: string): Promise<ThumbnailResult> => {
await mkdir(path.dirname(destination), { recursive: true });
const info = await sharp(source, { failOn: "none" })
.rotate()
.resize(THUMBNAIL_PX, THUMBNAIL_PX, { fit: "inside", withoutEnlargement: true })
.webp({ quality: 80 })
.toFile(destination);
return { width: info.width, height: info.height, size: info.size };
};
/** Indexe un fichier : classification, vignette et metadonnees d'image. */
export const indexMedia = async (
db: Db,
config: Config,
fileId: string,
mimeType: string | null,
source: string,
): Promise<void> => {
const kind = classify(mimeType);
if (!isRasterImage(mimeType)) {
await db.exec(
`INSERT INTO media_metadata (file_id, kind) VALUES (?, ?)
ON DUPLICATE KEY UPDATE kind = VALUES(kind)`,
[fileId, kind],
);
return;
}
const probe = await probeImage(source);
const relative = thumbnailRelativePath(fileId);
const thumbnail = await writeThumbnail(source, absolutePath(config.VARIANT_DIR, relative));
await db.exec(
`INSERT INTO file_variants
(id, file_id, purpose, format, path, size_bytes, width, height)
VALUES (?, ?, 'thumbnail', 'webp', ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE path = VALUES(path), size_bytes = VALUES(size_bytes),
width = VALUES(width), height = VALUES(height)`,
[randomUUID(), fileId, relative, thumbnail.size, thumbnail.width, thumbnail.height],
);
await db.exec(
`INSERT INTO media_metadata (file_id, kind, width, height, orientation)
VALUES (?, 'image', ?, ?, ?)
ON DUPLICATE KEY UPDATE kind = VALUES(kind), width = VALUES(width),
height = VALUES(height), orientation = VALUES(orientation)`,
[fileId, probe.width, probe.height, probe.orientation],
);
};
export const thumbnailSize = async (config: Config, relative: string): Promise<number | null> => {
try {
const info = await stat(absolutePath(config.VARIANT_DIR, relative));
return info.size;
} catch {
return null;
}
};
const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const;
export interface GalleryItem {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
is_starred: boolean;
kind: string | null;
width: number | null;
height: number | null;
created_at: string;
has_thumbnail: boolean;
}
/** Galerie des medias visibles, filtrable par type. */
export const gallery = async (
db: Db,
user: SessionUser,
kind: string,
limit: number,
offset: number,
): Promise<GalleryItem[]> => {
const rows = await db.query<{
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
is_starred: number;
kind: string | null;
width: number | null;
height: number | null;
created_at: string;
has_thumbnail: number;
}>(
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
(ufs.file_id IS NOT NULL) AS is_starred, mm.kind, mm.width, mm.height, fi.created_at,
EXISTS ( SELECT 1 FROM file_variants fv
WHERE fv.file_id = fi.id AND fv.purpose = 'thumbnail' ) AS has_thumbnail
FROM files fi
LEFT JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
LEFT JOIN media_metadata mm ON mm.file_id = fi.id
WHERE fi.deleted_at IS NULL
AND ( ? = '' OR mm.kind = ? )
AND ( ? = 1
OR fi.owner_id = ?
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f2
WHERE f2.id = fi.folder_id AND f2.owner_id = ? ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
AND fp.level IN ('read', 'write', 'admin')
AND ( fp.expires_at IS NULL
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
ORDER BY fi.created_at DESC
LIMIT ${limit} OFFSET ${offset}`,
[user.id, kind, kind, 0, user.id, user.id, user.id],
);
return rows.map((row) => ({
id: row.id,
folder_id: row.folder_id,
name: row.name,
mime_type: row.mime_type,
size_bytes: row.size_bytes,
owner_id: row.owner_id,
is_starred: row.is_starred === 1,
kind: row.kind,
width: row.width,
height: row.height,
created_at: row.created_at,
has_thumbnail: row.has_thumbnail === 1,
}));
};
export const galleryKinds = KINDS;
+111
View File
@@ -0,0 +1,111 @@
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
const escapeLike = (value: string): string =>
value.replace(/[\\%_]/g, (match) => `\\${match}`);
const LIMIT = 100;
export interface SearchResult {
query: string;
folders: {
id: string;
parent_id: string | null;
name: string;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
}[];
files: {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
is_starred: boolean;
created_at: string;
updated_at: string;
}[];
}
/** Recherche globale dans les dossiers et fichiers visibles. */
export const search = async (db: Db, user: SessionUser, q: string): Promise<SearchResult> => {
const pattern = `%${escapeLike(q).slice(0, 110)}%`;
const folders = await db.query<SearchResult["folders"][number]>(
`SELECT f.id, f.parent_id, f.name, f.owner_id,
f.access_type, f.created_at, f.updated_at
FROM folders f
WHERE f.deleted_at IS NULL
AND f.name LIKE ?
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
LIMIT ${LIMIT}`,
[pattern, 0, user.id, user.id],
);
const files = await db.query<{
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
is_starred: number;
created_at: string;
updated_at: string;
}>(
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
(ufs.file_id IS NOT NULL) AS is_starred, fi.created_at, fi.updated_at
FROM files fi
LEFT JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
WHERE fi.deleted_at IS NULL
AND fi.name LIKE ?
AND ( ? = 1
OR fi.owner_id = ?
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f2
WHERE f2.id = fi.folder_id AND f2.owner_id = ? ) )
OR ( fi.folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
ORDER BY fi.name
LIMIT ${LIMIT}`,
[user.id, pattern, 0, user.id, user.id, user.id],
);
return {
query: q,
folders: folders.map((row) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
owner_id: row.owner_id,
access_type: row.access_type,
created_at: row.created_at,
updated_at: row.updated_at,
})),
files: files.map((row) => ({
id: row.id,
folder_id: row.folder_id,
name: row.name,
mime_type: row.mime_type,
size_bytes: row.size_bytes,
owner_id: row.owner_id,
is_starred: row.is_starred === 1,
created_at: row.created_at,
updated_at: row.updated_at,
})),
};
};
+196
View File
@@ -0,0 +1,196 @@
import { createHash, randomUUID } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
import { mkdir, open, readdir, rename, rm, stat, statfs } from "node:fs/promises";
import path from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { AppError } from "../utils/errors.js";
import type { Db } from "../config/db.js";
const SLUG = /^[a-z0-9][a-z0-9-]{0,99}$/;
const EXTENSION = /^[.][a-z0-9]{1,10}$/i;
export interface StoredLocation {
id: number;
slug: string;
}
const extensionOf = (name: string): string => {
const ext = path.posix.extname(name);
return EXTENSION.test(ext) ? ext.toLowerCase() : "";
};
export const relativePathFor = (slug: string, uuid: string, name: string): string =>
path.posix.join(slug, uuid + extensionOf(name));
const resolveInside = (mediaDir: string, relative: string): string => {
const base = path.resolve(mediaDir);
const target = path.resolve(base, relative);
if (target !== base && !target.startsWith(base + path.sep)) {
throw AppError.badRequest("Chemin de stockage invalide.");
}
return target;
};
export const absolutePath = (mediaDir: string, relative: string): string =>
resolveInside(mediaDir, relative);
export const chooseLocation = async (db: Db, bytes: bigint): Promise<StoredLocation> => {
const rows = await db.query<{ id: number; slug: string; remaining: number | null }>(
`SELECT id, slug,
CASE WHEN quota_bytes IS NULL THEN NULL
ELSE quota_bytes - used_bytes END AS remaining
FROM storage_locations
WHERE is_active = 1 AND deleted_at IS NULL
ORDER BY (remaining IS NULL) DESC, remaining DESC, id
LIMIT 1`,
);
const row = rows[0];
if (!row || !SLUG.test(row.slug)) {
throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible.");
}
if (row.remaining !== null && BigInt(row.remaining) < bytes) {
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
}
return { id: row.id, slug: row.slug };
};
interface WriteResult {
size: number;
checksum: string;
}
export const writeBody = async (
destination: string,
body: ReadableStream<Uint8Array>,
declared: number,
maxBytes: number,
): Promise<WriteResult> => {
const hash = createHash("sha256");
let received = 0;
const meter = new Transform({
transform(chunk: Buffer, _encoding, callback) {
received += chunk.length;
if (received > maxBytes) {
callback(AppError.payloadTooLarge(`Fichier trop volumineux (maximum ${maxBytes} octets).`));
return;
}
hash.update(chunk);
callback(null, chunk);
},
});
const source = Readable.fromWeb(body as Parameters<typeof Readable.fromWeb>[0]);
await pipeline(source, meter, createWriteStream(destination, { flags: "wx" }));
if (received !== declared) {
throw AppError.badRequest(
`Longueur incoherente : ${declared} octets annonces, ${received} recus.`,
);
}
return { size: received, checksum: hash.digest("hex") };
};
export const ensureDir = async (directory: string): Promise<void> => {
await mkdir(directory, { recursive: true });
};
export const publish = async (temporary: string, destination: string): Promise<void> => {
await rename(temporary, destination);
};
export const discard = async (...paths: string[]): Promise<void> => {
await Promise.all(paths.map((entry) => rm(entry, { force: true }).catch(() => undefined)));
};
export const temporaryPath = (mediaDir: string, slug: string): string =>
path.join(path.resolve(mediaDir), slug, `.upload-${randomUUID()}`);
export const uploadTempDir = (mediaDir: string): string =>
path.join(path.resolve(mediaDir), ".uploads");
export const uploadTempPath = (mediaDir: string, id: string): string =>
path.join(uploadTempDir(mediaDir), `${id}.part`);
export const preallocateUpload = async (destination: string, size: number): Promise<void> => {
await ensureDir(path.dirname(destination));
const handle = await open(destination, "wx");
try {
await handle.truncate(size);
} finally {
await handle.close();
}
};
export const writeChunk = async (
destination: string,
offset: number,
body: ReadableStream<Uint8Array>,
maxBytes: number,
): Promise<number> => {
let received = 0;
const meter = new Transform({
transform(chunk: Buffer, _encoding, callback) {
received += chunk.length;
if (received > maxBytes) {
callback(AppError.payloadTooLarge(`Morceau trop volumineux (maximum ${maxBytes} octets).`));
return;
}
callback(null, chunk);
},
});
const source = Readable.fromWeb(body as Parameters<typeof Readable.fromWeb>[0]);
await pipeline(source, meter, createWriteStream(destination, { flags: "r+", start: offset }));
return received;
};
export const hashFile = async (absolute: string): Promise<string> => {
const hash = createHash("sha256");
for await (const chunk of createReadStream(absolute)) {
hash.update(chunk as Buffer);
}
return hash.digest("hex");
};
export const listUploadTemps = async (mediaDir: string): Promise<string[]> => {
const entries = await readdir(uploadTempDir(mediaDir)).catch(() => []);
return entries
.filter((entry) => entry.endsWith(".part"))
.map((entry) => path.join(uploadTempDir(mediaDir), entry));
};
export const fileExists = async (absolute: string): Promise<boolean> => {
try {
const info = await stat(absolute);
return info.isFile();
} catch {
return false;
}
};
export const openForDownload = (absolute: string, range?: { start: number; end: number }) =>
createReadStream(absolute, range);
export interface DiskUsage {
total_bytes: number;
free_bytes: number;
available_bytes: number;
}
export const diskUsage = async (target: string): Promise<DiskUsage | null> => {
try {
const info = await statfs(target, { bigint: true });
return {
total_bytes: Number(info.blocks * info.bsize),
free_bytes: Number(info.bfree * info.bsize),
available_bytes: Number(info.bavail * info.bsize),
};
} catch {
return null;
}
};
+337
View File
@@ -0,0 +1,337 @@
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { absolutePath, discard } from "./storageService.js";
export interface TrashFileRow {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
owner_id: string | null;
created_at: string;
updated_at: string;
deleted_at: string;
}
export interface TrashFolderRow {
id: string;
parent_id: string | null;
name: string;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
deleted_at: string;
}
const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
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);
};
const restoreAncestors = async (db: Db, folderId: string | null): Promise<void> => {
let current = folderId;
const guard = new Set<string>();
while (current !== null && !guard.has(current)) {
guard.add(current);
const parent = await db.one<{ parent_id: string | null }>(
"SELECT parent_id FROM folders WHERE id = ?",
[current],
);
if (!parent) break;
await db.exec("UPDATE folders SET deleted_at = NULL WHERE id = ?", [current]);
current = parent.parent_id;
}
};
const purgeFiles = async (db: Db, config: Config, fileIds: string[]): Promise<void> => {
if (fileIds.length === 0) return;
const placeholders = fileIds.map(() => "?").join(",");
const rows = await db.query<{
id: string;
relative_path: string;
size_bytes: number;
owner_id: string | null;
storage_location_id: number;
}>(
`SELECT id, relative_path, size_bytes, owner_id, storage_location_id
FROM files WHERE id IN (${placeholders})`,
fileIds,
);
const variants = await db.query<{ path: string }>(
`SELECT path FROM file_variants WHERE file_id IN (${placeholders})`,
fileIds,
);
await Promise.all([
...rows.map((row) => discard(absolutePath(config.MEDIA_DIR, row.relative_path))),
...variants.map((variant) => discard(absolutePath(config.VARIANT_DIR, variant.path))),
]);
await db.transaction(async (connection) => {
for (const row of rows) {
if (row.owner_id) {
await connection.execute(
"UPDATE users SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
[row.size_bytes, row.owner_id],
);
}
await connection.execute(
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
[row.size_bytes, row.storage_location_id],
);
}
await connection.execute(`DELETE FROM files WHERE id IN (${placeholders})`, fileIds);
});
};
const purgeFolderTree = async (db: Db, config: Config, rootId: string): Promise<void> => {
const folderIds = await subtreeIds(db, rootId);
const folderPlaceholders = folderIds.map(() => "?").join(",");
const files = await db.query<{ id: string }>(
`SELECT id FROM files WHERE folder_id IN (${folderPlaceholders})`,
folderIds,
);
await purgeFiles(db, config, files.map((row) => row.id));
await db.exec(`DELETE FROM folders WHERE id IN (${folderPlaceholders})`, folderIds);
};
export const publicTrashFolder = (row: TrashFolderRow) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
owner_id: row.owner_id,
access_type: row.access_type,
created_at: row.created_at,
updated_at: row.updated_at,
deleted_at: row.deleted_at,
});
export const publicTrashFile = (row: TrashFileRow) => ({
id: row.id,
folder_id: row.folder_id,
name: row.name,
mime_type: row.mime_type,
size_bytes: row.size_bytes,
owner_id: row.owner_id,
created_at: row.created_at,
updated_at: row.updated_at,
deleted_at: row.deleted_at,
});
export interface TrashContent {
retentionDays: number;
folders: TrashFolderRow[];
files: TrashFileRow[];
}
/** Contenu de la corbeille de l'utilisateur. */
export const listTrash = async (db: Db, user: SessionUser): Promise<TrashContent> => {
const folders = await db.query<TrashFolderRow>(
`SELECT f.id, f.parent_id, f.name, f.owner_id, f.access_type,
f.created_at, f.updated_at, f.deleted_at
FROM folders f
LEFT JOIN folders p ON p.id = f.parent_id
WHERE f.deleted_at IS NOT NULL
AND f.is_system = 0
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND f.owner_id = ?
ORDER BY f.deleted_at DESC`,
[user.id],
);
const files = await db.query<TrashFileRow>(
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
fi.created_at, fi.updated_at, fi.deleted_at
FROM files fi
LEFT JOIN folders p ON p.id = fi.folder_id
WHERE fi.deleted_at IS NOT NULL
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND fi.owner_id = ?
ORDER BY fi.deleted_at DESC`,
[user.id],
);
const retentionDays = await db.one<{ setting_value: string }>(
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
);
return {
retentionDays: retentionDays ? Number(retentionDays.setting_value) : 30,
folders,
files,
};
};
export const restoreFolder = async (
db: Db,
user: SessionUser,
id: string,
): Promise<TrashFolderRow> => {
const row = await db.one<TrashFolderRow>(
`SELECT id, parent_id, name, owner_id, access_type, created_at, updated_at, deleted_at
FROM folders
WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0`,
[id],
);
if (!row || row.owner_id !== user.id) throw AppError.notFound("Dossier introuvable.");
await restoreAncestors(db, row.parent_id);
const folderIds = await subtreeIds(db, id);
const placeholders = folderIds.map(() => "?").join(",");
try {
await db.transaction(async (connection) => {
await connection.execute(
`UPDATE folders SET deleted_at = NULL WHERE id IN (${placeholders})`,
folderIds,
);
await connection.execute(
`UPDATE files SET deleted_at = NULL WHERE folder_id IN (${placeholders})`,
folderIds,
);
});
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un element du meme nom occupe deja cet emplacement.");
}
throw error;
}
return row;
};
export const restoreFile = async (
db: Db,
user: SessionUser,
id: string,
): Promise<TrashFileRow> => {
const row = await db.one<TrashFileRow>(
`SELECT id, folder_id, name, mime_type, size_bytes, owner_id, created_at, updated_at, deleted_at
FROM files WHERE id = ? AND deleted_at IS NOT NULL`,
[id],
);
if (!row || row.owner_id !== user.id) throw AppError.notFound("Fichier introuvable.");
await restoreAncestors(db, row.folder_id);
try {
await db.exec("UPDATE files SET deleted_at = NULL WHERE id = ?", [id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un fichier du meme nom existe deja dans ce dossier.");
}
throw error;
}
return row;
};
/** Suppression definitive d'un dossier corbeille et de son arborescence. */
export const purgeFolder = async (
db: Db,
config: Config,
user: SessionUser,
id: string,
): Promise<TrashFolderRow> => {
const row = await db.one<TrashFolderRow>(
`SELECT id, parent_id, name, owner_id, access_type, created_at, updated_at, deleted_at
FROM folders
WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0`,
[id],
);
if (!row || row.owner_id !== user.id) throw AppError.notFound("Dossier introuvable.");
await purgeFolderTree(db, config, id);
return row;
};
/** Suppression definitive d'un fichier corbeille. */
export const purgeFile = async (
db: Db,
config: Config,
user: SessionUser,
id: string,
): Promise<TrashFileRow> => {
const row = await db.one<TrashFileRow>(
`SELECT id, folder_id, name, mime_type, size_bytes, owner_id, created_at, updated_at, deleted_at
FROM files WHERE id = ? AND deleted_at IS NOT NULL`,
[id],
);
if (!row || row.owner_id !== user.id) throw AppError.notFound("Fichier introuvable.");
await purgeFiles(db, config, [id]);
return row;
};
/** Vide la corbeille de l'utilisateur. */
export const emptyTrash = async (
db: Db,
config: Config,
user: SessionUser,
): Promise<{ folders: number; files: number }> => {
const folders = await db.query<{ id: string }>(
`SELECT f.id FROM folders f
LEFT JOIN folders p ON p.id = f.parent_id
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND f.owner_id = ?`,
[user.id],
);
const files = await db.query<{ id: string }>(
`SELECT fi.id FROM files fi
LEFT JOIN folders p ON p.id = fi.folder_id
WHERE fi.deleted_at IS NOT NULL
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND fi.owner_id = ?`,
[user.id],
);
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
await purgeFiles(db, config, files.map((row) => row.id));
return { folders: folders.length, files: files.length };
};
/** Purge automatique des elements expirant (retention configurable). */
export const purgeExpiredTrash = async (db: Db, config: Config): Promise<number> => {
const setting = await db.one<{ setting_value: string }>(
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
);
const days = setting ? Number(setting.setting_value) : 30;
if (!Number.isFinite(days) || days <= 0) return 0;
const folders = await db.query<{ id: string }>(
`SELECT f.id FROM folders f
LEFT JOIN folders p ON p.id = f.parent_id
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND f.deleted_at < UTC_TIMESTAMP() - INTERVAL ? DAY
ORDER BY f.deleted_at`,
[days],
);
const files = await db.query<{ id: string }>(
`SELECT fi.id FROM files fi
LEFT JOIN folders p ON p.id = fi.folder_id
WHERE fi.deleted_at IS NOT NULL
AND (p.id IS NULL OR p.deleted_at IS NULL)
AND fi.deleted_at < UTC_TIMESTAMP() - INTERVAL ? DAY
ORDER BY fi.deleted_at`,
[days],
);
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
await purgeFiles(db, config, files.map((row) => row.id));
return folders.length + files.length;
};
+376
View File
@@ -0,0 +1,376 @@
import { randomUUID } from "node:crypto";
import { stat } from "node:fs/promises";
import path from "node:path";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import type { FileRow, SessionUser } from "../models/types.js";
import { AppError } from "../utils/errors.js";
import { canWrite } from "./auditService.js";
import { indexMedia } from "./mediaService.js";
import { assertNameFree, SELECT_FILE } from "./fileService.js";
import {
absolutePath,
chooseLocation,
discard,
diskUsage,
ensureDir,
fileExists,
hashFile,
listUploadTemps,
preallocateUpload,
publish,
relativePathFor,
uploadTempPath,
writeChunk,
} from "./storageService.js";
export const CHUNK_SIZE = 50 * 1024 * 1024;
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
interface UploadSessionRow {
id: string;
user_id: string;
folder_id: string | null;
storage_location_id: number;
name: string;
mime_type: string | null;
size_bytes: number | string;
received_bytes: number | string;
chunk_size: number;
relative_path: string;
temp_path: string;
expires_at: string | Date;
}
const SELECT_SESSION = `SELECT id, user_id, folder_id, storage_location_id, name, mime_type,
size_bytes, received_bytes, chunk_size, relative_path, temp_path, expires_at
FROM upload_sessions`;
export const sessionPublic = (row: UploadSessionRow) => ({
uploadId: row.id,
name: row.name,
folderId: row.folder_id,
size: Number(row.size_bytes),
chunkSize: row.chunk_size,
uploadedBytes: Number(row.received_bytes),
expiresAt: new Date(row.expires_at).toISOString(),
});
export type UploadSession = ReturnType<typeof sessionPublic>;
const dropSession = async (db: Db, row: UploadSessionRow): Promise<void> => {
await discard(row.temp_path);
await db.exec("DELETE FROM upload_sessions WHERE id = ?", [row.id]).catch(() => undefined);
};
const loadSession = async (
db: Db,
user: { id: string },
id: string,
): Promise<UploadSessionRow> => {
const row = await db.one<UploadSessionRow>(`${SELECT_SESSION} WHERE id = ? AND user_id = ?`, [
id,
user.id,
]);
if (!row) throw AppError.notFound("Session d'envoi introuvable.");
if (new Date(row.expires_at).getTime() <= Date.now()) {
await dropSession(db, row);
throw AppError.notFound("Session d'envoi expiree.");
}
return row;
};
export interface CreateUploadInput {
name: string;
folderId: string | null;
size: number;
mimeType: string;
}
/** Cree une session d'envoi morcele avec preallocation du fichier temporaire. */
export const createUploadSession = async (
db: Db,
config: Config,
user: SessionUser,
input: CreateUploadInput,
): Promise<UploadSession> => {
const { name, folderId, size, mimeType } = input;
if (folderId !== null && !(await canWrite(db, user, folderId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
const budget = await db.one<{
used_bytes: number | string;
quota_bytes: number | string;
max_file_bytes: number | string;
}>(
"SELECT used_bytes, quota_bytes, max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!budget) throw AppError.unauthorized();
const pending = await db.one<{ bytes: number | string | null }>(
`SELECT COALESCE(SUM(size_bytes - received_bytes), 0) AS bytes
FROM upload_sessions
WHERE user_id = ? AND expires_at > UTC_TIMESTAMP()`,
[user.id],
);
if (BigInt(size) > BigInt(budget.max_file_bytes)) {
throw AppError.payloadTooLarge(
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
);
}
if (
BigInt(budget.used_bytes) + BigInt(pending?.bytes ?? 0) + BigInt(size) >
BigInt(budget.quota_bytes)
) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
await assertNameFree(db, user, folderId, name);
const disk = await diskUsage(config.MEDIA_DIR);
if (disk !== null && BigInt(size) > BigInt(disk.available_bytes)) {
throw AppError.insufficientStorage(
"Espace disque insuffisant sur le serveur pour ce fichier.",
);
}
const location = await chooseLocation(db, BigInt(size));
const id = randomUUID();
const relative = relativePathFor(location.slug, id, name);
const temporary = uploadTempPath(config.MEDIA_DIR, id);
await preallocateUpload(temporary, size);
try {
await db.exec(
`INSERT INTO upload_sessions
(id, user_id, folder_id, storage_location_id, name, mime_type, size_bytes,
received_bytes, chunk_size, relative_path, temp_path, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`,
[
id,
user.id,
folderId,
location.id,
name,
mimeType,
size,
CHUNK_SIZE,
relative,
temporary,
new Date(Date.now() + SESSION_TTL_MS),
],
);
} catch (error) {
await discard(temporary);
throw error;
}
const created = await db.required<UploadSessionRow>(`${SELECT_SESSION} WHERE id = ?`, [id]);
return sessionPublic(created);
};
export const getUploadSession = async (
db: Db,
user: SessionUser,
id: string,
): Promise<UploadSession> => {
const row = await loadSession(db, user, id);
return sessionPublic(row);
};
/** Ecrit un morceau a l'offset attendu et met a jour la progression. */
export const receiveChunk = async (
db: Db,
user: SessionUser,
id: string,
body: ReadableStream<Uint8Array>,
declared: number,
): Promise<UploadSession> => {
const row = await loadSession(db, user, id);
const offset = Number(row.received_bytes);
const size = Number(row.size_bytes);
if (declared > row.chunk_size) {
throw AppError.payloadTooLarge(`Morceau trop volumineux (maximum ${row.chunk_size} octets).`);
}
if (offset + declared > size) {
throw AppError.badRequest("Le morceau depasse la taille annoncee du fichier.");
}
const written = await writeChunk(row.temp_path, offset, body, declared);
if (written !== declared) {
throw AppError.badRequest(
`Longueur incoherente : ${declared} octets annonces, ${written} recus.`,
);
}
const reserved = await db.exec(
`UPDATE upload_sessions
SET received_bytes = received_bytes + ?
WHERE id = ? AND user_id = ? AND received_bytes = ?
AND received_bytes + ? <= size_bytes AND expires_at > UTC_TIMESTAMP()`,
[declared, row.id, user.id, offset, declared],
);
if (reserved.affectedRows === 0) {
const fresh = await db.one<UploadSessionRow>(
`${SELECT_SESSION} WHERE id = ? AND user_id = ?`,
[row.id, user.id],
);
if (!fresh) throw AppError.notFound("Session d'envoi introuvable.");
if (Number(fresh.received_bytes) < offset + declared) {
throw AppError.conflict("Morceau deja recu ou session modifiee. Reprenez depuis le statut.");
}
return sessionPublic(fresh);
}
return sessionPublic({ ...row, received_bytes: offset + declared });
};
/** Finalise l'envoi : controle, publication et enregistrement du fichier. */
export const completeUpload = async (
db: Db,
config: Config,
user: SessionUser,
id: string,
): Promise<FileRow> => {
const row = await loadSession(db, user, id);
const size = Number(row.size_bytes);
const received = Number(row.received_bytes);
if (received !== size) {
throw AppError.badRequest("Envoi incomplet : des morceaux sont encore manquants.");
}
if (!(await fileExists(row.temp_path))) {
await dropSession(db, row);
throw AppError.notFound("Fichier temporaire introuvable. Relancez l'envoi.");
}
const budget = await db.one<{ max_file_bytes: number | string }>(
"SELECT max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
[user.id],
);
if (!budget) {
await dropSession(db, row);
throw AppError.unauthorized();
}
if (BigInt(size) > BigInt(budget.max_file_bytes)) {
await dropSession(db, row);
throw AppError.payloadTooLarge(
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
);
}
if (row.folder_id !== null && !(await canWrite(db, user, row.folder_id))) {
await dropSession(db, row);
throw AppError.forbidden("Vous ne pouvez plus ecrire dans ce dossier.");
}
try {
await assertNameFree(db, user, row.folder_id, row.name);
} catch (error) {
await dropSession(db, row);
throw error;
}
const checksum = await hashFile(row.temp_path);
const destination = absolutePath(config.MEDIA_DIR, row.relative_path);
await ensureDir(path.dirname(destination));
await publish(row.temp_path, destination);
try {
await db.transaction(async (connection) => {
const [quota] = await connection.execute(
`UPDATE users SET used_bytes = used_bytes + ?
WHERE id = ? AND used_bytes + ? <= quota_bytes`,
[size, user.id, size],
);
if ((quota as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
}
const [support] = await connection.execute(
`UPDATE storage_locations
SET used_bytes = used_bytes + ?
WHERE id = ? AND (quota_bytes IS NULL OR used_bytes + ? <= quota_bytes)`,
[size, row.storage_location_id, size],
);
if ((support as { affectedRows: number }).affectedRows === 0) {
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
}
await connection.execute(
`INSERT INTO files
(id, storage_location_id, folder_id, name, mime_type, size_bytes,
checksum_sha256, relative_path, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
row.id,
row.storage_location_id,
row.folder_id,
row.name,
row.mime_type ?? "application/octet-stream",
size,
checksum,
row.relative_path,
user.id,
user.id,
],
);
await connection.execute("DELETE FROM upload_sessions WHERE id = ?", [row.id]);
});
} catch (error) {
await publish(destination, row.temp_path).catch(async () => {
await discard(destination);
await db.exec("DELETE FROM upload_sessions WHERE id = ?", [row.id]).catch(() => undefined);
});
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
await indexMedia(db, config, row.id, row.mime_type ?? "application/octet-stream", destination).catch(
() => undefined,
);
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
};
export const cancelUpload = async (
db: Db,
user: SessionUser,
id: string,
): Promise<UploadSessionRow> => {
const row = await loadSession(db, user, id);
await dropSession(db, row);
return row;
};
/** Purge les sessions d'envoi expirees et leurs fichiers temporaires. */
export const purgeExpiredUploads = async (db: Db, config: Config): Promise<number> => {
const expired = await db.query<UploadSessionRow>(
`${SELECT_SESSION} WHERE expires_at <= UTC_TIMESTAMP()`,
);
for (const row of expired) await discard(row.temp_path);
const result = await db.exec("DELETE FROM upload_sessions WHERE expires_at <= UTC_TIMESTAMP()");
const cutoff = Date.now() - SESSION_TTL_MS;
for (const temporary of await listUploadTemps(config.MEDIA_DIR)) {
const info = await stat(temporary).catch(() => null);
if (info !== null && info.mtimeMs < cutoff) await discard(temporary);
}
return result.affectedRows;
};