feat(backend): add minimal blob/KV store for mini-app sharing

This commit is contained in:
OmO Orchestrator committed 2026-11-17 21:50:44 -05:00
1 parent 3106c10643
commit 7d6c57fc4b
11 files changed
+358 -1

No files matched your search

+4
View File
@@ -12,6 +12,10 @@ dist
dist-ssr dist-ssr
*.local *.local
# local-filesystem stand-in for the todo 56 blob/KV store (dev/test only;
# real deploy uses @vercel/blob or @vercel/kv instead)
.data/
# Editor directories and files # Editor directories and files
.vscode/* .vscode/*
!.vscode/extensions.json !.vscode/extensions.json
@@ -0,0 +1,30 @@
{
"task": "task-56-the-commons-hollow",
"scenario": "failure",
"description": "Request a non-existent blob id and assert a clean 404, not a crash or a silent empty response",
"modules": [
"api/_lib/blobStore.ts",
"api/blob/[id].ts"
],
"ranAt": "2026-11-18T02:49:49.000Z",
"server": {
"transport": "real Node http.Server from api/_lib/devServer.ts, listening on 127.0.0.1:3987",
"storeBackend": "local filesystem (BLOB_STORE_DIR=/tmp/commons-blob-manual-qa) - see judgment-call note in api/_lib/blobStore.ts"
},
"request": {
"method": "GET",
"url": "http://127.0.0.1:3987/api/blob/00000000-0000-0000-0000-000000000000",
"tool": "curl -sS -i ..."
},
"responseStatus": 404,
"responseBody": { "error": "blob 00000000-0000-0000-0000-000000000000 not found" },
"relatedOversizedCheck": {
"description": "also exercised the 413 oversized-upload path in the same manual QA pass (not silently truncated)",
"request": { "method": "POST", "url": "http://127.0.0.1:3987/api/blob", "bodyBytes": 4195328 },
"responseStatus": 413,
"responseBody": { "error": "blob exceeds maximum size of 4194304 bytes", "maxBytes": 4194304 }
},
"assertion": "GET /api/blob/:id for an id that was never stored returns 404 with a JSON error body naming the missing id; the handler does not throw or return 200 with an empty/garbage body",
"passed": true,
"verifiedBy": "real curl HTTP request against a live api/_lib/devServer.ts process (tool.bash background session) + npx vitest run api/blob.integration.test.ts (3/3 passed, 'returns a clean 404 for a non-existent blob id')"
}
@@ -0,0 +1,39 @@
{
"task": "task-56-the-commons-hollow",
"scenario": "happy",
"description": "Store and retrieve a sample mini-app blob by id through the minimal blob/KV backend",
"modules": [
"api/_lib/blobStore.ts",
"api/_lib/httpUtils.ts",
"api/_lib/devServer.ts",
"api/blob/index.ts",
"api/blob/[id].ts"
],
"ranAt": "2026-11-18T02:49:45.000Z",
"server": {
"transport": "real Node http.Server from api/_lib/devServer.ts, listening on 127.0.0.1:3987",
"storeBackend": "local filesystem (BLOB_STORE_DIR=/tmp/commons-blob-manual-qa) - see judgment-call note in api/_lib/blobStore.ts"
},
"requests": [
{
"method": "POST",
"url": "http://127.0.0.1:3987/api/blob",
"headers": { "Content-Type": "text/html" },
"body": "<html><body>sample mini-app for cross-device sharing</body></html>",
"tool": "curl -sS -i -X POST ... --data-binary @/tmp/sample-miniapp.html",
"responseStatus": 201,
"responseBody": { "id": "6b09fdbb-a823-4f7b-a2ca-8b62fa7ffb5f" }
},
{
"method": "GET",
"url": "http://127.0.0.1:3987/api/blob/6b09fdbb-a823-4f7b-a2ca-8b62fa7ffb5f",
"tool": "curl -sS -i ...",
"responseStatus": 200,
"responseHeaders": { "Content-Type": "text/html", "Content-Length": "66" },
"responseBody": "<html><body>sample mini-app for cross-device sharing</body></html>"
}
],
"assertion": "POST /api/blob returns 201 with a generated id; GET /api/blob/:id with that id returns 200 with the exact original bytes and content-type",
"passed": true,
"verifiedBy": "real curl HTTP requests against a live api/_lib/devServer.ts process (tool.bash background session) + npx vitest run api/blob.integration.test.ts (3/3 passed, 'stores and retrieves a sample mini-app blob by id over real HTTP')"
}
+87
View File
@@ -0,0 +1,87 @@
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;
}
}
+30
View File
@@ -0,0 +1,30 @@
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import postBlob from "../blob/index.ts";
import getBlob from "../blob/[id].ts";
import { sendJson } from "./httpUtils.ts";
export function createApiServer() {
return createServer(async (req: IncomingMessage, res: ServerResponse) => {
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
try {
if (pathname === "/api/blob") {
await postBlob(req, res);
return;
}
if (pathname.startsWith("/api/blob/")) {
await getBlob(req, res);
return;
}
sendJson(res, 404, { error: "not found" });
} catch (err) {
sendJson(res, 500, { error: "internal error", detail: (err as Error).message });
}
});
}
if (import.meta.url === `file://${process.argv[1]}`) {
const port = Number(process.env.PORT ?? 3001);
createApiServer().listen(port, () => {
console.log(`blob API dev server listening on http://localhost:${port}`);
});
}
+27
View File
@@ -0,0 +1,27 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { BlobTooLargeError } from "./blobStore.ts";
export function sendJson(res: ServerResponse, status: number, body: unknown): void {
const payload = JSON.stringify(body);
res.writeHead(status, { "Content-Type": "application/json" });
res.end(payload);
}
export async function readLimitedBody(req: IncomingMessage, limitBytes: number): Promise<Buffer> {
const declaredLength = Number(req.headers["content-length"] ?? 0);
if (declaredLength > limitBytes) {
throw new BlobTooLargeError(limitBytes);
}
const chunks: Buffer[] = [];
let total = 0;
for await (const chunk of req) {
total += (chunk as Buffer).length;
if (total > limitBytes) {
req.destroy();
throw new BlobTooLargeError(limitBytes);
}
chunks.push(chunk as Buffer);
}
return Buffer.concat(chunks, total);
}
+69
View File
@@ -0,0 +1,69 @@
import type { AddressInfo } from "node:net";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createApiServer } from "./_lib/devServer.ts";
import { MAX_BLOB_SIZE_BYTES } from "./_lib/blobStore.ts";
describe("blob/KV backend integration (todo 56)", () => {
let server: ReturnType<typeof createApiServer>;
let baseUrl: string;
let storeDir: string;
beforeAll(async () => {
storeDir = await mkdtemp(join(tmpdir(), "commons-blob-test-"));
process.env.BLOB_STORE_DIR = storeDir;
server = createApiServer();
await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo;
baseUrl = `http://127.0.0.1:${port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
delete process.env.BLOB_STORE_DIR;
await rm(storeDir, { recursive: true, force: true });
});
it("stores and retrieves a sample mini-app blob by id over real HTTP", async () => {
const sampleHtml = "<html><body>sample mini-app</body></html>";
const putRes = await fetch(`${baseUrl}/api/blob`, {
method: "POST",
headers: { "Content-Type": "text/html" },
body: sampleHtml,
});
expect(putRes.status).toBe(201);
const { id } = (await putRes.json()) as { id: string };
expect(id).toMatch(/^[0-9a-f-]{36}$/);
const getRes = await fetch(`${baseUrl}/api/blob/${id}`);
expect(getRes.status).toBe(200);
expect(getRes.headers.get("content-type")).toBe("text/html");
expect(await getRes.text()).toBe(sampleHtml);
});
it("rejects an oversized upload with a clear 413 error, not silent truncation", async () => {
const oversized = new Uint8Array(MAX_BLOB_SIZE_BYTES + 1024);
const res = await fetch(`${baseUrl}/api/blob`, {
method: "POST",
headers: { "Content-Type": "application/octet-stream" },
body: oversized,
});
expect(res.status).toBe(413);
const body = (await res.json()) as { error: string; maxBytes: number };
expect(body.error).toMatch(/exceeds maximum size/i);
expect(body.maxBytes).toBe(MAX_BLOB_SIZE_BYTES);
});
it("returns a clean 404 for a non-existent blob id", async () => {
const res = await fetch(`${baseUrl}/api/blob/00000000-0000-0000-0000-000000000000`);
expect(res.status).toBe(404);
const body = (await res.json()) as { error: string };
expect(body.error).toMatch(/not found/i);
});
});
+23
View File
@@ -0,0 +1,23 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { getBlob } from "../_lib/blobStore.ts";
import { sendJson } from "../_lib/httpUtils.ts";
export default async function handler(req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.method !== "GET") {
sendJson(res, 405, { error: "method not allowed, use GET" });
return;
}
const id = new URL(req.url ?? "", "http://localhost").pathname.split("/").filter(Boolean).pop() ?? "";
const blob = await getBlob(id);
if (!blob) {
sendJson(res, 404, { error: `blob ${id} not found` });
return;
}
res.writeHead(200, {
"Content-Type": blob.contentType,
"Content-Length": String(blob.data.byteLength),
});
res.end(blob.data);
}
+24
View File
@@ -0,0 +1,24 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { BlobTooLargeError, MAX_BLOB_SIZE_BYTES, putBlob } from "../_lib/blobStore.ts";
import { readLimitedBody, sendJson } from "../_lib/httpUtils.ts";
export default async function handler(req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.method !== "POST") {
sendJson(res, 405, { error: "method not allowed, use POST" });
return;
}
const contentType = req.headers["content-type"] ?? "application/octet-stream";
try {
const body = await readLimitedBody(req, MAX_BLOB_SIZE_BYTES);
const { id } = await putBlob(body, contentType);
sendJson(res, 201, { id });
} catch (err) {
if (err instanceof BlobTooLargeError) {
sendJson(res, 413, { error: err.message, maxBytes: err.limitBytes });
return;
}
sendJson(res, 500, { error: "failed to store blob" });
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.api.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
"strict": true,
"module": "esnext",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["api"]
}
+2 -1
View File
@@ -2,6 +2,7 @@
"files": [], "files": [],
"references": [ "references": [
{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" } { "path": "./tsconfig.node.json" },
{ "path": "./tsconfig.api.json" }
] ]
} }