Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Let the emailed links edit the response they name (#3188)
Luke Vella95e616364e9f
diff --git a/apps/web/src/app/[locale]/invite/[urlId]/page.tsx b/apps/web/src/app/[locale]/invite/[urlId]/page.tsxindex 430693ea3..1cfa5f19b 100644--- a/apps/web/src/app/[locale]/invite/[urlId]/page.tsx+++ b/apps/web/src/app/[locale]/invite/[urlId]/page.tsx@@ -8,12 +8,12 @@ import { SessionRefresher } from "@/components/session-refresher";import { loadFooterLinks } from "@/features/instance-settings/loaders";import { PermissionProvider } from "@/features/poll/client";import { InviteOpenRecorder } from "@/features/poll/invite/components/invite-open-recorder";+import { loadParticipantIdsByToken } from "@/features/poll/loaders";import { UserProvider } from "@/features/user/client";import { getLocale } from "@/i18n/server/get-locale";import { getSession } from "@/lib/auth";import { DeviceDateTimeProvider } from "@/lib/datetime/device";import { getDeviceDateTimeConfig } from "@/lib/datetime/server";-import { decryptToken } from "@/lib/session";import { createPublicSSRHelper } from "@/trpc/server/create-ssr-helper";import { InvitePageLoader } from "./invite-page-loader";import Providers from "./providers";@@ -42,7 +42,10 @@ const getPollMetadata = cache(async (urlId: string) => {export default async function Page(props: {params: Promise<{ urlId: string }>;- searchParams: Promise<{ token?: string; invite?: string }>;+ searchParams: Promise<{+ token?: string | string[];+ invite?: string | string[];+ }>;}) {const params = await props.params;@@ -50,32 +53,36 @@ export default async function Page(props: {const trpc = await createPublicSSRHelper();- const { token, invite: inviteToken } = await props.searchParams;-- const [locale, session, deviceDateTimeConfig, footerLinks] =- await Promise.all([- getLocale(),- getSession(),- getDeviceDateTimeConfig(),- loadFooterLinks(),- trpc.polls.get.prefetch({ urlId: params.urlId }),- trpc.polls.participants.list.prefetch({ pollId: params.urlId, token }),- trpc.polls.comments.list.prefetch({ pollId: params.urlId }),- ]);+ // `invite` is the param older invite emails carry; both name the same+ // token and the client reads them the same way. A repeated param arrives+ // as an array; only a single value is a token.+ const searchParams = await props.searchParams;+ const token = [searchParams.token, searchParams.invite].find(+ (value): value is string => typeof value === "string",+ );- let impersonatedUserId: string | null = null;- if (token) {- const res = await decryptToken<{ userId: string }>(token);- if (res) {- impersonatedUserId = res.userId;- }- }+ const [+ locale,+ session,+ deviceDateTimeConfig,+ footerLinks,+ linkedParticipantIds,+ ] = await Promise.all([+ getLocale(),+ getSession(),+ getDeviceDateTimeConfig(),+ loadFooterLinks(),+ token ? loadParticipantIdsByToken(params.urlId, token) : [],+ trpc.polls.get.prefetch({ urlId: params.urlId }),+ trpc.polls.participants.list.prefetch({ pollId: params.urlId, token }),+ trpc.polls.comments.list.prefetch({ pollId: params.urlId }),+ ]);return (<HydrationBoundary state={dehydrate(trpc.queryClient)}><SessionRefresher />- {inviteToken ? (- <InviteOpenRecorder pollId={params.urlId} token={inviteToken} />+ {token ? (+ <InviteOpenRecorder pollId={params.urlId} token={token} />) : null}<UserProvider user={session?.user ?? null}><DeviceDateTimeProvider@@ -84,7 +91,7 @@ export default async function Page(props: {timeFormat={deviceDateTimeConfig.timeFormat}><Providers>- <PermissionProvider impersonatedUserId={impersonatedUserId}>+ <PermissionProvider linkedParticipantIds={linkedParticipantIds}><InvitePageLoader footerLinks={footerLinks} /></PermissionProvider></Providers>diff --git a/apps/web/src/features/poll/client.tsx b/apps/web/src/features/poll/client.tsxindex a7b534696..e041de333 100644--- a/apps/web/src/features/poll/client.tsx+++ b/apps/web/src/features/poll/client.tsx@@ -20,21 +20,25 @@ export const useRole = () => {return pathname?.includes("/poll") ? "admin" : "participant";};+/**+ * Responses the emailed link in the URL may edit, resolved on the server+ * from the same token the tRPC routes check.+ */const PermissionsContext = React.createContext<{- impersonatedUserId: string | null;+ linkedParticipantIds: string[];}>({- impersonatedUserId: null,+ linkedParticipantIds: [],});export const PermissionProvider = ({children,- impersonatedUserId,+ linkedParticipantIds,}: {children: React.ReactNode;- impersonatedUserId: string | null;+ linkedParticipantIds: string[];}) => {return (- <PermissionsContext.Provider value={{ impersonatedUserId }}>+ <PermissionsContext.Provider value={{ linkedParticipantIds }}>{children}</PermissionsContext.Provider>);@@ -47,8 +51,6 @@ export const usePermissions = () => {const role = useRole();const { participants } = useParticipants();return {- isUser: (userId: string) =>- userId === user?.id || userId === context.impersonatedUserId,canAddNewParticipant: poll.status === "open",canEditParticipant: (participantId: string) => {if (poll.status !== "open") {@@ -67,15 +69,10 @@ export const usePermissions = () => {return false;}- if (- participant.userId === user?.id ||- (context.impersonatedUserId &&- participant.userId === context.impersonatedUserId)- ) {- return true;- }-- return false;+ return (+ (!!user && participant.userId === user.id) ||+ context.linkedParticipantIds.includes(participantId)+ );},};};diff --git a/apps/web/src/features/poll/components/comments-sheet.tsx b/apps/web/src/features/poll/components/comments-sheet.tsxindex 5a04346a9..75e6b6119 100644--- a/apps/web/src/features/poll/components/comments-sheet.tsx+++ b/apps/web/src/features/poll/components/comments-sheet.tsx@@ -43,7 +43,6 @@ import {} from "@/components/empty-state";import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";import { usePoll, useRole } from "@/features/poll/client";-import { useEditToken } from "@/features/poll/components/mutations";import {Participant,ParticipantName,@@ -200,7 +199,6 @@ function CommentsSheetInner({ className }: { className?: string }) {const dialog = useDialog();const pollId = poll.id;- const token = useEditToken();const { data: comments } = trpc.polls.comments.list.useQuery({ pollId });@@ -342,7 +340,6 @@ function CommentsSheetInner({ className }: { className?: string }) {onClick={() => {deleteComment.mutate({commentId: comment.id,- token,});}}>diff --git a/apps/web/src/features/poll/components/mutations.ts b/apps/web/src/features/poll/components/mutations.tsindex 1f81e50b1..a60909e8a 100644--- a/apps/web/src/features/poll/components/mutations.ts+++ b/apps/web/src/features/poll/components/mutations.ts@@ -15,9 +15,13 @@ export const normalizeVotes = (}));};+/**+ * The token from an emailed link: a response's edit token, an invite token,+ * or a legacy seal. `invite` is the param older invite emails carry.+ */export const useEditToken = () => {const searchParams = useSearchParams();- return searchParams.get("token") ?? undefined;+ return searchParams.get("token") ?? searchParams.get("invite") ?? undefined;};export const useAddParticipantMutation = () => {diff --git a/apps/web/src/features/poll/components/new-participant-modal.tsx b/apps/web/src/features/poll/components/new-participant-modal.tsxindex 41b5c97c7..1c2057d6b 100644--- a/apps/web/src/features/poll/components/new-participant-modal.tsx+++ b/apps/web/src/features/poll/components/new-participant-modal.tsx@@ -25,13 +25,15 @@ import { Textarea } from "@rallly/ui/textarea";import { TRPCClientError } from "@trpc/client";import { CircleCheckIcon, PlusIcon } from "lucide-react";import Link from "next/link";-import { useSearchParams } from "next/navigation";import * as React from "react";import { useForm } from "react-hook-form";import * as z from "zod";import { IfCloudHosted } from "@/components/environment";import { usePoll } from "@/features/poll/client";-import { useAddParticipantMutation } from "@/features/poll/components/mutations";+import {+ useAddParticipantMutation,+ useEditToken,+} from "@/features/poll/components/mutations";import VoteIcon from "@/features/poll/components/vote-icon";import { MAX_RESPONSE_NOTE_LENGTH } from "@/features/poll/schema";import { useUser } from "@/features/user/client";@@ -175,9 +177,9 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {const noteLength = watch("note")?.length ?? 0;const [showNote, setShowNote] = React.useState(false);const addParticipant = useAddParticipantMutation();- // The emailed invite link carries the invitee token; joining the response- // to it lets the host see who has responded.- const inviteToken = useSearchParams()?.get("invite") ?? undefined;+ // An emailed invite link carries the invite token; the response takes it+ // over so the host sees who responded and the same link edits it later.+ const token = useEditToken();if (formState.isSubmitSuccessful) {return (@@ -271,7 +273,7 @@ export const NewParticipantForm = (props: NewParticipantModalProps) => {note: data.note,pollId: poll.id,timeZone,- inviteToken,+ token,});props.onSubmit?.(newParticipant);} catch (error) {diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.tsindex acb47d461..e248e2b30 100644--- a/apps/web/src/features/poll/data.ts+++ b/apps/web/src/features/poll/data.ts@@ -3,11 +3,13 @@ import "server-only";import type { PollStatus, Prisma } from "@rallly/database";import { prisma } from "@rallly/database";import { getInstancePolicy } from "@/features/instance-policy/data";+import { isLegacyEditToken } from "@/features/poll/utils";import { effectiveSpaceMemberWhere } from "@/features/space/member/utils";import type {AuthorizedSpaceId,SpaceContentScope,} from "@/features/space/types";+import { decryptToken } from "@/lib/session";export async function getPoll({pollId,@@ -456,3 +458,53 @@ export const hasPollAdminAccess = async (pollId: string, userId: string) => {return poll !== null;};++export async function getParticipant({+ participantId,+}: {+ participantId: string;+}) {+ return prisma.participant.findFirst({+ where: { id: participantId, deleted: false },+ select: { id: true, pollId: true, userId: true },+ });+}++/**+ * The responses an emailed link may edit. A response token names exactly one+ * row. A legacy seal names a guest user instead, so it resolves to that+ * user's responses in the poll that carry an email, the only rows such a+ * link was ever sent for.+ */+export async function listParticipantIdsByToken({+ pollId,+ token,+}: {+ pollId: string;+ token: string;+}) {+ if (isLegacyEditToken(token)) {+ const payload = await decryptToken<{ userId: string }>(token).catch(+ () => null,+ );+ if (!payload?.userId) {+ return [];+ }+ const participants = await prisma.participant.findMany({+ where: {+ pollId,+ userId: payload.userId,+ deleted: false,+ email: { not: null },+ },+ select: { id: true },+ });+ return participants.map((participant) => participant.id);+ }++ const participant = await prisma.participant.findFirst({+ where: { pollId, token, deleted: false },+ select: { id: true },+ });+ return participant ? [participant.id] : [];+}diff --git a/apps/web/src/features/poll/invite/utils.test.ts b/apps/web/src/features/poll/invite/utils.test.tsindex eee465b46..47d011c7c 100644--- a/apps/web/src/features/poll/invite/utils.test.ts+++ b/apps/web/src/features/poll/invite/utils.test.ts@@ -36,7 +36,7 @@ describe("derivePollInviteStatus", () => {describe("getPollInvitePath", () => {it("builds the per invitee path the email and the host copy share", () => {expect(getPollInvitePath({ pollId: "poll1", token: "AbC123" })).toBe(- "/invite/poll1?invite=AbC123",+ "/invite/poll1?token=AbC123",);});});diff --git a/apps/web/src/features/poll/invite/utils.ts b/apps/web/src/features/poll/invite/utils.tsindex 78af89901..be869e1bf 100644--- a/apps/web/src/features/poll/invite/utils.ts+++ b/apps/web/src/features/poll/invite/utils.ts@@ -20,7 +20,9 @@ export function derivePollInviteStatus(invite: {/*** The per invitee link, relative. Shared by the email and the host's copy- * action so the two can never point at different places.+ * action so the two can never point at different places. The same `token`+ * param carries a response's edit token: once the invitee responds their+ * response takes the invite's token, so this link keeps editing it.*/export function getPollInvitePath({pollId,@@ -29,5 +31,5 @@ export function getPollInvitePath({pollId: string;token: string;}) {- return `/invite/${pollId}?invite=${token}`;+ return `/invite/${pollId}?token=${token}`;}diff --git a/apps/web/src/features/poll/loaders.ts b/apps/web/src/features/poll/loaders.tsindex a10954457..bf754d042 100644--- a/apps/web/src/features/poll/loaders.ts+++ b/apps/web/src/features/poll/loaders.ts@@ -2,7 +2,11 @@ import "server-only";import { notFound } from "next/navigation";import { cache } from "react";-import { getPoll, getPollStatusCounts } from "@/features/poll/data";+import {+ getPoll,+ getPollStatusCounts,+ listParticipantIdsByToken,+} from "@/features/poll/data";import { getActiveSpaceContentScope } from "@/features/space/loaders";export const loadPollStatusCounts = cache(async () => {@@ -20,3 +24,12 @@ export const loadPoll = cache(async (pollId: string) => {return poll;});++/**+ * The token from the emailed link is its own proof of scope: no session is+ * consulted, so a forwarded link acts for the response it names.+ */+export const loadParticipantIdsByToken = cache(+ async (pollId: string, token: string) =>+ listParticipantIdsByToken({ pollId, token }),+);diff --git a/apps/web/src/features/poll/utils.ts b/apps/web/src/features/poll/utils.tsindex a41252917..a8b6a6b32 100644--- a/apps/web/src/features/poll/utils.ts+++ b/apps/web/src/features/poll/utils.ts@@ -6,3 +6,12 @@ export const generateAccessToken = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",32,);++/**+ * Confirmation emails sent before responses carried their own token linked+ * to an iron-session seal of the guest's user id. Seals are self describing,+ * so the branch is picked by prefix without a failed lookup.+ */+export function isLegacyEditToken(token: string) {+ return token.startsWith("Fe26.2*");+}diff --git a/apps/web/src/trpc/routers/auth.ts b/apps/web/src/trpc/routers/auth.tsindex 2ed455c14..fbc8e84b9 100644--- a/apps/web/src/trpc/routers/auth.ts+++ b/apps/web/src/trpc/routers/auth.ts@@ -1,22 +1,9 @@import { prisma } from "@rallly/database";import * as z from "zod";-import { decryptToken } from "@/lib/session";import { createRateLimitMiddleware, publicProcedure, router } from "../trpc";export const auth = router({- getUserPermission: publicProcedure- .input(z.object({ token: z.string() }))- .query(async ({ input }) => {- const res = await decryptToken<{ userId: string }>(input.token);-- if (!res) {- return null;- }-- return res;- }),-getLoginMethod: publicProcedure.input(z.object({ email: z.email() })).use(createRateLimitMiddleware("get_login_method", 10, "1 m"))diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.tsindex 1043d4de2..d4ea5e2e0 100644--- a/apps/web/src/trpc/routers/polls/comments.ts+++ b/apps/web/src/trpc/routers/polls/comments.ts@@ -21,7 +21,6 @@ import {requireUserMiddleware,router,} from "../../trpc";-import { resolveActor } from "./utils";const logger = createLogger("comments");@@ -200,14 +199,14 @@ export const comments = router({return newComment;}),delete: publicProcedure+ .use(requireUserMiddleware).input(z.object({commentId: z.string(),- token: z.string().optional(),}),)- .mutation(async ({ input: { commentId, token }, ctx }) => {- const actor = await resolveActor(token, ctx.user);+ .mutation(async ({ input: { commentId }, ctx }) => {+ const actor = ctx.user;const comment = await prisma.comment.findUnique({where: { id: commentId },diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.tsindex c6220940b..857eea708 100644--- a/apps/web/src/trpc/routers/polls/participants.ts+++ b/apps/web/src/trpc/routers/polls/participants.ts@@ -12,7 +12,10 @@ import { env } from "@/env";import { getNotificationRecipient } from "@/features/notifications/data";import { createUnsubscribeToken } from "@/features/notifications/utils";import { recordPollActivities } from "@/features/poll/activity/mutations";-import { hasPollAdminAccess } from "@/features/poll/data";+import {+ hasPollAdminAccess,+ listParticipantIdsByToken,+} from "@/features/poll/data";import {attachParticipantToInvite,findPendingPollInvite,@@ -27,11 +30,7 @@ import {router,} from "../../trpc";import { responseNoteInput } from "./schema";-import {- createParticipantEditToken,- resolveActor,- tryResolveUserId,-} from "./utils";+import { authorizeParticipantEdit } from "./utils";const logger = createLogger("participants");@@ -52,31 +51,6 @@ function createParticipantFullDTO(};}-async function canModifyParticipant(participantId: string, userId: string) {- const participant = await prisma.participant.findUnique({- where: { id: participantId },- select: { id: true, pollId: true, userId: true },- });-- if (!participant) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Participant not found",- });- }-- const isOwner = participant.userId === userId;-- if (!isOwner && !(await hasPollAdminAccess(participant.pollId, userId))) {- throw new TRPCError({- code: "FORBIDDEN",- message: "You are not allowed to modify this participant",- });- }-- return participant;-}-async function sendNewResponseNotificationEmail({pollId,pollTitle,@@ -186,18 +160,22 @@ export const participants = router({? await hasPollAdminAccess(pollId, ctx.user.id): false;- // Fall back to the edit token so a guest can still see their own- // response when opening the email link in a fresh browser.- const viewerId = isAdmin ? null : await tryResolveUserId(token, ctx.user);+ // The emailed link names the viewer's own response, so a guest still+ // sees it as theirs when opening the link in a fresh browser.+ const linkedIds = new Set(+ token && !isAdmin+ ? await listParticipantIdsByToken({ pollId, token })+ : [],+ );+ const isOwn = (participant: { id: string; userId: string | null }) =>+ linkedIds.has(participant.id) ||+ (!!ctx.user && participant.userId === ctx.user.id);// Response notes are visible to the host and their author only: strip// them from every other payload rather than hiding them in the UI.const participants = rawParticipants.map((participant) => {const dto = createParticipantFullDTO(participant);- if (- isAdmin ||- (participant.userId && participant.userId === viewerId)- ) {+ if (isAdmin || isOwn(participant)) {return dto;}return { ...dto, note: null };@@ -208,7 +186,7 @@ export const participants = router({if (poll.hideParticipants) {if (!isAdmin) {return participants.map((participant) => {- if (viewerId && participant.userId === viewerId) {+ if (isOwn(participant)) {return participant;}@@ -234,9 +212,11 @@ export const participants = router({}),).mutation(async ({ input: { participantId, token }, ctx }) => {- const actor = await resolveActor(token, ctx.user);-- const participant = await canModifyParticipant(participantId, actor.id);+ const { participant, actor } = await authorizeParticipantEdit({+ participantId,+ token,+ ctxUser: ctx.user,+ });await prisma.$transaction(async (tx) => {// Snapshot before the delete: the activity payload is the historical@@ -271,7 +251,7 @@ export const participants = router({{pollId: participant.pollId,type: "response_deleted",- userId: actor.id,+ userId: actor?.id,participantId,payload: {name: snapshot.name,@@ -286,15 +266,17 @@ export const participants = router({]);});- track(actor, {- event: "poll_response_delete",- properties: {- participant_id: participant.id,- },- groups: {- poll: participant.pollId,- },- });+ if (actor) {+ track(actor, {+ event: "poll_response_delete",+ properties: {+ participant_id: participant.id,+ },+ groups: {+ poll: participant.pollId,+ },+ });+ }}),add: publicProcedure.use(createRateLimitMiddleware("add_participant", 10, "1 h"))@@ -306,7 +288,7 @@ export const participants = router({email: z.string().optional(),note: responseNoteInput,timeZone: z.string().optional(),- inviteToken: z.string().optional(),+ token: z.string().optional(),votes: z.object({optionId: z.string(),@@ -318,7 +300,7 @@ export const participants = router({.mutation(async ({ctx,- input: { pollId, votes, name, email, note, timeZone, inviteToken },+ input: { pollId, votes, name, email, note, timeZone, token },}) => {const participantCount = await prisma.participant.count({where: {@@ -353,13 +335,14 @@ export const participants = router({existingOptionIds.has(optionId),);- const { participant, viaInvite } = await prisma.$transaction(+ const { participant, editToken, viaInvite } = await prisma.$transaction(async (tx) => {// A response answering an emailed invite takes the invite's// token, so the link the invitee already holds names it.- const invite = inviteToken- ? await findPendingPollInvite(tx, { pollId, token: inviteToken })+ const invite = token+ ? await findPendingPollInvite(tx, { pollId, token }): null;+ const editToken = invite?.token ?? generateAccessToken();const participant = await tx.participant.create({data: {@@ -368,7 +351,7 @@ export const participants = router({email,note,timeZone,- token: invite?.token ?? generateAccessToken(),+ token: editToken,userId: ctx.user.id,locale: ctx.locale,votes: {@@ -429,15 +412,13 @@ export const participants = router({});}- return { participant, viaInvite: invite !== null };+ return { participant, editToken, viaInvite: invite !== null };},);const totalResponses = participantCount + 1;if (email) {- const token = await createParticipantEditToken(ctx.user.id);-const space = participant.poll.space;after(async () =>@@ -450,7 +431,7 @@ export const participants = router({props: {title: participant.poll.title,editSubmissionUrl: absoluteUrl(- `/invite/${participant.poll.id}?token=${token}`,+ `/invite/${participant.poll.id}?token=${editToken}`,),},}),@@ -500,9 +481,11 @@ export const participants = router({}),).mutation(async ({ input: { participantId, newName, token }, ctx }) => {- const { id: userId } = await resolveActor(token, ctx.user);-- const participant = await canModifyParticipant(participantId, userId);+ const { participant, actor } = await authorizeParticipantEdit({+ participantId,+ token,+ ctxUser: ctx.user,+ });await prisma.$transaction(async (tx) => {await tx.participant.update({@@ -519,7 +502,7 @@ export const participants = router({{pollId: participant.pollId,type: "response_updated",- userId,+ userId: actor?.id,participantId,payload: { name: newName },},@@ -541,12 +524,12 @@ export const participants = router({}),).mutation(async ({ input: { participantId, votes, token }, ctx }) => {- const actor = await resolveActor(token, ctx.user);-- const existingParticipant = await canModifyParticipant(- participantId,- actor.id,- );+ const { participant: existingParticipant, actor } =+ await authorizeParticipantEdit({+ participantId,+ token,+ ctxUser: ctx.user,+ });const pollId = existingParticipant.pollId;@@ -610,7 +593,7 @@ export const participants = router({{pollId,type: "response_updated",- userId: actor.id,+ userId: actor?.id,participantId,payload: { name: updatedParticipant.name },},@@ -619,12 +602,14 @@ export const participants = router({return updatedParticipant;});- track(actor, {- event: "poll_response_update",- groups: {- poll: pollId,- },- });+ if (actor) {+ track(actor, {+ event: "poll_response_update",+ groups: {+ poll: pollId,+ },+ });+ }return createParticipantFullDTO(participant);}),diff --git a/apps/web/src/trpc/routers/polls/utils.ts b/apps/web/src/trpc/routers/polls/utils.tsindex a20e6cdb2..8bed5c173 100644--- a/apps/web/src/trpc/routers/polls/utils.ts+++ b/apps/web/src/trpc/routers/polls/utils.ts@@ -1,70 +1,62 @@import { TRPCError } from "@trpc/server";-import { createToken, decryptToken } from "@/lib/session";--export async function getUserIdFromToken(- token: string | undefined,-): Promise<string | null> {- if (!token) {- return null;- }-- const payload = await decryptToken<{ userId: string }>(token);- return payload?.userId ?? null;-}--export async function createParticipantEditToken(- userId: string,-): Promise<string> {- return await createToken(- { userId },- {- ttl: 0, // basically forever- },- );-}--export async function tryResolveUserId(- token: string | undefined,- ctxUser: { id: string } | undefined,-): Promise<string | null> {- const userIdFromToken = await getUserIdFromToken(token);- return userIdFromToken ?? ctxUser?.id ?? null;-}+import {+ getParticipant,+ hasPollAdminAccess,+ listParticipantIdsByToken,+} from "@/features/poll/data";type Actor = { id: string; isGuest: boolean };/**- * Resolve the acting user along with whether they should be treated as a guest- * for analytics (person-processing) purposes.+ * Proves the caller may edit a response. Two proofs are accepted: the token+ * from the emailed link, which names the response itself, and a session that+ * owns the response or administers its poll. Admin access is bound to the+ * session only, so a link never unlocks other people's responses.*- * Participant/comment edit tokens are only ever issued to guest participants,- * so a token-resolved actor is treated as a guest. A signed-in real user always- * acts through their session (`ctxUser`), never a token.+ * The returned actor is for attribution (activity log, analytics): the+ * session when there is one, otherwise the user the response was created+ * under, who was a guest at the time.*/-export async function tryResolveActor(- token: string | undefined,- ctxUser: Actor | undefined,-): Promise<Actor | null> {- const userIdFromToken = await getUserIdFromToken(token);- if (userIdFromToken) {- return { id: userIdFromToken, isGuest: true };- }- if (ctxUser) {- return { id: ctxUser.id, isGuest: ctxUser.isGuest };+export async function authorizeParticipantEdit({+ participantId,+ token,+ ctxUser,+}: {+ participantId: string;+ token: string | undefined;+ ctxUser: Actor | undefined;+}) {+ const participant = await getParticipant({ participantId });++ if (!participant) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Participant not found",+ });}- return null;-}-export async function resolveActor(- token: string | undefined,- ctxUser: Actor | undefined,-): Promise<Actor> {- const actor = await tryResolveActor(token, ctxUser);- if (!actor) {+ const ownedBySession = ctxUser+ ? participant.userId === ctxUser.id ||+ (await hasPollAdminAccess(participant.pollId, ctxUser.id))+ : false;++ const ownedByLink =+ !ownedBySession && token+ ? (+ await listParticipantIdsByToken({ pollId: participant.pollId, token })+ ).includes(participant.id)+ : false;++ if (!ownedBySession && !ownedByLink) {throw new TRPCError({- code: "UNAUTHORIZED",- message: "This method requires a user or valid token",+ code: "FORBIDDEN",+ message: "You are not allowed to modify this participant",});}- return actor;++ const actor: Actor | null =+ ctxUser ??+ (participant.userId ? { id: participant.userId, isGuest: true } : null);++ return { participant, actor };}diff --git a/apps/web/tests/email-invites.spec.ts b/apps/web/tests/email-invites.spec.tsindex ab8a7301b..a7b6b3f1c 100644--- a/apps/web/tests/email-invites.spec.ts+++ b/apps/web/tests/email-invites.spec.ts@@ -13,7 +13,8 @@ import {/*** The Share dialog sends one email invite per submit and lists every invite- * with its status. Free hosts see the pay wall instead of sending.+ * with its status. Free hosts see the pay wall instead of sending. The+ * emailed link keeps granting the invitee edit access to their response.*/const PRO_HOST = "[email protected]";@@ -39,6 +40,31 @@ async function openAsGuest(browser: Browser, inviteUrl: string) {// The invite list is server data, so a guest's activity only shows after// the host's page reloads.+/**+ * A fresh context has no guest cookie, so the only thing identifying the+ * viewer is the token in the link.+ */+async function renameThroughInviteLink(+ browser: Browser,+ inviteUrl: string,+ { from, to }: { from: string; to: string },+) {+ const guest = await openAsGuest(browser, inviteUrl);+ try {+ const { guestPage } = guest;+ await expect(guestPage.getByText(from)).toBeVisible();+ await guestPage.getByTestId("participant-menu").click();+ await guestPage.getByRole("menuitem", { name: "Change name" }).click();+ const dialog = guestPage.getByRole("dialog", { name: "Change name" });+ await dialog.getByLabel("Name").fill(to);+ await dialog.getByRole("button", { name: "Save" }).click();+ await expect(dialog).toBeHidden();+ await expect(guestPage.getByText(to)).toBeVisible();+ } finally {+ await guest.close();+ }+}+async function reopenShareDialog(page: Page) {await page.reload();await page.getByRole("button", { name: "Share" }).click();@@ -89,14 +115,14 @@ test.describe("Email invites", () => {`Pro Host invited you to respond to ${POLL_TITLE}`,);expect(email.HTML).toContain("/invite/");- expect(email.HTML).toContain("?invite=");+ expect(email.HTML).toContain("?token=");// Replies reach the host, not the From address.expect(email.ReplyTo.map((address) => address.Address)).toEqual([PRO_HOST]);// The row menu copies the same personal link the email carried, so a// host reaching the invitee another way keeps the response attributed.const emailedUrl = email.HTML.match(- /href="([^"]*\/invite\/[^"]*invite=[^"]*)"/,+ /href="([^"]*\/invite\/[^"]*token=[^"]*)"/,)?.[1];await row.getByRole("button", { name: `Options for ${INVITEE}` }).click();await page.getByRole("menuitem", { name: "Copy personal link" }).click();@@ -176,6 +202,15 @@ test.describe("Email invites", () => {.getByRole("listitem").filter({ hasText: INVITEE });await expect(respondedRow.getByText("Responded")).toBeVisible();+ await page.keyboard.press("Escape");++ // Opening the same link again, with no cookie, edits that response.+ await renameThroughInviteLink(browser as Browser, emailedUrl as string, {+ from: "Invited Guest",+ to: "Renamed Guest",+ });+ await page.reload();+ await expect(page.getByText("Renamed Guest")).toBeVisible();});test("creation opens the dialog and leaves the URL clean", async ({diff --git a/apps/web/tests/legacy-edit-link.spec.ts b/apps/web/tests/legacy-edit-link.spec.tsnew file mode 100644index 000000000..2863352d1--- /dev/null+++ b/apps/web/tests/legacy-edit-link.spec.ts@@ -0,0 +1,56 @@+import { randomUUID } from "node:crypto";+import { expect, test } from "@playwright/test";+import { prisma } from "@rallly/database";+import { sealData } from "iron-session";+import { createTestPoll, createUserInDb } from "./test-utils";++/**+ * Confirmation emails sent before responses carried their own token linked+ * to a seal of the guest's user id. Those links stay valid.+ */++const GUEST_EMAIL = "[email protected]";+const POLL_ID = "legacy-edit-link-poll";++async function cleanup() {+ await prisma.poll.deleteMany({ where: { id: POLL_ID } });+ await prisma.user.deleteMany({ where: { email: GUEST_EMAIL } });+}++test.describe("Legacy edit link", () => {+ test.beforeAll(cleanup);+ test.afterAll(cleanup);++ test("a sealed user token still edits the response it was emailed for", async ({+ page,+ }) => {+ const guest = await createUserInDb({+ email: GUEST_EMAIL,+ name: "Legacy Guest",+ isAnonymous: true,+ });+ await createTestPoll({+ id: POLL_ID,+ title: "Legacy Edit Link Poll",+ updatedAt: new Date(),+ hasFutureOptions: true,+ });+ await prisma.participant.create({+ data: {+ pollId: POLL_ID,+ name: "Legacy Guest",+ email: GUEST_EMAIL,+ userId: guest.id,+ token: randomUUID().replace(/-/g, ""),+ },+ });++ const sealed = await sealData(+ { userId: guest.id },+ { password: process.env.SECRET_PASSWORD as string, ttl: 0 },+ );++ await page.goto(`/invite/${POLL_ID}?token=${sealed}`);+ await expect(page.getByTestId("participant-menu")).toBeVisible();+ });+});