mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-10-12 19:37:23 +00:00
Closes #2177. ## What Node notifications can mail alerts computed outside CoreScope. With `userManagement.notifications.externalAlerts` configured, users can choose a new event, `node.external`, which is off by default and only offered when configured: ```json "notifications": { "enabled": true, "externalAlerts": { "url": "http://coverage-job/alerts.json", "maxAgeHours": 48, "label": "Coverage" } } ``` The feed: ```json { "generatedAt": "2026-10-11T01:35:12Z", "alerts": [ { "pubkey": "<64 hex>", "key": "SE", "text": "never heard to the south-east", "url": "https://example.org/coverage" } ] } ``` Mail lines: `<name>: Coverage: never heard to the south-east, <time>` when an alert appears, `<name>: Coverage resolved (SE), <time>` when it is gone from a fresh feed. ## How - `cmd/server/notify_external.go`: feed types, `parseExternalFeed` (RFC 3339 `generatedAt`, age check, per-alert validation), `fetchExternalFeed` (200 only, 1 MB cap, 10 s timeout). - `notify_eval.go`: `evalExternal`. Subjects are `<pubkey>/<key>`; a `<pubkey>/*` row is the per-node baseline, so the first fresh feed after watching stores the current alerts without a mail (like `foreign.new`), and later alerts mail at once. `External == nil` (not configured, nobody chose it, or stale) leaves every `node.external` state as it is. - `notify_service.go`: the feed is fetched only when configured and at least one user chose the event. Each new reason the feed is unusable is logged once, and so is the recovery. Mail text and link: the alert's `url`, otherwise the node page. - `notify_handlers.go`: `availableEvents` and the new `externalLabel` include the event only when configured; PUT answers 400 for `node.external` otherwise. - `internal/users/notify.go`: event constant, `OptionalNodeNotifyEvents` (canonical order: node, optional, admin), `RemoveWatch` also deletes the node's `<pubkey>/...` rows. - Account page label, OpenAPI descriptions, `config.example.json` comment, `docs/user-guide/accounts.md` section. Decisions on the three open questions in #2177: the generic name `node.external`; the resolved mail names the key instead of repeating the text, so there is **no `users.db` schema change** (a bump would also make older binaries refuse the file); one feed. ## Invariants - Read/write separation (#1283): the server only reads the feed over HTTP. State rows go to `users.db` through `internal/users`, like the other events. - A dead, garbled or old feed never mails "resolved": `TestEvaluateExternalStaleFeedChangesNothing` and `TestNotifierMailsExternalAlertsAndSkipsAStaleFeed` (HTTP 502 and a 72 h old feed in a row, then a fresh empty feed resolves). ## Performance The evaluator adds one pass over the stored states (already read every tick) plus, per user with the event on and per watched node, the node's current alerts. Bounded by `maxWatchesPerUser` (50) times the alerts per node. The feed is fetched once per tick (default 5 minutes) only when someone chose the event, capped at 1 MB. No packet-store lock is taken for it. Nothing changes for instances without `externalAlerts`. ## Tests - `cmd/server`: `go test` green locally (Windows; `TestSaveGeoFilterPreservesFileMode` skipped as it needs Unix mode bits). New: `notify_external_test.go` (feed parsing and limits, HTTP fetch 200/404/oversized, config resolution, evaluator baseline/new/resolved/returning/stale/not chosen/notifications off, notifier end to end with a fake feed, account routes). - `internal/users`: green, 2 new tests (optional event and canonical order, `RemoveWatch` deletes external subjects only for that node). - Frontend: `test-all.sh` green, 1 new test in `test-notifications-ui.js` (label from `externalLabel`, escaped). - `scripts/check-xss-sinks.sh --file public/notifications.js`: clean. ## Not done - No E2E test: the account page change is one label, covered by the unit test. - Not run against a live instance yet. The first feed in use is the coverage job of on8ar.eu (`alerts.json`, 29 alerts at the moment). Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
137 lines
4.0 KiB
Go
137 lines
4.0 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// External node alerts (#2177): a JSON feed of per-node alerts that a job
|
|
// outside CoreScope computes, e.g. coverage sectors where a repeater is
|
|
// never heard. The notifier reads it for the node.external event; the
|
|
// server never writes anything for it outside users.db.
|
|
|
|
const (
|
|
externalFeedMaxBytes = 1 << 20
|
|
externalFeedTimeout = 10 * time.Second
|
|
externalKeyMaxLen = 64
|
|
externalTextMaxLen = 200
|
|
// externalBaselineKey is the subject suffix "<pubkey>/*" that marks a
|
|
// user's node.external baseline for one watched node: the first fresh
|
|
// feed after watching stores every current alert without mailing;
|
|
// afterwards an alert without a row is new.
|
|
externalBaselineKey = "*"
|
|
)
|
|
|
|
// externalFeedJSON is the feed as published.
|
|
type externalFeedJSON struct {
|
|
GeneratedAt string `json:"generatedAt"`
|
|
Alerts []externalAlertJSON `json:"alerts"`
|
|
}
|
|
|
|
type externalAlertJSON struct {
|
|
Pubkey string `json:"pubkey"`
|
|
Key string `json:"key"`
|
|
Text string `json:"text"`
|
|
URL string `json:"url,omitempty"`
|
|
}
|
|
|
|
// externalAlert is one validated alert.
|
|
type externalAlert struct {
|
|
Text string // mail-safe
|
|
URL string // absolute http(s) or ""
|
|
}
|
|
|
|
// externalFeed is a validated, fresh feed: alerts by lowercase pubkey,
|
|
// then by key.
|
|
type externalFeed struct {
|
|
GeneratedAt time.Time
|
|
Alerts map[string]map[string]externalAlert
|
|
Skipped int // malformed entries left out
|
|
}
|
|
|
|
// parseExternalFeed validates body. It fails when the body does not
|
|
// decode, generatedAt is missing, or the feed is older than maxAge at now;
|
|
// the caller then treats the source as stale. Malformed alerts are
|
|
// skipped and counted; a duplicate (pubkey, key) keeps the first.
|
|
func parseExternalFeed(body []byte, now time.Time, maxAge time.Duration) (*externalFeed, error) {
|
|
var raw externalFeedJSON
|
|
if err := json.Unmarshal(body, &raw); err != nil {
|
|
return nil, fmt.Errorf("decode: %w", err)
|
|
}
|
|
gen, err := time.Parse(time.RFC3339, strings.TrimSpace(raw.GeneratedAt))
|
|
if err != nil {
|
|
return nil, errors.New("generatedAt missing or not RFC 3339")
|
|
}
|
|
if age := now.Sub(gen); age > maxAge {
|
|
return nil, fmt.Errorf("generated %s ago, older than %s", age.Round(time.Minute), maxAge)
|
|
}
|
|
f := &externalFeed{GeneratedAt: gen, Alerts: map[string]map[string]externalAlert{}}
|
|
for _, a := range raw.Alerts {
|
|
pk, ok := notifyPubkey(a.Pubkey)
|
|
key := mailSafeText(a.Key)
|
|
text := mailSafeText(a.Text)
|
|
if !ok || key == "" || key == externalBaselineKey || len(key) > externalKeyMaxLen || text == "" {
|
|
f.Skipped++
|
|
continue
|
|
}
|
|
if len(text) > externalTextMaxLen {
|
|
text = strings.ToValidUTF8(text[:externalTextMaxLen], "") + "..."
|
|
}
|
|
if f.Alerts[pk] == nil {
|
|
f.Alerts[pk] = map[string]externalAlert{}
|
|
}
|
|
if _, dup := f.Alerts[pk][key]; dup {
|
|
f.Skipped++
|
|
continue
|
|
}
|
|
f.Alerts[pk][key] = externalAlert{Text: text, URL: externalAlertURL(a.URL)}
|
|
}
|
|
return f, nil
|
|
}
|
|
|
|
// externalAlertURL keeps an absolute http(s) URL and drops anything else.
|
|
func externalAlertURL(raw string) string {
|
|
u, err := url.Parse(strings.TrimSpace(raw))
|
|
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
|
return ""
|
|
}
|
|
return u.String()
|
|
}
|
|
|
|
// sortedExternalKeys returns the keys of m in order.
|
|
func sortedExternalKeys(m map[string]externalAlert) []string {
|
|
keys := make([]string, 0, len(m))
|
|
for k := range m {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
return keys
|
|
}
|
|
|
|
// fetchExternalFeed GETs the feed: 200 only, at most externalFeedMaxBytes.
|
|
func fetchExternalFeed(client *http.Client, feedURL string) ([]byte, error) {
|
|
resp, err := client.Get(feedURL)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, externalFeedMaxBytes+1))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(body) > externalFeedMaxBytes {
|
|
return nil, fmt.Errorf("larger than %d bytes", externalFeedMaxBytes)
|
|
}
|
|
return body, nil
|
|
}
|