37.3 KiB · text History 84bfe6e

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 or open 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 seed          # starter categories, reactions, tags and the welcome topic (needs the staff account above)
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, a few tags, and a pinned “Welcome to {APP_NAME}” topic in Announcements: a short starter (what the forum is for, left for staff to fill in, then verifying email, trust levels, layouts, reactions/bookmarks/watching, flagging, Markdown and the exit page) written by the oldest staff account, for staff to edit. It is made once, ever: a seed_markers row records it, so renaming, editing or deleting the topic (or changing APP_NAME) never brings it back. With no staff account yet it’s skipped (“create a staff account first … then re-run manage seed”), so create the first account before seeding; with no announcements category it’s skipped too. It’s inserted quietly: no notifications. manage seed prints Welcome topic: created, already seeded, or why it was skipped.
  • 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 (the demo’s own welcome; the baseline welcome above is added by demo-admin too, so both show); 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 (the welcome by its seed_markers row) and only missing ones are created, so re-running changes nothing and never overwrites edits. An instance seeded before the welcome existed gets it on its next manage seed, and nothing else changes. 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 and, once, the welcome topic); run it by hand, after creating the first staff account, if you want them.

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 (open sign-up or 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 Open sign-up: /register creates an account without an invite (unverified until the emailed link is followed). Invite links work either way. See Registration
REGISTRATION_PER_IP_PER_DAY 3 Open sign-ups per client address per 24 hours (0: no limit). Invites are exempt
REGISTRATION_MIN_FILL_SECS 3 Least time between serving the sign-up form and submitting it (0: off). Invites are exempt
REGISTRATION_UNVERIFIED_TTL_DAYS 7 Accounts that never verify their email and never post are deleted after this many days (0: kept). Only while REQUIRE_EMAIL_VERIFICATION
PUBLIC_URL http://localhost:<BIND port> Public origin: base of email-verification links, the default OIDC redirect URI, the API-token curl example and link-preview URLs. 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).

Shader backgrounds

Behind every page (both layouts) a WebGL2 pattern drifts slowly: neiam’s moire wallpaper and its relatives (Moire, Halftone, Bokeh, Starfield, Prism, Oil on glass, Bubbles, Absorbing spheres, Alternate), ported from party-slut. /shaders (Theme menu → Shaders, or the profile page) has a live preview of each, the effect toggles and each pattern’s own controls, and an Off. The choice is per browser, in localStorage (app:shader), like the theme. A browser that hasn’t chosen gets Oil on glass at 17% coverage, set once in src/handlers/shaders.rs and handed to the script on <body data-shader-default>.

Readability comes first: while a pattern is on, the content column sits on an opaque base-100 panel, so text is on exactly the theme’s own colours, and the header, menus, cards and the reader overlay are opaque already. With prefers-reduced-motion it draws one still frame unless “Always move” is on. A hidden tab draws nothing, and without WebGL2 there’s simply no background. The fragment shaders in assets/f/js/shaders/*.frag are neiam-device’s moire/shaders/*.frag, byte for byte (copy them again when they change there). esbuild inlines them (--loader:.frag=text, in the Justfile and Dockerfile).

Live updates

Signed-in pages keep one WebSocket open (/ws, the htmx ws extension, bundled from npm like htmx itself; src/live.rs, assets/f/js/live.js). When a topic gets visible new activity (a new topic or reply that wasn’t held, a hold or flag-hide dismissed, a held or hidden post moderated, a topic or post restored) the server tells each connection whose user may see that topic, checked when it’s sent with the Latest list’s own conditions (readable categories, not deleted, held topics only for author and staff). What it sends is a signal naming the categories touched, never content, at most once every 2 s per connection. The page’s live lists then refetch the page through the ordinary route, as that user, and swap in the fresh copy: Latest on the landing page and /p/latest, and the category page’s list (both layouts). New or moved-up rows flash. Under the open reader, while you’re typing, or when you’ve scrolled past the list’s top, the update waits behind an “N new — show” button instead.

Popular (on the landing page and /p/popular) refreshes itself every 5 minutes for everyone, anonymous visitors included, only while the tab is visible and the reader is closed.

The socket needs the session cookie (anonymous: 401, no socket on the page) and an Origin equal to PUBLIC_URL‘s (else 403). There are at most 5 per user and 2000 in all (429). A ping every 25 s keeps proxies from closing it as idle. The session is re-checked every minute, and a signed-out or expired one is closed with 1008, which the extension doesn’t retry; drops and restarts reconnect with jittered backoff. Connects and disconnects are logged at debug.

Events are in-process (a tokio broadcast), so this assumes one replica, as deployed. More than one would need the events fanned out between them, e.g. Postgres LISTEN/NOTIFY on a channel carrying the topic id. Posts made by manage (the seed) don’t announce themselves. The Android app doesn’t use the socket; it would need an OkHttp WebSocket with the cookie or a token-authenticated variant of /ws, and a JSON signal.

Paste a URL into Slack, Discord, iMessage or https://www.linkpreview.app and the unfurler fetches it once and reads <head>. It doesn’t run JavaScript and doesn’t follow hx-boost, so everything it needs is in the first response. root.html emits OpenGraph and Twitter-card tags (plus <link rel=canonical> and <meta name=description>) from a meta value built by src/meta.rs.

Route og:title og:description og:image
/t/<id> (Classic and Focus) the topic title the opening post as plain text, cut at a word near 200 chars with … the post’s first image if it’s on our host, else the site mark
/c/<slug> the category name its description, else 12 topics: A, B, C and 9 more. site mark
/ the site name <site>: a discussion forum. Latest: A, B and C. site mark
/c/ Categories on <site> 4 categories: A, B, C and D. site mark
/p/latest, /p/popular Latest on <site> / Popular on <site> the newest / most active titles site mark
/tags, /tag/<slug> Tags on <site> / #<tag> the busiest tags / 3 topics tagged #x: A, B and C. site mark

A topic page is og:type article, with article:published_time, article:modified_time, article:section (the category), an article:tag per tag, and <meta name=author>. A Focus list opened at a topic (?view=focus&topic=<id>, on /, the feeds, a category or a tag) carries that topic’s card, since that’s the URL people copy. /p/<id> 303s to its topic, and the card is the topic’s: og:url is the canonical /t/<id> with no #post anchor (a fragment never reaches the server, and the card describes the topic anyway).

Details worth knowing:

  • Built as anonymous, always. The unfurler has no session, so the card is computed from what an anonymous visitor may read, even when the request is signed in, using the same Viewer::anonymous() / Visible rules as the pages. A topic in a members-only, trust-gated or staff-only category, a held or deleted topic, or a hidden opening post gets a generic card (“A members-only discussion on ”, no title or excerpt, noindex), so a member who copies a link can’t leak it through the preview. A moderated opening post’s excerpt is the staff note that replaced it; the original lives only in the revision history and is never read here. List cards only name topics and categories that anonymous visitors can see. (A signed-in reader’s <title> still names the topic: that’s their browser tab, and a scraper never carries their session.)
  • Absolute URLs come from PUBLIC_URL (default http://localhost:<port>). Unlike movie_monster, Host / X-Forwarded-Host are never read: they’re client-controlled, and recourse trusts no header it doesn’t have to. Set PUBLIC_URL in production or the cards point at localhost.
  • Images. Only images on our own origin go in a card. A third-party image in the opening post isn’t hotlinked: we never vetted it, its host can swap what it serves after the fact, and every unfurl would tell that host who’s looking. Everything else gets the site mark, assets/f/img/site-mark.png: 512×512, composited from the Android launcher icon’s layers (so it declares og:image:width/height). The card is twitter:card: summary because nothing we have is a known wide image; summary_large_image would letterbox the square mark.
  • Indexing is opt-in. A page that builds no card (admin, auth, profile, devices, invites, moderation, bookmarks, notifications, reactions, search results) gets the site name, a generic description and noindex, nofollow.
  • Attribute escaping. The <head> tags go through the attr filter instead of minijinja’s default autoescape, which turns every / in a URL into &#x2f;: legal HTML, but plenty of unfurlers hand it back verbatim. & < > " are still escaped, so a title can’t break out of its attribute.

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.

Registration

Invite-only by default: /register needs an invite link (/register?token=…, from the Invites page or manage invite create), optionally pinned to one email address. With REGISTRATION_ENABLED=true anyone can sign up at /register without one; an invite link still works and is still redeemed (email pin included). Either way the account starts unverified (below) and is mailed a verification link, and the sign-up shows in the moderation log (Signed up, “open sign-up” or “with an invite”) and at the top of /admin/users, which lists newest accounts first.

Open sign-ups (no invite) pass three cheap guards (src/registration.rs):

  • Per address: at most REGISTRATION_PER_IP_PER_DAY accounts from one client address in 24 hours (the address as resolved through TRUSTED_PROXIES, counted from user_ips), else 429.
  • Honeypot: a website field people never see; a bot that fills it in is refused.
  • Fill time: the form carries a signed timestamp (HMAC, key derived from LINK_SECRET); a submission sooner than REGISTRATION_MIN_FILL_SECS, or with a missing, forged or day-old stamp, is refused and the form is shown again.

Redeeming an invite skips all three. An account that never verifies and never writes anything is deleted after REGISTRATION_UNVERIFIED_TTL_DAYS, checked at start and hourly, with a Removed unverified account log entry; staff accounts are never touched.

At boot the server logs its registration settings, and warns when REGISTRATION_ENABLED=true is combined with REQUIRE_EMAIL_VERIFICATION=false (anyone could post without a working address) or with no mail-prism configured (verification links would only be logged, so nobody can verify). It warns rather than refusing to start.

Single sign-on is separate: REGISTRATION_ENABLED doesn’t affect it. See Sign in with NEIAM.

Email verification

New accounts (open sign-up or 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.

OIDC_PROVISION is independent of REGISTRATION_ENABLED. With OIDC_PROVISION=auto, anyone who can sign in to the provider gets an account on first login, whether or not password sign-up is open, and it skips the open sign-up guards (the provider vouched for the login). With OIDC_TRUST_EMAIL=true and a verified email claim the account starts verified. Otherwise it starts unverified, like any other: no link is mailed at creation, so the person uses the banner’s “Resend link”. If they never verify and never post, the unverified-account sweep removes it (and its NEIAM link). With auto they get a fresh account the next time they sign in.

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 and the one-time welcome topic; --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