feat: e-mails brandes, controle d'espace disque, maintenance
Courriels - gabarit HTML brande (logo, couleur #b71c1c, bouton, mention ne pas repondre) dans backend/src/lib/mail-template.ts ; repli texte conserve - MailMessage gagne un champ html optionnel - MAIL_LOGO_URL (defaut PUBLIC_ORIGIN/logo.png) + logo.png servi par le front - notification au nouvel utilisateur a la creation du compte admin - forgot-password, email-change et reset-password passent par le gabarit Espace disque - diskUsage() (statfs) dans storage.ts (total/free/available) - upload et avatar refuses si le disque est plein (507 INSUFFICIENT_STORAGE) - quota d'emplacement borne par la capacite reelle du disque - statistiques disque exposees aux endpoints admin Exploitation - make purge-logs : vide le journal d'audit - make reset : cloud vierge en conservant les administrateurs - docker/reset-cloud.sql ; documentation deployment.md et api.md
This commit is contained in:
@@ -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),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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, """)
|
||||
.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) =>
|
||||
`<p style="margin:0 0 16px;font-size:15px;line-height:1.6;color:#3f3f46;">${escapeHtml(paragraph)}</p>`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
const credentials = content.credentials
|
||||
? `
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 24px;background:#fafafa;border:1px solid #e4e4e7;border-radius:10px;">
|
||||
<tr><td style="padding:16px 18px;font-family:${FONT};">
|
||||
<p style="margin:0 0 10px;font:600 12px ${FONT};letter-spacing:.04em;text-transform:uppercase;color:#71717a;">Vos identifiants</p>
|
||||
<p style="margin:0 0 6px;font:400 14px ${FONT};color:#3f3f46;">Adresse : <strong style="color:#18181b;">${escapeHtml(content.credentials.email)}</strong></p>
|
||||
<p style="margin:0;font:400 14px ${FONT};color:#3f3f46;">Mot de passe temporaire :
|
||||
<span style="font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:14px;background:#ffffff;border:1px solid #e4e4e7;border-radius:6px;padding:2px 8px;color:#18181b;">${escapeHtml(content.credentials.password)}</span>
|
||||
</p>
|
||||
</td></tr>
|
||||
</table>`
|
||||
: "";
|
||||
|
||||
const cta = content.cta
|
||||
? `
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" style="margin:0 0 24px;">
|
||||
<tr><td align="center" style="background:${brand.color};border-radius:10px;">
|
||||
<a href="${escapeHtml(content.cta.url)}" style="display:inline-block;padding:13px 30px;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:#71717a;">${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="light only">
|
||||
<title>${escapeHtml(content.heading)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background:#f4f4f5;">
|
||||
<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:#f4f4f5;">${escapeHtml(content.preview)}</div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:32px 12px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="560" cellpadding="0" cellspacing="0" style="width:100%;max-width:560px;background:#ffffff;border:1px solid #e4e4e7;border-radius:14px;overflow:hidden;">
|
||||
<tr><td style="background:${brand.color};padding:18px 28px;">
|
||||
<a href="${escapeHtml(brand.origin)}" style="text-decoration:none;">
|
||||
<img src="${escapeHtml(brand.logoUrl)}" width="34" height="34" alt="" style="vertical-align:middle;border:0;border-radius:9px;background:#ffffff;">
|
||||
<span style="vertical-align:middle;margin-left:12px;font:600 17px ${FONT};color:#ffffff;">${escapeHtml(brand.appName)}</span>
|
||||
</a>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px 28px 6px;font-family:${FONT};">
|
||||
<h1 style="margin:0 0 16px;font:600 21px ${FONT};line-height:1.3;color:#18181b;">${escapeHtml(content.heading)}</h1>
|
||||
<p style="margin:0 0 16px;font:400 15px ${FONT};line-height:1.6;color:#3f3f46;">${escapeHtml(content.intro)}</p>
|
||||
${paragraphs}${credentials}${cta}${note}
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 28px 28px;font-family:${FONT};">
|
||||
<hr style="border:0;border-top:1px solid #e4e4e7;margin:0 0 16px;">
|
||||
<p style="margin:0 0 4px;font:400 12px ${FONT};line-height:1.6;color:#71717a;">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:#a1a1aa;">${escapeHtml(brand.footer)}</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
<p style="margin:18px 0 0;font:400 12px ${FONT};color:#a1a1aa;">${escapeHtml(brand.appName)} — <a href="${escapeHtml(brand.origin)}" style="color:#a1a1aa;">${escapeHtml(brand.origin.replace(/^https?:\/\//, ""))}</a></p>
|
||||
</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") };
|
||||
};
|
||||
@@ -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 } : {}),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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<typeof clientIp>[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);
|
||||
|
||||
|
||||
@@ -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<typeof currentUser>[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<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)}).`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
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<AdminUserRow>(`${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[] = [];
|
||||
|
||||
@@ -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);
|
||||
|
||||
+28
-1
@@ -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<boolean> => {
|
||||
};
|
||||
|
||||
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<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 {
|
||||
// Support absent ou non monté : l'appelant decide du repli.
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user