diff --git a/.env.example b/.env.example index f42691b..4155b77 100644 --- a/.env.example +++ b/.env.example @@ -19,7 +19,8 @@ CLOUD_DB_DIR=../db CLOUD_MEDIA_DIR=../media # --- Session (obligatoire pour toute API) ------------------------------- -# Secret de chiffrement des sessions. Obligatoire, 32 caracteres minimum. +# Secret qui poivre (HMAC-SHA-256) les jetons de session stockes en base. +# Obligatoire, 32 caracteres minimum. Le changer invalide toutes les sessions. # Generation : # node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))" SESSION_SECRET= diff --git a/README.md b/README.md index fe5e6e7..b4ec353 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ L'app répond sur **`http://localhost:8083`** (variable `COHAISE_HTTP_PORT`). | `COHAISE_DB_PORT` | port MariaDB | `3407` | | `CLOUD_DB_USER` / `CLOUD_DB_PASSWORD` | identifiants base | — | | `CLOUD_DB_ROOT_PASSWORD` | root, pour la sauvegarde | — | -| `SESSION_SECRET` | signature des sessions, obligatoire | — | +| `SESSION_SECRET` | poivre HMAC des sessions, obligatoire | — | Le démarrage échoue avec la liste exacte des variables manquantes ou mal formées, avant l'ouverture d'aucun port. C'est voulu. diff --git a/backend/src/index.ts b/backend/src/index.ts index 1624637..32b2ae4 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -25,13 +25,13 @@ void startService({ registerAuthRoutes(app, db, config); registerAccountRoutes(app, db, config); registerChatRoutes(app, db, config); - registerDirectoryRoutes(app, db); + registerDirectoryRoutes(app, db, config); registerFolderRoutes(app, db, config); registerFileRoutes(app, db, config); registerUploadRoutes(app, db, config); - registerMediaRoutes(app, db); + registerMediaRoutes(app, db, config); registerTrashRoutes(app, db, config); - registerSearchRoutes(app, db); + registerSearchRoutes(app, db, config); registerAdminRoutes(app, db, config); }, onReady: async ({ db, config, logger }) => { @@ -48,5 +48,18 @@ void startService({ logger.error("purge des envois inacheves", { error: String(error) }), ); }, 60 * 60 * 1000).unref(); + + // Sessions expirees et corbeille hors retention : sans ce balayage, elles + // ne disparaissent qu'au redemarrage. Les jetons expires sont deja refuses + // a chaque requete ; il s'agit ici d'eviter une table qui grossit sans fin + // et de faire respecter la retention de la corbeille sans redemarrage. + setInterval(() => { + void purgeExpiredSessions(db).catch((error: unknown) => + logger.error("purge des sessions expirees", { error: String(error) }), + ); + void purgeExpiredTrash(db, config).catch((error: unknown) => + logger.error("purge de la corbeille", { error: String(error) }), + ); + }, 60 * 60 * 1000).unref(); }, }); diff --git a/backend/src/lib/auth.ts b/backend/src/lib/auth.ts index a33344f..f8dbaa5 100644 --- a/backend/src/lib/auth.ts +++ b/backend/src/lib/auth.ts @@ -1,4 +1,11 @@ -import { createHash, randomBytes, randomUUID, scrypt as scryptCallback, timingSafeEqual } from "node:crypto"; +import { + createHash, + createHmac, + randomBytes, + randomUUID, + scrypt as scryptCallback, + timingSafeEqual, +} from "node:crypto"; import { promisify } from "node:util"; import type { Context, Next } from "hono"; import { getCookie, setCookie, deleteCookie } from "hono/cookie"; @@ -48,6 +55,17 @@ export const verifyPassword = async (password: string, stored: string): Promise< export const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex"); +/** + * Empreinte du jeton de session : SHA-256 poivre par SESSION_SECRET. + * + * Sans ce poivre, une ecriture frauduleuse dans `user_sessions` suffirait a + * forger une session : l'attaquant connaitrait le hachage a poser. Le secret + * vit hors de la base, donc une fuite de la base seule ne donne aucune session + * ouvrable. + */ +export const sessionTokenHash = (token: string, secret: string): string => + createHmac("sha256", secret).update(token).digest("hex"); + /** * Portrait de l'utilisateur porte par la session. * @@ -74,15 +92,17 @@ export interface SessionMeta { export const SESSION_COOKIE = "cohaise_session"; /** - * Le jeton brut part dans le cookie, son empreinte SHA-256 dans la base. - * Une copie de la base ne donne donc aucune session ouvrable : il faudrait - * en plus la table des cookies, qui n'existe pas. + * Le jeton brut part dans le cookie, son empreinte HMAC-SHA-256 (poivree par + * SESSION_SECRET) dans la base. Une copie de la base ne donne donc aucune + * session ouvrable : il faudrait en plus la table des cookies, qui n'existe pas, + * et le secret, qui vit hors de la base. */ export const createSession = async ( db: Db, userId: string, meta: SessionMeta, ttlHours: number, + secret: string, ): Promise<{ token: string; expiresAt: Date }> => { const token = randomBytes(32).toString("base64url"); const expiresAt = new Date(Date.now() + ttlHours * 3600_000); @@ -93,7 +113,7 @@ export const createSession = async ( [ randomUUID(), userId, - sha256(token), + sessionTokenHash(token, secret), meta.ipAddress ?? null, meta.userAgent?.slice(0, 255) ?? null, expiresAt, @@ -102,7 +122,11 @@ export const createSession = async ( return { token, expiresAt }; }; -export const resolveSession = async (db: Db, token: string): Promise => { +export const resolveSession = async ( + db: Db, + token: string, + secret: string, +): Promise => { const row = await db.one( `SELECT u.id, u.email, u.first_name, u.last_name, r.slug AS role_slug, r.name AS role_name, @@ -116,20 +140,20 @@ export const resolveSession = async (db: Db, token: string): Promise UTC_TIMESTAMP() AND u.deleted_at IS NULL AND u.is_active = 1`, - [sha256(token)], + [sessionTokenHash(token, secret)], ); if (!row) return null; // Etat vu, avec un decalage de 60 s pour ne pas ecrire a chaque requete. await db.exec( "UPDATE user_sessions SET last_seen_at = UTC_TIMESTAMP() WHERE token_hash = ? AND last_seen_at < UTC_TIMESTAMP(3) - INTERVAL 60 SECOND", - [sha256(token)], + [sessionTokenHash(token, secret)], ); return row; }; -export const revokeSession = async (db: Db, token: string): Promise => { +export const revokeSession = async (db: Db, token: string, secret: string): Promise => { await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE token_hash = ?", [ - sha256(token), + sessionTokenHash(token, secret), ]); }; @@ -183,11 +207,11 @@ export interface AuthState { /** Lit le cookie et attache l'utilisateur, sans exiger qu'il existe. */ export const attachUser = - (db: Db) => + (db: Db, secret: string) => async (context: Context, next: Next): Promise => { const token = getCookie(context, SESSION_COOKIE); if (token) { - const user = await resolveSession(db, token); + const user = await resolveSession(db, token, secret); if (user) { context.set("user", user); context.set("token", token); @@ -198,9 +222,23 @@ export const attachUser = await next(); }; +/** + * Routes encore accessibles lorsqu'un changement de mot de passe est impose : + * lire son profil, changer le mot de passe, se deconnecter. Tout le reste est + * refuse cote serveur, et pas seulement par la redirection du client. + */ +const PASSWORD_CHANGE_ALLOWED = new Set([ + "/api/cloud/auth/me", + "/api/cloud/auth/change-password", + "/api/cloud/auth/logout", +]); + export const requireAuth = async (context: Context, next: Next): Promise => { 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(); }; diff --git a/backend/src/lib/http.ts b/backend/src/lib/http.ts index de0a920..0975c70 100644 --- a/backend/src/lib/http.ts +++ b/backend/src/lib/http.ts @@ -75,6 +75,62 @@ export const clientIp = (context: Context, trustProxy: boolean): string | null = return address ? address.slice(0, 45) : null; }; +/** Taille maximale d'un corps JSON. Les envois de fichiers ont leur propre flux borne. */ +export const JSON_BODY_MAX_BYTES = 1024 * 1024; + +/** + * Lit le corps de la requete en memoire, avec une borne dure sur les octets + * reellement recus. `content-length` est verifie d'abord pour refuser tot, mais + * la lecture bornee est la vraie garantie : un client peut mentir sur l'en-tete + * et envoyer davantage que ce qu'il annonce. + */ +export const readBodyCapped = async (context: Context, maxBytes: number): Promise => { + const declared = Number(context.req.header("content-length") ?? ""); + if (Number.isFinite(declared) && declared > maxBytes) { + throw AppError.payloadTooLarge("Corps de requete trop volumineux."); + } + + const body = context.req.raw.body; + if (body === null) return Buffer.alloc(0); + + const chunks: Uint8Array[] = []; + let received = 0; + const reader = body.getReader(); + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + received += value.byteLength; + if (received > maxBytes) { + await reader.cancel().catch(() => undefined); + throw AppError.payloadTooLarge("Corps de requete trop volumineux."); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + return Buffer.concat(chunks); +}; + +/** + * Parse le corps JSON avec la meme borne. Un corps absent ou illisible rend + * `null`, comme l'ancien `req.json().catch(() => null)` : les routes continuent + * de repondre par leur validation zod habituelle. + */ +export const readJson = async ( + context: Context, + maxBytes = JSON_BODY_MAX_BYTES, +): Promise => { + const buffer = await readBodyCapped(context, maxBytes); + if (buffer.byteLength === 0) return null; + try { + return JSON.parse(buffer.toString("utf8")) as unknown; + } catch { + return null; + } +}; + /** Dependances remises aux routes metier au montage. */ export interface RouteDeps { db: Db; diff --git a/backend/src/lib/index.ts b/backend/src/lib/index.ts index c8f191e..67ee19b 100644 --- a/backend/src/lib/index.ts +++ b/backend/src/lib/index.ts @@ -11,6 +11,9 @@ export { createApp, createLogger, clientIp, + JSON_BODY_MAX_BYTES, + readBodyCapped, + readJson, type App, type AppEnv, type AppOptions, @@ -29,6 +32,7 @@ export { purgeExpiredSessions, revokeSession, SESSION_COOKIE, + sessionTokenHash, setSessionCookie, sha256, verifyPassword, diff --git a/backend/src/media.ts b/backend/src/media.ts index ca0799e..01c8641 100644 --- a/backend/src/media.ts +++ b/backend/src/media.ts @@ -48,6 +48,17 @@ export const classify = (mime: string | null): MediaKind => { export const isImage = (mime: string | null): boolean => (mime ?? "").toLowerCase().startsWith("image/"); +/** + * Le SVG est une image au sens MIME, mais pas une image sure a decoder : + * librsvg peut resolvere des references externes et son moteur est une surface + * d'attaque supplementaire. Il est deja exclu de l'apercu en ligne ; on ne le + * passe pas non plus a sharp pour la vignette. Le fichier reste telechargeable. + */ +const isRasterImage = (mime: string | null): boolean => { + const value = (mime ?? "").toLowerCase(); + return value.startsWith("image/") && value !== "image/svg+xml"; +}; + export const thumbnailRelativePath = (fileId: string): string => path.posix.join("thumbnails", `${fileId}.webp`); @@ -99,7 +110,7 @@ export const indexMedia = async ( ): Promise => { const kind = classify(mimeType); - if (!isImage(mimeType)) { + if (!isRasterImage(mimeType)) { await db.exec( `INSERT INTO media_metadata (file_id, kind) VALUES (?, ?) ON DUPLICATE KEY UPDATE kind = VALUES(kind)`, diff --git a/backend/src/routes/account.ts b/backend/src/routes/account.ts index 83f6a7a..b97fbeb 100644 --- a/backend/src/routes/account.ts +++ b/backend/src/routes/account.ts @@ -15,8 +15,11 @@ import { hashPassword, link, rateLimitKey, + readBodyCapped, + readJson, renderMail, requireAuth, + sessionTokenHash, sha256, verifyPassword, type App, @@ -69,8 +72,8 @@ const emailChangeInput = z.object({ }); export const registerAccountRoutes = (app: App, db: Db, config: Config): void => { - app.use("/api/cloud/account/*", attachUser(db)); - app.use("/api/cloud/account", attachUser(db)); + 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); @@ -85,7 +88,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void => app.patch("/api/cloud/account/profile", requireAuth, async (context) => { const user = currentUser(context); - const data = parse(profileInput, await context.req.json().catch(() => null)); + 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, @@ -107,7 +110,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void => app.patch("/api/cloud/account/preferences", requireAuth, async (context) => { const user = currentUser(context); - const data = parse(preferencesInput, await context.req.json().catch(() => null)); + const data = parse(preferencesInput, await readJson(context)); await db.exec("UPDATE users SET theme = ?, language = ? WHERE id = ?", [ data.theme, data.language, @@ -118,7 +121,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void => app.get("/api/cloud/account/sessions", requireAuth, async (context) => { const user = currentUser(context); - const current = sha256(context.get("token") ?? ""); + const current = sessionTokenHash(context.get("token") ?? "", config.SESSION_SECRET); const rows = await db.query<{ id: string; token_hash: string; @@ -160,7 +163,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void => app.delete("/api/cloud/account/sessions", requireAuth, async (context) => { const user = currentUser(context); - const current = sha256(context.get("token") ?? ""); + 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], @@ -178,7 +181,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void => throw AppError.payloadTooLarge("L'image ne doit pas depasser 8 Mo."); } - const source = Buffer.from(await context.req.arrayBuffer()); + const source = await readBodyCapped(context, AVATAR_MAX_BYTES); let processed: Buffer; try { processed = await sharp(source, { failOn: "none" }) @@ -274,7 +277,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void => }); app.post("/api/cloud/account/forgot-password", async (context) => { - const data = parse(forgotInput, await context.req.json().catch(() => null)); + const data = parse(forgotInput, await readJson(context)); throttle(context, `forgot:${data.email.toLowerCase()}`); const user = await db.one<{ id: string; email: string }>( @@ -312,7 +315,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void => }); app.post("/api/cloud/account/reset-password", async (context) => { - const data = parse(resetInput, await context.req.json().catch(() => null)); + const data = parse(resetInput, await readJson(context)); throttle(context, "reset"); const row = await db.one<{ id: string; user_id: string }>( @@ -362,7 +365,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void => app.post("/api/cloud/account/email-change", requireAuth, async (context) => { const user = currentUser(context); - const data = parse(emailChangeInput, await context.req.json().catch(() => null)); + const data = parse(emailChangeInput, await readJson(context)); throttle(context, `email:${user.id}`); const row = await db.one<{ password_hash: string }>( @@ -419,7 +422,7 @@ export const registerAccountRoutes = (app: App, db: Db, config: Config): void => app.post("/api/cloud/account/email-change/confirm", async (context) => { const data = parse( z.object({ token: z.string().min(10).max(400) }), - await context.req.json().catch(() => null), + await readJson(context), ); const row = await db.one<{ id: string; user_id: string; new_email: string }>( diff --git a/backend/src/routes/admin.ts b/backend/src/routes/admin.ts index f59f904..764bc95 100644 --- a/backend/src/routes/admin.ts +++ b/backend/src/routes/admin.ts @@ -1,4 +1,4 @@ -import { randomUUID } from "node:crypto"; +import { randomInt, randomUUID } from "node:crypto"; import { z } from "zod"; import { AppError, @@ -10,6 +10,7 @@ import { link, renderMail, requireAuth, + readJson, type App, type Config, type Db, @@ -116,10 +117,10 @@ const humanBytes = (bytes: number): string => { /** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */ const generatePasswordValue = (): string => { const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; - const bytes = new Uint8Array(18); - globalThis.crypto.getRandomValues(bytes); + // randomInt borne directement l'intervalle : pas de biais modulo, contrairement + // a `octet % longueur` qui favorise les premiers caracteres de l'alphabet. let out = ""; - for (const byte of bytes) out += alphabet[byte % alphabet.length]; + for (let index = 0; index < 18; index += 1) out += alphabet[randomInt(alphabet.length)]; return out; }; @@ -208,8 +209,8 @@ const rehomeUserFolders = async (db: Db, userId: string): Promise<{ kept: number }; export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { - app.use("/api/cloud/admin/*", attachUser(db)); - app.use("/api/cloud/admin", attachUser(db)); + 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); @@ -285,7 +286,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { app.post("/api/cloud/admin/users", requireAuth, async (context) => { requireAdmin(context); - const data = parse(createUserSchema, await context.req.json().catch(() => null)); + 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."); @@ -339,7 +340,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { 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 context.req.json().catch(() => null)); + 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]); @@ -465,7 +466,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { app.post("/api/cloud/admin/storage-locations", requireAuth, async (context) => { requireAdmin(context); - const data = parse(createLocationSchema, await context.req.json().catch(() => null)); + const data = parse(createLocationSchema, await readJson(context)); if (data.quota_bytes !== undefined && data.quota_bytes !== null) { await assertQuotaFits(data.quota_bytes); } @@ -488,7 +489,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { requireAdmin(context); const id = Number(context.req.param("id")); if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Emplacement introuvable."); - const data = parse(updateLocationSchema, await context.req.json().catch(() => null)); + const 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", diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts index c68d637..a1a717d 100644 --- a/backend/src/routes/auth.ts +++ b/backend/src/routes/auth.ts @@ -10,10 +10,11 @@ import { hashPassword, isHttpsRequest, rateLimitKey, + readJson, requireAuth, revokeSession, + sessionTokenHash, setSessionCookie, - sha256, verifyPassword, type App, type Config, @@ -87,7 +88,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => { context.header("cache-control", "no-store"); }); - app.use("/api/cloud/*", attachUser(db)); + 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) => { @@ -98,7 +99,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => { throw AppError.unprocessable("Trop de tentatives de connexion. Reessayez dans une minute."); } - const parsed = credentials.safeParse(await context.req.json().catch(() => null)); + const parsed = credentials.safeParse(await readJson(context)); if (!parsed.success) throw AppError.badRequest("Identifiants invalides."); const { email, password } = parsed.data; @@ -120,6 +121,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => { 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]); @@ -135,7 +137,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => { app.post("/api/cloud/auth/logout", requireAuth, async (context) => { const token = context.get("token"); - if (token) await revokeSession(db, token); + if (token) await revokeSession(db, token, config.SESSION_SECRET); clearSessionCookie(context); return context.json({ ok: true }); }); @@ -159,7 +161,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => { */ app.post("/api/cloud/auth/change-password", requireAuth, async (context) => { const session = currentUser(context); - const parsed = changePassword.safeParse(await context.req.json().catch(() => null)); + const parsed = changePassword.safeParse(await readJson(context)); if (!parsed.success) { throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres."); } @@ -189,7 +191,7 @@ export const registerAuthRoutes = (app: App, db: Db, config: Config): void => { `UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`, - [session.id, sha256(context.get("token") ?? "")], + [session.id, sessionTokenHash(context.get("token") ?? "", config.SESSION_SECRET)], ); return context.json({ ok: true }); diff --git a/backend/src/routes/chat.ts b/backend/src/routes/chat.ts index d86d967..8db3e60 100644 --- a/backend/src/routes/chat.ts +++ b/backend/src/routes/chat.ts @@ -3,6 +3,7 @@ import { AppError, createRateLimiter, currentUser, + readJson, requireAuth, type App, type Config, @@ -258,7 +259,7 @@ export const registerChatRoutes = (app: App, db: Db, config: Config): void => { if (!limiter.allow(user.id)) { throw AppError.unprocessable("Vous envoyez des messages trop rapidement."); } - const parsed = sendInput.safeParse(await context.req.json().catch(() => null)); + const parsed = sendInput.safeParse(await readJson(context)); if (!parsed.success) { throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide."); } @@ -292,7 +293,7 @@ export const registerChatRoutes = (app: App, db: Db, config: Config): void => { throw AppError.unprocessable("Vous envoyez des messages trop rapidement."); } - const parsed = editInput.safeParse(await context.req.json().catch(() => null)); + const parsed = editInput.safeParse(await readJson(context)); if (!parsed.success) { throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide."); } diff --git a/backend/src/routes/directory.ts b/backend/src/routes/directory.ts index 248fef2..44bd756 100644 --- a/backend/src/routes/directory.ts +++ b/backend/src/routes/directory.ts @@ -3,6 +3,7 @@ import { currentUser, requireAuth, type App, + type Config, type Db, } from "../lib/index.js"; @@ -11,8 +12,8 @@ import { * destinataire lors d'un partage. La session courante est exclue : on ne se * partage pas un dossier a soi-meme. Aucune donnee sensible n'est exposee. */ -export const registerDirectoryRoutes = (app: App, db: Db): void => { - app.use("/api/cloud/directory", attachUser(db)); +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); diff --git a/backend/src/routes/files.ts b/backend/src/routes/files.ts index 53ad970..f6a9713 100644 --- a/backend/src/routes/files.ts +++ b/backend/src/routes/files.ts @@ -8,6 +8,7 @@ import { currentUser, requireAuth, requireRole, + readJson, type App, type Config, type Db, @@ -206,8 +207,8 @@ const serveFile = ({ absolute, size, mime, disposition, range }: ServeOptions): }; export const registerFileRoutes = (app: App, db: Db, config: Config): void => { - app.use("/api/cloud/files/*", attachUser(db)); - app.use("/api/cloud/files", attachUser(db)); + app.use("/api/cloud/files/*", attachUser(db, config.SESSION_SECRET)); + app.use("/api/cloud/files", attachUser(db, config.SESSION_SECRET)); /** * Depot en un seul passage. Le corps n'est pas un formulaire multipart mais @@ -589,7 +590,7 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => { (row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id))); if (!permitted) throw AppError.notFound("Fichier introuvable."); - const { name: rawName } = parse(renameInput, await context.req.json().catch(() => null)); + const { name: rawName } = parse(renameInput, await readJson(context)); const name = assertName(rawName); try { @@ -624,7 +625,7 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => { (row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id))); if (!canLeave) throw AppError.notFound("Fichier introuvable."); - const { folderId } = parse(moveInput, await context.req.json().catch(() => null)); + const { folderId } = parse(moveInput, await readJson(context)); const destination = folderId ?? null; if (destination !== null && !(await canWrite(db, user, destination))) { diff --git a/backend/src/routes/folders.ts b/backend/src/routes/folders.ts index 17ae818..82f3c04 100644 --- a/backend/src/routes/folders.ts +++ b/backend/src/routes/folders.ts @@ -6,6 +6,7 @@ import { currentUser, requireAuth, requireRole, + readJson, type App, type Config, type Db, @@ -102,8 +103,8 @@ const subtreeIds = async (db: Db, rootId: string): Promise => { }; export const registerFolderRoutes = (app: App, db: Db, config: Config): void => { - app.use("/api/cloud/folders/*", attachUser(db)); - app.use("/api/cloud/folders", attachUser(db)); + app.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); @@ -149,7 +150,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void => const user = currentUser(context); const { name: rawName, parentId } = parse( createFolder, - await context.req.json().catch(() => null), + await readJson(context), ); const name = assertName(rawName); @@ -222,7 +223,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void => if (!existing) throw AppError.notFound("Dossier introuvable."); if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable."); - const data = parse(updateFolder, await context.req.json().catch(() => null)); + const data = parse(updateFolder, await readJson(context)); const name = assertName(data.name); try { @@ -249,7 +250,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void => if (existing.is_system === 1) throw AppError.forbidden("Le dossier public ne peut pas etre deplace."); if (!(await canManageFolder(db, user, id))) throw AppError.notFound("Dossier introuvable."); - const { parentId } = parse(moveFolder, await context.req.json().catch(() => null)); + const { parentId } = parse(moveFolder, await readJson(context)); if (parentId !== null && parentId !== undefined) { if (!(await canWrite(db, user, parentId))) { @@ -350,7 +351,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void => const { email, level, expiresAt } = parse( permissionInput, - await context.req.json().catch(() => null), + await readJson(context), ); const target = await db.one<{ id: string }>( diff --git a/backend/src/routes/media.ts b/backend/src/routes/media.ts index 557a54e..e38e27d 100644 --- a/backend/src/routes/media.ts +++ b/backend/src/routes/media.ts @@ -4,6 +4,7 @@ import { currentUser, requireAuth, type App, + type Config, type Db, } from "../lib/index.js"; @@ -15,8 +16,8 @@ import { const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const; -export const registerMediaRoutes = (app: App, db: Db): void => { - app.use("/api/cloud/media", attachUser(db)); +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); diff --git a/backend/src/routes/search.ts b/backend/src/routes/search.ts index 882a758..a5e7666 100644 --- a/backend/src/routes/search.ts +++ b/backend/src/routes/search.ts @@ -4,6 +4,7 @@ import { currentUser, requireAuth, type App, + type Config, type Db, } from "../lib/index.js"; @@ -19,8 +20,8 @@ const escapeLike = (value: string): string => const LIMIT = 100; -export const registerSearchRoutes = (app: App, db: Db): void => { - app.use("/api/cloud/search", attachUser(db)); +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); diff --git a/backend/src/routes/trash.ts b/backend/src/routes/trash.ts index adfb4eb..0d209e0 100644 --- a/backend/src/routes/trash.ts +++ b/backend/src/routes/trash.ts @@ -158,8 +158,8 @@ const publicFolder = (row: TrashFolderRow) => ({ }); export const registerTrashRoutes = (app: App, db: Db, config: Config): void => { - app.use("/api/cloud/trash/*", attachUser(db)); - app.use("/api/cloud/trash", attachUser(db)); + app.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); diff --git a/backend/src/routes/uploads.ts b/backend/src/routes/uploads.ts index d0115e2..e088d09 100644 --- a/backend/src/routes/uploads.ts +++ b/backend/src/routes/uploads.ts @@ -8,6 +8,7 @@ import { currentUser, requireAuth, requireRole, + readJson, type App, type Config, type Db, @@ -143,8 +144,8 @@ const assertNameFree = async ( }; export const registerUploadRoutes = (app: App, db: Db, config: Config): void => { - app.use("/api/cloud/uploads/*", attachUser(db)); - app.use("/api/cloud/uploads", attachUser(db)); + 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", @@ -152,7 +153,7 @@ export const registerUploadRoutes = (app: App, db: Db, config: Config): void => requireRole("admin", "user"), async (context) => { const user = currentUser(context); - const data = parse(createInput, await context.req.json().catch(() => null)); + const data = parse(createInput, await readJson(context)); const name = assertName(data.name); const folderId = data.folderId ?? null; const size = data.size; diff --git a/docker-compose.yml b/docker-compose.yml index e7bedc1..f32051b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -24,9 +24,6 @@ x-app: &app x-migrate-build: &migrate-build context: . dockerfile: docker/Dockerfile.api - # Le build utilise le reseau de l'hote : le demon Docker resout parfois un - # DNS mort (routeur), ce qui casse `npm ci` dans le conteneur. - network: host args: APP_DIR: backend @@ -37,7 +34,6 @@ services: context: . dockerfile: docker/Dockerfile.app target: export - network: host args: APP_DIR: frontend volumes: @@ -117,7 +113,6 @@ services: build: context: . dockerfile: docker/Dockerfile.api - network: host args: APP_DIR: backend image: cohaise-cloud-api diff --git a/docker/nginx/cloud.conf b/docker/nginx/cloud.conf index ae8b452..04a2ff6 100644 --- a/docker/nginx/cloud.conf +++ b/docker/nginx/cloud.conf @@ -63,6 +63,8 @@ server { } location @spa { + include /etc/nginx/snippets/security-headers.conf; + include /etc/nginx/snippets/cache-no-cache.conf; try_files /index.html =404; } } diff --git a/docs/agents.md b/docs/agents.md index 28fdce9..162afca 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -68,8 +68,10 @@ Le design system vit dans `frontend/src/ui`. - **`.env` ≠ `.env.example`** : comparer avant de conclure à un bug de port. - **README de paquet périmés** — utiliser ce dossier `docs/`. -- **Build Docker et DNS** : les `build:` passent par `network: host` ; si `npm ci` - échoue par `EAI_AGAIN`, le résolveur du démon est en cause. +- **Build Docker et DNS** : les `build:` utilisent le réseau Docker par défaut. + `network: host` est évité : Compose 5.6 / Buildx 0.38 refuse alors le build + (`additional privileges requested`), sans transmettre `--allow=network.host`. + Si `npm ci` échoue par `EAI_AGAIN`, corriger le DNS du démon Docker. - **Limitation de débit active** (applicatif + nginx) : un test en rafale peut recevoir `419`/`503` côté API ou `503` nginx — ce n'est pas un bug. - Après `make up`, vérifier l'ordre : `migrate` doit être `exited (0)` avant que diff --git a/docs/architecture.md b/docs/architecture.md index 88641cd..efcff1d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -44,7 +44,8 @@ app-build (publish.sh, terminé avant nginx) - `migrate` monte `./backend/migrations:/migrations:ro`. - `api` refuse de démarrer si une migration appliquée a été modifiée (dérive de - checksum). `onReady` purge les sessions et la corbeille expirées. + checksum). `onReady` purge les sessions, la corbeille et les envois inachevés, + puis un balayage horaire reprend ces purges sans redémarrage. - stockage : `app_data` (volume Docker, HTML), `$CLOUD_DB_DIR` (MariaDB) et `$CLOUD_MEDIA_DIR` (fichiers) en bind mounts hôte. diff --git a/docs/deployment.md b/docs/deployment.md index 82506d2..3b1a38a 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -26,7 +26,7 @@ pose problème (`backend/src/lib/config.ts`). | `CLOUD_DB_DIR` | dossier hôte des données MariaDB | `../db` | | `CLOUD_MEDIA_DIR` | dossier hôte des médias | `../media` | | `CLOUD_DB_CONNECTION_LIMIT` | taille du pool | `8` | -| `SESSION_SECRET` | **obligatoire**, ≥ 32 car. | — | +| `SESSION_SECRET` | **obligatoire**, ≥ 32 car., poivre HMAC des jetons de session | — | | `SESSION_TTL_HOURS` | durée de session | `336` | | `PUBLIC_ORIGIN` | **obligatoire**, URL absolue servant aux liens courriel | — | | `CLOUD_CORS_ORIGIN` | origines CORS (vide = CORS off) | vide | diff --git a/docs/security.md b/docs/security.md index ebf7449..b224190 100644 --- a/docs/security.md +++ b/docs/security.md @@ -7,10 +7,11 @@ | Mesure | Détail | | --- | --- | | Mots de passe | `scrypt` natif `node:crypto` (`N=16384, r=8, p=1`, keylen 64, sel 16 o.), comparaison `timingSafeEqual` | -| Stockage session | jeton aléatoire 32 o. côté client, **SHA-256** en base | +| Stockage session | jeton aléatoire 32 o. côté client, **HMAC-SHA-256 poivré par `SESSION_SECRET`** en base | | Cookie | `cohaise_session`, `httpOnly`, `SameSite=Lax`, `path=/`, `secure` selon le schéma réel | | Expiration | `SESSION_TTL_HOURS` (336 h) ; `revoked_at`, `is_active`, `deleted_at` vérifiés à chaque résolution | -| Révocation | logout, purge au démarrage, **toutes les autres sessions** au changement de mot de passe, gestion des sessions ouvertes depuis le compte | +| Révocation | logout, purge au démarrage et **toutes les heures**, **toutes les autres sessions** au changement de mot de passe, gestion des sessions ouvertes depuis le compte | +| Changement imposé | `must_change_password` vérifié dans `requireAuth` : seules `auth/me`, `auth/change-password` et `auth/logout` restent accessibles, la redirection du front n'est qu'un confort | | Anti-énumération | hash factice pour une adresse inconnue ; les flux « mot de passe oublié » répondent toujours `{ ok: true }` sans révéler l'existence du compte | | Jetons à usage unique | réinitialisation de mot de passe et changement d'adresse stockés **hachés**, avec expiration | | Changement d'adresse | mot de passe actuel exigé, confirmation **à la nouvelle adresse** avant application | @@ -24,6 +25,14 @@ - **Edge nginx** : zones `limit_req` `login` (15 r/min, burst 5) et `api` (60 r/s, burst élevé) — voir `docker/nginx/cloud.conf`. +### Limites d'entrée + +- Les corps JSON passent par `readJson` : **1 Mio** maximum, lecture bornée + même si `content-length` ment (le flux est coupé au-delà). +- L'avatar passe par `readBodyCapped` : **8 Mio** maximum, même garantie. +- Les envois de fichiers ont leur propre flux borné (`storage.ts`), indépendant + de `client_max_body_size` de nginx. + ### Droits d'accès Calculés **en base à chaque requête**, depuis la session — jamais depuis un @@ -84,6 +93,8 @@ aucun HTML utilisateur n'est injecté dans les messages. une **liste blanche** de types (`image/*` hors `image/svg+xml`, `video/*`, `audio/*`, `application/pdf`, `text/plain`) — jamais de HTML/SVG qui s'exécuterait dans l'origine. Les deux routes gèrent `Range` (206 / 416). +- Vignettes : le SVG est aussi exclu du passage à `sharp`/librsvg ; il reste + téléchargeable, mais n'est jamais décodé côté serveur. ## Hors périmètre (assumé) diff --git a/frontend/package.json b/frontend/package.json index 0ed7098..d33da8d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -14,12 +14,14 @@ "react": "^19.3.0", "react-dom": "^19.3.0", "react-router-dom": "^7.18.4", - "tailwind-merge": "^3.7.0" + "tailwind-merge": "^3.7.0", + "three": "^0.187.0" }, "devDependencies": { "@tailwindcss/vite": "^4.3.3", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", + "@types/three": "^0.187.0", "@vitejs/plugin-react": "^6.1.1", "tailwindcss": "^4.3.3", "typescript": "^7.0.2", diff --git a/frontend/public/icons/accounts.png b/frontend/public/icons/accounts.png new file mode 100644 index 0000000..90b20b2 Binary files /dev/null and b/frontend/public/icons/accounts.png differ diff --git a/frontend/public/icons/activity.png b/frontend/public/icons/activity.png new file mode 100644 index 0000000..4310f1a Binary files /dev/null and b/frontend/public/icons/activity.png differ diff --git a/frontend/public/icons/back.png b/frontend/public/icons/back.png new file mode 100644 index 0000000..c4c2a46 Binary files /dev/null and b/frontend/public/icons/back.png differ diff --git a/frontend/public/icons/close.png b/frontend/public/icons/close.png new file mode 100644 index 0000000..b48d828 Binary files /dev/null and b/frontend/public/icons/close.png differ diff --git a/frontend/public/icons/deactivate.png b/frontend/public/icons/deactivate.png new file mode 100644 index 0000000..ae09410 Binary files /dev/null and b/frontend/public/icons/deactivate.png differ diff --git a/frontend/public/icons/document.png b/frontend/public/icons/document.png new file mode 100644 index 0000000..fcce327 Binary files /dev/null and b/frontend/public/icons/document.png differ diff --git a/frontend/public/icons/download.png b/frontend/public/icons/download.png new file mode 100644 index 0000000..274548f Binary files /dev/null and b/frontend/public/icons/download.png differ diff --git a/frontend/public/icons/edit-pencil.png b/frontend/public/icons/edit-pencil.png new file mode 100644 index 0000000..3aaba14 Binary files /dev/null and b/frontend/public/icons/edit-pencil.png differ diff --git a/frontend/public/icons/favorite.png b/frontend/public/icons/favorite.png new file mode 100644 index 0000000..8591ee9 Binary files /dev/null and b/frontend/public/icons/favorite.png differ diff --git a/frontend/public/icons/file.png b/frontend/public/icons/file.png new file mode 100644 index 0000000..e37e388 Binary files /dev/null and b/frontend/public/icons/file.png differ diff --git a/frontend/public/icons/folder.png b/frontend/public/icons/folder.png new file mode 100644 index 0000000..08e9057 Binary files /dev/null and b/frontend/public/icons/folder.png differ diff --git a/frontend/public/icons/image-file.png b/frontend/public/icons/image-file.png new file mode 100644 index 0000000..52d5b13 Binary files /dev/null and b/frontend/public/icons/image-file.png differ diff --git a/frontend/public/icons/menu.png b/frontend/public/icons/menu.png new file mode 100644 index 0000000..ba7c471 Binary files /dev/null and b/frontend/public/icons/menu.png differ diff --git a/frontend/public/icons/move.png b/frontend/public/icons/move.png new file mode 100644 index 0000000..d1a8bce Binary files /dev/null and b/frontend/public/icons/move.png differ diff --git a/frontend/public/icons/opened-folder.png b/frontend/public/icons/opened-folder.png new file mode 100644 index 0000000..d4321fb Binary files /dev/null and b/frontend/public/icons/opened-folder.png differ diff --git a/frontend/public/icons/password-reset.png b/frontend/public/icons/password-reset.png new file mode 100644 index 0000000..1c87c06 Binary files /dev/null and b/frontend/public/icons/password-reset.png differ diff --git a/frontend/public/icons/personal-settings.png b/frontend/public/icons/personal-settings.png new file mode 100644 index 0000000..a5ff138 Binary files /dev/null and b/frontend/public/icons/personal-settings.png differ diff --git a/frontend/public/icons/picture.png b/frontend/public/icons/picture.png new file mode 100644 index 0000000..09c57dc Binary files /dev/null and b/frontend/public/icons/picture.png differ diff --git a/frontend/public/icons/plus.png b/frontend/public/icons/plus.png new file mode 100644 index 0000000..393d944 Binary files /dev/null and b/frontend/public/icons/plus.png differ diff --git a/frontend/public/icons/search.png b/frontend/public/icons/search.png new file mode 100644 index 0000000..50e78e0 Binary files /dev/null and b/frontend/public/icons/search.png differ diff --git a/frontend/public/icons/send.png b/frontend/public/icons/send.png new file mode 100644 index 0000000..4ada70e Binary files /dev/null and b/frontend/public/icons/send.png differ diff --git a/frontend/public/icons/share.png b/frontend/public/icons/share.png new file mode 100644 index 0000000..6842ad9 Binary files /dev/null and b/frontend/public/icons/share.png differ diff --git a/frontend/public/icons/sign-out.png b/frontend/public/icons/sign-out.png new file mode 100644 index 0000000..195f8f8 Binary files /dev/null and b/frontend/public/icons/sign-out.png differ diff --git a/frontend/public/icons/speech-bubble.png b/frontend/public/icons/speech-bubble.png new file mode 100644 index 0000000..0fedfad Binary files /dev/null and b/frontend/public/icons/speech-bubble.png differ diff --git a/frontend/public/icons/storage.png b/frontend/public/icons/storage.png new file mode 100644 index 0000000..4451616 Binary files /dev/null and b/frontend/public/icons/storage.png differ diff --git a/frontend/public/icons/synchronize.png b/frontend/public/icons/synchronize.png new file mode 100644 index 0000000..1e8a3e8 Binary files /dev/null and b/frontend/public/icons/synchronize.png differ diff --git a/frontend/public/icons/trash-can.png b/frontend/public/icons/trash-can.png new file mode 100644 index 0000000..cb6cd28 Binary files /dev/null and b/frontend/public/icons/trash-can.png differ diff --git a/frontend/public/icons/upload.png b/frontend/public/icons/upload.png new file mode 100644 index 0000000..4677773 Binary files /dev/null and b/frontend/public/icons/upload.png differ diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d620a92..c4ceb59 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,6 +2,7 @@ import { Navigate, Outlet, Route, Routes } from "react-router-dom"; import { Spinner } from "./ui/index.js"; import { useSession } from "./lib/session.js"; import { AppShell } from "./components/AppShell.js"; +import { AuthLayout } from "./components/AuthLayout.js"; import { Login } from "./pages/Login.js"; import { ForgotPassword } from "./pages/ForgotPassword.js"; import { ResetPassword } from "./pages/ResetPassword.js"; @@ -42,13 +43,17 @@ const RequireAdmin = () => { export const App = () => ( - } /> - } /> - } /> - } /> + }> + } /> + } /> + } /> + } /> + }> - } /> + }> + } /> + }> }> diff --git a/frontend/src/components/AppShell.tsx b/frontend/src/components/AppShell.tsx index 0d7d90c..17364bf 100644 --- a/frontend/src/components/AppShell.tsx +++ b/frontend/src/components/AppShell.tsx @@ -1,9 +1,10 @@ -import { useState } from "react"; +import { createContext, useContext, useEffect, useState, type ReactNode } from "react"; import { NavLink, Outlet } from "react-router-dom"; -import { Button, cn } from "../ui/index.js"; +import { cn } from "../ui/index.js"; import { useSession } from "../lib/session.js"; import { useI18n } from "../lib/i18n.js"; import { Avatar } from "./Avatar.js"; +import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js"; import { ActivityIcon, CloseIcon, @@ -18,6 +19,7 @@ import { StarIcon, TrashIcon, } from "./icons.js"; +import { IconAction } from "./IconAction.js"; interface NavItem { to: string; @@ -49,10 +51,27 @@ const navClass = ({ isActive }: { isActive: boolean }) => : "text-muted-foreground hover:bg-surface-hover hover:text-foreground", ); +type PageHeaderContextValue = { + header: ReactNode | null; + setHeader: (header: ReactNode | null) => void; +}; + +const PageHeaderContext = createContext(null); + +export const usePageHeader = (header: ReactNode | null) => { + const ctx = useContext(PageHeaderContext); + useEffect(() => { + if (!ctx) return; + ctx.setHeader(header); + return () => ctx.setHeader(null); + }, [ctx, header]); +}; + export const AppShell = () => { const { user, logout } = useSession(); const { t } = useI18n(); const [menuOpen, setMenuOpen] = useState(false); + const [pageHeader, setPageHeader] = useState(null); if (!user) return null; const isAdmin = user.role_slug === "admin"; @@ -88,24 +107,12 @@ export const AppShell = () => { }; return ( -
- + +
+ -
-
-
+
+
- {brand} + {brand}
@@ -135,30 +142,62 @@ export const AppShell = () => { hasAvatar={user.has_avatar} avatarUpdatedAt={user.avatar_updated_at} /> - + />
- {menuOpen ? ( - - ) : null}
-
-
- -
+ + + {menuOpen ? ( +
+
setMenuOpen(false)} aria-hidden="true" /> + +
+ ) : null} + +
+
+
+ {pageHeader ?
{pageHeader}
: null} +
+ +
+
+
-
+ ); }; diff --git a/frontend/src/components/AuthLayout.tsx b/frontend/src/components/AuthLayout.tsx new file mode 100644 index 0000000..e024878 --- /dev/null +++ b/frontend/src/components/AuthLayout.tsx @@ -0,0 +1,20 @@ +import { Outlet } from "react-router-dom"; +import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js"; + +/** + * Coque des ecrans d'authentification : fond carmin animé, puis une colonne + * centree qui contient la page courante. Le degrade garantit la lisibilite des + * cartes et des champs par-dessus le shader, dans les deux themes. + */ +export const AuthLayout = () => ( +
+ +
+); diff --git a/frontend/src/components/ColorBends.css b/frontend/src/components/ColorBends.css new file mode 100644 index 0000000..07f7f04 --- /dev/null +++ b/frontend/src/components/ColorBends.css @@ -0,0 +1,12 @@ +.color-bends-container { + position: relative; + width: 100%; + height: 100%; + overflow: hidden; +} + +.color-bends-container canvas { + display: block; + width: 100%; + height: 100%; +} diff --git a/frontend/src/components/ColorBends.tsx b/frontend/src/components/ColorBends.tsx new file mode 100644 index 0000000..a38f277 --- /dev/null +++ b/frontend/src/components/ColorBends.tsx @@ -0,0 +1,438 @@ +import { useEffect, useRef, type CSSProperties } from "react"; +import { + Clock, + Mesh, + OrthographicCamera, + PlaneGeometry, + Scene, + ShaderMaterial, + SRGBColorSpace, + Vector2, + Vector3, + WebGLRenderer, + type IUniform, +} from "three"; +import "./ColorBends.css"; + +/** + * Fond anime "ColorBends" (React Bits), porte en TypeScript pour le projet. + * + * Le rendu est un shader plein ecran : aucune image, aucun appel reseau. Le + * composant respecte `prefers-reduced-motion` en figeant le shader apres une + * premiere image, et libere le contexte WebGL au demontage. + */ + +const MAX_COLORS = 8; + +const frag = ` +#define MAX_COLORS ${MAX_COLORS} +uniform vec2 uCanvas; +uniform float uTime; +uniform float uSpeed; +uniform vec2 uRot; +uniform int uColorCount; +uniform vec3 uColors[MAX_COLORS]; +uniform int uTransparent; +uniform float uScale; +uniform float uFrequency; +uniform float uWarpStrength; +uniform vec2 uPointer; +uniform float uMouseInfluence; +uniform float uParallax; +uniform float uNoise; +uniform int uIterations; +uniform float uIntensity; +uniform float uBandWidth; +varying vec2 vUv; + +void main() { + float t = uTime * uSpeed; + vec2 p = vUv * 2.0 - 1.0; + p += uPointer * uParallax * 0.1; + vec2 rp = vec2(p.x * uRot.x - p.y * uRot.y, p.x * uRot.y + p.y * uRot.x); + vec2 q = vec2(rp.x * (uCanvas.x / uCanvas.y), rp.y); + q /= max(uScale, 0.0001); + q /= 0.5 + 0.2 * dot(q, q); + q += 0.2 * cos(t) - 7.56; + vec2 toward = (uPointer - rp); + q += toward * uMouseInfluence * 0.2; + + for (int j = 0; j < 5; j++) { + if (j >= uIterations - 1) break; + vec2 rr = sin(1.5 * (q.yx * uFrequency) + 2.0 * cos(q * uFrequency)); + q += (rr - q) * 0.15; + } + + vec3 col = vec3(0.0); + float a = 1.0; + + if (uColorCount > 0) { + vec2 s = q; + vec3 sumCol = vec3(0.0); + float cover = 0.0; + for (int i = 0; i < MAX_COLORS; ++i) { + if (i >= uColorCount) break; + s -= 0.01; + vec2 r = sin(1.5 * (s.yx * uFrequency) + 2.0 * cos(s * uFrequency)); + float m0 = length(r + sin(5.0 * r.y * uFrequency - 3.0 * t + float(i)) / 4.0); + float kBelow = clamp(uWarpStrength, 0.0, 1.0); + float kMix = pow(kBelow, 0.3); + float gain = 1.0 + max(uWarpStrength - 1.0, 0.0); + vec2 disp = (r - s) * kBelow; + vec2 warped = s + disp * gain; + float m1 = length(warped + sin(5.0 * warped.y * uFrequency - 3.0 * t + float(i)) / 4.0); + float m = mix(m0, m1, kMix); + float w = 1.0 - exp(-uBandWidth / exp(uBandWidth * m)); + sumCol += uColors[i] * w; + cover = max(cover, w); + } + col = clamp(sumCol, 0.0, 1.0); + a = uTransparent > 0 ? cover : 1.0; + } else { + vec2 s = q; + for (int k = 0; k < 3; ++k) { + s -= 0.01; + vec2 r = sin(1.5 * (s.yx * uFrequency) + 2.0 * cos(s * uFrequency)); + float m0 = length(r + sin(5.0 * r.y * uFrequency - 3.0 * t + float(k)) / 4.0); + float kBelow = clamp(uWarpStrength, 0.0, 1.0); + float kMix = pow(kBelow, 0.3); + float gain = 1.0 + max(uWarpStrength - 1.0, 0.0); + vec2 disp = (r - s) * kBelow; + vec2 warped = s + disp * gain; + float m1 = length(warped + sin(5.0 * warped.y * uFrequency - 3.0 * t + float(k)) / 4.0); + float m = mix(m0, m1, kMix); + col[k] = 1.0 - exp(-uBandWidth / exp(uBandWidth * m)); + } + a = uTransparent > 0 ? max(max(col.r, col.g), col.b) : 1.0; + } + + col *= uIntensity; + + if (uNoise > 0.0001) { + float n = fract(sin(dot(gl_FragCoord.xy + vec2(uTime), vec2(12.9898, 78.233))) * 43758.5453123); + col += (n - 0.5) * uNoise; + col = clamp(col, 0.0, 1.0); + } + + vec3 rgb = (uTransparent > 0) ? col * a : col; + gl_FragColor = vec4(rgb, a); +} +`; + +const vert = ` +varying vec2 vUv; +void main() { + vUv = uv; + gl_Position = vec4(position, 1.0); +} +`; + +export interface ColorBendsProps { + className?: string; + style?: CSSProperties; + rotation?: number; + speed?: number; + colors?: string[]; + transparent?: boolean; + autoRotate?: number; + scale?: number; + frequency?: number; + warpStrength?: number; + mouseInfluence?: number; + parallax?: number; + noise?: number; + iterations?: number; + intensity?: number; + bandWidth?: number; +} + +interface ColorBendsUniforms { + uCanvas: IUniform; + uTime: IUniform; + uSpeed: IUniform; + uRot: IUniform; + uColorCount: IUniform; + uColors: IUniform; + uTransparent: IUniform; + uScale: IUniform; + uFrequency: IUniform; + uWarpStrength: IUniform; + uPointer: IUniform; + uMouseInfluence: IUniform; + uParallax: IUniform; + uNoise: IUniform; + uIterations: IUniform; + uIntensity: IUniform; + uBandWidth: IUniform; +} + +const toVec3 = (hex: string): Vector3 => { + const value = hex.replace("#", "").trim(); + const channels = + value.length === 3 + ? [ + parseInt(value.slice(0, 1).repeat(2), 16), + parseInt(value.slice(1, 2).repeat(2), 16), + parseInt(value.slice(2, 3).repeat(2), 16), + ] + : [ + parseInt(value.slice(0, 2), 16), + parseInt(value.slice(2, 4), 16), + parseInt(value.slice(4, 6), 16), + ]; + return new Vector3(channels[0]! / 255, channels[1]! / 255, channels[2]! / 255); +}; + +export default function ColorBends({ + className, + style, + rotation = 90, + speed = 0.2, + colors = [], + transparent = true, + autoRotate = 0, + scale = 1, + frequency = 1, + warpStrength = 1, + mouseInfluence = 1, + parallax = 0.5, + noise = 0.15, + iterations = 1, + intensity = 1.5, + bandWidth = 6, +}: ColorBendsProps) { + const containerRef = useRef(null); + const rendererRef = useRef(null); + const rafRef = useRef(null); + const renderOnceRef = useRef<(() => void) | null>(null); + const materialRef = useRef(null); + const resizeObserverRef = useRef(null); + const rotationRef = useRef(rotation); + const autoRotateRef = useRef(autoRotate); + const pointerTargetRef = useRef(new Vector2(0, 0)); + const pointerCurrentRef = useRef(new Vector2(0, 0)); + const pointerSmoothRef = useRef(8); + + useEffect(() => { + const container = containerRef.current; + if (!container) return; + + let renderer: WebGLRenderer; + try { + renderer = new WebGLRenderer({ + antialias: false, + powerPreference: "high-performance", + alpha: true, + }); + } catch { + // Pas de WebGL (navigateur ancien, materiel bloque) : le fond reste + // simplement absent, l'ecran et le formulaire continuent de fonctionner. + return; + } + + const scene = new Scene(); + const camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1); + const geometry = new PlaneGeometry(2, 2); + const uColors = Array.from({ length: MAX_COLORS }, () => new Vector3(0, 0, 0)); + const material = new ShaderMaterial({ + vertexShader: vert, + fragmentShader: frag, + uniforms: { + uCanvas: { value: new Vector2(1, 1) }, + uTime: { value: 0 }, + uSpeed: { value: speed }, + uRot: { value: new Vector2(1, 0) }, + uColorCount: { value: 0 }, + uColors: { value: uColors }, + uTransparent: { value: transparent ? 1 : 0 }, + uScale: { value: scale }, + uFrequency: { value: frequency }, + uWarpStrength: { value: warpStrength }, + uPointer: { value: new Vector2(0, 0) }, + uMouseInfluence: { value: mouseInfluence }, + uParallax: { value: parallax }, + uNoise: { value: noise }, + uIterations: { value: iterations }, + uIntensity: { value: intensity }, + uBandWidth: { value: bandWidth }, + } satisfies ColorBendsUniforms, + premultipliedAlpha: true, + transparent: true, + }); + materialRef.current = material; + + const mesh = new Mesh(geometry, material); + scene.add(mesh); + + rendererRef.current = renderer; + renderer.outputColorSpace = SRGBColorSpace; + renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); + renderer.setClearColor(0x000000, transparent ? 0 : 1); + renderer.domElement.style.width = "100%"; + renderer.domElement.style.height = "100%"; + renderer.domElement.style.display = "block"; + container.appendChild(renderer.domElement); + + const clock = new Clock(); + const motion = window.matchMedia("(prefers-reduced-motion: reduce)"); + let reducedMotion = motion.matches; + + const handleResize = () => { + const width = container.clientWidth || 1; + const height = container.clientHeight || 1; + renderer.setSize(width, height, false); + material.uniforms.uCanvas!.value.set(width, height); + if (reducedMotion) renderer.render(scene, camera); + }; + + const renderFrame = () => { + const delta = clock.getDelta(); + const elapsed = clock.elapsedTime; + material.uniforms.uTime!.value = elapsed; + + const degrees = (rotationRef.current % 360) + autoRotateRef.current * elapsed; + const radians = (degrees * Math.PI) / 180; + material.uniforms.uRot!.value.set(Math.cos(radians), Math.sin(radians)); + + const current = pointerCurrentRef.current; + current.lerp(pointerTargetRef.current, Math.min(1, delta * pointerSmoothRef.current)); + material.uniforms.uPointer!.value.copy(current); + renderer.render(scene, camera); + }; + renderOnceRef.current = renderFrame; + + const stop = () => { + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + rafRef.current = null; + } + }; + + const loop = () => { + renderFrame(); + rafRef.current = requestAnimationFrame(loop); + }; + + const start = () => { + if (!reducedMotion && rafRef.current === null) { + clock.start(); + rafRef.current = requestAnimationFrame(loop); + } + }; + + handleResize(); + + if (typeof ResizeObserver !== "undefined") { + const observer = new ResizeObserver(handleResize); + observer.observe(container); + resizeObserverRef.current = observer; + } else { + window.addEventListener("resize", handleResize); + } + + const handleMotionChange = () => { + reducedMotion = motion.matches; + if (reducedMotion) { + stop(); + renderFrame(); + } else { + start(); + } + }; + motion.addEventListener("change", handleMotionChange); + + if (reducedMotion) renderFrame(); + else start(); + + return () => { + stop(); + motion.removeEventListener("change", handleMotionChange); + if (resizeObserverRef.current) resizeObserverRef.current.disconnect(); + else window.removeEventListener("resize", handleResize); + geometry.dispose(); + material.dispose(); + renderer.dispose(); + renderer.forceContextLoss(); + if (renderer.domElement.parentElement === container) { + container.removeChild(renderer.domElement); + } + materialRef.current = null; + rendererRef.current = null; + renderOnceRef.current = null; + resizeObserverRef.current = null; + }; + // Les uniformes sont mis a jour par l'effet suivant ; ce premier montage ne + // depend donc que du conteneur et ne recree jamais le contexte WebGL. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + useEffect(() => { + const material = materialRef.current; + if (!material) return; + + rotationRef.current = rotation; + autoRotateRef.current = autoRotate; + material.uniforms.uSpeed!.value = speed; + material.uniforms.uScale!.value = scale; + material.uniforms.uFrequency!.value = frequency; + material.uniforms.uWarpStrength!.value = warpStrength; + material.uniforms.uMouseInfluence!.value = mouseInfluence; + material.uniforms.uParallax!.value = parallax; + material.uniforms.uNoise!.value = noise; + material.uniforms.uIterations!.value = iterations; + material.uniforms.uIntensity!.value = intensity; + material.uniforms.uBandWidth!.value = bandWidth; + + const parsed = colors.filter(Boolean).slice(0, MAX_COLORS).map(toVec3); + const target = material.uniforms.uColors!.value as Vector3[]; + for (let index = 0; index < MAX_COLORS; index += 1) { + const vector = target[index]!; + if (index < parsed.length) vector.copy(parsed[index]!); + else vector.set(0, 0, 0); + } + material.uniforms.uColorCount!.value = parsed.length; + + material.uniforms.uTransparent!.value = transparent ? 1 : 0; + if (rendererRef.current) rendererRef.current.setClearColor(0x000000, transparent ? 0 : 1); + + // Sans boucle (prefers-reduced-motion), les uniformes viennent de changer : + // il faut une image de plus pour que la palette soit réellement appliquée. + if (rafRef.current === null) renderOnceRef.current?.(); + }, [ + rotation, + autoRotate, + speed, + scale, + frequency, + warpStrength, + mouseInfluence, + parallax, + noise, + iterations, + intensity, + bandWidth, + colors, + transparent, + ]); + + useEffect(() => { + const container = containerRef.current; + if (!container) return; + + const handlePointerMove = (event: PointerEvent) => { + const rect = container.getBoundingClientRect(); + const x = ((event.clientX - rect.left) / (rect.width || 1)) * 2 - 1; + const y = -(((event.clientY - rect.top) / (rect.height || 1)) * 2 - 1); + pointerTargetRef.current.set(x, y); + }; + + // Ecoute au niveau de la fenetre : le fond peut etre recouvert par la + // coque ou par une carte, et doit reagir quand meme au mouvement. + window.addEventListener("pointermove", handlePointerMove, { passive: true }); + return () => { + window.removeEventListener("pointermove", handlePointerMove); + }; + }, []); + + return
; +} diff --git a/frontend/src/components/ColorBendsBackdrop.tsx b/frontend/src/components/ColorBendsBackdrop.tsx new file mode 100644 index 0000000..0a1f9c6 --- /dev/null +++ b/frontend/src/components/ColorBendsBackdrop.tsx @@ -0,0 +1,86 @@ +import { lazy, Suspense } from "react"; +import { COHAISE_BENDS } from "./colorBendsPalette.js"; +import type { ColorBendsProps } from "./ColorBends.js"; + +const ColorBends = lazy(() => import("./ColorBends.js")); + +type BackdropVariant = "auth" | "shell" | "chat"; + +type BackdropPreset = Omit & { + className: string; +}; + +/** + * Fond carmin partage par les ecrans d'authentification, la coque connectee + * et le salon de discussion. Le composant WebGL reste charge a la demande : + * seuls les presets sont dans le bundle initial. + */ +const PRESETS: Record = { + auth: { + className: "opacity-[0.55] dark:opacity-[0.7]", + rotation: 90, + speed: 0.18, + scale: 1, + frequency: 1, + warpStrength: 1, + mouseInfluence: 0.6, + parallax: 0.4, + noise: 0.08, + iterations: 2, + intensity: 1.15, + bandWidth: 5, + }, + shell: { + className: "opacity-[0.85] dark:opacity-[0.9]", + rotation: 90, + speed: 0.18, + scale: 1, + frequency: 1, + warpStrength: 1, + mouseInfluence: 0.6, + parallax: 0.4, + noise: 0.08, + iterations: 2, + intensity: 1.3, + bandWidth: 5, + }, + chat: { + className: "opacity-[0.3] dark:opacity-[0.42]", + rotation: 90, + speed: 0.1, + scale: 1.05, + frequency: 0.95, + warpStrength: 0.9, + mouseInfluence: 0.3, + parallax: 0.25, + noise: 0.05, + iterations: 1, + intensity: 0.8, + bandWidth: 4.5, + }, +}; + +export const ColorBendsBackdrop = ({ + variant, + className, +}: { + variant: BackdropVariant; + className?: string; +}) => { + const { className: presetClassName, ...preset } = PRESETS[variant]; + return ( + + ); +}; diff --git a/frontend/src/components/FolderChat.tsx b/frontend/src/components/FolderChat.tsx index 0735bc2..69123d5 100644 --- a/frontend/src/components/FolderChat.tsx +++ b/frontend/src/components/FolderChat.tsx @@ -21,6 +21,7 @@ import { getLocale } from "../lib/locale.js"; import { useSession } from "../lib/session.js"; import { useConfirm } from "./confirm.js"; import { Avatar } from "./Avatar.js"; +import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js"; import { IconAction } from "./IconAction.js"; import { Alert, Badge, EmptyState } from "./feedback.js"; import { @@ -359,8 +360,9 @@ export const FolderChat = ({ folder, onClose }: { folder: ChatFolder; onClose: ( ); return ( -
-
+
+ +
diff --git a/frontend/src/components/IconAction.tsx b/frontend/src/components/IconAction.tsx index f1e3225..98e69c5 100644 --- a/frontend/src/components/IconAction.tsx +++ b/frontend/src/components/IconAction.tsx @@ -23,8 +23,8 @@ export const IconAction = ({ disabled={isLoading} onClick={onClick} className={cn( - "relative inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors", - "hover:bg-surface-hover hover:text-foreground disabled:pointer-events-none disabled:opacity-50", + "group relative inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-all", + "hover:-translate-y-0.5 hover:bg-surface/60 hover:text-foreground hover:shadow-sm backdrop-blur-sm disabled:pointer-events-none disabled:opacity-50", tone === "danger" && "hover:text-destructive", )} > diff --git a/frontend/src/components/colorBendsPalette.ts b/frontend/src/components/colorBendsPalette.ts new file mode 100644 index 0000000..455b06c --- /dev/null +++ b/frontend/src/components/colorBendsPalette.ts @@ -0,0 +1,2 @@ +/** Palette carmin de la marque, alignee sur `tokens.css`. */ +export const COHAISE_BENDS = ["#b71c1c", "#c92a2a", "#8f1116", "#5e0a14"]; diff --git a/frontend/src/components/dialogs.tsx b/frontend/src/components/dialogs.tsx index b84cb65..8c20451 100644 --- a/frontend/src/components/dialogs.tsx +++ b/frontend/src/components/dialogs.tsx @@ -10,7 +10,8 @@ import { } from "../lib/api.js"; import { useI18n } from "../lib/i18n.js"; import { Alert, Modal } from "./feedback.js"; -import { TrashIcon } from "./icons.js"; +import { PlusIcon, TrashIcon } from "./icons.js"; +import { IconAction } from "./IconAction.js"; const LEVELS = ["read", "write", "admin"] as const; const LEVEL_LABEL: Record = { @@ -69,13 +70,21 @@ export const CreateFolderDialog = ({ onChange={(event) => setName(event.target.value)} /> {error ? {error} : null} -
- - +
+ } + onClick={onClose} + /> + } + isLoading={busy} + onClick={(e) => { + e.preventDefault(); + void submit(e as any); + }} + />
@@ -234,13 +243,21 @@ export const MoveDialog = ({ )} {error ? {error} : null} -
- - +
+ } + onClick={onClose} + /> + } + isLoading={busy} + onClick={(e) => { + e.preventDefault(); + void submit(e as any); + }} + />
diff --git a/frontend/src/components/feedback.tsx b/frontend/src/components/feedback.tsx index 33024d4..c5f24e0 100644 --- a/frontend/src/components/feedback.tsx +++ b/frontend/src/components/feedback.tsx @@ -1,7 +1,8 @@ -import { useEffect, type ReactNode } from "react"; +import { useEffect, useMemo, type ReactNode } from "react"; import { cn } from "../ui/index.js"; import { useI18n } from "../lib/i18n.js"; import { CloseIcon } from "./icons.js"; +import { usePageHeader } from "./AppShell.js"; export const Modal = ({ open, @@ -52,7 +53,7 @@ export const Modal = ({ type="button" onClick={onClose} aria-label={t("Fermer")} - className="rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none" + className="rounded-md p-1 text-muted-foreground transition-all hover:-translate-y-0.5 hover:bg-surface/60 hover:text-foreground hover:shadow-sm focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none" > @@ -97,22 +98,29 @@ export const PageHeader = ({ description?: string; actions?: ReactNode; toolbar?: ReactNode; -}) => ( -
-
-
-

- {title} -

- {description ? ( -

{description}

- ) : null} -
- {actions ?
{actions}
: null} -
- {toolbar ?
{toolbar}
: null} -
-); +}) => { + const header = useMemo( + () => ( +
+
+
+

+ {title} +

+ {description ? ( +

{description}

+ ) : null} +
+ {actions ?
{actions}
: null} +
+ {toolbar ?
{toolbar}
: null} +
+ ), + [title, description, actions, toolbar], + ); + usePageHeader(header); + return null; +}; export const EmptyState = ({ icon, diff --git a/frontend/src/components/icons.tsx b/frontend/src/components/icons.tsx index 5f76171..70caddc 100644 --- a/frontend/src/components/icons.tsx +++ b/frontend/src/components/icons.tsx @@ -1,221 +1,148 @@ -import type { SVGProps } from "react"; +import type { ImgHTMLAttributes } from "react"; -type IconProps = SVGProps; +type IconProps = Omit, "src" | "alt"> & { + filled?: boolean; +}; -const base = (props: IconProps) => ({ - viewBox: "0 0 24 24", - fill: "none", - stroke: "currentColor", - strokeWidth: 1.6, - strokeLinecap: "round" as const, - strokeLinejoin: "round" as const, - "aria-hidden": true, - ...props, -}); +const ImgIcon = ({ + src, + className = "", + ...props +}: { src: string } & IconProps) => ( + +); export const FolderIcon = (props: IconProps) => ( - - - + ); export const FileIcon = (props: IconProps) => ( - - - - + ); export const ImageIcon = (props: IconProps) => ( - - - - - + ); export const PlayIcon = (props: IconProps) => ( - - - + ); export const AudioIcon = (props: IconProps) => ( - - - - - + ); export const ArchiveIcon = (props: IconProps) => ( - - - - + ); export const UploadIcon = (props: IconProps) => ( - - - + ); export const DownloadIcon = (props: IconProps) => ( - - - + ); export const PlusIcon = (props: IconProps) => ( - - - + ); export const TrashIcon = (props: IconProps) => ( - - - + ); export const RestoreIcon = (props: IconProps) => ( - - - + ); export const RefreshIcon = (props: IconProps) => ( - - - + ); -export const StarIcon = ({ filled, ...props }: IconProps & { filled?: boolean }) => ( - - - +export const StarIcon = (props: IconProps) => ( + ); export const SearchIcon = (props: IconProps) => ( - - - - + ); export const UsersIcon = (props: IconProps) => ( - - - - + ); export const SettingsIcon = (props: IconProps) => ( - - - - + ); export const LogoutIcon = (props: IconProps) => ( - - - + ); export const ShieldIcon = (props: IconProps) => ( - - - - + ); export const HardDriveIcon = (props: IconProps) => ( - - - - + ); export const ActivityIcon = (props: IconProps) => ( - - - + ); export const SearchNavIcon = (props: IconProps) => ( - - - - + ); export const ShareIcon = (props: IconProps) => ( - - - - - - + ); export const MenuIcon = (props: IconProps) => ( - - - + ); export const CloseIcon = (props: IconProps) => ( - - - + ); export const ArrowLeftIcon = (props: IconProps) => ( - - - + ); export const ArrowRightIcon = (props: IconProps) => ( - - - + ); export const PenIcon = (props: IconProps) => ( - - - - + ); /** Epingle : tete du pushpin en haut, pointe en bas. */ export const PinIcon = (props: IconProps) => ( - - - - + ); export const MoveIcon = (props: IconProps) => ( - - - - + ); export const ChatIcon = (props: IconProps) => ( - - - - + ); export const SendIcon = (props: IconProps) => ( - - - - + ); diff --git a/frontend/src/pages/Admin.tsx b/frontend/src/pages/Admin.tsx index e6b4751..5fd82af 100644 --- a/frontend/src/pages/Admin.tsx +++ b/frontend/src/pages/Admin.tsx @@ -129,13 +129,11 @@ export const AdminUsers = () => { title={t("Comptes")} description={t("Créer des membres, ajustez leurs quotas et gérez les accès.")} actions={ - + /> } toolbar={ <> @@ -210,18 +208,20 @@ export const AdminUsers = () => {
- + } + onClick={() => setEdit(user)} + /> } + icon={} isLoading={busy === user.id} onClick={() => void toggleActive(user)} /> } + icon={} isLoading={busy === user.id} onClick={() => void resetPassword(user)} /> @@ -505,13 +505,11 @@ export const AdminStorage = () => { title={t("Emplacements de stockage")} description={t("Volumes montés utilisés pour stocker les fichiers.")} actions={ - + /> } /> @@ -544,9 +542,11 @@ export const AdminStorage = () => { : t("{used} Go utilisés", { used: toGb(location.used_bytes) })} - + } + onClick={() => void toggle(location)} + /> ))} diff --git a/frontend/src/pages/Browser.tsx b/frontend/src/pages/Browser.tsx index 8421f22..b1a1edc 100644 --- a/frontend/src/pages/Browser.tsx +++ b/frontend/src/pages/Browser.tsx @@ -5,7 +5,7 @@ import { useState, type DragEvent, } from "react"; -import { Button, Card, Spinner, cn } from "../ui/index.js"; +import { Card, Spinner, cn } from "../ui/index.js"; import { ApiError, api, @@ -17,7 +17,7 @@ import { useSession } from "../lib/session.js"; import { useI18n } from "../lib/i18n.js"; import { getLocale } from "../lib/locale.js"; import { mediaKind } from "../lib/media.js"; -import { Badge, EmptyState, PageHeader } from "../components/feedback.js"; +import { EmptyState, PageHeader } from "../components/feedback.js"; import { useConfirm } from "../components/confirm.js"; import { MediaViewer } from "../components/MediaViewer.js"; import { MediaThumb } from "../components/MediaThumb.js"; @@ -33,8 +33,8 @@ import { import { ArrowLeftIcon, ChatIcon, + CloseIcon, DownloadIcon, - FolderIcon, PenIcon, PlusIcon, RefreshIcon, @@ -538,32 +538,22 @@ export const Browser = () => { - + /> {current.id ? ( - + /> ) : null}
} @@ -619,7 +609,7 @@ export const Browser = () => { ) : null} {canWrite ? ( -
+
{ className="sr-only" onChange={(event) => void upload(event.target.files)} /> - - + />
) : null}
@@ -681,25 +663,21 @@ export const Browser = () => { {canWrite && selectedItems.length > 0 ? (
-
+

{t("{count} élément(s) sélectionné(s).", { count: selectedItems.length, })}

-
- - - - + /> + } + onClick={clearSelection} + />
@@ -740,7 +717,7 @@ export const Browser = () => {
) : empty ? ( } + icon={} title={t("Emplacement vide")} description={t( "Créez un sous-dossier ou envoyez un fichier pour commencer.", @@ -762,7 +739,7 @@ export const Browser = () => { onDrop={(event) => onFolderDrop(event, folder)} onClick={() => toggleSelection(`f:${folder.id}`)} className={cn( - "group relative flex items-center gap-1 rounded-lg border border-border bg-surface p-2 transition-colors hover:border-border-strong hover:bg-surface-hover cursor-pointer", + "group relative flex items-center gap-1 rounded-xl border border-border/50 bg-surface/60 p-2 backdrop-blur-md transition-all hover:-translate-y-1 hover:border-border-strong hover:bg-surface/80 hover:shadow-lg cursor-pointer", dropTargetId === folder.id && "border-accent bg-accent/10 ring-1 ring-accent/50", selected.has(`f:${folder.id}`) && @@ -798,7 +775,7 @@ export const Browser = () => { className="flex min-w-0 flex-1 items-center gap-3 rounded-sm p-1 text-left focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none" > - + @@ -879,7 +856,7 @@ export const Browser = () => { {t("Rien à afficher pour ce filtre.")}

) : ( -
    +
      {visibleFiles.map((file, index) => (
    • { } icon={ } onClick={(event) => { @@ -956,13 +932,12 @@ export const Browser = () => { event.stopPropagation()} > - - - {t("Télécharger")} - + {canWrite ? ( diff --git a/frontend/src/pages/ChangePassword.tsx b/frontend/src/pages/ChangePassword.tsx index 0710bd0..59928d2 100644 --- a/frontend/src/pages/ChangePassword.tsx +++ b/frontend/src/pages/ChangePassword.tsx @@ -36,83 +36,81 @@ export const ChangePassword = () => { }; return ( -
      -
      -
      -
      - -
      -

      - CoHaiSe -

      -

      - {t("Nouveau mot de passe")} -

      -
      +
      +
      +
      + +
      +

      + CoHaiSe +

      +

      + {t("Nouveau mot de passe")} +

      -

      - {t("Bienvenue {name}. Ce mot de passe a été défini par un administrateur : choisissez le vôtre.", { name: user?.first_name ?? "" })} -

      -
      +
      +

      + {t("Bienvenue {name}. Ce mot de passe a été défini par un administrateur : choisissez le vôtre.", { name: user?.first_name ?? "" })} +

      +
      - - - {t("Changement requis")} - - {t("Les autres sessions ouvertes sur ce compte seront fermées.")} - - - -
      void submit(event)}> - setCurrent(event.target.value)} - /> - setNext(event.target.value)} - /> - setConfirm(event.target.value)} - /> - {error ? {error} : null} - - -
      -
      -
      -
      -
      + + + {t("Changement requis")} + + {t("Les autres sessions ouvertes sur ce compte seront fermées.")} + + + +
      void submit(event)}> + setCurrent(event.target.value)} + /> + setNext(event.target.value)} + /> + setConfirm(event.target.value)} + /> + {error ? {error} : null} + + +
      +
      +
      +
); }; diff --git a/frontend/src/pages/ConfirmEmail.tsx b/frontend/src/pages/ConfirmEmail.tsx index e8b66fa..9c4c516 100644 --- a/frontend/src/pages/ConfirmEmail.tsx +++ b/frontend/src/pages/ConfirmEmail.tsx @@ -36,57 +36,55 @@ export const ConfirmEmail = () => { }, [token, refresh]); return ( -
-
-
-
- -
-

- CoHaiSe -

-

- {t("Changement d'adresse")} -

-
+
+
+
+ +
+

+ CoHaiSe +

+

+ {t("Changement d'adresse")} +

-
+
+
- - - {t("Confirmation")} - - - {state === "loading" ? ( -
- -
- ) : state === "success" ? ( - <> - {t("Votre adresse e-mail a été mise à jour.")} - - - - - ) : ( - <> - {error} - - - - - )} -
-
-
-
+ + + {t("Confirmation")} + + + {state === "loading" ? ( +
+ +
+ ) : state === "success" ? ( + <> + {t("Votre adresse e-mail a été mise à jour.")} + + + + + ) : ( + <> + {error} + + + + + )} +
+
+
); }; diff --git a/frontend/src/pages/Favorites.tsx b/frontend/src/pages/Favorites.tsx index 7334787..a95a483 100644 --- a/frontend/src/pages/Favorites.tsx +++ b/frontend/src/pages/Favorites.tsx @@ -60,7 +60,7 @@ export const Favorites = () => { description={t("Étoilez un fichier dans l'explorateur pour le retrouver ici.")} /> ) : ( -
    +
      {files.map((file, index) => (
    • ))} diff --git a/frontend/src/pages/ForgotPassword.tsx b/frontend/src/pages/ForgotPassword.tsx index 0a8159f..43d31b1 100644 --- a/frontend/src/pages/ForgotPassword.tsx +++ b/frontend/src/pages/ForgotPassword.tsx @@ -27,75 +27,73 @@ export const ForgotPassword = () => { }; return ( -
      -
      -
      -
      - -
      -

      - CoHaiSe -

      -

      - {t("Mot de passe oublié")} -

      -
      +
      +
      +
      + +
      +

      + CoHaiSe +

      +

      + {t("Mot de passe oublié")} +

      -
      +
      +
      - - - {t("Réinitialisation")} - - {t("Nous vous enverrons un lien valable une heure.")} - - - - {sent ? ( -
      - - {t("Si cette adresse correspond à un compte, un message contenant le lien de réinitialisation vient d'être envoyé.")} - - - {t("Retour à la connexion")} - -
      - ) : ( -
      void submit(event)} + + + {t("Réinitialisation")} + + {t("Nous vous enverrons un lien valable une heure.")} + + + + {sent ? ( +
      + + {t("Si cette adresse correspond à un compte, un message contenant le lien de réinitialisation vient d'être envoyé.")} + + - setEmail(event.target.value)} - /> - {error ? {error} : null} - - - {t("Retour à la connexion")} - - - )} - - -
      -
      + {t("Retour à la connexion")} + +
+ ) : ( +
void submit(event)} + > + setEmail(event.target.value)} + /> + {error ? {error} : null} + + + {t("Retour à la connexion")} + +
+ )} + + +
); }; diff --git a/frontend/src/pages/Login.tsx b/frontend/src/pages/Login.tsx index 4937b31..cabd5fe 100644 --- a/frontend/src/pages/Login.tsx +++ b/frontend/src/pages/Login.tsx @@ -32,71 +32,69 @@ export const Login = () => { }; return ( -
-
-
-
- -
-

- CoHaiSe -

-

- Cloud -

-
+
+
+
+ +
+

+ CoHaiSe +

+

+ Cloud +

-

- {t("Connectez-vous pour accéder à vos fichiers.")} -

-
- - - - {t("Connexion")} - {t("Votre session reste ouverte 14 jours.")} - - -
void submit(event)}> - setEmail(event.target.value)} - /> - setPassword(event.target.value)} - {...(error ? { error } : {})} - /> - - -
-
-
- -

- - {t("Mot de passe oublié ?")} - +

+

+ {t("Connectez-vous pour accéder à vos fichiers.")}

-
-
+
+ + + + {t("Connexion")} + {t("Votre session reste ouverte 14 jours.")} + + +
void submit(event)}> + setEmail(event.target.value)} + /> + setPassword(event.target.value)} + {...(error ? { error } : {})} + /> + + +
+
+
+ +

+ + {t("Mot de passe oublié ?")} + +

+
); }; diff --git a/frontend/src/pages/ResetPassword.tsx b/frontend/src/pages/ResetPassword.tsx index dd0d1aa..af965f4 100644 --- a/frontend/src/pages/ResetPassword.tsx +++ b/frontend/src/pages/ResetPassword.tsx @@ -34,84 +34,82 @@ export const ResetPassword = () => { }; return ( -
-
-
-
- -
-

- CoHaiSe -

-

- {t("Nouveau mot de passe")} -

-
+
+
+
+ +
+

+ CoHaiSe +

+

+ {t("Nouveau mot de passe")} +

-
+
+
- - - {t("Réinitialisation")} - {t("Choisissez un mot de passe robuste.")} - - - {!token ? ( -
- {t("Ce lien est incomplet ou invalide.")} - - {t("Demander un nouveau lien")} - -
- ) : done ? ( -
- - {t("Votre mot de passe a été réinitialisé. Vous pouvez vous connecter.")} - - - - -
- ) : ( -
void submit(event)}> - setPassword(event.target.value)} - /> - setConfirm(event.target.value)} - /> - {error ? {error} : null} - -
- )} -
-
-
-
+ +
+ ) : ( +
void submit(event)}> + setPassword(event.target.value)} + /> + setConfirm(event.target.value)} + /> + {error ? {error} : null} + +
+ )} + + +
); }; diff --git a/frontend/src/pages/Search.tsx b/frontend/src/pages/Search.tsx index fb0a6da..2df53a2 100644 --- a/frontend/src/pages/Search.tsx +++ b/frontend/src/pages/Search.tsx @@ -1,7 +1,8 @@ import { useState, type FormEvent } from "react"; -import { Button, Input, Spinner } from "../ui/index.js"; +import { Input, Spinner } from "../ui/index.js"; import { ApiError, api, formatBytes, type Folder, type UploadedFile } from "../lib/api.js"; import { Alert, EmptyState, PageHeader } from "../components/feedback.js"; +import { IconAction } from "../components/IconAction.js"; import { DownloadIcon, FileIcon, FolderIcon, SearchIcon } from "../components/icons.js"; import { useI18n } from "../lib/i18n.js"; @@ -56,14 +57,16 @@ export const Search = () => { onChange={(event) => setQ(event.target.value)} /> - + onClick={(e) => { + e.preventDefault(); + const form = e.currentTarget.closest('form'); + form?.requestSubmit(); + }} + /> } /> @@ -87,7 +90,7 @@ export const Search = () => {

{t("Dossiers")}

-
    +
      {results.folders.map((folder) => (
    • @@ -107,7 +110,7 @@ export const Search = () => {

      {t("Fichiers")}

      -
        +
          {results.files.map((file) => (
        • diff --git a/frontend/src/pages/Trash.tsx b/frontend/src/pages/Trash.tsx index 82c942c..31ac1b4 100644 --- a/frontend/src/pages/Trash.tsx +++ b/frontend/src/pages/Trash.tsx @@ -121,7 +121,7 @@ export const Trash = () => {

          {t("Dossiers")}

          -
            +
              {data.folders.map((folder) => (
            • @@ -165,7 +165,7 @@ export const Trash = () => {

              {t("Fichiers")}

              -
                +
                  {data.files.map((file) => (
                • diff --git a/frontend/src/ui/components/Button.tsx b/frontend/src/ui/components/Button.tsx index 1a656c0..034529e 100644 --- a/frontend/src/ui/components/Button.tsx +++ b/frontend/src/ui/components/Button.tsx @@ -5,8 +5,8 @@ import type { SpinnerSize } from "./Spinner.js"; const variantClasses = { primary: "bg-primary text-primary-foreground hover:bg-primary-hover", - secondary: "border border-border-strong bg-surface text-foreground hover:bg-surface-hover", - ghost: "text-foreground hover:bg-surface-hover", + secondary: "rounded-lg border border-border-strong bg-surface/60 text-foreground backdrop-blur-sm transition-all hover:-translate-y-0.5 hover:bg-surface/80 hover:shadow-md", + ghost: "rounded-lg text-foreground transition-all hover:-translate-y-0.5 hover:bg-surface/50 hover:shadow-sm", destructive: "bg-destructive text-destructive-foreground hover:bg-destructive-hover", } as const; diff --git a/frontend/src/ui/components/Card.tsx b/frontend/src/ui/components/Card.tsx index 739f83f..0931007 100644 --- a/frontend/src/ui/components/Card.tsx +++ b/frontend/src/ui/components/Card.tsx @@ -4,8 +4,8 @@ import { cn } from "../lib/cn.js"; export const Card = ({ className, ...props }: HTMLAttributes) => (
                  =0.5.17", + "fflate": "~0.8.3", + "meshoptimizer": "~1.1.1" + } + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "dev": true, + "license": "MIT" + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -1671,6 +1716,13 @@ } } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2035,6 +2087,13 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/meshoptimizer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz", + "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==", + "dev": true, + "license": "MIT" + }, "node_modules/mysql2": { "version": "3.24.6", "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz", @@ -2373,6 +2432,12 @@ "url": "https://opencollective.com/webpack" } }, + "node_modules/three": { + "version": "0.187.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz", + "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==", + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",