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 { + 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); +} diff --git a/api/blob.integration.test.ts b/api/blob.integration.test.ts new file mode 100644 index 0000000..8332cd3 --- /dev/null +++ b/api/blob.integration.test.ts @@ -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; + 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((resolve) => server.listen(0, resolve)); + const { port } = server.address() as AddressInfo; + baseUrl = `http://127.0.0.1:${port}`; + }); + + afterAll(async () => { + await new Promise((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 = "sample mini-app"; + + 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); + }); +}); diff --git a/api/blob/[id].ts b/api/blob/[id].ts new file mode 100644 index 0000000..8572889 --- /dev/null +++ b/api/blob/[id].ts @@ -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 { + 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); +} diff --git a/api/blob/index.ts b/api/blob/index.ts new file mode 100644 index 0000000..5881855 --- /dev/null +++ b/api/blob/index.ts @@ -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 { + 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" }); + } +} diff --git a/tsconfig.api.json b/tsconfig.api.json new file mode 100644 index 0000000..bac340e --- /dev/null +++ b/tsconfig.api.json @@ -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"] +} diff --git a/tsconfig.json b/tsconfig.json index 1ffef60..c25c89f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,6 +2,7 @@ "files": [], "references": [ { "path": "./tsconfig.app.json" }, - { "path": "./tsconfig.node.json" } + { "path": "./tsconfig.node.json" }, + { "path": "./tsconfig.api.json" } ] }