Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(pulse): reject invalid recipient emails instead of dropping them (#921) (#924)
Gökhan Geyikaffb04d483d5
diff --git a/web/messages/en.json b/web/messages/en.jsonindex eaa2285bc..a10a73013 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2046,6 +2046,7 @@"pulseRecipients": "Recipients","pulseRecipientsPlaceholder": "[email protected], [email protected]","pulseRecipientsHint": "Comma-separated email addresses. Leave empty to send to every organization member.",+ "pulseRecipientsInvalid": "Not a valid email address: {emails}. Fix or remove it before saving.","pulseSaved": "Notification settings saved","pulseSaveFailed": "Could not save notification settings. Please try again.","pulseLoadFailed": "Could not load notification settings.",diff --git a/web/src/app/api/settings/pulse/route.ts b/web/src/app/api/settings/pulse/route.tsindex 0e64c6df8..c4753656b 100644--- a/web/src/app/api/settings/pulse/route.ts+++ b/web/src/app/api/settings/pulse/route.ts@@ -1,6 +1,7 @@import { NextResponse } from 'next/server';import { createClient } from '@/lib/supabase/server';import { supabaseAdmin } from '@/lib/supabase/admin';+import { parseRecipients } from '@/lib/pulse-recipients';/*** GET / PUT /api/settings/pulse@@ -105,13 +106,11 @@ export async function PUT(request: Request) {);}- const recipients = Array.isArray(body.recipients)- ? body.recipients- .filter((r): r is string => typeof r === 'string')- .map((r) => r.trim())- .filter((r) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r))- .slice(0, 50)- : [];+ const { valid, invalid } = parseRecipients(Array.isArray(body.recipients) ? body.recipients : []);+ if (invalid.length) {+ return NextResponse.json({ error: 'Invalid recipient email', invalid }, { status: 400 });+ }+ const recipients = valid.slice(0, 50);// The brand must belong to the caller's org.const { data: brand } = await supabaseAdmindiff --git a/web/src/components/settings/notifications-section.tsx b/web/src/components/settings/notifications-section.tsxindex 5749cc930..daade6645 100644--- a/web/src/components/settings/notifications-section.tsx+++ b/web/src/components/settings/notifications-section.tsx@@ -17,6 +17,7 @@ import {SelectValue,} from '@/components/ui/select';import { useUserRole } from '@/hooks/use-user-role';+import { parseRecipients } from '@/lib/pulse-recipients';/*** Settings → Notifications: Daily Pulse delivery preferences per brand@@ -38,6 +39,8 @@ export function NotificationsSection() {const { canManage } = useUserRole();const [brands, setBrands] = useState<BrandPulseSettings[]>([]);const [recipientDrafts, setRecipientDrafts] = useState<Record<string, string>>({});+ // Addresses that failed validation, per brand, shown under the field.+ const [invalidRecipients, setInvalidRecipients] = useState<Record<string, string[]>>({});const [loading, setLoading] = useState(true);const [savingBrand, setSavingBrand] = useState<string | null>(null);@@ -68,22 +71,28 @@ export function NotificationsSection() {async function save(brandId: string, frequency: string) {if (savingBrand) return;+ const { valid: recipients, invalid } = parseRecipients(+ (recipientDrafts[brandId] ?? '').split(','),+ );+ setInvalidRecipients((prev) => ({ ...prev, [brandId]: invalid }));+ if (invalid.length) return;setSavingBrand(brandId);try {- const recipients = (recipientDrafts[brandId] ?? '')- .split(',')- .map((r) => r.trim())- .filter(Boolean);const res = await fetch('/api/settings/pulse', {method: 'PUT',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ brandId, frequency, recipients }),});- const body = (await res.json().catch(() => ({}))) as { error?: string };+ const body = (await res.json().catch(() => ({}))) as { error?: string; invalid?: string[] };+ if (body.invalid?.length) {+ setInvalidRecipients((prev) => ({ ...prev, [brandId]: body.invalid ?? [] }));+ return;+ }if (!res.ok) throw new Error(body.error || 'Save failed');setBrands((prev) =>prev.map((b) => (b.brandId === brandId ? { ...b, frequency, recipients } : b)),);+ setRecipientDrafts((prev) => ({ ...prev, [brandId]: recipients.join(', ') }));toast.success(t('pulseSaved'));} catch {toast.error(t('pulseSaveFailed'));@@ -140,13 +149,23 @@ export function NotificationsSection() {<Inputid={`pulse-recipients-${brand.brandId}`}value={recipientDrafts[brand.brandId] ?? ''}- onChange={(e) =>- setRecipientDrafts((prev) => ({ ...prev, [brand.brandId]: e.target.value }))- }+ onChange={(e) => {+ setRecipientDrafts((prev) => ({ ...prev, [brand.brandId]: e.target.value }));+ setInvalidRecipients((prev) => ({ ...prev, [brand.brandId]: [] }));+ }}placeholder={t('pulseRecipientsPlaceholder')}disabled={!canManage}+ aria-invalid={invalidRecipients[brand.brandId]?.length ? true : undefined}/>- <p className="text-xs text-muted-foreground">{t('pulseRecipientsHint')}</p>+ {invalidRecipients[brand.brandId]?.length ? (+ <p className="text-xs text-destructive">+ {t('pulseRecipientsInvalid', {+ emails: invalidRecipients[brand.brandId].join(', '),+ })}+ </p>+ ) : (+ <p className="text-xs text-muted-foreground">{t('pulseRecipientsHint')}</p>+ )}</div>{canManage && (<Buttondiff --git a/web/src/lib/pulse-recipients.test.ts b/web/src/lib/pulse-recipients.test.tsnew file mode 100644index 000000000..badb8ec52--- /dev/null+++ b/web/src/lib/pulse-recipients.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { parseRecipients } from './pulse-recipients';++describe('parseRecipients', () => {+ it('keeps valid addresses, trimmed', () => {+ expect(parseRecipients([' [email protected]', '[email protected] '])).toEqual({+ valid: ['[email protected]', '[email protected]'],+ invalid: [],+ });+ });++ it('returns invalid addresses instead of dropping them', () => {+ expect(parseRecipients(['[email protected]', 'team@example', 'no-at-sign'])).toEqual({+ valid: ['[email protected]'],+ invalid: ['team@example', 'no-at-sign'],+ });+ });++ it('reports an all-invalid list as invalid, not as empty', () => {+ expect(parseRecipients(['team@example'])).toEqual({ valid: [], invalid: ['team@example'] });+ });++ it('ignores blank entries and non-strings', () => {+ expect(parseRecipients(['', ' ', 42, null, '[email protected]'])).toEqual({+ valid: ['[email protected]'],+ invalid: [],+ });+ });++ it('treats an empty list as empty', () => {+ expect(parseRecipients([])).toEqual({ valid: [], invalid: [] });+ });+});diff --git a/web/src/lib/pulse-recipients.ts b/web/src/lib/pulse-recipients.tsnew file mode 100644index 000000000..ce824bae8--- /dev/null+++ b/web/src/lib/pulse-recipients.ts@@ -0,0 +1,22 @@+/**+ * Daily Pulse recipient validation (#921), shared by the settings form and+ * PUT /api/settings/pulse so both reject the same addresses.+ *+ * Invalid entries are returned rather than dropped: an empty stored list+ * means "every organization member", so silently discarding a mistyped+ * address would widen the audience instead of failing the save.+ */++const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;++export function parseRecipients(input: unknown[]): { valid: string[]; invalid: string[] } {+ const valid: string[] = [];+ const invalid: string[] = [];+ for (const entry of input) {+ if (typeof entry !== 'string') continue;+ const email = entry.trim();+ if (!email) continue;+ (EMAIL.test(email) ? valid : invalid).push(email);+ }+ return { valid, invalid };+}