Invite and welcome emails signed a 10-minute sign-in token, so the link was usually dead by the time someone opened the mail and could never reach the set-password page. Invitations now use a 7-day single-use token, while requested sign-in links stay at 10 minutes. Expired or already-used links also explain themselves on the sign-in page and point at requesting a fresh one. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
@@ -2,7 +2,12 @@ import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { approveUser } from "@/auth/invites";
|
||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
||||
import {
|
||||
APP_ORIGIN,
|
||||
INVITE_LINK_TTL,
|
||||
requestOrigin,
|
||||
signMagicToken,
|
||||
} from "@/auth/magic-link";
|
||||
import { getUserById } from "@/db/users";
|
||||
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
||||
|
||||
@@ -48,7 +53,7 @@ export const POST = async (req: NextRequest) => {
|
||||
const approved = await getUserById(user.id);
|
||||
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
||||
if (approved) {
|
||||
const token = await signMagicToken(approved.email);
|
||||
const token = await signMagicToken(approved.email, INVITE_LINK_TTL);
|
||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||
token,
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
||||
import {
|
||||
APP_ORIGIN,
|
||||
INVITE_LINK_TTL,
|
||||
requestOrigin,
|
||||
signMagicToken,
|
||||
} from "@/auth/magic-link";
|
||||
import { validateUsername } from "@/auth/password";
|
||||
import { SYSTEM_ROLES } from "@/auth/roles";
|
||||
import { db } from "@/db";
|
||||
@@ -128,8 +133,9 @@ export const POST = async (req: NextRequest) => {
|
||||
});
|
||||
|
||||
// Hand the admin a sign-in link, exactly like the invite flow does. The
|
||||
// link only works once the account is active.
|
||||
const token = await signMagicToken(user.email);
|
||||
// link only works once the account is active. It is an invite, not a
|
||||
// just-requested sign-in, so it gets the invite lifetime.
|
||||
const token = await signMagicToken(user.email, INVITE_LINK_TTL);
|
||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||
token,
|
||||
|
||||
+22
-1
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { signIn } from "next-auth/react";
|
||||
import {
|
||||
Card,
|
||||
@@ -27,11 +27,27 @@ export default function LoginPage() {
|
||||
}>({ kind: "idle" });
|
||||
|
||||
const [email, setEmail] = useState("");
|
||||
const [linkNotice, setLinkNotice] = useState<string | null>(null);
|
||||
const [linkStatus, setLinkStatus] = useState<{
|
||||
kind: "idle" | "sending" | "sent" | "error";
|
||||
message?: string;
|
||||
}>({ kind: "idle" });
|
||||
|
||||
// /api/dev/complete redirects here when a link is dead. Say why, instead of
|
||||
// dropping people on a bare sign-in form after the link fails.
|
||||
useEffect(() => {
|
||||
const error = new URLSearchParams(window.location.search).get("error");
|
||||
if (error === "invalid_link") {
|
||||
setLinkNotice(
|
||||
"That sign-in link has expired or is invalid. Request a fresh email link below.",
|
||||
);
|
||||
} else if (error === "link_used") {
|
||||
setLinkNotice(
|
||||
"That sign-in link has already been used. Request a fresh email link below.",
|
||||
);
|
||||
}
|
||||
}, []);
|
||||
|
||||
async function onPasswordSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setPasswordStatus({ kind: "signing" });
|
||||
@@ -101,6 +117,11 @@ export default function LoginPage() {
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
{linkNotice && (
|
||||
<p role="alert" className="rounded border border-border bg-muted p-3 text-sm">
|
||||
{linkNotice}
|
||||
</p>
|
||||
)}
|
||||
<form onSubmit={onPasswordSubmit} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="login">Username or email</Label>
|
||||
|
||||
+8
-2
@@ -18,7 +18,13 @@ import { db } from "@/db";
|
||||
import { users } from "@/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
import { APP_ORIGIN, getUser, normalizeEmail, signMagicToken } from "./magic-link";
|
||||
import {
|
||||
APP_ORIGIN,
|
||||
INVITE_LINK_TTL,
|
||||
getUser,
|
||||
normalizeEmail,
|
||||
signMagicToken,
|
||||
} from "./magic-link";
|
||||
import type { UserStatus } from "@/db/schema";
|
||||
|
||||
export type UserAction = "invite" | "approve" | "deny";
|
||||
@@ -124,7 +130,7 @@ export async function inviteUser(input: {
|
||||
appOrigin?: string;
|
||||
}) {
|
||||
const user = await resolveOrCreateInvitee(input.email);
|
||||
const token = await signMagicToken(user.email);
|
||||
const token = await signMagicToken(user.email, INVITE_LINK_TTL);
|
||||
const origin = input.appOrigin ?? APP_ORIGIN;
|
||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||
token,
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { requestOrigin } from "./magic-link";
|
||||
import { decodeJwt } from "jose";
|
||||
import { INVITE_LINK_TTL, requestOrigin, signMagicToken } from "./magic-link";
|
||||
|
||||
function req(url: string, headers: Record<string, string>) {
|
||||
return { url, headers: new Headers(headers) };
|
||||
}
|
||||
|
||||
describe("magic token lifetimes", () => {
|
||||
it("keeps a just-requested sign-in link short", async () => {
|
||||
const payload = decodeJwt(await signMagicToken("person@example.com"));
|
||||
expect(payload.exp! - payload.iat!).toBe(10 * 60);
|
||||
});
|
||||
|
||||
it("lets an invite link survive days in an inbox", async () => {
|
||||
const payload = decodeJwt(
|
||||
await signMagicToken("person@example.com", INVITE_LINK_TTL),
|
||||
);
|
||||
expect(payload.exp! - payload.iat!).toBe(7 * 24 * 60 * 60);
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestOrigin", () => {
|
||||
it("uses the proxy's forwarded scheme and host", () => {
|
||||
expect(
|
||||
|
||||
+13
-2
@@ -221,7 +221,18 @@ export async function getOrCreateUser(email: string) {
|
||||
return raced;
|
||||
}
|
||||
|
||||
export async function signMagicToken(email: string): Promise<string> {
|
||||
/**
|
||||
* Sign-in links are short-lived because they are requested and clicked in the
|
||||
* same sitting. Invites and welcome mails are not: they land in an inbox and may
|
||||
* be opened days later, so they get their own lifetime (still single use).
|
||||
*/
|
||||
export const SIGN_IN_LINK_TTL = "10m";
|
||||
export const INVITE_LINK_TTL = "7d";
|
||||
|
||||
export async function signMagicToken(
|
||||
email: string,
|
||||
ttl: string = SIGN_IN_LINK_TTL,
|
||||
): Promise<string> {
|
||||
return new SignJWT({
|
||||
email,
|
||||
purpose: "magic-link",
|
||||
@@ -229,7 +240,7 @@ export async function signMagicToken(email: string): Promise<string> {
|
||||
.setProtectedHeader({ alg: "HS256" })
|
||||
.setJti(uuidv7())
|
||||
.setIssuedAt()
|
||||
.setExpirationTime("10m")
|
||||
.setExpirationTime(ttl)
|
||||
.sign(SECRET);
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ export async function sendWelcomeEmail(
|
||||
<a href="${link}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Sign in</a>
|
||||
</p>
|
||||
<p style="font-size: 12px; color: #6b7280;">
|
||||
The link expires in 10 minutes and works once. If it has expired, open the
|
||||
The link expires in 7 days and works once. If it has expired, open the
|
||||
sign-in page and request a fresh link with this email address. After
|
||||
signing in you can set a password from your profile.
|
||||
</p>
|
||||
@@ -75,7 +75,7 @@ export async function sendWelcomeEmail(
|
||||
`Sign in: ${user.email}`,
|
||||
`Username: ${user.username || user.email}`,
|
||||
"",
|
||||
`Open this link to sign in (expires in 10 minutes, single use):`,
|
||||
`Open this link to sign in (expires in 7 days, single use):`,
|
||||
url,
|
||||
"",
|
||||
"If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.",
|
||||
|
||||
Reference in New Issue
Block a user