OpenStock is an open-source alternative to expensive market platforms. Track real-time prices, set personalized alerts, and explore detailed company insights — built openly, for everyone, forever free.
fix(auth): rate-limit sign-in, sign-up, password reset and live quotes
ravixalgorithm27020483f042
diff --git a/app/api/quotes/route.ts b/app/api/quotes/route.tsindex ffe5fb5..7371965 100644--- a/app/api/quotes/route.ts+++ b/app/api/quotes/route.ts@@ -1,6 +1,7 @@import { NextRequest, NextResponse } from "next/server";import { getSession } from "@/lib/better-auth/auth";import { getLiveQuotes } from "@/lib/actions/finnhub.actions";+import { isRateLimited } from "@/lib/rate-limit";const MAX_SYMBOLS = 25;const SYMBOL_PATTERN = /^[A-Z0-9.:\-]{1,20}$/;@@ -17,6 +18,12 @@ export async function GET(req: NextRequest) {.filter((s) => SYMBOL_PATTERN.test(s)),)].slice(0, MAX_SYMBOLS);+ // Counted per symbol: unseen tickers each cost a Finnhub call. A 25-symbol watchlist polled every 15 s uses+ // about 100 a minute; the cap stops one free account from draining the shared key pool.+ if (await isRateLimited(`quotes:user:${session.user.id}`, 300, 60, symbols.length)) {+ return NextResponse.json({ error: "Too many requests" }, { status: 429 });+ }+return NextResponse.json(await getLiveQuotes(symbols), {headers: { "Cache-Control": "private, max-age=5" },});diff --git a/lib/actions/auth.actions.ts b/lib/actions/auth.actions.tsindex bc600cf..9780f4a 100644--- a/lib/actions/auth.actions.ts+++ b/lib/actions/auth.actions.ts@@ -5,6 +5,7 @@ import { inngest } from "@/lib/inngest/client";import { headers } from "next/headers";import { INVESTMENT_GOALS, PREFERRED_INDUSTRIES, RISK_TOLERANCE_OPTIONS } from "@/lib/constants";import countryList from "react-select-country-list";+import { clientIp, isRateLimited, TOO_MANY_ATTEMPTS } from "@/lib/rate-limit";const isOption = (options: readonly { value: string }[], value: unknown) => options.some((o) => o.value === value);const COUNTRY_CODES = new Set(countryList().getValues()); // the same list the sign-up country picker shows@@ -18,6 +19,10 @@ export const signUpWithEmail = async ({ email, password, fullName, country, inve|| !isOption(PREFERRED_INDUSTRIES, preferredIndustry)) {return { success: false, error: 'Sign up failed' };}+ // Each sign-up sends a welcome email from our Gmail and an AI call+ if (await isRateLimited(`sign-up:ip:${await clientIp()}`, 5, 60 * 60)) {+ return { success: false, error: TOO_MANY_ATTEMPTS };+ }try {const response = await auth.api.signUpEmail({ body: { email, password, name: fullName, country, investmentGoals, riskTolerance, preferredIndustry } })@@ -43,6 +48,11 @@ export const signUpWithEmail = async ({ email, password, fullName, country, inve}export const signInWithEmail = async ({ email, password }: SignInFormData) => {+ // Per IP against credential stuffing, per account against guessing one password from many IPs+ if (await isRateLimited(`sign-in:ip:${await clientIp()}`, 20, 10 * 60)+ || await isRateLimited(`sign-in:email:${String(email).trim().toLowerCase()}`, 10, 10 * 60)) {+ return { success: false, error: TOO_MANY_ATTEMPTS };+ }try {const response = await auth.api.signInEmail({ body: { email, password } })@@ -87,6 +97,11 @@ export const requestPasswordResetEmail =async ({ email }: { email: string }) =>if (!process.env.NODEMAILER_EMAIL || !process.env.NODEMAILER_PASSWORD) {return { success: false, error: 'Password reset email is not configured.' }}+ // Every request sends a real email from our Gmail; unlimited requests could exhaust its daily quota+ if (await isRateLimited(`reset:email:${String(email).trim().toLowerCase()}`, 3, 60 * 60)+ || await isRateLimited(`reset:ip:${await clientIp()}`, 10, 60 * 60)) {+ return { success: false, error: TOO_MANY_ATTEMPTS };+ }try {const configuredBaseUrl = process.env.BETTER_AUTH_URL;diff --git a/lib/rate-limit.ts b/lib/rate-limit.tsnew file mode 100644index 0000000..860f893--- /dev/null+++ b/lib/rate-limit.ts@@ -0,0 +1,39 @@+import { headers } from "next/headers";+import { connectToDatabase } from "@/database/mongoose";++type Counter = { _id: string; count: number; expiresAt: Date };+let ttlIndex: Promise<unknown> | null = null;++export const TOO_MANY_ATTEMPTS = 'Too many attempts. Please wait a few minutes and try again.';++// Fixed-window counters in MongoDB, shared by every server instance (an in-memory limit resets per serverless+// instance). better-auth's own limiter only runs on its /api/auth routes, not on auth.api calls from server actions.+// ponytail: two first hits in the same instant can both start at 1; fine for abuse limits.+export async function isRateLimited(key: string, max: number, windowSeconds: number, cost = 1): Promise<boolean> {+ const db = (await connectToDatabase()).connection.db;+ if (!db) return false;+ const counters = db.collection<Counter>('rate_limits');+ ttlIndex ??= counters.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 }).catch(() => null);++ const now = new Date();+ const counter = await counters.findOneAndUpdate(+ { _id: key, expiresAt: { $gt: now } },+ { $inc: { count: cost } },+ { returnDocument: 'after' },+ );+ if (counter) return counter.count > max;++ await counters.updateOne(+ { _id: key },+ { $set: { count: cost, expiresAt: new Date(now.getTime() + windowSeconds * 1000) } },+ { upsert: true },+ );+ return cost > max;+}++// Vercel and most proxies put the client first in x-forwarded-for. Self-hosted without a proxy the header can be+// forged, which is why every IP limit is paired with a per-account one.+export async function clientIp(): Promise<string> {+ const h = await headers();+ return h.get('x-forwarded-for')?.split(',')[0]?.trim() || h.get('x-real-ip') || 'unknown';+}