diff --git a/dist/modules/content/createSearchRoute.d.ts b/dist/modules/content/createSearchRoute.d.ts index 4383025..25300dc 100644 --- a/dist/modules/content/createSearchRoute.d.ts +++ b/dist/modules/content/createSearchRoute.d.ts @@ -11,6 +11,14 @@ type CreateSearchRouteArgs = { getCachedPayload: () => Promise; /** Home slug map/string so the home result collapses to root. */ homeSlug?: Record | 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; }; diff --git a/dist/modules/content/createSearchRoute.js b/dist/modules/content/createSearchRoute.js index 9d6b04e..0d23748 100644 --- a/dist/modules/content/createSearchRoute.js +++ b/dist/modules/content/createSearchRoute.js @@ -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; diff --git a/dist/modules/content/createSearchRoute.js.map b/dist/modules/content/createSearchRoute.js.map index 3c56a59..1de5a60 100644 --- a/dist/modules/content/createSearchRoute.js.map +++ b/dist/modules/content/createSearchRoute.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/content/createSearchRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { searchContent } from './searchContent.js'\n\ntype CreateSearchRouteArgs = {\n /** Absolute origin to prefix result URLs with. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Default result cap when ?limit is absent. Default 10. */\n defaultLimit?: number\n getCachedPayload: () => Promise\n /** Home slug map/string so the home result collapses to root. */\n homeSlug?: Record | string\n /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */\n summaryField?: string\n}\n\n/**\n * A JSON content-search endpoint. Powers both the site's own search UI and\n * external agents — one ranking, one source of truth (shares searchContent with\n * the MCP server's search_content tool).\n *\n * // app/api/search/route.ts\n * import { createSearchRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n *\n * Query params: `q` (required), `locale`, `limit`. Response:\n * { query, locale, count, results: [{ title, url, description?, slug }] }\n *\n * Uses the global Request/Response — no next/server import.\n */\nexport function createSearchRoute(\n args: CreateSearchRouteArgs,\n): (req: Request) => Promise {\n const {\n baseUrl,\n collection = 'pages',\n config,\n defaultLimit = 10,\n getCachedPayload,\n homeSlug,\n summaryField,\n } = args\n\n return async (req: Request) => {\n const url = new URL(req.url)\n const query = url.searchParams.get('q')?.trim() ?? ''\n const locale = url.searchParams.get('locale') ?? undefined\n const limitParam = url.searchParams.get('limit')\n const limit = limitParam ? Number(limitParam) : defaultLimit\n\n if (!query) {\n return Response.json(\n { count: 0, error: 'Missing ?q', query: '', results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 400 },\n )\n }\n\n try {\n const payload = await getCachedPayload()\n const results = await searchContent({\n baseUrl,\n collection,\n config,\n homeSlug,\n limit,\n locale,\n payload,\n query,\n summaryField,\n })\n return Response.json(\n { count: results.length, locale: locale ?? config.defaultLocale, query, results },\n {\n headers: {\n 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600',\n },\n },\n )\n } catch (err) {\n // DB unreachable (build) or unexpected — empty result rather than 500.\n console.warn('[ipal] createSearchRoute: search failed:', err)\n return Response.json(\n { count: 0, query, results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 200 },\n )\n }\n }\n}\n"],"names":["searchContent","createSearchRoute","args","baseUrl","collection","config","defaultLimit","getCachedPayload","homeSlug","summaryField","req","url","URL","query","searchParams","get","trim","locale","undefined","limitParam","limit","Number","Response","json","count","error","results","headers","status","payload","length","defaultLocale","err","console","warn"],"mappings":"AAIA,SAASA,aAAa,QAAQ,qBAAoB;AAiBlD;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASC,kBACdC,IAA2B;IAE3B,MAAM,EACJC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNC,eAAe,EAAE,EACjBC,gBAAgB,EAChBC,QAAQ,EACRC,YAAY,EACb,GAAGP;IAEJ,OAAO,OAAOQ;QACZ,MAAMC,MAAM,IAAIC,IAAIF,IAAIC,GAAG;QAC3B,MAAME,QAAQF,IAAIG,YAAY,CAACC,GAAG,CAAC,MAAMC,UAAU;QACnD,MAAMC,SAASN,IAAIG,YAAY,CAACC,GAAG,CAAC,aAAaG;QACjD,MAAMC,aAAaR,IAAIG,YAAY,CAACC,GAAG,CAAC;QACxC,MAAMK,QAAQD,aAAaE,OAAOF,cAAcb;QAEhD,IAAI,CAACO,OAAO;YACV,OAAOS,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAGC,OAAO;gBAAcZ,OAAO;gBAAIa,SAAS,EAAE;YAAC,GACxD;gBAAEC,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;QAEA,IAAI;YACF,MAAMC,UAAU,MAAMtB;YACtB,MAAMmB,UAAU,MAAM1B,cAAc;gBAClCG;gBACAC;gBACAC;gBACAG;gBACAY;gBACAH;gBACAY;gBACAhB;gBACAJ;YACF;YACA,OAAOa,SAASC,IAAI,CAClB;gBAAEC,OAAOE,QAAQI,MAAM;gBAAEb,QAAQA,UAAUZ,OAAO0B,aAAa;gBAAElB;gBAAOa;YAAQ,GAChF;gBACEC,SAAS;oBACP,iBAAiB;gBACnB;YACF;QAEJ,EAAE,OAAOK,KAAK;YACZ,uEAAuE;YACvEC,QAAQC,IAAI,CAAC,4CAA4CF;YACzD,OAAOV,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAGX;gBAAOa,SAAS,EAAE;YAAC,GAC/B;gBAAEC,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;IACF;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/content/createSearchRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js'\nimport { searchContent } from './searchContent.js'\n\ntype CreateSearchRouteArgs = {\n /** Absolute origin to prefix result URLs with. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Default result cap when ?limit is absent. Default 10. */\n defaultLimit?: number\n getCachedPayload: () => Promise\n /** Home slug map/string so the home result collapses to root. */\n homeSlug?: Record | string\n /**\n * Per-IP limit (in memory, per instance). Default { max: 120, windowMs: 60_000 }.\n * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).\n */\n rateLimit?: { max?: number; windowMs?: number } | false\n /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */\n summaryField?: string\n}\n\n/**\n * A JSON content-search endpoint. Powers both the site's own search UI and\n * external agents — one ranking, one source of truth (shares searchContent with\n * the MCP server's search_content tool).\n *\n * // app/api/search/route.ts\n * import { createSearchRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n *\n * Query params: `q` (required), `locale`, `limit`. Response:\n * { query, locale, count, results: [{ title, url, description?, slug }] }\n *\n * Uses the global Request/Response — no next/server import.\n */\nexport function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise {\n const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args\n // 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.\n const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit }\n\n return async (req: Request) => {\n if (rl) {\n const ip = clientIp(req)\n if (!checkRateLimit({ key: ip, scope: 'search', ...rl })) {\n return tooManyRequests(ip, 'search', { count: 0, error: 'Too many requests', query: '', results: [] })\n }\n }\n const url = new URL(req.url)\n const query = url.searchParams.get('q')?.trim() ?? ''\n const locale = url.searchParams.get('locale') ?? undefined\n const limitParam = url.searchParams.get('limit')\n const limit = limitParam ? Number(limitParam) : defaultLimit\n\n if (!query) {\n return Response.json(\n { count: 0, error: 'Missing ?q', query: '', results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 400 },\n )\n }\n\n try {\n const payload = await getCachedPayload()\n const results = await searchContent({\n baseUrl,\n collection,\n config,\n homeSlug,\n limit,\n locale,\n payload,\n query,\n summaryField,\n })\n return Response.json(\n { count: results.length, locale: locale ?? config.defaultLocale, query, results },\n { headers: { 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600' } },\n )\n } catch (err) {\n // DB unreachable (build) or unexpected — empty result rather than 500.\n console.warn('[ipal] createSearchRoute: search failed:', err)\n return Response.json(\n { count: 0, query, results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 200 },\n )\n }\n }\n}\n"],"names":["checkRateLimit","clientIp","tooManyRequests","searchContent","createSearchRoute","args","baseUrl","collection","config","defaultLimit","getCachedPayload","homeSlug","summaryField","rl","rateLimit","max","windowMs","req","ip","key","scope","count","error","query","results","url","URL","searchParams","get","trim","locale","undefined","limitParam","limit","Number","Response","json","headers","status","payload","length","defaultLocale","err","console","warn"],"mappings":"AAIA,SAASA,cAAc,EAAEC,QAAQ,EAAEC,eAAe,QAAQ,yBAAwB;AAClF,SAASC,aAAa,QAAQ,qBAAoB;AAsBlD;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASC,kBAAkBC,IAA2B;IAC3D,MAAM,EAAEC,OAAO,EAAEC,aAAa,OAAO,EAAEC,MAAM,EAAEC,eAAe,EAAE,EAAEC,gBAAgB,EAAEC,QAAQ,EAAEC,YAAY,EAAE,GAAGP;IAC/G,sFAAsF;IACtF,MAAMQ,KAAKR,KAAKS,SAAS,KAAK,QAAQ,OAAO;QAAEC,KAAK;QAAKC,UAAU;QAAQ,GAAGX,KAAKS,SAAS;IAAC;IAE7F,OAAO,OAAOG;QACZ,IAAIJ,IAAI;YACN,MAAMK,KAAKjB,SAASgB;YACpB,IAAI,CAACjB,eAAe;gBAAEmB,KAAKD;gBAAIE,OAAO;gBAAU,GAAGP,EAAE;YAAC,IAAI;gBACxD,OAAOX,gBAAgBgB,IAAI,UAAU;oBAAEG,OAAO;oBAAGC,OAAO;oBAAqBC,OAAO;oBAAIC,SAAS,EAAE;gBAAC;YACtG;QACF;QACA,MAAMC,MAAM,IAAIC,IAAIT,IAAIQ,GAAG;QAC3B,MAAMF,QAAQE,IAAIE,YAAY,CAACC,GAAG,CAAC,MAAMC,UAAU;QACnD,MAAMC,SAASL,IAAIE,YAAY,CAACC,GAAG,CAAC,aAAaG;QACjD,MAAMC,aAAaP,IAAIE,YAAY,CAACC,GAAG,CAAC;QACxC,MAAMK,QAAQD,aAAaE,OAAOF,cAAcvB;QAEhD,IAAI,CAACc,OAAO;YACV,OAAOY,SAASC,IAAI,CAClB;gBAAEf,OAAO;gBAAGC,OAAO;gBAAcC,OAAO;gBAAIC,SAAS,EAAE;YAAC,GACxD;gBAAEa,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;QAEA,IAAI;YACF,MAAMC,UAAU,MAAM7B;YACtB,MAAMc,UAAU,MAAMrB,cAAc;gBAClCG;gBACAC;gBACAC;gBACAG;gBACAsB;gBACAH;gBACAS;gBACAhB;gBACAX;YACF;YACA,OAAOuB,SAASC,IAAI,CAClB;gBAAEf,OAAOG,QAAQgB,MAAM;gBAAEV,QAAQA,UAAUtB,OAAOiC,aAAa;gBAAElB;gBAAOC;YAAQ,GAChF;gBAAEa,SAAS;oBAAE,iBAAiB;gBAA6D;YAAE;QAEjG,EAAE,OAAOK,KAAK;YACZ,uEAAuE;YACvEC,QAAQC,IAAI,CAAC,4CAA4CF;YACzD,OAAOP,SAASC,IAAI,CAClB;gBAAEf,OAAO;gBAAGE;gBAAOC,SAAS,EAAE;YAAC,GAC/B;gBAAEa,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;IACF;AACF"} \ No newline at end of file diff --git a/dist/modules/forms/rateLimit.d.ts b/dist/modules/forms/rateLimit.d.ts index 61eeac0..de3f977 100644 --- a/dist/modules/forms/rateLimit.d.ts +++ b/dist/modules/forms/rateLimit.d.ts @@ -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'; diff --git a/dist/modules/forms/rateLimit.js b/dist/modules/forms/rateLimit.js index 1b70b31..51be818 100644 --- a/dist/modules/forms/rateLimit.js +++ b/dist/modules/forms/rateLimit.js @@ -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 \ No newline at end of file diff --git a/dist/modules/forms/rateLimit.js.map b/dist/modules/forms/rateLimit.js.map index 8ba4636..ae9f7c7 100644 --- a/dist/modules/forms/rateLimit.js.map +++ b/dist/modules/forms/rateLimit.js.map @@ -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()\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"} \ No newline at end of file +{"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"} \ No newline at end of file diff --git a/dist/modules/mcp/createMcpRoute.d.ts b/dist/modules/mcp/createMcpRoute.d.ts index 653e5e0..f6a5c53 100644 --- a/dist/modules/mcp/createMcpRoute.d.ts +++ b/dist/modules/mcp/createMcpRoute.d.ts @@ -10,6 +10,16 @@ type CreateMcpRouteArgs = { /** Archive-backed collections (same as the plugin option) for get_page. */ content?: ContentOption; getCachedPayload: () => Promise; + /** 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'. */ diff --git a/dist/modules/mcp/createMcpRoute.js b/dist/modules/mcp/createMcpRoute.js index fd7602b..9d0c13d 100644 --- a/dist/modules/mcp/createMcpRoute.js +++ b/dist/modules/mcp/createMcpRoute.js @@ -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); diff --git a/dist/modules/mcp/createMcpRoute.js.map b/dist/modules/mcp/createMcpRoute.js.map index 7a56ca6..03d45ce 100644 --- a/dist/modules/mcp/createMcpRoute.js.map +++ b/dist/modules/mcp/createMcpRoute.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/mcp/createMcpRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { createMarkdownRenderer, searchContent } from '../content/index.js'\nimport { getDefaultLocale, isValidLocale } from '../i18n/index.js'\n\n/**\n * A read-only MCP (Model Context Protocol) server for the client site, as a Next\n * route handler. Lets Claude / any MCP client CONNECT to the site and query it\n * directly — search content, fetch a page as Markdown — instead of scraping\n * HTML. This is the \"better integration\" layer on top of the Markdown/llms work.\n *\n * Dependency-free on purpose: it does NOT pull in @modelcontextprotocol/sdk\n * (that would be an imposed dependency, and its API moves). It implements the\n * minimal JSON-RPC surface a read-only server needs over the Streamable-HTTP\n * transport: initialize, tools/list, tools/call, ping. Uses the global\n * Request/Response — no next/server import.\n *\n * Exposes two tools:\n * - search_content({ query, locale?, limit? }) → matching pages (title, url, description)\n * - get_page({ path }) → that page as Markdown\n *\n * // app/api/mcp/route.ts\n * import { createMcpRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: 'acme-site' })\n * export const POST = mcp.POST\n * export const GET = mcp.GET\n *\n * Add it in Claude as a custom connector pointing at https://site/api/mcp.\n */\n\nconst DEFAULT_PROTOCOL = '2025-06-18'\n\ntype CreateMcpRouteArgs = {\n /** Absolute origin for building result URLs. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Archive-backed collections (same as the plugin option) for get_page. */\n content?: ContentOption\n getCachedPayload: () => Promise\n /** Server name advertised in `initialize`. Default 'ipal-site'. */\n serverName?: string\n /** Server version advertised in `initialize`. Default '1.0.0'. */\n serverVersion?: string\n /** SiteSettings slug. Default 'site-settings'. */\n settingsSlug?: string\n /** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */\n summaryField?: string\n}\n\ntype JsonRpcId = null | number | string\ntype JsonRpcRequest = { id?: JsonRpcId; jsonrpc?: string; method?: string; params?: unknown }\n\nfunction rpcResult(id: JsonRpcId, result: unknown) {\n return { id, jsonrpc: '2.0', result }\n}\nfunction rpcError(id: JsonRpcId, code: number, message: string) {\n return { id, error: { code, message }, jsonrpc: '2.0' }\n}\n\nfunction toolText(text: string, isError = false) {\n return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) }\n}\n\nexport function createMcpRoute(args: CreateMcpRouteArgs) {\n const {\n baseUrl,\n collection = 'pages',\n config,\n content,\n getCachedPayload,\n serverName = 'ipal-site',\n serverVersion = '1.0.0',\n settingsSlug = 'site-settings',\n summaryField,\n } = args\n\n const origin = baseUrl?.replace(/\\/$/, '') ?? ''\n const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug })\n\n const TOOLS = [\n {\n name: 'search_content',\n description:\n 'Search the site content by keyword. Returns matching pages with title, URL and description.',\n inputSchema: {\n type: 'object',\n properties: {\n limit: { type: 'number', description: 'Max results (default 10)' },\n locale: { type: 'string', description: `Locale code (default ${config.defaultLocale})` },\n query: { type: 'string', description: 'Search keywords' },\n },\n required: ['query'],\n },\n },\n {\n name: 'get_page',\n description:\n 'Fetch a single page rendered as clean Markdown. `path` is the page path, e.g. /pl/o-nas.',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Page path, e.g. /pl/o-nas or /en/about' },\n },\n required: ['path'],\n },\n },\n ]\n\n async function runSearch(params: Record): Promise {\n const query = typeof params.query === 'string' ? params.query.trim() : ''\n if (!query) {return 'No query provided.'}\n const locale =\n typeof params.locale === 'string' && isValidLocale(params.locale, config)\n ? params.locale\n : getDefaultLocale(config)\n const limit = typeof params.limit === 'number' ? params.limit : 10\n\n const payload = await getCachedPayload()\n // Shared with the JSON search route — one ranking everywhere.\n const results = await searchContent({\n baseUrl: origin,\n collection,\n config,\n limit,\n locale,\n payload,\n query,\n summaryField,\n })\n if (results.length === 0) {return `No pages matched \"${query}\".`}\n return results\n .map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`)\n .join('\\n')\n }\n\n async function getPage(params: Record): Promise {\n const raw = typeof params.path === 'string' ? params.path.trim() : ''\n if (!raw) {return 'No path provided.'}\n const segments = raw\n .replace(/^\\/+|\\/+$/g, '')\n .split('/')\n .filter(Boolean)\n let locale = getDefaultLocale(config)\n let slug = segments\n if (segments.length && isValidLocale(segments[0], config)) {\n locale = segments[0]\n slug = segments.slice(1)\n }\n const payload = await getCachedPayload()\n const md = await renderMarkdown({ slug, locale, payload })\n return md ?? `No page found at ${raw}.`\n }\n\n async function handleOne(msg: JsonRpcRequest): Promise {\n const { id = null, method, params } = msg\n\n // Notifications (no id) get no response body.\n if (id === null && typeof method === 'string' && method.startsWith('notifications/')) {\n return null\n }\n\n switch (method) {\n case 'initialize': {\n const requested = (params as { protocolVersion?: string } | undefined)?.protocolVersion\n return rpcResult(id, {\n capabilities: { tools: { listChanged: false } },\n protocolVersion: requested || DEFAULT_PROTOCOL,\n serverInfo: { name: serverName, version: serverVersion },\n })\n }\n case 'ping':\n return rpcResult(id, {})\n case 'tools/call': {\n const p = (params ?? {}) as { arguments?: Record; name?: string }\n const toolArgs = p.arguments ?? {}\n try {\n if (p.name === 'search_content') {return rpcResult(id, toolText(await runSearch(toolArgs)))}\n if (p.name === 'get_page') {return rpcResult(id, toolText(await getPage(toolArgs)))}\n return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true))\n } catch (err) {\n // Log the real error server-side; return a GENERIC message to the\n // (anonymous) caller so internal details — DB schema, host, stack —\n // never leak over a public endpoint.\n console.warn('[ipal] createMcpRoute: tool execution failed:', err)\n return rpcResult(id, toolText('Tool execution failed.', true))\n }\n }\n case 'tools/list':\n return rpcResult(id, { tools: TOOLS })\n default:\n if (id === null) {return null} // unknown notification\n return rpcError(id, -32601, `Method not found: ${method}`)\n }\n }\n\n async function POST(req: Request): Promise {\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 })\n }\n\n // Batch or single.\n if (Array.isArray(body)) {\n const out = (await Promise.all(body.map((m) => handleOne(m as JsonRpcRequest)))).filter(\n (r): r is object => r !== null,\n )\n if (out.length === 0) {return new Response(null, { status: 202 })}\n return Response.json(out, { headers: { 'cache-control': 'no-store' } })\n }\n\n const res = await handleOne(body as JsonRpcRequest)\n if (res === null) {return new Response(null, { status: 202 })}\n return Response.json(res, { headers: { 'cache-control': 'no-store' } })\n }\n\n // No server→client SSE stream in this read-only server.\n async function GET(): Promise {\n return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {\n headers: { allow: 'POST' },\n status: 405,\n })\n }\n\n return { GET, POST }\n}\n"],"names":["createMarkdownRenderer","searchContent","getDefaultLocale","isValidLocale","DEFAULT_PROTOCOL","rpcResult","id","result","jsonrpc","rpcError","code","message","error","toolText","text","isError","content","type","createMcpRoute","args","baseUrl","collection","config","getCachedPayload","serverName","serverVersion","settingsSlug","summaryField","origin","replace","renderMarkdown","TOOLS","name","description","inputSchema","properties","limit","locale","defaultLocale","query","required","path","runSearch","params","trim","payload","results","length","map","r","title","url","join","getPage","raw","segments","split","filter","Boolean","slug","slice","md","handleOne","msg","method","startsWith","requested","protocolVersion","capabilities","tools","listChanged","serverInfo","version","p","toolArgs","arguments","err","console","warn","POST","req","body","json","Response","status","Array","isArray","out","Promise","all","m","headers","res","GET","allow"],"mappings":"AAKA,SAASA,sBAAsB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O,IAAIV,SAAS,wDAAwD;YAC1EQ,SAAS;gBAAEG,OAAO;YAAO;YACzBV,QAAQ;QACV;IACF;IAEA,OAAO;QAAES;QAAKd;IAAK;AACrB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/mcp/createMcpRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { createMarkdownRenderer, searchContent } from '../content/index.js'\nimport { getDefaultLocale, isValidLocale } from '../i18n/index.js'\nimport { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js'\n\n/**\n * A read-only MCP (Model Context Protocol) server for the client site, as a Next\n * route handler. Lets Claude / any MCP client CONNECT to the site and query it\n * directly — search content, fetch a page as Markdown — instead of scraping\n * HTML. This is the \"better integration\" layer on top of the Markdown/llms work.\n *\n * Dependency-free on purpose: it does NOT pull in @modelcontextprotocol/sdk\n * (that would be an imposed dependency, and its API moves). It implements the\n * minimal JSON-RPC surface a read-only server needs over the Streamable-HTTP\n * transport: initialize, tools/list, tools/call, ping. Uses the global\n * Request/Response — no next/server import.\n *\n * Exposes two tools:\n * - search_content({ query, locale?, limit? }) → matching pages (title, url, description)\n * - get_page({ path }) → that page as Markdown\n *\n * // app/api/mcp/route.ts\n * import { createMcpRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: 'acme-site' })\n * export const POST = mcp.POST\n * export const GET = mcp.GET\n *\n * Add it in Claude as a custom connector pointing at https://site/api/mcp.\n */\n\nconst DEFAULT_PROTOCOL = '2025-06-18'\n\ntype CreateMcpRouteArgs = {\n /** Absolute origin for building result URLs. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Archive-backed collections (same as the plugin option) for get_page. */\n content?: ContentOption\n getCachedPayload: () => Promise\n /** Max messages in one JSON-RPC batch. Default 10. */\n maxBatch?: number\n /**\n * Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory, per instance). Default { max: 60, windowMs: 60_000 }.\n * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).\n */\n rateLimit?: { max?: number; windowMs?: number } | false\n /** Server name advertised in `initialize`. Default 'ipal-site'. */\n serverName?: string\n /** Server version advertised in `initialize`. Default '1.0.0'. */\n serverVersion?: string\n /** SiteSettings slug. Default 'site-settings'. */\n settingsSlug?: string\n /** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */\n summaryField?: string\n}\n\ntype JsonRpcId = null | number | string\ntype JsonRpcRequest = { id?: JsonRpcId; jsonrpc?: string; method?: string; params?: unknown }\n\nfunction rpcResult(id: JsonRpcId, result: unknown) {\n return { id, jsonrpc: '2.0', result }\n}\nfunction rpcError(id: JsonRpcId, code: number, message: string) {\n return { id, error: { code, message }, jsonrpc: '2.0' }\n}\n\nfunction toolText(text: string, isError = false) {\n return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) }\n}\n\nexport function createMcpRoute(args: CreateMcpRouteArgs) {\n const {\n baseUrl,\n collection = 'pages',\n config,\n content,\n getCachedPayload,\n maxBatch = 10,\n serverName = 'ipal-site',\n serverVersion = '1.0.0',\n settingsSlug = 'site-settings',\n summaryField,\n } = args\n const rl = args.rateLimit === false ? null : { max: 60, windowMs: 60_000, ...args.rateLimit }\n\n const origin = baseUrl?.replace(/\\/$/, '') ?? ''\n const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug })\n\n const TOOLS = [\n {\n name: 'search_content',\n description:\n 'Search the site content by keyword. Returns matching pages with title, URL and description.',\n inputSchema: {\n type: 'object',\n properties: {\n limit: { type: 'number', description: 'Max results (default 10)' },\n locale: { type: 'string', description: `Locale code (default ${config.defaultLocale})` },\n query: { type: 'string', description: 'Search keywords' },\n },\n required: ['query'],\n },\n },\n {\n name: 'get_page',\n description:\n 'Fetch a single page rendered as clean Markdown. `path` is the page path, e.g. /pl/o-nas.',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Page path, e.g. /pl/o-nas or /en/about' },\n },\n required: ['path'],\n },\n },\n ]\n\n async function runSearch(params: Record): Promise {\n const query = typeof params.query === 'string' ? params.query.trim() : ''\n if (!query) {return 'No query provided.'}\n const locale =\n typeof params.locale === 'string' && isValidLocale(params.locale, config)\n ? params.locale\n : getDefaultLocale(config)\n const limit = typeof params.limit === 'number' ? params.limit : 10\n\n const payload = await getCachedPayload()\n // Shared with the JSON search route — one ranking everywhere.\n const results = await searchContent({\n baseUrl: origin,\n collection,\n config,\n limit,\n locale,\n payload,\n query,\n summaryField,\n })\n if (results.length === 0) {return `No pages matched \"${query}\".`}\n return results\n .map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`)\n .join('\\n')\n }\n\n async function getPage(params: Record): Promise {\n const raw = typeof params.path === 'string' ? params.path.trim() : ''\n if (!raw) {return 'No path provided.'}\n const segments = raw.replace(/^\\/+|\\/+$/g, '').split('/').filter(Boolean)\n let locale = getDefaultLocale(config)\n let slug = segments\n if (segments.length && isValidLocale(segments[0], config)) {\n locale = segments[0]\n slug = segments.slice(1)\n }\n const payload = await getCachedPayload()\n const md = await renderMarkdown({ slug, locale, payload })\n return md ?? `No page found at ${raw}.`\n }\n\n async function handleOne(msg: JsonRpcRequest): Promise {\n const { id = null, method, params } = msg\n\n // Notifications (no id) get no response body.\n if (id === null && typeof method === 'string' && method.startsWith('notifications/')) {\n return null\n }\n\n switch (method) {\n case 'initialize': {\n const requested = (params as { protocolVersion?: string } | undefined)?.protocolVersion\n return rpcResult(id, {\n capabilities: { tools: { listChanged: false } },\n protocolVersion: requested || DEFAULT_PROTOCOL,\n serverInfo: { name: serverName, version: serverVersion },\n })\n }\n case 'ping':\n return rpcResult(id, {})\n case 'tools/call': {\n const p = (params ?? {}) as { arguments?: Record; name?: string }\n const toolArgs = p.arguments ?? {}\n try {\n if (p.name === 'search_content') {return rpcResult(id, toolText(await runSearch(toolArgs)))}\n if (p.name === 'get_page') {return rpcResult(id, toolText(await getPage(toolArgs)))}\n return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true))\n } catch (err) {\n // Log the real error server-side; return a GENERIC message to the\n // (anonymous) caller so internal details — DB schema, host, stack —\n // never leak over a public endpoint.\n console.warn('[ipal] createMcpRoute: tool execution failed:', err)\n return rpcResult(id, toolText('Tool execution failed.', true))\n }\n }\n case 'tools/list':\n return rpcResult(id, { tools: TOOLS })\n default:\n if (id === null) {return null} // unknown notification\n return rpcError(id, -32601, `Method not found: ${method}`)\n }\n }\n\n async function POST(req: Request): Promise {\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 })\n }\n\n // Limits: a batch counts as many requests as it has messages, and is capped —\n // otherwise one POST could carry hundreds of tool calls (DB queries).\n const messages = Array.isArray(body) ? body.length : 1\n if (Array.isArray(body) && body.length > maxBatch) {\n return Response.json(rpcError(null, -32600, `Batch too large (max ${maxBatch})`), { status: 400 })\n }\n if (rl) {\n const ip = clientIp(req)\n if (!checkRateLimit({ cost: messages, key: ip, scope: 'mcp', ...rl })) {\n return tooManyRequests(ip, 'mcp', rpcError(null, -32000, 'Too many requests'))\n }\n }\n\n // Batch or single.\n if (Array.isArray(body)) {\n const out = (await Promise.all(body.map((m) => handleOne(m as JsonRpcRequest)))).filter(\n (r): r is object => r !== null,\n )\n if (out.length === 0) {return new Response(null, { status: 202 })}\n return Response.json(out, { headers: { 'cache-control': 'no-store' } })\n }\n\n const res = await handleOne(body as JsonRpcRequest)\n if (res === null) {return new Response(null, { status: 202 })}\n return Response.json(res, { headers: { 'cache-control': 'no-store' } })\n }\n\n // No server→client SSE stream in this read-only server.\n async function GET(): Promise {\n return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {\n headers: { allow: 'POST' },\n status: 405,\n })\n }\n\n return { GET, POST }\n}\n"],"names":["createMarkdownRenderer","searchContent","getDefaultLocale","isValidLocale","checkRateLimit","clientIp","tooManyRequests","DEFAULT_PROTOCOL","rpcResult","id","result","jsonrpc","rpcError","code","message","error","toolText","text","isError","content","type","createMcpRoute","args","baseUrl","collection","config","getCachedPayload","maxBatch","serverName","serverVersion","settingsSlug","summaryField","rl","rateLimit","max","windowMs","origin","replace","renderMarkdown","TOOLS","name","description","inputSchema","properties","limit","locale","defaultLocale","query","required","path","runSearch","params","trim","payload","results","length","map","r","title","url","join","getPage","raw","segments","split","filter","Boolean","slug","slice","md","handleOne","msg","method","startsWith","requested","protocolVersion","capabilities","tools","listChanged","serverInfo","version","p","toolArgs","arguments","err","console","warn","POST","req","body","json","Response","status","messages","Array","isArray","ip","cost","key","scope","out","Promise","all","m","headers","res","GET","allow"],"mappings":"AAKA,SAASA,sBAAsB,EAAEC,aAAa,QAAQ,sBAAqB;AAC3E,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,mBAAkB;AAClE,SAASC,cAAc,EAAEC,QAAQ,EAAEC,eAAe,QAAQ,yBAAwB;AAElF;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GAED,MAAMC,mBAAmB;AA+BzB,SAASC,UAAUC,EAAa,EAAEC,MAAe;IAC/C,OAAO;QAAED;QAAIE,SAAS;QAAOD;IAAO;AACtC;AACA,SAASE,SAASH,EAAa,EAAEI,IAAY,EAAEC,OAAe;IAC5D,OAAO;QAAEL;QAAIM,OAAO;YAAEF;YAAMC;QAAQ;QAAGH,SAAS;IAAM;AACxD;AAEA,SAASK,SAASC,IAAY,EAAEC,UAAU,KAAK;IAC7C,OAAO;QAAEC,SAAS;YAAC;gBAAEC,MAAM;gBAAQH;YAAK;SAAE;QAAE,GAAIC,UAAU;YAAEA,SAAS;QAAK,IAAI,CAAC,CAAC;IAAE;AACpF;AAEA,OAAO,SAASG,eAAeC,IAAwB;IACrD,MAAM,EACJC,OAAO,EACPC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AAE,iBAAiB;YAAW;QAAE;IACvE;IAEA,wDAAwD;IACxD,eAAeE;QACb,OAAO,IAAIf,SAAS,wDAAwD;YAC1Ea,SAAS;gBAAEG,OAAO;YAAO;YACzBf,QAAQ;QACV;IACF;IAEA,OAAO;QAAEc;QAAKnB;IAAK;AACrB"} \ No newline at end of file diff --git a/dist/modules/shared/rateLimit.d.ts b/dist/modules/shared/rateLimit.d.ts new file mode 100644 index 0000000..893148d --- /dev/null +++ b/dist/modules/shared/rateLimit.d.ts @@ -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; diff --git a/dist/modules/shared/rateLimit.js b/dist/modules/shared/rateLimit.js new file mode 100644 index 0000000..fa61d39 --- /dev/null +++ b/dist/modules/shared/rateLimit.js @@ -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 \ No newline at end of file diff --git a/dist/modules/shared/rateLimit.js.map b/dist/modules/shared/rateLimit.js.map new file mode 100644 index 0000000..fee129c --- /dev/null +++ b/dist/modules/shared/rateLimit.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/shared/rateLimit.ts"],"sourcesContent":["type Bucket = { count: number; resetAt: number }\n\n/**\n * Per-key fixed window, in memory. Shared by submitForm, createSearchRoute and\n * createMcpRoute — each uses its own `scope`, so a busy search box never eats\n * into the contact form's budget.\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()\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 /** Separate counter space per feature, e.g. 'form', 'search', 'mcp'. Default 'form'. */\n scope?: string\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({ cost = 1, key, max = 5, scope = 'form', windowMs = 60_000 }: { cost?: number } & RateLimitArgs): boolean {\n if (!key) {return true}\n\n const now = Date.now()\n sweep(now)\n\n const id = `${scope}:${key}`\n const bucket = buckets.get(id)\n\n if (!bucket || bucket.resetAt <= now) {\n if (cost > max) {return false}\n buckets.set(id, { count: cost, resetAt: now + windowMs })\n return true\n }\n\n if (bucket.count + cost > max) {\n return false\n }\n\n bucket.count += cost\n return true\n}\n\n/** Seconds until the key's window resets — for a Retry-After header. */\nexport function retryAfterSeconds(key: string, scope = 'form'): number {\n const bucket = buckets.get(`${scope}:${key}`)\n return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1\n}\n\n/**\n * Client IP from a Request. Cloudflare's `cf-connecting-ip` first (set by the\n * edge, the real visitor), then the first `x-forwarded-for` hop, then\n * `x-real-ip`. Empty string when none — the limiter then lets the request through.\n */\nexport function clientIp(req: Request): string {\n const h = req.headers\n return (\n h.get('cf-connecting-ip')?.trim() ||\n h.get('x-forwarded-for')?.split(',')[0]?.trim() ||\n h.get('x-real-ip')?.trim() ||\n ''\n )\n}\n\n/** Standard 429 for route handlers. */\nexport function tooManyRequests(key: string, scope: string, body: unknown): Response {\n return Response.json(body, {\n headers: { 'cache-control': 'no-store', 'retry-after': String(retryAfterSeconds(key, scope)) },\n status: 429,\n })\n}\n"],"names":["buckets","Map","lastSweep","Date","now","SWEEP_INTERVAL","sweep","key","bucket","resetAt","delete","checkRateLimit","cost","max","scope","windowMs","id","get","set","count","retryAfterSeconds","Math","ceil","clientIp","req","h","headers","trim","split","tooManyRequests","body","Response","json","String","status"],"mappings":"AAEA;;;;;;;;;;;;;CAaC,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;AAaA;;;;CAIC,GACD,OAAO,SAASI,eAAe,EAAEC,OAAO,CAAC,EAAEL,GAAG,EAAEM,MAAM,CAAC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;QAC7FoB,QAAQ;IACV;AACF"} \ No newline at end of file diff --git a/docs/content.md b/docs/content.md index 5bfb8e8..8c92097 100644 --- a/docs/content.md +++ b/docs/content.md @@ -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): diff --git a/docs/mcp.md b/docs/mcp.md index 11ed359..acfb255 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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`). diff --git a/src/modules/content/createSearchRoute.ts b/src/modules/content/createSearchRoute.ts index fcc3fbb..d7692f9 100644 --- a/src/modules/content/createSearchRoute.ts +++ b/src/modules/content/createSearchRoute.ts @@ -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 /** Home slug map/string so the home result collapses to root. */ homeSlug?: Record | 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 { - const { - baseUrl, - collection = 'pages', - config, - defaultLimit = 10, - getCachedPayload, - homeSlug, - summaryField, - } = args +export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise { + 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. diff --git a/src/modules/forms/rateLimit.ts b/src/modules/forms/rateLimit.ts index f41d9d0..d29a07c 100644 --- a/src/modules/forms/rateLimit.ts +++ b/src/modules/forms/rateLimit.ts @@ -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() - -/** 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' diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index eea0d39..8cae5ca 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -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 + /** 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): Promise { 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( diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts new file mode 100644 index 0000000..6348ef0 --- /dev/null +++ b/src/modules/shared/rateLimit.ts @@ -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() + +/** 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, + }) +}