diff --git a/backend/src/assets/logo.png b/backend/src/assets/logo.png index f34c330..bf32519 100644 Binary files a/backend/src/assets/logo.png and b/backend/src/assets/logo.png differ diff --git a/backend/src/routes/admin.ts b/backend/src/routes/admin.ts index 8dc9113..6524234 100644 --- a/backend/src/routes/admin.ts +++ b/backend/src/routes/admin.ts @@ -243,7 +243,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { }) .catch(() => undefined); - return context.json({ user: publicUser(created), password }, 201); + return context.json({ user: publicUser(created) }, 201); }); app.patch("/api/cloud/admin/users/:id", requireAuth, async (context) => { @@ -343,8 +343,8 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { [id], ); - // Le mot de passe est rendu une seule fois et envoye au compte. Un echec - // d'envoi n'invalide pas la reinitialisation. + // Le mot de passe est envoye au compte ; la reponse ne le contient pas. + // Un echec d'envoi n'invalide pas la reinitialisation. const mail = renderMail(brand, { preview: "Un nouveau mot de passe a ete genere pour votre compte.", heading: "Mot de passe reinitialise", @@ -362,7 +362,7 @@ export const registerAdminRoutes = (app: App, db: Db, config: Config): void => { }) .catch(() => undefined); - return context.json({ password }); + return context.json({ ok: true }); }); app.get("/api/cloud/admin/storage-locations", requireAuth, async (context) => { diff --git a/backend/src/routes/files.ts b/backend/src/routes/files.ts index d5e73a1..65240db 100644 --- a/backend/src/routes/files.ts +++ b/backend/src/routes/files.ts @@ -107,9 +107,100 @@ const mimeOf = (header: string | undefined): string => { }; /** Le nom HTTP ne contient que des octets ASCII imprimables, UTF-8 en prime. */ -const contentDisposition = (name: string): string => { +const contentDisposition = (name: string, inline = false): string => { const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_"); - return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`; + const kind = inline ? "inline" : "attachment"; + return `${kind}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`; +}; + +const BYTE_RANGE = /^bytes=(\d*)-(\d*)$/; + +/** + * Analyse un en-tete `Range` (une seule plage). Rend `null` quand il faut servir + * le corps entier (absent ou illisible), `"invalid"` quand la plage est + * insatisfiable (reponse 416), sinon les bornes inclusives a servir. + */ +const parseRange = ( + header: string | undefined, + total: number, +): { start: number; end: number } | "invalid" | null => { + if (!header) return null; + const match = BYTE_RANGE.exec(header.trim()); + if (!match) return null; + const [, rawStart, rawEnd] = match; + let start: number; + let end: number; + if (rawStart === "") { + const suffix = Number(rawEnd); + if (!Number.isInteger(suffix) || suffix <= 0) return "invalid"; + start = Math.max(0, total - suffix); + end = total - 1; + } else { + start = Number(rawStart); + end = rawEnd === "" ? total - 1 : Number(rawEnd); + } + if (!Number.isInteger(start) || !Number.isInteger(end)) return "invalid"; + if (start < 0 || start >= total) return "invalid"; + if (end >= total) end = total - 1; + if (end < start) return "invalid"; + return { start, end }; +}; + +/** + * Types servis en flux pour l'apercu en ligne. Liste blanche stricte : jamais + * `text/html`, `image/svg+xml` ni `application/xhtml+xml`, qui s'executeraient + * dans l'origine de l'application. Le telechargement, lui, reste `attachment`. + */ +const isPreviewable = (mime: string): boolean => { + const value = mime.toLowerCase(); + if (value === "image/svg+xml") return false; + return ( + value.startsWith("image/") || + value.startsWith("video/") || + value.startsWith("audio/") || + value === "application/pdf" || + value === "text/plain" + ); +}; + +interface ServeOptions { + absolute: string; + size: number; + mime: string; + disposition: string; + range: string | undefined; +} + +/** Repond avec le fichier, en gerant `Range` (206) et les plages invalides (416). */ +const serveFile = ({ absolute, size, mime, disposition, range }: ServeOptions): Response => { + const headers: Record = { + "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 => { @@ -354,19 +445,46 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => { ) .catch(() => undefined); - const mime = row.mime_type ?? "application/octet-stream"; - const stream = Readable.toWeb(openForDownload(absolute)) as ReadableStream; + return serveFile({ + absolute, + size: row.size_bytes, + mime: row.mime_type ?? "application/octet-stream", + disposition: contentDisposition(row.name), + range: context.req.header("range"), + }); + }); - return new Response(stream, { - headers: { - "content-type": mime, - "content-length": String(row.size_bytes), - "content-disposition": contentDisposition(row.name), - // Le type vient de la base, jamais du contenu : un fichier HTML - // telecharge ne doit jamais etre rendu en navigation. - "x-content-type-options": "nosniff", - "cache-control": "private, max-age=0, must-revalidate", - }, + /** + * Apercu en ligne (flux `inline`) : lecture d'une video ou d'un son, rendu + * d'une image ou d'un PDF. Memes droits que le telechargement, sans + * incrementation de `download_count`. Types sur liste blanche uniquement. + */ + app.get("/api/cloud/files/:id/preview", requireAuth, async (context) => { + const user = currentUser(context); + const rawId = context.req.param("id"); + if (!uuid.safeParse(rawId).success) throw AppError.notFound("Fichier introuvable."); + + const row = await db.one(`${SELECT_FILE} WHERE id = ? AND deleted_at IS NULL`, [rawId]); + if (!row) throw AppError.notFound("Fichier introuvable."); + + const allowed = + user.role_slug === "admin" || + (row.owner_id !== null && row.owner_id === user.id) || + (row.folder_id !== null && (await canRead(db, user, row.folder_id))); + if (!allowed) throw AppError.notFound("Fichier introuvable."); + + const 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"), }); }); diff --git a/backend/src/storage.ts b/backend/src/storage.ts index 43366ed..6774487 100644 --- a/backend/src/storage.ts +++ b/backend/src/storage.ts @@ -139,7 +139,13 @@ export const fileExists = async (absolute: string): Promise => { } }; -export const openForDownload = (absolute: string) => createReadStream(absolute); +/** + * Ouvre un fichier en lecture. `range` restreint le flux a un intervalle + * d'octets inclusif, ce qui permet de repondre a une requete HTTP `Range` + * (deplacement dans une video ou un morceau audio) sans lire tout le fichier. + */ +export const openForDownload = (absolute: string, range?: { start: number; end: number }) => + createReadStream(absolute, range); /** * Occupation reelle du support qui porte `target`. Sert a refuser un quota diff --git a/docs/api.md b/docs/api.md index 3b31abc..03945f6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -47,6 +47,7 @@ d'adresse). | GET | `/api/cloud/files` | `requireAuth` | | PUT | `/api/cloud/files` | `requireAuth` (corps brut, upload) | | GET | `/api/cloud/files/:id/download` | `requireAuth` | +| GET | `/api/cloud/files/:id/preview` | `requireAuth` (aperçu en ligne) | | GET | `/api/cloud/files/:id/thumbnail` | `requireAuth` | | PATCH | `/api/cloud/files/:id` | `requireAuth` + écriture (renommer) | | POST | `/api/cloud/files/:id/move` | `requireAuth` + écriture | diff --git a/docs/security.md b/docs/security.md index 332563e..e903619 100644 --- a/docs/security.md +++ b/docs/security.md @@ -59,6 +59,10 @@ aucun HTML utilisateur n'est injecté dans les messages. flux** (un fichier surdimensionné est coupé, pas bufferisé). - Téléchargement : `content-disposition: attachment`, `nosniff`, `cache-control: private, max-age=0, must-revalidate`. +- Aperçu en ligne : même contrôle d'accès que le téléchargement, `inline` sur + 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). ## Hors périmètre (assumé) diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico index cf90136..d9316d0 100644 Binary files a/frontend/public/favicon.ico and b/frontend/public/favicon.ico differ diff --git a/frontend/public/icon.png b/frontend/public/icon.png index f34c330..bf32519 100644 Binary files a/frontend/public/icon.png and b/frontend/public/icon.png differ diff --git a/frontend/src/components/AppShell.tsx b/frontend/src/components/AppShell.tsx index 86e427b..10ef239 100644 --- a/frontend/src/components/AppShell.tsx +++ b/frontend/src/components/AppShell.tsx @@ -87,8 +87,8 @@ export const AppShell = () => { }; return ( -
-