Repository navigation
Allow mobile clients to manage repeater claims and details - #2429
Conversation
d28374a to
34c9758
Compare
|
Thanks for the write-up, the discovery and conflict-recovery steps made this easy to follow. I read What I checked and found fine: a device token sent as the session cookie is still refused ( One thing I'd change before merge:
Smaller suggestions:
On your questions, for what it's worth (maintainers decide):
|
|
Thanks for the careful pass on the auth paths, and for the answers on the open questions. Changes in b51e264:
Noted on the test-file conflict for whichever merges second. Locally: |
Follow-up to #2415, see #2414. ## Situation A user can claim repeaters, but no page lists the ones they claimed. Claims show on each node page ("Maintained by"), in the admin user detail and in the "Download my data" export. A maintainer of several repeaters has to remember them and open each node page to see whether one went quiet. ## Change **`GET /api/account/repeaters`** (browser session; device tokens answer 403) returns the caller's claims. For each one: - `pubkey` and `name`. - `known`: false once the node left the analyzer database. The claim stays. - `role` and `claimedAt`. - `lastHeard`: the newer of the last advert and the last transmission certainly from the node, the same sources as the node page's Last Heard. - `lastRelayed`: when its hop prefix last relayed. Only used to mark a silent repeater as uncertain, since the prefix can be shared. - `status`: the saved repeater status, or null. - `comaintainers`: the other active claimers' display names. The list is sorted by name, with unnamed repeaters after, by pubkey. It's built on the existing `RepeaterClaimsByUser`, `NotifyNodes` and `LastHeardMap`. **My account, My repeaters**, a new section after Companions: - Silent repeaters come first. Health uses `getNodeStatus`, so the threshold matches the node pages and map (`infraSilentMs`): - green "heard 2h ago"; - yellow "last heard …, its prefix still relays"; - red "silent, last heard 184d ago" or "never heard"; - grey "no longer in the database". - Each row links to the node page and shows the saved status ("no details yet" without one), the claim date and "also maintained by …". - *Unclaim* asks for confirmation, then uses the existing `DELETE /api/repeaters/{pubkey}/claim`. - The empty state says how to claim. - `#/account?section=repeaters` deep-links to the section, like `section=notifications`. Editing stays on the node page, so there's only one editor. The admin user detail and the export are unchanged. Docs: `openapi.go` and the Repeater info section of `docs/user-guide/accounts.md`. ## Notes - A mobile client will want the same list. #2429 proposes device-token scopes for repeater claims. If it lands, letting a `repeater:claim` token read this route is a one-line addition to the bearer route table, and I'd rather do that there than here. - The two PRs touch nearby lines in `openapi.go`, `repeater_handlers.go` (route registration) and `public/account.js`. Whichever merges second needs a small rebase. ## Tests - `cmd/server/my_repeaters_test.go`: - empty list; - ordering (named first, case-insensitive); - unheard, heard and departed nodes; - saved status; - co-maintainers, excluding the caller and disabled users; - another user's view; - unclaim removes the row; - anonymous gets 401 and a device token 403; - no analyzer DB. - `tests/unit/test-user-management-ui.js`: health sort and chips, escaping, the short-pubkey fallback, status and co-maintainer lines, Unclaim on every row, and the empty state. - `tests/e2e/test-user-management-e2e.js`: - the claimed repeater appears with its status and node link; - axe on the section; - Unclaim: dismissing the confirm keeps the claim, accepting empties the list. Run locally: - `make test`: all 16 modules OK. - `sh test-all.sh` and `node tests/e2e/test-lint-network-calls.js`: pass, run in `node:24-bookworm`. - `npx eslint public/*.js`: 0 errors, the same 87 warnings as master. - `test-user-management-e2e.js` against local e2etest servers with the CI config: 46/46. - Manually in Chrome, light and dark: heard, silent and co-maintained rows, and the deep link. Not run: the full Playwright shard matrix from CI. --------- Co-authored-by: Adam <196335+anieto@users.noreply.github.com>
|
Review at What holds up:
Locally: Answers to the open questions: two scopes, web parity for unclaimed repeaters, no operator switch and One decision, and what I'd like in the PR:
Minor, none blocking:
When the draft status is lifted this is ready from my side. #2430 is merged now, so the conflict zfouts mentioned in |
POST /api/auth/device-token accepts an optional scopes list. Omitting
it still issues an rx token, so CoreDrive RX and every existing token
keep exactly their current permissions. Two new scopes open the
repeater routes to mobile clients:
- repeater:claim: POST and DELETE /api/repeaters/{pubkey}/claim, which
only ever add or remove the caller's own claim.
- repeater:edit: PUT /api/repeaters/{pubkey}/info, still subject to
CanEditRepeater, the same rule the browser follows.
Every device token may use /api/auth/me and logout. A token with either
repeater scope gets canEdit and claimedByMe on GET
/api/repeaters/{pubkey}/info; an unknown or expired token there answers
401 instead of passing as anonymous. The handlers, validation, rate
limits and admin claim removal are the existing ones; token writes add
via=device to their audit rows.
PUT /api/repeaters/{pubkey}/info replaces the whole record, so two
clients editing from the same copy silently overwrite each other. That
gets likelier once an app can edit offline-ish from a cached copy.
repeater_info gains a revision (users.db schema v10; existing rows start
at 1, a repeater without details is at 0). Reads return it, and a PUT
may send it back as baseRevision. A conditional save checks the base in
the same statement as the write: an UPDATE ... WHERE revision = ? for a
saved repeater, and an INSERT ... ON CONFLICT DO NOTHING for the first
save, so of two saves from the same base exactly one lands. The loser
gets 409 with the stored details, the shape PUT /api/account/settings
already uses for its conflicts, so the client can merge without another
read.
Without baseRevision the save stays unconditional, so the browser
editor keeps working unchanged. Claims do not change the revision.
/api/config/client announces userManagement.repeaterTokens, which lets
a client tell this server apart from one without device-token repeater
scopes or baseRevision.
My account, Devices labelled every device token "CoreDrive RX". A token issued to another app with repeater scopes would have shown up under that name too. /api/account/sessions now includes a device token's scopes. The page keeps the CoreDrive RX label for rx tokens (and for rows without scopes), and shows any other token under the device name the app sent, with a short line saying what it can do (claim repeaters, edit repeater details).
…e conditional
Review follow-up for mobile repeater writes.
GET /api/repeaters/{pubkey}/info answered 401 to any bearer that was no
live device token. An auth proxy may add its own Authorization header, so
a visitor behind one lost the Repeater info section. The public read now
treats such a bearer as anonymous; writes still answer 401. A client
learns its token is gone from /api/auth/me or its next write.
The node page editor now sends the revision its form was loaded from as
baseRevision, so it can no longer overwrite an app's save made in the
meantime. On 409 it shows the stored values from the answer with a note
to make the change again; a draft kept across a re-render keeps the
revision it was opened at.
/api/auth/me returns a device token's scopes, so an app can check what it
holds after an update or a restore.
The cors.go comment now names the repeater routes among the bearer CORS
routes and what a "*" origin entry means for them.
The node page now keeps what the user typed when a save answers 409, shows the stored record under the form and bases the next save on its revision, so Save replaces it on purpose and Cancel keeps it. A 409 for an account that can no longer edit says so instead of switching to the view silently. Docs: an admin's repeater:edit device token edits every repeater for its sliding 90-day lifetime. The inline CORS comment covers mobile apps.
b51e264 to
5541d3d
Compare
|
Thanks for the review. Rebased onto master after #2430 merged. In the Admin device tokens: under Mobile apps, The minor points:
Tests: |
GET /api/account/repeaters (My repeaters, from Kpa-clawbot#2430) now also takes a device token with repeater:claim or repeater:edit; an rx-only token still answers 403. An app cannot build this list from the public catalog: claimers there are display names, and a claimed repeater that left the node list is missing from it. Reading one repeater at a time would take a request per repeater and miss those as well.
|
One more small addition, bd4b8f1: This gives the app the account's claims in one request. It can't build that list any other way: claimers in the public catalog are only display names, and reading repeaters one at a time takes a request per repeater and misses claims on repeaters that have left the node list. It's one case in |
|
Re-review at
The new token read on Minor, none blocking:
The release that carries this gets the line that users.db goes to v10 and an older binary refuses it afterwards, so back up first. |
Reverts 80ea705. The repeater-info draft fix and the bearer scope comments are now a separate PR, so this one only carries push.
Master brings Kpa-clawbot#2407 (observers.idx, reviewed version), Kpa-clawbot#2429 (repeater details revision), Kpa-clawbot#2451-Kpa-clawbot#2454 (direct receptions, Heard by). - observers.idx files take master's reviewed Kpa-clawbot#2407 copy; the branch had the pre-review one. AssertReady uses master's primary-key probe (SQLite only; Postgres has pgschema.AssertReady). - Master's update-first observer UPDATE uses lastSeenClampSQL and CAST(? AS BIGINT), so it also runs on Postgres. - users.db: master's repeater_info revision stays v10; the branch's rate_limits moves to v11, on SQLite and Postgres. Master's revision tests run on both backends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… scope comments (#2450) Two follow-ups from the #2429 review, split out of #2447 so they don't wait on it. ## Change - **Restored drafts keep the "saved meanwhile" block** (`public/repeater-info.js`). When a save answers 409, the editor shows the record someone else saved under the form. If the panel re-rendered before the user saved again, the restored draft kept the typed values and the stored revision but lost that block. The draft now stores the conflicting record and restores it with the form. - **Comments only** (`cmd/server/auth_session.go`, `cmd/server/cors.go`): the `bearerCORSPath` and CORS comments now describe the current bearer routes, including the My repeaters list from #2430. No behavior change. ## Tests - `tests/unit/test-repeater-info.js`: a re-mount after a 409 keeps the typed values, the stored revision and the saved-meanwhile block. 32 pass; the new case fails without the fix. - `npx eslint public/repeater-info.js`: clean. - `go build ./...` and `go vet` in `cmd/server`. Co-authored-by: Adam <196335+anieto@users.noreply.github.com>
…d idx, closes DB on failed open (#2445) Closes #2443. Follow-up to #2407. ## What changes > **Master merged in** again (`da87b2cd`, master at `007ba78a`, with #2442 and #2450): no conflicts. CI is green on the head `7d2ab1a7`. One run on `da87b2cd` failed master's new repeater-info E2E; this PR changes nothing that suite uses, and it passed on the next run. > > Earlier merge (`3e5288b0`, master at `6ab97f52`, with #2429 and #2451–#2454): no conflicts, the three commits below are unchanged. Re-tested on the merge: `go vet` and `go test` across all modules (Alpine, cgo, 8 MiB musl stacks), all green. Three commits, one per fix, plus `ba69a7f2` for the first review (section 4), `0a17c0b8` from an internal review (section 5), and `7d2ab1a7` for the approving review's three points (section 6). ### 1. `4121a791` Close the DB when `OpenStore` fails `OpenStoreWithInterval` returned without closing the `*sql.DB` when ping, schema setup, `dbschema.Apply` or statement preparation failed. One deferred close now covers every error after `sql.Open` (`cmd/ingestor/db.go:159`). This is why `TestOpenStoreRefusesUnconvertibleObservers` could not remove its temp dir on Windows. - `TestOpenStoreClosesDBOnFailure` counts the descriptors open on the DB file after a failed open, using `/proc/self/fd` on Linux, and on every OS checks that the file can be removed afterwards (an open handle blocks that on Windows). On the old code: `failed OpenStore left 3 descriptor(s) open on the database`. ### 2. `6cac470c` Require `observers.idx` to be the INTEGER primary key `observersColumnsInfo` (`internal/dbschema/observers_idx.go:123`) treated `idx` as done when it had `pk == 1`. That accepts keys that are not the rowid alias `observer_idx` relies on. It now requires all of: - `idx` is the only primary-key column; - it is declared exactly `INTEGER`; - `pragma_index_list('observers')` has no `pk`-origin index. The last check catches `idx INTEGER PRIMARY KEY DESC` (a documented SQLite quirk: type INTEGER, `pk=1`, but not an alias) and `WITHOUT ROWID` tables. `AssertReady` and the rebuild share this check. So the server reports `observers.idx (not the rowid alias)` for these shapes, and the rebuild no longer takes them as already migrated: it refuses with its own message (section 4), leaving the table untouched. - The new `AssertReady` cases (`TEXT` key, composite key, `DESC`, `WITHOUT ROWID`) returned `err = <nil>` on the old code. - `TestObserversIdxRefusesNonRowidIdxKey` and `TestObserversIdxRefusesWithoutRowid` also returned `err = <nil>` on the old code: the table was treated as migrated. ### 3. `8bca5304` Keep local indexes, triggers and views across the rebuild Before this change, indexes and triggers an operator added to `observers` were dropped with the old table, without a message. Any view on `observers` made the rename fail with a raw `error in view …: no such table: main.observers`. The rebuild now recreates them rather than refusing. - **Capture.** Inside the rebuild transaction, before anything is dropped, `captureLocalObservers` (`observers_idx.go:460`) reads from `sqlite_master`, in creation order: - indexes and triggers on `observers`; - views, and triggers on other tables, whose SQL names `observers`, `packets_v` or an already captured view. It repeats until nothing new is found. CoreScope's own `packets_v` and two `observers` indexes are excluded. - **Drop.** The captured views, and the triggers on other tables, are dropped before the rename. - **Recreate.** Everything is recreated from its original SQL after our own objects. The ingestor logs one line naming what it recreated. - **Failure.** If an object cannot be recreated, the whole transaction rolls back. The error names the object and how to continue (`observers_idx.go:435`): drop it and recreate it after the upgrade, or run the previous version. These rules come from experiments on SQLite 3.53.4: - the rename fails for a view on `observers`, a view on a dropped view, and a trigger on another table that mentions `observers`; - `DROP TABLE` takes the table's own triggers with it, and `DROP VIEW` takes its `INSTEAD OF` triggers. **Concurrent starts.** A new test runs `Apply` 8 times at once over two `*sql.DB` handles on one WAL file. It found a second race: a deferred transaction that reads first fails with `database is locked` once another process has rebuilt, and `busy_timeout` doesn't retry that upgrade. The rebuild transaction now takes the write lock before its first read. Since `ba69a7f2` it does this with `BEGIN IMMEDIATE` (section 4); this commit first used a no-op `DELETE FROM observers WHERE 0`. - `BEGIN IMMEDIATE` waits on `busy_timeout`, so concurrent rebuilds take turns and the later one sees the table done. - It only runs when a rebuild is needed: a migrated table returns before the transaction. ### 4. `ba69a7f2` Review follow-ups - **Lock without compiling triggers.** `DELETE FROM observers WHERE 0` compiled every DELETE trigger on `observers`, so one referencing a dropped table failed the upgrade (`lock observers: no such table: main.gone`) where the base commit did not. The rebuild now runs as a raw `BEGIN IMMEDIATE` … `COMMIT` on the pinned connection, which compiles nothing against `observers`. Every exit that does not commit issues `ROLLBACK` on that same connection, so the connection never returns to the pool inside a transaction. If `ROLLBACK` itself fails, the connection is discarded. `TestObserversRebuildCarriesBrokenDeleteTrigger` failed with that error before this change. - **A refusal for `idx` that is not the rowid alias.** A plain `idx` column can be dropped, and the message suggests `ALTER TABLE observers DROP COLUMN idx`. An `idx` in the primary key cannot (`cannot drop PRIMARY KEY column`), so that message says to recreate the table without it. The tests execute every statement a message suggests, and check that `DROP COLUMN` really fails for the primary-key shapes. - **Quoted names in suggestions.** The suggested `DROP VIEW "my view"` is quoted the same way as the `DROP` the rebuild runs itself, through a shared `quoteIdent`. - **Wording.** `AssertReady` says `observers.idx (not the rowid alias)`. The unknown-column refusal no longer suggests renaming, which would not help. - **Tests.** There is now a direct table test for `mentionsIdentifier` (`observers_archive`, `client_observers`, `"Observers"`, `main.observers`, `[observers]`). Tests: | Test | Old code | |------|----------| | `TestObserversRebuildKeepsLocalObjects` (index, trigger, views, a view on a view with an `INSTEAD OF` trigger, a view on `packets_v`, a trigger on `observations` that writes `observers`) | the index and trigger vanished; the view failed the rename | | `TestObserversRebuildLocalTriggersFire` | `error in trigger local_observations_count` | | `TestObserversRebuildLocalViewsQueryable` | rename error | | `TestObserversRebuildRefusesUnrecreatableLocalObject` (schema, rows, local objects and `packets_v` unchanged after the refusal) | new behaviour | | `TestObserversRebuildLocalObjectsIdempotent` | new behaviour | | `TestObserversRebuildConcurrentApply` | `drop packets_v: database is locked` in 4 of 5 runs; 30 of 30 pass with the fix under `-race` | ### 5. `0a17c0b8` Internal review follow-ups - **Quoted view names.** A trigger on a view whose name contains `"` is now captured by its `tbl_name`, and mentions also match the name as written inside double quotes. Before, an INSTEAD OF trigger on such a view was lost without a word, and a view built on it failed the rename. - **`DROP COLUMN` suggestions.** Each refusal that suggests `DROP COLUMN` also says to drop any index, view or trigger that uses the column first; SQLite rejects the drop otherwise. - **Foreign-key refusal.** It now says how to continue: declare the child column `REFERENCES observers(id)` (extended in section 6). - **Rollback helper.** The rollback-or-discard step is a named helper, `rollbackOrDiscard`, with its own tests. A table dropped between the two reads now ends the rebuild instead of reporting a missing `id` column. - **CHANGELOG.** The concurrency sentence now covers only what the code serialises: concurrent rebuilds of the `observers` table. ### 6. `7d2ab1a7` Approving review's points - **Foreign key refusal.** It names both causes and both ways out: a child column declared `REFERENCES observers` with no column, or rows that already reference a missing observer (list them with `PRAGMA foreign_key_check(...)`). - **Lock test.** A deterministic test pins `BEGIN IMMEDIATE` and the "migrated meanwhile" exit. It fails 30 of 30 with plain `BEGIN`. - **Backtick-quoted names.** A captured view name written in backticks is matched too. Tests: `TestObserversIdxForeignKeyRefusalCoversOrphanRows` (runs the suggested `PRAGMA foreign_key_check`, deletes the orphan, then the rebuild succeeds) and `TestObserversRebuildWaitsForWriterThenSeesMigrated` (fails 30 of 30 with plain `BEGIN`). ## Not covered - A view or trigger in the database that is already broken, unrelated to `observers`, still makes the rename fail with the raw SQLite error, as it does today. - A local `SELECT *` view on `observers` gains the `idx` column after the rebuild. - Two ingestors starting on one legacy file at once can still fail in `EnsurePacketsView` (`view packets_v already exists`). That code predates this PR, which does not touch it. - A WITHOUT ROWID legacy table with no `idx` column fails with a raw `no such column: rowid` and is rolled back. That fails safe, and the shape is exotic. ## Performance None of this is on a hot path. The capture runs once, inside the one-time rebuild, over the schema's few dozen `sqlite_master` rows. The extra primary-key probe in `observersColumnsInfo` is one `pragma_index_list` read at startup, and only when the other checks pass. ## Testing Run in a cgo `golang:1.27-alpine` container: - `gofmt -l` is empty and `go vet` is clean in `internal/dbschema` and `cmd/ingestor`. - `internal/dbschema`: `go test -count=3 -race ./...` passes. - `cmd/ingestor`, `cmd/server` and `cmd/migrate`: `go test -count=1 ./...` passes. - On `ba69a7f2`: `go vet` and `go test -count=1 ./...` pass in `internal/dbschema`, `cmd/ingestor`, `cmd/server` and `cmd/migrate`. `TestObserversRebuildConcurrentApply` passes in 15 of 15 runs. - On `7d2ab1a7`: `gofmt -l` empty, `go vet` clean, `go test -count=1 ./...` ok in `internal/dbschema` and `cmd/ingestor`; the new tests pass in 20 repeated runs and `TestObserversRebuildWaitsForWriterThenSeesMigrated` with `-count=50`. - Windows (independent, on `7d2ab1a7`): `TestOpenStoreRefusesUnconvertibleObservers` and `TestOpenStoreClosesDBOnFailure` passed 5 consecutive runs, and the full native ingestor suite passed; the same cleanup test fails on master `007ba78a`. This is backend only, so there are no frontend or browser changes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Release notes and changelog entry for v3.19.0. - `docs/release-notes/v3.19.0.md`: the full notes, also the GitHub release body (`deploy.yml` reads it as `body_path`). - `CHANGELOG.md`: `[Unreleased]` becomes `[3.19.0] - 2026-11-24` with six highlights. The SMTP and map-provider lines that were under `[Unreleased]` are covered by the highlights and the notes. 32 commits since v3.18.0, up to `70dc4453` (#2445): 14 fix, 8 feat, 5 test, 2 ci, 2 docs, 1 refactor. Types come from the PR titles; #2442, #2429 and #2430 have no prefix and count as feat, #2450 as fix. Read before upgrading, in the notes: the one-time `observers` rebuild (#2407, #2445), the content-hash migration now running in the ingestor (#2409), `users.db` schema v10 with accounts on (#2429), and SNR per node from direct receptions only (#2451-#2454). Left out on purpose: #2446 (map picker follow-ups to #2434, not yet approved), for v3.19.1. Not done: no staging run of master before tagging. After merge: tag `v3.19.0` on this PR's squash commit once its `:edge` image carries that revision.
) Optional push delivery for watched-node alerts, through a push relay. CoreScope keeps deciding when an alert fires, with the same rules as email. When an admin connects the analyzer to a push relay, alerts can also go to a signed-in user's phone through the relay's mobile app. Nothing is sent to a relay until an admin enables it. A relay is needed because Apple and Google only accept pushes signed with the receiving app's own credentials, which a self-hosted analyzer does not have. The relay holds one app's credentials and forwards alerts from any analyzer enrolled with it. NodeScope runs one at `https://push.nodescope.app` ([source](https://github.com/anieto/nodescope-push-relay), GPL-3.0), and it is the built-in preset; any relay that implements the contract in `docs/specs/2026-11-22-push-relay-contract.md` can be used instead. This has been running on analyzer.meshtexas.org since November 19, delivering to iOS and Android. Updated after the review below: neutral naming, an admin-chosen relay, the contract spec in this repo, and a destination interface in the notifier. The #2429 follow-ups moved to #2450. ## How it works ``` CoreScope notifier ── alert ──> push relay ──> APNs / FCM ──> phone ^ ^ └── link (installation ID, ──┘── the phone registers its push token here; one-time proof from the app) CoreScope never sees it ``` **What CoreScope sends:** per alert, the alert type (`node.not_heard`, `node.heard_again`, `node.battery_low`, `node.battery_recovered`), the node's public key and name, when it happened, and the opaque subscription ID of the device link. Linking a device sends the relay the installation ID and a one-time proof the app got from the relay. No email addresses, account names, locations or messages. ## Change **Destination interface** (`cmd/server/notify_destination.go`) - The notifier hands each evaluation's changes to a list of destinations: `beginTick` before evaluating, `stage` to add rows to a `users.NotifyOutbox` written in the same transaction as the notification states, and `deliver` after the save. It no longer knows which destinations exist. - Email and the push relay are the two destinations. Email mails within the tick as before. The push relay queues jobs in `stage` and drains its queue on its own loop. - A further destination (Pushover, a webhook) adds its outbox fields and one entry in `notifyDestinations()`. - Transitions are now reported whatever the user's email setting, so each destination can decide. The email toggle and unsubscribe link still control only email. **Enrollment** (admin only) - **Admin → Notifications → Mobile push**: pick a relay (the NodeScope preset or a custom HTTPS origin), then Enable, Pause/Resume delivery, Disconnect relay. Nothing is picked by default. - Enable proves control of `userManagement.publicBaseUrl` to the relay: CoreScope generates a one-off Ed25519 key, the relay fetches `GET /api/push-relay/enrollment-proof?challenge=` from the public origin and checks the signature, then issues an analyzer ID. The proof route answers only while an enrollment is in progress. - The sender credential and enrollment state live in private files next to `users.db` (`.push-relay.json`, `.push-relay-lifecycle.json`, `.push-relay-pending-<hash>.json`, mode 0600). Never in `config.json` or the web customizer. - `userManagement.notifications.pushRelay`: - absent: the admin picks the relay on the card; - `{origin}`: self-service enrollment, locked to that relay; - `{origin, analyzerId, platforms}` plus `CORESCOPE_PUSH_RELAY_CREDENTIAL`: manual enrollment with a code from the relay operator. **Device links** (account routes, session + CSRF) - `PUT /api/account/notifications/devices/{installationID}` with `{proof}` links or renews the caller's device. Links last 30 days unless the app renews them. At most 16 devices per account per analyzer. Replaying the same proof after an ambiguous failure is safe. - `DELETE …/devices/{installationID}` removes the caller's link and queues revocation at the relay. - `GET /api/account/notifications` adds `pushRelay: {relayOrigin, analyzerId, contractVersion, platforms}` while enrolled, so an app can tell whether this analyzer supports its relay. **Delivery** - A durable outbox in `users.db` (`notification_push_jobs`) is drained every 5 seconds. Retries back off from 5 s to 5 min and follow `Retry-After` on 429 and 5xx. Other 4xx drop the job. Jobs expire an hour after the event. - Triggers keep the outbox consistent: removing a device link deletes its pending deliveries and queues a revoke; unwatching a node or turning an event type off deletes its pending jobs. - Node names go through the same sanitizing as mail subjects. Unnamed nodes get generic wording from the relay. - Pause drops queued deliveries and skips new ones; Disconnect revokes the analyzer at the relay and removes its local links. - On start, device links for other analyzers are removed when an enrollment exists. With no enrollment at all, nothing is removed and push stays off, so a configuration mistake can't unlink every device. **Schema** - `users.db` v11 adds `notification_push_bindings`, `notification_push_intents` and `notification_push_jobs`, with their indexes and triggers. New, empty tables, so the migration is cheap at any size. An older binary refuses a v11 database, as with v10, so back up first. **Also** - Account export includes `notifications.pushDevices` (`analyzerId`, `installationId`, `expiresAt`). Binding IDs, proof hashes and relay subscription IDs stay out. - Docs: the contract spec, the Mobile push section of `docs/user-guide/accounts.md`, `openapi.go`, and the export line in `docs/api-spec.md`. ## Follow-ups (not in this PR) - A `notifications` device-token scope for the device routes, like the repeater scopes in #2429. They use the browser session with CSRF today. - Pushover as a third destination. ## Tests - `internal/users/notify_push_test.go`: staging, activation and replay of links, the device limit, cross-account links, triggers on unlink, unwatch and event changes, pruning, and due-job ordering. - `cmd/server/notify_destination_test.go`: every destination gets the same changes in order (begin, stage, write, deliver), staged rows land with the states, the tick log; email-off users are not logged as skipped mail. - `cmd/server/notify_push_test.go`, `notify_push_handlers_test.go`: push events from notifier transitions, retry and drop rules, link and unlink handlers, config modes, startup pruning with and without an enrollment. - `cmd/server/notify_relay_client_test.go`: request shapes, error mapping, invalid responses, no redirects, and HTTPS-only origins. - `cmd/server/notify_relay_enrollment_admin_test.go`, `notify_relay_enrollment_store_test.go`, `notify_push_lifecycle_test.go`: the proof endpoint, enrollment with the preset, a custom relay and a locked origin, origin validation, pending credentials per relay, pause, resume, disconnect and restart. - `cmd/server/account_export_test.go`: the `pushDevices` section, and no binding IDs, proof hashes or subscription IDs in the export. - `tests/unit/test-admin-dashboard-ui.js`: the Mobile push card, including the relay picker, a custom origin and a locked origin. Run locally: - `make test`: all 16 modules OK; the notifier and push tests also with `-race`. - `sh test-all.sh`: all suites pass, run in `node:24-bookworm`. - `npx eslint public/*.js`: 0 errors, the same 87 warnings as master. - The admin card checked in a browser in light and dark themes and at phone width. Not run: the full Playwright shard matrix from CI. PREFLIGHT-MIGRATION-SCALE: <30s N=0 (v11 creates new, empty tables in users.db)
… waits on state (#2446) Closes #2444. Follow-ups from the review of #2434. ## What changes > **Master merged in** for v3.19.0 (`986bc45e`, master at `7beed94a`). It conflicted in `CHANGELOG.md` (this PR's line is now its own `[Unreleased]` / Fixed entry), in `test-all.sh`, and in `public/home.js` / `public/analytics.js`, against #2462's generation counters. Both sides are kept, and in the health card's `catch` the stale check runs before `removeMiniMap()`. Re-tested: `test-all.sh` (#2444 tile sync 23/23, #2461 17/17) and lint, 0 errors. CI is green. > > Earlier merge (`16300744`, master at `007ba78a`, with #2442 and #2450): no conflicts. Re-tested: `test-all.sh` and lint. > > Earlier merge (`c4da7137`, master at `6ab97f52`, with #2429 and #2451–#2454): no conflicts, the three commits below are unchanged. Re-tested on the merge: `test-all.sh` green (map tile pin 31/31); E2E against a local server: map providers 28/28, providers harness 16/16, map teardown races 19/19, vector zoom 3/3, map modal 10/10. Three commits, one per point in the issue, plus `1a8dcbda` for the review (section 4) and `7ef2d744` and `0cc89290` from an internal review (section 5). ### 1. `68dc7e27` No Auto tile burst on a load with a saved pick On a map with a picker that loads with a valid saved pick, `MC_attachAutoTiles` used to add the theme's Auto group to the map first. The control then swapped in the pinned layer straight away, so the Auto tiles were started only to be cancelled. Now, when the map has a picker and a valid saved pick at attach time (`public/map-tile-providers.js:1639`), the Auto group stays off the map. Its layer is built only when the group first joins the map, which happens in two cases: - the user picks **Auto**; - config arriving later turns the pinned group off, so the pin reads as Auto. Maps without a picker, and loads without a pin, are unchanged. Measured on a pinned reload (light theme, pin `osmfr-hot`, CI fixture server, Chromium), counting tile images started: | Page | Before: Auto / pinned | After: Auto / pinned | |------|-----------------------|----------------------| | `#/map` | 15 / 15 | 0 / 15 | | `#/live` | 18 / 24 | 0 / 24 | Chromium had already sent 0 network requests to the Auto host before this change: an image aborted in the same task never goes out. So the waste was DOM and JS work, not network. Other browsers were not measured. Remaining case: when config arrives after the map is created and the pinned group is opt-in, the pin is not valid yet at load, so Auto still shows first. Tests: - Unit (`tests/unit/test-map-layer-builder.js`): - a pinned picker-map load starts no Auto tile; on the old code it failed with `Auto tiles started: …cartocdn…light_all…`; - picking Auto afterwards shows the theme's map; - config turning the pinned group off and back on starts the Auto tile exactly once. - E2E `7d` (`tests/e2e/test-map-providers-e2e.js:453`) counts both `<img>` src assignments and network requests to each host. On the old code: `{"autoStarted":15,"pinStarted":15,"autoRequested":0,"pinRequested":15}`. ### 2. `23acaa15` A pick made in another tab reaches open maps The cross-tab `storage` handler only covered the two theme keys. It now also handles `mc-tile-pinned` and a cleared storage (`key === null`) (`public/map-tile-providers.js:1750`). - **Validation.** The new value goes through `getPinnedId` as usual. Empty or removed means Auto. An unregistered id reads as no pin, so a map without a picker drops to the theme's map, the same as after a reload. - **Maps without a picker** re-sync and follow the pin when it fits the theme, without a reload. - **Maps with a picker** keep their layer and radio, and their Auto still ignores the pin. An explicit pick in that tab stands until the next load. - **No write-back.** The handler never writes, so tabs can't echo picks between each other. - **Unsaved picks.** A newer value from another tab replaces this tab's in-memory copy of a pick it failed to save (quota full). The existing rule still holds: a failed write never brings back an older stored pin. - **No mid-click deferral.** A `storage` event runs as its own task, so it can't arrive during a layer-control click handler. This re-sync also never adds or removes a layer the picker lists. Tests: - Unit (`tests/unit/test-map-tile-pin.js`): a pick dispatches one event; clearing it, an empty value, an unregistered id and a cleared storage each behave as above; other keys are ignored; nothing is written back; a newer value supersedes an unsaved pick. - E2E `7e` (`:518`, `:523`, `:531`) uses three tabs in one browser context, with real `storage` events: - tab A picks and tab B's node map switches without a reload; - Auto in tab A returns tab B to the theme's map; - tab C, on the map page, keeps its layer and radio, and no tab writes the pick back. Since `1a8dcbda`, C first waits for its own `mc-tile-pinned` storage event. On the old code the pick checks time out. - Race stress scenario `h` (`tests/e2e/test-map-race-stress-e2e.js`, local only like the rest of that suite) has two tabs make rapid alternating picks. They must converge, with no page errors and bounded writes. It failed 4 of 6 iterations on the old code. One line each in `docs/user-guide/map.md`, `docs/deployment.md` and the CHANGELOG now describes the cross-tab behaviour. Since `1a8dcbda` that includes the Home and Analytics maps (section 4). ### 3. `6fda048f` `4b` waits on state, not a fixed 300 ms Both `waitForTimeout(300)` calls in check `4b` (`:263`) are replaced with `waitForFunction` on the write count and the checkbox state. After the wait the check confirms the count has not gone past the expected value. It still fails with the `0506fc1d` deferral disabled (`eox-labels box not ticked after the first click`). No `waitForTimeout` is left in either providers E2E file. ### 4. `1a8dcbda` Review follow-ups - **Home and Analytics follow the pick.** The Home mini-map and the Analytics route map used to resolve their tiles once, when built, so a pick in another tab (or a theme flip) did not reach them, although the docs said it did. Both now go through the shared `_applyTilesToNodeMap` helper (`public/nodes.js`), the same one the node, reach and RX coverage maps use. The provider's own `maxZoom` (OpenTopoMap 17, USGS 16) and dark filter carry over. - **Teardown.** Each page drops its map through one function that unregisters it from the tile-sync registry before removing it: `removeMiniMap` (`public/home.js:275`) and `removeSubpathMap` (`public/analytics.js:27`). That includes paths that used to replace the map's container without removing the map: `showChooser` and `renderHome` on Home, `renderTab` on Analytics. - **Other storage areas.** The `storage` handler ignores events from another storage area (`_otherStorageArea`, `public/map-tile-providers.js:1745`). A `sessionStorage.clear()` in a same-origin iframe (`key === null`) no longer drops an unsaved pick. An event with no `storageArea`, or a `localStorage` that throws when accessed, is treated as `localStorage`. Tests: - `tests/unit/test-issue-2444-secondary-map-tile-sync.js` (new, 18 cases) covers each map's build, a pick, a cross-tab storage event, a theme flip, destroy, replace, re-render and the fallback with no helper. On the old code: 4 passed, 12 failed. - `test-map-tile-pin.js` adds cases for a foreign storage area, an absent one and a throwing `localStorage`. On the old code the foreign-area case fails with "the unsaved pick was dropped". - E2E `7e` (`:551`): the Home and Analytics maps follow a pick in tab A, and its Auto. On the old code it times out. ### 5. `7ef2d744`, `0cc89290` Internal review follow-ups - **Lazy Auto tests.** These tests now pin the lazy Auto path: - on a pinned picker load, the Auto group stays empty, also after a theme flip and a cross-tab pin; - a vector theme default is not built, so there is no MapLibre download, until Auto is picked. Each test was checked by deleting the line it guards. The unreachable `lazy && !lc` fallback is removed: the control is null only without Leaflet. - **Home mini-map timer.** The resize timer now captures its own map, so a card replaced within 100 ms no longer throws on a null map. - **Overlapping and failed loads.** Tests cover overlapping Home loads and a failed load: the earlier map is removed and unregistered. - **Cleared storage.** A cleared `localStorage` in another tab now re-syncs the ticked overlays too. - **Unsaved overlay tick.** An overlay tick whose save failed now gives way to a newer value from another tab, or to storage cleared there, as the pin already did (`0cc89290`). A slower, older Home or Analytics load drawing over a newer one was fixed on `master` by #2462 (for #2461), which is now merged in here. ## Performance Commit 1 removes work: no Auto tile layer and its tile images on a pinned load of a picker map (table above). The `storage` handler runs only when another tab changes the pin: one validated read and one event dispatch, which each map handles with its existing `sync()`. ## Testing | Check | Result | |-------|--------| | `sh test-all.sh` | all standalone frontend suites pass (on `0cc89290`: layer builder 35/0, tile pin 34/0, secondary map tile sync 23/0, overlays + vector 34/0; on `1a8dcbda`: tile pin 34/0, layer builder 32/0, secondary map tile sync 18/0, secondary map tile builder 10/0) | | `npx eslint public/*.js` | 0 errors, 87 warnings, unchanged from `master` | | `test-map-providers-e2e.js` | 28 passed, 0 failed; on `1a8dcbda` 29 passed, 0 failed | | `test-map-providers-harness-e2e.js` | 16 passed, 0 failed | | Race stress, seeds 20261118, 4242, 777 and 31337 | all scenarios pass (the cross-tab one was called `g` in those runs) | | Race stress, cross-tab scenario only, seed 909, 20 iterations | passes | The E2E and stress suites ran against the CI fixture, freshened and migrated, on a local server. The engineer ran two of the seeds and I re-ran everything with the other two. **Scenario name and the other open PRs.** The cross-tab stress scenario is `h`, not `g`. #2436 (the ducting overlay) adds its own scenario `g`. With both named `g`, git merged the two branches silently into a file with two `scenarioG` declarations, and only one of them would have run. `h` also runs outside the scenario table, so the line #2436 changes there stays untouched. I checked on `master` with #2436, this PR and #2445 merged together: - all three merge with no conflicts, in each of three orders; - `test-all.sh`, lint and the Go suites pass; - the providers E2E passes 28/28, the harness 16/16 and the ducting E2E 28/28; - the race stress suite passes scenarios a–h on seeds 20261118 and 5150. No screenshots: nothing visual changes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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-tokenare limited torx(CoreDrive RX: settings and companion linking), andGET /api/repeaters/{pubkey}/infotreats 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}/infois 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-tokentakes an optionalscopeslist. Omitted (ornull) 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.repeater:claim:POSTandDELETE /api/repeaters/{pubkey}/claim. These already only add or remove the caller's own claim. Several claimers per repeater, idempotentPOST, unchanged.repeater:edit:PUT /api/repeaters/{pubkey}/info, still subject toCanEditRepeater./api/auth/meand/api/auth/logout, so a repeater-only token can check and end its own login.GET /api/repeaters/{pubkey}/infowith a token holding either repeater scope returnscanEditandclaimedByMe. 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 List my claimed repeaters on My account #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. Anrx-only token still answers 403.bearerScopesFor(method, path)). The repeater paths are added to the bearer CORS paths.repeater, 120/h per user and per IP), audit actions and admin claim removal as the browser. Token writes addvia: deviceto therepeater.claim,repeater.editandrepeater.unclaimrows, and theuser.loginrow records the granted scopes. The admin route keeps refusing bearer tokens.2. Conditional edits with a revision (
9f9bf47b)users.dbschema v10 addsrepeater_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) andPUTresponses includerevision.PUTaccepts an optionalbaseRevision. 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 = ?.409with the stored details (canEdit/claimedByMeincluded) and writes nothing. That's the same shapePUT /api/account/settingsuses for its conflicts.baseRevisionthe save is unconditional and bumps the revision, sopublic/repeater-info.jsworks unchanged./api/config/clientaddsuserManagement.repeaterTokens: true, so a client can tell this server from one without the scopes orbaseRevision(older servers answer the device-token request with the SPA page, as noted forcompanionLinking).Discovery and conflict recovery, for a client:
userManagement.repeaterTokensin/api/config/client. Without it, keep the claim and edit actions hidden.scopes: ["repeater:claim", "repeater:edit"](or just what the client offers). The response echoes the grantedscopes.GET /api/repeaters/{pubkey}/infowith the token. Show Claim/Unclaim fromclaimedByMeand Edit fromcanEdit, and keeprevision.PUT …/infoandbaseRevisionset to that revision. On 200, keep the newrevisionfrom the response. On 409, the body is the current record: show or merge it, then retry with itsrevision. On 401, log in again. On 403, the account can no longer edit (for example someone claimed it), so refresh fromcanEdit.3. Account page device list (
d28374aa)My account, Devices labelled every device token "CoreDrive RX".
/api/account/sessionsnow includes a device token'sscopes. The page keeps the CoreDrive RX label forrxtokens (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.mdand the Repeater info section ofdocs/user-guide/accounts.md.Questions
repeater:claimandrepeater: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. Onerepeaterscope would be simpler if you'd rather not split it.userManagementis on, and the user opts in when the app asks for them at login. Would you want an explicit opt-in such asuserManagement.mobileRepeaterWrites?revisionplusbaseRevisionin the body, with 409 returning the current record, fit? I matched account settings rather thanETag/If-Match, to keep one pattern in the API. The browser editor doesn't sendbaseRevisionyet. 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:via: deviceaudit rows, cookie writes still needing CSRF, and session scopes.rx-only token.cmd/server/repeater_revision_test.go:internal/users/repeater_revision_test.go:-race);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 innode:24-bookworm. On macOS,test-manage-workflow.jsfails 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.jstests/e2e/test-user-management-e2e.jsagainst local e2etest servers with the CI config: 44/44.Not run: the full Playwright shard matrix from CI.