feat: logo et favicon, confirmation modale, fil d'ariane, e-mails sombres (#4)
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:
Gitea Actions
2026-10-16 11:08:47 +00:00
committed by Esiah
co-authored by Esiah
parent 25b6e0669a
commit 9dd1ad72e0
105 changed files with 2638 additions and 592 deletions
+137
View File
@@ -0,0 +1,137 @@
import type { Context } from "hono";
import { clientIp as sharedClientIp, type Db, type SessionUser } from "./lib/index.js";
/**
* Les droits sont toujours recalcules depuis la session serveur. Le role de
* l'utilisateur ne vient jamais d'un en-tete client : une requete qui se
* declare admin n'a aucun effet sur cette evaluation.
*/
/**
* SQL de lecture repetee : proprietaire, permission nominative non expiree, ou
* dossier public (accessible a tout compte authentifie).
*/
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> => {
if (user.role_slug === "admin") return true;
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> => {
if (user.role_slug === "admin") return true;
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;
};
/**
* Ecriture explicite : proprietaire du dossier, ou permission nominative
* `write`/`admin`. Un dossier public en est exclu : il autorise le depot, mais
* pas la modification ni la suppression des fichiers d'autrui.
*/
export const canWriteExplicit = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<boolean> => {
if (user.role_slug === "admin") return true;
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;
};
/**
* Gestion du dossier (renommer, deplacer, supprimer, regler les permissions) :
* reservee au proprietaire ou a un administrateur. Un dossier public permet
* d'ajouter, pas de reorganiser l'espace commun.
*/
export const canManageFolder = async (
db: Db,
user: SessionUser,
folderId: string,
): Promise<boolean> => {
if (user.role_slug === "admin") return true;
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;
};
const clientIp = (context: Context, trustProxy: boolean): string | null =>
sharedClientIp(context, trustProxy);
/**
* Journalise une action sensible. audit_logs survit a la suppression du compte
* (ON DELETE SET NULL) avec un instantane de l'e-mail : c'est la seule trace
* qui reste une fois l'utilisateur efface.
*/
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);
};
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env node
import { randomUUID } from "node:crypto";
import { ConfigError, loadDbConfig, hashPassword, AppError, toSafeError } from "./lib/index.js";
/**
* Creation et reinitialisation des comptes, en dehors de toute requete HTTP.
*
* Cette commande ne lit que les variables DB : elle doit pouvoir creer le
* premier administrateur alors que l'API n'a pas encore le droit de demarrer.
*
* node dist/admin.js --email [email protected] --first Jean --last Dupont [--role admin]
* node dist/admin.js --email [email protected] --reset
*
* Mot de passe : ADMIN_PASSWORD dans l'environnement, sinon --password,
* sinon un mot de passe aleatoire est genere et affiche une seule fois.
*/
const USAGE = `Utilisation : cohaise-admin --email <adr> --first <prenom> --last <nom> [options]
--email <adr> Adresse du compte (obligatoire)
--first <nom> Prenom (obligatoire a la creation)
--last <nom> Nom (obligatoire a la creation)
--role <slug> admin | user (defaut : admin)
--password <mdp> Mot de passe, sinon variable ADMIN_PASSWORD
--reset Reinitialise le mot de passe d'un compte existant
--help Cette aide`;
interface Args {
email: string;
first: string;
last: string;
role: string;
password?: string;
reset: boolean;
help: boolean;
}
const parseArgs = (argv: string[]): Args => {
const args: Args = { email: "", first: "", last: "", role: "admin", reset: false, help: false };
const value = (index: number): string => {
const next = argv[index + 1];
if (next === undefined || next.startsWith("--")) {
throw AppError.badRequest(`Valeur manquante pour ${argv[index]}`);
}
return next;
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === undefined) continue;
if (arg === "--email") args.email = value(index++);
else if (arg === "--first") args.first = value(index++);
else if (arg === "--last") args.last = value(index++);
else if (arg === "--role") args.role = value(index++);
else if (arg === "--password") args.password = value(index++);
else if (arg === "--reset") args.reset = true;
else if (arg === "--help" || arg === "-h") args.help = true;
else throw AppError.badRequest(`Argument inconnu : ${arg}`);
}
return args;
};
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
const generatePassword = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const bytes = new Uint8Array(18);
globalThis.crypto.getRandomValues(bytes);
let out = "";
for (const byte of bytes) out += alphabet[byte % alphabet.length];
return out;
};
const main = async (argv: string[]): Promise<number> => {
let args: Args;
try {
args = parseArgs(argv);
} catch (error) {
console.error(` ${toSafeError(error).message}\n\n${USAGE}`);
return 2;
}
if (args.help) {
console.log(USAGE);
return 0;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(args.email)) {
console.error(" Adresse e-mail invalide.");
return 2;
}
let config;
try {
config = loadDbConfig();
} catch (error) {
if (error instanceof ConfigError) {
console.error(` Configuration invalide :\n - ${error.issues.join("\n - ")}`);
return 2;
}
throw error;
}
const { Db } = await import("./lib/index.js");
const db = new Db(config);
try {
const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [args.role]);
if (!role) {
console.error(` Role inconnu : ${args.role}`);
return 2;
}
const existing = await db.one<{ id: string }>(
"SELECT id FROM users WHERE active_email = ?",
[args.email],
);
if (existing && !args.reset) {
console.error(` Ce compte existe deja : ${args.email}`);
console.error(" Utilisez --reset pour reinitialiser son mot de passe.");
return 1;
}
const password = args.password ?? process.env.ADMIN_PASSWORD ?? generatePassword();
if (Buffer.byteLength(password) < 8) {
console.error(" Le mot de passe doit contenir au moins 8 caracteres.");
return 2;
}
const hash = await hashPassword(password);
if (existing) {
await db.exec(
`UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = NULL,
is_active = 1, deleted_at = NULL
WHERE id = ?`,
[hash, existing.id],
);
console.log(` Mot de passe reinitialise pour ${args.email}`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
}
if (!args.first || !args.last) {
console.error(" --first et --last sont obligatoires a la creation.");
console.error(`\n${USAGE}`);
return 2;
}
const id = randomUUID();
await db.exec(
`INSERT INTO users (id, email, first_name, last_name, password_hash, role_id, must_change_password, password_changed_at)
VALUES (?, ?, ?, ?, ?, ?, 1, NULL)`,
[id, args.email, args.first, args.last, hash, role.id],
);
console.log(` Compte cree : ${args.email} (${args.role})`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
} catch (error) {
const safe = toSafeError(error);
console.error(` Echec : ${safe.code} — ${safe.message}`);
return 1;
} finally {
await db.close().catch(() => undefined);
}
};
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(error) => {
console.error(` Erreur inattendue : ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
},
);
Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

+37
View File
@@ -0,0 +1,37 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
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";
import { registerFileRoutes } from "./routes/files.js";
import { registerFolderRoutes } from "./routes/folders.js";
import { registerMediaRoutes } from "./routes/media.js";
import { registerSearchRoutes } from "./routes/search.js";
import { registerTrashRoutes, purgeExpiredTrash } from "./routes/trash.js";
// Les migrations sont relues au demarrage. L'operation est idempotente et
// refuse de servir si une migration deja appliquee a change : une base non
// migree rend donc l'API inaccessible plutot que de renvoyer des erreurs 500.
const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "../migrations");
void startService({
service: "cloud",
migrationsDir,
routes: (app, { db, config }) => {
registerAuthRoutes(app, db, config);
registerAccountRoutes(app, db, config);
registerFolderRoutes(app, db, config);
registerFileRoutes(app, db, config);
registerMediaRoutes(app, db);
registerTrashRoutes(app, db, config);
registerSearchRoutes(app, db);
registerAdminRoutes(app, db, config);
},
onReady: async ({ db, config, logger }) => {
// Entretien au demarrage : sessions expirees et corbeille hors retention.
const sessions = await purgeExpiredSessions(db);
const purged = await purgeExpiredTrash(db, config);
logger.info("entretien au demarrage", { sessions, purged });
},
});
+223
View File
@@ -0,0 +1,223 @@
import { createHash, randomBytes, randomUUID, scrypt as scryptCallback, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
import type { Context, Next } from "hono";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
import type { Db } from "./db.js";
import { AppError } from "./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>;
/**
* scrypt du module natif, pas une dependance externe. Une lib native a compiler
* est la facon la plus rapide de casser un build sur une machine cible : argon2
* ou bcrypt produisent un binaire qui n'est pas portable sans outilchain.
* node:crypto est deja la, et scrypt est un KDF defini par RFC 7914.
*/
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");
/**
* Portrait de l'utilisateur porte par la session.
*
* Les budgets de stockage n'y figurent pas : une valeur figee dans un cookie
* serait fausse des la premiere ecriture. Chaque route qui en a besoin relit
* les colonnes en base au moment de l'usage.
*/
export interface SessionUser {
id: string;
email: string;
first_name: string;
last_name: string;
role_slug: string;
role_name: string;
is_active: number;
must_change_password: number;
}
export interface SessionMeta {
ipAddress?: string | null | undefined;
userAgent?: string | null | undefined;
}
export const SESSION_COOKIE = "cohaise_session";
/**
* Le jeton brut part dans le cookie, son empreinte SHA-256 dans la base.
* Une copie de la base ne donne donc aucune session ouvrable : il faudrait
* en plus la table des cookies, qui n'existe pas.
*/
export const createSession = async (
db: Db,
userId: string,
meta: SessionMeta,
ttlHours: number,
): 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,
sha256(token),
meta.ipAddress ?? null,
meta.userAgent?.slice(0, 255) ?? null,
expiresAt,
],
);
return { token, expiresAt };
};
export const resolveSession = async (db: Db, token: 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`,
[sha256(token)],
);
if (!row) return null;
// Etat vu, avec un decalage de 60 s pour ne pas ecrire a chaque requete.
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",
[sha256(token)],
);
return row;
};
export const revokeSession = async (db: Db, token: string): Promise<void> => {
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE token_hash = ?", [
sha256(token),
]);
};
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;
};
/**
* Secure depend du schema reel de la requete, pas d'une origine configuree.
*
* Deriver Secure de PUBLIC_ORIGIN rendait tout test local impossible : le
* navigateur rejette en HTTP un cookie marque Secure, donc la connexion
* echouait sans message exploitable. A l'inverse, un cookie non Secure servi en
* HTTPS laisserait le jeton circuler en clair.
*
* X-Forwarded-Proto n'est pris en compte que si le service fait confiance a son
* proxy ; sinon la connexion parle d'elle-meme.
*/
export const isHttpsRequest = (context: Context, trustProxy: boolean): boolean => {
if (trustProxy) {
const forwarded = context.req.header("x-forwarded-proto");
if (forwarded) return forwarded.split(",")[0]?.trim() === "https";
}
return context.req.raw.url.startsWith("https:");
};
export const setSessionCookie = (
context: Context,
token: string,
expiresAt: Date,
secure: boolean,
): void => {
setCookie(context, SESSION_COOKIE, token, {
httpOnly: true,
sameSite: "Lax",
secure,
path: "/",
expires: expiresAt,
});
};
export const clearSessionCookie = (context: Context): void => {
deleteCookie(context, SESSION_COOKIE, { path: "/" });
};
export interface AuthState {
user: SessionUser;
token: string;
}
/** Lit le cookie et attache l'utilisateur, sans exiger qu'il existe. */
export const attachUser =
(db: Db) =>
async (context: Context, next: Next): Promise<void> => {
const token = getCookie(context, SESSION_COOKIE);
if (token) {
const user = await resolveSession(db, token);
if (user) {
context.set("user", user);
context.set("token", token);
} else {
clearSessionCookie(context);
}
}
await next();
};
export const requireAuth = async (context: Context, next: Next): Promise<void> => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
await next();
};
/** Le role est impose en base, jamais en entete, donc ni cacheable ni falsifiable. */
export const requireRole =
(...slugs: string[]) =>
async (context: Context, next: Next): Promise<void> => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
if (!slugs.includes(user.role_slug)) {
throw AppError.forbidden(`Action reservee au role : ${slugs.join(", ")}.`);
}
await next();
};
export const currentUser = (context: Context): SessionUser => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
return user;
};
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env node
import { pathToFileURL } from "node:url";
import { resolve } from "node:path";
import { ConfigError, loadDbConfig } from "./config.js";
import { Db } from "./db.js";
import { AppError, toSafeError } from "./errors.js";
import { listMigrations, runMigrations } from "./migrate.js";
/**
* Point d'entree des migrations : `node dist/cli.js --dir <dossier>`.
*
* Le conteneur de migration n'a besoin d'aucun secret lisible a la main :
* les variables sont resolues par Docker depuis .env au lancement.
*
* Codes de sortie :
* 0 tout est applique, ou rien a faire
* 1 erreur (connexion, SQL, migration) OU derive detectee
* 2 configuration incomplete
*/
interface Options {
dir: string;
dryRun: boolean;
check: boolean;
help: boolean;
}
const USAGE = `Utilisation : cohaise-migrate --dir <dossier> [--dry-run] [--check]
--dir <dossier> Dossier contenant les fichiers NNN_nom.sql (obligatoire)
--dry-run Analyse sans ecrire en base
--check Echoue s'il reste une migration a appliquer
--help Cette aide`;
const parseArgs = (argv: string[]): Options => {
const options: Options = { dir: "", dryRun: false, check: false, help: false };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === undefined) continue;
if (arg === "--dry-run") options.dryRun = true;
else if (arg === "--check") options.check = true;
else if (arg === "--help" || arg === "-h") options.help = true;
else if (arg === "--dir") {
options.dir = argv[index + 1] ?? "";
index += 1;
} else if (arg.startsWith("--dir=")) {
options.dir = arg.slice("--dir=".length);
} else {
throw AppError.badRequest(`Argument inconnu : ${arg}`, { argument: arg });
}
}
return options;
};
const main = async (argv: string[]): Promise<number> => {
let options: Options;
try {
options = parseArgs(argv);
} catch (error) {
const safe = toSafeError(error);
console.error(` ${safe.message}\n\n${USAGE}`);
return 2;
}
if (options.help) {
console.log(USAGE);
return 0;
}
if (!options.dir) {
console.error(` --dir est obligatoire\n\n${USAGE}`);
return 2;
}
let config;
try {
config = loadDbConfig();
} catch (error) {
if (error instanceof ConfigError) {
console.error(` Configuration invalide :\n - ${error.issues.join("\n - ")}`);
return 2;
}
throw error;
}
const dir = resolve(options.dir);
const db = new Db(config);
try {
const migrations = await listMigrations(dir);
if (migrations.length === 0) {
console.log(` Aucune migration trouvee dans ${dir}`);
return 0;
}
const result = await runMigrations(db, dir, { dryRun: options.dryRun });
const prefix = options.dryRun ? "[dry-run] " : "";
console.log(
`${prefix}${migrations.length} migration(s) · ${result.applied.length} appliquee(s) · ` +
`${result.skipped.length} deja en place · ${result.drifted.length} derivee(s)`,
);
for (const version of result.applied) console.log(` + ${version}`);
for (const drift of result.drifted) {
console.error(` ! ${drift.version} modifiee depuis son execution (checksum attendu ${drift.recorded.slice(0, 12)}…, trouve ${drift.current.slice(0, 12)}…)`);
}
if (result.drifted.length > 0) return 1;
if (options.check && result.applied.length > 0) return 1;
return 0;
} catch (error) {
const safe = toSafeError(error);
console.error(` Echec : ${safe.code} — ${safe.message}`);
if (error instanceof AppError && error.status >= 500 && error.message.includes("migree")) {
console.error(" Appliquez d'abord les migrations : cohaise-migrate --dir <dossier>");
}
return 1;
} finally {
await db.close().catch(() => undefined);
}
};
const isDirectRun =
process.argv[1] !== undefined &&
import.meta.url === pathToFileURL(process.argv[1]).href;
if (isDirectRun) {
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(error) => {
console.error(` Erreur inattendue : ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
},
);
}
export { main, parseArgs };
+119
View File
@@ -0,0 +1,119 @@
import { z } from "zod";
/**
* Configuration lue une seule fois au demarrage. L'objet est fige :
* si une variable manque ou est mal formee, le processus s'arrete avant
* d'ouvrir le moindre port, avec la liste exacte de ce qui pose probleme.
* Une API qui demarre puis echoue sur la premiere requete est un defaut de
* deploiement, pas un defaut d'ecriture de code.
*/
const bool = (fallback: boolean) =>
z
.string()
.optional()
.transform((value) => {
if (value === undefined || value === "") return fallback;
return !["0", "false", "no", "off"].includes(value.toLowerCase());
});
const port = (fallback: number) =>
z.coerce.number().int().min(1).max(65535).default(fallback);
const positiveInt = (fallback: number) =>
z.coerce.number().int().positive().default(fallback);
const schema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
LOG_LEVEL: z.enum(["silent", "error", "warn", "info", "debug"]).default("info"),
PORT: port(3000),
/** Origine publique absolue, indispensable aux liens envoyes par courriel. */
PUBLIC_ORIGIN: z.url(),
DB_HOST: z.string().min(1),
DB_PORT: port(3306),
DB_USER: z.string().min(1),
DB_PASSWORD: z.string().min(1),
DB_NAME: z.string().min(1),
DB_CONNECTION_LIMIT: positiveInt(8),
DB_CONNECT_TIMEOUT_MS: positiveInt(10_000),
MEDIA_DIR: z.string().min(1).default("/data/media/originals"),
VARIANT_DIR: z.string().min(1).default("/data/media/variants"),
SESSION_SECRET: z.string().min(32),
SESSION_TTL_HOURS: positiveInt(24 * 14),
TRUST_PROXY: bool(false),
CORS_ORIGIN: z.string().optional().transform((v) => v ?? null),
// Envoi de courriel : obligatoire, l'application refuse de demarrer sans,
// car la reinitialisation de mot de passe et le changement d'adresse en
// dependent. Un relais local sans authentification reste possible : seuls
// l'hote et l'expediteur sont exiges.
SMTP_HOST: z.string().min(1),
SMTP_PORT: port(587),
SMTP_USER: z.string().optional().transform((v) => (v ? v : null)),
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),
RATE_LIMIT_LOGIN_WINDOW_MS: positiveInt(60_000),
});
export type Config = Readonly<z.infer<typeof schema>>;
export class ConfigError extends Error {
readonly issues: string[];
constructor(issues: string[]) {
super(`Configuration invalide (${issues.length}) :\n - ${issues.join("\n - ")}`);
this.name = "ConfigError";
this.issues = issues;
}
}
export const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => {
const parsed = schema.safeParse(env);
if (!parsed.success) throw new ConfigError(issuesOf(parsed.error));
return Object.freeze(parsed.data);
};
/** Sous-ensemble DB, pour les outils qui n'ouvrent aucun port (migrations, CLI). */
const dbSchema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
LOG_LEVEL: z.enum(["silent", "error", "warn", "info", "debug"]).default("info"),
DB_HOST: z.string().min(1),
DB_PORT: port(3306),
DB_USER: z.string().min(1),
DB_PASSWORD: z.string().min(1),
DB_NAME: z.string().min(1),
DB_CONNECTION_LIMIT: positiveInt(8),
DB_CONNECT_TIMEOUT_MS: positiveInt(10_000),
});
export type DbConfig = Readonly<z.infer<typeof dbSchema>>;
export const loadDbConfig = (env: NodeJS.ProcessEnv = process.env): DbConfig => {
const parsed = dbSchema.safeParse(env);
if (!parsed.success) throw new ConfigError(issuesOf(parsed.error));
return Object.freeze(parsed.data);
};
const issuesOf = (error: z.ZodError): string[] =>
error.issues.map((issue) => {
const path = issue.path.join(".") || "(racine)";
const missing = issue.code === "invalid_type" && issue.input === undefined;
return missing ? `${path} : variable absente` : `${path} : ${issue.message}`;
});
+107
View File
@@ -0,0 +1,107 @@
import mysql, { type Pool, type PoolConnection, type ResultSetHeader, type RowDataPacket } from "mysql2/promise";
import type { DbConfig } from "./config.js";
export interface QueryError {
code: string;
errno: number;
sqlMessage?: string;
}
export class Db {
readonly pool: Pool;
constructor(config: DbConfig) {
this.pool = mysql.createPool({
host: config.DB_HOST,
port: config.DB_PORT,
user: config.DB_USER,
password: config.DB_PASSWORD,
database: config.DB_NAME,
waitForConnections: true,
connectionLimit: config.DB_CONNECTION_LIMIT,
connectTimeout: config.DB_CONNECT_TIMEOUT_MS,
timezone: "Z",
charset: "utf8mb4_unicode_ci",
decimalNumbers: true,
// Porte refermee sur les requetes empilees : sans cet option, une
// contamination d'une lecture echappait en INSERT ou en DROP. Les valeurs
// sont toujours transmises en parametres, jamais concatenees dans le SQL.
multipleStatements: false,
namedPlaceholders: false,
});
}
/** Lecture en protocole prepare : les valeurs sont binaires, jamais des chains de texte. */
async query<T = RowDataPacket>(sql: string, params: unknown[] = []): Promise<T[]> {
const [rows] = await this.pool.execute(sql, params as never);
return rows as T[];
}
/** Requete brute, sans parametres, reservee au DDL des migrations.
Certains etats DDL ne passent pas le protocole prepare de MariaDB. */
async raw(sql: string): Promise<void> {
await this.pool.query(sql);
}
async one<T = RowDataPacket>(sql: string, params: unknown[] = []): Promise<T | null> {
const rows = await this.query<RowDataPacket>(sql, params);
return (rows[0] as T | undefined) ?? null;
}
/** Le premier resultat, ou une erreur explicite plutot qu'un undefined silencieux. */
async required<T = RowDataPacket>(sql: string, params: unknown[] = []): Promise<T> {
const row = await this.one<T>(sql, params);
if (row === null) {
throw Object.assign(new Error("Ligne introuvable"), { status: 404, code: "NOT_FOUND" });
}
return row;
}
async exec(sql: string, params: unknown[] = []): Promise<ResultSetHeader> {
const [result] = await this.pool.execute(sql, params as never);
return result as ResultSetHeader;
}
async transaction<T>(fn: (connection: PoolConnection) => Promise<T>): Promise<T> {
const connection = await this.pool.getConnection();
try {
await connection.beginTransaction();
const result = await fn(connection);
await connection.commit();
return result;
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.release();
}
}
/** Forme courte des erreurs de contrainte, pour les repondre en 409 et non en 500. */
static classify(error: unknown): { status: number; message: string } {
const errno = (error as { errno?: number })?.errno;
const sqlMessage = (error as { sqlMessage?: string })?.sqlMessage ?? "";
switch (errno) {
case 1062:
return { status: 409, message: "Cette valeur existe deja." };
case 1451:
case 1452:
return { status: 409, message: "Operation impossible : des enregistrements en referent encore." };
case 1406:
return { status: 422, message: "Valeur trop longue pour la colonne." };
case 1146:
return { status: 503, message: "Table absente : la base n'est peut-etre pas migree." };
case 1045:
return { status: 503, message: "Acces refuse par la base de donnees." };
case 1040:
case 1203:
return { status: 503, message: "Trop de connexions a la base de donnees." };
default:
return errno === undefined ? { status: 500, message: "Erreur interne." } : { status: 500, message: sqlMessage || "Erreur de base de donnees." };
}
}
async close(): Promise<void> {
await this.pool.end();
}
}
+100
View File
@@ -0,0 +1,100 @@
/**
* Erreurs portees par un code HTTP. Une erreur qui n'en porte pas est
* consideree interne : on journalise le detail, on ne le rend jamais au
* client, parce que le message d'une exception ne doit pas decrire le schema.
*/
export class AppError extends Error {
readonly status: number;
readonly code: string;
readonly details?: Record<string, unknown>;
constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {
super(message);
this.name = "AppError";
this.status = status;
this.code = code;
if (details !== undefined) this.details = details;
}
static badRequest(message: string, details?: Record<string, unknown>) {
return new AppError(400, "BAD_REQUEST", message, details);
}
static unauthorized(message = "Authentification requise.") {
return new AppError(401, "UNAUTHORIZED", message);
}
static forbidden(message = "Vous ne pouvez pas effectuer cette action.") {
return new AppError(403, "FORBIDDEN", message);
}
static notFound(message = "Ressource introuvable.") {
return new AppError(404, "NOT_FOUND", message);
}
static conflict(message: string) {
return new AppError(409, "CONFLICT", message);
}
static payloadTooLarge(message = "Fichier trop volumineux.") {
return new AppError(413, "PAYLOAD_TOO_LARGE", message);
}
static unprocessable(message: string, details?: Record<string, unknown>) {
return new AppError(422, "UNPROCESSABLE", message, details);
}
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 {
status: number;
code: string;
message: string;
details?: Record<string, unknown>;
}
export const toSafeError = (error: unknown): SafeError => {
if (error instanceof AppError) {
return error.details !== undefined
? { status: error.status, code: error.code, message: error.message, details: error.details }
: { status: error.status, code: error.code, message: error.message };
}
const status = (error as { status?: number })?.status;
const code = (error as { code?: string })?.code;
if (typeof status === "number" && status >= 400 && status < 500) {
return { status, code: code ?? "BAD_REQUEST", message: (error as Error).message };
}
// Une erreur MariaDB connue est un probleme d'exploitation, pas un crash.
const errno = (error as { errno?: number })?.errno;
if (errno !== undefined) {
const { status: dbStatus, message } = classifyDbError(errno);
return { status: dbStatus, code: errno === 1146 ? "NOT_MIGRATED" : "DATABASE", message };
}
return { status: 500, code: "INTERNAL", message: "Erreur interne." };
};
const classifyDbError = (errno: number): { status: number; message: string } => {
switch (errno) {
case 1062:
return { status: 409, message: "Cette valeur existe deja." };
case 1451:
case 1452:
return { status: 409, message: "Operation impossible : des enregistrements en referent encore." };
case 1406:
return { status: 422, message: "Valeur trop longue pour la colonne." };
case 1146:
return { status: 503, message: "Base non migree. Lancez les migrations avant de servir." };
case 1045:
return { status: 503, message: "Acces refuse par la base de donnees." };
case 1040:
case 1203:
return { status: 503, message: "Trop de connexions a la base de donnees." };
case 1053:
return { status: 503, message: "Base de donnees en cours d'initialisation." };
default:
return { status: 503, message: "Base de donnees indisponible." };
}
};
+171
View File
@@ -0,0 +1,171 @@
import { randomUUID } from "node:crypto";
import { Hono, type Context, type Next } from "hono";
import { cors } from "hono/cors";
import type { SessionUser } from "./auth.js";
import type { Config } from "./config.js";
import type { Db } from "./db.js";
import { AppError, toSafeError } from "./errors.js";
export interface Logger {
level: Config["LOG_LEVEL"];
info: (message: string, fields?: Record<string, unknown>) => void;
warn: (message: string, fields?: Record<string, unknown>) => void;
error: (message: string, fields?: Record<string, unknown>) => void;
debug: (message: string, fields?: Record<string, unknown>) => void;
}
const ORDER: Record<Config["LOG_LEVEL"], number> = {
silent: 0,
error: 1,
warn: 2,
info: 3,
debug: 4,
};
export const createLogger = (level: Config["LOG_LEVEL"], service: string): Logger => {
const emit = (name: keyof typeof ORDER, message: string, fields?: Record<string, unknown>) => {
if (ORDER[name] > ORDER[level]) return;
const line = JSON.stringify({
ts: new Date().toISOString(),
level: name,
service,
msg: message,
...fields,
});
if (name === "error") console.error(line);
else console.log(line);
};
return {
level,
info: (message, fields) => emit("info", message, fields),
warn: (message, fields) => emit("warn", message, fields),
error: (message, fields) => emit("error", message, fields),
debug: (message, fields) => emit("debug", message, fields),
};
};
/** Variables transportees par chaque requete : tracee d'identification. */
export interface AppEnv {
Variables: {
requestId: string;
/** Posee par attachUser quand le cookie de session est valide. */
user?: SessionUser;
token?: string;
};
}
/** Type public d'une application CoHaiSe, impose aux routes metier. */
export type App = Hono<AppEnv>;
/**
* IP reelle de l'appelant : X-Forwarded-For n'est cru que si le service fait
* confiance a son proxy. La valeur est tronquee a la taille de la colonne.
*/
export const clientIp = (context: Context, trustProxy: boolean): string | null => {
if (trustProxy) {
const forwarded = context.req.header("x-forwarded-for");
const first = forwarded?.split(",")[0]?.trim();
if (first) return first.slice(0, 45);
}
const env = context.env as
| { incoming?: { socket?: { remoteAddress?: string } } }
| undefined;
const address = env?.incoming?.socket?.remoteAddress;
return address ? address.slice(0, 45) : null;
};
/** Dependances remises aux routes metier au montage. */
export interface RouteDeps {
db: Db;
config: Config;
logger: Logger;
}
export interface AppOptions {
service: string;
config: Config;
db: Db;
logger: Logger;
/** Routes metier, montees sous /api/<service> dans le routing. */
routes: (app: App, deps: RouteDeps) => void;
/** Vrai quand l'API doit repondre a /healthz avec l'etat de la base. */
probeDb?: boolean;
}
export const createApp = ({ service, config, db, logger, routes, probeDb = true }: AppOptions): App => {
const app = new Hono<AppEnv>();
app.use("*", async (context: Context, next: Next) => {
const requestId = context.req.header("x-request-id") ?? randomUUID();
context.set("requestId", requestId);
context.res.headers.set("x-request-id", requestId);
context.res.headers.set("x-content-type-options", "nosniff");
context.res.headers.set("referrer-policy", "same-origin");
context.res.headers.set("x-frame-options", "DENY");
const started = performance.now();
await next();
const duration = Math.round(performance.now() - started);
if (context.req.method !== "OPTIONS") {
logger.debug("requete", {
requestId,
method: context.req.method,
path: new URL(context.req.url).pathname,
status: context.res.status,
durationMs: duration,
});
}
});
if (config.CORS_ORIGIN) {
app.use(
"*",
cors({
origin: config.CORS_ORIGIN.split(",").map((value) => value.trim()),
credentials: true,
maxAge: 600,
}),
);
}
app.get("/healthz", async (context) => {
if (!probeDb) return context.json({ status: "ok", service }, 200);
const started = performance.now();
try {
await db.query("SELECT 1");
return context.json(
{ status: "ok", service, db: "up", latencyMs: Math.round(performance.now() - started) },
200,
);
} catch (error) {
logger.error("sante base en echec", { error: String(error) });
return context.json({ status: "degraded", service, db: "down" }, 503);
}
});
routes(app, { db, config, logger });
app.notFound((context) =>
context.json({ error: { status: 404, code: "NOT_FOUND", message: "Route introuvable." } }, 404),
);
app.onError((error, context) => {
const safe = toSafeError(error);
const requestId = context.get("requestId");
if (safe.status >= 500) {
logger.error("erreur non geree", {
requestId,
code: safe.code,
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
});
} else {
logger.debug("refus", { requestId, code: safe.code, status: safe.status });
}
return context.json({ error: { ...safe, requestId } }, safe.status as 500);
});
return app;
};
export { AppError };
+57
View File
@@ -0,0 +1,57 @@
export {
loadConfig,
loadDbConfig,
ConfigError,
type Config,
type DbConfig,
} from "./config.js";
export { Db } from "./db.js";
export { AppError, toSafeError, type SafeError } from "./errors.js";
export {
createApp,
createLogger,
clientIp,
type App,
type AppEnv,
type AppOptions,
type Logger,
type RouteDeps,
} from "./http.js";
export {
attachUser,
clearSessionCookie,
createSession,
currentUser,
isHttpsRequest,
hashPassword,
requireAuth,
requireRole,
purgeExpiredSessions,
revokeSession,
SESSION_COOKIE,
setSessionCookie,
sha256,
verifyPassword,
type SessionUser,
} from "./auth.js";
export {
listMigrations,
runMigrations,
assertNoDrift,
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,
startService,
type Service,
type ServiceOptions,
} from "./service.js";
+147
View File
@@ -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, "&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") };
};
+75
View File
@@ -0,0 +1,75 @@
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.
*
* Le transport est construit une seule fois au demarrage. L'application exige
* les variables SMTP_* : sans elles, elle refuse de demarrer plutot que de
* 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 {
send: (message: MailMessage) => Promise<void>;
}
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,
});
// 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 }] }
: {}),
});
},
};
};
/** Lien absolu construit sur PUBLIC_ORIGIN, qui est valide au demarrage. */
export const link = (config: Config, path: string): string =>
new URL(path, config.PUBLIC_ORIGIN).toString();
+144
View File
@@ -0,0 +1,144 @@
import { createHash } from "node:crypto";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import type { Db } from "./db.js";
/**
* Applique les fichiers NNN_nom.sql dans l'ordre lexical, et uniquement ceux
* qui ne sont pas encore marques comme appliques. Idempotent : un second appel
* ne reexecute rien.
*
* Limite connue et assumee : le DDL MariaDB n'est pas transactionnel. Un fichier
* echoue au milieu, le reste des statements n'est pas applique et le fichier
* n'est pas enregistre. Le repasser reprend depuis son debut. C'est pourquoi
* chaque migration part de la ou la precedente a fini, et pourquoi une migration
* en desordre doit etre reparue et pas seulement sauvegardee depuis sa moitie.
*/
export interface MigrationFile {
version: string;
file: string;
sql: string;
checksum: string;
}
export interface MigrationResult {
applied: string[];
skipped: string[];
/** Migrations deja appliquees dont le contenu du fichier a change depuis. */
drifted: { version: string; recorded: string; current: string }[];
}
// Les deux bases utilisent un prefixe a trois chiffres (000, 001, …) ;
// quatre est accepte pour ne pas interdire le passage a un dossier plus large.
const FILE_PATTERN = /^(\d{3,4}_[a-z0-9_]+)\.sql$/;
export const listMigrations = async (dir: string): Promise<MigrationFile[]> => {
const entries = await readdir(dir);
const files = entries.filter((entry) => FILE_PATTERN.test(entry)).sort();
return Promise.all(
files.map(async (file) => {
const sql = await readFile(path.join(dir, file), "utf8");
return {
version: FILE_PATTERN.exec(file)?.[1] ?? file,
file,
sql,
checksum: createHash("sha256").update(sql).digest("hex"),
};
}),
);
};
const ensureLedger = async (db: Db): Promise<void> => {
await db.raw(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version VARCHAR(64) NOT NULL,
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`);
// Creer la colonne ici plutot que dans une migration : ajouter une ligne a un
// registre qui enregistre lui-meme les lignes ajoutees boucle sur lui-meme.
await db.raw(
"ALTER TABLE schema_migrations ADD COLUMN IF NOT EXISTS checksum CHAR(64) NULL AFTER applied_at",
);
};
export const runMigrations = async (
db: Db,
dir: string,
options: { dryRun?: boolean } = {},
): Promise<MigrationResult> => {
const files = await listMigrations(dir);
await ensureLedger(db);
const applied = new Map<string, { checksum: string | null }>();
const rows = await db.query<{ version: string; checksum: string | null }>(
"SELECT version, checksum FROM schema_migrations",
);
for (const row of rows) applied.set(row.version, { checksum: row.checksum });
const result: MigrationResult = { applied: [], skipped: [], drifted: [] };
for (const migration of files) {
const record = applied.get(migration.version);
if (record) {
result.skipped.push(migration.version);
if (record.checksum && record.checksum !== migration.checksum) {
result.drifted.push({
version: migration.version,
recorded: record.checksum,
current: migration.checksum,
});
}
continue;
}
if (options.dryRun) {
result.applied.push(migration.version);
continue;
}
// Un statement par un statement : un filet de faille reste visible et le
// point d'arret reste reproductible plutot qu'un bloc de 400 lignes perdu.
//
// Les lignes de commentaire sont retirees, pas le statement entier : un
// en-tete de fichier ou une legende au-dessus d'un INSERT ne doit pas
// faire sauter la requete, et encore moins la faire sauter en silence
// pendant que la version est enregistree comme appliquee.
const statements = migration.sql
.split(/;\s*(?:\r?\n|$)/)
.map((statement) =>
statement
.split(/\r?\n/)
.filter((line) => !line.trim().startsWith("--"))
.join("\n")
.trim(),
)
.filter((statement) => statement.length > 0);
for (const statement of statements) await db.raw(statement);
await db.exec("INSERT INTO schema_migrations (version, checksum) VALUES (?, ?)", [
migration.version,
migration.checksum,
]);
result.applied.push(migration.version);
}
return result;
};
export const assertNoDrift = (result: MigrationResult): void => {
if (result.drifted.length === 0) return;
const lines = result.drifted.map(
(d) => ` ${d.version} : appliquee ${d.recorded.slice(0, 12)}, fichier ${d.current.slice(0, 12)}`,
);
throw new Error(
`Migrations deja appliquees modifiees depuis leur execution (${result.drifted.length}) :\n` +
`${lines.join("\n")}\n` +
"Une migration appliquee ne se modifie pas : creez un nouveau fichier.",
);
};
+52
View File
@@ -0,0 +1,52 @@
/**
* Limiteur de debit en memoire.
*
* Volontairement minimal : une seule instance d'API, donc un simple compteur
* glissant par cle suffit. La protection robuste contre une attaque repartie
* vit dans nginx (`limit_req`) ; celle-ci couvre le cas ou l'API est jointe
* directement, sans proxy.
*
* La memoire est bornee : les entrees purgees a chaque appel ne s'accumulent
* pas, et une entree dont toutes les tentatives sont sorties de la fenetre est
* oubliee.
*/
interface Bucket {
count: number;
resetAt: number;
}
export interface RateLimiter {
/** Vrai quand la tentative est permise ; faux une fois la borne atteinte. */
allow: (key: string) => boolean;
}
export const createRateLimiter = (max: number, windowMs: number): RateLimiter => {
const buckets = new Map<string, Bucket>();
const prune = (now: number): void => {
for (const [key, bucket] of buckets) {
if (bucket.resetAt <= now) buckets.delete(key);
}
};
return {
allow: (key) => {
const now = Date.now();
// Purge a chaque appel : le cout est proportionnel au nombre de cles
// actives, borne par la fenetre, jamais par l'historique complet.
prune(now);
const bucket = buckets.get(key);
if (!bucket || bucket.resetAt <= now) {
buckets.set(key, { count: 1, resetAt: now + windowMs });
return true;
}
if (bucket.count >= max) return false;
bucket.count += 1;
return true;
},
};
};
/** Identifiant de limitation : IP reelle si le proxy est de confiance, sinon socket. */
export const rateLimitKey = (ip: string | null): string => ip ?? "unknown";
+152
View File
@@ -0,0 +1,152 @@
import { createServer, type Server } from "node:http";
import { type AddressInfo } from "node:net";
import { getRequestListener } from "@hono/node-server";
import { ConfigError, loadConfig, type Config } from "./config.js";
import { AppError } from "./errors.js";
import { Db } from "./db.js";
import {
createLogger,
createApp,
type App,
type AppOptions,
type Logger,
type RouteDeps,
} from "./http.js";
import { assertNoDrift, runMigrations } from "./migrate.js";
export interface ServiceOptions {
service: string;
/** Dossier contenant les fichiers NNN_nom.sql de cette application. */
migrationsDir?: string;
routes: (app: App, deps: RouteDeps) => void;
probeDb?: boolean;
/**
* Tache d'entretien executee une fois la base joignable et migree, avant
* l'ouverture du port (purge des sessions ou de la corbeille).
*/
onReady?: (deps: RouteDeps) => Promise<void> | void;
}
export interface Service {
config: Config;
db: Db;
logger: Logger;
app: App;
}
const fail = (error: unknown): never => {
if (error instanceof ConfigError) {
console.error(`\n [${new Date().toISOString()}] Demarrage refuse\n`);
console.error(error.message);
console.error(
"\n Verifiez .env (ou les variables du conteneur). .env.example recense l'ensemble du format attendu.\n",
);
} else {
console.error(
`\n [${new Date().toISOString()}] Demarrage refuse : ${
error instanceof Error ? error.message : String(error)
}\n`,
);
if (error instanceof Error && error.stack) console.error(error.stack);
}
process.exit(1);
};
/**
* Prepare le service sans lancer d'ecoute. Utile pour la CLI de migration et
* pour les tests, qui n'ont pas besoin d'un port.
*/
export const prepareService = async (options: ServiceOptions): Promise<Service> => {
const config = loadConfig();
const logger = createLogger(config.LOG_LEVEL, options.service);
const db = new Db(config);
if (options.migrationsDir) {
const result = await runMigrations(db, options.migrationsDir);
assertNoDrift(result);
if (result.applied.length > 0) {
logger.info("migrations appliquees", { versions: result.applied });
}
if (result.drifted.length > 0) {
logger.warn("migrations modifiees depuis leur execution", {
versions: result.drifted.map((d) => d.version),
});
}
}
if (options.onReady) {
try {
await options.onReady({ db, config, logger });
} catch (error) {
// L'entretien ne doit jamais empecher de servir : une purge en echec est
// signalee, la base reste exploitable.
logger.error("tache de demarrage en echec", {
error: error instanceof Error ? error.message : String(error),
});
}
}
const app = createApp({
service: options.service,
config,
db,
logger,
routes: options.routes,
probeDb: options.probeDb ?? true,
});
return { config, db, logger, app };
};
/** Demarre, ecoute, et s'arrete proprement. */
export const startService = async (options: ServiceOptions): Promise<Server> => {
let prepared: Service;
try {
prepared = await prepareService(options);
} catch (error) {
return fail(error);
}
const { config, db, logger, app } = prepared;
const server: Server = createServer(getRequestListener(app.fetch));
server.keepAliveTimeout = 65_000;
server.headersTimeout = 70_000;
const shutdown = async (signal: string) => {
logger.info("arret demande", { signal });
// Le SIGTERM de docker stop a un delai limite : fermer d'abord l'ecoute
// evite de nouvelles requetes, puis attendre les requetes en cours.
server.close(async () => {
await db.close().catch((error: unknown) => logger.error("fermeture base", { error: String(error) }));
logger.info("arret termine");
process.exit(0);
});
setTimeout(() => {
logger.warn("arret force apres delai");
process.exit(1);
}, 10_000).unref();
};
process.on("SIGTERM", () => void shutdown("SIGTERM"));
process.on("SIGINT", () => void shutdown("SIGINT"));
process.on("unhandledRejection", (reason) => {
logger.error("rejet de promesse non gere", { reason: String(reason) });
});
await new Promise<void>((resolve) => {
server.listen(config.PORT, "0.0.0.0", () => resolve());
});
const address = server.address() as AddressInfo;
logger.info("api prete", {
port: address.port,
env: config.NODE_ENV,
db: `${config.DB_HOST}:${config.DB_PORT}/${config.DB_NAME}`,
});
return server;
};
export { AppError, ConfigError, Db, createApp, createLogger, loadConfig, runMigrations };
export type { AppOptions, Config, Logger, RouteDeps };
+141
View File
@@ -0,0 +1,141 @@
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 "./lib/index.js";
import { absolutePath } from "./storage.js";
/**
* Traitement des images : vignette et metadonnees.
*
* sharp charge une bibliotheque native ; les images sont decodees en flux et
* la vignette est ecrite en WebP, format nettement plus compact que le JPEG
* d'origine pour un rendu equivalent dans une grille.
*/
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/");
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 qui vient d'etre ecrit. Les insertions sont idempotentes
* (ON DUPLICATE KEY) : un fichier deja indexe est simplement remis a jour.
*
* Un echec ici ne doit jamais faire echouer le depot lui-meme : le fichier est
* deja publie et payable, seule la vignette manquerait. L'appelant ignore donc
* l'erreur.
*/
export const indexMedia = async (
db: Db,
config: Config,
fileId: string,
mimeType: string | null,
source: string,
): Promise<void> => {
const kind = classify(mimeType);
if (!isImage(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],
);
};
/** Taille d'une vignette deja ecrite, ou null si le fichier a disparu. */
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;
}
};
+425
View File
@@ -0,0 +1,425 @@
import { randomBytes, randomUUID } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream";
import { z } from "zod";
import sharp from "sharp";
import {
AppError,
attachUser,
branding,
clientIp,
createMailer,
createRateLimiter,
currentUser,
hashPassword,
link,
rateLimitKey,
renderMail,
requireAuth,
sha256,
verifyPassword,
type App,
type Config,
type Db,
type SessionUser,
} from "../lib/index.js";
import { audit } from "../access.js";
import { absolutePath, diskUsage, fileExists, openForDownload } from "../storage.js";
const AVATAR_MAX_BYTES = 8 * 1024 * 1024;
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");
const parse = <T>(schema: z.ZodType<T>, body: unknown): T => {
const result = schema.safeParse(body);
if (!result.success) {
const issue = result.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
return result.data;
};
const profileInput = z.object({
first_name: z.string().trim().min(1).max(50),
last_name: z.string().trim().min(1).max(50),
});
const forgotInput = z.object({ email: z.string().trim().email().max(255) });
const resetInput = z.object({
token: z.string().min(10).max(400),
password: z.string().min(8).max(1024),
});
const emailChangeInput = z.object({
password: z.string().min(1).max(1024),
new_email: z.string().trim().email().max(255),
});
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 => {
const ip = clientIp(context, config.TRUST_PROXY);
const key = `${rateLimitKey(ip)}:${extra}`;
if (!limiter.allow(key)) {
throw AppError.unprocessable("Trop de tentatives. Reessayez dans une minute.");
}
};
app.patch("/api/cloud/account/profile", requireAuth, async (context) => {
const user = currentUser(context);
const data = parse(profileInput, await context.req.json().catch(() => null));
await db.exec("UPDATE users SET first_name = ?, last_name = ? WHERE id = ?", [
data.first_name,
data.last_name,
user.id,
]);
await audit(db, context, user, "profile.update", "user", user.id, null, config.TRUST_PROXY);
return context.json({ ok: true, first_name: data.first_name, last_name: data.last_name });
});
app.get("/api/cloud/account/sessions", requireAuth, async (context) => {
const user = currentUser(context);
const current = sha256(context.get("token") ?? "");
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 context.json({
sessions: 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,
})),
});
});
app.delete("/api/cloud/account/sessions/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
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.");
return context.json({ ok: true });
});
app.delete("/api/cloud/account/sessions", requireAuth, async (context) => {
const user = currentUser(context);
const current = sha256(context.get("token") ?? "");
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],
);
return context.json({ ok: true });
});
app.put("/api/cloud/account/avatar", requireAuth, async (context) => {
const user = currentUser(context);
const declared = Number(context.req.header("content-length") ?? "");
if (!Number.isSafeInteger(declared) || declared <= 0) {
throw AppError.badRequest("Envoi d'image invalide.");
}
if (declared > AVATAR_MAX_BYTES) {
throw AppError.payloadTooLarge("L'image ne doit pas depasser 8 Mo.");
}
const source = Buffer.from(await context.req.arrayBuffer());
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],
);
});
await audit(db, context, user, "avatar.update", "user", user.id, null, config.TRUST_PROXY);
return context.json({ ok: true });
});
app.get("/api/cloud/account/avatar/:userId", requireAuth, async (context) => {
const target = context.req.param("userId") ?? "";
const row = await db.one<{ original_path: string; size_bytes: number }>(
"SELECT original_path, size_bytes FROM user_avatars WHERE user_id = ?",
[target],
);
if (!row) throw AppError.notFound("Avatar introuvable.");
const absolute = absolutePath(config.VARIANT_DIR, row.original_path);
if (!(await fileExists(absolute))) throw AppError.notFound("Avatar introuvable.");
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
return new Response(stream, {
headers: {
"content-type": "image/webp",
"content-length": String(row.size_bytes),
"cache-control": "private, max-age=86400",
},
});
});
app.delete("/api/cloud/account/avatar", requireAuth, async (context) => {
const user = currentUser(context);
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],
);
});
return context.json({ ok: true });
});
app.post("/api/cloud/account/forgot-password", async (context) => {
const data = parse(forgotInput, await context.req.json().catch(() => null));
throttle(context, `forgot:${data.email.toLowerCase()}`);
const user = await db.one<{ id: string; email: string }>(
"SELECT id, email FROM users WHERE active_email = ? AND is_active = 1",
[data.email],
);
// Reponse identique que le compte existe ou non : rien ne permet de
// decouvrir une adresse enregistree.
if (user) {
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(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",
...mail,
})
.catch(() => undefined);
}
return context.json({ ok: true });
});
app.post("/api/cloud/account/reset-password", async (context) => {
const data = parse(resetInput, await context.req.json().catch(() => null));
throttle(context, "reset");
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(data.token)],
);
if (!row) throw AppError.badRequest("Lien invalide ou expire.");
const hash = await hashPassword(data.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) {
const actor: SessionUser = {
id: row.user_id,
email: account.email,
first_name: account.first_name,
last_name: account.last_name,
role_slug: "user",
role_name: "",
is_active: 1,
must_change_password: 0,
};
await audit(db, context, actor, "password.reset", "user", row.user_id, null, config.TRUST_PROXY);
}
return context.json({ ok: true });
});
app.post("/api/cloud/account/email-change", requireAuth, async (context) => {
const user = currentUser(context);
const data = parse(emailChangeInput, await context.req.json().catch(() => null));
throttle(context, `email:${user.id}`);
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(data.password, row.password_hash))) {
throw AppError.unauthorized("Mot de passe incorrect.");
}
if (data.new_email.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 = ?", [data.new_email]);
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, data.new_email, sha256(token), new Date(Date.now() + HOUR_MS)],
);
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: mail.text,
html: mail.html,
})
.catch(() => undefined);
await audit(
db,
context,
user,
"email.change_request",
"user",
user.id,
{ new_email: data.new_email },
config.TRUST_PROXY,
);
return context.json({ ok: true });
});
app.post("/api/cloud/account/email-change/confirm", async (context) => {
const data = parse(
z.object({ token: z.string().min(10).max(400) }),
await context.req.json().catch(() => null),
);
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(data.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 context.json({ ok: true, email: row.new_email });
});
};
+453
View File
@@ -0,0 +1,453 @@
import { randomUUID } from "node:crypto";
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()
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
const createUserSchema = z.object({
email: z.string().trim().email().max(255),
first_name: z.string().trim().min(1).max(50),
last_name: z.string().trim().min(1).max(50),
role_slug: z.enum(["admin", "user"]).default("user"),
quota_bytes: z.number().int().positive().nullish(),
max_file_bytes: z.number().int().positive().nullish(),
password: z.string().min(8).max(1024).nullish(),
});
const updateUserSchema = z.object({
first_name: z.string().trim().min(1).max(50).optional(),
last_name: z.string().trim().min(1).max(50).optional(),
role_slug: z.enum(["admin", "user"]).optional(),
quota_bytes: z.number().int().positive().optional(),
max_file_bytes: z.number().int().positive().optional(),
is_active: z.boolean().optional(),
});
const createLocationSchema = z.object({
name: z.string().trim().min(1).max(100),
slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,99}$/, "Identifiant technique invalide."),
mount_path: z.string().trim().min(1).max(255),
quota_bytes: z.number().int().positive().nullish(),
});
const updateLocationSchema = z.object({
name: z.string().trim().min(1).max(100).optional(),
quota_bytes: z.number().int().positive().nullable().optional(),
is_active: z.boolean().optional(),
});
const parse = <T>(schema: z.ZodType<T>, body: unknown): T => {
const result = schema.safeParse(body);
if (!result.success) {
const issue = result.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
return result.data;
};
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;
}
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"];
/** 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";
const bytes = new Uint8Array(18);
globalThis.crypto.getRandomValues(bytes);
let out = "";
for (const byte of bytes) out += alphabet[byte % alphabet.length];
return out;
};
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 }>(
"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 context.json({
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),
});
});
app.get("/api/cloud/admin/users", requireAuth, async (context) => {
requireAdmin(context);
const query = (context.req.query("q") ?? "").trim();
const rows = query
? await 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}%`],
)
: await db.query<AdminUserRow>(
`${SELECT_USER} WHERE u.deleted_at IS NULL ORDER BY u.email LIMIT 500`,
);
return context.json({ users: rows.map(publicUser) });
});
app.post("/api/cloud/admin/users", requireAuth, async (context) => {
requireAdmin(context);
const data = parse(createUserSchema, await context.req.json().catch(() => null));
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(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);
});
app.patch("/api/cloud/admin/users/:id", requireAuth, async (context) => {
const actor = currentUser(context);
requireAdmin(context);
const id = context.req.param("id") ?? "";
if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
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.");
const data = parse(updateUserSchema, await context.req.json().catch(() => null));
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 === actor.id) 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 === actor.id) {
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],
);
}
}
const updated = await db.required<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
return context.json({ user: publicUser(updated) });
});
app.delete("/api/cloud/admin/users/:id", requireAuth, async (context) => {
const actor = currentUser(context);
requireAdmin(context);
const id = context.req.param("id") ?? "";
if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
if (id === actor.id) throw AppError.badRequest("Vous ne pouvez pas supprimer votre propre compte.");
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.");
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]);
return context.json({ ok: true });
});
app.post("/api/cloud/admin/users/:id/reset-password", requireAuth, async (context) => {
requireAdmin(context);
const id = context.req.param("id") ?? "";
if (!uuidParam.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
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],
);
// 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: mail.text,
html: mail.html,
})
.catch(() => undefined);
return context.json({ password });
});
app.get("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
requireAdmin(context);
const rows = await db.query(
`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, 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)
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;
}
return context.json({ ok: true }, 201);
});
app.patch("/api/cloud/admin/storage-locations/:id", requireAuth, async (context) => {
requireAdmin(context);
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Emplacement introuvable.");
const data = parse(updateLocationSchema, await context.req.json().catch(() => null));
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(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);
return context.json({ ok: true });
});
app.get("/api/cloud/admin/audit", requireAuth, async (context) => {
requireAdmin(context);
const limit = Math.min(500, Math.max(1, Number(context.req.query("limit")) || 100));
const offset = Math.max(0, Number(context.req.query("offset")) || 0);
const action = context.req.query("action");
const rows = action
? await db.query(
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
FROM audit_logs WHERE action = ? ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`,
[action],
)
: await db.query(
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
FROM audit_logs ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`,
);
return context.json({ entries: rows });
});
};
+179
View File
@@ -0,0 +1,179 @@
import { z } from "zod";
import {
AppError,
attachUser,
clearSessionCookie,
clientIp,
createRateLimiter,
createSession,
currentUser,
hashPassword,
isHttpsRequest,
rateLimitKey,
requireAuth,
revokeSession,
setSessionCookie,
sha256,
verifyPassword,
type App,
type Config,
type Db,
} from "../lib/index.js";
const credentials = z.object({
email: z.string().trim().min(3).max(255),
password: z.string().min(1).max(1024),
});
/**
* Hachage de repli, calcule paresseusement a la premiere echec de connexion.
* Sans lui, un compte inexistant repond plus vite qu'un compte existant, ce qui
* permet d'enumerer les adresses e-mail en mesurant le temps de reponse.
*/
let dummyHash: Promise<string> | undefined;
const decoyHash = (): Promise<string> => (dummyHash ??= hashPassword("aucun-compte-ne-correspond"));
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;
}
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 === 1,
});
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
FROM users u
JOIN roles r ON r.id = u.role_id`;
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/*", attachUser(db));
const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS);
app.post("/api/cloud/auth/login", async (context) => {
// Borne les tentatives par IP : une attaque par dictionnaire sur un mot de
// passe faible est arretee avant le calcul scrypt, couteux.
const ip = clientIp(context, config.TRUST_PROXY);
if (!limiter.allow(rateLimitKey(ip))) {
throw AppError.unprocessable("Trop de tentatives de connexion. Reessayez dans une minute.");
}
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Identifiants invalides.");
const { email, password } = parsed.data;
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.active_email = ?`, [email]);
// Meme travail dans les deux cas, pour que le temps de reponse ne
// revele pas si l'adresse existe.
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 forwarded = context.req.header("x-forwarded-for");
const { token, expiresAt } = await createSession(
db,
row.id,
{
ipAddress: config.TRUST_PROXY && forwarded ? forwarded.split(",")[0]?.trim() : null,
userAgent: context.req.header("user-agent"),
},
config.SESSION_TTL_HOURS,
);
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP() WHERE id = ?", [row.id]);
// Le marqueur Secure suit le protocole reellement annonce, pas
// NODE_ENV : un deploiement en HTTP local doit rester utilisable, un
// deploiement https:// ne doit jamais poser de cookie cleartext.
// Le schema reel de la requete, pas PUBLIC_ORIGIN : voir isHttpsRequest.
const secure = isHttpsRequest(context, config.TRUST_PROXY);
setSessionCookie(context, token, expiresAt, secure);
return context.json({ user: publicUser(row) });
});
app.post("/api/cloud/auth/logout", requireAuth, async (context) => {
const token = context.get("token");
if (token) await revokeSession(db, token);
clearSessionCookie(context);
return context.json({ ok: true });
});
app.get("/api/cloud/auth/me", requireAuth, async (context) => {
const session = currentUser(context);
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ?`, [session.id]);
if (!row) throw AppError.unauthorized();
return context.json({ user: publicUser(row) });
});
const changePassword = z.object({
current: z.string().min(1).max(1024),
next: z.string().min(8).max(1024),
});
/**
* Changement impose a la premiere connexion. Les autres sessions sont
* revoquees : si le compte avait ete ouvert ailleurs, l'ancien mot de passe
* ne doit plus rien ouvrir.
*/
app.post("/api/cloud/auth/change-password", requireAuth, async (context) => {
const session = currentUser(context);
const parsed = changePassword.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
}
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[session.id],
);
if (!row) throw AppError.unauthorized();
if (!(await verifyPassword(parsed.data.current, row.password_hash))) {
throw AppError.unauthorized("Mot de passe actuel incorrect.");
}
if (parsed.data.current === parsed.data.next) {
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
}
const hash = await hashPassword(parsed.data.next);
await db.exec(
`UPDATE users
SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP()
WHERE id = ?`,
[hash, session.id],
);
// La session courante est conservee, toutes les autres sont revoquees.
await db.exec(
`UPDATE user_sessions
SET revoked_at = UTC_TIMESTAMP()
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
[session.id, sha256(context.get("token") ?? "")],
);
return context.json({ ok: true });
});
};
+539
View File
@@ -0,0 +1,539 @@
import { randomUUID } from "node:crypto";
import path from "node:path";
import { Readable } from "node:stream";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
requireRole,
type App,
type Config,
type Db,
} 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,
publish,
relativePathFor,
temporaryPath,
writeBody,
} from "../storage.js";
const uuid = z
.string()
.regex(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
"Identifiant invalide.",
);
const MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,127}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,127}$/;
const renameInput = z.object({
name: z.string().trim().min(1).max(255),
});
const moveInput = z.object({
folderId: uuid.nullish(),
});
const parse = <T>(schema: z.ZodType<T>, body: unknown): T => {
const result = schema.safeParse(body);
if (!result.success) {
const issue = result.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
return result.data;
};
interface FileRow {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
checksum_sha256: string | null;
relative_path: string;
owner_id: string | null;
is_starred: number;
download_count: number;
created_at: string;
updated_at: string;
}
const SELECT_FILE = `SELECT id, folder_id, name, mime_type, size_bytes, checksum_sha256,
relative_path, owner_id, is_starred, download_count, created_at, updated_at
FROM files`;
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,
});
/** Nom d'affichage : ni separateur, ni sequence d'echappement, ni point seul. */
const assertName = (raw: string | undefined): string => {
const name = (raw ?? "").trim();
if (!name || name.length > 255) {
throw AppError.badRequest("Le nom du fichier doit contenir entre 1 et 255 caracteres.");
}
if (name === "." || name === ".." || /[/\\\0-\x1f]/.test(name)) {
throw AppError.badRequest("Le nom du fichier ne peut pas contenir de separateur.");
}
return name;
};
const mimeOf = (header: string | undefined): string => {
const value = (header ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
return MIME.test(value) ? value : "application/octet-stream";
};
/** Le nom HTTP ne contient que des octets ASCII imprimables, UTF-8 en prime. */
const contentDisposition = (name: string): string => {
const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
};
export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/files/*", attachUser(db));
app.use("/api/cloud/files", attachUser(db));
/**
* Depot en un seul passage. Le corps n'est pas un formulaire multipart mais
* l'objet brut : le navigateur envoie le File tel quel, ce qui evite de
* faire tenir plusieurs gigaoctets en memoire pendant le decoupage.
*/
app.put(
"/api/cloud/files",
requireAuth,
requireRole("admin", "user"),
async (context) => {
const user = currentUser(context);
const name = assertName(context.req.query("name"));
const rawFolder = context.req.query("folderId");
const folderId = rawFolder === undefined || rawFolder === "" ? null : rawFolder;
if (folderId !== null) {
if (!uuid.safeParse(folderId).success) {
throw AppError.badRequest("Identifiant de dossier invalide.");
}
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 declaredHeader = context.req.header("content-length");
if (declaredHeader === undefined) {
throw new AppError(411, "LENGTH_REQUIRED", "En-tête Content-Length manquant.");
}
const declared = Number(declaredHeader);
if (!Number.isSafeInteger(declared) || declared < 0) {
throw AppError.badRequest("Longueur de corps invalide.");
}
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();
// Les deux bornes sont verifiees avant d'ecrire quoi que ce soit.
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.");
}
const duplicate = await db.one(
`SELECT 1 AS taken FROM files
WHERE folder_id <=> ? AND active_name = ? AND deleted_at IS NULL LIMIT 1`,
[folderId, name],
);
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);
const destination = absolutePath(config.MEDIA_DIR, relative);
const temporary = temporaryPath(config.MEDIA_DIR, location.slug);
await ensureDir(path.dirname(destination));
const body = context.req.raw.body;
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;
}
// Publication puis ecriture en base : si la base refuse, le fichier
// est retire, il ne reste aucun orphelin dans les deux sens.
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,
mimeOf(context.req.header("content-type")),
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;
}
// Vignette et metadonnees : best-effort, le depot reste valide si sharp
// echoue sur un format exotique.
await indexMedia(db, config, id, mimeOf(context.req.header("content-type")), destination).catch(
() => undefined,
);
await audit(
db,
context,
user,
"file.upload",
"file",
id,
{ name, size: written.size, folder_id: folderId },
config.TRUST_PROXY,
);
const created = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [id]);
return context.json({ file: publicFile(created) }, 201);
},
);
app.get("/api/cloud/files", requireAuth, async (context) => {
const user = currentUser(context);
const rawFolder = context.req.query("folderId");
const folderId = rawFolder === undefined || rawFolder === "" ? null : rawFolder;
if (folderId !== null && !uuid.safeParse(folderId).success) {
throw AppError.badRequest("Identifiant de dossier invalide.");
}
// Contre l'IDOR : un dossier qui n'appartient pas a la session rend une
// liste vide plutot que de confirmer son existence.
if (folderId !== null && user.role_slug !== "admin" && !(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.");
}
const rows = await db.query<FileRow>(
`${SELECT_FILE}
WHERE deleted_at IS NULL
AND (folder_id <=> ?)
AND ( ? = 1
OR owner_id = ?
OR ( folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folders f
WHERE f.id = files.folder_id AND f.access_type = 'public' ) )
OR ( folder_id IS NOT NULL
AND EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = files.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 name`,
[folderId, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
);
return context.json({ folderId, files: rows.map(publicFile) });
});
app.get("/api/cloud/files/:id/download", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const allowed =
user.role_slug === "admin" ||
(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.");
const absolute = absolutePath(config.MEDIA_DIR, row.relative_path);
if (!(await fileExists(absolute))) throw AppError.notFound("Fichier introuvable sur le support.");
await db
.exec(
`UPDATE files
SET download_count = download_count + 1, last_accessed_at = UTC_TIMESTAMP()
WHERE id = ?`,
[row.id],
)
.catch(() => undefined);
const mime = row.mime_type ?? "application/octet-stream";
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
return new Response(stream, {
headers: {
"content-type": mime,
"content-length": String(row.size_bytes),
"content-disposition": contentDisposition(row.name),
// Le type vient de la base, jamais du contenu : un fichier HTML
// telecharge ne doit jamais etre rendu en navigation.
"x-content-type-options": "nosniff",
"cache-control": "private, max-age=0, must-revalidate",
},
});
});
/** Vignette d'image. Memes droits que le telechargement, cache prive. */
app.get("/api/cloud/files/:id/thumbnail", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Image introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Image introuvable.");
const allowed =
user.role_slug === "admin" ||
(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("Image introuvable.");
const variant = await db.one<{ path: string }>(
"SELECT path FROM file_variants WHERE file_id = ? AND purpose = 'thumbnail'",
[row.id],
);
if (!variant) throw AppError.notFound("Vignette introuvable.");
const size = await thumbnailSize(config, variant.path);
if (size === null) throw AppError.notFound("Vignette introuvable.");
const absolute = absolutePath(config.VARIANT_DIR, variant.path);
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
return new Response(stream, {
headers: {
"content-type": "image/webp",
"content-length": String(size),
"cache-control": "private, max-age=86400",
"x-content-type-options": "nosniff",
},
});
});
/** Renomme un fichier. Le chemin physique ne bouge pas : il suit l'UUID. */
app.patch("/api/cloud/files/:id", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const owner = row.owner_id !== null && row.owner_id === user.id;
const permitted =
user.role_slug === "admin" ||
owner ||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!permitted) throw AppError.notFound("Fichier introuvable.");
const { name: rawName } = parse(renameInput, await context.req.json().catch(() => null));
const name = assertName(rawName);
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;
}
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [row.id]);
await audit(db, context, user, "file.rename", "file", row.id, { name }, config.TRUST_PROXY);
return context.json({ file: publicFile(updated) });
});
/** Deplace un fichier vers un autre dossier, racine comprise. */
app.post("/api/cloud/files/:id/move", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const owner = row.owner_id !== null && row.owner_id === user.id;
const canLeave =
user.role_slug === "admin" ||
owner ||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!canLeave) throw AppError.notFound("Fichier introuvable.");
const { folderId } = parse(moveInput, await context.req.json().catch(() => null));
const destination = folderId ?? null;
if (destination !== null && !(await canWrite(db, user, destination))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
try {
await db.exec("UPDATE files SET folder_id = ? WHERE id = ?", [destination, 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;
}
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [row.id]);
await audit(db, context, user, "file.move", "file", row.id, { folderId: destination }, config.TRUST_PROXY);
return context.json({ file: publicFile(updated) });
});
/** Bascule le marqueur favori. */
app.put("/api/cloud/files/:id/star", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const allowed =
user.role_slug === "admin" ||
(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.");
await db.exec("UPDATE files SET is_starred = 1 - is_starred WHERE id = ?", [row.id]);
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE id = ?`, [row.id]);
return context.json({ file: publicFile(updated) });
});
app.delete("/api/cloud/files/:id", requireAuth, async (context) => {
const user = currentUser(context);
const rawId = context.req.param("id");
if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]);
if (!row) throw AppError.notFound("Fichier introuvable.");
const owner = row.owner_id !== null && row.owner_id === user.id;
const permitted =
user.role_slug === "admin" ||
owner ||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
if (!permitted) throw AppError.notFound("Fichier introuvable.");
// Suppression logique : le fichier reste sur disque le temps de la
// retention (trash_retention_days), et son nom redevient disponible grace
// a la colonne active_name.
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.");
await audit(
db,
context,
user,
"file.delete",
"file",
row.id,
{ name: row.name, size: row.size_bytes, folder_id: row.folder_id },
config.TRUST_PROXY,
);
return context.json({ ok: true });
});
};
+397
View File
@@ -0,0 +1,397 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
requireRole,
type App,
type Config,
type Db,
} from "../lib/index.js";
import { audit, canManageFolder, canRead, canWrite } from "../access.js";
const uuid = z
.string()
.regex(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
"Identifiant invalide.",
);
const createFolder = z.object({
name: z.string().trim().min(1).max(255),
parentId: uuid.nullish(),
description: z.string().trim().max(2000).nullish(),
});
const updateFolder = z.object({
name: z.string().trim().min(1).max(255).optional(),
description: z.string().trim().max(2000).nullish(),
});
const moveFolder = z.object({
parentId: uuid.nullish(),
});
const permissionInput = z.object({
email: z.string().trim().min(3).max(255),
level: z.enum(["read", "write", "admin"]),
expiresAt: z.string().datetime().nullish(),
});
interface FolderRow {
id: string;
parent_id: string | null;
name: string;
description: string | null;
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.description, f.owner_id,
f.access_type, f.is_system, f.storage_location_id, f.created_at, f.updated_at
FROM folders f`;
const publicFolder = (row: FolderRow) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
description: row.description,
owner_id: row.owner_id,
access_type: row.access_type,
is_system: row.is_system === 1,
created_at: row.created_at,
updated_at: row.updated_at,
});
const assertName = (raw: string): string => {
const name = raw.trim();
if (!name || name.length > 255) {
throw AppError.badRequest("Le nom du dossier doit contenir entre 1 et 255 caracteres.");
}
if (name === "." || name === ".." || /[/\\\0-\x1f]/.test(name)) {
throw AppError.badRequest("Le nom du dossier ne peut pas contenir de separateur.");
}
return name;
};
const parse = <T>(schema: z.ZodType<T>, body: unknown): T => {
const result = schema.safeParse(body);
if (!result.success) {
const issue = result.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
return result.data;
};
/** Id du dossier et de tous ses descendants, y compris lui-meme. */
const subtreeIds = async (db: Db, rootId: string): Promise<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);
};
export const registerFolderRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/folders/*", attachUser(db));
app.use("/api/cloud/folders", attachUser(db));
app.get("/api/cloud/folders", requireAuth, async (context) => {
const user = currentUser(context);
const rawParent = context.req.query("parentId");
const parentId = rawParent === undefined || rawParent === "" ? null : rawParent;
if (parentId !== null && !uuid.safeParse(parentId).success) {
throw AppError.badRequest("Identifiant de dossier invalide.");
}
if (user.role_slug !== "admin" && parentId !== null) {
// Contre l'IDOR : on ne liste un dossier que si la session y a acces.
if (!(await canRead(db, user, parentId))) {
throw AppError.notFound("Dossier introuvable.");
}
}
const rows = await db.query<FolderRow>(
`${SELECT_FOLDER}
WHERE f.deleted_at IS NULL
AND (f.parent_id <=> ?)
AND ( ? = 1
OR f.owner_id = ?
OR f.access_type = 'public'
OR EXISTS ( SELECT 1 FROM folder_permissions fp
WHERE fp.folder_id = f.id AND fp.user_id = ?
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
ORDER BY f.name`,
[parentId, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
);
return context.json({ parentId, folders: rows.map(publicFolder) });
});
app.post(
"/api/cloud/folders",
requireAuth,
requireRole("admin", "user"),
async (context) => {
const user = currentUser(context);
const { name: rawName, parentId, description } = parse(
createFolder,
await context.req.json().catch(() => null),
);
const name = assertName(rawName);
if (parentId) {
if (!(await canWrite(db, user, parentId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
}
const duplicate = await db.one(
`SELECT 1 AS taken FROM folders
WHERE parent_id <=> ? AND active_name = ? AND deleted_at IS NULL LIMIT 1`,
[parentId ?? null, name],
);
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
const parent = parentId
? await db.one<{ id: string; storage_location_id: number }>(
"SELECT id, storage_location_id FROM folders WHERE id = ? AND deleted_at IS NULL",
[parentId],
)
: null;
if (parentId && !parent) throw AppError.notFound("Dossier parent introuvable.");
const locationId =
parent?.storage_location_id ??
(
await db.one<{ id: number }>(
`SELECT id FROM storage_locations
WHERE is_active = 1 AND deleted_at IS NULL ORDER BY id LIMIT 1`,
)
)?.id;
if (locationId === undefined) {
throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible.");
}
const id = randomUUID();
try {
await db.exec(
`INSERT INTO folders (id, storage_location_id, parent_id, name, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
[id, locationId, parentId ?? null, name, description ?? null, user.id, user.id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
const created = await db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
await audit(db, context, user, "folder.create", "folder", id, { name }, config.TRUST_PROXY);
return context.json({ folder: publicFolder(created) }, 201);
},
);
app.patch("/api/cloud/folders/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const existing = await db.one<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.");
const data = parse(updateFolder, await context.req.json().catch(() => null));
if (data.name === undefined && data.description === undefined) {
throw AppError.badRequest("Rien a modifier.");
}
const name = data.name === undefined ? existing.name : assertName(data.name);
try {
await db.exec(
"UPDATE folders SET name = ?, description = ? WHERE id = ?",
[name, data.description === undefined ? existing.description : data.description, id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja ici.");
}
throw error;
}
const updated = await db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
await audit(db, context, user, "folder.update", "folder", id, { name }, config.TRUST_PROXY);
return context.json({ folder: publicFolder(updated) });
});
app.post("/api/cloud/folders/:id/move", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const existing = await db.one<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.");
const { parentId } = parse(moveFolder, await context.req.json().catch(() => null));
if (parentId !== null && parentId !== undefined) {
if (!(await canWrite(db, user, parentId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier de destination.");
}
// Refuse un deplacement dans soi-meme ou dans un descendant : sans cela,
// l'arborescence se detache du graphe et devient inaccessible.
const descendants = await subtreeIds(db, id);
if (descendants.includes(parentId)) {
throw AppError.badRequest("Impossible de deplacer un dossier dans lui-meme.");
}
}
try {
await db.exec("UPDATE folders SET parent_id = ? WHERE id = ?", [parentId ?? null, id]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce nom existe deja dans la destination.");
}
throw error;
}
const updated = await db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
await audit(db, context, user, "folder.move", "folder", id, { parentId: parentId ?? null }, config.TRUST_PROXY);
return context.json({ folder: publicFolder(updated) });
});
/** Suppression logique recursive : le dossier, ses descendants et leurs fichiers. */
app.delete("/api/cloud/folders/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const existing = await db.one<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,
);
});
await audit(db, context, user, "folder.delete", "folder", id, { name: existing.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
// --- Permissions nominatives -------------------------------------------
app.get("/api/cloud/folders/:id/permissions", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const rows = await db.query<{
user_id: string;
email: string;
first_name: string;
last_name: string;
level: string;
expires_at: string | null;
created_at: string;
}>(
`SELECT fp.user_id, u.email, u.first_name, u.last_name, fp.level, fp.expires_at, fp.created_at
FROM folder_permissions fp
JOIN users u ON u.id = fp.user_id
WHERE fp.folder_id = ?
ORDER BY u.email`,
[id],
);
return context.json({
permissions: rows.map((row) => ({
user_id: row.user_id,
email: row.email,
first_name: row.first_name,
last_name: row.last_name,
level: row.level,
expires_at: row.expires_at,
created_at: row.created_at,
})),
});
});
app.post("/api/cloud/folders/:id/permissions", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const { email, level, expiresAt } = parse(
permissionInput,
await context.req.json().catch(() => null),
);
const target = await db.one<{ id: string }>(
"SELECT id FROM users WHERE active_email = ? AND deleted_at IS NULL",
[email],
);
if (!target) throw AppError.notFound("Aucun compte ne correspond a cette adresse.");
if (target.id === user.id) {
throw AppError.badRequest("Vous etes deja proprietaire de ce dossier.");
}
const expires = expiresAt ? new Date(expiresAt) : null;
await db.exec(
`INSERT INTO folder_permissions (id, folder_id, user_id, level, expires_at, granted_by)
VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE level = VALUES(level), expires_at = VALUES(expires_at), granted_by = VALUES(granted_by)`,
[randomUUID(), id, target.id, level, expires, user.id],
);
await audit(db, context, user, "folder.share", "folder", id, { email, level }, config.TRUST_PROXY);
return context.json({ ok: true }, 201);
});
app.delete("/api/cloud/folders/:id/permissions/:userId", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
const userId = context.req.param("userId") ?? "";
if (!uuid.safeParse(id).success || !uuid.safeParse(userId).success) {
throw AppError.notFound("Dossier introuvable.");
}
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
const result = await db.exec(
"DELETE FROM folder_permissions WHERE folder_id = ? AND user_id = ?",
[id, userId],
);
if (result.affectedRows === 0) throw AppError.notFound("Partage introuvable.");
await audit(db, context, user, "folder.unshare", "folder", id, { userId }, config.TRUST_PROXY);
return context.json({ ok: true });
});
};
+85
View File
@@ -0,0 +1,85 @@
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "../lib/index.js";
/**
* Galerie : liste des fichiers accompagnes de leur nature (image, video,
* document...), filtree par les memes droits que l'explorateur. Le dossier
* public et les permissions nominatives sont pris en compte, sans exception.
*/
const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const;
export const registerMediaRoutes = (app: App, db: Db): void => {
app.use("/api/cloud/media", attachUser(db));
app.get("/api/cloud/media", requireAuth, async (context) => {
const user = currentUser(context);
const kind = context.req.query("kind") ?? "";
if (kind !== "" && !(KINDS as readonly string[]).includes(kind)) {
throw AppError.badRequest("Type de media inconnu.");
}
const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 60));
const offset = Math.max(0, Number(context.req.query("offset")) || 0);
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,
fi.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 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 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}`,
[kind, kind, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
);
return context.json({
kind: kind || null,
items: 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,
})),
});
});
};
+113
View File
@@ -0,0 +1,113 @@
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "../lib/index.js";
/**
* Recherche par nom, filtree par les droits de la session. Le motif est
* echappe : `%` et `_` saisis par l'utilisateur deviennent des caracteres
* litteraux, jamais des jokers SQL. L'echappement par defaut de LIKE (barre
* oblique inverse) suffit.
*/
const escapeLike = (value: string): string =>
value.replace(/[\\%_]/g, (match) => `\\${match}`);
const LIMIT = 100;
export const registerSearchRoutes = (app: App, db: Db): void => {
app.use("/api/cloud/search", attachUser(db));
app.get("/api/cloud/search", requireAuth, async (context) => {
const user = currentUser(context);
const q = (context.req.query("q") ?? "").trim();
if (q.length < 1) throw AppError.badRequest("Indiquez un terme de recherche.");
const admin = user.role_slug === "admin";
const pattern = `%${escapeLike(q).slice(0, 110)}%`;
const folders = await db.query<{
id: string;
parent_id: string | null;
name: string;
description: string | null;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
}>(
`SELECT f.id, f.parent_id, f.name, f.description, 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, admin ? 1 : 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,
fi.is_starred, fi.created_at, fi.updated_at
FROM files fi
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 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}`,
[pattern, admin ? 1 : 0, user.id, user.id],
);
return context.json({
query: q,
folders: folders.map((row) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
description: row.description,
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,
})),
});
});
};
+378
View File
@@ -0,0 +1,378 @@
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Config,
type Db,
} from "../lib/index.js";
import { audit } from "../access.js";
import { absolutePath, discard } from "../storage.js";
const uuid = z
.string()
.regex(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
"Identifiant invalide.",
);
/**
* La corbeille se prete a l'echelle d'un utilisateur : un proprietaire voit ses
* propres elements supprimes, un administrateur voit tout. Un element supprime
* dont le parent est lui aussi supprime n'est pas liste : c'est la racine de la
* suppression qui porte l'action.
*/
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);
};
/** Remonte la chaine des parents et annule leur suppression. */
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;
}
};
/** Supprime physiquement des fichiers et rend leur espace aux quotas. */
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,
);
await Promise.all(
rows.map((row) => discard(absolutePath(config.MEDIA_DIR, row.relative_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);
});
};
/** Suppression definitive d'un dossier : ses fichiers puis lui-meme. */
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);
};
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;
}
interface TrashFolderRow {
id: string;
parent_id: string | null;
name: string;
description: string | null;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
deleted_at: string;
}
const publicFile = (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,
});
const publicFolder = (row: TrashFolderRow) => ({
id: row.id,
parent_id: row.parent_id,
name: row.name,
description: row.description,
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 registerTrashRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/cloud/trash/*", attachUser(db));
app.use("/api/cloud/trash", attachUser(db));
app.get("/api/cloud/trash", requireAuth, async (context) => {
const user = currentUser(context);
const admin = user.role_slug === "admin";
// Seuls les elements dont le parent n'est pas lui-meme supprime figurent en
// tete de corbeille : le reste suit la suppression du parent.
const folders = await db.query<TrashFolderRow>(
`SELECT f.id, f.parent_id, f.name, f.description, 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 ( ? = 1 OR f.owner_id = ? )
ORDER BY f.deleted_at DESC`,
[admin ? 1 : 0, 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 ( ? = 1 OR fi.owner_id = ? )
ORDER BY fi.deleted_at DESC`,
[admin ? 1 : 0, user.id],
);
const retentionDays = await db.one<{ setting_value: string }>(
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
);
return context.json({
retentionDays: retentionDays ? Number(retentionDays.setting_value) : 30,
folders: folders.map(publicFolder),
files: files.map(publicFile),
});
});
app.post("/api/cloud/trash/folders/:id/restore", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const row = await db.one<{ owner_id: string | null; parent_id: string | null; name: string }>(
`SELECT owner_id, parent_id, name FROM folders
WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0`,
[id],
);
if (!row) throw AppError.notFound("Dossier introuvable.");
if (user.role_slug !== "admin" && 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;
}
await audit(db, context, user, "trash.restore", "folder", id, { name: row.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
app.post("/api/cloud/trash/files/:id/restore", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<{ owner_id: string | null; folder_id: string | null; name: string }>(
"SELECT owner_id, folder_id, name FROM files WHERE id = ? AND deleted_at IS NOT NULL",
[id],
);
if (!row) throw AppError.notFound("Fichier introuvable.");
if (user.role_slug !== "admin" && 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;
}
await audit(db, context, user, "trash.restore", "file", id, { name: row.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
app.delete("/api/cloud/trash/folders/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Dossier introuvable.");
const row = await db.one<{ owner_id: string | null; name: string }>(
"SELECT owner_id, name FROM folders WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0",
[id],
);
if (!row) throw AppError.notFound("Dossier introuvable.");
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
throw AppError.notFound("Dossier introuvable.");
}
await purgeFolderTree(db, config, id);
await audit(db, context, user, "trash.purge", "folder", id, { name: row.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
app.delete("/api/cloud/trash/files/:id", requireAuth, async (context) => {
const user = currentUser(context);
const id = context.req.param("id") ?? "";
if (!uuid.safeParse(id).success) throw AppError.notFound("Fichier introuvable.");
const row = await db.one<{ owner_id: string | null; name: string }>(
"SELECT owner_id, name FROM files WHERE id = ? AND deleted_at IS NOT NULL",
[id],
);
if (!row) throw AppError.notFound("Fichier introuvable.");
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
throw AppError.notFound("Fichier introuvable.");
}
await purgeFiles(db, config, [id]);
await audit(db, context, user, "trash.purge", "file", id, { name: row.name }, config.TRUST_PROXY);
return context.json({ ok: true });
});
/** Vide la corbeille du compte appelant (tous les elements purges). */
app.delete("/api/cloud/trash", requireAuth, async (context) => {
const user = currentUser(context);
const admin = user.role_slug === "admin";
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 ( ? = 1 OR f.owner_id = ? )`,
[admin ? 1 : 0, 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 ( ? = 1 OR fi.owner_id = ? )`,
[admin ? 1 : 0, user.id],
);
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
await purgeFiles(db, config, files.map((row) => row.id));
await audit(
db,
context,
user,
"trash.empty",
"trash",
null,
{ folders: folders.length, files: files.length },
config.TRUST_PROXY,
);
return context.json({ ok: true, folders: folders.length, files: files.length });
});
};
/**
* Purge planifiee : les elements supprimes au-dela de la retention disparaissent
* au demarrage. Aucun ordonnanceur externe n'est requis.
*/
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;
};
+169
View File
@@ -0,0 +1,169 @@
import { createHash, randomUUID } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
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 "./lib/index.js";
/**
* Chemin physique : ${MEDIA_DIR}/${slug emplacement}/${uuid}.
*
* Le nom affiche n'apparait jamais dans le chemin. Outre qu'il evite toute
* escape via "../", il empeche deux depots homonymes de se marcher dessus et
* rend l'arborescence disque ininteressante a parcourir pour un tiers.
*/
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;
}
/** Extension conservee pour la lisibilite sur disque, jamais pour le routage. */
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);
/**
* Choix de l'emplacement : celui qui offre le plus de marge. Les comptes sont
* eux-memes plafonnes, donc cette valeur sert a ne pas remplir un support
* tandis qu'un autre reste vide.
*/
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;
}
/**
* Ecrit le corps de la requete sur disque en une seule passe : hachage,
* comptage et gravure avancent ensemble, sans jamais faire tenir le fichier
* en memoire. La lecture est interrompue des que la borne est depassee, donc
* un envoi enorme ne remplit pas d'abord le disque pour echouer ensuite.
*/
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" }));
// Taille declaree et taille recue doivent concorder : sans quoi le quota
// aurait ete reserve sur une valeur que le disque n'a pas confirmee.
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 });
};
/** Publie un fichier temporaire : meme systeme de fichiers, donc operation atomique. */
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 fileExists = async (absolute: string): Promise<boolean> => {
try {
const info = await stat(absolute);
return info.isFile();
} catch {
return false;
}
};
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;
}
};