From a725cf1a32055fb96b75498e7f92dbf68e7cd21f Mon Sep 17 00:00:00 2001
From: adilallo <39313955+adilallo@users.noreply.github.com>
Date: Sun, 22 Nov 2026 16:58:30 -0700
Subject: [PATCH] Spend login, invite, and email-change links only after a
confirm POST so mail scanners cannot use them up.
GET still shows a one-button page, a used invitation can resend or reopen for the signed-in invitee, and an email-change GET no longer signs the account out.
---
app/(app)/_components/ConfirmLinkScreen.tsx | 107 +++++++++++++
app/(app)/email-change/confirm/layout.tsx | 18 +++
app/(app)/email-change/confirm/page.tsx | 49 ++++++
app/(app)/invite/confirm/layout.tsx | 18 +++
app/(app)/invite/confirm/page.tsx | 53 +++++++
app/(app)/login/confirm/layout.tsx | 17 ++
app/(app)/login/confirm/page.tsx | 48 ++++++
app/api/auth/magic-link/verify/route.ts | 58 +++++--
.../invites/rule-stakeholder/verify/route.ts | 100 +++++++++---
.../[stakeholderId]/resend/route.ts | 3 +-
app/api/rules/[id]/stakeholders/route.ts | 3 +-
app/api/user/email-change/verify/route.ts | 47 ++++--
.../modals/Login/Login.container.tsx | 7 +
lib/create/confirmLinkPaths.ts | 39 +++++
lib/navigationChromelessPath.ts | 4 +-
lib/server/oneTimeLinkToken.ts | 42 +++++
lib/server/pruneExpiredRecords.ts | 4 +-
lib/server/redirectWithRequestId.ts | 14 ++
messages/en/metadata.json | 12 ++
messages/en/pages/invite.json | 5 +
messages/en/pages/login.json | 6 +
messages/en/pages/profile.json | 6 +
prisma/schema.prisma | 3 +-
tests/components/ConfirmLinkScreen.test.tsx | 77 +++++++++
tests/unit/authMagicLinkVerifyRoute.test.ts | 54 ++++++-
tests/unit/confirmLinkPaths.test.ts | 33 ++++
.../unit/lib/navigationChromelessPath.test.ts | 3 +
tests/unit/oneTimeLinkToken.test.ts | 31 ++++
...takeholderInviteResendExpiredRoute.test.ts | 35 +++++
.../ruleStakeholderInviteVerifyRoute.test.ts | 146 +++++++++++++++---
.../rulesStakeholderMutationsRoute.test.ts | 4 +-
tests/unit/rulesStakeholdersRoutes.test.ts | 2 +-
tests/unit/userEmailChangeVerifyRoute.test.ts | 43 +++++-
33 files changed, 1002 insertions(+), 89 deletions(-)
create mode 100644 app/(app)/_components/ConfirmLinkScreen.tsx
create mode 100644 app/(app)/email-change/confirm/layout.tsx
create mode 100644 app/(app)/email-change/confirm/page.tsx
create mode 100644 app/(app)/invite/confirm/layout.tsx
create mode 100644 app/(app)/invite/confirm/page.tsx
create mode 100644 app/(app)/login/confirm/layout.tsx
create mode 100644 app/(app)/login/confirm/page.tsx
create mode 100644 lib/create/confirmLinkPaths.ts
create mode 100644 lib/server/oneTimeLinkToken.ts
create mode 100644 lib/server/redirectWithRequestId.ts
create mode 100644 tests/components/ConfirmLinkScreen.test.tsx
create mode 100644 tests/unit/confirmLinkPaths.test.ts
create mode 100644 tests/unit/oneTimeLinkToken.test.ts
diff --git a/app/(app)/_components/ConfirmLinkScreen.tsx b/app/(app)/_components/ConfirmLinkScreen.tsx
new file mode 100644
index 0000000..3925839
--- /dev/null
+++ b/app/(app)/_components/ConfirmLinkScreen.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { useId } from "react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import Login from "../../components/modals/Login";
+import Button from "../../components/buttons/Button";
+import ContentLockup from "../../components/type/ContentLockup";
+
+const confirmPageBgClass =
+ "min-h-[100dvh] bg-[var(--color-surface-invert-brand-primary)]";
+
+export type ConfirmLinkScreenProps = {
+ title: string;
+ description: string;
+ buttonLabel: string;
+ action: string;
+ token: string;
+ backHref: string;
+ backLabel: string;
+ missingTitle: string;
+ missingDescription: string;
+ missingHref: string;
+ missingButtonLabel: string;
+};
+
+/**
+ * Figma: Overlay / Modal / Login (22078:587823)
+ * One-button confirm so a mail scanner's GET cannot spend a one-time link.
+ */
+export function ConfirmLinkScreen({
+ title,
+ description,
+ buttonLabel,
+ action,
+ token,
+ backHref,
+ backLabel,
+ missingTitle,
+ missingDescription,
+ missingHref,
+ missingButtonLabel,
+}: ConfirmLinkScreenProps) {
+ const router = useRouter();
+ const titleId = useId();
+ const hasToken = token.length >= 10;
+ const heading = hasToken
+ ? { title, description }
+ : { title: missingTitle, description: missingDescription };
+
+ return (
+
+
{
+ router.push(backHref);
+ }}
+ ariaLabelledBy={titleId}
+ belowCard={
+
+ {backLabel}
+
+ }
+ >
+
+
+ {hasToken ? (
+
+ ) : (
+
+ )}
+
+
+
+ );
+}
diff --git a/app/(app)/email-change/confirm/layout.tsx b/app/(app)/email-change/confirm/layout.tsx
new file mode 100644
index 0000000..8e46389
--- /dev/null
+++ b/app/(app)/email-change/confirm/layout.tsx
@@ -0,0 +1,18 @@
+import type { Metadata } from "next";
+import type { ReactNode } from "react";
+import messages from "../../../../messages/en/index";
+import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata";
+
+export const metadata: Metadata = routeMetadata("/email-change/confirm", {
+ title: messages.metadata.emailChangeConfirm.title,
+ description: messages.metadata.emailChangeConfirm.description,
+ robots: NO_INDEX_ROBOTS,
+});
+
+export default function EmailChangeConfirmLayout({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ return children;
+}
diff --git a/app/(app)/email-change/confirm/page.tsx b/app/(app)/email-change/confirm/page.tsx
new file mode 100644
index 0000000..e14ede1
--- /dev/null
+++ b/app/(app)/email-change/confirm/page.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { Suspense } from "react";
+import { useSearchParams } from "next/navigation";
+import { useTranslation } from "../../../contexts/MessagesContext";
+import { emailChangeVerifyPath } from "../../../../lib/create/confirmLinkPaths";
+import { ConfirmLinkScreen } from "../../_components/ConfirmLinkScreen";
+
+function EmailChangeConfirmFallback() {
+ const t = useTranslation("pages.profile");
+ return (
+
+ );
+}
+
+function EmailChangeConfirmWithParams() {
+ const t = useTranslation("pages.profile");
+ const tLogin = useTranslation("pages.login");
+ const searchParams = useSearchParams();
+ const token = searchParams.get("token") ?? "";
+
+ return (
+
+ );
+}
+
+export default function EmailChangeConfirmPage() {
+ return (
+ }>
+
+
+ );
+}
diff --git a/app/(app)/invite/confirm/layout.tsx b/app/(app)/invite/confirm/layout.tsx
new file mode 100644
index 0000000..c85716f
--- /dev/null
+++ b/app/(app)/invite/confirm/layout.tsx
@@ -0,0 +1,18 @@
+import type { Metadata } from "next";
+import type { ReactNode } from "react";
+import messages from "../../../../messages/en/index";
+import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata";
+
+export const metadata: Metadata = routeMetadata("/invite/confirm", {
+ title: messages.metadata.inviteConfirm.title,
+ description: messages.metadata.inviteConfirm.description,
+ robots: NO_INDEX_ROBOTS,
+});
+
+export default function InviteConfirmLayout({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ return children;
+}
diff --git a/app/(app)/invite/confirm/page.tsx b/app/(app)/invite/confirm/page.tsx
new file mode 100644
index 0000000..21fc619
--- /dev/null
+++ b/app/(app)/invite/confirm/page.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import { Suspense } from "react";
+import { useSearchParams } from "next/navigation";
+import { useTranslation } from "../../../contexts/MessagesContext";
+import { inviteVerifyPath } from "../../../../lib/create/confirmLinkPaths";
+import {
+ INVITE_COPY_QUERY,
+ INVITE_COPY_VALUE,
+} from "../../../../lib/create/invitePaths";
+import { ConfirmLinkScreen } from "../../_components/ConfirmLinkScreen";
+
+function InviteConfirmFallback() {
+ const t = useTranslation("pages.invite");
+ return (
+
+
+ {t("loadingFallback")}
+
+
+ );
+}
+
+function InviteConfirmWithParams() {
+ const t = useTranslation("pages.invite");
+ const searchParams = useSearchParams();
+ const token = searchParams.get("token") ?? "";
+ const copy = searchParams.get(INVITE_COPY_QUERY) === INVITE_COPY_VALUE;
+
+ return (
+
+ );
+}
+
+export default function InviteConfirmPage() {
+ return (
+ }>
+
+
+ );
+}
diff --git a/app/(app)/login/confirm/layout.tsx b/app/(app)/login/confirm/layout.tsx
new file mode 100644
index 0000000..91dd9b9
--- /dev/null
+++ b/app/(app)/login/confirm/layout.tsx
@@ -0,0 +1,17 @@
+import type { Metadata } from "next";
+import messages from "../../../../messages/en/index";
+import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata";
+
+export const metadata: Metadata = routeMetadata("/login/confirm", {
+ title: messages.metadata.loginConfirm.title,
+ description: messages.metadata.loginConfirm.description,
+ robots: NO_INDEX_ROBOTS,
+});
+
+export default function LoginConfirmLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return children;
+}
diff --git a/app/(app)/login/confirm/page.tsx b/app/(app)/login/confirm/page.tsx
new file mode 100644
index 0000000..7e164f3
--- /dev/null
+++ b/app/(app)/login/confirm/page.tsx
@@ -0,0 +1,48 @@
+"use client";
+
+import { Suspense } from "react";
+import { useSearchParams } from "next/navigation";
+import { useTranslation } from "../../../contexts/MessagesContext";
+import { magicLinkVerifyPath } from "../../../../lib/create/confirmLinkPaths";
+import { ConfirmLinkScreen } from "../../_components/ConfirmLinkScreen";
+
+function LoginConfirmFallback() {
+ const t = useTranslation("pages.login");
+ return (
+
+
+ {t("loadingFallback")}
+
+
+ );
+}
+
+function LoginConfirmWithParams() {
+ const t = useTranslation("pages.login");
+ const searchParams = useSearchParams();
+ const token = searchParams.get("token") ?? "";
+
+ return (
+
+ );
+}
+
+export default function LoginConfirmPage() {
+ return (
+ }>
+
+
+ );
+}
diff --git a/app/api/auth/magic-link/verify/route.ts b/app/api/auth/magic-link/verify/route.ts
index d5948bf..887a6da 100644
--- a/app/api/auth/magic-link/verify/route.ts
+++ b/app/api/auth/magic-link/verify/route.ts
@@ -1,4 +1,4 @@
-import { NextRequest, NextResponse } from "next/server";
+import { NextRequest } from "next/server";
import type { Prisma } from "@prisma/client";
import { prisma } from "../../../../../lib/server/db";
import {
@@ -16,12 +16,25 @@ import {
getOrCreateRequestId,
logRouteError,
} from "../../../../../lib/server/requestId";
+import { redirectWithRequestId } from "../../../../../lib/server/redirectWithRequestId";
+import { readOneTimeLinkToken } from "../../../../../lib/server/oneTimeLinkToken";
import { safeInternalPath } from "../../../../../lib/safeInternalPath";
-import { getPublicOrigin } from "../../../../../lib/server/publicOrigin";
+import { magicLinkConfirmPath } from "../../../../../lib/create/confirmLinkPaths";
const SCOPE = "auth.magicLink.verify";
export async function GET(request: NextRequest) {
+ return handleMagicLinkVerify(request, "get");
+}
+
+export async function POST(request: NextRequest) {
+ return handleMagicLinkVerify(request, "post");
+}
+
+async function handleMagicLinkVerify(
+ request: NextRequest,
+ mode: "get" | "post",
+) {
const requestId = getOrCreateRequestId(request);
if (!isDatabaseConfigured()) {
@@ -31,12 +44,13 @@ export async function GET(request: NextRequest) {
}
try {
- const token = request.nextUrl.searchParams.get("token");
- if (!token || token.length < 10) {
+ const token = await readOneTimeLinkToken(request);
+ if (!token) {
return redirectWithRequestId(
request,
"/login?error=invalid_link",
requestId,
+ redirectStatus(mode),
);
}
@@ -45,7 +59,12 @@ export async function GET(request: NextRequest) {
pepper = getSessionPepper();
} catch (err) {
logRouteError(SCOPE, requestId, err, { phase: "getSessionPepper" });
- return redirectWithRequestId(request, "/login?error=server", requestId);
+ return redirectWithRequestId(
+ request,
+ "/login?error=server",
+ requestId,
+ redirectStatus(mode),
+ );
}
const tokenHash = hashSessionToken(token, pepper);
@@ -59,6 +78,7 @@ export async function GET(request: NextRequest) {
request,
"/login?error=invalid_link",
requestId,
+ redirectStatus(mode),
);
}
@@ -67,6 +87,15 @@ export async function GET(request: NextRequest) {
request,
"/login?error=expired_link",
requestId,
+ redirectStatus(mode),
+ );
+ }
+
+ if (mode === "get") {
+ return redirectWithRequestId(
+ request,
+ magicLinkConfirmPath(token),
+ requestId,
);
}
@@ -97,19 +126,18 @@ export async function GET(request: NextRequest) {
await setSessionCookie(sessionToken, expiresAt);
const dest = safeInternalPath(row.nextPath);
- return redirectWithRequestId(request, dest, requestId);
+ return redirectWithRequestId(request, dest, requestId, 303);
} catch (err) {
logRouteError(SCOPE, requestId, err);
- return redirectWithRequestId(request, "/login?error=server", requestId);
+ return redirectWithRequestId(
+ request,
+ "/login?error=server",
+ requestId,
+ redirectStatus(mode),
+ );
}
}
-function redirectWithRequestId(
- request: NextRequest,
- path: string,
- requestId: string,
-): NextResponse {
- const res = NextResponse.redirect(new URL(path, getPublicOrigin(request)));
- res.headers.set(REQUEST_ID_HEADER, requestId);
- return res;
+function redirectStatus(mode: "get" | "post"): 303 | 307 {
+ return mode === "post" ? 303 : 307;
}
diff --git a/app/api/invites/rule-stakeholder/verify/route.ts b/app/api/invites/rule-stakeholder/verify/route.ts
index c36a562..48c295b 100644
--- a/app/api/invites/rule-stakeholder/verify/route.ts
+++ b/app/api/invites/rule-stakeholder/verify/route.ts
@@ -1,4 +1,4 @@
-import { NextRequest, NextResponse } from "next/server";
+import { NextRequest } from "next/server";
import { prisma } from "../../../../../lib/server/db";
import {
getSessionPepper,
@@ -16,7 +16,9 @@ import {
getSessionUser,
setSessionCookie,
} from "../../../../../lib/server/session";
-import { getPublicOrigin } from "../../../../../lib/server/publicOrigin";
+import { redirectWithRequestId } from "../../../../../lib/server/redirectWithRequestId";
+import { readOneTimeLinkToken } from "../../../../../lib/server/oneTimeLinkToken";
+import { inviteConfirmPath } from "../../../../../lib/create/confirmLinkPaths";
import {
INVITE_COPY_QUERY,
INVITE_COPY_VALUE,
@@ -27,6 +29,17 @@ import {
const SCOPE = "invites.ruleStakeholder.verify";
export async function GET(request: NextRequest) {
+ return handleStakeholderInviteVerify(request, "get");
+}
+
+export async function POST(request: NextRequest) {
+ return handleStakeholderInviteVerify(request, "post");
+}
+
+async function handleStakeholderInviteVerify(
+ request: NextRequest,
+ mode: "get" | "post",
+) {
const requestId = getOrCreateRequestId(request);
if (!isDatabaseConfigured()) {
@@ -36,12 +49,13 @@ export async function GET(request: NextRequest) {
}
try {
- const token = request.nextUrl.searchParams.get("token");
- if (!token || token.length < 10) {
+ const token = await readOneTimeLinkToken(request);
+ if (!token) {
return redirectWithRequestId(
request,
"/login?error=invalid_link",
requestId,
+ redirectStatus(mode),
);
}
@@ -50,10 +64,17 @@ export async function GET(request: NextRequest) {
pepper = getSessionPepper();
} catch (err) {
logRouteError(SCOPE, requestId, err, { phase: "getSessionPepper" });
- return redirectWithRequestId(request, "/login?error=server", requestId);
+ return redirectWithRequestId(
+ request,
+ "/login?error=server",
+ requestId,
+ redirectStatus(mode),
+ );
}
const tokenHash = hashSessionToken(token, pepper);
+ const copy =
+ request.nextUrl.searchParams.get(INVITE_COPY_QUERY) === INVITE_COPY_VALUE;
const row = await prisma.ruleStakeholder.findUnique({
where: { inviteTokenHash: tokenHash },
@@ -62,18 +83,16 @@ export async function GET(request: NextRequest) {
email: true,
ruleId: true,
inviteExpiresAt: true,
+ acceptedAt: true,
},
});
- if (
- !row ||
- !row.inviteExpiresAt ||
- row.inviteExpiresAt < new Date()
- ) {
+ if (!row) {
return redirectWithRequestId(
request,
inviteExpiredPath(token),
requestId,
+ redirectStatus(mode),
);
}
@@ -86,6 +105,43 @@ export async function GET(request: NextRequest) {
request,
"/login?error=stakeholder_wrong_account",
requestId,
+ redirectStatus(mode),
+ );
+ }
+
+ const dest = invitedRulePath(row.ruleId, { copy });
+
+ if (row.acceptedAt) {
+ if (existingSession) {
+ return redirectWithRequestId(
+ request,
+ dest,
+ requestId,
+ redirectStatus(mode),
+ );
+ }
+ return redirectWithRequestId(
+ request,
+ inviteExpiredPath(token),
+ requestId,
+ redirectStatus(mode),
+ );
+ }
+
+ if (!row.inviteExpiresAt || row.inviteExpiresAt < new Date()) {
+ return redirectWithRequestId(
+ request,
+ inviteExpiredPath(token),
+ requestId,
+ redirectStatus(mode),
+ );
+ }
+
+ if (mode === "get") {
+ return redirectWithRequestId(
+ request,
+ inviteConfirmPath(token, { copy }),
+ requestId,
);
}
@@ -100,8 +156,6 @@ export async function GET(request: NextRequest) {
data: {
userId: user.id,
acceptedAt: new Date(),
- inviteTokenHash: null,
- inviteExpiresAt: null,
},
});
@@ -110,22 +164,18 @@ export async function GET(request: NextRequest) {
);
await setSessionCookie(sessionToken, expiresAt);
- const copy =
- request.nextUrl.searchParams.get(INVITE_COPY_QUERY) === INVITE_COPY_VALUE;
- const dest = invitedRulePath(row.ruleId, { copy });
- return redirectWithRequestId(request, dest, requestId);
+ return redirectWithRequestId(request, dest, requestId, 303);
} catch (err) {
logRouteError(SCOPE, requestId, err);
- return redirectWithRequestId(request, "/login?error=server", requestId);
+ return redirectWithRequestId(
+ request,
+ "/login?error=server",
+ requestId,
+ redirectStatus(mode),
+ );
}
}
-function redirectWithRequestId(
- request: NextRequest,
- path: string,
- requestId: string,
-): NextResponse {
- const res = NextResponse.redirect(new URL(path, getPublicOrigin(request)));
- res.headers.set(REQUEST_ID_HEADER, requestId);
- return res;
+function redirectStatus(mode: "get" | "post"): 303 | 307 {
+ return mode === "post" ? 303 : 307;
}
diff --git a/app/api/rules/[id]/stakeholders/[stakeholderId]/resend/route.ts b/app/api/rules/[id]/stakeholders/[stakeholderId]/resend/route.ts
index 61618de..4ca068e 100644
--- a/app/api/rules/[id]/stakeholders/[stakeholderId]/resend/route.ts
+++ b/app/api/rules/[id]/stakeholders/[stakeholderId]/resend/route.ts
@@ -46,6 +46,7 @@ export const POST = apiRoute(
email: true,
inviteTokenHash: true,
inviteExpiresAt: true,
+ acceptedAt: true,
rule: { select: { userId: true, title: true, summary: true, document: true } },
},
});
@@ -56,7 +57,7 @@ export const POST = apiRoute(
if (row.rule.userId !== user.id) {
return forbidden();
}
- if (row.inviteTokenHash === null) {
+ if (row.acceptedAt) {
return errorJson(
"validation_error",
"This stakeholder has already accepted the invite",
diff --git a/app/api/rules/[id]/stakeholders/route.ts b/app/api/rules/[id]/stakeholders/route.ts
index 13840be..106274b 100644
--- a/app/api/rules/[id]/stakeholders/route.ts
+++ b/app/api/rules/[id]/stakeholders/route.ts
@@ -61,7 +61,6 @@ export const GET = apiRoute(
email: true,
invitedAt: true,
acceptedAt: true,
- inviteTokenHash: true,
},
});
@@ -72,7 +71,7 @@ export const GET = apiRoute(
invitedAt: r.invitedAt.toISOString(),
acceptedAt: r.acceptedAt?.toISOString() ?? null,
status:
- r.inviteTokenHash !== null ? ("pending" as const) : ("accepted" as const),
+ r.acceptedAt != null ? ("accepted" as const) : ("pending" as const),
})),
});
},
diff --git a/app/api/user/email-change/verify/route.ts b/app/api/user/email-change/verify/route.ts
index 4e6a08f..fa09b09 100644
--- a/app/api/user/email-change/verify/route.ts
+++ b/app/api/user/email-change/verify/route.ts
@@ -1,4 +1,4 @@
-import { NextRequest, NextResponse } from "next/server";
+import { NextRequest } from "next/server";
import { prisma } from "../../../../../lib/server/db";
import {
getSessionPepper,
@@ -16,11 +16,24 @@ import {
getOrCreateRequestId,
logRouteError,
} from "../../../../../lib/server/requestId";
-import { getPublicOrigin } from "../../../../../lib/server/publicOrigin";
+import { redirectWithRequestId } from "../../../../../lib/server/redirectWithRequestId";
+import { readOneTimeLinkToken } from "../../../../../lib/server/oneTimeLinkToken";
+import { emailChangeConfirmPath } from "../../../../../lib/create/confirmLinkPaths";
const SCOPE = "user.emailChange.verify";
export async function GET(request: NextRequest) {
+ return handleEmailChangeVerify(request, "get");
+}
+
+export async function POST(request: NextRequest) {
+ return handleEmailChangeVerify(request, "post");
+}
+
+async function handleEmailChangeVerify(
+ request: NextRequest,
+ mode: "get" | "post",
+) {
const requestId = getOrCreateRequestId(request);
if (!isDatabaseConfigured()) {
@@ -30,12 +43,13 @@ export async function GET(request: NextRequest) {
}
try {
- const token = request.nextUrl.searchParams.get("token");
- if (!token || token.length < 10) {
+ const token = await readOneTimeLinkToken(request);
+ if (!token) {
return redirectWithRequestId(
request,
"/profile?error=email_change_invalid",
requestId,
+ redirectStatus(mode),
);
}
@@ -48,6 +62,7 @@ export async function GET(request: NextRequest) {
request,
"/profile?error=email_change_server",
requestId,
+ redirectStatus(mode),
);
}
@@ -61,6 +76,15 @@ export async function GET(request: NextRequest) {
request,
"/profile?error=email_change_expired",
requestId,
+ redirectStatus(mode),
+ );
+ }
+
+ if (mode === "get") {
+ return redirectWithRequestId(
+ request,
+ emailChangeConfirmPath(token),
+ requestId,
);
}
@@ -118,6 +142,7 @@ export async function GET(request: NextRequest) {
request,
"/profile?error=email_change_taken",
requestId,
+ 303,
);
}
if (
@@ -130,6 +155,7 @@ export async function GET(request: NextRequest) {
request,
"/profile?error=email_change_expired",
requestId,
+ 303,
);
}
logRouteError(SCOPE, requestId, err, { phase: "transaction" });
@@ -137,6 +163,7 @@ export async function GET(request: NextRequest) {
request,
"/profile?error=email_change_server",
requestId,
+ 303,
);
}
@@ -151,6 +178,7 @@ export async function GET(request: NextRequest) {
request,
"/profile?email_change=ok",
requestId,
+ 303,
);
} catch (err) {
logRouteError(SCOPE, requestId, err);
@@ -158,16 +186,11 @@ export async function GET(request: NextRequest) {
request,
"/profile?error=email_change_server",
requestId,
+ redirectStatus(mode),
);
}
}
-function redirectWithRequestId(
- request: NextRequest,
- path: string,
- requestId: string,
-): NextResponse {
- const res = NextResponse.redirect(new URL(path, getPublicOrigin(request)));
- res.headers.set(REQUEST_ID_HEADER, requestId);
- return res;
+function redirectStatus(mode: "get" | "post"): 303 | 307 {
+ return mode === "post" ? 303 : 307;
}
diff --git a/app/components/modals/Login/Login.container.tsx b/app/components/modals/Login/Login.container.tsx
index 13210cd..c49a5a8 100644
--- a/app/components/modals/Login/Login.container.tsx
+++ b/app/components/modals/Login/Login.container.tsx
@@ -76,6 +76,13 @@ const LoginContainer = memo(
emailField.focus();
return;
}
+ const submitButton = dialog.querySelector(
+ 'button[type="submit"]:not([disabled])',
+ );
+ if (submitButton) {
+ submitButton.focus();
+ return;
+ }
const focusableElements = dialog.querySelectorAll(focusableSelector);
const firstElement = focusableElements[0] as HTMLElement;
if (firstElement) {
diff --git a/lib/create/confirmLinkPaths.ts b/lib/create/confirmLinkPaths.ts
new file mode 100644
index 0000000..39baaed
--- /dev/null
+++ b/lib/create/confirmLinkPaths.ts
@@ -0,0 +1,39 @@
+import { INVITE_COPY_QUERY, INVITE_COPY_VALUE } from "./invitePaths";
+
+export function magicLinkConfirmPath(token: string): string {
+ return `/login/confirm?token=${encodeURIComponent(token)}`;
+}
+
+export function magicLinkVerifyPath(token: string): string {
+ return `/api/auth/magic-link/verify?token=${encodeURIComponent(token)}`;
+}
+
+export function inviteConfirmPath(
+ token: string,
+ opts?: { copy?: boolean },
+): string {
+ const params = new URLSearchParams({ token });
+ if (opts?.copy) {
+ params.set(INVITE_COPY_QUERY, INVITE_COPY_VALUE);
+ }
+ return `/invite/confirm?${params.toString()}`;
+}
+
+export function inviteVerifyPath(
+ token: string,
+ opts?: { copy?: boolean },
+): string {
+ const params = new URLSearchParams({ token });
+ if (opts?.copy) {
+ params.set(INVITE_COPY_QUERY, INVITE_COPY_VALUE);
+ }
+ return `/api/invites/rule-stakeholder/verify?${params.toString()}`;
+}
+
+export function emailChangeConfirmPath(token: string): string {
+ return `/email-change/confirm?token=${encodeURIComponent(token)}`;
+}
+
+export function emailChangeVerifyPath(token: string): string {
+ return `/api/user/email-change/verify?token=${encodeURIComponent(token)}`;
+}
diff --git a/lib/navigationChromelessPath.ts b/lib/navigationChromelessPath.ts
index 95366e8..4b0af38 100644
--- a/lib/navigationChromelessPath.ts
+++ b/lib/navigationChromelessPath.ts
@@ -11,7 +11,9 @@ export function isChromelessNavigationPath(
if (
pathname.startsWith("/create") ||
pathname === "/login" ||
- pathname.startsWith("/invite")
+ pathname.startsWith("/login/") ||
+ pathname.startsWith("/invite") ||
+ pathname.startsWith("/email-change")
) {
return true;
}
diff --git a/lib/server/oneTimeLinkToken.ts b/lib/server/oneTimeLinkToken.ts
new file mode 100644
index 0000000..239ac36
--- /dev/null
+++ b/lib/server/oneTimeLinkToken.ts
@@ -0,0 +1,42 @@
+import type { NextRequest } from "next/server";
+import { readLimitedJson } from "./validation/requestBody";
+
+export const ONE_TIME_LINK_TOKEN_MIN_LENGTH = 10;
+
+function usableToken(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ if (value.length < ONE_TIME_LINK_TOKEN_MIN_LENGTH) return null;
+ return value;
+}
+
+/**
+ * One-time email links put the secret in the query string. Confirm pages POST
+ * that same URL (and a hidden field) so a GET from a mail scanner spends nothing.
+ */
+export async function readOneTimeLinkToken(
+ request: NextRequest,
+): Promise {
+ const fromQuery = usableToken(request.nextUrl.searchParams.get("token"));
+ if (fromQuery) return fromQuery;
+
+ if (request.method === "GET" || request.method === "HEAD") {
+ return null;
+ }
+
+ const contentType = request.headers.get("content-type") ?? "";
+ if (contentType.includes("application/json")) {
+ const parsed = await readLimitedJson(request);
+ if (parsed.ok === false) return null;
+ if (parsed.value && typeof parsed.value === "object" && "token" in parsed.value) {
+ return usableToken((parsed.value as { token: unknown }).token);
+ }
+ return null;
+ }
+
+ try {
+ const form = await request.formData();
+ return usableToken(form.get("token"));
+ } catch {
+ return null;
+ }
+}
diff --git a/lib/server/pruneExpiredRecords.ts b/lib/server/pruneExpiredRecords.ts
index e6f0e03..4bd2f16 100644
--- a/lib/server/pruneExpiredRecords.ts
+++ b/lib/server/pruneExpiredRecords.ts
@@ -47,8 +47,8 @@ export async function deleteExpiredWorkshopInquiries(
*
* Does not delete stakeholder rows, accounts, or invitation token hashes.
* Verify already rejects an invite once `inviteExpiresAt` has passed. The
- * hash is how `/invite/expired` finds that row to send a new link, and a
- * null hash is treated as an accepted invite.
+ * hash is how `/invite/expired` finds that row to send a new link, including
+ * after the original link was used. `acceptedAt` marks an accepted invite.
*/
export async function pruneExpiredRecords(
db: PruneStore,
diff --git a/lib/server/redirectWithRequestId.ts b/lib/server/redirectWithRequestId.ts
new file mode 100644
index 0000000..19a5a7d
--- /dev/null
+++ b/lib/server/redirectWithRequestId.ts
@@ -0,0 +1,14 @@
+import { NextRequest, NextResponse } from "next/server";
+import { REQUEST_ID_HEADER } from "./requestId";
+import { getPublicOrigin } from "./publicOrigin";
+
+export function redirectWithRequestId(
+ request: NextRequest,
+ path: string,
+ requestId: string,
+ status: 303 | 307 = 307,
+): NextResponse {
+ const res = NextResponse.redirect(new URL(path, getPublicOrigin(request)), status);
+ res.headers.set(REQUEST_ID_HEADER, requestId);
+ return res;
+}
diff --git a/messages/en/metadata.json b/messages/en/metadata.json
index 6e6ba24..d7d8339 100644
--- a/messages/en/metadata.json
+++ b/messages/en/metadata.json
@@ -53,14 +53,26 @@
"title": "Log in",
"description": "Enter your email and we'll send you a login link. No password needed."
},
+ "loginConfirm": {
+ "title": "Open this login link",
+ "description": "Press continue to log in."
+ },
"invite": {
"title": "Invitation",
"description": "Read a CommunityRule you were invited to see."
},
+ "inviteConfirm": {
+ "title": "Open this invitation",
+ "description": "Press continue to read the Rule you were invited to."
+ },
"inviteExpired": {
"title": "This link has expired",
"description": "Ask for a new invitation link to read the Rule."
},
+ "emailChangeConfirm": {
+ "title": "Confirm your new email",
+ "description": "Press continue to change the login address on this account."
+ },
"profile": {
"title": "Profile",
"description": "Manage the Rules you have finished, saved progress, and your account."
diff --git a/messages/en/pages/invite.json b/messages/en/pages/invite.json
index c7afd8c..9adf49d 100644
--- a/messages/en/pages/invite.json
+++ b/messages/en/pages/invite.json
@@ -33,6 +33,11 @@
"confirm": "Make a copy",
"copyFailed": "Could not make a copy. Try again.",
"nameRequired": "Add your community’s name to continue.",
+ "confirmTitle": "Open this invitation",
+ "confirmDescription": "Press continue to read the Rule you were invited to. This keeps the link unused until you choose to open it.",
+ "confirmButton": "Continue",
+ "confirmMissingTitle": "This invitation link is missing",
+ "confirmMissingDescription": "Ask the person who invited you to send the invitation again.",
"expiredTitle": "This link has expired",
"expiredDescription": "Enter the email the invitation was sent to. We’ll send a new link that works for 60 minutes.",
"emailLabel": "Email address",
diff --git a/messages/en/pages/login.json b/messages/en/pages/login.json
index d969a6f..ab60305 100644
--- a/messages/en/pages/login.json
+++ b/messages/en/pages/login.json
@@ -20,6 +20,12 @@
"sentBody": "We sent a login link to {email}. It works for {minutes} minutes.",
"expiredTitle": "That link has expired",
"expiredBody": "That login link has expired or was already used. Send a new one.",
+ "confirmTitle": "Open this login link",
+ "confirmDescription": "Press continue to log in. This keeps the link unused until you choose to open it.",
+ "confirmButton": "Continue",
+ "confirmMissingTitle": "This login link is missing",
+ "confirmMissingDescription": "Request a new login link from the login page.",
+ "confirmMissingButton": "Go to log in",
"legalPrefix": "By continuing, you agree to our ",
"legalAnd": " and ",
"legalSuffix": ".",
diff --git a/messages/en/pages/profile.json b/messages/en/pages/profile.json
index cc55fc4..637df87 100644
--- a/messages/en/pages/profile.json
+++ b/messages/en/pages/profile.json
@@ -55,6 +55,12 @@
"emailChangeSubmit": "Send confirmation link",
"emailChangeConfirmationClose": "Close",
"emailChangeSuccess": "Your account email was updated.",
+ "emailChangeConfirmTitle": "Confirm your new email",
+ "emailChangeConfirmDescription": "Press continue to change the login address on this account. This keeps the link unused until you choose to open it.",
+ "emailChangeConfirmButton": "Confirm email",
+ "emailChangeConfirmMissingTitle": "This confirmation link is missing",
+ "emailChangeConfirmMissingDescription": "Start a new email change from your profile.",
+ "emailChangeConfirmMissingButton": "Go to profile",
"emailChangeVerifyExpired": "That confirmation link expired or was already used. Start a new email change from your profile.",
"emailChangeVerifyInvalid": "That confirmation link is not valid.",
"emailChangeVerifyTaken": "That address was claimed by another account while you were confirming. Try a different email.",
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 6999e83..da78f2f 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -159,7 +159,8 @@ model RuleStakeholder {
/// Set when the invitee completes the verify link (same account as `email`).
userId String?
user User? @relation("RuleStakeholderUser", fields: [userId], references: [id], onDelete: SetNull)
- /// One-time invite token (hashed); null after accept or revoke path (consume on verify).
+ /// One-time invite token (hashed). Kept after accept so a used link can still
+ /// send a new one from the expired screen. `acceptedAt` is the accepted marker.
inviteTokenHash String? @unique
inviteExpiresAt DateTime?
invitedAt DateTime @default(now())
diff --git a/tests/components/ConfirmLinkScreen.test.tsx b/tests/components/ConfirmLinkScreen.test.tsx
new file mode 100644
index 0000000..17aa05a
--- /dev/null
+++ b/tests/components/ConfirmLinkScreen.test.tsx
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { renderWithProviders as render, screen } from "../utils/test-utils";
+import "@testing-library/jest-dom/vitest";
+import { ConfirmLinkScreen } from "../../app/(app)/_components/ConfirmLinkScreen";
+
+const { navMock } = vi.hoisted(() => ({
+ navMock: {
+ push: vi.fn(),
+ },
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ push: navMock.push,
+ replace: vi.fn(),
+ prefetch: vi.fn(),
+ refresh: vi.fn(),
+ back: vi.fn(),
+ forward: vi.fn(),
+ }),
+ useSearchParams: () => new URLSearchParams(),
+ usePathname: () => "/login/confirm",
+}));
+
+const baseProps = {
+ title: "Open this login link",
+ description: "Press continue to log in.",
+ buttonLabel: "Continue",
+ action: "/api/auth/magic-link/verify?token=abcdefghijkl",
+ token: "abcdefghijkl",
+ backHref: "/",
+ backLabel: "← Back to home",
+ missingTitle: "This login link is missing",
+ missingDescription: "Request a new login link from the login page.",
+ missingHref: "/login",
+ missingButtonLabel: "Go to log in",
+};
+
+describe("ConfirmLinkScreen", () => {
+ beforeEach(() => {
+ navMock.push.mockReset();
+ });
+
+ it("posts the token when Continue is pressed", () => {
+ const { container } = render();
+
+ expect(
+ screen.getByRole("heading", { name: "Open this login link" }),
+ ).toBeInTheDocument();
+ const form = container.querySelector("form");
+ expect(form).toHaveAttribute("method", "POST");
+ expect(form).toHaveAttribute(
+ "action",
+ "/api/auth/magic-link/verify?token=abcdefghijkl",
+ );
+ expect(container.querySelector('input[name="token"]')).toHaveValue(
+ "abcdefghijkl",
+ );
+ expect(screen.getByRole("button", { name: "Continue" })).toHaveAttribute(
+ "type",
+ "submit",
+ );
+ });
+
+ it("offers a way back when the token is missing", () => {
+ render();
+
+ expect(
+ screen.getByRole("heading", { name: "This login link is missing" }),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Continue" })).not.toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Go to log in" })).toHaveAttribute(
+ "href",
+ "/login",
+ );
+ });
+});
diff --git a/tests/unit/authMagicLinkVerifyRoute.test.ts b/tests/unit/authMagicLinkVerifyRoute.test.ts
index b16f634..8852dcd 100644
--- a/tests/unit/authMagicLinkVerifyRoute.test.ts
+++ b/tests/unit/authMagicLinkVerifyRoute.test.ts
@@ -34,10 +34,13 @@ vi.mock("../../lib/server/db", () => ({
user: {
upsert: (...args: unknown[]) => upsertMock(...args),
},
+ ruleDraft: {
+ upsert: vi.fn(),
+ },
},
}));
-import { GET } from "../../app/api/auth/magic-link/verify/route";
+import { GET, POST } from "../../app/api/auth/magic-link/verify/route";
beforeEach(() => {
isDatabaseConfiguredMock.mockReset();
@@ -87,5 +90,54 @@ describe("GET /api/auth/magic-link/verify", () => {
const res = await GET(getWithToken("a-token-value-long-enough"));
expect(res.status).toBe(307);
expect(res.headers.get("location")).toContain("error=expired_link");
+ expect(deleteMock).not.toHaveBeenCalled();
+ });
+
+ it("redirects a valid token to the confirm page without spending it", async () => {
+ const token = "a-token-value-long-enough";
+ findUniqueMock.mockResolvedValue({
+ id: "row-1",
+ email: "a@b.c",
+ expiresAt: new Date(Date.now() + 60_000),
+ nextPath: "/create/review",
+ draftPayload: null,
+ });
+ const res = await GET(getWithToken(token));
+ expect(res.status).toBe(307);
+ expect(res.headers.get("location")).toContain("/login/confirm");
+ expect(res.headers.get("location")).toContain(encodeURIComponent(token));
+ expect(deleteMock).not.toHaveBeenCalled();
+ expect(upsertMock).not.toHaveBeenCalled();
+ expect(createSessionForUserMock).not.toHaveBeenCalled();
+ expect(setSessionCookieMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("POST /api/auth/magic-link/verify", () => {
+ it("spends a valid token, starts a session, and redirects", async () => {
+ findUniqueMock.mockResolvedValue({
+ id: "row-1",
+ email: "a@b.c",
+ expiresAt: new Date(Date.now() + 60_000),
+ nextPath: "/create/review",
+ draftPayload: null,
+ });
+ upsertMock.mockResolvedValue({ id: "u1", email: "a@b.c" });
+ createSessionForUserMock.mockResolvedValue({
+ token: "sess",
+ expiresAt: new Date(),
+ });
+
+ const res = await POST(
+ new NextRequest(getWithToken("a-token-value-long-enough").url, {
+ method: "POST",
+ }),
+ );
+
+ expect(res.status).toBe(303);
+ expect(res.headers.get("location")).toContain("/create/review");
+ expect(deleteMock).toHaveBeenCalledWith({ where: { id: "row-1" } });
+ expect(upsertMock).toHaveBeenCalled();
+ expect(setSessionCookieMock).toHaveBeenCalled();
});
});
diff --git a/tests/unit/confirmLinkPaths.test.ts b/tests/unit/confirmLinkPaths.test.ts
new file mode 100644
index 0000000..c80ca57
--- /dev/null
+++ b/tests/unit/confirmLinkPaths.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import {
+ emailChangeConfirmPath,
+ emailChangeVerifyPath,
+ inviteConfirmPath,
+ inviteVerifyPath,
+ magicLinkConfirmPath,
+ magicLinkVerifyPath,
+} from "../../lib/create/confirmLinkPaths";
+
+describe("confirmLinkPaths", () => {
+ it("encodes tokens on confirm and verify URLs", () => {
+ expect(magicLinkConfirmPath("a+b")).toBe("/login/confirm?token=a%2Bb");
+ expect(magicLinkVerifyPath("a+b")).toBe(
+ "/api/auth/magic-link/verify?token=a%2Bb",
+ );
+ expect(emailChangeConfirmPath("a+b")).toBe(
+ "/email-change/confirm?token=a%2Bb",
+ );
+ expect(emailChangeVerifyPath("a+b")).toBe(
+ "/api/user/email-change/verify?token=a%2Bb",
+ );
+ });
+
+ it("keeps copy=1 on invitation confirm and verify URLs", () => {
+ expect(inviteConfirmPath("abc1234567", { copy: true })).toBe(
+ "/invite/confirm?token=abc1234567©=1",
+ );
+ expect(inviteVerifyPath("abc1234567", { copy: true })).toBe(
+ "/api/invites/rule-stakeholder/verify?token=abc1234567©=1",
+ );
+ });
+});
diff --git a/tests/unit/lib/navigationChromelessPath.test.ts b/tests/unit/lib/navigationChromelessPath.test.ts
index cf72948..62204de 100644
--- a/tests/unit/lib/navigationChromelessPath.test.ts
+++ b/tests/unit/lib/navigationChromelessPath.test.ts
@@ -6,7 +6,10 @@ describe("isChromelessNavigationPath", () => {
["/create", true],
["/create/completed", true],
["/login", true],
+ ["/login/confirm", true],
+ ["/invite/confirm", true],
["/invite/expired", true],
+ ["/email-change/confirm", true],
["/invite/rule-1", true],
["/use-cases/mutual-aid-colorado/rule", true],
["/use-cases/food-not-bombs/rule/", true],
diff --git a/tests/unit/oneTimeLinkToken.test.ts b/tests/unit/oneTimeLinkToken.test.ts
new file mode 100644
index 0000000..e6d90a1
--- /dev/null
+++ b/tests/unit/oneTimeLinkToken.test.ts
@@ -0,0 +1,31 @@
+import { NextRequest } from "next/server";
+import { describe, expect, it } from "vitest";
+import { readOneTimeLinkToken } from "../../lib/server/oneTimeLinkToken";
+
+describe("readOneTimeLinkToken", () => {
+ it("reads a token from the query string", async () => {
+ const request = new NextRequest(
+ "https://x.test/api/auth/magic-link/verify?token=abcdefghijkl",
+ );
+ await expect(readOneTimeLinkToken(request)).resolves.toBe("abcdefghijkl");
+ });
+
+ it("returns null for a short query token", async () => {
+ const request = new NextRequest(
+ "https://x.test/api/auth/magic-link/verify?token=short",
+ );
+ await expect(readOneTimeLinkToken(request)).resolves.toBeNull();
+ });
+
+ it("reads a token from a JSON body when the query is empty", async () => {
+ const request = new NextRequest(
+ "https://x.test/api/auth/magic-link/verify",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ token: "abcdefghijkl" }),
+ },
+ );
+ await expect(readOneTimeLinkToken(request)).resolves.toBe("abcdefghijkl");
+ });
+});
diff --git a/tests/unit/ruleStakeholderInviteResendExpiredRoute.test.ts b/tests/unit/ruleStakeholderInviteResendExpiredRoute.test.ts
index 95f9e90..f450be3 100644
--- a/tests/unit/ruleStakeholderInviteResendExpiredRoute.test.ts
+++ b/tests/unit/ruleStakeholderInviteResendExpiredRoute.test.ts
@@ -74,6 +74,41 @@ describe("POST /api/invites/rule-stakeholder/resend", () => {
expect(sendInviteMock).not.toHaveBeenCalled();
});
+ it("rotates the token and sends mail after the original link was used", async () => {
+ findUniqueMock.mockResolvedValueOnce({
+ id: "st-1",
+ email: "inv@example.com",
+ inviteTokenHash: "hash-old",
+ inviteExpiresAt: null,
+ acceptedAt: new Date(),
+ invitedBy: { email: "owner@example.com" },
+ rule: {
+ title: "Juniper Street Food Share",
+ summary: null,
+ document: {},
+ user: { email: "owner@example.com" },
+ },
+ });
+
+ const res = await POST(
+ new NextRequest("https://x.test/api/invites/rule-stakeholder/resend", {
+ method: "POST",
+ body: JSON.stringify({
+ token: "a".repeat(12),
+ email: "inv@example.com",
+ }),
+ headers: { "content-type": "application/json" },
+ }),
+ undefined,
+ );
+ expect(res.status).toBe(200);
+ expect(sendInviteMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ to: "inv@example.com",
+ }),
+ );
+ });
+
it("rotates the token and sends mail when email matches", async () => {
findUniqueMock.mockResolvedValueOnce({
id: "st-1",
diff --git a/tests/unit/ruleStakeholderInviteVerifyRoute.test.ts b/tests/unit/ruleStakeholderInviteVerifyRoute.test.ts
index c99740e..291751c 100644
--- a/tests/unit/ruleStakeholderInviteVerifyRoute.test.ts
+++ b/tests/unit/ruleStakeholderInviteVerifyRoute.test.ts
@@ -35,7 +35,7 @@ vi.mock("../../lib/server/session", () => ({
setSessionCookie: (...args: unknown[]) => setCookieMock(...args),
}));
-import { GET } from "../../app/api/invites/rule-stakeholder/verify/route";
+import { GET, POST } from "../../app/api/invites/rule-stakeholder/verify/route";
beforeEach(() => {
findUniqueMock.mockReset();
@@ -47,31 +47,29 @@ beforeEach(() => {
});
describe("GET /api/invites/rule-stakeholder/verify", () => {
- it("redirects to the rule after a valid token", async () => {
+ it("redirects a valid token to the confirm page without spending it", async () => {
getSessionUserMock.mockResolvedValue(null);
findUniqueMock.mockResolvedValue({
id: "st1",
email: "inv@example.com",
ruleId: "rule-1",
inviteExpiresAt: new Date(Date.now() + 60_000),
+ acceptedAt: null,
});
- upsertMock.mockResolvedValue({ id: "u1", email: "inv@example.com" });
- updateMock.mockResolvedValue({});
- createSessionMock.mockResolvedValue({
- token: "sess",
- expiresAt: new Date(),
- });
+ const token = "x".repeat(12);
const res = await GET(
new NextRequest(
- `https://x.test/api/invites/rule-stakeholder/verify?token=${"x".repeat(12)}`,
+ `https://x.test/api/invites/rule-stakeholder/verify?token=${token}`,
),
);
- expect(res.status).toBeGreaterThanOrEqual(300);
- expect(res.status).toBeLessThan(400);
- expect(res.headers.get("location")).toContain("/invite/rule-1");
- expect(setCookieMock).toHaveBeenCalled();
+ expect(res.status).toBe(307);
+ expect(res.headers.get("location")).toContain("/invite/confirm");
+ expect(res.headers.get("location")).toContain(`token=${token}`);
+ expect(upsertMock).not.toHaveBeenCalled();
+ expect(updateMock).not.toHaveBeenCalled();
+ expect(setCookieMock).not.toHaveBeenCalled();
});
it("redirects to login when another user is already signed in", async () => {
@@ -84,6 +82,7 @@ describe("GET /api/invites/rule-stakeholder/verify", () => {
email: "inv@example.com",
ruleId: "rule-1",
inviteExpiresAt: new Date(Date.now() + 60_000),
+ acceptedAt: null,
});
const res = await GET(
@@ -105,6 +104,7 @@ describe("GET /api/invites/rule-stakeholder/verify", () => {
email: "inv@example.com",
ruleId: "rule-1",
inviteExpiresAt: new Date(Date.now() - 60_000),
+ acceptedAt: null,
});
const token = "z".repeat(12);
@@ -119,19 +119,14 @@ describe("GET /api/invites/rule-stakeholder/verify", () => {
expect(upsertMock).not.toHaveBeenCalled();
});
- it("keeps copy=1 on the invited view after a valid token", async () => {
+ it("keeps copy=1 on the confirm page after a valid token", async () => {
getSessionUserMock.mockResolvedValue(null);
findUniqueMock.mockResolvedValue({
id: "st1",
email: "inv@example.com",
ruleId: "rule-1",
inviteExpiresAt: new Date(Date.now() + 60_000),
- });
- upsertMock.mockResolvedValue({ id: "u1", email: "inv@example.com" });
- updateMock.mockResolvedValue({});
- createSessionMock.mockResolvedValue({
- token: "sess",
- expiresAt: new Date(),
+ acceptedAt: null,
});
const res = await GET(
@@ -140,6 +135,117 @@ describe("GET /api/invites/rule-stakeholder/verify", () => {
),
);
+ expect(res.headers.get("location")).toContain("/invite/confirm");
+ expect(res.headers.get("location")).toContain("copy=1");
+ expect(setCookieMock).not.toHaveBeenCalled();
+ });
+
+ it("opens the Rule when a used link is opened by the signed-in invitee", async () => {
+ getSessionUserMock.mockResolvedValue({
+ id: "u1",
+ email: "inv@example.com",
+ });
+ findUniqueMock.mockResolvedValue({
+ id: "st1",
+ email: "inv@example.com",
+ ruleId: "rule-1",
+ inviteExpiresAt: null,
+ acceptedAt: new Date(),
+ });
+
+ const res = await GET(
+ new NextRequest(
+ `https://x.test/api/invites/rule-stakeholder/verify?token=${"x".repeat(12)}`,
+ ),
+ );
+
+ expect(res.headers.get("location")).toContain("/invite/rule-1");
+ expect(upsertMock).not.toHaveBeenCalled();
+ expect(setCookieMock).not.toHaveBeenCalled();
+ });
+
+ it("sends a used link to the expired screen when the invitee is signed out", async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ findUniqueMock.mockResolvedValue({
+ id: "st1",
+ email: "inv@example.com",
+ ruleId: "rule-1",
+ inviteExpiresAt: null,
+ acceptedAt: new Date(),
+ });
+ const token = "z".repeat(12);
+
+ const res = await GET(
+ new NextRequest(
+ `https://x.test/api/invites/rule-stakeholder/verify?token=${token}`,
+ ),
+ );
+
+ expect(res.headers.get("location")).toContain("/invite/expired");
+ expect(res.headers.get("location")).toContain(`token=${token}`);
+ expect(upsertMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("POST /api/invites/rule-stakeholder/verify", () => {
+ it("spends a valid token, keeps the hash, and redirects to the Rule", async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ findUniqueMock.mockResolvedValue({
+ id: "st1",
+ email: "inv@example.com",
+ ruleId: "rule-1",
+ inviteExpiresAt: new Date(Date.now() + 60_000),
+ acceptedAt: null,
+ });
+ upsertMock.mockResolvedValue({ id: "u1", email: "inv@example.com" });
+ updateMock.mockResolvedValue({});
+ createSessionMock.mockResolvedValue({
+ token: "sess",
+ expiresAt: new Date(),
+ });
+
+ const res = await POST(
+ new NextRequest(
+ `https://x.test/api/invites/rule-stakeholder/verify?token=${"x".repeat(12)}`,
+ { method: "POST" },
+ ),
+ );
+
+ expect(res.status).toBe(303);
+ expect(res.headers.get("location")).toContain("/invite/rule-1");
+ expect(setCookieMock).toHaveBeenCalled();
+ expect(updateMock).toHaveBeenCalledWith({
+ where: { id: "st1" },
+ data: {
+ userId: "u1",
+ acceptedAt: expect.any(Date),
+ },
+ });
+ });
+
+ it("keeps copy=1 on the invited view after confirm", async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ findUniqueMock.mockResolvedValue({
+ id: "st1",
+ email: "inv@example.com",
+ ruleId: "rule-1",
+ inviteExpiresAt: new Date(Date.now() + 60_000),
+ acceptedAt: null,
+ });
+ upsertMock.mockResolvedValue({ id: "u1", email: "inv@example.com" });
+ updateMock.mockResolvedValue({});
+ createSessionMock.mockResolvedValue({
+ token: "sess",
+ expiresAt: new Date(),
+ });
+
+ const res = await POST(
+ new NextRequest(
+ `https://x.test/api/invites/rule-stakeholder/verify?token=${"x".repeat(12)}©=1`,
+ { method: "POST" },
+ ),
+ );
+
expect(res.headers.get("location")).toContain("/invite/rule-1");
expect(res.headers.get("location")).toContain("copy=1");
});
diff --git a/tests/unit/rulesStakeholderMutationsRoute.test.ts b/tests/unit/rulesStakeholderMutationsRoute.test.ts
index ca33386..c857600 100644
--- a/tests/unit/rulesStakeholderMutationsRoute.test.ts
+++ b/tests/unit/rulesStakeholderMutationsRoute.test.ts
@@ -192,8 +192,9 @@ describe("POST /api/rules/[id]/stakeholders/[stakeholderId]/resend", () => {
findFirstStakeholderMock.mockResolvedValueOnce({
id: "st-1",
email: "inv@example.com",
- inviteTokenHash: null,
+ inviteTokenHash: "kept-after-accept",
inviteExpiresAt: null,
+ acceptedAt: new Date("2026-01-03T00:00:00Z"),
rule: { userId: owner.id, title: "My rule" },
});
const res = await POST_RESEND(
@@ -214,6 +215,7 @@ describe("POST /api/rules/[id]/stakeholders/[stakeholderId]/resend", () => {
email: "inv@example.com",
inviteTokenHash: "old-hash",
inviteExpiresAt: new Date("2026-01-01T00:00:00Z"),
+ acceptedAt: null,
rule: { userId: owner.id, title: "My rule" },
});
const res = await POST_RESEND(
diff --git a/tests/unit/rulesStakeholdersRoutes.test.ts b/tests/unit/rulesStakeholdersRoutes.test.ts
index 29722b7..35b9e5b 100644
--- a/tests/unit/rulesStakeholdersRoutes.test.ts
+++ b/tests/unit/rulesStakeholdersRoutes.test.ts
@@ -61,7 +61,7 @@ describe("GET /api/rules/[id]/stakeholders", () => {
email: "x@y.z",
invitedAt: new Date("2026-01-02T00:00:00Z"),
acceptedAt: new Date("2026-01-03T00:00:00Z"),
- inviteTokenHash: null,
+ inviteTokenHash: "kept-after-accept",
},
]);
const res = await GET(
diff --git a/tests/unit/userEmailChangeVerifyRoute.test.ts b/tests/unit/userEmailChangeVerifyRoute.test.ts
index 46d95e7..f046f69 100644
--- a/tests/unit/userEmailChangeVerifyRoute.test.ts
+++ b/tests/unit/userEmailChangeVerifyRoute.test.ts
@@ -36,7 +36,7 @@ vi.mock("../../lib/server/db", () => ({
},
}));
-import { GET } from "../../app/api/user/email-change/verify/route";
+import { GET, POST } from "../../app/api/user/email-change/verify/route";
beforeEach(() => {
isDatabaseConfiguredMock.mockReset();
@@ -103,8 +103,37 @@ describe("GET /api/user/email-change/verify", () => {
const res = await GET(getWithToken("long-enough-token"));
expect(res.status).toBe(307);
expect(res.headers.get("location")).toContain("error=email_change_expired");
+ expect(transactionMock).not.toHaveBeenCalled();
});
+ it("redirects a valid token to the confirm page without changing the address", async () => {
+ isDatabaseConfiguredMock.mockReturnValue(true);
+ emailChangeFindUniqueMock.mockResolvedValueOnce({
+ id: "tok1",
+ userId: "u1",
+ newEmail: "new@x.com",
+ expiresAt: new Date(Date.now() + 60_000),
+ tokenHash: "token-hash",
+ });
+ const token = "long-enough-token";
+ const res = await GET(getWithToken(token));
+ expect(res.status).toBe(307);
+ expect(res.headers.get("location")).toContain("/email-change/confirm");
+ expect(res.headers.get("location")).toContain(encodeURIComponent(token));
+ expect(transactionMock).not.toHaveBeenCalled();
+ expect(getValidatedSessionTokenHashForUserMock).not.toHaveBeenCalled();
+ expect(createSessionForUserMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("POST /api/user/email-change/verify", () => {
+ function postWithToken(token: string) {
+ return new NextRequest(
+ `https://x.test/api/user/email-change/verify?token=${encodeURIComponent(token)}`,
+ { method: "POST" },
+ );
+ }
+
it("redirects with email_change_taken when another user claims the email in the transaction", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
const future = new Date(Date.now() + 60_000);
@@ -137,8 +166,8 @@ describe("GET /api/user/email-change/verify", () => {
},
);
- const res = await GET(getWithToken("long-enough-token"));
- expect(res.status).toBe(307);
+ const res = await POST(postWithToken("long-enough-token"));
+ expect(res.status).toBe(303);
expect(res.headers.get("location")).toContain("error=email_change_taken");
});
@@ -180,8 +209,8 @@ describe("GET /api/user/email-change/verify", () => {
},
);
- const res = await GET(getWithToken("long-enough-token"));
- expect(res.status).toBe(307);
+ const res = await POST(postWithToken("long-enough-token"));
+ expect(res.status).toBe(303);
expect(res.headers.get("location")).toContain("email_change=ok");
expect(userUpdate).toHaveBeenCalledWith({
where: { id: "u1" },
@@ -233,8 +262,8 @@ describe("GET /api/user/email-change/verify", () => {
expiresAt: new Date("2026-06-01T00:00:00Z"),
});
- const res = await GET(getWithToken("long-enough-token"));
- expect(res.status).toBe(307);
+ const res = await POST(postWithToken("long-enough-token"));
+ expect(res.status).toBe(303);
expect(res.headers.get("location")).toContain("email_change=ok");
expect(sessionDeleteMany).toHaveBeenCalledWith({
where: { userId: "u1" },