Files
patriothacks/api/_lib/blobStore.ts
T

122 lines
4.9 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
/**
* Minimal blob/KV store for cross-device mini-app sharing (todo 55) and
* this deployment's own static-hosting needs (todo 57). This is the ONLY
* backend in the app - every other mini-app stays local-first (draft D9);
* nothing else may route through this module.
*
* Self-hosted decision (2026-11-19): the user explicitly rejected any
* managed third-party cloud database/service (even a free tier) for this
* project - "just self-host everything... if I do [deploy], give me
* instructions to self-host because I have that capability." This module
* therefore stores blobs in a local SQLite database file via Node's
* built-in `node:sqlite` (`DatabaseSync`, stable since Node 22.5, present
* in this environment's Node 24) rather than any managed Postgres/libSQL
* SaaS product or `@vercel/blob`/`@vercel/kv` (both of which need a live
* credential bound to a real cloud project and were never usable in this
* sandbox anyway). No external account or credential is required for
* this storage path at all.
*
* The db file's path is configurable via `BLOB_DB_PATH` and defaults to
* `.data/blobs.sqlite3` under the process's own working directory (this
* repo's existing `.gitignore` convention for local persistent state) - a
* real file that survives a process restart on a normal self-hosted
* machine, not `os.tmpdir()` (the old stub's assumption, which only made
* sense for Vercel's ephemeral serverless `/tmp`).
*
* Vercel-routing compatibility note: this project's `vercel.json`/`api/`
* file-routing convention still works unchanged if ever deployed to
* Vercel specifically - the handler contract in `api/blob/index.ts` and
* `api/blob/[id].ts` (store -> `{ id }`, retrieve by id -> bytes or 404,
* oversized -> 413) never changes. BUT Vercel's serverless functions only
* get a writable `/tmp`, which is ephemeral per-invocation, not a
* persistent disk - a real Vercel deployment of this exact code would
* need `BLOB_DB_PATH` pointed at a genuinely persistent mounted volume
* (Vercel's serverless platform does not offer one for `api/` functions),
* or - the user's actual stated preference - the app instead runs as a
* long-running self-hosted process (see `api/_lib/devServer.ts` and
* `DEPLOY.md` at the repo root) where the SQLite file lives on normal
* persistent disk. Do not assume the Vercel path "just works" without
* that qualification.
*/
export const MAX_BLOB_SIZE_BYTES = 4 * 1024 * 1024;
const DEFAULT_DB_PATH = join(process.cwd(), ".data", "blobs.sqlite3");
// Resolved lazily (inside getDb(), on first call) rather than as a
// module-load-time constant: a module-level `const DB_PATH = ...` would
// capture `process.env.BLOB_DB_PATH` at import time, before a test's
// `beforeAll` has a chance to set it - silently ignoring the override and
// writing to the repo-root default path instead.
function resolveDbPath(): string {
return process.env.BLOB_DB_PATH ?? DEFAULT_DB_PATH;
}
// Only server-generated ids (randomUUID) are ever accepted for lookup;
// anything else - including path-traversal attempts - is treated as "not
// found" rather than reaching the database with attacker-controlled input.
const BLOB_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export class BlobTooLargeError extends Error {
readonly limitBytes: number;
constructor(limitBytes: number) {
super(`blob exceeds maximum size of ${limitBytes} bytes`);
this.name = "BlobTooLargeError";
this.limitBytes = limitBytes;
}
}
let db: DatabaseSync | undefined;
function getDb(): DatabaseSync {
if (db) {
return db;
}
const dbPath = resolveDbPath();
mkdirSync(dirname(dbPath), { recursive: true });
const opened = new DatabaseSync(dbPath);
opened.exec(`
CREATE TABLE IF NOT EXISTS blobs (
id TEXT PRIMARY KEY,
data BLOB NOT NULL,
contentType TEXT NOT NULL
)
`);
db = opened;
return opened;
}
export function isValidBlobId(id: string): boolean {
return BLOB_ID_PATTERN.test(id);
}
export async function putBlob(data: Buffer, contentType: string): Promise<{ id: string }> {
if (data.byteLength > MAX_BLOB_SIZE_BYTES) {
throw new BlobTooLargeError(MAX_BLOB_SIZE_BYTES);
}
const id = randomUUID();
getDb()
.prepare("INSERT INTO blobs (id, data, contentType) VALUES (?, ?, ?)")
.run(id, data, contentType);
return { id };
}
export async function getBlob(id: string): Promise<{ data: Buffer; contentType: string } | null> {
if (!isValidBlobId(id)) {
return null;
}
const row = getDb().prepare("SELECT data, contentType FROM blobs WHERE id = ?").get(id) as
| { data: Uint8Array; contentType: string }
| undefined;
if (!row) {
return null;
}
return { data: Buffer.from(row.data), contentType: row.contentType };
}