diff --git a/.omo/evidence/the-commons-hollow/task-54-the-commons-hollow-malformed.json b/.omo/evidence/the-commons-hollow/task-54-the-commons-hollow-malformed.json new file mode 100644 index 0000000..05d92e3 --- /dev/null +++ b/.omo/evidence/the-commons-hollow/task-54-the-commons-hollow-malformed.json @@ -0,0 +1,30 @@ +{ + "task": "task-54-the-commons-hollow", + "scenario": "failure", + "description": "Upload HTML that fails to parse; assert a clear rejection message at mount time, not a silent failure or a crash of the shell around it", + "module": "src/shell/MountedMiniapp.tsx", + "function": "mountMiniapp", + "ranAt": "2026-11-18T02:36:22.178Z", + "manifest": { + "name": "Balance Reader", + "icon": "data:image/svg+xml;base64,PHN2Zy8+", + "entryPoint": "index.html", + "permissions": [ + "ledger.read", + "eventlog.write", + "identity.read" + ] + }, + "uploadedPackageId": "18a9fafe-c8a8-462c-b2e7-c6d19af13972", + "uploadedHtml": "

unclosed", + "threwAtMountTime": true, + "caughtErrorIsMiniappMountError": true, + "caughtError": { + "name": "MiniappMountError", + "message": "Mini-app HTML failed to parse: This page contains the following errors:error on line 1 at column 37: Opening and ending tag mismatch: body line 1 and html\nBelow is a rendering of the page up to the first error." + }, + "containerLeftInDocumentUnaffected": true, + "assertion": "mountMiniapp throws MiniappMountError with a message containing 'failed to parse' synchronously at mount time (caught by the caller, e.g. MountedMiniapp's useEffect, and rendered as a visible error state) rather than silently doing nothing or throwing an unrelated/generic error that could crash the shell", + "passed": true, + "verifiedBy": "npx vitest run src/shell/MountedMiniapp.test.tsx (MountedMiniapp: malformed upload suite, 2/2 passed) + direct script execution captured above" +} diff --git a/.omo/evidence/the-commons-hollow/task-54-the-commons-hollow.json b/.omo/evidence/the-commons-hollow/task-54-the-commons-hollow.json new file mode 100644 index 0000000..d56b509 --- /dev/null +++ b/.omo/evidence/the-commons-hollow/task-54-the-commons-hollow.json @@ -0,0 +1,68 @@ +{ + "task": "task-54-the-commons-hollow", + "scenario": "happy", + "description": "Upload a minimal valid mini-app that reads the ledger balance through the exposed SDK and renders it; assert the rendered value matches the real balance", + "modules": [ + "src/lib/miniappUpload.ts", + "src/shell/MountedMiniapp.tsx", + "src/shell/miniappSdk.ts" + ], + "ranAt": "2026-11-18T02:36:22.173Z", + "manifest": { + "name": "Balance Reader", + "icon": "data:image/svg+xml;base64,PHN2Zy8+", + "entryPoint": "index.html", + "permissions": [ + "ledger.read", + "eventlog.write", + "identity.read" + ] + }, + "uploadedPackageId": "98b6acd9-3fd3-4cff-b2d5-59caf47fcf19", + "realBalanceComputedIndependently": 100, + "renderedBalanceTextFromMountedMiniapp": "100", + "sdkDirectCalls": { + "identity.getPublicKey()": [ + 210, + 212, + 31, + 126, + 36, + 208, + 141, + 226, + 81, + 163, + 98, + 110, + 150, + 209, + 38, + 191, + 236, + 159, + 210, + 99, + 134, + 136, + 74, + 0, + 89, + 7, + 174, + 9, + 71, + 81, + 237, + 232 + ], + "eventlog.append(...)": { + "id": 3, + "lamportTs": 2 + }, + "ledger.getBalance()": 100 + }, + "assertion": "renderedBalanceTextFromMountedMiniapp equals String(realBalanceComputedIndependently), and ledger.getBalance()/eventlog.append()/identity.getPublicKey() all resolve successfully through the exposed SDK object", + "passed": true, + "verifiedBy": "npx vitest run src/shell/MountedMiniapp.test.tsx (MountedMiniapp: happy path suite, 3/3 passed) + direct script execution captured above" +} diff --git a/src/lib/db.ts b/src/lib/db.ts index bf1971e..08e0f9b 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -1,4 +1,5 @@ import Dexie, { type EntityTable } from "dexie"; +import type { MiniappManifest } from "./miniappManifest"; /** A single, non-custodial local identity record. Exactly one row ever exists. */ export interface IdentityRecord { @@ -31,9 +32,27 @@ export interface EventLogRecord { lamportTs: number; } +/** + * An uploaded mini-app package (plan todo 54, Wave 6 upload): the raw HTML + * (stored as a Dexie blob) paired with the manifest it was uploaded with, + * which has already passed `validateManifest`/`assertValidManifest` (todo + * 53) before this record is ever written - see src/lib/miniappUpload.ts, + * the only write path for this table. + */ +export interface MiniappPackageRecord { + /** Generated at upload time; stable identifier for this package. */ + id: string; + /** The manifest this package was uploaded and validated with. */ + manifest: MiniappManifest; + /** Raw HTML source of the mini-app, stored as a blob. */ + html: Blob; + installedAt: number; +} + export class CommonsDatabase extends Dexie { identity!: EntityTable; eventLog!: EntityTable; + miniappPackages!: EntityTable; constructor() { super("the-commons-hollow"); @@ -44,6 +63,11 @@ export class CommonsDatabase extends Dexie { identity: "id", eventLog: "++id, lamportTs", }); + this.version(3).stores({ + identity: "id", + eventLog: "++id, lamportTs", + miniappPackages: "id", + }); } } diff --git a/src/lib/miniappUpload.test.ts b/src/lib/miniappUpload.test.ts new file mode 100644 index 0000000..e2f9b45 --- /dev/null +++ b/src/lib/miniappUpload.test.ts @@ -0,0 +1,56 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { db } from "./db"; +import { init } from "./identity"; +import { + getMiniappPackage, + readPackageHtml, + uploadMiniapp, +} from "./miniappUpload"; +import { ManifestValidationError } from "./miniappManifest"; + +beforeEach(async () => { + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); + await init(); +}); + +const validManifest = { + name: "Balance Reader", + icon: "data:image/svg+xml;base64,PHN2Zy8+", + entryPoint: "index.html", + permissions: ["ledger.read"], +}; + +describe("miniappUpload.uploadMiniapp", () => { + it("stores a package whose manifest passes validation, with its HTML as a blob", async () => { + const html = "hi"; + const stored = await uploadMiniapp({ manifest: validManifest, html }); + + expect(stored.manifest).toEqual(validManifest); + expect(stored.html).toBeInstanceOf(Blob); + expect(await readPackageHtml(stored)).toBe(html); + + const fromDb = await getMiniappPackage(stored.id); + expect(fromDb).toBeDefined(); + expect(await readPackageHtml(fromDb!)).toBe(html); + }); + + it("assigns each upload a distinct id", async () => { + const a = await uploadMiniapp({ manifest: validManifest, html: "

a

" }); + const b = await uploadMiniapp({ manifest: validManifest, html: "

b

" }); + expect(a.id).not.toBe(b.id); + }); + + it("rejects a manifest missing a required field and stores nothing", async () => { + const withoutName: Record = { ...validManifest }; + delete withoutName.name; + + await expect( + uploadMiniapp({ manifest: withoutName, html: "

x

" }), + ).rejects.toThrow(ManifestValidationError); + + const all = await db.miniappPackages.toArray(); + expect(all).toHaveLength(0); + }); +}); diff --git a/src/lib/miniappUpload.ts b/src/lib/miniappUpload.ts new file mode 100644 index 0000000..0182b88 --- /dev/null +++ b/src/lib/miniappUpload.ts @@ -0,0 +1,76 @@ +/** + * Mini-app upload storage (plan todo 54, Wave 6 upload). + * + * Accepts an uploaded HTML file paired with a manifest, gates it through + * the real manifest validator (`assertValidManifest`, todo 53 - never + * bypassed), and - only once it passes - stores the HTML as a Dexie blob + * alongside the validated manifest. This module owns the only write path + * for the `miniappPackages` table. + * + * Scope limit (draft D10, explicit): this is storage + validation-gating + * only. It adds no permission-enforcement, sandboxing, or isolation layer + * of any kind - a stored package's declared permissions are never checked + * against what it actually does at mount/run time (see + * src/shell/MountedMiniapp.tsx and src/shell/miniappSdk.ts). + */ +import { db, type MiniappPackageRecord } from "./db"; +import { assertValidManifest } from "./miniappManifest"; + +export type StoredMiniappPackage = MiniappPackageRecord; + +/** An uploaded mini-app package awaiting validation + storage. */ +export interface MiniappUploadInput { + /** Raw manifest JSON as uploaded - validated by `assertValidManifest`. */ + manifest: unknown; + /** Raw HTML source of the mini-app, as uploaded. */ + html: string; +} + +function generatePackageId(): string { + if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") { + return crypto.randomUUID(); + } + return `miniapp-${Date.now()}-${Math.random().toString(36).slice(2)}`; +} + +/** + * Validate `input.manifest` against the mini-app manifest schema and, + * only if it passes, store the paired HTML as a Dexie blob. Throws + * `ManifestValidationError` (from src/lib/miniappManifest.ts) for a + * manifest that fails validation - the HTML is never persisted in that + * case. + */ +export async function uploadMiniapp( + input: MiniappUploadInput, +): Promise { + const manifest = assertValidManifest(input.manifest); + + const record: MiniappPackageRecord = { + id: generatePackageId(), + manifest, + html: new Blob([input.html], { type: "text/html" }), + installedAt: Date.now(), + }; + + await db.miniappPackages.add(record); + return record; +} + +/** Read a stored package by id, or `undefined` if no such package exists. */ +export async function getMiniappPackage( + id: string, +): Promise { + return db.miniappPackages.get(id); +} + +/** Every stored package, in no particular order. */ +export async function listMiniappPackages(): Promise { + return db.miniappPackages.toArray(); +} + +/** Decode a stored package's HTML blob back into text. */ +export async function readPackageHtml( + record: StoredMiniappPackage, +): Promise { + return record.html.text(); +} diff --git a/src/shell/MountedMiniapp.module.css b/src/shell/MountedMiniapp.module.css new file mode 100644 index 0000000..575c1b1 --- /dev/null +++ b/src/shell/MountedMiniapp.module.css @@ -0,0 +1,10 @@ +.container { + min-height: 4rem; +} + +.error { + padding: 1rem; + border-radius: 0.5rem; + background: #fef0f0; + color: #b42318; +} diff --git a/src/shell/MountedMiniapp.test.tsx b/src/shell/MountedMiniapp.test.tsx new file mode 100644 index 0000000..8da00f0 --- /dev/null +++ b/src/shell/MountedMiniapp.test.tsx @@ -0,0 +1,134 @@ +// @vitest-environment happy-dom +import "@testing-library/jest-dom/vitest"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { db } from "../lib/db"; +import { append, readAll } from "../lib/eventlog"; +import { getPublicKey, init } from "../lib/identity"; +import { balanceOf, computeBalances } from "../lib/ledger"; +import { uploadMiniapp } from "../lib/miniappUpload"; +import { toAccountId } from "./accountId"; +import { MiniappMountError, MountedMiniapp, mountMiniapp } from "./MountedMiniapp"; +import { buildMiniappSdk } from "./miniappSdk"; + +afterEach(cleanup); + +beforeEach(async () => { + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); + delete window.commons; +}); + +const manifest = { + name: "Balance Reader", + icon: "data:image/svg+xml;base64,PHN2Zy8+", + entryPoint: "index.html", + permissions: ["ledger.read", "eventlog.write", "identity.read"], +}; + +const BALANCE_READER_HTML = ` + +
pending
+
pending
+
pending
+ + +`; + +const UNPARSEABLE_HTML = `

unclosed`; + +describe("MountedMiniapp: happy path", () => { + it("mounts a valid uploaded mini-app that reads the ledger balance through the SDK and renders the real balance", async () => { + await init(); + const accountId = toAccountId(await getPublicKey()); + await append({ type: "wallet.issue", account: accountId, amount: 77 }); + await append({ type: "wallet.issue", account: accountId, amount: 23 }); + const realBalance = balanceOf(computeBalances(await readAll()), accountId); + + const stored = await uploadMiniapp({ manifest, html: BALANCE_READER_HTML }); + + render(); + + await waitFor(() => { + const container = screen.getByTestId("miniapp-mount-container"); + expect(container.querySelector("#balance")).toHaveTextContent(String(realBalance)); + expect(container.querySelector("#pubkey")).not.toHaveTextContent("pending"); + expect(container.querySelector("#appended-id")).not.toHaveTextContent("pending"); + }); + expect(realBalance).toBe(100); + }); + + it("gives the mounted mini-app's script working access to all three SDK surfaces: ledger.getBalance, eventlog.append, identity.getPublicKey", async () => { + await init(); + const realPublicKey = await getPublicKey(); + + const stored = await uploadMiniapp({ manifest, html: BALANCE_READER_HTML }); + render(); + + await waitFor(() => { + const container = screen.getByTestId("miniapp-mount-container"); + expect(container.querySelector("#pubkey")).toHaveTextContent(Array.from(realPublicKey).join(",")); + expect(container.querySelector("#appended-id")).not.toHaveTextContent("pending"); + expect(container.querySelector("#balance")).toHaveTextContent("0"); + }); + + const appendedId = Number( + screen.getByTestId("miniapp-mount-container").querySelector("#appended-id")?.textContent, + ); + const entries = await readAll(); + expect(entries.map((e) => e.id)).toContain(appendedId); + expect(entries.find((e) => e.id === appendedId)?.payload).toEqual({ type: "test.ping" }); + }); + + it("exposes a working ledger.getBalance/eventlog.append/identity.getPublicKey SDK object directly (non-DOM)", async () => { + await init(); + const sdk = await buildMiniappSdk(); + + const pubkey = await sdk.identity.getPublicKey(); + expect(pubkey).toEqual(await getPublicKey()); + + const stored = await sdk.eventlog.append({ type: "test.direct" }); + expect(stored.id).toBeGreaterThanOrEqual(0); + + const accountId = toAccountId(pubkey); + await sdk.eventlog.append({ type: "wallet.issue", account: accountId, amount: 10 }); + expect(await sdk.ledger.getBalance()).toBe(10); + }); +}); + +describe("MountedMiniapp: malformed upload", () => { + it("rejects HTML that fails to parse with a clear message at mount time, without crashing the shell", async () => { + await init(); + const stored = await uploadMiniapp({ manifest, html: UNPARSEABLE_HTML }); + + render(); + + await waitFor(() => { + expect(screen.getByTestId("miniapp-mount-error")).toBeInTheDocument(); + }); + expect(screen.getByTestId("miniapp-mount-error")).toHaveTextContent("failed to parse"); + expect(screen.queryByTestId("miniapp-mount-container")).not.toBeInTheDocument(); + }); + + it("mountMiniapp throws MiniappMountError (not a generic crash) for unparseable HTML", async () => { + await init(); + const container = document.createElement("div"); + const sdk = await buildMiniappSdk(); + + expect(() => mountMiniapp(container, UNPARSEABLE_HTML, sdk)).toThrow(MiniappMountError); + expect(() => mountMiniapp(container, UNPARSEABLE_HTML, sdk)).toThrow(/failed to parse/); + }); +}); diff --git a/src/shell/MountedMiniapp.tsx b/src/shell/MountedMiniapp.tsx new file mode 100644 index 0000000..29161e6 --- /dev/null +++ b/src/shell/MountedMiniapp.tsx @@ -0,0 +1,118 @@ +/** + * Direct-mount execution of an uploaded mini-app (plan todo 54, Wave 6 + * upload). A package that already passed manifest validation and storage + * (src/lib/miniappUpload.ts) is injected straight into the live shell DOM + * - no `sandbox` attribute, no postMessage isolation boundary, no runtime + * permission-enforcement layer, per draft D10 - with its own inline + * `