v3: comments say what the code can't — the documentation pass wanted JSDoc on every export and every field of an exported interface, which filled the code with restatements ("The dump.", "Whether it is loading.", "The props of X.", "Renders the X.") and module docs that told a reader nothing ("The hot and new feeds, and the props every main feed of the index takes."); some were wrong as well as vague. Every comment in api/, shared/ and src/ is rewritten under one rule, now stated in the README's "Comments" section: every module and export still has a JSDoc, and it gives context (who uses it and where), usage (what a caller must know: a precondition, what it leaves to the caller, a side effect) or its place in the chain (where its input comes from, where its output goes); a field, parameter, private function or local gets one only when it adds to its parent's, and context about a whole type goes on the type; a type's doc is phrased from the value's side ("Returned to Y by X when Z", "Passed to Y by X"); full sentences, as short as they can be, no label-colon-list; // goes wherever the code isn't obvious and says why, and the section banners and narration go. Every claim was checked against the code, which turned up some forty comments that were wrong: DumpCard's claimed it was only used by the hot and new feeds, the WebSocket welcome claimed to be a socket's first message (presence comes first), UpdateUserRequest said null removes a description (it keeps it), deletedDumpIds leaves out that it also holds dumps made private, THEME_COLOR claimed to mirror index.html's, and the like. The routers' JSDoc now says where they are mounted and what becomes of a thrown APIException. doc-lint.ts lets a field without a doc through; a module or export without one still fails. No code changes; 204 backend and 628 frontend tests pass, and doc:lint, deno check, deno lint and tsc are clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-09-29 14:31:14 +00:00
parent 42e0356d21
commit 0d4e344d77
287 changed files with 5679 additions and 5135 deletions

View File

@@ -1,6 +1,8 @@
/**
* Signed tokens and password hashes: session tokens, media tokens, password
* reset tokens, and scrypt hashing.
* Signs and verifies the server's three kinds of token (session, media and
* password reset), all HS256 with the one key, and hashes passwords. 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.
*
@@ -26,22 +28,26 @@ if (!JWT_SECRET) {
}
const JWT_KEY = new TextEncoder().encode(JWT_SECRET);
// ── Password reset tokens ─────────────────────────────────────────────────────
/** Signs a single-use password reset token for `userId`, valid for an hour. */
/**
* 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);
}
/**
* Verifies a password reset token and returns its payload, or null when it is
* invalid, expired or not a reset token.
* 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,
@@ -55,29 +61,29 @@ export async function verifyPasswordResetToken(
}
}
// ── Auth tokens ───────────────────────────────────────────────────────────────
/** Signs a session token carrying `payload`, valid for 7 days. */
/**
* 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" })
// `iat` is what a password change revokes against (users.tokens_valid_after).
// A password change revokes tokens by comparing `iat` with
// `users.tokens_valid_after`.
.setIssuedAt()
.setExpirationTime("7d")
.sign(JWT_KEY);
}
// ── Media tokens ──────────────────────────────────────────────────────────────
/**
* Signs a media token for `userId`, valid for 7 days.
*
* Media elements can't send an Authorization header, so a private dump's file
* and thumbnail URLs carry a token in the query string, where it lands in
* access logs and browser history. That token is this one: it only reads media,
* so a leaked URL exposes the owner's private files, not their account.
* 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 })
@@ -88,8 +94,8 @@ export async function createMediaToken(userId: string): Promise<string> {
}
/**
* Verifies a media token and returns its user id and issue time, or null when
* it is invalid, expired or not a media token.
* 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,
@@ -106,8 +112,9 @@ export async function verifyMediaToken(
}
/**
* Verifies a session token's signature and expiry and returns its payload, or
* null. Checking it against the live user is `authenticate`'s job (lib/auth.ts).
* 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 {
@@ -124,7 +131,10 @@ export async function verifyJWT(token: string): Promise<AuthPayload | null> {
}
}
/** Hashes `password` with scrypt and a random salt, as `hash.salt` in hex. */
/**
* Hashes `password` with scrypt and a random salt, as `hash.salt` in hex, for
* `users.password_hash`.
*/
export function hashPassword(password: string): Promise<string> {
const salt = randomBytes(16).toString("hex");
@@ -142,8 +152,7 @@ export function verifyPassword(
storedHash: string,
): Promise<boolean> {
const [hash, salt] = storedHash.split(".");
// A malformed stored hash can't match anything; scrypt would throw on the
// missing salt instead of answering.
// scrypt would throw on a missing salt, and a malformed hash matches nothing.
if (!hash || !salt) return Promise.resolve(false);
return new Promise((resolve, reject) => {