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
6 changes: 6 additions & 0 deletions apps/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ npm run dev

Fill the local `.env` without committing it. PostgreSQL and Redis are required to start the service; external integrations are optional only when the exercised code path permits.

## Request telemetry

Request analytics use an anonymous allowlist with no payloads or person lookups.
See the [event contract and PostHog privacy review](docs/request-telemetry.md) for
route grouping, dashboard migration and historical-data remediation.

## Redis cache maintenance

Every Redis key uses `REDIS_KEY_PREFIX` (default `lovat:`). The example local
Expand Down
60 changes: 60 additions & 0 deletions apps/server/docs/request-telemetry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Request telemetry

The Server emits one anonymous `response` event after each response finishes.
Use `route`, `method`, `statusCode` and `responseTime` for endpoint counts, error
rates and latency. Counts include anonymous callers and polling requests; this
changes the volume and meaning of older identity-dependent `response` events.
Static files served before the reporter, rejected JSON bodies and CORS failures
are outside this middleware's coverage. Compare trends across the deployment
boundary with that change in coverage in mind.

## Event contract

The event has a server-generated timestamp and the fixed distinct ID
`lovat-server`. Person-profile processing and GeoIP are disabled. Its properties
are limited to:

- `service`, `environment`, `railwayDeployment`: deployment configuration.
- `requestId`: fresh random UUID, independent of caller headers and identity.
- `method`: standard HTTP method or `OTHER`.
- `route`: registered Express route pattern under a known literal mount, or
`unmatched`. Parameter values, query strings and unknown paths never appear.
- `statusCode`, `responseTime`: HTTP status and elapsed milliseconds.
- `errorCode`: `SERVER_ERROR` for 5xx, `REQUEST_ERROR` for 4xx, absent on success.
These are coarse classifications, never application error messages or bodies.
- `cache`: `hit`, `miss` or `unknown`.
- `$process_person_profile: false`; the shared client also adds
`eventSource: server` and the configured `environment`.

There are no request/response bodies, headers, URLs, IPs, user or scouter
identifiers, team codes, person properties or aliases. Telemetry performs no
PostgreSQL/Redis lookup. SDK capture failures log a constant message and cannot
change the HTTP response.

Mounts are explicitly allowlisted in `posthogMiddleware.ts`. Keep this list in
sync when adding literal router mounts. Parameterized and unknown mounts
intentionally aggregate under `unmatched`; never normalize by copying `baseUrl`
or `originalUrl` into an event. Route patterns must remain source-code constants.

## Post-deployment privacy review (LVT-334)

The code change prevents new request events from carrying sensitive data. It
does not delete historical events or change hosted PostHog permissions. A Lovat
PostHog project administrator must complete and record the following before the
issue's historical-data acceptance item can be closed:

1. Identify the actual project receiving `POSTHOG_PROJECT_API_KEY`, without
copying the key into tickets or logs. Record project ID and reviewer/date.
2. Review historical `response` properties (`reqBody`, `resBody`, `query`, `path`,
`$set`, `$ip`, team codes and person/alias associations), retention, exports,
destinations and any downstream copies. Record the affected time range and
approved remediation; verify deletion through the provider's supported tools.
3. Review project members, organization administrators, roles and service/API
tokens. Record who retains access and why; restrict to the people operating
Lovat. No live access policy has been verified by this implementation.
4. Check event volume and retention after deployment. Migrate existing charts
from `path`/`$pathname` to `route`, remove person-level breakdowns, and verify
endpoint totals, 5xx rate and latency using the anonymous schema.

Do not paste captured payloads into an issue as review evidence. Record only
safe metadata, decisions and confirmation of completed remediation.
293 changes: 85 additions & 208 deletions apps/server/src/lib/middleware/posthogMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,215 +1,92 @@
import { Request, Response, NextFunction } from "express";
import { AuthenticatedRequest } from "./requireAuth.js";
import { randomUUID } from "node:crypto";
import type { Request, Response, NextFunction } from "express";
import { posthog } from "../../posthogClient.js";
import { kv } from "../../redisClient.js";
import prisma from "../../prismaClient.js";
import z from "zod";
import { runBackgroundTask } from "../errors.js";

const ALIAS_TTL_SECONDS = 60 * 60 * 24 * 30;
const getAliasCacheKey = (deviceId: string, scouterUuid: string) =>
`posthog:alias:${deviceId}:${scouterUuid}`;

const posthogReporter = async (
req: Request | AuthenticatedRequest,
import { ENVIRONMENT } from "../environment.js";

// Only literal mounts declared by app.ts and routes/*.routes.ts are safe.
// Express baseUrl contains actual values for parameterized mounts, so new or
// dynamic mounts fall back to an aggregate instead of exposing those values.
const telemetryMounts = new Set([
"/v1",
"/v1/slack",
"/v1/manager",
"/v1/analysis",
...[
"onboarding",
"picklists",
"mutablepicklists",
"registeredteams",
"scoutershifts",
"tournament",
"scoutreports",
"settings",
"apikey",
].map((mount) => `/v1/manager/${mount}`),
"/collection",
"/v2/collection",
]);
const methods = new Set([
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"HEAD",
"OPTIONS",
]);

const posthogReporter = (
req: Request,
res: Response,
next: NextFunction,
): Promise<void> => {
const t0 = performance.now();
const shouldSkipEvent = (statusCode: number) => {
if (statusCode >= 500) {
return false;
}

if (req.method !== "GET") {
return false;
}

const routePath = req.route?.path;
if (!routePath) {
return false;
): void => {
const started = performance.now();
// Never trust a caller-supplied request ID as telemetry.
const requestId = randomUUID();

res.once("finish", () => {
const routePath: unknown = req.route?.path;
// Express can clear baseUrl when an error unwinds a router. Count those
// responses as unmatched unless the request matches a literal root route.
const route =
typeof routePath === "string" &&
(telemetryMounts.has(req.baseUrl) ||
(req.baseUrl === "" && req.path === routePath))
? `${req.baseUrl}${routePath}`
: "unmatched";
const cache = res.getHeader("X-Lovat-Cache");

try {
posthog.capture({
distinctId: "lovat-server",
event: "response",
timestamp: new Date(),
disableGeoip: true,
properties: {
$process_person_profile: false,
service: "server",
environment: ENVIRONMENT,
requestId,
railwayDeployment: process.env.RAILWAY_DEPLOYMENT_ID,
method: methods.has(req.method) ? req.method : "OTHER",
route,
statusCode: res.statusCode,
errorCode:
res.statusCode >= 500
? "SERVER_ERROR"
: res.statusCode >= 400
? "REQUEST_ERROR"
: undefined,
responseTime: Math.round(performance.now() - started),
cache: cache === "hit" || cache === "miss" ? cache : "unknown",
},
});
} catch {
// Analytics must never affect the response or log an SDK error that may
// contain a serialized payload or provider credentials.
console.error("Request analytics failed");
}

const path = `${req.baseUrl}${routePath}`;
return (
path === "/v1/manager/scouters/:uuid/tournaments" ||
path === "/v1/manager/scouters" ||
path === "/v1/manager/scouterschedules/:tournament"
);
};
const getHeaderValue = (headerName: string) => {
const value = req.headers[headerName];

return Array.isArray(value) ? value[0] : value;
};

let resBody: unknown;
const originalSend = res.send.bind(res);
res.send = function (body?: unknown) {
if (res.statusCode >= 400) {
try {
resBody = typeof body === "string" ? JSON.parse(body) : body;
} catch {
resBody = body;
}
}
return originalSend(body);
};

res.once("finish", () =>
runBackgroundTask(async () => {
const t1 = performance.now();

const user = "user" in req && req.user;
const teamCode = getHeaderValue("x-team-code");
const appVersion = getHeaderValue("x-app-version");
const osName = getHeaderValue("x-os-name");
const scouterUuid = getHeaderValue("x-scouter-uuid");
const deviceId = getHeaderValue("x-device-id");
const appBuild = getHeaderValue("x-build-number");

let userProps;

if (user) {
userProps = {
name: user.username,
email: user.email,
role: user.role,
userType: "user", // as opposed to scouter
teamNumber: user.teamNumber,
$ip: req.ips[0] || req.ip,
};
} else {
try {
const parsedTeamCode = z.string().optional().parse(teamCode);
const parsedScouterUuid = z.string().optional().parse(scouterUuid);

if (parsedScouterUuid) {
const scouter = await prisma.scouter.findUnique({
where: {
uuid: parsedScouterUuid,
},
});

if (scouter) {
userProps = {
uuid: scouter.uuid,
name: scouter.name,
userType: "scouter",
teamNumber: scouter.sourceTeamNumber,
teamCode: parsedTeamCode,
};
}
}

if (!userProps && parsedTeamCode) {
const team = await prisma.registeredTeam.findUnique({
where: {
code: parsedTeamCode,
},
});

userProps = {
teamCode: parsedTeamCode,
userType: "scouter",
teamNumber: team?.number,
};
}
} catch (error) {
console.error(error);
}
}

if (userProps?.userType === "user") {
if (shouldSkipEvent(res.statusCode)) {
return;
}

posthog.capture({
distinctId: user.id,
event: "response",
properties: {
$ip: req.ips[0] || req.ip,
$set: userProps,
$pathname: req.baseUrl + req.route?.path,
method: req.method,
cache: res.getHeader("X-Lovat-Cache"),
authType: req["tokenType"],
$os_name: osName,
appVersion,
appBuild,
path: req.originalUrl,
query: req.query,
reqBody: req.body,
resBody,
statusCode: res.statusCode,
railwayDeployment: process.env.RAILWAY_DEPLOYMENT_ID,
railwayReplica: process.env.RAILWAY_REPLICA_ID,
gitCommit: process.env.RAILWAY_GIT_COMMIT_SHA,
responseTime: Math.round(t1 - t0),
},
disableGeoip: false,
});
}
if (userProps?.userType === "scouter") {
if (shouldSkipEvent(res.statusCode)) {
return;
}

const distinctId =
userProps.uuid ??
deviceId ??
(req.ip ? `scouter:ip:${req.ip}` : "scouter:unknown");

if (deviceId && userProps.uuid) {
const aliasKey = getAliasCacheKey(deviceId, userProps.uuid);
const alreadyAliased = await kv.get(aliasKey);

if (!alreadyAliased) {
posthog.alias({
distinctId: deviceId,
alias: userProps.uuid,
});
await kv.setEx(aliasKey, "1", ALIAS_TTL_SECONDS);
}
}

posthog.capture({
distinctId,
event: "response",
properties: {
$ip: req.ips[0] || req.ip,
$set: userProps,
$pathname: req.baseUrl + req.route?.path,
method: req.method,
cache: res.getHeader("X-Lovat-Cache"),
$os_name: osName,
appVersion,
appBuild,
path: req.originalUrl,
query: req.query,
reqBody: req.body,
resBody,
statusCode: res.statusCode,
railwayDeployment: process.env.RAILWAY_DEPLOYMENT_ID,
railwayReplica: process.env.RAILWAY_REPLICA_ID,
gitCommit: process.env.RAILWAY_GIT_COMMIT_SHA,
responseTime: Math.round(t1 - t0),
},
disableGeoip: false,
});
}
if (process.env.NODE_ENV === "development") {
console.log(
"%s %s: %d ms, HTTP %d",
req.method,
req.originalUrl,
Math.round(t1 - t0),
res.statusCode,
);
}
}, "Request analytics failed"),
);
});

next();
};
Expand Down
Loading
Loading