返回 CodeWhale
route.ts
根目录 / web / app / api / product-telemetry / route.ts
1 import { BodyReadError, readBoundedBody } from "@/lib/bounded-body";
2 import { NextResponse } from "next/server";
3 import { MAX_ENVELOPE_BYTES, privacySignalHeader, validateEnvelope } from "@/lib/telemetry/product-usage";
4
5 /**
6 * POST /api/product-telemetry — the website's same-origin forwarder.
7 *
8 * Inert without configuration: unless `CODEWHALE_TELEMETRY_INGEST_URL` is set
9 * to the exact canonical first-party ingest, the route accepts nothing and
10 * forwards nothing. With it set, a batch is forwarded only when it passes the
11 * closed-set validator for the `website` surface and fits in 4 KiB. The
12 * forward sets only a content-type header and the validated body; it does not
13 * copy client headers. Hosting infrastructure may add transport headers, so
14 * this is not a claim of network anonymity. Forwarding has a 1.5-second timeout
15 * with no retry. The response is
16 * `{ accepted, reason? }`, never the ingest's own body.
17 */
18
19 // No `runtime = "edge"`: @opennextjs/cloudflare does not support the edge
20 // runtime. Its `migrate` command says to remove the declaration, and its
21 // server bundle replaces Next's edge runtime with an empty shim. How the
22 // deployed route behaved while it was declared has not been checked. The
23 // default runtime already has fetch, Request, and TextDecoder.
24
25 export const CANONICAL_INGEST_URL = "https://telemetry.codewhale.net/v1/telemetry";
26 const FORWARD_TIMEOUT_MS = 1500;
27
28 export function ingestUrl(env: Record<string, string | undefined> = process.env): string | null {
29 const configured = env.CODEWHALE_TELEMETRY_INGEST_URL?.trim();
30 return configured === CANONICAL_INGEST_URL ? configured : null;
31 }
32
33 type Forward = (url: string, body: string, signal: AbortSignal) => Promise<{ ok: boolean }>;
34
35 const defaultForward: Forward = (url, body, signal) =>
36 fetch(url, {
37 method: "POST",
38 headers: { "content-type": "application/json" },
39 body,
40 signal,
41 redirect: "error",
42 });
43
44 export async function handleProductTelemetry(
45 request: Request,
46 deps: { ingestUrl?: string | null; forward?: Forward } = {},
47 ): Promise<Response> {
48 const target = deps.ingestUrl === undefined ? ingestUrl() : deps.ingestUrl;
49 const reply = (status: number, accepted: boolean, reason?: string) =>
50 NextResponse.json(reason ? { accepted, reason } : { accepted }, {
51 status,
52 headers: { "cache-control": "no-store" },
53 });
54
55 if (privacySignalHeader(request.headers) || !target) return reply(200, false, "disabled");
56
57 let text: string;
58 try {
59 const bytes = await readBoundedBody(request, MAX_ENVELOPE_BYTES);
60 text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
61 } catch (cause) {
62 if (cause instanceof BodyReadError) {
63 return reply(cause.status, false, cause.status === 413 ? "too_large" : "invalid_body");
64 }
65 return reply(422, false, "invalid_json");
66 }
67
68 let parsed: unknown;
69 try {
70 parsed = JSON.parse(text);
71 } catch {
72 return reply(422, false, "invalid_json");
73 }
74 const validated = validateEnvelope(parsed, { surfaces: ["website"] });
75 if (!validated.ok) return reply(422, false, "schema");
76
77 const controller = new AbortController();
78 const timer = setTimeout(() => controller.abort(), FORWARD_TIMEOUT_MS);
79 try {
80 // Re-serialise the validated envelope so only known fields travel.
81 const response = await (deps.forward ?? defaultForward)(
82 target,
83 JSON.stringify(validated.envelope),
84 controller.signal,
85 );
86 return reply(200, response.ok, response.ok ? undefined : "unavailable");
87 } catch {
88 return reply(200, false, "unavailable");
89 } finally {
90 clearTimeout(timer);
91 }
92 }
93
94 export async function POST(request: Request): Promise<Response> {
95 return handleProductTelemetry(request);
96 }
97
97 lines TYPESCRIPT