mcp and content fix

This commit is contained in:
2026-10-14 13:28:04 +02:00
parent 015092e773
commit a7846d9770
18 changed files with 336 additions and 154 deletions
+17 -17
View File
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js'
import { searchContent } from './searchContent.js'
type CreateSearchRouteArgs = {
@@ -15,6 +16,11 @@ type CreateSearchRouteArgs = {
getCachedPayload: () => Promise<BasePayload>
/** Home slug map/string so the home result collapses to root. */
homeSlug?: Record<string, string> | string
/**
* Per-IP limit (in memory, per instance). Default { max: 120, windowMs: 60_000 }.
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
*/
rateLimit?: { max?: number; windowMs?: number } | false
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
summaryField?: string
}
@@ -37,20 +43,18 @@ type CreateSearchRouteArgs = {
*
* Uses the global Request/Response — no next/server import.
*/
export function createSearchRoute(
args: CreateSearchRouteArgs,
): (req: Request) => Promise<Response> {
const {
baseUrl,
collection = 'pages',
config,
defaultLimit = 10,
getCachedPayload,
homeSlug,
summaryField,
} = args
export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> {
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.
const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit }
return async (req: Request) => {
if (rl) {
const ip = clientIp(req)
if (!checkRateLimit({ key: ip, scope: 'search', ...rl })) {
return tooManyRequests(ip, 'search', { count: 0, error: 'Too many requests', query: '', results: [] })
}
}
const url = new URL(req.url)
const query = url.searchParams.get('q')?.trim() ?? ''
const locale = url.searchParams.get('locale') ?? undefined
@@ -79,11 +83,7 @@ export function createSearchRoute(
})
return Response.json(
{ count: results.length, locale: locale ?? config.defaultLocale, query, results },
{
headers: {
'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600',
},
},
{ headers: { 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600' } },
)
} catch (err) {
// DB unreachable (build) or unexpected — empty result rather than 500.
+3 -62
View File
@@ -1,62 +1,3 @@
type Bucket = { count: number; resetAt: number }
/**
* Per-IP sliding window, in memory.
*
* Deliberately simple: no Redis, no dependency. The trade-off is that the
* counter lives in one process — with several instances behind a load balancer
* each keeps its own, so the effective limit is per-instance, not global. For a
* contact form that's fine (it raises the cost of flooding without pretending
* to be airtight); a high-security form should put a real limiter in front.
*
* State is module-level, so it survives between requests but resets on redeploy
* — acceptable for abuse throttling.
*/
const buckets = new Map<string, Bucket>()
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */
let lastSweep = Date.now()
const SWEEP_INTERVAL = 60_000
function sweep(now: number) {
if (now - lastSweep < SWEEP_INTERVAL) {return}
lastSweep = now
for (const [key, bucket] of buckets) {
if (bucket.resetAt <= now) {buckets.delete(key)}
}
}
export type RateLimitArgs = {
/** Identifier to limit on — typically the client IP. */
key: string
/** Max submissions allowed per window. Defaults to 5. */
max?: number
/** Window length in ms. Defaults to 60_000 (one minute). */
windowMs?: number
}
/**
* Returns true when the request is within the limit, false when it should be
* rejected. A missing key (no IP) is allowed through — better to accept a
* submission than to block everyone behind a proxy that strips the header.
*/
export function checkRateLimit({ key, max = 5, windowMs = 60_000 }: RateLimitArgs): boolean {
if (!key) {return true}
const now = Date.now()
sweep(now)
const bucket = buckets.get(key)
if (!bucket || bucket.resetAt <= now) {
buckets.set(key, { count: 1, resetAt: now + windowMs })
return true
}
if (bucket.count >= max) {
return false
}
bucket.count += 1
return true
}
// Moved to modules/shared/rateLimit.ts (shared with search and MCP routes).
export { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js'
export type { RateLimitArgs } from '../shared/rateLimit.js'
+24 -4
View File
@@ -5,6 +5,7 @@ import type { I18nConfig } from '../i18n/index.js'
import { createMarkdownRenderer, searchContent } from '../content/index.js'
import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js'
/**
* A read-only MCP (Model Context Protocol) server for the client site, as a Next
@@ -46,6 +47,13 @@ type CreateMcpRouteArgs = {
/** Archive-backed collections (same as the plugin option) for get_page. */
content?: ContentOption
getCachedPayload: () => Promise<BasePayload>
/** Max messages in one JSON-RPC batch. Default 10. */
maxBatch?: number
/**
* Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory, per instance). Default { max: 60, windowMs: 60_000 }.
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
*/
rateLimit?: { max?: number; windowMs?: number } | false
/** Server name advertised in `initialize`. Default 'ipal-site'. */
serverName?: string
/** Server version advertised in `initialize`. Default '1.0.0'. */
@@ -77,11 +85,13 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
config,
content,
getCachedPayload,
maxBatch = 10,
serverName = 'ipal-site',
serverVersion = '1.0.0',
settingsSlug = 'site-settings',
summaryField,
} = args
const rl = args.rateLimit === false ? null : { max: 60, windowMs: 60_000, ...args.rateLimit }
const origin = baseUrl?.replace(/\/$/, '') ?? ''
const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug })
@@ -145,10 +155,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
async function getPage(params: Record<string, unknown>): Promise<string> {
const raw = typeof params.path === 'string' ? params.path.trim() : ''
if (!raw) {return 'No path provided.'}
const segments = raw
.replace(/^\/+|\/+$/g, '')
.split('/')
.filter(Boolean)
const segments = raw.replace(/^\/+|\/+$/g, '').split('/').filter(Boolean)
let locale = getDefaultLocale(config)
let slug = segments
if (segments.length && isValidLocale(segments[0], config)) {
@@ -210,6 +217,19 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 })
}
// Limits: a batch counts as many requests as it has messages, and is capped —
// otherwise one POST could carry hundreds of tool calls (DB queries).
const messages = Array.isArray(body) ? body.length : 1
if (Array.isArray(body) && body.length > maxBatch) {
return Response.json(rpcError(null, -32600, `Batch too large (max ${maxBatch})`), { status: 400 })
}
if (rl) {
const ip = clientIp(req)
if (!checkRateLimit({ cost: messages, key: ip, scope: 'mcp', ...rl })) {
return tooManyRequests(ip, 'mcp', rpcError(null, -32000, 'Too many requests'))
}
}
// Batch or single.
if (Array.isArray(body)) {
const out = (await Promise.all(body.map((m) => handleOne(m as JsonRpcRequest)))).filter(
+97
View File
@@ -0,0 +1,97 @@
type Bucket = { count: number; resetAt: number }
/**
* Per-key fixed window, in memory. Shared by submitForm, createSearchRoute and
* createMcpRoute — each uses its own `scope`, so a busy search box never eats
* into the contact form's budget.
*
* Deliberately simple: no Redis, no dependency. The trade-off is that the
* counter lives in one process — with several instances behind a load balancer
* each keeps its own, so the effective limit is per-instance, not global. For a
* contact form that's fine (it raises the cost of flooding without pretending
* to be airtight); a high-security form should put a real limiter in front.
*
* State is module-level, so it survives between requests but resets on redeploy
* — acceptable for abuse throttling.
*/
const buckets = new Map<string, Bucket>()
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */
let lastSweep = Date.now()
const SWEEP_INTERVAL = 60_000
function sweep(now: number) {
if (now - lastSweep < SWEEP_INTERVAL) {return}
lastSweep = now
for (const [key, bucket] of buckets) {
if (bucket.resetAt <= now) {buckets.delete(key)}
}
}
export type RateLimitArgs = {
/** Identifier to limit on — typically the client IP. */
key: string
/** Max submissions allowed per window. Defaults to 5. */
max?: number
/** Separate counter space per feature, e.g. 'form', 'search', 'mcp'. Default 'form'. */
scope?: string
/** Window length in ms. Defaults to 60_000 (one minute). */
windowMs?: number
}
/**
* Returns true when the request is within the limit, false when it should be
* rejected. A missing key (no IP) is allowed through — better to accept a
* submission than to block everyone behind a proxy that strips the header.
*/
export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowMs = 60_000 }: { cost?: number } & RateLimitArgs): boolean {
if (!key) {return true}
const now = Date.now()
sweep(now)
const id = `${scope}:${key}`
const bucket = buckets.get(id)
if (!bucket || bucket.resetAt <= now) {
if (cost > max) {return false}
buckets.set(id, { count: cost, resetAt: now + windowMs })
return true
}
if (bucket.count + cost > max) {
return false
}
bucket.count += cost
return true
}
/** Seconds until the key's window resets — for a Retry-After header. */
export function retryAfterSeconds(key: string, scope = 'form'): number {
const bucket = buckets.get(`${scope}:${key}`)
return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1
}
/**
* Client IP from a Request. Cloudflare's `cf-connecting-ip` first (set by the
* edge, the real visitor), then the first `x-forwarded-for` hop, then
* `x-real-ip`. Empty string when none — the limiter then lets the request through.
*/
export function clientIp(req: Request): string {
const h = req.headers
return (
h.get('cf-connecting-ip')?.trim() ||
h.get('x-forwarded-for')?.split(',')[0]?.trim() ||
h.get('x-real-ip')?.trim() ||
''
)
}
/** Standard 429 for route handlers. */
export function tooManyRequests(key: string, scope: string, body: unknown): Response {
return Response.json(body, {
headers: { 'cache-control': 'no-store', 'retry-after': String(retryAfterSeconds(key, scope)) },
status: 429,
})
}