Skip to content

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

✨ Mint an edit token for every response (#3166)

Luke Vellae76c241325e9
diff --git a/apps/web/src/features/poll/invite/mutations.ts b/apps/web/src/features/poll/invite/mutations.ts
index e71a77035..03a4c39e6 100644
--- a/apps/web/src/features/poll/invite/mutations.ts
+++ b/apps/web/src/features/poll/invite/mutations.ts
@@ -4,22 +4,15 @@ import { Prisma, prisma } from "@rallly/database";
import { sendPollInviteEmail } from "@rallly/emails/templates/poll-invite";
import { createLogger } from "@rallly/logger";
import { absoluteUrl } from "@rallly/utils/absolute-url";
-import { customAlphabet } from "nanoid";
import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";
import { resolveSpaceTier } from "@/features/billing/utils";
import { recordPollActivities } from "@/features/poll/activity/mutations";
import { MAX_POLL_INVITES_PER_DAY } from "@/features/poll/invite/constants";
import { getPollInvitePath } from "@/features/poll/invite/utils";
+import { generateAccessToken } from "@/features/poll/utils";
const logger = createLogger("poll/invite/mutations");
-// Alphanumeric only: url safe with no linkifier edge cases. 32 chars is the
-// floor documented on PollInvite.token.
-const generateInviteToken = customAlphabet(
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
- 32,
-);
-
class InviteClaimedElsewhere extends Error {}
export type SendPollInviteResult =
@@ -123,7 +116,7 @@ export async function sendPollInvite({
return { ok: false, reason: "alreadyInvited" };
}
- const token = generateInviteToken();
+ const token = generateAccessToken();
// A reactivated invite keeps its id and gains a second invite_sent event,
// so the rollback below must only touch events from this attempt.
@@ -234,35 +227,38 @@ export async function sendPollInvite({
return { ok: true, invite };
}
+/**
+ * The pending invite behind an emailed link. Only the token counts as proof:
+ * a typed address is unverified, so matching on it would let anyone claim
+ * someone else's invite. Read inside the response's transaction so the
+ * response can take the invite's token as its own. Two responses racing on
+ * one link both find the row; the second fails on the participant token's
+ * unique index rather than silently claiming a token already in use.
+ */
+export async function findPendingPollInvite(
+ tx: Prisma.TransactionClient,
+ { pollId, token }: { pollId: string; token: string },
+) {
+ return tx.pollInvite.findFirst({
+ where: { pollId, token, participantId: null, revokedAt: null },
+ select: { id: true, token: true },
+ });
+}
+
/**
* Joins a new response to the invite it answers, so the host's list flips
- * from Sent to Responded. Only the token from the emailed link counts as
- * proof: a typed address is unverified, so matching on it would let anyone
- * claim someone else's invite. Runs inside the response's transaction so the
- * join commits with the participant.
+ * from Sent to Responded. Runs inside the response's transaction so the join
+ * commits with the participant.
*/
export async function attachParticipantToInvite(
tx: Prisma.TransactionClient,
- {
- pollId,
- participantId,
- inviteToken,
- }: {
- pollId: string;
- participantId: string;
- inviteToken?: string;
- },
+ { inviteId, participantId }: { inviteId: string; participantId: string },
) {
- if (!inviteToken) {
- return false;
- }
-
- const { count } = await tx.pollInvite.updateMany({
- where: { pollId, participantId: null, revokedAt: null, token: inviteToken },
+ await tx.pollInvite.update({
+ where: { id: inviteId },
data: { participantId },
+ select: { id: true },
});
-
- return count > 0;
}
/**
diff --git a/apps/web/src/features/poll/utils.ts b/apps/web/src/features/poll/utils.ts
new file mode 100644
index 000000000..a41252917
--- /dev/null
+++ b/apps/web/src/features/poll/utils.ts
@@ -0,0 +1,8 @@
+import { customAlphabet } from "nanoid";
+
+// Alphanumeric only: url safe with no linkifier edge cases. 32 chars is the
+// floor documented on Participant.token and PollInvite.token.
+export const generateAccessToken = customAlphabet(
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
+ 32,
+);
diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.ts
index 011ffd32d..c6220940b 100644
--- a/apps/web/src/trpc/routers/polls/participants.ts
+++ b/apps/web/src/trpc/routers/polls/participants.ts
@@ -13,7 +13,11 @@ 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 { attachParticipantToInvite } from "@/features/poll/invite/mutations";
+import {
+ attachParticipantToInvite,
+ findPendingPollInvite,
+} from "@/features/poll/invite/mutations";
+import { generateAccessToken } from "@/features/poll/utils";
import { AppError } from "@/lib/errors/app-error";
import { track } from "@/lib/posthog";
import {
@@ -38,7 +42,8 @@ function createParticipantFullDTO(
votes: { optionId: string; type: VoteType }[];
},
) {
- const { votes, user, ...rest } = participant;
+ // The token is the edit credential: it never leaves the server.
+ const { votes, user, token: _token, ...rest } = participant;
return {
...rest,
image: user?.image ?? null,
@@ -350,6 +355,12 @@ export const participants = router({
const { participant, 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 })
+ : null;
+
const participant = await tx.participant.create({
data: {
pollId: pollId,
@@ -357,6 +368,7 @@ export const participants = router({
email,
note,
timeZone,
+ token: invite?.token ?? generateAccessToken(),
userId: ctx.user.id,
locale: ctx.locale,
votes: {
@@ -410,13 +422,14 @@ export const participants = router({
},
]);
- const viaInvite = await attachParticipantToInvite(tx, {
- pollId,
- participantId: participant.id,
- inviteToken,
- });
+ if (invite) {
+ await attachParticipantToInvite(tx, {
+ inviteId: invite.id,
+ participantId: participant.id,
+ });
+ }
- return { participant, viaInvite };
+ return { participant, viaInvite: invite !== null };
},
);
diff --git a/apps/web/tests/email-invites.spec.ts b/apps/web/tests/email-invites.spec.ts
index 9c3171359..ab8a7301b 100644
--- a/apps/web/tests/email-invites.spec.ts
+++ b/apps/web/tests/email-invites.spec.ts
@@ -162,9 +162,15 @@ test.describe("Email invites", () => {
}),
).toBe(1);
- // Responding through the emailed link joins the response to the invite.
+ // Responding through the emailed link joins the response to the invite,
+ // and the response takes the invite's token as its own.
await new InvitePage(guest.guestPage).addParticipant("Invited Guest");
await guest.close();
+ const converted = await prisma.pollInvite.findUniqueOrThrow({
+ where: { id: invite.id },
+ select: { token: true, participant: { select: { token: true } } },
+ });
+ expect(converted.participant?.token).toBe(converted.token);
const respondedRow = (await reopenShareDialog(page))
.getByRole("listitem")
diff --git a/apps/web/tests/house-keeping.spec.ts b/apps/web/tests/house-keeping.spec.ts
index d20b68822..1ee0c318b 100644
--- a/apps/web/tests/house-keeping.spec.ts
+++ b/apps/web/tests/house-keeping.spec.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from "node:crypto";
import { expect, test } from "@playwright/test";
import { prisma } from "@rallly/database";
import dayjs from "dayjs";
@@ -486,6 +487,7 @@ test.describe("House-keeping API", () => {
name: "Guest Participant",
pollId: hostedPoll.id,
userId: guestParticipant.id,
+ token: randomUUID().replace(/-/g, ""),
},
});
diff --git a/apps/web/tests/test-utils.ts b/apps/web/tests/test-utils.ts
index 6f0cf6a3f..7fd985311 100644
--- a/apps/web/tests/test-utils.ts
+++ b/apps/web/tests/test-utils.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from "node:crypto";
import type { SpaceTier, UserRole } from "@rallly/database";
import { prisma } from "@rallly/database";
import dayjs from "dayjs";
@@ -141,6 +142,7 @@ export async function createTestPoll({
participants: {
create: {
name: "Test Participant",
+ token: randomUUID().replace(/-/g, ""),
createdAt: participantActiveAt,
updatedAt: participantActiveAt,
},
diff --git a/packages/database/prisma/migrations/20260904150000_backfill_participant_token/migration.sql b/packages/database/prisma/migrations/20260904150000_backfill_participant_token/migration.sql
new file mode 100644
index 000000000..a1219c125
--- /dev/null
+++ b/packages/database/prisma/migrations/20260904150000_backfill_participant_token/migration.sql
@@ -0,0 +1,17 @@
+-- A response that answered an emailed invite takes the invite's token, the
+-- same rule the write path applies from now on, so the link the invitee
+-- already holds names their response.
+UPDATE "participants" p
+SET "token" = i."token"
+FROM "poll_invites" i
+WHERE i."participant_id" = p."id"
+ AND p."token" IS NULL;
+
+-- Every other response gets hex from a v4 UUID: 32 characters, 122 bits of
+-- randomness, and within the alphanumeric alphabet the app mints with. The
+-- column stays nullable for one release: the code running while this
+-- applies still inserts null tokens, so the NOT NULL constraint follows in a
+-- later migration once every insert path mints.
+UPDATE "participants"
+SET "token" = replace(gen_random_uuid()::text, '-', '')
+WHERE "token" IS NULL;
diff --git a/packages/database/prisma/models/poll.prisma b/packages/database/prisma/models/poll.prisma
index 54049c2f8..8218aeeb7 100644
--- a/packages/database/prisma/models/poll.prisma
+++ b/packages/database/prisma/models/poll.prisma
@@ -73,7 +73,7 @@ model Participant {
name String
email String?
note String?
- /// Per person edit link: grants edit access to this response without a session. App minted, CSPRNG alphanumeric ≥32 chars (nanoid customAlphabet — url safe with no linkifier edge cases, unlike base64url); never a DB default, nullable because it's only minted when a link is issued
+ /// Per response edit link: grants edit access to this response without a session. App minted at creation, CSPRNG alphanumeric ≥32 chars (nanoid customAlphabet — url safe with no linkifier edge cases, unlike base64url); never a DB default. A response created through an emailed invite takes the invite's token. Rows that predate minting were backfilled with gen_random_uuid() hex. Nullable only until the minting code is live everywhere: until then a code path that forgets to mint inserts NULL; once the follow-up migration makes the column required, it fails loudly instead
token String? @unique
userId String? @map("user_id")
pollId String @map("poll_id")
diff --git a/packages/database/prisma/seed.ts b/packages/database/prisma/seed.ts
index 57a5bbf1d..323f4f5c3 100644
--- a/packages/database/prisma/seed.ts
+++ b/packages/database/prisma/seed.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from "node:crypto";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../generated/prisma/client";
import {
@@ -147,6 +148,7 @@ async function main() {
email: part.email,
note: part.note,
userId: part.userId,
+ token: randomUUID().replace(/-/g, ""),
},
});
participantCount++;