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 saveSettingsNow();
const char* getApiToken();
bool regenerateApiToken();
bool refreshApiToken();
void requestSaveNetworkSettings();
void requestSaveSettings();
// 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.
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() {
std::lock_guard<std::mutex> lock(settingsSaveMutex);
fsNetworkSettings.update();
@@ -169,13 +175,6 @@ void saveSettingsNow() {
}
// 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) {
if (strlen(token) != API_TOKEN_LENGTH) {
return false;
@@ -210,7 +209,7 @@ const char* getApiToken() {
return apiToken;
}
bool regenerateApiToken() {
bool refreshApiToken() {
uint8_t bytes[API_TOKEN_LENGTH / 2];
esp_fill_random(bytes, sizeof(bytes));
@@ -232,7 +231,7 @@ static void loadApiToken() {
nvs_close(handle);
}
if (!isApiTokenValid(apiToken) && !regenerateApiToken()) {
if (!isApiTokenValid(apiToken) && !refreshApiToken()) {
apiToken[0] = '\0';
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>()) {
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");
});
static constexpr char BEARER_PREFIX[] = "Bearer ";
// 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)) {
static AsyncMiddlewareFunction apiAuthMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) {
if (!isAuthenticationRequired(request)) {
return next();
}
if (request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) {
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);
}
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() {
@@ -422,7 +404,7 @@ static void restApi() {
// Send response
response->setLength();
request->send(setDownloadFilename(response, "backup", "json"));
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Request restart
@@ -434,7 +416,7 @@ static void restApi() {
// Schedule restart
restartTask.resume(15000);
request->send(202);
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Get network settings
@@ -446,7 +428,7 @@ static void restApi() {
// Send response
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Set network settings
@@ -489,7 +471,7 @@ static void restApi() {
}
});
networkSettingsHandler.setMaxContentLength(1024);
networkSettingsHandler.addMiddleware(&authMiddleware);
networkSettingsHandler.addMiddleware(&apiAuthMiddleware);
// Scan Wi-Fi
@@ -534,7 +516,7 @@ static void restApi() {
// Release scan results
WiFi.scanDelete();
}
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Get settings
@@ -590,7 +572,7 @@ static void restApi() {
// Send response
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Set settings
@@ -727,7 +709,7 @@ static void restApi() {
request->send(response);
});
settingsHandler.setMaxContentLength(3072);
settingsHandler.addMiddleware(&authMiddleware);
settingsHandler.addMiddleware(&apiAuthMiddleware);
// Get sensors list
@@ -756,7 +738,7 @@ static void restApi() {
// Send response
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Get sensor settings
@@ -785,7 +767,7 @@ static void restApi() {
// Send response
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Set sensor settings
@@ -870,7 +852,7 @@ static void restApi() {
request->send(response);
});
sensorSettingsHandler.setMaxContentLength(1024);
sensorSettingsHandler.addMiddleware(&authMiddleware);
sensorSettingsHandler.addMiddleware(&apiAuthMiddleware);
// Get sensor measurements
@@ -899,7 +881,7 @@ static void restApi() {
// Send response
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Set sensor value (JSON)
@@ -955,7 +937,7 @@ static void restApi() {
request->send(response);
});
sensorValueHandler.setMaxContentLength(64);
sensorValueHandler.addMiddleware(&sensorValueAuthMiddleware);
sensorValueHandler.addMiddleware(&apiAuthMiddleware);
// Set sensor value (form)
@@ -1028,16 +1010,16 @@ static void restApi() {
response->setLength();
response->setCode(201);
request->send(response);
}).addMiddleware(&sensorValueAuthMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Regenerate the API token, revoking the old one
webServer->on(AsyncURIMatcher::exact("/api/portal/token/regenerate"), HTTP_POST, [](AsyncWebServerRequest *request) {
// 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 (!regenerateApiToken()) {
if (!refreshApiToken()) {
return request->send(500);
}
@@ -1046,7 +1028,7 @@ static void restApi() {
response->setLength();
response->setCode(201);
request->send(response);
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Get vars
@@ -1058,7 +1040,7 @@ static void restApi() {
// Send response
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Set vars
auto& varsHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
@@ -1092,7 +1074,7 @@ static void restApi() {
}
});
varsHandler.setMaxContentLength(1536);
varsHandler.addMiddleware(&authMiddleware);
varsHandler.addMiddleware(&apiAuthMiddleware);
// Get info
webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) {
@@ -1163,7 +1145,7 @@ static void restApi() {
// Send response
response->setLength();
request->send(response);
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
// Get coredump
webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) {
@@ -1213,7 +1195,7 @@ static void restApi() {
// Send response
request->send(setDownloadFilename(response, "coredump", "bin"));
}).addMiddleware(&authMiddleware);
}).addMiddleware(&apiAuthMiddleware);
}
// Initialize portal
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "使用 mDNS",
"apiToken": {
"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.",
"regenerate": "Regenerate token",
"regenerateConfirm": "The current token will stop working. Continue?"
"note": "用于免密访问 API。可以手动输入 32 个字符的令牌,也可以通过<b>刷新</b>按钮生成。<br />令牌通过请求头 <code>Authorization: Bearer &lt;令牌&gt;</code> 发送。",
"refreshConfirm": "当前令牌将失效。要继续吗?"
}
},
"system": {
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "Use mDNS",
"apiToken": {
"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.",
"regenerate": "Regenerate token",
"regenerateConfirm": "The current token will stop working. Continue?"
"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": {
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "Usa mDNS",
"apiToken": {
"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.",
"regenerate": "Regenerate token",
"regenerateConfirm": "The current token will stop working. Continue?"
"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": {
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "Gebruik mDNS",
"apiToken": {
"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.",
"regenerate": "Regenerate token",
"regenerateConfirm": "The current token will stop working. Continue?"
"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": {
+2 -3
View File
@@ -369,9 +369,8 @@
"mdns": "Использовать mDNS",
"apiToken": {
"title": "API-токен",
"note": "Позволяет устройству передавать значения датчиков без пароля портала: <code>Authorization: Bearer &lt;токен&gt;</code> для <code>POST /api/sensor/value?id=N</code>. Действует только для этого адреса.",
"regenerate": "Сгенерировать новый токен",
"regenerateConfirm": "Текущий токен перестанет работать. Продолжить?"
"note": "Для доступа к API без пароля. Можно задать вручную (32 символа) или сгенерировать кнопкой <b>Обновить</b>.<br />Передавайте в заголовке <code>Authorization: Bearer &lt;токен&gt;</code>.",
"refreshConfirm": "Текущий токен перестанет работать. Продолжить?"
}
},
"system": {
+57 -50
View File
@@ -43,35 +43,38 @@
<div>
<div id="portal-settings-busy" aria-busy="true"></div>
<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>
<span data-i18n>settings.portal.login</span>
<input type="text" name="login" maxlength="12">
<input type="checkbox" name="auth" value="true">
<span data-i18n>settings.portal.auth</span>
</label>
<label>
<span data-i18n>settings.portal.password</span>
<input type="password" name="password" maxlength="32">
<input type="checkbox" name="mdns" value="true">
<span data-i18n>settings.portal.mdns</span>
</label>
</div>
</fieldset>
<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>
<label>
<span data-i18n>settings.portal.apiToken.title</span>
<input type="text" id="portal-api-token" readonly>
<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>
</label>
<button type="button" class="secondary" id="portal-api-token-regenerate" data-i18n>settings.portal.apiToken.regenerate</button>
<br />
</div>
<button type="submit" data-i18n>button.save</button>
</form>
@@ -1192,7 +1195,7 @@
setInputValue("[name='login']", data.portal.login, {}, form);
setInputValue("[name='password']", data.portal.password, {}, 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') {
setInputValue("[name='in_gpio']", data.opentherm.in_gpio < 255 ? data.opentherm.in_gpio : '', {}, form);
@@ -1514,33 +1517,7 @@
}
};
setupSettingsForm('#portal-settings', ['login', 'password']);
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('#portal-settings', ['login', 'password', 'api_token']);
setupSettingsForm('#system-settings', ['ntp.server', 'ntp.timezone']);
setupSettingsForm('#heating-settings');
setupSettingsForm('#dhw-settings');
@@ -1552,6 +1529,36 @@
setupSettingsForm('#extpump-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("#system-settings [name='ntp[timezone]']").value = event.target.value;
});