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

403 lines
13 KiB
Go

package main
import (
"errors"
"log"
"net/http"
"slices"
"strconv"
"strings"
"time"
"github.com/meshcore-analyzer/mailer"
"github.com/meshcore-analyzer/users"
)
const (
msgCheckMail = "If the address can receive mail, a message is on its way. Check your inbox."
msgBadLogin = "incorrect email or password"
msgMailFailed = "mail could not be sent, try again later"
)
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req registerRequest
if !decodeJSON(w, r, &req) {
return
}
email, err := users.NormalizeEmail(req.Email)
if writeValidation(w, err) {
return
}
name, err := users.ValidateDisplayName(req.DisplayName)
if writeValidation(w, err) {
return
}
if writeValidation(w, users.ValidatePassword(req.Password)) {
return
}
if !a.allow(w, r, a.signup, "email:"+email) {
return
}
// Hash before the lookup so new and existing addresses cost the same.
hash, err := users.HashPassword(req.Password)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
if existing, err := a.st.GetByEmail(email); err == nil {
// Identical response either way (no account enumeration).
if existing.Status == users.StatusPending {
// Newest registration wins: the account takes the password and
// name of the latest request, and activation demands that
// password, so a squatter cannot plant credentials and the owner
// can recover a squatted address. Failures stay invisible to the
// client (same response as every other branch).
switch err := a.st.UpdatePendingRegistration(existing.ID, hash, name); {
case errors.Is(err, users.ErrAccountChanged):
// Activation or another account change won the race. Keep the
// generic response without changing credentials or issuing mail.
case err != nil:
log.Printf("[users] register: update pending user #%d: %v", existing.ID, err)
default:
existing.DisplayName = name
_ = a.mailToken(r.Context(), existing, users.PurposeActivate, 48*time.Hour, "", "activate",
func(tok string) mailer.Message { return a.activationMail(existing, tok) })
}
} else {
_ = a.sendMail(r.Context(), existing, "register-notice", a.registerNoticeMail(existing))
}
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
return
}
u, err := a.st.CreatePending(email, name, hash)
if errors.Is(err, users.ErrEmailTaken) { // lost a race with a concurrent register
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
err = a.mailToken(r.Context(), u, users.PurposeActivate, 48*time.Hour, "", "activate",
func(tok string) mailer.Message { return a.activationMail(u, tok) })
if err != nil {
if derr := a.st.Delete(u.ID); derr != nil {
log.Printf("[users] rollback of user #%d failed: %v", u.ID, derr)
}
writeError(w, http.StatusServiceUnavailable, msgMailFailed)
return
}
a.audit(nil, "user.register", idPtr(u.ID), nil)
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
}
// handleActivate needs the token and the account password: a re-register
// of a pending address replaces the password, so whoever clicks must prove
// they know the newest one (a squatter's link cannot log the owner into an
// account carrying the squatter's password).
func (s *Server) handleActivate(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req activateRequest
if !decodeJSON(w, r, &req) {
return
}
uid, err := a.st.TokenUser(req.Token, users.PurposeActivate)
if err != nil {
writeTokenError(w, err)
return
}
if !a.allow(w, r, a.login, "activate:#"+strconv.FormatInt(uid, 10)) {
return
}
u, err := a.st.GetByID(uid)
if err != nil && !errors.Is(err, users.ErrNotFound) {
log.Printf("[users] activate: load user #%d: %v", uid, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
if err != nil || u.Status != users.StatusPending {
writeError(w, http.StatusGone, "this account is already activated, log in instead")
return
}
ok, err := users.VerifyPassword(u.PasswordHash, req.Password)
if err != nil {
log.Printf("[users] activate: verify password for user #%d: %v", u.ID, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
if !ok {
writeError(w, http.StatusUnauthorized, "wrong password for this account")
return
}
// Activate only on the hash that was just verified: a re-register in
// between replaces it, and the newest password must be proven.
switch err := a.st.ActivateWithToken(req.Token, u.ID, a.roleFor(u.Email), u.PasswordHash); {
case err == nil:
case errors.Is(err, users.ErrAccountChanged):
writeError(w, http.StatusConflict, "account changed, try again")
return
case errors.Is(err, users.ErrTokenInvalid), errors.Is(err, users.ErrTokenExpired):
writeTokenError(w, err)
return
default:
log.Printf("[users] activate user #%d: %v", u.ID, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
a.audit(nil, "user.activate", idPtr(u.ID), nil)
if u, err = a.st.GetByID(u.ID); err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
a.startSession(w, r, u)
}
// startSession creates a session, sets the cookie and answers with /me.
// It reports whether the session was started.
func (a *authService) startSession(w http.ResponseWriter, r *http.Request, u *users.User) bool {
raw, sess, err := a.st.CreateSession(u.ID, a.set.sessionTTL, r.UserAgent())
if err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return false
}
_ = a.st.TouchLogin(u.ID)
a.setSessionCookie(w, raw, sess.ExpiresAt)
writeJSON(w, meFrom(u, sess))
return true
}
// loginFailReason is the audit reason of a refused login for an existing
// account. A wrong password wins over the account state.
func loginFailReason(passwordOK bool, st users.Status) string {
if !passwordOK {
return "wrong_password"
}
if st == users.StatusPending {
return "pending"
}
return "disabled"
}
// verifyLogin is the credential check shared by /api/auth/login and
// /api/auth/device-token: rate limits per IP and per address, the
// constant-cost answer for unknown addresses, the failure audit row and
// the config-admin promotion. It returns the user, or nil after writing
// the answer.
func (a *authService) verifyLogin(w http.ResponseWriter, r *http.Request, rawEmail, password string) *users.User {
email, emailErr := users.NormalizeEmail(rawEmail)
key := "email:" + email
if emailErr != nil {
key = "email:invalid"
}
if !a.allow(w, r, a.login, key) {
return nil
}
var u *users.User
if emailErr == nil {
u, _ = a.st.GetByEmail(email)
}
if u == nil {
users.BurnPasswordCheck(password)
writeError(w, http.StatusUnauthorized, msgBadLogin)
return nil
}
ok, err := users.VerifyPassword(u.PasswordHash, password)
if err != nil || !ok || u.Status != users.StatusActive {
writeError(w, http.StatusUnauthorized, msgBadLogin)
// In the background after the answer is decided, so the write never
// changes response timing.
a.auditAsync(nil, "user.login.failed", idPtr(u.ID), map[string]string{"reason": loginFailReason(err == nil && ok, u.Status)})
return nil
}
// Config wins: an address in adminEmails is always admin.
if a.isConfigAdmin(u.Email) && u.Role != users.RoleAdmin {
if err := a.st.SetRole(u.ID, users.RoleAdmin); err == nil {
u.Role = users.RoleAdmin
a.audit(nil, "user.role.config", idPtr(u.ID), map[string]string{"role": "admin"})
}
}
return u
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req loginRequest
if !decodeJSON(w, r, &req) {
return
}
u := a.verifyLogin(w, r, req.Email, req.Password)
if u == nil {
return
}
if a.startSession(w, r, u) {
a.auditAsync(nil, "user.login", idPtr(u.ID), nil)
}
}
// requestedDeviceScopes returns the scopes a device-token request asks for:
// rx when it names none (CoreDrive RX, and every client from before scopes
// could be requested), otherwise its list without repeats, in deviceScopes
// order. An empty list or an unknown scope is a *users.ValidationError.
func requestedDeviceScopes(req []string) ([]string, error) {
if req == nil {
return []string{deviceScopeRX}, nil
}
if len(req) == 0 {
return nil, &users.ValidationError{Msg: "scopes must name at least one scope"}
}
want := make(map[string]bool, len(req))
for _, sc := range req {
if !slices.Contains(deviceScopes, sc) {
return nil, &users.ValidationError{Msg: "unknown scope: " + sc}
}
want[sc] = true
}
out := make([]string, 0, len(want))
for _, sc := range deviceScopes {
if want[sc] {
out = append(out, sc)
}
}
return out, nil
}
// handleDeviceToken issues a device token (CoreDrive RX, or a client that
// asks for repeater scopes). No Origin check: the token is returned in the
// body and nothing is stored in a browser, so login CSRF does not apply,
// and the client may run on another origin.
func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req deviceTokenRequest
if !decodeJSON(w, r, &req) {
return
}
// Checked before the password, so a malformed request costs no attempt.
scopes, err := requestedDeviceScopes(req.Scopes)
if writeValidation(w, err) {
return
}
u := a.verifyLogin(w, r, req.Email, req.Password)
if u == nil {
return
}
raw, sess, err := a.st.CreateDeviceSession(u.ID, req.DeviceName, scopes, r.UserAgent())
if err != nil {
log.Printf("[users] device token for user #%d: %v", u.ID, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
_ = a.st.TouchLogin(u.ID)
writeJSON(w, deviceTokenResponse{Token: raw, ExpiresAt: rfc3339(sess.ExpiresAt),
User: deviceTokenUser{ID: u.ID, DisplayName: u.DisplayName}, Scopes: sess.Scopes})
a.auditAsync(nil, "user.login", idPtr(u.ID), map[string]string{"via": "device", "device": sess.Label,
"scopes": strings.Join(sess.Scopes, ",")})
}
// handleLogout ends the caller's session: with a bearer header it revokes
// that device token, otherwise it ends the cookie session (origin-checked,
// as before).
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
a := s.auth
if tok, ok := bearerToken(r); ok {
_, sess, code := a.bearerUser(r, tok)
if code != 0 {
writeBearerFail(w, code)
return
}
if err := a.st.DeleteSession(sess.UserID, sess.ID); err != nil && !errors.Is(err, users.ErrNotFound) {
log.Printf("[users] revoke device session #%d: %v", sess.ID, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
writeJSON(w, okResponse{OK: true})
return
}
if !a.originOK(r) {
writeError(w, http.StatusForbidden, "request origin not allowed")
return
}
if c, err := r.Cookie(sessionCookieName); err == nil && c.Value != "" {
_ = a.st.DeleteSessionByToken(c.Value)
}
a.clearSessionCookie(w)
writeJSON(w, okResponse{OK: true})
}
// handleMe answers the caller; a device token gets no CSRF token (it never
// needs one) and its scopes.
func (s *Server) handleMe(w http.ResponseWriter, _ *http.Request, u *users.User, sess *users.Session) {
me := meFrom(u, sess)
if sess.Kind == users.SessionKindDevice {
me.CSRFToken = ""
me.Scopes = sess.Scopes
}
writeJSON(w, me)
}
func (s *Server) handleForgot(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req emailRequest
if !decodeJSON(w, r, &req) {
return
}
email, err := users.NormalizeEmail(req.Email)
if err != nil {
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
return
}
if !a.allow(w, r, a.signup, "email:"+email) {
return
}
u, err := a.st.GetByEmail(email)
if err != nil || u.Status != users.StatusActive {
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
return
}
err = a.mailToken(r.Context(), u, users.PurposeReset, time.Hour, "", "reset",
func(tok string) mailer.Message { return a.resetMail(u, tok) })
if err != nil {
writeError(w, http.StatusServiceUnavailable, msgMailFailed)
return
}
writeJSON(w, okResponse{OK: true, Message: msgCheckMail})
}
func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) {
a := s.auth
var req resetRequest
if !decodeJSON(w, r, &req) {
return
}
if writeValidation(w, users.ValidatePassword(req.Password)) {
return
}
uid, _, err := a.st.ConsumeToken(req.Token, users.PurposeReset)
if err != nil {
writeTokenError(w, err)
return
}
hash, err := users.HashPassword(req.Password)
if err == nil {
err = a.st.SetPassword(uid, hash)
}
if err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
// Sessions first: a token-store failure below must not leave an
// attacker's session alive.
if err := a.st.DeleteUserSessions(uid, 0); err != nil {
log.Printf("[users] reset: end sessions for user #%d: %v", uid, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
// A pending email change must not survive the owner's recovery.
if err := a.invalidateTokens("reset", uid, users.PurposeEmailChange); err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
a.audit(idPtr(uid), "user.password.reset", idPtr(uid), nil)
writeJSON(w, okResponse{OK: true, Message: "Password changed. Log in with your new password."})
}