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(watchlist): validate symbols and cap watchlists and alerts at 50
ravixalgorithm13e25774d8a0
diff --git a/__tests__/alert-actions.test.ts b/__tests__/alert-actions.test.tsindex 619a867..530d81c 100644--- a/__tests__/alert-actions.test.ts+++ b/__tests__/alert-actions.test.ts@@ -13,10 +13,12 @@ vi.mock('@/lib/market-data', () => ({ get alertsEnabled() { return flags.alertsEconst findOneAndDelete = vi.fn();const create = vi.fn();+const countDocuments = vi.fn().mockResolvedValue(0);vi.mock('@/database/models/alert.model', () => ({Alert: {findOneAndDelete: (...args: unknown[]) => findOneAndDelete(...args),create: (...args: unknown[]) => create(...args),+ countDocuments: (...args: unknown[]) => countDocuments(...args),},}));@@ -30,6 +32,13 @@ describe('alert actions are scoped to the session user', () => {create.mockImplementation(async (doc: unknown) => doc);});+ it('caps active alerts per user, counting only that user’s', async () => {+ countDocuments.mockResolvedValueOnce(50);+ await expect(createAlert({ symbol: 'AAPL', targetPrice: 200, condition: 'ABOVE' })).rejects.toThrow('up to 50 active alerts');+ expect(countDocuments).toHaveBeenCalledWith({ userId: 'user-123', active: true });+ expect(create).not.toHaveBeenCalled();+ });+it('deletes the user’s own alert', async () => {await expect(deleteAlert('alert-1')).resolves.toEqual({ success: true });expect(findOneAndDelete).toHaveBeenCalledWith({ _id: 'alert-1', userId: 'user-123' });diff --git a/components/WatchlistButton.tsx b/components/WatchlistButton.tsxindex ceaf2b1..60debf7 100644--- a/components/WatchlistButton.tsx+++ b/components/WatchlistButton.tsx@@ -27,8 +27,14 @@ const WatchlistButton = ({ symbol, company, isInWatchlist, variant = "button", osetAdded(next); // optimisticsetLoading(true);try {- if (next) await addToWatchlist(symbol, company);- else await removeFromWatchlist(symbol);+ if (next) {+ const result = await addToWatchlist(symbol, company);+ if (result && 'error' in result) {+ setAdded(false);+ toast.error(result.error);+ return;+ }+ } else await removeFromWatchlist(symbol);toast.success(next ? `${symbol} added to watchlist` : `${symbol} removed from watchlist`);onWatchlistChange?.(symbol, next);router.refresh(); // sidebar lists the watchlist from the layoutdiff --git a/lib/actions/alert.actions.ts b/lib/actions/alert.actions.tsindex bd586ca..5fd67a7 100644--- a/lib/actions/alert.actions.ts+++ b/lib/actions/alert.actions.ts@@ -11,6 +11,8 @@ import { alertsEnabled } from '@/lib/market-data';// the symbol ends up in alert emails.const SYMBOL_PATTERN = /^(BINANCE:[A-Z0-9]{2,20}|[A-Z0-9][A-Z0-9.-]{0,14})$/;const CONDITIONS = ['ABOVE', 'BELOW'];+// The checker re-prices every active alert's symbol through Finnhub every 5 minutes+const MAX_ACTIVE_ALERTS = 50;// Create a new alert. Server actions take untrusted input, so only validated fields are stored.export async function createAlert(params: {@@ -30,8 +32,12 @@ export async function createAlert(params: {if (!hasFinnhubQuotes(symbol)) throw new Error('Alerts are available for US stocks and crypto');if (!Number.isFinite(targetPrice) || targetPrice <= 0) throw new Error('Target price must be a positive number');+ await connectToDatabase();+ if (await Alert.countDocuments({ userId, active: true }) >= MAX_ACTIVE_ALERTS) {+ throw new Error(`You can have up to ${MAX_ACTIVE_ALERTS} active alerts`);+ }+try {- await connectToDatabase();// expiresAt and triggered come from the schema defaults, never from the callerconst newAlert = await Alert.create({ userId, symbol, targetPrice, condition, active: true });revalidatePath('/watchlist');diff --git a/lib/actions/watchlist.actions.ts b/lib/actions/watchlist.actions.tsindex 0b2a57f..08699bd 100644--- a/lib/actions/watchlist.actions.ts+++ b/lib/actions/watchlist.actions.ts@@ -5,20 +5,32 @@ import { Watchlist } from '@/database/models/watchlist.model';import { revalidatePath } from 'next/cache';import { requireUserId } from '@/lib/better-auth/auth';+// Tickers as Finnhub writes them (AAPL, BRK.B, RELIANCE.NS, M&M.NS, 0700.HK, BINANCE:BTCUSDT). Server actions take+// untrusted input, and every symbol here becomes Finnhub calls on /watchlist and in the news digest.+const SYMBOL_PATTERN = /^[A-Z0-9][A-Z0-9.&:-]{0,24}$/;+const MAX_WATCHLIST = 50;+// -- CRUD Operations --export async function addToWatchlist(symbol: string, company: string) {const userId = await requireUserId();+ const ticker = String(symbol ?? '').trim().toUpperCase();+ if (!SYMBOL_PATTERN.test(ticker)) throw new Error('Invalid symbol');+ const name = String(company ?? '').trim().slice(0, 120);try {await connectToDatabase();+ if (!(await Watchlist.exists({ userId, symbol: ticker })) && (await Watchlist.countDocuments({ userId })) >= MAX_WATCHLIST) {+ return { error: `Your watchlist is full (${MAX_WATCHLIST} stocks). Remove one to add another.` };+ }+// Upsert to avoid duplicates/errors if it already existsconst newItem = await Watchlist.findOneAndUpdate(- { userId, symbol: symbol.toUpperCase() },+ { userId, symbol: ticker },{userId,- symbol: symbol.toUpperCase(),- company,+ symbol: ticker,+ company: name,addedAt: new Date()},{ upsert: true, new: true }