Aperçu : route /api/preview en lecture seule et visualiseurs côté client
- GET /api/preview?path= et /api/public/{jeton}/preview : liste blanche d'extensions, inline, nosniff, CSP stricte, texte plafonné à 2 Mo
- Visualiseurs : texte brut, CSV paginé (PapaParse), Markdown sans HTML brut (react-markdown + remark-gfm), code colorisé (highlight.js), PDF natif
- Le HTML s'affiche comme du code, jamais rendu ; RTF/DOC/DOCX hors périmètre
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fe81055421
commit
d4da3db132
14 files changed
+2378
-39
No files matched your search
@@ -4,7 +4,7 @@ Dépôt et téléchargement de fichiers **auto-hébergé**, avec un navigateur d
|
|||||||
|
|
||||||
- **Envoi** : glisser-déposer de fichiers et de dossiers entiers, envoi en flux (pas de limite de mémoire), plusieurs fichiers en parallèle, progression, annulation, nouvel essai, choix « garder les deux / remplacer / ignorer », date de modification d'origine conservée.
|
- **Envoi** : glisser-déposer de fichiers et de dossiers entiers, envoi en flux (pas de limite de mémoire), plusieurs fichiers en parallèle, progression, annulation, nouvel essai, choix « garder les deux / remplacer / ignorer », date de modification d'origine conservée.
|
||||||
- **Navigation** : 4 affichages (liste, tableau triable, vignettes, galerie), recherche (noms, tags, **contenu des fichiers texte**), tags, favoris (fichiers et dossiers), sélection multiple, glisser-déposer pour déplacer, miniatures d'images (EXIF pris en compte).
|
- **Navigation** : 4 affichages (liste, tableau triable, vignettes, galerie), recherche (noms, tags, **contenu des fichiers texte**), tags, favoris (fichiers et dossiers), sélection multiple, glisser-déposer pour déplacer, miniatures d'images (EXIF pris en compte).
|
||||||
- **Aperçu intégré** : images, vidéo, audio, PDF, texte et code, avec navigation ←/→ dans le dossier.
|
- **Aperçu intégré** : images, vidéo, audio, PDF, texte, CSV (tableau paginé), Markdown et code colorisé (le HTML s'affiche comme du code, jamais rendu), avec navigation ←/→ dans le dossier.
|
||||||
- **Téléchargement** : fichier (reprise possible, `Range`) ou dossier / sélection en **ZIP** généré en flux.
|
- **Téléchargement** : fichier (reprise possible, `Range`) ou dossier / sélection en **ZIP** généré en flux.
|
||||||
- **Espaces** : arborescence commune + espace **Personnel** privé par utilisateur ; poubelle ; historique des versions (chaque remplacement garde l'ancien contenu, restauration en un clic).
|
- **Espaces** : arborescence commune + espace **Personnel** privé par utilisateur ; poubelle ; historique des versions (chaque remplacement garde l'ancien contenu, restauration en un clic).
|
||||||
- **Partage** par lien (`/s/<jeton>`) d'un fichier ou d'un dossier : durée au choix, **mot de passe** facultatif, compteur de téléchargements, révocation, sans compte pour le destinataire.
|
- **Partage** par lien (`/s/<jeton>`) d'un fichier ou d'un dossier : durée au choix, **mot de passe** facultatif, compteur de téléchargements, révocation, sans compte pour le destinataire.
|
||||||
|
|||||||
@@ -3,5 +3,6 @@
|
|||||||
- **Excalicloud** (MIT, vLab-BZH) : paquet d'authentification OIDC (`internal/auth`), organisation du stockage (espaces personnels, favoris, corbeille, tags, partage) et composants de l'explorateur.
|
- **Excalicloud** (MIT, vLab-BZH) : paquet d'authentification OIDC (`internal/auth`), organisation du stockage (espaces personnels, favoris, corbeille, tags, partage) et composants de l'explorateur.
|
||||||
- **Icônes Tabler** (MIT, Paweł Kuna) : tracés repris dans `frontend/src/icons.tsx` et `folderIcons.tsx`.
|
- **Icônes Tabler** (MIT, Paweł Kuna) : tracés repris dans `frontend/src/icons.tsx` et `folderIcons.tsx`.
|
||||||
- **React** (MIT, Meta), **Vite** (MIT).
|
- **React** (MIT, Meta), **Vite** (MIT).
|
||||||
|
- Aperçu : **highlight.js** (BSD-3-Clause), **react-markdown** et **remark-gfm** (MIT, unified), **PapaParse** (MIT).
|
||||||
|
|
||||||
Aucune autre dépendance : le serveur n'utilise que la bibliothèque standard de Go.
|
Le serveur n'utilise que la bibliothèque standard de Go.
|
||||||
Generated
+1531
-6
File diff suppressed because it is too large.
Load diff
@@ -9,10 +9,15 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"highlight.js": "^11.11.1",
|
||||||
|
"papaparse": "^5.5.3",
|
||||||
"react": "^19.1.0",
|
"react": "^19.1.0",
|
||||||
"react-dom": "^19.1.0"
|
"react-dom": "^19.1.0",
|
||||||
|
"react-markdown": "^10.1.0",
|
||||||
|
"remark-gfm": "^4.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/papaparse": "^5.5.2",
|
||||||
"@types/react": "^19.1.0",
|
"@types/react": "^19.1.0",
|
||||||
"@types/react-dom": "^19.1.0",
|
"@types/react-dom": "^19.1.0",
|
||||||
"@vitejs/plugin-react": "^5.0.0",
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
|
|||||||
@@ -593,7 +593,8 @@ export function Explorer({ me, refreshKey, goto, onDirChange, onMutated, toolbar
|
|||||||
modTime: e.modTime,
|
modTime: e.modTime,
|
||||||
src: api.downloadUrl(e.path, true),
|
src: api.downloadUrl(e.path, true),
|
||||||
download: api.downloadUrl(e.path),
|
download: api.downloadUrl(e.path),
|
||||||
text: () => api.readText(e.path),
|
preview: api.previewUrl(e.path),
|
||||||
|
text: () => api.readPreview(e.path),
|
||||||
});
|
});
|
||||||
const previewFiles = useMemo(() => (previewIndex >= 0 ? files.map(toPreview) : []), [previewIndex >= 0, files]); // eslint-disable-line react-hooks/exhaustive-deps
|
const previewFiles = useMemo(() => (previewIndex >= 0 ? files.map(toPreview) : []), [previewIndex >= 0, files]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
|||||||
+48
-10
@@ -1,9 +1,15 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { lazy, Suspense, useEffect, useState } from "react";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { ChevronLeftIcon, ChevronRightIcon, CloseIcon, DownloadIcon, ExpandIcon } from "./icons";
|
import { ChevronLeftIcon, ChevronRightIcon, CloseIcon, DownloadIcon, ExpandIcon } from "./icons";
|
||||||
import { FileGlyph } from "./FileGlyph";
|
import { FileGlyph } from "./FileGlyph";
|
||||||
import { kindOf, monospace, previewable, typeLabel } from "./filetypes";
|
import { kindOf, monospace, previewable, previewMode, typeLabel } from "./filetypes";
|
||||||
|
import type { PreviewText } from "./api";
|
||||||
|
|
||||||
|
// Visualiseurs riches (highlight.js, react-markdown, PapaParse) : module chargé à la première ouverture.
|
||||||
|
const CodeViewer = lazy(() => import("./viewers").then((m) => ({ default: m.CodeViewer })));
|
||||||
|
const MarkdownViewer = lazy(() => import("./viewers").then((m) => ({ default: m.MarkdownViewer })));
|
||||||
|
const CsvViewer = lazy(() => import("./viewers").then((m) => ({ default: m.CsvViewer })));
|
||||||
import { fmtDate, fmtSize } from "./format";
|
import { fmtDate, fmtSize } from "./format";
|
||||||
|
|
||||||
/** Fichier à prévisualiser : adresses d'affichage et de téléchargement fournies par l'appelant. */
|
/** Fichier à prévisualiser : adresses d'affichage et de téléchargement fournies par l'appelant. */
|
||||||
@@ -11,11 +17,13 @@ export interface PreviewFile {
|
|||||||
name: string;
|
name: string;
|
||||||
size: number;
|
size: number;
|
||||||
modTime: string;
|
modTime: string;
|
||||||
/** Adresse d'affichage en ligne (images, vidéo, PDF). */
|
/** Adresse d'affichage en ligne (images, vidéo, audio). */
|
||||||
src: string;
|
src: string;
|
||||||
|
/** Adresse /api/preview (PDF). */
|
||||||
|
preview: string;
|
||||||
download: string;
|
download: string;
|
||||||
/** Lit le début du contenu texte. */
|
/** Lit le contenu texte via /api/preview (début seulement au-delà du plafond serveur). */
|
||||||
text: () => Promise<{ text: string; truncated: boolean }>;
|
text: () => Promise<PreviewText>;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -126,14 +134,14 @@ function Viewer({ file }: { file: PreviewFile }) {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
case "pdf":
|
case "pdf":
|
||||||
return <iframe className="viewer-pdf" src={file.src} title={file.name} />;
|
return <iframe className="viewer-pdf" src={file.preview} title={file.name} />;
|
||||||
default:
|
default:
|
||||||
return <TextViewer file={file} onError={() => setError(true)} />;
|
return <TextViewer file={file} onError={() => setError(true)} />;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void }) {
|
function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void }) {
|
||||||
const [state, setState] = useState<{ text: string; truncated: boolean } | null>(null);
|
const [state, setState] = useState<PreviewText | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let live = true;
|
let live = true;
|
||||||
file
|
file
|
||||||
@@ -146,10 +154,40 @@ function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [file.src]);
|
}, [file.src]);
|
||||||
if (!state) return <div className="preview-none muted">Chargement…</div>;
|
if (!state) return <div className="preview-none muted">Chargement…</div>;
|
||||||
const lines = state.text.split("\n");
|
const footer = state.truncated && (
|
||||||
|
<div className="notice">Aperçu limité au début du fichier ({fmtSize(file.size)} au total) : télécharger pour le lire en entier.</div>
|
||||||
|
);
|
||||||
|
const loading = <div className="preview-none muted">Chargement…</div>;
|
||||||
|
switch (previewMode(file.name)) {
|
||||||
|
case "code":
|
||||||
|
return (
|
||||||
|
<Suspense fallback={loading}>
|
||||||
|
<CodeViewer name={file.name} text={state.text} footer={footer} />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
case "markdown":
|
||||||
|
return (
|
||||||
|
<Suspense fallback={loading}>
|
||||||
|
<MarkdownViewer text={state.text} footer={footer} />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
case "csv":
|
||||||
|
return (
|
||||||
|
<Suspense fallback={loading}>
|
||||||
|
<CsvViewer name={file.name} text={state.text} truncated={state.truncated} footer={footer} />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return <PlainViewer name={file.name} text={state.text} footer={footer} />;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Texte brut (.txt, .log...), lignes numérotées. */
|
||||||
|
function PlainViewer({ name, text, footer }: { name: string; text: string; footer: ReactNode }) {
|
||||||
|
const lines = text.split("\n");
|
||||||
return (
|
return (
|
||||||
<div className="viewer-text">
|
<div className="viewer-text">
|
||||||
<pre className={monospace(file.name) ? "mono" : ""}>
|
<pre className={monospace(name) ? "mono" : ""}>
|
||||||
{lines.map((l, i) => (
|
{lines.map((l, i) => (
|
||||||
<span key={i} className="ln" data-n={i + 1}>
|
<span key={i} className="ln" data-n={i + 1}>
|
||||||
{l || " "}
|
{l || " "}
|
||||||
@@ -157,7 +195,7 @@ function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void
|
|||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
</pre>
|
</pre>
|
||||||
{state.truncated && <div className="notice">Aperçu limité au début du fichier ({fmtSize(512 * 1024)}) : télécharger pour le lire en entier.</div>}
|
{footer}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -63,7 +63,8 @@ export function ShareView({ token }: { token: string }) {
|
|||||||
modTime: f.modTime,
|
modTime: f.modTime,
|
||||||
src: api.publicFileUrl(token, join(sub, f.name), true),
|
src: api.publicFileUrl(token, join(sub, f.name), true),
|
||||||
download: api.publicFileUrl(token, join(sub, f.name)),
|
download: api.publicFileUrl(token, join(sub, f.name)),
|
||||||
text: async () => ({ text: await api.publicText(token, join(sub, f.name)), truncated: f.size > 512 * 1024 }),
|
preview: api.publicPreviewUrl(token, join(sub, f.name)),
|
||||||
|
text: () => api.publicPreview(token, join(sub, f.name)),
|
||||||
}))
|
}))
|
||||||
: info?.name
|
: info?.name
|
||||||
? [
|
? [
|
||||||
@@ -73,7 +74,8 @@ export function ShareView({ token }: { token: string }) {
|
|||||||
modTime: info.modTime,
|
modTime: info.modTime,
|
||||||
src: api.publicFileUrl(token, "", true),
|
src: api.publicFileUrl(token, "", true),
|
||||||
download: api.publicFileUrl(token, ""),
|
download: api.publicFileUrl(token, ""),
|
||||||
text: async () => ({ text: await api.publicText(token, ""), truncated: info.size > 512 * 1024 }),
|
preview: api.publicPreviewUrl(token, ""),
|
||||||
|
text: () => api.publicPreview(token, ""),
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
: [],
|
: [],
|
||||||
|
|||||||
+19
-8
@@ -201,6 +201,17 @@ async function request(url: string, init?: RequestInit): Promise<Response> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const q = (p: string) => encodeURIComponent(p);
|
const q = (p: string) => encodeURIComponent(p);
|
||||||
|
|
||||||
|
/** Texte renvoyé par /api/preview : truncated si le fichier dépasse le plafond du serveur. */
|
||||||
|
export interface PreviewText {
|
||||||
|
text: string;
|
||||||
|
truncated: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readPreview(url: string): Promise<PreviewText> {
|
||||||
|
const res = await request(url);
|
||||||
|
return { text: await res.text(), truncated: res.headers.get("X-Preview-Truncated") === "1" };
|
||||||
|
}
|
||||||
const json = (body: unknown, method = "POST"): RequestInit => ({
|
const json = (body: unknown, method = "POST"): RequestInit => ({
|
||||||
method,
|
method,
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
@@ -267,12 +278,11 @@ export const api = {
|
|||||||
restoreTrash: async (paths: string[]): Promise<MoveResult[]> =>
|
restoreTrash: async (paths: string[]): Promise<MoveResult[]> =>
|
||||||
(await request("/api/trash/restore", json({ paths }))).json(),
|
(await request("/api/trash/restore", json({ paths }))).json(),
|
||||||
|
|
||||||
/** Contenu texte d'un fichier (les premiers octets seulement : max). */
|
/** Aperçu texte d'un fichier (/api/preview : liste blanche, début du fichier au-delà du plafond serveur). */
|
||||||
readText: async (path: string, max = 512 * 1024): Promise<{ text: string; truncated: boolean }> => {
|
readPreview: (path: string): Promise<PreviewText> => readPreview(`/api/preview?path=${q(path)}`),
|
||||||
const res = await request(`/api/file?path=${q(path)}&inline=1`, { headers: { Range: `bytes=0-${max - 1}` } });
|
|
||||||
const total = Number((res.headers.get("Content-Range") ?? "").split("/")[1]);
|
/** Adresse d'aperçu en ligne (PDF : visionneuse du navigateur). */
|
||||||
return { text: await res.text(), truncated: res.status === 206 && total > max };
|
previewUrl: (path: string) => `/api/preview?path=${q(path)}`,
|
||||||
},
|
|
||||||
|
|
||||||
/** Empreinte SHA-256 (calculée à la demande côté serveur). */
|
/** Empreinte SHA-256 (calculée à la demande côté serveur). */
|
||||||
hash: async (path: string): Promise<string> => (await request(`/api/hash?path=${q(path)}`)).json().then((j) => j.sha256),
|
hash: async (path: string): Promise<string> => (await request(`/api/hash?path=${q(path)}`)).json().then((j) => j.sha256),
|
||||||
@@ -342,8 +352,9 @@ export const api = {
|
|||||||
|
|
||||||
publicThumbUrl: (token: string, sub: string) => `/api/public/${q(token)}/thumb?sub=${q(sub)}`,
|
publicThumbUrl: (token: string, sub: string) => `/api/public/${q(token)}/thumb?sub=${q(sub)}`,
|
||||||
|
|
||||||
publicText: async (token: string, sub: string, max = 512 * 1024): Promise<string> =>
|
publicPreview: (token: string, sub: string): Promise<PreviewText> => readPreview(`/api/public/${q(token)}/preview?sub=${q(sub)}`),
|
||||||
(await request(`/api/public/${q(token)}/file?sub=${q(sub)}&inline=1`, { headers: { Range: `bytes=0-${max - 1}` } })).text(),
|
|
||||||
|
publicPreviewUrl: (token: string, sub: string) => `/api/public/${q(token)}/preview?sub=${q(sub)}`,
|
||||||
|
|
||||||
// --- Jetons d'API ------------------------------------------------------------
|
// --- Jetons d'API ------------------------------------------------------------
|
||||||
tokens: async (): Promise<ApiToken[]> => (await request("/api/tokens")).json(),
|
tokens: async (): Promise<ApiToken[]> => (await request("/api/tokens")).json(),
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const sets: Record<Exclude<Kind, "other">, string> = {
|
|||||||
audio: "mp3 ogg oga wav flac aac m4a opus wma aiff mid midi",
|
audio: "mp3 ogg oga wav flac aac m4a opus wma aiff mid midi",
|
||||||
pdf: "pdf",
|
pdf: "pdf",
|
||||||
text: "txt md markdown rst log csv tsv json yaml yml toml ini conf cfg env srt tex bib nfo",
|
text: "txt md markdown rst log csv tsv json yaml yml toml ini conf cfg env srt tex bib nfo",
|
||||||
code: "html htm css js mjs ts tsx jsx py go rs java c h cpp hpp cs php rb sh bash zsh ps1 sql tf lua xml vue svelte service gitignore",
|
code: "html htm css scss less js mjs cjs ts tsx jsx jsonc py go rs java kt c h cpp hpp cs php rb sh bash zsh ps1 sql tf hcl lua xml vue svelte service properties diff patch gitignore",
|
||||||
archive: "zip gz tgz bz2 xz 7z rar tar zst iso dmg jar deb rpm apk",
|
archive: "zip gz tgz bz2 xz 7z rar tar zst iso dmg jar deb rpm apk",
|
||||||
doc: "doc docx odt rtf pages",
|
doc: "doc docx odt rtf pages",
|
||||||
sheet: "xls xlsx ods numbers",
|
sheet: "xls xlsx ods numbers",
|
||||||
@@ -19,12 +19,54 @@ const sets: Record<Exclude<Kind, "other">, string> = {
|
|||||||
const byExt = new Map<string, Kind>();
|
const byExt = new Map<string, Kind>();
|
||||||
for (const [kind, list] of Object.entries(sets)) for (const e of list.split(" ")) byExt.set(e, kind as Kind);
|
for (const [kind, list] of Object.entries(sets)) for (const e of list.split(" ")) byExt.set(e, kind as Kind);
|
||||||
|
|
||||||
const textNames = new Set(["dockerfile", "makefile", "readme", "license", "changelog"]);
|
const textNames = new Set(["readme", "license", "changelog"]);
|
||||||
|
const codeNames = new Set(["dockerfile", "containerfile", "makefile", "jenkinsfile", "vagrantfile", ".gitignore", ".dockerignore", ".env"]);
|
||||||
|
const isDockerfile = (lower: string) => lower.startsWith("dockerfile.") || lower.startsWith("containerfile.");
|
||||||
|
|
||||||
export const kindOf = (name: string): Kind => {
|
export const kindOf = (name: string): Kind => {
|
||||||
|
const lower = name.toLowerCase();
|
||||||
|
if (codeNames.has(lower) || isDockerfile(lower)) return "code";
|
||||||
const k = byExt.get(extOf(name));
|
const k = byExt.get(extOf(name));
|
||||||
if (k) return k;
|
if (k) return k;
|
||||||
return textNames.has(name.toLowerCase()) ? "text" : "other";
|
return textNames.has(lower) ? "text" : "other";
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Rendu de l'aperçu (même liste blanche que /api/preview, voir internal/api/preview.go). */
|
||||||
|
export type PreviewMode = "text" | "csv" | "markdown" | "code" | "pdf";
|
||||||
|
|
||||||
|
const plainExts = new Set(["txt", "log", "rst", "srt", "sub", "tex", "bib", "nfo"]);
|
||||||
|
|
||||||
|
export const previewMode = (name: string): PreviewMode | null => {
|
||||||
|
const lower = name.toLowerCase();
|
||||||
|
const e = extOf(name);
|
||||||
|
if (e === "pdf") return "pdf";
|
||||||
|
if (e === "csv" || e === "tsv") return "csv";
|
||||||
|
if (e === "md" || e === "markdown") return "markdown";
|
||||||
|
if (plainExts.has(e) || textNames.has(lower)) return "text";
|
||||||
|
const k = kindOf(name);
|
||||||
|
return k === "code" || k === "text" ? "code" : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Langage highlight.js par extension (ou nom de fichier) ; absent : texte brut.
|
||||||
|
const langByExt: Record<string, string> = {
|
||||||
|
json: "json", jsonc: "json",
|
||||||
|
js: "javascript", mjs: "javascript", cjs: "javascript", jsx: "javascript",
|
||||||
|
ts: "typescript", tsx: "typescript",
|
||||||
|
yaml: "yaml", yml: "yaml",
|
||||||
|
toml: "ini", ini: "ini", conf: "ini", cfg: "ini", properties: "properties", service: "ini", env: "bash",
|
||||||
|
go: "go", py: "python", sh: "bash", bash: "bash", zsh: "bash", ps1: "powershell",
|
||||||
|
xml: "xml", html: "xml", htm: "xml", vue: "xml", svelte: "xml",
|
||||||
|
css: "css", scss: "scss", less: "less", sql: "sql",
|
||||||
|
rs: "rust", java: "java", kt: "kotlin", c: "c", h: "c", cpp: "cpp", hpp: "cpp", cs: "csharp",
|
||||||
|
php: "php", rb: "ruby", lua: "lua", diff: "diff", patch: "diff",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const codeLanguage = (name: string): string | null => {
|
||||||
|
const lower = name.toLowerCase();
|
||||||
|
if (lower === "dockerfile" || lower === "containerfile" || isDockerfile(lower)) return "dockerfile";
|
||||||
|
if (lower === "makefile") return "makefile";
|
||||||
|
if (lower === ".env") return "bash";
|
||||||
|
return langByExt[extOf(name)] ?? null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Le serveur sait-il en faire une miniature (JPEG, PNG, GIF) ? */
|
/** Le serveur sait-il en faire une miniature (JPEG, PNG, GIF) ? */
|
||||||
@@ -50,7 +92,7 @@ export const previewable = (name: string): boolean => {
|
|||||||
case "pdf":
|
case "pdf":
|
||||||
case "text":
|
case "text":
|
||||||
case "code":
|
case "code":
|
||||||
return true;
|
return previewMode(name) !== null;
|
||||||
default:
|
default:
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2006,3 +2006,210 @@ th.c-size .th-btn {
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- Aperçu : code colorisé, Markdown, CSV ------------------------------------ */
|
||||||
|
:root {
|
||||||
|
--hl-comment: #6a737d;
|
||||||
|
--hl-keyword: #cf222e;
|
||||||
|
--hl-string: #0a3069;
|
||||||
|
--hl-number: #0550ae;
|
||||||
|
--hl-title: #8250df;
|
||||||
|
--hl-attr: #116329;
|
||||||
|
--hl-meta: #953800;
|
||||||
|
}
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--hl-comment: #8b949e;
|
||||||
|
--hl-keyword: #ff7b72;
|
||||||
|
--hl-string: #a5d6ff;
|
||||||
|
--hl-number: #79c0ff;
|
||||||
|
--hl-title: #d2a8ff;
|
||||||
|
--hl-attr: #7ee787;
|
||||||
|
--hl-meta: #ffa657;
|
||||||
|
}
|
||||||
|
.viewer-code .code-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto 1fr;
|
||||||
|
min-width: max-content;
|
||||||
|
}
|
||||||
|
.viewer-code pre {
|
||||||
|
margin: 0;
|
||||||
|
padding: 1rem 0;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.5;
|
||||||
|
white-space: pre;
|
||||||
|
}
|
||||||
|
.viewer-code .code-gutter {
|
||||||
|
position: sticky;
|
||||||
|
left: 0;
|
||||||
|
padding: 1rem 0.8rem 1rem 0.6rem;
|
||||||
|
min-width: 3.6rem;
|
||||||
|
text-align: right;
|
||||||
|
color: var(--muted);
|
||||||
|
background: var(--panel);
|
||||||
|
border-right: 1px solid var(--border);
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.viewer-code .code-body {
|
||||||
|
padding-left: 1rem;
|
||||||
|
padding-right: 1rem;
|
||||||
|
}
|
||||||
|
.hljs-comment,
|
||||||
|
.hljs-quote {
|
||||||
|
color: var(--hl-comment);
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
.hljs-keyword,
|
||||||
|
.hljs-selector-tag,
|
||||||
|
.hljs-literal,
|
||||||
|
.hljs-doctag,
|
||||||
|
.hljs-type {
|
||||||
|
color: var(--hl-keyword);
|
||||||
|
}
|
||||||
|
.hljs-string,
|
||||||
|
.hljs-regexp,
|
||||||
|
.hljs-addition {
|
||||||
|
color: var(--hl-string);
|
||||||
|
}
|
||||||
|
.hljs-number,
|
||||||
|
.hljs-symbol,
|
||||||
|
.hljs-bullet,
|
||||||
|
.hljs-variable,
|
||||||
|
.hljs-template-variable {
|
||||||
|
color: var(--hl-number);
|
||||||
|
}
|
||||||
|
.hljs-title,
|
||||||
|
.hljs-section,
|
||||||
|
.hljs-built_in,
|
||||||
|
.hljs-name {
|
||||||
|
color: var(--hl-title);
|
||||||
|
}
|
||||||
|
.hljs-attr,
|
||||||
|
.hljs-attribute,
|
||||||
|
.hljs-selector-class,
|
||||||
|
.hljs-selector-id,
|
||||||
|
.hljs-tag {
|
||||||
|
color: var(--hl-attr);
|
||||||
|
}
|
||||||
|
.hljs-meta,
|
||||||
|
.hljs-deletion,
|
||||||
|
.hljs-params {
|
||||||
|
color: var(--hl-meta);
|
||||||
|
}
|
||||||
|
.hljs-emphasis {
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
.hljs-strong {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.viewer-md .md {
|
||||||
|
max-width: 860px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 1.5rem 2rem 2rem;
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1.6;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.md h1,
|
||||||
|
.md h2 {
|
||||||
|
padding-bottom: 0.3em;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.md a {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
.md code {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.88em;
|
||||||
|
padding: 0.1em 0.35em;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--panel-2);
|
||||||
|
}
|
||||||
|
.md pre {
|
||||||
|
padding: 0.8rem 1rem;
|
||||||
|
overflow: auto;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--panel-2);
|
||||||
|
}
|
||||||
|
.md pre code {
|
||||||
|
padding: 0;
|
||||||
|
background: none;
|
||||||
|
}
|
||||||
|
.md blockquote {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0 1rem;
|
||||||
|
color: var(--muted);
|
||||||
|
border-left: 3px solid var(--border);
|
||||||
|
}
|
||||||
|
.md table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
display: block;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
.md th,
|
||||||
|
.md td {
|
||||||
|
padding: 0.35rem 0.7rem;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.md th {
|
||||||
|
background: var(--panel-2);
|
||||||
|
}
|
||||||
|
.md img,
|
||||||
|
.md .md-img {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.md input[type="checkbox"] {
|
||||||
|
margin-right: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.viewer-csv {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.csv-bar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem 0.8rem;
|
||||||
|
padding: 0.6rem 1rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.csv-header {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.3rem;
|
||||||
|
}
|
||||||
|
.csv-scroll {
|
||||||
|
flex: 1;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
.csv-table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 13px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.csv-table th,
|
||||||
|
.csv-table td {
|
||||||
|
padding: 0.3rem 0.7rem;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
max-width: 28rem;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.csv-table thead th {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
background: var(--panel-2);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.csv-table .csv-n {
|
||||||
|
color: var(--muted);
|
||||||
|
text-align: right;
|
||||||
|
background: var(--panel-2);
|
||||||
|
}
|
||||||
|
.csv-table tbody tr:hover td {
|
||||||
|
background: var(--hover);
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
// Visualiseurs riches de l'aperçu, chargés à la demande (React.lazy) :
|
||||||
|
// code colorisé (highlight.js), Markdown (react-markdown + remark-gfm, sans
|
||||||
|
// HTML brut), CSV paginé (PapaParse). Tout est rendu côté client à partir du
|
||||||
|
// texte servi par /api/preview.
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import Markdown from "react-markdown";
|
||||||
|
import type { Components } from "react-markdown";
|
||||||
|
import remarkGfm from "remark-gfm";
|
||||||
|
import Papa from "papaparse";
|
||||||
|
import hljs from "highlight.js/lib/core";
|
||||||
|
import bash from "highlight.js/lib/languages/bash";
|
||||||
|
import c from "highlight.js/lib/languages/c";
|
||||||
|
import cpp from "highlight.js/lib/languages/cpp";
|
||||||
|
import csharp from "highlight.js/lib/languages/csharp";
|
||||||
|
import css from "highlight.js/lib/languages/css";
|
||||||
|
import diff from "highlight.js/lib/languages/diff";
|
||||||
|
import dockerfile from "highlight.js/lib/languages/dockerfile";
|
||||||
|
import go from "highlight.js/lib/languages/go";
|
||||||
|
import ini from "highlight.js/lib/languages/ini";
|
||||||
|
import java from "highlight.js/lib/languages/java";
|
||||||
|
import javascript from "highlight.js/lib/languages/javascript";
|
||||||
|
import json from "highlight.js/lib/languages/json";
|
||||||
|
import kotlin from "highlight.js/lib/languages/kotlin";
|
||||||
|
import less from "highlight.js/lib/languages/less";
|
||||||
|
import lua from "highlight.js/lib/languages/lua";
|
||||||
|
import makefile from "highlight.js/lib/languages/makefile";
|
||||||
|
import php from "highlight.js/lib/languages/php";
|
||||||
|
import powershell from "highlight.js/lib/languages/powershell";
|
||||||
|
import properties from "highlight.js/lib/languages/properties";
|
||||||
|
import python from "highlight.js/lib/languages/python";
|
||||||
|
import ruby from "highlight.js/lib/languages/ruby";
|
||||||
|
import rust from "highlight.js/lib/languages/rust";
|
||||||
|
import scss from "highlight.js/lib/languages/scss";
|
||||||
|
import sql from "highlight.js/lib/languages/sql";
|
||||||
|
import typescript from "highlight.js/lib/languages/typescript";
|
||||||
|
import xml from "highlight.js/lib/languages/xml";
|
||||||
|
import yaml from "highlight.js/lib/languages/yaml";
|
||||||
|
import { codeLanguage } from "./filetypes";
|
||||||
|
|
||||||
|
const languages = {
|
||||||
|
bash, c, cpp, csharp, css, diff, dockerfile, go, ini, java, javascript, json, kotlin, less, lua,
|
||||||
|
makefile, php, powershell, properties, python, ruby, rust, scss, sql, typescript, xml, yaml,
|
||||||
|
};
|
||||||
|
for (const [name, def] of Object.entries(languages)) hljs.registerLanguage(name, def);
|
||||||
|
// Alias des blocs de code Markdown (```yml, ```sh, ```html...).
|
||||||
|
hljs.registerAliases(["yml"], { languageName: "yaml" });
|
||||||
|
hljs.registerAliases(["sh", "shell", "zsh"], { languageName: "bash" });
|
||||||
|
hljs.registerAliases(["html", "htm", "svg"], { languageName: "xml" });
|
||||||
|
hljs.registerAliases(["js", "mjs"], { languageName: "javascript" });
|
||||||
|
hljs.registerAliases(["ts"], { languageName: "typescript" });
|
||||||
|
hljs.registerAliases(["py"], { languageName: "python" });
|
||||||
|
hljs.registerAliases(["toml"], { languageName: "ini" });
|
||||||
|
|
||||||
|
/** Au-delà, pas de coloration (temps de calcul) : texte brut numéroté. */
|
||||||
|
const MAX_HIGHLIGHT = 512 * 1024;
|
||||||
|
|
||||||
|
/** HTML coloré (échappé par highlight.js), ou null si le langage est inconnu. */
|
||||||
|
function highlight(text: string, lang: string | null): string | null {
|
||||||
|
if (!lang || !hljs.getLanguage(lang) || text.length > MAX_HIGHLIGHT) return null;
|
||||||
|
try {
|
||||||
|
return hljs.highlight(text, { language: lang, ignoreIllegals: true }).value;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Code numéroté et colorisé selon l'extension ; un fichier HTML s'affiche comme du code, jamais rendu. */
|
||||||
|
export function CodeViewer({ name, text, footer }: { name: string; text: string; footer?: ReactNode }) {
|
||||||
|
const lang = codeLanguage(name);
|
||||||
|
const html = useMemo(() => highlight(text, lang), [text, lang]);
|
||||||
|
// Un saut de ligne final n'ouvre pas de ligne supplémentaire.
|
||||||
|
const count = useMemo(() => text.split("\n").length - (text.endsWith("\n") ? 1 : 0), [text]);
|
||||||
|
const gutter = useMemo(() => Array.from({ length: count }, (_, i) => i + 1).join("\n"), [count]);
|
||||||
|
return (
|
||||||
|
<div className="viewer-text viewer-code">
|
||||||
|
<div className="code-grid">
|
||||||
|
<pre className="code-gutter" aria-hidden>
|
||||||
|
{gutter}
|
||||||
|
</pre>
|
||||||
|
{html !== null ? (
|
||||||
|
<pre className="code-body hljs" dangerouslySetInnerHTML={{ __html: html }} />
|
||||||
|
) : (
|
||||||
|
<pre className="code-body">{text}</pre>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{lang && html === null && text.length > MAX_HIGHLIGHT && <div className="notice">Fichier volumineux : affiché sans coloration.</div>}
|
||||||
|
{footer}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Markdown : pas de HTML brut (skipHtml), liens ouverts hors de l'application,
|
||||||
|
// images non chargées (aucune requête vers un site tiers) : remplacées par un lien.
|
||||||
|
const mdComponents: Components = {
|
||||||
|
a: ({ href, children }) => (
|
||||||
|
<a href={href} target="_blank" rel="noopener noreferrer nofollow">
|
||||||
|
{children}
|
||||||
|
</a>
|
||||||
|
),
|
||||||
|
img: ({ src, alt }) =>
|
||||||
|
typeof src === "string" && /^https?:\/\//i.test(src) ? (
|
||||||
|
<a href={src} target="_blank" rel="noopener noreferrer nofollow" className="md-img">
|
||||||
|
[image : {alt || src}]
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<span className="md-img">[image : {alt || String(src ?? "")}]</span>
|
||||||
|
),
|
||||||
|
code: ({ className, children }) => {
|
||||||
|
const lang = /language-([\w-]+)/.exec(className ?? "")?.[1] ?? null;
|
||||||
|
const src = String(children ?? "");
|
||||||
|
const html = lang ? highlight(src.replace(/\n$/, ""), lang) : null;
|
||||||
|
return html !== null ? <code className={`hljs ${className ?? ""}`} dangerouslySetInnerHTML={{ __html: html }} /> : <code className={className}>{children}</code>;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function MarkdownViewer({ text, footer }: { text: string; footer?: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="viewer-text viewer-md">
|
||||||
|
<article className="md">
|
||||||
|
<Markdown remarkPlugins={[remarkGfm]} skipHtml components={mdComponents}>
|
||||||
|
{text}
|
||||||
|
</Markdown>
|
||||||
|
</article>
|
||||||
|
{footer}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAGE = 100;
|
||||||
|
|
||||||
|
/** Tableau paginé ; séparateur détecté par PapaParse (virgule, point-virgule, tabulation...). */
|
||||||
|
export function CsvViewer({ name, text, truncated, footer }: { name: string; text: string; truncated: boolean; footer?: ReactNode }) {
|
||||||
|
const [page, setPage] = useState(0);
|
||||||
|
const [header, setHeader] = useState(true);
|
||||||
|
const parsed = useMemo(() => {
|
||||||
|
const r = Papa.parse<string[]>(text, {
|
||||||
|
skipEmptyLines: "greedy",
|
||||||
|
delimiter: name.toLowerCase().endsWith(".tsv") ? "\t" : undefined,
|
||||||
|
});
|
||||||
|
const rows = r.data;
|
||||||
|
if (truncated && rows.length > 1) rows.pop(); // dernière ligne coupée par le plafond
|
||||||
|
return { rows, delimiter: r.meta.delimiter, errors: r.errors.length };
|
||||||
|
}, [text, truncated, name]);
|
||||||
|
|
||||||
|
const head = header ? (parsed.rows[0] ?? []) : null;
|
||||||
|
const body = header ? parsed.rows.slice(1) : parsed.rows;
|
||||||
|
const pages = Math.max(1, Math.ceil(body.length / PAGE));
|
||||||
|
const p = Math.min(page, pages - 1);
|
||||||
|
const rows = body.slice(p * PAGE, (p + 1) * PAGE);
|
||||||
|
const cols = Math.max(head?.length ?? 0, ...rows.map((r) => r.length));
|
||||||
|
const delim = parsed.delimiter === "\t" ? "tabulation" : `« ${parsed.delimiter} »`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="viewer-text viewer-csv">
|
||||||
|
<div className="csv-bar">
|
||||||
|
<span className="muted">
|
||||||
|
{body.length.toLocaleString("fr-FR")} ligne{body.length > 1 ? "s" : ""} · {cols} colonne{cols > 1 ? "s" : ""} · séparateur {delim}
|
||||||
|
{parsed.errors > 0 && ` · ${parsed.errors} ligne${parsed.errors > 1 ? "s" : ""} mal formée${parsed.errors > 1 ? "s" : ""}`}
|
||||||
|
</span>
|
||||||
|
<label className="csv-header">
|
||||||
|
<input type="checkbox" checked={header} onChange={(e) => (setHeader(e.target.checked), setPage(0))} /> Première ligne = en-tête
|
||||||
|
</label>
|
||||||
|
<span className="spacer" />
|
||||||
|
<button className="ex-btn" disabled={p === 0} onClick={() => setPage(p - 1)}>
|
||||||
|
Précédent
|
||||||
|
</button>
|
||||||
|
<span className="muted">
|
||||||
|
Page {p + 1} / {pages}
|
||||||
|
</span>
|
||||||
|
<button className="ex-btn" disabled={p >= pages - 1} onClick={() => setPage(p + 1)}>
|
||||||
|
Suivant
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="csv-scroll">
|
||||||
|
<table className="csv-table">
|
||||||
|
{head && (
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th className="csv-n">#</th>
|
||||||
|
{Array.from({ length: cols }, (_, i) => (
|
||||||
|
<th key={i}>{head[i] ?? ""}</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
)}
|
||||||
|
<tbody>
|
||||||
|
{rows.map((r, i) => (
|
||||||
|
<tr key={p * PAGE + i}>
|
||||||
|
<td className="csv-n">{p * PAGE + i + 1}</td>
|
||||||
|
{Array.from({ length: cols }, (_, j) => (
|
||||||
|
<td key={j}>{r[j] ?? ""}</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{footer}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+13
-5
@@ -8,6 +8,7 @@
|
|||||||
// POST /api/meta/tags {"paths":[...],"add":[...],"remove":[...]} tags
|
// POST /api/meta/tags {"paths":[...],"add":[...],"remove":[...]} tags
|
||||||
// POST /api/meta/icon {"paths":[...],"icon":"server"} icône de dossiers ("" : défaut)
|
// POST /api/meta/icon {"paths":[...],"icon":"server"} icône de dossiers ("" : défaut)
|
||||||
// GET /api/file?path=a/b.pdf[&inline=1] téléchargement (Range, ETag) ; inline : affichage dans le navigateur si sûr
|
// GET /api/file?path=a/b.pdf[&inline=1] téléchargement (Range, ETag) ; inline : affichage dans le navigateur si sûr
|
||||||
|
// GET /api/preview?path=a/b.md aperçu en lecture seule (liste blanche, texte plafonné ; voir preview.go)
|
||||||
// PUT /api/file?path=a/b.pdf[&conflict=fail|overwrite|rename][&mtime=ms] dépôt en flux
|
// PUT /api/file?path=a/b.pdf[&conflict=fail|overwrite|rename][&mtime=ms] dépôt en flux
|
||||||
// POST /api/folder {"path":"a/b"} création de dossier
|
// POST /api/folder {"path":"a/b"} création de dossier
|
||||||
// POST /api/move {"from":"x","to":"y"} renommage / déplacement
|
// POST /api/move {"from":"x","to":"y"} renommage / déplacement
|
||||||
@@ -29,7 +30,7 @@
|
|||||||
// POST /api/shares/revoke-all révocation de tous les liens (administrateur)
|
// POST /api/shares/revoke-all révocation de tous les liens (administrateur)
|
||||||
// GET /api/public/{jeton}[?sub=d] lien de partage (sans authentification)
|
// GET /api/public/{jeton}[?sub=d] lien de partage (sans authentification)
|
||||||
// POST /api/public/{jeton}/unlock mot de passe d'un lien protégé
|
// POST /api/public/{jeton}/unlock mot de passe d'un lien protégé
|
||||||
// GET /api/public/{jeton}/file|zip|thumb contenu d'un lien de partage
|
// GET /api/public/{jeton}/file|zip|thumb|preview contenu d'un lien de partage
|
||||||
// GET /api/settings / PUT paramètres (écriture : administrateur)
|
// GET /api/settings / PUT paramètres (écriture : administrateur)
|
||||||
// GET /api/logo / PUT (image/png) / DELETE logo 64x64
|
// GET /api/logo / PUT (image/png) / DELETE logo 64x64
|
||||||
// POST /api/account/password changement du mot de passe (compte local)
|
// POST /api/account/password changement du mot de passe (compte local)
|
||||||
@@ -63,10 +64,12 @@ type Handler struct {
|
|||||||
Auth *auth.Auth // nil : pas d'authentification intégrée
|
Auth *auth.Auth // nil : pas d'authentification intégrée
|
||||||
Accounts *auth.Accounts // nil : pas de comptes (AUTH_MODE=none)
|
Accounts *auth.Accounts // nil : pas de comptes (AUTH_MODE=none)
|
||||||
|
|
||||||
MaxJSON int64 // taille maximale d'un corps JSON (octets)
|
MaxJSON int64 // taille maximale d'un corps JSON (octets)
|
||||||
Mode string // none, local, oidc ou both
|
// PreviewMaxText : octets de texte servis au plus par /api/preview.
|
||||||
OIDCName string // libellé du bouton de connexion OIDC
|
PreviewMaxText int64
|
||||||
Version string
|
Mode string // none, local, oidc ou both
|
||||||
|
OIDCName string // libellé du bouton de connexion OIDC
|
||||||
|
Version string
|
||||||
|
|
||||||
// SecureCookies : cookies de déverrouillage des liens marqués Secure même
|
// SecureCookies : cookies de déverrouillage des liens marqués Secure même
|
||||||
// en HTTP direct (URL publique en https).
|
// en HTTP direct (URL publique en https).
|
||||||
@@ -83,6 +86,9 @@ func (h *Handler) Init() *Handler {
|
|||||||
if h.MaxJSON == 0 {
|
if h.MaxJSON == 0 {
|
||||||
h.MaxJSON = 1 << 20
|
h.MaxJSON = 1 << 20
|
||||||
}
|
}
|
||||||
|
if h.PreviewMaxText == 0 {
|
||||||
|
h.PreviewMaxText = DefaultPreviewMaxText
|
||||||
|
}
|
||||||
h.unlocks = auth.NewLimiter(10, 15*time.Minute)
|
h.unlocks = auth.NewLimiter(10, 15*time.Minute)
|
||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
@@ -139,6 +145,7 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("POST /api/meta/tags", h.editTags)
|
mux.HandleFunc("POST /api/meta/tags", h.editTags)
|
||||||
mux.HandleFunc("POST /api/meta/icon", h.setIcon)
|
mux.HandleFunc("POST /api/meta/icon", h.setIcon)
|
||||||
mux.HandleFunc("GET /api/file", h.download)
|
mux.HandleFunc("GET /api/file", h.download)
|
||||||
|
mux.HandleFunc("GET /api/preview", h.preview)
|
||||||
mux.HandleFunc("PUT /api/file", h.upload)
|
mux.HandleFunc("PUT /api/file", h.upload)
|
||||||
mux.HandleFunc("POST /api/folder", h.mkdir)
|
mux.HandleFunc("POST /api/folder", h.mkdir)
|
||||||
mux.HandleFunc("POST /api/move", h.move)
|
mux.HandleFunc("POST /api/move", h.move)
|
||||||
@@ -163,6 +170,7 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("GET /api/public/{token}/file", h.publicFile)
|
mux.HandleFunc("GET /api/public/{token}/file", h.publicFile)
|
||||||
mux.HandleFunc("GET /api/public/{token}/zip", h.publicZip)
|
mux.HandleFunc("GET /api/public/{token}/zip", h.publicZip)
|
||||||
mux.HandleFunc("GET /api/public/{token}/thumb", h.publicThumb)
|
mux.HandleFunc("GET /api/public/{token}/thumb", h.publicThumb)
|
||||||
|
mux.HandleFunc("GET /api/public/{token}/preview", h.publicPreview)
|
||||||
mux.HandleFunc("GET /api/settings", h.readSettings)
|
mux.HandleFunc("GET /api/settings", h.readSettings)
|
||||||
mux.HandleFunc("PUT /api/settings", h.writeSettings)
|
mux.HandleFunc("PUT /api/settings", h.writeSettings)
|
||||||
mux.HandleFunc("GET /api/logo", h.readLogo)
|
mux.HandleFunc("GET /api/logo", h.readLogo)
|
||||||
|
|||||||
@@ -0,0 +1,196 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/vblogio/upandown/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Aperçu en lecture seule, rendu côté client.
|
||||||
|
//
|
||||||
|
// GET /api/preview?path=x (même authentification que /api/file)
|
||||||
|
// GET /api/public/{jeton}/preview?sub=x (même contrôle que /api/public/{jeton}/file)
|
||||||
|
//
|
||||||
|
// Seules les extensions de la liste blanche sont servies, toujours en
|
||||||
|
// Content-Disposition: inline, avec nosniff et une CSP stricte. Le contenu
|
||||||
|
// texte n'est jamais servi avec un type actif (HTML, XML, JavaScript) : un
|
||||||
|
// fichier .html part en text/plain et s'affiche comme du code. Le texte est
|
||||||
|
// plafonné à Handler.PreviewMaxText ; au-delà, seul le début est envoyé.
|
||||||
|
//
|
||||||
|
// En-têtes de réponse : X-Preview-Kind (text, csv, markdown, code, pdf),
|
||||||
|
// X-Preview-Size (taille réelle du fichier), X-Preview-Truncated (1 si coupé).
|
||||||
|
|
||||||
|
// Genres d'aperçu.
|
||||||
|
const (
|
||||||
|
PreviewText = "text"
|
||||||
|
PreviewCSV = "csv"
|
||||||
|
PreviewMarkdown = "markdown"
|
||||||
|
PreviewCode = "code"
|
||||||
|
PreviewPDF = "pdf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultPreviewMaxText : plafond par défaut du texte servi en aperçu.
|
||||||
|
const DefaultPreviewMaxText = 2 << 20
|
||||||
|
|
||||||
|
// previewExts : liste blanche des extensions prévisualisables.
|
||||||
|
var previewExts = map[string]string{
|
||||||
|
".txt": PreviewText, ".log": PreviewText, ".rst": PreviewText, ".srt": PreviewText, ".sub": PreviewText,
|
||||||
|
".tex": PreviewText, ".bib": PreviewText, ".nfo": PreviewText,
|
||||||
|
".csv": PreviewCSV, ".tsv": PreviewCSV,
|
||||||
|
".md": PreviewMarkdown, ".markdown": PreviewMarkdown,
|
||||||
|
".pdf": PreviewPDF,
|
||||||
|
}
|
||||||
|
|
||||||
|
// previewNames : fichiers sans extension reconnus par leur nom (en minuscules).
|
||||||
|
var previewNames = map[string]string{
|
||||||
|
"dockerfile": PreviewCode, "containerfile": PreviewCode, "makefile": PreviewCode,
|
||||||
|
"jenkinsfile": PreviewCode, "vagrantfile": PreviewCode,
|
||||||
|
"readme": PreviewText, "license": PreviewText, "changelog": PreviewText,
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
for _, e := range strings.Fields(`
|
||||||
|
.json .jsonc .js .mjs .cjs .jsx .ts .tsx .yaml .yml .toml .ini .conf .cfg .env .properties
|
||||||
|
.go .py .sh .bash .zsh .ps1 .xml .html .htm .css .scss .less .sql .rs .java .kt .c .h .cpp .hpp
|
||||||
|
.cs .php .rb .lua .tf .hcl .service .gitignore .dockerignore .diff .patch .vue .svelte`) {
|
||||||
|
previewExts[e] = PreviewCode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PreviewKind renvoie le genre d'aperçu d'un fichier ("" : non prévisualisable).
|
||||||
|
func PreviewKind(name string) string {
|
||||||
|
base := strings.ToLower(path.Base(name))
|
||||||
|
if k, ok := previewNames[base]; ok {
|
||||||
|
return k
|
||||||
|
}
|
||||||
|
// Dockerfile.dev, Containerfile.prod...
|
||||||
|
if strings.HasPrefix(base, "dockerfile.") || strings.HasPrefix(base, "containerfile.") {
|
||||||
|
return PreviewCode
|
||||||
|
}
|
||||||
|
return previewExts[strings.ToLower(path.Ext(base))]
|
||||||
|
}
|
||||||
|
|
||||||
|
// previewType : type MIME servi pour chaque genre. Jamais de type actif.
|
||||||
|
var previewType = map[string]string{
|
||||||
|
PreviewText: "text/plain; charset=utf-8",
|
||||||
|
PreviewCode: "text/plain; charset=utf-8",
|
||||||
|
PreviewCSV: "text/csv; charset=utf-8",
|
||||||
|
PreviewMarkdown: "text/markdown; charset=utf-8",
|
||||||
|
PreviewPDF: "application/pdf",
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Texte : récupéré par fetch, jamais affiché en navigation directe comme
|
||||||
|
// un document actif ; sandbox et aucune sous-ressource.
|
||||||
|
cspPreviewText = "sandbox; default-src 'none'; frame-ancestors 'none'"
|
||||||
|
// PDF : affiché par la visionneuse du navigateur dans une iframe de
|
||||||
|
// l'application. Pas de sandbox (Chrome refuse alors d'afficher le PDF).
|
||||||
|
cspPreviewPDF = "default-src 'none'; object-src 'self'; frame-ancestors 'self'"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Handler) preview(w http.ResponseWriter, r *http.Request) {
|
||||||
|
u, ok := h.space(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p := r.URL.Query().Get("path")
|
||||||
|
if PreviewKind(p) == "" {
|
||||||
|
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f, fi, err := u.Open(p)
|
||||||
|
if err != nil {
|
||||||
|
fail(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
h.servePreview(w, r, f, fi)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) publicPreview(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, st, full, _, ok := h.sharedItem(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f, fi, err := st.Open(full)
|
||||||
|
if err != nil {
|
||||||
|
fail(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
h.servePreview(w, r, f, fi)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.File, fi fs.FileInfo) {
|
||||||
|
name := fi.Name()
|
||||||
|
kind := PreviewKind(name)
|
||||||
|
if kind == "" || fi.IsDir() {
|
||||||
|
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hd := w.Header()
|
||||||
|
hd.Set("Content-Type", previewType[kind])
|
||||||
|
hd.Set("Content-Disposition", contentDisposition(true, name))
|
||||||
|
hd.Set("X-Content-Type-Options", "nosniff")
|
||||||
|
hd.Set("Cache-Control", "private, no-cache")
|
||||||
|
hd.Set("ETag", storage.ETag(fi))
|
||||||
|
hd.Set("X-Preview-Kind", kind)
|
||||||
|
hd.Set("X-Preview-Size", strconv.FormatInt(fi.Size(), 10))
|
||||||
|
|
||||||
|
if kind == PreviewPDF {
|
||||||
|
hd.Set("Content-Security-Policy", cspPreviewPDF)
|
||||||
|
hd.Set("X-Preview-Truncated", "0")
|
||||||
|
http.ServeContent(w, r, name, fi.ModTime(), f)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hd.Set("Content-Security-Policy", cspPreviewText)
|
||||||
|
max := h.PreviewMaxText
|
||||||
|
if max <= 0 {
|
||||||
|
max = DefaultPreviewMaxText
|
||||||
|
}
|
||||||
|
b, err := io.ReadAll(io.LimitReader(f, max))
|
||||||
|
if err != nil {
|
||||||
|
fail(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
truncated := fi.Size() > int64(len(b))
|
||||||
|
if truncated {
|
||||||
|
b = trimPartialRune(b)
|
||||||
|
}
|
||||||
|
if bytes.IndexByte(b[:min(len(b), 8192)], 0) >= 0 {
|
||||||
|
hd.Del("Content-Disposition")
|
||||||
|
writeErr(w, http.StatusUnsupportedMediaType, "contenu binaire : pas d'aperçu")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hd.Set("X-Preview-Truncated", map[bool]string{true: "1", false: "0"}[truncated])
|
||||||
|
// L'ETag désigne le fichier : il reste valable pour l'extrait tant que le
|
||||||
|
// plafond ne change pas. Pas de Range sur un extrait.
|
||||||
|
r.Header.Del("Range")
|
||||||
|
http.ServeContent(w, r, name, fi.ModTime(), bytes.NewReader(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
// trimPartialRune retire un caractère UTF-8 coupé en fin d'extrait.
|
||||||
|
func trimPartialRune(b []byte) []byte {
|
||||||
|
for i := 1; i <= utf8.UTFMax && i <= len(b); i++ {
|
||||||
|
c := b[len(b)-i]
|
||||||
|
if c < 0x80 { // ASCII : rien de coupé
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
if utf8.RuneStart(c) {
|
||||||
|
if r, _ := utf8.DecodeRune(b[len(b)-i:]); r == utf8.RuneError {
|
||||||
|
return b[:len(b)-i]
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/vblogio/upandown/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPreviewKind(t *testing.T) {
|
||||||
|
for name, k := range map[string]string{
|
||||||
|
"a.txt": PreviewText, "x/app.LOG": PreviewText, "d.csv": PreviewCSV, "README.md": PreviewMarkdown,
|
||||||
|
"doc.pdf": PreviewPDF, "c.json": PreviewCode, "i.html": PreviewCode, "k.yaml": PreviewCode,
|
||||||
|
"Dockerfile": PreviewCode, "dockerfile.dev": PreviewCode, "Makefile": PreviewCode,
|
||||||
|
"a.docx": "", "a.rtf": "", "a.doc": "", "a.png": "", "a.exe": "", "noext": "",
|
||||||
|
} {
|
||||||
|
if got := PreviewKind(name); got != k {
|
||||||
|
t.Errorf("PreviewKind(%q) = %q, attendu %q", name, got, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreviewHeadersAndWhitelist(t *testing.T) {
|
||||||
|
f := newFixture(t, nil)
|
||||||
|
s := f.register("alice")
|
||||||
|
want(t, s.put("page.html", "<script>alert(1)</script>"), 200)
|
||||||
|
want(t, s.put("data.csv", "a,b\n1,2\n"), 200)
|
||||||
|
want(t, s.put("note.md", "# titre"), 200)
|
||||||
|
want(t, s.put("doc.pdf", "%PDF-1.4\n"), 200)
|
||||||
|
want(t, s.put("x.docx", "PK"), 200)
|
||||||
|
want(t, s.put("bin.log", "abc\x00def"), 200)
|
||||||
|
|
||||||
|
// Même authentification que le téléchargement.
|
||||||
|
want(t, f.session().get("/api/preview?path=page.html"), 401)
|
||||||
|
|
||||||
|
for p, ct := range map[string]string{
|
||||||
|
"page.html": "text/plain; charset=utf-8",
|
||||||
|
"data.csv": "text/csv; charset=utf-8",
|
||||||
|
"note.md": "text/markdown; charset=utf-8",
|
||||||
|
"doc.pdf": "application/pdf",
|
||||||
|
} {
|
||||||
|
w := s.get("/api/preview?path=" + p)
|
||||||
|
want(t, w, 200)
|
||||||
|
h := w.Header()
|
||||||
|
if h.Get("Content-Type") != ct {
|
||||||
|
t.Errorf("%s : Content-Type %q, attendu %q", p, h.Get("Content-Type"), ct)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(h.Get("Content-Disposition"), "inline;") || h.Get("X-Content-Type-Options") != "nosniff" {
|
||||||
|
t.Errorf("%s : en-têtes %v", p, h)
|
||||||
|
}
|
||||||
|
csp := h.Get("Content-Security-Policy")
|
||||||
|
if !strings.Contains(csp, "default-src 'none'") {
|
||||||
|
t.Errorf("%s : CSP %q", p, csp)
|
||||||
|
}
|
||||||
|
if p != "doc.pdf" && !strings.HasPrefix(csp, "sandbox") {
|
||||||
|
t.Errorf("%s : CSP sans sandbox %q", p, csp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if b := s.get("/api/preview?path=page.html").Body.String(); b != "<script>alert(1)</script>" {
|
||||||
|
t.Errorf("contenu HTML : %q", b)
|
||||||
|
}
|
||||||
|
want(t, s.get("/api/preview?path=x.docx"), 415)
|
||||||
|
want(t, s.get("/api/preview?path=bin.log"), 415)
|
||||||
|
want(t, s.get("/api/preview?path=absent.txt"), 404)
|
||||||
|
want(t, s.get("/api/preview?path=../../etc/passwd.txt"), 404) // normalisé sous la racine
|
||||||
|
want(t, s.get("/api/preview?path=.accounts.json"), 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreviewTextCap(t *testing.T) {
|
||||||
|
f := newFixture(t, nil)
|
||||||
|
f.handler.PreviewMaxText = 10
|
||||||
|
s := f.register("alice")
|
||||||
|
want(t, s.put("court.txt", "court"), 200)
|
||||||
|
want(t, s.put("long.txt", "abcdefghié12345"), 200) // é sur les octets 10-11 : coupé à 9
|
||||||
|
w := s.get("/api/preview?path=court.txt")
|
||||||
|
want(t, w, 200)
|
||||||
|
if w.Body.String() != "court" || w.Header().Get("X-Preview-Truncated") != "0" || w.Header().Get("X-Preview-Size") != "5" {
|
||||||
|
t.Errorf("court : %q %v", w.Body, w.Header())
|
||||||
|
}
|
||||||
|
w = s.get("/api/preview?path=long.txt", "Range", "bytes=0-2")
|
||||||
|
want(t, w, 200) // pas de Range sur l'extrait
|
||||||
|
if w.Body.String() != "abcdefghi" || w.Header().Get("X-Preview-Truncated") != "1" || w.Header().Get("X-Preview-Size") != "16" {
|
||||||
|
t.Errorf("long : %q %v", w.Body, w.Header())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPublicPreview(t *testing.T) {
|
||||||
|
f := newFixture(t, nil)
|
||||||
|
s := f.register("alice")
|
||||||
|
want(t, s.put("dir/a.go", "package a"), 200)
|
||||||
|
want(t, s.put("dir/b.zip", "PK"), 200)
|
||||||
|
sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "dir", "days": 1}))
|
||||||
|
v := f.session()
|
||||||
|
w := v.get("/api/public/" + sh.Token + "/preview?sub=a.go")
|
||||||
|
want(t, w, 200)
|
||||||
|
if w.Body.String() != "package a" || w.Header().Get("X-Preview-Kind") != PreviewCode {
|
||||||
|
t.Errorf("public : %q %v", w.Body, w.Header())
|
||||||
|
}
|
||||||
|
want(t, v.get("/api/public/"+sh.Token+"/preview?sub=b.zip"), 415)
|
||||||
|
want(t, v.get("/api/public/nope/preview?sub=a.go"), 404)
|
||||||
|
}
|
||||||
Reference in new issue
Block a user