mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-11-11 13:58:07 +00:00
Observers publish to the broker with one shared MQTT login. Anyone who
has that login can publish under any observer's topic, and the ingestor
takes the observer id from the topic (`cmd/ingestor/main.go:1009`), so
the data in the analyzer DB is only as trustworthy as the shared
password. This PR gives each user a personal MQTT login, generated and
mailed by CoreScope, and lets the broker ask CoreScope whether a login
may connect and publish.
Closes #2319.
The feature is optional and off by default
(`userManagement.observerLogins.enabled`). It needs
`userManagement.enabled`. With it off, nothing changes.
## Changes in this PR
**Broker hooks.** `POST /api/mqtt-hook/emqx/authn` and `/authz`, for the
EMQX HTTP authenticator and authorizer.
- They check a shared secret header, `X-CoreScope-Hook-Secret`, in
constant time.
- A username CoreScope does not know gets `ignore`, so EMQX falls
through to its built-in database and existing users keep working.
- A personal login may only publish `meshcore/<iata>/<pubkey>/<type>`,
with a 64-hex pubkey that is unbound or bound to the same user.
- The first publish for an unbound pubkey binds that observer to the
user (first come wins), until the user owns 20 observers (admin
assignments count too).
- An admin can rebind any observer.
**Credentials.**
- Username `obs_` + 12 random `[a-z0-9]`, password 32 random
`[A-Za-z0-9]`, both from `crypto/rand`.
- The password is stored twice: SHA-256 for the auth check, and sealed
with AES-256-GCM (key from config or `CORESCOPE_OBSERVER_KEY`) so the
user can ask for the same credentials again.
- The UI and the API never show the password. It leaves the server only
in the mail.
**Mail.** One mail with four formats:
- the meshcoretomqtt TOML;
- the observer firmware CLI commands (Gessaman or Dutch-MeshCore, same
`mqttN` CLI), on slot 4: slots 1-2 (Gessaman, Let's Mesh US/EU) and 1-3
(Dutch-MeshCore, `MQTTDefaults.h:19-34`) hold default broker presets on
a fresh install, slot 4 is empty on both. `set mqtt4.server` gets the
bare host: the firmware picks the scheme from the port
(`MQTTBridge.cpp:2094-2145`), and builds before merge 32dd8ad
(2026-10-19) do not accept a scheme there (read from the source, not
tested on a device). A scheme is written only when the port would pick
the wrong one, for example TLS on 8884;
- the Home Assistant meshcore-ha broker form fields;
- the plain values.
Each block starts with a numbered title and one line on where it goes.
The account page can resend the mail, at most 3 times per 24 h.
**Account and admin UI.**
- The account page gets an "Observer MQTT login" section
(`#/account?section=observers`) with the username, the bound observers
and the resend button.
- The admin page gets an "Observer logins" tab
(`#/admin?tab=observer-logins`) that lists logins with revoke and
reissue, and every observer with its owner, "not migrated" or
"orphaned", with a reassign control.
**Notifications.** Creating a login adds `observer.offline.own` ("My
observers go offline") to the owner's notification events; mails go out
once the user has notifications switched on, and the user can untick it.
**Storage.** users.db schema v7 adds `mqtt_logins` and
`observer_bindings`. The server still writes only users.db through
`internal/users`, and the analyzer DB stays read-only.
**Docs.** `docs/observer-mqtt-logins.md` covers the EMQX setup (authn
and authz chains, the hook body templates, the closing `^obs_` deny rule
and why it is needed), how to enable it on a running EMQX through the
REST API step by step, with a check and a rollback per step, and how to
migrate observers off a shared login. `config.example.json` has the
block with placeholder values.
## Enabling it on an instance
Full steps in `docs/observer-mqtt-logins.md`. In short:
1. **CoreScope:** add `userManagement.observerLogins` to `config.json`
with `enabled: true`, a `hookSecret` (`openssl rand -hex 32`), an
`encryptionKey` (`openssl rand -base64 32`) and the `broker` host, port,
transport and TLS that observers should use. Restart. Keep the key safe:
without it, mails cannot be resent and logins must be reissued.
2. **EMQX, authorization:** add a file source with `{deny, {username,
{re, "^obs_"}}, all, ["#"]}.` and move it to the end, then add the HTTP
authorizer pointing at `/api/mqtt-hook/emqx/authz` (it lands at the
front).
3. **EMQX, authentication:** add the HTTP authenticator pointing at
`/api/mqtt-hook/emqx/authn` and move it to the front, before the
built-in database.
4. **Check:** the shared login still connects, an unknown `obs_` login
is refused, and `metrics.deny` on the authorizer stays 0 for existing
clients.
5. **Owners:** they request a login on their account page and paste the
block for their uploader. Each observer binds to them on its first
publish. An uploader that was refused before step 3 may need a restart.
6. **Later:** remove the shared login from the broker once enough
observers moved.
## Who can claim an observer
Any active account can request a login, and its first publish under an
unbound pubkey binds that observer, also when CoreScope already knew it
from the shared login (first come wins, a deliberate choice: owners
migrate without waiting for an admin). Observer pubkeys are public, and
registration cannot be closed, so with this feature on anyone with a
mail address can claim up to 20 unbound observers per account. Before,
publishing needed the shared password.
What limits it: each claim of a known observer mails the admins, an
admin can unbind or reassign it and revoke the login, and a bound
observer cannot be claimed by another login. The doc spells this out and
suggests assigning known observers to their owners before announcing the
feature. A stricter mode (admin approval of logins, or no auto-bind for
known observers) is not in this PR.
## Performance
`authorize()` runs for every publish that misses the EMQX authz cache.
It takes two short read locks, does map lookups and one topic split.
`BenchmarkAuthorizeBound` (2000 observers, 500 logins): 533.5 ns/op, 96
B/op, 2 allocs/op. The admin observers table renders once per load and
updates single rows after a change.
## Verification
- All 16 Go modules: `bash scripts/allmod.sh test ./...` green.
- Skipped `TestSaveGeoFilterPreservesFileMode` and
`TestWriteStatsAtomic_SymlinkAtDestIsReplaced`: both fail on Windows on
a clean master too.
- `sh test-all.sh` green.
- `tests/e2e/test-user-management-e2e.js` 36/36 locally. It covers:
request, mail, resend, revoke, reissue, reassign, no password in the
page or API body, and axe. The CI job for this suite gets the
`observerLogins` block with fake values in `deploy.yml`.
- Local EMQX 5.8.6 in Docker against a local CoreScope:
- a personal login connects and publishes, which binds the observer; a
second personal login is denied on that observer's topic, and subscribe
is denied;
- with CoreScope stopped, the built-in users still connect and publish,
and new personal-login connects are refused;
- the `^obs_` deny rule blocks an already-connected personal login while
CoreScope is down; without the rule, the same publish was delivered.
- Production: running on an EMQX 5.8.9 broker with about 50 clients
since 2026-10-25, set up through the REST API as in the doc. After the
hooks went in, the authorizer answered `ignore` for every existing login
(0 denies, 0 dropped messages), and 4 observers were bound to their
owners through personal logins on the same evening, with the shared
login still in use by the rest.
## Known behaviour
EMQX's HTTP client can mark the hook resource down for one health-check
interval (15 s measured) when CoreScope closes an idle keep-alive
connection just as a health check runs. During that window new
personal-login connects are refused and the uploader reconnects. I saw
it 3 times in about 25 minutes of runs with a forced 1-5 s idle timeout,
and could not trigger it on demand. EMQX 5.8.6 has no setting for it,
and 5.10.5 ships the same client code. The doc describes it and the
alarm to watch for.
## Not in this PR
- mosquitto (mosquitto-go-auth). EMQX only.
- A websocket path field: the mail does not carry one, the doc tells
operators to match the listener path.
- Disabling the shared login. That is an operator step after migration,
described in the doc.
- Tested on EMQX 5.8.6 (Docker) and 5.8.9 (production) only.
Note on cb9f4ff3: its message says the scheme problem was reported by an
operator. That report turned out to come from before the broker used the
hook, so it does not show this cause; the change rests on the firmware
source only.
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
211 lines
10 KiB
JavaScript
211 lines
10 KiB
JavaScript
/* Node notifications client (docs/specs/2026-10-07-node-notifications-design.md).
|
|
* window.CSNotify: the "Notify me" toggle on the node side pane and full
|
|
* page, and the account page's Notifications section. Inert unless
|
|
* /api/config/client advertises userManagement.notifications (roles.js sets
|
|
* window.MC_USER_MGMT). One GET /api/account/notifications per user, cached;
|
|
* every change answers the full state, which replaces the cache. Every
|
|
* dynamic value in HTML goes through escapeHtml; messages use textContent. */
|
|
(function () {
|
|
'use strict';
|
|
var cache = { userId: null, promise: null };
|
|
|
|
function enabled() { return !!(window.MC_USER_MGMT && window.MC_USER_MGMT.notifications); }
|
|
function currentUser() { return window.CSAuth ? window.CSAuth.user() : null; }
|
|
|
|
// load resolves to the caller's state (the GET body) or null.
|
|
function load() {
|
|
var u = currentUser();
|
|
if (!enabled() || !u) return Promise.resolve(null);
|
|
if (!cache.promise || cache.userId !== u.id) {
|
|
cache.userId = u.id;
|
|
cache.promise = window.CSAuth.request('GET', '/api/account/notifications').then(function (r) {
|
|
if (!r.ok) { cache.promise = null; return null; }
|
|
return r.data;
|
|
}, function () { cache.promise = null; return null; });
|
|
}
|
|
return cache.promise;
|
|
}
|
|
|
|
// store makes data (the answer of a change) the cached state.
|
|
function store(data) {
|
|
var u = currentUser();
|
|
cache.userId = u ? u.id : null;
|
|
cache.promise = Promise.resolve(data);
|
|
return data;
|
|
}
|
|
|
|
function isWatched(data, pubkey) {
|
|
var pk = String(pubkey || '').toLowerCase();
|
|
return !!(data && data.watches && data.watches.some(function (w) { return w.pubkey === pk; }));
|
|
}
|
|
|
|
// toggleState: 'hidden' (no state), 'on', 'off' or 'full' (limit reached).
|
|
function toggleState(data, pubkey) {
|
|
if (!data) return 'hidden';
|
|
if (isWatched(data, pubkey)) return 'on';
|
|
return (data.watches || []).length >= Number(data.limits && data.limits.maxWatches) ? 'full' : 'off';
|
|
}
|
|
|
|
function toggleHtml(state, data) {
|
|
if (state === 'hidden') return '';
|
|
var on = state === 'on';
|
|
var title = on ? 'You get a mail when this node goes offline, comes back or reports a low battery. Click to stop.'
|
|
: 'Get a mail when this node goes offline, comes back or reports a low battery.';
|
|
var html = '<button type="button" class="btn-primary node-notify-btn" data-notify-toggle aria-pressed="' + (on ? 'true' : 'false') + '"' +
|
|
(state === 'full' ? ' disabled' : '') + ' title="' + escapeHtml(title) + '"><svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor-sprite.svg#ph-envelope-simple"/></svg> ' +
|
|
escapeHtml(on ? 'Notifying' : 'Notify me') + '</button>';
|
|
if (state === 'full') {
|
|
html += ' <small class="node-notify-hint">' +
|
|
escapeHtml('You watch the maximum of ' + data.limits.maxWatches + ' nodes; remove one on your account page.') + '</small>';
|
|
}
|
|
return html + ' <small class="node-notify-hint" data-notify-msg role="status" aria-live="polite"></small>';
|
|
}
|
|
|
|
function say(slot, text) {
|
|
var m = slot.querySelector('[data-notify-msg]');
|
|
if (m) m.textContent = text;
|
|
}
|
|
|
|
function render(slot, pubkey, data) {
|
|
var state = toggleState(data, pubkey);
|
|
slot.innerHTML = toggleHtml(state, data);
|
|
var btn = slot.querySelector('[data-notify-toggle]');
|
|
if (!btn) return;
|
|
btn.addEventListener('click', function () {
|
|
var on = btn.getAttribute('aria-pressed') === 'true';
|
|
btn.disabled = true;
|
|
var path = '/api/account/notifications/watches/' + encodeURIComponent(String(pubkey).toLowerCase());
|
|
return window.CSAuth.request(on ? 'DELETE' : 'PUT', path).then(function (r) {
|
|
if (!r.ok) { btn.disabled = false; say(slot, window.CSAuth.errText(r)); return; }
|
|
render(slot, pubkey, store(r.data));
|
|
}, function () { btn.disabled = false; say(slot, 'Network error, try again.'); });
|
|
});
|
|
}
|
|
|
|
// mount fills slot with the toggle for pubkey; empty when the feature is
|
|
// off or nobody is logged in.
|
|
function mount(slot, pubkey) {
|
|
if (!slot) return Promise.resolve();
|
|
slot.innerHTML = '';
|
|
var ready = window.CSAuth && window.CSAuth.ready ? window.CSAuth.ready() : Promise.resolve();
|
|
return Promise.resolve(ready).then(function () {
|
|
if (!enabled() || !currentUser()) return;
|
|
return load().then(function (data) { render(slot, pubkey, data); });
|
|
});
|
|
}
|
|
|
|
var EVENT_LABELS = {
|
|
'node.offline': 'A watched node goes offline or comes back',
|
|
'node.battery': 'A watched node reports a low battery or recovers',
|
|
'foreign.new': 'A new foreign node appears (admin)',
|
|
'observer.offline': 'An observer goes offline or comes back (admin)',
|
|
'observer.offline.own': 'My observers go offline'
|
|
};
|
|
|
|
function eventLabel(e, data) {
|
|
if (e === 'node.external') return 'A watched node gets a ' + (data.externalLabel || 'external') + ' alert or it clears';
|
|
return EVENT_LABELS[e] || e;
|
|
}
|
|
|
|
function eventsHtml(data) {
|
|
var ownOn = !!(window.MC_USER_MGMT && window.MC_USER_MGMT.observerLogins);
|
|
return (data.availableEvents || []).filter(function (e) {
|
|
return e !== 'observer.offline.own' || ownOn;
|
|
}).map(function (e) {
|
|
var id = 'notifyEv-' + e.replace(/\./g, '-');
|
|
return '<label class="account-check" for="' + escapeHtml(id) + '"><input type="checkbox" id="' + escapeHtml(id) +
|
|
'" data-notify-event="' + escapeHtml(e) + '"' + ((data.events || []).indexOf(e) !== -1 ? ' checked' : '') + '> ' +
|
|
escapeHtml(eventLabel(e, data)) + '</label>';
|
|
}).join('');
|
|
}
|
|
|
|
function watchesHtml(data) {
|
|
if (!data.watches.length) return '<p class="account-hint">You watch no nodes yet. Use Notify me on a node page, or Watch my nodes below.</p>';
|
|
return '<ul class="account-watches">' + data.watches.map(function (w) {
|
|
return '<li data-pubkey="' + escapeHtml(w.pubkey) + '"><span><a href="#/nodes/' + encodeURIComponent(w.pubkey) + '">' +
|
|
escapeHtml(w.name || w.pubkey.slice(0, 12)) + '</a>' + (w.known ? '' : ' <small>(no longer in the database)</small>') + '</span>' +
|
|
'<button type="button" class="account-btn account-btn-secondary" data-unwatch="' + escapeHtml(w.pubkey) + '">Remove</button></li>';
|
|
}).join('') + '</ul>';
|
|
}
|
|
|
|
function sectionHtml(data) {
|
|
var lim = data.limits || {};
|
|
return '<form id="notifyForm" class="account-form" novalidate>' +
|
|
'<label class="account-check" for="notifyEnabled"><input type="checkbox" id="notifyEnabled"' + (data.enabled ? ' checked' : '') + '> Send me notification mails</label>' +
|
|
'<fieldset class="account-fieldset"><legend>Events</legend>' + eventsHtml(data) + '</fieldset>' +
|
|
'<p class="account-hint">' + escapeHtml('At most ' + lim.perUserPerDay + ' mails per 24 hours; sent in the last 24 hours: ' + lim.mailsLast24h + '.') + '</p>' +
|
|
'<button type="submit" class="account-btn account-btn-primary">Save</button></form>' +
|
|
'<h4>' + escapeHtml('Watched nodes (' + data.watches.length + ' of ' + lim.maxWatches + ')') + '</h4>' +
|
|
'<div id="notifyWatches">' + watchesHtml(data) + '</div>' +
|
|
'<button type="button" class="account-btn account-btn-secondary" id="notifyMyNodes">Watch my nodes</button>';
|
|
}
|
|
|
|
function sayIn(msgId, text, ok) { window.CSAuth.say(msgId, text, ok); }
|
|
function failed(msgId) { return function () { sayIn(msgId, 'Network error, try again.', false); }; }
|
|
|
|
// draw renders the section from data and binds its controls. Controls are
|
|
// found by id: they are unique on the account page. busy guards against a
|
|
// second request while one is in flight.
|
|
function draw(el, msgId, data) {
|
|
var busy = false;
|
|
function guarded(fn) {
|
|
if (busy) return Promise.resolve();
|
|
busy = true;
|
|
return fn().then(function () { busy = false; }, function () { busy = false; });
|
|
}
|
|
el.innerHTML = sectionHtml(data);
|
|
document.getElementById('notifyForm').addEventListener('submit', function (e) {
|
|
e.preventDefault();
|
|
var events = (data.availableEvents || []).filter(function (ev) {
|
|
var box = document.getElementById('notifyEv-' + ev.replace(/\./g, '-'));
|
|
return !!(box && box.checked);
|
|
});
|
|
var en = document.getElementById('notifyEnabled');
|
|
return guarded(function () {
|
|
return window.CSAuth.request('PUT', '/api/account/notifications', { enabled: !!(en && en.checked), events: events }).then(function (r) {
|
|
if (!r.ok) { sayIn(msgId, window.CSAuth.errText(r), false); return; }
|
|
draw(el, msgId, store(r.data));
|
|
sayIn(msgId, 'Saved.', true);
|
|
}, failed(msgId));
|
|
});
|
|
});
|
|
document.getElementById('notifyWatches').addEventListener('click', function (e) {
|
|
var pk = e.target && e.target.getAttribute && e.target.getAttribute('data-unwatch');
|
|
if (!pk) return;
|
|
return guarded(function () {
|
|
return window.CSAuth.request('DELETE', '/api/account/notifications/watches/' + encodeURIComponent(pk)).then(function (r) {
|
|
if (!r.ok) { sayIn(msgId, window.CSAuth.errText(r), false); return; }
|
|
draw(el, msgId, store(r.data));
|
|
sayIn(msgId, 'Removed.', true);
|
|
}, failed(msgId));
|
|
});
|
|
});
|
|
document.getElementById('notifyMyNodes').addEventListener('click', function () {
|
|
return guarded(function () {
|
|
return window.CSAuth.request('POST', '/api/account/notifications/watch-my-nodes').then(function (r) {
|
|
if (!r.ok) { sayIn(msgId, window.CSAuth.errText(r), false); return; }
|
|
var d = r.data;
|
|
draw(el, msgId, store(d.account));
|
|
sayIn(msgId, (d.added + d.already + d.skipped) === 0
|
|
? 'Your synced My nodes list is empty. Add nodes to My nodes on the Nodes page and turn on settings sync.'
|
|
: 'Added ' + d.added + ', already watched ' + d.already + ', skipped ' + d.skipped + '.', true);
|
|
}, failed(msgId));
|
|
});
|
|
});
|
|
}
|
|
|
|
// mountSection loads the caller's state (always fresh) into el.
|
|
function mountSection(el, msgId) {
|
|
if (!el || !enabled() || !currentUser()) return Promise.resolve();
|
|
return window.CSAuth.request('GET', '/api/account/notifications').then(function (r) {
|
|
if (!r.ok) { sayIn(msgId, window.CSAuth.errText(r), false); return; }
|
|
draw(el, msgId, store(r.data));
|
|
}, failed(msgId));
|
|
}
|
|
|
|
window.addEventListener('cs-auth-changed', function () { cache.userId = null; cache.promise = null; });
|
|
|
|
window.CSNotify = { enabled: enabled, load: load, store: store, toggleState: toggleState, toggleHtml: toggleHtml, mount: mount,
|
|
sectionHtml: sectionHtml, mountSection: mountSection };
|
|
})();
|