feat: logo et favicon, confirmation modale, fil d'ariane, e-mails sombres (#4)
CD — Déploiement / deploy (push) Failing after 25s
CD — Déploiement / deploy (push) Failing after 25s
- logo embarque dans les e-mails (CID) et gabarit repense en mode sombre - favicon multi-tailles + icone PNG, logo a gauche du titre (app et auth) - modale de confirmation animee a la place de window.confirm - bouton retour et fil d'ariane dans l'explorateur --------- Co-authored-by: xEsiah <[email protected]> Reviewed-on: #4 Reviewed-by: Esiah <[email protected]> Co-authored-by: Gitea Actions <-[email protected]>
This commit was merged in pull request #4.
This commit is contained in:
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/tsconfig",
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"composite": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"references": [{ "path": "../shared" }]
|
||||
}
|
||||
@@ -11,7 +11,9 @@
|
||||
"admin": "node dist/admin.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cohaise/server": "*",
|
||||
"@hono/node-server": "^2.1.3",
|
||||
"hono": "^4.13.13",
|
||||
"mysql2": "^3.24.5",
|
||||
"nodemailer": "^10.1.1",
|
||||
"sharp": "^0.35.5",
|
||||
"zod": "^4.6.5"
|
||||
@@ -22,6 +24,7 @@
|
||||
"typescript": "^7.0.2"
|
||||
},
|
||||
"bin": {
|
||||
"cohaise-admin": "./dist/admin.js"
|
||||
"cohaise-admin": "./dist/admin.js",
|
||||
"cohaise-migrate": "./dist/cli.js"
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
{
|
||||
"name": "@cohaise/server",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"clean": "node --eval \"import('node:fs').then(fs => { fs.rmSync('dist', { recursive: true, force: true }); fs.rmSync('tsconfig.tsbuildinfo', { force: true }); })\"",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.0.0",
|
||||
"typescript": "^7.0.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hono/node-server": "^2.1.3",
|
||||
"hono": "^4.13.13",
|
||||
"mysql2": "^3.24.5",
|
||||
"zod": "^4.6.5"
|
||||
},
|
||||
"bin": {
|
||||
"cohaise-migrate": "./dist/cli.js"
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Context } from "hono";
|
||||
import { clientIp as sharedClientIp, type Db, type SessionUser } from "@cohaise/server";
|
||||
import { clientIp as sharedClientIp, type Db, type SessionUser } from "./lib/index.js";
|
||||
|
||||
/**
|
||||
* Les droits sont toujours recalcules depuis la session serveur. Le role de
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { ConfigError, loadDbConfig, hashPassword, AppError, toSafeError } from "@cohaise/server";
|
||||
import { ConfigError, loadDbConfig, hashPassword, AppError, toSafeError } from "./lib/index.js";
|
||||
|
||||
/**
|
||||
* Creation et reinitialisation des comptes, en dehors de toute requete HTTP.
|
||||
@@ -98,7 +98,7 @@ const main = async (argv: string[]): Promise<number> => {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const { Db } = await import("@cohaise/server");
|
||||
const { Db } = await import("./lib/index.js");
|
||||
const db = new Db(config);
|
||||
|
||||
try {
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 138 KiB |
@@ -1,6 +1,6 @@
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { purgeExpiredSessions, startService } from "@cohaise/server";
|
||||
import { purgeExpiredSessions, startService } from "./lib/index.js";
|
||||
import { registerAccountRoutes } from "./routes/account.js";
|
||||
import { registerAdminRoutes } from "./routes/admin.js";
|
||||
import { registerAuthRoutes } from "./routes/auth.js";
|
||||
@@ -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 le logo embarque (`backend/src/assets/logo.png`,
|
||||
* joint au message) ; renseigner une URL pour forcer une image distante.
|
||||
*/
|
||||
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,147 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifiant de la piece jointe du logo. Le logo est embarque dans le message
|
||||
* (voir `mail.ts`) : l'image s'affiche meme si le client bloque les ressources
|
||||
* distantes. `MAIL_LOGO_URL` force une image distante a la place.
|
||||
*/
|
||||
export const LOGO_CID = "cohaise-logo";
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
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:#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") };
|
||||
};
|
||||
@@ -1,5 +1,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createTransport, type Transporter } from "nodemailer";
|
||||
import type { Config } from "./config.js";
|
||||
import { LOGO_CID } from "./mail-template.js";
|
||||
|
||||
/**
|
||||
* Envoi de courriel via SMTP.
|
||||
@@ -9,10 +11,26 @@ import type { Config } from "./config.js";
|
||||
* laisser une reinitialisation de mot de passe silencieusement sans effet.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Logo embarque dans les messages. Le chemin remonte depuis `src/lib` ou
|
||||
* `dist/lib` vers `backend/src/assets/logo.png`, present dans l'image.
|
||||
*/
|
||||
const LOGO_PATH = new URL("../../src/assets/logo.png", import.meta.url);
|
||||
|
||||
const loadLogo = (): Buffer | null => {
|
||||
try {
|
||||
return readFileSync(LOGO_PATH);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export interface MailMessage {
|
||||
to: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
/** Version enrichie ; les clients texte recoivent `text`, les autres `html`. */
|
||||
html?: string;
|
||||
}
|
||||
|
||||
export interface Mailer {
|
||||
@@ -31,13 +49,22 @@ export const createMailer = (config: Config): Mailer => {
|
||||
disableUrlAccess: true,
|
||||
});
|
||||
|
||||
// Logo embarque une seule fois. `MAIL_LOGO_URL` le remplace par une image
|
||||
// distante : dans ce cas on n'attache rien.
|
||||
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 }] }
|
||||
: {}),
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { mkdir, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import type { Config, Db } from "@cohaise/server";
|
||||
import type { Config, Db } from "./lib/index.js";
|
||||
import { absolutePath } from "./storage.js";
|
||||
|
||||
/**
|
||||
@@ -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,
|
||||
@@ -21,9 +23,9 @@ import {
|
||||
type Config,
|
||||
type Db,
|
||||
type SessionUser,
|
||||
} from "@cohaise/server";
|
||||
} 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 "@cohaise/server";
|
||||
} 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,7 +18,7 @@ import {
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
} from "../lib/index.js";
|
||||
|
||||
const credentials = z.object({
|
||||
email: z.string().trim().min(3).max(255),
|
||||
@@ -11,13 +11,14 @@ import {
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
} from "../lib/index.js";
|
||||
import { audit, canRead, canWrite, canWriteExplicit } from "../access.js";
|
||||
import { indexMedia, thumbnailSize } from "../media.js";
|
||||
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);
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
} from "../lib/index.js";
|
||||
import { audit, canManageFolder, canRead, canWrite } from "../access.js";
|
||||
|
||||
const uuid = z
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
} from "../lib/index.js";
|
||||
|
||||
/**
|
||||
* Galerie : liste des fichiers accompagnes de leur nature (image, video,
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
} from "../lib/index.js";
|
||||
|
||||
/**
|
||||
* Recherche par nom, filtree par les droits de la session. Le motif est
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
} from "../lib/index.js";
|
||||
import { audit } from "../access.js";
|
||||
import { absolutePath, discard } from "../storage.js";
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
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";
|
||||
import { AppError, type Db } from "@cohaise/server";
|
||||
import { AppError, type Db } from "./lib/index.js";
|
||||
|
||||
/**
|
||||
* Chemin physique : ${MEDIA_DIR}/${slug emplacement}/${uuid}.
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/tsconfig",
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"extends": "../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
@@ -10,7 +10,6 @@
|
||||
"outDir": "dist",
|
||||
"composite": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
Reference in New Issue
Block a user