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(email): escape the welcome email and accept only real sign-up values

ravixalgorithmf1f5319fe8a6
diff --git a/__tests__/welcome-email.test.ts b/__tests__/welcome-email.test.ts
new file mode 100644
index 0000000..4a4b0af
--- /dev/null
+++ b/__tests__/welcome-email.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const sendMail = vi.fn().mockResolvedValue({ messageId: 'msg-1' });
+vi.mock('nodemailer', () => ({
+ default: { createTransport: () => ({ sendMail, verify: () => {} }) },
+}));
+
+process.env.NODEMAILER_EMAIL = '[email protected]';
+process.env.NODEMAILER_PASSWORD = 'secret';
+const { sendWelcomeEmail } = await import('@/lib/nodemailer');
+
+describe('sendWelcomeEmail', () => {
+ it('escapes the name and keeps only text and <strong> from the AI intro', async () => {
+ await sendWelcomeEmail({
+ email: '[email protected]',
+ name: `<a href="https://evil.example">Click</a> $' $&`,
+ intro: `<p style="x">Hi <strong>growth</strong> fan. <a href="https://evil.example">Verify your account</a><img src=x onerror=alert(1)><strong onclick="x">bold</strong> R&amp;D</p>`,
+ });
+
+ const { html } = sendMail.mock.calls[0][0];
+ expect(html).not.toContain('evil.example">');
+ expect(html).not.toContain('<a href="https://evil');
+ expect(html).not.toContain('<img src=x');
+ expect(html).not.toContain('onclick');
+ expect(html).toContain('&lt;a href=&quot;https://evil.example&quot;&gt;Click&lt;/a&gt; $&#39; $&amp;');
+ expect(html).toContain('Hi <strong>growth</strong> fan. Verify your accountbold</strong> R&amp;D</p>');
+ });
+});
diff --git a/lib/actions/auth.actions.ts b/lib/actions/auth.actions.ts
index edb79aa..a0cc221 100644
--- a/lib/actions/auth.actions.ts
+++ b/lib/actions/auth.actions.ts
@@ -3,8 +3,19 @@
import { auth } from "@/lib/better-auth/auth";
import { inngest } from "@/lib/inngest/client";
import { headers } from "next/headers";
+import { INVESTMENT_GOALS, PREFERRED_INDUSTRIES, RISK_TOLERANCE_OPTIONS } from "@/lib/constants";
+
+const isOption = (options: readonly { value: string }[], value: unknown) => options.some((o) => o.value === value);
export const signUpWithEmail = async ({ email, password, fullName, country, investmentGoals, riskTolerance, preferredIndustry }: SignUpFormData) => {
+ // These fields go into the AI prompt for the welcome email, so only accept the form's own values
+ if (typeof fullName !== 'string' || !fullName.trim() || fullName.length > 80
+ || typeof country !== 'string' || !/^[A-Z]{2}$/.test(country)
+ || !isOption(INVESTMENT_GOALS, investmentGoals)
+ || !isOption(RISK_TOLERANCE_OPTIONS, riskTolerance)
+ || !isOption(PREFERRED_INDUSTRIES, preferredIndustry)) {
+ return { success: false, error: 'Sign up failed' };
+ }
try {
const response = await auth.api.signUpEmail({ body: { email, password, name: fullName, country, investmentGoals, riskTolerance, preferredIndustry } })
diff --git a/lib/nodemailer/index.ts b/lib/nodemailer/index.ts
index ef9ee00..f0a099e 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 { escapeHtml, formatPrice } from "@/lib/utils";
+import { escapeHtml, formatPrice, sanitizeEmailIntro } from "@/lib/utils";
type EmailSendResult =
| { status: 'skipped' }
@@ -48,9 +48,10 @@ export const sendWelcomeEmail = async ({ email, name, intro }: WelcomeEmailData)
return { status: 'skipped' } satisfies EmailSendResult;
}
+ // Function replacements: a string would expand $& or $' inside the name
const htmlTemplate = WELCOME_EMAIL_TEMPLATE
- .replace('{{name}}', name)
- .replace('{{intro}}', intro);
+ .replace('{{name}}', () => escapeHtml(name))
+ .replace('{{intro}}', () => sanitizeEmailIntro(intro));
const mailOptions = {
from: `"Openstock" <${process.env.NODEMAILER_EMAIL}>`,
diff --git a/lib/utils.ts b/lib/utils.ts
index 9983550..b71a4f5 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -267,3 +267,14 @@ export const escapeHtml = (value: string) =>
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
+
+// The welcome intro is AI output from a prompt that includes sign-up fields, so it is untrusted HTML.
+// Keep its text and plain <strong>, drop every other tag (links, images, styles), and wrap it ourselves.
+export const sanitizeEmailIntro = (html: string) => {
+ const text = html
+ .replace(/<(?!\/?strong>)[^>]*>/gi, '')
+ .replace(/&nbsp;/g, ' ').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
+ .trim();
+ const safe = escapeHtml(text).replace(/&lt;(\/?)strong&gt;/gi, '<$1strong>');
+ return `<p class="mobile-text" style="margin: 0 0 30px 0; font-size: 16px; line-height: 1.6; color: #CCDADC;">${safe}</p>`;
+};