v2: rewrite on Hono + SQLite with user namespaces

Replaces the Next.js/Prisma/next-auth app with a single-container
Hono server, SQLite via Drizzle, OIDC login against Authentik and a
React/Vite admin UI that talks to a JSON API.

- users get /<username>/<code>, admins (Authentik group) get root
  codes, pinning and full access
- link pages with link and Markdown text blocks, themes, avatars
- editable 302 redirects, random or custom codes
- personal API tokens, CSRF-protected cookie sessions
- privacy-friendly stats: daily-rotating visitor salt, 90-day click
  retention with daily totals kept
- QR codes as PNG/SVG
- tests for permissions, auth, redirects and stats; CI runs them
  before publishing images

See REQUIREMENTS.md for the full requirement list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 13:57:47 +02:00
co-authored by Claude Opus 5.5
parent 9758f4bf45
commit b217214512
108 changed files with 6942 additions and 9862 deletions
+38
View File
@@ -0,0 +1,38 @@
import { getCookie } from "hono/cookie";
import { createMiddleware } from "hono/factory";
import type { AppEnv, Deps } from "../app.js";
import { HttpError } from "../lib/errors.js";
import { SESSION_COOKIE } from "./routes.js";
import { actorFromApiToken, actorFromSession } from "./sessions.js";
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
// Guards the whole API: every request needs a bearer token or a session cookie.
// Cookie-authenticated writes must come from our own origin (CSRF protection).
export function requireActor({ db, config }: Deps) {
const ownOrigin = new URL(config.baseUrl).origin;
return createMiddleware<AppEnv>(async (c, next) => {
const authorization = c.req.header("authorization");
if (authorization) {
const [scheme, token] = authorization.split(" ");
const actor = scheme?.toLowerCase() === "bearer" && token ? actorFromApiToken(db, token) : null;
if (!actor) throw new HttpError(401, "Invalid API token");
c.set("actor", actor);
return next();
}
const session = getCookie(c, SESSION_COOKIE);
const actor = session ? actorFromSession(db, session) : null;
if (!actor) throw new HttpError(401, "Not logged in");
if (!SAFE_METHODS.has(c.req.method)) {
const origin = c.req.header("origin");
const site = c.req.header("sec-fetch-site");
if (origin !== ownOrigin && site !== "same-origin") throw new HttpError(403, "Cross-site request blocked");
}
c.set("actor", actor);
return next();
});
}
+53
View File
@@ -0,0 +1,53 @@
import * as client from "openid-client";
import type { Config } from "../config.js";
export interface OidcClaims {
sub: string;
username: string | undefined;
groups: string[];
}
// Thin wrapper so the app can be tested without a real identity provider.
export interface OidcProvider {
authorizationUrl(params: { state: string; codeChallenge: string; redirectUri: string }): Promise<URL>;
exchange(params: { currentUrl: URL; state: string; codeVerifier: string }): Promise<OidcClaims>;
}
export function createOidcProvider(config: Config): OidcProvider {
// Discovery happens lazily so the server can start while Authentik is unavailable.
let discovered: Promise<client.Configuration> | undefined;
const getConfiguration = () => {
discovered ??= client
.discovery(new URL(config.oidc.issuer), config.oidc.clientId, config.oidc.clientSecret)
.catch((err: unknown) => {
discovered = undefined;
throw err;
});
return discovered;
};
return {
async authorizationUrl({ state, codeChallenge, redirectUri }) {
return client.buildAuthorizationUrl(await getConfiguration(), {
redirect_uri: redirectUri,
scope: "openid profile email",
code_challenge: codeChallenge,
code_challenge_method: "S256",
state,
});
},
async exchange({ currentUrl, state, codeVerifier }) {
const tokens = await client.authorizationCodeGrant(await getConfiguration(), currentUrl, {
pkceCodeVerifier: codeVerifier,
expectedState: state,
});
const claims = tokens.claims();
if (!claims) throw new Error("No ID token returned");
const groups = Array.isArray(claims.groups) ? claims.groups.filter((g): g is string => typeof g === "string") : [];
const username = typeof claims.preferred_username === "string" ? claims.preferred_username : undefined;
return { sub: claims.sub, username, groups };
},
};
}
export { calculatePKCECodeChallenge, randomPKCECodeVerifier, randomState } from "openid-client";
+59
View File
@@ -0,0 +1,59 @@
import { Hono } from "hono";
import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
import type { AppEnv, Deps } from "../app.js";
import { calculatePKCECodeChallenge, randomPKCECodeVerifier, randomState } from "./oidc.js";
import { createSession, deleteSession, SESSION_TTL_MS, upsertUser } from "./sessions.js";
export const SESSION_COOKIE = "short_session";
const LOGIN_COOKIE = "short_login";
export function authRoutes({ db, config, oidc }: Deps) {
const secure = config.baseUrl.startsWith("https://");
const redirectUri = `${config.baseUrl}/~/auth/callback`;
return new Hono<AppEnv>()
.get("/login", async (c) => {
const state = randomState();
const codeVerifier = randomPKCECodeVerifier();
const url = await oidc.authorizationUrl({
state,
codeChallenge: await calculatePKCECodeChallenge(codeVerifier),
redirectUri,
});
await setSignedCookie(c, LOGIN_COOKIE, JSON.stringify({ state, codeVerifier }), config.sessionSecret, {
path: "/~/auth",
httpOnly: true,
secure,
sameSite: "Lax",
maxAge: 600,
});
return c.redirect(url.href);
})
.get("/callback", async (c) => {
const raw = await getSignedCookie(c, config.sessionSecret, LOGIN_COOKIE);
deleteCookie(c, LOGIN_COOKIE, { path: "/~/auth" });
if (!raw) return c.redirect("/~/auth/login");
const { state, codeVerifier } = JSON.parse(raw) as { state: string; codeVerifier: string };
// Behind a reverse proxy the request URL may be internal, so rebuild it from BASE_URL.
const requestUrl = new URL(c.req.url);
const currentUrl = new URL(`${redirectUri}${requestUrl.search}`);
const claims = await oidc.exchange({ currentUrl, state, codeVerifier });
const actor = upsertUser(db, claims, config.adminGroup);
setCookie(c, SESSION_COOKIE, createSession(db, actor.id), {
path: "/",
httpOnly: true,
secure,
sameSite: "Lax",
maxAge: SESSION_TTL_MS / 1000,
});
return c.redirect("/~/");
})
.post("/logout", (c) => {
const token = getCookie(c, SESSION_COOKIE);
if (token) deleteSession(db, token);
deleteCookie(c, SESSION_COOKIE, { path: "/" });
return c.body(null, 204);
});
}
+77
View File
@@ -0,0 +1,77 @@
import { and, eq, gt, lt } from "drizzle-orm";
import type { Db } from "../db/index.js";
import { apiTokens, sessions, users } from "../db/schema.js";
import { HttpError } from "../lib/errors.js";
import { randomToken, sha256 } from "../lib/crypto.js";
import { isValidUsername } from "../../shared/validation.js";
import type { Actor } from "../lib/permissions.js";
import type { OidcClaims } from "./oidc.js";
export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const TOKEN_PREFIX = "short_";
// Creates or updates the user for an OIDC login. The username is fixed at first login;
// only the admin flag follows the Authentik groups.
export function upsertUser(db: Db, claims: OidcClaims, adminGroup: string): Actor {
const isAdmin = claims.groups.includes(adminGroup);
const existing = db.select().from(users).where(eq(users.sub, claims.sub)).get();
if (existing) {
db.update(users).set({ isAdmin }).where(eq(users.id, existing.id)).run();
return { id: existing.id, username: existing.username, isAdmin };
}
const username = claims.username;
if (!username || !isValidUsername(username)) {
throw new HttpError(403, "Your username can't be used in URLs. Ask an admin to change it in Authentik.");
}
if (db.select().from(users).where(eq(users.username, username)).get()) {
throw new HttpError(409, "This username already belongs to another account.");
}
const row = db.insert(users).values({ sub: claims.sub, username, isAdmin }).returning().get();
return { id: row.id, username: row.username, isAdmin: row.isAdmin };
}
export function createSession(db: Db, userId: number, now = new Date()): string {
const token = randomToken();
db.insert(sessions)
.values({ id: sha256(token), userId, expiresAt: new Date(now.getTime() + SESSION_TTL_MS) })
.run();
return token;
}
export function deleteSession(db: Db, token: string): void {
db.delete(sessions).where(eq(sessions.id, sha256(token))).run();
}
export function actorFromSession(db: Db, token: string, now = new Date()): Actor | null {
const row = db
.select({ id: users.id, username: users.username, isAdmin: users.isAdmin })
.from(sessions)
.innerJoin(users, eq(users.id, sessions.userId))
.where(and(eq(sessions.id, sha256(token)), gt(sessions.expiresAt, now)))
.get();
return row ?? null;
}
export function actorFromApiToken(db: Db, token: string, now = new Date()): Actor | null {
if (!token.startsWith(TOKEN_PREFIX)) return null;
const row = db
.select({ tokenId: apiTokens.id, id: users.id, username: users.username, isAdmin: users.isAdmin })
.from(apiTokens)
.innerJoin(users, eq(users.id, apiTokens.userId))
.where(eq(apiTokens.tokenHash, sha256(token)))
.get();
if (!row) return null;
db.update(apiTokens).set({ lastUsedAt: now }).where(eq(apiTokens.id, row.tokenId)).run();
return { id: row.id, username: row.username, isAdmin: row.isAdmin };
}
export function createApiToken(db: Db, userId: number, name: string) {
const token = TOKEN_PREFIX + randomToken();
const row = db.insert(apiTokens).values({ userId, name, tokenHash: sha256(token) }).returning().get();
return { row, token };
}
export function pruneSessions(db: Db, now = new Date()): number {
return db.delete(sessions).where(lt(sessions.expiresAt, now)).run().changes;
}