Files
gerbeur/api/middleware/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

86 lines
2.3 KiB
TypeScript

import {
type Next,
type RouteParams,
type RouterContext,
type State,
} from "@oak/oak";
import { authenticate } from "../lib/auth.ts";
import { APIErrorCode } from "../../shared/api.ts";
import { APIException } from "../lib/api-exception.ts";
import type { AuthPayload } from "../model/auth.ts";
import { can } from "../lib/permissions.ts";
import type { Permission } from "../../shared/permissions.ts";
export interface AuthState extends State {
user: AuthPayload;
}
// A router context whose state is guaranteed to carry the authenticated user
// (populated by authMiddleware). Generic over the route path so `ctx.params`
// stays typed per-route — e.g. `AuthContext<"/:userId/role">`.
export type AuthContext<
R extends string = string,
P extends RouteParams<R> = RouteParams<R>,
> = RouterContext<R, P, AuthState>;
export async function authMiddleware<R extends string>(
ctx: AuthContext<R>,
next: Next,
): Promise<void> {
const authHeader = ctx.request.headers.get("Authorization");
if (!authHeader || !authHeader.startsWith("Bearer ")) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
401,
"Missing or invalid token",
);
}
const token = authHeader.substring(7);
// Also checks the user still exists and hasn't changed their password since
// the token was issued, and takes the live role from the DB.
const payload = await authenticate(token);
if (!payload) {
throw new APIException(APIErrorCode.UNAUTHORIZED, 401, "Invalid token");
}
ctx.state.user = payload;
await next();
}
export async function adminOnlyMiddleware<R extends string>(
ctx: AuthContext<R>,
next: Next,
): Promise<void> {
if (ctx.state.user.role !== "admin") {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
403,
"Admin access required",
);
}
await next();
}
// Gates a route on a named permission. Must run after authMiddleware. Generic
// over the route path so it composes with path-typed route handlers.
export function requirePermission(permission: Permission) {
return async <R extends string>(
ctx: AuthContext<R>,
next: Next,
): Promise<void> => {
if (!ctx.state.user || !can(ctx.state.user, permission)) {
throw new APIException(
APIErrorCode.UNAUTHORIZED,
403,
"Insufficient permissions",
);
}
await next();
};
}