This commit is contained in:
Anaïs Saraiva
2026-08-15 00:28:32 +02:00
parent 5f201cf725
commit 954384d1e4
14 changed files with 393 additions and 37 deletions
+45 -13
View File
@@ -1,9 +1,27 @@
import { json, jsonError } from "../http";
import { log } from "../log";
import { getBoundary, MultipartError, multipartParts } from "../multipart";
import { hashSecret, newDownloadKey, newFileId, sanitizeMime, sanitizeOriginalName } from "../security";
import { getBoundary, MultipartError, multipartParts, type MultipartPart } from "../multipart";
import {
hashPassword,
hashSecret,
newDownloadKey,
newFileId,
sanitizeMime,
sanitizeOriginalName,
} from "../security";
import { UploadTooLargeError, type Storage } from "../storage";
const MAX_PASSWORD_LENGTH = 256;
async function readField(part: MultipartPart, limit: number): Promise<string> {
let value = "";
for await (const chunk of part.chunks) {
value += Buffer.from(chunk).toString("utf8");
if (value.length > limit) throw new MultipartError("field too long");
}
return value;
}
export async function handleUpload(
req: Request,
storage: Storage,
@@ -21,34 +39,48 @@ export async function handleUpload(
let mime = "application/octet-stream";
let size = 0;
let hasFile = false;
let password = "";
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 (part.filename != null) {
if (!hasFile) {
hasFile = true;
filename = part.filename;
mime = sanitizeMime(part.contentType);
size = await storage.saveFile(id, part.chunks, maxFileSize);
} else {
for await (const _ of part.chunks) {
void _;
}
}
} else if (part.name === "password" && password === "") {
password = await readField(part, MAX_PASSWORD_LENGTH);
} else {
for await (const _ of part.chunks) {
void _;
}
}
}
if (!hasFile) return jsonError(400, "no file part in the upload");
const originalName = sanitizeOriginalName(filename);
const protected_ = password.trim().length > 0;
await storage.writeMetadata({
id,
originalName,
size,
mimeType: mime,
downloadKeyHash: hashSecret(key),
passwordHash: protected_ ? hashPassword(password) : undefined,
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 });
log(
"info",
`upload ok id=${id} size=${size} name=${JSON.stringify(originalName)} protected=${protected_}`,
);
return json({ id, key, url: `/d/${key}`, originalName, size, protected: protected_ });
} catch (err) {
await storage.delete(id);
await storage.deletePartial(id);