Merge branch 'dev' into nvs

This commit is contained in:
Yurii authored and GitHub committed 2026-12-06 16:14:21 +03:00
commit 05e329a9f7
10 files changed
+235 -39

No files matched your search

+2
View File
@@ -30,6 +30,8 @@ extern Settings settings;
extern Sensors::Settings sensorsSettings[SENSORS_AMOUNT]; extern Sensors::Settings sensorsSettings[SENSORS_AMOUNT];
void initConfig(); void initConfig();
void saveSettingsNow(); void saveSettingsNow();
const char* getApiToken();
bool refreshApiToken();
void requestSaveNetworkSettings(); void requestSaveNetworkSettings();
void requestSaveSettings(); void requestSaveSettings();
// Call after releasing lifecycle, MQTT queue and Sensors data locks. // Call after releasing lifecycle, MQTT queue and Sensors data locks.
+1
View File
@@ -37,6 +37,7 @@ inline const char S_ADDRESS[] = "address";
inline const char S_ANTI_STUCK_INTERVAL[] = "antistuck_interval"; inline const char S_ANTI_STUCK_INTERVAL[] = "antistuck_interval";
inline const char S_ANTI_STUCK_TIME[] = "antistuck_time"; inline const char S_ANTI_STUCK_TIME[] = "antistuck_time";
inline const char S_AP[] = "ap"; inline const char S_AP[] = "ap";
inline const char S_API_TOKEN[] = "api_token";
inline const char S_APP_VERSION[] = "app_version"; inline const char S_APP_VERSION[] = "app_version";
inline const char S_AUTH[] = "auth"; inline const char S_AUTH[] = "auth";
inline const char S_AUTO_DIAG_RESET[] = "auto_diag_reset"; inline const char S_AUTO_DIAG_RESET[] = "auto_diag_reset";
+89
View File
@@ -6,6 +6,8 @@
#endif #endif
#include <FileData.h> #include <FileData.h>
#include <LegacySettings.h> #include <LegacySettings.h>
#include <esp_random.h>
#include <nvs.h>
#include <LittleFS.h> #include <LittleFS.h>
#include <Preferences.h> #include <Preferences.h>
@@ -260,6 +262,12 @@ static bool writeToNvs(const NetworkSettings& src) {
return result; return result;
} }
// Kept in NVS rather than in Settings, so the settings file layout does not change.
static constexpr char API_TOKEN_NAMESPACE[] = "portal";
static constexpr char API_TOKEN_KEY[] = "api_token";
static constexpr size_t API_TOKEN_LENGTH = 32;
static char apiToken[API_TOKEN_LENGTH + 1] = "";
void requestSaveNetworkSettings() { void requestSaveNetworkSettings() {
std::lock_guard<std::mutex> lock(settingsSaveMutex); std::lock_guard<std::mutex> lock(settingsSaveMutex);
saveNetworkSettingsRequestedAt = millis(); saveNetworkSettingsRequestedAt = millis();
@@ -343,6 +351,69 @@ void saveSettingsNow() {
} }
} }
// API token
static bool isApiTokenValid(const char* token) {
if (strlen(token) != API_TOKEN_LENGTH) {
return false;
}
for (size_t i = 0; i < API_TOKEN_LENGTH; i++) {
if (!isxdigit(static_cast<unsigned char>(token[i]))) {
return false;
}
}
return true;
}
static bool storeApiToken(const char* token) {
nvs_handle_t handle;
if (nvs_open(API_TOKEN_NAMESPACE, NVS_READWRITE, &handle) != ESP_OK) {
return false;
}
const bool stored = nvs_set_str(handle, API_TOKEN_KEY, token) == ESP_OK && nvs_commit(handle) == ESP_OK;
nvs_close(handle);
if (stored) {
strcpy(apiToken, token);
}
return stored;
}
const char* getApiToken() {
return apiToken;
}
bool refreshApiToken() {
uint8_t bytes[API_TOKEN_LENGTH / 2];
esp_fill_random(bytes, sizeof(bytes));
char token[API_TOKEN_LENGTH + 1];
for (size_t i = 0; i < sizeof(bytes); i++) {
snprintf(token + i * 2, 3, "%02x", bytes[i]);
}
return storeApiToken(token);
}
static void loadApiToken() {
nvs_handle_t handle;
if (nvs_open(API_TOKEN_NAMESPACE, NVS_READONLY, &handle) == ESP_OK) {
size_t size = sizeof(apiToken);
if (nvs_get_str(handle, API_TOKEN_KEY, apiToken, &size) != ESP_OK) {
apiToken[0] = '\0';
}
nvs_close(handle);
}
if (!isApiTokenValid(apiToken) && !refreshApiToken()) {
apiToken[0] = '\0';
ESP_LOGW(L_SETTINGS, "Failed to create the API token");
}
}
// Initialization // Initialization
static void loadNetworkSettings() { static void loadNetworkSettings() {
// Read from legacy network.conf, if found, migrate to NVS and delete the file // Read from legacy network.conf, if found, migrate to NVS and delete the file
@@ -453,6 +524,7 @@ void initConfig() {
loadNetworkSettings(); loadNetworkSettings();
loadSettings(); loadSettings();
loadSensorsSettings(); loadSensorsSettings();
loadApiToken();
configureLoggingTask.forceRun(); configureLoggingTask.forceRun();
appTaskManager.addTask(settingsSaveTask.setInterval(100)); appTaskManager.addTask(settingsSaveTask.setInterval(100));
@@ -1004,6 +1076,7 @@ JsonVariant toJson(const PortalSettings& src, JsonVariant dst) {
portal[S_AUTH] = src.auth; portal[S_AUTH] = src.auth;
portal[S_LOGIN] = src.login; portal[S_LOGIN] = src.login;
portal[S_PASSWORD] = src.password; portal[S_PASSWORD] = src.password;
portal[S_API_TOKEN] = apiToken;
portal[S_MDNS] = src.mdns; portal[S_MDNS] = src.mdns;
return dst; return dst;
@@ -1050,6 +1123,22 @@ SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) {
} }
} }
// Both the portal and backup restore accept a hexadecimal token.
if (src[S_API_TOKEN].is<JsonString>()) {
const JsonString value = src[S_API_TOKEN].as<JsonString>();
if (strlen(value.c_str()) == value.size() && isApiTokenValid(value.c_str())) {
char token[API_TOKEN_LENGTH + 1];
for (size_t i = 0; i < sizeof(token); i++) {
token[i] = static_cast<char>(tolower(static_cast<unsigned char>(value.c_str()[i])));
}
if (strcmp(token, apiToken) == 0 || storeApiToken(token)) {
result.accepted = true;
}
}
}
if (dst.auth && (!strlen(dst.login) || !strlen(dst.password))) { if (dst.auth && (!strlen(dst.login) || !strlen(dst.password))) {
dst.auth = false; dst.auth = false;
result.changed = true; result.changed = true;
+55 -17
View File
@@ -142,6 +142,26 @@ static AsyncMiddlewareFunction authMiddleware([](AsyncWebServerRequest *request,
return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed");
}); });
static AsyncMiddlewareFunction apiAuthMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) {
if (!isAuthenticationRequired(request)) {
return next();
}
// Bearer auth
if (request->authType() == AsyncAuthType::AUTH_BEARER) {
if (request->authenticate(getApiToken())) {
return next();
}
auto* response = request->beginResponse(401);
response->addHeader(asyncsrv::T_WWW_AUTH, asyncsrv::T_BEARER);
return request->send(response);
}
// Fallback to basic auth for API requests
return authMiddleware.run(request, next);
});
static void initWebSerial() { static void initWebSerial() {
// Register before System starts. Unbuffered WebSerial preserves newlines inside each record. // Register before System starts. Unbuffered WebSerial preserves newlines inside each record.
webSerial = new WebSerial(); webSerial = new WebSerial();
@@ -384,7 +404,7 @@ static void restApi() {
// Send response // Send response
response->setLength(); response->setLength();
request->send(setDownloadFilename(response, "backup", "json")); request->send(setDownloadFilename(response, "backup", "json"));
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Request restart // Request restart
@@ -396,7 +416,7 @@ static void restApi() {
// Schedule restart // Schedule restart
restartTask.resume(15000); restartTask.resume(15000);
request->send(202); request->send(202);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Get network settings // Get network settings
@@ -408,7 +428,7 @@ static void restApi() {
// Send response // Send response
response->setLength(); response->setLength();
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Set network settings // Set network settings
@@ -451,7 +471,7 @@ static void restApi() {
} }
}); });
networkSettingsHandler.setMaxContentLength(1024); networkSettingsHandler.setMaxContentLength(1024);
networkSettingsHandler.addMiddleware(&authMiddleware); networkSettingsHandler.addMiddleware(&apiAuthMiddleware);
// Scan Wi-Fi // Scan Wi-Fi
@@ -496,7 +516,7 @@ static void restApi() {
// Release scan results // Release scan results
WiFi.scanDelete(); WiFi.scanDelete();
} }
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Get settings // Get settings
@@ -552,7 +572,7 @@ static void restApi() {
// Send response // Send response
response->setLength(); response->setLength();
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Set settings // Set settings
@@ -689,7 +709,7 @@ static void restApi() {
request->send(response); request->send(response);
}); });
settingsHandler.setMaxContentLength(3072); settingsHandler.setMaxContentLength(3072);
settingsHandler.addMiddleware(&authMiddleware); settingsHandler.addMiddleware(&apiAuthMiddleware);
// Get sensors list // Get sensors list
@@ -718,7 +738,7 @@ static void restApi() {
// Send response // Send response
response->setLength(); response->setLength();
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Get sensor settings // Get sensor settings
@@ -747,7 +767,7 @@ static void restApi() {
// Send response // Send response
response->setLength(); response->setLength();
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Set sensor settings // Set sensor settings
@@ -832,7 +852,7 @@ static void restApi() {
request->send(response); request->send(response);
}); });
sensorSettingsHandler.setMaxContentLength(1024); sensorSettingsHandler.setMaxContentLength(1024);
sensorSettingsHandler.addMiddleware(&authMiddleware); sensorSettingsHandler.addMiddleware(&apiAuthMiddleware);
// Get sensor measurements // Get sensor measurements
@@ -861,7 +881,7 @@ static void restApi() {
// Send response // Send response
response->setLength(); response->setLength();
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Set sensor value (JSON) // Set sensor value (JSON)
@@ -917,7 +937,7 @@ static void restApi() {
request->send(response); request->send(response);
}); });
sensorValueHandler.setMaxContentLength(64); sensorValueHandler.setMaxContentLength(64);
sensorValueHandler.addMiddleware(&authMiddleware); sensorValueHandler.addMiddleware(&apiAuthMiddleware);
// Set sensor value (form) // Set sensor value (form)
@@ -990,7 +1010,25 @@ static void restApi() {
response->setLength(); response->setLength();
response->setCode(201); response->setCode(201);
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Refresh the API token, revoking the old one
webServer->on(AsyncURIMatcher::exact("/api/portal/token_refresh"), HTTP_POST, [](AsyncWebServerRequest *request) {
if (upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503);
}
if (!refreshApiToken()) {
return request->send(500);
}
auto *response = new AsyncJsonResponse();
response->getRoot()[S_API_TOKEN] = getApiToken();
response->setLength();
response->setCode(201);
request->send(response);
}).addMiddleware(&apiAuthMiddleware);
// Get vars // Get vars
@@ -1002,7 +1040,7 @@ static void restApi() {
// Send response // Send response
response->setLength(); response->setLength();
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Set vars // Set vars
auto& varsHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { auto& varsHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
@@ -1036,7 +1074,7 @@ static void restApi() {
} }
}); });
varsHandler.setMaxContentLength(1536); varsHandler.setMaxContentLength(1536);
varsHandler.addMiddleware(&authMiddleware); varsHandler.addMiddleware(&apiAuthMiddleware);
// Get info // Get info
webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) { webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) {
@@ -1107,7 +1145,7 @@ static void restApi() {
// Send response // Send response
response->setLength(); response->setLength();
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Get coredump // Get coredump
webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) { webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) {
@@ -1157,7 +1195,7 @@ static void restApi() {
// Send response // Send response
request->send(setDownloadFilename(response, "coredump", "bin")); request->send(setDownloadFilename(response, "coredump", "bin"));
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
} }
// Initialize portal // Initialize portal
+6 -1
View File
@@ -366,7 +366,12 @@
"login": "登录", "login": "登录",
"password": "密码", "password": "密码",
"auth": "需身份验证", "auth": "需身份验证",
"mdns": "使用 mDNS" "mdns": "使用 mDNS",
"apiToken": {
"title": "API token",
"note": "用于免密访问 API。可以手动输入 32 个字符的令牌,也可以通过<b>刷新</b>按钮生成。<br />令牌通过请求头 <code>Authorization: Bearer &lt;令牌&gt;</code> 发送。",
"refreshConfirm": "当前令牌将失效。要继续吗?"
}
}, },
"system": { "system": {
"unit": "单位", "unit": "单位",
+6 -1
View File
@@ -366,7 +366,12 @@
"login": "Login", "login": "Login",
"password": "Password", "password": "Password",
"auth": "Require authentication", "auth": "Require authentication",
"mdns": "Use mDNS" "mdns": "Use mDNS",
"apiToken": {
"title": "API token",
"note": "For API access without a password. You can enter a 32-character token manually or generate one with <b>Refresh</b>.<br />The token is sent in the <code>Authorization: Bearer &lt;token&gt;</code> header.",
"refreshConfirm": "The current token will stop working. Continue?"
}
}, },
"system": { "system": {
"unit": "Unit system", "unit": "Unit system",
+6 -1
View File
@@ -366,7 +366,12 @@
"login": "Login", "login": "Login",
"password": "Password", "password": "Password",
"auth": "Richiede autenticazione", "auth": "Richiede autenticazione",
"mdns": "Usa mDNS" "mdns": "Usa mDNS",
"apiToken": {
"title": "API token",
"note": "Per accedere all’API senza password. Il token di 32 caratteri può essere inserito manualmente o generato con <b>Ricarica</b>.<br />Viene inviato nell’intestazione <code>Authorization: Bearer &lt;token&gt;</code>.",
"refreshConfirm": "Il token attuale smetterà di funzionare. Continuare?"
}
}, },
"system": { "system": {
"unit": "Unità di misura", "unit": "Unità di misura",
+6 -1
View File
@@ -366,7 +366,12 @@
"login": "Gebruikersnaam", "login": "Gebruikersnaam",
"password": "Wachtwoord", "password": "Wachtwoord",
"auth": "Authenticatie vereisen", "auth": "Authenticatie vereisen",
"mdns": "Gebruik mDNS" "mdns": "Gebruik mDNS",
"apiToken": {
"title": "API token",
"note": "Voor toegang tot de API zonder wachtwoord. Je kunt het token van 32 tekens zelf invoeren of genereren met <b>Vernieuwen</b>.<br />Het token wordt meegestuurd in de header <code>Authorization: Bearer &lt;token&gt;</code>.",
"refreshConfirm": "Het huidige token werkt daarna niet meer. Doorgaan?"
}
}, },
"system": { "system": {
"unit": "Eenheidssysteem", "unit": "Eenheidssysteem",
+6 -1
View File
@@ -366,7 +366,12 @@
"login": "Логин", "login": "Логин",
"password": "Пароль", "password": "Пароль",
"auth": "Требовать аутентификацию", "auth": "Требовать аутентификацию",
"mdns": "Использовать mDNS" "mdns": "Использовать mDNS",
"apiToken": {
"title": "API-токен",
"note": "Для доступа к API без пароля. Можно задать вручную (32 символа) или сгенерировать кнопкой <b>Обновить</b>.<br />Передавайте в заголовке <code>Authorization: Bearer &lt;токен&gt;</code>.",
"refreshConfirm": "Текущий токен перестанет работать. Продолжить?"
}
}, },
"system": { "system": {
"unit": "Система единиц", "unit": "Система единиц",
+58 -17
View File
@@ -43,29 +43,39 @@
<div> <div>
<div id="portal-settings-busy" aria-busy="true"></div> <div id="portal-settings-busy" aria-busy="true"></div>
<form action="/api/settings/portal" id="portal-settings" data-section="portal" class="hidden"> <form action="/api/settings/portal" id="portal-settings" data-section="portal" class="hidden">
<div class="grid"> <fieldset>
<div class="grid">
<label>
<span data-i18n>settings.portal.login</span>
<input type="text" name="login" maxlength="12">
</label>
<label>
<span data-i18n>settings.portal.password</span>
<input type="password" name="password" maxlength="32">
</label>
</div>
<label> <label>
<span data-i18n>settings.portal.login</span> <input type="checkbox" name="auth" value="true">
<input type="text" name="login" maxlength="12"> <span data-i18n>settings.portal.auth</span>
</label> </label>
<label> <label>
<span data-i18n>settings.portal.password</span> <input type="checkbox" name="mdns" value="true">
<input type="password" name="password" maxlength="32"> <span data-i18n>settings.portal.mdns</span>
</label> </label>
</fieldset>
<div>
<label for="api-token" data-i18n>settings.portal.apiToken.title</label>
<fieldset role="group">
<input type="text" id="api-token" name="api_token" pattern="[0-9A-Fa-f]{32}" required />
<button type="button" class="secondary refresh" data-i18n>button.refresh</button>
</fieldset>
<small data-i18n>settings.portal.apiToken.note</small>
</div> </div>
<label>
<input type="checkbox" name="auth" value="true">
<span data-i18n>settings.portal.auth</span>
</label>
<label>
<input type="checkbox" name="mdns" value="true">
<span data-i18n>settings.portal.mdns</span>
</label>
<br />
<button type="submit" data-i18n>button.save</button> <button type="submit" data-i18n>button.save</button>
</form> </form>
</div> </div>
@@ -1185,6 +1195,7 @@
setInputValue("[name='login']", data.portal.login, {}, form); setInputValue("[name='login']", data.portal.login, {}, form);
setInputValue("[name='password']", data.portal.password, {}, form); setInputValue("[name='password']", data.portal.password, {}, form);
setCheckboxValue("[name='mdns']", data.portal.mdns, form); setCheckboxValue("[name='mdns']", data.portal.mdns, form);
setInputValue("[name='api_token']", data.portal.api_token ?? '', {}, form);
} else if (section === 'opentherm') { } else if (section === 'opentherm') {
setInputValue("[name='in_gpio']", data.opentherm.in_gpio < 255 ? data.opentherm.in_gpio : '', {}, form); setInputValue("[name='in_gpio']", data.opentherm.in_gpio < 255 ? data.opentherm.in_gpio : '', {}, form);
@@ -1506,7 +1517,7 @@
} }
}; };
setupSettingsForm('#portal-settings', ['login', 'password']); setupSettingsForm('#portal-settings', ['login', 'password', 'api_token']);
setupSettingsForm('#system-settings', ['ntp.server', 'ntp.timezone']); setupSettingsForm('#system-settings', ['ntp.server', 'ntp.timezone']);
setupSettingsForm('#heating-settings'); setupSettingsForm('#heating-settings');
setupSettingsForm('#dhw-settings'); setupSettingsForm('#dhw-settings');
@@ -1518,6 +1529,36 @@
setupSettingsForm('#extpump-settings'); setupSettingsForm('#extpump-settings');
setupSettingsForm('#cc-settings'); setupSettingsForm('#cc-settings');
document.querySelector('#portal-settings .refresh').addEventListener('click', async (event) => {
if (!confirm(i18n('settings.portal.apiToken.refreshConfirm'))) {
return;
}
const button = event.currentTarget;
button.disabled = true;
button.setAttribute('aria-busy', true);
try {
const response = await fetch('/api/portal/token_refresh', {
method: "POST",
cache: "no-cache",
credentials: "include"
});
if (response.ok) {
const result = await response.json();
setInputValue("[name='api_token']", result.api_token, {}, button.form);
}
} catch (error) {
console.log(error);
} finally {
button.removeAttribute('aria-busy');
button.disabled = false;
}
});
document.querySelector(".presetTimezones").addEventListener('change', (event) => { document.querySelector(".presetTimezones").addEventListener('change', (event) => {
document.querySelector("#system-settings [name='ntp[timezone]']").value = event.target.value; document.querySelector("#system-settings [name='ntp[timezone]']").value = event.target.value;
}); });