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
View File
@@ -0,0 +1,45 @@
import { AUTH_COOKIE, AUTH_TTL_MS } from "../auth";
import { notFound } from "../http";
import { log } from "../log";
import { fileIdFromKey, KEY_PATTERN, makeAuthToken, passwordMatches } from "../security";
import type { Storage } from "../storage";
export async function handleAuth(
req: Request,
storage: Storage,
rawKey: string,
secret: string,
secure: boolean,
): Promise<Response> {
if (!KEY_PATTERN.test(rawKey)) return notFound();
const id = fileIdFromKey(rawKey);
if (!id) return notFound();
const meta = await storage.readMetadata(id);
if (!meta) return notFound();
if (!meta.passwordHash) {
return new Response(null, { status: 302, headers: { location: `/d/${rawKey}` } });
}
const password = await req.formData().then(
(form) => {
const value = form.get("password");
return typeof value === "string" ? value : "";
},
() => "",
);
if (!passwordMatches(meta.passwordHash, password)) {
log("warn", `auth failed id=${id}`);
return new Response(null, { status: 302, headers: { location: `/d/${rawKey}?e=1` } });
}
const token = makeAuthToken(rawKey, secret, AUTH_TTL_MS);
const cookie = `${AUTH_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax${
secure ? "; Secure" : ""
}; Max-Age=${Math.floor(AUTH_TTL_MS / 1000)}`;
log("info", `auth ok id=${id}`);
return new Response(null, { status: 302, headers: { location: `/d/${rawKey}`, "set-cookie": cookie } });
}
+7
View File
@@ -1,4 +1,5 @@
import { lstat } from "node:fs/promises";
import { hasValidAuth, renderPasswordForm } from "../auth";
import { notFound } from "../http";
import { log } from "../log";
import { contentDisposition, fileIdFromKey, KEY_PATTERN, secretMatches } from "../security";
@@ -8,6 +9,7 @@ export async function handleDownload(
req: Request,
storage: Storage,
rawKey: string,
secret: string,
): Promise<Response> {
if (!KEY_PATTERN.test(rawKey)) return notFound();
const id = fileIdFromKey(rawKey);
@@ -17,6 +19,11 @@ export async function handleDownload(
if (!meta) return notFound();
if (!secretMatches(meta.downloadKeyHash, rawKey)) return notFound();
if (meta.passwordHash && !hasValidAuth(req, secret, rawKey)) {
const url = new URL(req.url);
return renderPasswordForm(rawKey, meta.originalName, url.searchParams.has("e"));
}
const filePath = storage.filePath(id);
let fileStat;
try {
+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);