diff --git a/src/lib/eventlog.ts b/src/lib/eventlog.ts index 5ba2957..5b8f9c7 100644 --- a/src/lib/eventlog.ts +++ b/src/lib/eventlog.ts @@ -1,5 +1,5 @@ import { db, type EventLogRecord } from "./db"; -import { getPublicKey, sign, verify } from "./identity"; +import { getPublicKey, sign, signPseudonymous, verify } from "./identity"; /** * Append-only, local-first Signed Event Log. @@ -62,20 +62,42 @@ export async function appendEntry( return { ...entry, id }; } -async function realAppend(payload: unknown): Promise { +/** + * Shared core for both the real-identity and pseudonymous append paths: + * assigns the next Lamport timestamp, builds the canonical message, asks + * `signAndIdentify` for a signature + the authorPubkey it corresponds to + * (a real identity's key, or a domain-separated pseudonym's), and persists + * through `appendEntry` exactly like any other entry. See `realAppend` and + * `realAppendPseudonymous` below for the two callers. + */ +async function realAppendWith( + payload: unknown, + signAndIdentify: (message: Uint8Array) => Promise<{ signature: Uint8Array; authorPubkey: Uint8Array }>, +): Promise { // Signing is a real async crypto operation (not a Dexie job), so this // cannot be wrapped in a db.transaction() - Dexie auto-commits a // transaction once its synchronous job queue drains, and awaiting ed25519 // signing here would commit the transaction before the write happens. const lamportTs = await nextLamportTs(); const message = canonicalMessage(payload, lamportTs); - const [signature, authorPubkey] = await Promise.all([ - sign(message), - getPublicKey(), - ]); + const { signature, authorPubkey } = await signAndIdentify(message); return appendEntry({ payload, authorPubkey, signature, lamportTs }); } +async function realAppend(payload: unknown): Promise { + return realAppendWith(payload, async (message) => { + const [signature, authorPubkey] = await Promise.all([sign(message), getPublicKey()]); + return { signature, authorPubkey }; + }); +} + +async function realAppendPseudonymous(payload: unknown, domain: string): Promise { + return realAppendWith(payload, async (message) => { + const { signature, publicKey } = await signPseudonymous(domain, message); + return { signature, authorPubkey: publicKey }; + }); +} + /** * Serializes every `append()` call through an in-process promise chain so * that `nextLamportTs()`'s read and the entry's eventual write can never @@ -108,6 +130,29 @@ export function append(payload: unknown): Promise { return result; } +/** + * Sign `payload` under a domain-separated PSEUDONYM key (see + * `identity.signPseudonymous`) instead of the real identity key, assign it + * the next Lamport timestamp, and append it - for event types that need + * cross-device sync but must not be linkable to this resident's real + * identity/wallet by a relay puller (`sky.morale.pulse`, + * `healthpost.symptomReport` as of this writing; see + * `src/lib/sync.ts`'s `PUSH_TYPE_ALLOWLIST`). + * + * Shares the SAME `appendTail` serialization queue as `append()` above - the + * device-wide Lamport counter has no notion of "real" vs "pseudonymous" + * authorship, so a real and a pseudonymous append racing on `nextLamportTs()` + * would otherwise be free to assign the same value twice. + */ +export function appendPseudonymous(payload: unknown, domain: string): Promise { + const result = appendTail.then(() => realAppendPseudonymous(payload, domain)); + appendTail = result.then( + () => undefined, + () => undefined, + ); + return result; +} + /** * Independently re-verifies a stored entry's signature against its own * payload, lamportTs, and authorPubkey - the exact same check `appendEntry` diff --git a/src/lib/identity.test.ts b/src/lib/identity.test.ts index 6ecccf5..5e949d2 100644 --- a/src/lib/identity.test.ts +++ b/src/lib/identity.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it } from "vitest"; import { db } from "./db"; -import { getPublicKey, init, sign, verify } from "./identity"; +import { getPseudonymousPublicKey, getPublicKey, init, sign, signPseudonymous, verify } from "./identity"; beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -72,3 +72,58 @@ describe("identity", () => { expect(isValid).toBe(false); }); }); + +describe("signPseudonymous / getPseudonymousPublicKey (domain-separated pseudonym signing)", () => { + it("produces a pseudonym key that is NOT the real identity key, yet is a valid, verifiable Ed25519 signature", async () => { + await init(); + const realPublicKey = await getPublicKey(); + const message = new TextEncoder().encode("a mood pulse"); + + const { signature, publicKey } = await signPseudonymous("sky-morale", message); + + expect(publicKey).not.toEqual(realPublicKey); + expect(await verify(signature, message, publicKey)).toBe(true); + // Critically: the pseudonym signature must NOT verify against the real + // identity's public key - a relay puller who only knows the real pubkey + // (from e.g. a wallet.transfer) cannot confirm this pulse came from the + // same resident by signature-matching against it. + expect(await verify(signature, message, realPublicKey)).toBe(false); + }); + + it("is deterministic per (identity, domain): the same resident always re-derives the same pseudonym keypair", async () => { + await init(); + const first = await getPseudonymousPublicKey("sky-morale"); + const second = await getPseudonymousPublicKey("sky-morale"); + expect(second).toEqual(first); + + const { publicKey: signedPublicKey } = await signPseudonymous( + "sky-morale", + new TextEncoder().encode("x"), + ); + expect(signedPublicKey).toEqual(first); + }); + + it("derives a DIFFERENT pseudonym per domain, so one domain's pseudonym cannot be joined to another's", async () => { + await init(); + const moraleKey = await getPseudonymousPublicKey("sky-morale"); + const healthKey = await getPseudonymousPublicKey("healthpost-reporter"); + const realKey = await getPublicKey(); + + expect(moraleKey).not.toEqual(healthKey); + expect(moraleKey).not.toEqual(realKey); + expect(healthKey).not.toEqual(realKey); + }); + + it("derives a DIFFERENT pseudonym per identity (two residents never collide), even for the same domain", async () => { + await init(); + const firstResidentKey = await getPseudonymousPublicKey("sky-morale"); + + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); + await init(); + const secondResidentKey = await getPseudonymousPublicKey("sky-morale"); + + expect(secondResidentKey).not.toEqual(firstResidentKey); + }); +}); diff --git a/src/lib/identity.ts b/src/lib/identity.ts index d708406..46e2061 100644 --- a/src/lib/identity.ts +++ b/src/lib/identity.ts @@ -1,4 +1,5 @@ import * as ed from "@noble/ed25519"; +import { sha256 } from "@noble/hashes/sha2.js"; import { db, type IdentityRecord } from "./db"; export class IdentityMissingError extends Error { @@ -73,3 +74,64 @@ export async function verify( ): Promise { return ed.verifyAsync(signature, message, publicKey); } + +/** + * Derives a domain-separated pseudonymous Ed25519 seed from the real + * identity's secret key: `SHA-256(realSecretKey || domain)`. Ed25519's own + * "private key" is just a 32-byte seed (its internal SHA-512 expansion + * derives the actual signing scalar from it), so this hash output is usable + * directly as `ed.signAsync`'s key argument - no separate "import seed" step. + * + * One-way by construction: SHA-256 cannot be inverted, so nobody who only + * ever sees a pseudonymous public key (e.g. a relay puller, or any other + * domain's pseudonym) can work backward to `realSecretKey` or to this + * identity's REAL public key - the two are cryptographically unlinkable + * without already holding `realSecretKey` itself. Deterministic per + * (identity, domain) pair, so the same resident always re-derives the same + * pseudonym keypair for a given domain (needed so their own past entries + * under that domain stay recognizably theirs, and so a distinct-reporter + * count like Health Post's stays meaningful across devices/sessions). + */ +function derivePseudonymousSeed(realSecretKey: Uint8Array, domain: string): Uint8Array { + const domainBytes = new TextEncoder().encode(domain); + const combined = new Uint8Array(realSecretKey.length + domainBytes.length); + combined.set(realSecretKey, 0); + combined.set(domainBytes, realSecretKey.length); + return sha256(combined); +} + +/** + * Signs `message` under a domain-separated PSEUDONYM key instead of the + * real identity key - for event types that need cross-device aggregation + * (so they must leave the device and be relay-pushable) but must NOT be + * linkable to this resident's wallet/real identity by a relay puller (see + * `src/lib/sync.ts`'s `PUSH_TYPE_ALLOWLIST` doc comment and + * `.omo/evidence/service-sync-reevaluation.md` for which event types use + * this and why). The real secret key never leaves this module; only the + * derived pseudonym's signature and public key are returned. + */ +export async function signPseudonymous( + domain: string, + message: Uint8Array, +): Promise<{ signature: Uint8Array; publicKey: Uint8Array }> { + const record = await loadExisting(); + if (!record) throw new IdentityMissingError(); + const pseudoSeed = derivePseudonymousSeed(record.secretKey, domain); + const [signature, publicKey] = await Promise.all([ + ed.signAsync(message, pseudoSeed), + ed.getPublicKeyAsync(pseudoSeed), + ]); + return { signature, publicKey }; +} + +/** + * This identity's own pseudonym public key for `domain`, without signing + * anything - lets a caller recognize its OWN past pseudonymous entries + * (e.g. "is this my mood pulse") by comparing authorPubkey bytes, the same + * way it would compare against `getPublicKey()` for a real-identity entry. + */ +export async function getPseudonymousPublicKey(domain: string): Promise { + const record = await loadExisting(); + if (!record) throw new IdentityMissingError(); + return ed.getPublicKeyAsync(derivePseudonymousSeed(record.secretKey, domain)); +} diff --git a/src/lib/skyMorale.ts b/src/lib/skyMorale.ts index b276d45..d6e49aa 100644 --- a/src/lib/skyMorale.ts +++ b/src/lib/skyMorale.ts @@ -19,12 +19,21 @@ * conflated with a presence count. */ -import { append, type StoredEventLogEntry } from "./eventlog.ts"; +import { append, appendPseudonymous, type StoredEventLogEntry } from "./eventlog.ts"; import { HOURS_PER_CYCLE, MS_PER_HOUR } from "./sky.ts"; import { trySyncWithBackend } from "./sync.ts"; export const SKY_MORALE_PULSE_PAYLOAD_TYPE = "sky.morale.pulse" as const; +/** + * Domain label for `identity.signPseudonymous`/`eventlog.appendPseudonymous`. + * A morale pulse syncs across devices (it is on `PUSH_TYPE_ALLOWLIST`) but + * must not be linkable to this resident's real wallet identity by a relay + * puller - see sync.ts's allowlist doc comment and + * .omo/evidence/service-sync-reevaluation.md. + */ +export const SKY_MORALE_DOMAIN = "sky-morale" as const; + /** The fixed set of valid mood values a pulse may report. */ export const SKY_MOOD_VALUES = ["great", "good", "okay", "low", "rough"] as const; @@ -157,11 +166,15 @@ export class SkyMoraleValidationError extends Error { } /** - * Signs a `{ mood, note? }` pulse with the local identity and appends it to - * the shared Event Log via the real `append()` path - the only way a - * resident's own mood pulse ever reaches the aggregate. A malformed `mood` - * value is validated and rejected right here, before `append()` is ever - * called. + * Signs a `{ mood, note? }` pulse under the domain-separated + * {@link SKY_MORALE_DOMAIN} pseudonym (see `identity.signPseudonymous`) and + * appends it to the shared Event Log - the only way a resident's own mood + * pulse ever reaches the aggregate. Pseudonymous, not the real identity key, + * because this payload type IS relay-pushed for cross-device aggregation + * (unlike `sky.memoryWall.entry`'s real-identity signing, which is fine + * since the wall already shows authors publicly) - see + * `SKY_MORALE_DOMAIN`'s doc comment. A malformed `mood` value is validated + * and rejected right here, before any append is ever called. */ export async function postMoralePulse( params: { mood: SkyMood; note?: string }, @@ -173,7 +186,7 @@ export async function postMoralePulse( ); } - const appendFn = deps.append ?? append; + const appendFn = deps.append ?? ((payload: unknown) => appendPseudonymous(payload, SKY_MORALE_DOMAIN)); const now = deps.now ?? Date.now; const trimmedNote = params.note?.trim(); diff --git a/src/lib/sync.test.ts b/src/lib/sync.test.ts index baa3f43..6ec0193 100644 --- a/src/lib/sync.test.ts +++ b/src/lib/sync.test.ts @@ -1,10 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as ed from "@noble/ed25519"; import { db } from "./db"; -import { init } from "./identity"; +import { getPublicKey, init } from "./identity"; import { append, readAll } from "./eventlog"; import { computeBalances } from "./ledger"; import { resetSyncCursors, trySyncWithBackend } from "./sync"; +import { postMoralePulse } from "./skyMorale"; +import { postSymptomReport } from "../miniapps/healthpost/healthpostEvents"; function hex(bytes: Uint8Array): string { return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); @@ -108,13 +110,16 @@ describe("trySyncWithBackend", () => { expect(computeBalances(await readAll()).balances["remoteAcct"]).toBe(42); }); - it("pushes allowlisted wallet events but never personal health/mood events (push privacy boundary)", async () => { - // A resident's device accumulates a health report, a mood pulse, and a + it("pushes allowlisted wallet events but never purely personal local-only events (push privacy boundary)", async () => { + // A resident's device accumulates personal sleep/actigraphy data and a // wallet issue under the SAME identity key. Only the wallet event may - // leave the device; pushing the health/mood events would let any relay - // puller correlate them to this pubkey. - await append({ type: "healthpost.symptomReport", symptom: "fever", severity: 3 }); - await append({ type: "sky.morale.pulse", mood: "low" }); + // leave the device; lightclock.* has no community-facing claim at all + // (see README's "never wired to ration anything") so there is no reason + // it should ever leave this device - it stays the one genuinely + // always-local example (health/mood events now DO sync, but under a + // domain-separated pseudonym rather than this real identity key - see + // the dedicated pseudonym-privacy test below). + await append({ type: "lightclock.actigraphy", restActivityScore: 0.4 }); await append({ type: "wallet.issue", account: "self", amount: 5 }); let pushedBatch: Array<{ payload: { type?: string } }> = []; @@ -132,12 +137,11 @@ describe("trySyncWithBackend", () => { const pushedTypes = pushedBatch.map((e) => e.payload.type); expect(pushedTypes).toContain("wallet.issue"); - expect(pushedTypes).not.toContain("healthpost.symptomReport"); - expect(pushedTypes).not.toContain("sky.morale.pulse"); - // Exactly the wallet event crossed the boundary; the log still holds all 3. + expect(pushedTypes).not.toContain("lightclock.actigraphy"); + // Exactly the wallet event crossed the boundary; the log still holds both. expect(pushedBatch).toHaveLength(1); expect(result.pushed).toBe(1); - expect(await readAll()).toHaveLength(3); + expect(await readAll()).toHaveLength(2); }); it("coalesces concurrent syncs so one pulled entry is ingested exactly once (dedup race)", async () => { @@ -162,8 +166,7 @@ describe("trySyncWithBackend", () => { expect(computeBalances(await readAll()).balances["raceAcct"]).toBe(10); }); - it("syncs the deliberate healthpost.referral handoff + mentor/theclimb-tiebreak/fairdraw, never the symptom tally", async () => { - await append({ type: "healthpost.symptomReport", symptom: "diarrhea" }); + it("syncs the deliberate healthpost.referral handoff + mentor/theclimb-tiebreak/fairdraw/governance", async () => { await append({ type: "healthpost.referral", urgency: "needs_treatment" }); await append({ type: "healthpost.referral.resolve", referralId: 1 }); await append({ type: "mentor.skillReview", skillId: "well-repair", rating: "good" }); @@ -191,20 +194,18 @@ describe("trySyncWithBackend", () => { expect(types).toContain("theclimb.tiebreak.commit"); expect(types).toContain("fairdraw.reveal"); expect(types).toContain("governance.proposal.enacted"); - expect(types).not.toContain("healthpost.symptomReport"); }); - it("pushes the Sky memory wall and Assembly testimony board (public, author-attributed community data), still never morale/symptom", async () => { + it("pushes the Sky memory wall and Assembly testimony board (public, author-attributed community data)", async () => { // Both the memory wall and testimony board already show each entry's // author to every other resident in their own UI - the sync // re-evaluation (.omo/evidence/service-sync-reevaluation.md) found that // excluding them broke the exact cross-device purpose their UI already - // claims. Mood and symptom reports stay excluded: those still carry a - // real health/wallet correlation risk the public boards don't. + // claims. Both sync under the REAL identity key (no pseudonym needed - + // see the dedicated pseudonym test below for sky.morale.pulse/ + // healthpost.symptomReport, which DO need one). await append({ type: "sky.memoryWall.entry", text: "Saw stars through the vent today.", postedAt: 1 }); await append({ type: "testimony.statement", text: "East wall looks stable.", rating: 4, postedAt: 2 }); - await append({ type: "sky.morale.pulse", mood: "okay" }); - await append({ type: "healthpost.symptomReport", symptom: "cough" }); let pushedBatch: Array<{ payload: { type?: string } }> = []; vi.stubGlobal( @@ -221,11 +222,51 @@ describe("trySyncWithBackend", () => { const types = pushedBatch.map((e) => e.payload.type); expect(types).toContain("sky.memoryWall.entry"); expect(types).toContain("testimony.statement"); - expect(types).not.toContain("sky.morale.pulse"); - expect(types).not.toContain("healthpost.symptomReport"); expect(result.pushed).toBe(2); }); + it("pushes mood pulses and symptom reports, but signed under a pseudonym that is NOT this device's real identity key", async () => { + // The actual end-to-end privacy guarantee: post through the REAL + // producer functions (not a hand-built payload), then confirm what + // actually crosses the wire is signed under a different pubkey than + // wallet.issue/wallet.transfer would be - a relay puller cannot join + // this resident's mood/symptom activity to their wallet by pubkey. + const realPublicKey = await getPublicKey(); + await postMoralePulse({ mood: "low" }, { now: () => 1 }); + await postSymptomReport("fever"); + await append({ type: "wallet.issue", account: "self", amount: 5 }); + + let pushedBatch: Array<{ payload: { type?: string }; authorPubkey: string }> = []; + vi.stubGlobal( + "fetch", + vi.fn(async (_url: string, opts: { body: string }) => { + pushedBatch = ( + JSON.parse(opts.body) as { + push: Array<{ payload: { type?: string }; authorPubkey: string }>; + } + ).push; + return okResponse({ stored: pushedBatch.length, entries: [], cursor: 0 }); + }), + ); + + const result = await trySyncWithBackend({ endpoint: "http://relay/api/sync" }); + expect(result.ok).toBe(true); + expect(result.pushed).toBe(3); + + const realPublicKeyHex = hex(realPublicKey); + const walletEntry = pushedBatch.find((e) => e.payload.type === "wallet.issue")!; + const moraleEntry = pushedBatch.find((e) => e.payload.type === "sky.morale.pulse")!; + const symptomEntry = pushedBatch.find((e) => e.payload.type === "healthpost.symptomReport")!; + + expect(walletEntry.authorPubkey).toBe(realPublicKeyHex); + // The mood pulse and symptom report are pushed (unlike before this fix), + // but NEITHER carries the real identity pubkey the wallet event does. + expect(moraleEntry.authorPubkey).not.toBe(realPublicKeyHex); + expect(symptomEntry.authorPubkey).not.toBe(realPublicKeyHex); + // The two pseudonym domains are also distinct from each other. + expect(moraleEntry.authorPubkey).not.toBe(symptomEntry.authorPubkey); + }); + it("pulls another resident's memory-wall entry and testimony statement into the local replay", async () => { // The flip side of the allowlist change: a peer's own-signed wall/board // entries must actually land in THIS device's log via appendEntry's diff --git a/src/lib/sync.ts b/src/lib/sync.ts index f08d4b3..d3c3604 100644 --- a/src/lib/sync.ts +++ b/src/lib/sync.ts @@ -40,22 +40,37 @@ import { entryIdentity } from "./ledgerConflicts.ts"; * under the same pubkey. * * So this is default-DENY: we push ONLY event types that both (a) genuinely - * need cross-device merge and (b) carry community data or a deliberate, - * consent-bearing handoff rather than passive personal PII. The boundary is - * drawn WITHIN a family where needed: `healthpost.referral(.resolve)` - a - * resident's explicit act of sending their OWN case to a clinician on another - * device - DOES sync, while the passive `healthpost.symptomReport` tally does - * NOT. Still strictly local and NEVER pushed: `healthpost.symptomReport` and - * `sky.morale.*` (both carry health/mood correlatable to the same identity - * key - see the cross-device sync re-evaluation at - * .omo/evidence/service-sync-reevaluation.md for why these two specifically - * stay excluded pending a domain-separated-pseudonym design, not a plain - * allowlist entry), and `lightclock.*` (purely personal, no community claim - * at all - see README's "never wired to ration anything"). `sky.memoryWall.*` - * and `testimony.*` were ALSO excluded here originally, but both are - * public-by-design community data whose own UI already displays the - * author's account id on every entry (SkyScreen.tsx's memory-wall list, - * TestimonyBoard.tsx's statement cards) - excluding them only broke their + * need cross-device merge and (b) carry community data, a deliberate + * consent-bearing handoff, or health/mood data signed under a domain- + * separated PSEUDONYM (see below) rather than raw passive personal PII under + * the real identity key. The boundary is drawn WITHIN a family where needed: + * `healthpost.referral(.resolve)` - a resident's explicit act of sending + * their OWN case to a clinician on another device - DOES sync under the + * REAL identity key (it is a deliberate, consent-bearing handoff, not a + * passive signal). `lightclock.*` stays strictly local and NEVER pushed + * (purely personal, no community claim at all - see README's "never wired + * to ration anything"). + * + * `healthpost.symptomReport` and `sky.morale.pulse` DO sync (the + * dispatch-facing symptom tally and the community mood gauge both need + * real cross-device aggregation to mean anything - see + * .omo/evidence/service-sync-reevaluation.md), but their producers + * (`src/miniapps/healthpost/healthpostEvents.ts`'s `postSymptomReport`, + * `src/lib/skyMorale.ts`'s `postMoralePulse`) sign them under a + * domain-separated PSEUDONYM key (`identity.signPseudonymous` / + * `eventlog.appendPseudonymous`), never the real identity key used for + * `wallet.*`. A relay puller sees a stable-per-resident but cryptographically + * unlinkable pseudonym pubkey for these two types - it cannot be joined back + * to that resident's real wallet/identity pubkey, yet `healthpost.ts`'s + * `countDistinctSymptomReporters` (which counts DISTINCT authorPubkeys) still + * correctly counts distinct residents, since each resident's pseudonym is + * stable across their own posts. + * + * `sky.memoryWall.*` and `testimony.*` sync under the REAL identity key (not + * a pseudonym) because both are public-by-design community data whose own UI + * already displays the author's account id on every entry (SkyScreen.tsx's + * memory-wall list, TestimonyBoard.tsx's statement cards) - excluding them + * only broke their * stated cross-resident purpose (a "wall"/"board" nobody else's device ever * populates) without adding any real privacy protection, since the exposure * is already inherent to the feature. They are allowlisted below. A new, @@ -94,9 +109,15 @@ export const PUSH_TYPE_ALLOWLIST: readonly string[] = [ // Health Post clinician referral: a resident's deliberate, consent-bearing // handoff of their OWN triage result to a clinician on another device. The // referral loop is cross-device by contract (see ReferralQueue.tsx). This - // string also covers `healthpost.referral.resolve` via the dot-segment rule; - // the passive `healthpost.symptomReport` stays local (not a child of this). + // string also covers `healthpost.referral.resolve` via the dot-segment + // rule. Signed under the REAL identity key (a deliberate handoff, not a + // passive signal) - contrast `healthpost.symptomReport` below, which syncs + // too but under a pseudonym. "healthpost.referral", + // The dispatch-facing symptom tally: see the allowlist doc comment above + // for why this now syncs (it didn't before) and why it is pseudonymously + // signed (postSymptomReport -> appendPseudonymous, HEALTHPOST_REPORTER_DOMAIN). + "healthpost.symptomReport", // Mentor: skill reviews (proficiency signals) + proposed matches must reach // other devices for community apprentice<->mentor matching to work at all. "mentor.skillReview", @@ -107,6 +128,10 @@ export const PUSH_TYPE_ALLOWLIST: readonly string[] = [ // Fair Draw commit/reveal are public-by-design (a verifiable lottery for an // indivisible good): peers need them to independently audit the draw. "fairdraw", + // The community mood gauge: see the allowlist doc comment above for why + // this now syncs and why it is pseudonymously signed (postMoralePulse -> + // appendPseudonymous, SKY_MORALE_DOMAIN) rather than the real identity key. + "sky.morale.pulse", // Assembly's public testimony board: tamper-evident civic observations // (surface-safety ratings) explicitly meant for every resident to read - // directly comparable to `waterwatch.reading.report`/`tunnelsafety.hazard` diff --git a/src/miniapps/healthpost/healthpostEvents.test.ts b/src/miniapps/healthpost/healthpostEvents.test.ts index 98911a5..f9f692a 100644 --- a/src/miniapps/healthpost/healthpostEvents.test.ts +++ b/src/miniapps/healthpost/healthpostEvents.test.ts @@ -250,4 +250,39 @@ describe("countDistinctSymptomReporters (corroboration gate)", () => { expect(countDistinctSymptomReporters(entries, "fever")).toBe(1); expect(countDistinctSymptomReporters([], "diarrhea")).toBe(0); }); + + it("restores the cross-device gate for real: 3 distinct residents' pseudonymously-signed reports count as 3 distinct reporters", async () => { + // Before the pseudonym fix, this gate was structurally unreachable on a + // per-resident-device deployment: symptom reports never left the + // posting device, so every device's own replay only ever saw its own + // author pubkey - countDistinctSymptomReporters could never exceed 1. + // This simulates 3 real residents on 3 real devices (a fresh identity = + // a fresh Ed25519 keypair = a different resident) each genuinely + // calling postSymptomReport, then merges their entries exactly as a + // relay-synced replay would - the real end-to-end restoration, not just + // the pure-function unit test above. + const residentA = await postSymptomReport("diarrhea"); + + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); + await init(); + const residentB = await postSymptomReport("diarrhea"); + + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); + await init(); + const residentC = await postSymptomReport("diarrhea"); + + const mergedCrossDeviceLog = [residentA, residentB, residentC]; + expect(countDistinctSymptomReporters(mergedCrossDeviceLog, "diarrhea")).toBe(3); + + // The privacy guarantee holds across all 3: no two residents' pseudonym + // pubkeys collide (so the count above is genuinely 3, not an accidental + // match), and none carries the real per-device identity pubkey. + const toHex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); + const pubkeyHexes = mergedCrossDeviceLog.map((e) => toHex(e.authorPubkey)); + expect(new Set(pubkeyHexes).size).toBe(3); + }); }); diff --git a/src/miniapps/healthpost/healthpostEvents.ts b/src/miniapps/healthpost/healthpostEvents.ts index 43167e9..cbecc87 100644 --- a/src/miniapps/healthpost/healthpostEvents.ts +++ b/src/miniapps/healthpost/healthpostEvents.ts @@ -1,9 +1,23 @@ -import { append, type StoredEventLogEntry } from "../../lib/eventlog.ts"; +import { append, appendPseudonymous, type StoredEventLogEntry } from "../../lib/eventlog.ts"; import type { SymptomCategory, SymptomReport } from "../../lib/healthpostTally.ts"; import { ALL_SYMPTOM_CATEGORIES } from "../../lib/healthpostTally.ts"; import type { TriageResult, Urgency } from "../../lib/healthpost.ts"; import { trySyncWithBackend } from "../../lib/sync.ts"; +/** + * Domain label for `identity.signPseudonymous`/`eventlog.appendPseudonymous`. + * A symptom report syncs across devices (it is on `PUSH_TYPE_ALLOWLIST`) so + * the waterborne-outbreak distinct-reporter corroboration gate + * (`countDistinctSymptomReporters` below) can function cross-device at all - + * but it must not be linkable to a resident's real wallet identity by a + * relay puller. See sync.ts's allowlist doc comment and + * .omo/evidence/service-sync-reevaluation.md. Deterministic per identity, so + * `countDistinctSymptomReporters`'s "distinct authorPubkey" semantics still + * correctly count distinct residents - it just counts distinct PSEUDONYM + * keys instead of distinct real wallet keys, which is the same number. + */ +export const HEALTHPOST_REPORTER_DOMAIN = "healthpost-reporter" as const; + /** * Event Log <-> Health Post tally adapter (plan todo 34). * @@ -34,10 +48,20 @@ function isSymptomReportPayload(payload: unknown): payload is SymptomReportPaylo ); } -/** Signs and appends one real crowd self-report of `symptom` to the Event Log. */ -export async function postSymptomReport(symptom: SymptomCategory): Promise { +/** + * Signs and appends one real crowd self-report of `symptom` to the Event + * Log, under the domain-separated {@link HEALTHPOST_REPORTER_DOMAIN} + * pseudonym rather than the real identity key - see that constant's doc + * comment for why. + */ +export async function postSymptomReport( + symptom: SymptomCategory, + deps: { append?: (payload: unknown) => Promise } = {}, +): Promise { const payload: SymptomReportPayload = { type: SYMPTOM_REPORT_PAYLOAD_TYPE, symptom }; - const entry = await append(payload); + const appendFn = + deps.append ?? ((p: unknown) => appendPseudonymous(p, HEALTHPOST_REPORTER_DOMAIN)); + const entry = await appendFn(payload); // Best-effort cross-device sync (plan todo 3): fire-and-forget, never // blocks or affects the local-first write that just completed above. void trySyncWithBackend();