Skip to content

Optional mobile push for watched-node alerts through a push relay - #2447

Merged
efiten merged 14 commits into
Kpa-clawbot:masterfrom
anieto:nodescope-push
Nov 24, 2026
Merged

efiten merged 14 commits into
Kpa-clawbot:masterfrom
anieto:nodescope-push

Conversation

@anieto

@anieto anieto commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

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, 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)

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)

Carries the NodeScope push work (live on MeshTexas as 99a8d90) onto
current master. Its users.db migration is now v11, after master's v10
repeater_info revision, and the later node_name column is folded into
the v11 notification_push_jobs table.
… scope comments

Follow-ups from the Kpa-clawbot#2429 review. A draft restored after a re-render now
shows the record saved meanwhile under the form again, as it did before
the re-render. The bearerCORSPath and CORS comments now describe the
current bearer routes, including the My repeaters list.
Describe what push does, what CoreScope sends the relay, and link the
relay's public source and API. Drop the pilot wording.
The export lists each active device link's analyzer ID, installation ID
and expiry under notifications.pushDevices. Binding IDs, proof hashes and
relay subscription IDs stay out.
@zfouts

zfouts commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for this, Adam. I read the whole diff and the nodescope-push-relay source (read, not run), and it is a carefully built piece of work. This is a fellow contributor's view, not a maintainer's, so take it as input for whoever makes the call.

In the interest of transparency: I'm a user of analyzer.meshtexas.org myself, so I'd personally benefit from this landing and I'm not a neutral party. I've tried to review it the way I would any upstream PR, with the wider set of CoreScope deployments in mind, which is where the suggestions below come from. Please weigh them with that in mind.

(Edited to fold in a closer read of the relay and line-level detail, so everything is in one place.)

What I think is really good

On the CoreScope side:

  • The transactional outbox. ApplyNotifyChanges writes the notifier states and the push jobs in one transaction, so an alert can't be recorded without its delivery being queued, or the other way round. The triggers that clean up on unlink, unwatch and event changes keep it honest.
  • Retry handling. Following Retry-After, dropping on other 4xx, expiring an hour after the event, replay-safe linking.
  • The privacy shape. CoreScope never sees a push token, the relay never sees an email or account name, and the credential stays out of config.json and the customizer.
  • Domain-proof enrollment. Proving control of publicBaseUrl with a one-off Ed25519 key is a nice way to enroll without a shared secret.
  • The evaluator change. "Changes are reported regardless of email preference so each destination can decide" is exactly the seam the notifications spec asked for. Its non-goals say: "Other channels (Discord, Telegram, push, outbound webhooks). The design keeps the event detection separate from delivery so a second channel can be added later." This PR is that second channel, so the direction is clearly wanted.

And the relay is most of the way to generic already. Its README opens with "This standalone Go service implements the v1 CoreScope relay contract", which is exactly how I'd frame it:

  • App identity is already configuration. The APNs topic, Firebase project and signing keys all come from the environment, so another app could run the same relay for its own users without forking it.
  • The CoreScope-facing contract is small and clean. Enrollment, analyzer status and revoke, subscriptions, and idempotent deliveries carrying only a kind, a pubkey, an optional name and timestamps. Device registration stays between the app and its relay, which is the right boundary.
  • It's built with care. Replay-safe deliveries with clear conflict and gone responses, per-owner quotas, encrypted state, nothing sensitive in the logs. The README alone is a good operator guide.

A relay is also the right architecture: mobile push needs APNs/FCM credentials that belong to the app publisher, so a self-hosted analyzer can't deliver directly.

The one real concern

The mechanism is generic, but the CoreScope-side surface is NodeScope's: the config key, env vars, routes, private files, audit actions, account-response field and admin card all carry the name, and self-service enrollment only accepts the two nodescope.app relays, with production as the default. The wire contract is defined in the relay's repo rather than here.

So I don't think this needs a rethink. It mostly needs CoreScope to present the relay as a push relay rather than NodeScope's. Then NodeScope's relay is the reference implementation of a CoreScope push contract, and the next mobile app that wants push gets it for free. #2429 handled the same situation well: the code says "mobile apps" and device-token scopes, and the docs name the apps that use them.

Requested before merge

  1. Neutral names on the CoreScope side. Suggestions below; anything neutral works. The notification_push_* tables and the /api/account/notifications/devices/{id} routes are already neutral, and NodeScope stays in the docs as the known app and relay.
    • user_mgmt_config.go:89: nodeScopePush → pushRelay. The NotifyRelayConfig type name is already neutral, which helps.
    • notify_push.go:28-30: CORESCOPE_NODESCOPE_PUSH_CREDENTIAL → CORESCOPE_PUSH_RELAY_CREDENTIAL, and the same in the error text.
    • auth_routes.go:58-62: /api/admin/notifications/nodescope → /api/admin/notifications/push-relay, and /api/nodescope/enrollment-proof → /api/push-relay/enrollment-proof. The relay fetches the proof path, so it belongs in the spec (request 3) too.
    • notify_handlers.go:49: the nodeScopePush account field → pushRelay, same shape. It's how an app detects push support, so worth naming in the spec.
    • notify_relay_enrollment_store.go:28 and notify_push_lifecycle.go:61: .nodescope-*.json → .push-relay*.json. If meshtexas already has these files on disk, reading the old name as a fallback (or a one-time rename at startup) keeps it working.
    • notify_relay_enrollment_admin.go:235 and :305: notify.nodescope.* audit actions → notify.push.*.
    • public/admin-notifications.js:42: "NodeScope Push" → "Mobile push" or "Push relay", showing the connected relay origin in the card. Line 21's "official NodeScope HTTPS relay" message would become something like "Set pushRelay.origin to enable push".
  2. The relay origin is the admin's choice (notify_relay_enrollment_admin.go:23-37). One configured origin used by both self-service and manual enrollment, with no compiled-in default, no allowlist, and no CORESCOPE_NODESCOPE_SELF_ENROLL_RELAY_ORIGIN override. The domain proof already protects the relay side, and the admin owns the analyzer, so I don't think the allowlist buys much. The docs can give https://push.nodescope.app as the known public relay.
  3. The contract lives in this repo. A docs/specs/ file covering the analyzer, subscription and delivery endpoints, payloads, status codes, retry semantics, the proof route, the kind values and what contract_version means. Most of that text already exists in the relay README, so this is largely moving it, and the README can then link here. After that, a contract change is a reviewed change in CoreScope.
  4. Split out the Allow mobile clients to manage repeater claims and details #2429 leftovers. The CORS comment (cors.go:125) and the repeater-info 409 draft fix are good changes; they'd merge quickly as their own small PR.

Suggestions (your call)

  • A small destination seam in the notifier. saveNotificationChanges (notify_service.go:240) and the pushEpoch read in tick reach into n.a.nodeScopeDelivery directly. A narrow interface (email first, push relay second) would keep the notifier unaware of which destinations exist, and give a later outbound webhook somewhere to plug in. Fine as a follow-up.
  • Log noise for users with notifications off (notify_eval.go:310). Before, those users produced no changes. Now their changes reach deliver, and notifySkipReason logs "N change(s) not mailed: notifications off" on every transition, even on analyzers with no relay. Maybe skip the log for that reason.
  • Docs (accounts.md:395): one sentence saying the email toggle and unsubscribe link don't silence the phone (unlinking does), and that observer, external and new-foreign-node events stay email-only, since only offline and battery map to a kind in notifyPushKind. Worth noting in the spec that a new kind means a contract_version bump, since the relay writes the alert text.
  • In the relay (outside this PR): the notification title ("NodeScope" in relayAlert) and the default com.btdev.nodescope topic could become settings like the rest. That's the only app-specific code I found there.

Your three questions

  1. Allowlist: with request 2 it goes away: one admin-configured origin for both enrollment paths.
  2. Session vs device token: a notifications device-token scope fits the Allow mobile clients to manage repeater claims and details #2429 model better, since the app already holds a token for the repeater routes. A follow-up seems fine to me.
  3. Config switch: yes, and with request 2 the presence of the pushRelay block is the natural switch, matching how everything else under userManagement is off until configured.

None of this takes away from the quality of the work, and having it in production on meshtexas since the 19th is a good sign. You know the app side far better than I do, so if any of it doesn't fit how NodeScope needs to work, I'd much rather hear that than have you bend the design around my comment. Really nice work, and thanks for building it in a way that's this easy to open up.

Reverts 80ea705. The repeater-info draft fix and the bearer scope
comments are now a separate PR, so this one only carries push.
CoreScope's side of push now names a push relay rather than NodeScope,
which becomes one relay among others (review on Kpa-clawbot#2447):

- config and account response field: nodeScopePush -> pushRelay
- env: CORESCOPE_PUSH_RELAY_CREDENTIAL
- routes: /api/admin/notifications/push-relay and
  /api/push-relay/enrollment-proof (the relay asks this path first and
  falls back to the old one, so either side can update first)
- private files: <users.db>.push-relay.json, .push-relay-lifecycle.json
- audit actions: notify.push.*
- admin card: "Mobile push"; messages and Go identifiers to match

The self-enrollment allowlist and its pending files are unchanged here;
the relay presets replace them next.

Startup no longer removes device links when there is no enrollment at
all. A configuration slip or a moved enrollment file would otherwise
unlink every device; push stays off instead, and Disconnect relay removes
the links. Links for other analyzers are still pruned when an enrollment
exists.
Self-service enrollment no longer has a compiled-in default or an
allowlist of NodeScope relays. The admin picks the relay on the Mobile
push card:

- a preset: NodeScope, https://push.nodescope.app, iOS and Android. The
  server sends the preset list to the card, so another app's relay can
  be added there later.
- Custom relay: any HTTPS origin that implements the push relay
  contract, with iOS and Android.

Nothing is picked by default, and Enable stays off until the admin
chooses. POST /api/admin/notifications/push-relay takes {relayOrigin}.

A pushRelay block with only an origin (and optional platforms) locks
self-service enrollment to that relay; with an analyzerId it is still a
manual enrollment. CORESCOPE_NODESCOPE_SELF_ENROLL_RELAY_ORIGIN is gone.

The enrollment file records the relay's platforms (files without them
mean iOS and Android), and the pending retry credential is named after
its relay origin. The enroll audit row records the relay origin.
The notifier no longer reaches into the push relay state. Each
evaluation's changes go to a list of destinations (notifyDestination):

- beginTick, before evaluating
- stage, which adds rows to a users.NotifyOutbox written in the same
  transaction as the states, and returns a func run after that write
- deliver, after the states are saved, with a count for the tick log

Email and the push relay are the two destinations. Email mails within
the tick as before. The push relay queues jobs in stage, holding its
delivery lock across the write as before, and drains the queue on its
own loop (notifyWorker), which startup now starts for any destination
that has one. A further destination, such as Pushover, adds its fields
to NotifyOutbox and an entry in notifyDestinations.

ApplyNotifyChanges takes the outbox instead of a push analyzer ID and
events, and the states of every tick are now written in one transaction
whether or not a relay is enrolled. The tick log line is unchanged
(mails=N).

Users with email off are evaluated for push, so their transitions are
no longer logged as "not mailed: notifications off" (review on Kpa-clawbot#2447).
The contract between CoreScope and a push relay now lives here, so a
change to it is a reviewed change in this repository (review on Kpa-clawbot#2447).
It covers why a relay is needed, self-service and manual enrollment
with the proof route, status and revocation, the pushRelay field apps
use to detect push, device linking, the delivery request, the kind
values and when they need a contract_version bump, retry rules, and
what the reference relay keeps.
The accounts guide now describes push as CoreScope sending to a push
relay, with NodeScope's relay as the built-in choice and any relay that
implements the contract spec as an alternative. It explains why a relay
is needed and that each relay reaches only its own app's users, links
the contract spec, and says that the email toggle and unsubscribe link
don't silence push and which alerts stay email-only (review on Kpa-clawbot#2447).
Card names, the manual-enrollment example and the export description
follow the neutral naming.
@anieto anieto changed the title Optional NodeScope push delivery for watched-node alerts Optional mobile push for watched-node alerts through a push relay Nov 22, 2026
@anieto

anieto commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review, Zach, and for reading the relay too. I agreed with nearly all of it and have pushed the changes as separate commits, so the diff since your review is easy to follow. The description above is updated.

Requested before merge

  1. Neutral names (829354c). Done as you listed: pushRelay in the config and the account response, CORESCOPE_PUSH_RELAY_CREDENTIAL, /api/admin/notifications/push-relay, /api/push-relay/enrollment-proof, .push-relay*.json, notify.push.*, and a "Mobile push" card that shows the relay. The Go identifiers and messages follow. I left out a fallback for the old file names: only our own deployment has them, so I'll rename them there instead of carrying that code upstream. The relay now asks the new proof path first and falls back to the old one on 404, so either side can update first. That's already deployed on push.nodescope.app.

  2. The relay origin is the admin's choice (674f005). There is no compiled-in default, no allowlist, and no CORESCOPE_NODESCOPE_SELF_ENROLL_RELAY_ORIGIN. The card has a relay picker: NodeScope as a named preset, or a custom HTTPS origin. Nothing is picked by default. The presets are a small list on the server, so another app's relay could be added later. One difference from your suggestion: enrolling from the card is what turns push on, not the presence of a pushRelay block. With a preset an admin can click, requiring a config edit first seemed to defeat the purpose. The block is still there for operators who want config control:

    • {origin} locks self-service enrollment to that relay;
    • {origin, analyzerId, platforms} with the env credential is manual enrollment, as before.
  3. The contract lives in this repo (d2b020e): docs/specs/2026-11-22-push-relay-contract.md. It covers enrollment with the proof route, status and revocation, the pushRelay account field, device linking, the delivery request and its kind values, retries, and what contract_version means. A new kind is a version bump, since the relay writes the text. The relay README will point here once this merges.

  4. Allow mobile clients to manage repeater claims and details #2429 leftovers split out: Repeater info: restored drafts keep the saved-meanwhile block; bearer scope comments #2450. The commit here is reverted.

Suggestions

  • Destination seam (f802a43). I did this here rather than as a follow-up, since it touched the same lines as the renames. The notifier now hands each evaluation's changes to a list of notifyDestinations:

    • beginTick, before evaluating;
    • stage, which adds rows to a users.NotifyOutbox written in the same transaction as the states;
    • deliver, after the save.

    Email and the push relay are the two implementations, and tick no longer reads the relay's state. The tick log line is unchanged. We plan to add Pushover next as a third destination, in its own PR.

  • Log noise: fixed. Email-off users are no longer logged as "not mailed: notifications off".

  • Docs (ce83fc7): the section is now "Mobile push". It says the email toggle and unsubscribe don't silence the phone (turning push off in the app unlinks the device), and that observer, external and new-node alerts stay email-only.

  • Relay title and topic: RELAY_NOTIFICATION_TITLE is now a setting alongside RELAY_APNS_TOPIC. Both default to NodeScope's values for the public instance, and the README says what a relay for another app sets.

One more change, prompted by the renames: startup used to remove every device link when it found no enrollment. A missing file or a config slip would have unlinked everyone silently. Now, with no enrollment, CoreScope keeps the links and push stays off. Disconnect relay is the way to remove them.

The three questions

  1. Allowlist: gone, per your request 2.
  2. Device-token scope: agreed that a notifications scope fits the Allow mobile clients to manage repeater claims and details #2429 model better. I've listed it as a follow-up in the description.
  3. Config switch: answered under 2 above. Enrollment is the switch, and the block is optional.

Tests: make test (all 16 modules), the notifier and push tests with -race, test-all.sh, and eslint (0 errors) all pass. I also checked the new card in a browser.

@zfouts

zfouts commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Thanks, Adam. I've gone through the six commits since my review (829354c..ce83fc7). Everything I asked for is in, and it reads well: neutral names throughout, an admin-chosen relay with no allowlist, the contract in docs/specs/, the destination seam, and #2450 split out. The NodeScope preset is a good answer to my "config block as the switch" idea; you're right that a clickable preset beats requiring a config edit first. Keeping links when there's no enrollment is also a better default than what I'd have thought to ask for.

What I checked:

  • Destination seam (notify_destination.go, notify_service.go). Behavior-preserving as far as I can see. relayDestination.stage takes the delivery read lock and hands back RUnlock as its done, so the pause/disconnect-vs-write guarantee the old inline code had still holds across ApplyNotifyChanges. A small bonus: with no relay, drops and state writes are now one transaction instead of two.
  • Startup pruning (restoreAndPrunePushState). With no enrollment it now returns before pruneUnconfiguredPushState, and Disconnect still prunes with "". Good.
  • The card (admin-notifications.js). Preset and custom origins go through escapeHtml, and Enable stays disabled until a relay is picked.
  • Leftover names: git grep -i nodescope outside tests now only finds the preset entry (plus the unrelated nodeScopes region code).
  • Locally, at ce83fc7: internal/users with -race, go vet, and the notify, push, relay, destination and export tests in cmd/server with -race, plus test-admin-dashboard-ui.js (76 pass). All pass.

Requested before merge: bind the enrollment proof to the relay

This comes from the change I asked for, so it's on me as much as anyone. The enrollment proof signs the relay's challenge as-is (handlePushRelayEnrollmentProof, ed25519.Sign(*key, challenge)). Nothing in the signed message says which relay asked. While Enable is running, the proof route signs for anyone, and the public key went to the relay the admin picked.

With only the NodeScope relays allowed, that didn't matter. With custom origins, a malicious (or compromised) custom relay R could do this:

  1. The admin picks R. CoreScope sends R {origin, public_key, sender_credential}.
  2. R holds that request open (the client waits up to 10 s) and calls push.nodescope.app/v1/analyzers/self-enroll with the same origin and public_key but its own sender_credential.
  3. NodeScope's relay fetches the proof from the analyzer, which signs it, because an enrollment is in flight.
  4. NodeScope's relay now has this analyzer's origin enrolled under R's credential. When the admin later tries the NodeScope preset, they get 409 analyzer_already_enrolled, and the credential that could revoke it belongs to R.

It needs an admin to have chosen a bad relay, so it isn't an emergency. But custom origins are new in this PR, and once v1 is published and other relays implement it, changing the proof format means a version bump. So I'd ask for this before merge rather than as a follow-up. The usual fix is domain separation: sign a message that includes the requesting relay's origin, for example "corescope-push-relay-proof-v1\n" + relayOrigin + "\n" + challenge. Each relay then verifies against its own origin, so a signature made for R doesn't verify at NodeScope. It's a small change on both sides plus a line in the spec's Enrollment step 3. Since /api/push-relay/enrollment-proof is new anyway, the old /api/nodescope/... fallback could keep the raw-challenge format for your deployment's transition. Or the proof route could take an extra query parameter that selects the new format.

Small notes (not blocking)

  • canonicalRelayOrigin keeps an explicit port, so https://push.nodescope.app:443 entered as a custom origin won't match the preset (no name, default platforms). It's harmless, but stripping :443 would make the preset match.
  • With no enrollment, queued notification_push_jobs rows stay until the next enrollment or Disconnect, since nothing drains or expires them while no relay is configured. That's bounded by what was queued before, so it's fine to leave. I'm mentioning it only in case it surprises someone reading the table later.

Thanks again. This turned around quickly and the commit split made it easy to follow.

The proof signed the relay's challenge as-is, so a relay an admin chose
could replay the analyzer's public key at another relay during Enable and
get the analyzer enrolled there under its own credential. The analyzer now
signs "corescope-push-relay-proof-v1" LF relay origin LF challenge, with
the origin it sent the enrollment to; each relay verifies against its own.

canonicalRelayOrigin also drops an explicit :443, so a preset entered with
its default port matches the preset. Docs note that queued push jobs stay
while no relay is enrolled.
@anieto

anieto commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, Zach. Good catch on the proof. You're right that it only became a problem once custom origins existed.

Fixed in 5216caf. While an Enable request is in flight, CoreScope keeps the origin of the relay it sent the enrollment to. The proof route now signs

"corescope-push-relay-proof-v1" LF <relay origin> LF <challenge>

The origin is https://, the lowercase host, and :port only when it isn't 443, with no trailing slash. Each relay verifies against its own origin and rejects a signature over the bare challenge. So in your scenario, NodeScope's relay can't use a proof R obtained. The spec's Enrollment step 3 now defines the format. The tests check that a proof made for one relay fails at another and fails as a bare-challenge signature, and a separate test fixes the exact bytes, since changing them would mean a version bump.

On the relay side, the reference relay now takes its own origin from RELAY_PUBLIC_ORIGIN, required when self-enrollment is on. Its fallback to the old /api/nodescope/enrollment-proof path still accepts the bare-challenge format for our deployment's transition, and nothing else does. That relay change is deployed on push.nodescope.app.

Your two small notes:

  • canonicalRelayOrigin now drops an explicit :443, so https://push.nodescope.app:443 matches the preset. There's a test for it.
  • Queued jobs with no enrollment: left as is, and the accounts doc now says they stay until the next enrollment or a disconnect.

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 efiten left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of 5216caf (range ce83fc7..5216caf).

This closes the cross-relay case from the earlier review. relayProofMessage (cmd/server/notify_relay_enrollment_admin.go:71) signs context, origin and challenge separated by LF. The challenge is fixed at 32 bytes (:191-196) and an origin cannot contain LF, so two origins never give the same bytes. The signed origin is the same value passed to newNotifyRelayClient (:291, :296), and key and origin sit in one relayProofSigner behind one atomic.Pointer, so the proof handler reads both from one snapshot (:184).

Before v1 is published

  1. canonicalRelayOrigin (:56-62) is looser than spec line 69 ("https://, the lowercase host, and :<port> only when it isn't 443"):

    • https://relay.example.org: stays https://relay.example.org:
    • https://relay.example.org:0443 keeps :0443
    • a trailing dot on the host is kept
    • an IDN host is signed as UTF-8, and the spec does not say U-label or A-label

    All of these fail closed, the relay rejects. It matters because other relay implementations will copy this form from the spec. Building the origin from u.Hostname() and u.Port() (drop an empty port, parse it as an integer), rejecting or stripping a trailing dot, and one spec sentence on IDN would settle it. Rows for the empty and 0443 port in TestResolveSelfEnrollRelay would pin it.

Minor

  1. The 422 message (:405) tells the admin to check the proof route. With the binding, a relay also answers 422 when the admin entered an alias hostname, or when the relay's RELAY_PUBLIC_ORIGIN is wrong. Worth one more clause, and the same sentence in docs/user-guide/accounts.md:343-348 (Custom relay step).
  2. docs/specs/2026-11-22-push-relay-contract.md:69: "Otherwise the route answers 404." now follows the sentence on the bare challenge, so it reads as a consequence of that. It belongs next to the in-flight sentence on line 61.
  3. The signer is cleared by the defer at :297, so the proof route keeps answering during relay.Analyzer (:306) and activateRelayEnrollment (:311). Harmless now that the proof is origin-bound. Clearing it right after SelfEnroll returns would make "only while the enrollment is in flight" literal.

What I ran (Windows, scratch worktree on 5216caf)

  • go vet . in cmd/server: clean.
  • go test ./... in cmd/server: 4 failures, all on the 0600 file-mode check, which does not hold on Windows. The same 4 fail at ce83fc7. The output also had three panic( lines I did not trace; no other test was reported as failed.
  • With the two Perm() != 0o600 checks removed in the scratch copy: TestPushRelayAdminEnrollment (5 subtests) and TestRelayProofMessageFormat pass. Signing the bare challenge, or a fixed other origin, makes every subtest fail at notify_relay_enrollment_admin_test.go:110, so the test guards the binding.
  • Not checked: whether the reference relay verifies against RELAY_PUBLIC_ORIGIN and rejects a bare challenge. That is a separate repo, and this fix depends on it.

Question: tighten item 1 in this PR before merge, or merge now and do it in a follow-up before the contract is published?

…elay's answer

The relay origin is signed into the enrollment proof, so analyzer and
relay must build it the same way. canonicalRelayOrigin now produces
exactly the contract's form: the host from u.Hostname() in lowercase
ASCII without a trailing dot (a non-ASCII host is rejected; IDNs go in
their xn-- form), and the port parsed as a number, dropped when empty or
443. The spec says so, and TestResolveSelfEnrollRelay pins the empty,
0443, 08443, trailing-dot, IDN and out-of-range cases.

Also from review:
- The 422 message and the Custom relay step in the user guide name the
  other causes: an alias hostname, or a relay configured with the wrong
  public origin.
- The spec's "answers 404" sentence sits with the in-flight sentence.
- The proof signer is cleared as soon as SelfEnroll returns, so the
  proof route is closed while the enrollment is verified and saved; the
  enrollment test checks it from the relay's GET /v1/analyzer.
@anieto

anieto commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I've tightened it in this PR so the contract is published in its final form.

Review feedback addressed (commit 3b081ddd):

  1. Canonical origin. canonicalRelayOrigin now builds the origin from u.Hostname() and u.Port():

    • the host is lowercased and loses a trailing dot;
    • a non-ASCII host is rejected, so an IDN has to be given in its A-label (xn--) form;
    • the port is parsed as an integer, dropped when it is empty or 443, and otherwise written in plain decimal (out-of-range values are rejected).

    The spec now spells out this form in a short list, including the IDN rule and the empty port. TestResolveSelfEnrollRelay has rows for host:, :0443, :08443, a trailing dot, an xn-- host, a non-ASCII host, :0 and :65536.

  2. 422 message. It now also names an alias hostname and a relay configured with the wrong public origin. The Custom relay step in docs/user-guide/accounts.md says the same.

  3. Spec wording. "answers 404" now sits with the in-flight sentence in step 3.

  4. Proof route. The signer is cleared as soon as SelfEnroll returns, so the proof route is closed while the enrollment is verified and saved. The defer stays as a backstop. The enrollment test checks for a 404 from the relay's GET /v1/analyzer handler.

The reference relay. It verifies against its configured RELAY_PUBLIC_ORIGIN, canonicalized the same way, and rejects a signature over the bare challenge on the contract's proof route. Its one exception is a compatibility fallback: when an analyzer answers 404 on /api/push-relay/enrollment-proof, it tries the pre-rename path from earlier builds of this branch, which signed the bare challenge. That only applies to deployments of this branch from before the rename. The fallback will be removed, and released CoreScope never serves that path.

The panic( lines. On Linux, go test -v in cmd/server prints three panic stacks. All three come from tests that panic on purpose and check the recovery: TestNeighborGraphCacheRebuildPanicIncrementsCounter, and TestPlannerAPIPanicRecovered (its coverage and relay jobs). None come from the push code.

Ran:

  • gofmt and go vet are clean.
  • go test ./... in cmd/server passes, including all 5 TestPushRelayAdminEnrollment subtests, TestResolveSelfEnrollRelay and TestRelayProofMessageFormat.
  • make test passes in all modules.

@efiten efiten left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 3b081dd (range 5216caf..3b081dd).

All four points are resolved as described. canonicalRelayOrigin (cmd/server/notify_relay_enrollment_admin.go:61-94) still runs newNotifyRelayClient first, so the scheme, userinfo, path, query and fragment checks are unchanged, and IPv6 literals are re-bracketed (:79-81). A stored enrollment is reloaded as stored (notify_push.go:72-77), so existing origins keep working.

Two small points on the contract text, since the point of this commit is to publish it in its final form:

  1. :70: strings.TrimSuffix(..., ".") strips one dot. https://relay.example.org.. gives https://relay.example.org., which still ends in a dot and is not idempotent (a second pass strips it). Fails closed. Rejecting a host that still ends in . after the strip, plus one test row, would match the spec.
  2. docs/specs/2026-11-22-push-relay-contract.md:69-72 says nothing about IP literals, while the code accepts them: https://[2001:DB8::1]:0443/ gives https://[2001:db8::1], https://1.2.3.4:8443 is kept. IPv6 is lowercased but not compressed, so [::1] and [0:0:0:0:0:0:0:1] sign as two different origins. One sentence would settle it, either "an IPv6 literal in brackets, lowercase, as entered" or "IP literals are not valid relay origins".

Wording only:

  1. docs/specs/2026-11-22-push-relay-contract.md:61 now ends "otherwise the route answers 404:", and the colon introduces the {"signature": ...} block, so the block reads as the 404 body. "...answers 404. While it does answer:" fixes it.
  2. The spec bullet "a host with other non-ASCII characters is rejected": "other" has no referent.

What I ran (Windows, scratch worktree on 3b081dd)

  • gofmt -l on the two changed Go files, go vet . in cmd/server: clean.
  • go test ./... in cmd/server, with the 0600 and 0o077 file-mode checks shimmed in the scratch copy because they do not hold on Windows: the push relay tests, TestResolveSelfEnrollRelay and TestRelayProofMessageFormat pass.
  • Removing the early proofKey.Store(nil): all 5 TestPushRelayAdminEnrollment subtests fail at notify_relay_enrollment_admin_test.go:125. Restoring the previous canonicalRelayOrigin: 7 of the 8 new rows fail (the xn-- row passes either way, as expected).
  • 30 inputs through canonicalRelayOrigin: IPv6 with and without port, a zone id (now a 400 instead of a 500), uppercase scheme and host, userinfo, path, query, fragment, ports :, :0443, :08443, :0, :65536, a 20-digit port, a percent-encoded host. All as expected apart from items 1 and 2.
  • Not run: the other modules, frontend, E2E, Linux. The reference relay is a separate repo; its canonicalization and the legacy-path fallback are as you describe them, not checked by me.

Question: do you want to take items 1 and 2 in this PR before merge, or should I merge now and you take them in a follow-up before the contract is published?

The canonical origin is a DNS hostname. An IP literal (IPv4 or IPv6) is
rejected rather than given a second spelling, and a host that still ends
in a dot after one is stripped is rejected, so canonicalization is
idempotent. The contract says so, and its proof-route wording no longer
reads as if the signature block were the 404 body.
@anieto

anieto commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. I've taken all four in this PR (commit 3f3108cb) so the contract goes out in its final form.

  1. Trailing dots. A host that still ends in a dot after the one strip is now rejected, so canonicalization is idempotent. There's a test row for relay.example.org...
  2. IP literals. Rejected: a relay origin must be a DNS hostname. A relay needs a publicly trusted certificate anyway, so an IP origin had no practical use, and rejecting it avoids two spellings of the same IPv6 address. The spec says so. Test rows cover 1.2.3.4:8443, [2001:DB8::1]:0443, [::1] and a zone ID.
  3. 404 wording. It now reads "...answers 404. While it does answer, the body is:".
  4. "other". The bullet now reads "any other host containing non-ASCII characters is rejected", after the sentence on IDNs.

The reference relay applies the same rule to its RELAY_PUBLIC_ORIGIN (anieto/nodescope-push-relay b242498), and the production relay is running it.

Ran:

  • gofmt and go vet are clean.
  • go test ./... in cmd/server passes on Linux, including TestResolveSelfEnrollRelay with the new rows.
  • The relay's go test ./... passes.

# Conflicts:
#	cmd/server/openapi.go
#	public/admin.css
@anieto

anieto commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@efiten The four nits are in 3f3108cb, and master is merged in. It's ready to merge whenever you are.

@efiten
efiten merged commit 3240b3f into Kpa-clawbot:master Nov 24, 2026
17 checks passed
zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 26, 2026
…ot#2447)

TestLocationLeakRoutes requires every GET route to be requested or listed
as admin-only. GET /api/admin/notifications/push-relay is behind withAdmin;
GET /api/push-relay/enrollment-proof answers only a signature over the
challenge, and 404 while no enrollment runs. Push payloads carry no
coordinates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
efiten pushed a commit that referenced this pull request Nov 28, 2026
## Summary

Adds Pushover as an optional destination for watched-node alerts, next
to email and the push relay from #2447. An admin enables it with a
Pushover application token; each user then connects their own Pushover
account from **My account → Notifications** and gets the same alerts as
email in the Pushover app. CoreScope sends to Pushover directly; no
relay is involved.

It plugs into the `notifyDestination` interface from #2447 (now merged).
The changes are four commits:

- `eca5b21c` store and server: the per-user destination behind the
notifier interface
- `c12539c2` account page section, docs, OpenAPI and export test
- `6992fe4a` Connect Pushover through a Pushover subscription
- `41bbfefd` docs: stopping Pushover from the Pushover app

## Setup (admin)

1. Create an application on pushover.net.
2. Set `CORESCOPE_PUSHOVER_TOKEN` in the server environment. The token
never goes in `config.json`.
3. Add a block to `userManagement.notifications`:

```json
"pushover": { "maxPerMonth": 7500, "subscriptionCode": "YourApp-1oiwozgx5tg38a1" }
```

`subscriptionCode` is optional. It comes from a web-based subscription
in the application's settings on pushover.net, whose base URL must be
the analyzer's `publicBaseUrl`. Without it, users paste their user key
instead of using **Connect Pushover**. CoreScope refuses to start with
the block but without a valid token.

## Behavior

- **Same alerts as email, separate switch.** Pushover uses the events
the user chose for notifications. Turning mail off, or a mail's
unsubscribe link, doesn't stop Pushover, and the reverse.
- **One message per user per check.** All of a user's changes in one
evaluation go into one message (at most 1,024 characters): the
instance's host name as the title, the same lines a mail would contain,
and a link to the node or, for several changes, to the notification
settings.
- **Queued in `users.db`.** Messages are queued in the same transaction
as the notification state change and sent by a worker every 5 seconds.
Failures are retried with backoff (honoring Pushover's `Retry-After`)
for up to an hour, then dropped. If Pushover rejects a user's key,
Pushover is turned off for that user. Changing or removing the key, or
turning Pushover off, drops that user's queued messages.
- **Instance cap.** `maxPerMonth` (default 7,500) caps the messages sent
in a rolling 30 days, test messages included, below Pushover's free tier
of 10,000 per application per month. Messages queued after the cap is
reached expire unsent.
- **Keys are checked.** Every key is validated with Pushover's
`users/validate` endpoint before it is saved. Key checks (saving a key,
or the return from Connect Pushover) and Send test share a limit of 10
per hour per user. Each user has at most one Connect Pushover in
progress; starting another replaces it.
- **Personal data.** The account export includes the key. Deleting the
account or the key removes it and the queued messages.

## Connect Pushover

With `subscriptionCode` set, the account page shows **Connect
Pushover**. It sends the browser to the pushover.net subscription page
and saves the application-specific key Pushover returns.

- The success URL carries a one-time token tied to the user who started,
valid for 15 minutes. The return also needs that user's session. A
crafted link can't attach someone else's Pushover account to yours
(which would send your alerts to them). This is the check Pushover's
subscription docs recommend.
- A return with `pushover_unsubscribed` removes the saved key if it
matches.
- The account page reports the outcome (connected, cancelled, expired,
sign in first, try later, failed, disconnected) and drops it from the
address.
- The return responses send `Cache-Control: no-store` and
`Referrer-Policy: no-referrer`.

## Changes

- `internal/users`: users.db v12 with `notification_pushover`,
`notification_pushover_jobs` and `notification_pushover_sent`. Triggers
drop queued jobs when the key changes or Pushover is turned off. Jobs
are queued from `ApplyNotifyChanges` through
`NotifyOutbox.PushoverMessages`.
- `cmd/server`:
- `pushoverDestination` implements `notifyDestination`, alongside email
and the push relay.
- New routes: `PUT`/`DELETE /api/account/notifications/pushover`, `POST
.../pushover/test`, and, with a subscription code, `POST
.../pushover/subscribe`, `GET .../pushover/subscribed/{token}` and `GET
.../pushover/subscribe-failed`.
- `GET /api/account/notifications` gains a `pushover` object while the
instance offers Pushover.
  - The OpenAPI spec and account export are updated.
- `public/notifications.js`: the Pushover part of the Notifications
section.
- `docs/user-guide/accounts.md`: setup and behavior.

No changes to the analyzer DB, the ingestor or the read/write
separation: everything lives in `users.db` through `internal/users`.

## Testing

- `make test`: all modules pass. `go test -race` passes on the server
notification, push, destination, export and OpenAPI tests.
- New Go tests run against a fake Pushover server:
  - config resolution and the subscription code format;
  - message rendering and the 1,024-character fit;
  - delivery with email off;
  - retry, drop, and a rejected key turning Pushover off;
  - the monthly cap;
  - the account routes;
- the full Connect Pushover round trip: wrong user, no session, a used
or superseded token, an unknown key, unsubscribe and cancel.
- Store tests in `internal/users` cover the key lifecycle, queueing only
for active users, expiry, and send counting.
- `test-all.sh` and eslint pass. `tests/unit/test-notifications-ui.js`
has 20 tests, including Connect Pushover and the outcome messages.
- Running on the MeshTexas analyzer since 2026-11-22. Connect Pushover
was completed with a real Pushover account:

<!-- drag the subscription confirmation screenshot here -->
zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 29, 2026
… Pushover to Postgres

Brings in 37 master commits, including the push relay (Kpa-clawbot#2447), Pushover
(Kpa-clawbot#2455), plain SMTP (Kpa-clawbot#2466), neighbour rank (Kpa-clawbot#2457), the observers rebuild
fix (Kpa-clawbot#2445) and Kpa-clawbot#2486.

Conflicts: config.example.json, docs/api-spec.md and auth_service.go keep
both sides (as n30nex's merge notes say); dbschema's observers check keeps
the Postgres branch in front of Kpa-clawbot#2445's rowid-alias check; the
release-routing test keeps musl-test; CHANGELOG keeps only unreleased
entries; notify_service.go keeps master's destinations plus the cluster
lock on evaluation, and the email claim moves to notifyChanges.claim.

users.db schema: master's v11 (push relay) and v12 (Pushover) come first,
this branch's rate_limits becomes v13, and v14 adds push_relay_state,
push_relay_pending and notification_pushover_subscriptions.

Push relay and Pushover on Postgres with several server replicas:
- Postgres migrations v11-v14 with the five SQLite triggers as plpgsql;
  instr -> strpos, typed VALUES, a qualified ON CONFLICT WHERE, integer
  booleans. The parity test also compares trigger names.
- Relay enrollment, delivery phase and the pending enrollment (with the
  Ed25519 proof seed) move from <users.db>.push-relay*.json and process
  memory into the accounts store. Writes are compare-and-set on a
  revision; replicas reload it per tick, per dispatch pass and per job.
  Old files are imported once, except an enrollment under a manual relay
  or for another public origin, which is left on disk and never prunes.
- Credentials and the seed are sealed with userManagement.encryptionKey
  (CORESCOPE_ACCOUNTS_KEY), required on Postgres; on SQLite without a key
  they are stored as before, inside users.db. Leftover plain values are
  re-sealed at startup once a key is set. users.db is set to 0600, and
  user backups blank the relay secrets.
- Queue rows are claimed with a 5-minute lease (SKIP LOCKED on Postgres);
  each queue drains under a cluster lock; advisory locks use their own
  connection pool, so lock holders cannot starve the accounts store.
  Device links and the Pushover per-user limit lock the user.
- The enrollment proof and the Pushover connect token work on any
  replica; the proof endpoint validates before any database read and is
  limited per IP; device link/unlink are limited per user.

Also fixed while integrating:
- node_reach used IS NOT 'tx', which Postgres rejects (from Kpa-clawbot#2486).
- docker/server-exec.sh did not pass five variables the server reads
  (CORESCOPE_ACCOUNTS_KEY, CORESCOPE_PUSHOVER_TOKEN,
  CORESCOPE_PUSH_RELAY_CREDENTIAL, CORESCOPE_SMTP_PASSWORD, CORESCOPE_URL);
  tests/unit/test-server-exec-env.js now checks the list.
- corescope-migrate copy-users/verify-users failed on
  notification_pushover_sent (no key); it gets a rowid on Postgres, like
  mail_events, and verify redacts credential and seed columns.

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