Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ House-keeping job to delete orphaned anonymous guest users (#2764)
Luke Vella45f2bb80eff5
diff --git a/apps/web/src/app/api/house-keeping/[...method]/route.ts b/apps/web/src/app/api/house-keeping/[...method]/route.tsindex e452aaaad..e439f91e0 100644--- a/apps/web/src/app/api/house-keeping/[...method]/route.ts+++ b/apps/web/src/app/api/house-keeping/[...method]/route.ts@@ -13,7 +13,10 @@ import {} from "@/features/poll/mutations";import { findUsersScheduledForRemoval } from "@/features/user/account-deletion/data";import { getAccountDeletionCutoff } from "@/features/user/account-deletion/utils";-import { hardDeleteUser } from "@/features/user/mutations";+import {+ deleteOrphanedAnonymousUsers,+ hardDeleteUser,+} from "@/features/user/mutations";import {deletePostHogPerson,flushPostHog,@@ -179,4 +182,22 @@ app.get("/remove-deleted-users", async (c) => {});});+app.get("/delete-orphaned-anonymous-users", async (c) => {+ const deleted = await deleteOrphanedAnonymousUsers();++ logger.info(+ { task: "delete-orphaned-anonymous-users", deleted },+ "Deleted orphaned anonymous guest users idle longer than the session length",+ );++ return c.json({+ success: true,+ summary: {+ deleted: {+ anonymousUsers: deleted,+ },+ },+ });+});+export const GET = handle(app);diff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.tsindex 5ec3c75ed..b1d93c4b1 100644--- a/apps/web/src/features/user/mutations.ts+++ b/apps/web/src/features/user/mutations.ts@@ -1,8 +1,9 @@import "server-only";-import type { TimeFormat } from "@rallly/database";+import type { Prisma, TimeFormat } from "@rallly/database";import { prisma } from "@rallly/database";import { authLib } from "@/lib/auth";+import { SESSION_TTL_SECONDS } from "@/lib/auth-config";import { deleteImageFromS3 } from "@/lib/storage/image-upload";export async function createUser({@@ -156,6 +157,68 @@ export async function hardDeleteUser({await prisma.user.delete({ where: { id: userId } });}+const DELETE_ORPHANED_ANONYMOUS_USERS_BATCH_SIZE = 100;++/**+ * Delete orphaned anonymous guest users: guests that own no resources and+ * haven't been seen for longer than the session length.+ *+ * Two guards, both required:+ * - The `lastSeenAt` window IS the liveness check. Prod sessions live in+ * Redis, so we can't probe them at delete time; but session TTL equals+ * this window and every session refresh bumps `lastSeenAt`, so a guest+ * below the cutoff provably has no live session left to orphan.+ * - The resource filter guards the cascade. A guest's polls/comments are+ * onDelete: Cascade, so deleting one who still owns a live poll would+ * destroy everyone's votes/comments.+ *+ * `scheduledEventInvites` is the invitee link (invitee_id, SetNull); a guest+ * on that relation is a live participant elsewhere and must be retained.+ */+export async function deleteOrphanedAnonymousUsers() {+ const cutoff = new Date(Date.now() - SESSION_TTL_SECONDS * 1000);++ // Both guards live here so read and delete share exactly one predicate.+ const orphanedAnonymousFilter = {+ isAnonymous: true,+ lastSeenAt: { lt: cutoff },+ polls: { none: {} },+ comments: { none: {} },+ participants: { none: {} },+ scheduledEventInvites: { none: {} },+ } satisfies Prisma.UserWhereInput;++ let deleted = 0;+ let hasMore = true;++ while (hasMore) {+ const batch = await prisma.user.findMany({+ where: orphanedAnonymousFilter,+ select: { id: true },+ take: DELETE_ORPHANED_ANONYMOUS_USERS_BATCH_SIZE,+ });++ if (batch.length === 0) {+ hasMore = false;+ break;+ }++ // Re-apply the guards at delete time, not just id: a poll/comment/invite+ // created — or an account linked out of anonymous — between this snapshot+ // and the delete would otherwise be cascaded away. Any batched id that+ // fails the re-check is simply left for the next findMany to exclude.+ const { count } = await prisma.user.deleteMany({+ where: {+ AND: [orphanedAnonymousFilter, { id: { in: batch.map((u) => u.id) } }],+ },+ });++ deleted += count;+ }++ return deleted;+}+export async function setActiveSpace({userId,spaceId,diff --git a/apps/web/src/lib/auth-config.ts b/apps/web/src/lib/auth-config.tsnew file mode 100644index 000000000..5309551d1--- /dev/null+++ b/apps/web/src/lib/auth-config.ts@@ -0,0 +1,4 @@+// Session length, shared so the auth config and any window derived from it+// (e.g. the orphaned-guest cleanup) can't drift. The cleanup window must+// stay >= this value or its liveness guarantee breaks.+export const SESSION_TTL_SECONDS = 60 * 60 * 24 * 60; // 60 daysdiff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.tsindex a088dace5..29461ab78 100644--- a/apps/web/src/lib/auth.ts+++ b/apps/web/src/lib/auth.ts@@ -30,6 +30,7 @@ import { getStripe } from "@/features/billing/service";import type { UserDTO } from "@/features/user/schema";import { getTranslation } from "@/i18n/server";import { getLocale } from "@/i18n/server/get-locale";+import { SESSION_TTL_SECONDS } from "@/lib/auth-config";import { hostOnlyCookieCleanup } from "@/lib/auth-plugins/host-only-cookie-cleanup";import { redis } from "@/lib/kv";import {@@ -537,7 +538,7 @@ export const authLib = betterAuth({},},session: {- expiresIn: 60 * 60 * 24 * 60, // 60 days+ expiresIn: SESSION_TTL_SECONDS,updateAge: 60 * 60 * 24, // 1 daycookieCache: {enabled: true,diff --git a/apps/web/tests/house-keeping.spec.ts b/apps/web/tests/house-keeping.spec.tsindex c270b4eb0..2d900f80b 100644--- a/apps/web/tests/house-keeping.spec.ts+++ b/apps/web/tests/house-keeping.spec.ts@@ -1,6 +1,7 @@import { expect, test } from "@playwright/test";import { prisma } from "@rallly/database";import dayjs from "dayjs";+import { SESSION_TTL_SECONDS } from "@/lib/auth-config";import { createSpaceInDb, createTestPoll, createUserInDb } from "./test-utils";/**@@ -8,7 +9,12 @@ import { createSpaceInDb, createTestPoll, createUserInDb } from "./test-utils";* 1. delete-inactive-polls: Marks inactive polls as deleted* 2. remove-deleted-polls: Permanently removes polls that have been marked as deleted for more than 7 days* 3. auto-close-polls: Closes open polls whose options have all ended+ * 4. delete-orphaned-anonymous-users: Deletes idle guests that own no resources*/++// Session length; anything below now - this cutoff is provably session-less.+// Derived from the production constant so the boundary can't silently drift.+const SESSION_TTL_DAYS = SESSION_TTL_SECONDS / (60 * 60 * 24);test.describe("House-keeping API", () => {// Store created poll IDs for cleanupconst createdPollIds: string[] = [];@@ -433,4 +439,140 @@ test.describe("House-keeping API", () => {expect(await statusOf(noOptions.id)).toBe("open");expect(await statusOf(scheduled.id)).toBe("scheduled");});++ test("should delete only orphaned anonymous guests idle longer than the session length", async ({+ request,+ baseURL,+ }) => {+ const stale = dayjs()+ .subtract(SESSION_TTL_DAYS + 1, "day")+ .toDate();+ const recent = dayjs()+ .subtract(SESSION_TTL_DAYS - 1, "day")+ .toDate();++ // Should be deleted: stale guest with no resources.+ const orphanedGuest = await createUserInDb({+ name: "Orphaned Guest",+ email: "[email protected]",+ isAnonymous: true,+ lastSeenAt: stale,+ });+ createdUserIds.push(orphanedGuest.id);++ // Retained (window): guest seen within the session length.+ const recentGuest = await createUserInDb({+ name: "Recent Guest",+ email: "[email protected]",+ isAnonymous: true,+ lastSeenAt: recent,+ });+ createdUserIds.push(recentGuest.id);++ // Retained (cascade guard): stale guest who still owns a poll.+ const guestWithPoll = await createUserInDb({+ name: "Guest With Poll",+ email: "[email protected]",+ isAnonymous: true,+ lastSeenAt: stale,+ });+ createdUserIds.push(guestWithPoll.id);+ const guestPoll = await createTestPoll({+ id: "orphaned-guest-poll",+ title: "Guest Poll",+ userId: guestWithPoll.id,+ updatedAt: stale,+ });+ createdPollIds.push(guestPoll.id);++ // Retained (resource guard): stale guest who is a participant on a poll.+ const guestParticipant = await createUserInDb({+ name: "Guest Participant",+ email: "[email protected]",+ isAnonymous: true,+ lastSeenAt: stale,+ });+ createdUserIds.push(guestParticipant.id);+ const hostedPoll = await createTestPoll({+ id: "orphaned-guest-host-poll",+ title: "Host Poll",+ updatedAt: stale,+ });+ createdPollIds.push(hostedPoll.id);+ await prisma.participant.create({+ data: {+ name: "Guest Participant",+ pollId: hostedPoll.id,+ userId: guestParticipant.id,+ },+ });++ // Retained (resource guard): stale guest linked via a scheduled event+ // invite (invitee_id). Needs a registered host to own the event + space.+ const eventHost = await createUserInDb({+ name: "Event Host",+ email: "[email protected]",+ });+ createdUserIds.push(eventHost.id);+ const hostSpace = await prisma.space.findFirstOrThrow({+ where: { ownerId: eventHost.id },+ });+ const guestInvitee = await createUserInDb({+ name: "Guest Invitee",+ email: "[email protected]",+ isAnonymous: true,+ lastSeenAt: stale,+ });+ createdUserIds.push(guestInvitee.id);+ await prisma.scheduledEvent.create({+ data: {+ userId: eventHost.id,+ spaceId: hostSpace.id,+ title: "Orphaned Guest Event",+ uid: "orphaned-guest-event-uid",+ start: dayjs().add(1, "day").toDate(),+ end: dayjs().add(1, "day").add(1, "hour").toDate(),+ invites: {+ create: {+ uid: "orphaned-guest-invite-uid",+ inviteeName: "Guest Invitee",+ inviteeEmail: guestInvitee.email,+ inviteeId: guestInvitee.id,+ },+ },+ },+ });++ // Critical: a stale registered user with no resources must never be reaped.+ const staleRealUser = await createUserInDb({+ name: "Stale Real User",+ email: "[email protected]",+ lastSeenAt: stale,+ });+ createdUserIds.push(staleRealUser.id);++ const response = await request.get(+ `${baseURL}/api/house-keeping/delete-orphaned-anonymous-users`,+ {+ headers: {+ Authorization: `Bearer ${CRON_SECRET}`,+ },+ },+ );++ expect(response.ok()).toBeTruthy();+ const responseData = await response.json();+ expect(responseData.success).toBeTruthy();+ expect(responseData.summary.deleted.anonymousUsers).toBe(1);++ const exists = async (id: string) =>+ (await prisma.user.findUnique({ where: { id } })) !== null;++ expect(await exists(orphanedGuest.id)).toBe(false);+ expect(await exists(recentGuest.id)).toBe(true);+ expect(await exists(guestWithPoll.id)).toBe(true);+ expect(await exists(guestParticipant.id)).toBe(true);+ expect(await exists(guestInvitee.id)).toBe(true);+ expect(await exists(staleRealUser.id)).toBe(true);+ });});diff --git a/apps/web/tests/test-utils.ts b/apps/web/tests/test-utils.tsindex 1449b4c10..0d9bc4610 100644--- a/apps/web/tests/test-utils.ts+++ b/apps/web/tests/test-utils.ts@@ -8,10 +8,14 @@ export async function createUserInDb({email,name,role = "user",+ isAnonymous = false,+ lastSeenAt,}: {email: string;name: string;role?: UserRole;+ isAnonymous?: boolean;+ lastSeenAt?: Date;}) {return await prisma.$transaction(async (tx) => {const user = await tx.user.create({@@ -23,24 +27,29 @@ export async function createUserInDb({timeZone: "Europe/London",timeFormat: "hours24",emailVerified: true,+ isAnonymous,+ ...(lastSeenAt && { lastSeenAt }),},});- const space = await tx.space.create({- data: {- name: "Personal",- ownerId: user.id,- tier: "hobby",- },- });+ // Anonymous guests own no space; only registered users get one.+ if (!isAnonymous) {+ const space = await tx.space.create({+ data: {+ name: "Personal",+ ownerId: user.id,+ tier: "hobby",+ },+ });- await tx.spaceMember.create({- data: {- spaceId: space.id,- userId: user.id,- role: "ADMIN",- },- });+ await tx.spaceMember.create({+ data: {+ spaceId: space.id,+ userId: user.id,+ role: "ADMIN",+ },+ });+ }return user;});diff --git a/packages/database/prisma/migrations/20260723000000_add_orphaned_anonymous_user_indexes/migration.sql b/packages/database/prisma/migrations/20260723000000_add_orphaned_anonymous_user_indexes/migration.sqlnew file mode 100644index 000000000..e54166213--- /dev/null+++ b/packages/database/prisma/migrations/20260723000000_add_orphaned_anonymous_user_indexes/migration.sql@@ -0,0 +1,8 @@+-- CreateIndex+CREATE INDEX "comments_user_id_idx" ON "comments"("user_id");++-- CreateIndex+CREATE INDEX "participants_user_id_idx" ON "participants"("user_id");++-- CreateIndex+CREATE INDEX "users_anonymous_last_seen_at_idx" ON "users"("anonymous", "last_seen_at");diff --git a/packages/database/prisma/models/poll.prisma b/packages/database/prisma/models/poll.prismaindex 9e81bfbe9..33f4d50ce 100644--- a/packages/database/prisma/models/poll.prisma+++ b/packages/database/prisma/models/poll.prisma@@ -87,6 +87,7 @@ model Participant {user User? @relation(fields: [userId], references: [id], onDelete: SetNull)@@index([pollId], type: Hash)+ @@index([userId])@@map("participants")}@@ -145,5 +146,6 @@ model Comment {user User? @relation(fields: [userId], references: [id], onDelete: Cascade)@@index([pollId])+ @@index([userId])@@map("comments")}diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prismaindex cc4d2e5f7..b187a44ca 100644--- a/packages/database/prisma/models/user.prisma+++ b/packages/database/prisma/models/user.prisma@@ -87,6 +87,9 @@ model User {impersonatedSessions Session[] @relation("ImpersonatedSessions")@@index([deletedAt])+ // Supports the orphaned-anonymous-guest cleanup: filters anonymous users by+ // last-seen time before checking they own no resources.+ @@index([isAnonymous, lastSeenAt])@@map("users")}