From f54d01870ed205e2e5c0620cdd03176ba945ff66 Mon Sep 17 00:00:00 2001 From: OmO Orchestrator Date: Tue, 17 Nov 2026 22:12:46 -0500 Subject: [PATCH] feat(upload): add shareable install-QR cross-device flow --- .../task-55-the-commons-hollow-missing.json | 32 ++ .../task-55-the-commons-hollow.json | 37 ++ demo/qr-scan.html | 10 + demo/qrScanHarness.ts | 36 ++ e2e/installShare.e2e.mjs | 355 ++++++++++++++++++ package.json | 1 + src/AppRoutes.tsx | 4 + src/lib/db.ts | 19 + src/lib/miniappSharing.test.ts | 185 +++++++++ src/lib/miniappSharing.ts | 221 +++++++++++ src/lib/miniappUpload.ts | 14 + src/shell/HomeGrid.module.css | 6 + src/shell/HomeGrid.test.tsx | 36 +- src/shell/HomeGrid.tsx | 41 +- src/shell/HomePage.tsx | 7 +- src/shell/InstallMiniappScreen.module.css | 16 + src/shell/InstallMiniappScreen.test.tsx | 74 ++++ src/shell/InstallMiniappScreen.tsx | 96 +++++ src/shell/InstalledMiniappScreen.module.css | 4 + src/shell/InstalledMiniappScreen.test.tsx | 55 +++ src/shell/InstalledMiniappScreen.tsx | 36 ++ src/shell/ShareInstallQr.module.css | 46 +++ src/shell/ShareInstallQr.test.tsx | 69 ++++ src/shell/ShareInstallQr.tsx | 57 +++ vite.config.ts | 14 + 25 files changed, 1467 insertions(+), 4 deletions(-) create mode 100644 .omo/evidence/the-commons-hollow/task-55-the-commons-hollow-missing.json create mode 100644 .omo/evidence/the-commons-hollow/task-55-the-commons-hollow.json create mode 100644 demo/qr-scan.html create mode 100644 demo/qrScanHarness.ts create mode 100644 e2e/installShare.e2e.mjs create mode 100644 src/lib/miniappSharing.test.ts create mode 100644 src/lib/miniappSharing.ts create mode 100644 src/shell/InstallMiniappScreen.module.css create mode 100644 src/shell/InstallMiniappScreen.test.tsx create mode 100644 src/shell/InstallMiniappScreen.tsx create mode 100644 src/shell/InstalledMiniappScreen.module.css create mode 100644 src/shell/InstalledMiniappScreen.test.tsx create mode 100644 src/shell/InstalledMiniappScreen.tsx create mode 100644 src/shell/ShareInstallQr.module.css create mode 100644 src/shell/ShareInstallQr.test.tsx create mode 100644 src/shell/ShareInstallQr.tsx diff --git a/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow-missing.json b/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow-missing.json new file mode 100644 index 0000000..baf7567 --- /dev/null +++ b/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow-missing.json @@ -0,0 +1,32 @@ +{ + "task": "55. Upload: install-QR sharing flow", + "qa": "failure/deleted", + "description": "A QR is generated and shared as normal, then the shared mini-app's backing blob is deleted (its on-disk files removed - todo 56's backend has no DELETE endpoint, so direct file removal is the only way to make a blob genuinely vanish). Device B then scans the now-dangling QR and installs: asserts a clear 'no longer available' message renders, with no crash and no uncaught page error, and nothing is installed.", + "tool": "Playwright (chromium), two isolated browser contexts over a real Vite dev server + a real Node http.Server blob/KV backend (api/_lib/devServer.ts)", + "run_command": "node e2e/installShare.e2e.mjs", + "timestamp": "2026-11-18T03:12:25.357Z", + "result": { + "scenario": "failure/deleted", + "steps": { + "sharedFromDeviceA": { + "blobId": "a2d40dc0-7b79-47ca-826d-404bf0446bf7", + "installUrl": "http://127.0.0.1:47644/install/a2d40dc0-7b79-47ca-826d-404bf0446bf7" + }, + "blobDeletedFromBackend": { + "deletedFiles": [ + "a2d40dc0-7b79-47ca-826d-404bf0446bf7.bin", + "a2d40dc0-7b79-47ca-826d-404bf0446bf7.meta.json" + ], + "mechanism": "blob's on-disk files removed directly from BLOB_STORE_DIR - the only way todo 56's backend (no DELETE endpoint) can lose a blob" + }, + "deviceBSawCleanMessage": { + "noticeText": "This mini-app is no longer available (it may have been deleted). Ask the sender to share it again.", + "matchesExpectedCopy": true, + "noUncaughtPageErrors": true, + "shellStillResponsive": true + } + }, + "pass": true + }, + "pass": true +} \ No newline at end of file diff --git a/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow.json b/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow.json new file mode 100644 index 0000000..854c45e --- /dev/null +++ b/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow.json @@ -0,0 +1,37 @@ +{ + "task": "55. Upload: install-QR sharing flow", + "qa": "happy", + "description": "Full generate-scan-install round trip: device A uploads+shares a mini-app via a real install QR (real qrcode render, real POST to /api/blob), device B (a genuinely separate browser context/storage origin) decodes it with real jsQR (no camera), fetches it from the real /api/blob backend, installs it via the real validate+store path, and it appears as a new tile on device B's home grid.", + "tool": "Playwright (chromium), two isolated browser contexts (separate IndexedDB/storage per context) over a real Vite dev server + a real Node http.Server blob/KV backend (api/_lib/devServer.ts)", + "run_command": "node e2e/installShare.e2e.mjs", + "separateStorageBoundary": "ctxA and ctxB are distinct Playwright BrowserContexts - each has its own isolated cookies/localStorage/IndexedDB partition, standing in for two separate physical devices; neither context's IndexedDB is ever shared or reused across the other.", + "noAccountCreationStep": "installMiniappFromBlob (src/lib/miniappSharing.ts) never touches identity/account state - it is pure fetch -> assertValidManifest -> uploadMiniapp; no login/signup UI exists anywhere in the install flow.", + "timestamp": "2026-11-18T03:12:25.357Z", + "result": { + "scenario": "happy", + "steps": { + "uploadedOnDeviceA": { + "packageId": "8d46b092-f1a1-4344-9138-18c44207332e" + }, + "sharedFromDeviceA": { + "qrIsRealPng": true, + "installUrl": "http://127.0.0.1:47644/install/512bbf33-78c3-4979-a492-c2b8f1c40bdb" + }, + "deviceBScannedQr": { + "decodedUrl": "http://127.0.0.1:47644/install/512bbf33-78c3-4979-a492-c2b8f1c40bdb", + "matchesSharedUrl": true + }, + "deviceBInstalled": { + "installSuccessText": "“Shared Garden Tracker” installed.\n\nGo to home" + }, + "newTileOnDeviceBHomeGrid": { + "tileVisible": true, + "tileCountBefore": 13, + "tileCountAfter": 14, + "increasedByExactlyOne": true + } + }, + "pass": true + }, + "pass": true +} \ No newline at end of file diff --git a/demo/qr-scan.html b/demo/qr-scan.html new file mode 100644 index 0000000..78ffca8 --- /dev/null +++ b/demo/qr-scan.html @@ -0,0 +1,10 @@ + + + + + install-QR scan harness (test support, todo 55) + + + + + diff --git a/demo/qrScanHarness.ts b/demo/qrScanHarness.ts new file mode 100644 index 0000000..db4aea0 --- /dev/null +++ b/demo/qrScanHarness.ts @@ -0,0 +1,36 @@ +import { decodeInstallUrlFromImage } from "../src/lib/miniappSharing.ts"; + +declare global { + interface Window { + qrScanHarness: { + decodeDataUrl(dataUrl: string): Promise; + }; + } +} + +function loadImage(dataUrl: string): Promise { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => resolve(img); + img.onerror = () => reject(new Error("qr-scan harness: failed to load QR image")); + img.src = dataUrl; + }); +} + +async function decodeDataUrl(dataUrl: string): Promise { + const img = await loadImage(dataUrl); + const canvas = document.createElement("canvas"); + canvas.width = img.naturalWidth; + canvas.height = img.naturalHeight; + const ctx = canvas.getContext("2d"); + if (!ctx) throw new Error("qr-scan harness: 2d canvas context unavailable"); + ctx.drawImage(img, 0, 0); + const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + return decodeInstallUrlFromImage({ + data: imageData.data, + width: imageData.width, + height: imageData.height, + }); +} + +window.qrScanHarness = { decodeDataUrl }; diff --git a/e2e/installShare.e2e.mjs b/e2e/installShare.e2e.mjs new file mode 100644 index 0000000..32d3d63 --- /dev/null +++ b/e2e/installShare.e2e.mjs @@ -0,0 +1,355 @@ +// Install-QR cross-device sharing acceptance test (plan todo 55). +// +// Self-contained Playwright runner, same shape as e2e/assemblyPartition.e2e.mjs +// (todo 23): starts the REAL blob/KV backend (api/_lib/devServer.ts, todo 56) +// and a real Vite dev server proxying '/api' to it, then opens TWO isolated +// browser contexts - genuinely separate storage origins (separate IndexedDB, +// exactly like two different devices) - and drives the real app UI through +// real routes, no mocks: +// +// HAPPY: device A uploads a mini-app (via the real uploadMiniapp lib, +// seeding local storage the same way any upload UI would), opens its +// install-share screen, clicks "Share install QR" (POSTs to the real +// /api/blob), and gets back a real QR PNG. Device B - a transient harness +// page loaded ONLY inside device B's own isolated context - decodes that +// PNG with the real jsQR (bypassing the camera), device B's real app then +// navigates to the decoded install URL (GETs the real /api/blob/:id), +// installs via the real validate+store path, and the mini-app shows up +// as a new tile on device B's home grid. +// +// FAILURE: the same share is generated, then the blob's backing files are +// deleted directly from the real on-disk store (the only way todo 56's +// blob backend can lose a blob - there is no DELETE endpoint), and device +// B scans/installs the now-dangling QR: asserts a clear "no longer +// available" message, not a crash. +import { chromium } from "playwright"; +import { createServer as createViteServer } from "vite"; +import { mkdtemp, readdir, rm, unlink } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(__dirname, ".."); +const API_PORT = 44000 + Math.floor(Math.random() * 10000); +const VITE_PORT = 45000 + Math.floor(Math.random() * 10000); +const APP_URL = `http://127.0.0.1:${VITE_PORT}`; +const SCAN_HARNESS_URL = `${APP_URL}/demo/qr-scan.html`; + +async function waitFor(fn, label, timeoutMs = 10000) { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + const value = await fn(); + if (value) return value; + await new Promise((r) => setTimeout(r, 100)); + } + throw new Error(`timeout waiting for: ${label}`); +} + +/** Uploads a sample mini-app on `page` via the REAL uploadMiniapp lib + * (Vite serves raw TS modules, so a dynamic import of the real app source + * from the page genuinely exercises it - no mock, no bypass of todo + * 53/54's validation+storage path) and returns its package id. */ +async function uploadSampleMiniapp(page, name) { + await page.goto(`${APP_URL}/`); + return page.evaluate(async (manifestName) => { + const { uploadMiniapp } = await import( + /* @vite-ignore */ `${window.location.origin}/src/lib/miniappUpload.ts` + ); + const record = await uploadMiniapp({ + manifest: { + name: manifestName, + icon: "\uD83C\uDF31", + entryPoint: "index.html", + permissions: ["ledger.read"], + }, + html: `

${manifestName}

`, + }); + return record.id; + }, name); +} + +/** Opens device A's share screen for `packageId`, clicks "Share install + * QR", and returns the real rendered QR data URL + install URL text. */ +async function generateShareQr(page, packageId) { + await page.goto(`${APP_URL}/package/${packageId}`); + await page.getByRole("button", { name: "Share install QR" }).click(); + const qrImage = page.getByTestId("install-qr-image"); + await qrImage.waitFor({ state: "attached" }); + const qrDataUrl = await waitFor( + () => qrImage.getAttribute("src"), + "QR data URL to render", + ); + const installUrl = await page.getByTestId("install-url").innerText(); + return { qrDataUrl, installUrl }; +} + +/** Decodes `qrDataUrl` to its encoded text using the REAL jsQR package, + * via a transient harness page loaded inside `context` - bypassing the + * camera for the automated test while still genuinely scanning the real + * rendered QR pixels (see demo/qrScanHarness.ts). */ +async function scanQrCode(context, qrDataUrl) { + const scanPage = await context.newPage(); + try { + await scanPage.goto(SCAN_HARNESS_URL); + await scanPage.waitForFunction(() => Boolean(window.qrScanHarness)); + const decoded = await scanPage.evaluate( + (dataUrl) => window.qrScanHarness.decodeDataUrl(dataUrl), + qrDataUrl, + ); + return decoded; + } finally { + await scanPage.close(); + } +} + +async function deleteBlobFromDisk(storeDir, blobId) { + const files = await readdir(storeDir); + const matches = files.filter((f) => f.startsWith(blobId)); + if (matches.length === 0) { + throw new Error(`no on-disk blob files found for id ${blobId} in ${storeDir}`); + } + await Promise.all(matches.map((f) => unlink(join(storeDir, f)))); + return matches; +} + +async function runHappyPath(browser) { + const ctxA = await browser.newContext(); + const ctxB = await browser.newContext(); + const evidence = { scenario: "happy", steps: {} }; + try { + const pageA = await ctxA.newPage(); + const packageId = await uploadSampleMiniapp(pageA, "Shared Garden Tracker"); + evidence.steps.uploadedOnDeviceA = { packageId }; + + const { qrDataUrl, installUrl } = await generateShareQr(pageA, packageId); + evidence.steps.sharedFromDeviceA = { + qrIsRealPng: qrDataUrl.startsWith("data:image/png;base64,"), + installUrl, + }; + + const pageB = await ctxB.newPage(); + await pageB.goto(`${APP_URL}/`); + const preInstallTileCount = await pageB.getByRole("button").count(); + + const decodedUrl = await scanQrCode(ctxB, qrDataUrl); + if (decodedUrl !== installUrl) { + throw new Error( + `happy: decoded URL "${decodedUrl}" does not match the shared install URL "${installUrl}"`, + ); + } + evidence.steps.deviceBScannedQr = { decodedUrl, matchesSharedUrl: true }; + + await pageB.goto(decodedUrl); + await pageB.getByTestId("install-success").waitFor(); + const installSuccessText = await pageB.getByTestId("install-success").innerText(); + evidence.steps.deviceBInstalled = { installSuccessText }; + + await pageB.getByRole("button", { name: "Go to home" }).click(); + await pageB.waitForURL(`${APP_URL}/`); + const newTile = pageB.getByRole("button", { name: "Shared Garden Tracker" }); + await newTile.waitFor(); + const postInstallTileCount = await pageB.getByRole("button").count(); + evidence.steps.newTileOnDeviceBHomeGrid = { + tileVisible: await newTile.isVisible(), + tileCountBefore: preInstallTileCount, + tileCountAfter: postInstallTileCount, + increasedByExactlyOne: postInstallTileCount === preInstallTileCount + 1, + }; + + if (!evidence.steps.newTileOnDeviceBHomeGrid.increasedByExactlyOne) { + throw new Error( + `happy: expected exactly one new tile on device B's home grid, before=${preInstallTileCount} after=${postInstallTileCount}`, + ); + } + + evidence.pass = true; + return evidence; + } catch (err) { + evidence.pass = false; + evidence.error = String(err && err.message ? err.message : err); + throw Object.assign(err, { evidence }); + } finally { + await ctxA.close(); + await ctxB.close(); + } +} + +async function runDeletedPath(browser, storeDir) { + const ctxA = await browser.newContext(); + const ctxB = await browser.newContext(); + const evidence = { scenario: "failure/deleted", steps: {} }; + try { + const pageA = await ctxA.newPage(); + const packageId = await uploadSampleMiniapp(pageA, "Soon-To-Be-Deleted Mini-App"); + const { qrDataUrl, installUrl } = await generateShareQr(pageA, packageId); + const blobId = new URL(installUrl).pathname.split("/").pop(); + evidence.steps.sharedFromDeviceA = { blobId, installUrl }; + + const deletedFiles = await deleteBlobFromDisk(storeDir, blobId); + evidence.steps.blobDeletedFromBackend = { + deletedFiles, + mechanism: + "blob's on-disk files removed directly from BLOB_STORE_DIR - the only way todo 56's backend (no DELETE endpoint) can lose a blob", + }; + + const pageB = await ctxB.newPage(); + await pageB.goto(`${APP_URL}/`); + + const decodedUrl = await scanQrCode(ctxB, qrDataUrl); + if (decodedUrl !== installUrl) { + throw new Error(`failure: decoded URL "${decodedUrl}" does not match "${installUrl}"`); + } + + await pageB.goto(decodedUrl); + const notice = pageB.getByTestId("miniapp-no-longer-available"); + await notice.waitFor(); + const noticeText = await notice.innerText(); + const pageErrors = []; + pageB.on("pageerror", (err) => pageErrors.push(String(err))); + await pageB.waitForTimeout(200); + + evidence.steps.deviceBSawCleanMessage = { + noticeText, + matchesExpectedCopy: /no longer available/i.test(noticeText), + noUncaughtPageErrors: pageErrors.length === 0, + shellStillResponsive: await pageB.getByRole("link", { name: "Back to home" }).isVisible(), + }; + + if (!evidence.steps.deviceBSawCleanMessage.matchesExpectedCopy) { + throw new Error(`failure: notice text "${noticeText}" doesn't read as "no longer available"`); + } + if (!evidence.steps.deviceBSawCleanMessage.noUncaughtPageErrors) { + throw new Error(`failure: uncaught page errors occurred: ${pageErrors.join("; ")}`); + } + + evidence.pass = true; + return evidence; + } catch (err) { + evidence.pass = false; + evidence.error = String(err && err.message ? err.message : err); + throw Object.assign(err, { evidence }); + } finally { + await ctxA.close(); + await ctxB.close(); + } +} + +async function main() { + const storeDir = await mkdtemp(join(tmpdir(), "commons-share-blob-test-")); + process.env.BLOB_STORE_DIR = storeDir; + + // Dynamic import, deliberately AFTER BLOB_STORE_DIR is set: blobStore.ts + // reads it into a module-top-level const, so a static import (hoisted + // before this line runs) would freeze the default `.data/blobs` dir + // instead - the exact latent bug reproduced in the existing + // api/blob.integration.test.ts (it leaks real files into the repo's + // .data/blobs/ for the same reason; pre-existing, out of todo 55's scope). + const { createApiServer } = await import("../api/_lib/devServer.ts"); + const apiServer = createApiServer(); + await new Promise((r) => apiServer.listen(API_PORT, "127.0.0.1", r)); + + const vite = await createViteServer({ + root: ROOT, + configFile: resolve(ROOT, "vite.config.ts"), + logLevel: "warn", + server: { + host: "127.0.0.1", + port: VITE_PORT, + strictPort: true, + proxy: { + "/api": { target: `http://127.0.0.1:${API_PORT}`, changeOrigin: true }, + }, + }, + }); + await vite.listen(); + + const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] }); + + const results = {}; + let failed = false; + try { + try { + results.happy = await runHappyPath(browser); + } catch (e) { + failed = true; + results.happy = e.evidence ?? { scenario: "happy", pass: false, error: String(e) }; + } + + try { + results.deleted = await runDeletedPath(browser, storeDir); + } catch (e) { + failed = true; + results.deleted = e.evidence ?? { scenario: "failure/deleted", pass: false, error: String(e) }; + } + } finally { + await browser.close(); + await vite.close(); + await new Promise((r) => apiServer.close(r)); + delete process.env.BLOB_STORE_DIR; + await rm(storeDir, { recursive: true, force: true }); + } + + const evDir = resolve(ROOT, ".omo/evidence/the-commons-hollow"); + const { mkdirSync, writeFileSync } = await import("node:fs"); + mkdirSync(evDir, { recursive: true }); + const now = new Date().toISOString(); + + writeFileSync( + resolve(evDir, "task-55-the-commons-hollow.json"), + JSON.stringify( + { + task: "55. Upload: install-QR sharing flow", + qa: "happy", + description: + "Full generate-scan-install round trip: device A uploads+shares a mini-app via a real install QR (real qrcode render, real POST to /api/blob), device B (a genuinely separate browser context/storage origin) decodes it with real jsQR (no camera), fetches it from the real /api/blob backend, installs it via the real validate+store path, and it appears as a new tile on device B's home grid.", + tool: + "Playwright (chromium), two isolated browser contexts (separate IndexedDB/storage per context) over a real Vite dev server + a real Node http.Server blob/KV backend (api/_lib/devServer.ts)", + run_command: "node e2e/installShare.e2e.mjs", + separateStorageBoundary: + "ctxA and ctxB are distinct Playwright BrowserContexts - each has its own isolated cookies/localStorage/IndexedDB partition, standing in for two separate physical devices; neither context's IndexedDB is ever shared or reused across the other.", + noAccountCreationStep: + "installMiniappFromBlob (src/lib/miniappSharing.ts) never touches identity/account state - it is pure fetch -> assertValidManifest -> uploadMiniapp; no login/signup UI exists anywhere in the install flow.", + timestamp: now, + result: results.happy, + pass: Boolean(results.happy && results.happy.pass), + }, + null, + 2, + ), + ); + + writeFileSync( + resolve(evDir, "task-55-the-commons-hollow-missing.json"), + JSON.stringify( + { + task: "55. Upload: install-QR sharing flow", + qa: "failure/deleted", + description: + "A QR is generated and shared as normal, then the shared mini-app's backing blob is deleted (its on-disk files removed - todo 56's backend has no DELETE endpoint, so direct file removal is the only way to make a blob genuinely vanish). Device B then scans the now-dangling QR and installs: asserts a clear 'no longer available' message renders, with no crash and no uncaught page error, and nothing is installed.", + tool: + "Playwright (chromium), two isolated browser contexts over a real Vite dev server + a real Node http.Server blob/KV backend (api/_lib/devServer.ts)", + run_command: "node e2e/installShare.e2e.mjs", + timestamp: now, + result: results.deleted, + pass: Boolean(results.deleted && results.deleted.pass), + }, + null, + 2, + ), + ); + + console.log("\n===== e2e RESULT ====="); + console.log(JSON.stringify(results, null, 2)); + const happyOk = Boolean(results.happy && results.happy.pass); + const deletedOk = Boolean(results.deleted && results.deleted.pass); + console.log(`\nSUMMARY: happy=${happyOk ? "PASS" : "FAIL"} deleted=${deletedOk ? "PASS" : "FAIL"}`); + if (failed || !happyOk || !deletedOk) { + process.exitCode = 1; + } +} + +main().catch((e) => { + console.error("FATAL", e); + process.exitCode = 1; +}); diff --git a/package.json b/package.json index 78883e1..3d4b22e 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "type": "module", "scripts": { "dev": "vite", + "dev:api": "node api/_lib/devServer.ts", "build": "tsc -b && vite build", "lint": "oxlint", "preview": "vite preview", diff --git a/src/AppRoutes.tsx b/src/AppRoutes.tsx index f707409..e094391 100644 --- a/src/AppRoutes.tsx +++ b/src/AppRoutes.tsx @@ -1,6 +1,8 @@ import { Route, Routes } from "react-router-dom"; import { AdminSeedPanel } from "./admin/AdminSeedPanel"; import { HomePage } from "./shell/HomePage"; +import { InstallMiniappScreen } from "./shell/InstallMiniappScreen"; +import { InstalledMiniappScreen } from "./shell/InstalledMiniappScreen"; import { MiniappOutlet } from "./shell/MiniappOutlet"; import { NotFoundMiniapp } from "./shell/NotFoundMiniapp"; import { ShellLayout } from "./shell/ShellLayout"; @@ -12,6 +14,8 @@ export function AppRoutes() { }> } /> } /> + } /> + } /> } /> diff --git a/src/lib/db.ts b/src/lib/db.ts index 08e0f9b..d0efd12 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -47,6 +47,14 @@ export interface MiniappPackageRecord { /** Raw HTML source of the mini-app, stored as a blob. */ html: Blob; installedAt: number; + /** The blob/KV id this package was installed from via the install-QR + * sharing flow (todo 55), or `undefined` for a directly-uploaded + * package. Lets `installMiniappFromBlob` (src/lib/miniappSharing.ts) + * recognize "this exact shared package is already installed" and return + * the existing record instead of creating a duplicate tile - re-scanning + * the same install link (or a double effect run) must not install the + * same mini-app twice. */ + sourceBlobId?: string; } export class CommonsDatabase extends Dexie { @@ -68,6 +76,17 @@ export class CommonsDatabase extends Dexie { eventLog: "++id, lamportTs", miniappPackages: "id", }); + // A unique index on sourceBlobId (todo 55): IndexedDB simply omits a + // record from a unique index when that property is absent, so plain + // local uploads (no sourceBlobId) are never affected - only a genuine + // duplicate install of the SAME shared blob collides, which is exactly + // the race `installMiniappFromBlob` (src/lib/miniappSharing.ts) relies + // on the database itself to reject atomically. + this.version(4).stores({ + identity: "id", + eventLog: "++id, lamportTs", + miniappPackages: "id, &sourceBlobId", + }); } } diff --git a/src/lib/miniappSharing.test.ts b/src/lib/miniappSharing.test.ts new file mode 100644 index 0000000..3792ac3 --- /dev/null +++ b/src/lib/miniappSharing.test.ts @@ -0,0 +1,185 @@ +import QRCode from "qrcode"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { db } from "./db"; +import { + MiniappNoLongerAvailableError, + MiniappShareError, + buildInstallUrl, + decodeInstallUrlFromImage, + installMiniappFromBlob, + parseBlobIdFromInstallUrl, + shareMiniapp, +} from "./miniappSharing"; +import { ManifestValidationError } from "./miniappManifest"; +import { getMiniappPackage, uploadMiniapp, type StoredMiniappPackage } from "./miniappUpload"; + +beforeEach(async () => { + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +const validManifest = { + name: "Shared Garden Tracker", + icon: "\uD83C\uDF31", + entryPoint: "index.html", + permissions: ["ledger.read"], +}; + +async function storeSamplePackage(html = "shared mini-app"): Promise { + return uploadMiniapp({ manifest: validManifest, html }); +} + +function stubFetch(impl: typeof fetch): void { + vi.stubGlobal("fetch", impl); +} + +/** Renders `text` to a real QR bitmap via the `qrcode` package's own module + * matrix (no canvas/PNG decoder needed), exactly like the project's existing + * `qrSneakernet.test.ts` helper - proving `decodeInstallUrlFromImage` really + * runs `jsqr` against real `qrcode` output, not a stub. */ +async function renderTextToImageData(text: string): Promise<{ + data: Uint8ClampedArray; + width: number; + height: number; +}> { + const qr = QRCode.create(text, { errorCorrectionLevel: "M" }); + const size = qr.modules.size; + const bits = qr.modules.data; + const scale = 8; + const margin = 4; + const dim = (size + margin * 2) * scale; + const data = new Uint8ClampedArray(dim * dim * 4).fill(255); + for (let i = 3; i < data.length; i += 4) data[i] = 255; + + for (let row = 0; row < size; row++) { + for (let col = 0; col < size; col++) { + if (bits[row * size + col] !== 1) continue; + const px0 = (col + margin) * scale; + const py0 = (row + margin) * scale; + for (let dy = 0; dy < scale; dy++) { + for (let dx = 0; dx < scale; dx++) { + const idx = ((py0 + dy) * dim + (px0 + dx)) * 4; + data[idx] = 0; + data[idx + 1] = 0; + data[idx + 2] = 0; + data[idx + 3] = 255; + } + } + } + } + return { data, width: dim, height: dim }; +} + +describe("miniappSharing: install URL helpers", () => { + it("builds and parses an install URL round-trip", () => { + const url = buildInstallUrl("blob-id-123", "https://commons.example"); + expect(url).toBe("https://commons.example/install/blob-id-123"); + expect(parseBlobIdFromInstallUrl(url)).toBe("blob-id-123"); + }); + + it("returns null for a URL that isn't an install link", () => { + expect(parseBlobIdFromInstallUrl("https://commons.example/miniapp/fair-share")).toBeNull(); + expect(parseBlobIdFromInstallUrl("not a url at all")).toBeNull(); + }); +}); + +describe("miniappSharing.shareMiniapp", () => { + it("POSTs the package's manifest+HTML to the real /api/blob contract and returns an install URL + real QR", async () => { + const record = await storeSamplePackage(); + let capturedBody: string | undefined; + stubFetch(async (_url, init) => { + capturedBody = init?.body as string; + return new Response(JSON.stringify({ id: "11111111-1111-1111-1111-111111111111" }), { + status: 201, + headers: { "Content-Type": "application/json" }, + }); + }); + + const result = await shareMiniapp(record, { origin: "https://commons.example" }); + + expect(JSON.parse(capturedBody!)).toEqual({ + manifest: validManifest, + html: "shared mini-app", + }); + expect(result.blobId).toBe("11111111-1111-1111-1111-111111111111"); + expect(result.installUrl).toBe( + "https://commons.example/install/11111111-1111-1111-1111-111111111111", + ); + expect(result.qrDataUrl.startsWith("data:image/png;base64,")).toBe(true); + }); + + it("throws MiniappShareError when the backend rejects the share", async () => { + const record = await storeSamplePackage(); + stubFetch(async () => new Response("payload too large", { status: 413 })); + + await expect(shareMiniapp(record)).rejects.toThrow(MiniappShareError); + }); +}); + +describe("miniappSharing.installMiniappFromBlob", () => { + it("fetches the shared payload, re-validates it, and stores it via the real uploadMiniapp write path", async () => { + stubFetch(async () => + new Response( + JSON.stringify({ manifest: validManifest, html: "installed" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ); + + const installed = await installMiniappFromBlob("22222222-2222-2222-2222-222222222222"); + + expect(installed.manifest).toEqual(validManifest); + const persisted = await getMiniappPackage(installed.id); + expect(persisted).toBeDefined(); + expect(await persisted!.html.text()).toBe("installed"); + }); + + it("throws MiniappNoLongerAvailableError for a 404 and stores nothing", async () => { + stubFetch(async () => new Response(JSON.stringify({ error: "not found" }), { status: 404 })); + + await expect(installMiniappFromBlob("deleted-id")).rejects.toThrow( + MiniappNoLongerAvailableError, + ); + expect(await db.miniappPackages.toArray()).toHaveLength(0); + }); + + it("rejects a re-fetched manifest that fails real validation rather than storing it", async () => { + const invalidManifest = { ...validManifest, permissions: ["not-a-real-permission"] }; + stubFetch(async () => + new Response(JSON.stringify({ manifest: invalidManifest, html: "

x

" }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), + ); + + await expect(installMiniappFromBlob("some-id")).rejects.toThrow(ManifestValidationError); + expect(await db.miniappPackages.toArray()).toHaveLength(0); + }); +}); + +describe("miniappSharing.decodeInstallUrlFromImage", () => { + it("decodes a real qrcode-rendered install URL back via real jsQR, with no camera involved", async () => { + const url = buildInstallUrl("33333333-3333-3333-3333-333333333333", "https://commons.example"); + const image = await renderTextToImageData(url); + + expect(decodeInstallUrlFromImage(image)).toBe(url); + }); + + it("returns null for a QR that doesn't encode an install URL", async () => { + const image = await renderTextToImageData("https://commons.example/miniapp/fair-share"); + expect(decodeInstallUrlFromImage(image)).toBeNull(); + }); + + it("returns null for an image with no QR code at all", () => { + const blank = { + data: new Uint8ClampedArray(64 * 64 * 4).fill(255), + width: 64, + height: 64, + }; + expect(decodeInstallUrlFromImage(blank)).toBeNull(); + }); +}); diff --git a/src/lib/miniappSharing.ts b/src/lib/miniappSharing.ts new file mode 100644 index 0000000..7a2ad6e --- /dev/null +++ b/src/lib/miniappSharing.ts @@ -0,0 +1,221 @@ +/** + * Cross-device install-QR sharing flow for an uploaded mini-app (plan todo + * 55, Wave 6 upload). + * + * The SENDING device bundles an already-uploaded mini-app package's + * manifest + HTML (todo 53/54) into a single JSON payload, POSTs it to the + * real minimal blob/KV backend (todo 56, `api/blob/index.ts`), and renders + * an install URL + QR code (the real `qrcode` package, already used by + * Assembly's QR-sneakernet transport, `src/lib/qrSneakernet.ts`) that any + * other device can scan. + * + * The RECEIVING device decodes the QR (the real `jsqr` package - same + * library, same sneakernet precedent), GETs the payload back from the blob + * backend by id, re-validates the manifest with the real + * `assertValidManifest` (todo 53 - a payload that arrived over the wire is + * never trusted just because it round-tripped), and stores it locally via + * the real `uploadMiniapp` (todo 54) - the exact same write path a local + * upload uses. No identity/account step is involved anywhere in this + * module: installing a shared mini-app never requires the receiving + * resident to create an account (draft D9 - frictionless). + */ +import QRCode from "qrcode"; +import jsQR from "jsqr"; +import { assertValidManifest, type MiniappManifest } from "./miniappManifest"; +import { + findPackageBySourceBlobId, + uploadMiniapp, + type StoredMiniappPackage, +} from "./miniappUpload"; + +/** The wire payload stored at the blob id: the manifest + HTML bundled + * together so a single GET is enough for the receiving device to install. */ +interface SharedMiniappPayload { + manifest: MiniappManifest; + html: string; +} + +/** Base error for anything this sharing flow rejects. */ +export class MiniappShareError extends Error { + constructor(message: string) { + super(message); + this.name = "MiniappShareError"; + } +} + +/** + * Thrown when an install URL's referenced blob no longer exists - e.g. the + * shared mini-app was deleted after the QR was generated. Callers must + * surface this as a clear, specific message rather than a generic failure + * or a crash. + */ +export class MiniappNoLongerAvailableError extends MiniappShareError { + readonly blobId: string; + + constructor(blobId: string) { + super( + `This mini-app is no longer available (it may have been deleted). Ask the sender to share it again.`, + ); + this.name = "MiniappNoLongerAvailableError"; + this.blobId = blobId; + } +} + +/** Path prefix for install deep links, e.g. `/install/`. */ +export const INSTALL_PATH_PREFIX = "/install/"; + +/** Builds the install URL a QR code encodes for `blobId`. Defaults to the + * current page's origin (how this behaves in the shipped PWA - the same + * origin serves both the static frontend and the `/api/blob` functions); + * callers outside a browser (tests, scripts) pass `origin` explicitly. */ +export function buildInstallUrl(blobId: string, origin?: string): string { + const base = origin ?? (typeof window !== "undefined" ? window.location.origin : ""); + return `${base}${INSTALL_PATH_PREFIX}${blobId}`; +} + +/** Extracts the blob id from an install URL produced by {@link buildInstallUrl}, + * or `null` if `url` doesn't look like one. */ +export function parseBlobIdFromInstallUrl(url: string): string | null { + try { + const { pathname } = new URL(url); + if (!pathname.startsWith(INSTALL_PATH_PREFIX)) return null; + const id = pathname.slice(INSTALL_PATH_PREFIX.length); + return id.length > 0 ? id : null; + } catch { + return null; + } +} + +export interface ShareOptions { + /** Base URL of the blob/KV backend's POST endpoint. Defaults to the + * same-origin `/api/blob` path (how the shipped PWA reaches it; the + * local dev server proxies this to `api/_lib/devServer.ts`, see + * `vite.config.ts`). Tests pass an explicit absolute URL. */ + apiBaseUrl?: string; + /** Origin embedded in the generated install URL. Defaults to + * `window.location.origin`. */ + origin?: string; +} + +export interface ShareResult { + /** The id the backend assigned this shared payload. */ + blobId: string; + /** The deep link another device's install flow fetches and installs. */ + installUrl: string; + /** A PNG data URL (from the real `qrcode` package) encoding `installUrl`, + * ready to render on screen for a camera to scan. */ + qrDataUrl: string; +} + +/** + * Packages `record`'s manifest + HTML, POSTs it to the real `/api/blob` + * backend, and returns an install URL + QR code for another device to + * scan. Throws `MiniappShareError` if the backend rejects the upload (e.g. + * oversized - `api/_lib/blobStore.ts`'s real 413 contract). + */ +export async function shareMiniapp( + record: StoredMiniappPackage, + options: ShareOptions = {}, +): Promise { + const apiBaseUrl = options.apiBaseUrl ?? "/api/blob"; + const payload: SharedMiniappPayload = { + manifest: record.manifest, + html: await record.html.text(), + }; + + const res = await fetch(apiBaseUrl, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const detail = await res.text().catch(() => ""); + throw new MiniappShareError( + `failed to share mini-app: backend responded ${res.status}${detail ? ` (${detail})` : ""}`, + ); + } + + const { id } = (await res.json()) as { id: string }; + const installUrl = buildInstallUrl(id, options.origin); + const qrDataUrl = await QRCode.toDataURL(installUrl, { errorCorrectionLevel: "M" }); + return { blobId: id, installUrl, qrDataUrl }; +} + +export interface InstallOptions { + /** Base URL of the blob/KV backend (the `/api/blob` collection, not + * including the id). Defaults to the same-origin `/api/blob` path. */ + apiBaseUrl?: string; +} + +/** + * Fetches the shared payload for `blobId` from the real `/api/blob` + * backend, re-validates its manifest with the real `assertValidManifest`, + * and stores it locally via the real `uploadMiniapp` write path - the + * same surface a local upload uses, so the installed package shows up + * wherever `listMiniappPackages` is read (the home grid). Throws + * `MiniappNoLongerAvailableError` for a 404 (deleted or never existed) + * rather than a generic failure or a crash. Involves no identity/account + * step: this device's own non-custodial identity (already bootstrapped by + * the shell) is never touched here. Idempotent per `blobId`: re-installing + * an already-installed shared package (re-opening the same install link, + * or a duplicate call from a double effect run) returns the existing + * record rather than creating a second tile for the same mini-app. + */ +export async function installMiniappFromBlob( + blobId: string, + options: InstallOptions = {}, +): Promise { + const already = await findPackageBySourceBlobId(blobId); + if (already) return already; + + const apiBaseUrl = options.apiBaseUrl ?? "/api/blob"; + const res = await fetch(`${apiBaseUrl}/${blobId}`); + if (res.status === 404) { + throw new MiniappNoLongerAvailableError(blobId); + } + if (!res.ok) { + throw new MiniappShareError( + `failed to fetch shared mini-app: backend responded ${res.status}`, + ); + } + + const payload = (await res.json()) as SharedMiniappPayload; + const manifest = assertValidManifest(payload.manifest); + try { + return await uploadMiniapp({ manifest, html: payload.html, sourceBlobId: blobId }); + } catch (err) { + // Two concurrent installs of the SAME blobId (e.g. React StrictMode's + // dev-mode double effect run, or re-opening the same install link in + // two tabs at once) both pass the `already` check above before either + // writes. The database's own unique `sourceBlobId` index (db.ts) is + // what actually resolves the race: the loser's insert throws here, and + // by then the winner's record is already committed - return it instead + // of surfacing a confusing constraint error. + const winner = await findPackageBySourceBlobId(blobId); + if (winner) return winner; + throw err; + } +} + +/** One decoded camera/image frame's raw RGBA pixels, as produced by + * `canvas.getImageData` - the same shape Assembly's QR-sneakernet + * transport scans (`src/lib/qrSneakernet.ts`), kept independent here so + * this module has no import-time dependency on that one. */ +export interface ScannedImage { + data: Uint8ClampedArray; + width: number; + height: number; +} + +/** + * Decodes an install URL out of a scanned QR image using the real `jsqr` + * package, bypassing the camera entirely for an automated caller that + * already has pixel data (e.g. a canvas-rendered QR, or a captured camera + * frame). Returns `null` if no QR is found, or if what was found doesn't + * look like an install URL this module produced. + */ +export function decodeInstallUrlFromImage(image: ScannedImage): string | null { + const result = jsQR(image.data, image.width, image.height); + if (!result) return null; + return parseBlobIdFromInstallUrl(result.data) !== null ? result.data : null; +} diff --git a/src/lib/miniappUpload.ts b/src/lib/miniappUpload.ts index 0182b88..004268f 100644 --- a/src/lib/miniappUpload.ts +++ b/src/lib/miniappUpload.ts @@ -24,6 +24,10 @@ export interface MiniappUploadInput { manifest: unknown; /** Raw HTML source of the mini-app, as uploaded. */ html: string; + /** Set by the install-QR sharing flow (todo 55, src/lib/miniappSharing.ts) + * to the blob id this package was installed from; omitted for a direct + * local upload. */ + sourceBlobId?: string; } function generatePackageId(): string { @@ -50,6 +54,7 @@ export async function uploadMiniapp( manifest, html: new Blob([input.html], { type: "text/html" }), installedAt: Date.now(), + sourceBlobId: input.sourceBlobId, }; await db.miniappPackages.add(record); @@ -68,6 +73,15 @@ export async function listMiniappPackages(): Promise { return db.miniappPackages.toArray(); } +/** The already-installed package sourced from `blobId` via the install-QR + * sharing flow, or `undefined` if none exists yet. */ +export async function findPackageBySourceBlobId( + blobId: string, +): Promise { + const all = await db.miniappPackages.toArray(); + return all.find((pkg) => pkg.sourceBlobId === blobId); +} + /** Decode a stored package's HTML blob back into text. */ export async function readPackageHtml( record: StoredMiniappPackage, diff --git a/src/shell/HomeGrid.module.css b/src/shell/HomeGrid.module.css index 5748413..b9e8770 100644 --- a/src/shell/HomeGrid.module.css +++ b/src/shell/HomeGrid.module.css @@ -41,3 +41,9 @@ text-align: center; color: #1f2430; } + +.iconImage { + width: 32px; + height: 32px; + object-fit: contain; +} diff --git a/src/shell/HomeGrid.test.tsx b/src/shell/HomeGrid.test.tsx index 7613011..db8f2eb 100644 --- a/src/shell/HomeGrid.test.tsx +++ b/src/shell/HomeGrid.test.tsx @@ -1,12 +1,20 @@ // @vitest-environment happy-dom import "@testing-library/jest-dom/vitest"; -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { db } from "../lib/db"; +import { uploadMiniapp } from "../lib/miniappUpload"; import { HomeGrid } from "./HomeGrid"; import { miniappRegistry } from "./miniappRegistry"; afterEach(cleanup); +beforeEach(async () => { + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); +}); + describe("HomeGrid", () => { it("renders exactly one tile per registry entry with correct icon and label", () => { render( {}} />); @@ -32,4 +40,28 @@ describe("HomeGrid", () => { expect(onNavigate).toHaveBeenCalledTimes(1); expect(onNavigate).toHaveBeenCalledWith(target.id); }); + + it("renders an additional tile for each locally installed mini-app package and navigates via onNavigatePackage", async () => { + const installed = await uploadMiniapp({ + manifest: { + name: "Shared Garden Tracker", + icon: "\uD83C\uDF31", + entryPoint: "index.html", + permissions: ["ledger.read"], + }, + html: "

hi

", + }); + const onNavigatePackage = vi.fn(); + + render( {}} onNavigatePackage={onNavigatePackage} />); + + const installedTile = await screen.findByTestId(`installed-tile-${installed.id}`); + expect(installedTile).toHaveTextContent("Shared Garden Tracker"); + await waitFor(() => { + expect(screen.getAllByRole("button")).toHaveLength(miniappRegistry.length + 1); + }); + + fireEvent.click(installedTile); + expect(onNavigatePackage).toHaveBeenCalledWith(installed.id); + }); }); diff --git a/src/shell/HomeGrid.tsx b/src/shell/HomeGrid.tsx index ebc7f3f..f4f240c 100644 --- a/src/shell/HomeGrid.tsx +++ b/src/shell/HomeGrid.tsx @@ -1,11 +1,35 @@ +import { useEffect, useState } from "react"; +import { listMiniappPackages, type StoredMiniappPackage } from "../lib/miniappUpload"; import styles from "./HomeGrid.module.css"; import { miniappRegistry } from "./miniappRegistry"; export interface HomeGridProps { onNavigate: (miniappId: string) => void; + /** Fired when an installed (not statically registered) mini-app package + * tile is clicked - see `src/lib/miniappSharing.ts` / todo 55. */ + onNavigatePackage?: (packageId: string) => void; } -export function HomeGrid({ onNavigate }: HomeGridProps) { +function TileIcon({ icon }: { icon: string }) { + if (icon.startsWith("data:") || icon.startsWith("http:") || icon.startsWith("https:")) { + return ; + } + return <>{icon}; +} + +export function HomeGrid({ onNavigate, onNavigatePackage }: HomeGridProps) { + const [packages, setPackages] = useState([]); + + useEffect(() => { + let cancelled = false; + listMiniappPackages().then((records) => { + if (!cancelled) setPackages(records); + }); + return () => { + cancelled = true; + }; + }, []); + return (
{miniappRegistry.map((entry) => ( @@ -22,6 +46,21 @@ export function HomeGrid({ onNavigate }: HomeGridProps) { {entry.label} ))} + {packages.map((pkg) => ( + + ))}
); } diff --git a/src/shell/HomePage.tsx b/src/shell/HomePage.tsx index aa8cd5d..ccf2e1b 100644 --- a/src/shell/HomePage.tsx +++ b/src/shell/HomePage.tsx @@ -4,5 +4,10 @@ import { HomeGrid } from "./HomeGrid"; export function HomePage() { const navigate = useNavigate(); - return navigate(`/miniapp/${miniappId}`)} />; + return ( + navigate(`/miniapp/${miniappId}`)} + onNavigatePackage={(packageId) => navigate(`/package/${packageId}`)} + /> + ); } diff --git a/src/shell/InstallMiniappScreen.module.css b/src/shell/InstallMiniappScreen.module.css new file mode 100644 index 0000000..8ac91ac --- /dev/null +++ b/src/shell/InstallMiniappScreen.module.css @@ -0,0 +1,16 @@ +.status { + padding: 2rem 1rem; + text-align: center; + color: #1f2430; +} + +.goHomeButton { + margin-top: 1rem; + background: #1677ff; + color: #fff; + border: none; + border-radius: 8px; + padding: 0.6rem 1rem; + font: inherit; + cursor: pointer; +} diff --git a/src/shell/InstallMiniappScreen.test.tsx b/src/shell/InstallMiniappScreen.test.tsx new file mode 100644 index 0000000..22a87eb --- /dev/null +++ b/src/shell/InstallMiniappScreen.test.tsx @@ -0,0 +1,74 @@ +// @vitest-environment happy-dom +import "@testing-library/jest-dom/vitest"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { db } from "../lib/db"; +import { InstallMiniappScreen } from "./InstallMiniappScreen"; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +beforeEach(async () => { + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); +}); + +function renderAt(blobId: string) { + return render( + + + } /> + + , + ); +} + +const sharedManifest = { + name: "Shared Garden Tracker", + icon: "\uD83C\uDF31", + entryPoint: "index.html", + permissions: ["ledger.read"], +}; + +describe("InstallMiniappScreen", () => { + it("installs the fetched mini-app via the real write path and lets the resident go home - no account step", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async () => + new Response( + JSON.stringify({ manifest: sharedManifest, html: "

garden

" }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ), + ); + + renderAt("55555555-5555-5555-5555-555555555555"); + + await waitFor(() => { + expect(screen.getByTestId("install-success")).toHaveTextContent("Shared Garden Tracker"); + }); + expect(await db.miniappPackages.toArray()).toHaveLength(1); + expect(screen.queryByRole("button", { name: /sign in|create account|log in/i })).toBeNull(); + }); + + it("shows a clear 'no longer available' message, not a crash, when the shared mini-app was deleted", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(JSON.stringify({ error: "not found" }), { status: 404 })), + ); + + renderAt("deleted-blob-id"); + + await waitFor(() => { + expect(screen.getByTestId("miniapp-no-longer-available")).toBeInTheDocument(); + }); + expect(screen.getByTestId("miniapp-no-longer-available")).toHaveTextContent( + /no longer available/i, + ); + expect(await db.miniappPackages.toArray()).toHaveLength(0); + }); +}); diff --git a/src/shell/InstallMiniappScreen.tsx b/src/shell/InstallMiniappScreen.tsx new file mode 100644 index 0000000..7d39634 --- /dev/null +++ b/src/shell/InstallMiniappScreen.tsx @@ -0,0 +1,96 @@ +import { useEffect, useState } from "react"; +import { useNavigate, useParams } from "react-router-dom"; +import { + installMiniappFromBlob, + MiniappNoLongerAvailableError, +} from "../lib/miniappSharing"; +import type { StoredMiniappPackage } from "../lib/miniappUpload"; +import styles from "./InstallMiniappScreen.module.css"; + +type InstallState = + | { status: "installing" } + | { status: "installed"; record: StoredMiniappPackage } + | { status: "unavailable"; message: string } + | { status: "error"; message: string }; + +/** + * The receiving end of the install-QR sharing flow (plan todo 55). Routed + * at `/install/:blobId` - the deep link a scanned QR resolves to. Fetches + * and installs via the real `installMiniappFromBlob` with no identity or + * account step of any kind, then hands the resident straight to their home + * grid where the installed mini-app now shows up as a tile. + */ +export function InstallMiniappScreen() { + const { blobId } = useParams<{ blobId: string }>(); + const navigate = useNavigate(); + const [state, setState] = useState({ status: "installing" }); + + useEffect(() => { + let cancelled = false; + if (!blobId) { + setState({ status: "error", message: "No mini-app was specified to install." }); + return; + } + + installMiniappFromBlob(blobId) + .then((record) => { + if (!cancelled) setState({ status: "installed", record }); + }) + .catch((err: unknown) => { + if (cancelled) return; + if (err instanceof MiniappNoLongerAvailableError) { + setState({ status: "unavailable", message: err.message }); + } else { + setState({ + status: "error", + message: err instanceof Error ? err.message : String(err), + }); + } + }); + + return () => { + cancelled = true; + }; + }, [blobId]); + + if (state.status === "installing") { + return ( +
+ Installing mini-app… +
+ ); + } + + if (state.status === "unavailable") { + return ( +
+ {state.message} +
+ ); + } + + if (state.status === "error") { + return ( +
+ {state.message} +
+ ); + } + + return ( +
+

“{state.record.manifest.name}” installed.

+ +
+ ); +} diff --git a/src/shell/InstalledMiniappScreen.module.css b/src/shell/InstalledMiniappScreen.module.css new file mode 100644 index 0000000..83e5441 --- /dev/null +++ b/src/shell/InstalledMiniappScreen.module.css @@ -0,0 +1,4 @@ +.screen { + display: flex; + flex-direction: column; +} diff --git a/src/shell/InstalledMiniappScreen.test.tsx b/src/shell/InstalledMiniappScreen.test.tsx new file mode 100644 index 0000000..8328bb1 --- /dev/null +++ b/src/shell/InstalledMiniappScreen.test.tsx @@ -0,0 +1,55 @@ +// @vitest-environment happy-dom +import "@testing-library/jest-dom/vitest"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { db } from "../lib/db"; +import { uploadMiniapp } from "../lib/miniappUpload"; +import { InstalledMiniappScreen } from "./InstalledMiniappScreen"; + +afterEach(cleanup); + +beforeEach(async () => { + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); +}); + +function renderAt(packageId: string) { + return render( + + + } /> + + , + ); +} + +describe("InstalledMiniappScreen", () => { + it("mounts the installed package and offers a real share panel for it", async () => { + const record = await uploadMiniapp({ + manifest: { + name: "Shared Garden Tracker", + icon: "\uD83C\uDF31", + entryPoint: "index.html", + permissions: ["ledger.read"], + }, + html: "

garden

", + }); + + renderAt(record.id); + + await waitFor(() => { + expect(screen.getByTestId("miniapp-mount-container")).toBeInTheDocument(); + }); + expect(screen.getByTestId("share-install-qr")).toBeInTheDocument(); + }); + + it("renders the not-found fallback for an unknown package id, not a crash", async () => { + renderAt("no-such-package"); + + await waitFor(() => { + expect(screen.getByTestId("miniapp-not-found")).toBeInTheDocument(); + }); + }); +}); diff --git a/src/shell/InstalledMiniappScreen.tsx b/src/shell/InstalledMiniappScreen.tsx new file mode 100644 index 0000000..4190db8 --- /dev/null +++ b/src/shell/InstalledMiniappScreen.tsx @@ -0,0 +1,36 @@ +import { useEffect, useState } from "react"; +import { useParams } from "react-router-dom"; +import { getMiniappPackage, type StoredMiniappPackage } from "../lib/miniappUpload"; +import { MountedMiniapp } from "./MountedMiniapp"; +import { NotFoundMiniapp } from "./NotFoundMiniapp"; +import { ShareInstallQr } from "./ShareInstallQr"; +import styles from "./InstalledMiniappScreen.module.css"; + +export function InstalledMiniappScreen() { + const { packageId } = useParams<{ packageId: string }>(); + const [record, setRecord] = useState(); + + useEffect(() => { + let cancelled = false; + if (!packageId) { + setRecord(null); + return; + } + getMiniappPackage(packageId).then((found) => { + if (!cancelled) setRecord(found ?? null); + }); + return () => { + cancelled = true; + }; + }, [packageId]); + + if (record === null) return ; + if (record === undefined) return null; + + return ( +
+ + +
+ ); +} diff --git a/src/shell/ShareInstallQr.module.css b/src/shell/ShareInstallQr.module.css new file mode 100644 index 0000000..d143062 --- /dev/null +++ b/src/shell/ShareInstallQr.module.css @@ -0,0 +1,46 @@ +.panel { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.75rem; + padding: 1rem; +} + +.shareButton { + background: #1677ff; + color: #fff; + border: none; + border-radius: 8px; + padding: 0.6rem 1rem; + font: inherit; + cursor: pointer; +} + +.shareButton:disabled { + opacity: 0.6; + cursor: default; +} + +.error { + color: #d4380d; +} + +.result { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.5rem; +} + +.qrImage { + width: 200px; + height: 200px; + border-radius: 8px; + border: 1px solid #e5e8eb; +} + +.installUrl { + color: #1677ff; + word-break: break-all; + font-size: 0.85rem; +} diff --git a/src/shell/ShareInstallQr.test.tsx b/src/shell/ShareInstallQr.test.tsx new file mode 100644 index 0000000..473f327 --- /dev/null +++ b/src/shell/ShareInstallQr.test.tsx @@ -0,0 +1,69 @@ +// @vitest-environment happy-dom +import "@testing-library/jest-dom/vitest"; +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { db } from "../lib/db"; +import { uploadMiniapp, type StoredMiniappPackage } from "../lib/miniappUpload"; +import { ShareInstallQr } from "./ShareInstallQr"; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +beforeEach(async () => { + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); +}); + +const manifest = { + name: "Shared Garden Tracker", + icon: "\uD83C\uDF31", + entryPoint: "index.html", + permissions: ["ledger.read"], +}; + +async function storeSamplePackage(): Promise { + return uploadMiniapp({ manifest, html: "

hi

" }); +} + +describe("ShareInstallQr", () => { + it("generates and displays the real install QR + URL after a click", async () => { + const record = await storeSamplePackage(); + vi.stubGlobal( + "fetch", + vi.fn(async () => + new Response(JSON.stringify({ id: "44444444-4444-4444-4444-444444444444" }), { + status: 201, + headers: { "Content-Type": "application/json" }, + }), + ), + ); + + render(); + fireEvent.click(screen.getByRole("button", { name: "Share install QR" })); + + const qrImage = await screen.findByTestId("install-qr-image"); + expect(qrImage.getAttribute("src")).toMatch(/^data:image\/png;base64,/); + expect(screen.getByTestId("install-url")).toHaveTextContent( + "/install/44444444-4444-4444-4444-444444444444", + ); + }); + + it("surfaces a clear error instead of crashing when sharing fails", async () => { + const record = await storeSamplePackage(); + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response("oversized", { status: 413 })), + ); + + render(); + fireEvent.click(screen.getByRole("button", { name: "Share install QR" })); + + await waitFor(() => { + expect(screen.getByTestId("share-error")).toBeInTheDocument(); + }); + expect(screen.queryByTestId("install-qr-image")).not.toBeInTheDocument(); + }); +}); diff --git a/src/shell/ShareInstallQr.tsx b/src/shell/ShareInstallQr.tsx new file mode 100644 index 0000000..c3ea0da --- /dev/null +++ b/src/shell/ShareInstallQr.tsx @@ -0,0 +1,57 @@ +import { useState } from "react"; +import type { StoredMiniappPackage } from "../lib/miniappUpload"; +import { shareMiniapp, type ShareResult } from "../lib/miniappSharing"; +import styles from "./ShareInstallQr.module.css"; + +export function ShareInstallQr({ record }: { record: StoredMiniappPackage }) { + const [share, setShare] = useState(); + const [error, setError] = useState(); + const [pending, setPending] = useState(false); + + async function handleShare() { + setPending(true); + setError(undefined); + try { + setShare(await shareMiniapp(record)); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setPending(false); + } + } + + return ( +
+ + {error && ( +

+ {error} +

+ )} + {share && ( + + )} +
+ ); +} diff --git a/vite.config.ts b/vite.config.ts index df71d0a..0e116c4 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -4,6 +4,20 @@ import { VitePWA } from 'vite-plugin-pwa' // https://vite.dev/config/ export default defineConfig({ + server: { + // Local dev only: forwards the frontend's same-origin '/api/blob*' + // calls (install-QR cross-device sharing, todo 55) to the local blob + // API dev server (`node api/_lib/devServer.ts`, todo 56). At deploy + // time (todo 57) this proxy is unnecessary - Vercel serves `api/*.ts` + // functions from the exact same origin as the static frontend + // automatically, so '/api/blob' already resolves without a proxy. + proxy: { + '/api': { + target: `http://127.0.0.1:${process.env.BLOB_API_PORT ?? 3001}`, + changeOrigin: true, + }, + }, + }, plugins: [ react(), // Workbox-based service worker: precaches the app shell (HTML/JS/CSS