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
4 changes: 3 additions & 1 deletion docs/SECURITY_AND_PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 15 additions & 1 deletion docs/TELEMETRY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand Down
4 changes: 3 additions & 1 deletion services/telemetry/src/appinsights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export interface EnvelopeContext {
id?: string;
session?: string;
context?: Record<string, string>;
// Values the Worker adds itself, after validation (a host's country and US state). A client can't set them.
server?: Readonly<Record<string, string>>;
}

export function buildEnvelopes(
Expand Down Expand Up @@ -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 },
},
},
Expand Down
28 changes: 28 additions & 0 deletions services/telemetry/src/geo.ts
Original file line number Diff line number Diff line change
@@ -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 };
}
6 changes: 5 additions & 1 deletion services/telemetry/src/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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);
}
Expand Down
112 changes: 112 additions & 0 deletions services/telemetry/test/geo.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {}) => ({
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<string, unknown>): 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<string, unknown>) {
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");
});
});
Loading