diff --git a/DEPLOY.md b/DEPLOY.md index 5ba1a3c..bee4dbc 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -163,6 +163,56 @@ The SQLite file is created automatically on first use (`CREATE TABLE IF NOT EXISTS`) and needs nothing beyond a writable directory on disk. +## 5. (Optional) Self-hosted WebRTC signaling for peer-to-peer mini-apps + +Two mini-apps discover nearby devices over WebRTC and sync peer-to-peer with +no server-side source of truth: **Assembly** (CRDT governance votes, +`src/lib/assemblySync.ts`) and **Find Family** (private-set-intersection +search, `src/miniapps/findfamily/findFamilySync.ts`). WebRTC still needs a +tiny **signaling** server to broker the initial peer handshake - it only +relays "who is in this room"; it never sees document state or search +payloads (those travel directly between peers, encrypted). + +To honor the self-host preference, the signaling URL is **configurable and +defaults to a self-hostable value**, not a third-party host: + +- **Default (no config):** `ws://localhost:4444` - the port the + [`y-webrtc-signaling`](https://github.com/yjs/y-webrtc) server listens on + by default. Run your own with one command, no account or build step: + + ```bash + npx y-webrtc-signaling # listens on ws://0.0.0.0:4444 + ``` + + Put it behind the same reverse proxy as the rest of the app so browsers + reach it over TLS, e.g. add to the Caddy block above: + + ```caddyfile + handle /signaling { + reverse_proxy 127.0.0.1:4444 + } + ``` + +- **Override (recommended for production):** set the `VITE_SIGNALING_URL` + build-time env var to your deployed signaling URL before `npm run build`: + + ```bash + VITE_SIGNALING_URL=wss://commons.example.com/signaling npm run build + ``` + +- **Public fallback (opt-in only):** y-webrtc's bundled public server + `wss://y-webrtc-eu.fly.dev` still works with zero infrastructure, but it is + a **third-party host that can observe which device keys join which rooms**, + so it is never the default. Opt into it explicitly only if you accept that + trade-off: + + ```bash + VITE_SIGNALING_URL=wss://y-webrtc-eu.fly.dev npm run build + ``` + +These mini-apps' peer sync is off by default and opt-in per resident, so a +deployment that never configures signaling simply keeps them local-only. + ## Vercel caveat (if you ever go that route instead) `vercel.json`'s `/api/*` file-routing convention still works unchanged if diff --git a/src/lib/assemblySync.test.ts b/src/lib/assemblySync.test.ts index e52191c..9b290ab 100644 --- a/src/lib/assemblySync.test.ts +++ b/src/lib/assemblySync.test.ts @@ -8,6 +8,9 @@ import { } from "./assembly.ts"; import { DEFAULT_SIGNALING_SERVERS, + LOCAL_SELF_HOST_SIGNALING_SERVER, + PUBLIC_FALLBACK_SIGNALING_SERVER, + resolveDefaultSignalingServer, tallyProposal, } from "./assemblySync.ts"; @@ -92,11 +95,33 @@ describe("tallyProposal", () => { }); }); -describe("DEFAULT_SIGNALING_SERVERS", () => { - it("defaults to a zero-infrastructure public wss signaling server", () => { +describe("default signaling (self-host-first)", () => { + it("defaults to a self-hostable server, not the public third-party host", () => { expect(DEFAULT_SIGNALING_SERVERS.length).toBeGreaterThan(0); for (const url of DEFAULT_SIGNALING_SERVERS) { - expect(url.startsWith("wss://")).toBe(true); + expect(/^wss?:\/\//.test(url)).toBe(true); + expect(url).not.toBe(PUBLIC_FALLBACK_SIGNALING_SERVER); } }); + + it("falls back to the local self-host server when VITE_SIGNALING_URL is unset", () => { + expect(resolveDefaultSignalingServer({})).toBe( + LOCAL_SELF_HOST_SIGNALING_SERVER, + ); + expect(resolveDefaultSignalingServer({ VITE_SIGNALING_URL: "" })).toBe( + LOCAL_SELF_HOST_SIGNALING_SERVER, + ); + }); + + it("honors a configured VITE_SIGNALING_URL override", () => { + expect( + resolveDefaultSignalingServer({ + VITE_SIGNALING_URL: "wss://commons.example/signaling", + }), + ).toBe("wss://commons.example/signaling"); + }); + + it("keeps the public server available only as an explicit fallback", () => { + expect(PUBLIC_FALLBACK_SIGNALING_SERVER).toBe("wss://y-webrtc-eu.fly.dev"); + }); }); diff --git a/src/lib/assemblySync.ts b/src/lib/assemblySync.ts index 85a42ad..7bb108f 100644 --- a/src/lib/assemblySync.ts +++ b/src/lib/assemblySync.ts @@ -12,13 +12,20 @@ import { listVotes, type AssemblyDoc } from "./assembly.ts"; * traffic). There is still no server-side source of truth: the signaling * server only brokers the initial handshake and never sees document state. * - * Transport policy (matches the plan's todo 23): - * - Default signaling is y-webrtc's bundled public server - zero - * infrastructure, works between two real devices on the open internet. - * - For a controlled demo or an automated partition test (or whenever the - * public server is unreachable), callers inject their own signaling URL - * (e.g. a `y-webrtc-signaling` server on localhost). Nothing else about - * the wiring changes. + * Transport policy (self-host-first; see DEPLOY.md): + * - The DEFAULT signaling server is self-hostable, not a third party. It is + * resolved from the `VITE_SIGNALING_URL` build env var, falling back to + * `ws://localhost:4444` - the port a `y-webrtc-signaling` server listens + * on by default, so running one on your own box just works. Point + * `VITE_SIGNALING_URL` at your deployed signaling URL + * (e.g. `wss://commons.example/signaling`) to override it. + * - y-webrtc's bundled PUBLIC server is kept only as a documented fallback + * ({@link PUBLIC_FALLBACK_SIGNALING_SERVER}): it is a third-party host + * that can observe which device keys join which rooms, which conflicts + * with this project's self-host preference. Opt into it explicitly. + * - For a controlled demo or an automated partition test, callers still + * inject their own signaling URL per call; nothing else about the wiring + * changes. * * The provider is a genuine network client: when the browsing context goes * offline the signaling socket drops and every RTCDataChannel fails its ICE @@ -26,15 +33,51 @@ import { listVotes, type AssemblyDoc } from "./assembly.ts"; * exactly what the acceptance test proves rather than assumes. */ -/** y-webrtc's bundled public signaling server (the project default). */ +/** + * y-webrtc's bundled PUBLIC signaling server. Kept ONLY as a documented + * fallback (see DEPLOY.md), never the default: it is a third-party host that + * can observe which device keys join which rooms, which conflicts with this + * project's self-host preference. Use it by setting `VITE_SIGNALING_URL` to + * this value or injecting it per call. + */ +export const PUBLIC_FALLBACK_SIGNALING_SERVER = "wss://y-webrtc-eu.fly.dev"; + +/** + * Self-hostable default signaling endpoint used when `VITE_SIGNALING_URL` is + * unset. It is the port a `y-webrtc-signaling` server listens on by default, + * so `npx y-webrtc-signaling` on the same host needs no further config. + */ +export const LOCAL_SELF_HOST_SIGNALING_SERVER = "ws://localhost:4444"; + +/** + * Resolve the default signaling URL: the `VITE_SIGNALING_URL` env override if + * set and non-empty, else the self-hostable local default. Takes `env` as an + * argument (defaulting to `import.meta.env`) so it is deterministically + * testable without mutating the build environment. + */ +export function resolveDefaultSignalingServer( + env: Record | undefined = + (import.meta as ImportMeta & { env?: Record }) + .env, +): string { + const configured = env?.VITE_SIGNALING_URL; + return configured && configured.length > 0 + ? configured + : LOCAL_SELF_HOST_SIGNALING_SERVER; +} + +/** + * The project's default signaling servers. Self-hostable by default (see + * {@link resolveDefaultSignalingServer}); the public server is opt-in only. + */ export const DEFAULT_SIGNALING_SERVERS: readonly string[] = [ - "wss://y-webrtc-eu.fly.dev", + resolveDefaultSignalingServer(), ]; export interface AssemblySyncOptions { /** * Signaling server URLs used only to discover peers. Defaults to - * {@link DEFAULT_SIGNALING_SERVERS} (zero-infrastructure public server). + * {@link DEFAULT_SIGNALING_SERVERS} (self-hostable; see DEPLOY.md). * Inject a local URL for a reliable demo or test. */ signaling?: string[]; diff --git a/src/lib/sync.test.ts b/src/lib/sync.test.ts index e0b042d..28ed918 100644 --- a/src/lib/sync.test.ts +++ b/src/lib/sync.test.ts @@ -108,6 +108,38 @@ 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 + // 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" }); + await append({ type: "wallet.issue", account: "self", amount: 5 }); + + let pushedBatch: Array<{ payload: { type?: string } }> = []; + const fetchMock = vi.fn(async (_url: string, opts: { body: string }) => { + const body = JSON.parse(opts.body) as { + push: Array<{ payload: { type?: string } }>; + }; + pushedBatch = body.push; + return okResponse({ stored: pushedBatch.length, entries: [], cursor: 0 }); + }); + vi.stubGlobal("fetch", fetchMock); + + const result = await trySyncWithBackend({ endpoint: "http://relay/api/sync" }); + expect(result.ok).toBe(true); + + 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(pushedBatch).toHaveLength(1); + expect(result.pushed).toBe(1); + expect(await readAll()).toHaveLength(3); + }); + it("coalesces concurrent syncs so one pulled entry is ingested exactly once (dedup race)", async () => { const wire = await signedWireEntry( { type: "wallet.issue", account: "raceAcct", amount: 10 }, diff --git a/src/lib/sync.ts b/src/lib/sync.ts index 0d65acc..ac24ded 100644 --- a/src/lib/sync.ts +++ b/src/lib/sync.ts @@ -28,6 +28,64 @@ import { entryIdentity } from "./ledgerConflicts.ts"; * it throws nothing and leaves the local log untouched. */ +/** + * PUSH TYPE ALLOWLIST - the privacy boundary of cross-device sync. + * + * The relay (`/api/sync`) is a SHARED, pubkey-stamped store: every entry a + * device pushes carries its `authorPubkey`, and any peer that pulls can read + * it. Pushing *every* local event type (the previous behavior) therefore let + * anyone pulling the relay correlate a single resident's health, mood, sleep, + * and wallet activity by their one identity key - e.g. join a + * `healthpost.symptomReport` to a `sky.morale.pulse` to a `wallet.transfer` + * 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/aggregate data rather than + * personal PII. Everything else stays strictly local and is NEVER pushed - + * notably `healthpost.*` (symptom reports), `sky.morale.*`/`sky.memoryWall.*` + * (mood + personal memories), `lightclock.*` (personal light/sleep), + * `testimony.*`, `mentor.*`, `fairdraw.*`. A new, unlisted event type is never + * pushed by accident; adding one here is a deliberate, reviewable choice. + * + * Pull is unchanged: a device still ingests whatever a peer legitimately + * shares - this allowlist only governs what THIS device emits. + * + * An entry matches when its `payload.type` equals an allowlist string or is a + * dot-segment beneath one (so `"fairshare"` covers `"fairshare.need"` but not + * a hypothetical `"fairshareX"`). That lets family prefixes + * (`tunnelsafety.hazard`, `theclimb.plan`, `housing`) and exact types + * (`wallet.issue`) share one list. + */ +export const PUSH_TYPE_ALLOWLIST: readonly string[] = [ + // Wallet ledger - the original, canonical cross-device merge use case. + "wallet.issue", + "wallet.transfer", + // Fairshare allocation: its resource seeds + contributions/needs/floors/ + // allocation cycles must replay identically on every device. `seed.*` is + // non-personal aggregate config (population, resource totals, baselines). + "seed", + "fairshare", + // Public civic reports - shared community data, not personal to one author. + "waterwatch.reading.report", + "tunnelsafety.hazard", + "theclimb.plan", + "housing", + // Quadratic-voting ballots: public governance tallies. + "governance.qvBallot", +]; + +/** + * Whether an event payload's `type` is on {@link PUSH_TYPE_ALLOWLIST}. A + * payload with no string `type` is never pushed (default-deny). + */ +export function isPushableType(payload: unknown): boolean { + const type = (payload as { type?: unknown } | null | undefined)?.type; + if (typeof type !== "string") return false; + return PUSH_TYPE_ALLOWLIST.some( + (allowed) => type === allowed || type.startsWith(`${allowed}.`), + ); +} + export interface SyncOptions { /** Relay endpoint URL. Defaults to the same-origin `/api/sync`. */ endpoint?: string; @@ -170,7 +228,13 @@ async function runSync( try { const state = cursorFor(endpoint); const localEntries = await readAll(); - const toPush = localEntries.filter((e) => e.id > state.lastPushedId); + // Advance the cursor past EVERY new local id (allowlisted or not) below, + // so non-pushable types (health/mood/etc.) are skipped permanently rather + // than reconsidered on each sync. The id filter alone picks "new"; the + // allowlist filter enforces the privacy boundary on what is actually sent. + const toPush = localEntries.filter( + (e) => e.id > state.lastPushedId && isPushableType(e.payload), + ); const maxLocalId = localEntries.reduce( (max, e) => (e.id > max ? e.id : max), state.lastPushedId,