Skip to content

Allow mobile clients to manage repeater claims and details - #2429

Merged
efiten merged 6 commits into
Kpa-clawbot:masterfrom
anieto:mobile-repeater-writes
Nov 21, 2026
Merged

efiten merged 6 commits into
Kpa-clawbot:masterfrom
anieto:mobile-repeater-writes

Conversation

@anieto

@anieto anieto commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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 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. 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.

@anieto
anieto force-pushed the mobile-repeater-writes branch from d28374a to 34c9758 Compare November 19, 2026 19:18
@anieto
anieto marked this pull request as ready for review November 19, 2026 19:36
@zfouts

zfouts commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Thanks for the write-up, the discovery and conflict-recovery steps made this easy to follow. I read 34c9758a and ran it merged onto master together with #2430 and the map PRs (#2434, #2436): go test for cmd/server and internal/users, go vet, test-user-management-ui.js (101/0) and test-lint-network-calls.js (47/0) all pass. I didn't run the Playwright E2E, try it in a browser, or test against a real mobile client.

What I checked and found fine: a device token sent as the session cookie is still refused (currentUser), a web token as a bearer is still refused, the admin route refuses every token, a token with no scope for a route gets 403, scopes are validated before the password, and the conditional write is one statement per case with RowsAffected deciding, so the race can't land both saves.

One thing I'd change before merge:

  1. A proxy's Authorization header turns the public read into a 401 (cmd/server/auth_session.go:214, used at repeater_handlers.go:134). bearerToken already notes that an auth proxy may add its own Authorization: Bearer … header. Until now that only mattered on routes that need a login anyway. optionalUser puts it on a public route: a visitor with no CoreScope session but a proxy bearer header gets 401 from GET /api/repeaters/{pubkey}/info, and public/repeater-info.js:197 then leaves the Repeater info section hidden. I checked with a throwaway test on the repeater fixture: the same GET answers 200 with no header and 401 {"error":"invalid or expired token"} with Authorization: Bearer eyJ….proxy.jwt. Suggestions, either works:

    • simplest: on this route treat a bearer that doesn't resolve to a device session as anonymous (200, public view). The client can still learn its login is gone from GET /api/auth/me, which every device token may now call, or from the 401 on its next write;
    • or keep the 401, but only when the header value has the shape of a token from users.NewToken (length and alphabet), and fall back to anonymous for anything else.

    Either way a test with a foreign bearer value on the public GET would pin it.

Smaller suggestions:

  1. Browser saves can still overwrite an app's edit. The app is protected against the browser (it gets a 409), but public/repeater-info.js saves without baseRevision, so a browser tab opened before an app edit silently replaces it (repeater_handlers.go:329). You list this as a follow-up in question 4. I'd do it in this PR or right after: have the editor send the revision it loaded, and on 409 show the stored values with a "someone else changed this" message. Otherwise the lost update is only fixed in one direction.

  2. Let a token read its own scopes. A client gets scopes once, at login. Adding scopes to the /api/auth/me answer for a device token would let an app check what it holds after an update or a restore, instead of storing it next to the token. Related, low priority: /api/auth/me returns csrfToken to a device token too (meFrom), which it can't use; it could be left out for kind: device.

  3. Stale comment (cmd/server/cors.go:124). It still says the bearer CORS exception is "the bearer routes of companion linking"; it now also covers the repeater routes. Worth one sentence there that with "*" in corsAllowedOrigins any origin may send token-bearing writes to them (no cookies, so it needs the token).

  4. Heads-up for whichever of Allow mobile clients to manage repeater claims and details #2429 / List my claimed repeaters on My account #2430 merges second: the only real conflict is tests/unit/test-user-management-ui.js (both add tests after the device-token test; keep both). openapi.go, repeater_handlers.go, repeaters.go and account.js merge on their own, and both suites pass together.

On your questions, for what it's worth (maintainers decide):

  1. Two scopes: keep them. A claim puts the user's name on a repeater publicly and an edit doesn't, so a client asking for less is a real difference, and the cost is one more constant.
  2. Editing unclaimed repeaters: keep web parity. Different rules for app and browser are harder to explain than the risk they remove, and via: device in the audit log already tells the two apart.
  3. Operator switch: I wouldn't add one. A token can do nothing the account can't already do in the browser, the user sees and revokes it under Devices, and the rate limit is shared. If a switch is wanted later, the repeaterTokens flag is already the place a client looks.
  4. revision + baseRevision with 409 returning the record: fits, and matching account settings beats introducing If-Match for one route. See point 2 for the browser side.

@anieto

anieto commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful pass on the auth paths, and for the answers on the open questions. Changes in b51e264:

  1. Took the simpler option: on GET /api/repeaters/{pubkey}/info, a bearer that doesn't resolve to an active device token is treated as anonymous and gets the public view. Writes still answer 401. The test now covers a foreign JWT-shaped value on the GET (200, no caller fields) and on a PUT (401). openapi.go is updated.
  2. public/repeater-info.js now sends the revision its form was loaded from as baseRevision. On 409 it keeps the form open with the stored values from the response and a "someone else changed these details" message, and the retry uses the new revision. If the 409's record says the user can no longer edit, it shows the view. A draft kept across a re-render keeps the revision it was opened at. accounts.md is updated.
  3. /api/auth/me now includes scopes for a device token. csrfToken was already empty for device tokens (handleMe), so it was left as is.
  4. The cors.go comment now lists the repeater routes and notes that with "*" any origin may send token-bearing writes to them, which still need the token.

Noted on the test-file conflict for whichever merges second.

Locally: go test for cmd/server and internal/users, go vet, gofmt, test-repeater-info.js (31/0), test-user-management-ui.js (98/0) and test-lint-network-calls.js (47/0).

efiten pushed a commit that referenced this pull request Nov 20, 2026
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>
@efiten

efiten commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Review at b51e264a. Thanks for this, and for the open questions in the description.

What holds up:

  • Scope checks are in one method-aware place (bearerScopesFor, cmd/server/auth_session.go:54); repeaterRoute cannot match the admin claim route, and withAdmin still refuses every bearer. I found no way for a token to gain more than its scopes: it cannot mint tokens, /api/account/sessions stays closed to bearers, a web token as bearer is 401 and a device token as cookie is refused.
  • Backward compatible: omitted scopes means ["rx"] and omitted baseRevision means an unconditional save, so a cached older repeater-info.js and CoreDrive RX keep working.
  • The conditional write is one statement per case with RowsAffected deciding (internal/users/repeaters.go:225-252), covered by the 8-way race test and the HTTP concurrency test. Permission is checked before the 409 (repeater_handlers.go:276-284 before :314).
  • Migration v10 runs in the per-migration transaction, and TestMigrateV9DatabaseToV10 starts from a real v9 database.
  • The points from zfouts's review are in: a stray bearer on the public GET reads as anonymous (tested with nonsense, a web token and a JWT-shaped value), browser saves send baseRevision and handle 409, /api/auth/me returns the scopes for device sessions, and the CORS block comment is updated.

Locally: go vet, gofmt, go test in internal/users and cmd/server (173 s) pass, test-repeater-info.js 31/31, test-user-management-ui.js 98/98, test-lint-network-calls.js 47/47, and the branch merges cleanly onto master. Not run: -race, Playwright, a browser, a real mobile client.

Answers to the open questions: two scopes, web parity for unclaimed repeaters, no operator switch and revision/baseRevision with 409 are fine as implemented.

One decision, and what I'd like in the PR:

  1. An admin's device token carries the admin edit override (repeater_handlers.go:276, CanEditRepeater). A repeater:edit token of an admin account can edit every claimed repeater for 90 days sliding, without a browser. It is deliberate and tested (TestRepeaterTokenEditFollowsCanEdit), and the admin routes still refuse tokens, so I'm fine keeping it. Please add one sentence about it under Mobile apps in docs/user-guide/accounts.md, so an admin knows what such a token can do.

Minor, none blocking:

  • A 409 in the browser re-renders the form from the stored record (public/repeater-info.js:165-176), so whatever the user typed, up to 500 characters of notes, is gone. Keeping the typed values and showing the stored ones next to them would be kinder.
  • A 409 where the user can no longer edit switches to the view without a message (:173-175); one say() line would explain it.
  • The inline comment at cmd/server/cors.go:179-181 still describes only companion linking.
  • The release notes for the version that carries this need the line that users.db goes to v10 and an older binary refuses it afterwards (schema.go:216), so back up first.

When the draft status is lifted this is ready from my side. #2430 is merged now, so the conflict zfouts mentioned in tests/unit/test-user-management-ui.js will show up here: keep both blocks.

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.
@anieto
anieto force-pushed the mobile-repeater-writes branch from b51e264 to 5541d3d Compare November 20, 2026 15:49
@anieto

anieto commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Rebased onto master after #2430 merged. In the tests/unit/test-user-management-ui.js conflict I kept both blocks. New commit: 5541d3d.

Admin device tokens: under Mobile apps, docs/user-guide/accounts.md now says that 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). It also says to log the token out under Devices when the device is lost or changes hands.

The minor points:

  • 409 keeps the typed values: public/repeater-info.js keeps what the user typed and shows the stored record under the form ("Saved meanwhile by …"). The next save is based on the stored revision, so Save replaces it on purpose and Cancel keeps it. The draft carries the new revision across a re-render. The "Edits from two places" paragraph in the docs is updated to match.
  • 409 without edit rights: the view now comes with a say() line explaining that someone else saved and this account can no longer edit the repeater.
  • Inline CORS comment: cmd/server/cors.go:179 now names both device-token clients, CoreDrive RX and mobile apps.
  • Release notes: noted. The line about users.db moving to v10, and older binaries refusing it afterwards so back up first, belongs in the notes for the release that ships this.

Tests: test-repeater-info.js 32/32 (two 409 tests updated, one new one for a re-mount after a 409), test-user-management-ui.js 101/101, test-lint-network-calls.js 47/47. gofmt, go vet and go test pass in internal/users and cmd/server.

The #2430 follow-ups are in #2440.

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.
@anieto

anieto commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

One more small addition, bd4b8f1: GET /api/account/repeaters, the My repeaters list from #2430, now also takes a device token with repeater:claim or repeater:edit. An rx-only token still gets 403.

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 bearerScopesFor, for GET and HEAD only, plus the OpenAPI text, a sentence under Mobile apps in accounts.md, and tests. The new TestMyRepeatersAccess covers no login (401), an rx token (403), and claim and edit tokens each listing only their own account's claims. go vet, gofmt and go test in cmd/server pass.

@efiten

efiten commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

Re-review at bd4b8f10. All points from my review are in:

  • the admin token sentence in docs/user-guide/accounts.md:361-364;
  • a 409 keeps the typed values (public/repeater-info.js:186-194), and the no-edit 409 explains itself with say();
  • the cors.go comment is updated;
  • the List my claimed repeaters on My account #2430 tests survived the conflict resolution.

The new token read on /api/account/repeaters (bd4b8f10) is GET/HEAD only and needs repeater:claim or repeater:edit (cmd/server/auth_session.go:61-65). Checked refusals: anonymous 401, rx-only token 403, web token as bearer 401, garbage bearer 401, device token as cookie 401, disabled account 401. The response matches the session one. Merging, thanks.

Minor, none blocking:

  • The comments at cmd/server/auth_session.go:87-89 and cmd/server/cors.go:124-126 still describe the old scope.
  • A restored draft loses the "saved meanwhile" block (public/repeater-info.js:240).

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.

@efiten
efiten merged commit c834997 into Kpa-clawbot:master Nov 21, 2026
17 checks passed
anieto added a commit to anieto/CoreScope that referenced this pull request Nov 22, 2026
Reverts 80ea705. The repeater-info draft fix and the bearer scope
comments are now a separate PR, so this one only carries push.
zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 23, 2026
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>
efiten pushed a commit that referenced this pull request Nov 23, 2026
… 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>
efiten pushed a commit that referenced this pull request Nov 24, 2026
…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>
efiten added a commit that referenced this pull request Nov 24, 2026
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.
efiten pushed a commit that referenced this pull request Nov 24, 2026
)

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)
efiten pushed a commit that referenced this pull request Nov 27, 2026
… 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants