Polish invitation resend and upload recovery

This commit is contained in:
2026-09-10 11:53:59 -04:00
parent 361e14ec1d
commit d44ef7348c
15 changed files with 208 additions and 23 deletions
@@ -14,6 +14,15 @@ async function authorize(userId: string, eventId: string) {
}
export const bannersRouter = createTRPCRouter({
retry: protectedProcedure.input(bannerInputSchema).mutation(async ({ ctx, input }) => {
await authorize(ctx.session.user.id, input.eventId);
const limit = await consumeRateLimit({ namespace: "banner-retry", identifier: `${ctx.session.user.id}:${input.bannerId}`, limit: 3, windowMs: 600000 });
if (!limit.allowed) throw new TRPCError({ code: "TOO_MANY_REQUESTS", message: "Repeated processing failures. Try another image or contact support." });
const rows = await getDb().update(eventBanners).set({ status: "pending", updatedAt: new Date() })
.where(and(eq(eventBanners.id, input.bannerId), eq(eventBanners.eventId, input.eventId), eq(eventBanners.status, "failed"))).returning({ id: eventBanners.id });
if (!rows.length) throw new TRPCError({ code: "BAD_REQUEST", message: "This banner is not failed. Check its status again." });
return { ok: true };
}),
create: protectedProcedure.input(createBannerInputSchema).mutation(async ({ ctx, input }) => {
await authorize(ctx.session.user.id, input.eventId);
const limit = await consumeRateLimit({ namespace: "banner-upload", identifier: ctx.session.user.id, limit: 20, windowMs: 600_000 });
+19
View File
@@ -34,6 +34,8 @@ import { sendStaffInviteEmail } from "@album/email";
import { publicAppOrigin } from "@/server/public-app-url";
import { GROUP_COOKIE, serializeCookie } from "@/server/cookies";
import { invites } from "@album/database";
import { assertInviteRedeemable } from "@/server/invites";
import { consumeRateLimit } from "@/server/rate-limit";
async function validateInviteGrants(userId: string, input: {
groupId?: string; eventId?: string; eventRole?: string;
@@ -55,6 +57,23 @@ async function validateInviteGrants(userId: string, input: {
}
export const groupRouter = createTRPCRouter({
resendInvite: protectedProcedure.input(z.object({ groupId: z.string().uuid(), inviteId: z.string().uuid() })).mutation(async ({ ctx, input }) => {
const { access } = await loadGroupAccess(ctx.session.user.id, input.groupId, await getPlatformRole(ctx.session.user.id));
requireGroupPermission(access.permissions, GROUP_PERMISSIONS.PEOPLE_MANAGE);
const limit = await consumeRateLimit({ namespace: "invite-resend", identifier: `${input.groupId}:${input.inviteId}`, limit: 1, windowMs: 60000 });
if (!limit.allowed) throw new TRPCError({ code: "TOO_MANY_REQUESTS", message: "Wait one minute before resending this invite." });
await getDb().transaction(async tx => {
const [invite] = await tx.select().from(invites).where(and(eq(invites.id, input.inviteId), eq(invites.groupId, input.groupId))).limit(1).for("update");
if (!invite || invite.kind !== "email" || !invite.email) throw new TRPCError({ code: "NOT_FOUND" });
assertInviteRedeemable(invite);
await validateInviteGrants(ctx.session.user.id, { groupId: input.groupId, eventId: invite.eventId ?? undefined, eventRole: invite.eventRole ?? undefined, grantUnlimitedEvents: invite.grantUnlimitedEvents, grantEventLimit: invite.grantEventLimit, grantComplimentary: invite.grantComplimentary });
const token = newToken();
await tx.update(invites).set({ tokenHash: hashToken(token), updatedAt: new Date() }).where(and(eq(invites.id, invite.id), eq(invites.groupId, input.groupId)));
await sendStaffInviteEmail({ to: invite.email, inviterName: ctx.session.user.name, inviteUrl: `${publicAppOrigin()}/invitations/${token}` });
await tx.insert(auditEvents).values({ groupId: input.groupId, eventId: invite.eventId, actorUserId: ctx.session.user.id, action: "invite.resend", subjectType: "invite", subjectId: invite.id });
});
return { ok: true };
}),
rename: protectedProcedure
.input(z.object({ groupId: z.string().uuid(), name: z.string().trim().min(1).max(100) }))
.mutation(async ({ ctx, input }) => {
+17 -1
View File
@@ -1,4 +1,5 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { and, eq } from "drizzle-orm";
import { events, getDb, photoJobs, photos, submissions } from "@album/database";
import {
@@ -18,6 +19,21 @@ import { guests } from "@album/database";
import { effectiveEvent } from "@/lib/event-lifecycle";
export const photosRouter = createTRPCRouter({
retryUpload: publicProcedure.input(z.object({ eventId: z.string().uuid(), photoId: z.string().uuid() })).mutation(async ({ ctx, input }) => {
const [photo] = await getDb().select().from(photos).where(and(eq(photos.id, input.photoId), eq(photos.eventId, input.eventId))).limit(1);
const token = ctx.guestTokenForEvent(input.eventId);
const [owner] = photo && token ? await getDb().select({ id: guests.id }).from(guests)
.innerJoin(submissions, and(eq(submissions.guestId, guests.id), eq(submissions.eventId, input.eventId)))
.where(and(eq(submissions.id, photo.submissionId), eq(guests.eventId, input.eventId), eq(guests.tokenHash, hashToken(token)))).limit(1) : [];
if (!photo || !owner) throw new TRPCError({ code: "FORBIDDEN", message: "Guest session does not match this upload." });
if (photo.processingStatus !== "uploading") return { uploadUrl: null };
const [stored] = await getDb().select().from(events).where(eq(events.id, input.eventId)).limit(1);
const event = stored ? effectiveEvent(stored) : null;
if (!event || event.status !== "published" || !event.uploadEnabled) throw new TRPCError({ code: "FORBIDDEN", message: "Uploads are closed for this event." });
const limit = await consumeRateLimit({ namespace: `upload-retry:${input.eventId}`, identifier: ctx.clientIdentifier, limit: 40, windowMs: 600000 });
if (!limit.allowed) throw new TRPCError({ code: "TOO_MANY_REQUESTS", message: "Too many retries. Try again shortly." });
return { uploadUrl: await createPresignedPutUrl({ key: photo.originalKey, contentType: photo.contentType }) };
}),
create: publicProcedure
.input(createPhotoInputSchema)
.mutation(async ({ ctx, input }) => {
@@ -105,7 +121,7 @@ export const photosRouter = createTRPCRouter({
key,
contentType: input.contentType,
});
return { photoId: photo.id, uploadUrl };
return { photoId: photo.id, eventId: event.id, uploadUrl };
}),
complete: publicProcedure
@@ -0,0 +1,53 @@
import { test, expect } from "bun:test";
import { eq } from "drizzle-orm";
import { getDb, user, groups, events, invites, auditEvents } from "@album/database";
import { hashToken } from "./tokens";
import { redeemInviteForUser } from "./invites";
test.skipIf(process.env.INVITE_JOURNEY_INTEGRATION !== "1")("fresh account verifies via Mailpit and accepts the correct event invitation", async () => {
if (process.env.EMAIL_PROVIDER !== "mailpit" || !["localhost", "127.0.0.1"].includes(new URL(process.env.DATABASE_URL!).hostname)) throw new Error("Local database and Mailpit required");
const db = getDb();
const id = crypto.randomUUID();
const email = `journey-${id}@manyangles.test`;
const password = `Test-${crypto.randomUUID()}!`;
const token = crypto.randomUUID();
const origin = "http://localhost:3000";
let userId: string | undefined;
let groupId: string | undefined;
let messageId: string | undefined;
try {
const signup = await fetch(`${origin}/api/auth/sign-up/email`, { method: "POST", headers: { "Content-Type": "application/json", Origin: origin }, body: JSON.stringify({ name: "Invite journey test", email, password, callbackURL: `/invitations/${token}` }) });
expect(signup.ok).toBe(true);
const data = await signup.json() as { user: { id: string } };
userId = data.user.id;
const [group] = await db.insert(groups).values({ name: "Journey test", slug: id, createdByUserId: userId }).returning();
groupId = group!.id;
const [event] = await db.insert(events).values({ groupId, title: "Journey test event", slug: id }).returning();
await db.insert(invites).values({ groupId, eventId: event!.id, kind: "email", email, tokenHash: hashToken(token), eventRole: "manager" });
const landing = await (await fetch(`${origin}/invitations/${token}`)).text();
expect(landing).toContain("Help out with Journey test event");
expect(landing).toContain("Create account to accept");
await expect(redeemInviteForUser({ token, userId })).rejects.toThrow("Verify your email");
const search = await (await fetch(`http://localhost:8027/api/v1/search?query=${encodeURIComponent(`to:${email}`)}`)).json() as { messages: { ID: string }[] };
messageId = search.messages[0]?.ID;
expect(messageId).toBeDefined();
const message = await (await fetch(`http://localhost:8027/api/v1/message/${messageId}`)).json() as { Text: string };
const verification = message.Text.match(/https?:\/\/[^\s]+\/api\/auth\/verify-email[^\s]*/)?.[0];
expect(verification).toBeDefined();
expect(new URL(verification!).origin).toBe(origin);
const verified = await fetch(verification!, { redirect: "manual" });
expect(verified.status).toBeLessThan(400);
expect(verified.headers.get("location")).toContain(`/invitations/${token}`);
const [account] = await db.select().from(user).where(eq(user.id, userId));
expect(account!.emailVerified).toBe(true);
const login = await fetch(`${origin}/api/auth/sign-in/email`, { method: "POST", headers: { "Content-Type": "application/json", Origin: origin }, body: JSON.stringify({ email, password }) });
expect(login.ok).toBe(true);
const result = await redeemInviteForUser({ token, userId });
expect(result.eventId).toBe(event!.id);
await expect(redeemInviteForUser({ token, userId })).rejects.toThrow();
} finally {
if (groupId) { await db.delete(auditEvents).where(eq(auditEvents.groupId, groupId)); await db.delete(groups).where(eq(groups.id, groupId)); }
if (userId) await db.delete(user).where(eq(user.id, userId));
if (messageId) await fetch(`http://localhost:8027/api/v1/messages`, { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ IDs: [messageId] }) });
}
}, 30000);
+1
View File
@@ -99,6 +99,7 @@ async function redeemLockedInvite(input: { token: string; userId: string }, db:
if (!actor) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
if (!actor.emailVerified) throw new TRPCError({ code: "FORBIDDEN", message: "Verify your email address before accepting this invitation." });
if (invite.kind === "email" && (!invite.email || invite.email.trim().toLowerCase() !== actor.email.trim().toLowerCase())) {
throw new TRPCError({ code: "FORBIDDEN", message: "Sign in with the email address this invitation was sent to." });
}
+13 -1
View File
@@ -1,7 +1,8 @@
import { expect, test } from "bun:test";
import sharp from "sharp";
import { and, eq, inArray } from "drizzle-orm";
import { getDb, user, groups, events, eventMemberships, groupMemberships, invites, eventSigns, auditEvents } from "@album/database";
import { getDb, user, groups, events, eventMemberships, groupMemberships, invites, eventSigns, auditEvents, eventBanners } from "@album/database";
import { bannersRouter } from "./api/routers/banners";
import { deletePrefix } from "@album/storage";
import { hashToken } from "./tokens";
import { redeemInviteForUser } from "./invites";
@@ -12,6 +13,7 @@ import type { TrpcContext } from "./api/trpc";
test.skipIf(process.env.POLISH_INTEGRATION !== "1")("invitation isolation, atomic redemption, and saved sign roundtrip/conflicts", async () => {
for (const key of ["DATABASE_URL", "S3_ENDPOINT"]) if (!["localhost", "127.0.0.1"].includes(new URL(process.env[key]!).hostname)) throw new Error("Local services required");
if (process.env.EMAIL_PROVIDER !== "mailpit") throw new Error("Mailpit required");
const db = getDb();
const id = crypto.randomUUID();
const people = await db.insert(user).values([0, 1].map(n => ({ id: `${id}-${n}`, name: "Polish test", email: `${id}-${n}@manyangles.test`, emailVerified: true }))).returning();
@@ -21,6 +23,10 @@ test.skipIf(process.env.POLISH_INTEGRATION !== "1")("invitation isolation, atomi
try {
await db.insert(groupMemberships).values({ groupId: group!.id, userId: people[0]!.id, role: "owner" });
await db.insert(eventMemberships).values({ eventId: event!.id, userId: people[0]!.id, role: "owner" });
const [failedBanner] = await db.insert(eventBanners).values({ eventId: event!.id, originalKey: `events/${event!.id}/banners/test-missing`, contentType: "image/jpeg", byteSize: 10, status: "failed" }).returning();
await expect(bannersRouter.createCaller(ctx(1)).retry({ eventId: event!.id, bannerId: failedBanner!.id })).rejects.toThrow();
expect(await bannersRouter.createCaller(ctx(0)).retry({ eventId: event!.id, bannerId: failedBanner!.id })).toEqual({ ok: true });
await db.delete(eventBanners).where(and(eq(eventBanners.eventId, event!.id), eq(eventBanners.id, failedBanner!.id)));
const token = crypto.randomUUID();
await db.insert(invites).values({ kind: "email", email: people[0]!.email.toUpperCase(), tokenHash: hashToken(token), groupId: group!.id, maxUses: 1 });
await expect(redeemInviteForUser({ token, userId: people[1]!.id })).rejects.toThrow("email address");
@@ -57,6 +63,12 @@ test.skipIf(process.env.POLISH_INTEGRATION !== "1")("invitation isolation, atomi
expect(await workspace.pendingInvites({ groupId: group!.id })).toHaveLength(0);
const [revoked] = await db.select().from(invites).where(and(eq(invites.groupId, group!.id), eq(invites.id, pending!.id)));
expect(revoked!.status).toBe("revoked");
const resendToken = crypto.randomUUID();
const [resendTarget] = await db.insert(invites).values({ groupId: group!.id, kind: "email", email: people[1]!.email, tokenHash: hashToken(resendToken) }).returning();
await expect(groupRouter.createCaller(ctx(1)).resendInvite({ groupId: group!.id, inviteId: resendTarget!.id })).rejects.toThrow();
await workspace.resendInvite({ groupId: group!.id, inviteId: resendTarget!.id });
expect(await db.select().from(invites).where(and(eq(invites.groupId, group!.id), eq(invites.tokenHash, hashToken(resendToken))))).toHaveLength(0);
await expect(workspace.resendInvite({ groupId: group!.id, inviteId: resendTarget!.id })).rejects.toThrow("Wait one minute");
await expect(workspace.createCode({ groupId: group!.id, grantUnlimitedEvents: true })).rejects.toThrow("platform administrators");
const signs = signsRouter.createCaller(ctx(0));
await expect(signsRouter.createCaller(ctx(1)).prepare({ eventId: event!.id })).rejects.toThrow();
@@ -62,12 +62,16 @@ test.skipIf(process.env.PUBLISHING_INTEGRATION !== "1")("standalone notes, appro
original = await getObjectBuffer(source!.key);
}
const created = await photoCaller.create({ eventSlug: event.slug, submissionId: submission.submissionId, contentType: "image/jpeg", fileName: "test.jpg", byteSize: original?.length ?? 100 });
expect((await photoCaller.retryUpload({ eventId: event.id, photoId: created.photoId })).uploadUrl).toBeTruthy();
await expect(photosRouter.createCaller({ ...ctx, guestTokenForEvent: () => null }).retryUpload({ eventId: event.id, photoId: created.photoId })).rejects.toThrow("Guest session");
await expect(photoCaller.retryUpload({ eventId: crypto.randomUUID(), photoId: created.photoId })).rejects.toThrow();
await expect(photosRouter.createCaller({ ...ctx, guestTokenForEvent: () => null }).complete({ photoId: created.photoId })).rejects.toThrow("Guest session");
expect(await publicEvent.gallery(event.slug)).toEqual([]);
if (original) {
uploadedPhotoId = created.photoId;
expect((await fetch(created.uploadUrl, { method: "PUT", headers: { "Content-Type": "image/jpeg" }, body: new Uint8Array(original) })).ok).toBe(true);
await Promise.all([photoCaller.complete({ photoId: created.photoId }), photoCaller.complete({ photoId: created.photoId })]);
expect((await photoCaller.retryUpload({ eventId: event.id, photoId: created.photoId })).uploadUrl).toBeNull();
expect(await db.select({ id: photoJobs.id }).from(photoJobs).where(eq(photoJobs.photoId, created.photoId))).toHaveLength(1);
let ready = false;
for (let attempt = 0; attempt < 45; attempt++) {