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 { z } from "zod";
|
||||||
import { gateOrUser } from "@/auth/api";
|
import { gateOrUser } from "@/auth/api";
|
||||||
import { approveUser } from "@/auth/invites";
|
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 { getUserById } from "@/db/users";
|
||||||
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
||||||
|
|
||||||
@@ -48,7 +53,7 @@ export const POST = async (req: NextRequest) => {
|
|||||||
const approved = await getUserById(user.id);
|
const approved = await getUserById(user.id);
|
||||||
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
||||||
if (approved) {
|
if (approved) {
|
||||||
const token = await signMagicToken(approved.email);
|
const token = await signMagicToken(approved.email, INVITE_LINK_TTL);
|
||||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { gateOrUser } from "@/auth/api";
|
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 { validateUsername } from "@/auth/password";
|
||||||
import { SYSTEM_ROLES } from "@/auth/roles";
|
import { SYSTEM_ROLES } from "@/auth/roles";
|
||||||
import { db } from "@/db";
|
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
|
// Hand the admin a sign-in link, exactly like the invite flow does. The
|
||||||
// link only works once the account is active.
|
// link only works once the account is active. It is an invite, not a
|
||||||
const token = await signMagicToken(user.email);
|
// 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 origin = requestOrigin(req) || APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
+22
-1
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { signIn } from "next-auth/react";
|
import { signIn } from "next-auth/react";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
@@ -27,11 +27,27 @@ export default function LoginPage() {
|
|||||||
}>({ kind: "idle" });
|
}>({ kind: "idle" });
|
||||||
|
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
|
const [linkNotice, setLinkNotice] = useState<string | null>(null);
|
||||||
const [linkStatus, setLinkStatus] = useState<{
|
const [linkStatus, setLinkStatus] = useState<{
|
||||||
kind: "idle" | "sending" | "sent" | "error";
|
kind: "idle" | "sending" | "sent" | "error";
|
||||||
message?: string;
|
message?: string;
|
||||||
}>({ kind: "idle" });
|
}>({ 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) {
|
async function onPasswordSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setPasswordStatus({ kind: "signing" });
|
setPasswordStatus({ kind: "signing" });
|
||||||
@@ -101,6 +117,11 @@ export default function LoginPage() {
|
|||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-5">
|
<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">
|
<form onSubmit={onPasswordSubmit} className="flex flex-col gap-4">
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<Label htmlFor="login">Username or email</Label>
|
<Label htmlFor="login">Username or email</Label>
|
||||||
|
|||||||
+8
-2
@@ -18,7 +18,13 @@ import { db } from "@/db";
|
|||||||
import { users } from "@/db/schema";
|
import { users } from "@/db/schema";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
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";
|
import type { UserStatus } from "@/db/schema";
|
||||||
|
|
||||||
export type UserAction = "invite" | "approve" | "deny";
|
export type UserAction = "invite" | "approve" | "deny";
|
||||||
@@ -124,7 +130,7 @@ export async function inviteUser(input: {
|
|||||||
appOrigin?: string;
|
appOrigin?: string;
|
||||||
}) {
|
}) {
|
||||||
const user = await resolveOrCreateInvitee(input.email);
|
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 origin = input.appOrigin ?? APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -1,10 +1,25 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
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>) {
|
function req(url: string, headers: Record<string, string>) {
|
||||||
return { url, headers: new Headers(headers) };
|
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", () => {
|
describe("requestOrigin", () => {
|
||||||
it("uses the proxy's forwarded scheme and host", () => {
|
it("uses the proxy's forwarded scheme and host", () => {
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
+13
-2
@@ -221,7 +221,18 @@ export async function getOrCreateUser(email: string) {
|
|||||||
return raced;
|
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({
|
return new SignJWT({
|
||||||
email,
|
email,
|
||||||
purpose: "magic-link",
|
purpose: "magic-link",
|
||||||
@@ -229,7 +240,7 @@ export async function signMagicToken(email: string): Promise<string> {
|
|||||||
.setProtectedHeader({ alg: "HS256" })
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
.setJti(uuidv7())
|
.setJti(uuidv7())
|
||||||
.setIssuedAt()
|
.setIssuedAt()
|
||||||
.setExpirationTime("10m")
|
.setExpirationTime(ttl)
|
||||||
.sign(SECRET);
|
.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>
|
<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>
|
||||||
<p style="font-size: 12px; color: #6b7280;">
|
<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
|
sign-in page and request a fresh link with this email address. After
|
||||||
signing in you can set a password from your profile.
|
signing in you can set a password from your profile.
|
||||||
</p>
|
</p>
|
||||||
@@ -75,7 +75,7 @@ export async function sendWelcomeEmail(
|
|||||||
`Sign in: ${user.email}`,
|
`Sign in: ${user.email}`,
|
||||||
`Username: ${user.username || 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,
|
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.",
|
"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