From 2641560d9e8c3e24c4c36ccbbff46c2fd3c7a27a Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Fri, 30 Oct 2026 01:55:26 -0500 Subject: [PATCH] feat(telemetry): record a host's country and US state Host reports now carry where the host connects from: the two-letter country Cloudflare's edge assigns to the request and, for a US host, the state (50 states plus DC). The Worker adds both after validation, so a host can't set or change them, and keeps nothing finer: no city, postal code, coordinates or address. App, notification-extension and relay reports stay location-free. This lets the usage dashboard break models, OS and agents per host down by location. The docs describe the new values and note that a cloud or VPN host reports its server's location, not its owner's. --- docs/SECURITY_AND_PRIVACY.md | 4 +- docs/TELEMETRY.md | 16 +++- services/telemetry/src/appinsights.ts | 4 +- services/telemetry/src/geo.ts | 28 +++++++ services/telemetry/src/index.ts | 6 +- services/telemetry/test/geo.test.ts | 112 ++++++++++++++++++++++++++ 6 files changed, 166 insertions(+), 4 deletions(-) create mode 100644 services/telemetry/src/geo.ts create mode 100644 services/telemetry/test/geo.test.ts diff --git a/docs/SECURITY_AND_PRIVACY.md b/docs/SECURITY_AND_PRIVACY.md index c67c6123..d4d7c0ec 100644 --- a/docs/SECURITY_AND_PRIVACY.md +++ b/docs/SECURITY_AND_PRIVACY.md @@ -99,7 +99,9 @@ extension writes nothing and the app throws away what is there. The service is a Cloudflare Worker (`telemetry.bighelp.app`). It checks every batch against an allowlist, rate-limits by install ID and by a keyed hash of the network address (the address itself is never stored, logged or forwarded), and forwards what passes to Microsoft Azure (Application Insights -and Log Analytics), where it is kept for 90 days. +and Log Analytics), where it is kept for 90 days. Reports from a Hermes host (not from the app) also get the +host's country and, in the US, its state, as Cloudflare's edge assigns them to the connection; no city +or address is kept. See [TELEMETRY.md](TELEMETRY.md#host-location). ### The off switch diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 8f560a11..15abe77f 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -18,7 +18,8 @@ the file is dropped at the edge. - **A Hermes host with the bighelp plugin** sends `host.started`, `turn.completed`, `tool.completed`, `alert.queued`, `alert.sent` and `error`. They carry durations, counts, outcomes, the provider and model ID, and the plugin and Hermes versions. Tool names are sent only for built-in Hermes tools and `bighelp_*` tools. Other - tools report `mcp` or `custom`. + tools report `mcp` or `custom`. The Worker adds the host's country and, in the United States, its state (see + [Host location](#host-location)). - **The Link relay** reports `push.sent`, `push.token_invalid`, `push.retry`, `push.dlq`, `push.fallback_buzzkit` and `push.shadow`: the event type, a result code, timings and counts. @@ -42,8 +43,21 @@ How this is enforced: - **Unknown names are dropped.** An unknown event name or key never reaches storage. - **No address.** The Worker uses the client address only to make a keyed hash for rate limiting. It does not store, log or forward the address, and it sends Azure `0.0.0.0` in the location field. +- **Host location is coarse.** See [Host location](#host-location). - **Only the Worker holds the Azure key.** The app and the plugin hold no Azure credential. +## Host location + +Reports from a Hermes host carry two extra values the host never sends itself: `country`, the two-letter code +Cloudflare's edge assigns to the connection (for example `DE`), and `usState`, the state code for a host in the +United States (for example `TX`, or `DC`). The Worker reads them from the request's Cloudflare properties after the +batch passes validation, so a host can't set or change them. Nothing finer is kept: no city, postal code or +coordinates, and not the address. Unknown and Tor connections get neither value, and a US region that is not one of +the 50 states or DC keeps only the country. App, notification-extension and relay reports carry no location. + +This is where the connection comes from, not where a person lives. A host on a cloud server reports its data +center's country, and a host behind a VPN reports the VPN's. + ## Where it goes and how long it stays ```mermaid diff --git a/services/telemetry/src/appinsights.ts b/services/telemetry/src/appinsights.ts index cf4703cb..2f86c151 100644 --- a/services/telemetry/src/appinsights.ts +++ b/services/telemetry/src/appinsights.ts @@ -53,6 +53,8 @@ export interface EnvelopeContext { id?: string; session?: string; context?: Record; + // Values the Worker adds itself, after validation (a host's country and US state). A client can't set them. + server?: Readonly>; } export function buildEnvelopes( @@ -84,7 +86,7 @@ export function buildEnvelopes( baseData: { ver: 2, name: event.name, - properties: { ...context, ...event.properties }, + properties: { ...context, ...event.properties, ...batch.server }, measurements: { ...event.measurements }, }, }, diff --git a/services/telemetry/src/geo.ts b/services/telemetry/src/geo.ts new file mode 100644 index 00000000..2cc28296 --- /dev/null +++ b/services/telemetry/src/geo.ts @@ -0,0 +1,28 @@ +// Where a host's report came from: its country and, in the United States, its state. Cloudflare looks both up from +// the connection at its edge and hands the Worker two-letter codes. The Worker never sees a city, a postal code or +// coordinates from here, and the address itself stays out of this file. App and relay batches get none of this. + +const COUNTRY = /^[A-Z]{2}$/; +// Cloudflare's codes for an unknown country and for Tor. Neither is a place. +const NOT_A_COUNTRY = new Set(["XX", "T1"]); +// The 50 states and DC. Territories such as Puerto Rico arrive as their own country codes. +const US_STATES = new Set([ + "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", + "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", + "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY", +]); + +export interface HostLocation { + country?: string; + usState?: string; +} + +/** The country, and the state for the US, from the request's Cloudflare properties. Empty when unknown. */ +export function hostLocation(cf: unknown): HostLocation { + const props = typeof cf === "object" && cf !== null ? (cf as { country?: unknown; regionCode?: unknown }) : {}; + const country = typeof props.country === "string" ? props.country.trim().toUpperCase() : ""; + if (!COUNTRY.test(country) || NOT_A_COUNTRY.has(country)) return {}; + if (country !== "US") return { country }; + const state = typeof props.regionCode === "string" ? props.regionCode.trim().toUpperCase() : ""; + return US_STATES.has(state) ? { country, usState: state } : { country }; +} diff --git a/services/telemetry/src/index.ts b/services/telemetry/src/index.ts index a050c872..90f86e3b 100644 --- a/services/telemetry/src/index.ts +++ b/services/telemetry/src/index.ts @@ -1,5 +1,6 @@ import { WorkerEntrypoint } from "cloudflare:workers"; import { forwardEvents } from "./appinsights.js"; +import { hostLocation } from "./geo.js"; import { networkKey } from "./network.js"; import { SCHEMA } from "./schema.js"; import { sanitizeEvents, validateBatch } from "./validate.js"; @@ -136,7 +137,10 @@ async function handleBatch(request: Request, env: TelemetryEnv, ctx: ExecutionCo if (!(await allowed(env.RL_ID, `id:${batch.id}`))) throw reject(429, "telemetry_rate_limited"); if (batch.events.length > 0) { - ctx.waitUntil(forwardEvents(env.APPINSIGHTS_CONNECTION_STRING, batch, batch.events)); + // Host reports also carry where the host is: its country and, in the US, its state, as Cloudflare's edge + // assigned them to the connection. App and notification-extension reports carry no location. + const server = batch.source === "host" ? { ...hostLocation(request.cf) } : undefined; + ctx.waitUntil(forwardEvents(env.APPINSIGHTS_CONNECTION_STRING, { ...batch, server }, batch.events)); } return reply({ accepted: batch.events.length, dropped: batch.dropped }, 202); } diff --git a/services/telemetry/test/geo.test.ts b/services/telemetry/test/geo.test.ts new file mode 100644 index 00000000..7bbdd348 --- /dev/null +++ b/services/telemetry/test/geo.test.ts @@ -0,0 +1,112 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { hostLocation } from "../src/geo.js"; +import { appBatch, CLIENT_IP, INSTALL_ID, call, captureForwards } from "./helpers.js"; + +describe("hostLocation", () => { + it("keeps the country and, in the US, the state", () => { + expect(hostLocation({ country: "US", regionCode: "TX" })).toEqual({ country: "US", usState: "TX" }); + expect(hostLocation({ country: "us", regionCode: " dc " })).toEqual({ country: "US", usState: "DC" }); + }); + + it("keeps only the country outside the US", () => { + expect(hostLocation({ country: "DE", regionCode: "BE" })).toEqual({ country: "DE" }); + expect(hostLocation({ country: "PR", regionCode: "SJ" })).toEqual({ country: "PR" }); + }); + + it("drops a US region that is not a state or DC", () => { + expect(hostLocation({ country: "US", regionCode: "ZZ" })).toEqual({ country: "US" }); + expect(hostLocation({ country: "US", regionCode: "Texas" })).toEqual({ country: "US" }); + expect(hostLocation({ country: "US" })).toEqual({ country: "US" }); + }); + + it.each([ + ["unknown", { country: "XX" }], + ["Tor", { country: "T1", regionCode: "TX" }], + ["not a code", { country: "USA" }], + ["not a string", { country: 840 }], + ["missing", {}], + ])("returns nothing for a %s country", (_name, cf) => { + expect(hostLocation(cf)).toEqual({}); + }); + + it("returns nothing without Cloudflare properties", () => { + expect(hostLocation(undefined)).toEqual({}); + expect(hostLocation(null)).toEqual({}); + }); +}); + +describe("location on forwarded reports", () => { + const hostBatch = (context: Record = {}) => ({ + version: 1, + source: "host", + id: INSTALL_ID, + context: { pluginVersion: "3.31.0", hermesVersion: "0.22.1", osFamily: "linux", python: "3.11", agentCount: "2-5", ...context }, + events: [ + { name: "turn.completed", t: Date.now(), p: { durationMs: 5200, outcome: "ok", provider: "example", model: "custom" } }, + { name: "host.started", t: Date.now() }, + ], + }); + + function request(batch: unknown, cf?: Record): Request { + return new Request("https://telemetry.example/v1/batch", { + method: "POST", + headers: { "content-type": "application/json", "cf-connecting-ip": CLIENT_IP }, + body: JSON.stringify(batch), + ...(cf ? { cf } : {}), + } as RequestInit); + } + + async function forwarded(batch: unknown, cf?: Record) { + const { sent } = captureForwards(); + const response = await call(request(batch, cf)); + expect(response.status).toBe(202); + return sent; + } + + afterEach(() => vi.restoreAllMocks()); + + it("adds the country and state to every host event", async () => { + const sent = await forwarded(hostBatch(), { country: "US", regionCode: "TX", city: "Austin", postalCode: "78701", latitude: "30.27" }); + const envelopes = sent[0]!.body as any[]; + expect(envelopes).toHaveLength(2); + for (const envelope of envelopes) { + expect(envelope.data.baseData.properties.country).toBe("US"); + expect(envelope.data.baseData.properties.usState).toBe("TX"); + expect(envelope.tags["ai.location.ip"]).toBe("0.0.0.0"); + } + for (const leaked of [CLIENT_IP, "Austin", "78701", "30.27"]) expect(sent[0]!.raw).not.toContain(leaked); + }); + + it("adds only the country for a host outside the US", async () => { + const sent = await forwarded(hostBatch(), { country: "DE", regionCode: "BE" }); + const [envelope] = sent[0]!.body as any[]; + expect(envelope.data.baseData.properties.country).toBe("DE"); + expect(envelope.data.baseData.properties).not.toHaveProperty("usState"); + }); + + it("adds nothing when the country is unknown", async () => { + const sent = await forwarded(hostBatch(), { country: "XX" }); + const [envelope] = sent[0]!.body as any[]; + expect(envelope.data.baseData.properties).not.toHaveProperty("country"); + expect(envelope.data.baseData.properties).not.toHaveProperty("usState"); + }); + + it("never adds a location to app reports", async () => { + const sent = await forwarded(appBatch(), { country: "US", regionCode: "TX" }); + const raw = sent[0]!.raw; + expect(raw).not.toContain('"country"'); + expect(raw).not.toContain('"usState"'); + }); + + it("can't be set or overridden by the host", async () => { + const sent = await forwarded(hostBatch({ country: "FR", usState: "CA" }), { country: "US", regionCode: "TX" }); + const [envelope] = sent[0]!.body as any[]; + expect(envelope.data.baseData.properties.country).toBe("US"); + expect(envelope.data.baseData.properties.usState).toBe("TX"); + + const spoofOnly = await forwarded(hostBatch({ country: "FR", usState: "CA" })); + const [plain] = spoofOnly[0]!.body as any[]; + expect(plain.data.baseData.properties).not.toHaveProperty("country"); + expect(plain.data.baseData.properties).not.toHaveProperty("usState"); + }); +});