diff --git a/.omo/evidence/coherence-audit/tunnelsafety-geolocation-denied.png b/.omo/evidence/coherence-audit/tunnelsafety-geolocation-denied.png new file mode 100644 index 0000000..9485403 Binary files /dev/null and b/.omo/evidence/coherence-audit/tunnelsafety-geolocation-denied.png differ diff --git a/.omo/evidence/coherence-audit/tunnelsafety-geolocation-fix.e2e.json b/.omo/evidence/coherence-audit/tunnelsafety-geolocation-fix.e2e.json new file mode 100644 index 0000000..a798217 --- /dev/null +++ b/.omo/evidence/coherence-audit/tunnelsafety-geolocation-fix.e2e.json @@ -0,0 +1,48 @@ +{ + "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": "2026-11-20T22:46:35.349Z", + "results": [ + { + "scenario": "geolocation-granted", + "steps": { + "locationCaptured": { + "statusText": "Location captured (38.8977, -77.0365, ±20m)" + }, + "submitted": { + "text": "Hazard reported." + }, + "feedShowsCoords": { + "feedText": "Market Junction → Residential Loop\nFLOODED\nUnconfirmed - 1 report\nReported by 9659548c at 5:46:34 PM\nLocation: 38.8977, -77.0365 (±20m)\nMark resolved" + } + }, + "pass": true + }, + { + "scenario": "geolocation-denied", + "steps": { + "locationUnavailable": { + "statusText": "Location unavailable - segment selection above is used instead." + }, + "submittedDespiteNoLocation": { + "text": "Hazard reported." + }, + "feedShowsReportNoCoords": { + "feedText": "South Gate → Lower Commons\nBLOCKED\nUnconfirmed - 1 report\nReported by c52931d8 at 5:46:35 PM\nMark resolved", + "hasLocationLine": false + } + }, + "pass": true + } + ], + "pass": true +} \ No newline at end of file diff --git a/.omo/evidence/coherence-audit/tunnelsafety-geolocation-granted.png b/.omo/evidence/coherence-audit/tunnelsafety-geolocation-granted.png new file mode 100644 index 0000000..1a86d52 Binary files /dev/null and b/.omo/evidence/coherence-audit/tunnelsafety-geolocation-granted.png differ diff --git a/e2e/tunnelSafetyGeolocation.e2e.mjs b/e2e/tunnelSafetyGeolocation.e2e.mjs new file mode 100644 index 0000000..d415a5e --- /dev/null +++ b/e2e/tunnelSafetyGeolocation.e2e.mjs @@ -0,0 +1,251 @@ +// 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; +}); diff --git a/src/lib/tunnelsafety.test.ts b/src/lib/tunnelsafety.test.ts index 689bbc3..1139a8e 100644 --- a/src/lib/tunnelsafety.test.ts +++ b/src/lib/tunnelsafety.test.ts @@ -105,6 +105,64 @@ describe("reportHazard (happy path)", () => { }); }); +describe("reportHazard (optional best-effort geolocation coords)", () => { + it("stores coords on the payload and reads them back correctly via computeHazardReports", async () => { + await reportHazard({ + segmentId: "segment-7", + status: "flooded", + coords: { latitude: 38.8977, longitude: -77.0365, accuracy: 12.5 }, + }); + + const entries = await readAll(); + expect(entries).toHaveLength(1); + expect(entries[0].payload).toMatchObject({ + coords: { latitude: 38.8977, longitude: -77.0365, accuracy: 12.5 }, + }); + + const reports = computeHazardReports(entries); + expect(reports).toHaveLength(1); + expect(reports[0].coords).toEqual({ latitude: 38.8977, longitude: -77.0365, accuracy: 12.5 }); + }); + + it("works exactly as before with no coords (geolocation denied/unavailable) - no crash, field stays absent", async () => { + await reportHazard({ segmentId: "segment-8", status: "blocked" }); + + const entries = await readAll(); + expect(entries).toHaveLength(1); + expect(entries[0].payload).not.toHaveProperty("coords"); + + const reports = computeHazardReports(entries); + expect(reports).toHaveLength(1); + expect(reports[0].coords).toBeUndefined(); + expect(reports[0]).toMatchObject({ segmentId: "segment-8", status: "blocked", resolved: false }); + + // The hazard still closes its segment for routing exactly as before. + expect(activeHazardsForSegment(entries, "segment-8")).toHaveLength(1); + }); + + it("ignores a tampered/forged coords shape rather than trusting malformed geo data", async () => { + const entries = [ + { + id: 1, + lamportTs: 0, + authorPubkey: new Uint8Array([1]), + signature: new Uint8Array([1]), + payload: { + type: "tunnelsafety.hazard.report", + reportId: "h-bad-coords", + segmentId: "seg-x", + status: "flooded", + reportedAt: 0, + coords: { latitude: "not-a-number", longitude: -77, accuracy: 10 }, + }, + }, + ] as unknown as StoredEventLogEntry[]; + + const reports = computeHazardReports(entries); + expect(reports).toHaveLength(0); + }); +}); + describe("computeSegmentCorroboration (real crowd corroboration by distinct signers)", () => { /** Signs a hazard-report entry with an arbitrary keypair (NOT the local * identity) so a test can forge a second, independent resident the same diff --git a/src/lib/tunnelsafety.ts b/src/lib/tunnelsafety.ts index bef1927..78ea500 100644 --- a/src/lib/tunnelsafety.ts +++ b/src/lib/tunnelsafety.ts @@ -27,10 +27,24 @@ import { sortForReplay } from "./ledger"; export const HAZARD_STATUSES = ["flooded", "blocked"] as const; export type HazardStatus = (typeof HAZARD_STATUSES)[number]; +/** A best-effort device location fix (`navigator.geolocation`), attached to + * a hazard report as optional provenance metadata ONLY - it is never + * required, never fabricated when unavailable, and never used to resolve + * or override the manually-selected `segmentId` (GPS alone cannot tell you + * which named corridor you are in, especially underground). */ +export interface HazardCoords { + latitude: number; + longitude: number; + accuracy: number; +} + /** A newly submitted hazard report, before signing/appending. */ export interface HazardReportInput { segmentId: string; status: HazardStatus; + /** Optional best-effort geolocation fix, present only when the browser + * actually supplied one - see `HazardCoords`. */ + coords?: HazardCoords; } export interface HazardReportPayload { @@ -42,6 +56,8 @@ export interface HazardReportPayload { segmentId: string; status: HazardStatus; reportedAt: number; + /** Optional best-effort geolocation fix - see `HazardCoords`. */ + coords?: HazardCoords; } export interface HazardResolvePayload { @@ -67,6 +83,9 @@ export interface HazardReport { reporterId: string; resolved: boolean; resolvedAt?: number; + /** Optional best-effort geolocation fix carried over from the original + * report's payload - see `HazardCoords`. */ + coords?: HazardCoords; } /** @@ -105,6 +124,16 @@ export function validateHazardReportInput(input: HazardReportInput): void { } } +function isHazardCoords(value: unknown): value is HazardCoords { + if (typeof value !== "object" || value === null) return false; + const c = value as Record; + return ( + typeof c.latitude === "number" && + typeof c.longitude === "number" && + typeof c.accuracy === "number" + ); +} + function isHazardReportPayload( payload: unknown, ): payload is HazardReportPayload { @@ -116,7 +145,8 @@ function isHazardReportPayload( typeof p.segmentId === "string" && p.segmentId.trim().length > 0 && isHazardStatus(p.status) && - typeof p.reportedAt === "number" + typeof p.reportedAt === "number" && + (p.coords === undefined || isHazardCoords(p.coords)) ); } @@ -154,6 +184,7 @@ export async function reportHazard( segmentId: input.segmentId, status: input.status, reportedAt: Date.now(), + ...(input.coords ? { coords: input.coords } : {}), }; return append(payload); } @@ -199,6 +230,7 @@ export function computeHazardReports( reportedAt: entry.payload.reportedAt, reporterId: toHex(entry.authorPubkey), resolved: false, + ...(entry.payload.coords ? { coords: entry.payload.coords } : {}), }); continue; } diff --git a/src/miniapps/tunnelsafety/HazardFeed.tsx b/src/miniapps/tunnelsafety/HazardFeed.tsx index 8a6660e..bcab8a9 100644 --- a/src/miniapps/tunnelsafety/HazardFeed.tsx +++ b/src/miniapps/tunnelsafety/HazardFeed.tsx @@ -98,6 +98,12 @@ export function HazardFeed({ reports, corroborationBySegment }: HazardFeedProps) Reported by {report.reporterId.slice(0, 8)} at{" "} {new Date(report.reportedAt).toLocaleTimeString()} + {report.coords && ( +
+ Location: {report.coords.latitude.toFixed(4)}, {report.coords.longitude.toFixed(4)}{" "} + (±{Math.round(report.coords.accuracy)}m) +
+ )} {!report.resolved && (