sveltekit-rate-limiter
Version:
A modular rate limiter for SvelteKit. Use in password resets, account registration, etc.
55 lines (54 loc) • 1.84 kB
JavaScript
import { defaultHashFunction } from '../hashFunction.js';
import { nanoid } from 'nanoid';
export class CookieRateLimiter {
rate;
cookieOptions;
secret;
requirePreflight;
cookieId;
hashFunction;
constructor(options) {
this.cookieId = options.name;
this.secret = options.secret;
this.rate = options.rate;
this.requirePreflight = options.preflight;
this.hashFunction = options.hashFunction ?? defaultHashFunction;
this.cookieOptions = {
path: '/',
httpOnly: true,
maxAge: 60 * 60 * 24 * 7,
sameSite: 'strict',
...options.serializeOptions
};
}
async hash(event) {
const currentId = await this.userIdFromCookie(event.cookies.get(this.cookieId), event);
return currentId ? currentId : false;
}
async preflight(event) {
const data = event.cookies.get(this.cookieId);
if (data) {
const userId = await this.userIdFromCookie(data, event);
if (userId)
return userId;
}
return this.setPreflightCookie(event);
}
async setPreflightCookie(event) {
const userId = nanoid();
event.cookies.set(this.cookieId, userId + ';' + (await this.hashFunction(this.secret + userId)), this.cookieOptions);
return userId;
}
async userIdFromCookie(cookie, event) {
if (!cookie)
return this.requirePreflight ? null : this.preflight(event);
const [userId, secretHash] = cookie.split(';');
if (!userId || !secretHash) {
return this.setPreflightCookie(event);
}
if ((await this.hashFunction(this.secret + userId)) != secretHash) {
return this.setPreflightCookie(event);
}
return userId;
}
}