Aperçu : détection automatique des fichiers texte et réglages

- Hors liste blanche, reniflage du contenu (UTF-8 valide, sans NUL, peu de caractères de contrôle) : .pem, .csr, fichiers sans extension... servis en text/plain avec les mêmes protections
- Langage deviné côté client (highlight.js), sauf blocs PEM/PGP
- Paramètres > Aperçu : préférences d'affichage par navigateur (coloration, numéros de ligne, retour à la ligne, Markdown rendu/source, CSV) ; réglages administrateur (détection, plafond 1-50 Mo, extensions texte, extensions exclues, aperçu dans les partages)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
cedricandClaude Opus 5.5 committed 2026-11-20 12:19:30 +01:00
1 parent d4da3db132
commit ca53cedc32
12 files changed
+800 -79

No files matched your search

+43 -18
View File
@@ -4,7 +4,8 @@ import { createPortal } from "react-dom";
import { ChevronLeftIcon, ChevronRightIcon, CloseIcon, DownloadIcon, ExpandIcon } from "./icons";
import { FileGlyph } from "./FileGlyph";
import { kindOf, monospace, previewable, previewMode, typeLabel } from "./filetypes";
import type { PreviewText } from "./api";
import { ApiError, previewAllowed, type PreviewText } from "./api";
import { usePreviewPrefs } from "./prefs";
// Visualiseurs riches (highlight.js, react-markdown, PapaParse) : module chargé à la première ouverture.
const CodeViewer = lazy(() => import("./viewers").then((m) => ({ default: m.CodeViewer })));
@@ -96,16 +97,19 @@ export function Preview({ files, index, onIndex, onClose, actions }: Props) {
function Viewer({ file }: { file: PreviewFile }) {
const kind = kindOf(file.name);
const [zoom, setZoom] = useState(false);
const [error, setError] = useState(false);
// null : pas d'erreur ; "" : erreur d'affichage ; sinon refus du serveur (message).
const [error, setError] = useState<string | null>(null);
const fail = (e?: unknown) =>
setError(e instanceof ApiError && (e.status === 415 || e.status === 403) ? e.message.charAt(0).toUpperCase() + e.message.slice(1) + "." : "");
if (!previewable(file.name) || error) {
if (!previewable(file.name) || error !== null) {
return (
<div className="preview-none">
<FileGlyph name={file.name} size={72} />
<p>
<strong>{file.name}</strong>
</p>
<p className="muted">{error ? "Impossible d'afficher ce fichier dans le navigateur." : "Pas d'aperçu pour ce type de fichier."}</p>
<p className="muted">{error === null ? "Pas d'aperçu pour ce type de fichier." : error || "Impossible d'afficher ce fichier dans le navigateur."}</p>
<a className="ex-btn primary" href={file.download} download={file.name}>
<DownloadIcon />
<span>Télécharger ({fmtSize(file.size)})</span>
@@ -117,37 +121,56 @@ function Viewer({ file }: { file: PreviewFile }) {
case "image":
return (
<div className={`viewer-image ${zoom ? "zoom" : ""}`}>
<img src={file.src} alt={file.name} onClick={() => setZoom((z) => !z)} onError={() => setError(true)} draggable={false} />
<img src={file.src} alt={file.name} onClick={() => setZoom((z) => !z)} onError={() => fail()} draggable={false} />
<button className="icon-btn zoom-btn" onClick={() => setZoom((z) => !z)} title={zoom ? "Ajuster à la fenêtre" : "Taille réelle"} aria-label="Zoom">
<ExpandIcon />
</button>
</div>
);
case "video":
return <video className="viewer-media" src={file.src} controls autoPlay playsInline onError={() => setError(true)} />;
return <video className="viewer-media" src={file.src} controls autoPlay playsInline onError={() => fail()} />;
case "audio":
return (
<div className="viewer-audio">
<FileGlyph name={file.name} size={64} />
<p>{file.name}</p>
<audio src={file.src} controls autoPlay onError={() => setError(true)} />
<audio src={file.src} controls autoPlay onError={() => fail()} />
</div>
);
case "pdf":
return <iframe className="viewer-pdf" src={file.preview} title={file.name} />;
return <PdfViewer file={file} onError={fail} />;
default:
return <TextViewer file={file} onError={() => setError(true)} />;
return <TextViewer file={file} onError={fail} />;
}
}
function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void }) {
/** PDF : visionneuse du navigateur, après vérification que le serveur l'accepte (réglages). */
function PdfViewer({ file, onError }: { file: PreviewFile; onError: (e?: unknown) => void }) {
const [ok, setOk] = useState(false);
useEffect(() => {
let live = true;
previewAllowed(file.preview).then((v) => {
if (!live) return;
if (v) setOk(true);
else onError(new ApiError(415, "pas d'aperçu pour ce type de fichier"));
});
return () => {
live = false;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [file.preview]);
return ok ? <iframe className="viewer-pdf" src={file.preview} title={file.name} /> : <div className="preview-none muted">Chargement…</div>;
}
function TextViewer({ file, onError }: { file: PreviewFile; onError: (e?: unknown) => void }) {
const [prefs] = usePreviewPrefs();
const [state, setState] = useState<PreviewText | null>(null);
useEffect(() => {
let live = true;
file
.text()
.then((t) => live && setState(t))
.catch(() => live && onError());
.catch((e) => live && onError(e));
return () => {
live = false;
};
@@ -158,36 +181,38 @@ function TextViewer({ file, onError }: { file: PreviewFile; onError: () => void
<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)) {
// Extension inconnue reconnue comme texte par le serveur : langage deviné si la préférence le permet.
const mode = previewMode(file.name) ?? (state.detected && prefs.highlight && prefs.autoDetect ? "code" : "text");
switch (mode) {
case "code":
return (
<Suspense fallback={loading}>
<CodeViewer name={file.name} text={state.text} footer={footer} />
<CodeViewer name={file.name} text={state.text} prefs={prefs} detected={state.detected} footer={footer} />
</Suspense>
);
case "markdown":
return (
<Suspense fallback={loading}>
<MarkdownViewer text={state.text} footer={footer} />
<MarkdownViewer name={file.name} text={state.text} prefs={prefs} footer={footer} />
</Suspense>
);
case "csv":
return (
<Suspense fallback={loading}>
<CsvViewer name={file.name} text={state.text} truncated={state.truncated} footer={footer} />
<CsvViewer name={file.name} text={state.text} truncated={state.truncated} prefs={prefs} footer={footer} />
</Suspense>
);
default:
return <PlainViewer name={file.name} text={state.text} footer={footer} />;
return <PlainViewer name={file.name} text={state.text} numbered={prefs.lineNumbers} footer={footer} />;
}
}
/** Texte brut (.txt, .log...), lignes numérotées. */
function PlainViewer({ name, text, footer }: { name: string; text: string; footer: ReactNode }) {
function PlainViewer({ name, text, numbered, footer }: { name: string; text: string; numbered: boolean; footer: ReactNode }) {
const lines = text.split("\n");
return (
<div className="viewer-text">
<pre className={monospace(name) ? "mono" : ""}>
<pre className={[monospace(name) ? "mono" : "", numbered ? "" : "no-ln"].join(" ")}>
{lines.map((l, i) => (
<span key={i} className="ln" data-n={i + 1}>
{l || " "}
+159 -2
View File
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useState } from "react";
import type { ReactNode } from "react";
import { api, displayPath, type Account, type ApiToken, type Me, type Role, type Settings, type Share, type Status } from "./api";
import { CheckIcon, CloseIcon, CopyLinkIcon, KeyIcon, LockIcon, ShareIcon, ShieldIcon, TrashIcon, UserIcon, UsersIcon } from "./icons";
import { csvPageSizes, usePreviewPrefs } from "./prefs";
import { CheckIcon, CloseIcon, CopyLinkIcon, EyeIcon, KeyIcon, LockIcon, ShareIcon, ShieldIcon, TrashIcon, UserIcon, UsersIcon } from "./icons";
import { ConfirmDialog } from "./Dialogs";
import { fmtDate, fmtSize, plural } from "./format";
type Tab = "account" | "tokens" | "shares" | "general" | "users";
type Tab = "account" | "preview" | "tokens" | "shares" | "general" | "users";
interface Props {
me: Me;
@@ -39,6 +40,7 @@ export function SettingsDialog({ me, initialTab = "account", onClose, onChanged
const tabs: { id: Tab; label: string; icon: ReactNode; admin?: boolean; badge?: number }[] = [
{ id: "account", label: "Mon compte", icon: <UserIcon /> },
{ id: "preview", label: "Aperçu", icon: <EyeIcon /> },
{ id: "tokens", label: "Jetons d'API", icon: <KeyIcon /> },
{ id: "shares", label: "Partages", icon: <ShareIcon /> },
{ id: "general", label: "Général", icon: <ShieldIcon />, admin: true },
@@ -81,6 +83,7 @@ export function SettingsDialog({ me, initialTab = "account", onClose, onChanged
)}
<div className="settings-body">
{tab === "account" && <AccountTab me={me} onError={setError} onChanged={onChanged} />}
{tab === "preview" && <PreviewTab me={me} onError={setError} />}
{tab === "tokens" && <TokensTab onError={setError} />}
{tab === "shares" && <SharesTab me={me} onError={setError} />}
{tab === "general" && me.admin && <GeneralTab onError={setError} onChanged={onChanged} />}
@@ -378,6 +381,160 @@ function SharesTab({ me, onError }: { me: Me; onError: (m: string | null) => voi
);
}
// --- Aperçu : préférences du navigateur ; réglages serveur pour l'administrateur ---------------
const extList = (v: string) => v.split(/[\s,;]+/).filter(Boolean);
function PreviewTab({ me, onError }: { me: Me; onError: (m: string | null) => void }) {
const [prefs, setPrefs] = usePreviewPrefs();
const [st, setSt] = useState<Settings | null>(null);
const [maxMB, setMaxMB] = useState("2");
const [textExts, setTextExts] = useState("");
const [excl, setExcl] = useState("");
const [saved, setSaved] = useState<string | null>(null);
const sync = (s: Settings) => {
setSt(s);
setMaxMB(String(s.preview.maxTextMB));
setTextExts(s.preview.textExts.join(" "));
setExcl(s.preview.excludedExts.join(" "));
};
useEffect(() => {
if (me.admin)
api
.settings()
.then(sync)
.catch((e) => onError(msg(e)));
}, [me.admin, onError]);
const apply = async (preview: Partial<Settings["preview"]>) => {
onError(null);
setSaved(null);
try {
sync(await api.setSettings({ preview }));
setSaved("Enregistré.");
} catch (e) {
onError(msg(e));
}
};
const p = st?.preview;
return (
<div className="section">
{saved && (
<div className="notice">
<CheckIcon size={14} /> {saved}
</div>
)}
<h4>Affichage</h4>
<p className="muted small-text">Préférences enregistrées dans ce navigateur.</p>
<label className="check-row">
<input type="checkbox" checked={prefs.highlight} onChange={(e) => setPrefs({ highlight: e.target.checked })} />
<span>Coloration syntaxique du code</span>
</label>
<label className="check-row">
<input type="checkbox" checked={prefs.autoDetect} disabled={!prefs.highlight} onChange={(e) => setPrefs({ autoDetect: e.target.checked })} />
<span>Deviner le langage des fichiers texte sans extension connue (.pem, fichiers sans extension…)</span>
</label>
<label className="check-row">
<input type="checkbox" checked={prefs.lineNumbers} onChange={(e) => setPrefs({ lineNumbers: e.target.checked })} />
<span>Numéros de ligne</span>
</label>
<label className="check-row">
<input type="checkbox" checked={prefs.wrap} onChange={(e) => setPrefs({ wrap: e.target.checked })} />
<span>Retour à la ligne automatique dans le code</span>
</label>
<label className="field">
<span>Fichiers Markdown</span>
<select value={prefs.markdown} onChange={(e) => setPrefs({ markdown: e.target.value as "rendered" | "source" })}>
<option value="rendered">Rendu mis en forme</option>
<option value="source">Source colorisée</option>
</select>
</label>
<label className="field">
<span>Fichiers CSV : lignes par page</span>
<select value={prefs.csvPageSize} onChange={(e) => setPrefs({ csvPageSize: Number(e.target.value) })}>
{csvPageSizes.map((n) => (
<option key={n} value={n}>
{n}
</option>
))}
</select>
</label>
<label className="check-row">
<input type="checkbox" checked={prefs.csvHeader} onChange={(e) => setPrefs({ csvHeader: e.target.checked })} />
<span>CSV : première ligne affichée comme en-tête</span>
</label>
{me.admin && (
<>
<h4>Pour tous les utilisateurs</h4>
{!p ? (
<p className="muted">Chargement…</p>
) : (
<>
<label className="check-row">
<input type="checkbox" checked={p.sniff} onChange={(e) => apply({ sniff: e.target.checked })} />
<span>Détection automatique : afficher un fichier d'extension inconnue si son contenu est du texte lisible</span>
</label>
<label className="check-row">
<input type="checkbox" checked={p.shares} onChange={(e) => apply({ shares: e.target.checked })} />
<span>Aperçu du texte et des PDF dans les liens de partage</span>
</label>
<form
className="inline-form"
onSubmit={(e) => {
e.preventDefault();
apply({ maxTextMB: Math.floor(Number(maxMB) || 0) });
}}
>
<label className="field grow">
<span>Taille maximale du texte affiché (Mo, 1 à 50 ; au-delà, seul le début est affiché)</span>
<input type="number" min={1} max={50} value={maxMB} onChange={(e) => setMaxMB(e.target.value)} />
</label>
<button type="submit" disabled={Number(maxMB) === p.maxTextMB}>
Enregistrer
</button>
</form>
<form
className="inline-form"
onSubmit={(e) => {
e.preventDefault();
apply({ textExts: extList(textExts) });
}}
>
<label className="field grow">
<span>Extensions toujours affichées en texte, sans détection (ex. : pem crt csr)</span>
<input value={textExts} placeholder="pem crt csr" onChange={(e) => setTextExts(e.target.value)} />
</label>
<button type="submit" disabled={extList(textExts).join(" ") === p.textExts.join(" ")}>
Enregistrer
</button>
</form>
<form
className="inline-form"
onSubmit={(e) => {
e.preventDefault();
apply({ excludedExts: extList(excl) });
}}
>
<label className="field grow">
<span>Extensions jamais prévisualisées (ex. : key env)</span>
<input value={excl} placeholder="key env" onChange={(e) => setExcl(e.target.value)} />
</label>
<button type="submit" disabled={extList(excl).join(" ") === p.excludedExts.join(" ")}>
Enregistrer
</button>
</form>
<p className="muted small-text">RTF, DOC et DOCX ne sont jamais prévisualisés. Les images, vidéos et sons ne sont pas concernés par ces réglages.</p>
</>
)}
</>
)}
</div>
);
}
// --- Général (administrateur) ------------------------------------------------------------
function GeneralTab({ onError, onChanged }: { onError: (m: string | null) => void; onChanged: () => void }) {
+29 -3
View File
@@ -77,6 +77,18 @@ export interface Settings {
registration: Registration;
quotaMB: number;
commonReadonly: boolean;
preview: PreviewSettings;
}
/** Réglages de l'aperçu (administrateur) ; extensions sans point, en minuscules. */
export interface PreviewSettings {
/** Fichiers hors liste reconnus comme texte d'après leur contenu. */
sniff: boolean;
maxTextMB: number;
textExts: string[];
excludedExts: string[];
/** Aperçu texte et PDF dans les liens de partage. */
shares: boolean;
}
/** Version enregistrée d'un fichier (time : date de ce contenu). */
@@ -202,15 +214,27 @@ async function request(url: string, init?: RequestInit): Promise<Response> {
const q = (p: string) => encodeURIComponent(p);
/** Texte renvoyé par /api/preview : truncated si le fichier dépasse le plafond du serveur. */
/** Texte renvoyé par /api/preview : truncated si le fichier dépasse le plafond du serveur ;
* detected si le serveur l'a reconnu comme texte d'après son contenu (extension hors liste). */
export interface PreviewText {
text: string;
truncated: boolean;
detected: 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 h = (k: string) => res.headers.get(k) === "1";
return { text: await res.text(), truncated: h("X-Preview-Truncated"), detected: h("X-Preview-Detected") };
}
/** Le serveur accepte-t-il l'aperçu (PDF : avant de l'afficher dans une iframe) ? */
export async function previewAllowed(url: string): Promise<boolean> {
try {
return (await fetch(url, { method: "HEAD" })).ok;
} catch {
return false;
}
}
const json = (body: unknown, method = "POST"): RequestInit => ({
method,
@@ -390,7 +414,9 @@ export const api = {
settings: async (): Promise<Settings> => (await request("/api/settings")).json(),
setSettings: async (v: Partial<Pick<Settings, "title" | "trashDays" | "registration" | "quotaMB" | "commonReadonly">>): Promise<Settings> =>
setSettings: async (
v: Partial<Pick<Settings, "title" | "trashDays" | "registration" | "quotaMB" | "commonReadonly">> & { preview?: Partial<PreviewSettings> },
): Promise<Settings> =>
(await request("/api/settings", json(v, "PUT"))).json(),
/** Le serveur recadre au centre et ramène le PNG à 64x64. */
+5 -1
View File
@@ -78,7 +78,8 @@ export const browserImage = (name: string) => ["png", "jpg", "jpeg", "gif", "web
const browserVideo = ["mp4", "webm", "mov", "m4v", "ogv"];
const browserAudio = ["mp3", "ogg", "oga", "wav", "flac", "aac", "m4a", "opus"];
/** Aperçu intégré possible ? (texte limité aux premiers Mo, vidéo et audio selon le navigateur). */
/** Aperçu intégré possible ? (texte limité aux premiers Mo, vidéo et audio selon le navigateur ;
* extension inconnue : tentative, le serveur décide d'après le contenu et ses réglages). */
export const previewable = (name: string): boolean => {
const k = kindOf(name);
const e = extOf(name);
@@ -93,6 +94,9 @@ export const previewable = (name: string): boolean => {
case "text":
case "code":
return previewMode(name) !== null;
case "other":
// Extension inconnue ou absente : le serveur reconnaît le texte d'après le contenu.
return true;
default:
return false;
}
+64
View File
@@ -0,0 +1,64 @@
// Préférences d'affichage de l'aperçu, propres à chaque navigateur (localStorage).
import { useCallback, useState } from "react";
export interface PreviewPrefs {
/** Coloration syntaxique du code. */
highlight: boolean;
/** Langage deviné pour un fichier texte reconnu d'après son contenu (.pem, sans extension...). */
autoDetect: boolean;
/** Retour à la ligne automatique dans le code. */
wrap: boolean;
lineNumbers: boolean;
/** Markdown : rendu mis en forme ou source colorisée. */
markdown: "rendered" | "source";
csvPageSize: number;
/** CSV : première ligne affichée comme en-tête. */
csvHeader: boolean;
}
export const defaultPrefs: PreviewPrefs = {
highlight: true,
autoDetect: true,
wrap: false,
lineNumbers: true,
markdown: "rendered",
csvPageSize: 100,
csvHeader: true,
};
export const csvPageSizes = [50, 100, 250, 500];
const KEY = "udPreview";
export function loadPrefs(): PreviewPrefs {
try {
const v = JSON.parse(localStorage.getItem(KEY) ?? "{}");
const p = { ...defaultPrefs, ...(v && typeof v === "object" ? v : {}) };
if (!csvPageSizes.includes(p.csvPageSize)) p.csvPageSize = defaultPrefs.csvPageSize;
if (p.markdown !== "source") p.markdown = "rendered";
return p;
} catch {
return { ...defaultPrefs };
}
}
function savePrefs(p: PreviewPrefs) {
try {
localStorage.setItem(KEY, JSON.stringify(p));
} catch {
/* stockage indisponible : préférences pour cette session seulement */
}
}
/** Préférences et modificateur (enregistrement immédiat). */
export function usePreviewPrefs(): [PreviewPrefs, (patch: Partial<PreviewPrefs>) => void] {
const [prefs, setPrefs] = useState(loadPrefs);
const update = useCallback((patch: Partial<PreviewPrefs>) => {
setPrefs((p) => {
const n = { ...p, ...patch };
savePrefs(n);
return n;
});
}, []);
return [prefs, update];
}
+32 -12
View File
@@ -2026,11 +2026,6 @@ th.c-size .th-btn {
--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;
@@ -2038,21 +2033,46 @@ th.c-size .th-btn {
font-size: 13px;
line-height: 1.5;
white-space: pre;
min-width: max-content;
}
.viewer-code .code-gutter {
position: sticky;
.viewer-code .cl {
padding: 0 1rem;
min-height: 1.5em;
}
.viewer-code.numbered .cl {
position: relative;
padding-left: 4.8rem;
}
.viewer-code.numbered .cl::before {
content: attr(data-n);
position: absolute;
left: 0;
padding: 1rem 0.8rem 1rem 0.6rem;
min-width: 3.6rem;
width: 3.4rem;
padding-right: 0.6rem;
text-align: right;
color: var(--muted);
background: var(--panel);
border-right: 1px solid var(--border);
user-select: none;
}
.viewer-code .code-body {
.viewer-code.wrap pre {
white-space: pre-wrap;
word-break: break-word;
min-width: 0;
}
.viewer-code .code-bar {
position: sticky;
top: 0;
left: 0;
padding: 0.4rem 1rem;
font-size: 12px;
background: var(--panel-2);
border-bottom: 1px solid var(--border);
}
.viewer-text pre.no-ln .ln {
padding-left: 1rem;
padding-right: 1rem;
}
.viewer-text pre.no-ln .ln::before {
content: none;
}
.hljs-comment,
.hljs-quote {
+90 -23
View File
@@ -36,11 +36,13 @@ 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 markdown from "highlight.js/lib/languages/markdown";
import { codeLanguage } from "./filetypes";
import type { PreviewPrefs } from "./prefs";
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,
makefile, markdown, 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...).
@@ -65,26 +67,89 @@ function highlight(text: string, lang: string | null): string | null {
}
}
/** Langages essayés pour un fichier reconnu comme texte d'après son contenu. */
const autoSubset = ["json", "yaml", "xml", "bash", "ini", "properties", "dockerfile", "makefile", "sql", "python", "go", "javascript", "typescript", "css", "diff", "markdown"];
/** Pertinence minimale pour retenir un langage deviné (sinon texte brut). */
const MIN_RELEVANCE = 6;
function autoHighlight(text: string): { html: string; lang: string } | null {
// Certificats, clés, CSR (PEM) et blocs PGP : base64, aucun langage à deviner.
if (text.length > MAX_HIGHLIGHT || /^\s*-----BEGIN [A-Z0-9 ]+-----/.test(text)) return null;
try {
const r = hljs.highlightAuto(text, autoSubset);
return r.language && r.relevance >= MIN_RELEVANCE ? { html: r.value, lang: r.language } : null;
} catch {
return null;
}
}
/** Découpe le HTML de highlight.js en lignes : les <span> ouverts sont refermés
* en fin de ligne et rouverts au début de la suivante. */
function splitLines(html: string): string[] {
const lines: string[] = [];
const open: string[] = [];
let cur = "";
const re = /(<span[^>]*>)|(<\/span>)|(\n)|([^<\n]+)/g;
for (let m; (m = re.exec(html)); ) {
if (m[1]) {
open.push(m[1]);
cur += m[1];
} else if (m[2]) {
open.pop();
cur += m[2];
} else if (m[3]) {
lines.push(cur + "</span>".repeat(open.length));
cur = open.join("");
} else cur += m[4];
}
lines.push(cur + "</span>".repeat(open.length));
return lines;
}
const escapeHtml = (t: string) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
interface CodeProps {
name: string;
text: string;
prefs: PreviewPrefs;
/** Texte reconnu d'après son contenu : langage deviné si autorisé. */
detected?: boolean;
/** Langage imposé (source Markdown). */
language?: string;
footer?: ReactNode;
}
/** 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]);
export function CodeViewer({ name, text, prefs, detected, language, footer }: CodeProps) {
const lang = language ?? codeLanguage(name);
const result = useMemo(() => {
if (!prefs.highlight) return null;
if (lang) {
const html = highlight(text, lang);
return html === null ? null : { html, lang, guessed: false };
}
if (detected && prefs.autoDetect) {
const r = autoHighlight(text);
return r && { ...r, guessed: true };
}
return null;
}, [text, lang, detected, prefs.highlight, prefs.autoDetect]);
// 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]);
const lines = useMemo(() => {
const l = result ? splitLines(result.html) : escapeHtml(text).split("\n");
if (text.endsWith("\n") && l.length > 1) l.pop();
return l;
}, [result, text]);
const cls = ["viewer-text", "viewer-code", prefs.wrap ? "wrap" : "", prefs.lineNumbers ? "numbered" : ""].join(" ");
return (
<div className="viewer-text viewer-code">
<div className="code-grid">
<pre className="code-gutter" aria-hidden>
{gutter}
<div className={cls}>
{result?.guessed && <div className="code-bar muted">Langage détecté : {result.lang}</div>}
<pre className={`code-body mono ${result ? "hljs" : ""}`}>
{lines.map((l, i) => (
<div key={i} className="cl" data-n={i + 1} dangerouslySetInnerHTML={{ __html: l || " " }} />
))}
</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>}
{prefs.highlight && lang && result === null && text.length > MAX_HIGHLIGHT && <div className="notice">Fichier volumineux : affiché sans coloration.</div>}
{footer}
</div>
);
@@ -114,11 +179,14 @@ const mdComponents: Components = {
},
};
export function MarkdownViewer({ text, footer }: { text: string; footer?: ReactNode }) {
const mdPlain: Components = { a: mdComponents.a, img: mdComponents.img };
export function MarkdownViewer({ name, text, prefs, footer }: { name: string; text: string; prefs: PreviewPrefs; footer?: ReactNode }) {
if (prefs.markdown === "source") return <CodeViewer name={name} text={text} prefs={prefs} language="markdown" footer={footer} />;
return (
<div className="viewer-text viewer-md">
<article className="md">
<Markdown remarkPlugins={[remarkGfm]} skipHtml components={mdComponents}>
<Markdown remarkPlugins={[remarkGfm]} skipHtml components={prefs.highlight ? mdComponents : mdPlain}>
{text}
</Markdown>
</article>
@@ -127,12 +195,11 @@ export function MarkdownViewer({ text, footer }: { text: string; footer?: ReactN
);
}
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 }) {
export function CsvViewer({ name, text, truncated, prefs, footer }: { name: string; text: string; truncated: boolean; prefs: PreviewPrefs; footer?: ReactNode }) {
const PAGE = prefs.csvPageSize;
const [page, setPage] = useState(0);
const [header, setHeader] = useState(true);
const [header, setHeader] = useState(prefs.csvHeader);
const parsed = useMemo(() => {
const r = Papa.parse<string[]>(text, {
skipEmptyLines: "greedy",
+1 -4
View File
@@ -65,7 +65,7 @@ type Handler struct {
Accounts *auth.Accounts // nil : pas de comptes (AUTH_MODE=none)
MaxJSON int64 // taille maximale d'un corps JSON (octets)
// PreviewMaxText : octets de texte servis au plus par /api/preview.
// PreviewMaxText : si > 0, remplace le plafond de texte des paramètres (tests).
PreviewMaxText int64
Mode string // none, local, oidc ou both
OIDCName string // libellé du bouton de connexion OIDC
@@ -86,9 +86,6 @@ func (h *Handler) Init() *Handler {
if h.MaxJSON == 0 {
h.MaxJSON = 1 << 20
}
if h.PreviewMaxText == 0 {
h.PreviewMaxText = DefaultPreviewMaxText
}
h.unlocks = auth.NewLimiter(10, 15*time.Minute)
return h
}
+5
View File
@@ -102,6 +102,8 @@ type settingsReq struct {
Registration *string `json:"registration"`
QuotaMB *int64 `json:"quotaMB"`
CommonReadonly *bool `json:"commonReadonly"`
Preview *storage.PreviewPatch `json:"preview"`
}
func (h *Handler) writeSettings(w http.ResponseWriter, r *http.Request) {
@@ -125,6 +127,9 @@ func (h *Handler) writeSettings(w http.ResponseWriter, r *http.Request) {
if err == nil && req.CommonReadonly != nil {
st, err = h.Store.WriteCommonReadonly(*req.CommonReadonly)
}
if err == nil && req.Preview != nil {
st, err = h.Store.WritePreview(*req.Preview)
}
if err == nil && req.TrashDays != nil {
if st, err = h.Store.WriteTrashDays(*req.TrashDays); err == nil {
if perr := h.Spaces.PurgeTrash(); perr != nil {
+123 -15
View File
@@ -23,10 +23,20 @@ import (
// 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é.
// plafonné (2 Mo par défaut, réglable) ; au-delà, seul le début est envoyé.
//
// Hors liste blanche, le contenu est reniflé (sniffText) : un fichier lisible
// en texte (.pem, .csr, .crt, fichier sans extension...) est servi en
// text/plain avec les mêmes protections, genre "text" et X-Preview-Detected: 1.
// Les formats exclus (excludedExts) ne sont jamais reniflés.
//
// Réglages de l'administrateur (storage.PreviewSettings) : reniflage actif ou
// non, plafond du texte, extensions toujours en texte, extensions exclues,
// aperçu dans les liens de partage.
//
// 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é).
// X-Preview-Size (taille réelle du fichier), X-Preview-Truncated (1 si coupé),
// X-Preview-Detected (1 si le genre vient du reniflage du contenu).
// Genres d'aperçu.
const (
@@ -37,9 +47,6 @@ const (
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,
@@ -65,7 +72,12 @@ func init() {
}
}
// PreviewKind renvoie le genre d'aperçu d'un fichier ("" : non prévisualisable).
// excludedExts : formats texte ou binaires exclus de l'aperçu, même reniflés
// (RTF/DOC/DOCX hors périmètre ; SVG servi par /api/file).
var excludedExts = map[string]bool{".rtf": true, ".doc": true, ".docx": true, ".svg": true}
// PreviewKind renvoie le genre d'aperçu d'un fichier d'après son nom ("" :
// hors liste blanche, à renifler sauf extension exclue).
func PreviewKind(name string) string {
base := strings.ToLower(path.Base(name))
if k, ok := previewNames[base]; ok {
@@ -101,8 +113,12 @@ func (h *Handler) preview(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
cfg, ok := h.previewSettings(w)
if !ok {
return
}
p := r.URL.Query().Get("path")
if PreviewKind(p) == "" {
if cfg.excluded(p) {
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
return
}
@@ -112,7 +128,7 @@ func (h *Handler) preview(w http.ResponseWriter, r *http.Request) {
return
}
defer f.Close()
h.servePreview(w, r, f, fi)
h.servePreview(w, r, f, fi, cfg)
}
func (h *Handler) publicPreview(w http.ResponseWriter, r *http.Request) {
@@ -120,22 +136,90 @@ func (h *Handler) publicPreview(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
cfg, ok := h.previewSettings(w)
if !ok {
return
}
if !cfg.Shares {
writeErr(w, http.StatusForbidden, "aperçu désactivé pour les liens de partage")
return
}
f, fi, err := st.Open(full)
if err != nil {
fail(w, err)
return
}
defer f.Close()
h.servePreview(w, r, f, fi)
h.servePreview(w, r, f, fi, cfg)
}
func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.File, fi fs.FileInfo) {
// previewConfig : réglages de l'aperçu (paramètres de l'administrateur).
type previewConfig struct {
storage.PreviewSettings
text, excl map[string]bool // extensions avec le point, en minuscules
}
func (h *Handler) previewSettings(w http.ResponseWriter) (previewConfig, bool) {
st, err := h.Store.ReadSettings()
if err != nil {
fail(w, err)
return previewConfig{}, false
}
c := previewConfig{PreviewSettings: st.Preview, text: map[string]bool{}, excl: map[string]bool{}}
for _, e := range st.Preview.TextExts {
c.text["."+e] = true
}
for _, e := range st.Preview.ExcludedExts {
c.excl["."+e] = true
}
return c, true
}
// excluded : extension exclue d'office (RTF, DOC...) ou par l'administrateur.
func (c previewConfig) excluded(name string) bool {
e := strings.ToLower(path.Ext(name))
return excludedExts[e] || c.excl[e]
}
// kind : genre d'après le nom (liste blanche, puis extensions texte de l'administrateur).
func (c previewConfig) kind(name string) string {
if k := PreviewKind(name); k != "" {
return k
}
if c.text[strings.ToLower(path.Ext(name))] {
return PreviewText
}
return ""
}
func (c previewConfig) maxText() int64 {
if c.MaxTextMB < 1 {
return int64(storage.DefaultPreview.MaxTextMB) << 20
}
return int64(c.MaxTextMB) << 20
}
func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.File, fi fs.FileInfo, cfg previewConfig) {
name := fi.Name()
kind := PreviewKind(name)
if kind == "" || fi.IsDir() {
kind := cfg.kind(name)
if fi.IsDir() || cfg.excluded(name) || (kind == "" && !cfg.Sniff) {
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
return
}
detected := false
if kind == "" {
head := make([]byte, sniffLen)
n, _ := io.ReadFull(f, head)
if !sniffText(head[:n], int64(n) < fi.Size()) {
writeErr(w, http.StatusUnsupportedMediaType, "pas d'aperçu pour ce type de fichier")
return
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
fail(w, err)
return
}
kind, detected = PreviewText, true
}
hd := w.Header()
hd.Set("Content-Type", previewType[kind])
hd.Set("Content-Disposition", contentDisposition(true, name))
@@ -144,6 +228,7 @@ func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.Fil
hd.Set("ETag", storage.ETag(fi))
hd.Set("X-Preview-Kind", kind)
hd.Set("X-Preview-Size", strconv.FormatInt(fi.Size(), 10))
hd.Set("X-Preview-Detected", map[bool]string{true: "1", false: "0"}[detected])
if kind == PreviewPDF {
hd.Set("Content-Security-Policy", cspPreviewPDF)
@@ -153,9 +238,9 @@ func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.Fil
}
hd.Set("Content-Security-Policy", cspPreviewText)
max := h.PreviewMaxText
if max <= 0 {
max = DefaultPreviewMaxText
max := cfg.maxText()
if h.PreviewMaxText > 0 { // tests
max = h.PreviewMaxText
}
b, err := io.ReadAll(io.LimitReader(f, max))
if err != nil {
@@ -178,6 +263,29 @@ func (h *Handler) servePreview(w http.ResponseWriter, r *http.Request, f *os.Fil
http.ServeContent(w, r, name, fi.ModTime(), bytes.NewReader(b))
}
// sniffLen : octets examinés pour reconnaître un fichier texte.
const sniffLen = 8192
// sniffText indique si un début de fichier est du texte lisible : UTF-8 valide
// (un caractère coupé en fin d'échantillon est toléré si partial), aucun octet
// NUL, et au plus 1 % de caractères de contrôle hors \t \n \r \f et ESC.
// Un fichier vide est du texte.
func sniffText(b []byte, partial bool) bool {
if partial {
b = trimPartialRune(b)
}
if !utf8.Valid(b) || bytes.IndexByte(b, 0) >= 0 {
return false
}
ctrl := 0
for _, c := range b {
if (c < 0x20 && c != '\t' && c != '\n' && c != '\r' && c != '\f' && c != 0x1b) || c == 0x7f {
ctrl++
}
}
return ctrl*100 <= len(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++ {
+121 -1
View File
@@ -88,7 +88,7 @@ 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)
want(t, s.put("dir/b.zip", "PK\x03\x04\x00\x00"), 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")
@@ -99,3 +99,123 @@ func TestPublicPreview(t *testing.T) {
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)
}
func TestPreviewSniffUnknownExtensions(t *testing.T) {
f := newFixture(t, nil)
s := f.register("alice")
pem := "-----BEGIN CERTIFICATE-----\nMIIBszCCAVmgAwIBAgIUQ==\n-----END CERTIFICATE-----\n"
want(t, s.put("certs/server.pem", pem), 200)
want(t, s.put("certs/hosts", "127.0.0.1 localhost\n"), 200)
want(t, s.put("certs/vide.cfgx", ""), 200)
want(t, s.put("bin/blob.bin", "\x7fELF\x02\x01\x01\x00\x00"), 200)
want(t, s.put("bin/latin1.dat", "caf\xe9 cr\xe8me"), 200)
want(t, s.put("bin/ctrl.dat", strings.Repeat("ab\x01\x02", 50)), 200)
want(t, s.put("doc/lettre.rtf", `{\rtf1\ansi Bonjour}`), 200)
for p, body := range map[string]string{"certs/server.pem": pem, "certs/hosts": "127.0.0.1 localhost\n", "certs/vide.cfgx": ""} {
w := s.get("/api/preview?path=" + p)
want(t, w, 200)
h := w.Header()
if w.Body.String() != body || h.Get("Content-Type") != "text/plain; charset=utf-8" || h.Get("X-Preview-Kind") != PreviewText ||
h.Get("X-Preview-Detected") != "1" || !strings.HasPrefix(h.Get("Content-Security-Policy"), "sandbox") || h.Get("X-Content-Type-Options") != "nosniff" {
t.Errorf("%s : %q %v", p, w.Body, h)
}
}
// Liste blanche : pas de reniflage.
if w := s.get("/api/preview?path=certs/../certs/server.pem"); w.Header().Get("X-Preview-Detected") != "1" {
t.Errorf("chemin normalisé : %v", w.Header())
}
want(t, s.put("a.json", "{}"), 200)
if w := s.get("/api/preview?path=a.json"); w.Header().Get("X-Preview-Detected") != "0" {
t.Errorf("liste blanche : %v", w.Header())
}
for _, p := range []string{"bin/blob.bin", "bin/latin1.dat", "bin/ctrl.dat", "doc/lettre.rtf"} {
want(t, s.get("/api/preview?path="+p), 415)
}
// Reniflage aussi via un lien de partage.
sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "certs", "days": 1}))
w := f.session().get("/api/public/" + sh.Token + "/preview?sub=server.pem")
want(t, w, 200)
if w.Body.String() != pem {
t.Errorf("public : %q", w.Body)
}
}
func TestSniffText(t *testing.T) {
long := strings.Repeat("é", 4096) // 8192 octets
for name, c := range map[string]struct {
b string
partial bool
ok bool
}{
"ascii": {"hello\n", false, true},
"utf8": {"café ☕", false, true},
"coupé toléré": {long[:8191], true, true},
"coupé final": {long[:8191], false, false},
"nul": {"a\x00b", false, false},
"esc couleurs": {"\x1b[31mrouge\x1b[0m\n", false, true},
"trop de ctrl": {"\x01\x02\x03abc", false, false},
"vide": {"", false, true},
} {
if got := sniffText([]byte(c.b), c.partial); got != c.ok {
t.Errorf("%s : %v, attendu %v", name, got, c.ok)
}
}
}
func TestPreviewSettings(t *testing.T) {
f := newFixture(t, nil)
admin := f.register("alice")
want(t, admin.put("k/server.pem", "-----BEGIN CERTIFICATE-----\n"), 200)
want(t, admin.put("k/notes.mylog", "ligne\n"), 200)
want(t, admin.put("k/app.log", "log\n"), 200)
want(t, admin.put("k/gros.txt", strings.Repeat("a", 3<<20)), 200)
st := decode[storage.Settings](t, admin.get("/api/settings"))
if p := st.Preview; !p.Sniff || p.MaxTextMB != 2 || !p.Shares || len(p.TextExts) != 0 || len(p.ExcludedExts) != 0 {
t.Fatalf("défauts : %+v", p)
}
if w := admin.get("/api/preview?path=k/gros.txt"); w.Body.Len() != 2<<20 || w.Header().Get("X-Preview-Truncated") != "1" {
t.Errorf("plafond 2 Mo : %d", w.Body.Len())
}
// Validation.
want(t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"maxTextMB": 0}}), 400)
want(t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"maxTextMB": 51}}), 400)
want(t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"textExts": []string{"a/b"}}}), 400)
st = decode[storage.Settings](t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{
"sniff": false, "maxTextMB": 3, "textExts": []string{".MyLog", "mylog", " pem "}, "excludedExts": []string{"log"}, "shares": false,
}}))
if p := st.Preview; p.Sniff || p.MaxTextMB != 3 || p.Shares || strings.Join(p.TextExts, ",") != "mylog,pem" || strings.Join(p.ExcludedExts, ",") != "log" {
t.Fatalf("réglages : %+v", p)
}
// Un patch partiel ne touche pas aux autres champs.
st = decode[storage.Settings](t, admin.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"maxTextMB": 4}}))
if p := st.Preview; p.MaxTextMB != 4 || p.Sniff || strings.Join(p.TextExts, ",") != "mylog,pem" {
t.Fatalf("patch partiel : %+v", p)
}
w := admin.get("/api/preview?path=k/notes.mylog") // extension texte de l'administrateur
want(t, w, 200)
if w.Header().Get("X-Preview-Detected") != "0" || w.Header().Get("X-Preview-Kind") != PreviewText {
t.Errorf("textExts : %v", w.Header())
}
want(t, admin.get("/api/preview?path=k/app.log"), 415) // exclue
if w := admin.get("/api/preview?path=k/gros.txt"); w.Body.Len() != 3<<20 || w.Header().Get("X-Preview-Truncated") != "0" {
t.Errorf("plafond 4 Mo : %d", w.Body.Len())
}
// Reniflage désactivé : extension inconnue refusée.
want(t, admin.put("k/hosts", "127.0.0.1 localhost\n"), 200)
want(t, admin.get("/api/preview?path=k/hosts"), 415)
// Aperçu désactivé dans les partages.
sh := decode[storage.Share](t, admin.json("POST", "/api/shares", map[string]any{"path": "k", "days": 1}))
want(t, f.session().get("/api/public/"+sh.Token+"/preview?sub=server.pem"), 403)
// Réservé aux administrateurs.
want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "open"}), 200)
bob := f.register("bob")
want(t, bob.json("PUT", "/api/settings", map[string]any{"preview": map[string]any{"sniff": true}}), 403)
}
+128
View File
@@ -73,9 +73,55 @@ type Settings struct {
Registration string `json:"registration"`
QuotaMB int64 `json:"quotaMB"`
CommonReadonly bool `json:"commonReadonly"`
Preview PreviewSettings `json:"preview"`
}
// PreviewSettings : réglages de l'aperçu des fichiers (/api/preview).
type PreviewSettings struct {
// Sniff : un fichier hors liste blanche est prévisualisé si son contenu est
// du texte lisible (.pem, .csr, fichiers sans extension...).
Sniff bool `json:"sniff"`
// MaxTextMB : plafond du texte servi (au-delà, seul le début est affiché).
MaxTextMB int `json:"maxTextMB"`
// TextExts : extensions toujours affichées en texte, sans reniflage.
TextExts []string `json:"textExts"`
// ExcludedExts : extensions jamais prévisualisées.
ExcludedExts []string `json:"excludedExts"`
// Shares : aperçu texte et PDF dans les liens de partage.
Shares bool `json:"shares"`
}
// Bornes des réglages de l'aperçu.
const (
MaxPreviewTextMB = 50
maxPreviewExts = 100
maxPreviewExtLen = 16
)
// DefaultPreview : reniflage actif, 2 Mo de texte, aperçu dans les partages.
var DefaultPreview = PreviewSettings{Sniff: true, MaxTextMB: 2, TextExts: []string{}, ExcludedExts: []string{}, Shares: true}
// previewDisk : champs absents = valeur par défaut.
type previewDisk struct {
Sniff *bool `json:"sniff,omitempty"`
MaxTextMB *int `json:"maxTextMB,omitempty"`
TextExts []string `json:"textExts,omitempty"`
ExcludedExts []string `json:"excludedExts,omitempty"`
Shares *bool `json:"shares,omitempty"`
}
// PreviewPatch : seuls les champs non nil sont modifiés.
type PreviewPatch struct {
Sniff *bool `json:"sniff"`
MaxTextMB *int `json:"maxTextMB"`
TextExts *[]string `json:"textExts"`
ExcludedExts *[]string `json:"excludedExts"`
Shares *bool `json:"shares"`
}
type settingsDisk struct {
Preview *previewDisk `json:"preview,omitempty"`
Title string `json:"title"`
TrashDays *int `json:"trashDays,omitempty"`
Registration *string `json:"registration,omitempty"`
@@ -148,6 +194,24 @@ func (s *Store) readSettings() (Settings, error) {
if d.CommonReadonly != nil {
st.CommonReadonly = *d.CommonReadonly
}
st.Preview = DefaultPreview
if p := d.Preview; p != nil {
if p.Sniff != nil {
st.Preview.Sniff = *p.Sniff
}
if p.MaxTextMB != nil && *p.MaxTextMB >= 1 && *p.MaxTextMB <= MaxPreviewTextMB {
st.Preview.MaxTextMB = *p.MaxTextMB
}
if p.TextExts != nil {
st.Preview.TextExts = p.TextExts
}
if p.ExcludedExts != nil {
st.Preview.ExcludedExts = p.ExcludedExts
}
if p.Shares != nil {
st.Preview.Shares = *p.Shares
}
}
if fi, err := os.Stat(filepath.Join(s.root, logoFile)); err == nil {
st.Logo = strconv.FormatInt(fi.ModTime().UnixNano(), 36)
}
@@ -183,6 +247,70 @@ func (s *Store) WriteCommonReadonly(ro bool) (Settings, error) {
return s.updateSettings(func(d *settingsDisk) { d.CommonReadonly = &ro })
}
// WritePreview modifie les réglages de l'aperçu (champs non nil seulement).
// Les extensions sont normalisées : minuscules, sans point, [a-z0-9_+-].
func (s *Store) WritePreview(p PreviewPatch) (Settings, error) {
if p.MaxTextMB != nil && (*p.MaxTextMB < 1 || *p.MaxTextMB > MaxPreviewTextMB) {
return Settings{}, fmt.Errorf("%w : plafond de 1 à %d Mo", ErrInvalidPath, MaxPreviewTextMB)
}
var text, excl []string
var err error
if p.TextExts != nil {
if text, err = NormalizeExts(*p.TextExts); err != nil {
return Settings{}, err
}
}
if p.ExcludedExts != nil {
if excl, err = NormalizeExts(*p.ExcludedExts); err != nil {
return Settings{}, err
}
}
return s.updateSettings(func(d *settingsDisk) {
if d.Preview == nil {
d.Preview = &previewDisk{}
}
if p.Sniff != nil {
d.Preview.Sniff = p.Sniff
}
if p.MaxTextMB != nil {
d.Preview.MaxTextMB = p.MaxTextMB
}
if p.TextExts != nil {
d.Preview.TextExts = text
}
if p.ExcludedExts != nil {
d.Preview.ExcludedExts = excl
}
if p.Shares != nil {
d.Preview.Shares = p.Shares
}
})
}
// NormalizeExts nettoie une liste d'extensions (« .PEM », « crt »...) : minuscules,
// sans point, sans doublon ; refuse les caractères hors [a-z0-9_+-].
func NormalizeExts(in []string) ([]string, error) {
out := []string{}
seen := map[string]bool{}
for _, e := range in {
e = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(e)), ".")
if e == "" || seen[e] {
continue
}
if len(e) > maxPreviewExtLen || strings.IndexFunc(e, func(r rune) bool {
return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' || r == '+' || r == '-')
}) >= 0 {
return nil, fmt.Errorf("%w : extension %q", ErrInvalidPath, e)
}
seen[e] = true
out = append(out, e)
}
if len(out) > maxPreviewExts {
return nil, fmt.Errorf("%w : %d extensions au plus", ErrInvalidPath, maxPreviewExts)
}
return out, nil
}
// WriteTitle enregistre le titre affiché ("" = titre par défaut).
func (s *Store) WriteTitle(title string) (Settings, error) {
title = strings.TrimSpace(title)