diff --git a/.env.example b/.env.example
index e6055d4..a211477 100644
--- a/.env.example
+++ b/.env.example
@@ -47,6 +47,9 @@ SMTP_PASSWORD=
SMTP_FROM=
# true si le serveur SMTP exige TLS des la connexion (port 465).
SMTP_SECURE=false
+# Logo des courriels. Par defaut PUBLIC_ORIGIN/logo.png ; a surcharger si le
+# logo est heberge ailleurs. URL joignable depuis Internet.
+MAIL_LOGO_URL=
# --- Limitation des connexions -------------------------------------------
# Tentatives de connexion autorisees par fenetre et par IP.
diff --git a/Makefile b/Makefile
index 7643f3b..76f9a89 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
COMPOSE=docker compose
-.PHONY: help up down build logs ps front front-build db migrate admin backup dev typecheck check
+.PHONY: help up down build logs ps front front-build db migrate admin backup purge-logs reset dev typecheck check
help:
@echo "CoHaiSe Cloud"
@@ -20,6 +20,8 @@ help:
@echo " make migrate Appliquer les migrations SQL"
@echo " make backup Sauvegarder la base dans ./backups"
@echo " make admin ARGS=... Creer ou reinitialiser un compte"
+ @echo " make purge-logs Vider le journal d'audit"
+ @echo " make reset Cloud vierge, hors administrateurs"
@echo ""
@echo "Developpement, sans Docker"
@echo " make dev Vite sur 5174, API sur 3101"
@@ -75,6 +77,25 @@ backup:
admin:
$(COMPOSE) run --rm --no-deps api node dist/admin.js $(ARGS)
+# Vide le journal d'audit. La base est deja en marche : la commande passe par
+# le conteneur, aucun client MariaDB n'est requis sur l'hote.
+purge-logs:
+ $(COMPOSE) exec -T db sh -c 'mariadb --password="$$MARIADB_ROOT_PASSWORD" "$$MARIADB_DATABASE" -e "DELETE FROM audit_logs;"'
+ @echo " journal d'audit vide"
+
+# Repart d'un cloud vierge : fichiers, dossiers, partages, sessions et jetons
+# sont supprimes, les administrateurs sont conserves. Les medias sur disque
+# sont effaces dans la foulee.
+reset:
+ @printf "Cette commande efface toutes les donnees sauf les administrateurs. Continuer ? [o/N] "; \
+ read answer; \
+ if [ "$$answer" != "o" ] && [ "$$answer" != "O" ] && [ "$$answer" != "y" ]; then \
+ echo " annule"; exit 1; \
+ fi
+ $(COMPOSE) exec -T db sh -c 'mariadb --password="$$MARIADB_ROOT_PASSWORD" "$$MARIADB_DATABASE"' < docker/reset-cloud.sql
+ $(COMPOSE) run --rm --no-deps --entrypoint sh api -c 'find /data/media -mindepth 1 -delete'
+ @echo " cloud remis a zero"
+
dev:
npm run dev --workspace=frontend
diff --git a/backend/src/lib/config.ts b/backend/src/lib/config.ts
index a7d99bb..ffffc78 100644
--- a/backend/src/lib/config.ts
+++ b/backend/src/lib/config.ts
@@ -59,6 +59,14 @@ const schema = z.object({
SMTP_PASSWORD: z.string().optional().transform((v) => (v ? v : null)),
SMTP_FROM: z.string().min(3),
SMTP_SECURE: bool(false),
+ /**
+ * Logo des courriels. Par defaut celui publie par le front
+ * (`PUBLIC_ORIGIN/logo.png`) ; l'URL doit etre joignable depuis Internet.
+ */
+ MAIL_LOGO_URL: z
+ .string()
+ .optional()
+ .transform((v) => (v ? v : null)),
// Limitation des tentatives de connexion, appliquee dans le processus.
RATE_LIMIT_LOGIN_MAX: positiveInt(10),
diff --git a/backend/src/lib/errors.ts b/backend/src/lib/errors.ts
index 5e6d87a..3c81928 100644
--- a/backend/src/lib/errors.ts
+++ b/backend/src/lib/errors.ts
@@ -41,6 +41,9 @@ export class AppError extends Error {
static serviceUnavailable(message = "Service momentanement indisponible.") {
return new AppError(503, "UNAVAILABLE", message);
}
+ static insufficientStorage(message = "Espace de stockage insuffisant sur le serveur.") {
+ return new AppError(507, "INSUFFICIENT_STORAGE", message);
+ }
}
export interface SafeError {
diff --git a/backend/src/lib/index.ts b/backend/src/lib/index.ts
index ca4ba65..c8f191e 100644
--- a/backend/src/lib/index.ts
+++ b/backend/src/lib/index.ts
@@ -41,6 +41,13 @@ export {
type MigrationResult,
} from "./migrate.js";
export { createMailer, link, type Mailer, type MailMessage } from "./mail.js";
+export {
+ branding,
+ renderMail,
+ type Branding,
+ type MailContent,
+ type RenderedMail,
+} from "./mail-template.js";
export { createRateLimiter, rateLimitKey, type RateLimiter } from "./ratelimit.js";
export {
prepareService,
diff --git a/backend/src/lib/mail-template.ts b/backend/src/lib/mail-template.ts
new file mode 100644
index 0000000..9798b0c
--- /dev/null
+++ b/backend/src/lib/mail-template.ts
@@ -0,0 +1,133 @@
+import type { Config } from "./config.js";
+
+/**
+ * Gabarit de courriel de marque, sans dependance ni feuille de style externe :
+ * les clients de messagerie n'interpretent qu'une partie du CSS, tout est donc
+ * ecrit en ligne et pose sur des tableaux, y compris pour Outlook.
+ */
+
+export interface Branding {
+ appName: string;
+ origin: string;
+ logoUrl: string;
+ color: string;
+ /** Adresse d'expedition, reprise en pied pour dire ou ne pas repondre. */
+ footer: string;
+}
+
+export const branding = (config: Config): Branding => ({
+ appName: "CoHaiSe Cloud",
+ origin: config.PUBLIC_ORIGIN,
+ logoUrl: config.MAIL_LOGO_URL ?? new URL("/logo.png", config.PUBLIC_ORIGIN).toString(),
+ color: "#b71c1c",
+ footer: config.SMTP_FROM,
+});
+
+export interface MailContent {
+ /** Aperçu affiche par le client, avant ouverture (texte brut). */
+ preview: string;
+ heading: string;
+ intro: string;
+ paragraphs?: string[];
+ /** Identifiants d'acces, presentes dans un encadre monospace. */
+ credentials?: { email: string; password: string };
+ cta?: { label: string; url: string };
+ note?: string;
+}
+
+export interface RenderedMail {
+ html: string;
+ text: string;
+}
+
+const escapeHtml = (value: string): string =>
+ value
+ .replace(/&/g, "&")
+ .replace(//g, ">")
+ .replace(/"/g, """)
+ .replace(/'/g, "'");
+
+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) =>
+ `
+
+`;
+
+ 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") };
+};
\ No newline at end of file
diff --git a/backend/src/lib/mail.ts b/backend/src/lib/mail.ts
index 9512130..ff9d164 100644
--- a/backend/src/lib/mail.ts
+++ b/backend/src/lib/mail.ts
@@ -13,6 +13,8 @@ export interface MailMessage {
to: string;
subject: string;
text: string;
+ /** Version enrichie ; les clients texte recoivent `text`, les autres `html`. */
+ html?: string;
}
export interface Mailer {
@@ -38,6 +40,7 @@ export const createMailer = (config: Config): Mailer => {
to: message.to,
subject: message.subject,
text: message.text,
+ ...(message.html ? { html: message.html } : {}),
});
},
};
diff --git a/backend/src/routes/account.ts b/backend/src/routes/account.ts
index 2bc240e..38b4890 100644
--- a/backend/src/routes/account.ts
+++ b/backend/src/routes/account.ts
@@ -7,6 +7,7 @@ import sharp from "sharp";
import {
AppError,
attachUser,
+ branding,
clientIp,
createMailer,
createRateLimiter,
@@ -14,6 +15,7 @@ import {
hashPassword,
link,
rateLimitKey,
+ renderMail,
requireAuth,
sha256,
verifyPassword,
@@ -23,7 +25,7 @@ import {
type SessionUser,
} from "../lib/index.js";
import { audit } from "../access.js";
-import { absolutePath, fileExists, openForDownload } from "../storage.js";
+import { absolutePath, diskUsage, fileExists, openForDownload } from "../storage.js";
const AVATAR_MAX_BYTES = 8 * 1024 * 1024;
const AVATAR_PX = 512;
@@ -65,6 +67,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
app.use("/api/cloud/account/*", attachUser(db));
app.use("/api/cloud/account", attachUser(db));
const mailer = createMailer(config);
+ const brand = branding(config);
const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS);
const throttle = (context: Parameters[0], extra: string): void => {
@@ -167,6 +170,11 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
);
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 });
@@ -257,11 +265,19 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
[randomUUID(), user.id, sha256(token), new Date(Date.now() + HOUR_MS)],
);
const url = link(config, `/reset-password?token=${encodeURIComponent(token)}`);
+ const mail = renderMail(brand, {
+ 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 mailer
.send({
to: user.email,
subject: "CoHaiSe Cloud — reinitialisation du mot de passe",
- text: `Une reinitialisation de mot de passe a ete demandee pour ce compte.\n\n${url}\n\nCe lien expire dans une heure. Si vous n'etes pas a l'origine de cette demande, ignorez ce message.`,
+ ...mail,
})
.catch(() => undefined);
}
@@ -344,11 +360,20 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void =>
);
const url = link(config, `/confirm-email?token=${encodeURIComponent(token)}`);
+ const mail = renderMail(brand, {
+ 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 mailer
.send({
to: data.new_email,
subject: "CoHaiSe Cloud — confirmez votre nouvelle adresse",
- text: `Une demande de changement d'adresse a ete faite pour votre compte CoHaiSe Cloud.\n\n${url}\n\nCe lien expire dans une heure. Sans confirmation, l'adresse reste inchangee.`,
+ text: mail.text,
+ html: mail.html,
})
.catch(() => undefined);
diff --git a/backend/src/routes/admin.ts b/backend/src/routes/admin.ts
index 8047024..8dc9113 100644
--- a/backend/src/routes/admin.ts
+++ b/backend/src/routes/admin.ts
@@ -3,14 +3,18 @@ import { z } from "zod";
import {
AppError,
attachUser,
+ branding,
createMailer,
currentUser,
hashPassword,
+ link,
+ renderMail,
requireAuth,
type App,
type Config,
type Db,
} from "../lib/index.js";
+import { diskUsage } from "../storage.js";
const uuidParam = z
.string()
@@ -96,6 +100,19 @@ const SELECT_USER = `
FROM users u
JOIN roles r ON r.id = u.role_id`;
+const UNITS = ["o", "Ko", "Mo", "Go", "To", "Po"];
+
+/** Taille lisible, pour les messages d'erreur destines a l'administrateur. */
+const humanBytes = (bytes: number): string => {
+ let value = bytes;
+ let unit = 0;
+ while (value >= 1024 && unit < UNITS.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+ return `${value.toFixed(unit === 0 || value >= 10 ? 0 : 1)} ${UNITS[unit]}`;
+};
+
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
const generatePasswordValue = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
@@ -110,11 +127,27 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/admin/*", attachUser(db));
app.use("/api/cloud/admin", attachUser(db));
const mailer = createMailer(config);
+ const brand = branding(config);
const requireAdmin = (context: Parameters[0]): void => {
if (currentUser(context).role_slug !== "admin") throw AppError.forbidden();
};
+ /**
+ * Un quota ne peut depasser la capacite reelle du disque qui porte les
+ * medias : au-dela, la limite est un chiffre mort que le support ne pourra
+ * jamais honorer. Le controle est ignore si le support n'est pas lisible
+ * (chemin absent dans le conteneur), pour ne pas bloquer la configuration.
+ */
+ const assertQuotaFits = async (quota: number): Promise => {
+ const disk = await diskUsage(config.MEDIA_DIR);
+ if (disk !== null && quota > disk.total_bytes) {
+ throw AppError.badRequest(
+ `Le quota depasse la capacite du disque (${humanBytes(disk.total_bytes)}).`,
+ );
+ }
+ };
+
app.get("/api/cloud/admin/stats", requireAuth, async (context) => {
requireAdmin(context);
const [users] = await db.query<{ count: number }>(
@@ -145,6 +178,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
usedBytes: Number(files?.bytes ?? 0),
trashFiles: trash?.count ?? 0,
locations,
+ disk: await diskUsage(config.MEDIA_DIR),
});
});
@@ -191,6 +225,24 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
);
const created = await db.required(`${SELECT_USER} WHERE u.id = ?`, [id]);
+
+ const mail = renderMail(brand, {
+ preview: "Votre acces CoHaiSe Cloud est pret.",
+ heading: "Votre compte a ete cree",
+ intro: `Un compte CoHaiSe Cloud vient d'etre ouvert pour ${data.first_name}. Connectez-vous avec les identifiants ci-dessous.`,
+ credentials: { email: data.email, password },
+ cta: { label: "Se connecter", url: link(config, "/login") },
+ note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.",
+ });
+ await mailer
+ .send({
+ to: data.email,
+ subject: "CoHaiSe Cloud — votre compte est pret",
+ text: mail.text,
+ html: mail.html,
+ })
+ .catch(() => undefined);
+
return context.json({ user: publicUser(created), password }, 201);
});
@@ -293,11 +345,20 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
// Le mot de passe est rendu une seule fois et envoye au compte. Un echec
// d'envoi n'invalide pas la reinitialisation.
+ const mail = renderMail(brand, {
+ preview: "Un nouveau mot de passe a ete genere pour votre compte.",
+ heading: "Mot de passe reinitialise",
+ intro: "Un administrateur a reinitialise le mot de passe de votre compte CoHaiSe Cloud.",
+ credentials: { email: user.email, password },
+ cta: { label: "Se connecter", url: link(config, "/login") },
+ note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.",
+ });
await mailer
.send({
to: user.email,
subject: "CoHaiSe Cloud — mot de passe reinitialise",
- text: `Un administrateur a reinitialise le mot de passe de votre compte.\n\nMot de passe provisoire : ${password}\n\nIl vous sera demande de le changer a la prochaine connexion.`,
+ text: mail.text,
+ html: mail.html,
})
.catch(() => undefined);
@@ -310,12 +371,15 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
`SELECT id, name, slug, mount_path, quota_bytes, used_bytes, is_active, created_at
FROM storage_locations WHERE deleted_at IS NULL ORDER BY id`,
);
- return context.json({ locations: rows });
+ return context.json({ locations: rows, disk: await diskUsage(config.MEDIA_DIR) });
});
app.post("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
requireAdmin(context);
const data = parse(createLocationSchema, await context.req.json().catch(() => null));
+ if (data.quota_bytes !== undefined && data.quota_bytes !== null) {
+ await assertQuotaFits(data.quota_bytes);
+ }
try {
await db.exec(
`INSERT INTO storage_locations (name, slug, mount_path, quota_bytes)
@@ -345,6 +409,9 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
if (data.quota_bytes !== undefined && data.quota_bytes !== null && data.quota_bytes < row.used_bytes) {
throw AppError.badRequest("Le quota est inferieur a l'espace deja utilise.");
}
+ if (data.quota_bytes !== undefined && data.quota_bytes !== null) {
+ await assertQuotaFits(data.quota_bytes);
+ }
const fields: string[] = [];
const values: unknown[] = [];
diff --git a/backend/src/routes/files.ts b/backend/src/routes/files.ts
index 44267b2..d5e73a1 100644
--- a/backend/src/routes/files.ts
+++ b/backend/src/routes/files.ts
@@ -18,6 +18,7 @@ import {
absolutePath,
chooseLocation,
discard,
+ diskUsage,
ensureDir,
fileExists,
openForDownload,
@@ -180,6 +181,16 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
);
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
+ // Le disque est verifie avant l'ecriture : sans cela un support plein
+ // ferait echouer le depot en cours de route (ENOSPC), apres avoir
+ // annonce au client que le quota etait disponible.
+ 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);
diff --git a/backend/src/storage.ts b/backend/src/storage.ts
index 36809ce..43366ed 100644
--- a/backend/src/storage.ts
+++ b/backend/src/storage.ts
@@ -1,6 +1,6 @@
import { createHash, randomUUID } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
-import { mkdir, rename, rm, stat } from "node:fs/promises";
+import { mkdir, 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";
@@ -140,3 +140,30 @@ export const fileExists = async (absolute: string): Promise => {
};
export const openForDownload = (absolute: string) => createReadStream(absolute);
+
+/**
+ * Occupation reelle du support qui porte `target`. Sert a refuser un quota
+ * plus grand que le disque et a prevenir un eclatement d'ENOSPC : l'espace
+ * logique (used_bytes) peut etre disponible alors que le disque est plein.
+ */
+export interface DiskUsage {
+ total_bytes: number;
+ /** Blocs libres, blocs reserves du systeme de fichiers inclus. */
+ free_bytes: number;
+ /** Blocs utilisables par le processus (hors reserve root). */
+ available_bytes: number;
+}
+
+export const diskUsage = async (target: string): Promise => {
+ 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 {
+ // Support absent ou non monté : l'appelant decide du repli.
+ return null;
+ }
+};
diff --git a/docker-compose.yml b/docker-compose.yml
index 8db5695..e7bedc1 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -147,6 +147,7 @@ services:
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
SMTP_FROM: ${SMTP_FROM}
SMTP_SECURE: ${SMTP_SECURE:-false}
+ MAIL_LOGO_URL: ${MAIL_LOGO_URL:-}
RATE_LIMIT_LOGIN_MAX: ${RATE_LIMIT_LOGIN_MAX:-10}
RATE_LIMIT_LOGIN_WINDOW_MS: ${RATE_LIMIT_LOGIN_WINDOW_MS:-60000}
TRUST_PROXY: ${TRUST_PROXY:-true}
diff --git a/docker/reset-cloud.sql b/docker/reset-cloud.sql
new file mode 100644
index 0000000..ebbf195
--- /dev/null
+++ b/docker/reset-cloud.sql
@@ -0,0 +1,21 @@
+-- Remise a zero du cloud en conservant les comptes administrateurs.
+-- Execute par `make reset`. Les tables enfants partent avant les parents pour
+-- rester compatible avec les contraintes de cle etrangere.
+
+DELETE FROM file_variants;
+DELETE FROM media_metadata;
+DELETE FROM share_links;
+DELETE FROM files;
+DELETE FROM folder_permissions;
+DELETE FROM folders;
+DELETE FROM user_avatars;
+DELETE FROM password_reset_tokens;
+DELETE FROM email_change_requests;
+DELETE FROM user_sessions;
+DELETE FROM audit_logs;
+
+-- Les comptes utilisateurs disparaissent, les administrateurs restent.
+DELETE FROM users WHERE role_id NOT IN (SELECT id FROM roles WHERE slug = 'admin');
+
+-- Le compteur logique des supports repart de zero en meme temps que le disque.
+UPDATE storage_locations SET used_bytes = 0;
diff --git a/docs/api.md b/docs/api.md
index 88a8a38..6a9da17 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -106,10 +106,24 @@ par tous les membres authentifiés, en écriture pour son propriétaire.
| Corps | `PUT /files` en flux brut (pas de multipart), `?name=` et `?folderId=` |
| Taille | plafond `users.max_file_bytes`, vérifié en flux (coupure si dépassement) |
| Quota | `users.used_bytes` + quota `storage_locations`, revérifiés avant écriture |
+| Disque | `diskUsage()` (`statfs`) avant écriture ; `507` `INSUFFICIENT_STORAGE` si le support est plein |
+| Quota support | un quota d'emplacement ne peut dépasser la capacité réelle du disque (`assertQuotaFits`) |
| Chemin disque | dérivé du slug + UUID, jamais du nom affiché (`storage.ts`) |
| Renommage | `PATCH /files/:id { name }`, `PATCH /folders/:id { name, description }` |
| Déplacement | `folderId`/`parentId` : refuse de placer un dossier dans son propre sous-arbre |
+## Courriels
+
+Les messages sortants sont construits par `backend/src/lib/mail-template.ts` :
+gabarit HTML aux couleurs de l'app (`#b71c1c`), logo (`MAIL_LOGO_URL`, défaut
+`PUBLIC_ORIGIN/logo.png`), bouton d'action et mention **ne pas répondre**. Un
+repli texte accompagne chaque envoi.
+
+Points d'envoi : réinitialisation du mot de passe, changement d'adresse, et
+**notification au nouvel utilisateur** à la création d'un compte admin
+(identifiants temporaires + lien de connexion). Un échec d'envoi n'annule jamais
+l'opération en base.
+
## Modèle de données
`backend/migrations/` — application stricte dans l'ordre, checksum SHA-256
diff --git a/docs/architecture.md b/docs/architecture.md
index 73a4e20..88641cd 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -18,7 +18,7 @@ Node/TypeScript, une base MariaDB, un stockage de fichiers monté en volume.
## Découpage
```
-backend/src/lib/ socle serveur : config, db, mail, ratelimit, http, service, auth, errors
+backend/src/lib/ socle serveur : config, db, mail, mail-template, ratelimit, http, service, auth, errors
backend/src/ routes/, access.ts, storage.ts, media.ts, admin.ts
backend/migrations/ 000 … 006
frontend/src/ui/ design system (boutons, cartes, champs, spinner)
diff --git a/docs/deployment.md b/docs/deployment.md
index 92ee400..c452d73 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -35,6 +35,7 @@ pose problème (`backend/src/lib/config.ts`).
| `SMTP_USER` / `SMTP_PASSWORD` | authentification (vides = relais local) | vide |
| `SMTP_FROM` | adresse d'expédition | — |
| `SMTP_SECURE` | TLS implicite (port 465) | `false` |
+| `MAIL_LOGO_URL` | logo des courriels (défaut `PUBLIC_ORIGIN/logo.png`) | vide |
| `RATE_LIMIT_LOGIN_MAX` | tentatives par fenêtre | `10` |
| `RATE_LIMIT_LOGIN_WINDOW_MS` | largeur de fenêtre | `60000` |
| `LOG_LEVEL` | `silent…debug` | `info` |
@@ -85,13 +86,38 @@ make db # redémarrer la base
make migrate # rejouer explicitement les migrations (hors démarrage)
make backup # dump horodaté → ./backups/cloud-.sql.gz
make admin ARGS=... # créer / réinitialiser un compte
+make purge-logs # vider le journal d'audit
+make reset # cloud vierge, administrateurs conservés (confirmation)
make dev # Vite 5174, proxy /api → 3101
make check # typecheck + build
make down # arrêt, volumes conservés
```
-`make backup` lit le mot de passe **dans le conteneur** : il ne passe ni par la
-commande, ni par le dépôt.
+`make backup`, `make purge-logs` et `make reset` lisent le mot de passe **dans
+le conteneur** : il ne passe ni par la commande, ni par le dépôt.
+
+## Maintenance
+
+### Vider les journaux
+
+`make purge-logs` supprime le contenu de `audit_logs` (table
+`docker/reset-cloud.sql` mise à part). Les comptes, fichiers et dossiers sont
+intacts.
+
+### Remettre le cloud à zéro
+
+`make reset` repart d'une instance vierge **en conservant les comptes
+administrateurs** :
+
+- supprime fichiers, dossiers, partages, permissions, avatars, sessions, jetons
+ (réinitialisation, changement d'adresse) et journaux d'audit ;
+- supprime tous les comptes **sauf** ceux dont le rôle est `admin` ;
+- remet `storage_locations.used_bytes` à zéro ;
+- efface les médias sur disque (`$CLOUD_MEDIA_DIR`), originaux, vignettes et
+ avatars compris.
+
+La commande demande une confirmation (`o`/`y`). Enchaîner `make backup` avant
+si l'état doit être conservé.
## Migrations
diff --git a/frontend/index.html b/frontend/index.html
index 99cf0e3..86b8080 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -7,7 +7,8 @@
CoHaiSe Cloud
-
+
+
diff --git a/frontend/public/logo.png b/frontend/public/logo.png
new file mode 100644
index 0000000..59bda20
Binary files /dev/null and b/frontend/public/logo.png differ