Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions .env.local.example
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,16 @@ VITE_DEBUG=false
# SQLITE_BACKUP_UPLOAD_CMD=

# ─── Analytics (Umami via privacy relay) ─────────────────────────────
# All optional — if these are unset, /api/counter returns an error and
# All optional. If these are unset, /api/counter returns an error and
# the client helper silently swallows it. The browser never talks to
# Umami directly; the relay anonymizes the client IP using `geo-hash`
# (preserves coarse country/region info, randomizes per-visitor bits).
# (keeps a rough location, shuffles the rest with a random key held only
# in memory and replaced daily). That key needs no setting: IP_HASH_SALT
# is no longer read, so delete it from any server that still has it.

# Required when analytics is enabled (both cloud and self-hosted).
# UMAMI_WEBSITE_ID=

# Salt for the daily-rotating IP hash. Required for `geo-hash` to work.
# Use a long, random, server-only secret.
# IP_HASH_SALT=

# ─── Umami Cloud (use these OR the self-hosted block below) ──────────
# UMAMI_API_KEY=

Expand Down
12 changes: 5 additions & 7 deletions client/PrivacyPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { DocPage } from "./DocPage";
* strings `lib/analytics/events.ts` fires, so it stays a component.
*/

const LAST_UPDATED = "November 24, 2026";
const LAST_UPDATED = "November 25, 2026";

const TRACKED_EVENTS: { name: string; description: string }[] = [
{ name: "pageview", description: "A visit to a page on this site." },
Expand Down Expand Up @@ -116,12 +116,10 @@ view a shared matrix, the unique identifier in the URL (the part after

## How we anonymize your IP

Your browser never talks to the analytics service directly. It posts each
event to our own server, which strips most of the identifying bits from your
IP address before forwarding it. We keep enough information to estimate which
country or region the request came from, but not enough to identify you
across visits, and the salt used for the remaining randomization rotates
daily.
Your browser never talks to the analytics service directly. Our server keeps
enough of your IP address to estimate your country or region, and scrambles
the rest with a random key that is never saved and is erased every day. After
that, nobody, including us, can match the scrambled address to yours.

## Use it without contacting us at all

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"webcat:verify": "node scripts/webcat-verify.mjs"
},
"dependencies": {
"@activistchecklist/umami-extra-privacy": "https://github.com/ActivistChecklist/umami-extra-privacy.git#7669154d772ecbf3410c1243e8014ac8a0e74c5e",
"@activistchecklist/umami-extra-privacy": "https://github.com/ActivistChecklist/umami-extra-privacy.git#v1.0.0",
"@fontsource/geist": "^5.3.0",
"@fontsource/geist-mono": "^5",
"@fontsource/roboto": "^5.3.0",
Expand Down
179 changes: 179 additions & 0 deletions server/routes/counter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// @vitest-environment node
import { isIPv4 } from "node:net";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";

/**
* The analytics relay is the one place a visitor's IP is handed to anyone
* other than us. These pin what reaches Umami through the real route, with
* only `fetch` replaced: a `geo-hash` stand-in that keeps a rough location,
* stays stable for a day so sessions work, and changes when the day's key is
* thrown away. The Privacy page describes this to readers.
*/

const UMAMI = "https://umami.test";

let POST: (req: Request) => Promise<Response>;
let sent: { url: string; payload: Record<string, unknown> }[];

beforeAll(async () => {
// The route reads its Umami config once, when the module loads.
vi.stubEnv("UMAMI_API_KEY", "test-key");
vi.stubEnv("UMAMI_WEBSITE_ID", "test-site");
vi.stubEnv("UMAMI_API_CLIENT_ENDPOINT", UMAMI);
// Before v1.0.0 the hashing levels refused to run without a salt.
vi.stubEnv("IP_HASH_SALT", undefined);
vi.resetModules();
({ POST } = await import("./counter"));
});

afterAll(() => {
vi.unstubAllEnvs();
});

afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
});

function captureUmami() {
sent = [];
vi.stubGlobal(
"fetch",
vi.fn(async (url: string | URL, init?: RequestInit) => {
const body = JSON.parse(String(init?.body)) as {
payload: Record<string, unknown>;
};
sent.push({ url: String(url), payload: body.payload });
return new Response("{}", { status: 200 });
}),
);
}

/**
* `x-forwarded-for` is how the address arrives: `toWebRequest` has already
* reduced it to the one entry our proxies vouch for.
*/
function eventFrom(ip: string): Request {
return new Request("http://localhost/api/counter", {
method: "POST",
headers: {
"content-type": "application/json",
"x-forwarded-for": ip,
"user-agent": "test-agent",
},
body: JSON.stringify({
hostname: "riskmapper.test",
url: "/",
name: "download_pdf",
}),
});
}

async function standInFor(ip: string): Promise<unknown> {
const before = sent.length;
const res = await POST(eventFrom(ip));
expect(res.status).toBe(200);
expect(sent).toHaveLength(before + 1);
return sent[before]!.payload.ip;
}

function v4ToInt(ip: string): number {
return ip.split(".").reduce((acc, octet) => acc * 256 + Number(octet), 0);
}

/** Only for fully written-out IPv6, which is how the package formats it. */
function v6Groups(ip: string): number[] {
const groups = ip.split(":").map((g) => parseInt(g, 16));
expect(groups).toHaveLength(8);
return groups;
}

/** 64 visitors in one /19 (203.0.96.0/19 holds the 203.0.113.0/24 test net). */
const NEIGHBOURS = Array.from({ length: 64 }, (_, i) => `203.0.113.${i}`);

describe("POST /api/counter", () => {
it("forwards the event to Umami with a stand-in IP and no salt configured", async () => {
captureUmami();
const ip = await standInFor("203.0.113.77");

expect(sent[0]!.url).toBe(`${UMAMI}/api/send`);
expect(sent[0]!.payload).toMatchObject({
website: "test-site",
hostname: "riskmapper.test",
url: "/",
name: "download_pdf",
});
expect(typeof ip).toBe("string");
expect(isIPv4(ip as string)).toBe(true);
});

it("keeps the first 19 bits of an IPv4 address and shuffles the rest", async () => {
captureUmami();
const standIns: string[] = [];
for (const ip of NEIGHBOURS) standIns.push((await standInFor(ip)) as string);

for (const standIn of standIns) {
expect(isIPv4(standIn)).toBe(true);
expect(v4ToInt(standIn) >>> 13).toBe(v4ToInt("203.0.113.0") >>> 13);
}
// A keyed permutation: no two visitors share a stand-in.
expect(new Set(standIns).size).toBe(NEIGHBOURS.length);
// Each address can land on itself by chance (1 in 8192); more than a
// handful would mean the bits are not being shuffled at all.
const unchanged = standIns.filter((s, i) => s === NEIGHBOURS[i]).length;
expect(unchanged).toBeLessThan(4);
});

it("gives an address the same stand-in all day, and new ones the next day", async () => {
vi.useFakeTimers({ toFake: ["Date"] });
captureUmami();

vi.setSystemTime(new Date("2026-11-24T09:00:00Z"));
const morning: unknown[] = [];
for (const ip of NEIGHBOURS) morning.push(await standInFor(ip));

vi.setSystemTime(new Date("2026-11-24T23:59:00Z"));
const evening: unknown[] = [];
for (const ip of NEIGHBOURS) evening.push(await standInFor(ip));
expect(evening).toEqual(morning);

vi.setSystemTime(new Date("2026-11-25T00:01:00Z"));
const nextDay: unknown[] = [];
for (const ip of NEIGHBOURS) nextDay.push(await standInFor(ip));
const kept = nextDay.filter((s, i) => s === morning[i]).length;
expect(kept).toBeLessThan(4);
});

it("treats an IPv4-mapped IPv6 peer as the IPv4 address it wraps", async () => {
// Node reports IPv4 peers this way if the server listens on `::`
// (HOST=::), and `toWebRequest` falls back to the peer when there is no
// proxy header. Before v1.0.0, `geo-hash` passed this form to Umami
// unchanged.
captureUmami();
const ip = (await standInFor("::ffff:203.0.113.77")) as string;

expect(ip).not.toContain("203.0.113.77");
expect(isIPv4(ip)).toBe(true);
expect(v4ToInt(ip) >>> 13).toBe(v4ToInt("203.0.113.77") >>> 13);
});

it("keeps the first 28 bits of an IPv6 address and zeroes the interface ID", async () => {
captureUmami();
const real = "2001:db8:1234:5678:9abc:def0:1234:5678";
const ip = (await standInFor(real)) as string;

const want = v6Groups(real);
const got = v6Groups(ip);
// 28 bits: the first group and the top 12 bits of the second.
expect(got[0]).toBe(want[0]);
expect(got[1]! >> 4).toBe(want[1]! >> 4);
expect(got.slice(4)).toEqual([0, 0, 0, 0]);
});

it("leaves the IP out when the header is not an address", async () => {
// Before v1.0.0 anything unparseable was forwarded as is.
captureUmami();
await standInFor("unknown");
expect(sent[0]!.payload).not.toHaveProperty("ip");
});
});
29 changes: 16 additions & 13 deletions server/routes/counter.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
import { createRouteHandler } from "@activistchecklist/umami-extra-privacy/next";

/**
* POST /api/counter — server-side relay for Umami analytics events.
* POST /api/counter, the server-side relay for Umami analytics events.
*
* The browser never talks to Umami directly. The relay anonymizes the
* client IP via `geo-hash` (preserves coarse country/region info but
* randomizes per-visitor bits using a daily-rotating salted hash) and
* forwards the event to the configured Umami instance. See
* THREAT-MODEL.md for the privacy reasoning.
* The browser never talks to Umami directly. The relay replaces the client IP
* with a `geo-hash` stand-in and forwards the event to the configured Umami
* instance. The stand-in keeps the first 19 bits of an IPv4 address (28 of
* IPv6), enough for a rough location, and shuffles the rest with a random key
* that exists only in this process's memory and is wiped at each UTC
* midnight. Within a day one address always gets the same stand-in, so Umami
* sessions still work; once the key is gone nobody, us included, can tell
* which stand-in a real address was given. A restart also starts a new key.
*
* Credentials and salt are loaded from env vars (see `.env.local.example`).
* The client IP comes from `x-forwarded-for`, which `toWebRequest` in
* `server/webRequest.ts` has already cut down to the one address our proxies
* vouch for. Umami credentials come from env vars (see `.env.local.example`).
* What we tell readers about this is the "How we anonymize your IP" section of
* `client/PrivacyPage.tsx`; keep the two in step.
*/


// The package's adapter is typed against a structural `NextLikeRequest`
// shape; Next.js 16 validates Route Handler exports nominally and only
// accepts `Request | NextRequest`. Wrap the adapter so the exported
// function has the exact shape Next expects.
const handler = createRouteHandler({ level: "geo-hash" });

// Wrapped so the route has the same `(Request) => Promise<Response>` shape as
// the others in `server/index.ts`, rather than the package's structural type.
export async function POST(req: Request): Promise<Response> {
return handler(req);
}
6 changes: 3 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
# yarn lockfile v1


"@activistchecklist/umami-extra-privacy@https://github.com/ActivistChecklist/umami-extra-privacy.git#7669154d772ecbf3410c1243e8014ac8a0e74c5e":
version "0.1.0"
resolved "https://github.com/ActivistChecklist/umami-extra-privacy.git#7669154d772ecbf3410c1243e8014ac8a0e74c5e"
"@activistchecklist/umami-extra-privacy@https://github.com/ActivistChecklist/umami-extra-privacy.git#v1.0.0":
version "1.0.0"
resolved "https://github.com/ActivistChecklist/umami-extra-privacy.git#cdc7422d143c17ca647133200785d52ac589e259"

"@alloc/quick-lru@^5.2.0":
version "5.3.0"
Expand Down