feat(invitations): guide invited users without an account through sign-up

Clicking an invitation link while signed out dropped the visitor on a bare login form,
even though most invitees have no account yet and nothing on screen told them to create one.

Signed-out visitors now get the invitation itself: who invited them, which workspace/project,
which role, and which address it was sent to. The primary call to action follows whether an
account already exists for that address — "Create your account" when it does not, "Sign in to
accept" when it does.

The sign-up path carries the invitation forward, so a new account lands back on the invitation
and from there on the shared workspace/project instead of the onboarding wizard:
- the register link passes invitationToken, the invited email and a callbackUrl
- the register form locks the email to the invited address and shows what is being joined
- the verification email round-trips the destination through a sanitized `next` parameter
- login and verify-email keep the pending destination in their sign-in links

Signing in with a different address than the one invited now explains the mismatch instead of
silently redirecting to the dashboard.

Callback sanitization moves to lib/safe-redirect.ts so login, register, verify-email and the
verification route share one open-redirect guard.
This commit is contained in:
yusufipk
2026-07-25 18:44:02 +07:00
parent a14eb9fb84
commit 9c75ce91e1
11 changed files with 424 additions and 29 deletions
+9 -2
View File
@@ -94,7 +94,11 @@ function createTransport() {
return nodemailer.createTransport({ host, port, secure: port === 465, auth: { user, pass } });
}
export async function sendVerificationEmail(email: string, token: string): Promise<void> {
export async function sendVerificationEmail(
email: string,
token: string,
options?: { next?: string }
): Promise<void> {
const transporter = createTransport();
if (!transporter) return;
@@ -109,7 +113,10 @@ export async function sendVerificationEmail(email: string, token: string): Promi
return;
}
const verifyUrl = `${baseUrl}/api/auth/verify-email?token=${encodeURIComponent(token)}`;
// `next` survives the round-trip so an invited user lands back on the invitation
// (and from there on the shared project) instead of a generic login page.
const nextParam = options?.next ? `&next=${encodeURIComponent(options.next)}` : '';
const verifyUrl = `${baseUrl}/api/auth/verify-email?token=${encodeURIComponent(token)}${nextParam}`;
const from = process.env.SMTP_FROM || process.env.EMAIL_FROM || 'OpenFrame <[email protected]>';
const html = brandedEmailTemplate(
+58
View File
@@ -221,6 +221,64 @@ export async function createOrRefreshInvitation(params: {
throw new Error('Failed to create invitation after retrying');
}
export interface InvitationPreview {
email: string;
role: InvitationRole;
roleLabel: string;
scope: InvitationScope;
scopeLabel: string;
status: InvitationStatus;
/** PENDING but past its expiry — the DB row is only flipped to EXPIRED on acceptance. */
isExpired: boolean;
inviterName: string;
targetName: string | null;
/** Whether an account already exists for the invited address. */
hasAccount: boolean;
}
/**
* Public-facing summary of an invitation, safe to render to a signed-out visitor:
* the token itself is the secret, and everything here was already in the email we sent
* to that address.
*/
export async function getInvitationPreviewByToken(
token: string
): Promise<InvitationPreview | null> {
const invitation = await db.invitation.findUnique({
where: { token },
select: {
email: true,
role: true,
scope: true,
status: true,
expiresAt: true,
invitedBy: { select: { name: true } },
workspace: { select: { name: true } },
project: { select: { name: true } },
},
});
if (!invitation) return null;
const existingUser = await db.user.findUnique({
where: { email: invitation.email },
select: { id: true },
});
return {
email: invitation.email,
role: invitation.role,
roleLabel: roleLabel(invitation.role),
scope: invitation.scope,
scopeLabel: scopeLabel(invitation.scope),
status: invitation.status,
isExpired: invitation.expiresAt <= new Date(),
inviterName: invitation.invitedBy?.name?.trim() || 'A team member',
targetName: invitation.workspace?.name ?? invitation.project?.name ?? null,
hasAccount: Boolean(existingUser),
};
}
export async function getValidInvitationByToken(token: string) {
const now = new Date();
return db.invitation.findFirst({
+31
View File
@@ -0,0 +1,31 @@
/**
* Reduce an untrusted `callbackUrl`/`next` value to a same-origin relative path.
* Anything absolute, cross-origin or unparsable falls back to `fallback`.
*
* Works on both sides: in the browser the origin defaults to `window.location.origin`
* (so next-auth's absolute `result.url` still passes), on the server pass the public origin.
*/
export function getSafeCallbackUrl(
value: string | null | undefined,
options?: { origin?: string; fallback?: string }
): string {
const fallback = options?.fallback ?? '/dashboard';
if (!value) return fallback;
const baseOrigin =
options?.origin ??
(typeof window === 'undefined' ? 'http://localhost' : window.location.origin);
try {
const parsed = new URL(value, baseOrigin);
if (parsed.origin !== baseOrigin) return fallback;
return `${parsed.pathname}${parsed.search}${parsed.hash}`;
} catch {
return fallback;
}
}
/** True when a sanitized path points at the invitation acceptance route. */
export function isInvitationCallbackUrl(path: string): boolean {
return path.startsWith('/invitations/accept');
}