From 3dc2c2833012b8327213131338cc9ab20f7b43b9 Mon Sep 17 00:00:00 2001 From: Philipp Traber Date: Wed, 14 Oct 2026 17:49:30 +0200 Subject: [PATCH] Review fixes: forwarded IP, sign-in errors, revoking access - take the visitor IP from the last X-Forwarded-For entry (the one the proxy adds); the first can be set by the client to fake unique visitors - show "Sign-in failed" with a retry link when the identity provider rejects the callback instead of a generic 500 page - report concurrent unique-constraint conflicts (e.g. two requests claiming the same shortcode) as 409 instead of 500 - admins can revoke a user's access (end sessions, delete API tokens) from Administration; previously a removed user kept working tokens - README: security notes on the proxy header, offboarding and rate limiting Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++++ src/server/api.ts | 8 ++++- src/server/app.tsx | 4 +++ src/server/auth/routes.ts | 10 ++++++- src/server/auth/sessions.ts | 11 +++++++ src/server/public/routes.tsx | 3 +- src/web/screens/AdminUserScreen.tsx | 46 ++++++++++++++++++++++++++--- test/api.test.ts | 44 +++++++++++++++++++++++++++ test/helpers.ts | 9 ++++-- 9 files changed, 131 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 74fff79..fb84ca7 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,12 @@ docker compose up -d Put it behind a reverse proxy with TLS. Back up `data/`: it holds the SQLite database (`short.db`) and the uploaded avatars. Database migrations run automatically on startup. +## Security notes + +- **Reverse proxy:** with `TRUST_PROXY=true` the visitor IP is taken from the last `X-Forwarded-For` entry, so the proxy in front of short must append to that header (Traefik, Caddy and nginx' `$proxy_add_x_forwarded_for` do). +- **Removing someone:** admin rights and access follow Authentik at each sign-in, but existing sessions (up to 30 days) and API tokens keep working. When someone leaves or loses admin rights, use **Administration → user → Revoke access** to end their sessions and delete their tokens, and remove their access in Authentik. +- **Rate limiting** isn't built in. Every visit is recorded, so very public links can be flooded to inflate stats; rate-limit at the reverse proxy if needed. Individual clicks are deleted after 90 days. + ## API The admin UI uses the same JSON API. Create a token under **API tokens**; it has the same permissions as your account. diff --git a/src/server/api.ts b/src/server/api.ts index 428d2c9..e62efc5 100644 --- a/src/server/api.ts +++ b/src/server/api.ts @@ -16,7 +16,7 @@ import { } from "../shared/validation.js"; import type { AppEnv, Deps } from "./app.js"; import { requireActor } from "./auth/middleware.js"; -import { createApiToken } from "./auth/sessions.js"; +import { createApiToken, revokeAccess } from "./auth/sessions.js"; import { apiTokens } from "./db/schema.js"; import { forbidden, HttpError, notFound } from "./lib/errors.js"; import { removeMedia, saveAvatar } from "./lib/media.js"; @@ -186,6 +186,12 @@ export function apiRoutes(deps: Deps) { if (!c.var.actor.isAdmin) throw forbidden(); return c.json(pages.listUsernames(db)); }) + .delete("/users/:username/access", (c) => { + if (!c.var.actor.isAdmin) throw forbidden(); + const revoked = revokeAccess(db, c.req.param("username")); + if (!revoked) throw notFound(); + return c.json(revoked); + }) .get("/conflicts", (c) => { if (!c.var.actor.isAdmin) throw forbidden(); return c.json(pages.listConflicts(db)); diff --git a/src/server/app.tsx b/src/server/app.tsx index b512d2d..907196a 100644 --- a/src/server/app.tsx +++ b/src/server/app.tsx @@ -48,6 +48,10 @@ export function createApp(deps: Deps) { app.onError((err, c) => { const isApi = c.req.path.startsWith("/~/api/"); + // Two requests claiming the same unique value at once (e.g. a shortcode): the database rejects the second. + if ((err as { code?: string }).code === "SQLITE_CONSTRAINT_UNIQUE") { + err = new HttpError(409, "This already exists. Please try again with a different value."); + } if (err instanceof HttpError) { if (isApi) return c.json({ error: err.message, issues: err.issues }, err.status); return c.html(, err.status); diff --git a/src/server/auth/routes.ts b/src/server/auth/routes.ts index f053091..3ab16a8 100644 --- a/src/server/auth/routes.ts +++ b/src/server/auth/routes.ts @@ -2,6 +2,7 @@ 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 { HttpError } from "../lib/errors.js"; import { createSession, deleteSession, SESSION_TTL_MS, upsertUser } from "./sessions.js"; export const SESSION_COOKIE = "short_session"; @@ -38,7 +39,14 @@ export function authRoutes({ db, config, oidc }: Deps) { // 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 }); + let claims; + try { + claims = await oidc.exchange({ currentUrl, state, codeVerifier }); + } catch (err) { + // E.g. the login was cancelled at the identity provider or took too long. + console.warn("OIDC callback failed:", err instanceof Error ? err.message : err); + throw new HttpError(400, "Sign-in failed. Please try again."); + } const actor = upsertUser(db, claims, config.adminGroup); setCookie(c, SESSION_COOKIE, createSession(db, actor.id), { diff --git a/src/server/auth/sessions.ts b/src/server/auth/sessions.ts index 93bfddd..4da7b0f 100644 --- a/src/server/auth/sessions.ts +++ b/src/server/auth/sessions.ts @@ -75,3 +75,14 @@ export function createApiToken(db: Db, userId: number, name: string) { export function pruneSessions(db: Db, now = new Date()): number { return db.delete(sessions).where(lt(sessions.expiresAt, now)).run().changes; } + +// Ends all sessions and deletes all API tokens of a user, e.g. when they leave. +// They can sign in again only if Authentik still lets them. +export function revokeAccess(db: Db, username: string): { sessions: number; tokens: number } | null { + const user = db.select().from(users).where(eq(users.username, username)).get(); + if (!user) return null; + return db.transaction((tx) => ({ + sessions: tx.delete(sessions).where(eq(sessions.userId, user.id)).run().changes, + tokens: tx.delete(apiTokens).where(eq(apiTokens.userId, user.id)).run().changes, + })); +} diff --git a/src/server/public/routes.tsx b/src/server/public/routes.tsx index fe50ae7..76b8f17 100644 --- a/src/server/public/routes.tsx +++ b/src/server/public/routes.tsx @@ -11,7 +11,8 @@ import { LinkPage, MessagePage } from "./views.js"; export function publicRoutes({ db, config }: Deps) { const clientIp = (c: Context): string => { if (config.trustProxy) { - const forwarded = c.req.header("x-forwarded-for")?.split(",")[0]?.trim(); + // The last entry is the one added by our proxy; earlier ones can be set by the client. + const forwarded = c.req.header("x-forwarded-for")?.split(",").at(-1)?.trim(); if (forwarded) return forwarded; } try { diff --git a/src/web/screens/AdminUserScreen.tsx b/src/web/screens/AdminUserScreen.tsx index 6a48819..7109834 100644 --- a/src/web/screens/AdminUserScreen.tsx +++ b/src/web/screens/AdminUserScreen.tsx @@ -1,15 +1,51 @@ import { useState } from "react"; -import { ChevronRight, Link2, MousePointerClick, PanelsTopLeft, Plus, UserX } from "lucide-react"; +import { ChevronRight, Link2, MousePointerClick, PanelsTopLeft, Plus, ShieldOff, UserX } from "lucide-react"; import type { Me, PageKind, PageSummary } from "../../shared/api-types.js"; -import { useApi } from "../api.js"; +import { api, useApi } from "../api.js"; import { CreatePageDialog } from "../components/CreatePageDialog.js"; import { PageTable } from "../components/PageTable.js"; import { Button, buttonClass } from "../components/ui/button.js"; import { Link, Stat } from "../components/ui/misc.js"; -import { EmptyState, Skeleton } from "../components/ui/surface.js"; -import { useToast } from "../components/ui/toast.js"; +import { useConfirm } from "../components/ui/dialog.js"; +import { Card, CardHeader, EmptyState, Skeleton } from "../components/ui/surface.js"; +import { useAction, useToast } from "../components/ui/toast.js"; import { detailPath, navigate } from "../router.js"; +// Offboarding: ends the user's sessions and deletes their API tokens. Their content stays online. +function RevokeAccessCard({ username }: { username: string }) { + const confirm = useConfirm(); + const { busy, run } = useAction(); + const toast = useToast(); + + const revoke = async () => { + const ok = await confirm({ + title: `Revoke ${username}'s access?`, + description: `${username} is signed out everywhere and their API tokens are deleted. Their links and pages stay online. To stop them from signing in again, remove their access in Authentik.`, + confirmLabel: "Revoke access", + danger: true, + }); + if (!ok) return; + void run(async () => { + const { sessions, tokens } = await api<{ sessions: number; tokens: number }>("DELETE", `/users/${encodeURIComponent(username)}/access`); + toast(`Ended ${sessions} ${sessions === 1 ? "session" : "sessions"}, deleted ${tokens} API ${tokens === 1 ? "token" : "tokens"}`); + }); + }; + + return ( + + Revoke access} + description="Sign this user out everywhere and delete their API tokens, e.g. when they leave. Their links and pages stay online." + actions={ + + } + /> + + ); +} + // Everything one user owns, for admins. Kept apart from the admin's own and root content. export function AdminUserScreen({ username, me }: { username: string; me: Me }) { const users = useApi("/users"); @@ -88,6 +124,8 @@ export function AdminUserScreen({ username, me }: { username: string; me: Me })

Link pages

+ + {creating && ( diff --git a/test/api.test.ts b/test/api.test.ts index a84c82f..56678b3 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -63,6 +63,17 @@ describe("authentication", () => { }); }); + it("shows a friendly page when the identity provider rejects the login", async () => { + const { app, setNextLogin } = setup(); + const login = await app.request("/~/auth/login"); + setNextLogin(new Error("state mismatch")); + const res = await app.request("/~/auth/callback?code=c&state=s", { + headers: { cookie: login.headers.get("set-cookie")!.split(";")[0]! }, + }); + expect(res.status).toBe(400); + expect(await res.text()).toContain("Sign-in failed"); + }); + it("rejects usernames that aren't URL-safe", async () => { const { app, setNextLogin } = setup(); const login = await app.request("/~/auth/login"); @@ -167,6 +178,24 @@ describe("namespaces and permissions", () => { expect((await admin.api("PATCH", `/pages/${root.id}`, { code: "r" })).status).toBe(200); }); + it("lets admins revoke a user's sessions and API tokens", async () => { + const { app, user } = setup(); + const alice = user("alice"); + const bob = user("bob"); + const admin = user("root", true); + const cookie = `short_session=${alice.session}`; + + expect((await bob.api("DELETE", "/users/alice/access")).status).toBe(403); + expect((await admin.api("DELETE", "/users/nobody/access")).status).toBe(404); + + const res = await admin.api("DELETE", "/users/alice/access"); + expect(await res.json()).toEqual({ sessions: 1, tokens: 1 }); + expect((await alice.api("GET", "/me")).status).toBe(401); + expect((await app.request("/~/api/me", { headers: { cookie } })).status).toBe(401); + // Other users are unaffected. + expect((await bob.api("GET", "/me")).status).toBe(200); + }); + it("restricts admin-only endpoints", async () => { const { user } = setup(); const alice = user("alice"); @@ -323,6 +352,21 @@ describe("redirects and stats", () => { expect((await (await alice.api("GET", `/pages/${page.id}/stats`)).json()).total).toBe(0); }); + it("uses the proxy-added X-Forwarded-For entry, not the client-supplied ones", async () => { + const { app, user } = setup(); + const alice = user("alice"); + const page = await (await alice.api("POST", "/pages", { kind: "redirect", code: "cv", dest: "https://example.com/cv" })).json(); + + // Same real client (last entry) faking different addresses in front: still one visitor. + for (const fake of ["10.0.0.1", "10.9.9.9", "172.16.0.1"]) { + await app.request("/alice/cv", { headers: { "x-forwarded-for": `${fake}, 5.6.7.8`, "user-agent": "test" } }); + } + await flush(); + const stats = await (await alice.api("GET", `/pages/${page.id}/stats`)).json(); + expect(stats.today).toBe(3); + expect(stats.uniquesToday).toBe(1); + }); + it("returns 404 for unknown links and the pinned page at the root", async () => { const { app, user } = setup(); expect((await app.request("/nope")).status).toBe(404); diff --git a/test/helpers.ts b/test/helpers.ts index ed94bed..607b2f2 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -27,10 +27,13 @@ export function setup(overrides: Partial = {}) { const db = openDb(":memory:"); // The fake provider returns whatever claims the test queued for the next login. - let nextClaims: OidcClaims = { sub: "sub-x", username: "x", groups: [] }; + let nextClaims: OidcClaims | Error = { sub: "sub-x", username: "x", groups: [] }; const oidc: OidcProvider = { authorizationUrl: async ({ state }) => new URL(`https://auth.test/authorize?state=${state}`), - exchange: async () => nextClaims, + exchange: async () => { + if (nextClaims instanceof Error) throw nextClaims; + return nextClaims; + }, }; const app = createApp({ db, config, oidc }); @@ -53,7 +56,7 @@ export function setup(overrides: Partial = {}) { db, config, user, - setNextLogin: (claims: OidcClaims) => { + setNextLogin: (claims: OidcClaims | Error) => { nextClaims = claims; }, };