25.9 KiB · text History 5daaf12

recourse

A small forum in the spirit of Discourse, built with Rust, htmx and Postgres: nested categories, topics and replies in Markdown, tags, reactions, bookmarks, watches and notifications, trust levels, invites, and moderation (staff edits, locks, posting rules, flags, cooldowns, a lameness filter, a moderation log). Two layouts: Classic lists and a full-screen Focus mode. There is an Android app (android/) using the /api/v1 API.

Built with:

  • axum and minijinja templates (embedded at build time, hot-reloaded from templates/ in dev), htmx for partial updates
  • sea-orm + Postgres with a migration crate (auto-migrates on boot)
    • The migrations run CREATE EXTENSION IF NOT EXISTS pg_trgm, used by search’s trigram indexes. It ships in contrib with the stock postgres:17 image.
    • On a managed database, the migration role must be allowed to create it: the database owner, or on RDS/Cloud SQL an extension on the allow-list. Otherwise create it once as an admin before deploying.
    • Search needs at least 3 characters, the shortest pattern a trigram index can serve.
  • Auth: Argon2 password hashing, cookie sessions, invite-only registration, email verification (mail through mail-prism), optional “Sign in with NEIAM” (OIDC), and per-device bearer tokens (hashed, 90-day sliding expiry) for the Android app and scripts
  • Tailwind + DaisyUI with light and dark themes and a theme switcher (just assets to build)
  • Prometheus metrics at /metrics, health check at /healthz
  • A Dockerfile (assets → cargo → debian-slim) and compose.yml (Postgres + web)

Quick start

just deps          # npm install (frontend deps)
just assets        # build CSS + JS + webfonts
just db-up         # start Postgres via podman compose; a fresh DB is migrated and gets demo content
just migrate       # apply migrations
just admin alice alice@example.com   # first (staff) account; prints its password
just serve         # run the web service on :3000

Sign in with the printed password. Further members join through invites (just invite, or the Invites page), or are created the same way.

Seed and demo data

  • just seed (manage seed) creates what any forum can keep: a category tree up to three levels deep (Development › Backend › Databases, Hobbies › Games › Board Games, …) with distinct colors, a members-only category (“Members Lounge”, any signed-in account) and a min-trust one (“Regulars’ Corner”, trust level 3+), the default reaction types if missing, and a few tags.
  • just seed-demo (manage seed --demo) adds development data: verified accounts demo-admin (staff, Leader), demo-leader, demo-regular, demo-member, demo-basic and demo-new (one per trust level), all with the password recourse-demo, and topics spread over the last six weeks with replies, an edited post, a soft-deleted post, reactions, bookmarks, tags and a pinned announcement; and moderation in use: staff-only Announcements with reactions off, a read-only “Leaders’ Council” (Basic reads, Regulars post), a locked topic with a staff-moderated post whose original is hidden, a pending flag, and their moderation-log lines.

Both are idempotent: rows are matched by slug / key / username / topic title and only missing ones are created, so re-running changes nothing and never overwrites edits. just db-up runs seed --demo only when the database has no users yet.

Production never gets demo content. Demo accounts share a published password, so nothing automatic runs --demo: not the image, not compose, not AUTO_MIGRATE. manage seed --demo also refuses to run when PUBLIC_URL is https unless given --allow-public. Plain manage seed is safe in production (it only adds missing categories/reactions/tags); run it by hand if you want the starter categories.

Staff

Staff (category/reaction admin, moderation) is only ever granted on purpose: manage user create … --staff, or manage user set-staff <name> for an existing account. Registering — even as the very first account — never makes anyone staff.

Moderation

Staff have three panes (Flags / Users / Log, under the admin menu), each in Classic and Focus:

  • Posts: Moderate replaces a post with a note shown as “staff: …” and kept in the post’s history as a moderation revision. Staff can hide the earlier versions from everyone else (“hidden by staff”) and restore the body later. The author can’t edit a moderated post back.
  • Topics: lock (with an optional reason) and pin. A locked topic takes replies, reactions and edits only from staff.
  • Categories: besides who can read one (minimum trust), each has a rule for starting topics and one for replying: everyone who can read it, a minimum trust level, or staff only. That covers announcement forums (staff start topics, members reply) and read-only windows (TL1 reads, TL3 posts). A new subcategory starts with its parent’s rules; nothing is inherited after that.
  • Reactions per category: all reaction types (the default), only some, or none.
    • Off hides reaction buttons and counts on posts, tiles and strips there. The server refuses new reactions (reactions_off, or reaction_not_offered for a type outside the set).
    • The Reacted page and reaction notifications leave those categories out.
    • Existing reactions are kept and come back when turned on again.
    • A new subcategory starts with its parent’s setting.
    • Changes are in the moderation log.
  • Flags: members (MIN_TRUST_TO_FLAG, verified, not silenced) flag a post once for spam / abusive / off topic / other.
    • A post hides itself pending review when distinct flaggers ÷ readers ≥ FLAG_HIDE_RATIO and there are at least FLAG_HIDE_MIN_FLAGS of them, or once there are FLAG_HIDE_ENOUGH_FLAGS.
    • “Readers” are members whose read position in the topic is at or past the post (topic_reads), not counting its author: the people who could have seen it and chose not to flag.
    • The queue (/admin/flags) shows the ratio and its inputs, each flagger’s record (upheld ✓ / dismissed ✗), and the author at a glance. Every action is inline: dismiss, moderate, delete, lock, and silence, suspend or ignore flags for the author or a flagger.
  • People:
    • Cooldown: read-only (can read, can’t post, reply, react or flag) for 1h / 1d / 3d / 7d / 30d / 90d or a custom length, never more than 90 days, always with a reason. They see “Read-only until …: reason”. It ends by itself: the end is compared with the clock, so no job runs.
    • Suspend: can’t sign in; sessions and app tokens are revoked. Takes a reason and an optional end, both shown on the sign-in page.
    • Flag shadowban: their flags are recorded and look normal to them, but don’t count and are kept apart in the queue.
    • From the flag queue, /admin/users/{id}, or manage user cooldown|end-cooldown|suspend|unsuspend|flag-shadowban|unflag-shadowban <name>.
  • Lameness filter (src/lameness.rs): every new or edited post is scored, and junk is held for review instead of published.
    • Posts over MAX_POST_CHARS (32,000, Discourse’s default) are refused outright (413 too_long; the composers also set maxlength).
    • Signals, each with a reason staff and the author can read:
      • zlib compression ratio;
      • distinct-word share;
      • one 3-word phrase repeated (LAMENESS_MAX_REPEAT);
      • repeated lines;
      • character runs and short repeated units (“!!!!”, “lololo”);
      • low character entropy;
      • mostly capitals;
      • the same text as your recent posts;
      • many links from a TL0 account.
    • Fenced and inline code and > quotes are taken out of the prose signals: logs and tables repeat legitimately. Together they’re scored only by compression, at 4% over 4,000+ chars, so a wall pasted into a fence is still caught.
    • Calibrated against this README, docs/*.md, the demo posts, a source file and Cargo.lock in fences. Real prose compresses to 35–60%; the reported 22k-char wall compresses to 0.5%. The unit tests check both. manage lameness score <file|-> prints every measurement, for tuning.
    • A held post is saved but hidden, like the flag auto-hide. It is logged (system) and shown in the queue as the filter’s, with its scores.
      • The author sees “Held for review: ”; others see “Hidden pending staff review”. Staff are scored but never held.
      • Dismiss: a false positive. The post is shown again, with no strike.
      • Moderate or delete: upheld. That is a strike for the author.
      • The author deleting it first is a withdrawal, with no strike.
      • Edits are scored again, so an approved post edited into junk is held again.
    • Strikes: upheld holds within LAMENESS_STRIKE_DAYS (90). The Nth strike applies the Nth step of LAMENESS_LADDER:
      • 1: a warning;
      • 2: 1 hour read-only;
      • 3: 1 day;
      • 4: 7 days;
      • 5: 30 days;
      • 6: 90 days;
      • 7 and beyond: suspended pending staff review.
      • Each step is logged as system, and the user is told why.
      • A cooldown never shortens a longer one.
    • Only upheld holds strike: a false positive staff haven’t reviewed yet punishes no one, since the post is already hidden.
    • Flood guard: LAMENESS_FLOOD_HOLDS (3) holds within LAMENESS_FLOOD_WINDOW (1h) give an immediate LAMENESS_FLOOD_COOLDOWN (1h) read-only, without a strike.
    • Strikes and the next step are shown on /admin/users/{id} and in the queue. Staff clear them there or with manage user strikes <name> --clear; holds stay as history.
  • Log: every staff action, from the web or the CLI, is in /admin/log (also per user).

Posts are markdown (CommonMark plus tables, strikethrough, task lists, footnotes), and bare http(s):// addresses become links.

Off-site links go through /out. It is a page that says “You are leaving recourse @ this host to go to:”, with the address and its host in bold. An internationalised host is shown both ways (bücher.example / xn--bcher-kva.example). It has Continue and Back buttons, never redirects by itself, and works signed out.

  • Links to this site (PUBLIC_URL’s host) and relative links stay direct.
  • Every link gets rel="nofollow ugc noopener noreferrer".
  • /out?u=…&s=… carries an HMAC of the destination (LINK_SECRET). An unsigned or altered link shows the address as text, with a warning and no Continue, so the page can’t be used as an open redirect.
  • The rewrite happens when a post is shown, not when it’s saved. Old posts, a new host name or a rotated secret all just work, with no recook.
  • The API sends the same links, absolute. The app shows its own “Leaving” dialog for them and for any other off-site link.
  • Off-site images still load directly from their hosts. A caching image proxy would hide readers’ addresses from them; it isn’t built.

Client addresses

What is collected: the address an account used when it:

  • signed in (password or single sign-on);
  • registered (redeeming an invite);
  • started a topic or replied;
  • flagged a post;
  • used the app (at most one update per address every ten minutes).

That gives one row per account and address (first and last seen, a count, the last action), plus the address on each flag.

Why: spotting a sock-puppet or a returning suspended member. A flag queue item says when the author shares an address with other accounts.

Who sees it: staff only, and every look is logged.

  • The address list on /admin/users/{id} sits behind a button that writes to the moderation log. It shows the other accounts at each address and whether they are read-only or suspended.
  • /admin/ips/{ip} also lists the same /24 (IPv4) or /64 (IPv6), as a lead, not proof. It is logged too.
  • Addresses never appear on members’ pages or in /api/v1.

How long: rows not seen for IP_RETENTION_DAYS (default 180) are deleted, and older flags lose their address. The server purges at start and hourly; manage ips purge [--days N] does it on demand. 180 days covers several cooldown or suspension cycles (a cooldown is at most 90 days), which is when a returning account matters, without keeping a history of where everyone has been.

Behind a proxy: the server reads the TCP peer. Only when that peer is in TRUSTED_PROXIES does it take the client from X-Forwarded-For: the rightmost entry that isn’t itself a trusted proxy, since everything to its left is whatever the client sent. With no X-Forwarded-For it falls back to X-Real-IP. An untrusted peer’s headers are ignored. This is angler’s TRUSTED_PROXIES and gitgud’s rule.

Unset, it trusts loopback and the private ranges (127.0.0.0/8, ::1/128, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7), as angler and gitgud do: right for nginx on the same host or a cluster ingress. Narrow it to your proxy (e.g. 127.0.0.1/32, or the ingress pod range) if other machines on those private networks can reach the app directly, since they could otherwise claim any address. TRUSTED_PROXIES=none trusts nothing (exposed directly to the internet, no proxy).

Configuration (environment)

Var Default Meaning
APP_NAME recourse Display name in templates
DATABASE_URL postgres://recourse_user:recourse_password@localhost:5439/recourse Postgres connection
BIND_ADDRESS 0.0.0.0:3000 Listen address
SESSION_DURATION_HOURS 24 Cookie session lifetime
REGISTRATION_TOKEN_DURATION_DAYS 7 Default invite validity
AUTO_MIGRATE true Run migrations on boot
REGISTRATION_ENABLED false Allow /register without an invite link (token still required)
PUBLIC_URL http://localhost:<BIND port> Public origin: base of email-verification links, the default OIDC redirect URI and the API-token curl example. https:// also marks the session cookie Secure
MIN_TRUST_TO_CREATE_TAG 3 Trust level needed to mint new tags
MIN_TRUST_TO_FLAG 1 Trust level needed to flag a post (0–4)
FLAG_HIDE_RATIO 0.1 Auto-hide a post when distinct counted flaggers ÷ readers of it reaches this (0–1]; see Moderation
FLAG_HIDE_MIN_FLAGS 2 …and at least this many flaggers (one person never hides a post)
FLAG_HIDE_ENOUGH_FLAGS 10 …or this many, whatever the readership
TRUSTED_PROXIES loopback + private ranges Comma-separated CIDRs of reverse proxies whose X-Forwarded-For / X-Real-IP is believed, e.g. 127.0.0.1/32 (nginx on the host), 10.0.0.0/8 (a cluster ingress); none trusts nothing. See Client addresses
IP_RETENTION_DAYS 180 How long client addresses are kept
MAX_POST_CHARS 32000 Longer posts are refused (413 too_long)
LAMENESS_ENABLED true Score posts and hold junk for review (see Moderation)
LAMENESS_COMPRESS_RATIO / _MIN 0.20 / 800 Hold prose of 800+ chars that zlib shrinks below 20% (prose: 35–60%)
LAMENESS_CODE_COMPRESS_RATIO / _MIN 0.04 / 4000 The same for code and quotes, much stricter (logs and source: 12–45%)
LAMENESS_DISTINCT_RATIO / LAMENESS_WORDS_MIN 0.12 / 200 Hold when distinct words ÷ words falls below this (long prose: ~0.3)
LAMENESS_MAX_REPEAT 30 One 3-word phrase this many times
LAMENESS_REPEATED_LINES / _LINES_MIN 0.5 / 6 Share of lines that repeat an earlier one
LAMENESS_MAX_RUN 25 One character this many times in a row (markdown rules aside), or a short unit over twice that
LAMENESS_ENTROPY_BITS / _MIN 2.5 / 300 Character entropy floor (English ~4.2, a table of numbers ~3.2)
LAMENESS_CAPS_RATIO / _MIN 0.75 / 150 Share of letters in capitals
LAMENESS_DUP_MAX / _HOURS 2 / 24 The same text as this many of your posts in this many hours
LAMENESS_LINKS_MAX / _TRUST 8 / 1 More links than this from accounts below this trust level
LAMENESS_STRIKE_DAYS 90 How long an upheld hold counts as a strike
LAMENESS_LADDER none,1h,1d,7d,30d,90d,suspend What the 1st, 2nd, … strike brings (none, <n>m/h/d/w read-only up to 90d, suspend); past the end, the last
LAMENESS_FLOOD_HOLDS / _WINDOW / _COOLDOWN 3 / 1h / 1h That many holds in the window → read-only for the cooldown, before review
LINK_SECRET (a development value) Signs /out links (see Links in posts). Set a long random string in production; changing it just re-signs links as they’re shown
MAIL_PRISM_URL / MAIL_PRISM_API_KEY (unset) Send mail through mail-prism. Unset (or blank): mail is only logged
MAIL_FROM_ADDRESS (the key’s application address) Must equal the mail-prism application address if set
MAIL_FROM_NAME APP_NAME From display name
EMAIL_VERIFICATION_TTL_HOURS 48 Lifetime of a verification link
REQUIRE_EMAIL_VERIFICATION true Unverified accounts can read but not post/reply/react/bookmark/tag
OIDC_ENABLED, OIDC_LOGIN_MODE, OIDC_* off “Sign in with NEIAM”; see below and the neiam-auth README
OIDC_PASSWORD_LOGIN true false hides and refuses password login (implied by OIDC_LOGIN_MODE=sso_strict)

Layouts: Classic and Focus

Two layouts for browsing: Classic (lists and tables) and Focus (full-screen tiles with a reader you step through). Pick the default under Profile → Layout. The Classic/Focus switch on a page is a temporary override: signed in, it lasts until the browser closes (a session cookie) and never changes the profile, and saving the profile clears it; signed out, it is remembered in a cookie for a year. Links between pages carry no layout, so nothing flips while you browse. ?view=classic|focus works in any URL (the old list / visual are accepted too).

In Focus:

  • Category /c/{slug}: the category fills the page. The categories beside it are squares on a rail (the current one has the accent border; on small screens the rail is a horizontal strip), and .. goes up a level, or to the home page from a top-level category. The category’s own topics are tiles: title, poster and top-replier avatars, replies, views, last activity, tags, reactions, and new / N unread for signed-in users. Each subcategory is a column of compact topic squares with a “Focus on …” link.
  • Home /: two columns in both layouts. Categories on the left (top level, with their subcategories); on the right Latest and, under it, Popular (topics active in the last 30 days, ranked by replies, reactions and views, newer activity counting for more). A tile opens the reader on its own row. Each heading opens the full feed, /p/latest and /p/popular; in Focus those have a rail with .. back home, both feeds, and the top-level categories.
  • All categories /c/: a tile per top-level category with its subcategories and latest topics. Tags /tags: a tile per tag with its latest topics.
  • Tag, search, bookmarks, reactions and notifications: their topics as tiles. Tags get a rail of other tags. Bookmarks, reactions and notifications add lines to each tile saying what was bookmarked, how many reactions, or which notifications; notifications are grouped by topic.
  • Reader: on any of those pages, &topic=<id> opens a topic over the page with a filmstrip of that page’s list. ← / → (or k / j) step through it, Escape or a click outside closes it, and each step is a URL, so the back button works.
  • Topic /t/{id}: the same page at full screen. Posts are centred at reading width, with the category rail on one side and a filmstrip of the category’s topics below; ← / → step and Escape goes back to the category. The reply form, editing, history, tag editing, watch and moderation work as on the Classic page.

Visibility, min-trust, unverified/anonymous permissions, views and read tracking work the same in both layouts: the reader and the Focus topic page count a view and mark the topic read exactly as the Classic topic page does. Category management (/admin/categories: nested cards, with a + that turns into a form and then the new card) and invites (/invites) have Focus pages too. The rest of admin, auth, profile and the new-topic/edit forms are Classic only. See src/handlers/focus.rs (modelled on pin_flip’s focus mode and shared pages, and cartosnap’s shared-trip stepping).

Android app and API

android/ is the phone client (Kotlin + Compose): browse in Classic or Focus (the profile’s Layout), read, reply, start topics, react, bookmark, watch, tags, search, notifications, profile. Pair it from Devices in the account menu, which shows a QR of recourse://pair?base=…&token=… once; the same page renames and revokes devices. Build with just apk (it finds a JDK 17–21 even when the system java is 25); see android/README.md.

It talks to /api/v1 (docs/api.md), bearer tokens only, with the web’s visibility, trust, verification, view and read rules — the API calls the same code (src/actions.rs for writes). just test-db runs the API tests against a scratch database; just fixtures refreshes the responses the app’s contract test decodes. The plan, and what came out differently, is docs/android.md.

Email verification

New accounts (registration through an invite) start unverified: they can read everything but can’t post, reply, react, bookmark or create tags until they follow the link mailed to them. A banner says so, with a “Resend link” button (also on the profile; at most one link per 10 minutes). Links are single-use, expire after EMAIL_VERIFICATION_TTL_HOURS, and a new one replaces the previous one; only a SHA-256 of each token is stored. Accounts that existed before verification was added were marked verified by the migration; accounts made with manage user create start verified, as do accounts signing in through an OIDC provider with OIDC_TRUST_EMAIL=true that vouches for the address.

Mail goes through mail-prism when MAIL_PRISM_URL and MAIL_PRISM_API_KEY are set. The templates live in this repo under mail_prism/ and the webservice pushes them to mail-prism on startup (PUT /api/v1/templates); each verification mail carries an idempotency_key per token, so a retry never sends twice. The client crate is vendored in crates/mail-prism-client (the mail-prism repo is private; see its VENDORED.md).

Without mail-prism (development) the app runs normally and writes each message, link included, to its log at INFO (outbound mail (log transport …)). manage user verify-email <name> skips the link; manage user resend-verification <name> prints a fresh one; manage email test <to> checks the mail-prism setup.

Sign in with NEIAM

neiam-auth v0.4.0 (git dependency, pinned to the tag, sea-orm feature for sea-orm 1.1). Off by default: until OIDC_ENABLED=true there is no button and /auth/oidc/* returns 404 (except /auth/oidc/health). The oidc_identities migration always runs.

OIDC_ENABLED=true
OIDC_LOGIN_MODE=mixed                   # local | mixed (default) | sso | sso_strict
OIDC_ISSUER=https://auth.neiam.org
OIDC_CLIENT_ID=recourse
OIDC_CLIENT_SECRET=...                  # or OIDC_CLIENT_SECRET_FILE
OIDC_REDIRECT_URI=https://<host>/auth/oidc/neiam/callback   # default: ${PUBLIC_URL}/auth/oidc/neiam/callback
OIDC_SCOPES="openid profile email groups"
OIDC_GROUPS_CLAIM=groups
OIDC_TRUST_EMAIL=true                   # LDAP mail is admin-set
OIDC_LABEL="Sign in with NEIAM"
OIDC_LOGOUT_URL=https://auth.neiam.org/logout
# OIDC_PROVISION=invite_only            # default; `auto` creates accounts on first login
# OIDC_PROVISION_GROUPS=forum           # invite_only, but members of these groups get an account

Linking (src/auth/oidc.rs): an existing (iss, sub) link; “Link NEIAM account” on the profile; a single active account with the same verified email (with OIDC_TRUST_EMAIL); or a new, passwordless account — only through an invite (/register?token=… shows “Sign up with NEIAM”; in sso_strict the invite link goes straight there) or PROVISION=auto / PROVISION_GROUPS, keeping registration invite-only by default. A taken username or email is never taken over, and accounts created this way are never staff. In sso_strict, password login and local registration are refused.

Binaries

  • recourse — the web service
  • manage — admin CLI:
    • manage user create <name> --email E [--staff] [--password-stdin] — no invite needed; without --password-stdin a strong password is generated and printed once
    • manage user list | set-staff <name> [--revoke] | set-trust <name> <0-4> | activate <name> | deactivate <name> | delete <name> --yes
    • manage user verify-email <name> | resend-verification <name>
    • manage user cooldown <name> <12h|5d|2w> --reason R [--by STAFF] (≤ 90 days), suspend <name> [--reason R] [--hours N | --days N] [--by STAFF], end-cooldown|unsuspend <name>, flag-shadowban|unflag-shadowban <name> [--reason R] — logged as cli (and the --by account) in the moderation log
    • manage ips purge [--days N] — delete client addresses older than IP_RETENTION_DAYS
    • manage lameness score <file|-> — every lameness measurement for a post body, and whether it would be held
    • manage user strikes <name> [--clear [--by STAFF]] — lameness strikes and the next ladder step; --clear resets them (logged)
    • manage invite create [--email E] [--days N] | list | show <token>
    • manage email test <to> — send a test message through mail-prism (or report it isn’t configured)
    • manage seed [--demo [--allow-public]] — baseline categories/reactions/tags; --demo adds demo users and content
    • Justfile shortcuts: just manage …, just admin <name> <email>, just invite [days], just staff <name>, just trust <name> <level>, just seed, just seed-demo