Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

🔒️ Add content moderation docs (#2196)

Luke Vella8679bb5b19bf
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index b237bc68c..4ea231ecb 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -32,7 +32,7 @@
},
{
"group": "Guides",
- "pages": ["guide/participant-guide"]
+ "pages": ["guide/participant-guide", "guide/content-moderation"]
},
{
"group": "Contact",
diff --git a/apps/docs/guide/content-moderation.mdx b/apps/docs/guide/content-moderation.mdx
new file mode 100644
index 000000000..0fc6367eb
--- /dev/null
+++ b/apps/docs/guide/content-moderation.mdx
@@ -0,0 +1,19 @@
+---
+icon: shield-check
+title: Content Moderation
+description: Learn about what content is allowed when creating polls on Rallly
+---
+
+Rallly uses automated content moderation to keep the platform safe for all users. When you create or update a poll, the content is checked against our content policy.
+
+Content that is not related to scheduling or that violates our policies will be flagged and the poll will not be created or updated.
+
+## What happens if my content is flagged?
+
+If your content is flagged, you will see an error message. You can edit your content and try again.
+
+Repeated violations may result in your account being suspended.
+
+## My content was flagged by mistake
+
+If you believe your content was incorrectly flagged, please [contact support](/contact/support) and we'll review your case.
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 1cbc11a3f..12c1ea723 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -66,7 +66,6 @@
"sendFeedback": "Send Feedback",
"specifyTimes": "Specify times",
"specifyTimesDescription": "Include start and end times for each option",
- "stepSummary": "Step {current} of {total}",
"submit": "Submit",
"timeFormat": "Time format",
"timeZone": "Time zone",
@@ -254,10 +253,6 @@
"sendFeedbackSuccess": "Thank you for your feedback!",
"searchEventsPlaceholder": "Search events by title...",
"canceled": "Canceled",
- "tomorrow": "Tomorrow",
- "yesterday": "Yesterday",
- "lastWeek": "Last Week",
- "unconfirmed": "Unconfirmed",
"upcomingEventsEmptyStateTitle": "No Upcoming Events",
"upcomingEventsEmptyStateDescription": "When you schedule events, they will appear here.",
"pastEventsEmptyStateTitle": "No Past Events",
@@ -607,5 +602,7 @@
"deleteMenuItem": "Delete",
"deletePollPrompt": "Are you sure you want to delete <b>{title}</b>?",
"pollDeleted": "Poll deleted",
- "pollDeleteError": "Failed to delete poll"
+ "pollDeleteError": "Failed to delete poll",
+ "inappropriateContent": "Inappropriate content",
+ "pollReopened": "Poll Reopened"
}
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-details/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-details/page.tsx
index 4388216e8..e780c851d 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-details/page.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-details/page.tsx
@@ -46,7 +46,13 @@ const Page = () => {
//submit
updatePollMutation(
{ urlId, ...data },
- { onSuccess: redirectBackToPoll },
+ {
+ onSuccess: (res) => {
+ if (res.ok) {
+ redirectBackToPoll();
+ }
+ },
+ },
);
})}
>
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsx
index 21e168573..3bb6b67ca 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-options/page.tsx
@@ -108,7 +108,11 @@ const Page = () => {
optionsToAdd,
},
{
- onSuccess: redirectBackToPoll,
+ onSuccess: (res) => {
+ if (res.ok) {
+ redirectBackToPoll();
+ }
+ },
},
);
};
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsx
index bcc328291..c45f9e5c4 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/edit-settings/page.tsx
@@ -38,12 +38,13 @@ const Page = () => {
<form
onSubmit={form.handleSubmit(async (data) => {
//submit
- await update.mutateAsync(
- { urlId: poll.adminUrlId, ...data },
- {
- onSuccess: redirectBackToPoll,
- },
- );
+ const res = await update.mutateAsync({
+ urlId: poll.adminUrlId,
+ ...data,
+ });
+ if (res.ok) {
+ redirectBackToPoll();
+ }
})}
>
<PollSettingsForm>
diff --git a/apps/web/src/components/create-poll.tsx b/apps/web/src/components/create-poll.tsx
index e652d1c5b..1dc526a0f 100644
--- a/apps/web/src/components/create-poll.tsx
+++ b/apps/web/src/components/create-poll.tsx
@@ -16,7 +16,7 @@ import useFormPersist from "react-hook-form-persist";
import { useUnmount } from "react-use";
import { PollSettingsForm } from "@/components/forms/poll-settings";
import { useUser } from "@/components/user-provider";
-import { Trans } from "@/i18n/client";
+import { Trans, useTranslation } from "@/i18n/client";
import { trpc } from "@/trpc/client";
import type { NewEventData } from "./forms";
import { PollDetailsForm, PollOptionsForm } from "./forms";
@@ -38,6 +38,7 @@ export interface CreatePollPageProps {
export const CreatePoll: React.FunctionComponent = () => {
const router = useRouter();
+ const { t } = useTranslation();
const { createGuestIfNeeded } = useUser();
const form = useForm<NewEventData>({
defaultValues: {
@@ -60,14 +61,7 @@ export const CreatePoll: React.FunctionComponent = () => {
useUnmount(clear);
- const createPoll = trpc.polls.create.useMutation({
- networkMode: "always",
- onError: (error) => {
- if (error.data?.code === "BAD_REQUEST") {
- toast.error(error.message);
- }
- },
- });
+ const makePoll = trpc.polls.make.useMutation();
return (
<Form {...form}>
@@ -75,27 +69,41 @@ export const CreatePoll: React.FunctionComponent = () => {
onSubmit={form.handleSubmit(async (formData) => {
const title = required(formData?.title.trim());
await createGuestIfNeeded();
- await createPoll.mutateAsync(
- {
- title: title,
- location: formData?.location?.trim(),
- description: formData?.description?.trim(),
- timeZone: formData?.timeZone,
- hideParticipants: formData?.hideParticipants,
- disableComments: formData?.disableComments,
- hideScores: formData?.hideScores,
- requireParticipantEmail: formData?.requireParticipantEmail,
- options: required(formData?.options).map((option) => ({
- startDate: option.type === "date" ? option.date : option.start,
- endDate: option.type === "timeSlot" ? option.end : undefined,
- })),
- },
- {
- onSuccess: (res) => {
- router.push(`/poll/${res.id}`);
+ const res = await makePoll.mutateAsync({
+ title: title,
+ location: formData?.location?.trim(),
+ description: formData?.description?.trim(),
+ timeZone: formData?.timeZone,
+ hideParticipants: formData?.hideParticipants,
+ disableComments: formData?.disableComments,
+ hideScores: formData?.hideScores,
+ requireParticipantEmail: formData?.requireParticipantEmail,
+ options: required(formData?.options).map((option) => ({
+ startDate: option.type === "date" ? option.date : option.start,
+ endDate: option.type === "timeSlot" ? option.end : undefined,
+ })),
+ });
+
+ if (res.ok) {
+ router.push(`/poll/${res.data.id}`);
+ } else {
+ toast.error(
+ t("inappropriateContent", {
+ defaultValue: "Inappropriate content",
+ }),
+ {
+ action: {
+ label: t("learnMore", { defaultValue: "Learn more" }),
+ onClick: () => {
+ window.open(
+ "https://support.rallly.co/guide/content-moderation",
+ "_blank",
+ );
+ },
+ },
},
- },
- );
+ );
+ }
})}
>
<div className="space-y-4">
@@ -121,7 +129,7 @@ export const CreatePoll: React.FunctionComponent = () => {
<PollSettingsForm />
<hr />
<Button
- loading={form.formState.isSubmitting || createPoll.isSuccess}
+ loading={form.formState.isSubmitting}
size="lg"
type="submit"
className="w-full"
diff --git a/apps/web/src/components/poll/mutations.ts b/apps/web/src/components/poll/mutations.ts
index 63a1066f5..378a462fa 100644
--- a/apps/web/src/components/poll/mutations.ts
+++ b/apps/web/src/components/poll/mutations.ts
@@ -1,6 +1,7 @@
import { toast } from "@rallly/ui/sonner";
import { useSearchParams } from "next/navigation";
import { usePoll } from "@/components/poll-context";
+import { useTranslation } from "@/i18n/client";
import { trpc } from "@/trpc/client";
import type { ParticipantForm } from "./types";
@@ -63,10 +64,24 @@ export const useDeleteParticipantMutation = () => {
};
export const useUpdatePollMutation = () => {
- return trpc.polls.update.useMutation({
- onError: (error) => {
- if (error.data?.code === "BAD_REQUEST") {
- toast.error(error.message);
+ const { t } = useTranslation();
+ return trpc.polls.modify.useMutation({
+ onSuccess: (data) => {
+ if (!data.ok) {
+ toast.error(
+ t("inappropriateContent", { defaultValue: "Inappropriate content" }),
+ {
+ action: {
+ label: t("learnMore", { defaultValue: "Learn more" }),
+ onClick: () => {
+ window.open(
+ "https://support.rallly.co/guide/content-moderation",
+ "_blank",
+ );
+ },
+ },
+ },
+ );
}
},
});
diff --git a/apps/web/src/features/moderation/index.ts b/apps/web/src/features/moderation/index.ts
index 8524a4dd6..fa624f2dc 100644
--- a/apps/web/src/features/moderation/index.ts
+++ b/apps/web/src/features/moderation/index.ts
@@ -1,6 +1,7 @@
import { createLogger } from "@rallly/logger";
+import { waitUntil } from "@vercel/functions";
import { env } from "@/env";
-
+import { getEmailClient } from "@/utils/emails";
import { moderateContentWithAI } from "./libs/ai-moderation";
import { containsSuspiciousPatterns } from "./libs/pattern-moderation";
@@ -15,7 +16,13 @@ const logger = createLogger("moderation");
* @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
*/
-export async function moderateContent(content: Array<string | undefined>) {
+export async function moderateContent({
+ userId,
+ content,
+}: {
+ userId: string;
+ content: Array<string | undefined>;
+}) {
// Skip moderation if the feature is disabled in environment
if (env.MODERATION_ENABLED !== "true") {
return false;
@@ -40,7 +47,19 @@ export async function moderateContent(content: Array<string | undefined>) {
try {
const isFlagged = await moderateContentWithAI(textToModerate);
if (isFlagged) {
- logger.warn("Content flagged by AI moderation");
+ logger.warn({ userId }, "Content flagged by AI moderation");
+ const emailClient = await getEmailClient();
+ waitUntil(
+ emailClient.sendEmail({
+ to: env.SUPPORT_EMAIL,
+ subject: "Content flagged by moderation",
+ text: [
+ `User ID: ${userId}`,
+ "Flagged content:",
+ textToModerate,
+ ].join("\n\n"),
+ }),
+ );
}
return isFlagged;
} catch (error) {
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index 304447a0f..edcdefeef 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -165,7 +165,381 @@ export const polls = router({
};
}),
+ make: possiblyPublicProcedure
+ .input(
+ z.object({
+ title: z.string().trim().min(1),
+ timeZone: z.string().optional(),
+ location: z.string().trim().optional(),
+ description: z.string().trim().optional(),
+ hideParticipants: z.boolean().optional(),
+ hideScores: z.boolean().optional(),
+ disableComments: z.boolean().optional(),
+ requireParticipantEmail: z.boolean().optional(),
+ options: z
+ .object({
+ startDate: z.string(),
+ endDate: z.string().optional(),
+ })
+ .array(),
+ }),
+ )
+ .use(requireUserMiddleware)
+ .use(createRateLimitMiddleware("create_poll", 20, "1 h"))
+ .mutation(async ({ ctx, input }) => {
+ const isFlaggedContent = await moderateContent({
+ userId: ctx.user.id,
+ content: [input.title, input.description, input.location],
+ });
+
+ if (isFlaggedContent) {
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "flagged_content",
+ properties: {
+ action: "create_poll",
+ },
+ });
+ return {
+ ok: false as const,
+ error: { code: "INAPPROPRIATE_CONTENT" as const },
+ };
+ }
+
+ const title = input.title;
+ const location = input.location || undefined;
+ const description = input.description || undefined;
+ const adminToken = nanoid();
+ const participantUrlId = nanoid();
+ const pollId = nanoid();
+ let spaceId: string | undefined;
+
+ if (!ctx.user.isGuest) {
+ const data = await getCurrentUserSpace();
+ if (!data) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Space not found",
+ });
+ }
+ spaceId = data.space.id;
+ }
+
+ const poll = await prisma.poll.create({
+ include: {
+ options: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ data: {
+ id: pollId,
+ title,
+ timeZone: input.timeZone,
+ location,
+ description,
+ adminUrlId: adminToken,
+ participantUrlId,
+ ...(ctx.user.isLegacyGuest
+ ? { guestId: ctx.user.id }
+ : { userId: ctx.user.id }),
+ watchers: !ctx.user.isGuest
+ ? {
+ create: {
+ userId: ctx.user.id,
+ },
+ }
+ : undefined,
+ options: {
+ createMany: {
+ data: input.options.map((option) => ({
+ startTime: input.timeZone
+ ? dayjs(option.startDate).tz(input.timeZone, true).toDate()
+ : dayjs(option.startDate).utc(true).toDate(),
+ duration: option.endDate
+ ? dayjs(option.endDate).diff(
+ dayjs(option.startDate),
+ "minute",
+ )
+ : 0,
+ })),
+ },
+ },
+ hideParticipants: input.hideParticipants,
+ disableComments: input.disableComments,
+ hideScores: input.hideScores,
+ requireParticipantEmail: input.requireParticipantEmail,
+ spaceId,
+ },
+ });
+
+ const pollLink = absoluteUrl(`/poll/${pollId}`);
+
+ const participantLink = shortUrl(`/invite/${pollId}`);
+
+ if (ctx.user.isGuest === false) {
+ const user = await prisma.user.findUnique({
+ select: { email: true, name: true },
+ where: { id: ctx.user.id },
+ });
+
+ if (user) {
+ const emailClient = await getEmailClient(
+ ctx.user.locale ?? undefined,
+ );
+ emailClient.queueTemplate("NewPollEmail", {
+ to: user.email,
+ props: {
+ title: poll.title,
+ name: user.name,
+ adminLink: pollLink,
+ participantLink,
+ },
+ });
+ }
+ }
+
+ ctx.posthog?.groupIdentify({
+ groupType: "poll",
+ groupKey: poll.id,
+ properties: {
+ name: poll.title,
+ status: poll.status,
+ is_guest: ctx.user.isGuest,
+ created_at: poll.createdAt,
+ participant_count: 0,
+ comment_count: 0,
+ option_count: poll.options.length,
+ has_location: !!location,
+ has_description: !!description,
+ timezone: input.timeZone,
+ },
+ });
+
+ ctx.posthog?.capture({
+ event: "poll_create",
+ distinctId: ctx.user.id,
+ properties: {
+ title: poll.title,
+ optionCount: poll.options.length,
+ hasLocation: !!location,
+ hasDescription: !!description,
+ timezone: input.timeZone,
+ disableComments: poll.disableComments,
+ hideParticipants: poll.hideParticipants,
+ hideScores: poll.hideScores,
+ requireParticipantEmail: poll.requireParticipantEmail,
+ isGuest: ctx.user.isGuest,
+ },
+ groups: {
+ poll: poll.id,
+ ...(poll.spaceId ? { space: poll.spaceId } : {}),
+ },
+ });
+
+ revalidatePath("/", "layout");
+
+ return { ok: true as const, data: { id: poll.id } };
+ }),
+ modify: possiblyPublicProcedure
+ .input(
+ z.object({
+ urlId: z.string(),
+ title: z.string().trim().optional(),
+ timeZone: z.string().optional(),
+ location: z.string().trim().optional(),
+ description: z.string().trim().optional(),
+ optionsToDelete: z.string().array().optional(),
+ optionsToAdd: z.string().array().optional(),
+ hideParticipants: z.boolean().optional(),
+ disableComments: z.boolean().optional(),
+ hideScores: z.boolean().optional(),
+ requireParticipantEmail: z.boolean().optional(),
+ }),
+ )
+ .use(requireUserMiddleware)
+ .use(createRateLimitMiddleware("update_poll", 10, "1 m"))
+ .mutation(async ({ input, ctx }) => {
+ const pollId = await getPollIdFromAdminUrlId(input.urlId);
+
+ if (!(await hasPollAdminAccess(pollId, ctx.user.id))) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to update this poll",
+ });
+ }
+
+ const isFlaggedContent = await moderateContent({
+ userId: ctx.user.id,
+ content: [input.title, input.description, input.location],
+ });
+
+ if (isFlaggedContent) {
+ ctx.posthog?.capture({
+ distinctId: ctx.user.id,
+ event: "flagged_content",
+ properties: {
+ action: "update_poll",
+ },
+ });
+ return {
+ ok: false as const,
+ error: { code: "INAPPROPRIATE_CONTENT" as const },
+ };
+ }
+
+ await prisma.$transaction(async (tx) => {
+ if (input.optionsToDelete && input.optionsToDelete.length > 0) {
+ await tx.option.deleteMany({
+ where: {
+ pollId,
+ id: {
+ in: input.optionsToDelete,
+ },
+ },
+ });
+ }
+
+ if (input.optionsToAdd && input.optionsToAdd.length > 0) {
+ await tx.option.createMany({
+ data: input.optionsToAdd.map((optionValue) => {
+ const [start, end] = optionValue.split("/");
+
+ if (end) {
+ return {
+ startTime: input.timeZone
+ ? dayjs(start).tz(input.timeZone, true).toDate()
+ : dayjs(start).utc(true).toDate(),
+ duration: dayjs(end).diff(dayjs(start), "minute"),
+ pollId,
+ };
+ } else {
+ return {
+ startTime: dayjs(start).utc(true).toDate(),
+ pollId,
+ };
+ }
+ }),
+ });
+ }
+ });
+
+ await prisma.poll.update({
+ select: { id: true },
+ where: {
+ id: pollId,
+ },
+ data: {
+ title: input.title,
+ location: input.location,
+ description: input.description,
+ timeZone: input.timeZone,
+ hideScores: input.hideScores,
+ hideParticipants: input.hideParticipants,
+ disableComments: input.disableComments,
+ requireParticipantEmail: input.requireParticipantEmail,
+ },
+ });
+
+ // Get updated poll data for group update
+ const updatedPoll = await prisma.poll.findUnique({
+ where: { id: pollId },
+ select: {
+ title: true,
+ status: true,
+ createdAt: true,
+ location: true,
+ description: true,
+ disableComments: true,
+ requireParticipantEmail: true,
+ hideParticipants: true,
+ hideScores: true,
+ timeZone: true,
+ _count: {
+ select: {
+ participants: {
+ where: { deleted: false },
+ },
+ comments: true,
+ options: true,
+ },
+ },
+ },
+ });
+
+ if (!updatedPoll) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ });
+ }
+
+ // Track specific poll update events based on what was changed
+ const hasDetailsUpdate =
+ input.title !== undefined ||
+ input.location !== undefined ||
+ input.description !== undefined;
+ const hasOptionsUpdate =
+ (input.optionsToDelete && input.optionsToDelete.length > 0) ||
+ (input.optionsToAdd && input.optionsToAdd.length > 0);
+ const hasSettingsUpdate =
+ input.timeZone !== undefined ||
+ input.hideParticipants !== undefined ||
+ input.disableComments !== undefined ||
+ input.hideScores !== undefined ||
+ input.requireParticipantEmail !== undefined;
+
+ if (hasDetailsUpdate) {
+ ctx.posthog?.capture({
+ event: "poll_update_details",
+ distinctId: ctx.user.id,
+ properties: {
+ title: updatedPoll.title,
+ has_location: !!updatedPoll.location,
+ has_description: !!updatedPoll.description,
+ is_guest: ctx.user.isGuest,
+ },
+ groups: {
+ poll: pollId,
+ },
+ });
+ }
+
+ if (hasOptionsUpdate) {
+ ctx.posthog?.capture({
+ event: "poll_update_options",
+ distinctId: ctx.user.id,
+ properties: {
+ option_count: updatedPoll._count.options,
+ },
+ groups: {
+ poll: pollId,
+ },
+ });
+ }
+
+ if (hasSettingsUpdate) {
+ ctx.posthog?.capture({
+ event: "poll_update_settings",
+ distinctId: ctx.user.id,
+ properties: {
+ disable_comments: !!updatedPoll.disableComments,
+ hide_participants: !!updatedPoll.hideParticipants,
+ hide_scores: !!updatedPoll.hideScores,
+ require_participant_email: !!updatedPoll.requireParticipantEmail,
+ },
+ groups: {
+ poll: pollId,
+ },
+ });
+ }
+
+ revalidatePath("/", "layout");
+
+ return { ok: true as const };
+ }),
// START LEGACY ROUTES
+ /** @deprecated Use make instead */
create: possiblyPublicProcedure
.input(
z.object({
@@ -188,11 +562,10 @@ export const polls = router({
.use(requireUserMiddleware)
.use(createRateLimitMiddleware("create_poll", 20, "1 h"))
.use(async ({ ctx, input, next }) => {
- const isFlaggedContent = await moderateContent([
- input.title,
- input.description,
- input.location,
- ]);
+ const isFlaggedContent = await moderateContent({
+ userId: ctx.user.id,
+ content: [input.title, input.description, input.location],
+ });
if (isFlaggedContent) {
ctx.posthog?.capture({
@@ -331,7 +704,7 @@ export const polls = router({
hasLocation: !!location,
hasDescription: !!description,
timezone: input.timeZone,
- disableCommnets: poll.disableComments,
+ disableComments: poll.disableComments,
hideParticipants: poll.hideParticipants,
hideScores: poll.hideScores,
requireParticipantEmail: poll.requireParticipantEmail,
@@ -347,6 +720,7 @@ export const polls = router({
return { id: poll.id };
}),
+ /** @deprecated Use modify instead */
update: possiblyPublicProcedure
.input(
z.object({
@@ -366,11 +740,10 @@ export const polls = router({
.use(requireUserMiddleware)
.use(createRateLimitMiddleware("update_poll", 10, "1 m"))
.use(async ({ ctx, input, next }) => {
- const isFlaggedContent = await moderateContent([
- input.title,
- input.description,
- input.location,
- ]);
+ const isFlaggedContent = await moderateContent({
+ userId: ctx.user.id,
+ content: [input.title, input.description, input.location],
+ });
if (isFlaggedContent) {
ctx.posthog?.capture({