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
1 change: 1 addition & 0 deletions docs/site-map.md
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,7 @@ This file is generated by `npm run sitemap:update`. Run `npm run sitemap:check`
- `/api/local-project-id` - Local project identity guard. Source: `src/app/api/local-project-id/route.ts`.
- `/api/medications` - Route discovered from app directory Source: `src/app/api/medications/route.ts`.
- `/api/medications/[slug]` - Route discovered from app directory Source: `src/app/api/medications/[slug]/route.ts`.
- `/api/monitoring` - Route discovered from app directory Source: `src/app/api/monitoring/route.ts`.
- `/api/registry/records` - Registry record collection. Source: `src/app/api/registry/records/route.ts`.
- `/api/registry/records/[slug]` - Registry record detail. Source: `src/app/api/registry/records/[slug]/route.ts`.
- `/api/search` - Search endpoint. Source: `src/app/api/search/route.ts`.
Expand Down
14 changes: 13 additions & 1 deletion next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,24 @@ const nextConfig: NextConfig = {
turbopack: {
root: projectRoot,
},
webpack(config) {
webpack(config, { webpack }) {
// Avoid a Next/webpack WasmHash worker crash observed on Node 24 during local production builds.
config.output = {
...config.output,
hashFunction: "sha256",
};
// Build-time flag so the browser Sentry SDK (@sentry/browser) is fully
// tree-shaken out unless a public DSN is set at build. Next does NOT fold an
// UNSET NEXT_PUBLIC_* var to a compile-time constant, so a plain
// `if (process.env.NEXT_PUBLIC_SENTRY_DSN)` gate leaves the dynamic import (and
// its chunk) on disk. This literal boolean lets webpack dead-code-eliminate the
// whole block, so an unconfigured build ships zero Sentry bytes. See
// src/instrumentation-client.ts.
config.plugins.push(
new webpack.DefinePlugin({
__SENTRY_ENABLED__: JSON.stringify(Boolean(process.env.NEXT_PUBLIC_SENTRY_DSN)),
}),
);
return config;
},
async headers() {
Expand Down
69 changes: 69 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@
},
"dependencies": {
"@next/env": "16.2.10",
"@sentry/browser": "^10.65.0",
"@sentry/node": "^10.65.0",
"@supabase/ssr": "^0.12.0",
"@supabase/supabase-js": "^2.108.2",
Expand Down
144 changes: 144 additions & 0 deletions src/app/api/monitoring/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// Same-origin Sentry tunnel. The browser SDK is configured with
// `tunnel: "/api/monitoring"` (src/instrumentation-client.ts) so event envelopes
// are POSTed here instead of directly to Sentry's ingest host. This keeps the
// strict clinical CSP intact — `connect-src 'self'` already allows this route, so
// no Sentry ingest host has to be added to the policy — and lets ad-blockers that
// block *.sentry.io not silently drop client error reports.
//
// The route forwards the raw envelope to Sentry server-side (server fetches are not
// bound by CSP). Hardening: it (1) validates the envelope's embedded DSN against the
// project's own configured DSN so the endpoint cannot relay to arbitrary projects,
// (2) caps the buffered body at 1 MB (Content-Length preflight + streamed byte
// count) since this is an unauthenticated public POST under a large proxy body
// allowance, and (3) bounds the upstream relay with a timeout. Inert (404) until
// SENTRY_DSN / NEXT_PUBLIC_SENTRY_DSN is set.

export const runtime = "nodejs";

const MAX_ENVELOPE_BYTES = 1_000_000; // 1 MB — Sentry event envelopes are far smaller.
const UPSTREAM_TIMEOUT_MS = 5_000;

// Lightweight per-IP throttle. This is an unauthenticated public POST, so a
// spammer with a valid envelope could otherwise burn the project's Sentry ingest
// quota. A per-instance in-memory window is intentionally simple (unlike the
// durable answer/upload limiters this is best-effort telemetry relay, not a paid
// or state-changing path); Sentry's own ingest rate limits are the backstop.
const RATE_LIMIT_MAX = 120;
const RATE_LIMIT_WINDOW_MS = 60_000;
type RateWindow = { count: number; resetAt: number };
const rateLimitByIp = new Map<string, RateWindow>();

function isRateLimited(ip: string): boolean {
const now = Date.now();
if (rateLimitByIp.size > 5_000) {
for (const [key, window] of rateLimitByIp) if (now >= window.resetAt) rateLimitByIp.delete(key);
}
const existing = rateLimitByIp.get(ip);
if (!existing || now >= existing.resetAt) {
rateLimitByIp.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
return false;
}
existing.count += 1;
return existing.count > RATE_LIMIT_MAX;
}

type ParsedDsn = { host: string; projectId: string };

function parseDsn(dsn: string): ParsedDsn {
const url = new URL(dsn);
const projectId = url.pathname.replace(/^\//, "");
if (!url.host || !projectId) throw new Error("incomplete dsn");
return { host: url.host, projectId };
}

// Reads the request body as text but aborts once it exceeds `maxBytes`, returning
// null. Streams so an oversized body is never fully buffered.
async function readCappedText(request: Request, maxBytes: number): Promise<string | null> {
const reader = request.body?.getReader();
if (!reader) {
const text = await request.text();
return text.length > maxBytes ? null : text;
}
const decoder = new TextDecoder();
let total = 0;
let out = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > maxBytes) {
await reader.cancel();
return null;
}
out += decoder.decode(value, { stream: true });
}
out += decoder.decode();
return out;
}

export async function POST(request: Request): Promise<Response> {
const configuredDsn = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;
if (!configuredDsn) return new Response(null, { status: 404 });

Comment thread
BigSimmo marked this conversation as resolved.
const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
if (isRateLimited(ip)) {
return new Response("too many requests", { status: 429, headers: { "Retry-After": "60" } });
}

let expected: ParsedDsn;
try {
expected = parseDsn(configuredDsn);
} catch {
// Misconfigured server DSN — do not leak detail, just refuse.
return new Response(null, { status: 404 });
}

// Reject oversized payloads before buffering when the length is declared.
const declaredLength = Number(request.headers.get("content-length"));
if (Number.isFinite(declaredLength) && declaredLength > MAX_ENVELOPE_BYTES) {
return new Response("payload too large", { status: 413 });
}

const envelope = await readCappedText(request, MAX_ENVELOPE_BYTES);
if (envelope === null) return new Response("payload too large", { status: 413 });

const firstNewline = envelope.indexOf("\n");
if (firstNewline === -1) return new Response("invalid envelope", { status: 400 });

let header: { dsn?: unknown };
try {
header = JSON.parse(envelope.slice(0, firstNewline));
} catch {
return new Response("invalid envelope header", { status: 400 });
}

if (typeof header.dsn !== "string") return new Response("missing dsn", { status: 400 });

let incoming: ParsedDsn;
try {
incoming = parseDsn(header.dsn);
} catch {
return new Response("invalid dsn", { status: 400 });
}

// Reject anything not addressed to this project's own DSN (no open relay).
if (incoming.host !== expected.host || incoming.projectId !== expected.projectId) {
return new Response("forbidden", { status: 403 });
}

let upstream: Response;
try {
upstream = await fetch(`https://${expected.host}/api/${expected.projectId}/envelope/`, {
method: "POST",
body: envelope,
headers: { "Content-Type": "application/x-sentry-envelope" },
signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
});
} catch {
// Upstream slow/unreachable — fail fast without tying up the request thread.
return new Response("bad gateway", { status: 502 });
}

const body = await upstream.text();
return new Response(body, { status: upstream.status });
}
4 changes: 4 additions & 0 deletions src/app/global-error.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import { useEffect } from "react";

import { captureClientException } from "@/lib/observability/sentry-client";

/**
* Last-resort boundary for the App Router. Unlike `app/error.tsx`, this replaces
* the root layout entirely, so it is the ONLY thing that can recover from an
Expand All @@ -13,6 +15,8 @@ import { useEffect } from "react";
export default function GlobalError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
useEffect(() => {
console.error("Fatal error captured by global-error boundary:", error);
// No-op unless the browser Sentry SDK was initialized (NEXT_PUBLIC_SENTRY_DSN set at build).
captureClientException(error);
}, [error]);

return (
Expand Down
3 changes: 3 additions & 0 deletions src/components/route-error-boundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useEffect } from "react";
import { TriangleAlert, RefreshCw } from "lucide-react";

import { cn, primaryControl } from "@/components/ui-primitives";
import { captureClientException } from "@/lib/observability/sentry-client";

export type RouteErrorBoundaryProps = {
/** The error thrown by the segment, forwarded by Next.js. */
Expand Down Expand Up @@ -40,6 +41,8 @@ export function RouteErrorBoundary({
}: RouteErrorBoundaryProps) {
useEffect(() => {
console.error(logLabel, error);
// No-op unless the browser Sentry SDK was initialized (NEXT_PUBLIC_SENTRY_DSN set at build).
captureClientException(error);
}, [error, logLabel]);

return (
Expand Down
38 changes: 38 additions & 0 deletions src/instrumentation-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,43 @@
// (validation stays correct, just interpreted rather than compiled). The server
// has no CSP, so it keeps the faster JIT path — this is client-only by design.
import { config } from "zod";
import { registerSentryClient } from "@/lib/observability/sentry-client";

config({ jitless: true });

// Gated browser error tracking, the client counterpart to the server-side
// @sentry/node capture in src/instrumentation.ts. `__SENTRY_ENABLED__` is a
// build-time literal boolean injected by DefinePlugin (next.config.ts) — true only
// when a public DSN is set at build. As a real compile-time constant it lets the
// webpack production build dead-code-eliminate this whole block (and the entire
// @sentry/browser chunk) when false, so an unconfigured build ships ZERO Sentry
// bytes. The `typeof` guard keeps it safe under the Turbopack dev server, which
// does not run the webpack DefinePlugin and so leaves the identifier undefined.
// Events go through the same-origin tunnel (/api/monitoring) so the strict
// clinical CSP (connect-src 'self' …) needs no Sentry ingest host.
declare const __SENTRY_ENABLED__: boolean;

if (typeof __SENTRY_ENABLED__ !== "undefined" && __SENTRY_ENABLED__) {
void (async () => {
const [Sentry, { scrubClientSentryEvent }] = await Promise.all([
import("@sentry/browser"),
import("@/lib/observability/sentry-scrub"),
]);
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
tunnel: "/api/monitoring",
environment: process.env.NEXT_PUBLIC_SENTRY_ENVIRONMENT || process.env.NODE_ENV,
// Errors only: no performance tracing (avoids shipping navigation-timing/PII).
tracesSampleRate: 0,
sendDefaultPii: false,
// Same privacy boundary as the server init: strip request + breadcrumbs, and
// never record breadcrumbs in the first place.
beforeSend: scrubClientSentryEvent,
beforeBreadcrumb: () => null,
});
registerSentryClient(Sentry);
})().catch(() => {
// Loading/initializing the SDK is best-effort observability; a failed dynamic
// import (e.g. blocked chunk) must never surface as an unhandled rejection.
});
}
Comment thread
BigSimmo marked this conversation as resolved.
10 changes: 10 additions & 0 deletions src/lib/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ const envSchema = z.object({
(value) => (typeof value === "string" && value.trim() === "" ? undefined : value),
z.string().url().optional(),
),
// Optional client-side (browser) Sentry error capture, the counterpart to the
// server SENTRY_DSN above. This public DSN is safe to expose to the browser. Fully
// inert when unset: the @sentry/browser SDK is tree-shaken out of the client bundle
// (see src/instrumentation-client.ts). Blank is normalized to undefined so an empty
// NEXT_PUBLIC_SENTRY_DSN="" never fails envSchema.parse at startup.
NEXT_PUBLIC_SENTRY_DSN: z.preprocess(
(value) => (typeof value === "string" && value.trim() === "" ? undefined : value),
z.string().url().optional(),
),
NEXT_PUBLIC_SENTRY_ENVIRONMENT: z.string().optional(),
NEXT_PUBLIC_LOCAL_NO_AUTH: z.enum(["true", "false"]).optional().default("false"),
LOCAL_NO_AUTH: z.enum(["true", "false"]).optional().default("false"),
LOCAL_NO_AUTH_OWNER_EMAIL: z.string().optional(),
Expand Down
18 changes: 18 additions & 0 deletions src/lib/observability/sentry-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Client-side Sentry access indirection. Error boundaries call
// captureClientException() without ever statically importing @sentry/browser, so
// a build WITHOUT NEXT_PUBLIC_SENTRY_DSN ships zero Sentry code: instrumentation-
// client.ts only loads the SDK (and registers it here) when a DSN is present at
// build time. Until then every call here is a no-op.
type SentryClientModule = {
captureException: (error: unknown) => string;
};

let client: SentryClientModule | null = null;

export function registerSentryClient(mod: SentryClientModule): void {
client = mod;
}

export function captureClientException(error: unknown): void {
client?.captureException(error);
}
Loading