import { randomBytes } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; /** * Replaces Vercel Blob (public, unguessable URLs) for self-hosted deploys. * Files land on disk under UPLOAD_DIR — mount that path as a persistent * volume in Coolify or uploads vanish on the next container rebuild. */ const UPLOAD_DIR = process.env.UPLOAD_DIR ?? "/app/.data/uploads"; export async function putLocalBlob( key: string, file: File, opts: { contentType: string }, baseUrl: string ): Promise<{ url: string }> { const ext = path.extname(key); const base = key.slice(0, key.length - ext.length); const suffixed = `${base}-${randomBytes(10).toString("hex")}${ext}`; const dest = path.join(UPLOAD_DIR, suffixed); await mkdir(path.dirname(dest), { recursive: true }); await writeFile(dest, Buffer.from(await file.arrayBuffer())); return { url: `${baseUrl}/api/uploads/${suffixed}` }; } /** Resolves a public `/api/uploads/` path to its file on disk, rejecting traversal. */ export function resolveUploadPath(segments: string[]): string | null { if (segments.some((s) => s === "" || s === "." || s === "..")) return null; return path.join(UPLOAD_DIR, ...segments); }