diff --git a/src/app/api/dev/approve/route.ts b/src/app/api/dev/approve/route.ts index d490139..1f5d90c 100644 --- a/src/app/api/dev/approve/route.ts +++ b/src/app/api/dev/approve/route.ts @@ -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, diff --git a/src/app/api/dev/users/route.ts b/src/app/api/dev/users/route.ts index 9bb39e0..e9d958b 100644 --- a/src/app/api/dev/users/route.ts +++ b/src/app/api/dev/users/route.ts @@ -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, diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index a345eda..df97acc 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -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(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() { + {linkNotice && ( +

+ {linkNotice} +

+ )}
diff --git a/src/auth/invites.ts b/src/auth/invites.ts index b35998a..883086f 100644 --- a/src/auth/invites.ts +++ b/src/auth/invites.ts @@ -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, diff --git a/src/auth/magic-link.test.ts b/src/auth/magic-link.test.ts index 2e25dff..e3961b6 100644 --- a/src/auth/magic-link.test.ts +++ b/src/auth/magic-link.test.ts @@ -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) { 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( diff --git a/src/auth/magic-link.ts b/src/auth/magic-link.ts index b15868b..f9988cf 100644 --- a/src/auth/magic-link.ts +++ b/src/auth/magic-link.ts @@ -221,7 +221,18 @@ export async function getOrCreateUser(email: string) { return raced; } -export async function signMagicToken(email: string): Promise { +/** + * 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 { return new SignJWT({ email, purpose: "magic-link", @@ -229,7 +240,7 @@ export async function signMagicToken(email: string): Promise { .setProtectedHeader({ alg: "HS256" }) .setJti(uuidv7()) .setIssuedAt() - .setExpirationTime("10m") + .setExpirationTime(ttl) .sign(SECRET); } diff --git a/src/lib/welcome-email.ts b/src/lib/welcome-email.ts index dde13f3..139dca5 100644 --- a/src/lib/welcome-email.ts +++ b/src/lib/welcome-email.ts @@ -60,7 +60,7 @@ export async function sendWelcomeEmail( Sign in

- 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.

@@ -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.",