Spaces:
Paused
Paused
support rate limiting based on user IP (#342)
Browse files
src/lib/types/MessageEvent.ts
CHANGED
|
@@ -3,4 +3,5 @@ import type { User } from "./User";
|
|
| 3 |
|
| 4 |
export interface MessageEvent extends Pick<Timestamps, "createdAt"> {
|
| 5 |
userId: User["_id"] | User["sessionId"];
|
|
|
|
| 6 |
}
|
|
|
|
| 3 |
|
| 4 |
export interface MessageEvent extends Pick<Timestamps, "createdAt"> {
|
| 5 |
userId: User["_id"] | User["sessionId"];
|
| 6 |
+
ip?: string;
|
| 7 |
}
|
src/routes/conversation/[id]/+server.ts
CHANGED
|
@@ -17,7 +17,7 @@ import { error } from "@sveltejs/kit";
|
|
| 17 |
import { ObjectId } from "mongodb";
|
| 18 |
import { z } from "zod";
|
| 19 |
|
| 20 |
-
export async function POST({ request, fetch, locals, params }) {
|
| 21 |
const id = z.string().parse(params.id);
|
| 22 |
const convId = new ObjectId(id);
|
| 23 |
const date = new Date();
|
|
@@ -37,10 +37,21 @@ export async function POST({ request, fetch, locals, params }) {
|
|
| 37 |
throw error(404, "Conversation not found");
|
| 38 |
}
|
| 39 |
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
|
|
|
| 44 |
}
|
| 45 |
|
| 46 |
const model = models.find((m) => m.id === conv.model);
|
|
@@ -143,6 +154,7 @@ export async function POST({ request, fetch, locals, params }) {
|
|
| 143 |
await collections.messageEvents.insertOne({
|
| 144 |
userId: userId,
|
| 145 |
createdAt: new Date(),
|
|
|
|
| 146 |
});
|
| 147 |
|
| 148 |
await collections.conversations.updateOne(
|
|
|
|
| 17 |
import { ObjectId } from "mongodb";
|
| 18 |
import { z } from "zod";
|
| 19 |
|
| 20 |
+
export async function POST({ request, fetch, locals, params, getClientAddress }) {
|
| 21 |
const id = z.string().parse(params.id);
|
| 22 |
const convId = new ObjectId(id);
|
| 23 |
const date = new Date();
|
|
|
|
| 37 |
throw error(404, "Conversation not found");
|
| 38 |
}
|
| 39 |
|
| 40 |
+
if (RATE_LIMIT !== "") {
|
| 41 |
+
let nEvents = 0;
|
| 42 |
+
if (locals.user?._id) {
|
| 43 |
+
// if logged in do rate limiting based on user id
|
| 44 |
+
nEvents = await collections.messageEvents.countDocuments({ userId });
|
| 45 |
+
} else {
|
| 46 |
+
// do rate limiting based on session id but also ip address
|
| 47 |
+
const nEventsIp = await collections.messageEvents.countDocuments({ ip: getClientAddress() });
|
| 48 |
+
const nEventsSession = await collections.messageEvents.countDocuments({ userId });
|
| 49 |
+
nEvents = Math.max(nEventsIp, nEventsSession);
|
| 50 |
+
}
|
| 51 |
|
| 52 |
+
if (nEvents > parseInt(RATE_LIMIT)) {
|
| 53 |
+
throw error(429, ERROR_MESSAGES.rateLimited);
|
| 54 |
+
}
|
| 55 |
}
|
| 56 |
|
| 57 |
const model = models.find((m) => m.id === conv.model);
|
|
|
|
| 154 |
await collections.messageEvents.insertOne({
|
| 155 |
userId: userId,
|
| 156 |
createdAt: new Date(),
|
| 157 |
+
ip: getClientAddress(),
|
| 158 |
});
|
| 159 |
|
| 160 |
await collections.conversations.updateOne(
|