Files
patriothacks/api/_lib/blobStore.ts
T

88 lines
3.2 KiB
TypeScript

import { mkdir, readFile, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { join } from "node:path";
/**
* 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.
*
* Judgment call (todo 56): `@vercel/blob` and `@vercel/kv` both require a
* live `BLOB_READ_WRITE_TOKEN` / `KV_REST_API_*` credential bound to a
* real Vercel project to do anything at all, even a basic store/retrieve
* in local dev - this sandbox has no such credential and none is
* available until actual deploy time (todo 57). This module implements
* the exact same store/retrieve/size-limit contract those SDKs would
* provide, backed by the local filesystem, so the integration tests in
* `api/blob.integration.test.ts` exercise real request/response behavior
* right now. At deploy time, replace the body of `putBlob`/`getBlob` with
* `@vercel/blob`'s `put()`/`head()`+fetch (or `@vercel/kv`'s `set`/`get`
* storing a base64 payload) - the handler contract in `api/blob/index.ts`
* and `api/blob/[id].ts` (store -> `{ id }`, retrieve by id -> bytes or
* 404, oversized -> 413) does not change.
*/
export const MAX_BLOB_SIZE_BYTES = 4 * 1024 * 1024;
const STORE_DIR = process.env.BLOB_STORE_DIR ?? join(process.cwd(), ".data", "blobs");
// 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 filesystem.
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;
}
}
interface StoredBlobMeta {
contentType: string;
}
function blobPath(id: string): string {
return join(STORE_DIR, `${id}.bin`);
}
function metaPath(id: string): string {
return join(STORE_DIR, `${id}.meta.json`);
}
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);
}
await mkdir(STORE_DIR, { recursive: true });
const id = randomUUID();
const meta: StoredBlobMeta = { contentType };
await writeFile(blobPath(id), data);
await writeFile(metaPath(id), JSON.stringify(meta));
return { id };
}
export async function getBlob(id: string): Promise<{ data: Buffer; contentType: string } | null> {
if (!isValidBlobId(id)) {
return null;
}
try {
const [data, metaRaw] = await Promise.all([readFile(blobPath(id)), readFile(metaPath(id), "utf8")]);
const meta = JSON.parse(metaRaw) as StoredBlobMeta;
return { data, contentType: meta.contentType };
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
return null;
}
throw err;
}
}