Files
patriothacks/e2e/transactionHistorySignature.e2e.mjs

228 lines
9.6 KiB
JavaScript

// Wallet transaction-history signature-verification affordance acceptance
// test (plan todo 14). Self-contained Playwright runner, same shape as
// e2e/installShare.e2e.mjs: starts a real Vite dev server, opens a real
// browser page, and drives the real app UI through its real route.
//
// HAPPY: a genuine Ed25519-signed wallet.issue event is appended for the
// page's own local identity via the real append() path (dynamic import of
// the real src/lib/eventlog.ts from inside the page - no mock), the
// WalletCard's transaction history re-renders it live (Dexie liveQuery),
// and the test expands the row via its data-testid and asserts a real
// signature/pubkey are displayed and a "Verified" badge state is shown via
// specific selectors (not a visual/screenshot judgment).
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import * as ed from "@noble/ed25519";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const VITE_PORT = 46000 + Math.floor(Math.random() * 10000);
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
/**
* Pre-seeds the real local-identity record directly into IndexedDB (same
* schema `src/lib/db.ts` defines: Dexie database "the-commons-hollow",
* version 4, `identity` store keyed on "id") via `page.addInitScript` -
* BEFORE the page's own React tree ever mounts. This sidesteps a known,
* pre-existing, out-of-scope StrictMode double-invoke race in
* `useActiveAccountId()`/`identity.init()` (two concurrent first-time
* `db.identity.add()` calls under React 19 StrictMode's dev-mode double
* effect) rather than touching that unrelated code: with the identity row
* already present, `identity.init()`'s existing-record branch is the only
* one ever taken, so there is nothing left to race.
*/
async function seedIdentity(context) {
const { secretKey, publicKey } = await ed.keygenAsync();
await context.addInitScript(
({ secretKey, publicKey }) => {
const openReq = indexedDB.open("the-commons-hollow", 4);
openReq.onupgradeneeded = () => {
const db = openReq.result;
if (!db.objectStoreNames.contains("identity")) db.createObjectStore("identity", { keyPath: "id" });
if (!db.objectStoreNames.contains("eventLog")) {
const store = db.createObjectStore("eventLog", { keyPath: "id", autoIncrement: true });
store.createIndex("lamportTs", "lamportTs", { unique: false });
}
if (!db.objectStoreNames.contains("miniappPackages")) {
const store = db.createObjectStore("miniappPackages", { keyPath: "id" });
store.createIndex("sourceBlobId", "sourceBlobId", { unique: true });
}
};
openReq.onsuccess = () => {
const db = openReq.result;
const tx = db.transaction("identity", "readwrite");
tx.objectStore("identity").put({
id: "local",
publicKey: new Uint8Array(publicKey),
secretKey: new Uint8Array(secretKey),
createdAt: Date.now(),
});
};
},
{ secretKey: Array.from(secretKey), publicKey: Array.from(publicKey) },
);
}
async function runHappyPath(browser) {
const context = await browser.newContext();
const evidence = { scenario: "happy", steps: {} };
try {
await seedIdentity(context);
const page = await context.newPage();
await page.goto(`${APP_URL}/`);
await page.waitForFunction(
() => document.querySelector('[data-testid="wallet-balance"]')?.textContent !== "--",
{ timeout: 10000 },
);
const seeded = await page.evaluate(async () => {
const identity = await import(/* @vite-ignore */ `${window.location.origin}/src/lib/identity.ts`);
const accountIdModule = await import(/* @vite-ignore */ `${window.location.origin}/src/shell/accountId.ts`);
const eventlog = await import(/* @vite-ignore */ `${window.location.origin}/src/lib/eventlog.ts`);
const publicKey = await identity.getPublicKey();
const accountId = accountIdModule.toAccountId(publicKey);
const stored = await eventlog.append({ type: "wallet.issue", account: accountId, amount: 250 });
const toHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
return {
accountId,
entryId: stored.id,
signatureHex: toHex(stored.signature),
authorPubkeyHex: toHex(stored.authorPubkey),
};
});
evidence.steps.seededGenuineEvent = seeded;
const balance = page.getByTestId("wallet-balance");
await balance.waitFor();
const row = page.getByTestId("history-entry").first();
await row.waitFor();
evidence.steps.historyRowVisible = { text: await row.innerText() };
const badge = page.getByTestId(`history-signature-badge-${seeded.entryId}`);
await badge.waitFor();
const badgeTextBeforeVerified = await badge.innerText();
// Wait for the async verifyEntrySignature() re-check to settle to "Verified".
await page.waitForFunction(
(testid) => document.querySelector(`[data-testid="${testid}"]`)?.textContent === "Verified",
`history-signature-badge-${seeded.entryId}`,
{ timeout: 10000 },
);
const badgeTextVerified = await badge.innerText();
evidence.steps.verifiedBadge = {
beforeAsyncCheckResolved: badgeTextBeforeVerified,
afterAsyncCheckResolved: badgeTextVerified,
matchesExpected: badgeTextVerified === "Verified",
};
if (badgeTextVerified !== "Verified") {
throw new Error(`happy: expected badge text "Verified", got "${badgeTextVerified}"`);
}
const toggle = page.getByTestId(`history-expand-toggle-${seeded.entryId}`);
await toggle.click();
const detail = page.getByTestId(`history-signature-detail-${seeded.entryId}`);
await detail.waitFor();
const signatureValue = await page.getByTestId(`history-signature-value-${seeded.entryId}`).innerText();
const pubkeyValue = await page.getByTestId(`history-pubkey-value-${seeded.entryId}`).innerText();
evidence.steps.expandedSignatureDetail = {
signatureValue,
pubkeyValue,
signatureMatchesRealStoredSignature: signatureValue === seeded.signatureHex,
pubkeyMatchesRealStoredPubkey: pubkeyValue === seeded.authorPubkeyHex,
};
if (signatureValue !== seeded.signatureHex) {
throw new Error(`happy: displayed signature "${signatureValue}" != real stored signature "${seeded.signatureHex}"`);
}
if (pubkeyValue !== seeded.authorPubkeyHex) {
throw new Error(`happy: displayed pubkey "${pubkeyValue}" != real stored pubkey "${seeded.authorPubkeyHex}"`);
}
if (signatureValue.length !== 128 || pubkeyValue.length !== 64) {
throw new Error(
`happy: unexpected byte lengths - signature hex len=${signatureValue.length} (want 128 for 64 bytes), pubkey hex len=${pubkeyValue.length} (want 64 for 32 bytes)`,
);
}
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 context.close();
}
}
async function main() {
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 },
});
await vite.listen();
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
let result;
let failed = false;
try {
try {
result = await runHappyPath(browser);
} catch (e) {
failed = true;
result = e.evidence ?? { scenario: "happy", pass: false, error: String(e) };
}
} finally {
await browser.close();
await vite.close();
}
const evDir = resolve(ROOT, ".omo/evidence/the-commons-hollow-polish");
mkdirSync(evDir, { recursive: true });
const now = new Date().toISOString();
writeFileSync(
resolve(evDir, "task-14-the-commons-hollow-polish.json"),
JSON.stringify(
{
task: "14. Add a signature-verification affordance to transaction history",
qa: "happy",
description:
"A genuine Ed25519-signed wallet.issue event is appended for the page's own local identity via the real append() path. The wallet's TransactionHistory row for that entry is expanded via its data-testid, and the test asserts: (1) the verified-signature badge reaches a 'Verified' text state via a specific selector (not a visual/screenshot judgment), re-derived by the real independent verifyEntrySignature() re-check, and (2) the expanded detail panel displays the raw signature and author-public-key hex, byte-identical to the real stored StoredEventLogEntry fields.",
tool: "Playwright (chromium), real Vite dev server, real app UI at '/' (WalletCard -> TransactionHistory)",
run_command: "node e2e/transactionHistorySignature.e2e.mjs",
selectors_used: [
"history-entry",
"history-signature-badge-<id>",
"history-expand-toggle-<id>",
"history-signature-detail-<id>",
"history-signature-value-<id>",
"history-pubkey-value-<id>",
],
timestamp: now,
result,
pass: Boolean(result && result.pass),
},
null,
2,
),
);
console.log("\n===== e2e RESULT =====");
console.log(JSON.stringify(result, null, 2));
console.log(`\nSUMMARY: happy=${result && result.pass ? "PASS" : "FAIL"}`);
if (failed || !(result && result.pass)) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});