v3: the API stops trusting what it's handed — a review of api/ turned up a server anyone could crash, uploads that ran script on the app's origin, and a server that would fetch its own network on request, and this closes them along with the smaller holes around them. A WebSocket message that wasn't an object (a bare null will do) threw inside the listener, which Deno treats as uncaught and exits on; messages are now shape-checked and the handler can't throw out. Uploaded files kept the MIME type the uploader's browser claimed, so an .html or .svg dump opened from /api/files ran with the session token in reach; only images, audio, video, PDF and plain text are served inline now, the rest download, and every file carries nosniff and a sandboxing CSP (PDFs aside, which Chrome won't render sandboxed). The image proxy passed image/svg+xml straight through the same way and now takes raster formats only. Outbound fetches for previews, the proxy and Bandcamp checked the hostname against a partial list — no 169.254.169.254, no 0.0.0.0, an IPv6 check that never matched a bracketed hostname, nothing for names that resolve inward, and redirects followed blindly; every hop now resolves and is refused if any address is private or reserved, redirects are walked by hand, the curl fallback is pinned to the checked IP, and /api/preview needs a login. PATCH /users/me accepted a new password without the current one and now takes only the description and email; a wrong password at login answered 500 because the handler caught its own 401, and now says 401. Changing or resetting a password now ends every older session through users.tokens_valid_after (migration 0015) and an iat on every token, with change-password handing back fresh tokens the modal keeps, and all token checks go through one authenticate() that also refuses deleted users. Invites and reset links are claimed atomically before the async hash rather than marked after, so one invite no longer opens several accounts, and an email address belongs to one account. File and thumbnail URLs carry a media-only token rather than the session token, so a URL in a log exposes files and not the account; older sessions fetch one on load. Private things stop leaking into broadcasts: private playlist updates go to their owner, votes and likes on someone else's private dump 404 and their counts go to the owner alone, and a private dump can't be slipped into a playlist. Smaller: selfProvider only claims this site's own host, so github.com/users/bob stops rendering our bob; the chat read marker can't be parked in the future on an empty chat; dump mutations use the resolved id so a slug works; multipart dumps get the title and comment limits; logins and reset requests are rate-limited through a shared token bucket; the password compare is constant-time; ffmpeg reads only local files in known video containers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-09-24 20:07:33 +00:00
parent 3a09d0e354
commit 2ad8ae73d5
38 changed files with 1032 additions and 352 deletions

View File

@@ -1,6 +1,67 @@
import type { Context } from "@oak/oak";
import { verifyJWT } from "./jwt.ts";
import { APIErrorCode, APIException } from "../model/interfaces.ts";
import { verifyJWT, verifyMediaToken } from "./jwt.ts";
import {
APIErrorCode,
APIException,
type AuthPayload,
type Role,
} from "../model/interfaces.ts";
import { db } from "../model/db.ts";
/**
* Checks a signature-verified token against the live user row: the user must
* still exist, and the token must not predate their last password change
* (`users.tokens_valid_after`). Returns the live role, or null to refuse.
*
* `iat` has one-second resolution, so a token issued in the same second as the
* change survives it; one issued after it (the fresh one the change hands back)
* always does.
*/
function checkTokenOwner(
userId: string,
iat: number | undefined,
): { role: Role } | null {
const row = db.prepare(
`SELECT role, tokens_valid_after FROM users WHERE id = ?;`,
).get(userId) as
| { role: Role; tokens_valid_after: string | null }
| undefined;
if (!row) return null;
if (row.tokens_valid_after) {
const cutoff = Math.floor(
new Date(row.tokens_valid_after).getTime() / 1000,
);
if ((iat ?? 0) < cutoff) return null;
}
return { role: row.role };
}
/**
* Verifies a session token end to end: signature, expiry, a user that still
* exists and no password change since it was issued. The role comes from the
* DB, not the token, since tokens last 7 days and roles change under them.
*/
export async function authenticate(
token: string,
): Promise<AuthPayload | null> {
const payload = await verifyJWT(token);
if (!payload) return null;
const live = checkTokenOwner(payload.userId, payload.iat);
if (!live) return null;
return { ...payload, role: live.role };
}
/**
* Resolves the `?token=` on a media URL to the viewer's user id. Takes a media
* token, or a session token from a client that predates them.
*/
export async function authenticateMedia(token: string): Promise<string | null> {
const media = await verifyMediaToken(token);
if (media) {
return checkTokenOwner(media.userId, media.iat) ? media.userId : null;
}
return (await authenticate(token))?.userId ?? null;
}
/**
* Extracts the userId from an optional Bearer token.
@@ -8,10 +69,10 @@ import { APIErrorCode, APIException } from "../model/interfaces.ts";
* Distinguishes *missing* credentials from *invalid* ones:
* - No `Authorization: Bearer …` header (or a placeholder value such as the
* `Bearer undefined` that the client emits when logged out) → anonymous (null).
* - A real token that fails verification (expired / bad signature) → throws 401,
* so a stale client session surfaces as an auth error it can react to, instead
* of being silently downgraded to anonymous (which yields a misleading 404 on
* private resources).
* - A real token that fails verification (expired / bad signature / revoked) →
* throws 401, so a stale client session surfaces as an auth error it can react
* to, instead of being silently downgraded to anonymous (which yields a
* misleading 404 on private resources).
*/
export async function parseOptionalAuth(ctx: Context): Promise<string | null> {
const authHeader = ctx.request.headers.get("Authorization");
@@ -20,7 +81,7 @@ export async function parseOptionalAuth(ctx: Context): Promise<string | null> {
const token = authHeader.substring(7).trim();
if (!token || token === "undefined" || token === "null") return null;
const payload = await verifyJWT(token);
const payload = await authenticate(token);
if (!payload) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Invalid token");
}