feat(upload): add direct-mount execution with shared ledger/eventlog/identity SDK

This commit is contained in:
OmO Orchestrator committed 2026-11-17 21:36:49 -05:00
1 parent 22ca9fd656
commit 3106c10643
11 files changed
+625

No files matched your search

@@ -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": "<html><body><p>unclosed<body></html>",
"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"
}
@@ -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"
}
+24
View File
@@ -1,4 +1,5 @@
import Dexie, { type EntityTable } from "dexie"; import Dexie, { type EntityTable } from "dexie";
import type { MiniappManifest } from "./miniappManifest";
/** A single, non-custodial local identity record. Exactly one row ever exists. */ /** A single, non-custodial local identity record. Exactly one row ever exists. */
export interface IdentityRecord { export interface IdentityRecord {
@@ -31,9 +32,27 @@ export interface EventLogRecord {
lamportTs: number; 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 { export class CommonsDatabase extends Dexie {
identity!: EntityTable<IdentityRecord, "id">; identity!: EntityTable<IdentityRecord, "id">;
eventLog!: EntityTable<EventLogRecord, "id">; eventLog!: EntityTable<EventLogRecord, "id">;
miniappPackages!: EntityTable<MiniappPackageRecord, "id">;
constructor() { constructor() {
super("the-commons-hollow"); super("the-commons-hollow");
@@ -44,6 +63,11 @@ export class CommonsDatabase extends Dexie {
identity: "id", identity: "id",
eventLog: "++id, lamportTs", eventLog: "++id, lamportTs",
}); });
this.version(3).stores({
identity: "id",
eventLog: "++id, lamportTs",
miniappPackages: "id",
});
} }
} }
+56
View File
@@ -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 = "<html><body>hi</body></html>";
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: "<p>a</p>" });
const b = await uploadMiniapp({ manifest: validManifest, html: "<p>b</p>" });
expect(a.id).not.toBe(b.id);
});
it("rejects a manifest missing a required field and stores nothing", async () => {
const withoutName: Record<string, unknown> = { ...validManifest };
delete withoutName.name;
await expect(
uploadMiniapp({ manifest: withoutName, html: "<p>x</p>" }),
).rejects.toThrow(ManifestValidationError);
const all = await db.miniappPackages.toArray();
expect(all).toHaveLength(0);
});
});
+76
View File
@@ -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<StoredMiniappPackage> {
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<StoredMiniappPackage | undefined> {
return db.miniappPackages.get(id);
}
/** Every stored package, in no particular order. */
export async function listMiniappPackages(): Promise<StoredMiniappPackage[]> {
return db.miniappPackages.toArray();
}
/** Decode a stored package's HTML blob back into text. */
export async function readPackageHtml(
record: StoredMiniappPackage,
): Promise<string> {
return record.html.text();
}
+10
View File
@@ -0,0 +1,10 @@
.container {
min-height: 4rem;
}
.error {
padding: 1rem;
border-radius: 0.5rem;
background: #fef0f0;
color: #b42318;
}
+134
View File
@@ -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 = `<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div id="pubkey">pending</div>
<div id="appended-id">pending</div>
<div id="balance">pending</div>
<script>
(function () {
window.commons.identity.getPublicKey().then(function (key) {
document.getElementById("pubkey").textContent = Array.from(key).join(",");
});
window.commons.eventlog.append({ type: "test.ping" }).then(function (entry) {
document.getElementById("appended-id").textContent = String(entry.id);
});
window.commons.ledger.getBalance().then(function (bal) {
document.getElementById("balance").textContent = String(bal);
});
})();
</script>
</body>
</html>`;
const UNPARSEABLE_HTML = `<html><body><p>unclosed<body></html>`;
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(<MountedMiniapp record={stored} />);
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(<MountedMiniapp record={stored} />);
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(<MountedMiniapp record={stored} />);
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/);
});
});
+118
View File
@@ -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
* `<script>` content given direct access to the shared SDK
* (src/shell/miniappSdk.ts) via `window.commons`.
*/
import { useEffect, useRef, useState } from "react";
import { init as initIdentity } from "../lib/identity";
import { readPackageHtml, type StoredMiniappPackage } from "../lib/miniappUpload";
import styles from "./MountedMiniapp.module.css";
import { buildMiniappSdk, type MiniappSdk } from "./miniappSdk";
declare global {
interface Window {
/** The currently mounted mini-app's direct, unsandboxed access point
* onto the shell's ledger/event-log/identity SDK (todo 54 / D10). */
commons?: MiniappSdk;
}
}
/** Thrown when an uploaded mini-app's HTML cannot be mounted, e.g. because
* it fails to parse. Carries a specific, actionable message rather than a
* generic failure, and is always caught at mount time rather than left to
* crash the shell around the mount point. */
export class MiniappMountError extends Error {
constructor(message: string) {
super(message);
this.name = "MiniappMountError";
}
}
function parseMiniappHtml(html: string): Document {
const doc = new DOMParser().parseFromString(html, "application/xhtml+xml");
const parseErrors = doc.getElementsByTagName("parsererror");
if (parseErrors.length > 0) {
const detail = parseErrors[0].textContent?.trim() || "malformed markup";
throw new MiniappMountError(`Mini-app HTML failed to parse: ${detail}`);
}
return doc;
}
/**
* Direct-mount `html` into `container`: parses it, throws
* `MiniappMountError` if it fails to parse, otherwise injects its body
* content as plain DOM nodes, with `sdk` reachable from the mini-app's own
* inline `<script>` content as `window.commons`. `sdk` is wired onto
* `window` before any node is inserted: a `<script>` node carried over via
* `importNode` has no "already started" flag, so appending it into this
* already-connected `container` executes it immediately (same as a real
* browser - no separate re-creation step needed, and one that double-runs
* it).
*/
export function mountMiniapp(
container: HTMLElement,
html: string,
sdk: MiniappSdk,
): void {
const doc = parseMiniappHtml(html);
const source = doc.body ?? doc.documentElement;
window.commons = sdk;
container.innerHTML = "";
for (const node of Array.from(source.childNodes)) {
container.appendChild(document.importNode(node, true));
}
}
export function MountedMiniapp({ record }: { record: StoredMiniappPackage }) {
const containerRef = useRef<HTMLDivElement>(null);
const [mountError, setMountError] = useState<string>();
useEffect(() => {
let cancelled = false;
setMountError(undefined);
async function run() {
try {
await initIdentity();
const [html, sdk] = await Promise.all([
readPackageHtml(record),
buildMiniappSdk(),
]);
if (cancelled) return;
const container = containerRef.current;
if (!container) return;
mountMiniapp(container, html, sdk);
} catch (err) {
if (!cancelled) {
setMountError(err instanceof Error ? err.message : String(err));
}
}
}
run();
return () => {
cancelled = true;
};
}, [record]);
if (mountError) {
return (
<div className={styles.error} role="alert" data-testid="miniapp-mount-error">
{mountError}
</div>
);
}
return (
<div
ref={containerRef}
className={styles.container}
data-testid="miniapp-mount-container"
/>
);
}
+49
View File
@@ -0,0 +1,49 @@
import { beforeEach, describe, expect, it } from "vitest";
import { db } from "../lib/db";
import { append, readAll } from "../lib/eventlog";
import { getPublicKey, init } from "../lib/identity";
import { toAccountId } from "./accountId";
import { buildMiniappSdk } from "./miniappSdk";
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
await init();
});
describe("miniappSdk.buildMiniappSdk", () => {
it("exposes identity.getPublicKey as the real module function", async () => {
const sdk = await buildMiniappSdk();
expect(sdk.identity.getPublicKey).toBe(getPublicKey);
expect(await sdk.identity.getPublicKey()).toEqual(await getPublicKey());
});
it("exposes eventlog.append/readAll as the real module functions", async () => {
const sdk = await buildMiniappSdk();
expect(sdk.eventlog.append).toBe(append);
expect(sdk.eventlog.readAll).toBe(readAll);
const stored = await sdk.eventlog.append({ type: "test.ping" });
const all = await sdk.eventlog.readAll();
expect(all.map((e) => e.id)).toContain(stored.id);
});
it("ledger.getBalance() reflects the real ledger for the local identity's own account", async () => {
const sdk = await buildMiniappSdk();
const accountId = toAccountId(await getPublicKey());
expect(await sdk.ledger.getBalance()).toBe(0);
await sdk.eventlog.append({ type: "wallet.issue", account: accountId, amount: 25 });
expect(await sdk.ledger.getBalance()).toBe(25);
});
it("ledger.getBalance(accountId) reads a different account's balance", async () => {
const sdk = await buildMiniappSdk();
await sdk.eventlog.append({ type: "wallet.issue", account: "other-account", amount: 7 });
expect(await sdk.ledger.getBalance("other-account")).toBe(7);
});
});
+48
View File
@@ -0,0 +1,48 @@
/**
* The shared SDK object exposed directly to a mounted mini-app's own
* script (plan todo 54, draft D10: no sandbox attribute, no postMessage
* isolation boundary, no runtime permission-enforcement layer - a mounted
* mini-app gets the exact same capability any shell code has, for the
* MVP).
*
* `eventlog.append`/`readAll` and `identity.getPublicKey` are the real
* module functions themselves, exposed unwrapped. `ledger.getBalance` is a
* convenience composition, not a wrapper: src/lib/ledger.ts is
* intentionally pure and owns no persistence of its own (balances are
* always a reduction over the event log, never read from storage
* directly), so "what's my balance right now" has to compose the ledger's
* own `computeBalances`/`balanceOf` with the event log's `readAll` - there
* is no `ledger.getBalance` export to merely forward to.
*/
import { append, readAll } from "../lib/eventlog";
import { getPublicKey } from "../lib/identity";
import { balanceOf, computeBalances } from "../lib/ledger";
import { toAccountId } from "./accountId";
export interface MiniappSdk {
ledger: {
getBalance: (accountId?: string) => Promise<number>;
};
eventlog: {
append: typeof append;
readAll: typeof readAll;
};
identity: {
getPublicKey: typeof getPublicKey;
};
}
export async function buildMiniappSdk(): Promise<MiniappSdk> {
const defaultAccountId = toAccountId(await getPublicKey());
return {
ledger: {
getBalance: async (accountId = defaultAccountId) => {
const entries = await readAll();
return balanceOf(computeBalances(entries), accountId);
},
},
eventlog: { append, readAll },
identity: { getPublicKey },
};
}
+12
View File
@@ -4,5 +4,17 @@ export default defineConfig({
test: { test: {
environment: "node", environment: "node",
setupFiles: ["./src/lib/test-setup.ts"], setupFiles: ["./src/lib/test-setup.ts"],
// happy-dom disables JS evaluation by default (VM-based script
// execution risk). Tests opting into the happy-dom environment need
// real <script> execution to exercise todo 54's actual direct-mount
// design (no sandbox, no isolation) rather than a stubbed-out one.
environmentOptions: {
happyDOM: {
settings: {
enableJavaScriptEvaluation: true,
suppressInsecureJavaScriptEnvironmentWarning: true,
},
},
},
}, },
}); });