diff --git a/.gitignore b/.gitignore index a547bf3..b9011e6 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,10 @@ dist dist-ssr *.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 .vscode/* !.vscode/extensions.json diff --git a/.omo/evidence/the-commons-hollow/task-56-the-commons-hollow-404.json b/.omo/evidence/the-commons-hollow/task-56-the-commons-hollow-404.json new file mode 100644 index 0000000..315c884 --- /dev/null +++ b/.omo/evidence/the-commons-hollow/task-56-the-commons-hollow-404.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')" +} diff --git a/.omo/evidence/the-commons-hollow/task-56-the-commons-hollow.json b/.omo/evidence/the-commons-hollow/task-56-the-commons-hollow.json new file mode 100644 index 0000000..33b6b3f --- /dev/null +++ b/.omo/evidence/the-commons-hollow/task-56-the-commons-hollow.json @@ -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": "
sample mini-app for cross-device sharing", + "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": "sample mini-app for cross-device sharing" + } + ], + "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')" +} diff --git a/api/_lib/blobStore.ts b/api/_lib/blobStore.ts new file mode 100644 index 0000000..4ee2cb7 --- /dev/null +++ b/api/_lib/blobStore.ts @@ -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; + } +} diff --git a/api/_lib/devServer.ts b/api/_lib/devServer.ts new file mode 100644 index 0000000..be5b686 --- /dev/null +++ b/api/_lib/devServer.ts @@ -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}`); + }); +} diff --git a/api/_lib/httpUtils.ts b/api/_lib/httpUtils.ts new file mode 100644 index 0000000..4faeb48 --- /dev/null +++ b/api/_lib/httpUtils.ts @@ -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