Files
gerbeur/api/lib/auth.ts
khannurien d392be7cb8
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 50s
v3: api/ gets one layout rule and keeps to it, and whatever crosses the wire is defined once, in shared/ — api/model/interfaces.ts and src/model.ts declared the same 40 types by hand and had drifted: the error envelope, email required on one side and optional on the other, Invitee/InviteTreeEntry and LinkPreview/UrlPreviewResponse for one shape each. The validation limits, the role permissions, the chat length cap, the @mention pattern and the Bandcamp and YouTube player responses were copied too, behind "keep in sync" comments. shared/ now holds them once, one file per domain (api, category, chat, comment, dump, follow, mention, notification, permissions, player, playlist, search, user, validation, ws), and imports nothing from either half. The server sends Dates; the client reads Wire<T>, the same type with every Date an ISO string, and turns it back with src/utils/shared/deserialize.ts. APIErrorCode becomes a const object, since the frontend's erasableSyntaxOnly rejects an enum. The shared types showed two real gaps: the avatar upload and GET /api/users/me return the full self user and the frontend read them as public users, and a stored session may predate media tokens, so the client keeps it as its own Session type. The backend rule: each folder holds one kind of module, each file is named after its domain. routes/ parse and answer; services/ hold the logic and every SQL query (lib/auth.ts's token check moves to user-service); remote/ is the only place that fetches from other sites — the guarded fetch and the HTML scraping out of rich-content-service, public-address, the Bandcamp and YouTube resolvers, the link providers, the image proxy (fetch, checks and cache, out of routes/preview.ts) and the Twemoji glyphs (out of lib/site-icons.ts). model/ holds per table a row type, its guard and its mappers; validators/ the request guards; db/connection.ts the handle and transaction(), db/startup.ts the purges and default admin that db.ts ran on import, called at the same moment. Tests mirror the source one file per module, test/<layer>/<module>.test.ts, with shared/'s under shared/test/ (deno task test runs both); the test that covered the bandcamp and soundcloud providers together is two now, and the backend can() has its own, so 202 tests. deno lint src/ is clean too: window.* becomes globalThis.*, and test bodies and act() callbacks that never awaited lose their async. The README states the rule. No behaviour changes; the catalogues only move their source references.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 20:19:48 +00:00

84 lines
3.1 KiB
TypeScript

import type { Context } from "@oak/oak";
import { verifyJWT, verifyMediaToken } from "./jwt.ts";
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "./api-exception.ts";
import type { AuthPayload } from "../model/auth.ts";
import type { Role } from "../../shared/user.ts";
import { getSessionState } from "../services/user-service.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 state = getSessionState(userId);
if (!state) return null;
if (state.tokensValidAfter) {
const cutoff = Math.floor(
new Date(state.tokensValidAfter).getTime() / 1000,
);
if ((iat ?? 0) < cutoff) return null;
}
return { role: state.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.
*
* 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 / 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");
if (!authHeader?.startsWith("Bearer ")) return null;
const token = authHeader.substring(7).trim();
if (!token || token === "undefined" || token === "null") return null;
const payload = await authenticate(token);
if (!payload) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Invalid token");
}
return payload.userId;
}