🐛 Fix infinite loop when trying to migrate legacy cookie (#1561)

This commit is contained in:
Luke Vella 2025-02-13 10:14:03 +07:00 committed by GitHub
parent cb27ae9ea7
commit ff4a1d16cb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 260 additions and 139 deletions

View file

@ -0,0 +1,36 @@
import hkdf from "@panva/hkdf";
import { EncryptJWT } from "jose";
import type { JWT } from "next-auth/jwt";
const now = () => (Date.now() / 1000) | 0;
export async function getDerivedEncryptionKey(
keyMaterial: string | Buffer,
salt: string,
) {
return await hkdf(
"sha256",
keyMaterial,
salt,
`NextAuth.js Generated Encryption Key${salt ? ` (${salt})` : ""}`,
32,
);
}
interface JWTEncodeParams {
token?: JWT;
salt?: string;
secret: string | Buffer;
maxAge?: number;
}
export async function encode(params: JWTEncodeParams) {
/** @note empty `salt` means a session token. See {@link JWTEncodeParams.salt}. */
const { token = {}, secret, maxAge = 30 * 24 * 60 * 60, salt = "" } = params;
const encryptionSecret = await getDerivedEncryptionKey(secret, salt);
return await new EncryptJWT(token)
.setProtectedHeader({ alg: "dir", enc: "A256GCM" })
.setIssuedAt()
.setExpirationTime(now() + maxAge)
.setJti("some-random-id")
.encrypt(encryptionSecret);
}