Repository navigation
Expand file tree
/
Copy pathmiddleware.test.ts
More file actions
546 lines (485 loc) · 19.4 KB
/
Copy pathmiddleware.test.ts
File metadata and controls
546 lines (485 loc) · 19.4 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
import {unstable_doesMiddlewareMatch} from 'next/experimental/testing/server';
import {type NextFetchEvent, NextRequest} from 'next/server';
import {afterEach, describe, expect, it, vi} from 'vitest';
// Helper to import the middleware module fresh with given env vars.
// isDeveloperDocs and redirectMap are evaluated at module load time,
// so we need a fresh import per env var scenario.
const ENV_KEYS = ['NEXT_PUBLIC_DEVELOPER_DOCS'] as const;
async function importMiddleware(env: Record<string, string> = {}) {
vi.resetModules();
vi.unstubAllEnvs();
// Save originals so we can restore after import
const saved = new Map<string, string>();
for (const key of ENV_KEYS) {
if (key in process.env) {
saved.set(key, process.env[key]!);
}
delete process.env[key];
}
for (const [key, value] of Object.entries(env)) {
vi.stubEnv(key, value);
}
const mod = await import('./middleware');
vi.unstubAllEnvs();
// Restore any originals that were deleted
for (const [key, value] of saved) {
process.env[key] = value;
}
return mod;
}
function makeRequest(path: string): NextRequest {
return new NextRequest(new URL(path, 'http://localhost:3000'));
}
function isRedirect(res: Response): boolean {
return res.status === 301 || res.status === 302;
}
describe('middleware redirect set selection', () => {
afterEach(() => {
vi.unstubAllEnvs();
});
// "/" only exists in DEVELOPER_DOCS_REDIRECTS, so it's a good signal
// for which redirect set is active without hardcoding destinations.
describe('when NEXT_PUBLIC_DEVELOPER_DOCS is set', () => {
it('activates developer docs redirect set', async () => {
const {middleware} = await importMiddleware({NEXT_PUBLIC_DEVELOPER_DOCS: '1'});
expect(isRedirect(middleware(makeRequest('/')))).toBe(true);
});
it('does not use user docs redirects', async () => {
const {middleware} = await importMiddleware({NEXT_PUBLIC_DEVELOPER_DOCS: '1'});
// user-docs-only path should not redirect in developer docs mode
expect(isRedirect(middleware(makeRequest('/platforms/python/http_errors/')))).toBe(
false
);
});
});
describe('when NEXT_PUBLIC_DEVELOPER_DOCS is not set (docs.sentry.io)', () => {
it('activates user docs redirect set', async () => {
const {middleware} = await importMiddleware({});
// "/" should NOT redirect in user docs mode
expect(isRedirect(middleware(makeRequest('/')))).toBe(false);
});
it('does not use developer docs redirects', async () => {
const {middleware} = await importMiddleware({});
// developer-docs-only path "/docs-components/" should not redirect
expect(isRedirect(middleware(makeRequest('/docs-components/')))).toBe(false);
});
});
describe('pass-through', () => {
it('does not redirect unknown paths', async () => {
const {middleware} = await importMiddleware({});
expect(isRedirect(middleware(makeRequest('/not/a/real/path/')))).toBe(false);
});
it('does not redirect unknown paths in developer docs mode', async () => {
const {middleware} = await importMiddleware({NEXT_PUBLIC_DEVELOPER_DOCS: '1'});
expect(isRedirect(middleware(makeRequest('/not/a/real/path/')))).toBe(false);
});
});
});
describe('non-production host indexing', () => {
it('adds a noindex header on localhost', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/platforms/java/'));
expect(res.headers.get('X-Robots-Tag')).toBe('noindex');
});
});
describe('production build-url redirect to canonical (Deployment Protection off)', () => {
afterEach(() => {
vi.unstubAllEnvs();
});
function makeHostRequest(
url: string,
method = 'GET',
headers?: HeadersInit
): NextRequest {
return new NextRequest(new URL(url), {method, headers});
}
it('redirects a non-canonical production host to the canonical host', async () => {
const {middleware} = await importMiddleware({});
vi.stubEnv('VERCEL_ENV', 'production');
const res = middleware(
makeHostRequest('https://sentry-docs-abc123.vercel.app/platforms/javascript/')
);
expect(res.status).toBe(308);
expect(res.headers.get('location')).toBe(
'https://docs.sentry.io/platforms/javascript/'
);
});
it('preserves query strings when redirecting', async () => {
const {middleware} = await importMiddleware({});
vi.stubEnv('VERCEL_ENV', 'production');
const res = middleware(
makeHostRequest('https://sentry-docs-git-master-getsentry.vercel.app/search/?q=x')
);
expect(res.status).toBe(308);
expect(res.headers.get('location')).toBe('https://docs.sentry.io/search/?q=x');
});
it('redirects to develop.sentry.dev in developer docs mode', async () => {
const {middleware} = await importMiddleware({NEXT_PUBLIC_DEVELOPER_DOCS: '1'});
vi.stubEnv('VERCEL_ENV', 'production');
const res = middleware(
makeHostRequest('https://develop-docs-abc123.vercel.app/getting-started/')
);
expect(res.status).toBe(308);
expect(res.headers.get('location')).toBe(
'https://develop.sentry.dev/getting-started/'
);
});
it('does not redirect requests already on the canonical host', async () => {
const {middleware} = await importMiddleware({});
vi.stubEnv('VERCEL_ENV', 'production');
const res = middleware(makeHostRequest('https://docs.sentry.io/platforms/'));
expect(res.status).not.toBe(308);
});
it('leaves preview deployments accessible (no redirect)', async () => {
const {middleware} = await importMiddleware({});
vi.stubEnv('VERCEL_ENV', 'preview');
const res = middleware(
makeHostRequest('https://sentry-docs-git-my-branch.sentry.dev/getting-started/')
);
expect(res.status).not.toBe(308);
});
it('does nothing locally (VERCEL_ENV unset)', async () => {
const {middleware} = await importMiddleware({});
vi.stubEnv('VERCEL_ENV', '');
const res = middleware(makeHostRequest('https://sentry-docs-abc123.vercel.app/foo/'));
expect(res.status).not.toBe(308);
});
it('redirects HEAD requests', async () => {
const {middleware} = await importMiddleware({});
vi.stubEnv('VERCEL_ENV', 'production');
const res = middleware(
makeHostRequest('https://sentry-docs-abc123.vercel.app/foo/', 'HEAD')
);
expect(res.status).toBe(308);
expect(res.headers.get('location')).toBe('https://docs.sentry.io/foo/');
});
it('does not redirect non-page requests', async () => {
const {middleware} = await importMiddleware({});
vi.stubEnv('VERCEL_ENV', 'production');
const res = middleware(
makeHostRequest('https://sentry-docs-abc123.vercel.app/foo/', 'POST')
);
expect(res.status).not.toBe(308);
});
it('serves a production build URL to the evals pin header', async () => {
const {middleware} = await importMiddleware({});
vi.stubEnv('VERCEL_ENV', 'production');
const res = middleware(
makeHostRequest('https://sentry-docs-abc123.vercel.app/llms.txt', 'GET', {
'x-sentry-evals-pin': '1',
})
);
expect(res.status).not.toBe(308);
});
});
describe('redirects for .md exports', () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it.each([
['/product/sentry-basics/sampling.md', '/organization/dynamic-sampling.md'],
[
'/platforms/javascript/guides/react/sourcemaps/multiple-origins.md',
'/platforms/javascript/guides/react/sourcemaps.md',
],
[
'/pricing/quotas/manage-event-stream-guide/adjusting-quotas.md',
'/pricing/quotas/manage-event-stream-guide.md#adjusting-quotas',
],
])('redirects %s to %s', async (from, to) => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest(from));
expect(isRedirect(res)).toBe(true);
expect(res.headers.get('location')).toBe(`http://localhost:3000${to}`);
});
it('redirects to external destinations unchanged', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/product/sentry-mcp.md'));
expect(isRedirect(res)).toBe(true);
expect(res.headers.get('location')).toBe('https://mcp.sentry.dev/');
});
it('serves .md exports of pages that are not redirected', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/platforms/apple/cocoa.md'));
expect(isRedirect(res)).toBe(false);
});
});
describe('canonical Link header on .md responses', () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it('adds Link rel=canonical pointing to the HTML page for a deep path', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/platforms/apple/cocoa.md'));
expect(res.headers.get('Link')).toContain(
'<https://docs.sentry.io/platforms/apple/cocoa/>; rel="canonical"'
);
});
it.each([
'/platforms/java/migration/7.x-to-8.0',
'/platforms/python/migration/1.x-to-2.x',
])('does not add a trailing slash to a dotted document path: %s', async path => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest(`${path}.md`));
expect(res.headers.get('Link')).toContain(
`<https://docs.sentry.io${path}>; rel="canonical"`
);
});
it('maps /index.md to the root canonical URL', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/index.md'));
expect(res.headers.get('Link')).toContain(
'<https://docs.sentry.io/>; rel="canonical"'
);
});
it('handles top-level .md paths', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/platforms.md'));
expect(res.headers.get('Link')).toContain(
'<https://docs.sentry.io/platforms/>; rel="canonical"'
);
});
it('uses develop.sentry.dev origin in developer docs mode', async () => {
const {middleware} = await importMiddleware({NEXT_PUBLIC_DEVELOPER_DOCS: '1'});
const res = middleware(makeRequest('/platforms/apple/cocoa.md'));
expect(res.headers.get('Link')).toContain(
'<https://develop.sentry.dev/platforms/apple/cocoa/>; rel="canonical"'
);
});
it('uses the Markdown URL itself as canonical for /sitemap.md', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/sitemap.md'));
expect(res.headers.get('Link')).toContain(
'<https://docs.sentry.io/sitemap.md>; rel="canonical"'
);
});
it('adds Vary: Accept to .md responses', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/platforms/apple/cocoa.md'));
expect(res.headers.get('Vary')).toBe('Accept');
});
});
describe('HTML pages advertise their Markdown version', () => {
it('links the Markdown export and llms.txt', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/platforms/apple/cocoa/'));
expect(res.headers.get('Link')).toBe(
'<https://docs.sentry.io/platforms/apple/cocoa.md>; rel="alternate"; type="text/markdown", ' +
'<https://docs.sentry.io/llms.txt>; rel="describedby"'
);
});
it('maps the root page to /index.md', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(makeRequest('/'));
expect(res.headers.get('Link')).toContain(
'<https://docs.sentry.io/index.md>; rel="alternate"; type="text/markdown"'
);
});
});
describe('wantsMarkdownViaAccept: text/plain no longer triggers markdown', () => {
it('does not serve markdown for Accept: application/json, text/plain, */*', async () => {
const {middleware} = await importMiddleware({});
const req = new NextRequest(
new URL('/platforms/apple/cocoa/', 'http://localhost:3000'),
{
headers: {Accept: 'application/json, text/plain, */*'},
}
);
const res = middleware(req);
// Should not rewrite to .md — Next rewrite changes the URL; a plain next() keeps it
expect(res.headers.get('x-middleware-rewrite')).toBeNull();
});
it('still serves markdown for explicit text/markdown Accept header', async () => {
const {middleware} = await importMiddleware({});
const req = new NextRequest(
new URL('/platforms/apple/cocoa/', 'http://localhost:3000'),
{
headers: {Accept: 'text/markdown'},
}
);
const res = middleware(req);
// A rewrite to .md will set x-middleware-rewrite
expect(res.headers.get('x-middleware-rewrite')).toContain('.md');
});
});
describe('content negotiation on page URLs', () => {
function pageRequest(headers: Record<string, string>): NextRequest {
return new NextRequest(new URL('/platforms/apple/cocoa/', 'http://localhost:3000'), {
headers,
});
}
it('serves Markdown to an AI agent on an API reference page', async () => {
const {middleware} = await importMiddleware({});
const req = new NextRequest(new URL('/api/auth/', 'http://localhost:3000'), {
headers: {'user-agent': 'Mozilla/5.0 (compatible; ChatGPT-User/1.0)'},
});
const res = middleware(req);
expect(res.headers.get('x-middleware-rewrite')).toContain('/api/auth.md');
});
it('serves Markdown with Vary and canonical headers', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(pageRequest({Accept: 'text/markdown, text/html, */*'}));
expect(res.headers.get('x-middleware-rewrite')).toContain(
'/platforms/apple/cocoa.md'
);
expect(res.headers.get('Vary')).toBe('Accept, User-Agent');
expect(res.headers.get('Link')).toBe(
'<https://docs.sentry.io/platforms/apple/cocoa/>; rel="canonical", ' +
'<https://docs.sentry.io/llms.txt>; rel="describedby"'
);
});
it('serves HTML when the client ranks HTML above Markdown', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(pageRequest({Accept: 'text/html, text/markdown;q=0.9'}));
expect(res.headers.get('x-middleware-rewrite')).toBeNull();
});
it('serves Markdown to a recognized AI agent with no format preference', async () => {
const {middleware} = await importMiddleware({});
const res = middleware(pageRequest({'User-Agent': 'Claude-User', Accept: '*/*'}));
expect(res.headers.get('x-middleware-rewrite')).toContain('.md');
});
// The headers middleware sees: Next.js strips `RSC` before middleware runs.
it.each([
['opens a page', 'text/html,*/*;q=0.8', 'document', 'navigate'],
['follows a link', '*/*', 'empty', 'cors'],
])(
'serves the page, not Markdown, when an in-app browser %s',
async (_, accept, dest, mode) => {
const {middleware} = await importMiddleware({});
const res = middleware(
pageRequest({
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Claude/1.5.0 Chrome/136.0.0.0 Safari/537.36',
Accept: accept,
'Sec-Fetch-Dest': dest,
'Sec-Fetch-Mode': mode,
})
);
expect(res.headers.get('x-middleware-rewrite')).toBeNull();
}
);
it.each([
[
'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot',
{},
],
[
'Mozilla/5.0 (compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot)',
{'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate'},
],
])('serves Markdown to %s when it asks for HTML', async (userAgent, secFetch) => {
const {middleware} = await importMiddleware({});
const res = middleware(
pageRequest({
'User-Agent': userAgent,
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
...secFetch,
})
);
expect(res.headers.get('x-middleware-rewrite')).toContain('.md');
});
});
describe('reporting AI agent visits to Profound', () => {
afterEach(() => {
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});
const CHATGPT_USER =
'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; ChatGPT-User/1.0; +https://openai.com/bot';
async function visit(
userAgent: string,
{
path = '/platforms/apple/cocoa/',
env = {VERCEL_ENV: 'production', PROFOUND_LOG_TOKEN: 'test-token'},
}: {env?: Record<string, string>; path?: string} = {}
) {
const {middleware} = await importMiddleware({});
for (const [key, value] of Object.entries(env)) {
vi.stubEnv(key, value);
}
const fetchMock = vi.fn().mockResolvedValue(Response.json({}));
vi.stubGlobal('fetch', fetchMock);
const waitUntil = vi.fn();
middleware(
new NextRequest(`https://docs.sentry.io${path}`, {
headers: {'User-Agent': userAgent, 'x-real-ip': '203.0.113.7'},
}),
{waitUntil} as unknown as NextFetchEvent
);
return {fetchMock, waitUntil};
}
it('reports an AI agent visit as background work', async () => {
const {fetchMock, waitUntil} = await visit(CHATGPT_USER);
expect(waitUntil).toHaveBeenCalledOnce();
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('https://artemis.api.tryprofound.com/v1/logs/custom');
expect(init.headers['x-api-key']).toBe('test-token');
expect(JSON.parse(init.body)).toEqual([
{
timestamp: expect.any(String),
method: 'GET',
host: 'docs.sentry.io',
path: '/platforms/apple/cocoa/',
status_code: 200,
ip: '203.0.113.7',
user_agent: CHATGPT_USER,
},
]);
});
it.each([
['an API reference page', CHATGPT_USER, '/api/auth/'],
['a direct .md URL', CHATGPT_USER, '/platforms/apple/cocoa.md'],
['llms.txt', CHATGPT_USER, '/llms.txt'],
[
'an AI crawler that gets HTML',
'Mozilla/5.0 (Linux; Android 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible; Bytespider; spider-feedback@bytedance.com)',
'/platforms/apple/cocoa/',
],
])('reports %s', async (_name, userAgent, path) => {
const {fetchMock} = await visit(userAgent, {path});
expect(JSON.parse(fetchMock.mock.calls[0][1].body)[0].path).toBe(path);
});
it.each([
[
'a person in Chrome',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
{},
],
[
'the Claude desktop app',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Claude/1.5.0 Chrome/131.0.0.0 Electron/33.0.0 Safari/537.36',
{},
],
[
'Googlebot',
'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
{},
],
['a data file', CHATGPT_USER, {path: '/_platforms/javascript.json'}],
['robots.txt', CHATGPT_USER, {path: '/robots.txt'}],
[
'a preview deployment',
CHATGPT_USER,
{env: {VERCEL_ENV: 'preview', PROFOUND_LOG_TOKEN: 'test-token'}},
],
[
'a deployment without a token',
CHATGPT_USER,
{env: {VERCEL_ENV: 'production', PROFOUND_LOG_TOKEN: ''}},
],
])('reports nothing for %s', async (_name, userAgent, options) => {
const {fetchMock} = await visit(userAgent, options);
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe('middleware matcher', () => {
it.each([
['/api/auth/', true],
['/api/ip-ranges', false],
])('%s runs the middleware: %s', async (path, expected) => {
const {config} = await importMiddleware({});
expect(
unstable_doesMiddlewareMatch({config, url: `https://docs.sentry.io${path}`})
).toBe(expected);
});
});