files.ts

5.5 KB · raw

1import type { Database } from "bun:sqlite";23// §23: what an issue or reply may carry.4export const FILES_PER_POST = 4;5export const FILE_BYTES_PER_HOUR = 64 * 1024 * 1024;6// The whole site's attachments per UTC day: one address's hour is no ceiling on a botnet sharing7// the same files, and 200 MB leaves a busy repository's ordinary screenshots untouched.8export const ATTACHMENT_BYTES_PER_DAY = 200 * 1024 * 1024;9const IMAGE_BYTES = 8 * 1024 * 1024;10const LOG_BYTES = 2 * 1024 * 1024;11// A log shows this much of its start in the thread; the whole file is a link away.12const PREVIEW_BYTES = 16 * 1024;1314// Bytes kept today, in memory, like the rest of the limits: a restart forgets them.15let day = -1;16let bytesToday = 0;1718function rollDay(at: number): void {19	const today = Math.floor(at / 86_400);20	if (today === day) return;21	day = today;22	bytesToday = 0;23}2425/** Bytes attached site-wide on `at`'s UTC day, before this post's own. */26export function attachmentBytesToday(at: number): number {27	rollDay(at);28	return bytesToday;29}3031// A picture is known by its first bytes, never by the name or type the browser sent.32const IMAGES: [type: string, ext: string, magic: (head: string) => boolean][] = [33	["image/png", "png", (head) => head.startsWith("\x89PNG\r\n\x1a\n")],34	["image/jpeg", "jpg", (head) => head.startsWith("\xff\xd8\xff")],35	["image/gif", "gif", (head) => head.startsWith("GIF87a") || head.startsWith("GIF89a")],36	["image/webp", "webp", (head) => head.startsWith("RIFF") && head.slice(8, 12) === "WEBP"],37];38export const FILE_EXTENSIONS: Record<string, string> = {39	...Object.fromEntries(IMAGES.map(([type, ext]) => [type, ext])),40	"text/plain": "txt",41};4243export type Upload = { name: string; type: string; data: Uint8Array };44type StoredFile = { name: string; type: string; data: Uint8Array<ArrayBuffer> };4546export type Attachment = {47	id: number;48	entry_id: number | null;49	name: string;50	type: string;51	size: number;52	/** A log's first bytes, for its preview; null for a picture. */53	head: Uint8Array | null;54};5556/** Checks the files sent with one post, returning them ready to keep or the reason to refuse. */57export async function readUploads(files: File[]): Promise<Upload[] | string> {58	if (files.length > FILES_PER_POST) return `Attach at most ${FILES_PER_POST} files.`;59	const uploads: Upload[] = [];60	for (const file of files) {61		const data = new Uint8Array(await file.arrayBuffer());62		// Shown, never used as a path; control characters would only garble the page.63		const name = (file.name.split(/[\\/]/).pop() ?? "").replace(/\p{Cc}/gu, "").slice(0, 100);64		const head = Buffer.from(data.subarray(0, 12)).toString("latin1");65		const image = IMAGES.find(([, , magic]) => magic(head));66		if (image) {67			if (data.length > IMAGE_BYTES) return `${name} is over 8 MB.`;68			// The bytes decide the type, so the name follows them: a PNG called report.html would69			// otherwise be offered for download under an extension its bytes are not (§25).70			const stem = name.replace(/\.\w+$/, "");71			uploads.push({ name: `${stem || "screenshot"}.${image[1]}`, type: image[0], data });72			continue;73		}74		if (!/\.(txt|log)$/i.test(name)) {75			return `${name || "A file"} isn't a PNG, JPEG, GIF or WebP picture, or a .txt or .log file.`;76		}77		if (data.length > LOG_BYTES) return `${name} is over 2 MB.`;78		try {79			new TextDecoder("utf-8", { fatal: true }).decode(data);80		} catch {81			return `${name} isn't UTF-8 text.`;82		}83		uploads.push({ name, type: "text/plain", data });84	}85	return uploads;86}8788/** Bytes attached from one hashed IP since a time, hidden posts' included. */89export function fileBytesSince(db: Database, ipHash: string, since: number): number {90	const row = db91		.query<{ n: number | null }, [string, number]>(92			"SELECT SUM(size) AS n FROM issue_files WHERE ip_hash = ? AND created_at > ?",93		)94		.get(ipHash, since);95	return row?.n ?? 0;96}9798/** Keeps a post's files: the issue's own when `entryId` is null, else one reply's. */99export function attachFiles(100	db: Database,101	issueId: number,102	entryId: number | null,103	uploads: Upload[],104	ipHash: string,105	at: number,106): void {107	const insert = db.query(108		`INSERT INTO issue_files (issue_id, entry_id, name, type, size, data, ip_hash, created_at)109VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,110	);111	// Counted where bytes are actually kept, so a post refused after its uploads were read costs112	// nothing against the day's ceiling.113	rollDay(at);114	bytesToday += uploads.reduce((sum, upload) => sum + upload.data.length, 0);115	db.transaction(() => {116		for (const upload of uploads) {117			insert.run(118				issueId,119				entryId,120				upload.name,121				upload.type,122				upload.data.length,123				upload.data,124				ipHash,125				at,126			);127		}128	})();129}130131/** Every file of an issue's posts, oldest first, without their bytes beyond a log's start. */132export function issueAttachments(db: Database, issueId: number): Attachment[] {133	return db134		.query<Attachment, [number, number]>(135			`SELECT id, entry_id, name, type, size,136	CASE WHEN type = 'text/plain' THEN substr(data, 1, ?) END AS head137FROM issue_files138WHERE issue_id = ?139ORDER BY id`,140		)141		.all(PREVIEW_BYTES, issueId);142}143144/** One file, only while its issue, its repo's issue list and its post are all visible. */145export function visibleFile(146	db: Database,147	repo: string,148	number: number,149	id: number,150): StoredFile | null {151	return db152		.query<StoredFile, [string, number, number]>(153			`SELECT f.name, f.type, f.data154FROM issue_files f155JOIN issues i ON i.id = f.issue_id156LEFT JOIN issue_entries e ON e.id = f.entry_id157WHERE i.repo = ? AND i.number = ? AND f.id = ? AND i.hidden = 0158	AND (f.entry_id IS NULL OR e.hidden = 0)`,159		)160		.get(repo, number, id);161}