Repository Public
1/**2 * Private object storage for uploads and exports. Keys are opaque (`ab/cd/<uuid>`); nothing here is ever served3 * as a static file — every read goes through an authorisation check in src/server/assets.ts.4 *5 * Only the `local` driver (a directory on the node's volume, or a NAS mount) is implemented. An S3/MinIO driver6 * would implement the same four methods; STORAGE_DRIVER refuses any other value rather than pretending.7 */8import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";9import path from "node:path";10import { env } from "@/lib/env";1112export interface Storage {13 put(key: string, data: Buffer): Promise<void>;14 get(key: string): Promise<Buffer>;15 remove(key: string): Promise<void>;16 health(): Promise<{ ok: boolean; detail: string }>;17}1819const KEY = /^[a-z0-9]{2}\/[a-z0-9]{2}\/[a-z0-9-]{36}$/;2021class LocalStorage implements Storage {22 constructor(private root: string) {}23 private file(key: string) {24 if (!KEY.test(key)) throw new Error("Invalid storage key");25 return path.join(/*turbopackIgnore: true*/ this.root, key);26 }27 async put(key: string, data: Buffer) {28 const f = this.file(key);29 await mkdir(path.dirname(f), { recursive: true, mode: 0o700 });30 // Write then rename: a reader never sees a half-written file.31 await writeFile(f + ".part", data, { mode: 0o600 });32 await rename(f + ".part", f);33 }34 get(key: string) { return readFile(this.file(key)); }35 async remove(key: string) { await rm(this.file(key), { force: true }); }36 async health() {37 try {38 await mkdir(this.root, { recursive: true, mode: 0o700 });39 const probe = path.join(/*turbopackIgnore: true*/ this.root, ".probe");40 await writeFile(probe, "ok"); await stat(probe); await rm(probe);41 return { ok: true, detail: "local" };42 } catch (e) { return { ok: false, detail: (e as Error).message }; }43 }44}4546let instance: Storage | null = null;47export function storage(): Storage {48 if (instance) return instance;49 if (env.storageDriver !== "local") throw new Error(`STORAGE_DRIVER=${env.storageDriver} is not implemented (only "local")`);50 return (instance = new LocalStorage(env.storageRoot));51}52export const storageKey = (id: string) => `${id.slice(0, 2)}/${id.slice(2, 4)}/${id}`;53