An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
perf(analytics): proxy /relay straight to PostHog outside Better Auth (#1070)
Yoshiki Miuraf6eb63cd6f89
diff --git a/app/relay/[...path]/route.test.ts b/app/relay/[...path]/route.test.tsindex f2613845..e6c67c9f 100644--- a/app/relay/[...path]/route.test.ts+++ b/app/relay/[...path]/route.test.ts@@ -101,6 +101,19 @@ describe('relay route', () => {expect(fetchMock).not.toHaveBeenCalled()})+ it('refuses segments that carry an encoded slash', async () => {+ const fetchMock = vi.fn(async () => upstreamResponse())+ vi.stubGlobal('fetch', fetchMock)++ const response = await GET(+ new NextRequest('http://localhost:3000/relay/static%2F..%2Fcapture'),+ { params: Promise.resolve({ path: ['static/../capture'] }) }+ )++ expect(response.status).toBe(404)+ expect(fetchMock).not.toHaveBeenCalled()+ })+it('routes static and array paths to the asset host', async () => {const fetchMock = vi.fn(async () => upstreamResponse())vi.stubGlobal('fetch', fetchMock)diff --git a/app/relay/[...path]/route.ts b/app/relay/[...path]/route.tsindex ff9e72ba..28d711b9 100644--- a/app/relay/[...path]/route.ts+++ b/app/relay/[...path]/route.ts@@ -1,14 +1,10 @@import { type NextRequest } from 'next/server'-// Mirrors the destinations of the PostHog proxy rewrites this handler-// replaced.-const ASSET_SEGMENTS = new Set(['static', 'array'])-const ASSET_HOST = 'us-assets.i.posthog.com'-const API_HOST = 'us.i.posthog.com'-// Generous cap that only rejects absurd declared sizes; the body itself-// is streamed through, so an undeclared (chunked) payload cannot be-// used to balloon process memory.-const MAX_BODY_BYTES = 32 * 1024 * 1024+import {+ exceedsRelayBodyCap,+ RELAY_MAX_BODY_BYTES,+ relayTarget+} from '@/lib/analytics/relay-target'export class PayloadTooLargeError extends Error {}@@ -20,7 +16,7 @@ export class PayloadTooLargeError extends Error {}*/export function cappedBody(body: ReadableStream<Uint8Array> | null,- max: number = MAX_BODY_BYTES+ max: number = RELAY_MAX_BODY_BYTES): ReadableStream<Uint8Array> | null {if (!body) {return null@@ -41,30 +37,27 @@ export function cappedBody(}/**- * Same-origin PostHog relay, implemented as a route handler instead of a- * next.config rewrite so credentials are structurally never forwarded:- * a rewrite proxies the incoming request headers (session cookie- * included) to an external host, and keeping any middleware strip in- * sync with the rewrite's path matching is a drift hazard. This handler- * forwards only what PostHog needs and nothing else.+ * Same-origin PostHog relay for Better Auth. A proxy rewrite forwards the+ * incoming request headers to the external host, so this handler builds+ * the upstream request from an explicit allowlist instead: the session+ * cookie is structurally never forwarded. Other providers are rewritten+ * in proxy.ts and do not reach this handler.*/async function relay(request: NextRequest,{ params }: { params: Promise<{ path: string[] }> }): Promise<Response> {const { path } = await params- const host = ASSET_SEGMENTS.has(path[0]) ? ASSET_HOST : API_HOST- const target = new URL(`/${path.join('/')}`, `https://${host}`)- if (target.host !== host) {- // A decoded path segment escaped the PostHog origin (e.g. an encoded- // slash turning the joined path protocol-relative). Refuse rather- // than proxy payloads to an attacker-chosen host.+ // Segments arrive decoded: one holding a slash would shift the path+ // boundaries the host selection relies on.+ const target = path.some(segment => segment.includes('/'))+ ? null+ : relayTarget(`/${path.join('/')}`, request.nextUrl.search)+ if (!target) {return new Response('Not found', { status: 404 })}- target.search = request.nextUrl.search- const contentLength = Number(request.headers.get('content-length'))- if (Number.isFinite(contentLength) && contentLength > MAX_BODY_BYTES) {+ if (exceedsRelayBodyCap(request.headers)) {return new Response('Payload too large', { status: 413 })}diff --git a/lib/analytics/relay-target.ts b/lib/analytics/relay-target.tsnew file mode 100644index 00000000..c9bcbe28--- /dev/null+++ b/lib/analytics/relay-target.ts@@ -0,0 +1,52 @@+const ASSET_SEGMENTS = new Set(['static', 'array'])+const ASSET_HOST = 'us-assets.i.posthog.com'+const API_HOST = 'us.i.posthog.com'++export const RELAY_PREFIX = '/relay'+// Kept below the body size Next buffers for proxied requests.+export const RELAY_MAX_BODY_BYTES = 8 * 1024 * 1024++const FORWARDED_HEADERS = [+ 'accept',+ 'accept-encoding',+ 'accept-language',+ 'content-encoding',+ 'content-length',+ 'content-type',+ 'if-modified-since',+ 'if-none-match',+ 'user-agent',+ 'x-forwarded-for'+]++/** Request headers PostHog needs. Credentials are never among them. */+export function relayRequestHeaders(incoming: Headers): Headers {+ const headers = new Headers()+ for (const name of FORWARDED_HEADERS) {+ const value = incoming.get(name)+ if (value) {+ headers.set(name, value)+ }+ }+ return headers+}++export function exceedsRelayBodyCap(headers: Headers): boolean {+ const declared = Number(headers.get('content-length'))+ return Number.isFinite(declared) && declared > RELAY_MAX_BODY_BYTES+}++/**+ * Maps a path below /relay to its PostHog upstream URL. Returns null when+ * the path resolves off the PostHog origin (e.g. a protocol-relative path+ * built from an encoded slash).+ */+export function relayTarget(path: string, search = ''): URL | null {+ const host = ASSET_SEGMENTS.has(path.split('/')[1]) ? ASSET_HOST : API_HOST+ const target = new URL(path, `https://${host}`)+ if (target.host !== host) {+ return null+ }+ target.search = search+ return target+}diff --git a/proxy.test.ts b/proxy.test.tsindex 16cba587..ecbb9564 100644--- a/proxy.test.ts+++ b/proxy.test.ts@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { betterAuthProvider } from '@/lib/auth/providers/better-auth'import { updateSession } from '@/lib/supabase/middleware'import { proxy } from './proxy'@@ -70,4 +71,95 @@ describe('proxy', () => {expect(updateSession).toHaveBeenCalledTimes(1)})++ describe('PostHog relay', () => {+ it('rewrites API paths straight to PostHog without credentials', async () => {+ const request = new NextRequest('http://localhost:3000/relay/e/?ip=0', {+ method: 'POST',+ headers: {+ cookie: 'sb-access-token=abc',+ authorization: 'Bearer token',+ 'cf-access-jwt-assertion': 'gateway-token',+ 'x-forwarded-for': '203.0.113.7',+ 'user-agent': 'Mozilla/5.0 (test)'+ }+ })+ const response = await proxy(request)++ expect(response.headers.get('x-middleware-rewrite')).toBe(+ 'https://us.i.posthog.com/e/?ip=0'+ )+ const forwarded = response.headers.get('x-middleware-override-headers')+ expect(forwarded?.split(',').sort()).toEqual([+ 'user-agent',+ 'x-forwarded-for'+ ])+ expect(updateSession).not.toHaveBeenCalled()+ })++ it('rewrites static and array paths to the asset host', async () => {+ const response = await proxy(+ new NextRequest('http://localhost:3000/relay/static/array.js')+ )++ expect(response.headers.get('x-middleware-rewrite')).toBe(+ 'https://us-assets.i.posthog.com/static/array.js'+ )+ })++ it('rewrites in anonymous mode too', async () => {+ process.env.ENABLE_AUTH = 'false'+ const response = await proxy(+ new NextRequest('http://localhost:3000/relay/flags/?v=2')+ )++ expect(response.headers.get('x-middleware-rewrite')).toBe(+ 'https://us.i.posthog.com/flags/?v=2'+ )+ })++ it('refuses paths that resolve off the PostHog origin', async () => {+ const response = await proxy(+ new NextRequest('http://localhost:3000/relay//evil.example/x')+ )++ expect(response.status).toBe(404)+ expect(response.headers.get('x-middleware-rewrite')).toBeNull()+ })++ it('refuses declared payloads above the cap', async () => {+ const response = await proxy(+ new NextRequest('http://localhost:3000/relay/e/', {+ method: 'POST',+ headers: { 'content-length': String(64 * 1024 * 1024) },+ body: '{}'+ })+ )++ expect(response.status).toBe(413)+ expect(response.headers.get('x-middleware-rewrite')).toBeNull()+ })++ it('leaves /relay to the route handler under Better Auth', async () => {+ process.env.AUTH_PROVIDER = 'better-auth'+ const handleSession = vi+ .spyOn(betterAuthProvider, 'handleSession')+ .mockResolvedValue(NextResponse.next())++ const response = await proxy(+ new NextRequest('http://localhost:3000/relay/e/')+ )++ expect(handleSession).toHaveBeenCalledTimes(1)+ expect(response.headers.get('x-middleware-rewrite')).toBeNull()+ })++ it('does not treat lookalike paths as the relay', async () => {+ const response = await proxy(+ new NextRequest('http://localhost:3000/relayed')+ )++ expect(response.headers.get('x-middleware-rewrite')).toBeNull()+ })+ })})diff --git a/proxy.ts b/proxy.tsindex e0844746..97f6e108 100644--- a/proxy.ts+++ b/proxy.ts@@ -1,8 +1,42 @@import { type NextRequest, NextResponse } from 'next/server'-import { getAuthProvider } from '@/lib/auth/provider'+import {+ exceedsRelayBodyCap,+ RELAY_PREFIX,+ relayRequestHeaders,+ relayTarget+} from '@/lib/analytics/relay-target'+import { getAuthProvider, resolveAuthProviderName } from '@/lib/auth/provider'++// Better Auth sends /relay through the route handler. Other providers+// proxy straight to PostHog so analytics requests cost no function+// invocation and keep upstream caching.+function relayRewrite(request: NextRequest): NextResponse | null {+ const { pathname, search } = request.nextUrl+ if (pathname !== RELAY_PREFIX && !pathname.startsWith(`${RELAY_PREFIX}/`)) {+ return null+ }+ if (resolveAuthProviderName() === 'better-auth') {+ return null+ }+ const target = relayTarget(pathname.slice(RELAY_PREFIX.length) || '/', search)+ if (!target) {+ return new NextResponse('Not found', { status: 404 })+ }+ if (exceedsRelayBodyCap(request.headers)) {+ return new NextResponse('Payload too large', { status: 413 })+ }+ return NextResponse.rewrite(target, {+ request: { headers: relayRequestHeaders(request.headers) }+ })+}export async function proxy(request: NextRequest) {+ const relay = relayRewrite(request)+ if (relay) {+ return relay+ }+// Get the protocol from X-Forwarded-Proto header or request protocolconst protocol =request.headers.get('x-forwarded-proto') || request.nextUrl.protocol