Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions app/(chat)/api/chat/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { geolocation } from "@vercel/functions";
import { checkBotId } from "botid/server";
import { geolocation, ipAddress } from "@vercel/functions";
import {
convertToModelMessages,
createUIMessageStream,
Expand Down Expand Up @@ -31,6 +32,7 @@ import {
} from "@/lib/db/queries";
import type { DBMessage } from "@/lib/db/schema";
import { ChatbotError } from "@/lib/errors";
import { checkIpRateLimit } from "@/lib/ratelimit";
import type { ChatMessage } from "@/lib/types";
import { convertToUIMessages, generateUUID } from "@/lib/utils";
import { generateTitleFromUserMessage } from "../../actions";
Expand Down Expand Up @@ -62,12 +64,18 @@ export async function POST(request: Request) {
const { id, message, messages, selectedChatModel, selectedVisibilityType } =
requestBody;

const session = await auth();
const [botResult, session] = await Promise.all([checkBotId(), auth()]);

if (botResult.isBot) {
return new ChatbotError("unauthorized:chat").toResponse();
}

if (!session?.user) {
return new ChatbotError("unauthorized:chat").toResponse();
}

await checkIpRateLimit(ipAddress(request));

const userType: UserType = session.user.type;

const messageCount = await getMessageCountByUserId({
Expand Down
10 changes: 10 additions & 0 deletions instrumentation-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { initBotId } from "botid/client/core";

initBotId({
protect: [
{
path: "/api/chat",
method: "POST",
},
],
});
4 changes: 2 additions & 2 deletions lib/ai/entitlements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ export const entitlementsByUserType: Record<UserType, Entitlements> = {
* For users without an account
*/
guest: {
maxMessagesPerDay: 20,
maxMessagesPerDay: 10,
},

/*
* For users with an account
*/
regular: {
maxMessagesPerDay: 50,
maxMessagesPerDay: 10,
},

/*
Expand Down
42 changes: 42 additions & 0 deletions lib/ratelimit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { createClient } from "redis";

import { isProductionEnvironment } from "@/lib/constants";
import { ChatbotError } from "@/lib/errors";

const MAX_MESSAGES_PER_DAY = 10;
const TTL_SECONDS = 60 * 60 * 24;

let client: ReturnType<typeof createClient> | null = null;

function getClient() {
if (!client && process.env.REDIS_URL) {
client = createClient({ url: process.env.REDIS_URL });
client.on("error", () => {});
client.connect().catch(() => {
client = null;
});
}
return client;
}

export async function checkIpRateLimit(ip: string | undefined) {
if (!isProductionEnvironment || !ip) return;

const redis = getClient();
if (!redis?.isReady) return;

try {
const key = `ip-rate-limit:${ip}`;
const [count] = await redis
.multi()
.incr(key)
.expire(key, TTL_SECONDS, "NX")
.exec();

if (typeof count === "number" && count > MAX_MESSAGES_PER_DAY) {
throw new ChatbotError("rate_limit:chat");
}
} catch (error) {
if (error instanceof ChatbotError) throw error;
}
}
3 changes: 2 additions & 1 deletion next.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { NextConfig } from "next";
import { withBotId } from "botid/next/config";

const basePath = "/demo";

Expand All @@ -23,4 +24,4 @@ const nextConfig: NextConfig = {
},
};

export default nextConfig;
export default withBotId(nextConfig);
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"@xyflow/react": "^12.10.0",
"ai": "6.0.37",
"bcrypt-ts": "^5.0.2",
"botid": "1.5.6",
"class-variance-authority": "^0.7.1",
"classnames": "^2.5.1",
"clsx": "^2.1.1",
Expand Down
20 changes: 20 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading