Enhance MQTT implementation by adding support for JWT audience configuration in custom slots. Update MQTTBridge and CommonCLI to handle audience settings, enabling JWT authentication for custom brokers. Modify documentation to reflect changes in command usage and provide examples for custom broker setup with JWT authentication.

This commit is contained in:
agessaman committed 2026-03-30 21:44:05 -07:00
1 parent da775bb281
commit 1263e71d31
6 files changed
+93 -18

No files matched your search

+24 -1
View File
@@ -102,7 +102,7 @@ The MQTT bridge uses a slot-based architecture with up to 6 concurrent connectio
| `meshrank` | meshrank.net:8883 | None (token in topic) | MQTT over TLS |
| `waev` | mqtt.waev.app:443 | JWT (Ed25519) | WSS |
| `meshomatic` | us-east.meshomatic.net:443 | JWT (Ed25519) | WSS |
| `cascadiamesh` | cascadiamesh.ddns.net:1883 | None | MQTT (unencrypted) |
| `cascadiamesh` | mqtt-v1.cascadiamesh.org:443 | JWT (Ed25519) | WSS |
| `custom` | User-configured | Username/Password | MQTT or WSS |
| `none` | (disabled) | — | — |
@@ -218,6 +218,7 @@ Each slot (1-6) supports the following commands:
- `get mqttN.password` - Get custom password for slot N
- `get mqttN.token` - Get per-slot token (e.g., MeshRank account token)
- `get mqttN.topic` - Get custom topic template for slot N
- `get mqttN.audience` - Get JWT audience for slot N (custom slots only)
#### Set Commands
- `set mqttN.preset analyzer-us` - Set slot N to LetsMesh Analyzer US
@@ -235,6 +236,8 @@ Each slot (1-6) supports the following commands:
- `set mqttN.password <password>` - Set custom password for slot N
- `set mqttN.token <token>` - Set per-slot token (required for MeshRank preset)
- `set mqttN.topic <template>` - Set custom topic template (custom preset only, see below)
- `set mqttN.audience <audience>` - Set JWT audience for custom slot (enables Ed25519 JWT auth)
- `set mqttN.audience` - Clear JWT audience (reverts to username/password auth)
**Note:** Custom server/port/username/password settings only apply when the slot's preset is `custom`.
@@ -260,6 +263,26 @@ set mqtt3.username your-username
set mqtt3.password your-password
```
#### Example: Custom Broker with JWT Authentication (Ed25519)
For community brokers that support the MeshCore JWT auth protocol (same as the built-in presets), set the `audience` field to enable Ed25519-signed JWT authentication:
```bash
set mqtt3.preset custom
set mqtt3.server wss://my-broker.example.com:443/mqtt
set mqtt3.port 443
set mqtt3.audience my-broker.example.com
```
When `audience` is set, the device will:
- Connect with username `v1_{PUBLIC_KEY}` and an Ed25519-signed JWT as the password
- Automatically renew tokens before expiry (default 24h lifetime)
- Include owner public key and email in the JWT payload (if configured via `set mqtt.owner` / `set mqtt.email`)
To revert a slot back to username/password auth, clear the audience:
```bash
set mqtt3.audience
```
#### Example: Custom Broker with Custom Topic Template
```bash
set mqtt3.preset custom
+23
View File
@@ -545,6 +545,7 @@ void CommonCLI::syncMQTTPrefsToNodePrefs() {
StrHelper::strncpy(_prefs->mqtt_slot_password[i], _mqtt_prefs.mqtt_slot_password[i], sizeof(_prefs->mqtt_slot_password[i]));
StrHelper::strncpy(_prefs->mqtt_slot_token[i], _mqtt_prefs.mqtt_slot_token[i], sizeof(_prefs->mqtt_slot_token[i]));
StrHelper::strncpy(_prefs->mqtt_slot_topic[i], _mqtt_prefs.mqtt_slot_topic[i], sizeof(_prefs->mqtt_slot_topic[i]));
StrHelper::strncpy(_prefs->mqtt_slot_audience[i], _mqtt_prefs.mqtt_slot_audience[i], sizeof(_prefs->mqtt_slot_audience[i]));
}
StrHelper::strncpy(_prefs->mqtt_owner_public_key, _mqtt_prefs.mqtt_owner_public_key, sizeof(_prefs->mqtt_owner_public_key));
StrHelper::strncpy(_prefs->mqtt_email, _mqtt_prefs.mqtt_email, sizeof(_prefs->mqtt_email));
@@ -574,6 +575,7 @@ void CommonCLI::syncNodePrefsToMQTTPrefs() {
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_password[i], _prefs->mqtt_slot_password[i], sizeof(_mqtt_prefs.mqtt_slot_password[i]));
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_token[i], _prefs->mqtt_slot_token[i], sizeof(_mqtt_prefs.mqtt_slot_token[i]));
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_topic[i], _prefs->mqtt_slot_topic[i], sizeof(_mqtt_prefs.mqtt_slot_topic[i]));
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_audience[i], _prefs->mqtt_slot_audience[i], sizeof(_mqtt_prefs.mqtt_slot_audience[i]));
}
StrHelper::strncpy(_mqtt_prefs.mqtt_owner_public_key, _prefs->mqtt_owner_public_key, sizeof(_mqtt_prefs.mqtt_owner_public_key));
StrHelper::strncpy(_mqtt_prefs.mqtt_email, _prefs->mqtt_email, sizeof(_mqtt_prefs.mqtt_email));
@@ -894,6 +896,12 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
} else {
strcpy(reply, "> (default: meshcore/{iata}/{device}/{type})");
}
} else if (memcmp(subcmd, "audience", 8) == 0) {
if (_prefs->mqtt_slot_audience[slot][0] != '\0') {
sprintf(reply, "> %s", _prefs->mqtt_slot_audience[slot]);
} else {
strcpy(reply, "> (not set — custom slots use username/password auth)");
}
} else {
sprintf(reply, "??: %s", config);
}
@@ -1449,6 +1457,21 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
_callbacks->restartBridgeSlot(slot);
sprintf(reply, "OK - slot %d topic: %s", slot + 1, _prefs->mqtt_slot_topic[slot]);
}
} else if (memcmp(subcmd, "audience ", 8) == 0) {
StrHelper::strncpy(_prefs->mqtt_slot_audience[slot], &subcmd[8], sizeof(_prefs->mqtt_slot_audience[slot]));
savePrefs();
_callbacks->restartBridgeSlot(slot);
if (_prefs->mqtt_slot_audience[slot][0] != '\0') {
sprintf(reply, "OK - slot %d JWT audience: %s", slot + 1, _prefs->mqtt_slot_audience[slot]);
} else {
sprintf(reply, "OK - slot %d JWT audience cleared (using username/password auth)", slot + 1);
}
} else if (memcmp(subcmd, "audience", 8) == 0 && subcmd[8] == '\0') {
// "set mqttN.audience" with no value — clear the audience
_prefs->mqtt_slot_audience[slot][0] = '\0';
savePrefs();
_callbacks->restartBridgeSlot(slot);
sprintf(reply, "OK - slot %d JWT audience cleared (using username/password auth)", slot + 1);
} else {
sprintf(reply, "unknown config: %s", config);
}
+2
View File
@@ -94,6 +94,7 @@ struct NodePrefs { // persisted to file
// Per-slot extended fields
char mqtt_slot_token[MAX_MQTT_SLOTS][48]; // Per-slot token (e.g., MeshRank account token)
char mqtt_slot_topic[MAX_MQTT_SLOTS][96]; // Per-slot custom topic template (custom preset only)
char mqtt_slot_audience[MAX_MQTT_SLOTS][64]; // JWT audience (non-empty enables JWT auth for custom slots)
uint8_t loop_detect;
@@ -173,6 +174,7 @@ struct MQTTPrefs {
// --- New fields (appended at end for migration safety) ---
char mqtt_slot_token[MAX_MQTT_SLOTS][48]; // Per-slot token (e.g., MeshRank account token)
char mqtt_slot_topic[MAX_MQTT_SLOTS][96]; // Per-slot custom topic template (custom preset only)
char mqtt_slot_audience[MAX_MQTT_SLOTS][64]; // JWT audience (non-empty enables JWT auth for custom slots)
};
// 3-slot MQTTPrefs layout — used for migrating from 3-slot to 6-slot format.
+1 -1
View File
@@ -97,7 +97,7 @@ static const MQTTPresetDef MQTT_PRESETS[MQTT_PRESET_COUNT] = {
{ "meshrank", "mqtts://meshrank.net:8883", nullptr, ISRG_ROOT_X1, MQTT_AUTH_NONE, MQTT_TOPIC_MESHRANK, 0, false, 0 },
{ "waev", "wss://mqtt.waev.app:443/mqtt", "mqtt.waev.app", GTS_ROOT_R4, MQTT_AUTH_JWT, MQTT_TOPIC_MESHCORE, 3300, false, 55 },
{ "meshomatic", "wss://us-east.meshomatic.net:443/mqtt", "us-east.meshomatic.net", ISRG_ROOT_X1, MQTT_AUTH_JWT, MQTT_TOPIC_MESHCORE, 0, true, 55 },
{ "cascadiamesh", "mqtt://cascadiamesh.ddns.net:1883", nullptr, nullptr, MQTT_AUTH_NONE, MQTT_TOPIC_MESHCORE, 0, true, 0 },
{ "cascadiamesh", "wss://mqtt-v1.cascadiamesh.org:443/mqtt", "mqtt-v1.cascadiamesh.org", ISRG_ROOT_X1, MQTT_AUTH_JWT, MQTT_TOPIC_MESHCORE, 0, true, 55 },
};
// Find a preset by name, returns nullptr if not found
+41 -15
View File
@@ -359,6 +359,8 @@ void MQTTBridge::begin() {
_slots[i].username[sizeof(_slots[i].username) - 1] = '\0';
strncpy(_slots[i].password, _prefs->mqtt_slot_password[i], sizeof(_slots[i].password) - 1);
_slots[i].password[sizeof(_slots[i].password) - 1] = '\0';
strncpy(_slots[i].audience, _prefs->mqtt_slot_audience[i], sizeof(_slots[i].audience) - 1);
_slots[i].audience[sizeof(_slots[i].audience) - 1] = '\0';
} else {
const MQTTPresetDef* preset = findMQTTPreset(preset_name);
if (preset) {
@@ -831,7 +833,8 @@ void MQTTBridge::setupSlot(int index) {
if (slot.preset && slot.preset->keepalive > 0) {
slot.client->setKeepAlive(slot.preset->keepalive);
}
optimizeMqttClientConfig(slot.client, slot.preset && slot.preset->auth_type == MQTT_AUTH_JWT);
bool uses_jwt = (slot.preset && slot.preset->auth_type == MQTT_AUTH_JWT) || slot.audience[0] != '\0';
optimizeMqttClientConfig(slot.client, uses_jwt);
// Callbacks (capture index by value)
slot.client->onConnect([this, index](bool sessionPresent) {
@@ -968,7 +971,19 @@ void MQTTBridge::setupSlot(int index) {
MQTT_DEBUG_PRINTLN("MQTT%d custom broker uses non-TLS transport", index + 1);
}
if (strlen(slot.username) > 0) {
// Custom slot authentication: JWT if audience is set, else username/password
if (slot.audience[0] != '\0') {
// JWT auth for custom slot — allocate token buffer and create initial token
if (!slot.auth_token) {
slot.auth_token = (char*)psram_malloc(AUTH_TOKEN_SIZE);
if (slot.auth_token) slot.auth_token[0] = '\0';
}
createSlotAuthToken(index);
if (slot.auth_token && strlen(slot.auth_token) > 0) {
slot.client->setCredentials(_jwt_username, slot.auth_token);
}
MQTT_DEBUG_PRINTLN("MQTT%d custom broker using JWT auth (audience: %s)", index + 1, slot.audience);
} else if (strlen(slot.username) > 0) {
slot.client->setCredentials(slot.username, slot.password);
}
}
@@ -1044,7 +1059,9 @@ void MQTTBridge::maintainSlotConnections() {
if (!_slots[i].enabled || !_slots[i].client) continue;
// JWT slots need time sync before we can manage tokens
if (_slots[i].preset && _slots[i].preset->auth_type == MQTT_AUTH_JWT && !can_do_jwt) {
bool slot_jwt = (_slots[i].preset && _slots[i].preset->auth_type == MQTT_AUTH_JWT) ||
(!_slots[i].preset && _slots[i].audience[0] != '\0' && _slots[i].auth_token != nullptr);
if (slot_jwt && !can_do_jwt) {
continue;
}
@@ -1060,8 +1077,10 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
slot.max_backoff_failures = 0;
}
// JWT token renewal (only for preset slots with JWT auth)
if (slot.preset && slot.preset->auth_type == MQTT_AUTH_JWT) {
// JWT token renewal (for preset JWT slots and custom slots with audience set)
bool slot_uses_jwt = (slot.preset && slot.preset->auth_type == MQTT_AUTH_JWT) ||
(!slot.preset && slot.audience[0] != '\0' && slot.auth_token != nullptr);
if (slot_uses_jwt) {
bool token_needs_renewal = false;
if (!time_synced) {
token_needs_renewal = (slot.token_expires_at == 0);
@@ -1125,7 +1144,7 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
slot.last_reconnect_attempt = now_millis;
reconnect_attempted = true;
MQTT_DEBUG_PRINTLN("MQTT%d circuit breaker probe (attempting single reconnect after %lu ms)", index + 1, probe_elapsed);
if (slot.preset && slot.preset->auth_type == MQTT_AUTH_JWT) {
if (slot_uses_jwt) {
unsigned long current_time = time(nullptr);
bool token_still_valid = slot.token_expires_at > 0 &&
current_time < slot.token_expires_at &&
@@ -1189,7 +1208,7 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
}
MQTT_DEBUG_PRINTLN("MQTT%d reconnecting (backoff level %d, failures at max: %d)", index + 1, slot.reconnect_backoff, slot.max_backoff_failures);
reconnect_attempted = true;
if (slot.preset && slot.preset->auth_type == MQTT_AUTH_JWT) {
if (slot_uses_jwt) {
unsigned long current_time = time(nullptr);
bool token_still_valid = slot.token_expires_at > 0 &&
current_time < slot.token_expires_at &&
@@ -1250,9 +1269,18 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
bool MQTTBridge::createSlotAuthToken(int index) {
if (index < 0 || index >= MAX_MQTT_SLOTS) return false;
MQTTSlot& slot = _slots[index];
if (!_identity || !slot.preset || slot.preset->auth_type != MQTT_AUTH_JWT || !slot.auth_token) {
return false;
if (!_identity || !slot.auth_token) return false;
// Determine JWT audience: preset takes priority, then custom slot audience field
const char* audience = nullptr;
unsigned long base_lifetime = 86400; // default 24h
if (slot.preset && slot.preset->auth_type == MQTT_AUTH_JWT) {
audience = slot.preset->jwt_audience;
if (slot.preset->token_lifetime > 0) base_lifetime = slot.preset->token_lifetime;
} else if (slot.audience[0] != '\0') {
audience = slot.audience;
}
if (!audience || audience[0] == '\0') return false;
// Ensure JWT username is set
if (_jwt_username[0] == '\0') {
@@ -1278,9 +1306,6 @@ bool MQTTBridge::createSlotAuthToken(int index) {
const char* email = (_prefs->mqtt_email[0] != '\0') ? _prefs->mqtt_email : nullptr;
unsigned long current_time = time(nullptr);
// Use preset-specific lifetime if set, otherwise default to 24h
// Stagger token expiry per slot to avoid simultaneous renewal/reconnect
unsigned long base_lifetime = (slot.preset->token_lifetime > 0) ? slot.preset->token_lifetime : 86400;
// Stagger token expiry per slot to avoid simultaneous renewal/reconnect
// Use 5% of lifetime per slot, capped at 300s, so short-lived tokens aren't over-reduced
unsigned long stagger = index * min((unsigned long)300, base_lifetime / 20);
@@ -1288,7 +1313,7 @@ bool MQTTBridge::createSlotAuthToken(int index) {
bool time_synced = (current_time >= 1000000000);
if (JWTHelper::createAuthToken(
*_identity, slot.preset->jwt_audience,
*_identity, audience,
0, expires_in, slot.auth_token, AUTH_TOKEN_SIZE,
owner_key, client_version, email)) {
slot.token_expires_at = time_synced ? (current_time + expires_in) : 0;
@@ -2534,8 +2559,9 @@ void MQTTBridge::syncTimeWithNTP() {
if (_slots_setup_done && was_ntp_synced) {
unsigned long current_time = (unsigned long)time(nullptr);
for (int i = 0; i < _max_active_slots; i++) {
if (_slots[i].enabled && _slots[i].preset &&
_slots[i].preset->auth_type == MQTT_AUTH_JWT) {
bool slot_jwt = (_slots[i].preset && _slots[i].preset->auth_type == MQTT_AUTH_JWT) ||
(!_slots[i].preset && _slots[i].audience[0] != '\0' && _slots[i].auth_token != nullptr);
if (_slots[i].enabled && slot_jwt) {
// Check if the slot's token was created with a stale time
// (token_expires_at would be far in the past relative to current time)
if (_slots[i].token_expires_at > 0 && current_time > _slots[i].token_expires_at) {
+2 -1
View File
@@ -65,7 +65,7 @@ private:
bool connected; // Updated in callbacks
bool initial_connect_done; // True after first connect() call
// JWT auth state (only used when preset->auth_type == MQTT_AUTH_JWT)
// JWT auth state (used by preset JWT slots and custom slots with audience set)
char* auth_token; // PSRAM-allocated, AUTH_TOKEN_SIZE bytes
unsigned long token_expires_at;
unsigned long last_token_renewal;
@@ -75,6 +75,7 @@ private:
uint16_t port;
char username[32];
char password[64];
char audience[64]; // JWT audience for custom JWT slots (empty = username/password)
char broker_uri[128]; // Persistent URI for custom slots (avoids dangling pointer)
// Reconnect backoff