- Turnstile is on only when both keys are set (panel or env); then submitForm requires a valid token, so a bot can no longer skip the check by omitting it. Not configured -> no widget, no check. New getTurnstileConfig() for layouts. - /api/ipal/test-email now requires the admin role (403 for other users). - roles field: create access is admin-only, so open sign-up can't self-assign admin. - clientIp reads X-Forwarded-For from the right, accepts Headers, can be pinned via option or IPAL_IP_HEADER; exposed on search/MCP routes. - Pluggable shared rate-limit store (setRateLimitStore) for multi-instance setups. - Replace the template int.spec with real unit tests in test/ (44 tests). Co-Authored-By: Claude Opus 5.5 <[email protected]>
102 lines
3.9 KiB
TypeScript
102 lines
3.9 KiB
TypeScript
import type { BasePayload } from 'payload'
|
|
|
|
import type { I18nConfig } from '../i18n/index.js'
|
|
|
|
import type { ClientIpOptions } from '../shared/rateLimit.js'
|
|
|
|
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
|
|
import { searchContent } from './searchContent.js'
|
|
|
|
type CreateSearchRouteArgs = {
|
|
/** Absolute origin to prefix result URLs with. */
|
|
baseUrl?: string
|
|
/** How to read the client IP for the rate limit — see clientIp(). */
|
|
clientIp?: ClientIpOptions
|
|
/** Pages collection. Default 'pages'. */
|
|
collection?: string
|
|
config: I18nConfig
|
|
/** Default result cap when ?limit is absent. Default 10. */
|
|
defaultLimit?: number
|
|
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, or the store from setRateLimitStore). 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
|
|
}
|
|
|
|
/**
|
|
* A JSON content-search endpoint. Powers both the site's own search UI and
|
|
* external agents — one ranking, one source of truth (shares searchContent with
|
|
* the MCP server's search_content tool).
|
|
*
|
|
* // app/api/search/route.ts
|
|
* import { createSearchRoute } from '@intecion/ipal-kit'
|
|
* import { getCachedPayload } from '@/lib/content'
|
|
* import { i18nConfig } from '@/i18n.config'
|
|
* export const dynamic = 'force-dynamic'
|
|
* export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,
|
|
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
|
|
*
|
|
* Query params: `q` (required), `locale`, `limit`. Response:
|
|
* { query, locale, count, results: [{ title, url, description?, slug }] }
|
|
*
|
|
* 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
|
|
// 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 limit = await consumeRateLimit({ key: clientIp(req, args.clientIp), scope: 'search', ...rl })
|
|
if (!limit.ok) {
|
|
return tooManyRequests(limit.retryAfter, { 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
|
|
const limitParam = url.searchParams.get('limit')
|
|
const limit = limitParam ? Number(limitParam) : defaultLimit
|
|
|
|
if (!query) {
|
|
return Response.json(
|
|
{ count: 0, error: 'Missing ?q', query: '', results: [] },
|
|
{ headers: { 'cache-control': 'no-store' }, status: 400 },
|
|
)
|
|
}
|
|
|
|
try {
|
|
const payload = await getCachedPayload()
|
|
const results = await searchContent({
|
|
baseUrl,
|
|
collection,
|
|
config,
|
|
homeSlug,
|
|
limit,
|
|
locale,
|
|
payload,
|
|
query,
|
|
summaryField,
|
|
})
|
|
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' } },
|
|
)
|
|
} catch (err) {
|
|
// DB unreachable (build) or unexpected — empty result rather than 500.
|
|
console.warn('[ipal] createSearchRoute: search failed:', err)
|
|
return Response.json(
|
|
{ count: 0, query, results: [] },
|
|
{ headers: { 'cache-control': 'no-store' }, status: 200 },
|
|
)
|
|
}
|
|
}
|
|
}
|