Files
AdamandAdam c83499763d Allow mobile clients to manage repeater claims and details (#2429)
Draft for feedback: a working version of native repeater claims and
edits from mobile clients, built on the repeater info feature from
#2415. Four open questions are at the end.

## Situation

Repeater info (#2415) can only be claimed and edited from a browser
session. Device tokens from `POST /api/auth/device-token` are limited to
`rx` (CoreDrive RX: settings and companion linking), and `GET
/api/repeaters/{pubkey}/info` treats a bearer token as anonymous. A
mobile client can show a repeater's details but can't offer "claim" or
"edit" natively.

`PUT /api/repeaters/{pubkey}/info` is also a full replace with no
precondition. Two people editing from the same copy silently overwrite
each other. That's rare in the browser, but likelier from an app that
keeps a cached copy.

## Change

Three commits, one per piece.

**1. Device-token scopes for the repeater routes** (`8aba3715`)

- `POST /api/auth/device-token` takes an optional `scopes` list. Omitted
(or `null`) still means `["rx"]`, so CoreDrive RX and every existing
token keep exactly their current permissions. An empty list or an
unknown scope answers 400, checked before the password.
- New scopes:
- `repeater:claim`: `POST` and `DELETE /api/repeaters/{pubkey}/claim`.
These already only add or remove the caller's own claim. Several
claimers per repeater, idempotent `POST`, unchanged.
- `repeater:edit`: `PUT /api/repeaters/{pubkey}/info`, still subject to
`CanEditRepeater`.
- Every device token may use `/api/auth/me` and `/api/auth/logout`, so a
repeater-only token can check and end its own login.
- `GET /api/repeaters/{pubkey}/info` with a token holding either
repeater scope returns `canEdit` and `claimedByMe`. An unknown or
expired token answers 401 rather than passing as anonymous, so a client
learns its login is gone. A valid token without a repeater scope still
gets the public view. A cookie still wins over a bearer header, as
elsewhere.
- `GET /api/account/repeaters` (My repeaters, from #2430) also takes a
token holding either repeater scope, so an app gets the account's claims
in one request. It can't build that list from the public catalog, where
claimers are display names, and reading repeaters one at a time would
miss a claimed repeater that has left the node list. An `rx`-only token
still answers 403.
- Scope checks are method-aware (`bearerScopesFor(method, path)`). The
repeater paths are added to the bearer CORS paths.
- Same handlers, validation, rate limit (`repeater`, 120/h per user and
per IP), audit actions and admin claim removal as the browser. Token
writes add `via: device` to the `repeater.claim`, `repeater.edit` and
`repeater.unclaim` rows, and the `user.login` row records the granted
scopes. The admin route keeps refusing bearer tokens.

**2. Conditional edits with a revision** (`9f9bf47b`)

- `users.db` schema v10 adds `repeater_info.revision`. Existing rows
start at 1; a repeater with no saved details is at 0. Claims don't
change it.
- `GET` (single and list) and `PUT` responses include `revision`.
- `PUT` accepts an optional `baseRevision`. The check is part of the
write statement, so of two saves from the same base exactly one lands:
- `baseRevision: 0` (first save): `INSERT … ON CONFLICT(pubkey) DO
NOTHING`.
- `baseRevision: n`: `UPDATE … SET revision = revision + 1 … WHERE
pubkey = ? AND revision = ?`.
- No match answers `409` with the stored details
(`canEdit`/`claimedByMe` included) and writes nothing. That's the same
shape `PUT /api/account/settings` uses for its conflicts.
  - A stale base is refused even when the body would change nothing.
- Permission is checked first, so a 409 never shows details to someone
who can't edit.
- Without `baseRevision` the save is unconditional and bumps the
revision, so `public/repeater-info.js` works unchanged.
- `/api/config/client` adds `userManagement.repeaterTokens: true`, so a
client can tell this server from one without the scopes or
`baseRevision` (older servers answer the device-token request with the
SPA page, as noted for `companionLinking`).

**Discovery and conflict recovery, for a client:**

1. Check `userManagement.repeaterTokens` in `/api/config/client`.
Without it, keep the claim and edit actions hidden.
2. Log in with `scopes: ["repeater:claim", "repeater:edit"]` (or just
what the client offers). The response echoes the granted `scopes`.
3. Read `GET /api/repeaters/{pubkey}/info` with the token. Show
Claim/Unclaim from `claimedByMe` and Edit from `canEdit`, and keep
`revision`.
4. Save with `PUT …/info` and `baseRevision` set to that revision. On
200, keep the new `revision` from the response. On 409, the body is the
current record: show or merge it, then retry with its `revision`. On
401, log in again. On 403, the account can no longer edit (for example
someone claimed it), so refresh from `canEdit`.

**3. Account page device list** (`d28374aa`)

My account, Devices labelled every device token "CoreDrive RX".
`/api/account/sessions` now includes a device token's `scopes`. The page
keeps the CoreDrive RX label for `rx` tokens (and rows without scopes).
It shows other tokens under the device name the app sent, with a line
such as "can claim repeaters and edit repeater details".

Docs: `openapi.go`, `docs/api-spec.md` and the Repeater info section of
`docs/user-guide/accounts.md`.

## Questions

1. **One scope or two?** This uses separate `repeater:claim` and
`repeater:edit`, so a client can ask for less, and a token that only
edits can't put the user's name on a repeater publicly. One `repeater`
scope would be simpler if you'd rather not split it.
2. **Editing unclaimed repeaters from mobile.** This keeps web parity:
any active user may edit a repeater nobody has claimed, and once it has
claimers only they (and admins) can. The alternative is to require a
claim before a token may edit. That's stricter, but then app and browser
rules differ.
3. **Operator switch.** There's no new setting: the scopes are available
whenever `userManagement` is on, and the user opts in when the app asks
for them at login. Would you want an explicit opt-in such as
`userManagement.mobileRepeaterWrites`?
4. **Stale-edit contract.** Does `revision` plus `baseRevision` in the
body, with 409 returning the current record, fit? I matched account
settings rather than `ETag`/`If-Match`, to keep one pattern in the API.
The browser editor doesn't send `baseRevision` yet. Making it send one
would be a small follow-up, if you want browser saves protected too.

## Tests

- `cmd/server/repeater_device_token_test.go`:
- default and requested scopes, rejected scopes, and the method-aware
route table;
- per-scope allowed and denied routes, logout with a repeater-only
token;
  - claim and unclaim of own claim only, alongside another claimer;
- edit permission (unclaimed repeater, claimer, non-claimer, admin) and
a disabled account;
  - the admin route refusing tokens;
  - authenticated, public and expired-token reads;
- `via: device` audit rows, cookie writes still needing CSRF, and
session scopes.
- My repeaters with a claim or edit token (own claims only), and 403 for
an `rx`-only token.
- `cmd/server/repeater_revision_test.go`:
- revision on reads, a first edit with no saved row, and a stale base
returning 409 with the current record and no audit row;
  - unconditional browser saves, validation and permission order;
- two concurrent saves from the same revision (one 200, one 409), and
the client config flag.
- `internal/users/repeater_revision_test.go`:
  - revision counting and conditional first and later saves;
  - an 8-way race for both cases (`-race`);
  - the v9 to v10 upgrade.
- `tests/unit/test-user-management-ui.js`: app token labels and scope
line.

Run locally:

- `make test`: all 16 modules OK.
- `sh test-all.sh`: all suites pass, run in `node:24-bookworm`. On
macOS, `test-manage-workflow.js` fails 2 cases on unchanged master
because of the BSD tools.
- `npx eslint public/*.js`: 0 errors, the same 87 warnings as master.
- `node tests/e2e/test-lint-network-calls.js`
- `tests/e2e/test-user-management-e2e.js` against local e2etest servers
with the CI config: 44/44.
- Manually against a local instance:
  - in the browser: claim, edit, unclaim, and the Devices list;
  - with curl: the token flow, including a 409 after a browser save.

Not run: the full Playwright shard matrix from CI.

---------

Co-authored-by: Adam <196335+anieto@users.noreply.github.com>
2026-11-21 22:27:48 +01:00

309 lines
11 KiB
Go

package main
import (
"net/http"
"net/url"
"strings"
"time"
"github.com/meshcore-analyzer/users"
)
const (
sessionCookieName = "cs_session"
csrfHeader = "X-CS-CSRF"
)
// Device-token scopes. A token holds the scopes it asked for at
// POST /api/auth/device-token (deviceScopeRX when it asked for none).
const (
// deviceScopeRX is CoreDrive RX: account settings and companion linking.
deviceScopeRX = "rx"
// deviceScopeRepeaterClaim claims a repeater and removes the caller's own
// claim.
deviceScopeRepeaterClaim = "repeater:claim"
// deviceScopeRepeaterEdit edits a repeater's details, still only where
// CanEditRepeater allows the account to.
deviceScopeRepeaterEdit = "repeater:edit"
)
// deviceScopes are the scopes a client may request, in a fixed order.
var deviceScopes = []string{deviceScopeRX, deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}
// repeaterRoute splits /api/repeaters/{pubkey}/{what} and returns what
// ("info" or "claim"), or "" for any other path. The pubkey segment is only
// checked to be non-empty; the handler validates it.
func repeaterRoute(path string) string {
rest, ok := strings.CutPrefix(path, "/api/repeaters/")
if !ok {
return ""
}
pk, what, ok := strings.Cut(rest, "/")
if !ok || pk == "" || (what != "info" && what != "claim") {
return ""
}
return what
}
// bearerScopesFor returns the scopes that let a device token use method on
// path (any one of them is enough), or nil when no device token may use it.
// Any device token may read and end its own login; RX routes need rx;
// repeater claims need repeater:claim and repeater edits repeater:edit. A
// read of one repeater's details takes either repeater scope (it adds the
// caller's canEdit and claimedByMe), and so does the list of the caller's
// own claims (My repeaters), which an app cannot build from the public
// catalog: claimers there are display names, and a claimed repeater may
// have left the node list.
func bearerScopesFor(method, path string) []string {
switch {
case path == "/api/auth/me", path == "/api/auth/logout":
return deviceScopes
case path == "/api/account/repeaters":
if method == http.MethodGet || method == http.MethodHead {
return []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}
}
return nil
case path == "/api/account/settings", path == "/api/account/companions",
strings.HasPrefix(path, "/api/account/companions/"):
return []string{deviceScopeRX}
}
switch repeaterRoute(path) {
case "claim":
if method == http.MethodPost || method == http.MethodDelete {
return []string{deviceScopeRepeaterClaim}
}
case "info":
switch method {
case http.MethodPut:
return []string{deviceScopeRepeaterEdit}
case http.MethodGet, http.MethodHead:
return []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}
}
}
return nil
}
// bearerCORSPath reports whether path takes cross-origin writes from an
// allowlisted origin: the device-token login and the bearer routes. It is
// judged on the path alone, since a preflight names the method only in a
// header; outside the repeater routes the scopes do not depend on the method.
func bearerCORSPath(path string) bool {
return path == "/api/auth/device-token" || repeaterRoute(path) != "" ||
len(bearerScopesFor(http.MethodGet, path)) > 0
}
// hasAnyScope reports whether sess holds at least one of scopes.
func hasAnyScope(sess *users.Session, scopes []string) bool {
for _, sc := range scopes {
if sess.HasScope(sc) {
return true
}
}
return false
}
// bearerToken returns the token of an "Authorization: Bearer" header and
// whether the request is to be judged on it. A request that carries the
// session cookie is not: the cookie decides, so an auth proxy that adds its
// own Authorization header does not break browser logins.
func bearerToken(r *http.Request) (string, bool) {
if c, err := r.Cookie(sessionCookieName); err == nil && c.Value != "" {
return "", false
}
const prefix = "Bearer "
h := r.Header.Get("Authorization")
if len(h) < len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) {
return "", false
}
return strings.TrimSpace(h[len(prefix):]), true
}
// bearerUser resolves a device token for r. The code is 0 on success, 401
// for an unknown, expired or web token or an inactive account, and 403
// when the token's scope does not cover the route. A use more than a day
// after the last one extends the token by DeviceSessionTTL (sliding).
func (a *authService) bearerUser(r *http.Request, tok string) (*users.User, *users.Session, int) {
if tok == "" {
return nil, nil, http.StatusUnauthorized
}
sess, err := a.st.LookupSession(tok)
// A web token as a bearer would skip the CSRF check: refused.
if err != nil || sess.Kind != users.SessionKindDevice {
return nil, nil, http.StatusUnauthorized
}
u, err := a.st.GetByID(sess.UserID)
if err != nil || u.Status != users.StatusActive {
return nil, nil, http.StatusUnauthorized
}
if need := bearerScopesFor(r.Method, r.URL.Path); len(need) == 0 || !hasAnyScope(sess, need) {
return nil, nil, http.StatusForbidden
}
if time.Since(sess.LastSeenAt) > 24*time.Hour {
_ = a.st.ExtendSession(sess.ID, users.DeviceSessionTTL)
}
return u, sess, 0
}
func writeBearerFail(w http.ResponseWriter, code int) {
if code == http.StatusForbidden {
writeError(w, http.StatusForbidden, "this token is not allowed on this route")
return
}
writeError(w, http.StatusUnauthorized, "invalid or expired token")
}
func (a *authService) setSessionCookie(w http.ResponseWriter, raw string, expires time.Time) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName, Value: raw, Path: "/",
Expires: expires, MaxAge: int(time.Until(expires).Seconds()),
HttpOnly: true, Secure: a.set.secureCookie, SameSite: http.SameSiteLaxMode,
})
}
func (a *authService) clearSessionCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{Name: sessionCookieName, Value: "", Path: "/", MaxAge: -1,
HttpOnly: true, Secure: a.set.secureCookie, SameSite: http.SameSiteLaxMode})
}
// currentUser returns the active user behind the session cookie, or nils.
// A session last seen more than a day ago is extended (sliding expiry)
// and its cookie re-issued.
func (a *authService) currentUser(w http.ResponseWriter, r *http.Request) (*users.User, *users.Session) {
c, err := r.Cookie(sessionCookieName)
if err != nil || c.Value == "" {
return nil, nil
}
sess, err := a.st.LookupSession(c.Value)
// A device token is a bearer credential only: sent as the cookie it
// must not pass as a browser session.
if err != nil || sess.Kind != users.SessionKindWeb {
return nil, nil
}
u, err := a.st.GetByID(sess.UserID)
if err != nil || u.Status != users.StatusActive {
return nil, nil
}
if time.Since(sess.LastSeenAt) > 24*time.Hour {
if err := a.st.ExtendSession(sess.ID, a.set.sessionTTL); err == nil {
a.setSessionCookie(w, c.Value, time.Now().Add(a.set.sessionTTL))
}
}
return u, sess
}
// originOK requires the request's Origin (or, if absent, Referer) to be the
// configured publicBaseUrl's origin.
func (a *authService) originOK(r *http.Request) bool {
want := a.set.baseURL.Scheme + "://" + a.set.baseURL.Host
if o := r.Header.Get("Origin"); o != "" {
return strings.EqualFold(o, want)
}
if ref := r.Header.Get("Referer"); ref != "" {
u, err := url.Parse(ref)
return err == nil && strings.EqualFold(u.Scheme+"://"+u.Host, want)
}
return false
}
func (a *authService) csrfOK(r *http.Request, sess *users.Session) bool {
return a.originOK(r) && constantTimeEqual(r.Header.Get(csrfHeader), sess.CSRFToken)
}
func isSafeMethod(m string) bool { return m == http.MethodGet || m == http.MethodHead }
type authedHandler func(w http.ResponseWriter, r *http.Request, u *users.User, sess *users.Session)
// optionalUser returns the caller of a route that also answers anonymously
// (the read of one repeater's details), or nils for an anonymous one. A
// bearer that does not resolve to an active device token with a scope for
// the route counts as anonymous: an auth proxy may add its own
// Authorization header (see bearerToken), and a visitor behind it must still
// get the public view. A client learns its token is gone from /api/auth/me
// or the 401 on its next write. Otherwise the cookie session decides, as
// for currentUser.
func (s *Server) optionalUser(w http.ResponseWriter, r *http.Request) (*users.User, *users.Session) {
tok, ok := bearerToken(r)
if !ok {
return s.auth.currentUser(w, r)
}
if u, sess, code := s.auth.bearerUser(r, tok); code == 0 {
return u, sess
}
return nil, nil
}
// withUser requires a logged-in active user. A request with an
// Authorization: Bearer header and no session cookie is judged on that
// device token alone (scope check, no CSRF: browsers never attach it on
// their own).
// Otherwise the cookie session is used, and state-changing methods must
// pass the origin + CSRF-token check.
func (s *Server) withUser(h authedHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if tok, ok := bearerToken(r); ok {
u, sess, code := s.auth.bearerUser(r, tok)
if code != 0 {
writeBearerFail(w, code)
return
}
h(w, r, u, sess)
return
}
u, sess := s.auth.currentUser(w, r)
if u == nil {
writeError(w, http.StatusUnauthorized, "not logged in")
return
}
if !isSafeMethod(r.Method) && !s.auth.csrfOK(r, sess) {
writeError(w, http.StatusForbidden, "CSRF check failed")
return
}
h(w, r, u, sess)
}
}
// adminSessionOK is the one place that decides whether a session user may
// act as admin: state-changing methods must pass the origin + CSRF check,
// and the role must be admin. It writes the 403 itself when not.
func (a *authService) adminSessionOK(w http.ResponseWriter, r *http.Request, u *users.User, sess *users.Session) bool {
if !isSafeMethod(r.Method) && !a.csrfOK(r, sess) {
writeError(w, http.StatusForbidden, "CSRF check failed")
return false
}
if u.Role != users.RoleAdmin {
writeError(w, http.StatusForbidden, "admin role required")
return false
}
return true
}
// withAdmin requires a logged-in admin (see adminSessionOK).
func (s *Server) withAdmin(h authedHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := bearerToken(r); ok {
writeBearerFail(w, http.StatusForbidden)
return
}
u, sess := s.auth.currentUser(w, r)
if u == nil {
writeError(w, http.StatusUnauthorized, "not logged in")
return
}
if !s.auth.adminSessionOK(w, r, u, sess) {
return
}
h(w, r, u, sess)
}
}
// requireOrigin guards unauthenticated state-changing endpoints (login CSRF).
func (s *Server) requireOrigin(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !s.auth.originOK(r) {
writeError(w, http.StatusForbidden, "request origin not allowed")
return
}
h(w, r)
}
}