Export och import av hela böcker

- Export som zip (book.json + bilder) eller bara JSON, ersätter den gamla JSON-exporten
- Import via /api/books/import skapar alltid en ny bok med nya id och pekar om
  kopplingar (relationer, grupper, kopplingsfält, markeringar, scheman)
- Bevarar ID-nummer och räknar om räknarna, hoppar över ogiltiga bilder och länkar
- Kontroll av filtyp på innehållet, gränser mot zip-bomber och Origin-kontroll
- Höjd gräns för stora uppladdningar (serverActions och middlewareClientMaxBodySize)
- Nytt beroende: fflate. Importkort på startsidan, exportknappar i bokinställningar, README

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-26 19:51:05 +01:00
1 parent 1c62555abe
commit ba4683f867
14 files changed
+831 -32

No files matched your search

+30 -1
View File
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import { mkdir, unlink, writeFile } from "node:fs/promises";
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
export const UPLOAD_DIR = path.resolve(process.env.UPLOAD_DIR ?? "./data/uploads");
@@ -48,3 +48,32 @@ export async function deleteImage(name: string | null | undefined) {
export function fileUrl(name: string | null | undefined): string | null {
return name ? `/api/files/${name}` : null;
}
/** Bildtyp utifrån filens första bytes (inte filnamnet), eller null om det inte är en tillåten bild. */
export function detectImageExt(bytes: Uint8Array): "png" | "jpg" | "webp" | "gif" | null {
const at = (i: number) => bytes[i];
if (bytes.length > 8 && at(0) === 0x89 && at(1) === 0x50 && at(2) === 0x4e && at(3) === 0x47) return "png";
if (bytes.length > 3 && at(0) === 0xff && at(1) === 0xd8 && at(2) === 0xff) return "jpg";
if (bytes.length > 6 && at(0) === 0x47 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x38) return "gif";
if (bytes.length > 12 && at(0) === 0x52 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x46 && at(8) === 0x57 && at(9) === 0x45 && at(10) === 0x42 && at(11) === 0x50) return "webp";
return null;
}
/** Sparar en bild som redan ligger i minnet (t.ex. från en importfil). Returnerar filnamnet, eller null om bilden inte duger. */
export async function saveImageBytes(bytes: Uint8Array): Promise<string | null> {
const ext = detectImageExt(bytes);
if (!ext || bytes.length > MAX_UPLOAD_BYTES) return null;
await mkdir(UPLOAD_DIR, { recursive: true });
const name = `${randomUUID()}.${ext}`;
await writeFile(path.join(UPLOAD_DIR, name), bytes);
return name;
}
export async function readImageBytes(name: string | null | undefined): Promise<Buffer | null> {
if (!name || !FILE_NAME_PATTERN.test(name)) return null;
try {
return await readFile(path.join(UPLOAD_DIR, name));
} catch {
return null;
}
}