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): close review findings on server actions, alerts and email

ravixalgorithm9b2242d284d4
diff --git a/__tests__/alert-actions.test.ts b/__tests__/alert-actions.test.ts
index 0dbb50b..5f3e4c8 100644
--- a/__tests__/alert-actions.test.ts
+++ b/__tests__/alert-actions.test.ts
@@ -54,3 +54,25 @@ describe('alert actions are scoped to the session user', () => {
expect(create).not.toHaveBeenCalled();
});
});
+
+describe('createAlert validates untrusted input', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ requireUserId.mockResolvedValue('user-123');
+ create.mockImplementation(async (doc: unknown) => doc);
+ });
+
+ it('rejects symbols that could carry markup into alert emails', async () => {
+ await expect(createAlert({ symbol: '<img src=x>', targetPrice: 1, condition: 'ABOVE' })).rejects.toThrow('Invalid symbol');
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it('rejects unknown conditions', async () => {
+ await expect(createAlert({ symbol: 'AAPL', targetPrice: 1, condition: 'SIDEWAYS' as never })).rejects.toThrow('Invalid condition');
+ });
+
+ it('stores only validated fields, so callers cannot pre-trigger or extend an alert', async () => {
+ await createAlert({ symbol: ' brk.b ', targetPrice: 400, condition: 'BELOW', triggered: true, expiresAt: new Date(2100, 0) } as never);
+ expect(create).toHaveBeenCalledWith({ userId: 'user-123', symbol: 'BRK.B', targetPrice: 400, condition: 'BELOW', active: true });
+ });
+});
diff --git a/__tests__/reset-password-email.test.ts b/__tests__/reset-password-email.test.ts
index 6066bc4..2cdaeb7 100644
--- a/__tests__/reset-password-email.test.ts
+++ b/__tests__/reset-password-email.test.ts
@@ -11,7 +11,7 @@ import { sendPasswordResetEmail } from '@/lib/nodemailer/reset-password';
describe('sendPasswordResetEmail', () => {
const originalEnv = { ...process.env };
- const sendMailMock = vi.mocked(transporter.sendMail);
+ const sendMailMock = vi.mocked(transporter!.sendMail);
beforeEach(() => {
process.env = {
diff --git a/app/(root)/layout.tsx b/app/(root)/layout.tsx
index c75d18b..fcc73ab 100644
--- a/app/(root)/layout.tsx
+++ b/app/(root)/layout.tsx
@@ -18,7 +18,7 @@ const Layout = async ({ children }: { children: React.ReactNode }) => {
const [initialStocks, watchlist] = await Promise.all([
searchStocks(),
- getUserWatchlist(user.id),
+ getUserWatchlist(),
]);
return (
diff --git a/app/(root)/profile/page.tsx b/app/(root)/profile/page.tsx
index a4ed1ad..ffd11e8 100644
--- a/app/(root)/profile/page.tsx
+++ b/app/(root)/profile/page.tsx
@@ -4,18 +4,17 @@ import { Bell, KeyRound, ShieldCheck, Star } from "lucide-react";
import Panel from "@/components/Panel";
import ProfileForm from "@/components/profile/ProfileForm";
import PasswordForm from "@/components/profile/PasswordForm";
-import ConnectProviderButton from "@/components/profile/ConnectProviderButton";
import { auth, getSession } from "@/lib/better-auth/auth";
import { getUserWatchlist } from "@/lib/actions/watchlist.actions";
import { getUserAlerts } from "@/lib/actions/alert.actions";
export const metadata = { title: 'Profile | OpenStock' };
-const PROVIDERS = [
- { id: 'credential', label: 'Email and password', configured: true },
- { id: 'google', label: 'Google', configured: !!process.env.GOOGLE_CLIENT_ID },
- { id: 'github', label: 'GitHub', configured: !!process.env.GITHUB_CLIENT_ID },
-] as const;
+const METHOD_LABELS: Record<string, string> = {
+ credential: 'Email and password',
+ google: 'Google',
+ github: 'GitHub',
+};
export default async function ProfilePage() {
const session = await getSession();
@@ -24,8 +23,8 @@ export default async function ProfilePage() {
const [accounts, watchlist, alerts] = await Promise.all([
auth.api.listUserAccounts({ headers: await headers() }).catch(() => []),
- getUserWatchlist(user.id),
- getUserAlerts(user.id),
+ getUserWatchlist(),
+ getUserAlerts(),
]);
const linked = new Set(accounts.map((a: { providerId: string }) => a.providerId));
const activeAlerts = alerts.filter((a: { triggered?: boolean }) => !a.triggered).length;
@@ -75,17 +74,11 @@ export default async function ProfilePage() {
<div className="flex min-w-0 flex-col gap-3">
<Panel title="Sign-in methods" sub="Ways you can get into this account">
<ul className="row-list">
- {PROVIDERS.filter((p) => p.configured || linked.has(p.id)).map((p) => (
- <li key={p.id} className="flex items-center gap-3 px-3.5 py-3">
+ {[...linked].map((id) => (
+ <li key={id} className="flex items-center gap-3 px-3.5 py-3">
<span className="bento-ico"><KeyRound /></span>
- <span className="flex-1 font-semibold">{p.label}</span>
- {linked.has(p.id) ? (
- <span className="pill is-up">Connected</span>
- ) : p.id === 'credential' ? (
- <span className="pill">Not set</span>
- ) : (
- <ConnectProviderButton provider={p.id} />
- )}
+ <span className="flex-1 font-semibold">{METHOD_LABELS[id] ?? id}</span>
+ <span className="pill is-up">Connected</span>
</li>
))}
</ul>
diff --git a/app/(root)/watchlist/page.tsx b/app/(root)/watchlist/page.tsx
index 58872b9..b6d920d 100644
--- a/app/(root)/watchlist/page.tsx
+++ b/app/(root)/watchlist/page.tsx
@@ -1,6 +1,5 @@
import { Suspense } from 'react';
import { Plus } from 'lucide-react';
-import { requireUserId } from '@/lib/better-auth/auth';
import { getUserWatchlist } from '@/lib/actions/watchlist.actions';
import { getUserAlerts } from '@/lib/actions/alert.actions';
import { getNews, getWatchlistData } from '@/lib/actions/finnhub.actions';
@@ -33,8 +32,7 @@ async function News({ symbols }: { symbols: string[] }) {
// DB reads render first; everything from Finnhub streams in behind skeletons.
export default async function WatchlistPage() {
- const userId = await requireUserId();
- const [items, alerts] = await Promise.all([getUserWatchlist(userId), getUserAlerts(userId)]);
+ const [items, alerts] = await Promise.all([getUserWatchlist(), getUserAlerts()]);
const symbols: string[] = items.map((item: { symbol: string }) => item.symbol);
const activeAlerts = alerts.filter((a: { triggered?: boolean }) => !a.triggered).length;
diff --git a/components/profile/ConnectProviderButton.tsx b/components/profile/ConnectProviderButton.tsx
deleted file mode 100644
index 905a547..0000000
--- a/components/profile/ConnectProviderButton.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-'use client';
-
-import { useState } from "react";
-import { toast } from "sonner";
-import { connectProvider } from "@/lib/actions/profile.actions";
-
-export default function ConnectProviderButton({ provider }: { provider: 'google' | 'github' }) {
- const [pending, setPending] = useState(false);
-
- const onClick = async () => {
- setPending(true);
- const result = await connectProvider(provider);
- if (result.success && result.url) {
- window.location.href = result.url;
- return;
- }
- setPending(false);
- toast.error('Couldn’t connect', { description: result.error });
- };
-
- return (
- <button type="button" onClick={onClick} disabled={pending} className="btn btn-ghost h-8 px-3 text-[13px]">
- {pending ? 'Redirecting' : 'Connect'}
- </button>
- );
-}
diff --git a/components/stocks/StockHeader.tsx b/components/stocks/StockHeader.tsx
index c94dfd5..4dbc436 100644
--- a/components/stocks/StockHeader.tsx
+++ b/components/stocks/StockHeader.tsx
@@ -2,7 +2,6 @@ import { Bell, CalendarClock, Gauge, Landmark, MoveVertical } from "lucide-react
import WatchlistButton from "@/components/WatchlistButton";
import CreateAlertModal from "@/components/watchlist/CreateAlertModal";
import StockLivePrice from "@/components/stocks/StockLivePrice";
-import { requireUserId } from "@/lib/better-auth/auth";
import { isStockInWatchlist } from "@/lib/actions/watchlist.actions";
import { getCompanyProfile, getLiveQuotes } from "@/lib/actions/finnhub.actions";
import { formatNumber, formatPrice, formatSymbolForTradingView } from "@/lib/utils";
@@ -11,8 +10,8 @@ import { symbolInfoConfig } from "@/lib/constants";
import TradingViewWidget from "@/components/TradingViewWidget";
// Symbols Finnhub's free plan can't price (most non-US listings) use TradingView's quote panel instead.
-async function TradingViewHeader({ symbol, userId }: { symbol: string; userId: string }) {
- const isInWatchlist = await isStockInWatchlist(userId, symbol);
+async function TradingViewHeader({ symbol }: { symbol: string }) {
+ const isInWatchlist = await isStockInWatchlist(symbol);
const tvSymbol = formatSymbolForTradingView(symbol);
return (
<section className="hatch">
@@ -36,11 +35,10 @@ async function TradingViewHeader({ symbol, userId }: { symbol: string; userId: s
}
export default async function StockHeader({ symbol }: { symbol: string }) {
- const userId = await requireUserId();
- if (!hasFinnhubQuotes(symbol)) return <TradingViewHeader symbol={symbol} userId={userId} />;
+ if (!hasFinnhubQuotes(symbol)) return <TradingViewHeader symbol={symbol} />;
const [isInWatchlist, quotes, profile] = await Promise.all([
- isStockInWatchlist(userId, symbol),
+ isStockInWatchlist(symbol),
getLiveQuotes([symbol]),
getCompanyProfile(symbol),
]);
diff --git a/lib/actions/alert.actions.ts b/lib/actions/alert.actions.ts
index 980d3fc..cb02b80 100644
--- a/lib/actions/alert.actions.ts
+++ b/lib/actions/alert.actions.ts
@@ -1,33 +1,37 @@
'use server';
import { connectToDatabase } from '@/database/mongoose';
-import { Alert, type IAlert } from '@/database/models/alert.model';
+import { Alert } 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
+// A ticker (AAPL, BRK.B) or a Binance pair. Anything else, including markup, is rejected:
+// 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'];
+
+// Create a new alert. Server actions take untrusted input, so only validated fields are stored.
export async function createAlert(params: {
symbol: string;
targetPrice: number;
condition: 'ABOVE' | 'BELOW';
}) {
const userId = await requireUserId();
+ const symbol = String(params.symbol ?? '').trim().toUpperCase();
+ const targetPrice = Number(params.targetPrice);
+ const condition = params.condition;
+
+ if (!SYMBOL_PATTERN.test(symbol)) throw new Error('Invalid symbol');
+ if (!CONDITIONS.includes(condition)) throw new Error('Invalid condition');
// 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');
- }
+ 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');
+
try {
await connectToDatabase();
- const newAlert = await Alert.create({
- ...params,
- userId,
- active: true,
- // expiresAt handled by default value in schema
- });
+ // expiresAt and triggered come from the schema defaults, never from the caller
+ const newAlert = await Alert.create({ userId, symbol, targetPrice, condition, active: true });
revalidatePath('/watchlist');
return JSON.parse(JSON.stringify(newAlert));
} catch (error) {
@@ -37,7 +41,8 @@ export async function createAlert(params: {
}
// Get all alerts for a user
-export async function getUserAlerts(userId: string) {
+export async function getUserAlerts() {
+ const userId = await requireUserId();
try {
await connectToDatabase();
const alerts = await Alert.find({ userId }).sort({ createdAt: -1 });
diff --git a/lib/actions/finnhub.actions.ts b/lib/actions/finnhub.actions.ts
index cddb445..e53c875 100644
--- a/lib/actions/finnhub.actions.ts
+++ b/lib/actions/finnhub.actions.ts
@@ -5,6 +5,7 @@ import { POPULAR_STOCKS } from '@/lib/constants';
import { cache } from 'react';
import { QUOTE_TTL_SECONDS } from '@/lib/market-data';
import { hasFinnhubQuotes } from '@/lib/markets';
+import { getSession } from '@/lib/better-auth/auth';
const FINNHUB_BASE_URL = 'https://finnhub.io/api/v1';
// Key pool: each free key has its own 60 req/min, so N keys = N x the quota. Rotated per request.
@@ -129,10 +130,12 @@ async function fetchJSON<T>(url: string, revalidateSeconds = 0): Promise<T> {
return value;
},
(error) => {
- // A stalling endpoint fails fast for a minute instead of costing every visitor the full timeout
- if (!responseCache.get(url) || responseCache.get(url)!.failed) {
- store({ value: null, freshUntil: Date.now() + FAILURE_TTL_MS, failed: true });
- }
+ // A stalling endpoint fails fast for a minute instead of costing every visitor the full timeout.
+ // A stale value keeps being served, but its next refresh also waits out the cool-down.
+ const existing = responseCache.get(url);
+ store(existing && !existing.failed
+ ? { value: existing.value, freshUntil: Date.now() + FAILURE_TTL_MS }
+ : { value: null, freshUntil: Date.now() + FAILURE_TTL_MS, failed: true });
throw error;
},
);
@@ -314,6 +317,8 @@ export const searchStocks = cache(async (query?: string): Promise<StockWithWatch
__exchange: exchange,
}));
} else {
+ // A public server action: only signed-in users may spend Finnhub quota on searches
+ if (!(await getSession())?.user) return [];
const url = `${FINNHUB_BASE_URL}/search?q=${encodeURIComponent(trimmed)}`;
const data = await fetchJSON<FinnhubSearchResponse>(url, 1800);
results = Array.isArray(data?.result) ? data.result : [];
diff --git a/lib/actions/profile.actions.ts b/lib/actions/profile.actions.ts
index 8a82193..917abfd 100644
--- a/lib/actions/profile.actions.ts
+++ b/lib/actions/profile.actions.ts
@@ -57,16 +57,3 @@ export async function changePassword({ currentPassword, newPassword }: { current
return { success: false, error: 'Current password is incorrect, or the new one is too short.' };
}
}
-
-export async function connectProvider(provider: 'google' | 'github') {
- try {
- const { url } = await auth.api.linkSocialAccount({
- headers: await headers(),
- body: { provider, callbackURL: '/profile' },
- });
- return { success: true, url };
- } catch (e) {
- console.error('Account linking failed', e);
- return { success: false, error: `${provider === 'google' ? 'Google' : 'GitHub'} isn’t available right now.` };
- }
-}
diff --git a/lib/actions/user.actions.ts b/lib/actions/user.actions.ts
index 1630e5b..e527941 100644
--- a/lib/actions/user.actions.ts
+++ b/lib/actions/user.actions.ts
@@ -1,6 +1,8 @@
-'use server';
+// Server-only helpers for background jobs. Deliberately NOT a 'use server' module: these read
+// every user's email and watchlist, so they must never be callable from a browser.
import {connectToDatabase} from "@/database/mongoose";
+import { Watchlist } from "@/database/models/watchlist.model";
export const getAllUsersForNewsEmail = async () => {
try {
@@ -22,4 +24,28 @@ export const getAllUsersForNewsEmail = async () => {
console.error('Error fetching users for news email:', e)
return []
}
-}
\ No newline at end of file
+}
+
+export async function getWatchlistSymbolsByEmail(email: string): Promise<string[]> {
+ if (!email) return [];
+
+ try {
+ const mongoose = await connectToDatabase();
+ const db = mongoose.connection.db;
+ if (!db) throw new Error('MongoDB connection not found');
+
+ // Better Auth stores users in the "user" collection
+ const user = await db.collection('user').findOne<{ _id?: unknown; id?: string; email?: string }>({ email });
+
+ if (!user) return [];
+
+ const userId = (user.id as string) || String(user._id || '');
+ if (!userId) return [];
+
+ const items = await Watchlist.find({ userId }, { symbol: 1 }).lean();
+ return items.map((i) => String(i.symbol));
+ } catch (err) {
+ console.error('getWatchlistSymbolsByEmail error:', err);
+ return [];
+ }
+}
diff --git a/lib/actions/watchlist.actions.ts b/lib/actions/watchlist.actions.ts
index bf5dca5..0b2a57f 100644
--- a/lib/actions/watchlist.actions.ts
+++ b/lib/actions/watchlist.actions.ts
@@ -45,7 +45,8 @@ export async function removeFromWatchlist(symbol: string) {
}
}
-export async function getUserWatchlist(userId: string) {
+export async function getUserWatchlist() {
+ const userId = await requireUserId();
try {
await connectToDatabase();
const watchlist = await Watchlist.find({ userId }).sort({ addedAt: -1 });
@@ -57,7 +58,8 @@ export async function getUserWatchlist(userId: string) {
}
// Check if a symbol is in the user's watchlist
-export async function isStockInWatchlist(userId: string, symbol: string) {
+export async function isStockInWatchlist(symbol: string) {
+ const userId = await requireUserId();
try {
await connectToDatabase();
const item = await Watchlist.findOne({ userId, symbol: symbol.toUpperCase() });
@@ -67,29 +69,3 @@ export async function isStockInWatchlist(userId: string, symbol: string) {
return false;
}
}
-
-// -- Legacy Support (if needed by other components) --
-
-export async function getWatchlistSymbolsByEmail(email: string): Promise<string[]> {
- if (!email) return [];
-
- try {
- const mongoose = await connectToDatabase();
- const db = mongoose.connection.db;
- if (!db) throw new Error('MongoDB connection not found');
-
- // Better Auth stores users in the "user" collection
- const user = await db.collection('user').findOne<{ _id?: unknown; id?: string; email?: string }>({ email });
-
- if (!user) return [];
-
- const userId = (user.id as string) || String(user._id || '');
- if (!userId) return [];
-
- const items = await Watchlist.find({ userId }, { symbol: 1 }).lean();
- return items.map((i) => String(i.symbol));
- } catch (err) {
- console.error('getWatchlistSymbolsByEmail error:', err);
- return [];
- }
-}
\ No newline at end of file
diff --git a/lib/better-auth/auth.ts b/lib/better-auth/auth.ts
index 713e74e..03afe76 100644
--- a/lib/better-auth/auth.ts
+++ b/lib/better-auth/auth.ts
@@ -45,6 +45,13 @@ const createAuth = (database: MongoDb) => betterAuth({
session: {
cookieCache: { enabled: true, maxAge: 5 * 60 },
},
+ // No account linking. Sign-up doesn't verify emails, so linking a Google/GitHub identity to an
+ // existing account with the same email would let someone pre-register a victim's address and
+ // later capture their social sign-in. In Better Auth 1.3 this switch also blocks explicit
+ // linking; revisit (email verification or a newer Better Auth) when social sign-in ships.
+ account: {
+ accountLinking: { enabled: false },
+ },
// Providers stay disabled until their env vars are set
socialProviders: {
google: {
diff --git a/lib/inngest/functions.ts b/lib/inngest/functions.ts
index 4986d6d..f63c0e4 100644
--- a/lib/inngest/functions.ts
+++ b/lib/inngest/functions.ts
@@ -1,8 +1,7 @@
import { inngest } from "@/lib/inngest/client";
import { NEWS_SUMMARY_EMAIL_PROMPT, PERSONALIZED_WELCOME_EMAIL_PROMPT } from "@/lib/inngest/prompts";
import { sendNewsSummaryEmail, sendStockAlertEmail, sendWelcomeEmail } from "@/lib/nodemailer";
-import { getAllUsersForNewsEmail } from "@/lib/actions/user.actions";
-import { getWatchlistSymbolsByEmail } from "@/lib/actions/watchlist.actions";
+import { getAllUsersForNewsEmail, getWatchlistSymbolsByEmail } from "@/lib/actions/user.actions";
import { getNews } from "@/lib/actions/finnhub.actions";
import { getFormattedTodayDate } from "@/lib/utils";
import { callAIProviderWithFallback } from "@/lib/ai-provider";
@@ -281,9 +280,18 @@ export const checkStockAlerts = inngest.createFunction(
if (!db) throw new Error("No DB Connection");
for (const { alert, currentPrice } of triggeredAlerts) {
+ // Claim the alert atomically before emailing. Inngest's concurrency limits steps, not
+ // whole runs, so two overlapping runs can hold the same alert; only one wins this update.
+ const claimed = await Alert.findOneAndUpdate(
+ { _id: alert._id, active: true, triggered: false },
+ { $set: { triggered: true, active: false } },
+ );
+ if (!claimed) continue;
+ const release = () => Alert.findByIdAndUpdate(alert._id, { triggered: false, active: true }).catch(() => {});
+
console.log(`🚀 ALERT FIRED: ${alert.symbol} is ${currentPrice} (${alert.condition} ${alert.targetPrice})`);
- // Per-alert try/catch: a failure leaves the alert active so the next 5-min run retries it,
+ // Per-alert try/catch: a failure releases the claim so the next 5-min run retries it,
// and never throws the step (a step retry would re-email alerts already sent in this loop).
try {
// Better Auth users may be keyed by `id` or `_id` (see getWatchlistSymbolsByEmail)
@@ -301,14 +309,13 @@ export const checkStockAlerts = inngest.createFunction(
targetPrice: alert.targetPrice,
condition: alert.condition,
});
- // Email not configured: keep the alert active so it fires once email works
- if (result.status === 'skipped') continue;
+ // Email not configured: release so the alert fires once email works
+ if (result.status === 'skipped') await release();
} else {
console.warn(`⚠️ No email for user ${alert.userId}; closing alert ${alert._id} without notifying`);
}
-
- await Alert.findByIdAndUpdate(alert._id, { triggered: true, active: false });
} catch (error) {
+ await release();
console.error(`❌ Failed to process alert ${alert._id} (${alert.symbol}); will retry next run`, error);
}
}
diff --git a/lib/nodemailer/index.ts b/lib/nodemailer/index.ts
index c4591a8..ef9ee00 100644
--- a/lib/nodemailer/index.ts
+++ b/lib/nodemailer/index.ts
@@ -5,7 +5,7 @@ import {
STOCK_ALERT_UPPER_EMAIL_TEMPLATE,
STOCK_ALERT_LOWER_EMAIL_TEMPLATE,
} from "@/lib/nodemailer/templates";
-import { formatPrice } from "@/lib/utils";
+import { escapeHtml, formatPrice } from "@/lib/utils";
type EmailSendResult =
| { status: 'skipped' }
@@ -110,18 +110,22 @@ export const sendStockAlertEmail = async (
}
const isUpper = condition === 'ABOVE';
+ // Binance pairs are quoted in USDT, everything else Finnhub prices here is USD
+ const money = (value: number) => symbol.startsWith('BINANCE:')
+ ? `${value.toLocaleString('en-US', { maximumFractionDigits: value < 1 ? 6 : 2 })} USDT`
+ : formatPrice(value);
const htmlTemplate = (isUpper ? STOCK_ALERT_UPPER_EMAIL_TEMPLATE : STOCK_ALERT_LOWER_EMAIL_TEMPLATE)
- .replaceAll('{{symbol}}', symbol)
+ .replaceAll('{{symbol}}', escapeHtml(symbol))
.replaceAll('{{company}}', '') // Alerts don't store the company name
- .replaceAll('{{currentPrice}}', formatPrice(currentPrice))
- .replaceAll('{{targetPrice}}', formatPrice(targetPrice))
+ .replaceAll('{{currentPrice}}', money(currentPrice))
+ .replaceAll('{{targetPrice}}', money(targetPrice))
.replaceAll('{{timestamp}}', new Date().toUTCString());
const mailOptions = {
from: `"Openstock" <${process.env.NODEMAILER_EMAIL}>`,
to: email,
- subject: `🔔 Price Alert: ${symbol} is ${isUpper ? 'above' : 'below'} ${formatPrice(targetPrice)}`,
- text: `${symbol} is now ${formatPrice(currentPrice)}, ${isUpper ? 'above' : 'below'} your target of ${formatPrice(targetPrice)}.`,
+ subject: `🔔 Price Alert: ${symbol} is ${isUpper ? 'above' : 'below'} ${money(targetPrice)}`,
+ text: `${symbol} is now ${money(currentPrice)}, ${isUpper ? 'above' : 'below'} your target of ${money(targetPrice)}.`,
html: htmlTemplate,
};
diff --git a/lib/nodemailer/reset-password.ts b/lib/nodemailer/reset-password.ts
index 786eaa5..21080bd 100644
--- a/lib/nodemailer/reset-password.ts
+++ b/lib/nodemailer/reset-password.ts
@@ -1,12 +1,6 @@
import { transporter } from "@/lib/nodemailer";
+import { escapeHtml } from "@/lib/utils";
-const escapeHtml = (value: string) =>
- value
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&#39;');
// Better Auth hands us an already-encoded URL (callbackURL=http%3A%2F%2F...).
// encodeURI would turn those % into %25 and the link fails with INVALID_CALLBACKURL,
@@ -18,7 +12,7 @@ export const sendPasswordResetEmail = async (
{ email, name, resetUrl }: { email: string; name?: string | null; resetUrl: string }
) => {
try {
- if (!process.env.NODEMAILER_EMAIL || !process.env.NODEMAILER_PASSWORD) {
+ if (!transporter || !process.env.NODEMAILER_EMAIL || !process.env.NODEMAILER_PASSWORD) {
throw new Error('Email credentials not configured');
}
diff --git a/lib/utils.ts b/lib/utils.ts
index 51bc448..5a89571 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -240,4 +240,13 @@ export function formatSymbolForTradingView(symbol: string): string {
}
return upperSymbol;
-}
\ No newline at end of file
+}
+
+// For values interpolated into email HTML
+export const escapeHtml = (value: string) =>
+ value
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');