Skip to content

An AI-powered search engine with a generative UI

feat(chat): reject scripted /api/chat requests with Vercel BotID (#1109)

Yoshiki Miurafc6125771a52
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index 5019592b..104cf8b3 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -9,6 +9,7 @@ import {
} from '@/lib/analytics'
import { getCurrentUser, getCurrentUserId } from '@/lib/auth/get-current-user'
import { isAnonymousMode } from '@/lib/auth/provider'
+import { rejectIfBot } from '@/lib/bot-protection'
import { getUserMessageIds } from '@/lib/db/actions'
import { generateId } from '@/lib/db/schema'
import { checkAndEnforceAdaptiveLimit } from '@/lib/rate-limit/adaptive-limit'
@@ -66,6 +67,9 @@ export async function POST(req: Request) {
}
try {
+ const botRejection = await rejectIfBot()
+ if (botRejection) return botRejection
+
const body = await req.json()
const { message, messages, chatId, trigger, messageId, isNewChat } = body
const analyticsId: unknown = body.analyticsId
diff --git a/bun.lock b/bun.lock
index 2a153a9f..d3c2c16c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -57,6 +57,7 @@
"ai": "^7.0.152",
"ai-sdk-ollama": "^4.5.1",
"better-auth": "^1.7.16",
+ "botid": "^1.5.12",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.0",
"cmdk": "1.0.0",
@@ -1129,6 +1130,8 @@
"boolbase": ["[email protected]", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="],
+ "botid": ["[email protected]", "", { "peerDependencies": { "next": "*", "react": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["next", "react"] }, "sha512-bUYGLDLbNOQJyTVfuBGzm1ADztJ/euV6XH9JgXZ9MG2CZvElgOycybVOsgHBjVwB4tFl77g7zs31kEvjYm2gAw=="],
+
"bowser": ["[email protected]", "", {}, "sha512-AlcaJBi/pqqJBIQ8U9Mcpc9i8Aqxn88Skv5d+xBX006BY5u8N3mGLHa5Lgppa7L/HfwgwLgZ6NYs+Ag6uUmJRA=="],
"brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg=="],
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 4da71c91..bbffd714 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -516,6 +516,10 @@ MAINTENANCE_MODE=true
Every page then returns a static maintenance page and every API route returns `503` JSON. Paths the proxy matcher skips (static assets, image-extension paths and `/api/favicon`) are still served. The value is read at request time, but most hosts (including Vercel) apply an environment change only on the next deployment.
+### Bot Protection (Vercel only)
+
+Builds on Vercel enable [Vercel BotID](https://vercel.com/docs/botid) for `POST /api/chat`, so scripted requests get `403` before any model call. If the check itself fails, the request is allowed and the error is logged. Other hosts skip BotID, since it needs Vercel's OIDC token.
+
### Source Favicons
Favicons for cited sources are fetched by the server and served from your own origin at `/api/favicon`, so a visitor's browser never tells the icon provider which sources a result cites. Responses are cached in memory and at the edge.
diff --git a/instrumentation-client.ts b/instrumentation-client.ts
new file mode 100644
index 00000000..63c633d6
--- /dev/null
+++ b/instrumentation-client.ts
@@ -0,0 +1,10 @@
+import { initBotId } from 'botid/client/core'
+
+import {
+ BOT_PROTECTED_ROUTES,
+ isBotProtectionEnabled
+} from '@/lib/bot-protection'
+
+if (isBotProtectionEnabled()) {
+ initBotId({ protect: BOT_PROTECTED_ROUTES })
+}
diff --git a/lib/__tests__/bot-protection.test.ts b/lib/__tests__/bot-protection.test.ts
new file mode 100644
index 00000000..827cbc8a
--- /dev/null
+++ b/lib/__tests__/bot-protection.test.ts
@@ -0,0 +1,52 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const checkBotId = vi.fn()
+vi.mock('botid/server', () => ({ checkBotId }))
+
+import { rejectIfBot } from '@/lib/bot-protection'
+
+describe('rejectIfBot', () => {
+ beforeEach(() => {
+ checkBotId.mockReset()
+ vi.stubEnv('BOTID_ENABLED', 'true')
+ })
+
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ })
+
+ it('skips the check when BotID is not enabled', async () => {
+ vi.stubEnv('BOTID_ENABLED', 'false')
+
+ expect(await rejectIfBot()).toBeNull()
+ expect(checkBotId).not.toHaveBeenCalled()
+ })
+
+ it('allows humans', async () => {
+ checkBotId.mockResolvedValue({ isBot: false })
+
+ expect(await rejectIfBot()).toBeNull()
+ })
+
+ it('rejects bots with a forbidden payload', async () => {
+ checkBotId.mockResolvedValue({ isBot: true })
+
+ const response = await rejectIfBot()
+
+ expect(response?.status).toBe(403)
+ expect(await response?.json()).toMatchObject({
+ type: 'forbidden',
+ code: 'forbidden',
+ retryable: false
+ })
+ })
+
+ it('allows the request when the check itself fails', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
+ checkBotId.mockRejectedValue(new Error('VERCEL_OIDC_TOKEN is not set'))
+
+ expect(await rejectIfBot()).toBeNull()
+ expect(consoleError).toHaveBeenCalled()
+ consoleError.mockRestore()
+ })
+})
diff --git a/lib/bot-protection.ts b/lib/bot-protection.ts
new file mode 100644
index 00000000..9d452c4c
--- /dev/null
+++ b/lib/bot-protection.ts
@@ -0,0 +1,31 @@
+// Set by next.config.mjs on Vercel builds.
+export function isBotProtectionEnabled(): boolean {
+ return process.env.BOTID_ENABLED === 'true'
+}
+
+export const BOT_PROTECTED_ROUTES = [{ path: '/api/chat', method: 'POST' }]
+
+export async function rejectIfBot(): Promise<Response | null> {
+ if (!isBotProtectionEnabled()) return null
+
+ try {
+ const { checkBotId } = await import('botid/server')
+ const verification = await checkBotId()
+ if (!verification.isBot) return null
+ } catch (error) {
+ // A broken check should not take chat down for everyone.
+ console.error('BotID check failed, allowing request:', error)
+ return null
+ }
+
+ return Response.json(
+ {
+ error:
+ 'This request could not be verified. Reload the page and try again.',
+ type: 'forbidden',
+ code: 'forbidden',
+ retryable: false
+ },
+ { status: 403 }
+ )
+}
diff --git a/next.config.mjs b/next.config.mjs
index b26a4636..dcec089e 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -1,5 +1,12 @@
+import { withBotId } from 'botid/next/config'
+
+// BotID needs Vercel's OIDC token, so it only runs on Vercel. VERCEL is set
+// at build time there; env inlines the result into the client bundle too.
+const botIdEnabled = process.env.VERCEL === '1'
+
/** @type {import('next').NextConfig} */
const nextConfig = {
+ env: { BOTID_ENABLED: botIdEnabled ? 'true' : 'false' },
skipTrailingSlashRedirect: true,
experimental: {
staleTimes: { dynamic: 300 }
@@ -47,4 +54,4 @@ const nextConfig = {
}
}
-export default nextConfig
+export default botIdEnabled ? withBotId(nextConfig) : nextConfig
diff --git a/package.json b/package.json
index d53f3733..31c8cbe4 100644
--- a/package.json
+++ b/package.json
@@ -73,6 +73,7 @@
"ai": "^7.0.152",
"ai-sdk-ollama": "^4.5.1",
"better-auth": "^1.7.16",
+ "botid": "^1.5.12",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.0",
"cmdk": "1.0.0",