Compare commits

..
2 Commits
Author SHA1 Message Date
Gitea ActionsandEsiah f689ab4d57 refactor: restructure frontend and backend by domain services (#26)
CD — Deployment / deploy (push) Successful in 34s
Split the monolithic backend (lib/, routes/, access.ts, storage.ts, media.ts)
into a layered structure inspired by JeanXXIII-CRM:
- config/: appConfig, db
- middleware/: auth (session, roles, cookies)
- models/: shared types
- routes/: *Routes.ts (thin HTTP handlers)
- services/: *Service.ts (business logic, one per domain)
- utils/: errors, http, migrate, ratelimit, validators, service bootstrap

Frontend likewise: services/*Service.ts + apiClient, contexts/, types/, utils/format.
Route files now carry the "Routes" suffix; service files are named
authService.ts, ratelimit.ts, etc. and live in their own files, frontend and
backend separated.

Updated docs and READMEs to reflect the new layout. Typecheck and builds pass.

---------

Co-authored-by: xEsiah <[email protected]>
Reviewed-on: #26
Reviewed-by: Esiah <[email protected]>
Co-authored-by: Gitea Actions <-[email protected]>
2026-11-13 09:13:27 +00:00
Gitea ActionsandEsiah d837817bcb chore: remove agent-oriented comments from the codebase (#25)
CD — Deployment / deploy (push) Successful in 23s
PR automatique de chore/code-cleanup vers main.

---------

Co-authored-by: xEsiah <[email protected]>
Reviewed-on: #25
Reviewed-by: Esiah <[email protected]>
Co-authored-by: Gitea Actions <-[email protected]>
2026-11-04 15:04:00 +00:00
114 changed files with 5608 additions and 5675 deletions
+6 -5
View File
@@ -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
+5 -3
View File
@@ -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).
+4 -16
View File
@@ -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 {
+4 -16
View File
@@ -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 ?? "";
+15 -22
View File
@@ -1,21 +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 { purgeExpiredUploads, registerUploadRoutes } from "./routes/uploads.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({
@@ -35,24 +35,17 @@ void startService({
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);
const uploads = await purgeExpiredUploads(db, config);
logger.info("entretien au demarrage", { sessions, purged, uploads });
// Les envois abandonnes ne doivent pas garder leur temporaire indefiniment :
// un balayage horaire suffit, la session expirant apres 24 h.
setInterval(() => {
void purgeExpiredUploads(db, config).catch((error: unknown) =>
logger.error("purge des envois inacheves", { error: String(error) }),
);
}, 60 * 60 * 1000).unref();
// Sessions expirees et corbeille hors retention : sans ce balayage, elles
// ne disparaissent qu'au redemarrage. Les jetons expires sont deja refuses
// a chaque requete ; il s'agit ici d'eviter une table qui grossit sans fin
// et de faire respecter la retention de la corbeille sans redemarrage.
setInterval(() => {
void purgeExpiredSessions(db).catch((error: unknown) =>
logger.error("purge des sessions expirees", { error: String(error) }),
-261
View File
@@ -1,261 +0,0 @@
import {
createHash,
createHmac,
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");
/**
* Empreinte du jeton de session : SHA-256 poivre par SESSION_SECRET.
*
* Sans ce poivre, une ecriture frauduleuse dans `user_sessions` suffirait a
* forger une session : l'attaquant connaitrait le hachage a poser. Le secret
* vit hors de la base, donc une fuite de la base seule ne donne aucune session
* ouvrable.
*/
export const sessionTokenHash = (token: string, secret: string): string =>
createHmac("sha256", secret).update(token).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 HMAC-SHA-256 (poivree par
* SESSION_SECRET) 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,
* et le secret, qui vit hors de la base.
*/
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;
// 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",
[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;
};
/**
* 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, 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();
};
/**
* Routes encore accessibles lorsqu'un changement de mot de passe est impose :
* lire son profil, changer le mot de passe, se deconnecter. Tout le reste est
* refuse cote serveur, et pas seulement par la redirection du client.
*/
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();
};
/** 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;
};
-61
View File
@@ -1,61 +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,
JSON_BODY_MAX_BYTES,
readBodyCapped,
readJson,
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,
sessionTokenHash,
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";
-75
View File
@@ -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();
+87
View File
@@ -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;
};
+37
View File
@@ -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;
}
-454
View File
@@ -1,454 +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,
readBodyCapped,
readJson,
renderMail,
requireAuth,
sessionTokenHash,
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, config.SESSION_SECRET));
app.use("/api/cloud/account", attachUser(db, config.SESSION_SECRET));
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 readJson(context));
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 readJson(context));
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 = sessionTokenHash(context.get("token") ?? "", 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 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 = sessionTokenHash(context.get("token") ?? "", 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],
);
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);
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 readJson(context));
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 readJson(context));
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 readJson(context));
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 readJson(context),
);
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 });
});
};
+197
View File
@@ -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 });
});
};
-575
View File
@@ -1,575 +0,0 @@
import { randomInt, randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
branding,
createMailer,
currentUser,
hashPassword,
link,
renderMail,
requireAuth,
readJson,
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";
// randomInt borne directement l'intervalle : pas de biais modulo, contrairement
// a `octet % longueur` qui favorise les premiers caracteres de l'alphabet.
let out = "";
for (let index = 0; index < 18; index += 1) out += alphabet[randomInt(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, config.SESSION_SECRET));
app.use("/api/cloud/admin", attachUser(db, config.SESSION_SECRET));
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 readJson(context));
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 readJson(context));
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 readJson(context));
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 readJson(context));
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 });
});
};
+148
View File
@@ -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 });
});
};
-199
View File
@@ -1,199 +0,0 @@
import { z } from "zod";
import {
AppError,
attachUser,
clearSessionCookie,
clientIp,
createRateLimiter,
createSession,
currentUser,
hashPassword,
isHttpsRequest,
rateLimitKey,
readJson,
requireAuth,
revokeSession,
sessionTokenHash,
setSessionCookie,
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, 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) => {
// 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 readJson(context));
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,
config.SESSION_SECRET,
);
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, config.SESSION_SECRET);
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 readJson(context));
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, sessionTokenHash(context.get("token") ?? "", config.SESSION_SECRET)],
);
return context.json({ ok: true });
});
};
+87
View File
@@ -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 });
});
};
-423
View File
@@ -1,423 +0,0 @@
import { z } from "zod";
import {
AppError,
createRateLimiter,
currentUser,
readJson,
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."),
});
/** Meme borne que l'envoi : un message edite ne peut pas devenir plus long. */
const editInput = z.object({
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
});
/** Horodatage renvoye tel quel par le serveur : `AAAA-MM-JJTHH:MM:SS.ffffff`. */
const DATETIME_CURSOR = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?$/;
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;
}
/** 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, 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`;
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,
});
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);
/**
* Curseur d'edition. Le curseur `after` ne voit que les messages plus
* recents : une reecriture d'un ancien message y resterait invisible.
*
* Le curseur est un horodatage de la base, dans le meme cadran que la
* colonne `edited_at` : le client le renvoie tel quel, sans conversion.
* Comparer une chaine ISO (UTC) a un DATETIME stocke en heure locale
* decalerait la fenetre de la difference de fuseau.
*
* Il est calcule AVANT la requete : une edition survenue entre les deux
* porte un horodatage posterieur au curseur, elle sera donc vue au tour
* suivant plutot que perdue.
*/
// `cursor` est un mot reserve en MariaDB : l'alias est renomme.
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 = context.req.query("editedAfter");
const editedSince =
typeof editedAfterRaw === "string" && DATETIME_CURSOR.test(editedAfterRaw)
? editedAfterRaw
: serverCursor;
// `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 > ?
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(folderId, user.id, newest);
return context.json({ messages: rows.map(publicMessage), cursor: serverCursor });
});
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 readJson(context));
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);
});
/**
* Edition d'un message. Seul l'auteur peut modifier ce qu'il a ecrit : le
* filtre `user_id = ?` est porte par la requete SQL, donc un message d'autrui
* est indistinguishable d'un message inexistant. Le gestionnaire du dossier
* peut supprimer un message, mais pas le reecrire a la place de son auteur.
*/
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"));
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.");
if (!limiter.allow(user.id)) {
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
}
const parsed = editInput.safeParse(await readJson(context));
if (!parsed.success) {
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
}
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`,
[parsed.data.body, id, folderId, user.id],
);
if (result.affectedRows === 0) throw AppError.notFound("Message introuvable.");
await audit(
db,
context,
user,
"chat.edit",
"message",
String(id),
{ folderId },
config.TRUST_PROXY,
);
const row = await db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [id]);
return context.json({ message: publicMessage(row) });
},
);
/**
* Epinglage d'un message. Bascule atomique en base : le salon compte
* plusieurs participants, deux clics croises ne doivent pas laisser le
* message dans un etat incoherent. Tout membre du salon peut epingler.
*/
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"));
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.");
if (!limiter.allow(user.id)) {
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
}
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],
);
const pinned = row.is_pinned === 1;
await audit(
db,
context,
user,
pinned ? "chat.pin" : "chat.unpin",
"message",
String(id),
{ folderId },
config.TRUST_PROXY,
);
return context.json({ pinned });
},
);
/**
* Messages epingles du salon. Relu a chaque tour de synchronisation : le
* curseur `after` ne remonte que les messages plus recents, donc un
* epinglage pose sur un ancien message resterait invisible sans cette lecture
* dediee.
*/
app.get("/api/cloud/folders/:folderId/chat/pins", 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 rows = await 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],
);
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"));
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.");
}
// Un message retire quitte aussi les epingles : le laisser marque ferait
// apparaitre un epingle fantome dans le bandeau. `deleted_at` suit la
// meme horloge que `created_at`.
await db.exec(
"UPDATE chat_messages SET deleted_at = CURRENT_TIMESTAMP(3), is_pinned = 0 WHERE id = ?",
[id],
);
await audit(db, context, user, "chat.delete", "message", String(id), { folderId }, config.TRUST_PROXY);
return context.json({ ok: true });
},
);
};
+162
View File
@@ -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 });
},
);
};
-48
View File
@@ -1,48 +0,0 @@
import {
attachUser,
currentUser,
requireAuth,
type App,
type Config,
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, 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 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,
})),
});
});
};
+15
View File
@@ -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 });
});
};
+327
View File
@@ -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 });
});
};
-718
View File
@@ -1,718 +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,
readJson,
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;
};
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;
}
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,
});
/** Nom d'affichage : ni separateur, ni sequence d'echappement, ni point seul. */
export 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;
};
export 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, config.SESSION_SECRET));
app.use("/api/cloud/files", attachUser(db, config.SESSION_SECRET));
/**
* 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.");
}
// Un nom est unique dans un dossier, mais la racine est un espace
// personnel : chaque utilisateur y depose ses propres fichiers, et la
// liste n'en montre que les siens. Le controle de doublon doit donc
// suivre la meme regle, sinon le fichier d'un autre compte a la racine
// bloquerait un depot qui n'a rien a voir avec lui.
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.");
// 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 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],
);
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 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],
);
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 readJson(context));
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 readJson(context));
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 });
});
};
+164
View File
@@ -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 });
});
};
-396
View File
@@ -1,396 +0,0 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
requireRole,
readJson,
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, 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.");
}
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 readJson(context),
);
const name = assertName(rawName);
if (parentId) {
if (!(await canWrite(db, user, parentId))) {
throw AppError.forbidden("Vous ne pouvez pas ecrire dans ce dossier.");
}
}
// La racine est l'espace personnel de chaque compte : un dossier du meme
// nom cree par quelqu'un d'autre ne doit pas bloquer celui-ci. Dans un
// dossier, le nom reste unique pour tous ses participants.
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;
}
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 readJson(context));
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 readJson(context));
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 readJson(context),
);
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 });
});
};
-91
View File
@@ -1,91 +0,0 @@
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Config,
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, 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 !== "" && !(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 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 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,
})),
});
});
};
+23
View File
@@ -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 });
});
};
-115
View File
@@ -1,115 +0,0 @@
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Config,
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, 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.");
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 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 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,
})),
});
});
};
+18
View File
@@ -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));
});
};
-382
View File
@@ -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, 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);
// 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;
};
+90
View File
@@ -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 });
});
};
+122
View File
@@ -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 });
});
};
-483
View File
@@ -1,483 +0,0 @@
import { randomUUID } from "node:crypto";
import { stat } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
requireRole,
readJson,
type App,
type Config,
type Db,
} from "../lib/index.js";
import { audit, canWrite } from "../access.js";
import { indexMedia } from "../media.js";
import {
absolutePath,
chooseLocation,
discard,
diskUsage,
ensureDir,
fileExists,
hashFile,
listUploadTemps,
preallocateUpload,
publish,
relativePathFor,
uploadTempPath,
writeChunk,
} from "../storage.js";
import { SELECT_FILE, assertName, mimeOf, publicFile, type FileRow } from "./files.js";
/**
* Upload resumable pour les fichiers qui depassent la limite de corps de
* requete de Cloudflare. Le client envoie des morceaux sequentiels de 50 MiB,
* ce qui reste sous la limite de 100 MB des offres Free/Pro.
*
* Le fichier temporaire est prealloue et rempli a l'offset courant. Une
* session ne peut appartenir qu'a son createur, et les droits d'ecriture sont
* revalides au moment de la finalisation : un partage retire pendant l'envoi
* ne permet pas de publier le fichier.
*/
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.",
);
/** 50 MiB : sous la limite Cloudflare (100 MB) avec une marge confortable. */
export const CHUNK_SIZE = 50 * 1024 * 1024;
/** Duree de vie d'une session abandonnee, avant purge du temporaire. */
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
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(),
});
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 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`;
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(),
});
/** Supprime la session et son temporaire, sans bruit si deja absente. */
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> => {
if (!uuid.safeParse(id).success) throw AppError.notFound("Session d'envoi introuvable.");
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;
};
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 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);
const folderId = data.folderId ?? null;
const size = data.size;
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();
// Les sessions en cours immobilisent deja une part du quota : sans
// cette somme, plusieurs envois simultanes pourraient chacun passer le
// controle puis depasser le quota au moment de la finalisation.
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,
mimeOf(data.mimeType ?? undefined),
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]);
await audit(
db,
context,
user,
"file.upload.start",
"file",
id,
{ name, size, folder_id: folderId },
config.TRUST_PROXY,
);
return context.json({ upload: sessionPublic(created) }, 201);
},
);
app.get("/api/cloud/uploads/:id", requireAuth, async (context) => {
const user = currentUser(context);
const row = await loadSession(db, user, context.req.param("id") ?? "");
return context.json({ upload: sessionPublic(row) });
});
app.put("/api/cloud/uploads/:id/chunks", requireAuth, async (context) => {
const user = currentUser(context);
const row = await loadSession(db, user, context.req.param("id") ?? "");
const offset = Number(row.received_bytes);
const size = Number(row.size_bytes);
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.");
}
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 body = context.req.raw.body;
if (!body) throw AppError.badRequest("Corps de requete vide.");
// Ecriture d'abord, curseur ensuite : un morceau interrompu laisse le
// curseur intact, donc le prochain essai reecrit la meme plage sans creer
// de trou. Deux requetes concurrentes sur la meme plage ecrivent les
// memes octets : une seule avance le curseur, l'autre constate que le
// morceau est deja applique.
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 context.json({ upload: sessionPublic(fresh) });
}
return context.json({ upload: sessionPublic({ ...row, received_bytes: offset + declared }) });
});
app.post("/api/cloud/uploads/:id/complete", requireAuth, async (context) => {
const user = currentUser(context);
const row = await loadSession(db, user, context.req.param("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.");
}
// La limite de taille est propre au compte : elle peut avoir baisse
// pendant un envoi long, il faut donc la reverifier avant de publier.
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);
// Le dossier de l'emplacement peut ne pas encore exister : l'envoi direct
// le cree avant d'ecrire, l'envoi resumable ecrit d'abord dans .uploads.
await ensureDir(path.dirname(destination));
// Publication avant la base, comme le depot direct : si la transaction
// echoue, le temporaire est remis en place pour permettre un nouvel essai.
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,
);
await audit(
db,
context,
user,
"file.upload",
"file",
row.id,
{ name: row.name, size, folder_id: row.folder_id },
config.TRUST_PROXY,
);
const created = await db.required<FileRow>(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]);
return context.json({ file: publicFile(created) }, 201);
});
app.delete("/api/cloud/uploads/:id", requireAuth, async (context) => {
const user = currentUser(context);
const row = await loadSession(db, user, context.req.param("id") ?? "");
await dropSession(db, row);
await audit(
db,
context,
user,
"file.upload.cancel",
"file",
row.id,
{ name: row.name },
config.TRUST_PROXY,
);
return context.json({ ok: true });
});
};
/**
* Purge les sessions arrivees a echeance et les temporaires orphelins (session
* supprimee avec le dossier ou le compte, par exemple). Appelee au demarrage
* puis periodiquement par le service.
*/
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;
};
+373
View File
@@ -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;
};
+494
View File
@@ -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,
+241
View File
@@ -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)],
);
};
+278
View File
@@ -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],
);
};
+40
View File
@@ -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,
}));
};
+364
View File
@@ -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;
};
+290
View File
@@ -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, "&amp;")
@@ -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,12 +42,6 @@ export const classify = (mime: string | null): MediaKind => {
export const isImage = (mime: string | null): boolean =>
(mime ?? "").toLowerCase().startsWith("image/");
/**
* Le SVG est une image au sens MIME, mais pas une image sure a decoder :
* librsvg peut resolvere des references externes et son moteur est une surface
* d'attaque supplementaire. Il est deja exclu de l'apercu en ligne ; on ne le
* passe pas non plus a sharp pour la vignette. Le fichier reste telechargeable.
*/
const isRasterImage = (mime: string | null): boolean => {
const value = (mime ?? "").toLowerCase();
return value.startsWith("image/") && value !== "image/svg+xml";
@@ -93,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,
@@ -141,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));
@@ -150,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;
+111
View File
@@ -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,
})),
};
};
@@ -4,15 +4,8 @@ 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,17 +108,12 @@ export const discard = async (...paths: string[]): Promise<void> => {
export const temporaryPath = (mediaDir: string, slug: string): string =>
path.join(path.resolve(mediaDir), slug, `.upload-${randomUUID()}`);
/**
* Dossier des uploads resumables. Il reste sous MEDIA_DIR : le renommage
* final vers l'emplacement de stockage est donc atomique.
*/
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`);
/** Prealloue le temporaire a la taille annoncee, sans ecrire les octets. */
export const preallocateUpload = async (destination: string, size: number): Promise<void> => {
await ensureDir(path.dirname(destination));
const handle = await open(destination, "wx");
@@ -151,10 +124,6 @@ export const preallocateUpload = async (destination: string, size: number): Prom
}
};
/**
* Ecrit un morceau a l'offset courant. Le flux est borne : un client qui
* annonce une taille et en envoie davantage est coupe avant d'ecrire l'exces.
*/
export const writeChunk = async (
destination: string,
offset: number,
@@ -180,7 +149,6 @@ export const writeChunk = async (
return received;
};
/** SHA-256 du fichier complet, calcule au moment de la finalisation. */
export const hashFile = async (absolute: string): Promise<string> => {
const hash = createHash("sha256");
for await (const chunk of createReadStream(absolute)) {
@@ -189,7 +157,6 @@ export const hashFile = async (absolute: string): Promise<string> => {
return hash.digest("hex");
};
/** Fichiers `.part` abandonnes : utilises par la purge des sessions expirees. */
export const listUploadTemps = async (mediaDir: string): Promise<string[]> => {
const entries = await readdir(uploadTempDir(mediaDir)).catch(() => []);
return entries
@@ -206,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;
}
@@ -236,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;
}
};
+337
View File
@@ -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;
};
+376
View File
@@ -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,15 +68,8 @@ export const clientIp = (context: Context, trustProxy: boolean): string | null =
return address ? address.slice(0, 45) : null;
};
/** Taille maximale d'un corps JSON. Les envois de fichiers ont leur propre flux borne. */
export const JSON_BODY_MAX_BYTES = 1024 * 1024;
/**
* Lit le corps de la requete en memoire, avec une borne dure sur les octets
* reellement recus. `content-length` est verifie d'abord pour refuser tot, mais
* la lecture bornee est la vraie garantie : un client peut mentir sur l'en-tete
* et envoyer davantage que ce qu'il annonce.
*/
export const readBodyCapped = async (context: Context, maxBytes: number): Promise<Buffer> => {
const declared = Number(context.req.header("content-length") ?? "");
if (Number.isFinite(declared) && declared > maxBytes) {
@@ -113,11 +99,6 @@ export const readBodyCapped = async (context: Context, maxBytes: number): Promis
return Buffer.concat(chunks);
};
/**
* Parse le corps JSON avec la meme borne. Un corps absent ou illisible rend
* `null`, comme l'ancien `req.json().catch(() => null)` : les routes continuent
* de repondre par leur validation zod habituelle.
*/
export const readJson = async (
context: Context,
maxBytes = JSON_BODY_MAX_BYTES,
@@ -131,7 +112,6 @@ export const readJson = async (
}
};
/** Dependances remises aux routes metier au montage. */
export interface RouteDeps {
db: Db;
config: Config;
@@ -143,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");
+47
View File
@@ -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";
};
+11 -7
View File
@@ -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
+6 -6
View File
@@ -91,7 +91,7 @@ l'offset exact.
### 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.
@@ -158,7 +158,7 @@ utilise alors le sien.
## 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 |
| --- | --- |
@@ -190,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.
@@ -229,7 +229,7 @@ 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 :
+30 -20
View File
@@ -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
@@ -58,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
@@ -78,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`.
+1 -1
View File
@@ -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
+3 -3
View File
@@ -18,7 +18,7 @@
### 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).
@@ -36,7 +36,7 @@
### 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.
@@ -64,7 +64,7 @@ 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.
+1 -1
View File
@@ -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) |
+8 -8
View File
@@ -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` |
+30 -26
View File
@@ -1,8 +1,9 @@
import { Navigate, Outlet, Route, Routes } from "react-router-dom";
import { Spinner } from "./ui/index.js";
import { useSession } from "./lib/session.js";
import { useSession } from "./contexts/SessionContext.js";
import { AppShell } from "./components/AppShell.js";
import { AuthLayout } from "./components/AuthLayout.js";
import { DocumentTitle } from "./components/DocumentTitle.js";
import { Login } from "./pages/Login.js";
import { ForgotPassword } from "./pages/ForgotPassword.js";
import { ResetPassword } from "./pages/ResetPassword.js";
@@ -42,39 +43,42 @@ const RequireAdmin = () => {
};
export const App = () => (
<Routes>
<Route element={<AuthLayout />}>
<Route path="/login" element={<Login />} />
<Route path="/forgot-password" element={<ForgotPassword />} />
<Route path="/reset-password" element={<ResetPassword />} />
<Route path="/confirm-email" element={<ConfirmEmail />} />
</Route>
<Route element={<RequireAuth />}>
<>
<DocumentTitle />
<Routes>
<Route element={<AuthLayout />}>
<Route path="/change-password" element={<ChangePassword />} />
<Route path="/login" element={<Login />} />
<Route path="/forgot-password" element={<ForgotPassword />} />
<Route path="/reset-password" element={<ResetPassword />} />
<Route path="/confirm-email" element={<ConfirmEmail />} />
</Route>
<Route element={<RequireReady />}>
<Route element={<AppShell />}>
<Route path="/files" element={<Browser />} />
<Route path="/favorites" element={<Favorites />} />
<Route path="/search" element={<Search />} />
<Route path="/gallery" element={<Gallery />} />
<Route path="/trash" element={<Trash />} />
<Route path="/profile" element={<Profile />} />
<Route element={<RequireAuth />}>
<Route element={<AuthLayout />}>
<Route path="/change-password" element={<ChangePassword />} />
</Route>
<Route element={<RequireAdmin />}>
<Route element={<RequireReady />}>
<Route element={<AppShell />}>
<Route path="/admin/comptes" element={<AdminUsers />} />
<Route path="/admin/stockage" element={<AdminStorage />} />
<Route path="/admin/audit" element={<AdminAudit />} />
<Route path="/files" element={<Browser />} />
<Route path="/favorites" element={<Favorites />} />
<Route path="/search" element={<Search />} />
<Route path="/gallery" element={<Gallery />} />
<Route path="/trash" element={<Trash />} />
<Route path="/profile" element={<Profile />} />
</Route>
<Route element={<RequireAdmin />}>
<Route element={<AppShell />}>
<Route path="/admin/comptes" element={<AdminUsers />} />
<Route path="/admin/stockage" element={<AdminStorage />} />
<Route path="/admin/audit" element={<AdminAudit />} />
</Route>
</Route>
</Route>
</Route>
</Route>
<Route path="*" element={<Navigate to="/files" replace />} />
</Routes>
<Route path="*" element={<Navigate to="/files" replace />} />
</Routes>
</>
);
+2 -2
View File
@@ -7,8 +7,8 @@ import {
} from "react";
import { NavLink, Outlet } from "react-router-dom";
import { cn } from "../ui/index.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import { Avatar } from "./Avatar.js";
import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js";
import {
-5
View File
@@ -1,11 +1,6 @@
import { Outlet } from "react-router-dom";
import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js";
/**
* Coque des ecrans d'authentification : fond carmin animé, puis une colonne
* centree qui contient la page courante. Le degrade garantit la lisibilite des
* cartes et des champs par-dessus le shader, dans les deux themes.
*/
export const AuthLayout = () => (
<main className="relative flex min-h-dvh items-center justify-center overflow-hidden bg-background px-4 py-10">
<ColorBendsBackdrop variant="auth" />
+2 -7
View File
@@ -1,14 +1,9 @@
import { api } from "../lib/api.js";
import { accountService } from "../services/accountService.js";
import { cn } from "../ui/index.js";
const initials = (first: string, last: string): string =>
`${first.charAt(0)}${last.charAt(0)}`.toUpperCase() || "?";
/**
* Pastille d'identite : initiales sur fond neutre, remplacees par la photo de
* profil quand elle existe. La version de la photo est passee en parametre
* pour invalider le cache navigateur des qu'elle change.
*/
export const Avatar = ({
userId,
firstName,
@@ -34,7 +29,7 @@ export const Avatar = ({
{initials(firstName, lastName)}
{hasAvatar ? (
<img
src={`${api.avatarUrl(userId)}?v=${encodeURIComponent(avatarUpdatedAt ?? "")}`}
src={`${accountService.avatarUrl(userId)}?v=${encodeURIComponent(avatarUpdatedAt ?? "")}`}
alt=""
className="absolute inset-0 h-full w-full object-cover"
onError={(event) => {
-17
View File
@@ -14,14 +14,6 @@ import {
} from "three";
import "./ColorBends.css";
/**
* Fond anime "ColorBends" (React Bits), porte en TypeScript pour le projet.
*
* Le rendu est un shader plein ecran : aucune image, aucun appel reseau. Le
* composant respecte `prefers-reduced-motion` en figeant le shader apres une
* premiere image, et libere le contexte WebGL au demontage.
*/
const MAX_COLORS = 8;
const frag = `
@@ -225,8 +217,6 @@ export default function ColorBends({
alpha: true,
});
} catch {
// Pas de WebGL (navigateur ancien, materiel bloque) : le fond reste
// simplement absent, l'ecran et le formulaire continuent de fonctionner.
return;
}
@@ -361,9 +351,6 @@ export default function ColorBends({
renderOnceRef.current = null;
resizeObserverRef.current = null;
};
// Les uniformes sont mis a jour par l'effet suivant ; ce premier montage ne
// depend donc que du conteneur et ne recree jamais le contexte WebGL.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
@@ -395,8 +382,6 @@ export default function ColorBends({
material.uniforms.uTransparent!.value = transparent ? 1 : 0;
if (rendererRef.current) rendererRef.current.setClearColor(0x000000, transparent ? 0 : 1);
// Sans boucle (prefers-reduced-motion), les uniformes viennent de changer :
// il faut une image de plus pour que la palette soit réellement appliquée.
if (rafRef.current === null) renderOnceRef.current?.();
}, [
rotation,
@@ -426,8 +411,6 @@ export default function ColorBends({
pointerTargetRef.current.set(x, y);
};
// Ecoute au niveau de la fenetre : le fond peut etre recouvert par la
// coque ou par une carte, et doit reagir quand meme au mouvement.
window.addEventListener("pointermove", handlePointerMove, { passive: true });
return () => {
window.removeEventListener("pointermove", handlePointerMove);
@@ -10,11 +10,6 @@ type BackdropPreset = Omit<ColorBendsProps, "colors" | "transparent" | "classNam
className: string;
};
/**
* Fond carmin partage par les ecrans d'authentification, la coque connectee
* et le salon de discussion. Le composant WebGL reste charge a la demande :
* seuls les presets sont dans le bundle initial.
*/
const PRESETS: Record<BackdropVariant, BackdropPreset> = {
auth: {
className: "opacity-[0.55] dark:opacity-[0.7]",
+41
View File
@@ -0,0 +1,41 @@
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { useI18n } from "../contexts/I18nContext.js";
const BRAND = "CoHaiSe Cloud";
const SECTIONS: Array<[string, string]> = [
["/files", "Fichiers"],
["/favorites", "Favoris"],
["/search", "Recherche"],
["/gallery", "Galerie"],
["/trash", "Corbeille"],
["/profile", "Mon compte"],
["/admin/comptes", "Comptes"],
["/admin/stockage", "Stockage"],
["/admin/audit", "Journal"],
["/login", "Connexion"],
["/forgot-password", "Mot de passe oublié"],
["/reset-password", "Réinitialisation"],
["/confirm-email", "Confirmation"],
["/change-password", "Changement requis"],
];
const sectionFor = (pathname: string): string | undefined => {
const found = SECTIONS.find(
([path]) => pathname === path || pathname.startsWith(`${path}/`),
);
return found?.[1];
};
export const DocumentTitle = () => {
const { pathname } = useLocation();
const { t } = useI18n();
useEffect(() => {
const section = sectionFor(pathname);
document.title = section ? `${t(section)} | ${BRAND}` : BRAND;
}, [pathname, t]);
return null;
};
+16 -47
View File
@@ -8,17 +8,13 @@ import {
type KeyboardEvent as ReactKeyboardEvent,
} from "react";
import { Button, Spinner, cn } from "../ui/index.js";
import {
ApiError,
api,
formatDate,
formatDateTimeSeconds,
type ChatMember,
type ChatMessage,
} from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { chatService } from "../services/chatService.js";
import { formatDate, formatDateTimeSeconds } from "../utils/format.js";
import type { ChatMember, ChatMessage } from "../types/index.js";
import { useI18n } from "../contexts/I18nContext.js";
import { getLocale } from "../lib/locale.js";
import { useSession } from "../lib/session.js";
import { useSession } from "../contexts/SessionContext.js";
import { useConfirm } from "./confirm.js";
import { Avatar } from "./Avatar.js";
import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js";
@@ -70,12 +66,6 @@ export interface ChatFolder {
name: string;
}
/**
* Salon de discussion d'un dossier, ouvert en plein ecran par-dessus la vue
* des fichiers. Les membres sont les comptes ayant acces au dossier (le role
* admin n'ouvre aucun acces supplementaire) ; le serveur reevalue cet acces a
* chaque requete, l'interface ne fait que l'afficher.
*/
export const FolderChat = ({
folder,
onClose,
@@ -105,13 +95,7 @@ export const FolderChat = ({
const scrollRef = useRef<HTMLDivElement | null>(null);
const lastIdRef = useRef(0);
// Curseur d'edition : horodatage delivre par le serveur, renvoye tel quel.
// Le curseur d'identifiant ne voit que les messages plus recents, ce second
// curseur rattrape les reecritures d'anciens messages.
const editedSinceRef = useRef<string | null>(null);
// Tant que l'utilisateur reste au bas de la conversation, chaque nouveau
// message le ramene en bas ; s'il remonte lire l'historique, on ne le force
// pas a redescendre.
const stickToBottomRef = useRef(true);
const scrollToBottom = useCallback(() => {
@@ -132,9 +116,6 @@ export const FolderChat = ({
changed = true;
continue;
}
// Un message deja connu peut avoir ete reecrit ou change d'etat
// d'epinglage : on ne remplace que si la version recue est plus
// recente, pour ne pas ecraser une edition locale toute recente.
const knownEdited = known.edited_at ? Date.parse(known.edited_at) : 0;
const incomingEdited = message.edited_at
? Date.parse(message.edited_at)
@@ -157,7 +138,7 @@ export const FolderChat = ({
);
const loadMembers = useCallback(async () => {
const { members: list } = await api.chatMembers(folderId);
const { members: list } = await chatService.chatMembers(folderId);
setMembers(list);
}, [folderId]);
@@ -171,9 +152,9 @@ export const FolderChat = ({
void (async () => {
try {
const [memberResult, messageResult, pinResult] = await Promise.all([
api.chatMembers(folderId),
api.chatMessages(folderId, 0, 50),
api.chatPins(folderId),
chatService.chatMembers(folderId),
chatService.chatMessages(folderId, 0, 50),
chatService.chatPins(folderId),
]);
if (!active) return;
setMembers(memberResult.members);
@@ -201,28 +182,23 @@ export const FolderChat = ({
};
}, [folderId, scrollToBottom]);
// Synchronisation incrementale : rien n'est charge tant que l'onglet est en
// arriere-plan, la reprise se fait au retour de visibilite.
useEffect(() => {
const poll = async () => {
if (document.hidden) return;
try {
const [result, pinResult] = await Promise.all([
api.chatMessages(
chatService.chatMessages(
folderId,
lastIdRef.current,
100,
editedSinceRef.current,
),
api.chatPins(folderId),
chatService.chatPins(folderId),
]);
// Le curseur avance avec la reponse : le serveur le calcule avant la
// requete, une edition survenue entre les deux sera vue au tour suivant.
editedSinceRef.current = result.cursor;
mergeMessages(result.messages);
setPins(pinResult.messages);
} catch {
/* le prochain cycle retentera */
}
};
const onVisible = () => {
@@ -243,7 +219,6 @@ export const FolderChat = ({
return () => window.clearInterval(timer);
}, [loadMembers]);
// Fermeture au clavier et blocage du defilement de la page sous l'overlay.
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") onClose();
@@ -271,7 +246,7 @@ export const FolderChat = ({
setSending(true);
setError(null);
try {
const { message } = await api.chatSend(folderId, body);
const { message } = await chatService.chatSend(folderId, body);
stickToBottomRef.current = true;
mergeMessages([message]);
setDraft("");
@@ -298,11 +273,10 @@ export const FolderChat = ({
return;
setDeletingId(message.id);
try {
await api.chatDeleteMessage(folderId, message.id);
await chatService.chatDeleteMessage(folderId, message.id);
setMessages((previous) =>
previous.filter((item) => item.id !== message.id),
);
// Un message retire disparait aussi des epingles.
setPins((previous) => previous.filter((item) => item.id !== message.id));
} catch (caught) {
setError(
@@ -331,7 +305,7 @@ export const FolderChat = ({
setSavingEdit(true);
setError(null);
try {
const { message: updated } = await api.chatEditMessage(
const { message: updated } = await chatService.chatEditMessage(
folderId,
message.id,
body,
@@ -359,7 +333,7 @@ export const FolderChat = ({
setPinningId(message.id);
setError(null);
try {
const { pinned } = await api.chatTogglePin(folderId, message.id);
const { pinned } = await chatService.chatTogglePin(folderId, message.id);
const updated = { ...message, is_pinned: pinned };
mergeMessages([updated]);
setPins((previous) =>
@@ -367,8 +341,6 @@ export const FolderChat = ({
? [updated, ...previous.filter((item) => item.id !== updated.id)]
: previous.filter((item) => item.id !== updated.id),
);
// Le bandeau s'ouvre quand on epingle : c'est le moment ou l'utilisateur
// veut voir ce qu'il vient de mettre de cote.
if (pinned) setPinsOpen(true);
} catch (caught) {
setError(
@@ -405,7 +377,6 @@ export const FolderChat = ({
GROUP_WINDOW_MS;
const own = message.user_id === user?.id;
const canDelete = own;
// Seul l'auteur peut reecrire son message, sans limite de temps.
const canEdit = own;
return { message, newDay, continuation, own, canDelete, canEdit };
}),
@@ -705,8 +676,6 @@ export const FolderChat = ({
</>
)}
</div>
{/* L'epinglage est ouvert a tous les participants ; l'edition
et la suppression restent reservees a l'auteur. */}
<span className="flex shrink-0 items-center opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
<IconAction
label={
+3 -12
View File
@@ -1,16 +1,7 @@
import { api } from "../lib/api.js";
import { fileService } from "../services/fileService.js";
import { mediaKind } from "../lib/media.js";
import { ArchiveIcon, AudioIcon, FileIcon, PlayIcon } from "./icons.js";
/**
* Vignette d'un fichier, partagee entre le navigateur et la galerie.
* - image : la vignette WebP du backend ;
* - video : la premiere frame, lue en flux par le navigateur (`preload=metadata`
* et fragment `#t=0.1`), avec un bouton lecture en surimpression ;
* - audio / archive / document : une icone dediee.
* Le contenu est `pointer-events-none` : le clic atteint toujours le bouton
* parent qui ouvre l'apercu.
*/
export const MediaThumb = ({
id,
mime,
@@ -27,7 +18,7 @@ export const MediaThumb = ({
if (kind === "image") {
return (
<img
src={api.thumbnailUrl(id)}
src={fileService.thumbnailUrl(id)}
alt=""
loading="lazy"
className="pointer-events-none h-full w-full object-cover"
@@ -41,7 +32,7 @@ export const MediaThumb = ({
return (
<span className="relative block h-full w-full bg-black">
<video
src={`${api.previewUrl(id)}#t=0.1`}
src={`${fileService.previewUrl(id)}#t=0.1`}
preload="metadata"
muted
playsInline
+9 -9
View File
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { cn } from "../ui/index.js";
import { api } from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { fileService } from "../services/fileService.js";
import { useI18n } from "../contexts/I18nContext.js";
import { ArrowLeftIcon, ArrowRightIcon, CloseIcon, DownloadIcon, FileIcon } from "./icons.js";
export interface MediaViewerItem {
@@ -38,7 +38,7 @@ const TextViewer = ({ id }: { id: string }) => {
let active = true;
setText(null);
setFailed(false);
void fetch(api.previewUrl(id))
void fetch(fileService.previewUrl(id))
.then((response) => (response.ok ? response.text() : Promise.reject(new Error("failed"))))
.then((body) => {
if (active) setText(body);
@@ -80,7 +80,7 @@ const Panel = ({
<div className="flex flex-wrap items-center justify-center gap-2">
{openable ? (
<a
href={api.previewUrl(item.id)}
href={fileService.previewUrl(item.id)}
target="_blank"
rel="noopener noreferrer"
className={actionClass}
@@ -88,7 +88,7 @@ const Panel = ({
{t("Ouvrir")}
</a>
) : null}
<a href={api.downloadUrl(item.id)} download={item.name} className={actionClass}>
<a href={fileService.downloadUrl(item.id)} download={item.name} className={actionClass}>
<DownloadIcon className="h-4 w-4" />
{t("Télécharger")}
</a>
@@ -103,7 +103,7 @@ const Body = ({ item }: { item: MediaViewerItem }) => {
if (kind === "image") {
return (
<img
src={api.previewUrl(item.id)}
src={fileService.previewUrl(item.id)}
alt={item.name}
className="max-h-full max-w-full rounded-md object-contain shadow-2xl"
/>
@@ -112,7 +112,7 @@ const Body = ({ item }: { item: MediaViewerItem }) => {
if (kind === "video") {
return (
<video
src={api.previewUrl(item.id)}
src={fileService.previewUrl(item.id)}
controls
autoPlay
className="max-h-full max-w-full rounded-md bg-black shadow-2xl"
@@ -124,7 +124,7 @@ const Body = ({ item }: { item: MediaViewerItem }) => {
<div className="flex w-full max-w-md flex-col items-center gap-4 rounded-lg bg-black/40 p-6">
<FileIcon className="h-10 w-10 text-white/70" />
<p className="max-w-full truncate text-sm text-white/90">{item.name}</p>
<audio src={api.previewUrl(item.id)} controls autoPlay className="w-full" />
<audio src={fileService.previewUrl(item.id)} controls autoPlay className="w-full" />
</div>
);
}
@@ -173,7 +173,7 @@ export const MediaViewer = ({
<p className="min-w-0 truncate text-sm font-medium">{current.name}</p>
<div className="flex shrink-0 items-center gap-2">
<a
href={api.downloadUrl(current.id)}
href={fileService.downloadUrl(current.id)}
download={current.name}
className={controlClass}
aria-label={t("Télécharger")}
@@ -1,2 +1 @@
/** Palette carmin de la marque, alignee sur `tokens.css`. */
export const COHAISE_BENDS = ["#b71c1c", "#c92a2a", "#8f1116", "#5e0a14"];
+1 -9
View File
@@ -5,21 +5,17 @@ import {
useState,
type ReactNode,
} from "react";
import { useI18n } from "../lib/i18n.js";
import { useI18n } from "../contexts/I18nContext.js";
import { Modal } from "./feedback.js";
import { IconAction } from "./IconAction.js";
import { CloseIcon, TrashIcon, MoveIcon } from "./icons.js";
export interface ConfirmOptions {
/** Titre de la modale. */
title?: string;
/** Corps du message ; accepte du balisage pour mettre un nom en valeur. */
message: ReactNode;
confirmLabel?: string;
cancelLabel?: string;
/** `danger` reserve l'action a une operation destructive. */
tone?: "default" | "danger";
/** Icone du bouton de confirmation (defaut selon le tone). */
confirmIcon?: ReactNode;
}
@@ -32,10 +28,6 @@ interface PendingConfirm {
const ConfirmContext = createContext<ConfirmFn | null>(null);
/**
* Remplace `window.confirm` par une modale maison aux couleurs de l'app.
* `useConfirm()` renvoie une promesse resolue a `true` (confirme) ou `false`.
*/
export const ConfirmProvider = ({ children }: { children: ReactNode }) => {
const { t } = useI18n();
const [pending, setPending] = useState<PendingConfirm | null>(null);
+17 -20
View File
@@ -1,14 +1,12 @@
import { useEffect, useState, type FormEvent } from "react";
import { Button, Input, cn } from "../ui/index.js";
import {
ApiError,
api,
formatDate,
type DirectoryUser,
type Folder,
type FolderPermission,
} from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { directoryService } from "../services/directoryService.js";
import { fileService } from "../services/fileService.js";
import { folderService } from "../services/folderService.js";
import { formatDate } from "../utils/format.js";
import type { DirectoryUser, Folder, FolderPermission } from "../types/index.js";
import { useI18n } from "../contexts/I18nContext.js";
import { Alert, Modal } from "./feedback.js";
import { CloseIcon, MoveIcon, PenIcon, PlusIcon, TrashIcon } from "./icons.js";
import { IconAction } from "./IconAction.js";
@@ -48,7 +46,7 @@ export const CreateFolderDialog = ({
setBusy(true);
setError(null);
try {
await api.createFolder(name, parentId);
await folderService.createFolder(name, parentId);
onCreated();
} catch (caught) {
setError(messageOf(caught, t("Création impossible.")));
@@ -112,8 +110,8 @@ export const RenameDialog = ({
setBusy(true);
setError(null);
try {
if (target.type === "folder") await api.updateFolder(target.id, name);
else await api.renameFile(target.id, name);
if (target.type === "folder") await folderService.updateFolder(target.id, name);
else await fileService.renameFile(target.id, name);
onDone();
} catch (caught) {
setError(messageOf(caught, t("Renommage impossible.")));
@@ -166,7 +164,7 @@ const loadTree = async (): Promise<TreeEntry[]> => {
const entries: TreeEntry[] = [];
const walk = async (parentId: string | null, prefix: string, depth: number): Promise<void> => {
if (depth > 6) return;
const { folders } = await api.folders(parentId);
const { folders } = await folderService.folders(parentId);
for (const folder of folders) {
entries.push({ id: folder.id, label: `${prefix}${folder.name}` });
await walk(folder.id, `${prefix}${folder.name} / `, depth + 1);
@@ -209,8 +207,8 @@ export const MoveDialog = ({
const parentId = destination === "" ? null : destination;
try {
for (const item of items) {
if (item.type === "folder") await api.moveFolder(item.id, parentId);
else await api.moveFile(item.id, parentId);
if (item.type === "folder") await folderService.moveFolder(item.id, parentId);
else await fileService.moveFile(item.id, parentId);
}
onDone();
} catch (caught) {
@@ -297,8 +295,8 @@ export const ShareDialog = ({
const load = async () => {
try {
const [{ permissions: list }, { users }] = await Promise.all([
api.folderPermissions(folder.id),
api.directory(),
folderService.folderPermissions(folder.id),
directoryService.directory(),
]);
setPermissions(list);
setMembers(users);
@@ -312,7 +310,6 @@ export const ShareDialog = ({
useEffect(() => {
void load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [folder.id]);
const candidates = (members ?? []).filter(
@@ -325,7 +322,7 @@ export const ShareDialog = ({
setError(null);
try {
const iso = expiresAt ? new Date(expiresAt).toISOString() : null;
await api.grantPermission(folder.id, email, level, expiresAt ? iso : null);
await folderService.grantPermission(folder.id, email, level, expiresAt ? iso : null);
setEmail("");
setExpiresAt("");
await load();
@@ -339,7 +336,7 @@ export const ShareDialog = ({
const revoke = async (userId: string) => {
setError(null);
try {
await api.revokePermission(folder.id, userId);
await folderService.revokePermission(folder.id, userId);
await load();
} catch (caught) {
setError(messageOf(caught, t("Révocation impossible.")));
+1 -1
View File
@@ -1,6 +1,6 @@
import { useEffect, useMemo, type ReactNode } from "react";
import { cn } from "../ui/index.js";
import { useI18n } from "../lib/i18n.js";
import { useI18n } from "../contexts/I18nContext.js";
import { CloseIcon } from "./icons.js";
import { usePageHeader } from "./AppShell.js";
+1 -1
View File
@@ -6,7 +6,7 @@ import {
type ReactNode,
} from "react";
import { cn } from "../ui/index.js";
import { useI18n } from "../lib/i18n.js";
import { useI18n } from "../contexts/I18nContext.js";
import { CloseIcon } from "./icons.js";
type ToastTone = "success" | "error" | "info";
@@ -5,16 +5,10 @@ import {
useMemo,
type ReactNode,
} from "react";
import type { Language } from "./api.js";
import { setLanguage } from "./locale.js";
import type { Language } from "../types/index.js";
import { setLanguage } from "../lib/locale.js";
/**
* Traduction par clef de source : la chaine francaise sert de clef, le
* dictionnaire anglais fournit la variante. Une clef absente retombe sur le
* francais, donc un oubli ne casse jamais l'interface.
*/
const en: Record<string, string> = {
// --- Commun ------------------------------------------------------------
"Annuler": "Cancel",
"Enregistrer": "Save",
"Créer": "Create",
@@ -50,7 +44,6 @@ const en: Record<string, string> = {
"Chargement des dossiers…": "Loading folders…",
"Chargement des partages impossible.": "Unable to load shares.",
// --- Navigation / coque ------------------------------------------------
"Fichiers": "Files",
"Favoris": "Favorites",
"Recherche": "Search",
@@ -65,7 +58,6 @@ const en: Record<string, string> = {
"Fermer le menu": "Close menu",
"Ouvrir le menu": "Open menu",
// --- Connexion ---------------------------------------------------------
"Connectez-vous pour accéder à vos fichiers.": "Sign in to access your files.",
"Connexion": "Sign in",
"Votre session reste ouverte 14 jours.": "Your session stays open for 14 days.",
@@ -74,7 +66,6 @@ const en: Record<string, string> = {
"Se connecter": "Sign in",
"Mot de passe oublié ?": "Forgot your password?",
// --- Mot de passe oublié ----------------------------------------------
"Mot de passe oublié": "Forgot password",
"Réinitialisation": "Reset",
"Nous vous enverrons un lien valable une heure.": "We will email you a link valid for one hour.",
@@ -83,7 +74,6 @@ const en: Record<string, string> = {
"Retour à la connexion": "Back to sign in",
"Envoyer le lien": "Send link",
// --- Réinitialisation --------------------------------------------------
"Nouveau mot de passe": "New password",
"Choisissez un mot de passe robuste.": "Choose a strong password.",
"Ce lien est incomplet ou invalide.": "This link is incomplete or invalid.",
@@ -95,12 +85,10 @@ const en: Record<string, string> = {
"Réinitialiser": "Reset",
"Les deux mots de passe ne correspondent pas.": "The two passwords do not match.",
// --- Changement d'adresse ---------------------------------------------
"Changement d'adresse": "Email change",
"Votre adresse e-mail a été mise à jour.": "Your email address has been updated.",
"Accéder à mes fichiers": "Go to my files",
// --- Changement de mot de passe ---------------------------------------
"Bienvenue {name}. Ce mot de passe a été défini par un administrateur : choisissez le vôtre.":
"Welcome {name}. This password was set by an administrator: choose your own.",
"Changement requis": "Change required",
@@ -109,7 +97,6 @@ const en: Record<string, string> = {
"Mot de passe actuel": "Current password",
"Se déconnecter": "Sign out",
// --- Explorateur -------------------------------------------------------
"Racine": "Root",
"Vos dossiers et fichiers. Envoyez un fichier ou créez un dossier.":
"Your folders and files. Upload a file or create a folder.",
@@ -138,7 +125,6 @@ const en: Record<string, string> = {
"ce fichier": "this file",
"Placer {name} ({kind}) dans la corbeille ?": "Move {name} ({kind}) to the trash?",
// --- Boites de dialogue ------------------------------------------------
"Lecture": "Read",
"Écriture": "Write",
"Nom": "Name",
@@ -162,7 +148,6 @@ const en: Record<string, string> = {
"Épinglage impossible.": "Unable to pin.",
"Envoi du message impossible.": "Unable to send the message.",
// --- Discussion de dossier --------------------------------------------
"Compte supprimé": "Deleted account",
"Supprimer le message": "Delete message",
"Ce message sera retiré du salon pour tout le monde.":
@@ -189,7 +174,6 @@ const en: Record<string, string> = {
"Désépingler le message": "Unpin message",
"Messages épinglés": "Pinned messages",
// --- Explorateur / drag & drop -----------------------------------------
"Déposez vos fichiers ici": "Drop your files here",
"{count} fichier(s) déposé(s) dans {name}.": "{count} file(s) uploaded to {name}.",
"{count} fichier(s) déposé(s) dans ce dossier.": "{count} file(s) uploaded to this folder.",
@@ -197,7 +181,6 @@ const en: Record<string, string> = {
"Envoi {current}/{total}…": "Uploading {current}/{total}…",
"{current}/{total}": "{current}/{total}",
// --- Sélection multiple -----------------------------------------------
"Sélectionner {name}": "Select {name}",
"{count} élément(s) sélectionné(s).": "{count} item(s) selected.",
"Annuler la sélection": "Clear selection",
@@ -208,7 +191,6 @@ const en: Record<string, string> = {
"Seuls les fichiers peuvent être téléchargés.": "Only files can be downloaded.",
"Les dossiers n'ont pas été téléchargés.": "Folders were not downloaded.",
// --- Visionneuse -------------------------------------------------------
"Lecture impossible.": "Unable to read.",
"Ouvrir": "Open",
"Le PDF s'ouvre dans un nouvel onglet.": "The PDF opens in a new tab.",
@@ -216,14 +198,12 @@ const en: Record<string, string> = {
"Fichier précédent": "Previous file",
"Fichier suivant": "Next file",
// --- Favoris -----------------------------------------------------------
"Les fichiers que vous avez étoilés, tous dossiers confondus.":
"The files you starred, across all folders.",
"Aucun favori": "No favorites",
"Étoilez un fichier dans l'explorateur pour le retrouver ici.":
"Star a file in the browser to find it here.",
// --- Recherche ---------------------------------------------------------
"Saisissez au moins deux caractères.": "Enter at least two characters.",
"Recherchez par nom dans les dossiers et fichiers auxquels vous avez accès.":
"Search by name in the folders and files you can access.",
@@ -234,7 +214,6 @@ const en: Record<string, string> = {
"Aucun résultat": "No results",
"Rien ne correspond à « {q} ».": "Nothing matches “{q}”.",
// --- Galerie -----------------------------------------------------------
"Tout": "All",
"Images": "Images",
"Vidéos": "Videos",
@@ -247,7 +226,6 @@ const en: Record<string, string> = {
"Aucun média": "No media",
"Rien à afficher pour ce filtre.": "Nothing to show for this filter.",
// --- Corbeille ---------------------------------------------------------
"Vider la corbeille": "Empty trash",
"Tous les éléments seront définitivement supprimés. Cette action est irréversible.":
"All items will be permanently deleted. This action cannot be undone.",
@@ -266,7 +244,6 @@ const en: Record<string, string> = {
"Restaurer {name}": "Restore {name}",
"Supprimer définitivement {name}": "Permanently delete {name}",
// --- Compte ------------------------------------------------------------
"Profil, photo, adresse e-mail et sessions ouvertes.":
"Profile, photo, email address and open sessions.",
"Identité": "Identity",
@@ -298,7 +275,6 @@ const en: Record<string, string> = {
"Fermer la session en cours vous déconnectera immédiatement.":
"Closing the current session will sign you out immediately.",
// --- Préférences -------------------------------------------------------
"Préférences": "Preferences",
"Apparence et langue de l'interface.": "Interface appearance and language.",
"Thème": "Theme",
@@ -308,7 +284,6 @@ const en: Record<string, string> = {
"Langue": "Language",
"Préférences enregistrées.": "Preferences saved.",
// --- Administration ----------------------------------------------------
"Créer des membres, ajustez leurs quotas et gérez les accès.":
"Create members, adjust their quotas and manage access.",
"Nouveau membre": "New member",
@@ -382,9 +357,6 @@ export const I18nProvider = ({
language: Language;
children: ReactNode;
}) => {
// La langue est poussee dans le module des que le provider rend : les
// formatages (`formatBytes`, `formatDate`) lisent cette valeur partagee, en
// dehors de React. L'appel est idempotent.
setLanguage(language);
const t = useCallback<Translate>(
@@ -7,7 +7,8 @@ import {
useState,
type ReactNode,
} from "react";
import { api, type User } from "./api.js";
import type { User } from "../types/index.js";
import { authService } from "../services/authService.js";
interface SessionValue {
user: User | null;
@@ -25,7 +26,7 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
const refresh = useCallback(async () => {
try {
const { user: current } = await api.me();
const { user: current } = await authService.me();
setUser(current);
} catch {
setUser(null);
@@ -39,7 +40,7 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
}, [refresh]);
const logout = useCallback(async () => {
await api.logout().catch(() => undefined);
await authService.logout().catch(() => undefined);
setUser(null);
}, []);
@@ -1,5 +1,5 @@
import { useEffect, type ReactNode } from "react";
import type { Theme } from "./api.js";
import type { Theme } from "../types/index.js";
const STORAGE_KEY = "cohaise-theme";
@@ -10,11 +10,6 @@ const prefersDark = (): boolean =>
const isDark = (theme: Theme): boolean =>
theme === "dark" || (theme === "system" && prefersDark());
/**
* Applique le theme choisi dans le compte sur la racine du document. Le meme
* choix est recopie dans `localStorage` pour que `public/theme.js` reproduise
* le rendu des le premier pixel, avant que React ne demarre.
*/
export const ThemeProvider = ({ theme, children }: { theme: Theme; children: ReactNode }) => {
useEffect(() => {
const apply = () => {
@@ -24,7 +19,6 @@ export const ThemeProvider = ({ theme, children }: { theme: Theme; children: Rea
try {
localStorage.setItem(STORAGE_KEY, theme);
} catch {
/* stockage indisponible : le rendu reste correct */
}
if (theme !== "system") return undefined;
-639
View File
@@ -1,639 +0,0 @@
import { getLanguage, getLocale } from "./locale";
export type Theme = "system" | "light" | "dark";
export type Language = "fr" | "en";
export interface User {
id: string;
email: string;
first_name: string;
last_name: string;
role_slug: string;
role_name: string;
quota_bytes: number;
used_bytes: number;
max_file_bytes: number;
must_change_password: boolean;
theme: Theme;
language: Language;
has_avatar: boolean;
avatar_updated_at: string | null;
}
export interface Folder {
id: string;
parent_id: string | null;
name: string;
owner_id: string | null;
access_type: string;
is_system: boolean;
created_at: string;
updated_at: string;
}
export interface UploadedFile {
id: string;
folder_id: string | null;
name: string;
mime_type: string | null;
size_bytes: number;
checksum_sha256: string | null;
owner_id: string | null;
is_starred: boolean;
download_count: number;
created_at: string;
updated_at: string;
}
/** Etat d'une session d'envoi resumable, cote serveur. */
export interface UploadSession {
uploadId: string;
name: string;
folderId: string | null;
size: number;
chunkSize: number;
uploadedBytes: number;
expiresAt: string;
}
/** Au-dela de ce seuil, l'envoi passe par des morceaux de 50 MiB. */
export const LARGE_UPLOAD_THRESHOLD = 90 * 1024 * 1024;
export interface FavoriteFile extends UploadedFile {
folder_name: string | null;
}
export interface FolderPermission {
user_id: string;
email: string;
first_name: string;
last_name: string;
level: string;
expires_at: string | null;
created_at: string;
}
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;
}
export interface TrashFolder {
id: string;
parent_id: string | null;
name: string;
owner_id: string | null;
access_type: string;
created_at: string;
updated_at: string;
deleted_at: string;
}
export interface TrashFile {
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 MediaItem {
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;
}
export interface AdminUser {
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: boolean;
must_change_password: boolean;
last_login_at: string | null;
created_at: string;
}
export interface StorageLocation {
id: number;
name: string;
slug: string;
mount_path: string;
quota_bytes: number | null;
used_bytes: number;
is_active: boolean;
created_at: string;
}
export interface AdminStats {
users: number;
folders: number;
files: number;
usedBytes: number;
trashFiles: number;
locations: { id: number; name: string; used_bytes: number; quota_bytes: number | null }[];
}
export interface AuditEntry {
id: number;
user_id: string | null;
user_email: string | null;
action: string;
resource: string;
resource_id: string | null;
details: string | null;
ip_address: string | null;
created_at: string;
}
export interface ChatMember {
id: string;
first_name: string;
last_name: string;
role_slug: string;
has_avatar: boolean;
avatar_updated_at: string | null;
last_login_at: string | null;
is_self: boolean;
}
export interface ChatMessage {
id: number;
user_id: string | null;
first_name: string | null;
last_name: string | null;
body: string;
created_at: string;
edited_at: string | null;
is_pinned: boolean;
has_avatar: boolean;
avatar_updated_at: string | null;
}
export interface DirectoryUser {
id: string;
first_name: string;
last_name: string;
email: string;
has_avatar: boolean;
avatar_updated_at: string | null;
}
export class ApiError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.name = "ApiError";
this.status = status;
}
}
const BASE = "/api/cloud";
const messageOf = (body: unknown, fallback: string): string =>
(body as { error?: { message?: string } } | null)?.error?.message ?? fallback;
/**
* Un seul point d'entree HTTP. Le cookie de session est envoye
* automatiquement (same-origin), et toute erreur non-2xx devient une
* ApiError portant le message serveur, jamais un corps brut.
*/
const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
let response: Response;
try {
response = await fetch(`${BASE}${path}`, {
credentials: "same-origin",
...init,
headers: {
...(init?.body ? { "content-type": "application/json" } : {}),
...init?.headers,
},
});
} catch {
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
}
const body: unknown = await response.json().catch(() => null);
if (!response.ok) throw new ApiError(response.status, messageOf(body, "Une erreur est survenue."));
return body as T;
};
const post = <T>(path: string, payload?: unknown): Promise<T> =>
request<T>(path, {
method: "POST",
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
});
const patch = <T>(path: string, payload: unknown): Promise<T> =>
request<T>(path, { method: "PATCH", body: JSON.stringify(payload) });
const put = <T>(path: string, payload?: unknown): Promise<T> =>
request<T>(path, {
method: "PUT",
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
});
const del = <T>(path: string): Promise<T> => request<T>(path, { method: "DELETE" });
const query = (params: Record<string, string | number | null | undefined>): string => {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== null && value !== undefined && value !== "") search.set(key, String(value));
}
const suffix = search.toString();
return suffix ? `?${suffix}` : "";
};
/** Envoi d'un corps brut (fichier, image), hors JSON. */
const putBinary = async <T>(path: string, body: BodyInit, type: string): Promise<T> => {
let response: Response;
try {
response = await fetch(`${BASE}${path}`, {
method: "PUT",
credentials: "same-origin",
headers: type ? { "content-type": type } : {},
body,
});
} catch {
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
}
const parsed: unknown = await response.json().catch(() => null);
if (!response.ok) throw new ApiError(response.status, messageOf(parsed, "L'envoi a echoue."));
return parsed as T;
};
/**
* Identifiant de reprise, stocke localement : si l'onglet est ferme pendant un
* gros envoi, le meme fichier reprend a l'octet pres au lieu de repartir de
* zero. La cle inclut la date de modification pour ne pas confondre deux
* fichiers homonymes.
*/
const resumeKey = (file: File, folderId: string | null): string =>
`cohaise.upload:${folderId ?? "root"}:${file.name}:${file.size}:${file.lastModified}`;
const readResume = (key: string): string | null => {
try {
return window.localStorage.getItem(key);
} catch {
return null;
}
};
const writeResume = (key: string, uploadId: string): void => {
try {
window.localStorage.setItem(key, uploadId);
} catch {
/* navigation privee : la reprise inter-onglets est simplement indisponible */
}
};
const clearResume = (key: string): void => {
try {
window.localStorage.removeItem(key);
} catch {
/* voir writeResume */
}
};
/** Envoi d'un morceau en XHR : `fetch` n'expose pas la progression montante. */
const sendChunk = (
uploadId: string,
blob: Blob,
onProgress: (loaded: number) => void,
): Promise<void> =>
new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("PUT", `${BASE}/uploads/${encodeURIComponent(uploadId)}/chunks`);
xhr.withCredentials = true;
xhr.setRequestHeader("content-type", "application/octet-stream");
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) onProgress(event.loaded);
};
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve();
return;
}
let parsed: unknown = null;
try {
parsed = JSON.parse(xhr.responseText);
} catch {
/* reponse non JSON : message generique */
}
reject(new ApiError(xhr.status, messageOf(parsed, "L'envoi du morceau a echoue.")));
};
xhr.onerror = () => reject(new ApiError(0, "Serveur injoignable. Verifiez votre connexion."));
xhr.onabort = () => reject(new ApiError(0, "Envoi interrompu."));
xhr.send(blob);
});
const sessionPath = (uploadId: string): string => `/uploads/${encodeURIComponent(uploadId)}`;
/**
* Envoi resumable en morceaux de 50 MiB. Chaque morceau reste sous la limite
* de corps de requete de Cloudflare ; le serveur ne publie le fichier qu'une
* fois tous les morceaux recus et le nom verifie.
*/
const uploadFileResumable = async (
file: File,
folderId: string | null,
onProgress?: (loaded: number, total: number) => void,
): Promise<{ file: UploadedFile }> => {
const key = resumeKey(file, folderId);
let upload: UploadSession | null = null;
const saved = readResume(key);
if (saved !== null) {
try {
const result = await request<{ upload: UploadSession }>(sessionPath(saved));
if (result.upload.name === file.name && result.upload.size === file.size) {
upload = result.upload;
} else {
clearResume(key);
}
} catch (error) {
if (error instanceof ApiError && error.status === 404) clearResume(key);
else throw error;
}
}
if (upload === null) {
const result = await post<{ upload: UploadSession }>("/uploads", {
name: file.name,
folderId,
size: file.size,
mimeType: file.type || null,
});
upload = result.upload;
writeResume(key, upload.uploadId);
}
const uploadId = upload.uploadId;
let offset = upload.uploadedBytes;
let attempts = 0;
while (offset < file.size) {
const end = Math.min(offset + upload.chunkSize, file.size);
try {
await sendChunk(uploadId, file.slice(offset, end), (loaded) =>
onProgress?.(offset + loaded, file.size),
);
offset = end;
attempts = 0;
} catch (error) {
const transient =
!(error instanceof ApiError) ||
error.status === 0 ||
error.status === 409 ||
error.status >= 500;
attempts += 1;
if (!transient || attempts > 4) throw error;
// Laisse au serveur le temps de terminer (ou d'annuler) le morceau
// avant de lui demander ou en est reellement le curseur.
await new Promise((resolve) => setTimeout(resolve, 400 * attempts));
const status = await request<{ upload: UploadSession }>(sessionPath(uploadId));
if (status.upload.name !== file.name || status.upload.size !== file.size) {
throw new ApiError(409, "La session d'envoi ne correspond plus au fichier.");
}
offset = status.upload.uploadedBytes;
}
}
onProgress?.(file.size, file.size);
const result = await post<{ file: UploadedFile }>(`${sessionPath(uploadId)}/complete`);
clearResume(key);
return result;
};
export const api = {
// --- Session -----------------------------------------------------------
me: () => request<{ user: User }>("/auth/me"),
login: (email: string, password: string) =>
post<{ user: User }>("/auth/login", { email, password }),
logout: () => post<{ ok: boolean }>("/auth/logout"),
changePassword: (current: string, next: string) =>
post<{ ok: boolean }>("/auth/change-password", { current, next }),
forgotPassword: (email: string) => post<{ ok: boolean }>("/account/forgot-password", { email }),
resetPassword: (token: string, password: string) =>
post<{ ok: boolean }>("/account/reset-password", { token, password }),
requestEmailChange: (password: string, new_email: string) =>
post<{ ok: boolean }>("/account/email-change", { password, new_email }),
confirmEmailChange: (token: string) =>
post<{ ok: boolean; email: string }>("/account/email-change/confirm", { token }),
// --- Compte ------------------------------------------------------------
updateProfile: (first_name: string, last_name: string) =>
patch<{ ok: boolean }>("/account/profile", { first_name, last_name }),
preferences: () => request<{ theme: Theme; language: Language }>("/account/preferences"),
updatePreferences: (theme: Theme, language: Language) =>
patch<{ theme: Theme; language: Language }>("/account/preferences", { theme, language }),
sessions: () => request<{ sessions: SessionInfo[] }>("/account/sessions"),
revokeSession: (id: string) => del<{ ok: boolean }>(`/account/sessions/${encodeURIComponent(id)}`),
revokeOtherSessions: () => del<{ ok: boolean }>("/account/sessions"),
avatarUrl: (userId: string) => `${BASE}/account/avatar/${encodeURIComponent(userId)}`,
uploadAvatar: (file: File) => putBinary<{ ok: boolean }>("/account/avatar", file, file.type),
deleteAvatar: () => del<{ ok: boolean }>("/account/avatar"),
directory: () => request<{ users: DirectoryUser[] }>("/directory"),
// --- Dossiers ----------------------------------------------------------
folders: (parentId?: string | null) =>
request<{ parentId: string | null; folders: Folder[] }>(
`/folders${query({ parentId })}`,
),
createFolder: (name: string, parentId?: string | null) =>
post<{ folder: Folder }>("/folders", { name, parentId: parentId ?? null }),
updateFolder: (id: string, name: string) =>
patch<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}`, { name }),
moveFolder: (id: string, parentId: string | null) =>
post<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}/move`, { parentId }),
deleteFolder: (id: string) => del<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}`),
folderPermissions: (id: string) =>
request<{ permissions: FolderPermission[] }>(
`/folders/${encodeURIComponent(id)}/permissions`,
),
grantPermission: (id: string, email: string, level: string, expiresAt: string | null) =>
post<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}/permissions`, {
email,
level,
expiresAt,
}),
revokePermission: (id: string, userId: string) =>
del<{ ok: boolean }>(
`/folders/${encodeURIComponent(id)}/permissions/${encodeURIComponent(userId)}`,
),
// --- Fichiers ----------------------------------------------------------
files: (folderId?: string | null) =>
request<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`),
uploadFile: (
file: File,
folderId: string | null,
onProgress?: (loaded: number, total: number) => void,
) => {
if (file.size >= LARGE_UPLOAD_THRESHOLD) {
return uploadFileResumable(file, folderId, onProgress);
}
return putBinary<{ file: UploadedFile }>(
`/files${query({ name: file.name, folderId })}`,
file,
file.type,
).then((result) => {
onProgress?.(file.size, file.size);
return result;
});
},
uploadSession: (uploadId: string) =>
request<{ upload: UploadSession }>(sessionPath(uploadId)),
cancelUpload: (uploadId: string) => del<{ ok: boolean }>(sessionPath(uploadId)),
renameFile: (id: string, name: string) =>
patch<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}`, { name }),
moveFile: (id: string, folderId: string | null) =>
post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }),
starFile: (id: string) =>
request<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`, { method: "PUT" }),
favorites: () => request<{ files: FavoriteFile[] }>("/favorites"),
deleteFile: (id: string) => del<{ ok: boolean }>(`/files/${encodeURIComponent(id)}`),
downloadUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/download`,
thumbnailUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/thumbnail`,
previewUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/preview`,
// --- Corbeille, recherche, galerie ------------------------------------
trash: () =>
request<{ retentionDays: number; folders: TrashFolder[]; files: TrashFile[] }>("/trash"),
restoreFolder: (id: string) =>
post<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}/restore`),
restoreFile: (id: string) =>
post<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}/restore`),
purgeFolder: (id: string) => del<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}`),
purgeFile: (id: string) => del<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}`),
emptyTrash: () => del<{ ok: boolean }>("/trash"),
search: (q: string) =>
request<{ query: string; folders: Folder[]; files: UploadedFile[] }>(`/search${query({ q })}`),
gallery: (kind: string, limit = 60, offset = 0) =>
request<{ kind: string | null; items: MediaItem[] }>(
`/media${query({ kind, limit, offset })}`,
),
// --- Chat d'un dossier ------------------------------------------------
chatMembers: (folderId: string) =>
request<{ members: ChatMember[] }>(`/folders/${encodeURIComponent(folderId)}/chat/members`),
chatMessages: (folderId: string, after = 0, limit = 50, editedAfter?: string | null) =>
request<{ messages: ChatMessage[]; cursor: string }>(
`/folders/${encodeURIComponent(folderId)}/chat/messages${query({ after, limit, editedAfter })}`,
),
chatSend: (folderId: string, body: string) =>
post<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages`, { body }),
chatEditMessage: (folderId: string, id: number, body: string) =>
patch<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`, {
body,
}),
chatTogglePin: (folderId: string, id: number) =>
put<{ pinned: boolean }>(
`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}/pin`,
),
chatPins: (folderId: string) =>
request<{ messages: ChatMessage[] }>(`/folders/${encodeURIComponent(folderId)}/chat/pins`),
chatDeleteMessage: (folderId: string, id: number) =>
del<{ ok: boolean }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`),
chatUnread: () => request<{ unread: Record<string, number> }>("/chat/unread"),
// --- Administration ----------------------------------------------------
adminStats: () => request<AdminStats>("/admin/stats"),
adminUsers: (q?: string) =>
request<{ users: AdminUser[] }>(`/admin/users${query({ q })}`),
adminCreateUser: (payload: {
email: string;
first_name: string;
last_name: string;
role_slug: string;
quota_bytes?: number | null;
max_file_bytes?: number | null;
}) => post<{ user: AdminUser }>("/admin/users", payload),
adminUpdateUser: (
id: string,
payload: Partial<{
first_name: string;
last_name: string;
role_slug: string;
quota_bytes: number;
max_file_bytes: number;
is_active: boolean;
}>,
) => patch<{ user: AdminUser }>(`/admin/users/${encodeURIComponent(id)}`, payload),
adminDeleteUser: (id: string) => del<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}`),
adminResetPassword: (id: string) =>
post<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}/reset-password`),
adminStorageLocations: () =>
request<{ locations: StorageLocation[] }>("/admin/storage-locations"),
adminCreateStorageLocation: (payload: {
name: string;
slug: string;
mount_path: string;
quota_bytes?: number | null;
}) => post<{ ok: boolean }>("/admin/storage-locations", payload),
adminUpdateStorageLocation: (
id: number,
payload: { name?: string; quota_bytes?: number | null; is_active?: boolean },
) => patch<{ ok: boolean }>(`/admin/storage-locations/${id}`, payload),
adminAudit: (limit = 100, offset = 0, action?: string, userId?: string) =>
request<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action, userId })}`),
adminAuditFilters: () =>
request<{ actions: string[]; users: { id: string; email: string | null }[] }>(
"/admin/audit/filters",
),
};
/** Octets en lecture humaine, sans precision inutile. */
export const formatBytes = (bytes: number): string => {
const english = getLanguage() === "en";
if (bytes < 1024) return `${bytes} ${english ? "B" : "o"}`;
const units = english ? ["KB", "MB", "GB", "TB"] : ["Ko", "Mo", "Go", "To"];
let value = bytes;
let index = -1;
do {
value /= 1024;
index += 1;
} while (value >= 1024 && index < units.length - 1);
return `${value.toLocaleString(getLocale(), { maximumFractionDigits: value < 10 ? 1 : 0 })} ${units[index]}`;
};
export const formatDate = (value: string | null): string =>
value ? new Date(value).toLocaleString(getLocale(), { dateStyle: "medium", timeStyle: "short" }) : "—";
/** Date et heure completes, avec les secondes : utilise au survol d'un mention. */
export const formatDateTimeSeconds = (value: string | null): string =>
value
? new Date(value).toLocaleString(getLocale(), {
day: "2-digit",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
})
: "—";
+1 -6
View File
@@ -1,10 +1,5 @@
import type { Language } from "./api";
import type { Language } from "../types/index.js";
/**
* Langue d'affichage courante, partagee par tout le module (hors composants
* React) : formatage des tailles et des dates. Le provider i18n la met a jour
* des qu'un utilisateur change de langue dans son compte.
*/
let language: Language = "fr";
export const getLanguage = (): Language => language;
-1
View File
@@ -1,6 +1,5 @@
export type MediaKind = "image" | "video" | "audio" | "document" | "archive" | "other";
/** Miroir de `classify()` cote backend, pour choisir la vignette d'un fichier. */
export const mediaKind = (mime: string | null): MediaKind => {
const value = (mime ?? "").toLowerCase();
if (value.startsWith("image/")) return "image";
+3 -7
View File
@@ -2,9 +2,9 @@ import { StrictMode, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { App } from "./App.js";
import { SessionProvider, useSession } from "./lib/session.js";
import { I18nProvider } from "./lib/i18n.js";
import { ThemeProvider } from "./lib/theme.js";
import { SessionProvider, useSession } from "./contexts/SessionContext.js";
import { I18nProvider } from "./contexts/I18nContext.js";
import { ThemeProvider } from "./contexts/ThemeContext.js";
import { ConfirmProvider } from "./components/confirm.js";
import { ToastProvider } from "./components/toast.js";
import "./styles/index.css";
@@ -15,10 +15,6 @@ if (!container) {
throw new Error("Element racine introuvable");
}
/**
* Enveloppe les preferences de la session (theme, langue) pour qu'elles
* s'appliquent a toute l'application, y compris aux ecrans hors coque.
*/
const Providers = ({ children }: { children: ReactNode }) => {
const { user } = useSession();
return (
+18 -26
View File
@@ -1,15 +1,10 @@
import { useEffect, useRef, useState, type FormEvent } from "react";
import { Button, Input, Spinner } from "../ui/index.js";
import {
ApiError,
api,
formatDate,
type AdminStats,
type AdminUser,
type AuditEntry,
type StorageLocation,
} from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { adminService } from "../services/adminService.js";
import { formatDate } from "../utils/format.js";
import type { AdminStats, AdminUser, AuditEntry, StorageLocation } from "../types/index.js";
import { useI18n } from "../contexts/I18nContext.js";
import { getLocale } from "../lib/locale.js";
import { Alert, Badge, EmptyState, Modal, PageHeader } from "../components/feedback.js";
import { useConfirm } from "../components/confirm.js";
@@ -63,7 +58,7 @@ export const AdminUsers = () => {
termRef.current = term;
setError(null);
try {
const { users: list } = await api.adminUsers(term || undefined);
const { users: list } = await adminService.adminUsers(term || undefined);
setUsers(list);
} catch (caught) {
setError(messageOf(caught, t("Chargement impossible.")));
@@ -73,18 +68,17 @@ export const AdminUsers = () => {
useEffect(() => {
void load("");
api
adminService
.adminStats()
.then(setStats)
.catch(() => undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const toggleActive = async (user: AdminUser) => {
setBusy(user.id);
setError(null);
try {
await api.adminUpdateUser(user.id, { is_active: !user.is_active });
await adminService.adminUpdateUser(user.id, { is_active: !user.is_active });
await load(termRef.current);
} catch (caught) {
setError(messageOf(caught, t("Mise à jour impossible.")));
@@ -98,7 +92,7 @@ export const AdminUsers = () => {
setError(null);
setNotice(null);
try {
await api.adminResetPassword(user.id);
await adminService.adminResetPassword(user.id);
setNotice(t("Mot de passe réinitialisé. Les identifiants ont été envoyés à {email}.", { email: user.email }));
} catch (caught) {
setError(messageOf(caught, t("Réinitialisation impossible.")));
@@ -120,7 +114,7 @@ export const AdminUsers = () => {
setBusy(user.id);
setError(null);
try {
await api.adminDeleteUser(user.id);
await adminService.adminDeleteUser(user.id);
await load(termRef.current);
} catch (caught) {
setError(messageOf(caught, t("Suppression impossible.")));
@@ -299,7 +293,7 @@ const CreateUserDialog = ({
setBusy(true);
setError(null);
try {
const { user } = await api.adminCreateUser({
const { user } = await adminService.adminCreateUser({
email: email.trim(),
first_name: firstName.trim(),
last_name: lastName.trim(),
@@ -417,7 +411,7 @@ const EditUserDialog = ({
setBusy(true);
setError(null);
try {
await api.adminUpdateUser(user.id, {
await adminService.adminUpdateUser(user.id, {
first_name: firstName.trim(),
last_name: lastName.trim(),
role_slug: role,
@@ -512,7 +506,7 @@ export const AdminStorage = () => {
const load = async () => {
setError(null);
try {
const { locations: list } = await api.adminStorageLocations();
const { locations: list } = await adminService.adminStorageLocations();
setLocations(list);
} catch (caught) {
setError(messageOf(caught, t("Chargement impossible.")));
@@ -522,13 +516,12 @@ export const AdminStorage = () => {
useEffect(() => {
void load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const toggle = async (location: StorageLocation) => {
setError(null);
try {
await api.adminUpdateStorageLocation(location.id, { is_active: !location.is_active });
await adminService.adminUpdateStorageLocation(location.id, { is_active: !location.is_active });
await load();
} catch (caught) {
setError(messageOf(caught, t("Mise à jour impossible.")));
@@ -622,7 +615,7 @@ const CreateLocationDialog = ({
setBusy(true);
setError(null);
try {
await api.adminCreateStorageLocation({
await adminService.adminCreateStorageLocation({
name: name.trim(),
slug: slug.trim(),
mount_path: mountPath.trim(),
@@ -708,7 +701,7 @@ export const AdminAudit = () => {
const load = async (nextAction: string, nextUser: string) => {
setError(null);
try {
const { entries: list } = await api.adminAudit(
const { entries: list } = await adminService.adminAudit(
100,
0,
nextAction || undefined,
@@ -723,11 +716,10 @@ export const AdminAudit = () => {
useEffect(() => {
void load("", "");
void api
void adminService
.adminAuditFilters()
.then(setFilters)
.catch(() => undefined);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const apply = (nextAction: string, nextUser: string) => {
@@ -742,7 +734,7 @@ export const AdminAudit = () => {
setLoadingMore(true);
setError(null);
try {
const { entries: more } = await api.adminAudit(
const { entries: more } = await adminService.adminAudit(
100,
entries.length,
action || undefined,
+20 -50
View File
@@ -6,15 +6,14 @@ import {
type DragEvent,
} from "react";
import { Card, Spinner, cn } from "../ui/index.js";
import {
ApiError,
api,
formatBytes,
type Folder,
type UploadedFile,
} from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { chatService } from "../services/chatService.js";
import { fileService } from "../services/fileService.js";
import { folderService } from "../services/folderService.js";
import { formatBytes } from "../utils/format.js";
import type { Folder, UploadedFile } from "../types/index.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import { getLocale } from "../lib/locale.js";
import { mediaKind } from "../lib/media.js";
import { EmptyState, PageHeader } from "../components/feedback.js";
@@ -71,8 +70,6 @@ const KINDS = [
{ value: "other", label: "Autres" },
] as const;
// Rafraichissement de l'explorateur : un autre compte peut deposer ou
// supprimer un fichier dans un dossier partage sans prevenir.
const REFRESH_FOLDER_MS = 60_000;
export const Browser = () => {
@@ -95,9 +92,6 @@ export const Browser = () => {
const [unread, setUnread] = useState<Record<string, number>>({});
const [kind, setKind] = useState<string>("");
const fileInputRef = useRef<HTMLInputElement>(null);
// Depot par glisser-deposer : `dragDepth` compte les entrees et sorties
// successives. La garde `stillInside` evite en plus que la zone clignote
// quand le pointeur passe d'un element enfant a un autre.
const [dragDepth, setDragDepth] = useState(0);
const [dropTargetId, setDropTargetId] = useState<string | null>(null);
const [selected, setSelected] = useState<Set<string>>(new Set());
@@ -119,8 +113,8 @@ export const Browser = () => {
setError(null);
try {
const [folderResult, fileResult] = await Promise.all([
api.folders(parentId),
api.files(parentId),
folderService.folders(parentId),
fileService.files(parentId),
]);
if (sequence !== loadSeq.current) return;
setFolders(folderResult.folders);
@@ -131,8 +125,6 @@ export const Browser = () => {
caught instanceof ApiError
? caught.message
: t("Chargement impossible.");
// Un rafraichissement automatique echoue en silence : pas de toast
// toutes les minutes si le reseau tombe pendant la consultation.
if (!options?.silent) {
setError(msg);
toast.error(msg);
@@ -148,10 +140,9 @@ export const Browser = () => {
const refreshUnread = useCallback(async () => {
try {
const { unread: counts } = await api.chatUnread();
const { unread: counts } = await chatService.chatUnread();
setUnread(counts);
} catch {
/* les pastilles sont un confort : un echec ne bloque pas l'explorateur */
}
}, []);
@@ -163,8 +154,6 @@ export const Browser = () => {
void refreshUnread();
}, [current.id, refreshUnread]);
// Un autre compte peut deposer ou supprimer un fichier dans un dossier
// partage : la vue se resynchronise d'elle-meme tant que l'onglet est actif.
useEffect(() => {
const timer = window.setInterval(() => {
if (document.hidden) return;
@@ -175,8 +164,6 @@ export const Browser = () => {
return () => window.clearInterval(timer);
}, [chat, current.id, dialog, load, refreshUnread, uploading, viewer]);
// Le filtre de type n'est propre qu'au dossier affiche : on repart sur
// « Tout » a chaque navigation, faute de voir un dossier vide pour rien.
useEffect(() => {
setKind("");
}, [current.id]);
@@ -217,7 +204,7 @@ export const Browser = () => {
for (let i = 0; i < filesArr.length; i++) {
const f = filesArr[i] as File;
update(i + 1, 0);
await api.uploadFile(f, current.id, (loaded) => update(i + 1, loaded));
await fileService.uploadFile(f, current.id, (loaded) => update(i + 1, loaded));
completedBytes += f.size;
}
void refresh();
@@ -234,11 +221,6 @@ export const Browser = () => {
}
};
/**
* Depot d'un lot de fichiers dans un dossier precis. Le dossier peut etre le
* dossier affiche ou l'un des sous-dossiers listes ; le serveur revalide les
* droits d'ecriture dans tous les cas.
*/
const uploadInto = async (
selectedFiles: FileList | null,
folderId: string | null,
@@ -259,12 +241,10 @@ export const Browser = () => {
for (let i = 0; i < filesArr.length; i++) {
const f = filesArr[i] as File;
update(i + 1, 0);
await api.uploadFile(f, folderId, (loaded) => update(i + 1, loaded));
await fileService.uploadFile(f, folderId, (loaded) => update(i + 1, loaded));
completedBytes += f.size;
}
void refresh();
// Seule la vue courante est rechargée : un depot dans un sous-dossier ne
// change rien a l'ecran tant qu'on ne l'ouvre pas.
if (folderId === current.id) await reload();
const msg = label
? t("{count} fichier(s) déposé(s) dans {name}.", {
@@ -287,15 +267,9 @@ export const Browser = () => {
}
};
/** Le glisser porte-t-il des fichiers (et non du texte ou une URL) ? */
const carriesFiles = (event: DragEvent): boolean =>
Array.from(event.dataTransfer.types).includes("Files");
/**
* Le pointeur est-il reste dans la zone qui recoit l'evenement ? Vrai quand
* le pointeur passe d'un enfant a un autre : sans cette garde, la zone
* clignoterait a chaque changement d element.
*/
const stillInside = (event: DragEvent): boolean => {
const related = event.relatedTarget as Node | null;
return related !== null && event.currentTarget.contains(related);
@@ -310,7 +284,6 @@ export const Browser = () => {
const onDragOver = (event: DragEvent) => {
if (!carriesFiles(event)) return;
// Sans preventDefault le navigateur refuse le depot.
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
};
@@ -330,7 +303,6 @@ export const Browser = () => {
void uploadInto(event.dataTransfer.files, current.id);
};
/** Cible precise : un sous-dossier de la liste courante. */
const onFolderDragOver = (event: DragEvent, folderId: string) => {
if (!carriesFiles(event)) return;
event.preventDefault();
@@ -372,9 +344,9 @@ export const Browser = () => {
setError(null);
try {
if (target.type === "folder") {
await api.deleteFolder(target.id);
await folderService.deleteFolder(target.id);
} else {
await api.deleteFile(target.id);
await fileService.deleteFile(target.id);
void refresh();
}
await reload();
@@ -403,8 +375,8 @@ export const Browser = () => {
setError(null);
try {
for (const target of selectedItems) {
if (target.type === "folder") await api.deleteFolder(target.id);
else await api.deleteFile(target.id);
if (target.type === "folder") await folderService.deleteFolder(target.id);
else await fileService.deleteFile(target.id);
}
clearSelection();
await reload();
@@ -422,7 +394,7 @@ export const Browser = () => {
const toggleStar = async (file: UploadedFile) => {
setError(null);
try {
const { file: updated } = await api.starFile(file.id);
const { file: updated } = await fileService.starFile(file.id);
setFiles((previous) =>
previous.map((item) => (item.id === updated.id ? updated : item)),
);
@@ -663,8 +635,6 @@ export const Browser = () => {
</div>
) : null}
{/* Alerts replaced by toasts */}
{canWrite && selectedItems.length > 0 ? (
<div className="fixed bottom-3 left-1/2 z-40 w-[calc(100%-1rem)] max-w-xl -translate-x-1/2 px-1 sm:bottom-4 sm:w-auto">
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-border-strong bg-surface/80 px-3 py-2 shadow-lg backdrop-blur-md sm:flex-row sm:flex-wrap sm:items-center sm:justify-center">
@@ -690,7 +660,7 @@ export const Browser = () => {
}
for (const target of files) {
const link = document.createElement("a");
link.href = api.downloadUrl(target.id);
link.href = fileService.downloadUrl(target.id);
link.download = target.name;
link.click();
}
@@ -934,7 +904,7 @@ export const Browser = () => {
/>
<a
href={api.downloadUrl(file.id)}
href={fileService.downloadUrl(file.id)}
download={file.name}
aria-label={t("Télécharger {name}", { name: file.name })}
title={t("Télécharger {name}", { name: file.name })}
+5 -4
View File
@@ -2,9 +2,10 @@ import { useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
import { Alert } from "../components/feedback.js";
import { ApiError, api } from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { authService } from "../services/authService.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
export const ChangePassword = () => {
const { user, refresh, logout } = useSession();
@@ -25,7 +26,7 @@ export const ChangePassword = () => {
setBusy(true);
setError(null);
try {
await api.changePassword(current, next);
await authService.changePassword(current, next);
await refresh();
navigate("/files", { replace: true });
} catch (caught) {
+5 -4
View File
@@ -2,9 +2,10 @@ import { useEffect, useRef, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { Button, Card, CardContent, CardHeader, CardTitle, Spinner } from "../ui/index.js";
import { Alert } from "../components/feedback.js";
import { ApiError, api } from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { accountService } from "../services/accountService.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
export const ConfirmEmail = () => {
const [params] = useSearchParams();
@@ -23,7 +24,7 @@ export const ConfirmEmail = () => {
setError(t("Ce lien est incomplet ou invalide."));
return;
}
api
accountService
.confirmEmailChange(token)
.then(() => {
setState("success");
+8 -5
View File
@@ -1,12 +1,15 @@
import { useEffect, useState } from "react";
import { Spinner } from "../ui/index.js";
import { ApiError, api, formatBytes, type FavoriteFile } from "../lib/api.js";
import { ApiError } from "../services/apiClient.js";
import { fileService } from "../services/fileService.js";
import { formatBytes } from "../utils/format.js";
import type { FavoriteFile } from "../types/index.js";
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
import { MediaViewer } from "../components/MediaViewer.js";
import { MediaThumb } from "../components/MediaThumb.js";
import { IconAction } from "../components/IconAction.js";
import { DownloadIcon, FolderIcon, StarIcon } from "../components/icons.js";
import { useI18n } from "../lib/i18n.js";
import { useI18n } from "../contexts/I18nContext.js";
export const Favorites = () => {
const { t } = useI18n();
@@ -17,7 +20,7 @@ export const Favorites = () => {
useEffect(() => {
setLoading(true);
void api
void fileService
.favorites()
.then(({ files: list }) => {
setFiles(list);
@@ -33,7 +36,7 @@ export const Favorites = () => {
const unstar = async (file: FavoriteFile) => {
setError(null);
try {
await api.starFile(file.id);
await fileService.starFile(file.id);
setFiles((previous) => previous.filter((item) => item.id !== file.id));
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Action impossible."));
@@ -90,7 +93,7 @@ export const Favorites = () => {
/>
<a
href={api.downloadUrl(file.id)}
href={fileService.downloadUrl(file.id)}
download={file.name}
aria-label={t("Télécharger {name}", { name: file.name })}
title={t("Télécharger {name}", { name: file.name })}
+4 -3
View File
@@ -2,8 +2,9 @@ import { useState, type FormEvent } from "react";
import { Link } from "react-router-dom";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
import { Alert } from "../components/feedback.js";
import { ApiError, api } from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { accountService } from "../services/accountService.js";
import { useI18n } from "../contexts/I18nContext.js";
export const ForgotPassword = () => {
const { t } = useI18n();
@@ -17,7 +18,7 @@ export const ForgotPassword = () => {
setBusy(true);
setError(null);
try {
await api.forgotPassword(email);
await accountService.forgotPassword(email);
setSent(true);
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Demande impossible."));
+7 -4
View File
@@ -1,11 +1,14 @@
import { useCallback, useEffect, useState } from "react";
import { Button, Spinner, cn } from "../ui/index.js";
import { ApiError, api, formatBytes, type MediaItem } from "../lib/api.js";
import { ApiError } from "../services/apiClient.js";
import { mediaService } from "../services/mediaService.js";
import { formatBytes } from "../utils/format.js";
import type { MediaItem } from "../types/index.js";
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
import { MediaViewer } from "../components/MediaViewer.js";
import { MediaThumb } from "../components/MediaThumb.js";
import { ImageIcon } from "../components/icons.js";
import { useI18n } from "../lib/i18n.js";
import { useI18n } from "../contexts/I18nContext.js";
const KINDS = [
{ value: "", label: "Tout" },
@@ -30,7 +33,7 @@ export const Gallery = () => {
useEffect(() => {
setLoading(true);
void api
void mediaService
.gallery(kind, PAGE, 0)
.then(({ items: first }) => {
setItems(first);
@@ -47,7 +50,7 @@ export const Gallery = () => {
setLoadingMore(true);
setError(null);
try {
const { items: more } = await api.gallery(kind, PAGE, items.length);
const { items: more } = await mediaService.gallery(kind, PAGE, items.length);
setItems((previous) => [...previous, ...more]);
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Chargement impossible."));
+5 -4
View File
@@ -1,9 +1,10 @@
import { useState, type FormEvent } from "react";
import { Link, Navigate, useNavigate } from "react-router-dom";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
import { ApiError, api } from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { authService } from "../services/authService.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
export const Login = () => {
const { user, setUser } = useSession();
@@ -21,7 +22,7 @@ export const Login = () => {
setBusy(true);
setError(null);
try {
const { user: current } = await api.login(email, password);
const { user: current } = await authService.login(email, password);
setUser(current);
navigate(current.must_change_password ? "/change-password" : "/files", { replace: true });
} catch (caught) {
+15 -13
View File
@@ -1,8 +1,11 @@
import { useEffect, useRef, useState, type FormEvent } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Spinner } from "../ui/index.js";
import { ApiError, api, formatDate, type Language, type SessionInfo, type Theme } from "../lib/api.js";
import { useSession } from "../lib/session.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { accountService } from "../services/accountService.js";
import { formatDate } from "../utils/format.js";
import type { Language, SessionInfo, Theme } from "../types/index.js";
import { useSession } from "../contexts/SessionContext.js";
import { useI18n } from "../contexts/I18nContext.js";
import { Alert, Badge, PageHeader } from "../components/feedback.js";
import { useConfirm } from "../components/confirm.js";
import { IconAction } from "../components/IconAction.js";
@@ -61,7 +64,7 @@ export const Profile = () => {
const loadSessions = async () => {
setSessionsError(null);
try {
const { sessions: list } = await api.sessions();
const { sessions: list } = await accountService.sessions();
setSessions(list);
} catch (caught) {
setSessionsError(caught instanceof ApiError ? caught.message : t("Chargement impossible."));
@@ -71,7 +74,6 @@ export const Profile = () => {
useEffect(() => {
void loadSessions();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const saveProfile = async (event: FormEvent<HTMLFormElement>) => {
@@ -80,7 +82,7 @@ export const Profile = () => {
setProfileError(null);
setProfileMessage(null);
try {
await api.updateProfile(firstName.trim(), lastName.trim());
await accountService.updateProfile(firstName.trim(), lastName.trim());
await refresh();
setProfileMessage(t("Informations enregistrées."));
} catch (caught) {
@@ -96,7 +98,7 @@ export const Profile = () => {
setPrefError(null);
setPrefMessage(null);
try {
await api.updatePreferences(theme, language);
await accountService.updatePreferences(theme, language);
await refresh();
setPrefMessage(t("Préférences enregistrées."));
} catch (caught) {
@@ -112,7 +114,7 @@ export const Profile = () => {
setEmailError(null);
setEmailMessage(null);
try {
await api.requestEmailChange(password, newEmail.trim());
await accountService.requestEmailChange(password, newEmail.trim());
setPassword("");
setNewEmail("");
setEmailMessage(t("Un e-mail de confirmation a été envoyé à la nouvelle adresse."));
@@ -127,7 +129,7 @@ export const Profile = () => {
if (!file) return;
setAvatarError(null);
try {
await api.uploadAvatar(file);
await accountService.uploadAvatar(file);
await refresh();
} catch (caught) {
setAvatarError(caught instanceof ApiError ? caught.message : t("Envoi impossible."));
@@ -139,7 +141,7 @@ export const Profile = () => {
const removeAvatar = async () => {
setAvatarError(null);
try {
await api.deleteAvatar();
await accountService.deleteAvatar();
await refresh();
} catch (caught) {
setAvatarError(caught instanceof ApiError ? caught.message : t("Suppression impossible."));
@@ -159,7 +161,7 @@ export const Profile = () => {
setRevoking(session.id);
setSessionsError(null);
try {
await api.revokeSession(session.id);
await accountService.revokeSession(session.id);
if (session.current) {
await refresh();
return;
@@ -175,7 +177,7 @@ export const Profile = () => {
const revokeOthers = async () => {
setSessionsError(null);
try {
await api.revokeOtherSessions();
await accountService.revokeOtherSessions();
setSessions((previous) => (previous ?? []).filter((item) => item.current));
} catch (caught) {
setSessionsError(caught instanceof ApiError ? caught.message : t("Révocation impossible."));
@@ -306,7 +308,7 @@ export const Profile = () => {
<div className="flex items-center gap-4">
<span className="flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-surface-muted">
<img
src={`${api.avatarUrl(user.id)}?v=${user.avatar_updated_at ?? ""}`}
src={`${accountService.avatarUrl(user.id)}?v=${user.avatar_updated_at ?? ""}`}
alt=""
className="h-full w-full object-cover"
onError={(event) => {
+4 -3
View File
@@ -2,8 +2,9 @@ import { useState, type FormEvent } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
import { Alert } from "../components/feedback.js";
import { ApiError, api } from "../lib/api.js";
import { useI18n } from "../lib/i18n.js";
import { ApiError } from "../services/apiClient.js";
import { accountService } from "../services/accountService.js";
import { useI18n } from "../contexts/I18nContext.js";
export const ResetPassword = () => {
const { t } = useI18n();
@@ -24,7 +25,7 @@ export const ResetPassword = () => {
setBusy(true);
setError(null);
try {
await api.resetPassword(token, password);
await accountService.resetPassword(token, password);
setDone(true);
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Réinitialisation impossible."));
+8 -4
View File
@@ -1,10 +1,14 @@
import { useState, type FormEvent } from "react";
import { Input, Spinner } from "../ui/index.js";
import { ApiError, api, formatBytes, type Folder, type UploadedFile } from "../lib/api.js";
import { ApiError } from "../services/apiClient.js";
import { fileService } from "../services/fileService.js";
import { searchService } from "../services/searchService.js";
import { formatBytes } from "../utils/format.js";
import type { Folder, UploadedFile } from "../types/index.js";
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
import { IconAction } from "../components/IconAction.js";
import { DownloadIcon, FileIcon, FolderIcon, SearchIcon } from "../components/icons.js";
import { useI18n } from "../lib/i18n.js";
import { useI18n } from "../contexts/I18nContext.js";
interface Results {
folders: Folder[];
@@ -28,7 +32,7 @@ export const Search = () => {
setLoading(true);
setError(null);
try {
const { folders, files } = await api.search(query);
const { folders, files } = await searchService.search(query);
setResults({ folders, files });
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Recherche impossible."));
@@ -126,7 +130,7 @@ export const Search = () => {
</span>
</span>
<a
href={api.downloadUrl(file.id)}
href={fileService.downloadUrl(file.id)}
download={file.name}
aria-label={t("Télécharger {name}", { name: file.name })}
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground"
+11 -15
View File
@@ -1,18 +1,14 @@
import { useCallback, useEffect, useState } from "react";
import { Spinner } from "../ui/index.js";
import {
ApiError,
api,
formatBytes,
formatDate,
type TrashFile,
type TrashFolder,
} from "../lib/api.js";
import { ApiError } from "../services/apiClient.js";
import { trashService } from "../services/trashService.js";
import { formatBytes, formatDate } from "../utils/format.js";
import type { TrashFile, TrashFolder } from "../types/index.js";
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
import { useConfirm } from "../components/confirm.js";
import { IconAction } from "../components/IconAction.js";
import { FileIcon, FolderIcon, RestoreIcon, TrashEmptyIcon, TrashIcon } from "../components/icons.js";
import { useI18n } from "../lib/i18n.js";
import { useI18n } from "../contexts/I18nContext.js";
interface TrashData {
retentionDays: number;
@@ -32,7 +28,7 @@ export const Trash = () => {
setLoading(true);
setError(null);
try {
setData(await api.trash());
setData(await trashService.trash());
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : t("Chargement impossible."));
setData(null);
@@ -67,7 +63,7 @@ export const Trash = () => {
confirmIcon: <TrashEmptyIcon className="h-4 w-4" />,
});
if (!ok) return;
void run("empty", () => api.emptyTrash());
void run("empty", () => trashService.emptyTrash());
};
const purge = async (key: string, name: string, action: () => Promise<unknown>) => {
@@ -145,7 +141,7 @@ export const Trash = () => {
icon={<RestoreIcon className="h-4 w-4" />}
isLoading={busy === `restore-${folder.id}`}
onClick={() =>
void run(`restore-${folder.id}`, () => api.restoreFolder(folder.id))
void run(`restore-${folder.id}`, () => trashService.restoreFolder(folder.id))
}
/>
<IconAction
@@ -155,7 +151,7 @@ export const Trash = () => {
isLoading={busy === `purge-${folder.id}`}
onClick={() =>
void purge(`purge-${folder.id}`, folder.name, () =>
api.purgeFolder(folder.id),
trashService.purgeFolder(folder.id),
)
}
/>
@@ -190,7 +186,7 @@ export const Trash = () => {
icon={<RestoreIcon className="h-4 w-4" />}
isLoading={busy === `restore-${file.id}`}
onClick={() =>
void run(`restore-${file.id}`, () => api.restoreFile(file.id))
void run(`restore-${file.id}`, () => trashService.restoreFile(file.id))
}
/>
<IconAction
@@ -199,7 +195,7 @@ export const Trash = () => {
isLoading={busy === `purge-${file.id}`}
tone="danger"
onClick={() =>
void purge(`purge-${file.id}`, file.name, () => api.purgeFile(file.id))
void purge(`purge-${file.id}`, file.name, () => trashService.purgeFile(file.id))
}
/>
</li>
+24
View File
@@ -0,0 +1,24 @@
import type { SessionInfo, Theme, Language } from "../types/index.js";
import { BASE, del, get, patch, post, putBinary } from "./apiClient.js";
export const accountService = {
forgotPassword: (email: string) => post<{ ok: boolean }>("/account/forgot-password", { email }),
resetPassword: (token: string, password: string) =>
post<{ ok: boolean }>("/account/reset-password", { token, password }),
requestEmailChange: (password: string, new_email: string) =>
post<{ ok: boolean }>("/account/email-change", { password, new_email }),
confirmEmailChange: (token: string) =>
post<{ ok: boolean; email: string }>("/account/email-change/confirm", { token }),
updateProfile: (first_name: string, last_name: string) =>
patch<{ ok: boolean }>("/account/profile", { first_name, last_name }),
preferences: () => get<{ theme: Theme; language: Language }>("/account/preferences"),
updatePreferences: (theme: Theme, language: Language) =>
patch<{ theme: Theme; language: Language }>("/account/preferences", { theme, language }),
sessions: () => get<{ sessions: SessionInfo[] }>("/account/sessions"),
revokeSession: (id: string) => del<{ ok: boolean }>(`/account/sessions/${encodeURIComponent(id)}`),
revokeOtherSessions: () => del<{ ok: boolean }>("/account/sessions"),
avatarUrl: (userId: string) => `${BASE}/account/avatar/${encodeURIComponent(userId)}`,
uploadAvatar: (file: File) => putBinary<{ ok: boolean }>("/account/avatar", file, file.type),
deleteAvatar: () => del<{ ok: boolean }>("/account/avatar"),
};
+48
View File
@@ -0,0 +1,48 @@
import type { AdminStats, AdminUser, AuditEntry, StorageLocation } from "../types/index.js";
import { del, get, patch, post, query } from "./apiClient.js";
export const adminService = {
adminStats: () => get<AdminStats>("/admin/stats"),
adminUsers: (q?: string) =>
get<{ users: AdminUser[] }>(`/admin/users${query({ q })}`),
adminCreateUser: (payload: {
email: string;
first_name: string;
last_name: string;
role_slug: string;
quota_bytes?: number | null;
max_file_bytes?: number | null;
}) => post<{ user: AdminUser }>("/admin/users", payload),
adminUpdateUser: (
id: string,
payload: Partial<{
first_name: string;
last_name: string;
role_slug: string;
quota_bytes: number;
max_file_bytes: number;
is_active: boolean;
}>,
) => patch<{ user: AdminUser }>(`/admin/users/${encodeURIComponent(id)}`, payload),
adminDeleteUser: (id: string) => del<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}`),
adminResetPassword: (id: string) =>
post<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}/reset-password`),
adminStorageLocations: () =>
get<{ locations: StorageLocation[] }>("/admin/storage-locations"),
adminCreateStorageLocation: (payload: {
name: string;
slug: string;
mount_path: string;
quota_bytes?: number | null;
}) => post<{ ok: boolean }>("/admin/storage-locations", payload),
adminUpdateStorageLocation: (
id: number,
payload: { name?: string; quota_bytes?: number | null; is_active?: boolean },
) => patch<{ ok: boolean }>(`/admin/storage-locations/${id}`, payload),
adminAudit: (limit = 100, offset = 0, action?: string, userId?: string) =>
get<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action, userId })}`),
adminAuditFilters: () =>
get<{ actions: string[]; users: { id: string; email: string | null }[] }>(
"/admin/audit/filters",
),
};
+82
View File
@@ -0,0 +1,82 @@
export class ApiError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.name = "ApiError";
this.status = status;
}
}
export const BASE = "/api/cloud";
/** Au-dela de ce seuil, l'envoi passe par des sessions morcelees. */
export const LARGE_UPLOAD_THRESHOLD = 90 * 1024 * 1024;
const messageOf = (body: unknown, fallback: string): string =>
(body as { error?: { message?: string } } | null)?.error?.message ?? fallback;
export const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
let response: Response;
try {
response = await fetch(`${BASE}${path}`, {
credentials: "same-origin",
...init,
headers: {
...(init?.body ? { "content-type": "application/json" } : {}),
...init?.headers,
},
});
} catch {
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
}
const body: unknown = await response.json().catch(() => null);
if (!response.ok) throw new ApiError(response.status, messageOf(body, "Une erreur est survenue."));
return body as T;
};
export const get = <T>(path: string): Promise<T> => request<T>(path);
export const post = <T>(path: string, payload?: unknown): Promise<T> =>
request<T>(path, {
method: "POST",
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
});
export const patch = <T>(path: string, payload: unknown): Promise<T> =>
request<T>(path, { method: "PATCH", body: JSON.stringify(payload) });
export const put = <T>(path: string, payload?: unknown): Promise<T> =>
request<T>(path, {
method: "PUT",
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
});
export const del = <T>(path: string): Promise<T> => request<T>(path, { method: "DELETE" });
export const query = (params: Record<string, string | number | null | undefined>): string => {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== null && value !== undefined && value !== "") search.set(key, String(value));
}
const suffix = search.toString();
return suffix ? `?${suffix}` : "";
};
export const putBinary = async <T>(path: string, body: BodyInit, type: string): Promise<T> => {
let response: Response;
try {
response = await fetch(`${BASE}${path}`, {
method: "PUT",
credentials: "same-origin",
headers: type ? { "content-type": type } : {},
body,
});
} catch {
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
}
const parsed: unknown = await response.json().catch(() => null);
if (!response.ok) throw new ApiError(response.status, messageOf(parsed, "L'envoi a echoue."));
return parsed as T;
};
+11
View File
@@ -0,0 +1,11 @@
import type { User } from "../types/index.js";
import { get, post } from "./apiClient.js";
export const authService = {
me: () => get<{ user: User }>("/auth/me"),
login: (email: string, password: string) =>
post<{ user: User }>("/auth/login", { email, password }),
logout: () => post<{ ok: boolean }>("/auth/logout"),
changePassword: (current: string, next: string) =>
post<{ ok: boolean }>("/auth/change-password", { current, next }),
};
+26
View File
@@ -0,0 +1,26 @@
import type { ChatMember, ChatMessage } from "../types/index.js";
import { del, get, patch, post, put, query } from "./apiClient.js";
export const chatService = {
chatMembers: (folderId: string) =>
get<{ members: ChatMember[] }>(`/folders/${encodeURIComponent(folderId)}/chat/members`),
chatMessages: (folderId: string, after = 0, limit = 50, editedAfter?: string | null) =>
get<{ messages: ChatMessage[]; cursor: string }>(
`/folders/${encodeURIComponent(folderId)}/chat/messages${query({ after, limit, editedAfter })}`,
),
chatSend: (folderId: string, body: string) =>
post<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages`, { body }),
chatEditMessage: (folderId: string, id: number, body: string) =>
patch<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`, {
body,
}),
chatTogglePin: (folderId: string, id: number) =>
put<{ pinned: boolean }>(
`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}/pin`,
),
chatPins: (folderId: string) =>
get<{ messages: ChatMessage[] }>(`/folders/${encodeURIComponent(folderId)}/chat/pins`),
chatDeleteMessage: (folderId: string, id: number) =>
del<{ ok: boolean }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`),
chatUnread: () => get<{ unread: Record<string, number> }>("/chat/unread"),
};

Some files were not shown because too many files have changed in this diff Show More