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>
This commit is contained in:
AdamandAdam authored and GitHub committed 2026-11-21 22:27:48 +01:00
1 parent 900bffb782
commit c83499763d
24 files changed
+1187 -85

No files matched your search

+44 -7
View File
@@ -4,7 +4,9 @@ import (
"errors"
"log"
"net/http"
"slices"
"strconv"
"strings"
"time"
"github.com/meshcore-analyzer/mailer"
@@ -233,20 +235,53 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
}
}
// handleDeviceToken issues a CoreDrive RX device token. No Origin check:
// the token is returned in the body and nothing is stored in a browser,
// so login CSRF does not apply, and RX may run on another origin.
// 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, []string{deviceScopeRX}, r.UserAgent())
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")
@@ -254,8 +289,9 @@ func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) {
}
_ = a.st.TouchLogin(u.ID)
writeJSON(w, deviceTokenResponse{Token: raw, ExpiresAt: rfc3339(sess.ExpiresAt),
User: deviceTokenUser{ID: u.ID, DisplayName: u.DisplayName}})
a.auditAsync(nil, "user.login", idPtr(u.ID), map[string]string{"via": "device", "device": sess.Label})
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
@@ -289,11 +325,12 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
}
// handleMe answers the caller; a device token gets no CSRF token (it never
// needs one).
// 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)
}
+100 -15
View File
@@ -14,26 +14,92 @@ const (
csrfHeader = "X-CS-CSRF"
)
// deviceScopeRX is the scope of CoreDrive RX device tokens: the routes
// bearerScopeFor lists.
const deviceScopeRX = "rx"
// 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"
)
// bearerScopeFor returns the scope a device token needs on path, or ""
// when no device token may use it (spec: /api/auth/me, /api/auth/logout,
// /api/account/companions*, /api/account/settings).
func bearerScopeFor(path string) string {
switch {
case path == "/api/auth/me", path == "/api/auth/logout", path == "/api/account/settings",
path == "/api/account/companions", strings.HasPrefix(path, "/api/account/companions/"):
return deviceScopeRX
// 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 ""
}
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.
// 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" || bearerScopeFor(path) != ""
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
@@ -69,7 +135,7 @@ func (a *authService) bearerUser(r *http.Request, tok string) (*users.User, *use
if err != nil || u.Status != users.StatusActive {
return nil, nil, http.StatusUnauthorized
}
if need := bearerScopeFor(r.URL.Path); need == "" || !sess.HasScope(need) {
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 {
@@ -147,6 +213,25 @@ func isSafeMethod(m string) bool { return m == http.MethodGet || m == http.Metho
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
+10 -1
View File
@@ -20,6 +20,9 @@ type meResponse struct {
DisplayName string `json:"displayName"`
Role users.Role `json:"role"`
CSRFToken string `json:"csrfToken"`
// Scopes: a device token's granted scopes, so an app can check what it
// holds after an update or a restore; absent for a browser session.
Scopes []string `json:"scopes,omitempty"`
}
type registerRequest struct {
@@ -37,6 +40,8 @@ type deviceTokenRequest struct {
Email string `json:"email"`
Password string `json:"password"`
DeviceName string `json:"deviceName"`
// Scopes the token asks for; omitted means ["rx"] (CoreDrive RX).
Scopes []string `json:"scopes"`
}
type deviceTokenUser struct {
@@ -48,6 +53,7 @@ type deviceTokenResponse struct {
Token string `json:"token"`
ExpiresAt string `json:"expiresAt"`
User deviceTokenUser `json:"user"`
Scopes []string `json:"scopes"`
}
type companionChallengeRequest struct {
@@ -131,6 +137,9 @@ type sessionJSON struct {
ExpiresAt string `json:"expiresAt"`
UserAgent string `json:"userAgent"`
Current bool `json:"current"`
// Scopes of a device token (rx, repeater:claim, repeater:edit); absent
// for a web session, which has full access.
Scopes []string `json:"scopes,omitempty"`
}
type mailEventJSON struct {
@@ -201,7 +210,7 @@ func meFrom(u *users.User, sess *users.Session) meResponse {
func sessionToJSON(s users.Session, currentID int64) sessionJSON {
return sessionJSON{ID: s.ID, Kind: s.Kind, Label: s.Label, CreatedAt: rfc3339(s.CreatedAt), LastSeenAt: rfc3339(s.LastSeenAt),
ExpiresAt: rfc3339(s.ExpiresAt), UserAgent: s.UserAgent, Current: s.ID == currentID}
ExpiresAt: rfc3339(s.ExpiresAt), UserAgent: s.UserAgent, Current: s.ID == currentID, Scopes: s.Scopes}
}
func mailToJSON(m users.MailRecord) mailJSON {
+10 -7
View File
@@ -121,10 +121,12 @@ const corsExposedHeaders = "Retry-After, X-CoreScope-Load-Status"
// /api/packets/observations, /api/paths/inspect; see simple_post_test.go).
// Same-origin writes (admin UI, API-key holders on the canonical origin) are
// unaffected — they never go through the preflight path.
// The exception is the bearer routes of companion linking (bearerCORSPath,
// only with user management on), which also allow POST, PUT, DELETE and the
// Authorization header, for every listed origin: each deployment under a
// wildcard entry included.
// The exception is the bearer routes (bearerCORSPath, only with user
// management on): companion linking and the repeater claim and details
// routes. They also allow POST, PUT, DELETE and the Authorization header,
// for every listed origin: each deployment under a wildcard entry included,
// so with "*" in corsAllowedOrigins any origin may send token-bearing writes
// to them. No cookies go with those requests, so a write needs the token.
// Credentialed CORS is intentionally NOT enabled.
func (s *Server) corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -175,9 +177,10 @@ func (s *Server) corsMiddleware(next http.Handler) http.Handler {
}
w.Header().Set("Access-Control-Expose-Headers", corsExposedHeaders)
if s.auth != nil && bearerCORSPath(r.URL.Path) {
// Companion linking: CoreDrive RX on an allowlisted origin logs in
// and writes with a device token in Authorization. Still no
// credentials: nothing rides on cookies.
// Device-token clients on an allowlisted origin: CoreDrive RX
// (companion linking) and mobile apps (repeater claims and
// details) log in and write with a device token in Authorization.
// Still no credentials: nothing rides on cookies.
w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
} else {
+22 -4
View File
@@ -97,12 +97,30 @@ func TestMyRepeatersList(t *testing.T) {
}
}
func TestMyRepeatersNeedsBrowserSession(t *testing.T) {
// A browser session or a device token with a repeater scope lists the
// caller's claims; an rx-only token and no login do not.
func TestMyRepeatersAccess(t *testing.T) {
f := repeaterFixture(t)
f.registerAndActivate(t, "alice@example.org", "Alice", pw)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
f.registerAndActivate(t, "bob@example.org", "Bob", pw)
if _, err := f.st.ClaimRepeater(alice.me.ID, rpkA); err != nil {
t.Fatal(err)
}
expectStatus(t, f.do("GET", "/api/account/repeaters", nil), http.StatusUnauthorized)
tok := f.deviceToken(t, "alice@example.org", pw, "Pixel").Token
expectStatus(t, f.do("GET", "/api/account/repeaters", nil, bearer(tok)), http.StatusForbidden)
rx := f.deviceToken(t, "alice@example.org", pw, "Pixel").Token
expectStatus(t, f.do("GET", "/api/account/repeaters", nil, bearer(rx)), http.StatusForbidden)
for _, scope := range []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit} {
tok := f.scopedToken(t, "alice@example.org", scope, scope)
got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, bearer(tok))).Repeaters
if len(got) != 1 || got[0].Pubkey != rpkA {
t.Errorf("%s token: got %+v, want alice's one claim", scope, got)
}
}
// Bob's repeater token lists Bob's claims, not Alice's.
bobTok := f.scopedToken(t, "bob@example.org", "bob", deviceScopeRepeaterClaim)
if got := decode[myRepeatersJSON](t, f.do("GET", "/api/account/repeaters", nil, bearer(bobTok))).Repeaters; len(got) != 0 {
t.Errorf("bob's token listed %+v", got)
}
}
// Without the analyzer database (auth-only fixture) the claims still list,
+1 -1
View File
@@ -210,7 +210,7 @@ func TestClientConfigAdvertisesNotifications(t *testing.T) {
srv.auth = a
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/client", nil))
if !strings.Contains(w.Body.String(), `"userManagement":{"enabled":true,"notifications":true,"companionLinking":true}`) {
if !strings.Contains(w.Body.String(), `"userManagement":{"enabled":true,"notifications":true,"companionLinking":true,"repeaterTokens":true}`) {
t.Fatalf("client config = %s", w.Body.String())
}
}
+9 -9
View File
@@ -70,9 +70,9 @@ func routeDescriptions() map[string]routeMeta {
"POST /api/auth/register": {Summary: "Register an account", Description: "Creates a pending account and mails an activation link. The response is identical whether or not the address is already registered.", Tag: "users"},
"POST /api/auth/activate": {Summary: "Activate an account", Description: "Request body {token, password}: the mailed activation token and the account password chosen at (the newest) registration. A wrong password answers 401 and leaves the token usable; attempts are rate-limited per account. On success consumes the token, activates the account and starts a session.", Tag: "users"},
"POST /api/auth/login": {Summary: "Log in", Description: "Email + password. Sets the cs_session cookie. Rate-limited per IP and per address.", Tag: "users"},
"POST /api/auth/device-token": {Summary: "Issue a device token (CoreDrive RX)", Description: "Body {email, password, deviceName}. 200 {token, expiresAt, user: {id, displayName}}. The token is a bearer credential (Authorization: Bearer <token>), valid 90 days and extended on use, limited to /api/auth/me, /api/auth/logout, /api/account/settings and /api/account/companions*; other account routes answer 403 to it. deviceName is cleaned (control characters removed, trimmed, at most 64 characters) and shown under Devices. Same 401 answer, rate limits (shared with /api/auth/login) and user.login audit row (detail via=device) as /api/auth/login. No Origin check: nothing is stored in the browser.", Tag: "users"},
"POST /api/auth/device-token": {Summary: "Issue a device token (CoreDrive RX, mobile clients)", Description: "Body {email, password, deviceName, scopes}. scopes is optional: omitted (or null) means [\"rx\"], what CoreDrive RX gets; otherwise a non-empty list of rx, repeater:claim and repeater:edit (400 for an empty list or any other value, checked before the password). 200 {token, expiresAt, user: {id, displayName}, scopes} with the granted scopes, repeats removed, in that order. The token is a bearer credential (Authorization: Bearer <token>), valid 90 days and extended on use. Every device token may use /api/auth/me and /api/auth/logout; rx adds /api/account/settings and /api/account/companions*; repeater:claim adds POST and DELETE /api/repeaters/{pubkey}/claim; repeater:edit adds PUT /api/repeaters/{pubkey}/info; either repeater scope adds the caller fields on GET /api/repeaters/{pubkey}/info and opens GET /api/account/repeaters. Other routes answer 403 to it. deviceName is cleaned (control characters removed, trimmed, at most 64 characters) and shown under Devices. Same 401 answer, rate limits (shared with /api/auth/login) and user.login audit row (detail via=device, plus the scopes) as /api/auth/login. No Origin check: nothing is stored in the browser.", Tag: "users"},
"POST /api/auth/logout": {Summary: "Log out", Description: "With the cs_session cookie (Origin must be publicBaseUrl): ends that browser session and clears the cookie. With Authorization: Bearer <device token>: revokes that device token.", Tag: "users"},
"GET /api/auth/me": {Summary: "Current user", Description: "Returns the logged-in user and the CSRF token, or 401. Also accepts a device token (Authorization: Bearer); csrfToken is then empty.", Tag: "users", Session: true},
"GET /api/auth/me": {Summary: "Current user", Description: "Returns the logged-in user and the CSRF token, or 401. Also accepts a device token (Authorization: Bearer); csrfToken is then empty and scopes lists the token's granted scopes (absent for a browser session).", Tag: "users", Session: true},
"POST /api/auth/forgot": {Summary: "Request a password reset", Tag: "users"},
"POST /api/auth/reset": {Summary: "Reset the password", Description: "Consumes the mailed reset token and ends all sessions of the user.", Tag: "users"},
"PATCH /api/account": {Summary: "Update profile", Tag: "users", Session: true},
@@ -80,27 +80,27 @@ func routeDescriptions() map[string]routeMeta {
"POST /api/account/password": {Summary: "Change password", Tag: "users", Session: true},
"POST /api/account/email": {Summary: "Request an address change", Tag: "users", Session: true},
"POST /api/account/confirm-email": {Summary: "Confirm an address change", Tag: "users"},
"GET /api/account/sessions": {Summary: "List own sessions", Description: "[{id, kind, label, createdAt, lastSeenAt, expiresAt, userAgent, current}]. kind is web (a browser) or device (a CoreDrive RX device token); label is the device name, empty for web sessions. DELETE /api/account/sessions/{id} revokes either kind.", Tag: "users", Session: true},
"GET /api/account/sessions": {Summary: "List own sessions", Description: "[{id, kind, label, createdAt, lastSeenAt, expiresAt, userAgent, current, scopes}]. kind is web (a browser) or device (a device token: CoreDrive RX or another app); label is the device name, empty for web sessions; scopes lists a device token's scopes (absent for web sessions). DELETE /api/account/sessions/{id} revokes either kind.", Tag: "users", Session: true},
"DELETE /api/account/sessions/{id}": {Summary: "Revoke one own session", Tag: "users", Session: true},
"GET /api/account/settings": {Summary: "Get own synced settings", Description: "Returns {revision, generation, doc, allowlist}. doc is {v: 1, keys: {<localStorage key>: <raw string>}} or null at revision 0. generation is a random id of the stored document (empty at revision 0); revisions restart at 1 after a DELETE, the generation does not repeat. allowlist lists the keys the server accepts: {key, kind: set|scalar, id?}, where id names the field that identifies an item of a set (absent: the item itself).", Tag: "users", Session: true},
"PUT /api/account/settings": {Summary: "Replace own synced settings", Description: "Body {baseRevision, baseGeneration, doc}. 200 {revision, generation}. 409 {revision, generation, doc} when baseRevision is not the stored revision or, with a stored document, baseGeneration is not its generation. baseRevision 0 without a stored document starts a new generation. 400 when doc is not {v: 1, keys} or holds a key that is never synced or not allowlisted. 413 above 256 KiB. 429 above 60 PUT requests per hour per user.", Tag: "users", Session: true},
"DELETE /api/account/settings": {Summary: "Delete own synced settings", Description: "Removes the stored document; the next PUT (baseRevision 0) starts a new one in a new generation.", Tag: "users", Session: true},
"POST /api/account/companions/challenge": {Summary: "Start linking a companion", Description: "Body {pubkey} (64 hex). 200 {challenge, expiresAt, host}: host is what to sign (the host of userManagement.publicBaseUrl); challenge is 32 random bytes as hex, single use, valid 5 minutes, bound to the caller and the pubkey. 400 malformed pubkey; 429 above 60 challenge + link requests per hour per user and per IP. Accepts a device token (Authorization: Bearer).", Tag: "users", Session: true},
"POST /api/account/companions": {Summary: "Link a companion", Description: "Body {pubkey, challenge, signature, name}. signature is the companion's Ed25519 signature (64 bytes, hex) over the UTF-8 string \"corescope-link:\" + host of userManagement.publicBaseUrl + \":\" + challenge. The challenge is consumed in every case. 200 {pubkey, name, linkedAt}. The synced settings (meshcore-my-nodes) are not touched: a companion is not a node to monitor. A companion linked to another account moves to the caller (the newest proof wins); both get a companion.transfer audit row and the previous owner a mail (a security notice, sent whatever the node notification settings are). 400 malformed pubkey or signature, or a signature that does not verify; 410 challenge missing, expired, used, or bound to another user or pubkey; 429 rate limited. Accepts a device token.", Tag: "users", Session: true},
"GET /api/account/repeaters": {Summary: "List own claimed repeaters", Description: "{repeaters: [{pubkey, name, known, inactive, role, claimedAt, lastHeard, lastRelayed, status, comaintainers}]} for My account, My repeaters: named repeaters first by name, then the unnamed by pubkey. inactive is true when retention moved the node to inactive_nodes (silent longer than retention.nodeDays); its name, role and last advert are read from there. known is false only when the node is in neither nodes nor inactive_nodes (the claim stays). lastHeard is the newer of the last advert and the last transmission certainly from the node, or null; lastRelayed is the last time its hop prefix was seen relaying (it may be shared with other repeaters), or null. status is the saved repeater status or null. comaintainers are the other active claimers' display names. Browser session only; device tokens answer 403.", Tag: "users", Session: true},
"GET /api/account/repeaters": {Summary: "List own claimed repeaters", Description: "{repeaters: [{pubkey, name, known, inactive, role, claimedAt, lastHeard, lastRelayed, status, comaintainers}]} for My account, My repeaters: named repeaters first by name, then the unnamed by pubkey. inactive is true when retention moved the node to inactive_nodes (silent longer than retention.nodeDays); its name, role and last advert are read from there. known is false only when the node is in neither nodes nor inactive_nodes (the claim stays). lastHeard is the newer of the last advert and the last transmission certainly from the node, or null; lastRelayed is the last time its hop prefix was seen relaying (it may be shared with other repeaters), or null. status is the saved repeater status or null. comaintainers are the other active claimers' display names. A browser session or a device token with repeater:claim or repeater:edit; an rx-only token answers 403.", Tag: "users", Session: true},
"GET /api/account/companions": {Summary: "List own linked companions", Description: "[{pubkey, name, linkedAt, lastSeenAt}], newest link first. lastSeenAt is the newest client reception of that companion (rx_at as stored) or null. Accepts a device token.", Tag: "users", Session: true},
"DELETE /api/account/companions/{pubkey}": {Summary: "Unlink an own companion", Description: "204. Stored coverage stays. 400 malformed pubkey, 404 not linked to the caller. Accepts a device token.", Tag: "users", Session: true},
"GET /api/account/observer-login": {Summary: "Own observer MQTT login", Description: "{login: null} or {login: {username, createdAt, revoked}, observers: [{pubkey, name, lastSeenAt}]}. observers are the pubkeys bound to the caller (the first time an observer publishes with the login); name and lastSeenAt come from the analyzer observers (empty name and null lastSeenAt when unknown). Never contains the password, its hash or its ciphertext. Routes exist only when userManagement.observerLogins is enabled. Not available to device tokens.", Tag: "users", Session: true},
"POST /api/account/observer-login": {Summary: "Request an observer MQTT login", Description: "Generates a username and password, stores the password hashed and sealed, and mails the credentials to the account address in five formats (meshcoretomqtt, Gessaman or Dutch-MeshCore observer firmware, Home Assistant meshcore-ha, OpenHop, plain). 201 {sent: true}: the response never carries the credentials. 409 when the caller already has a login, 403 when it was revoked, 503 when the mail could not be sent (the login exists; use resend) or the feature failed to load.", Tag: "users", Session: true},
"POST /api/account/observer-login/resend": {Summary: "Mail the observer MQTT credentials again", Description: "Mails the same credentials again. 200 {sent: true}. 404 without a login, 403 when revoked, 429 after 3 credential mails in 24 hours (the first mail counts; Retry-After in seconds), 503 when the mail fails.", Tag: "users", Session: true},
"PUT /api/repeaters/{pubkey}/info": {Summary: "Edit a repeater's community details", Description: "Body is a full replace, omitted fields are cleared, and an unchanged body is a no-op: {heightM (null = unknown, 0 to 300), gainDbi (omitted = 0, -10 to 30), status (active|maintenance|decommissioned|empty), power (mains|battery|solar|empty), notes (at most 500 characters)}. 200 the repeater info with canEdit and claimedByMe. Allowed for an admin, for any active user when the repeater has no active claimer, otherwise only for its claimers. Writes a repeater.edit audit row with the changed fields (none when nothing changed). 400 malformed pubkey, invalid value, or a node that is not a repeater; 401 not logged in; 403 not a maintainer or CSRF failure; 404 unknown node; 429 above 120 repeater requests per hour per user and per IP.", Tag: "users", Session: true},
"POST /api/repeaters/{pubkey}/claim": {Summary: "Claim a repeater", Description: "No body. 200 the repeater info with canEdit and claimedByMe. Idempotent: a repeat answers 200 and writes no second repeater.claim audit row. 400 malformed pubkey or not a repeater; 401 not logged in; 403 CSRF failure; 404 unknown node; 429 rate limited.", Tag: "users", Session: true},
"DELETE /api/repeaters/{pubkey}/claim": {Summary: "Remove own claim on a repeater", Description: "200 the repeater info with canEdit and claimedByMe. Writes a repeater.unclaim audit row. 400 malformed pubkey; 401 not logged in; 403 CSRF failure; 404 the caller has no claim on it; 429 rate limited.", Tag: "users", Session: true},
"PUT /api/repeaters/{pubkey}/info": {Summary: "Edit a repeater's community details", Description: "A browser session (with the CSRF header) or a device token with repeater:edit. Body is a full replace, omitted fields are cleared, and an unchanged body is a no-op: {heightM (null = unknown, 0 to 300), gainDbi (omitted = 0, -10 to 30), status (active|maintenance|decommissioned|empty), power (mains|battery|solar|empty), notes (at most 500 characters), baseRevision (optional)}. With baseRevision the save is conditional: it must be the stored revision (0 when no details are saved yet), checked in the same statement as the write; otherwise 409 with the stored repeater info (canEdit and claimedByMe included) and nothing is written, also for a body that would change nothing. Merge and retry from the 409's revision. Without baseRevision the save is unconditional. 200 the repeater info with canEdit and claimedByMe. Allowed for an admin, for any active user when the repeater has no active claimer, otherwise only for its claimers. Writes a repeater.edit audit row with the changed fields (none when nothing changed), with via=device when sent with a device token. 400 malformed pubkey, invalid value, negative baseRevision, or a node that is not a repeater; 401 not logged in or the token is gone; 403 not a maintainer, CSRF failure or a token without repeater:edit; 404 unknown node; 429 above 120 repeater requests per hour per user and per IP.", Tag: "users", Session: true},
"POST /api/repeaters/{pubkey}/claim": {Summary: "Claim a repeater", Description: "A browser session (with the CSRF header) or a device token with repeater:claim. No body. 200 the repeater info with canEdit and claimedByMe. A repeater may have several claimers. Idempotent: a repeat answers 200 and writes no second repeater.claim audit row (via=device when sent with a device token). 400 malformed pubkey or not a repeater; 401 not logged in or the token is gone; 403 CSRF failure or a token without repeater:claim; 404 unknown node; 429 rate limited.", Tag: "users", Session: true},
"DELETE /api/repeaters/{pubkey}/claim": {Summary: "Remove own claim on a repeater", Description: "A browser session (with the CSRF header) or a device token with repeater:claim. Removes only the caller's claim; other claimers keep theirs. 200 the repeater info with canEdit and claimedByMe. Writes a repeater.unclaim audit row (via=device when sent with a device token). 400 malformed pubkey; 401 not logged in or the token is gone; 403 CSRF failure or a token without repeater:claim; 404 the caller has no claim on it; 429 rate limited.", Tag: "users", Session: true},
"GET /api/repeaters/info": {Summary: "Community details of all repeaters with details or claimers", Description: "{repeaters: [...]} ordered by pubkey; each entry has the shape of GET /api/repeaters/{pubkey}/info without canEdit and claimedByMe. Contains every pubkey with a saved info row or at least one active claimer. Only display names are public, never email. 404 when user management is off.", Tag: "users", Session: false},
"GET /api/repeaters/{pubkey}/info": {Summary: "Community details of one repeater", Description: "{pubkey, heightM, gainDbi, status, power, notes, claimers: [{displayName, claimedAt}], updatedAt, updatedBy}. A repeater without a saved row answers 200 with defaults: heightM null, gainDbi 0, status null, power null, notes \"\", claimers [], updatedAt null, updatedBy null. heightM 0 is a real value, null is unknown. canEdit and claimedByMe appear only with a browser session (a bearer token is treated as anonymous). The pubkey is case-insensitive; 400 when it is not 64 hex characters. No analyzer lookup: any well-formed pubkey answers. 404 when user management is off.", Tag: "users", Session: false},
"GET /api/repeaters/{pubkey}/info": {Summary: "Community details of one repeater", Description: "{pubkey, revision, heightM, gainDbi, status, power, notes, claimers: [{displayName, claimedAt}], updatedAt, updatedBy}. revision counts saves of the details from 1 (claims do not change it); send it as baseRevision with PUT. A repeater without a saved row answers 200 with defaults: revision 0, heightM null, gainDbi 0, status null, power null, notes \"\", claimers [], updatedAt null, updatedBy null. heightM 0 is a real value, null is unknown. canEdit and claimedByMe appear with a browser session, or with a device token holding repeater:claim or repeater:edit; a device token without either scope, or a bearer that is no live device token (unknown, expired, or an auth proxy's own Authorization header), reads the public view. The pubkey is case-insensitive; 400 when it is not 64 hex characters. No analyzer lookup: any well-formed pubkey answers. 404 when user management is off.", Tag: "users", Session: false},
"GET /api/account/export": {Summary: "Download own account data", Description: "One JSON file (Content-Disposition attachment corescope-account-<YYYY-MM-DD>.json): {formatVersion: 1, exportedAt, instance, profile, sessions (with kind web|device and the device label), companions (linked companions: pubkey, name, linkedAt), settings, proposals, notifications: {prefs, watches}, audit, mail, observerLogin: {username, createdAt, revoked} or null, observerBindings: [{pubkey, boundAt, boundBy}], repeaterClaims: [{pubkey, claimedAt}], newest first, all own claims}. Every row, no caps. Leaves out the password hash, every session, link and unsubscribe token, and companion link challenges. Audit rows name other accounts by id only. Includes activatedAt, activatedBy (id) and each mail row's to-address. Records a user.export audit row after the file is built.", Tag: "users", Session: true},
"GET /api/admin/users": {Summary: "List users (admin)", Tag: "users", Session: true, QueryParams: []paramMeta{{Name: "status", Description: "pending | active | disabled", Type: "string"}, {Name: "role", Description: "user | admin", Type: "string"}, {Name: "q", Description: "Substring of email or display name", Type: "string"}, {Name: "bouncing", Description: "1 = only addresses whose mail bounces", Type: "string"}}},
"DELETE /api/admin/repeaters/{pubkey}/claims/{userId}": {Summary: "Remove a user's claim on a repeater (admin)", Description: "204. Writes a repeater.unclaim audit row with actor = the admin, target = the user and detail {pubkey, by: admin}. 400 malformed pubkey or user id; 401 not logged in; 403 not an admin or CSRF failure; 404 no such claim.", Tag: "users", Session: true},
"DELETE /api/admin/repeaters/{pubkey}/claims/{userId}": {Summary: "Remove a user's claim on a repeater (admin)", Description: "Browser session only; device tokens answer 403. 204. Writes a repeater.unclaim audit row with actor = the admin, target = the user and detail {pubkey, by: admin}. 400 malformed pubkey or user id; 401 not logged in; 403 not an admin or CSRF failure; 404 no such claim.", Tag: "users", Session: true},
"GET /api/admin/users/{id}": {Summary: "User detail with sessions, companions, repeater claims, mail log and audit (admin)", Description: "{user, sessions, companions, repeaterClaims, mail, audit}. companions is [{pubkey, name, linkedAt, lastSeenAt}] like GET /api/account/companions. repeaterClaims is [{pubkey, claimedAt}], newest first, every claim of the user whatever the user's status.", Tag: "users", Session: true},
"DELETE /api/admin/users/{id}": {Summary: "Delete a user (admin)", Tag: "users", Session: true},
"POST /api/admin/users/{id}/disable": {Summary: "Disable a user (admin)", Tag: "users", Session: true},
+1 -1
View File
@@ -113,7 +113,7 @@ func TestClientConfigAdvertisesChannelProposals(t *testing.T) {
a, _ := newTestAuthService(t)
a.set.proposals = defaultProposalSettings()
srv.auth = a
if body := getBody(router, "/api/config/client"); !strings.Contains(body, `"userManagement":{"enabled":true,"channelProposals":true,"companionLinking":true}`) {
if body := getBody(router, "/api/config/client"); !strings.Contains(body, `"userManagement":{"enabled":true,"channelProposals":true,"companionLinking":true,"repeaterTokens":true}`) {
t.Fatalf("client config = %s", body)
}
}
+348
View File
@@ -0,0 +1,348 @@
package main
import (
"net/http"
"slices"
"strings"
"testing"
"github.com/meshcore-analyzer/users"
)
// scopedToken logs in like a mobile client asking for scopes.
func (f *authFixture) scopedToken(t *testing.T, email, name string, scopes ...string) string {
t.Helper()
w := f.do("POST", "/api/auth/device-token",
deviceTokenRequest{Email: email, Password: pw, DeviceName: name, Scopes: scopes})
expectStatus(t, w, http.StatusOK)
got := decode[deviceTokenResponse](t, w)
if !slices.Equal(got.Scopes, scopes) {
t.Fatalf("granted scopes = %v, want %v", got.Scopes, scopes)
}
return got.Token
}
func TestDeviceTokenScopesDefaultToRX(t *testing.T) {
f := newAuthFixture(t)
f.registerAndActivate(t, "alice@example.org", "Alice", pw)
got := f.deviceToken(t, "alice@example.org", pw, "Pixel")
if !slices.Equal(got.Scopes, []string{deviceScopeRX}) {
t.Fatalf("scopes = %v, want [rx]", got.Scopes)
}
sess, err := f.st.LookupSession(got.Token)
if err != nil || sess.HasScope(deviceScopeRepeaterClaim) || sess.HasScope(deviceScopeRepeaterEdit) {
t.Fatalf("an RX token holds repeater scopes: %+v, %v", sess, err)
}
}
func TestDeviceTokenScopesRequested(t *testing.T) {
f := newAuthFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
// Repeats collapse and the order is fixed.
w := f.do("POST", "/api/auth/device-token", deviceTokenRequest{Email: "alice@example.org", Password: pw,
DeviceName: "iPhone", Scopes: []string{deviceScopeRepeaterEdit, deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}})
expectStatus(t, w, http.StatusOK)
got := decode[deviceTokenResponse](t, w)
want := []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}
if !slices.Equal(got.Scopes, want) {
t.Fatalf("scopes = %v, want %v", got.Scopes, want)
}
sess, err := f.st.LookupSession(got.Token)
if err != nil || !slices.Equal(sess.Scopes, want) || sess.HasScope(deviceScopeRX) {
t.Fatalf("stored session = %+v, %v", sess, err)
}
rows := auditOf(t, f, alice.me.ID, "user.login")
if len(rows) == 0 || rows[0].Detail["scopes"] != "repeater:claim,repeater:edit" {
t.Fatalf("login audit = %+v", rows)
}
}
func TestDeviceTokenScopesRejected(t *testing.T) {
f := newAuthFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
for _, scopes := range [][]string{{}, {"admin"}, {deviceScopeRX, "repeater:delete"}, {""}} {
w := f.do("POST", "/api/auth/device-token", deviceTokenRequest{Email: "alice@example.org", Password: pw,
DeviceName: "x", Scopes: scopes})
if w.Code != http.StatusBadRequest {
t.Errorf("scopes %q = %d, want 400", scopes, w.Code)
}
}
list, err := f.st.ListSessions(alice.me.ID)
if err != nil {
t.Fatal(err)
}
for _, s := range list {
if s.Kind == users.SessionKindDevice {
t.Fatalf("a rejected request created a device session: %+v", s)
}
}
}
func TestBearerScopesForRoutes(t *testing.T) {
both := []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}
for _, c := range []struct {
method, path string
want []string
}{
{"GET", "/api/auth/me", deviceScopes},
{"POST", "/api/auth/logout", deviceScopes},
{"PUT", "/api/account/settings", []string{deviceScopeRX}},
{"DELETE", "/api/account/companions/" + rpkA, []string{deviceScopeRX}},
{"POST", repPath(rpkA, "claim"), []string{deviceScopeRepeaterClaim}},
{"DELETE", repPath(rpkA, "claim"), []string{deviceScopeRepeaterClaim}},
{"PUT", repPath(rpkA, "info"), []string{deviceScopeRepeaterEdit}},
{"GET", repPath(rpkA, "info"), both},
{"GET", "/api/account/repeaters", both},
{"HEAD", "/api/account/repeaters", both},
{"POST", "/api/account/repeaters", nil},
{"DELETE", "/api/account/repeaters", nil},
{"GET", repPath(rpkA, "claim"), nil},
{"POST", repPath(rpkA, "info"), nil},
{"GET", "/api/repeaters/info", nil},
{"PUT", "/api/repeaters//info", nil},
{"PUT", repPath(rpkA, "info/x"), nil},
{"DELETE", "/api/admin/repeaters/" + rpkA + "/claims/1", nil},
{"GET", "/api/account/sessions", nil},
} {
if got := bearerScopesFor(c.method, c.path); !slices.Equal(got, c.want) {
t.Errorf("bearerScopesFor(%s %s) = %v, want %v", c.method, c.path, got, c.want)
}
}
for path, want := range map[string]bool{
repPath(rpkA, "info"): true, repPath(rpkA, "claim"): true, "/api/auth/device-token": true,
"/api/account/companions": true, "/api/account/repeaters": true, "/api/repeaters/info": false, "/api/account/sessions": false,
} {
if got := bearerCORSPath(path); got != want {
t.Errorf("bearerCORSPath(%s) = %v, want %v", path, got, want)
}
}
}
// Each scope opens only its own routes; RX and repeater tokens stay apart.
func TestRepeaterTokenScopesPerRoute(t *testing.T) {
f := repeaterFixture(t)
f.registerAndActivate(t, "alice@example.org", "Alice", pw)
tokens := map[string]string{
"rx": f.deviceToken(t, "alice@example.org", pw, "RX").Token,
"claim": f.scopedToken(t, "alice@example.org", "claim", deviceScopeRepeaterClaim),
"edit": f.scopedToken(t, "alice@example.org", "edit", deviceScopeRepeaterEdit),
}
for _, c := range []struct {
token, method, path string
body any
want int
}{
{"rx", "POST", repPath(rpkA, "claim"), nil, 403},
{"rx", "PUT", repPath(rpkA, "info"), map[string]any{"heightM": 1}, 403},
{"edit", "POST", repPath(rpkA, "claim"), nil, 403},
{"claim", "PUT", repPath(rpkA, "info"), map[string]any{"heightM": 1}, 403},
{"claim", "GET", "/api/account/settings", nil, 403},
{"edit", "GET", "/api/account/companions", nil, 403},
{"claim", "GET", "/api/auth/me", nil, 200},
{"edit", "GET", "/api/auth/me", nil, 200},
{"edit", "PUT", repPath(rpkA, "info"), map[string]any{"heightM": 1}, 200},
{"claim", "POST", repPath(rpkA, "claim"), nil, 200},
{"claim", "DELETE", repPath(rpkA, "claim"), nil, 200},
} {
if w := f.do(c.method, c.path, c.body, bearer(tokens[c.token])); w.Code != c.want {
t.Errorf("%s token: %s %s = %d (%s), want %d", c.token, c.method, c.path, w.Code, w.Body.String(), c.want)
}
}
// A repeater-only token can still end its own login.
expectStatus(t, f.do("POST", "/api/auth/logout", nil, bearer(tokens["claim"])), 200)
if _, err := f.st.LookupSession(tokens["claim"]); err == nil {
t.Fatal("logout left the claim token valid")
}
}
// A claim token manages the caller's own claim only, beside other claimers.
func TestRepeaterTokenClaimsOwnClaimOnly(t *testing.T) {
f := repeaterFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
f.registerAndActivate(t, "bob@example.org", "Bob", pw)
expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200)
bob := f.scopedToken(t, "bob@example.org", "Bob's phone", deviceScopeRepeaterClaim)
// Bob has no claim yet: his DELETE must not touch Alice's.
expectStatus(t, f.do("DELETE", repPath(rpkA, "claim"), nil, bearer(bob)), 404)
w := f.do("POST", repPath(rpkA, "claim"), nil, bearer(bob))
expectStatus(t, w, 200)
got := decode[repeaterInfoJSON](t, w)
if len(got.Claimers) != 2 || got.ClaimedByMe == nil || !*got.ClaimedByMe {
t.Fatalf("after Bob's claim: %+v", got)
}
// Repeating the claim stays a 200 without a second claim.
got = decode[repeaterInfoJSON](t, f.do("POST", repPath(rpkA, "claim"), nil, bearer(bob)))
if len(got.Claimers) != 2 {
t.Fatalf("a repeated claim changed the claimers: %+v", got.Claimers)
}
w = f.do("DELETE", repPath(rpkA, "claim"), nil, bearer(bob))
expectStatus(t, w, 200)
got = decode[repeaterInfoJSON](t, w)
if len(got.Claimers) != 1 || got.Claimers[0].DisplayName != "Alice" || *got.ClaimedByMe {
t.Fatalf("after Bob's unclaim: %+v", got)
}
expectStatus(t, f.do("POST", repPath(rpkComp, "claim"), nil, bearer(bob)), 400)
if rows := auditOf(t, f, alice.me.ID, "repeater.unclaim"); len(rows) != 0 {
t.Fatalf("Alice's claim was audited as removed: %+v", rows)
}
}
// An edit token follows the browser's rule: anyone on an unclaimed repeater,
// then only its active claimers, and admins always.
func TestRepeaterTokenEditFollowsCanEdit(t *testing.T) {
f := repeaterFixture(t, "boss@example.org")
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
f.registerAndActivate(t, "bob@example.org", "Bob", pw)
f.registerAndActivate(t, "boss@example.org", "Boss", pw)
bobEdit := f.scopedToken(t, "bob@example.org", "Bob", deviceScopeRepeaterEdit)
bobBoth := f.scopedToken(t, "bob@example.org", "Bob 2", deviceScopeRepeaterClaim, deviceScopeRepeaterEdit)
boss := f.scopedToken(t, "boss@example.org", "Boss", deviceScopeRepeaterEdit)
expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 10}, bearer(bobEdit)), 200)
expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200)
w := f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 11}, bearer(bobEdit))
expectStatus(t, w, 403)
if info, _ := f.st.GetRepeaterInfo(rpkA); info == nil || info.HeightM == nil || *info.HeightM != 10 {
t.Fatalf("a refused edit changed the row: %+v", info)
}
// Claiming makes Bob a maintainer again.
expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, bearer(bobBoth)), 200)
expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 12}, bearer(bobBoth)), 200)
// The admin edits a claimed repeater through a token too.
w = f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 13}, bearer(boss))
expectStatus(t, w, 200)
if got := decode[repeaterInfoJSON](t, w); got.CanEdit == nil || !*got.CanEdit || *got.ClaimedByMe {
t.Fatalf("admin response = %+v", got)
}
// A disabled account's token stops working.
bobMe := decode[meResponse](t, f.do("GET", "/api/auth/me", nil, bearer(bobBoth)))
bobID := bobMe.ID
// A token reads its own scopes back (review on #2429), with no CSRF token.
if !slices.Equal(bobMe.Scopes, []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}) || bobMe.CSRFToken != "" {
t.Fatalf("/api/auth/me for a device token = %+v", bobMe)
}
if err := f.st.SetStatus(bobID, users.StatusDisabled); err != nil {
t.Fatal(err)
}
expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 14}, bearer(bobBoth)), 401)
}
// Admin claim removal stays a browser-only admin action.
func TestRepeaterTokenCannotUseAdminRoute(t *testing.T) {
f := repeaterFixture(t, "boss@example.org")
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
f.registerAndActivate(t, "boss@example.org", "Boss", pw)
expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200)
boss := f.scopedToken(t, "boss@example.org", "Boss", deviceScopeRepeaterClaim, deviceScopeRepeaterEdit)
expectStatus(t, f.do("DELETE", adminClaimPath(rpkA, alice.me.ID), nil, bearer(boss)), 403)
if c, _ := f.st.RepeaterClaims(rpkA); len(c) != 1 {
t.Fatalf("claims = %+v", c)
}
}
func TestRepeaterInfoGetWithToken(t *testing.T) {
f := newAuthFixture(t)
alice := seedAliceRepeater(t, f)
f.registerAndActivate(t, "bob@example.org", "Bob", pw)
aliceClaim := f.scopedToken(t, "alice@example.org", "Alice", deviceScopeRepeaterClaim)
bobEdit := f.scopedToken(t, "bob@example.org", "Bob", deviceScopeRepeaterEdit)
rx := f.deviceToken(t, "bob@example.org", pw, "RX").Token
got := decode[repeaterInfoJSON](t, f.do("GET", repPath(rpkA, "info"), nil, bearer(aliceClaim)))
if got.CanEdit == nil || !*got.CanEdit || got.ClaimedByMe == nil || !*got.ClaimedByMe {
t.Fatalf("Alice's token: %+v", got)
}
got = decode[repeaterInfoJSON](t, f.do("GET", repPath(rpkA, "info"), nil, bearer(bobEdit)))
if got.CanEdit == nil || *got.CanEdit || got.ClaimedByMe == nil || *got.ClaimedByMe {
t.Fatalf("Bob's token: %+v", got)
}
// An RX token reads the public view, like an anonymous visitor.
w := f.do("GET", repPath(rpkA, "info"), nil, bearer(rx))
expectStatus(t, w, 200)
if strings.Contains(w.Body.String(), "canEdit") {
t.Fatalf("RX token got caller fields: %s", w.Body.String())
}
// A bearer that is no live device token reads the public view: a token
// that is gone, a web session token, and an auth proxy's own header
// (review on #2429: a 401 here hid the Repeater info section).
for _, tok := range []string{"nonsense", alice.cookie.Value, "eyJhbGciOiJSUzI1NiJ9.proxy.jwt"} {
w := f.do("GET", repPath(rpkA, "info"), nil, bearer(tok))
if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "canEdit") {
t.Errorf("bearer %.8s… = %d %s, want 200 with the public view", tok, w.Code, w.Body.String())
}
}
// The same foreign header still gets 401 on a write, which needs a login.
expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": "x"}, bearer("eyJhbGciOiJSUzI1NiJ9.proxy.jwt")), http.StatusUnauthorized)
// The cookie still decides when both are sent, and anonymous reads stay public.
got = decode[repeaterInfoJSON](t, f.do("GET", repPath(rpkA, "info"), nil, as(alice), bearer("nonsense")))
if got.ClaimedByMe == nil || !*got.ClaimedByMe {
t.Fatalf("cookie with a stray bearer: %+v", got)
}
if w := f.do("GET", repPath(rpkA, "info"), nil); strings.Contains(w.Body.String(), "claimedByMe") || w.Code != 200 {
t.Fatalf("anonymous read = %d %s", w.Code, w.Body.String())
}
}
func TestRepeaterTokenWritesAuditVia(t *testing.T) {
f := repeaterFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
tok := f.scopedToken(t, "alice@example.org", "iPhone", deviceScopeRepeaterClaim, deviceScopeRepeaterEdit)
expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, bearer(tok)), 200)
expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": "roof"}, bearer(tok)), 200)
expectStatus(t, f.do("DELETE", repPath(rpkA, "claim"), nil, bearer(tok)), 200)
expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200)
for action, want := range map[string][]string{
"repeater.claim": {"", "device"}, "repeater.edit": {"device"}, "repeater.unclaim": {"device"},
} {
rows := auditOf(t, f, alice.me.ID, action)
var via []string
for _, r := range rows {
via = append(via, r.Detail["via"])
}
if !slices.Equal(via, want) {
t.Errorf("%s via = %q, want %q (newest first)", action, via, want)
}
}
}
// The browser path is unchanged: a cookie write still needs the CSRF token.
func TestRepeaterCookieWriteStillNeedsCSRF(t *testing.T) {
f := repeaterFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
noCSRF := &client{cookie: alice.cookie}
for _, c := range []struct{ method, what string }{{"POST", "claim"}, {"PUT", "info"}, {"DELETE", "claim"}} {
if w := f.do(c.method, repPath(rpkA, c.what), map[string]any{}, as(noCSRF)); w.Code != http.StatusForbidden {
t.Errorf("%s %s without CSRF = %d, want 403", c.method, c.what, w.Code)
}
}
if c, _ := f.st.RepeaterClaims(rpkA); len(c) != 0 {
t.Fatalf("claims = %+v", c)
}
}
// My account, Devices tells an app token's scopes apart from CoreDrive RX.
func TestAccountSessionsListScopes(t *testing.T) {
f := newAuthFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
f.deviceToken(t, "alice@example.org", pw, "RX")
f.scopedToken(t, "alice@example.org", "iPhone", deviceScopeRepeaterClaim, deviceScopeRepeaterEdit)
w := f.do("GET", "/api/account/sessions", nil, as(alice))
expectStatus(t, w, http.StatusOK)
got := map[string][]string{}
for _, s := range decode[[]sessionJSON](t, w) {
got[s.Kind+":"+s.Label] = s.Scopes
}
if s, ok := got["web:"]; !ok || s != nil {
t.Errorf("web session scopes = %v (present %v), want none", s, ok)
}
if s := got["device:RX"]; !slices.Equal(s, []string{deviceScopeRX}) {
t.Errorf("RX scopes = %v", s)
}
if s := got["device:iPhone"]; !slices.Equal(s, []string{deviceScopeRepeaterClaim, deviceScopeRepeaterEdit}) {
t.Errorf("app scopes = %v", s)
}
if strings.Contains(w.Body.String(), `"scopes":null`) {
t.Errorf("web session has a null scopes field: %s", w.Body.String())
}
}
+62 -11
View File
@@ -33,6 +33,7 @@ func claimRefsJSON(claims []users.RepeaterClaim) []repeaterClaimRefJSON {
type repeaterInfoJSON struct {
Pubkey string `json:"pubkey"`
Revision int64 `json:"revision"`
HeightM *float64 `json:"heightM"`
GainDBi float64 `json:"gainDbi"`
Status *string `json:"status"`
@@ -80,6 +81,7 @@ func repeaterInfoBase(pk string, info *users.RepeaterInfo, claims []users.Repeat
if info == nil {
return out
}
out.Revision = info.Revision
out.HeightM = info.HeightM
out.GainDBi = info.GainDBi
out.Status = stringPtrOrNil(info.Status)
@@ -130,7 +132,7 @@ func (s *Server) handleRepeaterInfoGet(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "pubkey must be 64 hex characters")
return
}
u, _ := s.auth.currentUser(w, r)
u, _ := s.optionalUser(w, r)
out, err := s.repeaterInfoFor(pk, u)
if err != nil {
log.Printf("[users] repeater info %s: %v", pk, err)
@@ -174,6 +176,10 @@ type repeaterEditRequest struct {
Status string `json:"status"`
Power string `json:"power"`
Notes string `json:"notes"`
// BaseRevision makes the save conditional: it must be the stored
// revision (0: no details saved yet). nil saves unconditionally, as the
// browser editor does.
BaseRevision *int64 `json:"baseRevision"`
}
func fmtFloat(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) }
@@ -206,6 +212,15 @@ func repeaterEditDiff(prev *users.RepeaterInfo, next users.RepeaterEdit) map[str
return out
}
// withVia marks an audit detail written through a device token, so admins can
// tell app writes from browser ones.
func withVia(detail map[string]string, sess *users.Session) map[string]string {
if sess != nil && sess.Kind == users.SessionKindDevice {
detail["via"] = "device"
}
return detail
}
// repeaterTarget applies the per-user rate limit and normalises the pubkey;
// with needKnown it also requires a known repeater in the analyzer DB. ok
// false means the error answer is already written.
@@ -246,7 +261,7 @@ func (s *Server) writeRepeaterInfo(w http.ResponseWriter, pk string, u *users.Us
writeJSON(w, out)
}
func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u *users.User, _ *users.Session) {
func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u *users.User, sess *users.Session) {
pk, ok := s.repeaterTarget(w, r, u, true)
if !ok {
return
@@ -255,6 +270,10 @@ func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u
if !decodeJSON(w, r, &req) {
return
}
if req.BaseRevision != nil && *req.BaseRevision < 0 {
writeError(w, http.StatusBadRequest, "baseRevision must not be negative")
return
}
can, err := s.auth.st.CanEditRepeater(u, pk)
if err != nil {
log.Printf("[users] repeater permission %s: %v", pk, err)
@@ -287,11 +306,31 @@ func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u
writeError(w, http.StatusInternalServerError, "internal error")
return
}
// An unchanged body writes nothing: updated_at and updated_by stay. The
// early read only decides that; the audit diff comes from the row the
// save replaced.
var curRev int64
if cur != nil {
curRev = cur.Revision
}
// A conditional save from a stale base is refused even when it would
// change nothing: the client's copy is out of date either way.
if req.BaseRevision != nil && *req.BaseRevision != curRev {
s.writeRepeaterConflict(w, pk, u)
return
}
// An unchanged body writes nothing: updated_at, updated_by and the
// revision stay. The early read only decides that; the audit diff comes
// from the row the save replaced.
if len(repeaterEditDiff(cur, edit)) > 0 {
prev, err := s.auth.st.SaveRepeaterInfo(u.ID, pk, edit)
var prev *users.RepeaterInfo
if req.BaseRevision != nil {
prev, err = s.auth.st.SaveRepeaterInfoAt(u.ID, pk, edit, *req.BaseRevision)
} else {
prev, err = s.auth.st.SaveRepeaterInfo(u.ID, pk, edit)
}
if errors.Is(err, users.ErrRepeaterConflict) {
// Another save landed between the read above and this one.
s.writeRepeaterConflict(w, pk, u)
return
}
if err != nil {
if writeValidation(w, err) {
return
@@ -302,12 +341,24 @@ func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u
}
diff := repeaterEditDiff(prev, edit)
diff["pubkey"] = pk
s.auth.auditAsync(idPtr(u.ID), "repeater.edit", nil, diff)
s.auth.auditAsync(idPtr(u.ID), "repeater.edit", nil, withVia(diff, sess))
}
s.writeRepeaterInfo(w, pk, u)
}
func (s *Server) handleRepeaterClaim(w http.ResponseWriter, r *http.Request, u *users.User, _ *users.Session) {
// writeRepeaterConflict answers 409 with the stored details, so the client
// can merge and retry from their revision without another read.
func (s *Server) writeRepeaterConflict(w http.ResponseWriter, pk string, u *users.User) {
out, err := s.repeaterInfoFor(pk, u)
if err != nil {
log.Printf("[users] repeater info %s: %v", pk, err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
writeJSONStatus(w, http.StatusConflict, out)
}
func (s *Server) handleRepeaterClaim(w http.ResponseWriter, r *http.Request, u *users.User, sess *users.Session) {
pk, ok := s.repeaterTarget(w, r, u, true)
if !ok {
return
@@ -319,12 +370,12 @@ func (s *Server) handleRepeaterClaim(w http.ResponseWriter, r *http.Request, u *
return
}
if added {
s.auth.auditAsync(idPtr(u.ID), "repeater.claim", idPtr(u.ID), map[string]string{"pubkey": pk})
s.auth.auditAsync(idPtr(u.ID), "repeater.claim", idPtr(u.ID), withVia(map[string]string{"pubkey": pk}, sess))
}
s.writeRepeaterInfo(w, pk, u)
}
func (s *Server) handleRepeaterUnclaim(w http.ResponseWriter, r *http.Request, u *users.User, _ *users.Session) {
func (s *Server) handleRepeaterUnclaim(w http.ResponseWriter, r *http.Request, u *users.User, sess *users.Session) {
pk, ok := s.repeaterTarget(w, r, u, false)
if !ok {
return
@@ -339,7 +390,7 @@ func (s *Server) handleRepeaterUnclaim(w http.ResponseWriter, r *http.Request, u
writeError(w, http.StatusInternalServerError, "internal error")
return
}
s.auth.auditAsync(idPtr(u.ID), "repeater.unclaim", idPtr(u.ID), map[string]string{"pubkey": pk})
s.auth.auditAsync(idPtr(u.ID), "repeater.unclaim", idPtr(u.ID), withVia(map[string]string{"pubkey": pk}, sess))
s.writeRepeaterInfo(w, pk, u)
}
+164
View File
@@ -0,0 +1,164 @@
package main
import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
func editAt(base int64, fields map[string]any) map[string]any {
out := map[string]any{"baseRevision": base}
for k, v := range fields {
out[k] = v
}
return out
}
func TestRepeaterRevisionOnReads(t *testing.T) {
f := repeaterFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
if got := decode[repeaterInfoJSON](t, f.do("GET", repPath(rpkA, "info"), nil)); got.Revision != 0 {
t.Fatalf("revision without details = %d, want 0", got.Revision)
}
got := decode[repeaterInfoJSON](t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": "a"}, as(alice)))
if got.Revision != 1 {
t.Fatalf("revision after the first save = %d", got.Revision)
}
// Claims are not details: they leave the revision alone.
got = decode[repeaterInfoJSON](t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)))
if got.Revision != 1 {
t.Fatalf("revision after a claim = %d", got.Revision)
}
list := decode[repeaterInfoListJSON](t, f.do("GET", "/api/repeaters/info", nil))
if len(list.Repeaters) != 1 || list.Repeaters[0].Revision != 1 {
t.Fatalf("list = %+v", list)
}
}
// Two clients start from the same copy: the first save wins, the second gets
// 409 with what is stored now and changes nothing.
func TestRepeaterEditBaseRevisionConflict(t *testing.T) {
f := repeaterFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
f.registerAndActivate(t, "bob@example.org", "Bob", pw)
bob := f.scopedToken(t, "bob@example.org", "Bob", deviceScopeRepeaterEdit)
// First edit of a repeater with no details yet.
w := f.do("PUT", repPath(rpkA, "info"), editAt(0, map[string]any{"notes": "from Alice"}), as(alice))
expectStatus(t, w, 200)
if got := decode[repeaterInfoJSON](t, w); got.Revision != 1 || got.Notes != "from Alice" {
t.Fatalf("Alice's save = %+v", got)
}
w = f.do("PUT", repPath(rpkA, "info"), editAt(0, map[string]any{"notes": "from Bob"}), bearer(bob))
expectStatus(t, w, http.StatusConflict)
got := decode[repeaterInfoJSON](t, w)
if got.Revision != 1 || got.Notes != "from Alice" || got.CanEdit == nil || !*got.CanEdit {
t.Fatalf("409 body = %+v, want the stored details with caller fields", got)
}
// Bob merges and retries from the revision the 409 gave him.
w = f.do("PUT", repPath(rpkA, "info"), editAt(got.Revision, map[string]any{"notes": "from Alice\nand Bob"}), bearer(bob))
expectStatus(t, w, 200)
if got := decode[repeaterInfoJSON](t, w); got.Revision != 2 || got.UpdatedBy == nil || *got.UpdatedBy != "Bob" {
t.Fatalf("Bob's retry = %+v", got)
}
// Alice's copy is now stale, even for a body that would change nothing.
expectStatus(t, f.do("PUT", repPath(rpkA, "info"), editAt(1, map[string]any{"notes": "from Alice\nand Bob"}), as(alice)), http.StatusConflict)
// One audit row per accepted save; the refused ones wrote none.
if rows := auditOf(t, f, alice.me.ID, "repeater.edit"); len(rows) != 1 {
t.Fatalf("Alice's edit audit rows = %d, want 1", len(rows))
}
}
// Without baseRevision a save is unconditional, as the browser editor sends it.
func TestRepeaterEditWithoutBaseRevision(t *testing.T) {
f := repeaterFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
for i, notes := range []string{"one", "two"} {
w := f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": notes}, as(alice))
expectStatus(t, w, 200)
if got := decode[repeaterInfoJSON](t, w); got.Revision != int64(i+1) {
t.Fatalf("save %d revision = %d", i+1, got.Revision)
}
}
// An unchanged save writes nothing, so the revision stays.
if got := decode[repeaterInfoJSON](t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": "two"}, as(alice))); got.Revision != 2 {
t.Fatalf("revision after an unchanged save = %d", got.Revision)
}
if got := decode[repeaterInfoJSON](t, f.do("PUT", repPath(rpkA, "info"), editAt(2, map[string]any{"notes": "two"}), as(alice))); got.Revision != 2 {
t.Fatalf("revision after an unchanged conditional save = %d", got.Revision)
}
}
func TestRepeaterEditBaseRevisionValidation(t *testing.T) {
f := repeaterFixture(t)
alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw)
w := f.do("PUT", repPath(rpkA, "info"), editAt(-1, map[string]any{"notes": "x"}), as(alice))
expectStatus(t, w, 400)
if !strings.Contains(w.Body.String(), "baseRevision") {
t.Fatalf("body = %s", w.Body.String())
}
// Permission is checked before the revision: no 409 leaks the details.
alicePK := rpkA
expectStatus(t, f.do("POST", repPath(alicePK, "claim"), nil, as(alice)), 200)
bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw)
expectStatus(t, f.do("PUT", repPath(rpkA, "info"), editAt(7, map[string]any{"notes": "y"}), as(bob)), 403)
}
// Two requests from the same revision at the same time: one 200, one 409.
func TestRepeaterEditConcurrentSaves(t *testing.T) {
f := repeaterFixture(t)
f.registerAndActivate(t, "alice@example.org", "Alice", pw)
f.registerAndActivate(t, "bob@example.org", "Bob", pw)
tokens := []string{
f.scopedToken(t, "alice@example.org", "Alice", deviceScopeRepeaterEdit),
f.scopedToken(t, "bob@example.org", "Bob", deviceScopeRepeaterEdit),
}
for _, base := range []int64{0, 1} {
codes := make([]int, len(tokens))
var wg sync.WaitGroup
for i, tok := range tokens {
wg.Add(1)
go func(i int, tok string) {
defer wg.Done()
body := editAt(base, map[string]any{"notes": "client " + string(rune('A'+i)) + " at " + string(rune('0'+base))})
codes[i] = f.serve("PUT", repPath(rpkA, "info"), body, bearer(tok)).Code
}(i, tok)
}
wg.Wait()
f.srv.auth.waitAudits()
ok, conflict := 0, 0
for _, c := range codes {
switch c {
case 200:
ok++
case http.StatusConflict:
conflict++
}
}
if ok != 1 || conflict != 1 {
t.Fatalf("base %d: codes %v, want one 200 and one 409", base, codes)
}
}
if info, err := f.st.GetRepeaterInfo(rpkA); err != nil || info.Revision != 2 {
t.Fatalf("stored = %+v, %v", info, err)
}
}
func TestClientConfigAnnouncesRepeaterTokens(t *testing.T) {
srv, router := setupTestServer(t)
get := func() string {
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/client", nil))
return w.Body.String()
}
if strings.Contains(get(), "repeaterTokens") {
t.Fatal("repeaterTokens present with user management off")
}
a, _ := newTestAuthService(t)
srv.auth = a
if !strings.Contains(get(), `"repeaterTokens":true`) {
t.Fatalf("repeaterTokens missing with user management on: %s", get())
}
}
+1 -1
View File
@@ -581,7 +581,7 @@ func (s *Server) clientUserManagement() *ClientUserManagement {
if s.auth == nil {
return nil
}
return &ClientUserManagement{Enabled: true, ChannelProposals: s.auth.set.proposals.enabled, Notifications: s.auth.notify != nil, CompanionLinking: true, ObserverLogins: s.auth.set.observerLogins.enabled}
return &ClientUserManagement{Enabled: true, ChannelProposals: s.auth.set.proposals.enabled, Notifications: s.auth.notify != nil, CompanionLinking: true, ObserverLogins: s.auth.set.observerLogins.enabled, RepeaterTokens: true}
}
func (s *Server) handleConfigAreas(w http.ResponseWriter, r *http.Request) {
+4
View File
@@ -1145,12 +1145,16 @@ type ClientConfigResponse struct {
// channel proposals and node notifications are on. CompanionLinking says the
// device-token and companion routes exist: CoreDrive RX shows its login only
// then, because an older CoreScope answers those paths with the SPA page.
// RepeaterTokens says device tokens may ask for the repeater scopes and that
// repeater edits take a baseRevision; a client offers native claims and
// edits only then.
type ClientUserManagement struct {
Enabled bool `json:"enabled"`
ChannelProposals bool `json:"channelProposals,omitempty"`
Notifications bool `json:"notifications,omitempty"`
CompanionLinking bool `json:"companionLinking,omitempty"`
ObserverLogins bool `json:"observerLogins,omitempty"`
RepeaterTokens bool `json:"repeaterTokens,omitempty"`
}
// CustomizerClientConfig is the operator-side customizer-modal knobs that
+1 -1
View File
@@ -49,7 +49,7 @@ func TestClientConfigAdvertisesUserManagement(t *testing.T) {
srv.auth = a
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/client", nil))
if !strings.Contains(w.Body.String(), `"userManagement":{"enabled":true,"companionLinking":true}`) {
if !strings.Contains(w.Body.String(), `"userManagement":{"enabled":true,"companionLinking":true,"repeaterTokens":true}`) {
t.Fatalf("client config = %s", w.Body.String())
}
}
+1 -1
View File
@@ -162,7 +162,7 @@ Error codes you can get on the routes above:
| `502` | `"mail provider unavailable"` (mail refresh) |
| `503` | `"mail could not be sent, try again later"` |
With user management on, every endpoint that needs `X-API-Key` also accepts an admin session (plus the CSRF header for unsafe methods). A request that sends `X-API-Key` is judged on the key alone. `GET /api/config/client` gains `"userManagement": {"enabled": true}` only when the feature is on; that block also carries `"companionLinking": true` on servers with the device-token and companion routes, which CoreDrive RX checks before it shows its login (an older server answers those paths with the SPA page).
With user management on, every endpoint that needs `X-API-Key` also accepts an admin session (plus the CSRF header for unsafe methods). A request that sends `X-API-Key` is judged on the key alone. `GET /api/config/client` gains `"userManagement": {"enabled": true}` only when the feature is on; that block also carries `"companionLinking": true` on servers with the device-token and companion routes, which CoreDrive RX checks before it shows its login (an older server answers those paths with the SPA page), and `"repeaterTokens": true` on servers whose device tokens can ask for the `repeater:claim` and `repeater:edit` scopes and whose repeater edits take a `baseRevision` (a mobile client offers native repeater claims and edits only then).
---
+16 -1
View File
@@ -305,7 +305,8 @@ With user management on, a user logs in from the CoreDrive RX app with their ema
RX then holds a **device token** instead of a cookie: it shows under *My account, Devices* as
"CoreDrive RX – <device name>", lasts 90 days from its last use, and *Log out* there revokes it.
The token is limited to the account routes RX needs (`/api/auth/me`, `/api/auth/logout`,
`/api/account/settings`, `/api/account/companions*`); anything else answers 403.
`/api/account/settings`, `/api/account/companions*`); anything else answers 403. Other apps can
ask for other scopes instead (see *Repeater info, Mobile apps*).
RX then links the companion it is connected to: the companion signs a server challenge with its
own key, so only whoever holds the device can link it. The newest proof wins: a companion that
@@ -351,6 +352,20 @@ enabled.
longer in the database until you unclaim it. Deep link: `#/account?section=repeaters`.
- **Removing a claim:** *Admin, Users*, open the user, *Remove* next to the claim. Admins use
this when a claimer left or claimed a repeater that is not theirs.
- **Mobile apps:** an app logs in at `POST /api/auth/device-token` like CoreDrive RX, but asks
for the scopes it needs: `repeater:claim` to claim a repeater and remove its own claim,
`repeater:edit` to edit details (still only where the account may edit, as above). Either
scope also lets the app read the account's own *My repeaters* list
(`GET /api/account/repeaters`). The token shows under *My account, Devices*, and its claims and edits are recorded with `via: device`.
Admin claim removal stays in the browser. There is no separate switch. An admin's
`repeater:edit` token can edit the details of every repeater, as an admin can in the browser,
for as long as the token lives (90 days, renewed with use); log it out under *Devices* when the
device is lost or changes hands.
- **Edits from two places:** each save of the details counts up a `revision`. The node page and
an app both send the revision they started from, and if someone saved in between, CoreScope
refuses the save and returns the current details instead of overwriting them. The node page
keeps what you typed and shows the saved values under the form: *Save* again replaces them,
*Cancel* keeps them.
### Observer MQTT logins (optional)
+162
View File
@@ -0,0 +1,162 @@
package users
import (
"database/sql"
"errors"
"path/filepath"
"sync"
"testing"
)
const revPK = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11"
func revisionOf(t *testing.T, st *Store) int64 {
t.Helper()
info, err := st.GetRepeaterInfo(revPK)
if errors.Is(err, ErrNotFound) {
return 0
}
if err != nil {
t.Fatal(err)
}
return info.Revision
}
func TestRepeaterInfoRevisionCountsSaves(t *testing.T) {
st, _ := newTestStore(t)
u := activeUser(t, st, "a@example.org", "Aa")
if got := revisionOf(t, st); got != 0 {
t.Fatalf("revision without a row = %d, want 0", got)
}
for want := int64(1); want <= 3; want++ {
if _, err := st.SaveRepeaterInfo(u.ID, revPK, RepeaterEdit{GainDBi: float64(want)}); err != nil {
t.Fatal(err)
}
if got := revisionOf(t, st); got != want {
t.Fatalf("after save %d revision = %d", want, got)
}
}
rows, err := st.ListRepeaterInfo()
if err != nil || len(rows) != 1 || rows[0].Revision != 3 {
t.Fatalf("ListRepeaterInfo = %+v, %v", rows, err)
}
}
func TestSaveRepeaterInfoAtFirstSave(t *testing.T) {
st, _ := newTestStore(t)
u := activeUser(t, st, "a@example.org", "Aa")
// A base above 0 when nothing is saved yet is stale.
if _, err := st.SaveRepeaterInfoAt(u.ID, revPK, RepeaterEdit{Notes: "x"}, 1); !errors.Is(err, ErrRepeaterConflict) {
t.Fatalf("base 1 without a row: %v, want ErrRepeaterConflict", err)
}
if _, err := st.GetRepeaterInfo(revPK); !errors.Is(err, ErrNotFound) {
t.Fatalf("a refused save created a row: %v", err)
}
prev, err := st.SaveRepeaterInfoAt(u.ID, revPK, RepeaterEdit{Notes: "first"}, 0)
if err != nil || prev != nil || revisionOf(t, st) != 1 {
t.Fatalf("first save from 0: prev=%+v err=%v rev=%d", prev, err, revisionOf(t, st))
}
// Base 0 again means "nothing saved yet", which is no longer true.
if _, err := st.SaveRepeaterInfoAt(u.ID, revPK, RepeaterEdit{Notes: "second"}, 0); !errors.Is(err, ErrRepeaterConflict) {
t.Fatalf("second save from 0: %v, want ErrRepeaterConflict", err)
}
if info, _ := st.GetRepeaterInfo(revPK); info.Notes != "first" || info.Revision != 1 {
t.Fatalf("row after the refused save = %+v", info)
}
}
func TestSaveRepeaterInfoAtStaleBase(t *testing.T) {
st, _ := newTestStore(t)
u := activeUser(t, st, "a@example.org", "Aa")
if _, err := st.SaveRepeaterInfo(u.ID, revPK, RepeaterEdit{Notes: "one"}); err != nil {
t.Fatal(err)
}
prev, err := st.SaveRepeaterInfoAt(u.ID, revPK, RepeaterEdit{Notes: "two"}, 1)
if err != nil || prev == nil || prev.Notes != "one" || revisionOf(t, st) != 2 {
t.Fatalf("save from 1: prev=%+v err=%v rev=%d", prev, err, revisionOf(t, st))
}
if _, err := st.SaveRepeaterInfoAt(u.ID, revPK, RepeaterEdit{Notes: "stale"}, 1); !errors.Is(err, ErrRepeaterConflict) {
t.Fatalf("save from stale 1: %v, want ErrRepeaterConflict", err)
}
// Validation still comes first.
if _, err := st.SaveRepeaterInfoAt(u.ID, revPK, RepeaterEdit{Status: "planned"}, 2); errors.Is(err, ErrRepeaterConflict) || err == nil {
t.Fatalf("invalid edit: %v, want a validation error", err)
}
if info, _ := st.GetRepeaterInfo(revPK); info.Notes != "two" || info.Revision != 2 {
t.Fatalf("row = %+v", info)
}
}
// Of several saves from the same base, exactly one wins: both for the first
// save of a repeater and for a later one.
func TestSaveRepeaterInfoAtConcurrent(t *testing.T) {
st, _ := newTestStore(t)
u := activeUser(t, st, "a@example.org", "Aa")
race := func(base int64) (wins, conflicts int) {
const n = 8
var wg sync.WaitGroup
errs := make([]error, n)
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
_, errs[i] = st.SaveRepeaterInfoAt(u.ID, revPK, RepeaterEdit{GainDBi: float64(i)}, base)
}(i)
}
wg.Wait()
for _, err := range errs {
switch {
case err == nil:
wins++
case errors.Is(err, ErrRepeaterConflict):
conflicts++
default:
t.Fatalf("unexpected error: %v", err)
}
}
return
}
if w, c := race(0); w != 1 || c != 7 {
t.Fatalf("first-save race: %d wins, %d conflicts", w, c)
}
if w, c := race(1); w != 1 || c != 7 {
t.Fatalf("update race: %d wins, %d conflicts", w, c)
}
if got := revisionOf(t, st); got != 2 {
t.Fatalf("revision = %d, want 2", got)
}
}
// A users.db written by a v9 binary keeps its repeater details, which start
// at revision 1.
func TestMigrateV9DatabaseToV10(t *testing.T) {
path := filepath.Join(t.TempDir(), "users.db")
db, err := sql.Open("sqlite", path)
if err != nil {
t.Fatal(err)
}
stmts := []string{`CREATE TABLE schema_version (version INTEGER NOT NULL)`, `INSERT INTO schema_version (version) VALUES (9)`}
for _, m := range migrations[:9] {
stmts = append(stmts, m...)
}
stmts = append(stmts, `INSERT INTO repeater_info (pubkey, notes, updated_at) VALUES ('`+revPK+`', 'old', 1)`)
for _, s := range stmts {
if _, err := db.Exec(s); err != nil {
t.Fatalf("build v9 db: %v", err)
}
}
db.Close()
st, err := Open(path)
if err != nil {
t.Fatalf("Open v9 db: %v", err)
}
defer st.Close()
if v, err := st.SchemaVersion(); err != nil || v != len(migrations) || v < 10 {
t.Fatalf("SchemaVersion = %d, %v; want %d", v, err, len(migrations))
}
info, err := st.GetRepeaterInfo(revPK)
if err != nil || info.Notes != "old" || info.Revision != 1 {
t.Fatalf("migrated row = %+v, %v", info, err)
}
}
+52 -12
View File
@@ -87,11 +87,17 @@ func ValidateRepeaterEdit(e RepeaterEdit) (RepeaterEdit, error) {
return e, nil
}
// ErrRepeaterConflict: a conditional SaveRepeaterInfoAt was given a base
// revision that is not the stored one.
var ErrRepeaterConflict = errors.New("users: repeater details revision conflict")
// RepeaterInfo is the community-maintained detail row of one repeater.
// UpdatedBy and UpdatedByName are empty when the editor was deleted or is not
// an active user.
// an active user. Revision counts saves from 1; a repeater without a row is
// at revision 0.
type RepeaterInfo struct {
Pubkey string
Revision int64
HeightM *float64
GainDBi float64
Status string
@@ -110,7 +116,7 @@ type RepeaterClaim struct {
ClaimedAt time.Time
}
const repeaterInfoSelect = `SELECT i.pubkey, i.height_m, i.gain_dbi, i.status, i.power, i.notes, i.updated_at, u.id, u.display_name
const repeaterInfoSelect = `SELECT i.pubkey, i.revision, i.height_m, i.gain_dbi, i.status, i.power, i.notes, i.updated_at, u.id, u.display_name
FROM repeater_info i LEFT JOIN users u ON u.id = i.updated_by AND u.status = 'active'`
func scanRepeaterInfo(r rowScanner) (*RepeaterInfo, error) {
@@ -121,7 +127,7 @@ func scanRepeaterInfo(r rowScanner) (*RepeaterInfo, error) {
ub sql.NullInt64
updatedAtUnix int64
)
if err := r.Scan(&ri.Pubkey, &h, &ri.GainDBi, &st, &pw, &ri.Notes, &updatedAtUnix, &ub, &name); err != nil {
if err := r.Scan(&ri.Pubkey, &ri.Revision, &h, &ri.GainDBi, &st, &pw, &ri.Notes, &updatedAtUnix, &ub, &name); err != nil {
return nil, err
}
if h.Valid {
@@ -168,10 +174,22 @@ func (s *Store) ListRepeaterInfo() ([]RepeaterInfo, error) {
return out, rows.Err()
}
// SaveRepeaterInfo validates and upserts the row. It returns the row the write
// replaced (nil if there was none), read in the same transaction, for the
// audit diff.
// SaveRepeaterInfo validates and upserts the row, whatever its revision. It
// returns the row the write replaced (nil if there was none), read in the
// same transaction, for the audit diff.
func (s *Store) SaveRepeaterInfo(userID int64, pubkey string, e RepeaterEdit) (*RepeaterInfo, error) {
return s.saveRepeaterInfo(userID, pubkey, e, nil)
}
// SaveRepeaterInfoAt is SaveRepeaterInfo only while the stored revision is
// base (0: no row yet). Otherwise it writes nothing and returns
// ErrRepeaterConflict. The check is part of the write statement, so of two
// saves from the same base exactly one wins.
func (s *Store) SaveRepeaterInfoAt(userID int64, pubkey string, e RepeaterEdit, base int64) (*RepeaterInfo, error) {
return s.saveRepeaterInfo(userID, pubkey, e, &base)
}
func (s *Store) saveRepeaterInfo(userID int64, pubkey string, e RepeaterEdit, base *int64) (*RepeaterInfo, error) {
pk, err := NormalizePubkey(pubkey)
if err != nil {
return nil, err
@@ -202,14 +220,36 @@ func (s *Store) SaveRepeaterInfo(userID int64, pubkey string, e RepeaterEdit) (*
if e.Power != "" {
pw = e.Power
}
if _, err := tx.Exec(`INSERT INTO repeater_info (pubkey, height_m, gain_dbi, status, power, notes, updated_at, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(pubkey) DO UPDATE SET height_m = excluded.height_m, gain_dbi = excluded.gain_dbi,
status = excluded.status, power = excluded.power, notes = excluded.notes,
updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
pk, h, e.GainDBi, st, pw, e.Notes, unix(s.now()), userID); err != nil {
now := unix(s.now())
var res sql.Result
switch {
case base == nil:
res, err = tx.Exec(`INSERT INTO repeater_info (pubkey, revision, height_m, gain_dbi, status, power, notes, updated_at, updated_by)
VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(pubkey) DO UPDATE SET revision = repeater_info.revision + 1,
height_m = excluded.height_m, gain_dbi = excluded.gain_dbi,
status = excluded.status, power = excluded.power, notes = excluded.notes,
updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
pk, h, e.GainDBi, st, pw, e.Notes, now, userID)
case *base == 0:
// Only the first save of a repeater: a row that exists is a conflict.
res, err = tx.Exec(`INSERT INTO repeater_info (pubkey, revision, height_m, gain_dbi, status, power, notes, updated_at, updated_by)
VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(pubkey) DO NOTHING`,
pk, h, e.GainDBi, st, pw, e.Notes, now, userID)
default:
res, err = tx.Exec(`UPDATE repeater_info SET revision = revision + 1, height_m = ?, gain_dbi = ?,
status = ?, power = ?, notes = ?, updated_at = ?, updated_by = ?
WHERE pubkey = ? AND revision = ?`,
h, e.GainDBi, st, pw, e.Notes, now, userID, pk, *base)
}
if err != nil {
return nil, err
}
if n, err := res.RowsAffected(); err != nil {
return nil, err
} else if n != 1 {
return nil, ErrRepeaterConflict
}
if err := tx.Commit(); err != nil {
return nil, err
}
+7
View File
@@ -190,6 +190,13 @@ var migrations = [][]string{
updated_by INTEGER REFERENCES users(id) ON DELETE SET NULL
)`,
},
// v10: a repeater_info revision for conditional edits. It counts saves
// from 1; a repeater without a row is at revision 0, so the rows that
// exist start at 1.
{
`ALTER TABLE repeater_info ADD COLUMN revision INTEGER NOT NULL DEFAULT 0`,
`UPDATE repeater_info SET revision = 1`,
},
}
func (s *Store) migrate() error {
+22 -4
View File
@@ -127,16 +127,34 @@
submitBtn('Delete my account', true) + msgBox('delMsg') + '</form>');
}
// A CoreDrive RX device token (kind "device") shows its label and a marker;
// a browser session its user agent. Both are revoked with the same button.
// What a device token's repeater scopes allow, as shown under its name.
var DEVICE_SCOPE_TEXT = { 'repeater:claim': 'claim repeaters', 'repeater:edit': 'edit repeater details' };
// A device token without scopes or with rx is CoreDrive RX; any other app
// shows its label (the device name it sent).
function deviceName(s) {
var scopes = s.scopes || [];
if (!scopes.length || scopes.indexOf('rx') !== -1) return 'CoreDrive RX' + (s.label ? ' – ' + s.label : '');
return s.label || 'App';
}
function deviceScopesText(s) {
var parts = (s.scopes || []).map(function (sc) { return DEVICE_SCOPE_TEXT[sc]; }).filter(Boolean);
return parts.length ? 'can ' + parts.join(' and ') + ' · ' : '';
}
// A device token (kind "device") shows its name, a marker and what it may
// do; a browser session its user agent. Both are revoked with the same
// button.
function sessionsHtml(list) {
var html = '';
(list || []).forEach(function (s) {
var device = s.kind === 'device';
var name = device ? 'CoreDrive RX' + (s.label ? ' – ' + s.label : '') : (s.userAgent || 'Unknown device');
var name = device ? deviceName(s) : (s.userAgent || 'Unknown device');
html += '<li' + (device ? ' data-kind="device"' : '') + '><span>' + escapeHtml(name) +
(device ? ' <span class="um-chip um-chip-device">app</span>' : '') +
'<br><small>last seen ' + escapeHtml(fmtDate(s.lastSeenAt)) + '</small></span>' +
'<br><small>' + (device ? escapeHtml(deviceScopesText(s)) : '') +
'last seen ' + escapeHtml(fmtDate(s.lastSeenAt)) + '</small></span>' +
(s.current ? '<span class="um-chip">this device</span>'
: '<button type="button" class="account-btn account-btn-secondary" data-sess="' + escapeHtml(String(s.id)) + '">Log out</button>') + '</li>';
});
+58 -9
View File
@@ -20,14 +20,20 @@
return isNaN(d.getTime()) ? String(s) : d.toLocaleDateString();
}
function viewHtml(info, user) {
// detailRows renders the stored details as <dl> rows ('' when none).
function detailRows(info) {
var rows = '';
var claimers = info.claimers || [];
if (has(info.heightM)) rows += row('Antenna height', esc(info.heightM + ' m'));
if (info.updatedAt) rows += row('Antenna gain', esc(Number(info.gainDbi || 0) + ' dBi'));
if (has(info.status)) rows += row('Status', esc(info.status));
if (has(info.power)) rows += row('Power', esc(info.power));
if (has(info.notes)) rows += row('Notes', '<span class="repeater-info-notes">' + esc(info.notes) + '</span>');
return rows;
}
function viewHtml(info, user) {
var rows = detailRows(info);
var claimers = info.claimers || [];
if (claimers.length) rows += row('Maintained by', claimers.map(function (c) { return esc(c.displayName); }).join(', '));
if (info.updatedAt) {
rows += has(info.updatedBy)
@@ -54,13 +60,24 @@
}).join('');
}
function formHtml(info) {
// formHtml renders the edit form filled from info. theirs, when set, is
// the record someone else saved meanwhile (a 409), shown under the form
// so the typed values stay and can be compared with it.
function formHtml(info, theirs) {
var saved = '';
if (theirs) {
var rows = detailRows(theirs);
saved = '<div class="repeater-info-theirs" data-ri-theirs><p>Saved meanwhile' +
(has(theirs.updatedBy) ? ' by ' + esc(theirs.updatedBy) : '') + ':</p>' +
(rows ? '<dl class="repeater-info-list">' + rows + '</dl>' : '<p class="text-muted">No details.</p>') + '</div>';
}
return '<form class="repeater-info-form" data-ri-form novalidate>' +
'<label>Antenna height (m)<input type="number" name="heightM" min="0" max="300" step="0.1" value="' + (has(info.heightM) ? esc(info.heightM) : '') + '"></label>' +
'<label>Antenna gain (dBi)<input type="number" name="gainDbi" min="-10" max="30" step="0.1" value="' + esc(has(info.gainDbi) ? info.gainDbi : 0) + '"></label>' +
'<label>Status<select name="status">' + options(STATUSES, info.status) + '</select></label>' +
'<label>Power<select name="power">' + options(POWERS, info.power) + '</select></label>' +
'<label>Notes<textarea name="notes" maxlength="500" rows="3">' + esc(info.notes || '') + '</textarea></label>' +
saved +
'<p class="repeater-info-notice">Your display name will be shown publicly as the last editor of this repeater.</p>' +
'<div class="repeater-info-actions"><button type="submit" class="btn-primary" data-ri-save>Save</button> ' +
'<button type="button" class="btn-primary" data-ri-cancel>Cancel</button></div>' +
@@ -130,22 +147,29 @@
var base = '/api/repeaters/' + encodeURIComponent(pk);
var slot = el.id || '';
var info = null;
// editRev is the revision the open form was loaded from, sent as
// baseRevision so a save made meanwhile (another tab, the app) answers
// 409 instead of being overwritten. undefined: unconditional save.
var editRev;
function keep() {
var form = el.querySelector('[data-ri-form]');
if (form) drafts[slot] = { pk: pk, values: rawForm(form) };
if (form) drafts[slot] = { pk: pk, values: rawForm(form), rev: editRev };
}
// shown is the mode on screen, or '' while nothing is (the view before
// the GET answered).
var shown = '';
function show(mode, values) {
function show(mode, values, theirs) {
var user = auth.user();
if (mode !== 'edit') delete drafts[slot];
if (mode === 'view' && !info) { shown = ''; el.innerHTML = ''; el.hidden = true; return; }
shown = mode;
el.innerHTML = '<h4>Repeater info</h4>' +
(mode === 'edit' ? formHtml(values || info) : mode === 'confirm' ? confirmHtml() : viewHtml(info, user));
if (mode === 'edit' && !values) keep();
(mode === 'edit' ? formHtml(values || info, theirs) : mode === 'confirm' ? confirmHtml() : viewHtml(info, user));
if (mode === 'edit' && !values) {
editRev = info && typeof info.revision === 'number' ? info.revision : undefined;
keep();
}
}
var busy = false;
function send(btn, method, path, body, done) {
@@ -155,6 +179,29 @@
function settle() { busy = false; if (btn) btn.disabled = false; }
return auth.request(method, path, body).then(function (r) {
settle();
if (r.status === 409 && method === 'PUT' && r.data && typeof r.data === 'object') {
// Someone saved since the form opened. Keep what the user typed,
// show the stored record under it, and base the next save on the
// stored revision, so Save then replaces it on purpose.
var form = el.querySelector('[data-ri-form]');
var typed = form ? rawForm(form) : null;
info = r.data;
if (info.canEdit) {
editRev = typeof info.revision === 'number' ? info.revision : undefined;
if (typed) {
show('edit', typed, info);
keep();
say(el, 'Someone else saved these details while you were editing. Your changes are still in the form and their saved values are below it. Save again to replace them, or Cancel to keep theirs.');
} else {
show('edit');
say(el, 'Someone else saved these details while you were editing. The form now shows the saved values; make your change again and save.');
}
} else {
show('view');
say(el, 'Someone else saved these details while you were editing, and this account can no longer edit this repeater. These are the saved values.');
}
return;
}
if (!r.ok) { say(el, auth.errText(r)); return; }
info = r.data;
done();
@@ -176,7 +223,9 @@
var form = el.querySelector('[data-ri-form]');
var err = formError(form);
if (err) { say(el, err); return; }
send(t, 'PUT', base + '/info', readForm(form), back);
var body = readForm(form);
if (typeof editRev === 'number') body.baseRevision = editRev;
send(t, 'PUT', base + '/info', body, back);
}
});
el.addEventListener('submit', function (ev) { ev.preventDefault(); });
@@ -190,7 +239,7 @@
// An open draft comes back at once, in the same task as the re-render:
// waiting for the GET would empty the section for a round trip.
var d = drafts[slot];
if (d && d.pk === pk) { show('edit', d.values); el.hidden = false; }
if (d && d.pk === pk) { editRev = d.rev; show('edit', d.values); el.hidden = false; }
return auth.request('GET', base + '/info').then(function (r) {
// A section the node page already replaced must not touch the draft
// its successor owns.
+2
View File
@@ -6020,6 +6020,8 @@ body.embed #app.app-fixed {
display: block; width: 100%; box-sizing: border-box; margin-top: 2px;
background: var(--input-bg, var(--card-bg)); color: var(--text); border: 1px solid var(--border); border-radius: 4px; padding: 4px 6px;
}
.repeater-info-theirs { border-left: 3px solid var(--border); padding: 2px 0 2px 8px; margin: 0 0 8px; }
.repeater-info-theirs p { margin: 0 0 4px; color: var(--text-muted); }
.repeater-info-notice, .repeater-info-msg { color: var(--text-muted); font-size: 12px; }
.repeater-info-actions { display: flex; gap: 6px; flex-wrap: wrap; margin: 6px 0; }
/* Global .btn-primary is white on --accent (2.75:1); same fix as .account-btn-primary. */
+74
View File
@@ -177,6 +177,80 @@ test('save PUTs the form body', async () => {
assert.strictEqual(c.p, '/api/repeaters/' + PK + '/info');
assert.deepStrictEqual(JSON.parse(JSON.stringify(c.body)), { heightM: 12.5, gainDbi: 3, status: 'active', power: 'solar', notes: 'hi' });
});
// Review on #2429: the browser sends the revision its form was loaded
// from, so it cannot silently overwrite a save made meanwhile (by the app).
test('save sends the loaded revision as baseRevision', async () => {
const form = { heightM: '12', gainDbi: '3', status: '', power: '', notes: '' };
const f = mountFlow({ info: INFO({ canEdit: true, revision: 4 }), form });
await f.l.R.mount(f.el, { public_key: PK, role: 'repeater' });
f.click('data-ri-edit');
f.click('data-ri-save');
await tick();
assert.strictEqual(f.l.calls[1].body.baseRevision, 4);
});
test('a 409 keeps the typed values, shows the stored ones under them, and the next save uses their revision', async () => {
const form = { heightM: '12', gainDbi: '3', status: '', power: '', notes: 'mine' };
const f = mountFlow({ info: INFO({ canEdit: true, revision: 4 }), form });
await f.l.R.mount(f.el, { public_key: PK, role: 'repeater' });
f.click('data-ri-edit');
const stored = INFO({ canEdit: true, revision: 5, heightM: 30, notes: 'from the app <b>', updatedBy: 'Bob <i>', updatedAt: '2026-11-20T00:00:00Z' });
const realRequest = f.l.auth.request;
f.l.auth.request = (m, p, b) => { f.l.calls.push({ method: m, p, body: b }); return Promise.resolve({ ok: false, status: 409, data: stored }); };
f.click('data-ri-save');
await tick();
assert(f.el.innerHTML.includes('data-ri-form'), 'form not kept open: ' + f.el.innerHTML);
const h = f.el.innerHTML;
assert(h.includes('value="12"') && h.includes('>mine</textarea>'), 'typed values lost: ' + h);
const theirs = h.slice(h.indexOf('data-ri-theirs'));
assert(h.indexOf('data-ri-theirs') !== -1 && theirs.includes('Saved meanwhile by Bob &lt;i&gt;:') &&
theirs.includes('30 m') && theirs.includes('from the app &lt;b&gt;'), 'stored values not shown under the form: ' + h);
assert(!h.includes('<b>') && !h.includes('<i>'), 'raw tag: ' + h);
assert(/Your changes are still in the form/.test(f.el.msg.textContent), f.el.msg.textContent);
f.l.auth.request = realRequest;
f.click('data-ri-save');
await tick();
assert.strictEqual(f.l.calls[f.l.calls.length - 1].body.baseRevision, 5, 'retry not based on the stored revision');
});
test('a 409 without edit rights any more shows the view', async () => {
const f = mountFlow({ info: INFO({ canEdit: true, revision: 1 }), form: { heightM: '', gainDbi: '', status: '', power: '', notes: '' } });
await f.l.R.mount(f.el, { public_key: PK, role: 'repeater' });
f.click('data-ri-edit');
f.l.auth.request = () => Promise.resolve({ ok: false, status: 409, data: INFO({ canEdit: false, revision: 2, heightM: 7 }) });
f.click('data-ri-save');
await tick();
assert(!f.el.innerHTML.includes('data-ri-form') && f.el.innerHTML.includes('7 m'), f.el.innerHTML);
assert(/can no longer edit this repeater/.test(f.el.msg.textContent), 'no explanation: ' + f.el.msg.textContent);
});
test('a re-mount after a 409 keeps the typed values and the stored revision', async () => {
const opts = { info: INFO({ canEdit: true, revision: 4 }), form: { heightM: '12', gainDbi: '3', status: '', power: '', notes: 'mine' } };
const a = mountFlow(opts);
await a.l.R.mount(a.el, { public_key: PK, role: 'repeater' });
a.click('data-ri-edit');
a.l.auth.request = (m, p, body) => { a.l.calls.push({ method: m, p, body }); return Promise.resolve({ ok: false, status: 409, data: INFO({ canEdit: true, revision: 6 }) }); };
a.click('data-ri-save');
await tick();
a.l.auth.request = (m, p, body) => { a.l.calls.push({ method: m, p, body }); return Promise.resolve({ ok: true, status: 200, data: INFO({ canEdit: true, revision: 6 }) }); };
const b = mountFlow(opts, a.l);
await b.l.R.mount(b.el, { public_key: PK, role: 'repeater' });
assert(b.el.innerHTML.includes('>mine</textarea>'), 'draft lost the typed notes: ' + b.el.innerHTML);
b.click('data-ri-save');
await tick();
assert.strictEqual(a.l.calls[a.l.calls.length - 1].body.baseRevision, 6, 'draft did not keep the stored revision');
});
test('a re-mounted draft keeps the revision it was opened at', async () => {
const opts = { info: INFO({ canEdit: true, revision: 3 }), form: { heightM: '25', gainDbi: '3', status: '', power: '', notes: '' } };
const a = mountFlow(opts);
await a.l.R.mount(a.el, { public_key: PK, role: 'repeater' });
a.click('data-ri-edit');
a.el.handlers.input({});
// The page re-renders; its GET now sees a newer revision from elsewhere.
a.l.auth.request = (m, p, body) => { a.l.calls.push({ method: m, p, body }); return Promise.resolve({ ok: true, status: 200, data: INFO({ canEdit: true, revision: 9 }) }); };
const b = mountFlow(opts, a.l);
await b.l.R.mount(b.el, { public_key: PK, role: 'repeater' });
b.click('data-ri-save');
await tick();
assert.strictEqual(a.l.calls[a.l.calls.length - 1].body.baseRevision, 3, 'the draft must not adopt the newer revision');
});
test('error response shows its text via textContent; clicks are ignored while busy', async () => {
const f = mountFlow({ info: INFO({ canEdit: true, claimedByMe: true }) });
await f.l.R.mount(f.el, { public_key: PK, role: 'repeater' });
+16
View File
@@ -571,6 +571,22 @@ test('my repeaters empty state explains how to claim', () => {
}
});
test('app tokens with repeater scopes show their own name and what they may do', () => {
const env = loadAccount('#/account', () => ({}));
const h = env.t.sessionsHtml([
{ id: 4, kind: 'device', label: 'NodeScope – iPhone', scopes: ['repeater:claim', 'repeater:edit'], lastSeenAt: '2026-01-01T00:00:00Z', current: false },
{ id: 5, kind: 'device', label: '', scopes: ['repeater:edit'], lastSeenAt: '2026-01-01T00:00:00Z', current: false },
{ id: 6, kind: 'device', label: '<b>x</b>', scopes: ['rx'], lastSeenAt: '2026-01-01T00:00:00Z', current: false },
{ id: 7, kind: 'device', label: 'Pixel', scopes: ['rx', 'repeater:claim'], lastSeenAt: '2026-01-01T00:00:00Z', current: false }]);
assert(h.indexOf('<span>NodeScope – iPhone <span class="um-chip um-chip-device">') !== -1, 'no app name: ' + h);
assert(h.indexOf('can claim repeaters and edit repeater details · last seen') !== -1, 'no scope line: ' + h);
assert(h.indexOf('<span>App <span class="um-chip um-chip-device">') !== -1 && h.indexOf('can edit repeater details · last seen') !== -1,
'unlabelled app row: ' + h);
assert(h.indexOf('CoreDrive RX – &lt;b&gt;x&lt;/b&gt;') !== -1 && h.indexOf('<b>x</b>') === -1, 'rx row: ' + h);
assert(h.indexOf('CoreDrive RX – Pixel') !== -1 && h.indexOf('can claim repeaters · last seen') !== -1, 'rx token with a repeater scope: ' + h);
assert.strictEqual((h.match(/data-sess=/g) || []).length, 4, 'every app row keeps its logout button');
});
test('companions list escapes fields, shortens the pubkey and says never without a reception', () => {
const env = loadAccount('#/account', () => ({}));
const pk = 'ab'.repeat(32);