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
+8
View File
@@ -11,6 +11,14 @@ 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;
};
+22
View File
@@ -1,3 +1,4 @@
import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js';
import { searchContent } from './searchContent.js';
/**
* A JSON content-search endpoint. Powers both the site's own search UI and
@@ -18,7 +19,28 @@ import { searchContent } from './searchContent.js';
* Uses the global Request/Response — no next/server import.
*/ export function createSearchRoute(args) {
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)=>{
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;
File diff suppressed because one or more lines are too long
+2 -14
View File
@@ -1,14 +1,2 @@
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 declare function checkRateLimit({ key, max, windowMs }: RateLimitArgs): boolean;
export { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js';
export type { RateLimitArgs } from '../shared/rateLimit.js';
+2 -49
View File
@@ -1,51 +1,4 @@
/**
* 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();
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */ let lastSweep = Date.now();
const SWEEP_INTERVAL = 60_000;
function sweep(now) {
if (now - lastSweep < SWEEP_INTERVAL) {
return;
}
lastSweep = now;
for (const [key, bucket] of buckets){
if (bucket.resetAt <= now) {
buckets.delete(key);
}
}
}
/**
* 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 }) {
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';
//# sourceMappingURL=rateLimit.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/rateLimit.ts"],"sourcesContent":["type Bucket = { count: number; resetAt: number }\n\n/**\n * Per-IP sliding window, in memory.\n *\n * Deliberately simple: no Redis, no dependency. The trade-off is that the\n * counter lives in one process — with several instances behind a load balancer\n * each keeps its own, so the effective limit is per-instance, not global. For a\n * contact form that's fine (it raises the cost of flooding without pretending\n * to be airtight); a high-security form should put a real limiter in front.\n *\n * State is module-level, so it survives between requests but resets on redeploy\n * — acceptable for abuse throttling.\n */\nconst buckets = new Map<string, Bucket>()\n\n/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */\nlet lastSweep = Date.now()\nconst SWEEP_INTERVAL = 60_000\n\nfunction sweep(now: number) {\n if (now - lastSweep < SWEEP_INTERVAL) {return}\n lastSweep = now\n for (const [key, bucket] of buckets) {\n if (bucket.resetAt <= now) {buckets.delete(key)}\n }\n}\n\nexport type RateLimitArgs = {\n /** Identifier to limit on — typically the client IP. */\n key: string\n /** Max submissions allowed per window. Defaults to 5. */\n max?: number\n /** Window length in ms. Defaults to 60_000 (one minute). */\n windowMs?: number\n}\n\n/**\n * Returns true when the request is within the limit, false when it should be\n * rejected. A missing key (no IP) is allowed through — better to accept a\n * submission than to block everyone behind a proxy that strips the header.\n */\nexport function checkRateLimit({ key, max = 5, windowMs = 60_000 }: RateLimitArgs): boolean {\n if (!key) {return true}\n\n const now = Date.now()\n sweep(now)\n\n const bucket = buckets.get(key)\n\n if (!bucket || bucket.resetAt <= now) {\n buckets.set(key, { count: 1, resetAt: now + windowMs })\n return true\n }\n\n if (bucket.count >= max) {\n return false\n }\n\n bucket.count += 1\n return true\n}\n"],"names":["buckets","Map","lastSweep","Date","now","SWEEP_INTERVAL","sweep","key","bucket","resetAt","delete","checkRateLimit","max","windowMs","get","set","count"],"mappings":"AAEA;;;;;;;;;;;CAWC,GACD,MAAMA,UAAU,IAAIC;AAEpB,0EAA0E,GAC1E,IAAIC,YAAYC,KAAKC,GAAG;AACxB,MAAMC,iBAAiB;AAEvB,SAASC,MAAMF,GAAW;IACxB,IAAIA,MAAMF,YAAYG,gBAAgB;QAAC;IAAM;IAC7CH,YAAYE;IACZ,KAAK,MAAM,CAACG,KAAKC,OAAO,IAAIR,QAAS;QACnC,IAAIQ,OAAOC,OAAO,IAAIL,KAAK;YAACJ,QAAQU,MAAM,CAACH;QAAI;IACjD;AACF;AAWA;;;;CAIC,GACD,OAAO,SAASI,eAAe,EAAEJ,GAAG,EAAEK,MAAM,CAAC,EAAEC,WAAW,MAAM,EAAiB;IAC/E,IAAI,CAACN,KAAK;QAAC,OAAO;IAAI;IAEtB,MAAMH,MAAMD,KAAKC,GAAG;IACpBE,MAAMF;IAEN,MAAMI,SAASR,QAAQc,GAAG,CAACP;IAE3B,IAAI,CAACC,UAAUA,OAAOC,OAAO,IAAIL,KAAK;QACpCJ,QAAQe,GAAG,CAACR,KAAK;YAAES,OAAO;YAAGP,SAASL,MAAMS;QAAS;QACrD,OAAO;IACT;IAEA,IAAIL,OAAOQ,KAAK,IAAIJ,KAAK;QACvB,OAAO;IACT;IAEAJ,OAAOQ,KAAK,IAAI;IAChB,OAAO;AACT"}
{"version":3,"sources":["../../../src/modules/forms/rateLimit.ts"],"sourcesContent":["// Moved to modules/shared/rateLimit.ts (shared with search and MCP routes).\nexport { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js'\nexport type { RateLimitArgs } from '../shared/rateLimit.js'\n"],"names":["checkRateLimit","clientIp","retryAfterSeconds","tooManyRequests"],"mappings":"AAAA,4EAA4E;AAC5E,SAASA,cAAc,EAAEC,QAAQ,EAAEC,iBAAiB,EAAEC,eAAe,QAAQ,yBAAwB"}
+10
View File
@@ -10,6 +10,16 @@ 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'. */
+26 -1
View File
@@ -1,5 +1,6 @@
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
* route handler. Lets Claude / any MCP client CONNECT to the site and query it
@@ -59,7 +60,12 @@ function toolText(text, isError = false) {
};
}
export function createMcpRoute(args) {
const { baseUrl, collection = 'pages', config, content, getCachedPayload, serverName = 'ipal-site', serverVersion = '1.0.0', settingsSlug = 'site-settings', summaryField } = args;
const { baseUrl, collection = 'pages', 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,
@@ -217,6 +223,25 @@ export function createMcpRoute(args) {
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)))).filter((r)=>r !== null);
File diff suppressed because one or more lines are too long
+28
View File
@@ -0,0 +1,28 @@
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 declare function checkRateLimit({ cost, key, max, scope, windowMs }: {
cost?: number;
} & RateLimitArgs): boolean;
/** Seconds until the key's window resets — for a Retry-After header. */
export declare function retryAfterSeconds(key: string, scope?: string): number;
/**
* 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 declare function clientIp(req: Request): string;
/** Standard 429 for route handlers. */
export declare function tooManyRequests(key: string, scope: string, body: unknown): Response;
+78
View File
@@ -0,0 +1,78 @@
/**
* 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();
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */ let lastSweep = Date.now();
const SWEEP_INTERVAL = 60_000;
function sweep(now) {
if (now - lastSweep < SWEEP_INTERVAL) {
return;
}
lastSweep = now;
for (const [key, bucket] of buckets){
if (bucket.resetAt <= now) {
buckets.delete(key);
}
}
}
/**
* 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 }) {
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, scope = 'form') {
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) {
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, scope, body) {
return Response.json(body, {
headers: {
'cache-control': 'no-store',
'retry-after': String(retryAfterSeconds(key, scope))
},
status: 429
});
}
//# sourceMappingURL=rateLimit.js.map
File diff suppressed because one or more lines are too long
+6 -2
View File
@@ -315,8 +315,12 @@ Query: `?q=` (wymagane), `?locale=`, `?limit=`. Odpowiedź:
"results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] }
```
Brak `q` → 400. Tylko opublikowane, bez `noindex`. Błąd/baza offline → pusty
wynik (200), nie 500. Niska wartość `s-maxage` (60s) — wyniki świeże, ale z
Brak `q` → 400. Tylko opublikowane, bez `noindex`, maks. 50 wyników. Błąd/baza
offline → pusty wynik (200), nie 500. **Limit zapytań:** 120/min na IP (w pamięci,
per instancja) → `429` z `Retry-After`; zmiana: `rateLimit: { max, windowMs }`,
wyłączenie (limiter z przodu, np. Cloudflare WAF): `rateLimit: false`.
Kolizja z `@payloadcms/plugin-search` (kolekcja `search` → REST pod `/api/search/...`):
przenieś route, np. `app/api/site-search/route.ts`. Niska wartość `s-maxage` (60s) — wyniki świeże, ale z
cache'em CDN.
Sam helper (do własnej wyszukiwarki po stronie serwera):
+9 -2
View File
@@ -58,7 +58,8 @@ wykona `initialize` → `tools/list` → i będzie mógł wołać `search_conten
`getCachedPayload`, `config` (wymagane); `baseUrl` (URL-e w wynikach), `collection`
(`'pages'`), `settingsSlug`, `content` (kolekcje-archiwa dla `get_page`),
`serverName` (`'ipal-site'`), `serverVersion` (`'1.0.0'`).
`serverName` (`'ipal-site'`), `serverVersion` (`'1.0.0'`), `rateLimit`
(`{ max: 60, windowMs: 60_000 }` na IP, `false` = wyłączony), `maxBatch` (`10`).
## Bezpieczeństwo
@@ -66,10 +67,16 @@ wykona `initialize` → `tools/list` → i będzie mógł wołać `search_conten
- `search_content` używa `like` i odpada bezpiecznie (komunikat), gdy pole nie
jest odpytywalne — nie wywala route'a.
- Nie wystawiaj tu niczego spoza publicznej treści strony.
- **Limit zapytań:** 60 wiadomości JSON-RPC/min na IP (batch liczy się jako tyle
wiadomości, ile zawiera) → `429` z `Retry-After`. Batch > 10 → `400`. Limit jest w
pamięci, per instancja — za Cloudflare dołóż regułę Rate limiting w WAF.
- Za Cloudflare Access route musi mieć Bypass (klienci MCP nie wyślą Service Token)
— patrz instrukcja Cloudflare Access.
## Protokół (dla debugowania)
Pojedynczy obiekt JSON-RPC albo batch (tablica). Notyfikacje (`notifications/*`,
bez `id`) → HTTP 202 bez ciała. Żądania → `{ jsonrpc:'2.0', id, result }` albo
`error` (`-32601` nieznana metoda, `-32700` parse error). `initialize` odbija
`error` (`-32601` nieznana metoda, `-32700` parse error, `-32600` batch za duży,
`-32000` limit zapytań). `initialize` odbija
`protocolVersion` klienta (fallback `2025-06-18`).
+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,
})
}