Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🔒️ Updates to AI moderation (#2197)
Luke Vella4b5416c54dda
diff --git a/apps/web/src/features/moderation/index.ts b/apps/web/src/features/moderation/index.tsindex fa624f2dc..37acb8633 100644--- a/apps/web/src/features/moderation/index.ts+++ b/apps/web/src/features/moderation/index.ts@@ -2,19 +2,21 @@ import { createLogger } from "@rallly/logger";import { waitUntil } from "@vercel/functions";import { env } from "@/env";import { getEmailClient } from "@/utils/emails";+import type { ModerationVerdict } from "./libs/ai-moderation";import { moderateContentWithAI } from "./libs/ai-moderation";import { containsSuspiciousPatterns } from "./libs/pattern-moderation";const logger = createLogger("moderation");+export type { ModerationVerdict };+/*** Moderates content to detect spam, inappropriate content, or abuse* Uses a two-layer approach:* 1. Pattern-based detection for common spam patterns* 2. AI-based moderation for more sophisticated content analysis*- * @param content Array of strings to moderate (can include undefined values which will be filtered out)- * @returns True if the content is flagged as inappropriate, false otherwise+ * @returns "flagged" (block), "suspicious" (allow but notify), or "safe" (allow)*/export async function moderateContent({userId,@@ -22,10 +24,10 @@ export async function moderateContent({}: {userId: string;content: Array<string | undefined>;-}) {+}): Promise<ModerationVerdict> {// Skip moderation if the feature is disabled in environmentif (env.MODERATION_ENABLED !== "true") {- return false;+ return "safe";}// Check if OpenAI API key is available@@ -33,7 +35,7 @@ export async function moderateContent({logger.warn("Content moderation is enabled but OPENAI_API_KEY is not set. AI-based moderation will be skipped.",);- return false;+ return "safe";}const textToModerate = content.filter(Boolean).join("\n");@@ -45,30 +47,33 @@ export async function moderateContent({if (hasSuspiciousPatterns) {logger.info("Suspicious patterns detected, performing AI moderation check");try {- const isFlagged = await moderateContentWithAI(textToModerate);- if (isFlagged) {- logger.warn({ userId }, "Content flagged by AI moderation");+ const verdict = await moderateContentWithAI(textToModerate);++ if (verdict === "flagged" || verdict === "suspicious") {+ logger.warn({ userId, verdict }, `Content ${verdict} by AI moderation`);const emailClient = await getEmailClient();waitUntil(emailClient.sendEmail({to: env.SUPPORT_EMAIL,- subject: "Content flagged by moderation",+ subject: `Content ${verdict} by moderation`,text: [`User ID: ${userId}`,- "Flagged content:",+ `Verdict: ${verdict}`,+ "Content:",textToModerate,].join("\n\n"),}),);}- return isFlagged;++ return verdict;} catch (error) {logger.error({ error }, "Error during AI content moderation");- return false;+ return "safe";}}- return false;+ return "safe";}/**diff --git a/apps/web/src/features/moderation/libs/ai-moderation.ts b/apps/web/src/features/moderation/libs/ai-moderation.tsindex d28dfaaa2..4fe895802 100644--- a/apps/web/src/features/moderation/libs/ai-moderation.ts+++ b/apps/web/src/features/moderation/libs/ai-moderation.ts@@ -4,40 +4,60 @@ import { generateText } from "ai";const logger = createLogger("moderation/ai");+export type ModerationVerdict = "flagged" | "suspicious" | "safe";+/**- * Moderates content using OpenAI's GPT-4 to detect inappropriate content+ * Moderates content using AI to detect inappropriate content* @param text The text to moderate- * @returns True if the content is flagged as inappropriate, false otherwise+ * @returns The moderation verdict: "flagged", "suspicious", or "safe"*/-export async function moderateContentWithAI(text: string) {+export async function moderateContentWithAI(+ text: string,+): Promise<ModerationVerdict> {try {const result = await generateText({- model: openai("gpt-4.1-nano"),+ model: openai("gpt-4.1-mini"),messages: [{role: "system",content: `You are a content moderator for a scheduling and polling application. Users create polls about any topic — finding meeting times, making group decisions, voting on proposals, etc. Content may be in any language.-Flag the content ONLY if it clearly matches one of these categories:-- Phishing or scams: fake account notifications, brand impersonation (e.g. Binance, Coinbase, PayPal), "your balance/funds/account" language, urgency tactics to click external links-- Financial fraud: fake crypto mining, investment scams, unclaimed funds, lottery winnings-- Illegal activities: drugs, prostitution, illegal gambling-- Malicious links: content whose primary purpose is to trick readers into clicking an external link unrelated to the poll-- Spam relay: content that is not a genuine poll but a mass marketing message, advertisement, or message blast using the platform as a delivery mechanism+Respond with one of three verdicts:+- FLAGGED: Content is clearly abusive and should be blocked. Use this for:+ - Phishing or scams: fake account notifications, brand impersonation (e.g. Binance, Coinbase, PayPal), "your balance/funds/account" language, urgency tactics to click external links+ - Financial fraud: fake crypto mining, investment scams, unclaimed funds, lottery winnings+ - Illegal activities: drugs, prostitution, illegal gambling+ - Malicious links: content whose primary purpose is to trick readers into clicking an external link unrelated to the poll+ - Spam relay: content that is not a genuine poll but a mass marketing message, advertisement, or message blast using the platform as a delivery mechanism++- SUSPICIOUS: Content is ambiguous — it could be legitimate but has characteristics that warrant human review. Use this when content doesn't clearly fit the FLAGGED categories but seems unusual for a polling app.++- SAFE: Content is clearly legitimate.-Do NOT flag content because it is in a non-English language, uses uppercase letters, is about a non-scheduling topic (e.g. votes, approvals, group decisions), or includes instructions for participants.+Do NOT flag or mark as suspicious content because it is in a non-English language, uses uppercase letters, is about a non-scheduling topic (e.g. votes, approvals, group decisions), or includes instructions for participants.-When in doubt, respond SAFE.+When in doubt between FLAGGED and SUSPICIOUS, choose SUSPICIOUS.+When in doubt between SUSPICIOUS and SAFE, choose SAFE.-Respond with only 'FLAGGED' or 'SAFE'.`,+Respond with only 'FLAGGED', 'SUSPICIOUS', or 'SAFE'.`,},{ role: "user", content: text },],});- return result.text.includes("FLAGGED");+ const response = result.text.trim().toUpperCase();++ if (response.includes("FLAGGED")) {+ return "flagged";+ }++ if (response.includes("SUSPICIOUS")) {+ return "suspicious";+ }++ return "safe";} catch (err) {logger.error({ error: err }, "AI moderation failed");- return false;+ return "safe";}}diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex edcdefeef..ff1812a1d 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -187,12 +187,12 @@ export const polls = router({.use(requireUserMiddleware).use(createRateLimitMiddleware("create_poll", 20, "1 h")).mutation(async ({ ctx, input }) => {- const isFlaggedContent = await moderateContent({+ const moderationVerdict = await moderateContent({userId: ctx.user.id,content: [input.title, input.description, input.location],});- if (isFlaggedContent) {+ if (moderationVerdict === "flagged") {ctx.posthog?.capture({distinctId: ctx.user.id,event: "flagged_content",@@ -370,12 +370,12 @@ export const polls = router({});}- const isFlaggedContent = await moderateContent({+ const moderationVerdict = await moderateContent({userId: ctx.user.id,content: [input.title, input.description, input.location],});- if (isFlaggedContent) {+ if (moderationVerdict === "flagged") {ctx.posthog?.capture({distinctId: ctx.user.id,event: "flagged_content",@@ -562,12 +562,12 @@ export const polls = router({.use(requireUserMiddleware).use(createRateLimitMiddleware("create_poll", 20, "1 h")).use(async ({ ctx, input, next }) => {- const isFlaggedContent = await moderateContent({+ const moderationVerdict = await moderateContent({userId: ctx.user.id,content: [input.title, input.description, input.location],});- if (isFlaggedContent) {+ if (moderationVerdict === "flagged") {ctx.posthog?.capture({distinctId: ctx.user.id,event: "flagged_content",@@ -740,12 +740,12 @@ export const polls = router({.use(requireUserMiddleware).use(createRateLimitMiddleware("update_poll", 10, "1 m")).use(async ({ ctx, input, next }) => {- const isFlaggedContent = await moderateContent({+ const moderationVerdict = await moderateContent({userId: ctx.user.id,content: [input.title, input.description, input.location],});- if (isFlaggedContent) {+ if (moderationVerdict === "flagged") {ctx.posthog?.capture({distinctId: ctx.user.id,event: "flagged_content",