356 lines
14 KiB
JavaScript
356 lines
14 KiB
JavaScript
// 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: `<html><body><p>${manifestName}</p></body></html>`,
|
|
});
|
|
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;
|
|
});
|