Skip to content

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(security): scope server actions to the signed-in user, load middleware, redact DB credentials

ravixalgorithmf1045c2ab480
diff --git a/database/mongoose.ts b/database/mongoose.ts
index 6228935..85ab821 100644
--- a/database/mongoose.ts
+++ b/database/mongoose.ts
@@ -47,6 +47,6 @@ export const connectToDatabase = async () => {
throw err;
}
- console.log(`MongoDB Connected ${MONGODB_URI} in ${process.env.NODE_ENV}`);
+ console.log(`MongoDB Connected ${MONGODB_URI.replace(/\/\/[^@]*@/, '//***@')} in ${process.env.NODE_ENV}`);
return cached.conn;
}
\ No newline at end of file
diff --git a/lib/actions/alert.actions.ts b/lib/actions/alert.actions.ts
index eb7fb8e..1130d92 100644
--- a/lib/actions/alert.actions.ts
+++ b/lib/actions/alert.actions.ts
@@ -3,18 +3,28 @@
import { connectToDatabase } from '@/database/mongoose';
import { Alert, type IAlert } from '@/database/models/alert.model';
import { revalidatePath } from 'next/cache';
+import { requireUserId } from '@/lib/better-auth/auth';
+import { hasFinnhubQuotes } from '@/lib/markets';
// Create a new alert
export async function createAlert(params: {
- userId: string;
symbol: string;
targetPrice: number;
condition: 'ABOVE' | 'BELOW';
}) {
+ const userId = await requireUserId();
+ // The alert checker prices symbols through Finnhub, whose free plan covers US stocks and crypto
+ if (!hasFinnhubQuotes(params.symbol)) {
+ throw new Error('Alerts are available for US stocks and crypto');
+ }
+ if (!Number.isFinite(params.targetPrice) || params.targetPrice <= 0) {
+ throw new Error('Target price must be a positive number');
+ }
try {
await connectToDatabase();
const newAlert = await Alert.create({
...params,
+ userId,
active: true,
// expiresAt handled by default value in schema
});
@@ -40,9 +50,10 @@ export async function getUserAlerts(userId: string) {
// Delete an alert
export async function deleteAlert(alertId: string) {
+ const userId = await requireUserId();
try {
await connectToDatabase();
- await Alert.findByIdAndDelete(alertId);
+ await Alert.findOneAndDelete({ _id: alertId, userId });
revalidatePath('/watchlist');
return { success: true };
} catch (error) {
@@ -53,9 +64,10 @@ export async function deleteAlert(alertId: string) {
// Toggle alert active status (optional utility)
export async function toggleAlert(alertId: string, active: boolean) {
+ const userId = await requireUserId();
try {
await connectToDatabase();
- await Alert.findByIdAndUpdate(alertId, { active });
+ await Alert.findOneAndUpdate({ _id: alertId, userId }, { active });
revalidatePath('/watchlist');
return { success: true };
} catch (error) {
diff --git a/lib/actions/watchlist.actions.ts b/lib/actions/watchlist.actions.ts
index 9e877f5..bf5dca5 100644
--- a/lib/actions/watchlist.actions.ts
+++ b/lib/actions/watchlist.actions.ts
@@ -3,10 +3,12 @@
import { connectToDatabase } from '@/database/mongoose';
import { Watchlist } from '@/database/models/watchlist.model';
import { revalidatePath } from 'next/cache';
+import { requireUserId } from '@/lib/better-auth/auth';
// -- CRUD Operations --
-export async function addToWatchlist(userId: string, symbol: string, company: string) {
+export async function addToWatchlist(symbol: string, company: string) {
+ const userId = await requireUserId();
try {
await connectToDatabase();
@@ -22,7 +24,7 @@ export async function addToWatchlist(userId: string, symbol: string, company: st
{ upsert: true, new: true }
);
- revalidatePath('/watchlist');
+ revalidatePath('/', 'layout'); // sidebar lists the watchlist on every page
return JSON.parse(JSON.stringify(newItem));
} catch (error) {
console.error('Error adding to watchlist:', error);
@@ -30,12 +32,12 @@ export async function addToWatchlist(userId: string, symbol: string, company: st
}
}
-export async function removeFromWatchlist(userId: string, symbol: string) {
+export async function removeFromWatchlist(symbol: string) {
+ const userId = await requireUserId();
try {
await connectToDatabase();
await Watchlist.findOneAndDelete({ userId, symbol: symbol.toUpperCase() });
- revalidatePath('/watchlist');
- revalidatePath('/'); // In case it's used elsewhere
+ revalidatePath('/', 'layout'); // sidebar lists the watchlist on every page
return { success: true };
} catch (error) {
console.error('Error removing from watchlist:', error);
diff --git a/middleware/index.ts b/middleware.ts
similarity index 74%
rename from middleware/index.ts
rename to middleware.ts
index 9a66eba..324001c 100644
--- a/middleware/index.ts
+++ b/middleware.ts
@@ -1,7 +1,12 @@
import { NextRequest, NextResponse } from 'next/server';
import { getSessionCookie } from "better-auth/cookies";
+const PUBLIC_PATHS = new Set(['/', '/about', '/help', '/terms', '/api-docs', '/sponsor']);
+
export async function middleware(request: NextRequest) {
+ // The marketing site is public
+ if (PUBLIC_PATHS.has(request.nextUrl.pathname)) return NextResponse.next();
+
const sessionCookie = getSessionCookie(request);
// Check cookie presence - prevents obviously unauthorized users