Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: add Cloudflare client geo tracking for users and machines

0xken15866f71d188aa
diff --git a/backend/README.md b/backend/README.md
index 95bdb5d6c..d65cc648b 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -102,4 +102,21 @@ Prisma over the **same MongoDB** as the agent-manager (no migration files — `p
startup). The backend owns the `users` + `agent_bindings` collections; it never manages the
manager-owned `agent_nodes`/`managers` (read those via raw queries when status enrichment is needed).
+### Client country (Cloudflare)
+
+Production DNS is proxied through Cloudflare, so every request and WebSocket upgrade arrives with a
+`CF-IPCountry` header. `src/lib/clientGeo.ts` is the only reader; it feeds:
+
+- `users.lastCountryCode` / `lastCountryAt` — from the owner's own control-plane calls
+ (`middlewares/authMiddleware.ts`), rate-floored to one write per user per hour unless the country
+ changes. This is the "where is the user" answer.
+- `machines.countryCode` — the computer's country on its last `/api/adapter-ws` connect.
+- `machine_daily_presence.countryCode` / `user_daily_device_presence.countryCode` — same header on the
+ daily presence rows. `user_daily_presence` deliberately has none: it is keyed by
+ (user, machine, day) and its socket is the daemon's, so the machine's country is the one on
+ `machine_daily_presence` for that `machineId`.
+
+Off Cloudflare (local dev, direct origin hits) the header is absent and nothing is written; a value
+is only ever set, never cleared.
+
Historical architecture notes still live in `autonomous-code/docs`.
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 2356e6d5d..6f1bf3d77 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -16,23 +16,31 @@ generator client {
/// `customer_id`. A device may connect before its owner has signed in, so that provisional row uses a
/// deterministic non-deliverable email until the first production SSO login claims it.
model User {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- email String @unique // normalized SSO identity; provisional device rows use @pending.harness.invalid
- externalId String @unique // production SSO subject == SDS `customer_id`; local-prod-* until known
- stagExternalId String? // staging SSO subject; authentication still keys by email
- passwordHash String? // legacy only; SSO users have none
- name String?
- role String @default("user") // user | admin
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ email String @unique // normalized SSO identity; provisional device rows use @pending.harness.invalid
+ externalId String @unique // production SSO subject == SDS `customer_id`; local-prod-* until known
+ stagExternalId String? // staging SSO subject; authentication still keys by email
+ passwordHash String? // legacy only; SSO users have none
+ name String?
+ role String @default("user") // user | admin
// Which Autonomous account plane this user signs in against. Existing rows are backfilled to
// staging because they were created while the app used staging globally; new users default prod.
- autonomousEnv String @default("prod") // prod | stag
+ autonomousEnv String @default("prod") // prod | stag
// The user's private harness grid, minted on first ask and never rewritten (see routes/grid.ts).
// Deliberately NOT @unique: on MongoDB a unique index counts nulls as values, so every user
// without a grid would collide with every other. Global uniqueness is the grid control plane's
// rule to enforce; ours is only one name per user, which the conditional write in the route gives.
- gridName String?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ gridName String?
+ // Cloudflare `CF-IPCountry` (ISO-2) of the last control-plane request this user made, stamped by
+ // middlewares/authMiddleware.ts through lib/clientGeo.ts (rate-floored, never per request). The
+ // REST call always comes from the person's own computer, so this is the "where is the user" answer;
+ // `Machine.countryCode` and the machine/device presence rows carry the CONNECTING SOCKET's country
+ // instead, which for a remote machine is the VPS, not the person.
+ // Null on rows that predate it or when the request did not come through Cloudflare.
+ lastCountryCode String?
+ lastCountryAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index([stagExternalId])
@@map("users")
@@ -79,6 +87,10 @@ model Machine {
// Self-declared and sanitized at the upgrade; null for a machine that never connected or a client
// old enough not to send it.
clientVersion String?
+ // Cloudflare `CF-IPCountry` (ISO-2) of the computer on its LAST adapter-ws connect — same
+ // overwrite-every-connect rule as `hostname`/`clientVersion`. Null when the upgrade did not come
+ // through Cloudflare (local dev) or the row predates the field.
+ countryCode String?
// Billing lifecycle for newly-created campaign machines. Missing on old rows means legacy-active.
// Grandfathered Remote machines are `not_required`; new paid Remote and managed machines move pending -> active only after
// checkout verification. A cancelled paid subscription stays active until its period end, then
@@ -429,15 +441,28 @@ model AnalyticsMachineState {
/// collector-reported; derived directly from the relays: web-ws in src/lib/webWs.ts, device-ws in
/// src/lib/deviceWs.ts, adapter-ws in src/lib/adapterWs.ts).
-/// Per-day record of whether a user had the desktop app open. One row per (user, UTC day). The
-/// source is the local `harness` daemon reporting its own loopback clients over adapter-ws
-/// (`app_presence`, src/lib/adapterWs.ts) — NOT the web-ws upgrade, which the app never performs
-/// itself (only the daemon does, per foreign machine it relays) and which therefore missed every
-/// single-machine user. `connections` = times a window attached to the daemon that day; a session
-/// spanning midnight produces a row for each day it touches with `connections: 0`.
+/// Per-day record of whether a user had the desktop app open, and on which machine. One row per
+/// (user, machine, UTC day): "user online that day" is therefore a DISTINCT count of `userId`, while
+/// `connections` still sums. The source is the local `harness` daemon reporting its own loopback
+/// clients over adapter-ws (`app_presence`, src/lib/adapterWs.ts) — NOT the web-ws upgrade, which
+/// the app never performs itself (only the daemon does, per foreign machine it relays) and which
+/// therefore missed every single-machine user. `connections` = times a window attached to that
+/// daemon that day; a session spanning midnight produces a row for each day it touches with
+/// `connections: 0`.
+/// Deliberately NO `countryCode` here, unlike the device/machine rows: the signal arrives over the
+/// DAEMON's socket, so the country would be the daemon's (a VPS for a remote machine), not the
+/// person's. "Where is the user" is `User.lastCountryCode`, stamped from their own REST calls; the
+/// machine's own country sits on `machine_daily_presence`, joinable through `machineId`.
model UserDailyPresence {
id String @id @default(auto()) @map("_id") @db.ObjectId
userId String
+ // Machine.machineId whose daemon reported the window (the adapter-ws socket the `app_presence`
+ // frame came over). Null ONLY on rows that predate the field — those were one per (user, day).
+ // Optional rather than required for that reason: Prisma-Mongo refuses to READ a row missing a
+ // required field. The old `(userId, dayUtc)` unique index is dropped at worker boot
+ // (lib/db/migrate.ts migrateUserPresencePerMachine); the legacy rows stay distinct under the new
+ // key because they were already distinct on (userId, dayUtc).
+ machineId String?
dayUtc DateTime
connections Int @default(0)
firstSeenAt DateTime
@@ -445,7 +470,8 @@ model UserDailyPresence {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
- @@unique([userId, dayUtc])
+ @@unique([userId, machineId, dayUtc])
+ @@index([userId, dayUtc])
@@map("user_daily_presence")
}
@@ -476,6 +502,7 @@ model UserDailyDevicePresence {
deviceId String
dayUtc DateTime
connections Int @default(0)
+ countryCode String? // Cloudflare `CF-IPCountry` (ISO-2) at the LAST write that carried one; null = unknown / pre-feature row
firstSeenAt DateTime
lastSeenAt DateTime
createdAt DateTime @default(now())
@@ -501,6 +528,7 @@ model MachineDailyPresence {
dayUtc DateTime
connections Int @default(0)
turnsStarted Int @default(0) // `turn_started` up-frames the daemon sent that day (adapterWs tap)
+ countryCode String? // Cloudflare `CF-IPCountry` (ISO-2) at the LAST write that carried one; null = unknown / pre-feature row
firstSeenAt DateTime
lastSeenAt DateTime
createdAt DateTime @default(now())
@@ -596,4 +624,3 @@ model Desk {
@@map("desks")
}
-
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index 11fb73dce..b6822423c 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -26,6 +26,7 @@ import { trackSocketLiveness } from './hub.js'
import { guardedSend, guardedSendJson } from './wsSend.js'
import { attachNodeRole, PRESENCE_TTL_SEC } from './nodeRole.js'
import { presenceWriteDue, recordTurnStarted, touchMachineOnlineDay, touchUserOnlineDay, type PresenceWriteState } from './dailyTracking.js'
+import { countryCodeFromHeaders } from './clientGeo.js'
import { recordCreatedAgent, recordDeletedAgent } from './agentTracker.js'
import type { Frame } from './tunnel.js'
import { logger } from '../utils/logger.js'
@@ -162,6 +163,9 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:
autonomousEnv = parseAutonomousEnvironment(params.get('autonomousEnv'))
} catch { deny(); return }
if (!computerId) { deny(); return }
+ // Where this computer is, per Cloudflare (absent off-Cloudflare). Read once here, at the only point
+ // that still has the upgrade request, and carried into the machine row + its daily presence.
+ const countryCode = countryCodeFromHeaders(req.headers)
void (async () => {
let user
try { user = await authenticateAccessToken(accessToken, autonomousEnv) } catch (err) {
@@ -179,7 +183,7 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:
if (!machineBillingAllowsDataPlane(machine)) { denyPayment(); return }
// Single-computer claim BEFORE upgrade/attach, so a rejected second computer never supersedes the first.
if (!(await claimMachineOwner(machineId, computerId, PRESENCE_TTL_SEC))) { denyBusy(); return }
- wss.handleUpgrade(req, socket, head, (ws) => void attachAdapter(ws, machineId, machine.userId, machine.name, label, computerId, clientVersion))
+ wss.handleUpgrade(req, socket, head, (ws) => void attachAdapter(ws, machineId, machine.userId, machine.name, label, computerId, clientVersion, countryCode))
})().catch((err) => {
if (err instanceof AppError) {
// 403 is the revoked-machine answer from `resolveOrCreateForComputer`; the CLI keys off the
@@ -195,7 +199,7 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:
})
}
-async function attachAdapter(ws: WebSocket, machineId: string, userId: string, currentName: string | null, label?: string, computerId?: string, clientVersion?: string): Promise<void> {
+async function attachAdapter(ws: WebSocket, machineId: string, userId: string, currentName: string | null, label?: string, computerId?: string, clientVersion?: string, countryCode?: string): Promise<void> {
// A different computer was already rejected at the upgrade (denyBusy), so this only closes our OWN
// stale local socket on a same-computer reconnect landing on this worker.
owners.get(machineId)?.close(4000, 'superseded')
@@ -245,7 +249,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
// (see the upgrade handler): that key is a self-consistent liveness token nothing joins against, and
// re-keying it would 409 every already-connected adapter until its old claim aged out.
const boundComputer = computerId ? normalizeComputerId(computerId) : null
- if (label || seededName || clientVersion || boundComputer) {
+ if (label || seededName || clientVersion || boundComputer || countryCode) {
void prisma.machine.update({
where: { machineId },
data: {
@@ -254,6 +258,8 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
// Same overwrite-every-connect rule as `hostname`; absent (old client) leaves the last value.
...(clientVersion ? { clientVersion } : {}),
...(boundComputer ? { computerId: boundComputer } : {}),
+ // Same rule again; absent (not behind Cloudflare) leaves the last value.
+ ...(countryCode ? { countryCode } : {}),
},
}).catch(() => { /* best effort */ })
}
@@ -279,14 +285,15 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
const now = new Date()
if (kind === 'heartbeat' && (machinePresenceInFlight || !presenceWriteDue(lastMachinePresence, now, MACHINE_PRESENCE_WRITE_MS))) return
machinePresenceInFlight = true
- touchMachineOnlineDay(userId, machineId, now, { isNewConnection: kind === 'connect' })
+ touchMachineOnlineDay(userId, machineId, now, { isNewConnection: kind === 'connect', countryCode })
.then(() => { lastMachinePresence.dayKey = utcDayKey(now); lastMachinePresence.wroteAt = now.getTime() })
.catch((err) => logger.warn('machine presence tracking failed', { machineId, kind, error: String(err) }))
.finally(() => { machinePresenceInFlight = false })
}
// Same shape for the person behind the app: `open` bypasses the interval the way `connect` does
// above, `ping` is rate-floored. `userId` is the machine's owner — the only person a desktop app
- // on this computer can be signed in as.
+ // on this computer can be signed in as. The row is keyed by THIS machine too, so the same person
+ // on a second computer lands in a second row rather than in this one.
const lastUserPresence: PresenceWriteState = { dayKey: null, wroteAt: 0 }
let userPresenceInFlight = false
let lastUserOpenAt = 0
@@ -298,7 +305,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
lastUserOpenAt = now.getTime()
}
userPresenceInFlight = true
- touchUserOnlineDay(userId, now, { isNewConnection: kind === 'open' })
+ touchUserOnlineDay(userId, machineId, now, { isNewConnection: kind === 'open' })
.then(() => { lastUserPresence.dayKey = utcDayKey(now); lastUserPresence.wroteAt = now.getTime() })
.catch((err) => logger.warn('user presence tracking failed', { machineId, userId, kind, error: String(err) }))
.finally(() => { userPresenceInFlight = false })
diff --git a/backend/src/lib/clientGeo.test.ts b/backend/src/lib/clientGeo.test.ts
new file mode 100644
index 000000000..ef3754a1f
--- /dev/null
+++ b/backend/src/lib/clientGeo.test.ts
@@ -0,0 +1,106 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const db = vi.hoisted(() => ({ userUpdate: vi.fn() }))
+vi.mock('./prisma.js', () => ({ prisma: { user: { update: db.userUpdate } } }))
+
+import {
+ countryCodeFromHeaders,
+ resetUserCountryCacheForTests,
+ stampUserCountry,
+ USER_COUNTRY_WRITE_MS,
+} from './clientGeo.js'
+
+describe('countryCodeFromHeaders', () => {
+ it('returns the ISO-2 code Cloudflare stamped', () => {
+ expect(countryCodeFromHeaders({ 'cf-ipcountry': 'VN' })).toBe('VN')
+ })
+
+ it('normalizes case and whitespace', () => {
+ expect(countryCodeFromHeaders({ 'cf-ipcountry': ' vn ' })).toBe('VN')
+ })
+
+ it('takes the first value of a repeated header', () => {
+ expect(countryCodeFromHeaders({ 'cf-ipcountry': ['US', 'VN'] as unknown as string })).toBe('US')
+ })
+
+ it('is undefined when the header is absent (not behind Cloudflare)', () => {
+ expect(countryCodeFromHeaders({})).toBeUndefined()
+ })
+
+ it.each(['XX', 'T1', 'xx'])('drops the Cloudflare placeholder %s', (v) => {
+ expect(countryCodeFromHeaders({ 'cf-ipcountry': v })).toBeUndefined()
+ })
+
+ it.each(['', 'VNM', 'V', '12', 'V N', 'US; DROP'])('rejects the malformed value %j', (v) => {
+ expect(countryCodeFromHeaders({ 'cf-ipcountry': v })).toBeUndefined()
+ })
+})
+
+describe('stampUserCountry', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ resetUserCountryCacheForTests()
+ db.userUpdate.mockResolvedValue({})
+ })
+
+ it('writes lastCountryCode/lastCountryAt on the first request', async () => {
+ const now = new Date('2026-09-21T10:00:00.000Z')
+ await stampUserCountry('user-1', 'VN', now)
+ expect(db.userUpdate).toHaveBeenCalledTimes(1)
+ expect(db.userUpdate.mock.calls[0][0]).toEqual({
+ where: { id: 'user-1' },
+ data: { lastCountryCode: 'VN', lastCountryAt: now },
+ })
+ })
+
+ it('does not write again for the same country inside the write interval', async () => {
+ const t0 = new Date('2026-09-21T10:00:00.000Z')
+ await stampUserCountry('user-1', 'VN', t0)
+ await stampUserCountry('user-1', 'VN', new Date(t0.getTime() + USER_COUNTRY_WRITE_MS - 1))
+ expect(db.userUpdate).toHaveBeenCalledTimes(1)
+ })
+
+ it('writes again once the interval has elapsed', async () => {
+ const t0 = new Date('2026-09-21T10:00:00.000Z')
+ await stampUserCountry('user-1', 'VN', t0)
+ await stampUserCountry('user-1', 'VN', new Date(t0.getTime() + USER_COUNTRY_WRITE_MS))
+ expect(db.userUpdate).toHaveBeenCalledTimes(2)
+ })
+
+ it('writes immediately when the country changes', async () => {
+ const t0 = new Date('2026-09-21T10:00:00.000Z')
+ await stampUserCountry('user-1', 'VN', t0)
+ await stampUserCountry('user-1', 'US', new Date(t0.getTime() + 1000))
+ expect(db.userUpdate).toHaveBeenCalledTimes(2)
+ expect(db.userUpdate.mock.calls[1][0].data.lastCountryCode).toBe('US')
+ })
+
+ it('keys the cache per user', async () => {
+ const t0 = new Date('2026-09-21T10:00:00.000Z')
+ await stampUserCountry('user-1', 'VN', t0)
+ await stampUserCountry('user-2', 'VN', t0)
+ expect(db.userUpdate).toHaveBeenCalledTimes(2)
+ })
+
+ it('collapses a burst of parallel requests into one write', async () => {
+ const t0 = new Date('2026-09-21T10:00:00.000Z')
+ let release!: () => void
+ db.userUpdate.mockImplementationOnce(() => new Promise<void>((resolve) => { release = resolve }))
+ const first = stampUserCountry('user-1', 'VN', t0)
+ await Promise.all([
+ stampUserCountry('user-1', 'VN', t0),
+ stampUserCountry('user-1', 'VN', new Date(t0.getTime() + 5)),
+ ])
+ release()
+ await first
+ expect(db.userUpdate).toHaveBeenCalledTimes(1)
+ })
+
+ it('retries on the next request after a failed write, and never throws', async () => {
+ const t0 = new Date('2026-09-21T10:00:00.000Z')
+ db.userUpdate.mockRejectedValueOnce(new Error('mongo down'))
+ await expect(stampUserCountry('user-1', 'VN', t0)).resolves.toBeUndefined()
+ await stampUserCountry('user-1', 'VN', new Date(t0.getTime() + 1000))
+ expect(db.userUpdate).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/backend/src/lib/clientGeo.ts b/backend/src/lib/clientGeo.ts
new file mode 100644
index 000000000..89aaab196
--- /dev/null
+++ b/backend/src/lib/clientGeo.ts
@@ -0,0 +1,93 @@
+/**
+ * Where a client is, as Cloudflare saw it. Production DNS is proxied through Cloudflare, which
+ * stamps every request AND every WebSocket upgrade with `CF-IPCountry` (ISO 3166-1 alpha-2, plus
+ * `XX` for "unknown" and `T1` for Tor). This module is the ONLY reader of that header: the WS
+ * upgrade handlers (adapterWs / deviceWs) pass it down into the daily presence rows, and the REST
+ * auth hook stamps it on the user.
+ *
+ * The header is not gated on an env flag on purpose. Off Cloudflare (local dev, a direct hit on the
+ * origin) it is simply absent and nothing is written; a spoofed value can only dirty a statistics
+ * column, never an authorization decision, so there is nothing to defend here.
+ */
+import type { IncomingHttpHeaders } from 'http'
+import { prisma } from './prisma.js'
+import { logger } from '../utils/logger.js'
+
+const COUNTRY_RE = /^[A-Z]{2}$/
+
+/**
+ * The client's country code from `CF-IPCountry`, or undefined when the header is missing,
+ * malformed, or one of Cloudflare's non-country placeholders (`XX` unknown, `T1` Tor).
+ * Takes the headers bag rather than the request so the same function serves an `IncomingMessage`
+ * (WS upgrade) and a `FastifyRequest`.
+ */
+export function countryCodeFromHeaders(headers: IncomingHttpHeaders): string | undefined {
+ const raw = headers['cf-ipcountry']
+ const v = (Array.isArray(raw) ? raw[0] : raw)?.trim().toUpperCase()
+ if (!v || !COUNTRY_RE.test(v) || v === 'XX' || v === 'T1') return undefined
+ return v
+}
+
+/** Minimum age of the last stamp before the same country is written again for one user. */
+export const USER_COUNTRY_WRITE_MS = 60 * 60 * 1000
+/** Cache entries older than this are evicted on the next sweep; sweeps run only past `USER_COUNTRY_CACHE_MAX`. */
+const USER_COUNTRY_CACHE_TTL_MS = 24 * 60 * 60 * 1000
+const USER_COUNTRY_CACHE_MAX = 50_000
+
+interface LastStamp { countryCode: string; at: number }
+// Per-process (pm2 cluster: one map per worker). A handful of redundant writes across workers is
+// the accepted price of not adding a Redis round-trip to every control-plane request.
+const lastStamps = new Map<string, LastStamp>()
+
+function sweepStale(now: number): void {
+ if (lastStamps.size <= USER_COUNTRY_CACHE_MAX) return
+ for (const [id, s] of lastStamps) {
+ if (now - s.at >= USER_COUNTRY_CACHE_TTL_MS) lastStamps.delete(id)
+ }
+ // More live users than the cap: forgetting them all costs one extra write each, which beats an
+ // unbounded map. Insertion order is oldest-first, so drop from the front down to half the cap.
+ if (lastStamps.size > USER_COUNTRY_CACHE_MAX) {
+ const excess = lastStamps.size - USER_COUNTRY_CACHE_MAX / 2
+ let dropped = 0
+ for (const id of lastStamps.keys()) {
+ if (dropped++ >= excess) break
+ lastStamps.delete(id)
+ }
+ }
+}
+
+/** Test seam only. */
+export function resetUserCountryCacheForTests(): void {
+ lastStamps.clear()
+}
+
+/**
+ * Remember `countryCode` as where `userId` last made a control-plane request. Fire-and-forget from
+ * the auth hook — never awaited on the request path. Mongo is written only when the country changed
+ * or the last write is at least `USER_COUNTRY_WRITE_MS` old, in the spirit of UserService's
+ * "SSO auth runs on every request; don't make it a write-per-request hot path".
+ *
+ * The cache entry is claimed BEFORE the write, not after: the desktop app opens with a burst of
+ * parallel requests, and claiming late would let every one of them reach Mongo. A failed write puts
+ * the previous entry back so the next request retries instead of waiting out the interval.
+ */
+export async function stampUserCountry(userId: string, countryCode: string, now: Date = new Date()): Promise<void> {
+ const t = now.getTime()
+ const last = lastStamps.get(userId)
+ if (last && last.countryCode === countryCode && t - last.at < USER_COUNTRY_WRITE_MS) return
+ lastStamps.set(userId, { countryCode, at: t })
+ sweepStale(t)
+ try {
+ await prisma.user.update({
+ where: { id: userId },
+ data: { lastCountryCode: countryCode, lastCountryAt: now },
+ })
+ } catch (err) {
+ // Only undo our own claim: a later, successful stamp must not be rolled back by an older failure.
+ if (lastStamps.get(userId)?.at === t) {
+ if (last) lastStamps.set(userId, last)
+ else lastStamps.delete(userId)
+ }
+ logger.warn('user country stamp failed', { userId, countryCode, error: String(err) })
+ }
+}
diff --git a/backend/src/lib/dailyTracking.test.ts b/backend/src/lib/dailyTracking.test.ts
index 533ab1eb4..26199a723 100644
--- a/backend/src/lib/dailyTracking.test.ts
+++ b/backend/src/lib/dailyTracking.test.ts
@@ -23,22 +23,25 @@ describe('touchUserOnlineDay', () => {
db.userPresenceUpsert.mockResolvedValue({})
})
- it('an app `open` upserts the (user, UTC day) row and bumps connections', async () => {
+ it('an app `open` upserts the (user, machine, UTC day) row and bumps connections', async () => {
const now = new Date('2026-09-16T10:15:30.000Z')
- await touchUserOnlineDay('user-1', now, { isNewConnection: true })
+ await touchUserOnlineDay('user-1', 'machine-a', now, { isNewConnection: true })
expect(db.userPresenceUpsert).toHaveBeenCalledTimes(1)
const call = db.userPresenceUpsert.mock.calls[0][0]
- expect(call.where).toEqual({ userId_dayUtc: { userId: 'user-1', dayUtc: utcDayStart(now) } })
+ expect(call.where).toEqual({
+ userId_machineId_dayUtc: { userId: 'user-1', machineId: 'machine-a', dayUtc: utcDayStart(now) },
+ })
expect(call.create).toEqual({
- userId: 'user-1', dayUtc: utcDayStart(now), connections: 1, firstSeenAt: now, lastSeenAt: now,
+ userId: 'user-1', machineId: 'machine-a', dayUtc: utcDayStart(now),
+ connections: 1, firstSeenAt: now, lastSeenAt: now,
})
expect(call.update).toEqual({ lastSeenAt: now, connections: { increment: 1 } })
})
it('an app `ping` only touches lastSeenAt — a session spanning midnight opens no connection that day', async () => {
const now = new Date('2026-09-16T00:00:20.000Z')
- await touchUserOnlineDay('user-1', now, { isNewConnection: false })
+ await touchUserOnlineDay('user-1', 'machine-a', now, { isNewConnection: false })
const call = db.userPresenceUpsert.mock.calls[0][0]
expect(call.update).toEqual({ lastSeenAt: now })
@@ -77,6 +80,24 @@ describe('touchMachineOnlineDay', () => {
expect(call.create.connections).toBe(0)
})
+ it('carries the Cloudflare country into both create and update (last write of the day wins)', async () => {
+ const now = new Date('2026-09-16T10:15:30.000Z')
+ await touchMachineOnlineDay('user-1', 'machine-a', now, { isNewConnection: false, countryCode: 'VN' })
+
+ const call = db.machinePresenceUpsert.mock.calls[0][0]
+ expect(call.create.countryCode).toBe('VN')
+ expect(call.update).toEqual({ lastSeenAt: now, countryCode: 'VN' })
+ })
+
+ it('never clears a country: a touch without one leaves the column out of the write', async () => {
+ const now = new Date('2026-09-16T10:15:30.000Z')
+ await touchMachineOnlineDay('user-1', 'machine-a', now, { isNewConnection: true })
+
+ const call = db.machinePresenceUpsert.mock.calls[0][0]
+ expect(call.create).not.toHaveProperty('countryCode')
+ expect(call.update).not.toHaveProperty('countryCode')
+ })
+
it('propagates a DB failure so the caller can log it and keep its guard unchanged', async () => {
db.machinePresenceUpsert.mockRejectedValueOnce(new Error('mongo down'))
await expect(
diff --git a/backend/src/lib/dailyTracking.ts b/backend/src/lib/dailyTracking.ts
index ba76f97a9..52afecd29 100644
--- a/backend/src/lib/dailyTracking.ts
+++ b/backend/src/lib/dailyTracking.ts
@@ -13,16 +13,32 @@
*
* All entry points are meant to be called fire-and-forget from the hot path (connection open,
* heartbeat/ping, p2p_offer) — callers must not await them inline.
+ *
+ * `countryCode` on the device and machine touches is Cloudflare's `CF-IPCountry` read at the WS
+ * upgrade (lib/clientGeo.ts). It is last-write-wins within the day and only ever SET, never cleared:
+ * a touch without one (local dev, a relay not fronted by Cloudflare) leaves whatever the row has.
+ * `touchUserOnlineDay` takes none on purpose — its socket belongs to the daemon, not the person
+ * (see the model doc in schema.prisma); the person's country is `User.lastCountryCode`.
*/
import { prisma } from './prisma.js'
import { utcDayKey, utcDayStart } from '../types/analytics.js'
+/** Options for the device/machine presence touches. */
+export interface PresenceTouchOpts {
+ isNewConnection: boolean
+ /** ISO-2 from `CF-IPCountry` at the upgrade; omit when unknown (see module doc). */
+ countryCode?: string
+}
+
/**
- * Mark a user online for the UTC day containing `now`. The signal is the `harness` daemon's
- * `app_presence` frame over adapter-ws (src/lib/adapterWs.ts), sent about its own loopback clients:
- * `isNewConnection: true` when a desktop window just attached to the daemon (bumps `connections`),
- * `false` for the periodic ping while one stays attached (just touches `lastSeenAt`, at most every
- * USER_PRESENCE_WRITE_MS). Not the web-ws upgrade — the app never dials that itself.
+ * Mark a user online, on `machineId`, for the UTC day containing `now`. The signal is the `harness`
+ * daemon's `app_presence` frame over adapter-ws (src/lib/adapterWs.ts), sent about its own loopback
+ * clients: `isNewConnection: true` when a desktop window just attached to the daemon (bumps
+ * `connections`), `false` for the periodic ping while one stays attached (just touches `lastSeenAt`,
+ * at most every USER_PRESENCE_WRITE_MS). Not the web-ws upgrade — the app never dials that itself.
+ *
+ * One row per (user, machine, day): a person with the app open on two computers gets two rows that
+ * day, so "users online on day X" is a distinct count of `userId`, never a row count.
*
* `connections` counts app sessions OPENED on that day: a touch that is the first write of a new
* UTC day but is not an open (a session spanning midnight) creates the row with `connections: 0`,
@@ -31,13 +47,14 @@ import { utcDayKey, utcDayStart } from '../types/analytics.js'
*/
export async function touchUserOnlineDay(
userId: string,
+ machineId: string,
now: Date,
opts: { isNewConnection: boolean },
): Promise<void> {
const dayUtc = utcDayStart(now)
await prisma.userDailyPresence.upsert({
- where: { userId_dayUtc: { userId, dayUtc } },
- create: { userId, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now },
+ where: { userId_machineId_dayUtc: { userId, machineId, dayUtc } },
+ create: { userId, machineId, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now },
update: {
lastSeenAt: now,
...(opts.isNewConnection ? { connections: { increment: 1 } } : {}),
@@ -66,15 +83,16 @@ export async function touchDeviceOnlineDay(
userId: string,
deviceId: string,
now: Date,
- opts: { isNewConnection: boolean },
+ opts: PresenceTouchOpts,
): Promise<void> {
const dayUtc = utcDayStart(now)
await prisma.userDailyDevicePresence.upsert({
where: { userId_deviceId_dayUtc: { userId, deviceId, dayUtc } },
- create: { userId, deviceId, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now },
+ create: { userId, deviceId, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now, ...(opts.countryCode ? { countryCode: opts.countryCode } : {}) },
update: {
lastSeenAt: now,
...(opts.isNewConnection ? { connections: { increment: 1 } } : {}),
+ ...(opts.countryCode ? { countryCode: opts.countryCode } : {}),
},
})
}
@@ -88,15 +106,16 @@ export async function touchMachineOnlineDay(
userId: string,
machineId: string,
now: Date,
- opts: { isNewConnection: boolean },
+ opts: PresenceTouchOpts,
): Promise<void> {
const dayUtc = utcDayStart(now)
await prisma.machineDailyPresence.upsert({
where: { machineId_dayUtc: { machineId, dayUtc } },
- create: { machineId, userId, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now },
+ create: { machineId, userId, dayUtc, connections: opts.isNewConnection ? 1 : 0, firstSeenAt: now, lastSeenAt: now, ...(opts.countryCode ? { countryCode: opts.countryCode } : {}) },
update: {
lastSeenAt: now,
...(opts.isNewConnection ? { connections: { increment: 1 } } : {}),
+ ...(opts.countryCode ? { countryCode: opts.countryCode } : {}),
},
})
}
diff --git a/backend/src/lib/db/migrate.test.ts b/backend/src/lib/db/migrate.test.ts
new file mode 100644
index 000000000..383cde6ac
--- /dev/null
+++ b/backend/src/lib/db/migrate.test.ts
@@ -0,0 +1,78 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const db = vi.hoisted(() => ({ runCommandRaw: vi.fn() }))
+
+vi.mock('../../config/env.js', () => ({ env: { DATABASE_URL: 'mongodb://test' } }))
+vi.mock('../prisma.js', () => ({ prisma: { $runCommandRaw: db.runCommandRaw } }))
+vi.mock('../../utils/logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }))
+
+import { dropLegacyUniqueIndex, migrateUserPresencePerMachine } from './migrate.js'
+
+function listIndexes(indexes: Array<{ name: string; key: Record<string, number>; unique?: boolean }>): void {
+ db.runCommandRaw.mockImplementation(async (cmd: Record<string, unknown>) => {
+ if ('listIndexes' in cmd) return { cursor: { firstBatch: indexes } }
+ return { ok: 1 }
+ })
+}
+
+function droppedIndexes(): string[] {
+ return db.runCommandRaw.mock.calls
+ .map((c) => c[0] as Record<string, unknown>)
+ .filter((cmd) => 'dropIndexes' in cmd)
+ .map((cmd) => cmd.index as string)
+}
+
+describe('dropLegacyUniqueIndex', () => {
+ beforeEach(() => { db.runCommandRaw.mockReset() })
+
+ it('drops exactly the unique index whose key is the given field set', async () => {
+ listIndexes([
+ { name: '_id_', key: { _id: 1 } },
+ { name: 'userId_1_dayUtc_1', key: { userId: 1, dayUtc: 1 }, unique: true },
+ ])
+ await dropLegacyUniqueIndex('user_daily_presence', ['userId', 'dayUtc'])
+ expect(droppedIndexes()).toEqual(['userId_1_dayUtc_1'])
+ expect(db.runCommandRaw).toHaveBeenCalledWith({ dropIndexes: 'user_daily_presence', index: 'userId_1_dayUtc_1' })
+ })
+
+ it('leaves the compound replacement and the non-unique twin alone', async () => {
+ listIndexes([
+ { name: 'userId_1_machineId_1_dayUtc_1', key: { userId: 1, machineId: 1, dayUtc: 1 }, unique: true },
+ { name: 'userId_1_dayUtc_1', key: { userId: 1, dayUtc: 1 } },
+ ])
+ await dropLegacyUniqueIndex('user_daily_presence', ['userId', 'dayUtc'])
+ expect(droppedIndexes()).toEqual([])
+ })
+
+ it('does not match a unique index with only some of the fields', async () => {
+ listIndexes([{ name: 'userId_1', key: { userId: 1 }, unique: true }])
+ await dropLegacyUniqueIndex('user_daily_presence', ['userId', 'dayUtc'])
+ expect(droppedIndexes()).toEqual([])
+ })
+
+ it('still finds a single-field legacy index (the pre-existing call sites)', async () => {
+ listIndexes([{ name: 'name_1', key: { name: 1 }, unique: true }])
+ await dropLegacyUniqueIndex('subscription_plans', ['name'])
+ expect(droppedIndexes()).toEqual(['name_1'])
+ })
+
+ it('swallows listIndexes failures (cold database) and never throws', async () => {
+ db.runCommandRaw.mockRejectedValue(new Error('ns not found'))
+ await expect(dropLegacyUniqueIndex('user_daily_presence', ['userId', 'dayUtc'])).resolves.toBeUndefined()
+ })
+})
+
+describe('migrateUserPresencePerMachine', () => {
+ beforeEach(() => { db.runCommandRaw.mockReset() })
+
+ it('drops the old (user, day) unique on user_daily_presence and is a no-op once it is gone', async () => {
+ listIndexes([{ name: 'user_daily_presence_userId_dayUtc_key', key: { userId: 1, dayUtc: 1 }, unique: true }])
+ await migrateUserPresencePerMachine()
+ expect(droppedIndexes()).toEqual(['user_daily_presence_userId_dayUtc_key'])
+
+ db.runCommandRaw.mockClear()
+ listIndexes([{ name: 'user_daily_presence_userId_machineId_dayUtc_key', key: { userId: 1, machineId: 1, dayUtc: 1 }, unique: true }])
+ await migrateUserPresencePerMachine()
+ expect(droppedIndexes()).toEqual([])
+ })
+})
diff --git a/backend/src/lib/db/migrate.ts b/backend/src/lib/db/migrate.ts
index d9d4f4dca..2b1251533 100644
--- a/backend/src/lib/db/migrate.ts
+++ b/backend/src/lib/db/migrate.ts
@@ -39,7 +39,12 @@ export function ensureSchema(): void {
type MongoIndex = { name?: string; key?: Record<string, number>; unique?: boolean }
-async function dropLegacyUniqueIndex(collection: string, field: string): Promise<void> {
+/**
+ * Drop the unique index on `collection` whose key is EXACTLY `fields` (ascending, same count, same
+ * members). A superset or subset key is a different index — the compound replacement Prisma is
+ * about to install must never match. Idempotent: no such index, no-op.
+ */
+export async function dropLegacyUniqueIndex(collection: string, fields: string[]): Promise<void> {
try {
const result = (await prisma.$runCommandRaw({ listIndexes: collection, cursor: {} })) as {
cursor?: { firstBatch?: MongoIndex[] }
@@ -47,15 +52,15 @@ async function dropLegacyUniqueIndex(collection: string, field: string): Promise
const index = result.cursor?.firstBatch?.find((candidate) =>
candidate.unique === true &&
candidate.key != null &&
- Object.keys(candidate.key).length === 1 &&
- candidate.key[field] === 1)
+ Object.keys(candidate.key).length === fields.length &&
+ fields.every((field) => candidate.key![field] === 1))
if (!index?.name) return
await prisma.$runCommandRaw({ dropIndexes: collection, index: index.name })
- logger.info('legacy environment-global unique index removed', { collection, index: index.name })
+ logger.info('legacy unique index removed', { collection, index: index.name })
} catch (err) {
// NamespaceNotFound is expected on a cold database. Any real failure will also be retried on the
// next worker boot, while ensureSchema logs whether the replacement indexes could be installed.
- logger.warn('legacy unique index cleanup skipped', { collection, field, error: String(err) })
+ logger.warn('legacy unique index cleanup skipped', { collection, fields, error: String(err) })
}
}
@@ -95,8 +100,20 @@ export async function migrateAutonomousEnvironment(): Promise<void> {
// The old global constraints prevent storing the same plan name/free entitlement in both planes.
// Drop only those exact single-field unique indexes; Prisma recreates the compound replacements.
- await dropLegacyUniqueIndex('subscription_plans', 'name')
- await dropLegacyUniqueIndex('machine_free_entitlements', 'userId')
+ await dropLegacyUniqueIndex('subscription_plans', ['name'])
+ await dropLegacyUniqueIndex('machine_free_entitlements', ['userId'])
+}
+
+/**
+ * `user_daily_presence` went from one row per (user, day) to one per (user, machine, day). The old
+ * `(userId, dayUtc)` unique index would E11000 the first time a person opens the app on a second
+ * computer the same day, so drop it BEFORE db push installs the `(userId, machineId, dayUtc)` unique
+ * and the non-unique `(userId, dayUtc)` that replaces it. Legacy rows are left as they are: they have
+ * no `machineId`, and were already distinct on (userId, dayUtc), so the new unique index builds over
+ * them without conflict.
+ */
+export async function migrateUserPresencePerMachine(): Promise<void> {
+ await dropLegacyUniqueIndex('user_daily_presence', ['userId', 'dayUtc'])
}
const PENDING_EMAIL_SUFFIX = '@pending.harness.invalid'
diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.ts
index fbebac0b5..f7dadf544 100644
--- a/backend/src/lib/deviceWs.ts
+++ b/backend/src/lib/deviceWs.ts
@@ -29,6 +29,7 @@ import { reserveVoice, releaseVoice } from './voiceBudget.js'
import { prisma } from './prisma.js'
import { deviceService } from '../services/index.js'
import { touchDeviceOnlineDay } from './dailyTracking.js'
+import { countryCodeFromHeaders } from './clientGeo.js'
import { utcDayKey } from '../types/analytics.js'
import { agentLimit, recordCreatedAgent } from './agentTracker.js'
import { env } from '../config/env.js'
@@ -289,6 +290,8 @@ interface RelayOpts {
* machine from the other one. `webWs` has always enforced this; the device plane could not, because
* until SSO auth landed here there was no authenticated env to compare against. */
autonomousEnv: 'prod' | 'stag'
+ /** Cloudflare `CF-IPCountry` at the upgrade (lib/clientGeo.ts); undefined off-Cloudflare. */
+ countryCode?: string
}
/** Hook from server.ts `upgrade` for `/api/device-ws`.
@@ -346,7 +349,13 @@ export function handleDeviceUpgrade(req: IncomingMessage, socket: Duplex, head:
label ?? 'computer',
)
wss.handleUpgrade(req, socket, head, (ws) =>
- relay(ws, { userId: device.userId, deviceId: device.deviceId, autonomousEnv: user.autonomousEnv }))
+ relay(ws, {
+ userId: device.userId,
+ deviceId: device.deviceId,
+ autonomousEnv: user.autonomousEnv,
+ // Where this device is, per Cloudflare (absent off-Cloudflare); lands on the daily presence row.
+ countryCode: countryCodeFromHeaders(req.headers),
+ }))
})().catch((err) => {
if (err instanceof AppError) { denyWith(err.statusCode, 'Service Unavailable'); return }
logger.warn('device-ws upgrade failed', { error: errMsg(err) })
@@ -461,7 +470,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {
const now = new Date()
const dayKey = utcDayKey(now)
if (!isNewConnection && dayKey === lastDevicePresenceDayKey) return
- touchDeviceOnlineDay(userId, id, now, { isNewConnection })
+ touchDeviceOnlineDay(userId, id, now, { isNewConnection, countryCode: opts.countryCode })
.then(() => { lastDevicePresenceDayKey = dayKey })
.catch((err) => logger.warn('device presence tracking failed', { userId, deviceId: id, error: String(err) }))
}
diff --git a/backend/src/middlewares/authMiddleware.test.ts b/backend/src/middlewares/authMiddleware.test.ts
index 7b625da0b..82ae40e67 100644
--- a/backend/src/middlewares/authMiddleware.test.ts
+++ b/backend/src/middlewares/authMiddleware.test.ts
@@ -1,22 +1,56 @@
import Fastify from 'fastify'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+const geo = vi.hoisted(() => ({ stampUserCountry: vi.fn() }))
+vi.mock('../lib/clientGeo.js', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../lib/clientGeo.js')>()),
+ stampUserCountry: geo.stampUserCountry,
+}))
+
import { SsoAuthError } from '../lib/ssoAuth.js'
import { registerAuthMiddleware, resolveSsoAuth, shouldSkipAuth } from './authMiddleware.js'
const authenticate = vi.fn()
-async function request() {
+async function request(extraHeaders: Record<string, string> = {}) {
const app = Fastify()
registerAuthMiddleware(app, authenticate)
app.get('/private', async (req) => ({ user: req.user }))
- const result = await app.inject({ method: 'GET', url: '/private', headers: { authorization: 'Bearer sso-token' } })
+ const result = await app.inject({
+ method: 'GET',
+ url: '/private',
+ headers: { authorization: 'Bearer sso-token', ...extraHeaders },
+ })
await app.close()
return result
}
describe('control-plane SSO auth middleware', () => {
- beforeEach(() => authenticate.mockReset())
+ beforeEach(() => {
+ authenticate.mockReset()
+ geo.stampUserCountry.mockReset()
+ geo.stampUserCountry.mockResolvedValue(undefined)
+ })
+
+ it('stamps the Cloudflare country on the authenticated user, off the request path', async () => {
+ authenticate.mockResolvedValue({ sub: 'internal-1', email: '[email protected]', role: 'user' })
+ const res = await request({ 'cf-ipcountry': 'VN' })
+ expect(res.statusCode).toBe(200)
+ expect(geo.stampUserCountry).toHaveBeenCalledWith('internal-1', 'VN')
+ })
+
+ it('stamps nothing when the request did not come through Cloudflare', async () => {
+ authenticate.mockResolvedValue({ sub: 'internal-1', email: '[email protected]', role: 'user' })
+ await request()
+ expect(geo.stampUserCountry).not.toHaveBeenCalled()
+ })
+
+ it('stamps nothing for a rejected token', async () => {
+ authenticate.mockRejectedValue(new SsoAuthError('expired', 'INVALID_TOKEN'))
+ const res = await request({ 'cf-ipcountry': 'VN' })
+ expect(res.statusCode).toBe(401)
+ expect(geo.stampUserCountry).not.toHaveBeenCalled()
+ })
it('attaches the internal user resolved from a valid access token', async () => {
authenticate.mockResolvedValue({ sub: 'internal-1', email: '[email protected]', role: 'user' })
diff --git a/backend/src/middlewares/authMiddleware.ts b/backend/src/middlewares/authMiddleware.ts
index e02723ee9..93f4b2a07 100644
--- a/backend/src/middlewares/authMiddleware.ts
+++ b/backend/src/middlewares/authMiddleware.ts
@@ -3,6 +3,7 @@ import { authenticateAccessToken, bearerToken, SsoAuthError } from '../lib/ssoAu
import type { AuthUser } from '../lib/ssoAuth.js'
import { ForbiddenError } from '../errors/index.js'
import { parseAutonomousEnvironment, type AutonomousEnvironment } from '../lib/autonomousEnvironment.js'
+import { countryCodeFromHeaders, stampUserCountry } from '../lib/clientGeo.js'
/**
* Public local routes (no user access token). Data-plane requests never reach Fastify — they're
@@ -70,6 +71,11 @@ export function registerAuthMiddleware(
const auth = await resolveSsoAuth(token, authenticate, autonomousEnv)
if ('user' in auth) {
request.user = auth.user
+ // Where the person is, per Cloudflare (`CF-IPCountry`, absent off-Cloudflare). Every control-plane
+ // call comes from their own computer, which is what makes this — and not the daemon's socket —
+ // the "user country" signal. Fire-and-forget and rate-floored inside; never on the request path.
+ const countryCode = countryCodeFromHeaders(request.headers)
+ if (countryCode) void stampUserCountry(auth.user.sub, countryCode)
return
}
return reply.code(auth.status).send({
diff --git a/backend/src/worker.ts b/backend/src/worker.ts
index b94694f09..b3fd84925 100644
--- a/backend/src/worker.ts
+++ b/backend/src/worker.ts
@@ -8,6 +8,7 @@ import {
migrateAutonomousEnvironment,
migrateMachineRename,
migrateUserIdentityByEmail,
+ migrateUserPresencePerMachine,
pruneLegacyDeviceBindings,
} from './lib/db/migrate.js'
import { ensurePlans } from './lib/db/seed.js'
@@ -22,6 +23,8 @@ async function start(): Promise<void> {
// the old global unique indexes for their per-environment replacements.
await migrateAutonomousEnvironment()
await migrateUserIdentityByEmail()
+ // Same reason: the old (user, day) unique must be gone before the push installs its replacement.
+ await migrateUserPresencePerMachine()
ensureSchema()
// AFTER the push: it creates the new collections + their unique indexes, and the copy uses $merge
// so those indexes survive. Copying first would leave the unique index build to fail silently.