Files
gerbeur/api/lib/jwt.ts
khannurien 7960d74c55 v4: weekly digests and monthly recaps go out by email, every email is written once as Markdown in the app's one catalog, and a review of the last two commits removes what they stated twice — users get a weekly digest (what happened to them, what the people and playlists they follow posted, the week's top dumps, the community) and a monthly recap (the month's top dumps and the community), both on by default, in their own style and scheme. digest-service sends what is due every quarter of an hour from digest_schedule (migration 0020), which holds each user's rolling 7- or 30-day period; existing users' first periods are spread over the coming week or month, a digest more than a period late covers the last full one, an empty one isn't sent, and an address like admin@localhost is skipped. Each digest carries a one-click unsubscribe (List-Unsubscribe and List-Unsubscribe-Post, POST /api/users/unsubscribe) and a link to the new /unsubscribe page, which asks before turning that cadence off, since mail scanners open every link; the token (lib/jwt) names the user and the cadence and never expires. The welcome email now says the digests are on. The emails' words moved out of a hand-written api/mail/strings.ts into the Lingui catalogs the interface uses: lingui extracts api/mail/ too, the catalogs moved to a top-level locales/ that both halves read, compile emits ES modules the server imports (api/mail/i18n.ts), messages take ICU plurals, and the labels the settings tab, the unsubscribe page and the emails share are one message each (their French had already drifted apart). Each template writes its email once as Markdown, which is the plain-text part, and EmailKit.render draws its blocks in the style (a lone link is a button, a list item starting with an image a thumbnail row, a numbered list a ranking, --- the footer), so no string is declared for an HTML and a text version; user text is escaped for Markdown, which the welcome body didn't do for usernames, whose _ read as emphasis. paint() set colors before a border-top shorthand that reset them, so every divider was black. The review also gave one home to what was written twice: the locale list (shared/locale.ts, read by lingui.config, the client, the server and its catalog loader), the base style and default scheme (shared/theme.ts), an email's look (lookOf, which digest-service, welcome and reset share), whether email is on (EMAIL_ENABLED, read by email-service and index.html), a setting's column and its default in the digests' SQL (SETTINGS_COLUMNS, DEFAULT_SETTINGS), the unsubscribe token (made once, not parsed back from a URL), AuthProvider's compare-and-store, ThemeProvider's twin style and scheme code (useThemeChoice), the test JWT encoder, and duplicate digest messages. The email palettes stay a flattened copy of the themes' tokens, now under a test that caught Times' secondary and link colors drifting. The Dockerfile copies api/mail and locales so the build extracts the emails' messages and the server finds its catalogs, and deno.json maps @lingui/core for the runtime image. 236 backend tests (new: digest building, sending, catch-up, scheduling and unsubscribing; the Markdown renderer; French from the catalog; palettes against themes; the stagger migration; unsubscribe tokens) and 661 frontend tests (new: the unsubscribe page) pass, and tsc, eslint, doc:lint, deno check, deno lint and deno fmt are clean.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:14:46 +00:00

168 lines
5.0 KiB
TypeScript

/**
* Signs and verifies the server's four kinds of token (session, media,
* password reset and unsubscribe), all HS256 with the one key. Only a token's signature and
* expiry are checked here: `lib/auth.ts` checks a session or media token
* against its user.
*
* Importing this module throws when `GERBEUR_JWT_SECRET` is unset.
*
* @module
*/
import { jwtVerify, SignJWT } from "@panva/jose";
import {
type AuthPayload,
isAuthPayload,
isPasswordResetPayload,
type PasswordResetPayload,
} from "../model/auth.ts";
import { JWT_SECRET } from "../config.ts";
import { type DigestCadence, isDigestCadence } from "../../shared/settings.ts";
if (!JWT_SECRET) {
throw new Error(
"GERBEUR_JWT_SECRET environment variable is required. Generate one with: openssl rand -hex 32",
);
}
const JWT_KEY = new TextEncoder().encode(JWT_SECRET);
/**
* Signs a password reset token for `userId`, valid for an hour. The token
* isn't single-use by itself: `requestPasswordReset` stores it, and
* `resetPassword` marks it used.
*/
export async function createPasswordResetToken(
userId: string,
): Promise<string> {
return await new SignJWT({ purpose: "password-reset", userId })
.setProtectedHeader({ alg: "HS256" })
// Two requests in the same second would otherwise sign the same token,
// which is the primary key of `password_reset_tokens`.
.setJti(crypto.randomUUID())
.setExpirationTime("1h")
.sign(JWT_KEY);
}
/**
* Returns the payload of a password reset token, or null when it is invalid,
* expired or another kind of token. Whether it was used is the caller's check.
*/
export async function verifyPasswordResetToken(
token: string,
): Promise<PasswordResetPayload | null> {
try {
const { payload } = await jwtVerify(token, JWT_KEY);
if (!isPasswordResetPayload(payload)) return null;
return payload as PasswordResetPayload;
} catch {
return null;
}
}
/**
* Signs a session token carrying `payload`, valid for 7 days. The users routes
* issue it on sign-up, sign-in and password change, and the client sends it as
* a bearer token.
*/
export async function createJWT(
payload: Omit<AuthPayload, "exp">,
): Promise<string> {
return await new SignJWT(payload)
.setProtectedHeader({ alg: "HS256" })
// A password change revokes tokens by comparing `iat` with
// `users.tokens_valid_after`.
.setIssuedAt()
.setExpirationTime("7d")
.sign(JWT_KEY);
}
/**
* Signs a media token for `userId`, valid for 7 days. Media elements can't send
* an `Authorization` header, so the URLs of private files, thumbnails and
* playlist covers carry this token as `?token=`, where it lands in logs and
* browser history. It only reads media, so a leaked URL doesn't expose the
* account.
*/
export async function createMediaToken(userId: string): Promise<string> {
return await new SignJWT({ purpose: "media", userId })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("7d")
.sign(JWT_KEY);
}
/**
* Returns the user id and issue time of a media token, or null when it is
* invalid, expired or another kind of token.
*/
export async function verifyMediaToken(
token: string,
): Promise<{ userId: string; iat?: number } | null> {
try {
const { payload } = await jwtVerify(token, JWT_KEY);
if (payload.purpose !== "media" || typeof payload.userId !== "string") {
return null;
}
return { userId: payload.userId, iat: payload.iat };
} catch {
return null;
}
}
/**
* Returns the payload of a session token whose signature and expiry are valid,
* or null. Call `authenticate` (`lib/auth.ts`) instead, which also checks the
* token against its user.
*/
export async function verifyJWT(token: string): Promise<AuthPayload | null> {
try {
const { payload } = await jwtVerify(token, JWT_KEY);
if (!isAuthPayload(payload)) {
return null;
}
return payload;
} catch (err) {
console.error("JWT verification failed:", err);
return null;
}
}
/**
* Signs the token of a digest's unsubscribe link, which turns off `cadence`
* for `userId` without signing in. It never expires, so the link in an old
* email still works; turning the digest back on doesn't revoke it, which is
* harmless since all it can do is turn it off again.
*/
export async function createUnsubscribeToken(
userId: string,
cadence: DigestCadence,
): Promise<string> {
return await new SignJWT({ purpose: "unsubscribe", userId, cadence })
.setProtectedHeader({ alg: "HS256" })
.sign(JWT_KEY);
}
/**
* Returns the user and cadence of an unsubscribe token, or null when it is
* invalid or another kind of token.
*/
export async function verifyUnsubscribeToken(
token: string,
): Promise<{ userId: string; cadence: DigestCadence } | null> {
try {
const { payload } = await jwtVerify(token, JWT_KEY);
if (
payload.purpose !== "unsubscribe" || typeof payload.userId !== "string" ||
!isDigestCadence(payload.cadence)
) {
return null;
}
return { userId: payload.userId, cadence: payload.cadence };
} catch {
return null;
}
}