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