mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-11-22 04:37:19 +00:00
master
3
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c83499763d |
Allow mobile clients to manage repeater claims and details (#2429)
Draft for feedback: a working version of native repeater claims and edits from mobile clients, built on the repeater info feature from #2415. Four open questions are at the end. ## Situation Repeater info (#2415) can only be claimed and edited from a browser session. Device tokens from `POST /api/auth/device-token` are limited to `rx` (CoreDrive RX: settings and companion linking), and `GET /api/repeaters/{pubkey}/info` treats a bearer token as anonymous. A mobile client can show a repeater's details but can't offer "claim" or "edit" natively. `PUT /api/repeaters/{pubkey}/info` is also a full replace with no precondition. Two people editing from the same copy silently overwrite each other. That's rare in the browser, but likelier from an app that keeps a cached copy. ## Change Three commits, one per piece. **1. Device-token scopes for the repeater routes** (`8aba3715`) - `POST /api/auth/device-token` takes an optional `scopes` list. Omitted (or `null`) still means `["rx"]`, so CoreDrive RX and every existing token keep exactly their current permissions. An empty list or an unknown scope answers 400, checked before the password. - New scopes: - `repeater:claim`: `POST` and `DELETE /api/repeaters/{pubkey}/claim`. These already only add or remove the caller's own claim. Several claimers per repeater, idempotent `POST`, unchanged. - `repeater:edit`: `PUT /api/repeaters/{pubkey}/info`, still subject to `CanEditRepeater`. - Every device token may use `/api/auth/me` and `/api/auth/logout`, so a repeater-only token can check and end its own login. - `GET /api/repeaters/{pubkey}/info` with a token holding either repeater scope returns `canEdit` and `claimedByMe`. An unknown or expired token answers 401 rather than passing as anonymous, so a client learns its login is gone. A valid token without a repeater scope still gets the public view. A cookie still wins over a bearer header, as elsewhere. - `GET /api/account/repeaters` (My repeaters, from #2430) also takes a token holding either repeater scope, so an app gets the account's claims in one request. It can't build that list from the public catalog, where claimers are display names, and reading repeaters one at a time would miss a claimed repeater that has left the node list. An `rx`-only token still answers 403. - Scope checks are method-aware (`bearerScopesFor(method, path)`). The repeater paths are added to the bearer CORS paths. - Same handlers, validation, rate limit (`repeater`, 120/h per user and per IP), audit actions and admin claim removal as the browser. Token writes add `via: device` to the `repeater.claim`, `repeater.edit` and `repeater.unclaim` rows, and the `user.login` row records the granted scopes. The admin route keeps refusing bearer tokens. **2. Conditional edits with a revision** (`9f9bf47b`) - `users.db` schema v10 adds `repeater_info.revision`. Existing rows start at 1; a repeater with no saved details is at 0. Claims don't change it. - `GET` (single and list) and `PUT` responses include `revision`. - `PUT` accepts an optional `baseRevision`. The check is part of the write statement, so of two saves from the same base exactly one lands: - `baseRevision: 0` (first save): `INSERT … ON CONFLICT(pubkey) DO NOTHING`. - `baseRevision: n`: `UPDATE … SET revision = revision + 1 … WHERE pubkey = ? AND revision = ?`. - No match answers `409` with the stored details (`canEdit`/`claimedByMe` included) and writes nothing. That's the same shape `PUT /api/account/settings` uses for its conflicts. - A stale base is refused even when the body would change nothing. - Permission is checked first, so a 409 never shows details to someone who can't edit. - Without `baseRevision` the save is unconditional and bumps the revision, so `public/repeater-info.js` works unchanged. - `/api/config/client` adds `userManagement.repeaterTokens: true`, so a client can tell this server from one without the scopes or `baseRevision` (older servers answer the device-token request with the SPA page, as noted for `companionLinking`). **Discovery and conflict recovery, for a client:** 1. Check `userManagement.repeaterTokens` in `/api/config/client`. Without it, keep the claim and edit actions hidden. 2. Log in with `scopes: ["repeater:claim", "repeater:edit"]` (or just what the client offers). The response echoes the granted `scopes`. 3. Read `GET /api/repeaters/{pubkey}/info` with the token. Show Claim/Unclaim from `claimedByMe` and Edit from `canEdit`, and keep `revision`. 4. Save with `PUT …/info` and `baseRevision` set to that revision. On 200, keep the new `revision` from the response. On 409, the body is the current record: show or merge it, then retry with its `revision`. On 401, log in again. On 403, the account can no longer edit (for example someone claimed it), so refresh from `canEdit`. **3. Account page device list** (`d28374aa`) My account, Devices labelled every device token "CoreDrive RX". `/api/account/sessions` now includes a device token's `scopes`. The page keeps the CoreDrive RX label for `rx` tokens (and rows without scopes). It shows other tokens under the device name the app sent, with a line such as "can claim repeaters and edit repeater details". Docs: `openapi.go`, `docs/api-spec.md` and the Repeater info section of `docs/user-guide/accounts.md`. ## Questions 1. **One scope or two?** This uses separate `repeater:claim` and `repeater:edit`, so a client can ask for less, and a token that only edits can't put the user's name on a repeater publicly. One `repeater` scope would be simpler if you'd rather not split it. 2. **Editing unclaimed repeaters from mobile.** This keeps web parity: any active user may edit a repeater nobody has claimed, and once it has claimers only they (and admins) can. The alternative is to require a claim before a token may edit. That's stricter, but then app and browser rules differ. 3. **Operator switch.** There's no new setting: the scopes are available whenever `userManagement` is on, and the user opts in when the app asks for them at login. Would you want an explicit opt-in such as `userManagement.mobileRepeaterWrites`? 4. **Stale-edit contract.** Does `revision` plus `baseRevision` in the body, with 409 returning the current record, fit? I matched account settings rather than `ETag`/`If-Match`, to keep one pattern in the API. The browser editor doesn't send `baseRevision` yet. Making it send one would be a small follow-up, if you want browser saves protected too. ## Tests - `cmd/server/repeater_device_token_test.go`: - default and requested scopes, rejected scopes, and the method-aware route table; - per-scope allowed and denied routes, logout with a repeater-only token; - claim and unclaim of own claim only, alongside another claimer; - edit permission (unclaimed repeater, claimer, non-claimer, admin) and a disabled account; - the admin route refusing tokens; - authenticated, public and expired-token reads; - `via: device` audit rows, cookie writes still needing CSRF, and session scopes. - My repeaters with a claim or edit token (own claims only), and 403 for an `rx`-only token. - `cmd/server/repeater_revision_test.go`: - revision on reads, a first edit with no saved row, and a stale base returning 409 with the current record and no audit row; - unconditional browser saves, validation and permission order; - two concurrent saves from the same revision (one 200, one 409), and the client config flag. - `internal/users/repeater_revision_test.go`: - revision counting and conditional first and later saves; - an 8-way race for both cases (`-race`); - the v9 to v10 upgrade. - `tests/unit/test-user-management-ui.js`: app token labels and scope line. Run locally: - `make test`: all 16 modules OK. - `sh test-all.sh`: all suites pass, run in `node:24-bookworm`. On macOS, `test-manage-workflow.js` fails 2 cases on unchanged master because of the BSD tools. - `npx eslint public/*.js`: 0 errors, the same 87 warnings as master. - `node tests/e2e/test-lint-network-calls.js` - `tests/e2e/test-user-management-e2e.js` against local e2etest servers with the CI config: 44/44. - Manually against a local instance: - in the browser: claim, edit, unclaim, and the Devices list; - with curl: the token flow, including a 409 after a browser save. Not run: the full Playwright shard matrix from CI. --------- Co-authored-by: Adam <196335+anieto@users.noreply.github.com> |
||
|
|
b2cda21a27 |
feat(server): companion linking routes, device tokens and bearer auth (#2175)
Part 2 of 3 for #2173 (companion linking): the server routes, bearer auth and the link handshake. Builds on #2174 (merged); `upstream/master` is merged in, so the diff shows only this part. Everything here is behind `userManagement.enabled` and answers 404 with it off. ## Changes in this PR **Device tokens and bearer auth** - `POST /api/auth/device-token`: email + password returns a bearer token, stored as a `kind = 'device'` session with a label. Same failure answers and the same rate limit as login. - Server-enforced scope for a bearer token: `/api/auth/me`, `/api/auth/logout`, `/api/account/companions*`, `/api/account/settings`. Everything else answers 403. - A bearer header only counts when there is no session cookie, so an auth proxy that adds its own `Authorization` header does not hide a logged-in browser. Cookies never accept a device token. - The sessions list on the account API carries `kind` and `label`; logout with a bearer token revokes that device. **Linking a companion** - `POST /api/account/companions/challenge` `{pubkey}` returns `{challenge, expiresAt, host}`: 32 random bytes, single use, 5 minutes, bound to the caller and the pubkey. - `POST /api/account/companions` `{pubkey, challenge, signature, name}`: the signature is the companion's Ed25519 signature over `corescope-link:<host>:<challenge>` (`internal/sigvalidate.VerifyMessage`). The challenge is consumed in every case. - A companion linked to another account moves to the caller (the newest proof wins). Both users get a `companion.transfer` audit row and the previous owner a mail. That mail is a security notice: it is sent whatever the node notification settings are. - `GET /api/account/companions` (with `lastSeenAt` from `client_receptions`) and `DELETE /api/account/companions/{pubkey}`. - Linking does not touch the synced `meshcore-my-nodes`: a companion is not a node to monitor. - Admin user detail lists linked companions; the account data export includes companions and device sessions. **Coverage and config** - `GET /api/rx-coverage?mine=1`: only coverage of the caller's linked companions (401 when logged out, 403 for a device token). With `gaps=1` (#2172) the reply carries no `gaps` member under `mine=1`, because the track query takes one companion and cannot narrow to a set yet (`TestRxCoverageMineOmitsGaps`). - `clientRxCoverage.requireLinkedCompanion` (default off) is read and reported in `/api/config/client`, which also announces `userManagement.companionLinking`, so CoreDrive RX shows its login only where linking exists. The ingestor side is part 3. - CORS: for origins in `corsAllowedOrigins`, the device-token routes alone also allow POST/PUT/DELETE and the `Authorization` and `Content-Type` headers. No credentialed CORS. Documented in `config.example.json`. - OpenAPI and `docs/api-spec.md` cover the new routes. ## Verification - 26 new tests in `cmd/server` and `internal/sigvalidate`, among them: `TestCompanionLinkFlow`, `TestCompanionLinkRejections` (signature by another key, malformed signature, challenge bound to another pubkey, unknown challenge; reuse and expiry are covered by the store tests in #2174), `TestCompanionTransfer`, `TestCompanionTransferMailIgnoresNotificationSettings`, `TestBearerScopedRoutes`, `TestBearerIgnoredWithCookie`, `TestDeviceTokenSharesLoginRateLimit`, `TestCORSBearerRoutes`, `TestCompanionRoutesAbsentWhenOff`, `TestRxCoverageMine`, `TestRxCoverageMineOmitsGaps` (fails without the `mine == nil` guard), `TestVerifyMessage`. - `cmd/server`, `internal/sigvalidate` and `internal/users`: `go vet` and `go test ./...` green, `gofmt` clean. - The linking flow runs on analyzer.on8ar.eu since 9 October 2026 with CoreDrive RX v1.19.0 (a real companion linked through the signed challenge). ## Not in this PR - The ingestor's linked-only filter, the account page (Devices, Companions), the "My coverage" toggle and the user docs: part 3. - Per-user broker credentials and per-user API keys (non-goals in the spec). --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
d232072f85 |
feat: optional user accounts (part A: foundation) (#2129)
Part A of #2128: optional, off-by-default user accounts. With the feature off nothing changes; with it on, visitors can register and log in, and admins manage users and use the operator actions without the API key. PR #2130 (settings sync) builds on this one. The two are meant to be merged together. ## The situation - Operator actions (geofilter save and prune, backup, perf reset) need the shared `apiKey`. There is no per-person right. - Nothing in CoreScope knows who a visitor is, so the requests in #2128 that need that (#1835, #2092, #1508, #730) have nothing to build on. ## What this PR adds **Two new Go modules** - `internal/users`: a separate `users.db` (SQLite through `modernc.org/sqlite`) with users, sessions, single-use tokens, an audit log and a mail log. Passwords use argon2id. - `internal/mailer`: a `Mailer` interface with a Brevo client (send, delivery events, webhook parsing) and an in-memory fake for tests. **Server (`cmd/server`)**, active only with `userManagement.enabled` - 24 routes, all documented in OpenAPI under the `users` tag ([`auth_routes.go`](https://github.com/efiten/CoreScope/blob/feat/user-management/cmd/server/auth_routes.go)): - auth: register, activate, login, logout, me, forgot, reset; - account: profile, password, email change with confirmation, sessions, self-delete; - admin: list, detail, disable, enable, delete, role, resend activation, manual activation, mail status refresh; - a Brevo webhook, registered only when `mail.webhookSecret` is set. - `requireAdmin` replaces `requireAPIKey` at the 7 operator call sites: the API key **or** an admin session. With the feature off it is the old API-key gate (`TestRequireAdminWithoutUserManagementIsAPIKeyGate`). - `/api/config/client` gets `userManagement: {enabled: true}` only when the service started; with the feature off the response is byte-identical. **Frontend** - `auth.js` (header account control, request helper that adds the CSRF header), `account.js` (login, register, activate, forgot, reset, confirm email, my account), `admin-users.js` (`#/admin/users`, deep-linked filters), `account.css` (theme tokens only). - On phones the top-bar control is hidden, so a conditional entry goes into the bottom-nav "More" sheet and the nav drawer. - The customizer geofilter tab and the Perf "Reset stats" button use the admin session when there is one. **Config.** A `userManagement` block (`config.example.json`, [`docs/user-guide/accounts.md`](https://github.com/efiten/CoreScope/blob/feat/user-management/docs/user-guide/accounts.md)). The Brevo key can come from `CORESCOPE_BREVO_API_KEY`. The server refuses to start when the block is enabled but incomplete. ## Security choices - Session cookie `cs_session`: HttpOnly, SameSite=Lax, Secure when `publicBaseUrl` is https. Every cookie-authenticated state change needs the `X-CS-CSRF` header and a matching Origin. - Activation needs the token **and** the account password. Without the password, an attacker who keeps re-registering a known address could get the owner to activate an account that carries the attacker's password. - Register, forgot and email change answer identically for known and unknown addresses. A password reset ends all sessions, a password change ends all other sessions, and both end outstanding email-change links. - Rate limits: login 10 per 15 minutes, register and forgot 5 per hour, per IP and per address. The bucket count is capped. `trustedProxies` makes the per-IP limits see real client IPs behind a proxy. - Server logs carry `#<user id>`, never addresses, tokens or passwords; mail-provider error texts are redacted before logging. ## Performance No change to an existing hot path with the feature off. With it on: - One `users.db` lookup per authenticated request (session by token hash). - The admin user table rebuilds its `tbody` on each filter change. `users.List` caps the result at 1000 rows (`internal/users/users.go`), which bounds the rebuild. - `map[string]interface{}` in `openapi.go`: 79 before, 78 after. ## Verification - `internal/users`, `internal/mailer` and `cmd/server`: `go vet` and `go test -race` pass locally. 121 new Go tests. - `cmd/server` with `-tags e2etest`: vet and the e2e hook tests pass. - `sh test-all.sh` exits 0. `tests/unit/test-user-management-ui.js`: 67 passing (vm, real modules). - `tests/e2e/test-user-management-e2e.js` (6 steps) passed locally against an `e2etest` build with the fake mailer and against a feature-off build. CI builds the `e2etest` binary and runs the suite on a second server (`deploy.yml`). - On a staging instance with a real Brevo key: register, activation mail delivered, activate, admin table, "Refresh status" showing sent, deferred, delivered, opened and clicked. ## Not in this PR - Settings sync (#2130), the admin dashboard, approval flows and notifications (parts B to E of #2128). - A `requireReadAuth` mode (#1835). Sessions from this PR are what such a mode would accept. - Binary size and build time with `modernc.org/sqlite` linked next to `mattn/go-sqlite3` were not measured. Their driver names do not collide. #1992 discusses the driver choice. - No Brevo webhook was configured on staging; delivery status there came from "Refresh status". --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |