Repository navigation
Expand file tree
/
Copy pathproxy.ts
More file actions
196 lines (178 loc) · 7.5 KB
/
Copy pathproxy.ts
File metadata and controls
196 lines (178 loc) · 7.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import { NextResponse } from "next/server";
import type { NextFetchEvent, NextRequest } from "next/server";
import {
classifyAgentTraffic,
createIpRangesCache,
isAgentOrAiCrawler,
} from "./lib/agent-traffic";
const posthogKey = process.env.NEXT_PUBLIC_POSTHOG_KEY?.trim();
const posthogHost =
process.env.NEXT_PUBLIC_POSTHOG_HOST || "https://eu.posthog.com";
// Matched routes: the generated llms*.txt indexes plus all page routes
// (static assets and API routes excluded to limit middleware invocations).
// `.md` markdown mirrors are page-route lookalikes and covered by the broad
// pattern since `md` is not in the excluded-extension list.
// The `md-src/`, `.well-known/`, `api/`, and extension exclusions mirror the
// markdown content-negotiation rewrite in next.config.mjs so a request is
// only ever labeled `markdown_negotiation` when that rewrite actually serves
// markdown — keep the two patterns in sync.
export const config = {
matcher: [
"/llms.txt",
"/llms-docs.txt",
"/llms-integrations.txt",
"/llms-self-hosting.txt",
"/((?!_next/|api/|md-src/|\\.well-known/|.*\\.(?:png|jpe?g|gif|svg|ico|webp|avif|css|js|mjs|map|woff2?|ttf|otf|eot|mp4|webm|mp3|zip|pdf|xml|txt|json|ya?ml|webmanifest|ipynb)$).*)",
],
};
// Crawler IP ranges, loaded in the background (never on the response path).
const getIpRanges = createIpRangesCache();
// Links copied from prose, chat answers, or broken Markdown often drag the
// next characters into the URL: `/pricing,`, `/docs/v4.`, `/docs)`,
// `/docs/halo](https:/langfuse.com/docs/halo`, `.../annotation%3E(1)`. No page
// path contains these characters, so cut the path at the first one (and drop
// trailing dots and colons) and redirect to what is left. Redirects in
// next.config.mjs then apply to the cleaned path as usual.
//
// /cloud is skipped: app/cloud/[[...path]] forwards any subpath to the
// Langfuse app, where resource names (prompts, datasets) may contain these
// characters.
const STRAY_PATH_SUFFIX =
/(?:https?:\/|[)\]>"'`*,;!]|%21|%22|%27|%29|%2C|%3B|%3E|%5B|%5D|%60|%E2%80%8B|%EF%BC%89).*$/i;
const TRAILING_PUNCTUATION = /[.:]+$/;
const UNCLEANED_PATH = /^\/cloud(?:\/|$)/;
function strippedPathname(pathname: string): string | null {
if (UNCLEANED_PATH.test(pathname)) return null;
const cleaned =
pathname.replace(STRAY_PATH_SUFFIX, "").replace(TRAILING_PUNCTUATION, "") ||
"/";
return cleaned === pathname ? null : cleaned;
}
// Pages whose Markdown mirror lives in public/md-src (see
// scripts/copy_md_sources.js and md-override/). Every page under these
// prefixes has a mirror, except the virtual /faq/tag/<tag> listings.
// ChatGPT-User (ChatGPT and Codex fetching a page for a person) gets the
// mirror even though it does not ask for Markdown. Every other client keeps
// the HTML page: browsers, search crawlers (including OAI-SearchBot), ChatGPT
// agent (drives a real browser), and agents that already send
// `Accept: text/markdown`, such as Claude Code.
const MARKDOWN_FOR_AGENT_PATHS =
/^\/(?:(?:docs|integrations|self-hosting|faq|guides|security|compare)(?:\/.*)?|pricing|pricing-self-host)\/?$/;
const NO_MARKDOWN_MIRROR = /^\/faq\/tag(?:\/|$)|\.(?:md|txt|json|xml)$/;
function markdownMirrorPath(pathname: string): string {
return `/md-src${pathname.replace(/\/$/, "")}.md`;
}
function contentKind(
pathname: string,
accept: string | null,
servedMarkdownToAgent: boolean,
): string {
if (pathname.startsWith("/llms") && pathname.endsWith(".txt")) {
return "llms_txt";
}
if (servedMarkdownToAgent) {
return "markdown_user_agent";
}
if (pathname.endsWith(".md")) {
return "markdown_file";
}
if (accept?.includes("text/markdown")) {
return "markdown_negotiation";
}
return "page";
}
export function proxy(
request: NextRequest,
event: NextFetchEvent,
): NextResponse {
const stripped = strippedPathname(request.nextUrl.pathname);
if (stripped) {
const url = request.nextUrl.clone();
url.pathname = stripped;
return NextResponse.redirect(url, 307);
}
const headers = request.headers;
const pathname = request.nextUrl.pathname;
const accept = headers.get("accept");
const ip = headers.get("x-forwarded-for")?.split(",")[0]?.trim();
// Requests that ask for Markdown are served by the rewrites in
// next.config.mjs. This covers ChatGPT-User, which fetches pages like a
// browser does. The rewrite targets a separate file, so the CDN caches the Markdown under
// /md-src/... and the HTML under the page URL: the two never mix, and no
// `Vary: User-Agent` is needed.
let markdownRewrite: URL | null = null;
if (
(request.method === "GET" || request.method === "HEAD") &&
MARKDOWN_FOR_AGENT_PATHS.test(pathname) &&
!NO_MARKDOWN_MIRROR.test(pathname) &&
!accept?.includes("text/markdown") &&
/chatgpt-user/i.test(headers.get("user-agent") ?? "")
) {
if (classifyAgentTraffic(headers, ip).id === "chatgpt-user") {
markdownRewrite = request.nextUrl.clone();
markdownRewrite.pathname = markdownMirrorPath(pathname);
}
}
if (posthogKey && process.env.DISABLE_AGENT_FETCH_TRACKING !== "true") {
const userAgent = headers.get("user-agent") ?? "";
const kind = contentKind(pathname, accept, markdownRewrite !== null);
// Agent-facing content endpoints (markdown mirrors, llms*.txt) are
// tracked for every caller; regular page routes only when the request
// comes from an AI agent or AI crawler — never for human traffic
// (posthog-js covers that). This first pass is user-agent and header
// based only, so it adds no latency.
const shouldTrack =
kind !== "page" || isAgentOrAiCrawler(classifyAgentTraffic(headers, ip));
if (shouldTrack) {
const send = async () => {
// Re-classify with IP ranges to verify crawlers and catch
// impersonators (category "bot", kind "impersonator").
const traffic = classifyAgentTraffic(headers, ip, await getIpRanges());
const payload = {
api_key: posthogKey,
event: "agent_content_fetch",
distinct_id: userAgent || "unknown-agent",
timestamp: new Date().toISOString(),
properties: {
$process_person_profile: false,
$lib: "docs-proxy",
// PostHog computes its $virt_* traffic classification (traffic
// type, bot name, bot operator) from $raw_user_agent and $ip at
// query time.
$raw_user_agent: userAgent,
$ip: ip,
$current_url: request.nextUrl.href,
$host: request.nextUrl.host,
$pathname: pathname,
$referrer: headers.get("referer") ?? undefined,
content_kind: kind,
method: request.method,
accept: accept ?? undefined,
// @mintlify/agent-traffic classification.
agent_category: traffic.category,
agent_kind: traffic.kind,
agent_name: traffic.name,
agent_operator: traffic.operator,
agent_version: traffic.version,
agent_verified: traffic.verified,
agent_confidence: traffic.confidence,
},
};
await fetch(`${posthogHost}/i/v0/e/`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
};
event.waitUntil(
send().catch(() => {
// Analytics must never affect content delivery.
}),
);
}
}
if (markdownRewrite) {
return NextResponse.rewrite(markdownRewrite);
}
return NextResponse.next();
}