Files
freno-dev/src/routes/api/the-nook/download.test.ts
Paperclip Agent 1d9287a199 analytics: fix the two FRE-369 findings in the funnel instrumentation
The security review of 39d874a (FRE-369) found the address fix recorded
the wrong thing twice. Both are fixed here; the branch is the same one
under review, this commit does not rewrite it.

Q1 — the first x-forwarded-for hop is attacker-chosen text. In
client → Cloudflare → same-host proxy → app, both proxies *append*, so
the header arrives as `<client spoof…>, <true client>, <CF edge>` and
`split(",")[0]` took the sender's own invention — the loopback-peer gate
was sound, the hop selection defeated it. Preference is now
`cf-connecting-ip` (Cloudflare overwrites it, so a client value never
survives the edge), then x-forwarded-for counted from the right with one
trusted hop discounted, then the direct peer. Every candidate must parse
as an address. h3's `getRequestIP(…, { xForwardedFor: true })` has the
same leftmost flaw and is documented as not a fix.

Q4 — the table held full client addresses indefinitely. Every analytics
entry now passes through `truncateIpAddress` in `enrichAnalyticsEntry`
(IPv4 /24, IPv6 /56, unparseable dropped), so no writer can persist a
full address by accident. Retention got the schedule it never had:
`/api/analytics/retention` on a daily Vercel cron, Bearer-authenticated
and fail-closed, with the window parameterised (the old
`cleanupOldAnalytics` spliced the number into the SQL). Default 365 days
rather than the review's 90 so enabling the cron is not itself a
destructive event — the tighter window is an operational decision, named
on the task.

Also from the review: the module doc now forbids feeding this helper into
any security decision; `isLoopbackAddress` parses instead of
string-matching (`::ffff:127.9.9.9`, `0:0:0:0:0:0:0:1`); and `host` is
normalised (lowercased, port stripped) so `nook.freno.me:443` cannot
silently miss the `host = ?` scope. The weekly loopback caveat matches
the truncated shapes writers produce now, and says plainly that "unique
visitors" counts prefixes.
2026-10-29 18:05:44 +00:00

219 lines
6.6 KiB
TypeScript

import { describe, expect, it, mock, beforeEach } from "bun:test";
import { truncateIpAddress } from "~/server/request-client";
// The route's contracts:
// 1. Every click is recorded through the shared analytics buffer with the
// path, referrer, country and device type the funnel needs.
// 2. The response is a no-store 302 to the newest release enclosure, so a
// CDN can never serve a later click without it reaching this handler.
// 3. An unreadable appcast degrades to 503 — but the click is still logged,
// because a failed download is exactly the event worth seeing.
type Entry = Record<string, unknown>;
const logged: Entry[] = [];
let appcastXml = "";
let s3ShouldThrow = false;
let flushCalls = 0;
mock.module("~/env/server", () => ({
env: {
AWS_REGION: "us-east-1",
MY_AWS_ACCESS_KEY: "test-key",
MY_AWS_SECRET_KEY: "test-secret",
VITE_DOWNLOAD_BUCKET_STRING: "test-bucket"
}
}));
mock.module("@aws-sdk/client-s3", () => ({
S3Client: class {
async send() {
if (s3ShouldThrow) throw new Error("s3 unavailable");
return {
Body: appcastXml
? { transformToString: async () => appcastXml }
: null
};
}
},
GetObjectCommand: class {
input: unknown;
constructor(input: unknown) {
this.input = input;
}
}
}));
mock.module("vinxi/http", () => ({
getRequestIP: () => null
}));
mock.module("~/server/analytics", () => ({
logVisit: async (entry: Entry) => {
logged.push(entry);
},
// The route must flush, not merely buffer: the batch timer is not
// guaranteed to survive the response on serverless.
flushAnalytics: async () => {
flushCalls += 1;
},
// Mirrors the real enrichment contract: deviceType is derived from the UA,
// and the address is cut to its prefix by the FRE-369 privacy floor. The
// real `enrichAnalyticsEntry` does both, so the mirror has to apply the same
// truncation — otherwise this file would prove the door stores a full address.
enrichAnalyticsEntry: (entry: Entry) => ({
...entry,
ipAddress: truncateIpAddress(entry.ipAddress as string | null),
deviceType: String(entry.userAgent ?? "").includes("Macintosh")
? "desktop"
: null
})
}));
const { GET } = await import("./download");
const { pickEnclosure, invalidateDownloadCache } = await import("./_download");
const DMG = "https://cdn.example/TheNook-0.6.3.dmg";
const ZIP = "https://cdn.example/TheNook-0.6.3.zip";
const appcast = (urls: string[]) =>
`<?xml version="1.0"?><rss><channel><item>` +
urls
.map(
(u) =>
`<enclosure url="${u}" sparkle:version="1" length="1" type="application/octet-stream"/>`
)
.join("") +
`</item></channel></rss>`;
function request(headers: Record<string, string> = {}, query = "") {
return {
request: new Request(
`https://nook.freno.me/api/the-nook/download${query}`,
{ headers }
),
nativeEvent: {}
} as never;
}
const MAC_UA =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15";
beforeEach(() => {
logged.length = 0;
appcastXml = appcast([DMG, ZIP]);
s3ShouldThrow = false;
flushCalls = 0;
invalidateDownloadCache();
});
describe("GET /api/the-nook/download", () => {
it("logs the click and 302s to the newest dmg", async () => {
const res = await GET(request({ referer: "https://nook.freno.me/" }));
expect(res.status).toBe(302);
expect(res.headers.get("Location")).toBe(DMG);
expect(res.headers.get("Cache-Control")).toBe("no-store");
expect(logged.length).toBe(1);
expect(logged[0]).toMatchObject({
path: "/api/downloads/thenook",
method: "GET",
// The door is the click half of the split; the file route writes
// "served". And the row names the site it came from (FRE-366).
stage: "click",
host: "nook.freno.me",
referrer: "https://nook.freno.me/"
});
// Flushed within the request, not left to the batch timer.
expect(flushCalls).toBe(1);
});
it("derives the device type from the user agent", async () => {
await GET(request({ "user-agent": MAC_UA }));
expect(logged[0]!.deviceType).toBe("desktop");
});
it("records the edge country, and lets ?c= override it", async () => {
await GET(request({ "x-vercel-ip-country": "GB" }));
expect(logged[0]!.country).toBe("GB");
invalidateDownloadCache();
await GET(request({ "cf-ipcountry": "DE" }));
expect(logged[1]!.country).toBe("DE");
invalidateDownloadCache();
await GET(request({ "x-vercel-ip-country": "GB" }, "?c=JP"));
expect(logged[2]!.country).toBe("JP");
});
it("records the forwarded visitor below the trusted edge, truncated", async () => {
// Client → Cloudflare → origin proxy: the sender's spoof is first, the real
// client second, the edge last. And the stored value is the /24, never the
// address itself (FRE-369).
await GET(
request({
"x-forwarded-for": "198.51.100.9, 203.0.113.7, 198.51.100.1"
})
);
expect(logged[0]!.ipAddress).toBe("203.0.113.0");
});
it("still logs the click when the appcast cannot be read", async () => {
s3ShouldThrow = true;
const res = await GET(request());
expect(res.status).toBe(503);
expect(res.headers.get("Cache-Control")).toBe("no-store");
expect(logged.length).toBe(1);
});
it("503s when the appcast carries no enclosure", async () => {
appcastXml = "<?xml version='1.0'?><rss><channel></channel></rss>";
invalidateDownloadCache();
const res = await GET(request());
expect(res.status).toBe(503);
});
it("captures campaign tags from the click URL and the referer", async () => {
await GET(
request(
{ referer: "https://nook.freno.me/?utm_source=hn&utm_campaign=launch" },
"?utm_medium=post"
)
);
expect(logged[0]).toMatchObject({
utmSource: "hn",
utmMedium: "post",
utmCampaign: "launch"
});
});
it("logs nulls when nothing is tagged", async () => {
await GET(request({ referer: "https://nook.freno.me/" }));
expect(logged[0]).toMatchObject({
utmSource: null,
utmMedium: null,
utmCampaign: null
});
});
});
describe("pickEnclosure", () => {
it("prefers a dmg over a zip even when the zip comes first", () => {
expect(pickEnclosure(appcast([ZIP, DMG]))).toBe(DMG);
});
it("falls back to a zip, then to any enclosure", () => {
expect(pickEnclosure(appcast([ZIP]))).toBe(ZIP);
expect(pickEnclosure(appcast(["https://cdn.example/notes.txt"]))).toBe(
"https://cdn.example/notes.txt"
);
});
it("returns null when there is no enclosure", () => {
expect(pickEnclosure("<rss><channel></channel></rss>")).toBeNull();
});
});