/api/v1 for the Android app; device tokens; Devices page with QR pairing

63417ef · gmorell · 2026-12-03 01:23

43 files +2397 -269
Message
{commit_body(@commit)}

Files changed

modified Cargo.lock
+8 −0
@@ -3006,6 +3006,12 @@ version = "0.11.0"
3006 3006 source = "registry+https://github.com/rust-lang/crates.io-index"
3007 3007 checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
3008 3008
3009 +[[package]]
3010 +name = "qrcode"
3011 +version = "0.14.1"
3012 +source = "registry+https://github.com/rust-lang/crates.io-index"
3013 +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
3014 +
3009 3015 [[package]]
3010 3016 name = "quanta"
3011 3017 version = "0.12.6"
@@ -3230,11 +3236,13 @@ dependencies = [
3230 3236 "minijinja-embed",
3231 3237 "neiam-auth",
3232 3238 "pulldown-cmark",
3239 + "qrcode",
3233 3240 "sea-orm",
3234 3241 "serde",
3235 3242 "serde_json",
3236 3243 "sha2 0.10.9",
3237 3244 "tokio",
3245 + "tower",
3238 3246 "tower-http",
3239 3247 "tracing",
3240 3248 "tracing-subscriber",
modified Cargo.toml
+6 −0
@@ -54,6 +54,8 @@ neiam-auth = { git = "https://gg.neiam.co/neiam/neiam-auth.git", tag = "v0.4.0",
54 54 mail-prism-client = { path = "crates/mail-prism-client" }
55 55 # SHA-256 of email-verification tokens (only the hash is stored).
56 56 sha2 = "0.10"
57 +# The Devices page's pairing QR (movie_monster's, SVG only).
58 +qrcode = { version = "0.14", default-features = false, features = ["svg"] }
57 59
58 60 # Markdown rendering for post bodies
59 61 pulldown-cmark = "0.12"
@@ -64,3 +66,7 @@ clap = { version = "4.5", features = ["derive"] }
64 66
65 67 [build-dependencies]
66 68 minijinja-embed = "2.12"
69 +
70 +[dev-dependencies]
71 +# Drives the real router in tests/api_db.rs (`ServiceExt::oneshot`).
72 +tower = { version = "0.5", features = ["util"] }
modified Justfile
+10 −0
@@ -86,6 +86,16 @@ check:
86 86 cargo check --bins --lib
87 87 cargo test --lib
88 88
89 +# The /api/v1 tests against a real database (tests/api_db.rs). They create
90 +# their own rows with unique names, but use a scratch database, not your dev one:
91 +# podman exec recourse_postgres createdb -U recourse_user recourse_test
92 +test-db url="postgres://recourse_user:recourse_password@localhost:5439/recourse_test":
93 + TEST_DATABASE_URL={{url}} cargo test --test api_db
94 +
95 +# Re-capture the API responses the Android ContractTest decodes (needs the test database)
96 +fixtures url="postgres://recourse_user:recourse_password@localhost:5439/recourse_test":
97 + TEST_DATABASE_URL={{url}} WRITE_ANDROID_FIXTURES=1 cargo test --test api_db android_fixtures
98 +
89 99 # A fresh database (no users yet) is also migrated and given demo content
90 100 # (`seed --demo`); an existing one is left alone.
91 101 # Bring up just Postgres for local dev (fresh DB: migrate + seed --demo)
added docs/api.md
+132 −0
@@ -0,0 +1,132 @@
1 +# recourse mobile API
2 +
3 +The JSON API the Android app (`android/`, plan in `docs/android.md`) talks
4 +to. It follows the family's conventions (pin_flip's `docs/api.md`,
5 +party-slut's `/api/v1`), and the server half is rosin_hunter_3000's shape: a
6 +`/api/v1` nest with its own bearer-only middleware.
7 +
8 +## Signing in
9 +
10 +Each device gets its own **token**. Only its SHA-256 is stored; the token
11 +itself is shown once.
12 +
13 +1. On the web, open **Devices** (the account menu) → *Pair a device*. The
14 + page shows a QR of `recourse://pair?base=<server>&token=<token>`, and the
15 + two fields as text. `base` is `PUBLIC_URL` when set, otherwise the origin
16 + the browser is using (`X-Forwarded-Proto`/`-Host`, then `Host`).
17 +2. The app scans it (or the phone opens the link, or the fields are typed),
18 + calls `GET /api/v1/me`, and keeps the token only if that answers 200.
19 +
20 +Send it as `Authorization: Bearer <token>`. The session cookie is **not**
21 +accepted here: the API has no CSRF protection of its own.
22 +
23 +A token stays valid for 90 days after it was last used; use is recorded at
24 +most once a day, and each recording slides the expiry. Tokens minted before
25 +expiries existed keep none. A deactivated account's tokens stop working.
26 +`DELETE /api/v1/sessions/current` unpairs the calling device; the Devices page
27 +and `DELETE /api/v1/me/devices/{id}` revoke any. A revoked token's next
28 +request is a `401`.
29 +
30 +The older `GET /api/profile` (cookie or bearer) is unchanged.
31 +
32 +## Conventions
33 +
34 +- **Format:** snake_case keys, UUIDv7 ids, ISO-8601 UTC timestamps.
35 +- **Permissions:** `may_write`, `may_create_tags`, `can_reply`,
36 + `can_edit_tags`, `can_post`, `can_edit` are computed by the server; the app
37 + shows or hides controls from them and holds no rules of its own. The server
38 + checks every write regardless.
39 +- **Visibility:** exactly the web's. A category is visible when it and every
40 + ancestor admit the user's trust level (or they're staff). Anything you
41 + can't see is a `404`, whether or not it exists — topics, posts, tags used
42 + only in hidden categories, and writes aimed at any of them. Lists (search,
43 + tags, bookmarks, notifications, unread count) leave hidden things out.
44 +- **Email verification:** when the site requires it, an unverified account
45 + reads everything it may see, and every write answers
46 + `403 unverified`. `POST /me/verification` sends a new link.
47 +- **Reading** a topic counts a view (at most once per ten minutes per user)
48 + and marks it read up to its last post, as on the web.
49 +- **Toggles** take the desired state (`{"bookmarked": true}`), so a retried
50 + request lands on the same value.
51 +- **Images:** `avatar_url` is server-relative (`/u/{id}/avatar`), public, and
52 + is either the upload or a generated SVG.
53 +- **Post bodies:** `cooked` is the server's sanitized HTML of the markdown —
54 + the web's own rendering.
55 +- **Errors** always use this shape:
56 + `{"error": {"code": "...", "message": "...", "details": {...}|null}}`
57 +
58 +| Status | Codes |
59 +|---|---|
60 +| 400 | `bad_request` (unreadable JSON or a malformed id; `details.reason`) |
61 +| 401 | `unauthorized` |
62 +| 403 | `unverified`, `closed` (topic closed to replies), `not_author` (tags) |
63 +| 404 | `not_found` |
64 +| 410 | `removed` (a deleted topic, for non-staff) |
65 +| 422 | `invalid` (the message says what) |
66 +
67 +## Endpoints
68 +
69 +All paths start with `/api/v1`, and all need a token.
70 +
71 +**Me and devices**
72 +
73 +| Method | Path | Notes |
74 +|---|---|---|
75 +| GET | `/me` | `{user, verification_required, min_trust_to_create_tag}`. `user` has `preferred_view` (`classic`/`focus`), `preferred_sort`, `may_write`, `email_verified`, `trust_level`, `trust_name`, … |
76 +| PATCH | `/me` | `{layout?, sort?, reaction_notifications?}` → as `GET /me`. The web's profile reads the same fields. |
77 +| PUT | `/me/avatar` | multipart, part `avatar` (PNG/JPEG/GIF/WebP, ≤ 5 MB) → as `GET /me` |
78 +| DELETE | `/me/avatar` | back to the letter avatar → as `GET /me` |
79 +| POST | `/me/verification` | `{result: sent \| recent \| verified \| failed}`; rate-limited as on the web |
80 +| GET | `/me/devices` | `{devices: [{id, label, created_at, last_used_at, expires_at, current}]}` |
81 +| DELETE | `/me/devices/{id}` | 204 |
82 +| DELETE | `/sessions/current` | 204; this device's token is revoked |
83 +
84 +**Browsing**
85 +
86 +| Method | Path | Notes |
87 +|---|---|---|
88 +| GET | `/categories` | `{categories: [{id, slug, name, colors, description, parent_id, depth, topic_count, watching}]}` in tree order |
89 +| GET | `/categories/{slug}?sort=` | `{category, ancestors, subcategories, sort, topics, can_post}`. `topics` covers the category and its visible subcategories, pinned first. A given `sort` is saved as the account's, as on the web. |
90 +| PUT | `/categories/{slug}/watch` | `{watching}` → `{watching}` |
91 +| POST | `/categories/{slug}/topics` | `{title, body, tags?: [..]}` → 201, as `GET /topics/{id}` |
92 +| GET | `/topics/{id}` | `{topic, posts, can_reply, can_edit_tags, watching}` |
93 +| POST | `/topics/{id}/posts` | `{body}` (markdown) → 201, a post |
94 +| PUT | `/topics/{id}/tags` | `{tags: [..]}` → `{tags}`. Replaces; up to five; new names need `may_create_tags` and are otherwise dropped. |
95 +| PUT | `/posts/{id}/reaction` | `{key}` or `{key: null}` → `{reactions}` |
96 +| PUT | `/posts/{id}/bookmark` | `{bookmarked}` → `{bookmarked}` |
97 +
98 +A **topic summary** (in every list) is `{id, title, category, author,
99 +is_pinned, is_closed, posts_count, replies, views, created_at, bumped_at,
100 +tags, posters, reactions, is_new, unread, notes}` — what a Focus tile shows.
101 +`category` is `{id, slug, name, colors}`; `colors` is the lineage, root
102 +first, the web's category circle.
103 +
104 +A **post** is `{id, post_number, author, cooked, created_at, edited_at,
105 +deleted, bookmarked, reactions: [{key, emoji, count, reacted}], can_edit}`.
106 +
107 +**Finding**
108 +
109 +| Method | Path | Notes |
110 +|---|---|---|
111 +| GET | `/tags` | `{tags: [{name, slug, count}]}`, most used first |
112 +| GET | `/tags/{slug}` | `{tag, topics}` |
113 +| GET | `/search?q=` | `{q, topics}`; titles, post bodies, tag names; two characters minimum, 50 results |
114 +| GET | `/bookmarks` | `{bookmarks: [{post_id, topic_id, topic_title, post_number, cooked, deleted, created_at}]}` |
115 +| GET | `/notifications` | `{unread, notifications: [{id, kind, topic_id, post_id, topic_title, actor, is_read, created_at}]}`, the 50 newest |
116 +| GET | `/notifications/unread` | `{unread}` |
117 +| POST | `/notifications/{id}/read` | 204 |
118 +| POST | `/notifications/read` | 204; all of them |
119 +
120 +## Not in the API
121 +
122 +Everything under `/admin` (categories, reaction types), invites, editing and
123 +deleting posts and topics, sign-up and password sign-in stay on the web or
124 +the `manage` CLI. There is no push (docs/android.md §2e).
125 +
126 +## Testing
127 +
128 +`tests/api_db.rs` drives these routes through the real router against
129 +Postgres (`just test-db`; skipped without `TEST_DATABASE_URL`). `just
130 +fixtures` also writes the responses to
131 +`android/app/src/test/resources/api/`, which the app's `ContractTest`
132 +decodes.
modified migration/src/lib.rs
+2 −0
@@ -17,6 +17,7 @@ mod m20240101_000014_category_min_trust;
17 17 mod m20240101_000015_email_verification;
18 18 mod m20240101_000016_visual_mode;
19 19 mod m20240101_000017_layout_names;
20 +mod m20240101_000018_api_token_hash;
20 21
21 22 pub struct Migrator;
22 23
@@ -45,6 +46,7 @@ impl MigratorTrait for Migrator {
45 46 // apply this one next.
46 47 Box::new(m20240101_000016_visual_mode::Migration),
47 48 Box::new(m20240101_000017_layout_names::Migration),
49 + Box::new(m20240101_000018_api_token_hash::Migration),
48 50 ]
49 51 }
50 52 }
added migration/src/m20240101_000018_api_token_hash.rs
+39 −0

Click to load diff…

added src/api/error.rs
+95 −0

Click to load diff…

added src/api/find.rs
+228 −0

Click to load diff…

added src/api/forum.rs
+368 −0

Click to load diff…

added src/api/json.rs
+48 −0

Click to load diff…

added src/api/me.rs
+152 −0

Click to load diff…

added src/api/mod.rs
+60 −0

Click to load diff…

added src/api/views.rs
+246 −0

Click to load diff…

modified src/auth/api_tokens.rs
+118 −35

Click to load diff…

modified src/auth/mod.rs
+2 −1

Click to load diff…

modified src/entities/api_tokens.rs
+4 −1

Click to load diff…

deleted src/handlers/api_tokens.rs
+0 −128

Click to load diff…

added src/handlers/devices.rs
+200 −0

Click to load diff…

modified src/handlers/mod.rs
+1 −2

Click to load diff…

modified src/lib.rs
+1 −0

Click to load diff…

modified src/main.rs
+8 −5

Click to load diff…

modified src/middleware/auth.rs
+41 −1

Click to load diff…

modified src/middleware/mod.rs
+1 −1

Click to load diff…

modified templates/_index.html
+2 −2

Click to load diff…

deleted templates/api_tokens/created.html
+0 −28

Click to load diff…

deleted templates/api_tokens/list.html
+0 −64

Click to load diff…

added templates/devices/list.html
+55 −0

Click to load diff…

added templates/devices/pair.html
+52 −0

Click to load diff…

modified templates/root.html
+1 −1

Click to load diff…

added tests/api_db.rs
+517 −0

Click to load diff…

Parents: 7e143f3