refactor: rework after #312

This commit is contained in:
Yurii committed 2026-12-06 16:13:00 +03:00
1 parent 75e22e92e9
commit 96473129a8
9 files changed
+111 -128

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ extern Sensors::Settings sensorsSettings[SENSORS_AMOUNT];
void initConfig(); void initConfig();
void saveSettingsNow(); void saveSettingsNow();
const char* getApiToken(); const char* getApiToken();
bool regenerateApiToken(); 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.
+9 -10
View File
@@ -106,6 +106,12 @@ static FileData fsSensorsSettings(&LittleFS, "/sensors.conf", 'e', &sensorsSetti
// FileData requests can arrive while the save task is running. // FileData requests can arrive while the save task is running.
static std::mutex settingsSaveMutex; static std::mutex settingsSaveMutex;
// 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);
fsNetworkSettings.update(); fsNetworkSettings.update();
@@ -169,13 +175,6 @@ void saveSettingsNow() {
} }
// API token // API token
// Kept in NVS rather than in Settings, so the settings file layout does not change.
static constexpr char API_TOKEN_NAMESPACE[] = "otgw";
static constexpr char API_TOKEN_KEY[] = "api_token";
static constexpr size_t API_TOKEN_LENGTH = 32;
static char apiToken[API_TOKEN_LENGTH + 1] = "";
static bool isApiTokenValid(const char* token) { static bool isApiTokenValid(const char* token) {
if (strlen(token) != API_TOKEN_LENGTH) { if (strlen(token) != API_TOKEN_LENGTH) {
return false; return false;
@@ -210,7 +209,7 @@ const char* getApiToken() {
return apiToken; return apiToken;
} }
bool regenerateApiToken() { bool refreshApiToken() {
uint8_t bytes[API_TOKEN_LENGTH / 2]; uint8_t bytes[API_TOKEN_LENGTH / 2];
esp_fill_random(bytes, sizeof(bytes)); esp_fill_random(bytes, sizeof(bytes));
@@ -232,7 +231,7 @@ static void loadApiToken() {
nvs_close(handle); nvs_close(handle);
} }
if (!isApiTokenValid(apiToken) && !regenerateApiToken()) { if (!isApiTokenValid(apiToken) && !refreshApiToken()) {
apiToken[0] = '\0'; apiToken[0] = '\0';
ESP_LOGW(L_SETTINGS, "Failed to create the API token"); ESP_LOGW(L_SETTINGS, "Failed to create the API token");
} }
@@ -952,7 +951,7 @@ SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) {
} }
} }
// Accepted for restoring a backup; the portal shows the token read-only. // Both the portal and backup restore accept a hexadecimal token.
if (src[S_API_TOKEN].is<JsonString>()) { if (src[S_API_TOKEN].is<JsonString>()) {
const JsonString value = src[S_API_TOKEN].as<JsonString>(); const JsonString value = src[S_API_TOKEN].as<JsonString>();
+34 -52
View File
@@ -142,42 +142,24 @@ 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 constexpr char BEARER_PREFIX[] = "Bearer "; static AsyncMiddlewareFunction apiAuthMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) {
if (!isAuthenticationRequired(request)) {
// Checks "Authorization: Bearer <API token>".
static bool isApiTokenRequest(AsyncWebServerRequest* request) {
if (!request->hasHeader("Authorization")) {
return false;
}
const String& header = request->getHeader("Authorization")->value();
const size_t prefixLength = sizeof(BEARER_PREFIX) - 1;
const char* token = getApiToken();
const size_t tokenLength = strlen(token);
if (!tokenLength || header.length() != prefixLength + tokenLength || !header.startsWith(BEARER_PREFIX)) {
return false;
}
// Compare without an early exit.
uint8_t diff = 0;
for (size_t i = 0; i < tokenLength; i++) {
diff |= tolower(static_cast<unsigned char>(header[prefixLength + i])) ^ token[i];
}
return diff == 0;
}
// Setting a sensor value also accepts the API token, so a device needs no portal password.
static AsyncMiddlewareFunction sensorValueAuthMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) {
if (!isAuthenticationRequired(request) || isApiTokenRequest(request)) {
return next(); return next();
} }
if (request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { // Bearer auth
return next(); 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);
} }
return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); // Fallback to basic auth for API requests
return authMiddleware.run(request, next);
}); });
static void initWebSerial() { static void initWebSerial() {
@@ -422,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
@@ -434,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
@@ -446,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
@@ -489,7 +471,7 @@ static void restApi() {
} }
}); });
networkSettingsHandler.setMaxContentLength(1024); networkSettingsHandler.setMaxContentLength(1024);
networkSettingsHandler.addMiddleware(&authMiddleware); networkSettingsHandler.addMiddleware(&apiAuthMiddleware);
// Scan Wi-Fi // Scan Wi-Fi
@@ -534,7 +516,7 @@ static void restApi() {
// Release scan results // Release scan results
WiFi.scanDelete(); WiFi.scanDelete();
} }
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Get settings // Get settings
@@ -590,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
@@ -727,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
@@ -756,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
@@ -785,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
@@ -870,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
@@ -899,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)
@@ -955,7 +937,7 @@ static void restApi() {
request->send(response); request->send(response);
}); });
sensorValueHandler.setMaxContentLength(64); sensorValueHandler.setMaxContentLength(64);
sensorValueHandler.addMiddleware(&sensorValueAuthMiddleware); sensorValueHandler.addMiddleware(&apiAuthMiddleware);
// Set sensor value (form) // Set sensor value (form)
@@ -1028,16 +1010,16 @@ static void restApi() {
response->setLength(); response->setLength();
response->setCode(201); response->setCode(201);
request->send(response); request->send(response);
}).addMiddleware(&sensorValueAuthMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Regenerate the API token, revoking the old one // Refresh the API token, revoking the old one
webServer->on(AsyncURIMatcher::exact("/api/portal/token/regenerate"), HTTP_POST, [](AsyncWebServerRequest *request) { webServer->on(AsyncURIMatcher::exact("/api/portal/token_refresh"), HTTP_POST, [](AsyncWebServerRequest *request) {
if (upgrading || restartTask.scheduled() || restartTask.active()) { if (upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503); return request->send(503);
} }
if (!regenerateApiToken()) { if (!refreshApiToken()) {
return request->send(500); return request->send(500);
} }
@@ -1046,7 +1028,7 @@ static void restApi() {
response->setLength(); response->setLength();
response->setCode(201); response->setCode(201);
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&apiAuthMiddleware);
// Get vars // Get vars
@@ -1058,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) {
@@ -1092,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) {
@@ -1163,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) {
@@ -1213,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
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "使用 mDNS", "mdns": "使用 mDNS",
"apiToken": { "apiToken": {
"title": "API token", "title": "API token",
"note": "Lets a device push sensor values without the portal password: <code>Authorization: Bearer &lt;token&gt;</code> for <code>POST /api/sensor/value?id=N</code>. Works only for this endpoint.", "note": "用于免密访问 API。可以手动输入 32 个字符的令牌,也可以通过<b>刷新</b>按钮生成。<br />令牌通过请求头 <code>Authorization: Bearer &lt;令牌&gt;</code> 发送。",
"regenerate": "Regenerate token", "refreshConfirm": "当前令牌将失效。要继续吗?"
"regenerateConfirm": "The current token will stop working. Continue?"
} }
}, },
"system": { "system": {
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "Use mDNS", "mdns": "Use mDNS",
"apiToken": { "apiToken": {
"title": "API token", "title": "API token",
"note": "Lets a device push sensor values without the portal password: <code>Authorization: Bearer &lt;token&gt;</code> for <code>POST /api/sensor/value?id=N</code>. Works only for this endpoint.", "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.",
"regenerate": "Regenerate token", "refreshConfirm": "The current token will stop working. Continue?"
"regenerateConfirm": "The current token will stop working. Continue?"
} }
}, },
"system": { "system": {
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "Usa mDNS", "mdns": "Usa mDNS",
"apiToken": { "apiToken": {
"title": "API token", "title": "API token",
"note": "Lets a device push sensor values without the portal password: <code>Authorization: Bearer &lt;token&gt;</code> for <code>POST /api/sensor/value?id=N</code>. Works only for this endpoint.", "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>.",
"regenerate": "Regenerate token", "refreshConfirm": "Il token attuale smetterà di funzionare. Continuare?"
"regenerateConfirm": "The current token will stop working. Continue?"
} }
}, },
"system": { "system": {
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "Gebruik mDNS", "mdns": "Gebruik mDNS",
"apiToken": { "apiToken": {
"title": "API token", "title": "API token",
"note": "Lets a device push sensor values without the portal password: <code>Authorization: Bearer &lt;token&gt;</code> for <code>POST /api/sensor/value?id=N</code>. Works only for this endpoint.", "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>.",
"regenerate": "Regenerate token", "refreshConfirm": "Het huidige token werkt daarna niet meer. Doorgaan?"
"regenerateConfirm": "The current token will stop working. Continue?"
} }
}, },
"system": { "system": {
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "Использовать mDNS", "mdns": "Использовать mDNS",
"apiToken": { "apiToken": {
"title": "API-токен", "title": "API-токен",
"note": "Позволяет устройству передавать значения датчиков без пароля портала: <code>Authorization: Bearer &lt;токен&gt;</code> для <code>POST /api/sensor/value?id=N</code>. Действует только для этого адреса.", "note": "Для доступа к API без пароля. Можно задать вручную (32 символа) или сгенерировать кнопкой <b>Обновить</b>.<br />Передавайте в заголовке <code>Authorization: Bearer &lt;токен&gt;</code>.",
"regenerate": "Сгенерировать новый токен", "refreshConfirm": "Текущий токен перестанет работать. Продолжить?"
"regenerateConfirm": "Текущий токен перестанет работать. Продолжить?"
} }
}, },
"system": { "system": {
+57 -50
View File
@@ -43,35 +43,38 @@
<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>
</div> </fieldset>
<label> <div>
<input type="checkbox" name="auth" value="true"> <label for="api-token" data-i18n>settings.portal.apiToken.title</label>
<span data-i18n>settings.portal.auth</span> <fieldset role="group">
</label> <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>
<label> </fieldset>
<input type="checkbox" name="mdns" value="true">
<span data-i18n>settings.portal.mdns</span>
</label>
<label>
<span data-i18n>settings.portal.apiToken.title</span>
<input type="text" id="portal-api-token" readonly>
<small data-i18n>settings.portal.apiToken.note</small> <small data-i18n>settings.portal.apiToken.note</small>
</label> </div>
<button type="button" class="secondary" id="portal-api-token-regenerate" data-i18n>settings.portal.apiToken.regenerate</button>
<br />
<button type="submit" data-i18n>button.save</button> <button type="submit" data-i18n>button.save</button>
</form> </form>
@@ -1192,7 +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);
form.querySelector("#portal-api-token").value = data.portal.api_token ?? ''; 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);
@@ -1514,33 +1517,7 @@
} }
}; };
setupSettingsForm('#portal-settings', ['login', 'password']); setupSettingsForm('#portal-settings', ['login', 'password', 'api_token']);
document.querySelector('#portal-api-token-regenerate').addEventListener('click', async (event) => {
if (!confirm(i18n("settings.portal.apiToken.regenerateConfirm"))) {
return;
}
const button = event.currentTarget;
button.setAttribute('aria-busy', true);
try {
const response = await fetch("/api/portal/token/regenerate", {
method: "POST",
cache: "no-cache",
credentials: "include"
});
if (response.ok) {
document.querySelector('#portal-api-token').value = (await response.json()).api_token;
}
} catch (error) {
console.log(error);
} finally {
button.removeAttribute('aria-busy');
}
});
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');
@@ -1552,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;
}); });