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.
This commit is contained in:
adilallo committed 2026-11-22 16:58:30 -07:00
1 parent 600056499c
commit a725cf1a32
33 files changed
+1002 -89

No files matched your search

+107
View File
@@ -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 (
<div className={confirmPageBgClass}>
<Login
isOpen
usePortal={false}
backdropVariant="solid"
onClose={() => {
router.push(backHref);
}}
ariaLabelledBy={titleId}
belowCard={
<Link
href={backHref}
className="text-small-paragraph text-[var(--color-content-invert-tertiary,#2d2d2d)] text-center hover:opacity-90"
>
{backLabel}
</Link>
}
>
<div className="flex min-h-0 flex-1 flex-col gap-6 pt-2">
<ContentLockup
titleId={titleId}
title={heading.title}
description={heading.description}
variant="login"
alignment="left"
/>
{hasToken ? (
<form method="POST" action={action} className="mt-auto flex flex-col gap-4">
<input type="hidden" name="token" value={token} />
<Button
type="submit"
size="large"
buttonType="filled"
palette="default"
autoFocus
className="w-full !justify-center text-center px-[var(--space-400)] py-[var(--space-300)]"
>
{buttonLabel}
</Button>
</form>
) : (
<Button
href={missingHref}
size="large"
buttonType="filled"
palette="default"
className="mt-auto w-full !justify-center text-center px-[var(--space-400)] py-[var(--space-300)]"
>
{missingButtonLabel}
</Button>
)}
</div>
</Login>
</div>
);
}
+18
View File
@@ -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;
}
+49
View File
@@ -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 (
<div className="flex min-h-[100dvh] items-center justify-center bg-[var(--color-surface-invert-brand-primary)]">
<p className="text-[14px] text-[var(--color-content-default-primary)]">
{t("loading")}
</p>
</div>
);
}
function EmailChangeConfirmWithParams() {
const t = useTranslation("pages.profile");
const tLogin = useTranslation("pages.login");
const searchParams = useSearchParams();
const token = searchParams.get("token") ?? "";
return (
<ConfirmLinkScreen
title={t("emailChangeConfirmTitle")}
description={t("emailChangeConfirmDescription")}
buttonLabel={t("emailChangeConfirmButton")}
action={emailChangeVerifyPath(token)}
token={token}
backHref="/"
backLabel={tLogin("backToHome")}
missingTitle={t("emailChangeConfirmMissingTitle")}
missingDescription={t("emailChangeConfirmMissingDescription")}
missingHref="/profile"
missingButtonLabel={t("emailChangeConfirmMissingButton")}
/>
);
}
export default function EmailChangeConfirmPage() {
return (
<Suspense fallback={<EmailChangeConfirmFallback />}>
<EmailChangeConfirmWithParams />
</Suspense>
);
}
+18
View File
@@ -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;
}
+53
View File
@@ -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 (
<div className="flex min-h-[100dvh] items-center justify-center bg-[var(--color-surface-invert-brand-primary)]">
<p className="text-[14px] text-[var(--color-content-default-primary)]">
{t("loadingFallback")}
</p>
</div>
);
}
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 (
<ConfirmLinkScreen
title={t("confirmTitle")}
description={t("confirmDescription")}
buttonLabel={t("confirmButton")}
action={inviteVerifyPath(token, { copy })}
token={token}
backHref="/"
backLabel={t("backToHome")}
missingTitle={t("confirmMissingTitle")}
missingDescription={t("confirmMissingDescription")}
missingHref="/"
missingButtonLabel={t("backToHome")}
/>
);
}
export default function InviteConfirmPage() {
return (
<Suspense fallback={<InviteConfirmFallback />}>
<InviteConfirmWithParams />
</Suspense>
);
}
+17
View File
@@ -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;
}
+48
View File
@@ -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 (
<div className="flex min-h-[100dvh] items-center justify-center bg-[var(--color-surface-invert-brand-primary)]">
<p className="text-[14px] text-[var(--color-content-default-primary)]">
{t("loadingFallback")}
</p>
</div>
);
}
function LoginConfirmWithParams() {
const t = useTranslation("pages.login");
const searchParams = useSearchParams();
const token = searchParams.get("token") ?? "";
return (
<ConfirmLinkScreen
title={t("confirmTitle")}
description={t("confirmDescription")}
buttonLabel={t("confirmButton")}
action={magicLinkVerifyPath(token)}
token={token}
backHref="/"
backLabel={t("backToHome")}
missingTitle={t("confirmMissingTitle")}
missingDescription={t("confirmMissingDescription")}
missingHref="/login"
missingButtonLabel={t("confirmMissingButton")}
/>
);
}
export default function LoginConfirmPage() {
return (
<Suspense fallback={<LoginConfirmFallback />}>
<LoginConfirmWithParams />
</Suspense>
);
}
+43 -15
View File
@@ -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;
}
@@ -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;
}
@@ -46,6 +46,7 @@ export const POST = apiRoute<RouteContext>(
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<RouteContext>(
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",
+1 -2
View File
@@ -61,7 +61,6 @@ export const GET = apiRoute<RouteContext>(
email: true,
invitedAt: true,
acceptedAt: true,
inviteTokenHash: true,
},
});
@@ -72,7 +71,7 @@ export const GET = apiRoute<RouteContext>(
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),
})),
});
},
+35 -12
View File
@@ -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;
}
@@ -76,6 +76,13 @@ const LoginContainer = memo<LoginProps>(
emailField.focus();
return;
}
const submitButton = dialog.querySelector<HTMLButtonElement>(
'button[type="submit"]:not([disabled])',
);
if (submitButton) {
submitButton.focus();
return;
}
const focusableElements = dialog.querySelectorAll(focusableSelector);
const firstElement = focusableElements[0] as HTMLElement;
if (firstElement) {
+39
View File
@@ -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)}`;
}
+3 -1
View File
@@ -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;
}
+42
View File
@@ -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<string | null> {
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;
}
}
+2 -2
View File
@@ -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,
+14
View File
@@ -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;
}
+12
View File
@@ -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."
+5
View File
@@ -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",
+6
View File
@@ -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": ".",
+6
View File
@@ -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.",
+2 -1
View File
@@ -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())
@@ -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(<ConfirmLinkScreen {...baseProps} />);
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(<ConfirmLinkScreen {...baseProps} token="" action="" />);
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",
);
});
});
+53 -1
View File
@@ -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();
});
});
+33
View File
@@ -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&copy=1",
);
expect(inviteVerifyPath("abc1234567", { copy: true })).toBe(
"/api/invites/rule-stakeholder/verify?token=abc1234567&copy=1",
);
});
});
@@ -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],
+31
View File
@@ -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");
});
});
@@ -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",
@@ -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)}&copy=1`,
{ method: "POST" },
),
);
expect(res.headers.get("location")).toContain("/invite/rule-1");
expect(res.headers.get("location")).toContain("copy=1");
});
@@ -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(
+1 -1
View File
@@ -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(
+36 -7
View File
@@ -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" },