VYBECODEDDDDDDDDD

This commit is contained in:
Anaïs Saraiva
2026-08-15 00:20:45 +02:00
parent 1a2c8aaf7c
commit 5f201cf725
23 changed files with 2263 additions and 2 deletions
+66
View File
@@ -0,0 +1,66 @@
import { json, jsonError } from "../http";
import { log } from "../log";
import { getBoundary, MultipartError, multipartParts } from "../multipart";
import { hashSecret, newDownloadKey, newFileId, sanitizeMime, sanitizeOriginalName } from "../security";
import { UploadTooLargeError, type Storage } from "../storage";
export async function handleUpload(
req: Request,
storage: Storage,
maxFileSize: number,
): Promise<Response> {
const contentType = req.headers.get("content-type");
const boundary = contentType ? getBoundary(contentType) : null;
if (!boundary || !req.body) return jsonError(400, "expected a multipart/form-data upload");
const id = newFileId();
const key = id + newDownloadKey();
try {
let filename = "";
let mime = "application/octet-stream";
let size = 0;
let hasFile = false;
for await (const part of multipartParts(req.body, boundary)) {
if (!hasFile) {
hasFile = true;
filename = part.filename;
mime = sanitizeMime(part.contentType);
size = await storage.saveFile(id, part.chunks, maxFileSize);
break;
}
for await (const _ of part.chunks) {
void _;
}
}
if (!hasFile) return jsonError(400, "no file part in the upload");
const originalName = sanitizeOriginalName(filename);
await storage.writeMetadata({
id,
originalName,
size,
mimeType: mime,
downloadKeyHash: hashSecret(key),
createdAt: new Date().toISOString(),
});
log("info", `upload ok id=${id} size=${size} name=${JSON.stringify(originalName)}`);
return json({ id, key, url: `/d/${key}`, originalName, size });
} catch (err) {
await storage.delete(id);
await storage.deletePartial(id);
if (err instanceof UploadTooLargeError) {
log("warn", `upload rejected id=${id} exceeding max size ${maxFileSize}`);
return jsonError(413, "file too large");
}
if (err instanceof MultipartError) {
log("warn", `upload rejected id=${id}: ${err.message}`);
return jsonError(400, "invalid multipart body");
}
log("error", `upload failed id=${id}: ${err instanceof Error ? err.message : String(err)}`);
return jsonError(500, "upload failed");
}
}