Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f689ab4d57 | ||
|
|
d837817bcb | ||
|
|
fb7d0bab16 | ||
|
|
a82711c9b1 | ||
|
|
82cd712252 | ||
|
|
3542b33c89 | ||
|
|
b52417053f | ||
|
|
220ca62974 | ||
|
|
f39c07e58c | ||
|
|
60b0795849 | ||
|
|
699c523caa |
@@ -19,7 +19,8 @@ CLOUD_DB_DIR=../db
|
||||
CLOUD_MEDIA_DIR=../media
|
||||
|
||||
# --- Session (obligatoire pour toute API) -------------------------------
|
||||
# Secret de chiffrement des sessions. Obligatoire, 32 caracteres minimum.
|
||||
# Secret qui poivre (HMAC-SHA-256) les jetons de session stockes en base.
|
||||
# Obligatoire, 32 caracteres minimum. Le changer invalide toutes les sessions.
|
||||
# Generation :
|
||||
# node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
|
||||
SESSION_SECRET=
|
||||
|
||||
@@ -7,13 +7,14 @@ Application autonome — front **et** back dans ce dépôt.
|
||||
|
||||
```
|
||||
frontend application React + Vite, design system inclus (src/ui, src/styles)
|
||||
backend API : socle serveur (src/lib), auth, dossiers, fichiers, médias
|
||||
docker/ images nginx et API
|
||||
backend API : routes (src/routes/*Routes.ts) + services (src/services/*Service.ts)
|
||||
docker/ images nginx et API
|
||||
```
|
||||
|
||||
Chaque application porte son propre code : le socle serveur (`backend/src/lib`)
|
||||
et le design system (`frontend/src/ui`) appartiennent au Cloud et ne sont
|
||||
partagés avec aucun autre dépôt.
|
||||
Chaque application porte son propre code : le socle serveur
|
||||
(`backend/src/{config,middleware,utils}`) et le design system
|
||||
(`frontend/src/ui`) appartiennent au Cloud et ne sont partagés avec aucun autre
|
||||
dépôt.
|
||||
|
||||
## Démarrer
|
||||
|
||||
@@ -32,7 +33,7 @@ L'app répond sur **`http://localhost:8083`** (variable `COHAISE_HTTP_PORT`).
|
||||
| `COHAISE_DB_PORT` | port MariaDB | `3407` |
|
||||
| `CLOUD_DB_USER` / `CLOUD_DB_PASSWORD` | identifiants base | — |
|
||||
| `CLOUD_DB_ROOT_PASSWORD` | root, pour la sauvegarde | — |
|
||||
| `SESSION_SECRET` | signature des sessions, obligatoire | — |
|
||||
| `SESSION_SECRET` | poivre HMAC des sessions, obligatoire | — |
|
||||
|
||||
Le démarrage échoue avec la liste exacte des variables manquantes ou mal formées,
|
||||
avant l'ouverture d'aucun port. C'est voulu.
|
||||
|
||||
@@ -4,9 +4,11 @@ Stockage privé de fichiers. Le contenu ne vit jamais dans la base : MariaDB ne
|
||||
décrit que des métadonnées, les octets restent sur le disque sous
|
||||
`storage_locations.mount_path`.
|
||||
|
||||
Le service **existe et sert ce modèle** : 10 routes sous `/api/cloud`
|
||||
(`src/routes/{auth,folders,files}.ts`). Le détail des endpoints, des droits et
|
||||
du déploiement est dans [`../../docs/api.md`](../../docs/api.md),
|
||||
Le service **existe et sert ce modèle** : 11 routeurs sous `/api/cloud`
|
||||
(`src/routes/{authRoutes,accountRoutes,adminRoutes,chatRoutes,directoryRoutes,fileRoutes,folderRoutes,mediaRoutes,searchRoutes,trashRoutes,uploadRoutes}.ts`),
|
||||
adossés aux services métier de `src/services/*Service.ts`. Le détail des
|
||||
endpoints, des droits et du déploiement est dans
|
||||
[`../../docs/api.md`](../../docs/api.md),
|
||||
[`../../docs/security.md`](../../docs/security.md) et
|
||||
[`../../docs/architecture.md`](../../docs/architecture.md).
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
-- 009_chat_edits_and_pins.sql
|
||||
--
|
||||
-- 1. Edition des messages : `edited_at` enregistre l'instant de la derniere
|
||||
-- modification. NULL signifie que le message n'a jamais ete edite, donc
|
||||
-- l'interface n'affiche aucune mention. La colonne est posee par le
|
||||
-- serveur, jamais par le client.
|
||||
--
|
||||
-- `edited_at` suit exactement la convention de `created_at` (meme horloge
|
||||
-- de la base, meme cadran) : les deux colonnes doivent afficher la meme
|
||||
-- heure relative l'une a l'autre, sinon la mention « (modifié) » paraitrait
|
||||
-- anterieure au message qu'elle annote.
|
||||
--
|
||||
-- 2. Epinglage : `is_pinned` marque les messages mis de cote dans le salon.
|
||||
-- Plusieurs messages peuvent etre epingles en meme temps. L'index sert a
|
||||
-- retrouver les epingles d'un dossier sans parcourir tout le salon.
|
||||
--
|
||||
-- L'index sur `edited_at` sert au curseur `editedAfter` de la lecture
|
||||
-- incrementale : il rattrape les messages reecrits dont le curseur
|
||||
-- d'identifiant ne peut pas dire grand-chose.
|
||||
|
||||
ALTER TABLE chat_messages
|
||||
ADD COLUMN edited_at DATETIME(3) NULL AFTER created_at,
|
||||
ADD COLUMN is_pinned TINYINT(1) NOT NULL DEFAULT 0 AFTER edited_at,
|
||||
ADD KEY idx_chat_messages_pinned (folder_id, is_pinned, id),
|
||||
ADD KEY idx_chat_messages_edited (folder_id, edited_at);
|
||||
@@ -0,0 +1,36 @@
|
||||
-- 010_upload_sessions.sql
|
||||
--
|
||||
-- Upload resumable pour les fichiers qui depassent la limite de corps de
|
||||
-- requete de Cloudflare (100 MB en Free/Pro). Le client cree une session,
|
||||
-- envoie des morceaux de 50 MiB, puis demande la finalisation.
|
||||
--
|
||||
-- Le fichier temporaire est prealloue a la taille finale : le disque est donc
|
||||
-- verifie avant le premier octet utile, et les ecritures se font a une offset
|
||||
-- connue sans jamais garder le fichier complet en memoire.
|
||||
--
|
||||
-- `received_bytes` avance uniquement quand la plage demandee correspond
|
||||
-- exactement a la suite deja recue : les morceaux sont sequentiels, ce qui
|
||||
-- rend la reprise simple (GET renvoie l'offset courant) et evite les trous.
|
||||
|
||||
CREATE TABLE upload_sessions (
|
||||
id CHAR(36) NOT NULL,
|
||||
user_id CHAR(36) NOT NULL,
|
||||
folder_id CHAR(36) NULL,
|
||||
storage_location_id INT UNSIGNED NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
mime_type VARCHAR(255) NULL,
|
||||
size_bytes BIGINT UNSIGNED NOT NULL,
|
||||
received_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
chunk_size INT UNSIGNED NOT NULL,
|
||||
relative_path VARCHAR(1024) NOT NULL,
|
||||
temp_path VARCHAR(1024) NOT NULL,
|
||||
expires_at DATETIME NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_upload_sessions_user (user_id),
|
||||
KEY idx_upload_sessions_expiry (expires_at),
|
||||
CONSTRAINT chk_upload_sessions_received CHECK (received_bytes <= size_bytes),
|
||||
CONSTRAINT fk_upload_sessions_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_upload_sessions_folder FOREIGN KEY (folder_id) REFERENCES folders (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_upload_sessions_location FOREIGN KEY (storage_location_id) REFERENCES storage_locations (id) ON DELETE RESTRICT
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
@@ -1,19 +1,9 @@
|
||||
#!/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.
|
||||
*/
|
||||
import { ConfigError, loadDbConfig } from "./config/appConfig.js";
|
||||
import { Db } from "./config/db.js";
|
||||
import { hashPassword } from "./services/authService.js";
|
||||
import { AppError, toSafeError } from "./utils/errors.js";
|
||||
|
||||
const USAGE = `Utilisation : cohaise-admin --email <adr> --first <prenom> --last <nom> [options]
|
||||
|
||||
@@ -59,7 +49,6 @@ const parseArgs = (argv: string[]): Args => {
|
||||
return args;
|
||||
};
|
||||
|
||||
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
|
||||
const generatePassword = (): string => {
|
||||
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
const bytes = new Uint8Array(18);
|
||||
@@ -98,7 +87,6 @@ const main = async (argv: string[]): Promise<number> => {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const { Db } = await import("./lib/index.js");
|
||||
const db = new Db(config);
|
||||
|
||||
try {
|
||||
|
||||
@@ -2,22 +2,10 @@
|
||||
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { resolve } from "node:path";
|
||||
import { ConfigError, loadDbConfig } from "./lib/config.js";
|
||||
import { Db } from "./lib/db.js";
|
||||
import { AppError, toSafeError } from "./lib/errors.js";
|
||||
import { listMigrations, runMigrations } from "./lib/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
|
||||
*/
|
||||
import { ConfigError, loadDbConfig } from "./config/appConfig.js";
|
||||
import { Db } from "./config/db.js";
|
||||
import { AppError, toSafeError } from "./utils/errors.js";
|
||||
import { listMigrations, runMigrations } from "./utils/migrate.js";
|
||||
|
||||
interface Options {
|
||||
dir: string;
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
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()
|
||||
@@ -28,7 +20,6 @@ const schema = z.object({
|
||||
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),
|
||||
@@ -49,26 +40,17 @@ const schema = z.object({
|
||||
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),
|
||||
});
|
||||
@@ -90,7 +72,6 @@ export const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => {
|
||||
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"),
|
||||
@@ -1,5 +1,5 @@
|
||||
import mysql, { type Pool, type PoolConnection, type ResultSetHeader, type RowDataPacket } from "mysql2/promise";
|
||||
import type { DbConfig } from "./config.js";
|
||||
import type { DbConfig } from "./appConfig.js";
|
||||
|
||||
export interface QueryError {
|
||||
code: string;
|
||||
@@ -23,22 +23,16 @@ export class Db {
|
||||
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);
|
||||
}
|
||||
@@ -48,7 +42,6 @@ export class Db {
|
||||
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) {
|
||||
@@ -77,7 +70,6 @@ export class Db {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 ?? "";
|
||||
@@ -1,20 +1,21 @@
|
||||
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 { registerChatRoutes } from "./routes/chat.js";
|
||||
import { registerDirectoryRoutes } from "./routes/directory.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";
|
||||
import { startService } from "./utils/service.js";
|
||||
import { purgeExpiredSessions } from "./services/authService.js";
|
||||
import { purgeExpiredTrash } from "./services/trashService.js";
|
||||
import { purgeExpiredUploads } from "./services/uploadService.js";
|
||||
import { registerAccountRoutes } from "./routes/accountRoutes.js";
|
||||
import { registerAdminRoutes } from "./routes/adminRoutes.js";
|
||||
import { registerAuthRoutes } from "./routes/authRoutes.js";
|
||||
import { registerChatRoutes } from "./routes/chatRoutes.js";
|
||||
import { registerDirectoryRoutes } from "./routes/directoryRoutes.js";
|
||||
import { registerFileRoutes } from "./routes/fileRoutes.js";
|
||||
import { registerFolderRoutes } from "./routes/folderRoutes.js";
|
||||
import { registerMediaRoutes } from "./routes/mediaRoutes.js";
|
||||
import { registerSearchRoutes } from "./routes/searchRoutes.js";
|
||||
import { registerTrashRoutes } from "./routes/trashRoutes.js";
|
||||
import { registerUploadRoutes } from "./routes/uploadRoutes.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({
|
||||
@@ -24,18 +25,34 @@ void startService({
|
||||
registerAuthRoutes(app, db, config);
|
||||
registerAccountRoutes(app, db, config);
|
||||
registerChatRoutes(app, db, config);
|
||||
registerDirectoryRoutes(app, db);
|
||||
registerDirectoryRoutes(app, db, config);
|
||||
registerFolderRoutes(app, db, config);
|
||||
registerFileRoutes(app, db, config);
|
||||
registerMediaRoutes(app, db);
|
||||
registerUploadRoutes(app, db, config);
|
||||
registerMediaRoutes(app, db, config);
|
||||
registerTrashRoutes(app, db, config);
|
||||
registerSearchRoutes(app, db);
|
||||
registerSearchRoutes(app, db, config);
|
||||
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 });
|
||||
const uploads = await purgeExpiredUploads(db, config);
|
||||
logger.info("entretien au demarrage", { sessions, purged, uploads });
|
||||
|
||||
setInterval(() => {
|
||||
void purgeExpiredUploads(db, config).catch((error: unknown) =>
|
||||
logger.error("purge des envois inacheves", { error: String(error) }),
|
||||
);
|
||||
}, 60 * 60 * 1000).unref();
|
||||
|
||||
setInterval(() => {
|
||||
void purgeExpiredSessions(db).catch((error: unknown) =>
|
||||
logger.error("purge des sessions expirees", { error: String(error) }),
|
||||
);
|
||||
void purgeExpiredTrash(db, config).catch((error: unknown) =>
|
||||
logger.error("purge de la corbeille", { error: String(error) }),
|
||||
);
|
||||
}, 60 * 60 * 1000).unref();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
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;
|
||||
};
|
||||
@@ -1,57 +0,0 @@
|
||||
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";
|
||||
@@ -1,75 +0,0 @@
|
||||
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();
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { Context, Next } from "hono";
|
||||
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { resolveSession, SESSION_COOKIE } from "../services/authService.js";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** Resout la session depuis le cookie et l'attache au contexte. */
|
||||
export const attachUser =
|
||||
(db: Db, secret: string) =>
|
||||
async (context: Context, next: Next): Promise<void> => {
|
||||
const token = getCookie(context, SESSION_COOKIE);
|
||||
if (token) {
|
||||
const user = await resolveSession(db, token, secret);
|
||||
if (user) {
|
||||
context.set("user", user);
|
||||
context.set("token", token);
|
||||
} else {
|
||||
clearSessionCookie(context);
|
||||
}
|
||||
}
|
||||
await next();
|
||||
};
|
||||
|
||||
const PASSWORD_CHANGE_ALLOWED = new Set([
|
||||
"/api/cloud/auth/me",
|
||||
"/api/cloud/auth/change-password",
|
||||
"/api/cloud/auth/logout",
|
||||
]);
|
||||
|
||||
export const requireAuth = async (context: Context, next: Next): Promise<void> => {
|
||||
const user = context.get("user") as SessionUser | undefined;
|
||||
if (!user) throw AppError.unauthorized();
|
||||
if (user.must_change_password === 1 && !PASSWORD_CHANGE_ALLOWED.has(context.req.path)) {
|
||||
throw AppError.forbidden("Vous devez changer votre mot de passe avant de continuer.");
|
||||
}
|
||||
await next();
|
||||
};
|
||||
|
||||
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;
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Types partages entre les middlewares, les services et les routes.
|
||||
*/
|
||||
|
||||
/** Utilisateur courant porte par la session (contexte Hono). */
|
||||
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;
|
||||
}
|
||||
|
||||
/** Metadonnees enregistrees a la creation d'une session. */
|
||||
export interface SessionMeta {
|
||||
ipAddress?: string | null | undefined;
|
||||
userAgent?: string | null | undefined;
|
||||
}
|
||||
|
||||
/** Ligne `files` (partagee entre fileService et uploadService). */
|
||||
export 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;
|
||||
}
|
||||
@@ -1,451 +0,0 @@
|
||||
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 preferencesInput = z.object({
|
||||
theme: z.enum(["system", "light", "dark"]),
|
||||
language: z.enum(["fr", "en"]),
|
||||
});
|
||||
|
||||
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/preferences", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const row = await db.one<{ theme: string; language: string }>(
|
||||
"SELECT theme, language FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[user.id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Compte introuvable.");
|
||||
return context.json({ theme: row.theme, language: row.language });
|
||||
});
|
||||
|
||||
app.patch("/api/cloud/account/preferences", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const data = parse(preferencesInput, await context.req.json().catch(() => null));
|
||||
await db.exec("UPDATE users SET theme = ?, language = ? WHERE id = ?", [
|
||||
data.theme,
|
||||
data.language,
|
||||
user.id,
|
||||
]);
|
||||
return context.json({ theme: data.theme, language: data.language });
|
||||
});
|
||||
|
||||
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 });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,197 @@
|
||||
import { Readable } from "node:stream";
|
||||
import { z } from "zod";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
|
||||
import { audit } from "../services/auditService.js";
|
||||
import {
|
||||
confirmEmailChange,
|
||||
deleteAvatar,
|
||||
forgotPassword,
|
||||
getAvatar,
|
||||
getPreferences,
|
||||
listSessions,
|
||||
requestEmailChange,
|
||||
resetPassword,
|
||||
revokeOtherSessions,
|
||||
revokeSessionById,
|
||||
updatePreferences,
|
||||
updateProfile,
|
||||
uploadAvatar,
|
||||
} from "../services/accountService.js";
|
||||
import { openForDownload } from "../services/storageService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { clientIp, readBodyCapped, readJson, type App } from "../utils/http.js";
|
||||
import { createRateLimiter, rateLimitKey } from "../utils/ratelimit.js";
|
||||
import { parse } from "../utils/validators.js";
|
||||
|
||||
const AVATAR_MAX_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
const profileInput = z.object({
|
||||
first_name: z.string().trim().min(1).max(50),
|
||||
last_name: z.string().trim().min(1).max(50),
|
||||
});
|
||||
|
||||
const preferencesInput = z.object({
|
||||
theme: z.enum(["system", "light", "dark"]),
|
||||
language: z.enum(["fr", "en"]),
|
||||
});
|
||||
|
||||
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, config.SESSION_SECRET));
|
||||
app.use("/api/cloud/account", attachUser(db, config.SESSION_SECRET));
|
||||
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 readJson(context));
|
||||
const updated = await updateProfile(db, user, data.first_name, data.last_name);
|
||||
await audit(db, context, user, "profile.update", "user", user.id, null, config.TRUST_PROXY);
|
||||
return context.json({ ok: true, ...updated });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/account/preferences", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
return context.json(await getPreferences(db, user));
|
||||
});
|
||||
|
||||
app.patch("/api/cloud/account/preferences", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const data = parse(preferencesInput, await readJson(context));
|
||||
return context.json(await updatePreferences(db, user, data.theme, data.language));
|
||||
});
|
||||
|
||||
app.get("/api/cloud/account/sessions", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const sessions = await listSessions(db, config, user, context.get("token") ?? "");
|
||||
return context.json({ sessions });
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/account/sessions/:id", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
await revokeSessionById(db, user, context.req.param("id") ?? "");
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/account/sessions", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
await revokeOtherSessions(db, config, user, context.get("token") ?? "");
|
||||
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 = await readBodyCapped(context, AVATAR_MAX_BYTES);
|
||||
await uploadAvatar(db, config, user, source);
|
||||
|
||||
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 avatar = await getAvatar(db, config, context.req.param("userId") ?? "");
|
||||
if (!avatar) throw AppError.notFound("Avatar introuvable.");
|
||||
const stream = Readable.toWeb(openForDownload(avatar.absolute)) as ReadableStream<Uint8Array>;
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"content-type": "image/webp",
|
||||
"content-length": String(avatar.size),
|
||||
"cache-control": "private, max-age=86400",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/account/avatar", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
await deleteAvatar(db, user);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/account/forgot-password", async (context) => {
|
||||
const data = parse(forgotInput, await readJson(context));
|
||||
throttle(context, `forgot:${data.email.toLowerCase()}`);
|
||||
await forgotPassword(db, config, data.email);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/account/reset-password", async (context) => {
|
||||
const data = parse(resetInput, await readJson(context));
|
||||
throttle(context, "reset");
|
||||
|
||||
const actor = await resetPassword(db, data.token, data.password);
|
||||
if (actor) {
|
||||
const sessionUser: SessionUser = {
|
||||
id: actor.userId,
|
||||
email: actor.email,
|
||||
first_name: actor.first_name,
|
||||
last_name: actor.last_name,
|
||||
role_slug: "user",
|
||||
role_name: "",
|
||||
is_active: 1,
|
||||
must_change_password: 0,
|
||||
};
|
||||
await audit(db, context, sessionUser, "password.reset", "user", actor.userId, 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 readJson(context));
|
||||
throttle(context, `email:${user.id}`);
|
||||
|
||||
await requestEmailChange(db, config, user, data.password, data.new_email);
|
||||
|
||||
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 readJson(context),
|
||||
);
|
||||
|
||||
const email = await confirmEmailChange(db, data.token);
|
||||
return context.json({ ok: true, email });
|
||||
});
|
||||
};
|
||||
@@ -1,574 +0,0 @@
|
||||
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;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reprise des dossiers d'un compte supprime. Un dossier partage (permission
|
||||
* nominative active vers un autre compte actif) survit avec un nouveau
|
||||
* proprietaire : le meilleur candidat par niveau (admin puis write puis read),
|
||||
* le plus ancien en cas d'egalite. Un dossier sans partage disparait avec son
|
||||
* sous-arbre, a la maniere de `DELETE /folders/:id`. Un enfant partage dont le
|
||||
* parent disparait remonte a la racine ; il en va de meme pour les dossiers
|
||||
* d'autres comptes instales sous un dossier supprime, qui ne doivent pas
|
||||
* devenir orphelins. Les permissions detenues par le compte supprime sur les
|
||||
* dossiers d'autrui sont retirees.
|
||||
*/
|
||||
const rehomeUserFolders = async (db: Db, userId: string): Promise<{ kept: number; deleted: number }> => {
|
||||
const folders = await db.query<{ id: string; parent_id: string | null }>(
|
||||
"SELECT id, parent_id FROM folders WHERE owner_id = ? AND deleted_at IS NULL AND is_system = 0",
|
||||
[userId],
|
||||
);
|
||||
if (folders.length === 0) return { kept: 0, deleted: 0 };
|
||||
|
||||
const ids = folders.map((folder) => folder.id);
|
||||
const placeholders = ids.map(() => "?").join(",");
|
||||
|
||||
// Meilleur candidat par dossier : permission non expiree vers un compte actif.
|
||||
const candidates = await db.query<{
|
||||
folder_id: string;
|
||||
user_id: string;
|
||||
level: string;
|
||||
created_at: string;
|
||||
}>(
|
||||
`SELECT fp.folder_id, fp.user_id, fp.level, fp.created_at
|
||||
FROM folder_permissions fp
|
||||
JOIN users u ON u.id = fp.user_id AND u.deleted_at IS NULL AND u.is_active = 1
|
||||
WHERE fp.folder_id IN (${placeholders})
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() )
|
||||
ORDER BY FIELD(fp.level, 'admin', 'write', 'read'), fp.created_at ASC`,
|
||||
[...ids],
|
||||
);
|
||||
|
||||
const newOwner = new Map<string, string>();
|
||||
for (const row of candidates) {
|
||||
if (!newOwner.has(row.folder_id)) newOwner.set(row.folder_id, row.user_id);
|
||||
}
|
||||
|
||||
const owned = new Map(folders.map((folder) => [folder.id, folder.parent_id]));
|
||||
const keepIds = [...newOwner.keys()];
|
||||
const deleteIds = ids.filter((id) => !newOwner.has(id));
|
||||
|
||||
await db.transaction(async (connection) => {
|
||||
for (const [id, owner] of newOwner) {
|
||||
const parentId = owned.get(id) ?? null;
|
||||
// Parent supprime avec le compte : l'enfant partage remonte a la racine.
|
||||
const parentGone = parentId !== null && owned.has(parentId) && !newOwner.has(parentId);
|
||||
await connection.execute(
|
||||
"UPDATE folders SET owner_id = ?, parent_id = ? WHERE id = ?",
|
||||
[owner, parentGone ? null : parentId, id],
|
||||
);
|
||||
}
|
||||
|
||||
if (deleteIds.length > 0) {
|
||||
const delPh = deleteIds.map(() => "?").join(",");
|
||||
// Dossiers d'autres comptes installes sous un dossier supprime : a la racine.
|
||||
await connection.execute(
|
||||
`UPDATE folders SET parent_id = NULL
|
||||
WHERE parent_id IN (${delPh}) AND deleted_at IS NULL
|
||||
AND owner_id <> ? AND id NOT IN (${keepIds.map(() => "?").join(",") || "''"})`,
|
||||
[...deleteIds, userId, ...(keepIds.length > 0 ? keepIds : [])],
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${delPh}) AND deleted_at IS NULL`,
|
||||
deleteIds,
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${delPh}) AND deleted_at IS NULL`,
|
||||
deleteIds,
|
||||
);
|
||||
}
|
||||
|
||||
// Permissions du compte supprime sur les dossiers d'autrui.
|
||||
await connection.execute("DELETE FROM folder_permissions WHERE user_id = ?", [userId]);
|
||||
await connection.execute("DELETE FROM user_file_stars WHERE user_id = ?", [userId]);
|
||||
});
|
||||
|
||||
return { kept: keepIds.length, deleted: deleteIds.length };
|
||||
};
|
||||
|
||||
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) }, 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.");
|
||||
|
||||
// Avant la reprise : les dossiers partages trouvent un nouveau proprietaire,
|
||||
// les autres disparaissent avec leur sous-arbre.
|
||||
const rehomed = await rehomeUserFolders(db, id);
|
||||
|
||||
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]);
|
||||
return context.json({ ok: true, folders: rehomed });
|
||||
});
|
||||
|
||||
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 envoye au compte ; la reponse ne le contient pas.
|
||||
// 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({ ok: true });
|
||||
});
|
||||
|
||||
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 });
|
||||
});
|
||||
|
||||
/**
|
||||
* Facettes du journal : valeurs distinctes utilisees pour alimenter les
|
||||
* listes deroulantes de filtre (actions et comptes ayant agi). Un compte
|
||||
* supprime reste identifiable par son e-mail conserve dans le journal.
|
||||
*/
|
||||
app.get("/api/cloud/admin/audit/filters", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const actions = await db.query<{ action: string }>(
|
||||
"SELECT DISTINCT action FROM audit_logs ORDER BY action ASC",
|
||||
);
|
||||
const users = await db.query<{ user_id: string; user_email: string | null }>(
|
||||
`SELECT user_id, MAX(user_email) AS user_email
|
||||
FROM audit_logs
|
||||
WHERE user_id IS NOT NULL
|
||||
GROUP BY user_id
|
||||
ORDER BY user_email ASC`,
|
||||
);
|
||||
return context.json({
|
||||
actions: actions.map((row) => row.action),
|
||||
users: users.map((row) => ({ id: row.user_id, email: row.user_email })),
|
||||
});
|
||||
});
|
||||
|
||||
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") || null;
|
||||
const userId = context.req.query("userId") || null;
|
||||
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
if (action) {
|
||||
conditions.push("action = ?");
|
||||
params.push(action);
|
||||
}
|
||||
if (userId) {
|
||||
conditions.push("user_id = ?");
|
||||
params.push(userId);
|
||||
}
|
||||
const where = conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "";
|
||||
|
||||
const rows = await db.query(
|
||||
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
|
||||
FROM audit_logs${where} ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`,
|
||||
params,
|
||||
);
|
||||
return context.json({ entries: rows });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,148 @@
|
||||
import { z } from "zod";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
|
||||
import {
|
||||
auditEntries,
|
||||
auditFilters,
|
||||
createStorageLocation,
|
||||
createUser,
|
||||
deleteUser,
|
||||
getStats,
|
||||
listStorageLocations,
|
||||
listUsers,
|
||||
publicUser,
|
||||
resetUserPassword,
|
||||
updateStorageLocation,
|
||||
updateUser,
|
||||
} from "../services/adminService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { readJson, type App } from "../utils/http.js";
|
||||
import { parse, uuid } from "../utils/validators.js";
|
||||
|
||||
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(),
|
||||
});
|
||||
|
||||
export const registerAdminRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/admin/*", attachUser(db, config.SESSION_SECRET));
|
||||
app.use("/api/cloud/admin", attachUser(db, config.SESSION_SECRET));
|
||||
|
||||
const requireAdmin = (context: Parameters<typeof currentUser>[0]): void => {
|
||||
if (currentUser(context).role_slug !== "admin") throw AppError.forbidden();
|
||||
};
|
||||
|
||||
app.get("/api/cloud/admin/stats", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
return context.json(await getStats(db, config));
|
||||
});
|
||||
|
||||
app.get("/api/cloud/admin/users", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const users = await listUsers(db, context.req.query("q") ?? "");
|
||||
return context.json({ users: users.map(publicUser) });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/admin/users", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const data = parse(createUserSchema, await readJson(context));
|
||||
const created = await createUser(db, config, data);
|
||||
return context.json({ user: publicUser(created) }, 201);
|
||||
});
|
||||
|
||||
app.patch("/api/cloud/admin/users/:id", requireAuth, async (context) => {
|
||||
const actor = currentUser(context);
|
||||
requireAdmin(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
const data = parse(updateUserSchema, await readJson(context));
|
||||
const updated = await updateUser(db, actor.id, id, data);
|
||||
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 (!uuid.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
const rehomed = await deleteUser(db, actor.id, id);
|
||||
return context.json({ ok: true, folders: rehomed });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/admin/users/:id/reset-password", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
await resetUserPassword(db, config, id);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
return context.json(await listStorageLocations(db, config));
|
||||
});
|
||||
|
||||
app.post("/api/cloud/admin/storage-locations", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
const data = parse(createLocationSchema, await readJson(context));
|
||||
await createStorageLocation(db, config, data);
|
||||
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 readJson(context));
|
||||
|
||||
await updateStorageLocation(db, config, id, data);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/admin/audit/filters", requireAuth, async (context) => {
|
||||
requireAdmin(context);
|
||||
return context.json(await auditFilters(db));
|
||||
});
|
||||
|
||||
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") || null;
|
||||
const userId = context.req.query("userId") || null;
|
||||
|
||||
const entries = await auditEntries(db, { limit, offset, action, userId });
|
||||
return context.json({ entries });
|
||||
});
|
||||
};
|
||||
@@ -1,197 +0,0 @@
|
||||
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;
|
||||
theme: string;
|
||||
language: string;
|
||||
avatar_updated_at: Date | null;
|
||||
}
|
||||
|
||||
const publicUser = (row: UserRow) => ({
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
role_slug: row.role_slug,
|
||||
role_name: row.role_name,
|
||||
quota_bytes: row.quota_bytes,
|
||||
used_bytes: row.used_bytes,
|
||||
max_file_bytes: row.max_file_bytes,
|
||||
must_change_password: row.must_change_password,
|
||||
theme: row.theme,
|
||||
language: row.language,
|
||||
has_avatar: row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
});
|
||||
|
||||
const SELECT_USER = `
|
||||
SELECT u.id, u.email, u.first_name, u.last_name, u.password_hash,
|
||||
r.slug AS role_slug, r.name AS role_name,
|
||||
u.quota_bytes, u.used_bytes, u.max_file_bytes, u.must_change_password, u.is_active,
|
||||
u.theme, u.language,
|
||||
ua.updated_at AS avatar_updated_at
|
||||
FROM users u
|
||||
JOIN roles r ON r.id = u.role_id
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = u.id`;
|
||||
|
||||
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
// Aucune reponse de l'API ne doit etre mise en cache. Sans en-tete explicite,
|
||||
// les navigateurs appliquent un cache heuristique et reservent une liste de
|
||||
// fichiers obsolete apres une suppression ou un depot.
|
||||
app.use("/api/cloud/*", async (context, next) => {
|
||||
await next();
|
||||
context.header("cache-control", "no-store");
|
||||
});
|
||||
|
||||
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 });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import { z } from "zod";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import {
|
||||
attachUser,
|
||||
clearSessionCookie,
|
||||
currentUser,
|
||||
isHttpsRequest,
|
||||
requireAuth,
|
||||
setSessionCookie,
|
||||
} from "../middleware/auth.js";
|
||||
import { changePassword, login, me, revokeSession } from "../services/authService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { clientIp, readJson, type App } from "../utils/http.js";
|
||||
import { createRateLimiter, rateLimitKey } from "../utils/ratelimit.js";
|
||||
|
||||
const credentials = z.object({
|
||||
email: z.string().trim().min(3).max(255),
|
||||
password: z.string().min(1).max(1024),
|
||||
});
|
||||
|
||||
const changePasswordInput = z.object({
|
||||
current: z.string().min(1).max(1024),
|
||||
next: z.string().min(8).max(1024),
|
||||
});
|
||||
|
||||
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/*", async (context, next) => {
|
||||
await next();
|
||||
context.header("cache-control", "no-store");
|
||||
});
|
||||
|
||||
app.use("/api/cloud/*", attachUser(db, config.SESSION_SECRET));
|
||||
const limiter = createRateLimiter(config.RATE_LIMIT_LOGIN_MAX, config.RATE_LIMIT_LOGIN_WINDOW_MS);
|
||||
|
||||
app.post("/api/cloud/auth/login", async (context) => {
|
||||
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 readJson(context));
|
||||
if (!parsed.success) throw AppError.badRequest("Identifiants invalides.");
|
||||
|
||||
const forwarded = context.req.header("x-forwarded-for");
|
||||
const { user, token, expiresAt } = await login(db, config, parsed.data.email, parsed.data.password, {
|
||||
ipAddress: config.TRUST_PROXY && forwarded ? forwarded.split(",")[0]?.trim() : null,
|
||||
userAgent: context.req.header("user-agent"),
|
||||
});
|
||||
|
||||
const secure = isHttpsRequest(context, config.TRUST_PROXY);
|
||||
setSessionCookie(context, token, expiresAt, secure);
|
||||
|
||||
return context.json({ user });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/auth/logout", requireAuth, async (context) => {
|
||||
const token = context.get("token");
|
||||
if (token) await revokeSession(db, token, config.SESSION_SECRET);
|
||||
clearSessionCookie(context);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/auth/me", requireAuth, async (context) => {
|
||||
const session = currentUser(context);
|
||||
return context.json({ user: await me(db, session.id) });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/auth/change-password", requireAuth, async (context) => {
|
||||
const session = currentUser(context);
|
||||
const parsed = changePasswordInput.safeParse(await readJson(context));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
|
||||
}
|
||||
|
||||
await changePassword(
|
||||
db,
|
||||
config,
|
||||
session.id,
|
||||
context.get("token") ?? "",
|
||||
parsed.data.current,
|
||||
parsed.data.next,
|
||||
);
|
||||
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -1,262 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
createRateLimiter,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
import { audit, canManageFolder, canRead, READ_SQL } from "../access.js";
|
||||
|
||||
/**
|
||||
* Chat attache a un dossier. Le salon ne se lit et ne s'ecrit qu'avec l'acces
|
||||
* au dossier : le role global ne suffit jamais, `admin` compris.
|
||||
*
|
||||
* Les membres du salon sont exactement les comptes qui ont acces au dossier
|
||||
* (proprietaire, permissions nominatives, dossier public). Un administrateur
|
||||
* n'est donc membre que des salons des dossiers partages avec lui.
|
||||
*/
|
||||
|
||||
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 sendInput = z.object({
|
||||
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
|
||||
});
|
||||
|
||||
interface MessageRow {
|
||||
id: number;
|
||||
user_id: string | null;
|
||||
body: string;
|
||||
created_at: string;
|
||||
first_name: string | null;
|
||||
last_name: string | null;
|
||||
avatar_updated_at: Date | null;
|
||||
}
|
||||
|
||||
/** Auteur joint a la ligne : meme jointure que la lecture, pour la reponse du POST. */
|
||||
const SELECT_MESSAGE = `
|
||||
SELECT m.id, m.user_id, m.body, m.created_at,
|
||||
u.first_name, u.last_name, ua.updated_at AS avatar_updated_at
|
||||
FROM chat_messages m
|
||||
LEFT JOIN users u ON u.id = m.user_id
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = m.user_id`;
|
||||
|
||||
const publicMessage = (row: MessageRow) => ({
|
||||
id: row.id,
|
||||
user_id: row.user_id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
body: row.body,
|
||||
created_at: row.created_at,
|
||||
has_avatar: row.user_id !== null && row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
});
|
||||
|
||||
export const registerChatRoutes = (app: App, db: Db, config: Config): void => {
|
||||
// Ecriture bornee par compte : le salon reste utilisable meme si un client
|
||||
// s'emballe. La lecture (interrogation periodique) n'est pas limitee ici.
|
||||
const limiter = createRateLimiter(20, 10_000);
|
||||
|
||||
/**
|
||||
* Le dossier doit exister et etre accessible : `canRead` rejette une session
|
||||
* sans acces comme un dossier inexistant (404, pour ne rien confirmer).
|
||||
*/
|
||||
const assertFolder = async (
|
||||
folderId: string,
|
||||
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
|
||||
if (!uuid.safeParse(folderId).success) throw AppError.notFound("Dossier introuvable.");
|
||||
const folder = await db.one<{ id: string; owner_id: string | null; access_type: string }>(
|
||||
"SELECT id, owner_id, access_type FROM folders WHERE id = ? AND deleted_at IS NULL",
|
||||
[folderId],
|
||||
);
|
||||
if (!folder) throw AppError.notFound("Dossier introuvable.");
|
||||
return folder;
|
||||
};
|
||||
|
||||
/** Reprise du curseur de lecture du salon pour la session courante. */
|
||||
const markRead = async (folderId: string, userId: string, messageId: number): Promise<void> => {
|
||||
if (messageId <= 0) return;
|
||||
await db
|
||||
.exec(
|
||||
`INSERT INTO chat_reads (folder_id, user_id, last_read_message_id)
|
||||
VALUES (?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
last_read_message_id = GREATEST(last_read_message_id, ?),
|
||||
updated_at = UTC_TIMESTAMP(3)`,
|
||||
[folderId, userId, messageId, messageId],
|
||||
)
|
||||
.catch(() => undefined);
|
||||
};
|
||||
|
||||
/**
|
||||
* Pastilles de messages non lus : tous les salons accessibles a la session
|
||||
* qui contiennent au moins un message qu'elle n'a pas encore lu. Les
|
||||
* messages de la session ignores : il n'a rien de neuf a lire.
|
||||
*/
|
||||
app.get("/api/cloud/chat/unread", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rows = await db.query<{ folder_id: string; unread: number }>(
|
||||
`SELECT f.id AS folder_id, COUNT(m.id) AS unread
|
||||
FROM folders f
|
||||
JOIN chat_messages m
|
||||
ON m.folder_id = f.id
|
||||
AND m.deleted_at IS NULL
|
||||
AND m.user_id <> ?
|
||||
WHERE f.deleted_at IS NULL
|
||||
AND m.id > COALESCE (
|
||||
( SELECT cr.last_read_message_id
|
||||
FROM chat_reads cr
|
||||
WHERE cr.folder_id = f.id AND cr.user_id = ? ), 0 )
|
||||
AND ${READ_SQL}
|
||||
GROUP BY f.id
|
||||
HAVING unread > 0`,
|
||||
[user.id, user.id, user.id, user.id],
|
||||
);
|
||||
|
||||
const unread: Record<string, number> = {};
|
||||
for (const row of rows) unread[row.folder_id] = Number(row.unread);
|
||||
return context.json({ unread });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/folders/:folderId/chat/members", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
const folder = await assertFolder(folderId);
|
||||
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
// Les membres sont ceux qui ont acces au dossier : proprietaire,
|
||||
// permission nominative non expiree, et tous les comptes actifs si le
|
||||
// dossier est public. Le role global ne compte pas.
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
avatar_updated_at: Date | null;
|
||||
last_login_at: string | null;
|
||||
}>(
|
||||
`SELECT u.id, u.first_name, u.last_name, r.slug AS role_slug,
|
||||
ua.updated_at AS avatar_updated_at, u.last_login_at
|
||||
FROM users u
|
||||
JOIN roles r ON r.id = u.role_id
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = u.id
|
||||
WHERE u.deleted_at IS NULL AND u.is_active = 1
|
||||
AND ( u.id = ?
|
||||
OR ? = 1
|
||||
OR EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = ? AND fp.user_id = u.id
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||
ORDER BY u.first_name ASC, u.last_name ASC`,
|
||||
[folder.owner_id, folder.access_type === "public" ? 1 : 0, folderId],
|
||||
);
|
||||
|
||||
return context.json({
|
||||
members: rows.map((row) => ({
|
||||
id: row.id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
role_slug: row.role_slug,
|
||||
has_avatar: row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
last_login_at: row.last_login_at,
|
||||
is_self: row.id === user.id,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
await assertFolder(folderId);
|
||||
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 50));
|
||||
const after = Math.max(0, Number(context.req.query("after")) || 0);
|
||||
|
||||
// `after` sert a la synchronisation incrementale (polling) : on ne remonte
|
||||
// que les messages posterieurs au dernier connu, dans l'ordre du temps.
|
||||
// Sans `after` : les `limit` derniers, remis dans l'ordre croissant.
|
||||
const rows =
|
||||
after > 0
|
||||
? await db.query<MessageRow>(
|
||||
`${SELECT_MESSAGE}
|
||||
WHERE m.folder_id = ? AND m.deleted_at IS NULL AND m.id > ?
|
||||
ORDER BY m.id ASC
|
||||
LIMIT ${limit}`,
|
||||
[folderId, after],
|
||||
)
|
||||
: (
|
||||
await db.query<MessageRow>(
|
||||
`${SELECT_MESSAGE}
|
||||
WHERE m.folder_id = ? AND m.deleted_at IS NULL
|
||||
ORDER BY m.id DESC
|
||||
LIMIT ${limit}`,
|
||||
[folderId],
|
||||
)
|
||||
).reverse();
|
||||
|
||||
const newest = rows.reduce((max, row) => Math.max(max, row.id), 0);
|
||||
await markRead(folderId, user.id, newest);
|
||||
|
||||
return context.json({ messages: rows.map(publicMessage) });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
await assertFolder(folderId);
|
||||
// Etre membre du salon suffit a ecrire : un acces `read` participe a la
|
||||
// discussion, exactement comme le proprietaire.
|
||||
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
if (!limiter.allow(user.id)) {
|
||||
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
|
||||
}
|
||||
const parsed = sendInput.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
|
||||
}
|
||||
|
||||
const result = await db.exec(
|
||||
"INSERT INTO chat_messages (folder_id, user_id, body) VALUES (?, ?, ?)",
|
||||
[folderId, user.id, parsed.data.body],
|
||||
);
|
||||
const row = await db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [result.insertId]);
|
||||
return context.json({ message: publicMessage(row) }, 201);
|
||||
});
|
||||
|
||||
app.delete(
|
||||
"/api/cloud/folders/:folderId/chat/messages/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
const id = Number(context.req.param("id"));
|
||||
await assertFolder(folderId);
|
||||
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
|
||||
|
||||
const row = await db.one<{ user_id: string | null }>(
|
||||
"SELECT user_id FROM chat_messages WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
|
||||
[id, folderId],
|
||||
);
|
||||
// Auteur ou gestionnaire du dossier (proprietaire) : meme reponse qu'un
|
||||
// message inexistant pour ne rien laisser deviner.
|
||||
if (!row || (row.user_id !== user.id && !(await canManageFolder(db, user, folderId)))) {
|
||||
throw AppError.notFound("Message introuvable.");
|
||||
}
|
||||
|
||||
await db.exec("UPDATE chat_messages SET deleted_at = UTC_TIMESTAMP(3) WHERE id = ?", [id]);
|
||||
await audit(db, context, user, "chat.delete", "message", String(id), { folderId }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,162 @@
|
||||
import { z } from "zod";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { currentUser, requireAuth } from "../middleware/auth.js";
|
||||
import { audit } from "../services/auditService.js";
|
||||
import {
|
||||
deleteMessage,
|
||||
editMessage,
|
||||
members,
|
||||
messages,
|
||||
pins,
|
||||
publicMessage,
|
||||
sendMessage,
|
||||
togglePin,
|
||||
unreadCounts,
|
||||
} from "../services/chatService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { readJson, type App } from "../utils/http.js";
|
||||
import { createRateLimiter } from "../utils/ratelimit.js";
|
||||
|
||||
const sendInput = z.object({
|
||||
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
|
||||
});
|
||||
|
||||
const editInput = z.object({
|
||||
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
|
||||
});
|
||||
|
||||
export const registerChatRoutes = (app: App, db: Db, config: Config): void => {
|
||||
const limiter = createRateLimiter(20, 10_000);
|
||||
|
||||
const assertRate = (user: { id: string }): void => {
|
||||
if (!limiter.allow(user.id)) {
|
||||
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
|
||||
}
|
||||
};
|
||||
|
||||
app.get("/api/cloud/chat/unread", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const unread = await unreadCounts(db, user);
|
||||
return context.json({ unread });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/folders/:folderId/chat/members", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rows = await members(db, user, context.req.param("folderId") ?? "");
|
||||
return context.json({
|
||||
members: rows.map((row) => ({
|
||||
id: row.id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
role_slug: row.role_slug,
|
||||
has_avatar: row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
last_login_at: row.last_login_at,
|
||||
is_self: row.is_self,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 50));
|
||||
const after = Math.max(0, Number(context.req.query("after")) || 0);
|
||||
const editedAfterRaw = context.req.query("editedAfter");
|
||||
const editedAfter = typeof editedAfterRaw === "string" ? editedAfterRaw : null;
|
||||
|
||||
const result = await messages(db, user, folderId, { after, limit, editedAfter });
|
||||
return context.json({ messages: result.messages.map(publicMessage), cursor: result.cursor });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
assertRate(user);
|
||||
|
||||
const parsed = sendInput.safeParse(await readJson(context));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
|
||||
}
|
||||
|
||||
const message = await sendMessage(db, user, folderId, parsed.data.body);
|
||||
return context.json({ message: publicMessage(message) }, 201);
|
||||
});
|
||||
|
||||
app.patch(
|
||||
"/api/cloud/folders/:folderId/chat/messages/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
const id = Number(context.req.param("id"));
|
||||
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
|
||||
assertRate(user);
|
||||
|
||||
const parsed = editInput.safeParse(await readJson(context));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
|
||||
}
|
||||
|
||||
const message = await editMessage(db, user, folderId, id, parsed.data.body);
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"chat.edit",
|
||||
"message",
|
||||
String(id),
|
||||
{ folderId },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
return context.json({ message: publicMessage(message) });
|
||||
},
|
||||
);
|
||||
|
||||
app.put(
|
||||
"/api/cloud/folders/:folderId/chat/messages/:id/pin",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
const id = Number(context.req.param("id"));
|
||||
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
|
||||
assertRate(user);
|
||||
|
||||
const pinned = await togglePin(db, user, folderId, id);
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
pinned ? "chat.pin" : "chat.unpin",
|
||||
"message",
|
||||
String(id),
|
||||
{ folderId },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
return context.json({ pinned });
|
||||
},
|
||||
);
|
||||
|
||||
app.get("/api/cloud/folders/:folderId/chat/pins", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rows = await pins(db, user, context.req.param("folderId") ?? "");
|
||||
return context.json({ messages: rows.map(publicMessage) });
|
||||
});
|
||||
|
||||
app.delete(
|
||||
"/api/cloud/folders/:folderId/chat/messages/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
const id = Number(context.req.param("id"));
|
||||
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
|
||||
|
||||
await deleteMessage(db, user, folderId, id);
|
||||
await audit(db, context, user, "chat.delete", "message", String(id), { folderId }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -1,47 +0,0 @@
|
||||
import {
|
||||
attachUser,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
|
||||
/**
|
||||
* Repertoire des comptes actifs, reduit au strict necessaire pour choisir un
|
||||
* destinataire lors d'un partage. La session courante est exclue : on ne se
|
||||
* partage pas un dossier a soi-meme. Aucune donnee sensible n'est exposee.
|
||||
*/
|
||||
export const registerDirectoryRoutes = (app: App, db: Db): void => {
|
||||
app.use("/api/cloud/directory", attachUser(db));
|
||||
|
||||
app.get("/api/cloud/directory", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
avatar_updated_at: Date | null;
|
||||
}>(
|
||||
`SELECT u.id, u.first_name, u.last_name, u.email,
|
||||
ua.updated_at AS avatar_updated_at
|
||||
FROM users u
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = u.id
|
||||
WHERE u.deleted_at IS NULL AND u.is_active = 1 AND u.id <> ?
|
||||
ORDER BY u.first_name ASC, u.last_name ASC
|
||||
LIMIT 1000`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
return context.json({
|
||||
users: rows.map((row) => ({
|
||||
id: row.id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
email: row.email,
|
||||
has_avatar: row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
})),
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
|
||||
import { listUsers } from "../services/directoryService.js";
|
||||
import type { App } from "../utils/http.js";
|
||||
|
||||
export const registerDirectoryRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/directory", attachUser(db, config.SESSION_SECRET));
|
||||
|
||||
app.get("/api/cloud/directory", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const users = await listUsers(db, user);
|
||||
return context.json({ users });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,327 @@
|
||||
import { Readable } from "node:stream";
|
||||
import { z } from "zod";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { attachUser, currentUser, requireAuth, requireRole } from "../middleware/auth.js";
|
||||
import { audit } from "../services/auditService.js";
|
||||
import {
|
||||
deleteFile,
|
||||
getFile,
|
||||
listFavorites,
|
||||
listFiles,
|
||||
moveFile,
|
||||
publicFile,
|
||||
renameFile,
|
||||
toggleStar,
|
||||
uploadFile,
|
||||
} from "../services/fileService.js";
|
||||
import { thumbnailSize } from "../services/mediaService.js";
|
||||
import { absolutePath, fileExists, openForDownload } from "../services/storageService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { readJson, type App } from "../utils/http.js";
|
||||
import { assertName, mimeOf, parse, uuid } from "../utils/validators.js";
|
||||
|
||||
const renameInput = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
});
|
||||
|
||||
const moveInput = z.object({
|
||||
folderId: uuid.nullish(),
|
||||
});
|
||||
|
||||
const contentDisposition = (name: string, inline = false): string => {
|
||||
const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
|
||||
const kind = inline ? "inline" : "attachment";
|
||||
return `${kind}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
|
||||
};
|
||||
|
||||
const BYTE_RANGE = /^bytes=(\d*)-(\d*)$/;
|
||||
|
||||
const parseRange = (
|
||||
header: string | undefined,
|
||||
total: number,
|
||||
): { start: number; end: number } | "invalid" | null => {
|
||||
if (!header) return null;
|
||||
const match = BYTE_RANGE.exec(header.trim());
|
||||
if (!match) return null;
|
||||
const [, rawStart, rawEnd] = match;
|
||||
let start: number;
|
||||
let end: number;
|
||||
if (rawStart === "") {
|
||||
const suffix = Number(rawEnd);
|
||||
if (!Number.isInteger(suffix) || suffix <= 0) return "invalid";
|
||||
start = Math.max(0, total - suffix);
|
||||
end = total - 1;
|
||||
} else {
|
||||
start = Number(rawStart);
|
||||
end = rawEnd === "" ? total - 1 : Number(rawEnd);
|
||||
}
|
||||
if (!Number.isInteger(start) || !Number.isInteger(end)) return "invalid";
|
||||
if (start < 0 || start >= total) return "invalid";
|
||||
if (end >= total) end = total - 1;
|
||||
if (end < start) return "invalid";
|
||||
return { start, end };
|
||||
};
|
||||
|
||||
const isPreviewable = (mime: string): boolean => {
|
||||
const value = mime.toLowerCase();
|
||||
if (value === "image/svg+xml") return false;
|
||||
return (
|
||||
value.startsWith("image/") ||
|
||||
value.startsWith("video/") ||
|
||||
value.startsWith("audio/") ||
|
||||
value === "application/pdf" ||
|
||||
value === "text/plain"
|
||||
);
|
||||
};
|
||||
|
||||
interface ServeOptions {
|
||||
absolute: string;
|
||||
size: number;
|
||||
mime: string;
|
||||
disposition: string;
|
||||
range: string | undefined;
|
||||
}
|
||||
|
||||
const serveFile = ({ absolute, size, mime, disposition, range }: ServeOptions): Response => {
|
||||
const headers: Record<string, string> = {
|
||||
"content-type": mime,
|
||||
"content-disposition": disposition,
|
||||
"accept-ranges": "bytes",
|
||||
"cache-control": "private, max-age=0, must-revalidate",
|
||||
"x-content-type-options": "nosniff",
|
||||
};
|
||||
|
||||
const parsed = parseRange(range, size);
|
||||
if (parsed === "invalid") {
|
||||
return new Response(null, {
|
||||
status: 416,
|
||||
headers: { ...headers, "content-range": `bytes */${size}` },
|
||||
});
|
||||
}
|
||||
if (parsed) {
|
||||
const stream = Readable.toWeb(openForDownload(absolute, parsed)) as ReadableStream<Uint8Array>;
|
||||
return new Response(stream, {
|
||||
status: 206,
|
||||
headers: {
|
||||
...headers,
|
||||
"content-range": `bytes ${parsed.start}-${parsed.end}/${size}`,
|
||||
"content-length": String(parsed.end - parsed.start + 1),
|
||||
},
|
||||
});
|
||||
}
|
||||
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
|
||||
return new Response(stream, { headers: { ...headers, "content-length": String(size) } });
|
||||
};
|
||||
|
||||
export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/files/*", attachUser(db, config.SESSION_SECRET));
|
||||
app.use("/api/cloud/files", attachUser(db, config.SESSION_SECRET));
|
||||
|
||||
app.put(
|
||||
"/api/cloud/files",
|
||||
requireAuth,
|
||||
requireRole("admin", "user"),
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const name = assertName(context.req.query("name"), "fichier");
|
||||
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.");
|
||||
}
|
||||
|
||||
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 created = await uploadFile(db, config, user, {
|
||||
name,
|
||||
folderId,
|
||||
declared,
|
||||
mimeType: mimeOf(context.req.header("content-type")),
|
||||
body: context.req.raw.body,
|
||||
});
|
||||
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"file.upload",
|
||||
"file",
|
||||
created.id,
|
||||
{ name, size: created.size_bytes, folder_id: folderId },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
const files = await listFiles(db, user, folderId);
|
||||
return context.json({ folderId, files: files.map(publicFile) });
|
||||
});
|
||||
|
||||
app.get("/api/cloud/favorites", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const files = await listFavorites(db, user);
|
||||
return context.json({
|
||||
files: files.map((row) => ({ ...publicFile(row), folder_name: row.folder_name })),
|
||||
});
|
||||
});
|
||||
|
||||
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 getFile(db, user, rawId);
|
||||
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);
|
||||
|
||||
return serveFile({
|
||||
absolute,
|
||||
size: row.size_bytes,
|
||||
mime: row.mime_type ?? "application/octet-stream",
|
||||
disposition: contentDisposition(row.name),
|
||||
range: context.req.header("range"),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/cloud/files/:id/preview", 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 getFile(db, user, rawId);
|
||||
const mime = (row.mime_type ?? "").toLowerCase();
|
||||
if (!isPreviewable(mime)) throw AppError.notFound("Apercu indisponible.");
|
||||
|
||||
const absolute = absolutePath(config.MEDIA_DIR, row.relative_path);
|
||||
if (!(await fileExists(absolute))) throw AppError.notFound("Fichier introuvable sur le support.");
|
||||
|
||||
return serveFile({
|
||||
absolute,
|
||||
size: row.size_bytes,
|
||||
mime: row.mime_type ?? "application/octet-stream",
|
||||
disposition: contentDisposition(row.name, true),
|
||||
range: context.req.header("range"),
|
||||
});
|
||||
});
|
||||
|
||||
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 getFile(db, user, rawId);
|
||||
|
||||
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",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
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 { name: rawName } = parse(renameInput, await readJson(context));
|
||||
const name = assertName(rawName, "fichier");
|
||||
|
||||
const updated = await renameFile(db, user, rawId, name);
|
||||
await audit(db, context, user, "file.rename", "file", rawId, { name }, config.TRUST_PROXY);
|
||||
return context.json({ file: publicFile(updated) });
|
||||
});
|
||||
|
||||
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 { folderId } = parse(moveInput, await readJson(context));
|
||||
const destination = folderId ?? null;
|
||||
|
||||
const updated = await moveFile(db, user, rawId, destination);
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"file.move",
|
||||
"file",
|
||||
rawId,
|
||||
{ folderId: destination },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
return context.json({ file: publicFile(updated) });
|
||||
});
|
||||
|
||||
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 updated = await toggleStar(db, user, rawId);
|
||||
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 deleteFile(db, user, rawId);
|
||||
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 });
|
||||
});
|
||||
};
|
||||
@@ -1,702 +0,0 @@
|
||||
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 f.id, f.folder_id, f.name, f.mime_type, f.size_bytes, f.checksum_sha256,
|
||||
f.relative_path, f.owner_id,
|
||||
EXISTS (SELECT 1 FROM user_file_stars s WHERE s.file_id = f.id AND s.user_id = ?) AS is_starred,
|
||||
f.download_count, f.created_at, f.updated_at
|
||||
FROM files f`;
|
||||
|
||||
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, inline = false): string => {
|
||||
const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
|
||||
const kind = inline ? "inline" : "attachment";
|
||||
return `${kind}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
|
||||
};
|
||||
|
||||
const BYTE_RANGE = /^bytes=(\d*)-(\d*)$/;
|
||||
|
||||
/**
|
||||
* Analyse un en-tete `Range` (une seule plage). Rend `null` quand il faut servir
|
||||
* le corps entier (absent ou illisible), `"invalid"` quand la plage est
|
||||
* insatisfiable (reponse 416), sinon les bornes inclusives a servir.
|
||||
*/
|
||||
const parseRange = (
|
||||
header: string | undefined,
|
||||
total: number,
|
||||
): { start: number; end: number } | "invalid" | null => {
|
||||
if (!header) return null;
|
||||
const match = BYTE_RANGE.exec(header.trim());
|
||||
if (!match) return null;
|
||||
const [, rawStart, rawEnd] = match;
|
||||
let start: number;
|
||||
let end: number;
|
||||
if (rawStart === "") {
|
||||
const suffix = Number(rawEnd);
|
||||
if (!Number.isInteger(suffix) || suffix <= 0) return "invalid";
|
||||
start = Math.max(0, total - suffix);
|
||||
end = total - 1;
|
||||
} else {
|
||||
start = Number(rawStart);
|
||||
end = rawEnd === "" ? total - 1 : Number(rawEnd);
|
||||
}
|
||||
if (!Number.isInteger(start) || !Number.isInteger(end)) return "invalid";
|
||||
if (start < 0 || start >= total) return "invalid";
|
||||
if (end >= total) end = total - 1;
|
||||
if (end < start) return "invalid";
|
||||
return { start, end };
|
||||
};
|
||||
|
||||
/**
|
||||
* Types servis en flux pour l'apercu en ligne. Liste blanche stricte : jamais
|
||||
* `text/html`, `image/svg+xml` ni `application/xhtml+xml`, qui s'executeraient
|
||||
* dans l'origine de l'application. Le telechargement, lui, reste `attachment`.
|
||||
*/
|
||||
const isPreviewable = (mime: string): boolean => {
|
||||
const value = mime.toLowerCase();
|
||||
if (value === "image/svg+xml") return false;
|
||||
return (
|
||||
value.startsWith("image/") ||
|
||||
value.startsWith("video/") ||
|
||||
value.startsWith("audio/") ||
|
||||
value === "application/pdf" ||
|
||||
value === "text/plain"
|
||||
);
|
||||
};
|
||||
|
||||
interface ServeOptions {
|
||||
absolute: string;
|
||||
size: number;
|
||||
mime: string;
|
||||
disposition: string;
|
||||
range: string | undefined;
|
||||
}
|
||||
|
||||
/** Repond avec le fichier, en gerant `Range` (206) et les plages invalides (416). */
|
||||
const serveFile = ({ absolute, size, mime, disposition, range }: ServeOptions): Response => {
|
||||
const headers: Record<string, string> = {
|
||||
"content-type": mime,
|
||||
"content-disposition": disposition,
|
||||
"accept-ranges": "bytes",
|
||||
"cache-control": "private, max-age=0, must-revalidate",
|
||||
"x-content-type-options": "nosniff",
|
||||
};
|
||||
|
||||
const parsed = parseRange(range, size);
|
||||
if (parsed === "invalid") {
|
||||
return new Response(null, {
|
||||
status: 416,
|
||||
headers: { ...headers, "content-range": `bytes */${size}` },
|
||||
});
|
||||
}
|
||||
if (parsed) {
|
||||
const stream = Readable.toWeb(openForDownload(absolute, parsed)) as ReadableStream<Uint8Array>;
|
||||
return new Response(stream, {
|
||||
status: 206,
|
||||
headers: {
|
||||
...headers,
|
||||
"content-range": `bytes ${parsed.start}-${parsed.end}/${size}`,
|
||||
"content-length": String(parsed.end - parsed.start + 1),
|
||||
},
|
||||
});
|
||||
}
|
||||
const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream<Uint8Array>;
|
||||
return new Response(stream, { headers: { ...headers, "content-length": String(size) } });
|
||||
};
|
||||
|
||||
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 f.id = ?`, [user.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 && !(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 f.deleted_at IS NULL
|
||||
AND (f.folder_id <=> ?)
|
||||
AND ( ? = 1
|
||||
OR f.owner_id = ?
|
||||
OR ( f.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f2
|
||||
WHERE f2.id = f.folder_id AND f2.access_type = 'public' ) )
|
||||
OR ( f.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = f.folder_id
|
||||
AND fp.user_id = ?
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL
|
||||
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY is_starred DESC, f.name`,
|
||||
[user.id, folderId, 0, user.id, user.id],
|
||||
);
|
||||
|
||||
return context.json({ folderId, files: rows.map(publicFile) });
|
||||
});
|
||||
|
||||
/**
|
||||
* Favoris : tous les fichiers etoiles accessibles a la session, tous dossiers
|
||||
* confondus. Le filtre reprend exactement les droits de lecture de
|
||||
* l'explorateur (proprietaire, dossier public, permission nominative), sans
|
||||
* exception pour le role global.
|
||||
*/
|
||||
app.get("/api/cloud/favorites", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const rows = await db.query<FileRow & { folder_name: string | null }>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.checksum_sha256,
|
||||
fi.relative_path, fi.owner_id, 1 AS is_starred, fi.download_count,
|
||||
fi.created_at, fi.updated_at, fo.name AS folder_name
|
||||
FROM files fi
|
||||
JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
|
||||
LEFT JOIN folders fo ON fo.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NULL
|
||||
AND ( fi.owner_id = ?
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = fi.folder_id AND f.deleted_at IS NULL
|
||||
AND f.access_type = 'public' ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL
|
||||
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY ufs.created_at DESC`,
|
||||
[user.id, user.id, user.id],
|
||||
);
|
||||
|
||||
return context.json({
|
||||
files: rows.map((row) => ({ ...publicFile(row), folder_name: row.folder_name })),
|
||||
});
|
||||
});
|
||||
|
||||
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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const allowed =
|
||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
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);
|
||||
|
||||
return serveFile({
|
||||
absolute,
|
||||
size: row.size_bytes,
|
||||
mime: row.mime_type ?? "application/octet-stream",
|
||||
disposition: contentDisposition(row.name),
|
||||
range: context.req.header("range"),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Apercu en ligne (flux `inline`) : lecture d'une video ou d'un son, rendu
|
||||
* d'une image ou d'un PDF. Memes droits que le telechargement, sans
|
||||
* incrementation de `download_count`. Types sur liste blanche uniquement.
|
||||
*/
|
||||
app.get("/api/cloud/files/:id/preview", 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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const allowed =
|
||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const mime = (row.mime_type ?? "").toLowerCase();
|
||||
if (!isPreviewable(mime)) throw AppError.notFound("Apercu indisponible.");
|
||||
|
||||
const absolute = absolutePath(config.MEDIA_DIR, row.relative_path);
|
||||
if (!(await fileExists(absolute))) throw AppError.notFound("Fichier introuvable sur le support.");
|
||||
|
||||
return serveFile({
|
||||
absolute,
|
||||
size: row.size_bytes,
|
||||
mime: row.mime_type ?? "application/octet-stream",
|
||||
disposition: contentDisposition(row.name, true),
|
||||
range: context.req.header("range"),
|
||||
});
|
||||
});
|
||||
|
||||
/** 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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
|
||||
if (!row) throw AppError.notFound("Image introuvable.");
|
||||
|
||||
const allowed =
|
||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||
if (!allowed) throw AppError.notFound("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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||
const permitted =
|
||||
owner ||
|
||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
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 f.id = ?`, [user.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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||
const canLeave =
|
||||
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 f.id = ?`, [user.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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const allowed =
|
||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const starred = await db.one(
|
||||
"SELECT 1 AS mark FROM user_file_stars WHERE user_id = ? AND file_id = ?",
|
||||
[user.id, row.id],
|
||||
);
|
||||
if (starred) {
|
||||
await db.exec(
|
||||
"DELETE FROM user_file_stars WHERE user_id = ? AND file_id = ?",
|
||||
[user.id, row.id],
|
||||
);
|
||||
} else {
|
||||
await db.exec(
|
||||
"INSERT INTO user_file_stars (user_id, file_id) VALUES (?, ?)",
|
||||
[user.id, row.id],
|
||||
);
|
||||
}
|
||||
const updated = await db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.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 f.id = ? AND f.deleted_at IS NULL`, [user.id, rawId]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||
const permitted =
|
||||
owner ||
|
||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
// 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 });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,164 @@
|
||||
import { z } from "zod";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { attachUser, currentUser, requireAuth, requireRole } from "../middleware/auth.js";
|
||||
import { audit } from "../services/auditService.js";
|
||||
import {
|
||||
createFolder,
|
||||
deleteFolder,
|
||||
grantPermission,
|
||||
listFolders,
|
||||
listPermissions,
|
||||
moveFolder,
|
||||
publicFolder,
|
||||
renameFolder,
|
||||
revokePermission,
|
||||
} from "../services/folderService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { readJson, type App } from "../utils/http.js";
|
||||
import { assertName, parse, uuid } from "../utils/validators.js";
|
||||
|
||||
const createFolderInput = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
parentId: uuid.nullish(),
|
||||
});
|
||||
|
||||
const updateFolderInput = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
});
|
||||
|
||||
const moveFolderInput = 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(),
|
||||
});
|
||||
|
||||
export const registerFolderRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/folders/*", attachUser(db, config.SESSION_SECRET));
|
||||
app.use("/api/cloud/folders", attachUser(db, config.SESSION_SECRET));
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
const folders = await listFolders(db, user, parentId);
|
||||
return context.json({ parentId, folders: folders.map(publicFolder) });
|
||||
});
|
||||
|
||||
app.post(
|
||||
"/api/cloud/folders",
|
||||
requireAuth,
|
||||
requireRole("admin", "user"),
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const { name: rawName, parentId } = parse(createFolderInput, await readJson(context));
|
||||
const name = assertName(rawName, "dossier");
|
||||
|
||||
const created = await createFolder(db, user, name, parentId ?? null);
|
||||
|
||||
await audit(db, context, user, "folder.create", "folder", created.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 data = parse(updateFolderInput, await readJson(context));
|
||||
const name = assertName(data.name, "dossier");
|
||||
|
||||
const updated = await renameFolder(db, user, id, name);
|
||||
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 { parentId } = parse(moveFolderInput, await readJson(context));
|
||||
|
||||
const updated = await moveFolder(db, user, id, parentId ?? null);
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"folder.move",
|
||||
"folder",
|
||||
id,
|
||||
{ parentId: parentId ?? null },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
return context.json({ folder: publicFolder(updated) });
|
||||
});
|
||||
|
||||
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 removed = await deleteFolder(db, user, id);
|
||||
|
||||
await audit(db, context, user, "folder.delete", "folder", id, { name: removed.name }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
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.");
|
||||
|
||||
const permissions = await listPermissions(db, user, id);
|
||||
return context.json({
|
||||
permissions: permissions.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.");
|
||||
|
||||
const { email, level, expiresAt } = parse(permissionInput, await readJson(context));
|
||||
|
||||
const granted = await grantPermission(db, user, id, { email, level, expiresAt: expiresAt ?? null });
|
||||
|
||||
await audit(db, context, user, "folder.share", "folder", id, granted, 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.");
|
||||
}
|
||||
|
||||
await revokePermission(db, user, id, userId);
|
||||
|
||||
await audit(db, context, user, "folder.unshare", "folder", id, { userId }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -1,390 +0,0 @@
|
||||
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, canTraverse, 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(),
|
||||
});
|
||||
|
||||
const updateFolder = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
});
|
||||
|
||||
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;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
is_system: number;
|
||||
storage_location_id: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const SELECT_FOLDER = `SELECT f.id, f.parent_id, f.name, f.owner_id,
|
||||
f.access_type, f.is_system, f.storage_location_id, f.created_at, f.updated_at
|
||||
FROM folders f`;
|
||||
|
||||
const publicFolder = (row: FolderRow) => ({
|
||||
id: row.id,
|
||||
parent_id: row.parent_id,
|
||||
name: row.name,
|
||||
owner_id: row.owner_id,
|
||||
access_type: row.access_type,
|
||||
is_system: row.is_system === 1,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
|
||||
const 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 (parentId !== null) {
|
||||
// Permet la traversée vers un sous-dossier partage.
|
||||
if (!(await canTraverse(db, user, parentId))) {
|
||||
throw AppError.notFound("Dossier introuvable.");
|
||||
}
|
||||
}
|
||||
|
||||
const rows = await db.query<FolderRow>(
|
||||
`${SELECT_FOLDER}
|
||||
WHERE f.deleted_at IS NULL
|
||||
AND (f.parent_id <=> ?)
|
||||
ORDER BY f.name`,
|
||||
[parentId],
|
||||
);
|
||||
|
||||
// Un enfant est visible s'il est lisible directement ou s'il mene a un
|
||||
// partage. Le role admin ne donne aucun droit special ici (voir access.ts).
|
||||
const visible: FolderRow[] = [];
|
||||
for (const row of rows) {
|
||||
if (row.owner_id === user.id || (await canTraverse(db, user, row.id))) {
|
||||
visible.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
return context.json({ parentId, folders: visible.map(publicFolder) });
|
||||
});
|
||||
|
||||
app.post(
|
||||
"/api/cloud/folders",
|
||||
requireAuth,
|
||||
requireRole("admin", "user"),
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const { name: rawName, parentId } = 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, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
[id, locationId, parentId ?? null, name, user.id, user.id],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
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));
|
||||
const name = assertName(data.name);
|
||||
|
||||
try {
|
||||
await db.exec("UPDATE folders SET name = ? WHERE id = ?", [name, id]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
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 });
|
||||
});
|
||||
};
|
||||
@@ -1,86 +0,0 @@
|
||||
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,
|
||||
(ufs.file_id IS NOT NULL) AS is_starred, mm.kind, mm.width, mm.height, fi.created_at,
|
||||
EXISTS ( SELECT 1 FROM file_variants fv
|
||||
WHERE fv.file_id = fi.id AND fv.purpose = 'thumbnail' ) AS has_thumbnail
|
||||
FROM files fi
|
||||
LEFT JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
|
||||
LEFT JOIN media_metadata mm ON mm.file_id = fi.id
|
||||
WHERE fi.deleted_at IS NULL
|
||||
AND ( ? = '' OR mm.kind = ? )
|
||||
AND ( ? = 1
|
||||
OR fi.owner_id = ?
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY fi.created_at DESC
|
||||
LIMIT ${limit} OFFSET ${offset}`,
|
||||
[user.id, kind, kind, 0, user.id, user.id],
|
||||
);
|
||||
|
||||
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,
|
||||
})),
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
|
||||
import { gallery, galleryKinds } from "../services/mediaService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import type { App } from "../utils/http.js";
|
||||
|
||||
export const registerMediaRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/media", attachUser(db, config.SESSION_SECRET));
|
||||
|
||||
app.get("/api/cloud/media", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const kind = context.req.query("kind") ?? "";
|
||||
if (kind !== "" && !(galleryKinds 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 items = await gallery(db, user, kind, limit, offset);
|
||||
return context.json({ kind: kind || null, items });
|
||||
});
|
||||
};
|
||||
@@ -1,111 +0,0 @@
|
||||
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 pattern = `%${escapeLike(q).slice(0, 110)}%`;
|
||||
|
||||
const folders = await db.query<{
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}>(
|
||||
`SELECT f.id, f.parent_id, f.name, f.owner_id,
|
||||
f.access_type, f.created_at, f.updated_at
|
||||
FROM folders f
|
||||
WHERE f.deleted_at IS NULL
|
||||
AND f.name LIKE ?
|
||||
AND ( ? = 1
|
||||
OR f.owner_id = ?
|
||||
OR f.access_type = 'public'
|
||||
OR EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = f.id AND fp.user_id = ?
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||
ORDER BY f.name
|
||||
LIMIT ${LIMIT}`,
|
||||
[pattern, 0, user.id, user.id],
|
||||
);
|
||||
|
||||
const files = await db.query<{
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
is_starred: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
|
||||
(ufs.file_id IS NOT NULL) AS is_starred, fi.created_at, fi.updated_at
|
||||
FROM files fi
|
||||
LEFT JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
|
||||
WHERE fi.deleted_at IS NULL
|
||||
AND fi.name LIKE ?
|
||||
AND ( ? = 1
|
||||
OR fi.owner_id = ?
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY fi.name
|
||||
LIMIT ${LIMIT}`,
|
||||
[user.id, pattern, 0, user.id, user.id],
|
||||
);
|
||||
|
||||
return context.json({
|
||||
query: q,
|
||||
folders: folders.map((row) => ({
|
||||
id: row.id,
|
||||
parent_id: row.parent_id,
|
||||
name: row.name,
|
||||
owner_id: row.owner_id,
|
||||
access_type: row.access_type,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
})),
|
||||
files: files.map((row) => ({
|
||||
id: row.id,
|
||||
folder_id: row.folder_id,
|
||||
name: row.name,
|
||||
mime_type: row.mime_type,
|
||||
size_bytes: row.size_bytes,
|
||||
owner_id: row.owner_id,
|
||||
is_starred: row.is_starred === 1,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
})),
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
|
||||
import { search } from "../services/searchService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import type { App } from "../utils/http.js";
|
||||
|
||||
export const registerSearchRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/search", attachUser(db, config.SESSION_SECRET));
|
||||
|
||||
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.");
|
||||
|
||||
return context.json(await search(db, user, q));
|
||||
});
|
||||
};
|
||||
@@ -1,382 +0,0 @@
|
||||
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 compte : chacun ne voit et ne gere
|
||||
* que ses propres elements supprimes. 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,
|
||||
);
|
||||
|
||||
// Les vignettes vivent dans VARIANT_DIR : sans cette etape, chaque purge
|
||||
// laisse un .webp orphelin sur le disque (les lignes partent en cascade).
|
||||
const variants = await db.query<{ path: string }>(
|
||||
`SELECT path FROM file_variants WHERE file_id IN (${placeholders})`,
|
||||
fileIds,
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
...rows.map((row) => discard(absolutePath(config.MEDIA_DIR, row.relative_path))),
|
||||
...variants.map((variant) => discard(absolutePath(config.VARIANT_DIR, variant.path))),
|
||||
]);
|
||||
|
||||
await db.transaction(async (connection) => {
|
||||
for (const row of rows) {
|
||||
if (row.owner_id) {
|
||||
await connection.execute(
|
||||
"UPDATE users SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
|
||||
[row.size_bytes, row.owner_id],
|
||||
);
|
||||
}
|
||||
await connection.execute(
|
||||
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
|
||||
[row.size_bytes, row.storage_location_id],
|
||||
);
|
||||
}
|
||||
await connection.execute(`DELETE FROM files WHERE id IN (${placeholders})`, fileIds);
|
||||
});
|
||||
};
|
||||
|
||||
/** 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;
|
||||
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,
|
||||
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);
|
||||
|
||||
// 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.owner_id, f.access_type,
|
||||
f.created_at, f.updated_at, f.deleted_at
|
||||
FROM folders f
|
||||
LEFT JOIN folders p ON p.id = f.parent_id
|
||||
WHERE f.deleted_at IS NOT NULL
|
||||
AND f.is_system = 0
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND f.owner_id = ?
|
||||
ORDER BY f.deleted_at DESC`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
const files = await db.query<TrashFileRow>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
|
||||
fi.created_at, fi.updated_at, fi.deleted_at
|
||||
FROM files fi
|
||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NOT NULL
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND fi.owner_id = ?
|
||||
ORDER BY fi.deleted_at DESC`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
const retentionDays = await db.one<{ setting_value: string }>(
|
||||
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
|
||||
);
|
||||
|
||||
return 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 (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 (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 (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 (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 folders = await db.query<{ id: string }>(
|
||||
`SELECT f.id FROM folders f
|
||||
LEFT JOIN folders p ON p.id = f.parent_id
|
||||
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND f.owner_id = ?`,
|
||||
[user.id],
|
||||
);
|
||||
const files = await db.query<{ id: string }>(
|
||||
`SELECT fi.id FROM files fi
|
||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NOT NULL
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND fi.owner_id = ?`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
|
||||
await purgeFiles(db, config, files.map((row) => row.id));
|
||||
|
||||
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;
|
||||
};
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { attachUser, currentUser, requireAuth } from "../middleware/auth.js";
|
||||
import { audit } from "../services/auditService.js";
|
||||
import {
|
||||
emptyTrash,
|
||||
listTrash,
|
||||
publicTrashFile,
|
||||
publicTrashFolder,
|
||||
purgeFile,
|
||||
purgeFolder,
|
||||
restoreFile,
|
||||
restoreFolder,
|
||||
} from "../services/trashService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import type { App } from "../utils/http.js";
|
||||
import { uuid } from "../utils/validators.js";
|
||||
|
||||
export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/trash/*", attachUser(db, config.SESSION_SECRET));
|
||||
app.use("/api/cloud/trash", attachUser(db, config.SESSION_SECRET));
|
||||
|
||||
app.get("/api/cloud/trash", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const content = await listTrash(db, user);
|
||||
return context.json({
|
||||
retentionDays: content.retentionDays,
|
||||
folders: content.folders.map(publicTrashFolder),
|
||||
files: content.files.map(publicTrashFile),
|
||||
});
|
||||
});
|
||||
|
||||
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 restoreFolder(db, user, id);
|
||||
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 restoreFile(db, user, id);
|
||||
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 purgeFolder(db, config, user, 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 purgeFile(db, config, user, id);
|
||||
await audit(db, context, user, "trash.purge", "file", id, { name: row.name }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/trash", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
|
||||
const result = await emptyTrash(db, config, user);
|
||||
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"trash.empty",
|
||||
"trash",
|
||||
null,
|
||||
{ folders: result.folders, files: result.files },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
return context.json({ ok: true, folders: result.folders, files: result.files });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
import { z } from "zod";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { attachUser, currentUser, requireAuth, requireRole } from "../middleware/auth.js";
|
||||
import { audit } from "../services/auditService.js";
|
||||
import { publicFile } from "../services/fileService.js";
|
||||
import {
|
||||
cancelUpload,
|
||||
completeUpload,
|
||||
createUploadSession,
|
||||
getUploadSession,
|
||||
receiveChunk,
|
||||
} from "../services/uploadService.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { readJson, type App } from "../utils/http.js";
|
||||
import { assertName, mimeOf, parse, uuid } from "../utils/validators.js";
|
||||
|
||||
const createInput = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
folderId: uuid.nullish(),
|
||||
size: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
||||
mimeType: z.string().max(255).nullish(),
|
||||
});
|
||||
|
||||
export const registerUploadRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/cloud/uploads/*", attachUser(db, config.SESSION_SECRET));
|
||||
app.use("/api/cloud/uploads", attachUser(db, config.SESSION_SECRET));
|
||||
|
||||
app.post(
|
||||
"/api/cloud/uploads",
|
||||
requireAuth,
|
||||
requireRole("admin", "user"),
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const data = parse(createInput, await readJson(context));
|
||||
const name = assertName(data.name, "fichier");
|
||||
const folderId = data.folderId ?? null;
|
||||
|
||||
const upload = await createUploadSession(db, config, user, {
|
||||
name,
|
||||
folderId,
|
||||
size: data.size,
|
||||
mimeType: mimeOf(data.mimeType ?? undefined),
|
||||
});
|
||||
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"file.upload.start",
|
||||
"file",
|
||||
upload.uploadId,
|
||||
{ name, size: data.size, folder_id: folderId },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
|
||||
return context.json({ upload }, 201);
|
||||
},
|
||||
);
|
||||
|
||||
app.get("/api/cloud/uploads/:id", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const upload = await getUploadSession(db, user, context.req.param("id") ?? "");
|
||||
return context.json({ upload });
|
||||
});
|
||||
|
||||
app.put("/api/cloud/uploads/:id/chunks", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
|
||||
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 morceau invalide.");
|
||||
}
|
||||
|
||||
const body = context.req.raw.body;
|
||||
if (!body) throw AppError.badRequest("Corps de requete vide.");
|
||||
|
||||
const upload = await receiveChunk(db, user, id, body, declared);
|
||||
return context.json({ upload });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/uploads/:id/complete", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const id = context.req.param("id") ?? "";
|
||||
|
||||
const created = await completeUpload(db, config, user, id);
|
||||
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"file.upload",
|
||||
"file",
|
||||
created.id,
|
||||
{ name: created.name, size: created.size_bytes, folder_id: created.folder_id },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
|
||||
return context.json({ file: publicFile(created) }, 201);
|
||||
});
|
||||
|
||||
app.delete("/api/cloud/uploads/:id", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const row = await cancelUpload(db, user, context.req.param("id") ?? "");
|
||||
await audit(
|
||||
db,
|
||||
context,
|
||||
user,
|
||||
"file.upload.cancel",
|
||||
"file",
|
||||
row.id,
|
||||
{ name: row.name },
|
||||
config.TRUST_PROXY,
|
||||
);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,373 @@
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { hashPassword, sessionTokenHash, sha256, verifyPassword } from "./authService.js";
|
||||
import { branding, getMailer, link, renderMail } from "./mailService.js";
|
||||
import { absolutePath, diskUsage, fileExists } from "./storageService.js";
|
||||
|
||||
const AVATAR_PX = 512;
|
||||
const HOUR_MS = 3600_000;
|
||||
|
||||
const avatarRelativePath = (userId: string): string => path.posix.join("avatars", `${userId}.webp`);
|
||||
|
||||
const newToken = (): string => randomBytes(32).toString("base64url");
|
||||
|
||||
export const updateProfile = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
first_name: string,
|
||||
last_name: string,
|
||||
): Promise<{ first_name: string; last_name: string }> => {
|
||||
await db.exec("UPDATE users SET first_name = ?, last_name = ? WHERE id = ?", [
|
||||
first_name,
|
||||
last_name,
|
||||
user.id,
|
||||
]);
|
||||
return { first_name, last_name };
|
||||
};
|
||||
|
||||
export const getPreferences = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
): Promise<{ theme: string; language: string }> => {
|
||||
const row = await db.one<{ theme: string; language: string }>(
|
||||
"SELECT theme, language FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[user.id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Compte introuvable.");
|
||||
return { theme: row.theme, language: row.language };
|
||||
};
|
||||
|
||||
export const updatePreferences = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
theme: string,
|
||||
language: string,
|
||||
): Promise<{ theme: string; language: string }> => {
|
||||
await db.exec("UPDATE users SET theme = ?, language = ? WHERE id = ?", [
|
||||
theme,
|
||||
language,
|
||||
user.id,
|
||||
]);
|
||||
return { theme, language };
|
||||
};
|
||||
|
||||
export interface SessionInfo {
|
||||
id: string;
|
||||
ip_address: string | null;
|
||||
user_agent: string | null;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
expires_at: string;
|
||||
current: boolean;
|
||||
}
|
||||
|
||||
/** Sessions actives de l'utilisateur, la session courante marquee. */
|
||||
export const listSessions = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
currentToken: string,
|
||||
): Promise<SessionInfo[]> => {
|
||||
const current = sessionTokenHash(currentToken, config.SESSION_SECRET);
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
token_hash: string;
|
||||
ip_address: string | null;
|
||||
user_agent: string | null;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
expires_at: string;
|
||||
}>(
|
||||
`SELECT id, token_hash, ip_address, user_agent, created_at, last_seen_at, expires_at
|
||||
FROM user_sessions
|
||||
WHERE user_id = ? AND revoked_at IS NULL AND expires_at > UTC_TIMESTAMP()
|
||||
ORDER BY last_seen_at DESC`,
|
||||
[user.id],
|
||||
);
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
ip_address: row.ip_address,
|
||||
user_agent: row.user_agent,
|
||||
created_at: row.created_at,
|
||||
last_seen_at: row.last_seen_at,
|
||||
expires_at: row.expires_at,
|
||||
current: row.token_hash === current,
|
||||
}));
|
||||
};
|
||||
|
||||
export const revokeSessionById = async (db: Db, user: SessionUser, id: string): Promise<void> => {
|
||||
const result = await db.exec(
|
||||
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE id = ? AND user_id = ? AND revoked_at IS NULL",
|
||||
[id, user.id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Session introuvable.");
|
||||
};
|
||||
|
||||
export const revokeOtherSessions = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
currentToken: string,
|
||||
): Promise<void> => {
|
||||
const current = sessionTokenHash(currentToken, config.SESSION_SECRET);
|
||||
await db.exec(
|
||||
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND token_hash <> ? AND revoked_at IS NULL",
|
||||
[user.id, current],
|
||||
);
|
||||
};
|
||||
|
||||
/** Traite l'image recue (recadrage, webp) et met a jour l'avatar + le quota. */
|
||||
export const uploadAvatar = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
source: Buffer,
|
||||
): Promise<void> => {
|
||||
let processed: Buffer;
|
||||
try {
|
||||
processed = await sharp(source, { failOn: "none" })
|
||||
.rotate()
|
||||
.resize(AVATAR_PX, AVATAR_PX, { fit: "cover" })
|
||||
.webp({ quality: 82 })
|
||||
.toBuffer();
|
||||
} catch {
|
||||
throw AppError.badRequest("Le fichier n'est pas une image exploitable.");
|
||||
}
|
||||
|
||||
const location = await db.one<{ id: number }>(
|
||||
`SELECT id FROM storage_locations
|
||||
WHERE is_active = 1 AND deleted_at IS NULL ORDER BY id LIMIT 1`,
|
||||
);
|
||||
if (!location) throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible.");
|
||||
|
||||
const disk = await diskUsage(config.VARIANT_DIR);
|
||||
if (disk !== null && processed.byteLength > disk.available_bytes) {
|
||||
throw AppError.insufficientStorage("Espace disque insuffisant sur le serveur.");
|
||||
}
|
||||
|
||||
const relative = avatarRelativePath(user.id);
|
||||
const destination = absolutePath(config.VARIANT_DIR, relative);
|
||||
await mkdir(path.dirname(destination), { recursive: true });
|
||||
await writeFile(destination, processed);
|
||||
|
||||
const size = processed.byteLength;
|
||||
const previous = await db.one<{ storage_location_id: number; size_bytes: number }>(
|
||||
"SELECT storage_location_id, size_bytes FROM user_avatars WHERE user_id = ?",
|
||||
[user.id],
|
||||
);
|
||||
|
||||
await db.transaction(async (connection) => {
|
||||
if (previous) {
|
||||
await connection.execute(
|
||||
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
|
||||
[previous.size_bytes, previous.storage_location_id],
|
||||
);
|
||||
}
|
||||
await connection.execute(
|
||||
`UPDATE storage_locations SET used_bytes = used_bytes + ? WHERE id = ?`,
|
||||
[size, location.id],
|
||||
);
|
||||
await connection.execute(
|
||||
`INSERT INTO user_avatars (user_id, storage_location_id, original_path, mime_type, size_bytes, width, height)
|
||||
VALUES (?, ?, ?, 'image/webp', ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE storage_location_id = VALUES(storage_location_id),
|
||||
original_path = VALUES(original_path), mime_type = VALUES(mime_type),
|
||||
size_bytes = VALUES(size_bytes), width = VALUES(width), height = VALUES(height)`,
|
||||
[user.id, location.id, relative, processed.byteLength, AVATAR_PX, AVATAR_PX],
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
/** Chemin et taille de l'avatar d'un utilisateur (null si absent). */
|
||||
export const getAvatar = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
userId: string,
|
||||
): Promise<{ absolute: string; size: number } | null> => {
|
||||
const row = await db.one<{ original_path: string; size_bytes: number }>(
|
||||
"SELECT original_path, size_bytes FROM user_avatars WHERE user_id = ?",
|
||||
[userId],
|
||||
);
|
||||
if (!row) return null;
|
||||
const absolute = absolutePath(config.VARIANT_DIR, row.original_path);
|
||||
if (!(await fileExists(absolute))) return null;
|
||||
return { absolute, size: row.size_bytes };
|
||||
};
|
||||
|
||||
export const deleteAvatar = async (db: Db, user: SessionUser): Promise<void> => {
|
||||
const row = await db.one<{ storage_location_id: number; size_bytes: number }>(
|
||||
"SELECT storage_location_id, size_bytes FROM user_avatars WHERE user_id = ?",
|
||||
[user.id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Avatar introuvable.");
|
||||
await db.transaction(async (connection) => {
|
||||
await connection.execute("DELETE FROM user_avatars WHERE user_id = ?", [user.id]);
|
||||
await connection.execute(
|
||||
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
|
||||
[row.size_bytes, row.storage_location_id],
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
/** Cree un jeton de reinitialisation et envoie le lien (silencieux si compte absent). */
|
||||
export const forgotPassword = async (db: Db, config: Config, email: string): Promise<void> => {
|
||||
const user = await db.one<{ id: string; email: string }>(
|
||||
"SELECT id, email FROM users WHERE active_email = ? AND is_active = 1",
|
||||
[email],
|
||||
);
|
||||
if (!user) return;
|
||||
|
||||
const token = newToken();
|
||||
await db.exec(
|
||||
"INSERT INTO password_reset_tokens (id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)",
|
||||
[randomUUID(), user.id, sha256(token), new Date(Date.now() + HOUR_MS)],
|
||||
);
|
||||
const url = link(config, `/reset-password?token=${encodeURIComponent(token)}`);
|
||||
const mail = renderMail(branding(config), {
|
||||
preview: "Reinitialisez le mot de passe de votre compte.",
|
||||
heading: "Reinitialisation du mot de passe",
|
||||
intro:
|
||||
"Une reinitialisation de mot de passe a ete demandee pour votre compte CoHaiSe Cloud. Choisissez un nouveau mot de passe en suivant le lien ci-dessous.",
|
||||
cta: { label: "Choisir un mot de passe", url },
|
||||
note: "Ce lien expire dans une heure. Si vous n'etes pas a l'origine de cette demande, ignorez ce message : votre mot de passe reste inchange.",
|
||||
});
|
||||
await getMailer(config)
|
||||
.send({
|
||||
to: user.email,
|
||||
subject: "CoHaiSe Cloud — reinitialisation du mot de passe",
|
||||
...mail,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
};
|
||||
|
||||
export interface ResetActor {
|
||||
userId: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
}
|
||||
|
||||
/** Applique la reinitialisation du mot de passe. Renvoie l'acteur pour l'audit. */
|
||||
export const resetPassword = async (
|
||||
db: Db,
|
||||
token: string,
|
||||
password: string,
|
||||
): Promise<ResetActor | null> => {
|
||||
const row = await db.one<{ id: string; user_id: string }>(
|
||||
`SELECT id, user_id FROM password_reset_tokens
|
||||
WHERE token_hash = ? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP()`,
|
||||
[sha256(token)],
|
||||
);
|
||||
if (!row) throw AppError.badRequest("Lien invalide ou expire.");
|
||||
|
||||
const hash = await hashPassword(password);
|
||||
const account = await db.one<{ email: string; first_name: string; last_name: string }>(
|
||||
"SELECT email, first_name, last_name FROM users WHERE id = ?",
|
||||
[row.user_id],
|
||||
);
|
||||
|
||||
await db.transaction(async (connection) => {
|
||||
await connection.execute(
|
||||
"UPDATE users SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP() WHERE id = ?",
|
||||
[hash, row.user_id],
|
||||
);
|
||||
await connection.execute(
|
||||
"UPDATE password_reset_tokens SET used_at = UTC_TIMESTAMP() WHERE id = ?",
|
||||
[row.id],
|
||||
);
|
||||
await connection.execute(
|
||||
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL",
|
||||
[row.user_id],
|
||||
);
|
||||
});
|
||||
|
||||
if (!account) return null;
|
||||
return {
|
||||
userId: row.user_id,
|
||||
email: account.email,
|
||||
first_name: account.first_name,
|
||||
last_name: account.last_name,
|
||||
};
|
||||
};
|
||||
|
||||
/** Demande un changement d'adresse : verifie le mot de passe puis envoie le lien. */
|
||||
export const requestEmailChange = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
password: string,
|
||||
newEmail: string,
|
||||
): Promise<void> => {
|
||||
const row = await db.one<{ password_hash: string }>(
|
||||
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[user.id],
|
||||
);
|
||||
if (!row || !(await verifyPassword(password, row.password_hash))) {
|
||||
throw AppError.unauthorized("Mot de passe incorrect.");
|
||||
}
|
||||
if (newEmail.toLowerCase() === user.email.toLowerCase()) {
|
||||
throw AppError.badRequest("La nouvelle adresse est identique a l'actuelle.");
|
||||
}
|
||||
const taken = await db.one("SELECT id FROM users WHERE active_email = ?", [newEmail]);
|
||||
if (taken) throw AppError.conflict("Cette adresse est deja utilisee.");
|
||||
|
||||
const token = newToken();
|
||||
await db.exec(
|
||||
`INSERT INTO email_change_requests (id, user_id, new_email, token_hash, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
[randomUUID(), user.id, newEmail, sha256(token), new Date(Date.now() + HOUR_MS)],
|
||||
);
|
||||
|
||||
const url = link(config, `/confirm-email?token=${encodeURIComponent(token)}`);
|
||||
const mail = renderMail(branding(config), {
|
||||
preview: "Confirmez votre nouvelle adresse e-mail.",
|
||||
heading: "Confirmez votre nouvelle adresse",
|
||||
intro:
|
||||
"Une demande de changement d'adresse a ete faite pour votre compte CoHaiSe Cloud. Confirmez la nouvelle adresse en suivant le lien ci-dessous.",
|
||||
cta: { label: "Confirmer l'adresse", url },
|
||||
note: "Ce lien expire dans une heure. Sans confirmation, l'adresse reste inchangee.",
|
||||
});
|
||||
await getMailer(config)
|
||||
.send({
|
||||
to: newEmail,
|
||||
subject: "CoHaiSe Cloud — confirmez votre nouvelle adresse",
|
||||
text: mail.text,
|
||||
html: mail.html,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
};
|
||||
|
||||
/** Confirme le changement d'adresse. Renvoie la nouvelle adresse. */
|
||||
export const confirmEmailChange = async (db: Db, token: string): Promise<string> => {
|
||||
const row = await db.one<{ id: string; user_id: string; new_email: string }>(
|
||||
`SELECT id, user_id, new_email FROM email_change_requests
|
||||
WHERE token_hash = ? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP()`,
|
||||
[sha256(token)],
|
||||
);
|
||||
if (!row) throw AppError.badRequest("Lien invalide ou expire.");
|
||||
|
||||
const taken = await db.one("SELECT id FROM users WHERE active_email = ? AND id <> ?", [
|
||||
row.new_email,
|
||||
row.user_id,
|
||||
]);
|
||||
if (taken) throw AppError.conflict("Cette adresse est deja utilisee.");
|
||||
|
||||
await db.transaction(async (connection) => {
|
||||
await connection.execute("UPDATE users SET email = ? WHERE id = ?", [
|
||||
row.new_email,
|
||||
row.user_id,
|
||||
]);
|
||||
await connection.execute(
|
||||
"UPDATE email_change_requests SET used_at = UTC_TIMESTAMP() WHERE id = ?",
|
||||
[row.id],
|
||||
);
|
||||
});
|
||||
|
||||
return row.new_email;
|
||||
};
|
||||
@@ -0,0 +1,494 @@
|
||||
import { randomInt, randomUUID } from "node:crypto";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { hashPassword } from "./authService.js";
|
||||
import { branding, getMailer, link, renderMail } from "./mailService.js";
|
||||
import { diskUsage } from "./storageService.js";
|
||||
|
||||
export interface AdminUserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
quota_bytes: number;
|
||||
used_bytes: number;
|
||||
max_file_bytes: number;
|
||||
is_active: number;
|
||||
must_change_password: number;
|
||||
last_login_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export const publicUser = (row: AdminUserRow) => ({
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
role_slug: row.role_slug,
|
||||
quota_bytes: row.quota_bytes,
|
||||
used_bytes: row.used_bytes,
|
||||
max_file_bytes: row.max_file_bytes,
|
||||
is_active: row.is_active === 1,
|
||||
must_change_password: row.must_change_password === 1,
|
||||
last_login_at: row.last_login_at,
|
||||
created_at: row.created_at,
|
||||
});
|
||||
|
||||
const SELECT_USER = `
|
||||
SELECT u.id, u.email, u.first_name, u.last_name, r.slug AS role_slug,
|
||||
u.quota_bytes, u.used_bytes, u.max_file_bytes, u.is_active,
|
||||
u.must_change_password, u.last_login_at, u.created_at
|
||||
FROM users u
|
||||
JOIN roles r ON r.id = u.role_id`;
|
||||
|
||||
const UNITS = ["o", "Ko", "Mo", "Go", "To", "Po"];
|
||||
|
||||
const humanBytes = (bytes: number): string => {
|
||||
let value = bytes;
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < UNITS.length - 1) {
|
||||
value /= 1024;
|
||||
unit += 1;
|
||||
}
|
||||
return `${value.toFixed(unit === 0 || value >= 10 ? 0 : 1)} ${UNITS[unit]}`;
|
||||
};
|
||||
|
||||
const generatePasswordValue = (): string => {
|
||||
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
let out = "";
|
||||
for (let index = 0; index < 18; index += 1) out += alphabet[randomInt(alphabet.length)];
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Reaffecte ou supprime les dossiers d'un compte supprime. */
|
||||
const rehomeUserFolders = async (
|
||||
db: Db,
|
||||
userId: string,
|
||||
): Promise<{ kept: number; deleted: number }> => {
|
||||
const folders = await db.query<{ id: string; parent_id: string | null }>(
|
||||
"SELECT id, parent_id FROM folders WHERE owner_id = ? AND deleted_at IS NULL AND is_system = 0",
|
||||
[userId],
|
||||
);
|
||||
if (folders.length === 0) return { kept: 0, deleted: 0 };
|
||||
|
||||
const ids = folders.map((folder) => folder.id);
|
||||
const placeholders = ids.map(() => "?").join(",");
|
||||
|
||||
const candidates = await db.query<{
|
||||
folder_id: string;
|
||||
user_id: string;
|
||||
level: string;
|
||||
created_at: string;
|
||||
}>(
|
||||
`SELECT fp.folder_id, fp.user_id, fp.level, fp.created_at
|
||||
FROM folder_permissions fp
|
||||
JOIN users u ON u.id = fp.user_id AND u.deleted_at IS NULL AND u.is_active = 1
|
||||
WHERE fp.folder_id IN (${placeholders})
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() )
|
||||
ORDER BY FIELD(fp.level, 'admin', 'write', 'read'), fp.created_at ASC`,
|
||||
[...ids],
|
||||
);
|
||||
|
||||
const newOwner = new Map<string, string>();
|
||||
for (const row of candidates) {
|
||||
if (!newOwner.has(row.folder_id)) newOwner.set(row.folder_id, row.user_id);
|
||||
}
|
||||
|
||||
const owned = new Map(folders.map((folder) => [folder.id, folder.parent_id]));
|
||||
const keepIds = [...newOwner.keys()];
|
||||
const deleteIds = ids.filter((id) => !newOwner.has(id));
|
||||
|
||||
await db.transaction(async (connection) => {
|
||||
for (const [id, owner] of newOwner) {
|
||||
const parentId = owned.get(id) ?? null;
|
||||
const parentGone = parentId !== null && owned.has(parentId) && !newOwner.has(parentId);
|
||||
await connection.execute(
|
||||
"UPDATE folders SET owner_id = ?, parent_id = ? WHERE id = ?",
|
||||
[owner, parentGone ? null : parentId, id],
|
||||
);
|
||||
}
|
||||
|
||||
if (deleteIds.length > 0) {
|
||||
const delPh = deleteIds.map(() => "?").join(",");
|
||||
await connection.execute(
|
||||
`UPDATE folders SET parent_id = NULL
|
||||
WHERE parent_id IN (${delPh}) AND deleted_at IS NULL
|
||||
AND owner_id <> ? AND id NOT IN (${keepIds.map(() => "?").join(",") || "''"})`,
|
||||
[...deleteIds, userId, ...(keepIds.length > 0 ? keepIds : [])],
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${delPh}) AND deleted_at IS NULL`,
|
||||
deleteIds,
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${delPh}) AND deleted_at IS NULL`,
|
||||
deleteIds,
|
||||
);
|
||||
}
|
||||
|
||||
await connection.execute("DELETE FROM folder_permissions WHERE user_id = ?", [userId]);
|
||||
await connection.execute("DELETE FROM user_file_stars WHERE user_id = ?", [userId]);
|
||||
});
|
||||
|
||||
return { kept: keepIds.length, deleted: deleteIds.length };
|
||||
};
|
||||
|
||||
const assertQuotaFits = async (config: Config, quota: number): Promise<void> => {
|
||||
const disk = await diskUsage(config.MEDIA_DIR);
|
||||
if (disk !== null && quota > disk.total_bytes) {
|
||||
throw AppError.badRequest(
|
||||
`Le quota depasse la capacite du disque (${humanBytes(disk.total_bytes)}).`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const getStats = async (db: Db, config: Config) => {
|
||||
const [users] = await db.query<{ count: number }>(
|
||||
"SELECT COUNT(*) AS count FROM users WHERE deleted_at IS NULL",
|
||||
);
|
||||
const [folders] = await db.query<{ count: number }>(
|
||||
"SELECT COUNT(*) AS count FROM folders WHERE deleted_at IS NULL",
|
||||
);
|
||||
const [files] = await db.query<{ count: number; bytes: number }>(
|
||||
"SELECT COUNT(*) AS count, COALESCE(SUM(size_bytes), 0) AS bytes FROM files WHERE deleted_at IS NULL",
|
||||
);
|
||||
const [trash] = await db.query<{ count: number }>(
|
||||
"SELECT COUNT(*) AS count FROM files WHERE deleted_at IS NOT NULL",
|
||||
);
|
||||
const locations = await db.query<{
|
||||
id: number;
|
||||
name: string;
|
||||
used_bytes: number;
|
||||
quota_bytes: number | null;
|
||||
}>(
|
||||
`SELECT id, name, used_bytes, quota_bytes FROM storage_locations
|
||||
WHERE deleted_at IS NULL ORDER BY id`,
|
||||
);
|
||||
return {
|
||||
users: users?.count ?? 0,
|
||||
folders: folders?.count ?? 0,
|
||||
files: files?.count ?? 0,
|
||||
usedBytes: Number(files?.bytes ?? 0),
|
||||
trashFiles: trash?.count ?? 0,
|
||||
locations,
|
||||
disk: await diskUsage(config.MEDIA_DIR),
|
||||
};
|
||||
};
|
||||
|
||||
export const listUsers = async (db: Db, q: string): Promise<AdminUserRow[]> => {
|
||||
const query = q.trim();
|
||||
if (query) {
|
||||
return db.query<AdminUserRow>(
|
||||
`${SELECT_USER}
|
||||
WHERE u.deleted_at IS NULL
|
||||
AND (u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)
|
||||
ORDER BY u.email LIMIT 500`,
|
||||
[`%${query}%`, `%${query}%`, `%${query}%`],
|
||||
);
|
||||
}
|
||||
return db.query<AdminUserRow>(
|
||||
`${SELECT_USER} WHERE u.deleted_at IS NULL ORDER BY u.email LIMIT 500`,
|
||||
);
|
||||
};
|
||||
|
||||
export interface CreateUserInput {
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
quota_bytes?: number | null | undefined;
|
||||
max_file_bytes?: number | null | undefined;
|
||||
password?: string | null | undefined;
|
||||
}
|
||||
|
||||
export const createUser = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
data: CreateUserInput,
|
||||
): Promise<AdminUserRow> => {
|
||||
const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]);
|
||||
if (!role) throw AppError.badRequest("Role inconnu.");
|
||||
|
||||
const existing = await db.one("SELECT id FROM users WHERE active_email = ?", [data.email]);
|
||||
if (existing) throw AppError.conflict("Ce compte existe deja.");
|
||||
|
||||
const password = data.password ?? generatePasswordValue();
|
||||
const hash = await hashPassword(password);
|
||||
const id = randomUUID();
|
||||
|
||||
await db.exec(
|
||||
`INSERT INTO users
|
||||
(id, email, first_name, last_name, password_hash, role_id,
|
||||
quota_bytes, max_file_bytes, must_change_password, password_changed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?,
|
||||
COALESCE(?, (SELECT CAST(setting_value AS UNSIGNED) FROM settings WHERE setting_key = 'default_quota_bytes'), 429496729600),
|
||||
COALESCE(?, 5368709120),
|
||||
1, NULL)`,
|
||||
[id, data.email, data.first_name, data.last_name, hash, role.id, data.quota_bytes ?? null, data.max_file_bytes ?? null],
|
||||
);
|
||||
|
||||
const created = await db.required<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
|
||||
|
||||
const mail = renderMail(branding(config), {
|
||||
preview: "Votre acces CoHaiSe Cloud est pret.",
|
||||
heading: "Votre compte a ete cree",
|
||||
intro: `Un compte CoHaiSe Cloud vient d'etre ouvert pour ${data.first_name}. Connectez-vous avec les identifiants ci-dessous.`,
|
||||
credentials: { email: data.email, password },
|
||||
cta: { label: "Se connecter", url: link(config, "/login") },
|
||||
note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.",
|
||||
});
|
||||
await getMailer(config)
|
||||
.send({
|
||||
to: data.email,
|
||||
subject: "CoHaiSe Cloud — votre compte est pret",
|
||||
text: mail.text,
|
||||
html: mail.html,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
|
||||
return created;
|
||||
};
|
||||
|
||||
export interface UpdateUserInput {
|
||||
first_name?: string | undefined;
|
||||
last_name?: string | undefined;
|
||||
role_slug?: string | undefined;
|
||||
quota_bytes?: number | undefined;
|
||||
max_file_bytes?: number | undefined;
|
||||
is_active?: boolean | undefined;
|
||||
}
|
||||
|
||||
export const updateUser = async (
|
||||
db: Db,
|
||||
actorId: string,
|
||||
id: string,
|
||||
data: UpdateUserInput,
|
||||
): Promise<AdminUserRow> => {
|
||||
const existing = await db.one<AdminUserRow>(
|
||||
`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!existing) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
if (data.role_slug !== undefined && data.role_slug !== existing.role_slug) {
|
||||
const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]);
|
||||
if (!role) throw AppError.badRequest("Role inconnu.");
|
||||
if (id === actorId) throw AppError.badRequest("Vous ne pouvez pas modifier votre propre role.");
|
||||
if (existing.role_slug === "admin") {
|
||||
const [count] = await db.query<{ count: number }>(
|
||||
`SELECT COUNT(*) AS count FROM users u JOIN roles r ON r.id = u.role_id
|
||||
WHERE r.slug = 'admin' AND u.is_active = 1 AND u.deleted_at IS NULL`,
|
||||
);
|
||||
if ((count?.count ?? 0) <= 1) {
|
||||
throw AppError.badRequest("Impossible de retirer le dernier administrateur.");
|
||||
}
|
||||
}
|
||||
await db.exec("UPDATE users SET role_id = ? WHERE id = ?", [role.id, id]);
|
||||
}
|
||||
|
||||
if (data.first_name !== undefined) {
|
||||
await db.exec("UPDATE users SET first_name = ? WHERE id = ?", [data.first_name, id]);
|
||||
}
|
||||
if (data.last_name !== undefined) {
|
||||
await db.exec("UPDATE users SET last_name = ? WHERE id = ?", [data.last_name, id]);
|
||||
}
|
||||
if (data.quota_bytes !== undefined) {
|
||||
if (data.quota_bytes < existing.used_bytes) {
|
||||
throw AppError.badRequest("Le quota ne peut pas etre inferieur a l'espace deja utilise.");
|
||||
}
|
||||
await db.exec("UPDATE users SET quota_bytes = ? WHERE id = ?", [data.quota_bytes, id]);
|
||||
}
|
||||
if (data.max_file_bytes !== undefined) {
|
||||
await db.exec("UPDATE users SET max_file_bytes = ? WHERE id = ?", [data.max_file_bytes, id]);
|
||||
}
|
||||
if (data.is_active !== undefined) {
|
||||
if (!data.is_active && id === actorId) {
|
||||
throw AppError.badRequest("Vous ne pouvez pas desactiver votre propre compte.");
|
||||
}
|
||||
await db.exec("UPDATE users SET is_active = ? WHERE id = ?", [data.is_active ? 1 : 0, id]);
|
||||
if (!data.is_active) {
|
||||
await db.exec(
|
||||
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return db.required<AdminUserRow>(`${SELECT_USER} WHERE u.id = ?`, [id]);
|
||||
};
|
||||
|
||||
/** Supprime (logiquement) un compte et reattribue ses dossiers. */
|
||||
export const deleteUser = async (
|
||||
db: Db,
|
||||
actorId: string,
|
||||
id: string,
|
||||
): Promise<{ kept: number; deleted: number }> => {
|
||||
const result = await db.exec(
|
||||
"UPDATE users SET deleted_at = UTC_TIMESTAMP(), is_active = 0 WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Compte introuvable.");
|
||||
if (id === actorId) throw AppError.badRequest("Vous ne pouvez pas supprimer votre propre compte.");
|
||||
|
||||
const rehomed = await rehomeUserFolders(db, id);
|
||||
|
||||
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]);
|
||||
return rehomed;
|
||||
};
|
||||
|
||||
/** Reinitialise le mot de passe d'un compte et envoie les identifiants. */
|
||||
export const resetUserPassword = async (db: Db, config: Config, id: string): Promise<void> => {
|
||||
const user = await db.one<{ email: string }>(
|
||||
"SELECT email FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (!user) throw AppError.notFound("Compte introuvable.");
|
||||
|
||||
const password = generatePasswordValue();
|
||||
const hash = await hashPassword(password);
|
||||
await db.exec(
|
||||
"UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = NULL WHERE id = ?",
|
||||
[hash, id],
|
||||
);
|
||||
await db.exec(
|
||||
"UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
|
||||
const mail = renderMail(branding(config), {
|
||||
preview: "Un nouveau mot de passe a ete genere pour votre compte.",
|
||||
heading: "Mot de passe reinitialise",
|
||||
intro: "Un administrateur a reinitialise le mot de passe de votre compte CoHaiSe Cloud.",
|
||||
credentials: { email: user.email, password },
|
||||
cta: { label: "Se connecter", url: link(config, "/login") },
|
||||
note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.",
|
||||
});
|
||||
await getMailer(config)
|
||||
.send({
|
||||
to: user.email,
|
||||
subject: "CoHaiSe Cloud — mot de passe reinitialise",
|
||||
text: mail.text,
|
||||
html: mail.html,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
};
|
||||
|
||||
export interface StorageLocationRow {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
mount_path: string;
|
||||
quota_bytes: number | null;
|
||||
used_bytes: number;
|
||||
is_active: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export const listStorageLocations = async (db: Db, config: Config) => ({
|
||||
locations: await db.query<StorageLocationRow>(
|
||||
`SELECT id, name, slug, mount_path, quota_bytes, used_bytes, is_active, created_at
|
||||
FROM storage_locations WHERE deleted_at IS NULL ORDER BY id`,
|
||||
),
|
||||
disk: await diskUsage(config.MEDIA_DIR),
|
||||
});
|
||||
|
||||
export const createStorageLocation = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
data: { name: string; slug: string; mount_path: string; quota_bytes?: number | null | undefined },
|
||||
): Promise<void> => {
|
||||
if (data.quota_bytes !== undefined && data.quota_bytes !== null) {
|
||||
await assertQuotaFits(config, data.quota_bytes);
|
||||
}
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO storage_locations (name, slug, mount_path, quota_bytes)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
[data.name, data.slug, data.mount_path, data.quota_bytes ?? null],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un emplacement porte deja ce nom ou ce chemin.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const updateStorageLocation = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
id: number,
|
||||
data: { name?: string | undefined; quota_bytes?: number | null | undefined; is_active?: boolean | undefined },
|
||||
): Promise<void> => {
|
||||
const row = await db.one<{ used_bytes: number }>(
|
||||
"SELECT used_bytes FROM storage_locations WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Emplacement introuvable.");
|
||||
if (data.quota_bytes !== undefined && data.quota_bytes !== null && data.quota_bytes < row.used_bytes) {
|
||||
throw AppError.badRequest("Le quota est inferieur a l'espace deja utilise.");
|
||||
}
|
||||
if (data.quota_bytes !== undefined && data.quota_bytes !== null) {
|
||||
await assertQuotaFits(config, data.quota_bytes);
|
||||
}
|
||||
|
||||
const fields: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (data.name !== undefined) {
|
||||
fields.push("name = ?");
|
||||
values.push(data.name);
|
||||
}
|
||||
if (data.quota_bytes !== undefined) {
|
||||
fields.push("quota_bytes = ?");
|
||||
values.push(data.quota_bytes);
|
||||
}
|
||||
if (data.is_active !== undefined) {
|
||||
fields.push("is_active = ?");
|
||||
values.push(data.is_active ? 1 : 0);
|
||||
}
|
||||
if (fields.length === 0) throw AppError.badRequest("Rien a modifier.");
|
||||
values.push(id);
|
||||
await db.exec(`UPDATE storage_locations SET ${fields.join(", ")} WHERE id = ?`, values);
|
||||
};
|
||||
|
||||
export const auditFilters = async (db: Db) => {
|
||||
const actions = await db.query<{ action: string }>(
|
||||
"SELECT DISTINCT action FROM audit_logs ORDER BY action ASC",
|
||||
);
|
||||
const users = await db.query<{ user_id: string; user_email: string | null }>(
|
||||
`SELECT user_id, MAX(user_email) AS user_email
|
||||
FROM audit_logs
|
||||
WHERE user_id IS NOT NULL
|
||||
GROUP BY user_id
|
||||
ORDER BY user_email ASC`,
|
||||
);
|
||||
return {
|
||||
actions: actions.map((row) => row.action),
|
||||
users: users.map((row) => ({ id: row.user_id, email: row.user_email })),
|
||||
};
|
||||
};
|
||||
|
||||
export const auditEntries = async (
|
||||
db: Db,
|
||||
options: { limit: number; offset: number; action?: string | null; userId?: string | null },
|
||||
) => {
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
if (options.action) {
|
||||
conditions.push("action = ?");
|
||||
params.push(options.action);
|
||||
}
|
||||
if (options.userId) {
|
||||
conditions.push("user_id = ?");
|
||||
params.push(options.userId);
|
||||
}
|
||||
const where = conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "";
|
||||
|
||||
return db.query(
|
||||
`SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at
|
||||
FROM audit_logs${where} ORDER BY created_at DESC LIMIT ${options.limit} OFFSET ${options.offset}`,
|
||||
params,
|
||||
);
|
||||
};
|
||||
@@ -1,22 +1,9 @@
|
||||
import type { Context } from "hono";
|
||||
import { clientIp as sharedClientIp, type Db, type SessionUser } from "./lib/index.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
import { clientIp } from "../utils/http.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.
|
||||
*
|
||||
* Le role `admin` ne donne aucun droit special sur les dossiers ni sur les
|
||||
* fichiers : un administrateur n'accede qu'a ses propres dossiers et a ceux
|
||||
* partages nominativement avec lui, exactement comme un compte ordinaire. Son
|
||||
* role ne sert qu'au panneau d'administration. Consequence directe : il n'est
|
||||
* membre que des salons de discussion des dossiers auxquels il a acces.
|
||||
*/
|
||||
|
||||
/**
|
||||
* SQL de lecture repetee : proprietaire, permission nominative non expiree, ou
|
||||
* dossier public (accessible a tout compte authentifie).
|
||||
*/
|
||||
/** Fragment SQL de lisibilite d'un dossier, partage par les requetes du chat. */
|
||||
export const READ_SQL = `( f.owner_id = ?
|
||||
OR f.access_type = 'public'
|
||||
OR EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
@@ -58,11 +45,6 @@ export const canRead = async (db: Db, user: SessionUser, folderId: string): Prom
|
||||
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,
|
||||
@@ -83,11 +65,6 @@ export const canWriteExplicit = async (
|
||||
return row !== null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gestion du dossier (renommer, deplacer, supprimer, regler les permissions,
|
||||
* moderer le salon) : reservee au proprietaire. Un dossier public permet
|
||||
* d'ajouter, pas de reorganiser l'espace commun.
|
||||
*/
|
||||
export const canManageFolder = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
@@ -101,19 +78,11 @@ export const canManageFolder = async (
|
||||
return row !== null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Verifie si l'utilisateur peut traverser un dossier pour atteindre un
|
||||
* sous-dossier auquel il a acces. Un dossier est traversable s'il y a un
|
||||
* acces direct OU s'il existe un descendant non supprime ayant un acces
|
||||
* direct valide (proprietaire, permission nominative, ou descendant public).
|
||||
* Cela n'accorde PAS d'acces au contenu des dossiers intermediaires.
|
||||
*/
|
||||
export const canTraverse = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string,
|
||||
): Promise<boolean> => {
|
||||
// Acces direct au dossier
|
||||
const direct = await db.one(
|
||||
`SELECT 1 AS granted
|
||||
FROM folders f
|
||||
@@ -129,7 +98,6 @@ export const canTraverse = async (
|
||||
);
|
||||
if (direct !== null) return true;
|
||||
|
||||
// Verifie s'il existe un descendant avec acces direct valide
|
||||
const descendant = await db.one(
|
||||
`WITH RECURSIVE descendants AS (
|
||||
SELECT id, parent_id FROM folders WHERE parent_id = ? AND deleted_at IS NULL
|
||||
@@ -153,14 +121,7 @@ export const canTraverse = async (
|
||||
return descendant !== 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.
|
||||
*/
|
||||
/** Consigne une action dans le journal d'audit (silencieux en cas d'echec). */
|
||||
export const audit = async (
|
||||
db: Db,
|
||||
context: Context,
|
||||
@@ -0,0 +1,241 @@
|
||||
import {
|
||||
createHash,
|
||||
createHmac,
|
||||
randomBytes,
|
||||
randomUUID,
|
||||
scrypt as scryptCallback,
|
||||
timingSafeEqual,
|
||||
} from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { SessionMeta, SessionUser } from "../models/types.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
|
||||
const scrypt = promisify(scryptCallback) as (
|
||||
password: string | Buffer,
|
||||
salt: Buffer,
|
||||
keylen: number,
|
||||
options: { N: number; r: number; p: number; maxmem?: number },
|
||||
) => Promise<Buffer>;
|
||||
|
||||
const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 64, maxmem: 32 * 1024 * 1024 };
|
||||
|
||||
export const hashPassword = async (password: string): Promise<string> => {
|
||||
if (Buffer.byteLength(password) < 8) {
|
||||
throw AppError.badRequest("Le mot de passe doit contenir au moins 8 caracteres.");
|
||||
}
|
||||
const salt = randomBytes(16);
|
||||
const derived = await scrypt(password, salt, SCRYPT.keylen, SCRYPT);
|
||||
return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${salt.toString("base64")}$${derived.toString("base64")}`;
|
||||
};
|
||||
|
||||
export const verifyPassword = async (password: string, stored: string): Promise<boolean> => {
|
||||
const parts = stored.split("$");
|
||||
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
|
||||
const [, n, r, p, saltB64, hashB64] = parts;
|
||||
const salt = Buffer.from(saltB64 ?? "", "base64");
|
||||
const expected = Buffer.from(hashB64 ?? "", "base64");
|
||||
if (expected.length === 0) return false;
|
||||
|
||||
const derived = await scrypt(password, salt, expected.length, {
|
||||
N: Number(n),
|
||||
r: Number(r),
|
||||
p: Number(p),
|
||||
maxmem: SCRYPT.maxmem,
|
||||
});
|
||||
return derived.length === expected.length && timingSafeEqual(derived, expected);
|
||||
};
|
||||
|
||||
export const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex");
|
||||
|
||||
export const sessionTokenHash = (token: string, secret: string): string =>
|
||||
createHmac("sha256", secret).update(token).digest("hex");
|
||||
|
||||
export const SESSION_COOKIE = "cohaise_session";
|
||||
|
||||
export const createSession = async (
|
||||
db: Db,
|
||||
userId: string,
|
||||
meta: SessionMeta,
|
||||
ttlHours: number,
|
||||
secret: string,
|
||||
): Promise<{ token: string; expiresAt: Date }> => {
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const expiresAt = new Date(Date.now() + ttlHours * 3600_000);
|
||||
|
||||
await db.exec(
|
||||
`INSERT INTO user_sessions (id, user_id, token_hash, ip_address, user_agent, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
randomUUID(),
|
||||
userId,
|
||||
sessionTokenHash(token, secret),
|
||||
meta.ipAddress ?? null,
|
||||
meta.userAgent?.slice(0, 255) ?? null,
|
||||
expiresAt,
|
||||
],
|
||||
);
|
||||
return { token, expiresAt };
|
||||
};
|
||||
|
||||
export const resolveSession = async (
|
||||
db: Db,
|
||||
token: string,
|
||||
secret: string,
|
||||
): Promise<SessionUser | null> => {
|
||||
const row = await db.one<SessionUser & { last_seen_at: string }>(
|
||||
`SELECT u.id, u.email, u.first_name, u.last_name,
|
||||
r.slug AS role_slug, r.name AS role_name,
|
||||
u.is_active, u.must_change_password,
|
||||
s.last_seen_at
|
||||
FROM user_sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
JOIN roles r ON r.id = u.role_id
|
||||
WHERE s.token_hash = ?
|
||||
AND s.revoked_at IS NULL
|
||||
AND s.expires_at > UTC_TIMESTAMP()
|
||||
AND u.deleted_at IS NULL
|
||||
AND u.is_active = 1`,
|
||||
[sessionTokenHash(token, secret)],
|
||||
);
|
||||
if (!row) return null;
|
||||
await db.exec(
|
||||
"UPDATE user_sessions SET last_seen_at = UTC_TIMESTAMP() WHERE token_hash = ? AND last_seen_at < UTC_TIMESTAMP(3) - INTERVAL 60 SECOND",
|
||||
[sessionTokenHash(token, secret)],
|
||||
);
|
||||
return row;
|
||||
};
|
||||
|
||||
export const revokeSession = async (db: Db, token: string, secret: string): Promise<void> => {
|
||||
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE token_hash = ?", [
|
||||
sessionTokenHash(token, secret),
|
||||
]);
|
||||
};
|
||||
|
||||
export const purgeExpiredSessions = async (db: Db): Promise<number> => {
|
||||
const result = await db.exec("DELETE FROM user_sessions WHERE expires_at < UTC_TIMESTAMP()");
|
||||
return result.affectedRows;
|
||||
};
|
||||
|
||||
export interface UserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
password_hash: string;
|
||||
role_slug: string;
|
||||
role_name: string;
|
||||
quota_bytes: number;
|
||||
used_bytes: number;
|
||||
max_file_bytes: number;
|
||||
must_change_password: number;
|
||||
is_active: number;
|
||||
theme: string;
|
||||
language: string;
|
||||
avatar_updated_at: Date | null;
|
||||
}
|
||||
|
||||
export const SELECT_USER = `
|
||||
SELECT u.id, u.email, u.first_name, u.last_name, u.password_hash,
|
||||
r.slug AS role_slug, r.name AS role_name,
|
||||
u.quota_bytes, u.used_bytes, u.max_file_bytes, u.must_change_password, u.is_active,
|
||||
u.theme, u.language,
|
||||
ua.updated_at AS avatar_updated_at
|
||||
FROM users u
|
||||
JOIN roles r ON r.id = u.role_id
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = u.id`;
|
||||
|
||||
export const publicUser = (row: UserRow) => ({
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
role_slug: row.role_slug,
|
||||
role_name: row.role_name,
|
||||
quota_bytes: row.quota_bytes,
|
||||
used_bytes: row.used_bytes,
|
||||
max_file_bytes: row.max_file_bytes,
|
||||
must_change_password: row.must_change_password,
|
||||
theme: row.theme,
|
||||
language: row.language,
|
||||
has_avatar: row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
});
|
||||
|
||||
export type PublicUser = ReturnType<typeof publicUser>;
|
||||
|
||||
let dummyHash: Promise<string> | undefined;
|
||||
const decoyHash = (): Promise<string> => (dummyHash ??= hashPassword("aucun-compte-ne-correspond"));
|
||||
|
||||
/** Verifie les identifiants, cree la session et marque la derniere connexion. */
|
||||
export const login = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
email: string,
|
||||
password: string,
|
||||
meta: SessionMeta,
|
||||
): Promise<{ user: PublicUser; token: string; expiresAt: Date }> => {
|
||||
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.active_email = ?`, [email]);
|
||||
|
||||
const stored = row && row.is_active === 1 ? row.password_hash : await decoyHash();
|
||||
if (!row || row.is_active !== 1 || !(await verifyPassword(password, stored))) {
|
||||
throw AppError.unauthorized("Identifiants invalides.");
|
||||
}
|
||||
|
||||
const { token, expiresAt } = await createSession(
|
||||
db,
|
||||
row.id,
|
||||
meta,
|
||||
config.SESSION_TTL_HOURS,
|
||||
config.SESSION_SECRET,
|
||||
);
|
||||
|
||||
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP() WHERE id = ?", [row.id]);
|
||||
|
||||
return { user: publicUser(row), token, expiresAt };
|
||||
};
|
||||
|
||||
/** Renvoie le profil public de l'utilisateur courant. */
|
||||
export const me = async (db: Db, userId: string): Promise<PublicUser> => {
|
||||
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ?`, [userId]);
|
||||
if (!row) throw AppError.unauthorized();
|
||||
return publicUser(row);
|
||||
};
|
||||
|
||||
/** Change le mot de passe et revoque toutes les autres sessions. */
|
||||
export const changePassword = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
userId: string,
|
||||
currentToken: string,
|
||||
currentPassword: string,
|
||||
nextPassword: string,
|
||||
): Promise<void> => {
|
||||
const row = await db.one<{ password_hash: string }>(
|
||||
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[userId],
|
||||
);
|
||||
if (!row) throw AppError.unauthorized();
|
||||
|
||||
if (!(await verifyPassword(currentPassword, row.password_hash))) {
|
||||
throw AppError.unauthorized("Mot de passe actuel incorrect.");
|
||||
}
|
||||
if (currentPassword === nextPassword) {
|
||||
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
|
||||
}
|
||||
|
||||
const hash = await hashPassword(nextPassword);
|
||||
await db.exec(
|
||||
`UPDATE users
|
||||
SET password_hash = ?, must_change_password = 0, password_changed_at = UTC_TIMESTAMP()
|
||||
WHERE id = ?`,
|
||||
[hash, userId],
|
||||
);
|
||||
await db.exec(
|
||||
`UPDATE user_sessions
|
||||
SET revoked_at = UTC_TIMESTAMP()
|
||||
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
|
||||
[userId, sessionTokenHash(currentToken, config.SESSION_SECRET)],
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,278 @@
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { canManageFolder, canRead, READ_SQL } from "./auditService.js";
|
||||
|
||||
const DATETIME_CURSOR = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?$/;
|
||||
|
||||
export interface MessageRow {
|
||||
id: number;
|
||||
user_id: string | null;
|
||||
body: string;
|
||||
created_at: string;
|
||||
edited_at: string | null;
|
||||
is_pinned: number;
|
||||
first_name: string | null;
|
||||
last_name: string | null;
|
||||
avatar_updated_at: Date | null;
|
||||
}
|
||||
|
||||
const SELECT_MESSAGE = `
|
||||
SELECT m.id, m.user_id, m.body, m.created_at, m.edited_at, m.is_pinned,
|
||||
u.first_name, u.last_name, ua.updated_at AS avatar_updated_at
|
||||
FROM chat_messages m
|
||||
LEFT JOIN users u ON u.id = m.user_id
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = m.user_id`;
|
||||
|
||||
export const publicMessage = (row: MessageRow) => ({
|
||||
id: row.id,
|
||||
user_id: row.user_id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
body: row.body,
|
||||
created_at: row.created_at,
|
||||
edited_at: row.edited_at,
|
||||
is_pinned: row.is_pinned === 1,
|
||||
has_avatar: row.user_id !== null && row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
});
|
||||
|
||||
const assertFolder = async (
|
||||
db: Db,
|
||||
folderId: string,
|
||||
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
|
||||
const folder = await db.one<{ id: string; owner_id: string | null; access_type: string }>(
|
||||
"SELECT id, owner_id, access_type FROM folders WHERE id = ? AND deleted_at IS NULL",
|
||||
[folderId],
|
||||
);
|
||||
if (!folder) throw AppError.notFound("Dossier introuvable.");
|
||||
return folder;
|
||||
};
|
||||
|
||||
const assertReadableFolder = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string,
|
||||
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
|
||||
const folder = await assertFolder(db, folderId);
|
||||
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||
return folder;
|
||||
};
|
||||
|
||||
const markRead = async (db: Db, folderId: string, userId: string, messageId: number): Promise<void> => {
|
||||
if (messageId <= 0) return;
|
||||
await db
|
||||
.exec(
|
||||
`INSERT INTO chat_reads (folder_id, user_id, last_read_message_id)
|
||||
VALUES (?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
last_read_message_id = GREATEST(last_read_message_id, ?),
|
||||
updated_at = UTC_TIMESTAMP(3)`,
|
||||
[folderId, userId, messageId, messageId],
|
||||
)
|
||||
.catch(() => undefined);
|
||||
};
|
||||
|
||||
/** Nombre de messages non lus par dossier. */
|
||||
export const unreadCounts = async (db: Db, user: SessionUser): Promise<Record<string, number>> => {
|
||||
const rows = await db.query<{ folder_id: string; unread: number }>(
|
||||
`SELECT f.id AS folder_id, COUNT(m.id) AS unread
|
||||
FROM folders f
|
||||
JOIN chat_messages m
|
||||
ON m.folder_id = f.id
|
||||
AND m.deleted_at IS NULL
|
||||
AND m.user_id <> ?
|
||||
WHERE f.deleted_at IS NULL
|
||||
AND m.id > COALESCE (
|
||||
( SELECT cr.last_read_message_id
|
||||
FROM chat_reads cr
|
||||
WHERE cr.folder_id = f.id AND cr.user_id = ? ), 0 )
|
||||
AND ${READ_SQL}
|
||||
GROUP BY f.id
|
||||
HAVING unread > 0`,
|
||||
[user.id, user.id, user.id, user.id],
|
||||
);
|
||||
|
||||
const unread: Record<string, number> = {};
|
||||
for (const row of rows) unread[row.folder_id] = Number(row.unread);
|
||||
return unread;
|
||||
};
|
||||
|
||||
export interface ChatMember {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
avatar_updated_at: Date | null;
|
||||
last_login_at: string | null;
|
||||
is_self: boolean;
|
||||
}
|
||||
|
||||
export const members = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string,
|
||||
): Promise<ChatMember[]> => {
|
||||
const folder = await assertReadableFolder(db, user, folderId);
|
||||
|
||||
const rows = await db.query<Omit<ChatMember, "is_self">>(
|
||||
`SELECT u.id, u.first_name, u.last_name, r.slug AS role_slug,
|
||||
ua.updated_at AS avatar_updated_at, u.last_login_at
|
||||
FROM users u
|
||||
JOIN roles r ON r.id = u.role_id
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = u.id
|
||||
WHERE u.deleted_at IS NULL AND u.is_active = 1
|
||||
AND ( u.id = ?
|
||||
OR ? = 1
|
||||
OR EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = ? AND fp.user_id = u.id
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||
ORDER BY u.first_name ASC, u.last_name ASC`,
|
||||
[folder.owner_id, folder.access_type === "public" ? 1 : 0, folderId],
|
||||
);
|
||||
|
||||
return rows.map((row) => ({ ...row, is_self: row.id === user.id }));
|
||||
};
|
||||
|
||||
export const messages = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string,
|
||||
options: { after?: number; limit?: number; editedAfter?: string | null },
|
||||
): Promise<{ messages: MessageRow[]; cursor: string }> => {
|
||||
await assertReadableFolder(db, user, folderId);
|
||||
|
||||
const limit = Math.min(200, Math.max(1, options.limit ?? 50));
|
||||
const after = Math.max(0, options.after ?? 0);
|
||||
|
||||
const cursorRow = await db.one<{ chat_cursor: string }>(
|
||||
"SELECT DATE_FORMAT(CURRENT_TIMESTAMP(3), '%Y-%m-%dT%H:%i:%s.%f') AS chat_cursor",
|
||||
);
|
||||
const serverCursor = cursorRow?.chat_cursor ?? "1970-01-01T00:00:00.000000";
|
||||
const editedAfterRaw = options.editedAfter;
|
||||
const editedSince =
|
||||
typeof editedAfterRaw === "string" && DATETIME_CURSOR.test(editedAfterRaw)
|
||||
? editedAfterRaw
|
||||
: serverCursor;
|
||||
|
||||
const rows =
|
||||
after > 0
|
||||
? await db.query<MessageRow>(
|
||||
`${SELECT_MESSAGE}
|
||||
WHERE m.folder_id = ? AND m.deleted_at IS NULL
|
||||
AND ( m.id > ?
|
||||
OR ( m.edited_at IS NOT NULL AND m.edited_at >= ? ) )
|
||||
ORDER BY m.id ASC
|
||||
LIMIT ${limit}`,
|
||||
[folderId, after, editedSince],
|
||||
)
|
||||
: (
|
||||
await db.query<MessageRow>(
|
||||
`${SELECT_MESSAGE}
|
||||
WHERE m.folder_id = ? AND m.deleted_at IS NULL
|
||||
ORDER BY m.id DESC
|
||||
LIMIT ${limit}`,
|
||||
[folderId],
|
||||
)
|
||||
).reverse();
|
||||
|
||||
const newest = rows.reduce((max, row) => Math.max(max, row.id), 0);
|
||||
await markRead(db, folderId, user.id, newest);
|
||||
|
||||
return { messages: rows, cursor: serverCursor };
|
||||
};
|
||||
|
||||
export const sendMessage = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string,
|
||||
body: string,
|
||||
): Promise<MessageRow> => {
|
||||
await assertReadableFolder(db, user, folderId);
|
||||
|
||||
const result = await db.exec(
|
||||
"INSERT INTO chat_messages (folder_id, user_id, body) VALUES (?, ?, ?)",
|
||||
[folderId, user.id, body],
|
||||
);
|
||||
return db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [result.insertId]);
|
||||
};
|
||||
|
||||
export const editMessage = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string,
|
||||
id: number,
|
||||
body: string,
|
||||
): Promise<MessageRow> => {
|
||||
await assertReadableFolder(db, user, folderId);
|
||||
|
||||
const result = await db.exec(
|
||||
`UPDATE chat_messages
|
||||
SET body = ?, edited_at = CURRENT_TIMESTAMP(3)
|
||||
WHERE id = ? AND folder_id = ? AND user_id = ? AND deleted_at IS NULL`,
|
||||
[body, id, folderId, user.id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Message introuvable.");
|
||||
|
||||
return db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [id]);
|
||||
};
|
||||
|
||||
export const togglePin = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string,
|
||||
id: number,
|
||||
): Promise<boolean> => {
|
||||
await assertReadableFolder(db, user, folderId);
|
||||
|
||||
const result = await db.exec(
|
||||
"UPDATE chat_messages SET is_pinned = 1 - is_pinned WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
|
||||
[id, folderId],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Message introuvable.");
|
||||
|
||||
const row = await db.required<{ is_pinned: number }>(
|
||||
"SELECT is_pinned FROM chat_messages WHERE id = ?",
|
||||
[id],
|
||||
);
|
||||
return row.is_pinned === 1;
|
||||
};
|
||||
|
||||
export const pins = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string,
|
||||
): Promise<MessageRow[]> => {
|
||||
await assertReadableFolder(db, user, folderId);
|
||||
|
||||
return db.query<MessageRow>(
|
||||
`${SELECT_MESSAGE}
|
||||
WHERE m.folder_id = ? AND m.is_pinned = 1 AND m.deleted_at IS NULL
|
||||
ORDER BY m.id DESC
|
||||
LIMIT 50`,
|
||||
[folderId],
|
||||
);
|
||||
};
|
||||
|
||||
export const deleteMessage = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string,
|
||||
id: number,
|
||||
): Promise<void> => {
|
||||
await assertReadableFolder(db, user, folderId);
|
||||
|
||||
const row = await db.one<{ user_id: string | null }>(
|
||||
"SELECT user_id FROM chat_messages WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
|
||||
[id, folderId],
|
||||
);
|
||||
if (!row || (row.user_id !== user.id && !(await canManageFolder(db, user, folderId)))) {
|
||||
throw AppError.notFound("Message introuvable.");
|
||||
}
|
||||
|
||||
await db.exec(
|
||||
"UPDATE chat_messages SET deleted_at = CURRENT_TIMESTAMP(3), is_pinned = 0 WHERE id = ?",
|
||||
[id],
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
|
||||
export interface DirectoryUser {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
has_avatar: boolean;
|
||||
avatar_updated_at: Date | null;
|
||||
}
|
||||
|
||||
/** Annuaire des comptes actifs (hors soi-meme). */
|
||||
export const listUsers = async (db: Db, user: SessionUser): Promise<DirectoryUser[]> => {
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
avatar_updated_at: Date | null;
|
||||
}>(
|
||||
`SELECT u.id, u.first_name, u.last_name, u.email,
|
||||
ua.updated_at AS avatar_updated_at
|
||||
FROM users u
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = u.id
|
||||
WHERE u.deleted_at IS NULL AND u.is_active = 1 AND u.id <> ?
|
||||
ORDER BY u.first_name ASC, u.last_name ASC
|
||||
LIMIT 1000`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
email: row.email,
|
||||
has_avatar: row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
}));
|
||||
};
|
||||
@@ -0,0 +1,364 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { FileRow, SessionUser } from "../models/types.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { canRead, canWrite, canWriteExplicit } from "./auditService.js";
|
||||
import { indexMedia } from "./mediaService.js";
|
||||
import {
|
||||
absolutePath,
|
||||
chooseLocation,
|
||||
discard,
|
||||
diskUsage,
|
||||
ensureDir,
|
||||
publish,
|
||||
relativePathFor,
|
||||
temporaryPath,
|
||||
writeBody,
|
||||
} from "./storageService.js";
|
||||
|
||||
export const SELECT_FILE = `SELECT f.id, f.folder_id, f.name, f.mime_type, f.size_bytes, f.checksum_sha256,
|
||||
f.relative_path, f.owner_id,
|
||||
EXISTS (SELECT 1 FROM user_file_stars s WHERE s.file_id = f.id AND s.user_id = ?) AS is_starred,
|
||||
f.download_count, f.created_at, f.updated_at
|
||||
FROM files f`;
|
||||
|
||||
export const publicFile = (row: FileRow) => ({
|
||||
id: row.id,
|
||||
folder_id: row.folder_id,
|
||||
name: row.name,
|
||||
mime_type: row.mime_type,
|
||||
size_bytes: row.size_bytes,
|
||||
checksum_sha256: row.checksum_sha256,
|
||||
owner_id: row.owner_id,
|
||||
is_starred: row.is_starred === 1,
|
||||
download_count: row.download_count,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
|
||||
export const assertNameFree = async (
|
||||
db: Db,
|
||||
user: { id: string },
|
||||
folderId: string | null,
|
||||
name: string,
|
||||
): Promise<void> => {
|
||||
const duplicate = await db.one(
|
||||
`SELECT 1 AS taken FROM files
|
||||
WHERE folder_id <=> ? AND active_name = ? AND deleted_at IS NULL
|
||||
AND ( folder_id IS NOT NULL OR owner_id = ? )
|
||||
LIMIT 1`,
|
||||
[folderId, name, user.id],
|
||||
);
|
||||
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
|
||||
};
|
||||
|
||||
export interface UploadInput {
|
||||
name: string;
|
||||
folderId: string | null;
|
||||
declared: number;
|
||||
mimeType: string;
|
||||
body: ReadableStream<Uint8Array> | null;
|
||||
}
|
||||
|
||||
/** Envoi direct (petits fichiers) : controle, ecriture disque et enregistrement. */
|
||||
export const uploadFile = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
input: UploadInput,
|
||||
): Promise<FileRow> => {
|
||||
const { name, folderId, declared, mimeType, body } = input;
|
||||
|
||||
if (folderId !== null) {
|
||||
const folder = await db.one(
|
||||
"SELECT 1 AS present FROM folders WHERE id = ? AND deleted_at IS NULL",
|
||||
[folderId],
|
||||
);
|
||||
if (!folder) throw AppError.notFound("Dossier introuvable.");
|
||||
if (!(await canWrite(db, user, folderId))) {
|
||||
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
|
||||
}
|
||||
}
|
||||
|
||||
const budget = await db.one<{
|
||||
used_bytes: number;
|
||||
quota_bytes: number;
|
||||
max_file_bytes: number;
|
||||
}>(
|
||||
"SELECT used_bytes, quota_bytes, max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[user.id],
|
||||
);
|
||||
if (!budget) throw AppError.unauthorized();
|
||||
|
||||
if (declared > budget.max_file_bytes) {
|
||||
throw AppError.payloadTooLarge(
|
||||
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
|
||||
);
|
||||
}
|
||||
if (BigInt(budget.used_bytes) + BigInt(declared) > BigInt(budget.quota_bytes)) {
|
||||
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
|
||||
}
|
||||
|
||||
await assertNameFree(db, user, folderId, name);
|
||||
|
||||
const disk = await diskUsage(config.MEDIA_DIR);
|
||||
if (disk !== null && declared > disk.available_bytes) {
|
||||
throw AppError.insufficientStorage(
|
||||
"Espace disque insuffisant sur le serveur pour ce fichier.",
|
||||
);
|
||||
}
|
||||
|
||||
const location = await chooseLocation(db, BigInt(declared));
|
||||
const id = randomUUID();
|
||||
const relative = relativePathFor(location.slug, id, name);
|
||||
const destination = absolutePath(config.MEDIA_DIR, relative);
|
||||
const temporary = temporaryPath(config.MEDIA_DIR, location.slug);
|
||||
|
||||
await ensureDir(path.dirname(destination));
|
||||
|
||||
if (!body) throw AppError.badRequest("Corps de requete vide.");
|
||||
|
||||
let written;
|
||||
try {
|
||||
written = await writeBody(temporary, body, declared, budget.max_file_bytes);
|
||||
} catch (error) {
|
||||
await discard(temporary);
|
||||
throw error;
|
||||
}
|
||||
|
||||
await publish(temporary, destination);
|
||||
|
||||
try {
|
||||
await db.transaction(async (connection) => {
|
||||
const [quota] = await connection.execute(
|
||||
`UPDATE users SET used_bytes = used_bytes + ?
|
||||
WHERE id = ? AND used_bytes + ? <= quota_bytes`,
|
||||
[written.size, user.id, written.size],
|
||||
);
|
||||
if ((quota as { affectedRows: number }).affectedRows === 0) {
|
||||
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
|
||||
}
|
||||
|
||||
const [inserted] = await connection.execute(
|
||||
`INSERT INTO files
|
||||
(id, storage_location_id, folder_id, name, mime_type, size_bytes,
|
||||
checksum_sha256, relative_path, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
id,
|
||||
location.id,
|
||||
folderId,
|
||||
name,
|
||||
mimeType,
|
||||
written.size,
|
||||
written.checksum,
|
||||
relative,
|
||||
user.id,
|
||||
user.id,
|
||||
],
|
||||
);
|
||||
|
||||
const [support] = await connection.execute(
|
||||
`UPDATE storage_locations
|
||||
SET used_bytes = used_bytes + ?
|
||||
WHERE id = ? AND (quota_bytes IS NULL OR used_bytes + ? <= quota_bytes)`,
|
||||
[written.size, location.id, written.size],
|
||||
);
|
||||
if ((support as { affectedRows: number }).affectedRows === 0) {
|
||||
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
|
||||
}
|
||||
void inserted;
|
||||
});
|
||||
} catch (error) {
|
||||
await discard(destination);
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
await indexMedia(db, config, id, mimeType, destination).catch(() => undefined);
|
||||
|
||||
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, id]);
|
||||
};
|
||||
|
||||
/** Liste les fichiers d'un dossier (ou de la racine). */
|
||||
export const listFiles = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
folderId: string | null,
|
||||
): Promise<FileRow[]> => {
|
||||
if (folderId !== null && !(await canRead(db, user, folderId))) {
|
||||
const readable = await db.one(
|
||||
`SELECT 1 AS granted FROM folders f
|
||||
WHERE f.id = ? AND f.deleted_at IS NULL AND f.owner_id = ? LIMIT 1`,
|
||||
[folderId, user.id],
|
||||
);
|
||||
if (!readable) throw AppError.notFound("Dossier introuvable.");
|
||||
}
|
||||
|
||||
return db.query<FileRow>(
|
||||
`${SELECT_FILE}
|
||||
WHERE f.deleted_at IS NULL
|
||||
AND (f.folder_id <=> ?)
|
||||
AND ( ? = 1
|
||||
OR f.owner_id = ?
|
||||
OR ( f.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f2
|
||||
WHERE f2.id = f.folder_id AND f2.access_type = 'public' ) )
|
||||
OR ( f.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f3
|
||||
WHERE f3.id = f.folder_id
|
||||
AND f3.owner_id = ? ) )
|
||||
OR ( f.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = f.folder_id
|
||||
AND fp.user_id = ?
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL
|
||||
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY is_starred DESC, f.name`,
|
||||
[user.id, folderId, 0, user.id, user.id, user.id],
|
||||
);
|
||||
};
|
||||
|
||||
/** Liste les fichiers etoiles de l'utilisateur. */
|
||||
export const listFavorites = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
): Promise<(FileRow & { folder_name: string | null })[]> =>
|
||||
db.query<FileRow & { folder_name: string | null }>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.checksum_sha256,
|
||||
fi.relative_path, fi.owner_id, 1 AS is_starred, fi.download_count,
|
||||
fi.created_at, fi.updated_at, fo.name AS folder_name
|
||||
FROM files fi
|
||||
JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
|
||||
LEFT JOIN folders fo ON fo.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NULL
|
||||
AND ( fi.owner_id = ?
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = fi.folder_id AND f.deleted_at IS NULL
|
||||
AND f.access_type = 'public' ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = fi.folder_id AND f.deleted_at IS NULL
|
||||
AND f.owner_id = ? ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL
|
||||
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY ufs.created_at DESC`,
|
||||
[user.id, user.id, user.id, user.id],
|
||||
);
|
||||
|
||||
/** Charge un fichier en verifiant la lisibilite (ou la gestion) de l'utilisateur. */
|
||||
export const getFile = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
options: { manage?: boolean } = {},
|
||||
): Promise<FileRow> => {
|
||||
const row = await db.one<FileRow>(`${SELECT_FILE} WHERE f.id = ? AND f.deleted_at IS NULL`, [
|
||||
user.id,
|
||||
id,
|
||||
]);
|
||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
if (options.manage) {
|
||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||
const permitted =
|
||||
owner || (row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
||||
return row;
|
||||
}
|
||||
|
||||
const allowed =
|
||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
||||
return row;
|
||||
};
|
||||
|
||||
export const renameFile = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
name: string,
|
||||
): Promise<FileRow> => {
|
||||
const row = await getFile(db, user, id, { manage: true });
|
||||
|
||||
try {
|
||||
await db.exec("UPDATE files SET name = ? WHERE id = ? AND deleted_at IS NULL", [name, row.id]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
|
||||
};
|
||||
|
||||
export const moveFile = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
folderId: string | null,
|
||||
): Promise<FileRow> => {
|
||||
const row = await getFile(db, user, id, { manage: true });
|
||||
|
||||
if (folderId !== null && !(await canWrite(db, user, folderId))) {
|
||||
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
|
||||
}
|
||||
|
||||
try {
|
||||
await db.exec("UPDATE files SET folder_id = ? WHERE id = ?", [folderId, row.id]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un fichier du meme nom existe deja dans la destination.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
|
||||
};
|
||||
|
||||
export const toggleStar = async (db: Db, user: SessionUser, id: string): Promise<FileRow> => {
|
||||
const row = await getFile(db, user, id);
|
||||
|
||||
const starred = await db.one(
|
||||
"SELECT 1 AS mark FROM user_file_stars WHERE user_id = ? AND file_id = ?",
|
||||
[user.id, row.id],
|
||||
);
|
||||
if (starred) {
|
||||
await db.exec("DELETE FROM user_file_stars WHERE user_id = ? AND file_id = ?", [
|
||||
user.id,
|
||||
row.id,
|
||||
]);
|
||||
} else {
|
||||
await db.exec("INSERT INTO user_file_stars (user_id, file_id) VALUES (?, ?)", [
|
||||
user.id,
|
||||
row.id,
|
||||
]);
|
||||
}
|
||||
|
||||
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
|
||||
};
|
||||
|
||||
/** Deplace le fichier vers la corbeille (suppression logique). */
|
||||
export const deleteFile = async (db: Db, user: SessionUser, id: string): Promise<FileRow> => {
|
||||
const row = await getFile(db, user, id, { manage: true });
|
||||
|
||||
const result = await db.exec(
|
||||
"UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
|
||||
[row.id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
return row;
|
||||
};
|
||||
@@ -0,0 +1,290 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { canManageFolder, canTraverse, canWrite } from "./auditService.js";
|
||||
|
||||
export interface FolderRow {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
is_system: number;
|
||||
storage_location_id: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const SELECT_FOLDER = `SELECT f.id, f.parent_id, f.name, f.owner_id,
|
||||
f.access_type, f.is_system, f.storage_location_id, f.created_at, f.updated_at
|
||||
FROM folders f`;
|
||||
|
||||
export const publicFolder = (row: FolderRow) => ({
|
||||
id: row.id,
|
||||
parent_id: row.parent_id,
|
||||
name: row.name,
|
||||
owner_id: row.owner_id,
|
||||
access_type: row.access_type,
|
||||
is_system: row.is_system === 1,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
|
||||
const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
|
||||
const rows = await db.query<{ id: string }>(
|
||||
`WITH RECURSIVE subtree AS (
|
||||
SELECT id FROM folders WHERE id = ?
|
||||
UNION ALL
|
||||
SELECT f.id FROM folders f JOIN subtree s ON f.parent_id = s.id
|
||||
)
|
||||
SELECT id FROM subtree`,
|
||||
[rootId],
|
||||
);
|
||||
return rows.map((row) => row.id);
|
||||
};
|
||||
|
||||
/** Liste les dossiers visibles sous un parent (racine si null). */
|
||||
export const listFolders = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
parentId: string | null,
|
||||
): Promise<FolderRow[]> => {
|
||||
if (parentId !== null && !(await canTraverse(db, user, parentId))) {
|
||||
throw AppError.notFound("Dossier introuvable.");
|
||||
}
|
||||
|
||||
const rows = await db.query<FolderRow>(
|
||||
`${SELECT_FOLDER}
|
||||
WHERE f.deleted_at IS NULL
|
||||
AND (f.parent_id <=> ?)
|
||||
ORDER BY f.name`,
|
||||
[parentId],
|
||||
);
|
||||
|
||||
const visible: FolderRow[] = [];
|
||||
for (const row of rows) {
|
||||
if (row.owner_id === user.id || (await canTraverse(db, user, row.id))) {
|
||||
visible.push(row);
|
||||
}
|
||||
}
|
||||
return visible;
|
||||
};
|
||||
|
||||
export const createFolder = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
name: string,
|
||||
parentId: string | null,
|
||||
): Promise<FolderRow> => {
|
||||
if (parentId && !(await canWrite(db, user, parentId))) {
|
||||
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
|
||||
}
|
||||
|
||||
const duplicate = await db.one(
|
||||
`SELECT 1 AS taken FROM folders
|
||||
WHERE parent_id <=> ? AND active_name = ? AND deleted_at IS NULL
|
||||
AND ( parent_id IS NOT NULL OR owner_id = ? )
|
||||
LIMIT 1`,
|
||||
[parentId ?? null, name, user.id],
|
||||
);
|
||||
if (duplicate) throw AppError.conflict("Ce nom existe deja ici.");
|
||||
|
||||
const parent = parentId
|
||||
? await db.one<{ id: string; storage_location_id: number }>(
|
||||
"SELECT id, storage_location_id FROM folders WHERE id = ? AND deleted_at IS NULL",
|
||||
[parentId],
|
||||
)
|
||||
: null;
|
||||
if (parentId && !parent) throw AppError.notFound("Dossier parent introuvable.");
|
||||
|
||||
const locationId =
|
||||
parent?.storage_location_id ??
|
||||
(
|
||||
await db.one<{ id: number }>(
|
||||
`SELECT id FROM storage_locations
|
||||
WHERE is_active = 1 AND deleted_at IS NULL ORDER BY id LIMIT 1`,
|
||||
)
|
||||
)?.id;
|
||||
if (locationId === undefined) {
|
||||
throw AppError.serviceUnavailable("Aucun emplacement de stockage disponible.");
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO folders (id, storage_location_id, parent_id, name, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
[id, locationId, parentId ?? null, name, user.id, user.id],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
|
||||
};
|
||||
|
||||
export const renameFolder = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
name: string,
|
||||
): Promise<FolderRow> => {
|
||||
const existing = await db.one<FolderRow>(
|
||||
`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!existing) throw AppError.notFound("Dossier introuvable.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
try {
|
||||
await db.exec("UPDATE folders SET name = ? WHERE id = ?", [name, id]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
|
||||
};
|
||||
|
||||
export const moveFolder = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
parentId: string | null,
|
||||
): Promise<FolderRow> => {
|
||||
const existing = await db.one<FolderRow>(
|
||||
`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!existing) throw AppError.notFound("Dossier introuvable.");
|
||||
if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre deplace.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
if (parentId !== null) {
|
||||
if (!(await canWrite(db, user, parentId))) {
|
||||
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier de destination.");
|
||||
}
|
||||
const descendants = await subtreeIds(db, id);
|
||||
if (descendants.includes(parentId)) {
|
||||
throw AppError.badRequest("Impossible de deplacer un dossier dans lui-meme.");
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await db.exec("UPDATE folders SET parent_id = ? WHERE id = ?", [parentId, id]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja dans la destination.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<FolderRow>(`${SELECT_FOLDER} WHERE f.id = ?`, [id]);
|
||||
};
|
||||
|
||||
/** Deplace le dossier et son arborescence vers la corbeille. */
|
||||
export const deleteFolder = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
): Promise<FolderRow> => {
|
||||
const existing = await db.one<FolderRow>(
|
||||
`${SELECT_FOLDER} WHERE f.id = ? AND f.deleted_at IS NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!existing) throw AppError.notFound("Dossier introuvable.");
|
||||
if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre supprime.");
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const ids = await subtreeIds(db, id);
|
||||
const placeholders = ids.map(() => "?").join(",");
|
||||
await db.transaction(async (connection) => {
|
||||
await connection.execute(
|
||||
`UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${placeholders}) AND deleted_at IS NULL`,
|
||||
ids,
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${placeholders}) AND deleted_at IS NULL`,
|
||||
ids,
|
||||
);
|
||||
});
|
||||
|
||||
return existing;
|
||||
};
|
||||
|
||||
export interface FolderPermissionRow {
|
||||
user_id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
level: string;
|
||||
expires_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export const listPermissions = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
): Promise<FolderPermissionRow[]> => {
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const rows = await db.query<FolderPermissionRow>(
|
||||
`SELECT fp.user_id, u.email, u.first_name, u.last_name, fp.level, fp.expires_at, fp.created_at
|
||||
FROM folder_permissions fp
|
||||
JOIN users u ON u.id = fp.user_id
|
||||
WHERE fp.folder_id = ?
|
||||
ORDER BY u.email`,
|
||||
[id],
|
||||
);
|
||||
return rows;
|
||||
};
|
||||
|
||||
export const grantPermission = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
input: { email: string; level: string; expiresAt: string | null },
|
||||
): Promise<{ email: string; level: string }> => {
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const target = await db.one<{ id: string }>(
|
||||
"SELECT id FROM users WHERE active_email = ? AND deleted_at IS NULL",
|
||||
[input.email],
|
||||
);
|
||||
if (!target) throw AppError.notFound("Aucun compte ne correspond a cette adresse.");
|
||||
if (target.id === user.id) {
|
||||
throw AppError.badRequest("Vous etes deja proprietaire de ce dossier.");
|
||||
}
|
||||
|
||||
const expires = input.expiresAt ? new Date(input.expiresAt) : null;
|
||||
await db.exec(
|
||||
`INSERT INTO folder_permissions (id, folder_id, user_id, level, expires_at, granted_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE level = VALUES(level), expires_at = VALUES(expires_at), granted_by = VALUES(granted_by)`,
|
||||
[randomUUID(), id, target.id, input.level, expires, user.id],
|
||||
);
|
||||
|
||||
return { email: input.email, level: input.level };
|
||||
};
|
||||
|
||||
export const revokePermission = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
userId: string,
|
||||
): Promise<void> => {
|
||||
if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const result = await db.exec(
|
||||
"DELETE FROM folder_permissions WHERE folder_id = ? AND user_id = ?",
|
||||
[id, userId],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Partage introuvable.");
|
||||
};
|
||||
@@ -1,42 +1,31 @@
|
||||
import type { Config } from "./config.js";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createTransport, type Transporter } from "nodemailer";
|
||||
import type { Config } from "../config/appConfig.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 MailMessage {
|
||||
to: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
html?: string;
|
||||
}
|
||||
|
||||
export interface Mailer {
|
||||
send: (message: MailMessage) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface Branding {
|
||||
appName: string;
|
||||
origin: string;
|
||||
logoUrl: string;
|
||||
color: string;
|
||||
/** 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;
|
||||
@@ -47,6 +36,71 @@ export interface RenderedMail {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export const LOGO_CID = "cohaise-logo";
|
||||
|
||||
const LOGO_PATH = new URL("../../src/assets/logo.png", import.meta.url);
|
||||
|
||||
const loadLogo = (): Buffer | null => {
|
||||
try {
|
||||
return readFileSync(LOGO_PATH);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const mailers = new WeakMap<Config, Mailer>();
|
||||
|
||||
/** Transport SMTP partage (un par configuration). */
|
||||
export const getMailer = (config: Config): Mailer => {
|
||||
const existing = mailers.get(config);
|
||||
if (existing) return existing;
|
||||
const mailer = createMailer(config);
|
||||
mailers.set(config, mailer);
|
||||
return mailer;
|
||||
};
|
||||
|
||||
export const createMailer = (config: Config): Mailer => {
|
||||
const transport: Transporter = createTransport({
|
||||
host: config.SMTP_HOST,
|
||||
port: config.SMTP_PORT,
|
||||
secure: config.SMTP_SECURE,
|
||||
...(config.SMTP_USER
|
||||
? { auth: { user: config.SMTP_USER, pass: config.SMTP_PASSWORD ?? "" } }
|
||||
: {}),
|
||||
disableFileAccess: true,
|
||||
disableUrlAccess: true,
|
||||
});
|
||||
|
||||
const logo = config.MAIL_LOGO_URL ? null : loadLogo();
|
||||
|
||||
return {
|
||||
send: async (message) => {
|
||||
const inlineLogo = logo !== null && message.html?.includes(`cid:${LOGO_CID}`) === true;
|
||||
await transport.sendMail({
|
||||
from: config.SMTP_FROM,
|
||||
to: message.to,
|
||||
subject: message.subject,
|
||||
text: message.text,
|
||||
...(message.html ? { html: message.html } : {}),
|
||||
...(inlineLogo
|
||||
? { attachments: [{ filename: "logo.png", content: logo, cid: LOGO_CID }] }
|
||||
: {}),
|
||||
});
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const link = (config: Config, path: string): string =>
|
||||
new URL(path, config.PUBLIC_ORIGIN).toString();
|
||||
|
||||
export const branding = (config: Config): Branding => ({
|
||||
appName: "CoHaiSe Cloud",
|
||||
origin: config.PUBLIC_ORIGIN,
|
||||
logoUrl: config.MAIL_LOGO_URL ?? `cid:${LOGO_CID}`,
|
||||
color: "#b71c1c",
|
||||
footer: config.SMTP_FROM,
|
||||
});
|
||||
|
||||
const escapeHtml = (value: string): string =>
|
||||
value
|
||||
.replace(/&/g, "&")
|
||||
@@ -144,4 +198,4 @@ export const renderMail = (brand: Branding, content: MailContent): RenderedMail
|
||||
lines.push("", "Message automatique : merci de ne pas repondre a cet e-mail.", brand.footer);
|
||||
|
||||
return { html, text: lines.join("\n") };
|
||||
};
|
||||
};
|
||||
@@ -2,16 +2,10 @@ 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.
|
||||
*/
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
import { absolutePath } from "./storageService.js";
|
||||
|
||||
export type MediaKind = "image" | "video" | "audio" | "document" | "archive" | "other";
|
||||
|
||||
@@ -48,6 +42,11 @@ export const classify = (mime: string | null): MediaKind => {
|
||||
export const isImage = (mime: string | null): boolean =>
|
||||
(mime ?? "").toLowerCase().startsWith("image/");
|
||||
|
||||
const isRasterImage = (mime: string | null): boolean => {
|
||||
const value = (mime ?? "").toLowerCase();
|
||||
return value.startsWith("image/") && value !== "image/svg+xml";
|
||||
};
|
||||
|
||||
export const thumbnailRelativePath = (fileId: string): string =>
|
||||
path.posix.join("thumbnails", `${fileId}.webp`);
|
||||
|
||||
@@ -82,14 +81,7 @@ const writeThumbnail = async (source: string, destination: string): Promise<Thum
|
||||
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.
|
||||
*/
|
||||
/** Indexe un fichier : classification, vignette et metadonnees d'image. */
|
||||
export const indexMedia = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
@@ -99,7 +91,7 @@ export const indexMedia = async (
|
||||
): Promise<void> => {
|
||||
const kind = classify(mimeType);
|
||||
|
||||
if (!isImage(mimeType)) {
|
||||
if (!isRasterImage(mimeType)) {
|
||||
await db.exec(
|
||||
`INSERT INTO media_metadata (file_id, kind) VALUES (?, ?)
|
||||
ON DUPLICATE KEY UPDATE kind = VALUES(kind)`,
|
||||
@@ -130,7 +122,6 @@ export const indexMedia = async (
|
||||
);
|
||||
};
|
||||
|
||||
/** 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));
|
||||
@@ -139,3 +130,88 @@ export const thumbnailSize = async (config: Config, relative: string): Promise<n
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const;
|
||||
|
||||
export interface GalleryItem {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
is_starred: boolean;
|
||||
kind: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
created_at: string;
|
||||
has_thumbnail: boolean;
|
||||
}
|
||||
|
||||
/** Galerie des medias visibles, filtrable par type. */
|
||||
export const gallery = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
kind: string,
|
||||
limit: number,
|
||||
offset: number,
|
||||
): Promise<GalleryItem[]> => {
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
is_starred: number;
|
||||
kind: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
created_at: string;
|
||||
has_thumbnail: number;
|
||||
}>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
|
||||
(ufs.file_id IS NOT NULL) AS is_starred, mm.kind, mm.width, mm.height, fi.created_at,
|
||||
EXISTS ( SELECT 1 FROM file_variants fv
|
||||
WHERE fv.file_id = fi.id AND fv.purpose = 'thumbnail' ) AS has_thumbnail
|
||||
FROM files fi
|
||||
LEFT JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
|
||||
LEFT JOIN media_metadata mm ON mm.file_id = fi.id
|
||||
WHERE fi.deleted_at IS NULL
|
||||
AND ( ? = '' OR mm.kind = ? )
|
||||
AND ( ? = 1
|
||||
OR fi.owner_id = ?
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f2
|
||||
WHERE f2.id = fi.folder_id AND f2.owner_id = ? ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL
|
||||
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY fi.created_at DESC
|
||||
LIMIT ${limit} OFFSET ${offset}`,
|
||||
[user.id, kind, kind, 0, user.id, user.id, user.id],
|
||||
);
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
folder_id: row.folder_id,
|
||||
name: row.name,
|
||||
mime_type: row.mime_type,
|
||||
size_bytes: row.size_bytes,
|
||||
owner_id: row.owner_id,
|
||||
is_starred: row.is_starred === 1,
|
||||
kind: row.kind,
|
||||
width: row.width,
|
||||
height: row.height,
|
||||
created_at: row.created_at,
|
||||
has_thumbnail: row.has_thumbnail === 1,
|
||||
}));
|
||||
};
|
||||
|
||||
export const galleryKinds = KINDS;
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
|
||||
const escapeLike = (value: string): string =>
|
||||
value.replace(/[\\%_]/g, (match) => `\\${match}`);
|
||||
|
||||
const LIMIT = 100;
|
||||
|
||||
export interface SearchResult {
|
||||
query: string;
|
||||
folders: {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}[];
|
||||
files: {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
is_starred: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
/** Recherche globale dans les dossiers et fichiers visibles. */
|
||||
export const search = async (db: Db, user: SessionUser, q: string): Promise<SearchResult> => {
|
||||
const pattern = `%${escapeLike(q).slice(0, 110)}%`;
|
||||
|
||||
const folders = await db.query<SearchResult["folders"][number]>(
|
||||
`SELECT f.id, f.parent_id, f.name, f.owner_id,
|
||||
f.access_type, f.created_at, f.updated_at
|
||||
FROM folders f
|
||||
WHERE f.deleted_at IS NULL
|
||||
AND f.name LIKE ?
|
||||
AND ( ? = 1
|
||||
OR f.owner_id = ?
|
||||
OR f.access_type = 'public'
|
||||
OR EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = f.id AND fp.user_id = ?
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||
ORDER BY f.name
|
||||
LIMIT ${LIMIT}`,
|
||||
[pattern, 0, user.id, user.id],
|
||||
);
|
||||
|
||||
const files = await db.query<{
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
is_starred: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
|
||||
(ufs.file_id IS NOT NULL) AS is_starred, fi.created_at, fi.updated_at
|
||||
FROM files fi
|
||||
LEFT JOIN user_file_stars ufs ON ufs.file_id = fi.id AND ufs.user_id = ?
|
||||
WHERE fi.deleted_at IS NULL
|
||||
AND fi.name LIKE ?
|
||||
AND ( ? = 1
|
||||
OR fi.owner_id = ?
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f
|
||||
WHERE f.id = fi.folder_id AND f.access_type = 'public' ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folders f2
|
||||
WHERE f2.id = fi.folder_id AND f2.owner_id = ? ) )
|
||||
OR ( fi.folder_id IS NOT NULL
|
||||
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||
ORDER BY fi.name
|
||||
LIMIT ${LIMIT}`,
|
||||
[user.id, pattern, 0, user.id, user.id, user.id],
|
||||
);
|
||||
|
||||
return {
|
||||
query: q,
|
||||
folders: folders.map((row) => ({
|
||||
id: row.id,
|
||||
parent_id: row.parent_id,
|
||||
name: row.name,
|
||||
owner_id: row.owner_id,
|
||||
access_type: row.access_type,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
})),
|
||||
files: files.map((row) => ({
|
||||
id: row.id,
|
||||
folder_id: row.folder_id,
|
||||
name: row.name,
|
||||
mime_type: row.mime_type,
|
||||
size_bytes: row.size_bytes,
|
||||
owner_id: row.owner_id,
|
||||
is_starred: row.is_starred === 1,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
})),
|
||||
};
|
||||
};
|
||||
@@ -1,18 +1,11 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createReadStream, createWriteStream } from "node:fs";
|
||||
import { mkdir, rename, rm, stat, statfs } from "node:fs/promises";
|
||||
import { mkdir, open, readdir, rename, rm, stat, statfs } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { Readable, Transform } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { AppError, 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.
|
||||
*/
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
|
||||
const SLUG = /^[a-z0-9][a-z0-9-]{0,99}$/;
|
||||
const EXTENSION = /^[.][a-z0-9]{1,10}$/i;
|
||||
@@ -22,7 +15,6 @@ export interface StoredLocation {
|
||||
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() : "";
|
||||
@@ -43,11 +35,6 @@ const resolveInside = (mediaDir: string, relative: string): string => {
|
||||
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,
|
||||
@@ -73,12 +60,6 @@ interface WriteResult {
|
||||
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>,
|
||||
@@ -103,8 +84,6 @@ export const writeBody = async (
|
||||
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.`,
|
||||
@@ -118,7 +97,6 @@ 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);
|
||||
};
|
||||
@@ -130,6 +108,62 @@ export const discard = async (...paths: string[]): Promise<void> => {
|
||||
export const temporaryPath = (mediaDir: string, slug: string): string =>
|
||||
path.join(path.resolve(mediaDir), slug, `.upload-${randomUUID()}`);
|
||||
|
||||
export const uploadTempDir = (mediaDir: string): string =>
|
||||
path.join(path.resolve(mediaDir), ".uploads");
|
||||
|
||||
export const uploadTempPath = (mediaDir: string, id: string): string =>
|
||||
path.join(uploadTempDir(mediaDir), `${id}.part`);
|
||||
|
||||
export const preallocateUpload = async (destination: string, size: number): Promise<void> => {
|
||||
await ensureDir(path.dirname(destination));
|
||||
const handle = await open(destination, "wx");
|
||||
try {
|
||||
await handle.truncate(size);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
|
||||
export const writeChunk = async (
|
||||
destination: string,
|
||||
offset: number,
|
||||
body: ReadableStream<Uint8Array>,
|
||||
maxBytes: number,
|
||||
): Promise<number> => {
|
||||
let received = 0;
|
||||
|
||||
const meter = new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
received += chunk.length;
|
||||
if (received > maxBytes) {
|
||||
callback(AppError.payloadTooLarge(`Morceau trop volumineux (maximum ${maxBytes} octets).`));
|
||||
return;
|
||||
}
|
||||
callback(null, chunk);
|
||||
},
|
||||
});
|
||||
|
||||
const source = Readable.fromWeb(body as Parameters<typeof Readable.fromWeb>[0]);
|
||||
await pipeline(source, meter, createWriteStream(destination, { flags: "r+", start: offset }));
|
||||
|
||||
return received;
|
||||
};
|
||||
|
||||
export const hashFile = async (absolute: string): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(absolute)) {
|
||||
hash.update(chunk as Buffer);
|
||||
}
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
export const listUploadTemps = async (mediaDir: string): Promise<string[]> => {
|
||||
const entries = await readdir(uploadTempDir(mediaDir)).catch(() => []);
|
||||
return entries
|
||||
.filter((entry) => entry.endsWith(".part"))
|
||||
.map((entry) => path.join(uploadTempDir(mediaDir), entry));
|
||||
};
|
||||
|
||||
export const fileExists = async (absolute: string): Promise<boolean> => {
|
||||
try {
|
||||
const info = await stat(absolute);
|
||||
@@ -139,24 +173,12 @@ export const fileExists = async (absolute: string): Promise<boolean> => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Ouvre un fichier en lecture. `range` restreint le flux a un intervalle
|
||||
* d'octets inclusif, ce qui permet de repondre a une requete HTTP `Range`
|
||||
* (deplacement dans une video ou un morceau audio) sans lire tout le fichier.
|
||||
*/
|
||||
export const openForDownload = (absolute: string, range?: { start: number; end: number }) =>
|
||||
createReadStream(absolute, range);
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
@@ -169,7 +191,6 @@ export const diskUsage = async (target: string): Promise<DiskUsage | null> => {
|
||||
available_bytes: Number(info.bavail * info.bsize),
|
||||
};
|
||||
} catch {
|
||||
// Support absent ou non monté : l'appelant decide du repli.
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,337 @@
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { SessionUser } from "../models/types.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { absolutePath, discard } from "./storageService.js";
|
||||
|
||||
export interface TrashFileRow {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string;
|
||||
}
|
||||
|
||||
export interface TrashFolderRow {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string;
|
||||
}
|
||||
|
||||
const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
|
||||
const rows = await db.query<{ id: string }>(
|
||||
`WITH RECURSIVE subtree AS (
|
||||
SELECT id FROM folders WHERE id = ?
|
||||
UNION ALL
|
||||
SELECT f.id FROM folders f JOIN subtree s ON f.parent_id = s.id
|
||||
)
|
||||
SELECT id FROM subtree`,
|
||||
[rootId],
|
||||
);
|
||||
return rows.map((row) => row.id);
|
||||
};
|
||||
|
||||
const restoreAncestors = async (db: Db, folderId: string | null): Promise<void> => {
|
||||
let current = folderId;
|
||||
const guard = new Set<string>();
|
||||
while (current !== null && !guard.has(current)) {
|
||||
guard.add(current);
|
||||
const parent = await db.one<{ parent_id: string | null }>(
|
||||
"SELECT parent_id FROM folders WHERE id = ?",
|
||||
[current],
|
||||
);
|
||||
if (!parent) break;
|
||||
await db.exec("UPDATE folders SET deleted_at = NULL WHERE id = ?", [current]);
|
||||
current = parent.parent_id;
|
||||
}
|
||||
};
|
||||
|
||||
const purgeFiles = async (db: Db, config: Config, fileIds: string[]): Promise<void> => {
|
||||
if (fileIds.length === 0) return;
|
||||
const placeholders = fileIds.map(() => "?").join(",");
|
||||
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
relative_path: string;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
storage_location_id: number;
|
||||
}>(
|
||||
`SELECT id, relative_path, size_bytes, owner_id, storage_location_id
|
||||
FROM files WHERE id IN (${placeholders})`,
|
||||
fileIds,
|
||||
);
|
||||
|
||||
const variants = await db.query<{ path: string }>(
|
||||
`SELECT path FROM file_variants WHERE file_id IN (${placeholders})`,
|
||||
fileIds,
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
...rows.map((row) => discard(absolutePath(config.MEDIA_DIR, row.relative_path))),
|
||||
...variants.map((variant) => discard(absolutePath(config.VARIANT_DIR, variant.path))),
|
||||
]);
|
||||
|
||||
await db.transaction(async (connection) => {
|
||||
for (const row of rows) {
|
||||
if (row.owner_id) {
|
||||
await connection.execute(
|
||||
"UPDATE users SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
|
||||
[row.size_bytes, row.owner_id],
|
||||
);
|
||||
}
|
||||
await connection.execute(
|
||||
"UPDATE storage_locations SET used_bytes = GREATEST(0, CAST(used_bytes AS SIGNED) - ?) WHERE id = ?",
|
||||
[row.size_bytes, row.storage_location_id],
|
||||
);
|
||||
}
|
||||
await connection.execute(`DELETE FROM files WHERE id IN (${placeholders})`, fileIds);
|
||||
});
|
||||
};
|
||||
|
||||
const purgeFolderTree = async (db: Db, config: Config, rootId: string): Promise<void> => {
|
||||
const folderIds = await subtreeIds(db, rootId);
|
||||
const folderPlaceholders = folderIds.map(() => "?").join(",");
|
||||
const files = await db.query<{ id: string }>(
|
||||
`SELECT id FROM files WHERE folder_id IN (${folderPlaceholders})`,
|
||||
folderIds,
|
||||
);
|
||||
await purgeFiles(db, config, files.map((row) => row.id));
|
||||
await db.exec(`DELETE FROM folders WHERE id IN (${folderPlaceholders})`, folderIds);
|
||||
};
|
||||
|
||||
export const publicTrashFolder = (row: TrashFolderRow) => ({
|
||||
id: row.id,
|
||||
parent_id: row.parent_id,
|
||||
name: row.name,
|
||||
owner_id: row.owner_id,
|
||||
access_type: row.access_type,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
deleted_at: row.deleted_at,
|
||||
});
|
||||
|
||||
export const publicTrashFile = (row: TrashFileRow) => ({
|
||||
id: row.id,
|
||||
folder_id: row.folder_id,
|
||||
name: row.name,
|
||||
mime_type: row.mime_type,
|
||||
size_bytes: row.size_bytes,
|
||||
owner_id: row.owner_id,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
deleted_at: row.deleted_at,
|
||||
});
|
||||
|
||||
export interface TrashContent {
|
||||
retentionDays: number;
|
||||
folders: TrashFolderRow[];
|
||||
files: TrashFileRow[];
|
||||
}
|
||||
|
||||
/** Contenu de la corbeille de l'utilisateur. */
|
||||
export const listTrash = async (db: Db, user: SessionUser): Promise<TrashContent> => {
|
||||
const folders = await db.query<TrashFolderRow>(
|
||||
`SELECT f.id, f.parent_id, f.name, f.owner_id, f.access_type,
|
||||
f.created_at, f.updated_at, f.deleted_at
|
||||
FROM folders f
|
||||
LEFT JOIN folders p ON p.id = f.parent_id
|
||||
WHERE f.deleted_at IS NOT NULL
|
||||
AND f.is_system = 0
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND f.owner_id = ?
|
||||
ORDER BY f.deleted_at DESC`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
const files = await db.query<TrashFileRow>(
|
||||
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id,
|
||||
fi.created_at, fi.updated_at, fi.deleted_at
|
||||
FROM files fi
|
||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NOT NULL
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND fi.owner_id = ?
|
||||
ORDER BY fi.deleted_at DESC`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
const retentionDays = await db.one<{ setting_value: string }>(
|
||||
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
|
||||
);
|
||||
|
||||
return {
|
||||
retentionDays: retentionDays ? Number(retentionDays.setting_value) : 30,
|
||||
folders,
|
||||
files,
|
||||
};
|
||||
};
|
||||
|
||||
export const restoreFolder = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
): Promise<TrashFolderRow> => {
|
||||
const row = await db.one<TrashFolderRow>(
|
||||
`SELECT id, parent_id, name, owner_id, access_type, created_at, updated_at, deleted_at
|
||||
FROM folders
|
||||
WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0`,
|
||||
[id],
|
||||
);
|
||||
if (!row || row.owner_id !== user.id) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
await restoreAncestors(db, row.parent_id);
|
||||
const folderIds = await subtreeIds(db, id);
|
||||
const placeholders = folderIds.map(() => "?").join(",");
|
||||
try {
|
||||
await db.transaction(async (connection) => {
|
||||
await connection.execute(
|
||||
`UPDATE folders SET deleted_at = NULL WHERE id IN (${placeholders})`,
|
||||
folderIds,
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE files SET deleted_at = NULL WHERE folder_id IN (${placeholders})`,
|
||||
folderIds,
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un element du meme nom occupe deja cet emplacement.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return row;
|
||||
};
|
||||
|
||||
export const restoreFile = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
): Promise<TrashFileRow> => {
|
||||
const row = await db.one<TrashFileRow>(
|
||||
`SELECT id, folder_id, name, mime_type, size_bytes, owner_id, created_at, updated_at, deleted_at
|
||||
FROM files WHERE id = ? AND deleted_at IS NOT NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!row || row.owner_id !== user.id) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
await restoreAncestors(db, row.folder_id);
|
||||
try {
|
||||
await db.exec("UPDATE files SET deleted_at = NULL WHERE id = ?", [id]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un fichier du meme nom existe deja dans ce dossier.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return row;
|
||||
};
|
||||
|
||||
/** Suppression definitive d'un dossier corbeille et de son arborescence. */
|
||||
export const purgeFolder = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
): Promise<TrashFolderRow> => {
|
||||
const row = await db.one<TrashFolderRow>(
|
||||
`SELECT id, parent_id, name, owner_id, access_type, created_at, updated_at, deleted_at
|
||||
FROM folders
|
||||
WHERE id = ? AND deleted_at IS NOT NULL AND is_system = 0`,
|
||||
[id],
|
||||
);
|
||||
if (!row || row.owner_id !== user.id) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
await purgeFolderTree(db, config, id);
|
||||
return row;
|
||||
};
|
||||
|
||||
/** Suppression definitive d'un fichier corbeille. */
|
||||
export const purgeFile = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
): Promise<TrashFileRow> => {
|
||||
const row = await db.one<TrashFileRow>(
|
||||
`SELECT id, folder_id, name, mime_type, size_bytes, owner_id, created_at, updated_at, deleted_at
|
||||
FROM files WHERE id = ? AND deleted_at IS NOT NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!row || row.owner_id !== user.id) throw AppError.notFound("Fichier introuvable.");
|
||||
|
||||
await purgeFiles(db, config, [id]);
|
||||
return row;
|
||||
};
|
||||
|
||||
/** Vide la corbeille de l'utilisateur. */
|
||||
export const emptyTrash = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
): Promise<{ folders: number; files: number }> => {
|
||||
const folders = await db.query<{ id: string }>(
|
||||
`SELECT f.id FROM folders f
|
||||
LEFT JOIN folders p ON p.id = f.parent_id
|
||||
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND f.owner_id = ?`,
|
||||
[user.id],
|
||||
);
|
||||
const files = await db.query<{ id: string }>(
|
||||
`SELECT fi.id FROM files fi
|
||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NOT NULL
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND fi.owner_id = ?`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
|
||||
await purgeFiles(db, config, files.map((row) => row.id));
|
||||
|
||||
return { folders: folders.length, files: files.length };
|
||||
};
|
||||
|
||||
/** Purge automatique des elements expirant (retention configurable). */
|
||||
export const purgeExpiredTrash = async (db: Db, config: Config): Promise<number> => {
|
||||
const setting = await db.one<{ setting_value: string }>(
|
||||
"SELECT setting_value FROM settings WHERE setting_key = 'trash_retention_days'",
|
||||
);
|
||||
const days = setting ? Number(setting.setting_value) : 30;
|
||||
if (!Number.isFinite(days) || days <= 0) return 0;
|
||||
|
||||
const folders = await db.query<{ id: string }>(
|
||||
`SELECT f.id FROM folders f
|
||||
LEFT JOIN folders p ON p.id = f.parent_id
|
||||
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND f.deleted_at < UTC_TIMESTAMP() - INTERVAL ? DAY
|
||||
ORDER BY f.deleted_at`,
|
||||
[days],
|
||||
);
|
||||
const files = await db.query<{ id: string }>(
|
||||
`SELECT fi.id FROM files fi
|
||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||
WHERE fi.deleted_at IS NOT NULL
|
||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||
AND fi.deleted_at < UTC_TIMESTAMP() - INTERVAL ? DAY
|
||||
ORDER BY fi.deleted_at`,
|
||||
[days],
|
||||
);
|
||||
|
||||
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
|
||||
await purgeFiles(db, config, files.map((row) => row.id));
|
||||
return folders.length + files.length;
|
||||
};
|
||||
@@ -0,0 +1,376 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import type { FileRow, SessionUser } from "../models/types.js";
|
||||
import { AppError } from "../utils/errors.js";
|
||||
import { canWrite } from "./auditService.js";
|
||||
import { indexMedia } from "./mediaService.js";
|
||||
import { assertNameFree, SELECT_FILE } from "./fileService.js";
|
||||
import {
|
||||
absolutePath,
|
||||
chooseLocation,
|
||||
discard,
|
||||
diskUsage,
|
||||
ensureDir,
|
||||
fileExists,
|
||||
hashFile,
|
||||
listUploadTemps,
|
||||
preallocateUpload,
|
||||
publish,
|
||||
relativePathFor,
|
||||
uploadTempPath,
|
||||
writeChunk,
|
||||
} from "./storageService.js";
|
||||
|
||||
export const CHUNK_SIZE = 50 * 1024 * 1024;
|
||||
|
||||
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
interface UploadSessionRow {
|
||||
id: string;
|
||||
user_id: string;
|
||||
folder_id: string | null;
|
||||
storage_location_id: number;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number | string;
|
||||
received_bytes: number | string;
|
||||
chunk_size: number;
|
||||
relative_path: string;
|
||||
temp_path: string;
|
||||
expires_at: string | Date;
|
||||
}
|
||||
|
||||
const SELECT_SESSION = `SELECT id, user_id, folder_id, storage_location_id, name, mime_type,
|
||||
size_bytes, received_bytes, chunk_size, relative_path, temp_path, expires_at
|
||||
FROM upload_sessions`;
|
||||
|
||||
export const sessionPublic = (row: UploadSessionRow) => ({
|
||||
uploadId: row.id,
|
||||
name: row.name,
|
||||
folderId: row.folder_id,
|
||||
size: Number(row.size_bytes),
|
||||
chunkSize: row.chunk_size,
|
||||
uploadedBytes: Number(row.received_bytes),
|
||||
expiresAt: new Date(row.expires_at).toISOString(),
|
||||
});
|
||||
|
||||
export type UploadSession = ReturnType<typeof sessionPublic>;
|
||||
|
||||
const dropSession = async (db: Db, row: UploadSessionRow): Promise<void> => {
|
||||
await discard(row.temp_path);
|
||||
await db.exec("DELETE FROM upload_sessions WHERE id = ?", [row.id]).catch(() => undefined);
|
||||
};
|
||||
|
||||
const loadSession = async (
|
||||
db: Db,
|
||||
user: { id: string },
|
||||
id: string,
|
||||
): Promise<UploadSessionRow> => {
|
||||
const row = await db.one<UploadSessionRow>(`${SELECT_SESSION} WHERE id = ? AND user_id = ?`, [
|
||||
id,
|
||||
user.id,
|
||||
]);
|
||||
if (!row) throw AppError.notFound("Session d'envoi introuvable.");
|
||||
if (new Date(row.expires_at).getTime() <= Date.now()) {
|
||||
await dropSession(db, row);
|
||||
throw AppError.notFound("Session d'envoi expiree.");
|
||||
}
|
||||
return row;
|
||||
};
|
||||
|
||||
export interface CreateUploadInput {
|
||||
name: string;
|
||||
folderId: string | null;
|
||||
size: number;
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
/** Cree une session d'envoi morcele avec preallocation du fichier temporaire. */
|
||||
export const createUploadSession = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
input: CreateUploadInput,
|
||||
): Promise<UploadSession> => {
|
||||
const { name, folderId, size, mimeType } = input;
|
||||
|
||||
if (folderId !== null && !(await canWrite(db, user, folderId))) {
|
||||
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
|
||||
}
|
||||
|
||||
const budget = await db.one<{
|
||||
used_bytes: number | string;
|
||||
quota_bytes: number | string;
|
||||
max_file_bytes: number | string;
|
||||
}>(
|
||||
"SELECT used_bytes, quota_bytes, max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[user.id],
|
||||
);
|
||||
if (!budget) throw AppError.unauthorized();
|
||||
|
||||
const pending = await db.one<{ bytes: number | string | null }>(
|
||||
`SELECT COALESCE(SUM(size_bytes - received_bytes), 0) AS bytes
|
||||
FROM upload_sessions
|
||||
WHERE user_id = ? AND expires_at > UTC_TIMESTAMP()`,
|
||||
[user.id],
|
||||
);
|
||||
|
||||
if (BigInt(size) > BigInt(budget.max_file_bytes)) {
|
||||
throw AppError.payloadTooLarge(
|
||||
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
BigInt(budget.used_bytes) + BigInt(pending?.bytes ?? 0) + BigInt(size) >
|
||||
BigInt(budget.quota_bytes)
|
||||
) {
|
||||
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
|
||||
}
|
||||
|
||||
await assertNameFree(db, user, folderId, name);
|
||||
|
||||
const disk = await diskUsage(config.MEDIA_DIR);
|
||||
if (disk !== null && BigInt(size) > BigInt(disk.available_bytes)) {
|
||||
throw AppError.insufficientStorage(
|
||||
"Espace disque insuffisant sur le serveur pour ce fichier.",
|
||||
);
|
||||
}
|
||||
|
||||
const location = await chooseLocation(db, BigInt(size));
|
||||
const id = randomUUID();
|
||||
const relative = relativePathFor(location.slug, id, name);
|
||||
const temporary = uploadTempPath(config.MEDIA_DIR, id);
|
||||
|
||||
await preallocateUpload(temporary, size);
|
||||
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO upload_sessions
|
||||
(id, user_id, folder_id, storage_location_id, name, mime_type, size_bytes,
|
||||
received_bytes, chunk_size, relative_path, temp_path, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`,
|
||||
[
|
||||
id,
|
||||
user.id,
|
||||
folderId,
|
||||
location.id,
|
||||
name,
|
||||
mimeType,
|
||||
size,
|
||||
CHUNK_SIZE,
|
||||
relative,
|
||||
temporary,
|
||||
new Date(Date.now() + SESSION_TTL_MS),
|
||||
],
|
||||
);
|
||||
} catch (error) {
|
||||
await discard(temporary);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const created = await db.required<UploadSessionRow>(`${SELECT_SESSION} WHERE id = ?`, [id]);
|
||||
return sessionPublic(created);
|
||||
};
|
||||
|
||||
export const getUploadSession = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
): Promise<UploadSession> => {
|
||||
const row = await loadSession(db, user, id);
|
||||
return sessionPublic(row);
|
||||
};
|
||||
|
||||
/** Ecrit un morceau a l'offset attendu et met a jour la progression. */
|
||||
export const receiveChunk = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
body: ReadableStream<Uint8Array>,
|
||||
declared: number,
|
||||
): Promise<UploadSession> => {
|
||||
const row = await loadSession(db, user, id);
|
||||
const offset = Number(row.received_bytes);
|
||||
const size = Number(row.size_bytes);
|
||||
|
||||
if (declared > row.chunk_size) {
|
||||
throw AppError.payloadTooLarge(`Morceau trop volumineux (maximum ${row.chunk_size} octets).`);
|
||||
}
|
||||
if (offset + declared > size) {
|
||||
throw AppError.badRequest("Le morceau depasse la taille annoncee du fichier.");
|
||||
}
|
||||
|
||||
const written = await writeChunk(row.temp_path, offset, body, declared);
|
||||
if (written !== declared) {
|
||||
throw AppError.badRequest(
|
||||
`Longueur incoherente : ${declared} octets annonces, ${written} recus.`,
|
||||
);
|
||||
}
|
||||
|
||||
const reserved = await db.exec(
|
||||
`UPDATE upload_sessions
|
||||
SET received_bytes = received_bytes + ?
|
||||
WHERE id = ? AND user_id = ? AND received_bytes = ?
|
||||
AND received_bytes + ? <= size_bytes AND expires_at > UTC_TIMESTAMP()`,
|
||||
[declared, row.id, user.id, offset, declared],
|
||||
);
|
||||
|
||||
if (reserved.affectedRows === 0) {
|
||||
const fresh = await db.one<UploadSessionRow>(
|
||||
`${SELECT_SESSION} WHERE id = ? AND user_id = ?`,
|
||||
[row.id, user.id],
|
||||
);
|
||||
if (!fresh) throw AppError.notFound("Session d'envoi introuvable.");
|
||||
if (Number(fresh.received_bytes) < offset + declared) {
|
||||
throw AppError.conflict("Morceau deja recu ou session modifiee. Reprenez depuis le statut.");
|
||||
}
|
||||
return sessionPublic(fresh);
|
||||
}
|
||||
|
||||
return sessionPublic({ ...row, received_bytes: offset + declared });
|
||||
};
|
||||
|
||||
/** Finalise l'envoi : controle, publication et enregistrement du fichier. */
|
||||
export const completeUpload = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
): Promise<FileRow> => {
|
||||
const row = await loadSession(db, user, id);
|
||||
const size = Number(row.size_bytes);
|
||||
const received = Number(row.received_bytes);
|
||||
|
||||
if (received !== size) {
|
||||
throw AppError.badRequest("Envoi incomplet : des morceaux sont encore manquants.");
|
||||
}
|
||||
if (!(await fileExists(row.temp_path))) {
|
||||
await dropSession(db, row);
|
||||
throw AppError.notFound("Fichier temporaire introuvable. Relancez l'envoi.");
|
||||
}
|
||||
|
||||
const budget = await db.one<{ max_file_bytes: number | string }>(
|
||||
"SELECT max_file_bytes FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[user.id],
|
||||
);
|
||||
if (!budget) {
|
||||
await dropSession(db, row);
|
||||
throw AppError.unauthorized();
|
||||
}
|
||||
if (BigInt(size) > BigInt(budget.max_file_bytes)) {
|
||||
await dropSession(db, row);
|
||||
throw AppError.payloadTooLarge(
|
||||
`Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`,
|
||||
);
|
||||
}
|
||||
|
||||
if (row.folder_id !== null && !(await canWrite(db, user, row.folder_id))) {
|
||||
await dropSession(db, row);
|
||||
throw AppError.forbidden("Vous ne pouvez plus ecrire dans ce dossier.");
|
||||
}
|
||||
|
||||
try {
|
||||
await assertNameFree(db, user, row.folder_id, row.name);
|
||||
} catch (error) {
|
||||
await dropSession(db, row);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const checksum = await hashFile(row.temp_path);
|
||||
const destination = absolutePath(config.MEDIA_DIR, row.relative_path);
|
||||
|
||||
await ensureDir(path.dirname(destination));
|
||||
|
||||
await publish(row.temp_path, destination);
|
||||
|
||||
try {
|
||||
await db.transaction(async (connection) => {
|
||||
const [quota] = await connection.execute(
|
||||
`UPDATE users SET used_bytes = used_bytes + ?
|
||||
WHERE id = ? AND used_bytes + ? <= quota_bytes`,
|
||||
[size, user.id, size],
|
||||
);
|
||||
if ((quota as { affectedRows: number }).affectedRows === 0) {
|
||||
throw AppError.payloadTooLarge("Votre quota de stockage est depasse.");
|
||||
}
|
||||
|
||||
const [support] = await connection.execute(
|
||||
`UPDATE storage_locations
|
||||
SET used_bytes = used_bytes + ?
|
||||
WHERE id = ? AND (quota_bytes IS NULL OR used_bytes + ? <= quota_bytes)`,
|
||||
[size, row.storage_location_id, size],
|
||||
);
|
||||
if ((support as { affectedRows: number }).affectedRows === 0) {
|
||||
throw AppError.payloadTooLarge("L'espace disponible sur le support est insuffisant.");
|
||||
}
|
||||
|
||||
await connection.execute(
|
||||
`INSERT INTO files
|
||||
(id, storage_location_id, folder_id, name, mime_type, size_bytes,
|
||||
checksum_sha256, relative_path, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
row.id,
|
||||
row.storage_location_id,
|
||||
row.folder_id,
|
||||
row.name,
|
||||
row.mime_type ?? "application/octet-stream",
|
||||
size,
|
||||
checksum,
|
||||
row.relative_path,
|
||||
user.id,
|
||||
user.id,
|
||||
],
|
||||
);
|
||||
|
||||
await connection.execute("DELETE FROM upload_sessions WHERE id = ?", [row.id]);
|
||||
});
|
||||
} catch (error) {
|
||||
await publish(destination, row.temp_path).catch(async () => {
|
||||
await discard(destination);
|
||||
await db.exec("DELETE FROM upload_sessions WHERE id = ?", [row.id]).catch(() => undefined);
|
||||
});
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce nom existe deja ici.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
await indexMedia(db, config, row.id, row.mime_type ?? "application/octet-stream", destination).catch(
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
return db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
|
||||
};
|
||||
|
||||
export const cancelUpload = async (
|
||||
db: Db,
|
||||
user: SessionUser,
|
||||
id: string,
|
||||
): Promise<UploadSessionRow> => {
|
||||
const row = await loadSession(db, user, id);
|
||||
await dropSession(db, row);
|
||||
return row;
|
||||
};
|
||||
|
||||
/** Purge les sessions d'envoi expirees et leurs fichiers temporaires. */
|
||||
export const purgeExpiredUploads = async (db: Db, config: Config): Promise<number> => {
|
||||
const expired = await db.query<UploadSessionRow>(
|
||||
`${SELECT_SESSION} WHERE expires_at <= UTC_TIMESTAMP()`,
|
||||
);
|
||||
for (const row of expired) await discard(row.temp_path);
|
||||
|
||||
const result = await db.exec("DELETE FROM upload_sessions WHERE expires_at <= UTC_TIMESTAMP()");
|
||||
|
||||
const cutoff = Date.now() - SESSION_TTL_MS;
|
||||
for (const temporary of await listUploadTemps(config.MEDIA_DIR)) {
|
||||
const info = await stat(temporary).catch(() => null);
|
||||
if (info !== null && info.mtimeMs < cutoff) await discard(temporary);
|
||||
}
|
||||
|
||||
return result.affectedRows;
|
||||
};
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
/**
|
||||
* 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;
|
||||
@@ -66,7 +60,6 @@ export const toSafeError = (error: unknown): SafeError => {
|
||||
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);
|
||||
@@ -1,9 +1,9 @@
|
||||
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 type { SessionUser } from "../models/types.js";
|
||||
import type { Config } from "../config/appConfig.js";
|
||||
import type { Db } from "../config/db.js";
|
||||
import { AppError, toSafeError } from "./errors.js";
|
||||
|
||||
export interface Logger {
|
||||
@@ -45,23 +45,16 @@ export const createLogger = (level: Config["LOG_LEVEL"], service: string): Logge
|
||||
};
|
||||
};
|
||||
|
||||
/** 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");
|
||||
@@ -75,7 +68,50 @@ export const clientIp = (context: Context, trustProxy: boolean): string | null =
|
||||
return address ? address.slice(0, 45) : null;
|
||||
};
|
||||
|
||||
/** Dependances remises aux routes metier au montage. */
|
||||
export const JSON_BODY_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
export const readBodyCapped = async (context: Context, maxBytes: number): Promise<Buffer> => {
|
||||
const declared = Number(context.req.header("content-length") ?? "");
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw AppError.payloadTooLarge("Corps de requete trop volumineux.");
|
||||
}
|
||||
|
||||
const body = context.req.raw.body;
|
||||
if (body === null) return Buffer.alloc(0);
|
||||
|
||||
const chunks: Uint8Array[] = [];
|
||||
let received = 0;
|
||||
const reader = body.getReader();
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
received += value.byteLength;
|
||||
if (received > maxBytes) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
throw AppError.payloadTooLarge("Corps de requete trop volumineux.");
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
};
|
||||
|
||||
export const readJson = async (
|
||||
context: Context,
|
||||
maxBytes = JSON_BODY_MAX_BYTES,
|
||||
): Promise<unknown> => {
|
||||
const buffer = await readBodyCapped(context, maxBytes);
|
||||
if (buffer.byteLength === 0) return null;
|
||||
try {
|
||||
return JSON.parse(buffer.toString("utf8")) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export interface RouteDeps {
|
||||
db: Db;
|
||||
config: Config;
|
||||
@@ -87,9 +123,7 @@ export interface AppOptions {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,19 +1,7 @@
|
||||
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.
|
||||
*/
|
||||
import type { Db } from "../config/db.js";
|
||||
|
||||
export interface MigrationFile {
|
||||
version: string;
|
||||
@@ -25,12 +13,9 @@ export interface MigrationFile {
|
||||
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[]> => {
|
||||
@@ -58,8 +43,6 @@ const ensureLedger = async (db: Db): Promise<void> => {
|
||||
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",
|
||||
);
|
||||
@@ -101,13 +84,6 @@ export const runMigrations = async (
|
||||
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) =>
|
||||
@@ -1,23 +1,9 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
@@ -33,8 +19,6 @@ export const createRateLimiter = (max: number, windowMs: number): RateLimiter =>
|
||||
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) {
|
||||
@@ -48,5 +32,4 @@ export const createRateLimiter = (max: number, windowMs: number): RateLimiter =>
|
||||
};
|
||||
};
|
||||
|
||||
/** Identifiant de limitation : IP reelle si le proxy est de confiance, sinon socket. */
|
||||
export const rateLimitKey = (ip: string | null): string => ip ?? "unknown";
|
||||
@@ -1,9 +1,9 @@
|
||||
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 { ConfigError, loadConfig, type Config } from "../config/appConfig.js";
|
||||
import { AppError } from "./errors.js";
|
||||
import { Db } from "./db.js";
|
||||
import { Db } from "../config/db.js";
|
||||
import {
|
||||
createLogger,
|
||||
createApp,
|
||||
@@ -16,14 +16,9 @@ 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;
|
||||
}
|
||||
|
||||
@@ -52,10 +47,6 @@ const fail = (error: unknown): never => {
|
||||
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);
|
||||
@@ -78,8 +69,6 @@ export const prepareService = async (options: ServiceOptions): Promise<Service>
|
||||
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),
|
||||
});
|
||||
@@ -98,7 +87,6 @@ export const prepareService = async (options: ServiceOptions): Promise<Service>
|
||||
return { config, db, logger, app };
|
||||
};
|
||||
|
||||
/** Demarre, ecoute, et s'arrete proprement. */
|
||||
export const startService = async (options: ServiceOptions): Promise<Server> => {
|
||||
let prepared: Service;
|
||||
try {
|
||||
@@ -115,8 +103,6 @@ export const startService = async (options: ServiceOptions): Promise<Server> =>
|
||||
|
||||
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");
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from "zod";
|
||||
import { AppError } from "./errors.js";
|
||||
|
||||
/** Identifiant UUID canonique (fichiers, dossiers, sessions...). */
|
||||
export 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.",
|
||||
);
|
||||
|
||||
/** Valide un corps JSON avec zod et leve une erreur 400 explicite. */
|
||||
export 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;
|
||||
};
|
||||
|
||||
/** Valide et nettoie un nom de fichier ou de dossier. */
|
||||
export const assertName = (
|
||||
raw: string | undefined,
|
||||
what: "fichier" | "dossier",
|
||||
): string => {
|
||||
const name = (raw ?? "").trim();
|
||||
if (!name || name.length > 255) {
|
||||
throw AppError.badRequest(
|
||||
`Le nom du ${what} doit contenir entre 1 et 255 caracteres.`,
|
||||
);
|
||||
}
|
||||
if (name === "." || name === ".." || /[/\\\0-\x1f]/.test(name)) {
|
||||
throw AppError.badRequest(`Le nom du ${what} ne peut pas contenir de separateur.`);
|
||||
}
|
||||
return name;
|
||||
};
|
||||
|
||||
const MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,127}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,127}$/;
|
||||
|
||||
/** Normalise un en-tete Content-Type, avec repli sur application/octet-stream. */
|
||||
export const mimeOf = (header: string | undefined): string => {
|
||||
const value = (header ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
|
||||
return MIME.test(value) ? value : "application/octet-stream";
|
||||
};
|
||||
@@ -24,9 +24,6 @@ x-app: &app
|
||||
x-migrate-build: &migrate-build
|
||||
context: .
|
||||
dockerfile: docker/Dockerfile.api
|
||||
# Le build utilise le reseau de l'hote : le demon Docker resout parfois un
|
||||
# DNS mort (routeur), ce qui casse `npm ci` dans le conteneur.
|
||||
network: host
|
||||
args:
|
||||
APP_DIR: backend
|
||||
|
||||
@@ -37,7 +34,6 @@ services:
|
||||
context: .
|
||||
dockerfile: docker/Dockerfile.app
|
||||
target: export
|
||||
network: host
|
||||
args:
|
||||
APP_DIR: frontend
|
||||
volumes:
|
||||
@@ -117,7 +113,6 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/Dockerfile.api
|
||||
network: host
|
||||
args:
|
||||
APP_DIR: backend
|
||||
image: cohaise-cloud-api
|
||||
|
||||
@@ -63,6 +63,8 @@ server {
|
||||
}
|
||||
|
||||
location @spa {
|
||||
include /etc/nginx/snippets/security-headers.conf;
|
||||
include /etc/nginx/snippets/cache-no-cache.conf;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@ proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
|
||||
proxy_read_timeout 60s;
|
||||
proxy_read_timeout 120s;
|
||||
proxy_send_timeout 120s;
|
||||
# La finalisation d'un gros envoi resumable lit et hache le fichier complet
|
||||
# avant de repondre : 120 s laisse la marge necessaire, sans depasser la
|
||||
# limite de reponse de Cloudflare (~100 s).
|
||||
# Aligne sur la borne de depot du Cloud.
|
||||
client_max_body_size 5g;
|
||||
|
||||
@@ -32,8 +32,8 @@ CI). L'exécuter avant de déclarer un travail fini.
|
||||
seulement. Le checksum bloquerait le démarrage.
|
||||
5. **API admin** : les routes `/api/cloud/admin/*` existent (UI Administration).
|
||||
La CLI (`make admin`) reste pour l'amorçage et les cas hors ligne.
|
||||
6. **Chemin disque** : toujours via `storage.ts` (`resolveInside`), jamais par
|
||||
concaténation depuis une entrée utilisateur.
|
||||
6. **Chemin disque** : toujours via `services/storageService.ts` (`resolveInside`),
|
||||
jamais par concaténation depuis une entrée utilisateur.
|
||||
7. **404 plutôt que 403** sur une ressource non accessible : ne pas introduire
|
||||
d'énumération.
|
||||
8. **CSP stricte** : pas de script en ligne dans `index.html` (utiliser un
|
||||
@@ -42,13 +42,17 @@ CI). L'exécuter avant de déclarer un travail fini.
|
||||
## Conventions
|
||||
|
||||
- TypeScript strict, project references racine.
|
||||
- Back : `routes/*Routes.ts` (HTTP fin) appellent `services/*Service.ts`
|
||||
(métier) ; le socle vit dans `config/`, `middleware/`, `utils/`, les types
|
||||
partagés dans `models/types.ts`.
|
||||
- Hono + Zod : toute route avec corps passe par un schéma Zod dédié.
|
||||
- Erreurs : `AppError` + codes (`errors.ts`) — jamais `throw` brut, jamais de
|
||||
détail de schéma dans une 500.
|
||||
- Erreurs : `AppError` + codes (`utils/errors.ts`) — jamais `throw` brut, jamais
|
||||
de détail de schéma dans une 500.
|
||||
- SQL : requêtes préparées uniquement, pas de `raw()` hors DDL.
|
||||
- Front : un seul client HTTP (`frontend/src/lib/api.ts`),
|
||||
`credentials: "same-origin"`. React Router 7 (`App.tsx`) + `AppShell`, contexte
|
||||
de session dans `lib/session.tsx`.
|
||||
- Front : un client HTTP (`frontend/src/services/apiClient.ts`), puis un service
|
||||
par domaine (`services/*Service.ts`), `credentials: "same-origin"`. React
|
||||
Router 7 (`App.tsx`) + `AppShell`, contexte de session dans
|
||||
`contexts/SessionContext.tsx`.
|
||||
- `.editorconfig` : 2 espaces, LF, UTF-8.
|
||||
|
||||
## Design system
|
||||
@@ -68,8 +72,10 @@ Le design system vit dans `frontend/src/ui`.
|
||||
|
||||
- **`.env` ≠ `.env.example`** : comparer avant de conclure à un bug de port.
|
||||
- **README de paquet périmés** — utiliser ce dossier `docs/`.
|
||||
- **Build Docker et DNS** : les `build:` passent par `network: host` ; si `npm ci`
|
||||
échoue par `EAI_AGAIN`, le résolveur du démon est en cause.
|
||||
- **Build Docker et DNS** : les `build:` utilisent le réseau Docker par défaut.
|
||||
`network: host` est évité : Compose 5.6 / Buildx 0.38 refuse alors le build
|
||||
(`additional privileges requested`), sans transmettre `--allow=network.host`.
|
||||
Si `npm ci` échoue par `EAI_AGAIN`, corriger le DNS du démon Docker.
|
||||
- **Limitation de débit active** (applicatif + nginx) : un test en rafale peut
|
||||
recevoir `419`/`503` côté API ou `503` nginx — ce n'est pas un bug.
|
||||
- Après `make up`, vérifier l'ordre : `migrate` doit être `exited (0)` avant que
|
||||
|
||||
@@ -54,6 +54,27 @@ d'adresse).
|
||||
| PUT | `/api/cloud/files/:id/star` | `requireAuth` |
|
||||
| DELETE | `/api/cloud/files/:id` | `requireAuth` + écriture (corbeille) |
|
||||
|
||||
### Envoi resumable (gros fichiers)
|
||||
|
||||
Au-delà de la limite de corps de requête de Cloudflare (100 MB en Free/Pro), le
|
||||
client découpe le fichier en morceaux de 50 MiB. Une session est créée en base,
|
||||
le temporaire est préalloué sous `MEDIA_DIR/.uploads`, puis les morceaux sont
|
||||
écrits à l'offset courant. La finalisation vérifie le nom et les droits une
|
||||
dernière fois, calcule le SHA-256, publie le fichier et met à jour les quotas.
|
||||
|
||||
| Méthode | Chemin | Garde |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/cloud/uploads` | `requireAuth` (nom, `folderId`, `size`, `mimeType`) |
|
||||
| GET | `/api/cloud/uploads/:id` | `requireAuth` (propriétaire de la session, donne l'offset de reprise) |
|
||||
| PUT | `/api/cloud/uploads/:id/chunks` | `requireAuth` (corps brut, `Content-Length` obligatoire) |
|
||||
| POST | `/api/cloud/uploads/:id/complete` | `requireAuth` (vérifie taille, nom, droits, quotas) |
|
||||
| DELETE | `/api/cloud/uploads/:id` | `requireAuth` (annule et supprime le temporaire) |
|
||||
|
||||
Les sessions expirent après 24 h ; une purge au démarrage puis toutes les
|
||||
heures supprime les temporaires orphelins. Un morceau interrompu ne fait pas
|
||||
avancer le curseur : le client interroge `GET /uploads/:id` puis reprend à
|
||||
l'offset exact.
|
||||
|
||||
### Corbeille, recherche, galerie
|
||||
|
||||
| Méthode | Chemin | Garde |
|
||||
@@ -70,7 +91,7 @@ d'adresse).
|
||||
### Discussion (chat d'un dossier et membres)
|
||||
|
||||
Chaque dossier possède son propre salon. Le droit d'accès au dossier fait loi :
|
||||
lecture comme écriture passent par `canRead` (`backend/src/access.ts`), donc le
|
||||
lecture comme écriture passent par `canRead` (`backend/src/services/auditService.ts`), donc le
|
||||
salon d'un dossier `public` est ouvert à tout compte authentifié. La lecture est
|
||||
en texte brut, React échappe le rendu. La synchronisation est incrémentale par
|
||||
identifiant (`after`), sans WebSocket.
|
||||
@@ -78,8 +99,11 @@ identifiant (`after`), sans WebSocket.
|
||||
| Méthode | Chemin | Garde |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/cloud/folders/:folderId/chat/members` | `requireAuth` + `canRead` |
|
||||
| GET | `/api/cloud/folders/:folderId/chat/messages?after=&limit=` | `requireAuth` + `canRead` |
|
||||
| GET | `/api/cloud/folders/:folderId/chat/messages?after=&limit=&editedAfter=` | `requireAuth` + `canRead` |
|
||||
| POST | `/api/cloud/folders/:folderId/chat/messages` | `requireAuth` + `canRead` (limiteur 20 / 10 s par compte) |
|
||||
| PATCH | `/api/cloud/folders/:folderId/chat/messages/:id` | `requireAuth` + `canRead` + **auteur du message** (limiteur 20 / 10 s par compte) |
|
||||
| PUT | `/api/cloud/folders/:folderId/chat/messages/:id/pin` | `requireAuth` + `canRead` (limiteur 20 / 10 s par compte) |
|
||||
| GET | `/api/cloud/folders/:folderId/chat/pins` | `requireAuth` + `canRead` |
|
||||
| DELETE | `/api/cloud/folders/:folderId/chat/messages/:id` | `requireAuth` + `canRead` (auteur ou gestionnaire du dossier, soft-delete) |
|
||||
|
||||
`GET .../chat/members` renvoie les membres du salon, c'est-à-dire les comptes qui
|
||||
@@ -87,6 +111,35 @@ ont accès au dossier : propriétaire, titulaires d'une permission nominative no
|
||||
expirée, rôle global `admin`, et tous les comptes actifs si le dossier est
|
||||
`public` (prénom, nom, rôle, présence d'avatar, `last_login_at`).
|
||||
|
||||
**Édition.** `PATCH .../chat/messages/:id` réécrit le corps du message et pose
|
||||
`edited_at`. Seul l'auteur peut le faire, sans limite de temps : le filtre
|
||||
`user_id` est porté par la requête SQL, donc un message d'autrui renvoie le
|
||||
même `404` qu'un message inexistant. Le gestionnaire du dossier peut supprimer
|
||||
un message, mais pas le réécrire à la place de son auteur.
|
||||
|
||||
**Épinglage.** `PUT .../chat/messages/:id/pin` bascule `is_pinned` en base
|
||||
(bascule atomique, safe face à deux clics croisés). Plusieurs messages peuvent
|
||||
être épinglés en même temps dans un même salon. Tout membre du salon peut
|
||||
épingler et désépingler, y compris un message qu'il n'a pas écrit. La lecture
|
||||
dédiée `GET .../chat/pins` est nécessaire parce que le curseur `after` ne
|
||||
remonte que les messages plus récents : un épinglage posé sur un ancien
|
||||
message resterait invisible sans elle.
|
||||
|
||||
**Synchronisation.** `GET .../chat/messages` accepte deux curseurs : `after`
|
||||
(identifiant, messages plus récents) et `editedAfter` (horodatage, messages
|
||||
réécrits depuis). Le second rattrape les réécritures d'anciens messages, que le
|
||||
premier ne peut pas voir. `edited_at` est null pour un message jamais modifié.
|
||||
|
||||
Le curseur d'édition est un horodatage de la base au format
|
||||
`AAAA-MM-JJTHH:MM:SS.ffffff`, et non un horodatage ISO : il est renvoyé tel quel
|
||||
par la réponse (`cursor`) et doit être renvoyé tel quel par le client. Comparer
|
||||
une chaîne ISO (UTC) à un `DATETIME` stocké en heure locale décalerait la
|
||||
fenêtre de la différence de fuseau. Le serveur calcule son curseur **avant** la
|
||||
requête de lecture : une réécriture survenue entre les deux porte un
|
||||
horodatage postérieur au curseur, elle sera donc vue au tour suivant plutôt que
|
||||
perdue. Une valeur qui ne respecte pas le format est ignorée, le serveur
|
||||
utilise alors le sien.
|
||||
|
||||
### Administration (`role_slug = admin`)
|
||||
|
||||
| Méthode | Chemin |
|
||||
@@ -105,7 +158,7 @@ expirée, rôle global `admin`, et tous les comptes actifs si le dossier est
|
||||
## Droits d'accès
|
||||
|
||||
Calculés **en base à chaque requête**, depuis la session — jamais depuis un
|
||||
en-tête (`backend/src/access.ts`).
|
||||
en-tête (`backend/src/services/auditService.ts`).
|
||||
|
||||
| Concept | Règle |
|
||||
| --- | --- |
|
||||
@@ -125,6 +178,8 @@ par tous les membres authentifiés, en écriture pour son propriétaire.
|
||||
| Contrôle | Détail |
|
||||
| --- | --- |
|
||||
| Corps | `PUT /files` en flux brut (pas de multipart), `?name=` et `?folderId=` |
|
||||
| Gros fichiers | au-delà de 90 MiB, le front bascule sur `/uploads` (morceaux de 50 MiB) pour rester sous la limite Cloudflare |
|
||||
| Reprise | l'ID de session est conservé localement ; un envoi interrompu repart de `uploadedBytes` |
|
||||
| Taille | plafond `users.max_file_bytes`, vérifié en flux (coupure si dépassement) |
|
||||
| Quota | `users.used_bytes` + quota `storage_locations`, revérifiés avant écriture |
|
||||
| Disque | `diskUsage()` (`statfs`) avant écriture ; `507` `INSUFFICIENT_STORAGE` si le support est plein |
|
||||
@@ -135,9 +190,9 @@ par tous les membres authentifiés, en écriture pour son propriétaire.
|
||||
|
||||
## Courriels
|
||||
|
||||
Les messages sortants sont construits par `backend/src/lib/mail-template.ts` :
|
||||
gabarit HTML aux couleurs de l'app (`#b71c1c`), logo, bouton d'action et mention
|
||||
**ne pas répondre**. Un repli texte accompagne chaque envoi.
|
||||
Les messages sortants sont construits par `backend/src/services/mailService.ts`
|
||||
(gabarit HTML aux couleurs de l'app (`#b71c1c`), logo, bouton d'action et mention
|
||||
**ne pas répondre**). Un repli texte accompagne chaque envoi.
|
||||
|
||||
Le logo `backend/src/assets/logo.png` est **embarqué** dans le message (pièce
|
||||
jointe `cid`), donc visible même quand le client bloque les images distantes.
|
||||
@@ -163,14 +218,18 @@ par fichier, dérive refusée au démarrage.
|
||||
| `005_storage_location_realign.sql` | réalignement des emplacements |
|
||||
| `006_public_folder.sql` | `folders.access_type` / `is_system`, dossier `Public` |
|
||||
| `007_chat.sql` | `chat_messages` (salon global, auteur `ON DELETE SET NULL`) |
|
||||
| `008_user_preferences.sql` | préférences d'affichage, `user_file_stars`, `chat_reads` |
|
||||
| `009_chat_edits_and_pins.sql` | `chat_messages.edited_at`, `chat_messages.is_pinned`, index `idx_chat_messages_pinned`, `idx_chat_messages_edited` |
|
||||
| `010_upload_sessions.sql` | `upload_sessions` (envoi resumable, temporaire préalloué, expiration) |
|
||||
|
||||
Tables actives : `users, user_sessions, folders, folder_permissions, files,
|
||||
media_metadata, file_variants, user_avatars, chat_messages, storage_locations,
|
||||
settings, password_reset_tokens, email_change_requests, audit_logs`.
|
||||
media_metadata, file_variants, user_avatars, chat_messages, upload_sessions,
|
||||
storage_locations, settings, password_reset_tokens, email_change_requests,
|
||||
audit_logs, user_file_stars, chat_reads`.
|
||||
|
||||
## Erreurs métier
|
||||
|
||||
`AppError` avec codes stables (`backend/src/lib/errors.ts`). Correspondances
|
||||
`AppError` avec codes stables (`backend/src/utils/errors.ts`). Correspondances
|
||||
MariaDB : `1062` → 409, `1146` → 503 `NOT_MIGRATED`, `1406` → 422. Le corps d'une
|
||||
500 ne contient jamais de détail de schéma. Réponse normalisée :
|
||||
|
||||
|
||||
@@ -9,27 +9,36 @@ Node/TypeScript, une base MariaDB, un stockage de fichiers monté en volume.
|
||||
| Élément | Où |
|
||||
| --- | --- |
|
||||
| React 19 + Vite 8 + Tailwind 4 + react-router-dom 7 | `frontend` |
|
||||
| Hono | `backend/src/index.ts` (`src/lib` pour le socle) |
|
||||
| MariaDB (`mysql2`) | `backend/src/lib/db.ts` |
|
||||
| Nodemailer | `backend/src/lib/mail.ts` |
|
||||
| sharp (vignettes) | `backend/src/media.ts` |
|
||||
| Validation Zod | `backend/src/lib/config.ts` et chaque route |
|
||||
| Hono | `backend/src/index.ts` (`src/utils` pour le socle HTTP) |
|
||||
| MariaDB (`mysql2`) | `backend/src/config/db.ts` |
|
||||
| Nodemailer | `backend/src/services/mailService.ts` |
|
||||
| sharp (vignettes) | `backend/src/services/mediaService.ts` |
|
||||
| Validation Zod | `backend/src/config/appConfig.ts`, `src/utils/validators.ts` et chaque route |
|
||||
|
||||
## Découpage
|
||||
|
||||
```
|
||||
backend/src/lib/ socle serveur : config, db, mail, mail-template, ratelimit, http, service, auth, errors
|
||||
backend/src/ routes/, access.ts, storage.ts, media.ts, admin.ts
|
||||
backend/migrations/ 000 … 006
|
||||
frontend/src/ui/ design system (boutons, cartes, champs, spinner)
|
||||
frontend/src/ router + AppShell + pages/
|
||||
docker/ Dockerfile(.app/.api), nginx/, publish.sh
|
||||
backend/src/config/ configuration et connexion base (appConfig, db)
|
||||
backend/src/middleware/ gardes HTTP (auth : session, rôles)
|
||||
backend/src/models/ types partages (types.ts)
|
||||
backend/src/routes/ routeurs HTTP fins, un par domaine (*Routes.ts)
|
||||
backend/src/services/ logique metier, un fichier par domaine (*Service.ts)
|
||||
backend/src/utils/ socle technique : errors, http, ratelimit, validators, migrate, service
|
||||
backend/src/ index.ts (bootstrap), cli.ts, admin.ts
|
||||
backend/migrations/ 000 … 010
|
||||
frontend/src/services/ clients API par domaine (*Service.ts + apiClient.ts)
|
||||
frontend/src/contexts/ SessionContext, ThemeContext, I18nContext
|
||||
frontend/src/types/ types partages du front
|
||||
frontend/src/utils/ formatage (format.ts)
|
||||
frontend/src/ui/ design system (boutons, cartes, champs, spinner)
|
||||
frontend/src/ router + AppShell + pages/
|
||||
docker/ Dockerfile(.app/.api), nginx/, publish.sh
|
||||
```
|
||||
|
||||
`backend/src/lib` porte la mécanique générique (sessions, erreurs,
|
||||
migrations, courriel, limitation de débit), le reste de `backend` porte le
|
||||
métier : droits, quotas, chemins disque, traitement média. Tout vit dans un seul
|
||||
paquet, sans dépendance de workspace.
|
||||
`backend/src/utils` porte la mécanique générique (erreurs, HTTP, migrations,
|
||||
limitation de débit, validation), `backend/src/services` porte le métier :
|
||||
sessions, droits, quotas, chemins disque, traitement média, courriel.
|
||||
Tout vit dans un seul paquet, sans dépendance de workspace.
|
||||
|
||||
## Chaîne de démarrage
|
||||
|
||||
@@ -44,7 +53,8 @@ app-build (publish.sh, terminé avant nginx)
|
||||
|
||||
- `migrate` monte `./backend/migrations:/migrations:ro`.
|
||||
- `api` refuse de démarrer si une migration appliquée a été modifiée (dérive de
|
||||
checksum). `onReady` purge les sessions et la corbeille expirées.
|
||||
checksum). `onReady` purge les sessions, la corbeille et les envois inachevés,
|
||||
puis un balayage horaire reprend ces purges sans redémarrage.
|
||||
- stockage : `app_data` (volume Docker, HTML), `$CLOUD_DB_DIR` (MariaDB) et
|
||||
`$CLOUD_MEDIA_DIR` (fichiers) en bind mounts hôte.
|
||||
|
||||
@@ -57,8 +67,9 @@ app-build (publish.sh, terminé avant nginx)
|
||||
- Pages : `Login`, `ForgotPassword`, `ResetPassword`, `ConfirmEmail`,
|
||||
`ChangePassword`, `Browser`, `Search`, `Gallery`, `Trash`, `Profile`,
|
||||
`Admin` (comptes / stockage / journal).
|
||||
- Client HTTP unique `lib/api.ts` (base `/api/cloud`, `same-origin`) ; contexte
|
||||
de session `lib/session.tsx` ; dialogues réutilisables dans
|
||||
- Client HTTP unique `services/apiClient.ts` (base `/api/cloud`, `same-origin`) ;
|
||||
services par domaine dans `services/*Service.ts` ; contexte de session
|
||||
`contexts/SessionContext.tsx` ; dialogues réutilisables dans
|
||||
`components/dialogs.tsx`.
|
||||
- En-têtes nginx : CSP stricte, HSTS, `nosniff`, `Referrer-Policy`,
|
||||
`Permissions-Policy` (`docker/nginx/snippets/`). `X-Frame-Options` est
|
||||
@@ -77,9 +88,9 @@ app-build (publish.sh, terminé avant nginx)
|
||||
## Stockage et médias
|
||||
|
||||
- `MEDIA_DIR=/data/media/originals`, `VARIANT_DIR=/data/media/variants`.
|
||||
- Chemin physique `${MEDIA_DIR}/<slug>/<uuid><ext>` (`storage.ts`), nom affiché
|
||||
jamais dans le chemin.
|
||||
- `media.ts` : classification (`image/video/audio/document/archive/other`),
|
||||
- Chemin physique `${MEDIA_DIR}/<slug>/<uuid><ext>` (`storageService.ts`), nom
|
||||
affiché jamais dans le chemin.
|
||||
- `mediaService.ts` : classification (`image/video/audio/document/archive/other`),
|
||||
vignette (`sharp`, seuil 480 px) écrite dans `VARIANT_DIR`, métadonnées dans
|
||||
`media_metadata` / `file_variants`. Indexation **best-effort** après upload.
|
||||
- Avatars dans `user_avatars`.
|
||||
|
||||
@@ -12,7 +12,7 @@ Réponse sur **`http://localhost:8083`**.
|
||||
|
||||
La configuration est validée **avant** l'ouverture d'aucun port : si une variable
|
||||
manque ou est mal formée, le process s'arrête en listant exactement ce qui
|
||||
pose problème (`backend/src/lib/config.ts`).
|
||||
pose problème (`backend/src/config/appConfig.ts`).
|
||||
|
||||
## Variables
|
||||
|
||||
@@ -26,7 +26,7 @@ pose problème (`backend/src/lib/config.ts`).
|
||||
| `CLOUD_DB_DIR` | dossier hôte des données MariaDB | `../db` |
|
||||
| `CLOUD_MEDIA_DIR` | dossier hôte des médias | `../media` |
|
||||
| `CLOUD_DB_CONNECTION_LIMIT` | taille du pool | `8` |
|
||||
| `SESSION_SECRET` | **obligatoire**, ≥ 32 car. | — |
|
||||
| `SESSION_SECRET` | **obligatoire**, ≥ 32 car., poivre HMAC des jetons de session | — |
|
||||
| `SESSION_TTL_HOURS` | durée de session | `336` |
|
||||
| `PUBLIC_ORIGIN` | **obligatoire**, URL absolue servant aux liens courriel | — |
|
||||
| `CLOUD_CORS_ORIGIN` | origines CORS (vide = CORS off) | vide |
|
||||
@@ -177,6 +177,11 @@ adresse ni aucun domaine n'est codé en dur.
|
||||
de connexion globale, audit inutile).
|
||||
- Certificat et HSTS sont assurés en amont par Cloudflare — ne pas exposer
|
||||
directement le port 8083 sur Internet.
|
||||
- **Corps de requête** : Cloudflare plafonne le corps à 100 MB (Free/Pro). Les
|
||||
fichiers plus gros passent par l'envoi resumable (`/api/cloud/uploads`) en
|
||||
morceaux de 50 MiB, sans relever la limite de corps de nginx ni exposer
|
||||
l'origine. La valeur `client_max_body_size 5g` de nginx ne concerne que le
|
||||
chemin direct local.
|
||||
|
||||
**Tunnel Docker sur un réseau partagé (recommandé).** On joint nginx au réseau
|
||||
du tunnel plutôt que de publier un port : `cloudflared` résout `nginx` par nom,
|
||||
|
||||
@@ -7,34 +7,64 @@
|
||||
| Mesure | Détail |
|
||||
| --- | --- |
|
||||
| Mots de passe | `scrypt` natif `node:crypto` (`N=16384, r=8, p=1`, keylen 64, sel 16 o.), comparaison `timingSafeEqual` |
|
||||
| Stockage session | jeton aléatoire 32 o. côté client, **SHA-256** en base |
|
||||
| Stockage session | jeton aléatoire 32 o. côté client, **HMAC-SHA-256 poivré par `SESSION_SECRET`** en base |
|
||||
| Cookie | `cohaise_session`, `httpOnly`, `SameSite=Lax`, `path=/`, `secure` selon le schéma réel |
|
||||
| Expiration | `SESSION_TTL_HOURS` (336 h) ; `revoked_at`, `is_active`, `deleted_at` vérifiés à chaque résolution |
|
||||
| Révocation | logout, purge au démarrage, **toutes les autres sessions** au changement de mot de passe, gestion des sessions ouvertes depuis le compte |
|
||||
| Révocation | logout, purge au démarrage et **toutes les heures**, **toutes les autres sessions** au changement de mot de passe, gestion des sessions ouvertes depuis le compte |
|
||||
| Changement imposé | `must_change_password` vérifié dans `requireAuth` : seules `auth/me`, `auth/change-password` et `auth/logout` restent accessibles, la redirection du front n'est qu'un confort |
|
||||
| Anti-énumération | hash factice pour une adresse inconnue ; les flux « mot de passe oublié » répondent toujours `{ ok: true }` sans révéler l'existence du compte |
|
||||
| Jetons à usage unique | réinitialisation de mot de passe et changement d'adresse stockés **hachés**, avec expiration |
|
||||
| Changement d'adresse | mot de passe actuel exigé, confirmation **à la nouvelle adresse** avant application |
|
||||
|
||||
### Limitation de débit
|
||||
|
||||
- **Applicatif** : `createRateLimiter` (`backend/src/lib/ratelimit.ts`) par IP
|
||||
- **Applicatif** : `createRateLimiter` (`backend/src/utils/ratelimit.ts`) par IP
|
||||
sur `auth/login`, `account/forgot-password`, `account/reset-password`,
|
||||
`account/email-change`. Réglages `RATE_LIMIT_LOGIN_MAX` (10) et
|
||||
`RATE_LIMIT_LOGIN_WINDOW_MS` (60 s).
|
||||
- **Edge nginx** : zones `limit_req` `login` (15 r/min, burst 5) et `api`
|
||||
(60 r/s, burst élevé) — voir `docker/nginx/cloud.conf`.
|
||||
|
||||
### Limites d'entrée
|
||||
|
||||
- Les corps JSON passent par `readJson` : **1 Mio** maximum, lecture bornée
|
||||
même si `content-length` ment (le flux est coupé au-delà).
|
||||
- L'avatar passe par `readBodyCapped` : **8 Mio** maximum, même garantie.
|
||||
- Les envois de fichiers ont leur propre flux borné (`storage.ts`), indépendant
|
||||
de `client_max_body_size` de nginx.
|
||||
|
||||
### Droits d'accès
|
||||
|
||||
Calculés **en base à chaque requête**, depuis la session — jamais depuis un
|
||||
en-tête (`backend/src/access.ts`). Lecture : propriétaire, permission
|
||||
en-tête (`backend/src/services/auditService.ts`). Lecture : propriétaire, permission
|
||||
`folder_permissions` (`read`/`write`/`admin`), ou dossier `public`. Écriture :
|
||||
`write`/`admin`. **404 plutôt que 403** : jamais d'indice sur l'existence d'une
|
||||
ressource.
|
||||
|
||||
### Discussion
|
||||
|
||||
Le salon d'un dossier est ouvert à qui a accès au dossier (`canRead`). L'accès
|
||||
en lecture et l'envoi de messages se distinguent de l'**édition** :
|
||||
|
||||
- l'édition d'un message (`PATCH .../chat/messages/:id`) est réservée à son
|
||||
**auteur**, sans limite de temps. Le filtre `user_id` est porté par la
|
||||
requête SQL : un message d'autrui répond `404`, comme un message inexistant,
|
||||
sans rien laisser deviner. Le gestionnaire du dossier peut supprimer un
|
||||
message mais pas le réécrire à la place de son auteur ;
|
||||
- l'épinglage (`PUT .../chat/messages/:id/pin`) est ouvert à tout membre du
|
||||
salon : c'est une mise de côté de lecture, pas une prise de contrôle du
|
||||
contenu ;
|
||||
- la suppression est un soft-delete (`deleted_at`), un message retiré quitte
|
||||
aussi les épingles ;
|
||||
- `edited_at` est posé par le serveur, jamais reçu du client : un client ne
|
||||
peut pas dater sa propre modification.
|
||||
|
||||
Chaque écriture dans le salon passe par le limiteur de débit (20 requêtes
|
||||
d'écriture par compte sur 10 s), édition et épinglage compris.
|
||||
|
||||
### Courriel
|
||||
|
||||
Nodemailer (`backend/src/lib/mail.ts`) avec `SMTP_HOST`. `PUBLIC_ORIGIN`
|
||||
Nodemailer (`backend/src/services/mailService.ts`) avec `SMTP_HOST`. `PUBLIC_ORIGIN`
|
||||
(obligatoire) construit les liens de réinitialisation et de confirmation ;
|
||||
aucun HTML utilisateur n'est injecté dans les messages.
|
||||
|
||||
@@ -63,6 +93,8 @@ aucun HTML utilisateur n'est injecté dans les messages.
|
||||
une **liste blanche** de types (`image/*` hors `image/svg+xml`, `video/*`,
|
||||
`audio/*`, `application/pdf`, `text/plain`) — jamais de HTML/SVG qui
|
||||
s'exécuterait dans l'origine. Les deux routes gèrent `Range` (206 / 416).
|
||||
- Vignettes : le SVG est aussi exclu du passage à `sharp`/librsvg ; il reste
|
||||
téléchargeable, mais n'est jamais décodé côté serveur.
|
||||
|
||||
## Hors périmètre (assumé)
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ Design system local à `frontend/src/ui` : `Button`, `Card`, `Input`,
|
||||
|
||||
| Élément | Attendu |
|
||||
| --- | --- |
|
||||
| Socle & design system | internes à `backend/src/lib` et `frontend/src/ui` |
|
||||
| Socle & design system | internes à `backend/src/{config,middleware,utils}` et `frontend/src/ui` |
|
||||
| Port HTTP | `8083` (`COHAISE_HTTP_PORT`) |
|
||||
| Dépôt | autonome, importance égale front et back |
|
||||
| `.env` | jamais versionné (`.env.example` seulement) |
|
||||
|
||||
@@ -33,13 +33,13 @@ fichier est copié dans l'image, pas monté.
|
||||
|
||||
## Modifier une route
|
||||
|
||||
1. Schéma d'entrée : Zod dans `backend/src/routes/<entity>.ts`.
|
||||
2. Droits : passer par `backend/src/access.ts` (jamais par un paramètre
|
||||
venu du client).
|
||||
1. Schéma d'entrée : Zod dans `backend/src/routes/<entity>Routes.ts`.
|
||||
2. Droits : passer par `backend/src/services/auditService.ts` (jamais par un
|
||||
paramètre venu du client).
|
||||
3. Réponse : renvoyer **404** si la ressource n'est pas censée exister pour ce
|
||||
compte, 403 seulement pour une règle explicite.
|
||||
4. Erreur métier : `AppError` depuis `backend/src/lib/errors.ts`.
|
||||
5. Audit si l'action est sensible (`audit()` dans `access.ts`).
|
||||
4. Erreur métier : `AppError` depuis `backend/src/utils/errors.ts`.
|
||||
5. Audit si l'action est sensible (`audit()` dans `services/auditService.ts`).
|
||||
6. `make check`, puis redémarrage de l'API (`docker compose up -d api`).
|
||||
|
||||
## Modifier le schéma
|
||||
@@ -65,10 +65,10 @@ Le design system vit dans `frontend/src/ui` (+ `src/styles`).
|
||||
|
||||
| Besoin | Fichier |
|
||||
| --- | --- |
|
||||
| Droit d'accès à un dossier/fichier | `backend/src/access.ts` |
|
||||
| Droit d'accès à un dossier/fichier | `backend/src/services/auditService.ts` |
|
||||
| Taille/quota par défaut | migration `004`, table `users` / `settings` |
|
||||
| Chemin physique des fichiers | `backend/src/storage.ts` |
|
||||
| En-têtes, CORS, healthz | `backend/src/lib/http.ts` |
|
||||
| Chemin physique des fichiers | `backend/src/services/storageService.ts` |
|
||||
| En-têtes, CORS, healthz | `backend/src/utils/http.ts` |
|
||||
| Durée de session | `SESSION_TTL_HOURS` |
|
||||
| Port | `COHAISE_HTTP_PORT` (nginx), `COHAISE_API_PORT` (API) |
|
||||
| Interface (parcours dossiers) | `frontend/src/pages/Browser.tsx` |
|
||||
|
||||
@@ -14,12 +14,14 @@
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router-dom": "^7.18.4",
|
||||
"tailwind-merge": "^3.7.0"
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"three": "^0.187.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@types/three": "^0.187.0",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^7.0.2",
|
||||
|
||||
|
After Width: | Height: | Size: 826 B |
|
After Width: | Height: | Size: 792 B |
|
After Width: | Height: | Size: 466 B |
|
After Width: | Height: | Size: 680 B |
|
After Width: | Height: | Size: 626 B |
|
After Width: | Height: | Size: 932 B |
|
After Width: | Height: | Size: 656 B |
|
After Width: | Height: | Size: 680 B |
|
After Width: | Height: | Size: 482 B |
|
After Width: | Height: | Size: 702 B |
|
After Width: | Height: | Size: 544 B |
|
After Width: | Height: | Size: 576 B |
|
After Width: | Height: | Size: 490 B |
|
After Width: | Height: | Size: 730 B |
|
After Width: | Height: | Size: 466 B |
|
After Width: | Height: | Size: 608 B |
|
After Width: | Height: | Size: 566 B |
|
After Width: | Height: | Size: 704 B |
|
After Width: | Height: | Size: 520 B |
|
After Width: | Height: | Size: 732 B |
|
After Width: | Height: | Size: 608 B |
|
After Width: | Height: | Size: 752 B |
|
After Width: | Height: | Size: 814 B |
|
After Width: | Height: | Size: 746 B |
|
After Width: | Height: | Size: 878 B |
|
After Width: | Height: | Size: 808 B |
|
After Width: | Height: | Size: 764 B |
|
After Width: | Height: | Size: 588 B |
|
After Width: | Height: | Size: 604 B |
|
After Width: | Height: | Size: 728 B |
|
After Width: | Height: | Size: 832 B |
|
After Width: | Height: | Size: 576 B |
|
After Width: | Height: | Size: 520 B |