From 68d4d5dea0f4835a2a92479a83a63afe727748b8 Mon Sep 17 00:00:00 2001 From: xEsiah Date: Fri, 13 Nov 2026 09:45:21 +0100 Subject: [PATCH] refactor: restructure frontend and backend by domain services 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. --- README.md | 11 +- backend/README.md | 8 +- backend/src/admin.ts | 6 +- backend/src/cli.ts | 8 +- .../{lib/config.ts => config/appConfig.ts} | 0 backend/src/{lib => config}/db.ts | 2 +- backend/src/index.ts | 27 +- backend/src/lib/index.ts | 61 -- backend/src/lib/mail.ts | 59 -- backend/src/middleware/auth.ts | 87 +++ backend/src/models/types.ts | 37 + backend/src/routes/account.ts | 452 ------------ backend/src/routes/accountRoutes.ts | 197 ++++++ backend/src/routes/admin.ts | 541 -------------- backend/src/routes/adminRoutes.ts | 148 ++++ backend/src/routes/auth.ts | 177 ----- backend/src/routes/authRoutes.ts | 87 +++ backend/src/routes/chat.ts | 355 ---------- backend/src/routes/chatRoutes.ts | 162 +++++ backend/src/routes/directory.ts | 43 -- backend/src/routes/directoryRoutes.ts | 15 + backend/src/routes/fileRoutes.ts | 327 +++++++++ backend/src/routes/files.ts | 667 ------------------ backend/src/routes/folderRoutes.ts | 164 +++++ backend/src/routes/folders.ts | 384 ---------- backend/src/routes/media.ts | 85 --- backend/src/routes/mediaRoutes.ts | 23 + backend/src/routes/search.ts | 108 --- backend/src/routes/searchRoutes.ts | 18 + backend/src/routes/trash.ts | 364 ---------- backend/src/routes/trashRoutes.ts | 90 +++ backend/src/routes/uploadRoutes.ts | 122 ++++ backend/src/routes/uploads.ts | 450 ------------ backend/src/services/accountService.ts | 373 ++++++++++ backend/src/services/adminService.ts | 494 +++++++++++++ .../{access.ts => services/auditService.ts} | 9 +- .../{lib/auth.ts => services/authService.ts} | 206 +++--- backend/src/services/chatService.ts | 278 ++++++++ backend/src/services/directoryService.ts | 40 ++ backend/src/services/fileService.ts | 364 ++++++++++ backend/src/services/folderService.ts | 290 ++++++++ .../mailService.ts} | 92 ++- .../{media.ts => services/mediaService.ts} | 92 ++- backend/src/services/searchService.ts | 111 +++ .../storageService.ts} | 3 +- backend/src/services/trashService.ts | 337 +++++++++ backend/src/services/uploadService.ts | 376 ++++++++++ backend/src/{lib => utils}/errors.ts | 0 backend/src/{lib => utils}/http.ts | 6 +- backend/src/{lib => utils}/migrate.ts | 2 +- backend/src/{lib => utils}/ratelimit.ts | 0 backend/src/{lib => utils}/service.ts | 4 +- backend/src/utils/validators.ts | 47 ++ docs/agents.md | 18 +- docs/api.md | 12 +- docs/architecture.md | 50 +- docs/deployment.md | 2 +- docs/security.md | 6 +- docs/standards.md | 2 +- docs/workflow.md | 16 +- frontend/src/App.tsx | 2 +- frontend/src/components/AppShell.tsx | 4 +- frontend/src/components/Avatar.tsx | 4 +- frontend/src/components/DocumentTitle.tsx | 2 +- frontend/src/components/FolderChat.tsx | 36 +- frontend/src/components/MediaThumb.tsx | 6 +- frontend/src/components/MediaViewer.tsx | 18 +- frontend/src/components/confirm.tsx | 2 +- frontend/src/components/dialogs.tsx | 36 +- frontend/src/components/feedback.tsx | 2 +- frontend/src/components/toast.tsx | 2 +- .../i18n.tsx => contexts/I18nContext.tsx} | 4 +- .../SessionContext.tsx} | 7 +- .../theme.tsx => contexts/ThemeContext.tsx} | 2 +- frontend/src/lib/api.ts | 605 ---------------- frontend/src/lib/locale.ts | 2 +- frontend/src/main.tsx | 6 +- frontend/src/pages/Admin.tsx | 41 +- frontend/src/pages/Browser.tsx | 41 +- frontend/src/pages/ChangePassword.tsx | 9 +- frontend/src/pages/ConfirmEmail.tsx | 9 +- frontend/src/pages/Favorites.tsx | 13 +- frontend/src/pages/ForgotPassword.tsx | 7 +- frontend/src/pages/Gallery.tsx | 11 +- frontend/src/pages/Login.tsx | 9 +- frontend/src/pages/Profile.tsx | 27 +- frontend/src/pages/ResetPassword.tsx | 7 +- frontend/src/pages/Search.tsx | 12 +- frontend/src/pages/Trash.tsx | 26 +- frontend/src/services/accountService.ts | 24 + frontend/src/services/adminService.ts | 48 ++ frontend/src/services/apiClient.ts | 82 +++ frontend/src/services/authService.ts | 11 + frontend/src/services/chatService.ts | 26 + frontend/src/services/directoryService.ts | 6 + frontend/src/services/fileService.ts | 36 + frontend/src/services/folderService.ts | 30 + frontend/src/services/mediaService.ts | 9 + frontend/src/services/searchService.ts | 7 + frontend/src/services/trashService.ts | 14 + frontend/src/services/uploadService.ts | 141 ++++ frontend/src/types/index.ts | 196 +++++ frontend/src/utils/format.ts | 29 + 103 files changed, 5415 insertions(+), 4711 deletions(-) rename backend/src/{lib/config.ts => config/appConfig.ts} (100%) rename backend/src/{lib => config}/db.ts (98%) delete mode 100644 backend/src/lib/index.ts delete mode 100644 backend/src/lib/mail.ts create mode 100644 backend/src/middleware/auth.ts create mode 100644 backend/src/models/types.ts delete mode 100644 backend/src/routes/account.ts create mode 100644 backend/src/routes/accountRoutes.ts delete mode 100644 backend/src/routes/admin.ts create mode 100644 backend/src/routes/adminRoutes.ts delete mode 100644 backend/src/routes/auth.ts create mode 100644 backend/src/routes/authRoutes.ts delete mode 100644 backend/src/routes/chat.ts create mode 100644 backend/src/routes/chatRoutes.ts delete mode 100644 backend/src/routes/directory.ts create mode 100644 backend/src/routes/directoryRoutes.ts create mode 100644 backend/src/routes/fileRoutes.ts delete mode 100644 backend/src/routes/files.ts create mode 100644 backend/src/routes/folderRoutes.ts delete mode 100644 backend/src/routes/folders.ts delete mode 100644 backend/src/routes/media.ts create mode 100644 backend/src/routes/mediaRoutes.ts delete mode 100644 backend/src/routes/search.ts create mode 100644 backend/src/routes/searchRoutes.ts delete mode 100644 backend/src/routes/trash.ts create mode 100644 backend/src/routes/trashRoutes.ts create mode 100644 backend/src/routes/uploadRoutes.ts delete mode 100644 backend/src/routes/uploads.ts create mode 100644 backend/src/services/accountService.ts create mode 100644 backend/src/services/adminService.ts rename backend/src/{access.ts => services/auditService.ts} (94%) rename backend/src/{lib/auth.ts => services/authService.ts} (51%) create mode 100644 backend/src/services/chatService.ts create mode 100644 backend/src/services/directoryService.ts create mode 100644 backend/src/services/fileService.ts create mode 100644 backend/src/services/folderService.ts rename backend/src/{lib/mail-template.ts => services/mailService.ts} (76%) rename backend/src/{media.ts => services/mediaService.ts} (55%) create mode 100644 backend/src/services/searchService.ts rename backend/src/{storage.ts => services/storageService.ts} (98%) create mode 100644 backend/src/services/trashService.ts create mode 100644 backend/src/services/uploadService.ts rename backend/src/{lib => utils}/errors.ts (100%) rename backend/src/{lib => utils}/http.ts (97%) rename backend/src/{lib => utils}/migrate.ts (98%) rename backend/src/{lib => utils}/ratelimit.ts (100%) rename backend/src/{lib => utils}/service.ts (97%) create mode 100644 backend/src/utils/validators.ts rename frontend/src/{lib/i18n.tsx => contexts/I18nContext.tsx} (99%) rename frontend/src/{lib/session.tsx => contexts/SessionContext.tsx} (85%) rename frontend/src/{lib/theme.tsx => contexts/ThemeContext.tsx} (95%) delete mode 100644 frontend/src/lib/api.ts create mode 100644 frontend/src/services/accountService.ts create mode 100644 frontend/src/services/adminService.ts create mode 100644 frontend/src/services/apiClient.ts create mode 100644 frontend/src/services/authService.ts create mode 100644 frontend/src/services/chatService.ts create mode 100644 frontend/src/services/directoryService.ts create mode 100644 frontend/src/services/fileService.ts create mode 100644 frontend/src/services/folderService.ts create mode 100644 frontend/src/services/mediaService.ts create mode 100644 frontend/src/services/searchService.ts create mode 100644 frontend/src/services/trashService.ts create mode 100644 frontend/src/services/uploadService.ts create mode 100644 frontend/src/types/index.ts create mode 100644 frontend/src/utils/format.ts diff --git a/README.md b/README.md index b4ec353..ddf0522 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/backend/README.md b/backend/README.md index e0317b8..d3dac63 100644 --- a/backend/README.md +++ b/backend/README.md @@ -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). diff --git a/backend/src/admin.ts b/backend/src/admin.ts index add8267..b12c783 100644 --- a/backend/src/admin.ts +++ b/backend/src/admin.ts @@ -1,6 +1,9 @@ #!/usr/bin/env node import { randomUUID } from "node:crypto"; -import { ConfigError, loadDbConfig, hashPassword, AppError, toSafeError } from "./lib/index.js"; +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 --first --last [options] @@ -84,7 +87,6 @@ const main = async (argv: string[]): Promise => { throw error; } - const { Db } = await import("./lib/index.js"); const db = new Db(config); try { diff --git a/backend/src/cli.ts b/backend/src/cli.ts index d4bde4a..e5be377 100644 --- a/backend/src/cli.ts +++ b/backend/src/cli.ts @@ -2,10 +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"; +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; diff --git a/backend/src/lib/config.ts b/backend/src/config/appConfig.ts similarity index 100% rename from backend/src/lib/config.ts rename to backend/src/config/appConfig.ts diff --git a/backend/src/lib/db.ts b/backend/src/config/db.ts similarity index 98% rename from backend/src/lib/db.ts rename to backend/src/config/db.ts index d2d702c..d31fb00 100644 --- a/backend/src/lib/db.ts +++ b/backend/src/config/db.ts @@ -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; diff --git a/backend/src/index.ts b/backend/src/index.ts index 5c430ae..cb2f1a4 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -1,17 +1,20 @@ 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"; const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "../migrations"); diff --git a/backend/src/lib/index.ts b/backend/src/lib/index.ts deleted file mode 100644 index 67ee19b..0000000 --- a/backend/src/lib/index.ts +++ /dev/null @@ -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"; diff --git a/backend/src/lib/mail.ts b/backend/src/lib/mail.ts deleted file mode 100644 index 998a62f..0000000 --- a/backend/src/lib/mail.ts +++ /dev/null @@ -1,59 +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"; - -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; - html?: string; -} - -export interface Mailer { - send: (message: MailMessage) => Promise; -} - -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(); diff --git a/backend/src/middleware/auth.ts b/backend/src/middleware/auth.ts new file mode 100644 index 0000000..a19597f --- /dev/null +++ b/backend/src/middleware/auth.ts @@ -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 => { + 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 => { + 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 => { + 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; +}; diff --git a/backend/src/models/types.ts b/backend/src/models/types.ts new file mode 100644 index 0000000..1f02815 --- /dev/null +++ b/backend/src/models/types.ts @@ -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; +} diff --git a/backend/src/routes/account.ts b/backend/src/routes/account.ts deleted file mode 100644 index af50c26..0000000 --- a/backend/src/routes/account.ts +++ /dev/null @@ -1,452 +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 = (schema: z.ZodType, 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[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; - 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], - ); - - 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 }); - }); -}; diff --git a/backend/src/routes/accountRoutes.ts b/backend/src/routes/accountRoutes.ts new file mode 100644 index 0000000..fc0f22e --- /dev/null +++ b/backend/src/routes/accountRoutes.ts @@ -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[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; + 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 }); + }); +}; diff --git a/backend/src/routes/admin.ts b/backend/src/routes/admin.ts deleted file mode 100644 index 4264387..0000000 --- a/backend/src/routes/admin.ts +++ /dev/null @@ -1,541 +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 = (schema: z.ZodType, 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"]; - -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; -}; - -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(); - 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 }; -}; - -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[0]): void => { - if (currentUser(context).role_slug !== "admin") throw AppError.forbidden(); - }; - - const assertQuotaFits = async (quota: number): Promise => { - 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( - `${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( - `${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(`${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(`${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(`${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."); - - 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], - ); - - 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 }); - }); - - 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 }); - }); -}; diff --git a/backend/src/routes/adminRoutes.ts b/backend/src/routes/adminRoutes.ts new file mode 100644 index 0000000..7ac3277 --- /dev/null +++ b/backend/src/routes/adminRoutes.ts @@ -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[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 }); + }); +}; diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts deleted file mode 100644 index 670566c..0000000 --- a/backend/src/routes/auth.ts +++ /dev/null @@ -1,177 +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), -}); - -let dummyHash: Promise | undefined; -const decoyHash = (): Promise => (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 => { - 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 { email, password } = parsed.data; - const row = await db.one(`${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 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]); - 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(`${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), - }); - - 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], - ); - 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 }); - }); -}; diff --git a/backend/src/routes/authRoutes.ts b/backend/src/routes/authRoutes.ts new file mode 100644 index 0000000..b0dc1de --- /dev/null +++ b/backend/src/routes/authRoutes.ts @@ -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 }); + }); +}; diff --git a/backend/src/routes/chat.ts b/backend/src/routes/chat.ts deleted file mode 100644 index c6ef546..0000000 --- a/backend/src/routes/chat.ts +++ /dev/null @@ -1,355 +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"; - -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."), -}); - -const editInput = z.object({ - body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."), -}); - -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; -} - -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 => { - const limiter = createRateLimiter(20, 10_000); - - 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; - }; - - const markRead = async (folderId: string, userId: string, messageId: number): Promise => { - 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); - }; - - 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 = {}; - 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."); - - 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); - - 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; - - const rows = - after > 0 - ? await db.query( - `${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( - `${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); - 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(`${SELECT_MESSAGE} WHERE m.id = ?`, [result.insertId]); - return context.json({ message: publicMessage(row) }, 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")); - 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(`${SELECT_MESSAGE} WHERE m.id = ?`, [id]); - return context.json({ message: publicMessage(row) }); - }, - ); - - 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 }); - }, - ); - - 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( - `${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], - ); - 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], - ); - await audit(db, context, user, "chat.delete", "message", String(id), { folderId }, config.TRUST_PROXY); - return context.json({ ok: true }); - }, - ); -}; diff --git a/backend/src/routes/chatRoutes.ts b/backend/src/routes/chatRoutes.ts new file mode 100644 index 0000000..bd0c837 --- /dev/null +++ b/backend/src/routes/chatRoutes.ts @@ -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 }); + }, + ); +}; diff --git a/backend/src/routes/directory.ts b/backend/src/routes/directory.ts deleted file mode 100644 index d5ff605..0000000 --- a/backend/src/routes/directory.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { - attachUser, - currentUser, - requireAuth, - type App, - type Config, - type Db, -} from "../lib/index.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 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, - })), - }); - }); -}; diff --git a/backend/src/routes/directoryRoutes.ts b/backend/src/routes/directoryRoutes.ts new file mode 100644 index 0000000..751a9a9 --- /dev/null +++ b/backend/src/routes/directoryRoutes.ts @@ -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 }); + }); +}; diff --git a/backend/src/routes/fileRoutes.ts b/backend/src/routes/fileRoutes.ts new file mode 100644 index 0000000..679559b --- /dev/null +++ b/backend/src/routes/fileRoutes.ts @@ -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 = { + "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; + 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; + 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; + 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 }); + }); +}; diff --git a/backend/src/routes/files.ts b/backend/src/routes/files.ts deleted file mode 100644 index 4fc24e9..0000000 --- a/backend/src/routes/files.ts +++ /dev/null @@ -1,667 +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 = (schema: z.ZodType, 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, -}); - -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"; -}; - -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 = { - "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; - 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; - 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")); - 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(); - - if (declared > budget.max_file_bytes) { - throw AppError.payloadTooLarge( - `Fichier trop volumineux (maximum ${budget.max_file_bytes} octets).`, - ); - } - if (BigInt(budget.used_bytes) + BigInt(declared) > BigInt(budget.quota_bytes)) { - throw AppError.payloadTooLarge("Votre quota de stockage est depasse."); - } - - const duplicate = await db.one( - `SELECT 1 AS taken FROM files - WHERE folder_id <=> ? AND active_name = ? AND deleted_at IS NULL - 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."); - - 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; - } - - 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; - } - - 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(`${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."); - } - - 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( - `${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) }); - }); - - app.get("/api/cloud/favorites", requireAuth, async (context) => { - const user = currentUser(context); - const rows = await db.query( - `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(`${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"), - }); - }); - - 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(`${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"), - }); - }); - - 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(`${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; - 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 row = await db.one(`${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(`${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) }); - }); - - 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(`${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(`${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) }); - }); - - 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(`${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(`${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(`${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 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 }); - }); -}; diff --git a/backend/src/routes/folderRoutes.ts b/backend/src/routes/folderRoutes.ts new file mode 100644 index 0000000..724bbf3 --- /dev/null +++ b/backend/src/routes/folderRoutes.ts @@ -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 }); + }); +}; diff --git a/backend/src/routes/folders.ts b/backend/src/routes/folders.ts deleted file mode 100644 index b59681e..0000000 --- a/backend/src/routes/folders.ts +++ /dev/null @@ -1,384 +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 = (schema: z.ZodType, 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 subtreeIds = async (db: Db, rootId: string): Promise => { - 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) { - if (!(await canTraverse(db, user, parentId))) { - throw AppError.notFound("Dossier introuvable."); - } - } - - const rows = await db.query( - `${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 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."); - } - } - - 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(`${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(`${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(`${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(`${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."); - } - 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(`${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) }); - }); - - 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(`${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 }); - }); - - 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 }); - }); -}; diff --git a/backend/src/routes/media.ts b/backend/src/routes/media.ts deleted file mode 100644 index 1b7f70e..0000000 --- a/backend/src/routes/media.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { - AppError, - attachUser, - currentUser, - requireAuth, - type App, - type Config, - type Db, -} from "../lib/index.js"; - -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, - })), - }); - }); -}; diff --git a/backend/src/routes/mediaRoutes.ts b/backend/src/routes/mediaRoutes.ts new file mode 100644 index 0000000..9b347dd --- /dev/null +++ b/backend/src/routes/mediaRoutes.ts @@ -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 }); + }); +}; diff --git a/backend/src/routes/search.ts b/backend/src/routes/search.ts deleted file mode 100644 index 4ec060b..0000000 --- a/backend/src/routes/search.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { - AppError, - attachUser, - currentUser, - requireAuth, - type App, - type Config, - type Db, -} from "../lib/index.js"; - -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, - })), - }); - }); -}; diff --git a/backend/src/routes/searchRoutes.ts b/backend/src/routes/searchRoutes.ts new file mode 100644 index 0000000..d8b28bc --- /dev/null +++ b/backend/src/routes/searchRoutes.ts @@ -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)); + }); +}; diff --git a/backend/src/routes/trash.ts b/backend/src/routes/trash.ts deleted file mode 100644 index 46df794..0000000 --- a/backend/src/routes/trash.ts +++ /dev/null @@ -1,364 +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.", - ); - -const subtreeIds = async (db: Db, rootId: string): Promise => { - 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 => { - let current = folderId; - const guard = new Set(); - 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 => { - 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 => { - 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); - - const folders = await db.query( - `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( - `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 }); - }); - - 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 }); - }); -}; - -export const purgeExpiredTrash = async (db: Db, config: Config): Promise => { - 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; -}; diff --git a/backend/src/routes/trashRoutes.ts b/backend/src/routes/trashRoutes.ts new file mode 100644 index 0000000..47435b1 --- /dev/null +++ b/backend/src/routes/trashRoutes.ts @@ -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 }); + }); +}; diff --git a/backend/src/routes/uploadRoutes.ts b/backend/src/routes/uploadRoutes.ts new file mode 100644 index 0000000..b0d1d36 --- /dev/null +++ b/backend/src/routes/uploadRoutes.ts @@ -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 }); + }); +}; diff --git a/backend/src/routes/uploads.ts b/backend/src/routes/uploads.ts deleted file mode 100644 index dd6eb32..0000000 --- a/backend/src/routes/uploads.ts +++ /dev/null @@ -1,450 +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"; - -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.", - ); - -export const CHUNK_SIZE = 50 * 1024 * 1024; - -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 = (schema: z.ZodType, 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(), -}); - -const dropSession = async (db: Db, row: UploadSessionRow): Promise => { - 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 => { - if (!uuid.safeParse(id).success) throw AppError.notFound("Session d'envoi introuvable."); - const row = await db.one(`${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 => { - 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(); - - 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(`${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."); - - 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( - `${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."); - } - - 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, - ); - - 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(`${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 }); - }); -}; - -export const purgeExpiredUploads = async (db: Db, config: Config): Promise => { - const expired = await db.query( - `${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; -}; diff --git a/backend/src/services/accountService.ts b/backend/src/services/accountService.ts new file mode 100644 index 0000000..d6f4bee --- /dev/null +++ b/backend/src/services/accountService.ts @@ -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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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; +}; diff --git a/backend/src/services/adminService.ts b/backend/src/services/adminService.ts new file mode 100644 index 0000000..9fc13b5 --- /dev/null +++ b/backend/src/services/adminService.ts @@ -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(); + 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 => { + 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 => { + const query = q.trim(); + if (query) { + return db.query( + `${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( + `${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 => { + 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(`${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 => { + const existing = await db.one( + `${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(`${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 => { + 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( + `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 => { + 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 => { + 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, + ); +}; diff --git a/backend/src/access.ts b/backend/src/services/auditService.ts similarity index 94% rename from backend/src/access.ts rename to backend/src/services/auditService.ts index e18d25f..b285f6c 100644 --- a/backend/src/access.ts +++ b/backend/src/services/auditService.ts @@ -1,6 +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"; +/** 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 @@ -118,9 +121,7 @@ export const canTraverse = async ( return descendant !== null; }; -const clientIp = (context: Context, trustProxy: boolean): string | null => - sharedClientIp(context, trustProxy); - +/** Consigne une action dans le journal d'audit (silencieux en cas d'echec). */ export const audit = async ( db: Db, context: Context, diff --git a/backend/src/lib/auth.ts b/backend/src/services/authService.ts similarity index 51% rename from backend/src/lib/auth.ts rename to backend/src/services/authService.ts index 16c227c..dd47694 100644 --- a/backend/src/lib/auth.ts +++ b/backend/src/services/authService.ts @@ -7,10 +7,10 @@ import { 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"; +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, @@ -52,22 +52,6 @@ export const sha256 = (value: string): string => createHash("sha256").update(val export const sessionTokenHash = (token: string, secret: string): string => createHmac("sha256", secret).update(token).digest("hex"); -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"; export const createSession = async ( @@ -134,82 +118,124 @@ export const purgeExpiredSessions = async (db: Db): Promise => { return result.affectedRows; }; -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; +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 attachUser = - (db: Db, secret: string) => - async (context: Context, next: Next): Promise => { - 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(); - }; +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`; -const PASSWORD_CHANGE_ALLOWED = new Set([ - "/api/cloud/auth/me", - "/api/cloud/auth/change-password", - "/api/cloud/auth/logout", -]); +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 const requireAuth = async (context: Context, next: Next): Promise => { - 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."); +export type PublicUser = ReturnType; + +let dummyHash: Promise | undefined; +const decoyHash = (): Promise => (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(`${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."); } - await next(); + + 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 }; }; -export const requireRole = - (...slugs: string[]) => - async (context: Context, next: Next): Promise => { - 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(); - }; +/** Renvoie le profil public de l'utilisateur courant. */ +export const me = async (db: Db, userId: string): Promise => { + const row = await db.one(`${SELECT_USER} WHERE u.id = ?`, [userId]); + if (!row) throw AppError.unauthorized(); + return publicUser(row); +}; -export const currentUser = (context: Context): SessionUser => { - const user = context.get("user") as SessionUser | undefined; - if (!user) throw AppError.unauthorized(); - return user; +/** 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 => { + 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)], + ); }; diff --git a/backend/src/services/chatService.ts b/backend/src/services/chatService.ts new file mode 100644 index 0000000..3bdb63a --- /dev/null +++ b/backend/src/services/chatService.ts @@ -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 => { + 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> => { + 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 = {}; + 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 => { + const folder = await assertReadableFolder(db, user, folderId); + + const rows = await db.query>( + `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( + `${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( + `${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 => { + 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(`${SELECT_MESSAGE} WHERE m.id = ?`, [result.insertId]); +}; + +export const editMessage = async ( + db: Db, + user: SessionUser, + folderId: string, + id: number, + body: string, +): Promise => { + 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(`${SELECT_MESSAGE} WHERE m.id = ?`, [id]); +}; + +export const togglePin = async ( + db: Db, + user: SessionUser, + folderId: string, + id: number, +): Promise => { + 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 => { + await assertReadableFolder(db, user, folderId); + + return db.query( + `${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 => { + 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], + ); +}; diff --git a/backend/src/services/directoryService.ts b/backend/src/services/directoryService.ts new file mode 100644 index 0000000..79d17fd --- /dev/null +++ b/backend/src/services/directoryService.ts @@ -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 => { + 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, + })); +}; diff --git a/backend/src/services/fileService.ts b/backend/src/services/fileService.ts new file mode 100644 index 0000000..8786181 --- /dev/null +++ b/backend/src/services/fileService.ts @@ -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 => { + 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 | null; +} + +/** Envoi direct (petits fichiers) : controle, ecriture disque et enregistrement. */ +export const uploadFile = async ( + db: Db, + config: Config, + user: SessionUser, + input: UploadInput, +): Promise => { + 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(`${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 => { + 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( + `${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( + `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 => { + const row = await db.one(`${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 => { + 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(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]); +}; + +export const moveFile = async ( + db: Db, + user: SessionUser, + id: string, + folderId: string | null, +): Promise => { + 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(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]); +}; + +export const toggleStar = async (db: Db, user: SessionUser, id: string): Promise => { + 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(`${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 => { + 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; +}; diff --git a/backend/src/services/folderService.ts b/backend/src/services/folderService.ts new file mode 100644 index 0000000..a0512b8 --- /dev/null +++ b/backend/src/services/folderService.ts @@ -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 => { + 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 => { + if (parentId !== null && !(await canTraverse(db, user, parentId))) { + throw AppError.notFound("Dossier introuvable."); + } + + const rows = await db.query( + `${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 => { + 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(`${SELECT_FOLDER} WHERE f.id = ?`, [id]); +}; + +export const renameFolder = async ( + db: Db, + user: SessionUser, + id: string, + name: string, +): Promise => { + const existing = await db.one( + `${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(`${SELECT_FOLDER} WHERE f.id = ?`, [id]); +}; + +export const moveFolder = async ( + db: Db, + user: SessionUser, + id: string, + parentId: string | null, +): Promise => { + const existing = await db.one( + `${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(`${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 => { + const existing = await db.one( + `${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 => { + if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable."); + + const rows = await db.query( + `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 => { + 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."); +}; diff --git a/backend/src/lib/mail-template.ts b/backend/src/services/mailService.ts similarity index 76% rename from backend/src/lib/mail-template.ts rename to backend/src/services/mailService.ts index 7de6cdc..4ba03c1 100644 --- a/backend/src/lib/mail-template.ts +++ b/backend/src/services/mailService.ts @@ -1,4 +1,17 @@ -import type { Config } from "./config.js"; +import { readFileSync } from "node:fs"; +import { createTransport, type Transporter } from "nodemailer"; +import type { Config } from "../config/appConfig.js"; + +export interface MailMessage { + to: string; + subject: string; + text: string; + html?: string; +} + +export interface Mailer { + send: (message: MailMessage) => Promise; +} export interface Branding { appName: string; @@ -8,16 +21,6 @@ export interface Branding { footer: string; } -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 { preview: string; heading: string; @@ -33,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(); + +/** 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, "&") @@ -130,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") }; -}; \ No newline at end of file +}; diff --git a/backend/src/media.ts b/backend/src/services/mediaService.ts similarity index 55% rename from backend/src/media.ts rename to backend/src/services/mediaService.ts index 2723364..5d6c78d 100644 --- a/backend/src/media.ts +++ b/backend/src/services/mediaService.ts @@ -2,8 +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"; +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"; @@ -79,6 +81,7 @@ const writeThumbnail = async (source: string, destination: string): Promise => { + 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; diff --git a/backend/src/services/searchService.ts b/backend/src/services/searchService.ts new file mode 100644 index 0000000..afe7189 --- /dev/null +++ b/backend/src/services/searchService.ts @@ -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 => { + const pattern = `%${escapeLike(q).slice(0, 110)}%`; + + const folders = await db.query( + `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, + })), + }; +}; diff --git a/backend/src/storage.ts b/backend/src/services/storageService.ts similarity index 98% rename from backend/src/storage.ts rename to backend/src/services/storageService.ts index 6c774f8..6528f19 100644 --- a/backend/src/storage.ts +++ b/backend/src/services/storageService.ts @@ -4,7 +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"; +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; diff --git a/backend/src/services/trashService.ts b/backend/src/services/trashService.ts new file mode 100644 index 0000000..be299ae --- /dev/null +++ b/backend/src/services/trashService.ts @@ -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 => { + 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 => { + let current = folderId; + const guard = new Set(); + 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 => { + 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 => { + 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 => { + const folders = await db.query( + `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( + `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 => { + const row = await db.one( + `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 => { + const row = await db.one( + `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 => { + const row = await db.one( + `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 => { + const row = await db.one( + `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 => { + 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; +}; diff --git a/backend/src/services/uploadService.ts b/backend/src/services/uploadService.ts new file mode 100644 index 0000000..d1bc2b1 --- /dev/null +++ b/backend/src/services/uploadService.ts @@ -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; + +const dropSession = async (db: Db, row: UploadSessionRow): Promise => { + 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 => { + const row = await db.one(`${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 => { + 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(`${SELECT_SESSION} WHERE id = ?`, [id]); + return sessionPublic(created); +}; + +export const getUploadSession = async ( + db: Db, + user: SessionUser, + id: string, +): Promise => { + 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, + declared: number, +): Promise => { + 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( + `${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 => { + 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(`${SELECT_FILE} WHERE f.id = ?`, [user.id, row.id]); +}; + +export const cancelUpload = async ( + db: Db, + user: SessionUser, + id: string, +): Promise => { + 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 => { + const expired = await db.query( + `${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; +}; + diff --git a/backend/src/lib/errors.ts b/backend/src/utils/errors.ts similarity index 100% rename from backend/src/lib/errors.ts rename to backend/src/utils/errors.ts diff --git a/backend/src/lib/http.ts b/backend/src/utils/http.ts similarity index 97% rename from backend/src/lib/http.ts rename to backend/src/utils/http.ts index fac100c..9a23f93 100644 --- a/backend/src/lib/http.ts +++ b/backend/src/utils/http.ts @@ -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 { diff --git a/backend/src/lib/migrate.ts b/backend/src/utils/migrate.ts similarity index 98% rename from backend/src/lib/migrate.ts rename to backend/src/utils/migrate.ts index 471af2c..b1f3057 100644 --- a/backend/src/lib/migrate.ts +++ b/backend/src/utils/migrate.ts @@ -1,7 +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"; +import type { Db } from "../config/db.js"; export interface MigrationFile { version: string; diff --git a/backend/src/lib/ratelimit.ts b/backend/src/utils/ratelimit.ts similarity index 100% rename from backend/src/lib/ratelimit.ts rename to backend/src/utils/ratelimit.ts diff --git a/backend/src/lib/service.ts b/backend/src/utils/service.ts similarity index 97% rename from backend/src/lib/service.ts rename to backend/src/utils/service.ts index 7f52c88..b5c5555 100644 --- a/backend/src/lib/service.ts +++ b/backend/src/utils/service.ts @@ -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, diff --git a/backend/src/utils/validators.ts b/backend/src/utils/validators.ts new file mode 100644 index 0000000..dc9b462 --- /dev/null +++ b/backend/src/utils/validators.ts @@ -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 = (schema: z.ZodType, 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"; +}; diff --git a/docs/agents.md b/docs/agents.md index 162afca..1a4831b 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -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 diff --git a/docs/api.md b/docs/api.md index 317d128..a8a7a3b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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 : diff --git a/docs/architecture.md b/docs/architecture.md index efcff1d..6fa256e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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}//` (`storage.ts`), nom affiché - jamais dans le chemin. -- `media.ts` : classification (`image/video/audio/document/archive/other`), +- Chemin physique `${MEDIA_DIR}//` (`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`. diff --git a/docs/deployment.md b/docs/deployment.md index 3b1a38a..d18ff45 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -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 diff --git a/docs/security.md b/docs/security.md index b224190..a60294f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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. diff --git a/docs/standards.md b/docs/standards.md index 8c4d84b..89c6c69 100644 --- a/docs/standards.md +++ b/docs/standards.md @@ -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) | diff --git a/docs/workflow.md b/docs/workflow.md index 9442810..038e1b3 100644 --- a/docs/workflow.md +++ b/docs/workflow.md @@ -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/.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/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` | diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index c1dc63c..19abf7a 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,6 +1,6 @@ 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"; diff --git a/frontend/src/components/AppShell.tsx b/frontend/src/components/AppShell.tsx index 074b29c..77f08f9 100644 --- a/frontend/src/components/AppShell.tsx +++ b/frontend/src/components/AppShell.tsx @@ -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 { diff --git a/frontend/src/components/Avatar.tsx b/frontend/src/components/Avatar.tsx index 0922f78..eebf715 100644 --- a/frontend/src/components/Avatar.tsx +++ b/frontend/src/components/Avatar.tsx @@ -1,4 +1,4 @@ -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 => @@ -29,7 +29,7 @@ export const Avatar = ({ {initials(firstName, lastName)} {hasAvatar ? ( { diff --git a/frontend/src/components/DocumentTitle.tsx b/frontend/src/components/DocumentTitle.tsx index 2c3ffaf..ffbfbca 100644 --- a/frontend/src/components/DocumentTitle.tsx +++ b/frontend/src/components/DocumentTitle.tsx @@ -1,6 +1,6 @@ import { useEffect } from "react"; import { useLocation } from "react-router-dom"; -import { useI18n } from "../lib/i18n.js"; +import { useI18n } from "../contexts/I18nContext.js"; const BRAND = "CoHaiSe Cloud"; diff --git a/frontend/src/components/FolderChat.tsx b/frontend/src/components/FolderChat.tsx index 6b60253..f73f03a 100644 --- a/frontend/src/components/FolderChat.tsx +++ b/frontend/src/components/FolderChat.tsx @@ -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"; @@ -142,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]); @@ -156,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); @@ -191,13 +187,13 @@ export const FolderChat = ({ 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), ]); editedSinceRef.current = result.cursor; mergeMessages(result.messages); @@ -250,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(""); @@ -277,7 +273,7 @@ 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), ); @@ -309,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, @@ -337,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) => diff --git a/frontend/src/components/MediaThumb.tsx b/frontend/src/components/MediaThumb.tsx index 2516c57..35ca368 100644 --- a/frontend/src/components/MediaThumb.tsx +++ b/frontend/src/components/MediaThumb.tsx @@ -1,4 +1,4 @@ -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"; @@ -18,7 +18,7 @@ export const MediaThumb = ({ if (kind === "image") { return (