Files
patriothacks/e2e/tunnelSafetyGeolocation.e2e.mjs
OmO Orchestratorandsisyphus-dev-ai e321949195 fix(tunnelsafety): add best-effort geolocation metadata to hazard reports
Coherence audit (.omo/evidence/coherence-audit/tunnelsafety.md) found
navigator.geolocation unused repo-wide while hazard reports carried no
location signal beyond a manual segment-name dropdown. ReportHazardForm
now reads a best-effort GPS/network fix on mount via
useBestEffortGeolocation() and attaches it as an optional coords field
on submit - never required, never fabricated on denial/timeout/absence,
and never used to auto-select segmentId (GPS alone cannot resolve which
named corridor a resident is in; segment selection stays manual and
authoritative). tunnelrouting.ts is untouched - routing stays purely
segment-id-based.

- HazardReportPayload/HazardReport gain an optional coords field
  (latitude/longitude/accuracy), validated and round-tripped by
  computeHazardReports; a malformed coords shape is rejected like any
  other corrupt payload.
- The form shows a "Location captured"/"Location unavailable" indicator;
  the hazard feed renders captured coords per report.
- New tests: reportHazard coords round-trip, no-coords unaffected
  behavior, tampered-coords rejection, and a component test mocking
  navigator.geolocation.getCurrentPosition for both the success and
  denied/unavailable paths.
- New Playwright e2e (chromium, real context.permissions geolocation
  grant/deny) proves the full grant and deny flows end to end with
  screenshot evidence.

Co-authored-by: sisyphus-dev-ai <sisyphus-dev-ai@users.noreply.github.com>
2026-11-20 17:47:44 -05:00

252 lines
10 KiB
JavaScript

// Tunnel Safety best-effort geolocation acceptance test (coherence-audit
// gap fix). Self-contained Playwright runner, same shape as
// e2e/housingMentorWalletDemo.e2e.mjs: starts a real Vite dev server, opens
// a real browser page per scenario with Playwright's real geolocation
// permission grant/deny, and drives the real ReportHazardForm UI through
// its real submit path - no mocks of navigator.geolocation itself.
//
// GRANTED: context permissions include "geolocation" with a real fixed
// coordinate -> the form must show "Location captured", and the submitted
// hazard report must carry those coords through to the feed.
// DENIED: context permissions omit "geolocation" -> Chromium resolves
// getCurrentPosition with PERMISSION_DENIED -> the form must show
// "Location unavailable" and still submit the report successfully (no
// crash, no required field), with no coords line rendered for it.
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 = 48000 + Math.floor(Math.random() * 10000);
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
const EV_DIR = resolve(ROOT, ".omo/evidence/coherence-audit");
const FIXED_COORDS = { latitude: 38.8977, longitude: -77.0365, accuracy: 20 };
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(),
});
// Close this raw connection once the seed write lands, so it never
// blocks the real app's Dexie connection (which opens the same
// database at Dexie's own internal version encoding) from
// completing its own open/upgrade a moment later.
tx.oncomplete = () => db.close();
};
},
{ secretKey: Array.from(secretKey), publicKey: Array.from(publicKey) },
);
}
async function runGrantedScenario(browser) {
const context = await browser.newContext({ permissions: ["geolocation"], geolocation: FIXED_COORDS });
const evidence = { scenario: "geolocation-granted", steps: {} };
try {
await seedIdentity(context);
const page = await context.newPage();
await page.goto(`${APP_URL}/miniapp/tunnel-safety`);
const locationStatus = page.getByTestId("tunnel-safety-report-location-status");
await locationStatus.waitFor();
await page.waitForFunction(
() => document.querySelector('[data-testid="tunnel-safety-report-location-status"]')?.textContent?.includes("Location captured"),
{ timeout: 5000 },
);
const statusText = await locationStatus.innerText();
evidence.steps.locationCaptured = { statusText };
if (!statusText.includes("Location captured")) {
throw new Error(`granted: expected "Location captured" text, got "${statusText}"`);
}
if (!statusText.includes("38.8977") || !statusText.includes("-77.0365")) {
throw new Error(`granted: expected the real fixed coords in the status text, got "${statusText}"`);
}
await page.getByTestId("tunnel-safety-report-segment").selectOption("seg-market-residential");
await page.getByTestId("tunnel-safety-report-status").selectOption("flooded");
await page.getByTestId("tunnel-safety-report-submit").click();
const submitStatus = page.getByTestId("tunnel-safety-report-status-text");
await page.waitForFunction(
() => document.querySelector('[data-testid="tunnel-safety-report-status-text"]')?.textContent?.includes("Hazard reported."),
{ timeout: 5000 },
);
evidence.steps.submitted = { text: await submitStatus.innerText() };
const feed = page.getByTestId("tunnel-safety-hazard-feed");
await feed.waitFor();
await page.waitForFunction(
() => document.querySelector('[data-testid="tunnel-safety-hazard-feed"]')?.textContent?.includes("Location:"),
{ timeout: 5000 },
);
const feedText = await feed.innerText();
evidence.steps.feedShowsCoords = { feedText };
if (!feedText.includes("38.8977") || !feedText.includes("-77.0365")) {
throw new Error(`granted: expected the hazard feed to render the captured coords, got: ${feedText}`);
}
mkdirSync(EV_DIR, { recursive: true });
await page.screenshot({ path: resolve(EV_DIR, "tunnelsafety-geolocation-granted.png") });
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 runDeniedScenario(browser) {
// No "geolocation" permission granted -> Chromium's getCurrentPosition
// resolves the error callback with PERMISSION_DENIED, exactly like a
// resident declining the browser prompt.
const context = await browser.newContext();
const evidence = { scenario: "geolocation-denied", steps: {} };
try {
await seedIdentity(context);
const page = await context.newPage();
await page.goto(`${APP_URL}/miniapp/tunnel-safety`);
const locationStatus = page.getByTestId("tunnel-safety-report-location-status");
await locationStatus.waitFor();
await page.waitForFunction(
() => document.querySelector('[data-testid="tunnel-safety-report-location-status"]')?.textContent?.includes("Location unavailable"),
{ timeout: 5000 },
);
const statusText = await locationStatus.innerText();
evidence.steps.locationUnavailable = { statusText };
if (!statusText.includes("Location unavailable")) {
throw new Error(`denied: expected "Location unavailable" text, got "${statusText}"`);
}
await page.getByTestId("tunnel-safety-report-segment").selectOption("seg-south-commons");
await page.getByTestId("tunnel-safety-report-status").selectOption("blocked");
await page.getByTestId("tunnel-safety-report-submit").click();
const submitStatus = page.getByTestId("tunnel-safety-report-status-text");
await page.waitForFunction(
() => document.querySelector('[data-testid="tunnel-safety-report-status-text"]')?.textContent?.includes("Hazard reported."),
{ timeout: 5000 },
);
evidence.steps.submittedDespiteNoLocation = { text: await submitStatus.innerText() };
const feed = page.getByTestId("tunnel-safety-hazard-feed");
await feed.waitFor();
const feedText = await feed.innerText();
evidence.steps.feedShowsReportNoCoords = { feedText, hasLocationLine: feedText.includes("Location:") };
if (feedText.includes("Location:")) {
throw new Error(`denied: expected NO coords line in the feed for a report with no geolocation fix, got: ${feedText}`);
}
if (!feedText.includes("South Gate") && !feedText.includes("Lower Commons")) {
throw new Error(`denied: expected the hazard to still report and appear in the feed, got: ${feedText}`);
}
mkdirSync(EV_DIR, { recursive: true });
await page.screenshot({ path: resolve(EV_DIR, "tunnelsafety-geolocation-denied.png") });
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"] });
const results = [];
let failed = false;
try {
for (const run of [runGrantedScenario, runDeniedScenario]) {
try {
results.push(await run(browser));
} catch (e) {
failed = true;
results.push(e.evidence ?? { pass: false, error: String(e) });
}
}
} finally {
await browser.close();
await vite.close();
}
mkdirSync(EV_DIR, { recursive: true });
const now = new Date().toISOString();
writeFileSync(
resolve(EV_DIR, "tunnelsafety-geolocation-fix.e2e.json"),
JSON.stringify(
{
task: "Tunnel Safety coherence-audit fix: best-effort navigator.geolocation on ReportHazardForm",
tool: "Playwright (chromium), real Vite dev server, real app UI ('/miniapp/tunnel-safety' -> ReportHazardForm/HazardFeed), real context.permissions/geolocation grant+deny",
run_command: "node e2e/tunnelSafetyGeolocation.e2e.mjs",
selectors_used: [
"tunnel-safety-report-location-status",
"tunnel-safety-report-segment",
"tunnel-safety-report-status",
"tunnel-safety-report-submit",
"tunnel-safety-report-status-text",
"tunnel-safety-hazard-feed",
],
timestamp: now,
results,
pass: results.every((r) => r && r.pass),
},
null,
2,
),
);
console.log("\n===== e2e RESULTS =====");
console.log(JSON.stringify(results, null, 2));
const allPass = results.every((r) => r && r.pass);
console.log(`\nSUMMARY: geolocation-granted=${results[0] && results[0].pass ? "PASS" : "FAIL"} geolocation-denied=${results[1] && results[1].pass ? "PASS" : "FAIL"}`);
if (failed || !allPass) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});