feat: add ratelimiting to guestbook posts

This commit is contained in:
dusk 2024-11-26 20:32:04 +03:00
parent d8f2f2928e
commit 7b2267df8c
Signed by: dusk
SSH Key Fingerprint: SHA256:Abmvag+juovVufZTxyWY8KcVgrznxvBjQpJesv071Aw
3 changed files with 15 additions and 2 deletions

BIN
bun.lockb

Binary file not shown.

View File

@ -31,6 +31,7 @@
"svelte": "^4.2.19", "svelte": "^4.2.19",
"svelte-adapter-bun": "^0.5.2", "svelte-adapter-bun": "^0.5.2",
"svelte-check": "^3.8.6", "svelte-check": "^3.8.6",
"sveltekit-rate-limiter": "^0.6.1",
"tailwindcss": "^3.4.15", "tailwindcss": "^3.4.15",
"tslib": "^2.8.1", "tslib": "^2.8.1",
"typescript": "^5.7.2", "typescript": "^5.7.2",

View File

@ -1,10 +1,16 @@
import { env } from '$env/dynamic/private' import { env } from '$env/dynamic/private'
import { redirect, type Cookies } from '@sveltejs/kit' import { redirect, type Cookies, type RequestEvent } from '@sveltejs/kit'
import auth from '$lib/guestbookAuth' import auth from '$lib/guestbookAuth'
import { scopeCookies as _scopeCookies } from '$lib'; import { scopeCookies as _scopeCookies } from '$lib';
import { RetryAfterRateLimiter } from 'sveltekit-rate-limiter/server';
export const prerender = false; export const prerender = false;
const createPostRatelimiter = new RetryAfterRateLimiter({
IP: [10, 'd'],
IPUA: [5, 'h'],
})
interface Entry { interface Entry {
author: string, author: string,
content: string, content: string,
@ -16,9 +22,15 @@ const scopeCookies = (cookies: Cookies) => {
} }
const postAction = (client: any, scopes: string[]) => { const postAction = (client: any, scopes: string[]) => {
return async ({ request, cookies }: { request: Request, cookies: Cookies }) => { return async (event: RequestEvent) => {
const { request, cookies } = event
const scopedCookies = scopeCookies(cookies) const scopedCookies = scopeCookies(cookies)
scopedCookies.set("postAuth", client.name) scopedCookies.set("postAuth", client.name)
const rateStatus = await createPostRatelimiter.check(event)
if (rateStatus.limited) {
scopedCookies.set("sendError", `you are being ratelimited sowwy :c, try again after ${rateStatus.retryAfter} seconds`)
redirect(303, auth.callbackUrl)
}
const form = await request.formData() const form = await request.formData()
const content = form.get("content")?.toString().substring(0, 512) const content = form.get("content")?.toString().substring(0, 512)
const anon = !(form.get("anon") === null) const anon = !(form.get("anon") === null)