diff --git a/README.md b/README.md
index 7a24b9c..cf020f6 100644
--- a/README.md
+++ b/README.md
@@ -10,8 +10,9 @@ It provides basic "infrastructure" and "Framework" for specific developments.
- Eases updates by providing OTA update mechanism using update-server URL
- Role based User Management
- Standard Roles
- - Sysadmin (Can administer the system, update, change settings)
- - UserAdmin (Can administer user accounts)
+ - SystemAdmin (Can administer the system, update, change settings)
+ - AccessAdmin (Can administer user accounts, roles, and API access)
+ - NetworkAdmin (Can administer network settings)
- WebUIConnect (Allows logging in to the Web UI)
- Debugger (Allowed to use API Test UI in the Web UI)
- Secure, Role based Rest API for all functions
@@ -33,7 +34,7 @@ It provides basic "infrastructure" and "Framework" for specific developments.
- Users can be assigned zero or more roles
- Allows to interactively calling of the Rest APIs via the web UI
- The corresponding user token is preset with the current user's token by decfault, but it can be overwritten
- - This functionality is only accessible when the user has the role Debugger
+ - This functionality is only accessible when the user has the role AccessAdmin
- Enables secrity configuration of the exposed API functions
- Configuration of logging
- log level
@@ -116,7 +117,7 @@ The firmware in `src/main.cpp` implements the boilerplate as a compact Arduino E
- Configurable API access control where each route can be `PUBLIC` or require one role.
- Public boilerplate APIs: ping, add, and LED brightness.
- LED brightness is persisted in non-volatile memory, applied on boot, and loaded into the Admin UI slider.
-- User management with the standard roles `Sysadmin`, `UserAdmin`, `WebUIConnect`, and `Debugger`.
+- User management with the standard roles `SystemAdmin`, `AccessAdmin`, `NetworkAdmin`, `WebUIConnect`, and `Debugger`.
- Custom role management. System roles are protected and cannot be deleted.
- Active/inactive user accounts with role checkboxes in the Admin UI.
- API security management through a list/detail UI with a role dropdown per API.
@@ -224,7 +225,7 @@ The Admin UI stores HTTPS certificate material so applications built on this boi
To configure the stored certificate material:
-1. Log in as a user with the `Sysadmin` role.
+1. Log in as a user with the `NetworkAdmin` role.
2. Open `Networking` -> `HTTPS Certificate`.
3. Select a certificate file and click `Save certificate`.
4. Use `Load current` to verify what is currently stored.
@@ -305,23 +306,26 @@ Protected APIs and their default roles:
| --- | --- |
| `POST /api/logout` | `WebUIConnect` |
| `GET /api/me` | `WebUIConnect` |
-| `GET /api/apis` | `Sysadmin` |
-| `POST /api/apis` | `Sysadmin` |
-| `GET /api/users` | `UserAdmin` |
-| `POST /api/users` | `UserAdmin` |
+| `GET /api/apis` | `AccessAdmin` |
+| `POST /api/apis` | `AccessAdmin` |
+| `GET /api/users` | `AccessAdmin` |
+| `POST /api/users` | `AccessAdmin` |
| `POST /api/password` | `WebUIConnect` |
-| `GET /api/settings` | `Sysadmin` |
-| `POST /api/settings` | `Sysadmin` |
-| `GET /api/logs` | `Debugger` |
-| `POST /api/logs/clear` | `Debugger` |
-| `GET /api/files` | `Debugger` |
-| `GET /api/files/download` | `Debugger` |
-| `POST /api/factory-reset` | `Sysadmin` |
-| `POST /api/ota/check` | `Sysadmin` |
-| `POST /api/ota/run` | `Sysadmin` |
-| `POST /api/update` | `Sysadmin` |
-| `GET /api/cert` | `Sysadmin` |
-| `POST /api/cert` | `Sysadmin` |
+| `GET /api/settings` | `SystemAdmin` |
+| `POST /api/settings` | `SystemAdmin` |
+| `GET /api/network` | `NetworkAdmin` |
+| `POST /api/network` | `NetworkAdmin` |
+| `GET /api/logs` | `SystemAdmin` |
+| `POST /api/logs/clear` | `SystemAdmin` |
+| `GET /api/files` | `SystemAdmin` |
+| `GET /api/files/download` | `SystemAdmin` |
+| `POST /api/restart` | `SystemAdmin` |
+| `POST /api/factory-reset` | `SystemAdmin` |
+| `POST /api/ota/check` | `SystemAdmin` |
+| `POST /api/ota/run` | `SystemAdmin` |
+| `POST /api/update` | `SystemAdmin` |
+| `GET /api/cert` | `NetworkAdmin` |
+| `POST /api/cert` | `NetworkAdmin` |
Change API security:
diff --git a/data/www/admin.html b/data/www/admin.html
index 94eb290..05cfa82 100644
--- a/data/www/admin.html
+++ b/data/www/admin.html
@@ -2,8 +2,17 @@
- ESP32-C3 Admin
+
+
+
+
+
+
+
+
+
+
@@ -11,8 +20,14 @@
- ESP32-C3 Admin
- Working...
+
+
+
+
UI request...
+
Server event...
+
+
Logout
+
Login
@@ -43,7 +58,7 @@
-
User Overview Refresh New
+
User Overview New
@@ -59,7 +74,7 @@
-
Role Overview Refresh New
+
Role Overview New
@@ -98,7 +113,7 @@
diff --git a/data/www/components/uptime-card.js b/data/www/components/uptime-card.js
index 8cda3a8..8cd36b5 100644
--- a/data/www/components/uptime-card.js
+++ b/data/www/components/uptime-card.js
@@ -1,7 +1,7 @@
class UptimeCard extends HTMLElement {
constructor() {
super();
- this.source = null;
+ this.timer = null;
}
connectedCallback() {
@@ -11,11 +11,16 @@ class UptimeCard extends HTMLElement {
Live uptime
- Server-Sent Events
+ Auto refresh
-- s
Disconnected
`;
window.addEventListener('app:login', event => this.start(event.detail.token));
+ window.addEventListener('app:logout', () => {
+ this.stop();
+ this.setState('Disconnected', false);
+ this.querySelector('#seconds').textContent = '--';
+ });
window.addEventListener('beforeunload', () => this.stop());
if (window.App && window.App.token()) this.start(window.App.token());
}
@@ -31,28 +36,32 @@ class UptimeCard extends HTMLElement {
start(token) {
this.stop();
- if (!token || !window.EventSource) {
+ if (!token) {
this.setState('Unavailable', false);
return;
}
- this.setState('Connecting', false);
- this.source = new EventSource('/api/uptime/events?token=' + encodeURIComponent(token));
- this.source.addEventListener('open', () => this.setState('Connected', true));
- this.source.addEventListener('uptime', event => {
+ this.setState('Loading', false);
+ const load = async () => {
try {
- const json = JSON.parse(event.data);
+ const text = await window.App.serverReq('GET', '/api/uptime');
+ const json = JSON.parse(text);
+ if (!json.success) {
+ this.setState('Unavailable', false);
+ return;
+ }
this.querySelector('#seconds').textContent = json.uptimeSeconds;
this.setState('Connected', true);
} catch (error) {
- this.setState('Invalid event', false);
+ this.setState('Retrying', false);
}
- });
- this.source.addEventListener('error', () => this.setState('Reconnecting', false));
+ };
+ load();
+ this.timer = setInterval(load, 5000);
}
stop() {
- if (this.source) this.source.close();
- this.source = null;
+ if (this.timer) clearInterval(this.timer);
+ this.timer = null;
}
}
diff --git a/data/www/css/app.css b/data/www/css/app.css
index 7ab6940..52a0d2d 100644
--- a/data/www/css/app.css
+++ b/data/www/css/app.css
@@ -20,7 +20,8 @@ pre{white-space:pre-wrap;background:#111;color:#d7ffd7;padding:10px;border-radiu
.pill{display:inline-flex;gap:6px;align-items:center;background:#eef3f6;border-radius:6px;padding:5px 8px;margin:4px 4px 0 0}.pill button{margin:0;padding:3px 7px;background:#b3261e}
.detailTitle{margin:0 0 8px}.inlineCheck{display:flex;gap:8px;align-items:center;margin-top:10px}.inlineCheck input{width:auto}
.toolbar{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:10px}.toolbar button{margin-top:0}.detailActions{display:flex;gap:8px;flex-wrap:wrap}.detailActions button{flex:0 1 auto}
-.fullWidth{grid-column:1/-1}.busyChip{position:fixed;right:14px;top:10px;z-index:10;background:#1261a6;color:white;border-radius:6px;padding:7px 10px;box-shadow:0 2px 10px rgba(0,0,0,.22);font-size:13px}
+.fullWidth{grid-column:1/-1}.activityDock{position:fixed;right:14px;top:10px;z-index:10;display:flex;gap:8px;align-items:flex-start}.activityChips{display:flex;flex-direction:row;gap:6px;align-items:flex-start}.busyChip{background:#1261a6;color:white;border-radius:6px;padding:7px 10px;box-shadow:0 2px 10px rgba(0,0,0,.22);font-size:13px;white-space:nowrap}.serverBusy{background:#607d8b}.logoutBtn{margin:0;background:#607d8b;box-shadow:0 2px 10px rgba(0,0,0,.22);padding:7px 10px;font-size:13px}
.fileList{gap:3px}.fileRow{display:grid;grid-template-columns:28px minmax(0,1fr) auto;gap:8px;align-items:center;background:#eef3f6;border-radius:6px;color:#263238;min-height:30px;padding:3px 8px;box-sizing:border-box}.fileRow[data-path]{cursor:pointer}.fileRow:hover{background:#dbe7ed}.filePath{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:13px}.filePathChip{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:13px;color:#263238;background:#eef3f6;border-radius:6px;padding:6px 8px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%}.fileSize{color:#607d8b;font-size:12px;white-space:nowrap}.iconBtn,.folderIcon{width:24px;height:24px;display:inline-grid;place-items:center}.iconBtn{border:0;border-radius:5px;background:transparent;color:#1261a6;margin:0;padding:0}.iconBtn:hover{background:#c9dbe5}.iconBtn svg,.folderIcon svg{width:16px;height:16px}.folderIcon{color:#607d8b}
.apiRow{display:grid;grid-template-columns:minmax(180px,1fr) minmax(220px,auto);gap:10px;align-items:center;background:#eef3f6;border-radius:6px;padding:7px 9px}.apiPath{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:13px}.apiVerbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.verbBadge{display:inline-flex;gap:6px;align-items:center;background:white;color:#263238;border:1px solid #cfd8dc;border-radius:6px;margin:0;padding:5px 7px;font-size:12px}.verbBadge:hover{background:#dbe7ed}.verbBadge span{color:#607d8b}
.usageGrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin:12px 0}.usageGrid h3{font-size:14px;margin:0 0 6px}.usageList{display:flex;flex-direction:column;gap:4px}.usageItem{display:flex;gap:6px;align-items:center;background:#eef3f6;border-radius:6px;padding:6px 8px;min-height:28px}.usageItem code{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:12px}
+@media (max-width:600px){main{padding:14px}.apiRow{grid-template-columns:1fr;gap:7px;align-items:start}.apiVerbs{justify-content:flex-start}.verbBadge{min-height:30px;box-sizing:border-box;flex:1 1 96px;justify-content:space-between}.activityDock{right:8px;top:8px;gap:6px}.busyChip,.logoutBtn{font-size:12px;padding:6px 8px}}
diff --git a/data/www/icons/icon-192.png b/data/www/icons/icon-192.png
new file mode 100644
index 0000000..64b2bea
Binary files /dev/null and b/data/www/icons/icon-192.png differ
diff --git a/data/www/icons/icon-512.png b/data/www/icons/icon-512.png
new file mode 100644
index 0000000..5fdf32f
Binary files /dev/null and b/data/www/icons/icon-512.png differ
diff --git a/data/www/icons/icon.svg b/data/www/icons/icon.svg
new file mode 100644
index 0000000..27aa803
--- /dev/null
+++ b/data/www/icons/icon.svg
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/data/www/js/app.js b/data/www/js/app.js
index 4711408..48b3185 100644
--- a/data/www/js/app.js
+++ b/data/www/js/app.js
@@ -7,47 +7,103 @@ let selectedRole = '';
let selectedApi = -1;
let currentFilePath = '/';
let filesLoaded = false;
-let busyCount = 0;
+let uiBusyCount = 0;
+let serverBusyCount = 0;
+let currentUserRoles = [];
const el = id => document.getElementById(id);
+const hasCurrentRole = role => currentUserRoles.includes(role);
-function setGlobalBusy(on) {
- busyCount += on ? 1 : -1;
- if (busyCount < 0) busyCount = 0;
- el('busyChip').classList.toggle('hidden', busyCount == 0);
+function setProjectName(projectName) {
+ if (!projectName) return;
+ document.title = projectName;
+ el('appTitle').textContent = projectName;
}
-async function tracked(fn) {
- setGlobalBusy(true);
+async function loadAppInfo() {
+ try {
+ const response = await fetch('/api/app-info');
+ const json = await response.json();
+ setProjectName(json.projectName || '');
+ } catch (error) {}
+}
+
+function setActivityBusy(kind, on) {
+ if (kind == 'server') {
+ serverBusyCount += on ? 1 : -1;
+ if (serverBusyCount < 0) serverBusyCount = 0;
+ el('serverBusyChip').classList.toggle('hidden', serverBusyCount == 0);
+ return;
+ }
+ uiBusyCount += on ? 1 : -1;
+ if (uiBusyCount < 0) uiBusyCount = 0;
+ el('uiBusyChip').classList.toggle('hidden', uiBusyCount == 0);
+}
+
+async function tracked(fn, kind = 'ui') {
+ setActivityBusy(kind, true);
try {
return await fn();
} finally {
- setGlobalBusy(false);
+ setActivityBusy(kind, false);
}
}
-async function apiFetch(url, options) {
- return await tracked(() => fetch(url, options));
+async function apiFetch(url, options, activity = 'ui') {
+ return await tracked(() => fetch(url, options), activity);
}
-async function req(method, url, body) {
+async function req(method, url, body, activity = 'ui') {
const options = {method, headers: {'Content-Type': 'application/json'}};
if (token) options.headers.Authorization = 'Bearer ' + token;
if (body !== undefined && method != 'GET') options.body = JSON.stringify(body);
- const response = await apiFetch(url, options);
+ const response = await apiFetch(url, options, activity);
return await response.text();
}
+async function serverReq(method, url, body) {
+ return await req(method, url, body, 'server');
+}
+
window.App = {
apiFetch,
req,
- token: () => token
+ serverReq,
+ setActivityBusy,
+ token: () => token,
+ roles: () => [...currentUserRoles]
};
+const topLevelTabs = [
+ {id: 'dashboard', role: 'WebUIConnect'},
+ {id: 'access', role: 'AccessAdmin'},
+ {id: 'network', role: 'NetworkAdmin'},
+ {id: 'ops', role: 'SystemAdmin'}
+];
+
+function visibleTopLevelTabs() {
+ return topLevelTabs.filter(tab => hasCurrentRole(tab.role)).map(tab => tab.id);
+}
+
+function applyRoleVisibility() {
+ const visible = visibleTopLevelTabs();
+ topLevelTabs.forEach(tab => {
+ const allowed = visible.includes(tab.id);
+ document.querySelectorAll('[data-tab="' + tab.id + '"]').forEach(button => button.classList.toggle('hidden', !allowed));
+ const panel = el(tab.id);
+ if (panel) panel.classList.toggle('hidden', !allowed);
+ });
+ const topTabs = document.querySelector('#app > .tabs');
+ if (topTabs) topTabs.classList.toggle('hidden', visible.length <= 1);
+ if (visible.length) showTab(visible[0]);
+ return visible;
+}
+
function showTab(id) {
+ if (!visibleTopLevelTabs().includes(id)) return;
document.querySelectorAll('.tab[data-tab]').forEach(button => button.classList.toggle('active', button.dataset.tab == id));
document.querySelectorAll('.panel').forEach(panel => panel.classList.toggle('active', panel.id == id));
- if (id == 'network') loadSettings();
+ if (id == 'network') loadNetworkSettings();
if (id == 'ops' && !filesLoaded) loadFiles('/');
}
@@ -65,12 +121,40 @@ async function doLogin() {
const json = JSON.parse(text);
if (!json.success) return;
token = json.token;
+ currentUserRoles = (json.roles || '').split('|').filter(Boolean);
el('loginPanel').classList.add('hidden');
el('app').classList.remove('hidden');
- window.dispatchEvent(new CustomEvent('app:login', {detail: {token}}));
- loadSettings();
- loadAccess();
- loadFiles('/');
+ el('logoutBtn').classList.remove('hidden');
+ window.dispatchEvent(new CustomEvent('app:login', {detail: {token, roles: currentUserRoles}}));
+ const visible = applyRoleVisibility();
+ if (hasCurrentRole('SystemAdmin')) loadSettings();
+ if (hasCurrentRole('AccessAdmin')) loadAccess();
+ if (hasCurrentRole('NetworkAdmin')) loadNetworkSettings();
+ if (visible.includes('ops')) loadFiles('/');
+}
+
+async function doLogout() {
+ if (token) {
+ try {
+ await req('POST', '/api/logout');
+ } catch (error) {}
+ }
+ token = '';
+ currentUserRoles = [];
+ roles = [];
+ users = [];
+ apis = [];
+ selectedUser = '';
+ selectedRole = '';
+ selectedApi = -1;
+ filesLoaded = false;
+ currentFilePath = '/';
+ el('app').classList.add('hidden');
+ el('loginPanel').classList.remove('hidden');
+ el('logoutBtn').classList.add('hidden');
+ el('pass').value = '';
+ el('loginOut').textContent = '';
+ window.dispatchEvent(new CustomEvent('app:logout'));
}
function esc(value) {
@@ -443,6 +527,16 @@ async function factoryResetDevice() {
el('maintOut').textContent = await req('POST', '/api/factory-reset');
}
+async function restartDevice() {
+ if (!confirm('Restart this device now?')) return;
+ setBusy('restartDevice', true, 'Restarting');
+ try {
+ el('maintOut').textContent = await req('POST', '/api/restart');
+ } finally {
+ setBusy('restartDevice', false, 'Restart');
+ }
+}
+
async function loadLogs() {
const text = await req('GET', '/api/logs');
try {
@@ -472,12 +566,20 @@ async function loadSettings() {
const json = JSON.parse(text);
if (!json.success) return;
const settings = json.settings;
- const projectName = settings.projectName || 'ESP32-C3';
- el('appTitle').textContent = projectName + ' Admin';
- document.title = projectName + ' Admin';
+ setProjectName(settings.projectName);
el('logLevel').value = settings.logLevel;
el('logMax').value = settings.maxLogBytes;
el('upd').value = settings.updateUrl;
+ window.dispatchEvent(new CustomEvent('app:settings-loaded', {detail: {settings}}));
+}
+
+async function loadNetworkSettings() {
+ const text = await req('GET', '/api/network');
+ el('networkOut').textContent = text;
+ const json = JSON.parse(text);
+ if (!json.success) return;
+ const settings = json.settings;
+ setProjectName(settings.projectName);
el('netHost').value = settings.hostname || '';
el('netHost').placeholder = settings.defaultHostname || 'Default host name';
el('netDhcp').value = String(settings.dhcp !== false);
@@ -488,7 +590,6 @@ async function loadSettings() {
el('netDns2').value = settings.dns2 || '';
el('netCurrent').textContent = 'Current IP: ' + (settings.currentIp || 'not connected');
syncNetworkMode();
- window.dispatchEvent(new CustomEvent('app:settings-loaded', {detail: {settings}}));
}
async function saveSettings() {
@@ -499,9 +600,9 @@ async function saveNetwork() {
setBusy('networkSaveBtn', true, 'Saving');
try {
const body = {hostname: el('netHost').value, dhcp: el('netDhcp').value == 'true', ip: el('netIp').value, gateway: el('netGateway').value, subnet: el('netSubnet').value, dns1: el('netDns1').value, dns2: el('netDns2').value};
- const text = await req('POST', '/api/settings', body);
+ const text = await req('POST', '/api/network', body);
el('networkOut').textContent = text + '\nNetwork changes apply on the next WiFi reconnect or reboot.';
- if (JSON.parse(text).success) await loadSettings();
+ if (JSON.parse(text).success) await loadNetworkSettings();
} catch (error) {
el('networkOut').textContent = 'Network save failed: ' + error.message;
} finally {
@@ -545,13 +646,12 @@ async function runOta() {
function bindEvents() {
el('loginBtn').addEventListener('click', doLogin);
+ el('logoutBtn').addEventListener('click', doLogout);
document.querySelectorAll('.tab[data-tab]').forEach(button => button.addEventListener('click', () => showTab(button.dataset.tab)));
document.querySelectorAll('.subtab').forEach(button => button.addEventListener('click', () => showAccessTab(button.dataset.subtab)));
- el('usersRefresh').addEventListener('click', loadUsers);
el('userNew').addEventListener('click', newUserRecord);
el('userBack').addEventListener('click', showUserOverview);
el('userSave').addEventListener('click', saveSelectedUser);
- el('rolesRefresh').addEventListener('click', loadRoles);
el('roleNew').addEventListener('click', newRoleRecord);
el('roleBack').addEventListener('click', showRoleOverview);
el('roleSave').addEventListener('click', addRole);
@@ -582,6 +682,7 @@ function bindEvents() {
el('otaRun').addEventListener('click', runOta);
el('configDownload').addEventListener('click', downloadConfig);
el('restoreConfigBtn').addEventListener('click', restoreConfig);
+ el('restartDevice').addEventListener('click', restartDevice);
el('factoryReset').addEventListener('click', factoryResetDevice);
el('fileList').addEventListener('click', event => {
const button = event.target.closest('[data-download]');
@@ -596,4 +697,5 @@ function bindEvents() {
el('logsClear').addEventListener('click', clearLogs);
}
+loadAppInfo();
bindEvents();
diff --git a/data/www/js/pwa.js b/data/www/js/pwa.js
new file mode 100644
index 0000000..a29f166
--- /dev/null
+++ b/data/www/js/pwa.js
@@ -0,0 +1,9 @@
+(function () {
+ if (!('serviceWorker' in navigator)) return;
+
+ window.addEventListener('load', function () {
+ navigator.serviceWorker.register('/service-worker.js').catch(function (error) {
+ console.warn('PWA service worker registration failed:', error);
+ });
+ });
+})();
diff --git a/data/www/js/setup.js b/data/www/js/setup.js
index 2ed17e5..6cfd0ba 100644
--- a/data/www/js/setup.js
+++ b/data/www/js/setup.js
@@ -4,6 +4,16 @@ const admin = document.getElementById('admin');
const adminPass = document.getElementById('adminPass');
const out = document.getElementById('out');
+async function loadAppInfo() {
+ try {
+ const response = await fetch('/api/app-info');
+ const json = await response.json();
+ const projectName = json.projectName || '';
+ document.title = projectName;
+ document.getElementById('setupTitle').textContent = projectName;
+ } catch (error) {}
+}
+
async function scan() {
const response = await fetch('/api/wifi/scan');
const json = await response.json();
@@ -17,4 +27,5 @@ async function save() {
}
document.getElementById('saveSetup').addEventListener('click', save);
+loadAppInfo();
scan();
diff --git a/data/www/manifest.webmanifest b/data/www/manifest.webmanifest
new file mode 100644
index 0000000..d31d22e
--- /dev/null
+++ b/data/www/manifest.webmanifest
@@ -0,0 +1,32 @@
+{
+ "name": "TSL-Embedded Admin",
+ "short_name": "TSL Admin",
+ "description": "Installable administration app for the embedded ESP32-C3 device.",
+ "id": "/",
+ "start_url": "/",
+ "scope": "/",
+ "display": "standalone",
+ "orientation": "any",
+ "background_color": "#f5f7f8",
+ "theme_color": "#1261a6",
+ "icons": [
+ {
+ "src": "/icons/icon.svg",
+ "sizes": "any",
+ "type": "image/svg+xml",
+ "purpose": "any maskable"
+ },
+ {
+ "src": "/icons/icon-192.png",
+ "sizes": "192x192",
+ "type": "image/png",
+ "purpose": "any maskable"
+ },
+ {
+ "src": "/icons/icon-512.png",
+ "sizes": "512x512",
+ "type": "image/png",
+ "purpose": "any maskable"
+ }
+ ]
+}
diff --git a/data/www/service-worker.js b/data/www/service-worker.js
new file mode 100644
index 0000000..274919c
--- /dev/null
+++ b/data/www/service-worker.js
@@ -0,0 +1,55 @@
+const CACHE_NAME = 'tsl-embedded-pwa-v12';
+
+const APP_SHELL = [
+ '/',
+ '/admin.html',
+ '/setup.html',
+ '/manifest.webmanifest',
+ '/css/app.css',
+ '/css/setup.css',
+ '/js/app.js',
+ '/js/setup.js',
+ '/js/pwa.js',
+ '/components/status-card.js',
+ '/components/uptime-card.js',
+ '/components/led-card.js',
+ '/components/add-card.js',
+ '/icons/icon.svg',
+ '/icons/icon-192.png',
+ '/icons/icon-512.png'
+];
+
+self.addEventListener('install', event => {
+ event.waitUntil(
+ caches.open(CACHE_NAME)
+ .then(cache => cache.addAll(APP_SHELL))
+ .then(() => self.skipWaiting())
+ );
+});
+
+self.addEventListener('activate', event => {
+ event.waitUntil(
+ caches.keys()
+ .then(names => Promise.all(names.filter(name => name !== CACHE_NAME).map(name => caches.delete(name))))
+ .then(() => self.clients.claim())
+ );
+});
+
+self.addEventListener('fetch', event => {
+ const requestUrl = new URL(event.request.url);
+ if (requestUrl.origin !== location.origin || requestUrl.pathname.startsWith('/api/')) return;
+
+ if (event.request.mode === 'navigate') {
+ event.respondWith(fetch(event.request).catch(() => caches.match('/admin.html')));
+ return;
+ }
+
+ event.respondWith(
+ caches.match(event.request).then(cached => cached || fetch(event.request).then(response => {
+ if (!response || response.status !== 200 || event.request.method !== 'GET') return response;
+ const copy = response.clone();
+ caches.open(CACHE_NAME).then(cache => cache.put(event.request, copy));
+ return response;
+ }))
+ );
+});
diff --git a/data/www/setup.html b/data/www/setup.html
index f869408..070ea32 100644
--- a/data/www/setup.html
+++ b/data/www/setup.html
@@ -2,12 +2,12 @@
- ESP32-C3 first-run setup
+
- ESP32-C3 first-run setup
+
Network and admin setup
diff --git a/include/app.h b/include/app.h
index e9945e6..165f11c 100644
--- a/include/app.h
+++ b/include/app.h
@@ -158,10 +158,13 @@ void handleApisGet();
void handleApisPost();
void handleSettingsGet();
void handleSettingsPost();
+void handleNetworkSettingsGet();
+void handleNetworkSettingsPost();
void handleLogsGet();
void handleLogsClear();
void handleFilesList();
void handleFileDownload();
+void handleRestart();
void handleFactoryReset();
void handleConfigExport();
void handleConfigImport();
diff --git a/include/custom_api.h b/include/custom_api.h
index 8dd766e..299241b 100644
--- a/include/custom_api.h
+++ b/include/custom_api.h
@@ -1,5 +1,6 @@
#pragma once
+void handleAppInfo();
void handlePing();
void handleAdd();
void handleLed();
diff --git a/src/config/api_definitions.cpp b/src/config/api_definitions.cpp
index 712d06f..6be3d77 100644
--- a/src/config/api_definitions.cpp
+++ b/src/config/api_definitions.cpp
@@ -1,33 +1,36 @@
#include "app.h"
ApiDef apiDefs[] = {
- {"/api/wifi/scan", "GET", "Sysadmin", false, handleWifiScan, nullptr},
- {"/api/setup", "POST", "Sysadmin", false, handleSetupSubmit, nullptr},
+ {"/api/wifi/scan", "GET", "SystemAdmin", false, handleWifiScan, nullptr},
+ {"/api/setup", "POST", "SystemAdmin", false, handleSetupSubmit, nullptr},
{"/api/login", "POST", "", true, handleLogin, nullptr},
{"/api/logout", "POST", "WebUIConnect", false, handleLogout, nullptr},
{"/api/me", "GET", "WebUIConnect", false, handleMe, nullptr},
- {"/api/apis", "GET", "Sysadmin", false, handleApisGet, nullptr},
- {"/api/apis", "POST", "Sysadmin", false, handleApisPost, nullptr},
- {"/api/users", "GET", "UserAdmin", false, handleUsersGet, nullptr},
- {"/api/users", "POST", "UserAdmin", false, handleUsersPost, nullptr},
- {"/api/roles", "GET", "UserAdmin", false, handleRolesGet, nullptr},
- {"/api/roles", "POST", "UserAdmin", false, handleRolesPost, nullptr},
- {"/api/roles", "DELETE", "UserAdmin", false, handleRolesDelete, nullptr},
+ {"/api/apis", "GET", "AccessAdmin", false, handleApisGet, nullptr},
+ {"/api/apis", "POST", "AccessAdmin", false, handleApisPost, nullptr},
+ {"/api/users", "GET", "AccessAdmin", false, handleUsersGet, nullptr},
+ {"/api/users", "POST", "AccessAdmin", false, handleUsersPost, nullptr},
+ {"/api/roles", "GET", "AccessAdmin", false, handleRolesGet, nullptr},
+ {"/api/roles", "POST", "AccessAdmin", false, handleRolesPost, nullptr},
+ {"/api/roles", "DELETE", "AccessAdmin", false, handleRolesDelete, nullptr},
{"/api/password", "POST", "WebUIConnect", false, handlePassword, nullptr},
- {"/api/settings", "GET", "Sysadmin", false, handleSettingsGet, nullptr},
- {"/api/settings", "POST", "Sysadmin", false, handleSettingsPost, nullptr},
- {"/api/logs", "GET", "Debugger", false, handleLogsGet, nullptr},
- {"/api/logs/clear", "POST", "Debugger", false, handleLogsClear, nullptr},
- {"/api/files", "GET", "Debugger", false, handleFilesList, nullptr},
- {"/api/files/download", "GET", "Debugger", false, handleFileDownload, nullptr},
- {"/api/factory-reset", "POST", "Sysadmin", false, handleFactoryReset, nullptr},
- {"/api/config/export", "GET", "Sysadmin", false, handleConfigExport, nullptr},
- {"/api/config/import", "POST", "Sysadmin", false, handleConfigImport, nullptr},
- {"/api/ota/check", "POST", "Sysadmin", false, handleOtaCheck, nullptr},
- {"/api/ota/run", "POST", "Sysadmin", false, handleOtaRun, nullptr},
- {"/api/update", "POST", "Sysadmin", false, handleUpdateUploadDone, handleUpdateUploadChunk},
- {"/api/cert", "GET", "Sysadmin", false, handleCertGet, nullptr},
- {"/api/cert", "POST", "Sysadmin", false, handleCertPost, nullptr},
+ {"/api/settings", "GET", "SystemAdmin", false, handleSettingsGet, nullptr},
+ {"/api/settings", "POST", "SystemAdmin", false, handleSettingsPost, nullptr},
+ {"/api/network", "GET", "NetworkAdmin", false, handleNetworkSettingsGet, nullptr},
+ {"/api/network", "POST", "NetworkAdmin", false, handleNetworkSettingsPost, nullptr},
+ {"/api/logs", "GET", "SystemAdmin", false, handleLogsGet, nullptr},
+ {"/api/logs/clear", "POST", "SystemAdmin", false, handleLogsClear, nullptr},
+ {"/api/files", "GET", "SystemAdmin", false, handleFilesList, nullptr},
+ {"/api/files/download", "GET", "SystemAdmin", false, handleFileDownload, nullptr},
+ {"/api/restart", "POST", "SystemAdmin", false, handleRestart, nullptr},
+ {"/api/factory-reset", "POST", "SystemAdmin", false, handleFactoryReset, nullptr},
+ {"/api/config/export", "GET", "SystemAdmin", false, handleConfigExport, nullptr},
+ {"/api/config/import", "POST", "SystemAdmin", false, handleConfigImport, nullptr},
+ {"/api/ota/check", "POST", "SystemAdmin", false, handleOtaCheck, nullptr},
+ {"/api/ota/run", "POST", "SystemAdmin", false, handleOtaRun, nullptr},
+ {"/api/update", "POST", "SystemAdmin", false, handleUpdateUploadDone, handleUpdateUploadChunk},
+ {"/api/cert", "GET", "NetworkAdmin", false, handleCertGet, nullptr},
+ {"/api/cert", "POST", "NetworkAdmin", false, handleCertPost, nullptr},
};
const size_t API_DEF_COUNT = sizeof(apiDefs) / sizeof(apiDefs[0]);
diff --git a/src/config/api_definitions_custom.cpp b/src/config/api_definitions_custom.cpp
index b93fe57..7a829fe 100644
--- a/src/config/api_definitions_custom.cpp
+++ b/src/config/api_definitions_custom.cpp
@@ -2,6 +2,7 @@
#include "custom_api.h"
ApiDef customApiDefs[] = {
+ {"/api/app-info", "GET", "", true, handleAppInfo, nullptr},
{"/api/ping", "GET", "", true, handlePing, nullptr},
{"/api/add", "POST", "", true, handleAdd, nullptr},
{"/api/led", "POST", "", true, handleLed, nullptr},
diff --git a/src/core/auth.cpp b/src/core/auth.cpp
index 75218cb..d53bc40 100644
--- a/src/core/auth.cpp
+++ b/src/core/auth.cpp
@@ -1,12 +1,19 @@
#include "app.h"
+static String canonicalRoleName(const String &role) {
+ if (role == "Sysadmin") return "SystemAdmin";
+ if (role == "UserAdmin") return "AccessAdmin";
+ return role;
+}
+
bool hasRole(const String &roles, const String &role) {
- if (role.length() == 0) return true;
+ String required = canonicalRoleName(role);
+ if (required.length() == 0) return true;
int start = 0;
while (start <= (int)roles.length()) {
int end = roles.indexOf('|', start);
if (end < 0) end = roles.length();
- if (roles.substring(start, end) == role) return true;
+ if (canonicalRoleName(roles.substring(start, end)) == required) return true;
start = end + 1;
}
return false;
@@ -39,15 +46,16 @@ String cleanRoles(const String &roles) {
}
bool isKnownRole(const String &role) {
- return role == "PUBLIC" || hasRole(allRoles(), role);
+ return role == "PUBLIC" || hasRole(allRoles(), canonicalRoleName(role));
}
bool isSystemRole(const String &role) {
- return role == "Sysadmin" || role == "UserAdmin" || role == "WebUIConnect" || role == "Debugger";
+ String canonical = canonicalRoleName(role);
+ return canonical == "SystemAdmin" || canonical == "AccessAdmin" || canonical == "NetworkAdmin" || canonical == "WebUIConnect" || canonical == "Debugger";
}
String allRoles() {
- String roles = "Sysadmin|UserAdmin|WebUIConnect|Debugger";
+ String roles = "SystemAdmin|AccessAdmin|NetworkAdmin|WebUIConnect|Debugger";
String custom = prefString("roles", "");
int start = 0;
while (start <= (int)custom.length()) {
@@ -129,7 +137,7 @@ bool deleteCustomRole(const String &role) {
}
static String defaultUsers() {
- return String(DEFAULT_ADMIN) + "\t" + passwordHash("") + "\tSysadmin|UserAdmin|WebUIConnect|Debugger\t1\n";
+ return String(DEFAULT_ADMIN) + "\t" + passwordHash("") + "\tSystemAdmin|AccessAdmin|NetworkAdmin|WebUIConnect|Debugger\t1\n";
}
static String usersText() {
@@ -247,7 +255,7 @@ ApiDef *findApi(const String &path, const String &method) {
String configuredRole(ApiDef *api) {
if (!api) return "";
String key = apiKey(api->path, api->method);
- return prefString(key.c_str(), api->publicByDefault ? "PUBLIC" : api->defaultRole);
+ return canonicalRoleName(prefString(key.c_str(), api->publicByDefault ? "PUBLIC" : api->defaultRole));
}
static String requestMethodName() {
diff --git a/src/handlers/handlers_admin.cpp b/src/handlers/handlers_admin.cpp
index c49f223..1547e03 100644
--- a/src/handlers/handlers_admin.cpp
+++ b/src/handlers/handlers_admin.cpp
@@ -26,11 +26,35 @@ static bool validIpValue(const String &value) {
void handleSettingsGet() {
if (!authorize()) return;
- String out = "\"settings\":{\"projectName\":\"" + jsonEscape(PROJECT_NAME_VALUE) + "\",\"logLevel\":" + String(currentLogLevel) + ",\"maxLogBytes\":" + String(maxLogBytes) + ",\"updateUrl\":\"" + jsonEscape(updateUrl) + "\",\"ledInverted\":" + String(ledInverted ? "true" : "false") + ",\"ledBrightness\":" + String(ledBrightness) + "," + networkSettingsJson(true) + "}";
+ String out = "\"settings\":{\"projectName\":\"" + jsonEscape(PROJECT_NAME_VALUE) + "\",\"logLevel\":" + String(currentLogLevel) + ",\"maxLogBytes\":" + String(maxLogBytes) + ",\"updateUrl\":\"" + jsonEscape(updateUrl) + "\",\"ledInverted\":" + String(ledInverted ? "true" : "false") + ",\"ledBrightness\":" + String(ledBrightness) + "}";
sendJson(200, jsonOk(out));
}
void handleSettingsPost() {
+ if (!authorize()) return;
+ String body = requestBody();
+ currentLogLevel = (LogLevel)constrain(jsonIntValue(body, "logLevel", currentLogLevel), 0, 4);
+ maxLogBytes = constrain(jsonIntValue(body, "maxLogBytes", maxLogBytes), 4096, 128 * 1024);
+ ledInverted = jsonBoolValue(body, "ledInverted", ledInverted);
+ ledBrightness = constrain(jsonIntValue(body, "ledBrightness", ledBrightness), 0, 100);
+ updateUrl = jsonStringValue(body, "updateUrl", updateUrl);
+ prefs.putUChar("logLevel", currentLogLevel);
+ prefs.putUInt("logMax", maxLogBytes);
+ prefs.putBool("ledInv", ledInverted);
+ prefs.putUChar("ledBright", ledBrightness);
+ prefs.putString("updateUrl", updateUrl);
+ applyLed();
+ appendLog(LOG_SECURITY_AUDIT, "system settings updated");
+ sendJson(200, jsonOk());
+}
+
+void handleNetworkSettingsGet() {
+ if (!authorize()) return;
+ String out = "\"settings\":{\"projectName\":\"" + jsonEscape(PROJECT_NAME_VALUE) + "\"," + networkSettingsJson(true) + "}";
+ sendJson(200, jsonOk(out));
+}
+
+void handleNetworkSettingsPost() {
if (!authorize()) return;
String body = requestBody();
String nextHostname = jsonStringValue(body, "hostname", networkHostname);
@@ -52,11 +76,6 @@ void handleSettingsPost() {
if (nextDns1.length() && !validIpValue(nextDns1)) return sendJson(400, jsonError("DNS 1 must be a valid IPv4 address"));
if (nextDns2.length() && !validIpValue(nextDns2)) return sendJson(400, jsonError("DNS 2 must be a valid IPv4 address"));
}
- currentLogLevel = (LogLevel)constrain(jsonIntValue(body, "logLevel", currentLogLevel), 0, 4);
- maxLogBytes = constrain(jsonIntValue(body, "maxLogBytes", maxLogBytes), 4096, 128 * 1024);
- ledInverted = jsonBoolValue(body, "ledInverted", ledInverted);
- ledBrightness = constrain(jsonIntValue(body, "ledBrightness", ledBrightness), 0, 100);
- updateUrl = jsonStringValue(body, "updateUrl", updateUrl);
networkHostname = nextHostname;
networkDhcp = nextDhcp;
networkIp = nextIp;
@@ -64,11 +83,6 @@ void handleSettingsPost() {
networkSubnet = nextSubnet;
networkDns1 = nextDns1;
networkDns2 = nextDns2;
- prefs.putUChar("logLevel", currentLogLevel);
- prefs.putUInt("logMax", maxLogBytes);
- prefs.putBool("ledInv", ledInverted);
- prefs.putUChar("ledBright", ledBrightness);
- prefs.putString("updateUrl", updateUrl);
prefs.putString("netHost", networkHostname);
prefs.putBool("netDhcp", networkDhcp);
prefs.putString("netIp", networkIp);
@@ -76,8 +90,7 @@ void handleSettingsPost() {
prefs.putString("netMask", networkSubnet);
prefs.putString("netDns1", networkDns1);
prefs.putString("netDns2", networkDns2);
- applyLed();
- appendLog(LOG_SECURITY_AUDIT, "settings updated");
+ appendLog(LOG_SECURITY_AUDIT, "network settings updated");
sendJson(200, jsonOk());
}
@@ -163,6 +176,14 @@ void handleFileDownload() {
file.close();
}
+void handleRestart() {
+ if (!authorize()) return;
+ appendLog(LOG_SECURITY_AUDIT, "restart requested");
+ sendJson(200, jsonOk("\"restart\":true"));
+ delay(500);
+ ESP.restart();
+}
+
void handleFactoryReset() {
if (!authorize()) return;
factoryReset();
@@ -353,11 +374,11 @@ void handleConfigImport() {
userCount++;
}
if (!userCount) return sendJson(400, jsonError("Backup must contain at least one user"));
- bool hasActiveSysadmin = false;
+ bool hasActiveSystemAdmin = false;
for (size_t i = 0; i < userCount; i++) {
- if (users[i].active && hasRole(users[i].roles, "Sysadmin")) hasActiveSysadmin = true;
+ if (users[i].active && hasRole(users[i].roles, "SystemAdmin")) hasActiveSystemAdmin = true;
}
- if (!hasActiveSysadmin) return sendJson(400, jsonError("Backup must contain an active Sysadmin user"));
+ if (!hasActiveSystemAdmin) return sendJson(400, jsonError("Backup must contain an active SystemAdmin user"));
saveUsers(users, userCount);
currentLogLevel = (LogLevel)constrain(jsonIntValue(body, "logLevel", currentLogLevel), 0, 4);
diff --git a/src/handlers/handlers_custom_api.cpp b/src/handlers/handlers_custom_api.cpp
index 7c87e7c..a879a5f 100644
--- a/src/handlers/handlers_custom_api.cpp
+++ b/src/handlers/handlers_custom_api.cpp
@@ -5,6 +5,10 @@ static String uptimeJsonFields() {
return "\"uptimeSeconds\":" + String(millis() / 1000);
}
+void handleAppInfo() {
+ sendJson(200, jsonOk("\"projectName\":\"" + jsonEscape(PROJECT_NAME_VALUE) + "\",\"version\":\"" + APP_VERSION + "\""));
+}
+
void handlePing() {
if (!authorize()) return;
sendJson(200, jsonOk("\"uptimeMs\":" + String(millis()) + ",\"version\":\"" + APP_VERSION + "\",\"name\":\"" + jsonEscape(deviceName()) + "\",\"ip\":\"" + WiFi.localIP().toString() + "\""));
@@ -34,7 +38,7 @@ void handleUptime() {
void handleUptimeEvents() {
if (!authorize()) return;
- String payload = "retry: 1000\n";
+ String payload = "retry: 3000\n";
payload += "event: uptime\n";
payload += "data: {" + uptimeJsonFields() + "}\n\n";
server.sendHeader("Cache-Control", "no-store");
diff --git a/src/handlers/handlers_setup.cpp b/src/handlers/handlers_setup.cpp
index b854a70..25fe01c 100644
--- a/src/handlers/handlers_setup.cpp
+++ b/src/handlers/handlers_setup.cpp
@@ -23,7 +23,7 @@ void handleSetupSubmit() {
if (!validName(admin)) return sendJson(400, jsonError("Admin username is invalid"));
prefs.putString("wifiSsid", ssid);
prefs.putString("wifiPass", wifiPass);
- User u{admin, passwordHash(adminPass), "Sysadmin|UserAdmin|WebUIConnect|Debugger", true};
+ User u{admin, passwordHash(adminPass), "SystemAdmin|AccessAdmin|NetworkAdmin|WebUIConnect|Debugger", true};
saveUsers(&u, 1);
prefs.putBool("configured", true);
appendLog(LOG_SECURITY_AUDIT, "initial setup saved");
diff --git a/src/web/routes.cpp b/src/web/routes.cpp
index 6cfe442..d0894ac 100644
--- a/src/web/routes.cpp
+++ b/src/web/routes.cpp
@@ -1,5 +1,7 @@
#include "app.h"
+#include
+
static HTTPMethod httpMethod(const char *method) {
if (strcmp(method, "GET") == 0) return HTTP_GET;
if (strcmp(method, "POST") == 0) return HTTP_POST;
@@ -42,6 +44,22 @@ static String requestMethodName() {
}
}
+static void handleFallbackRequest() {
+ if (setupMode) {
+ if (server.uri().startsWith("/api/")) {
+ appendLog(LOG_SECURITY_AUDIT, "undefined URL or method " + requestMethodName() + " " + server.uri());
+ sendJson(404, jsonError("Not found"));
+ } else if (!handleHtmlFileRequest()) {
+ redirectToSetupPage();
+ }
+ } else if (server.method() == HTTP_GET && !server.uri().startsWith("/api/")) {
+ if (!handleHtmlFileRequest()) handleAdminPage();
+ } else {
+ appendLog(LOG_SECURITY_AUDIT, "undefined URL or method " + requestMethodName() + " " + server.uri());
+ sendJson(404, jsonError("Not found"));
+ }
+}
+
void registerRoutes() {
static const char *headers[] = {"Authorization", "X-Auth-Token"};
server.collectHeaders(headers, 2);
@@ -58,19 +76,6 @@ void registerRoutes() {
registerApiRoutes();
- server.onNotFound([]() {
- if (setupMode) {
- if (server.uri().startsWith("/api/")) {
- appendLog(LOG_SECURITY_AUDIT, "undefined URL or method " + requestMethodName() + " " + server.uri());
- sendJson(404, jsonError("Not found"));
- } else if (!handleHtmlFileRequest()) {
- redirectToSetupPage();
- }
- } else if (server.method() == HTTP_GET && !server.uri().startsWith("/api/")) {
- if (!handleHtmlFileRequest()) handleAdminPage();
- } else {
- appendLog(LOG_SECURITY_AUDIT, "undefined URL or method " + requestMethodName() + " " + server.uri());
- sendJson(404, jsonError("Not found"));
- }
- });
+ server.on(UriGlob("*"), HTTP_ANY, handleFallbackRequest);
+ server.onNotFound(handleFallbackRequest);
}
diff --git a/src/web/ui.cpp b/src/web/ui.cpp
index dd95acd..93346eb 100644
--- a/src/web/ui.cpp
+++ b/src/web/ui.cpp
@@ -10,6 +10,7 @@ static String contentTypeFor(const String &path) {
if (path.endsWith(".html")) return "text/html";
if (path.endsWith(".css")) return "text/css";
if (path.endsWith(".js") || path.endsWith(".mjs")) return "text/javascript";
+ if (path.endsWith(".webmanifest")) return "application/manifest+json";
if (path.endsWith(".json")) return "application/json";
if (path.endsWith(".svg")) return "image/svg+xml";
if (path.endsWith(".png")) return "image/png";
@@ -26,7 +27,7 @@ static bool serveWwwFile(const String &path) {
if (file) file.close();
return false;
}
- server.sendHeader("Cache-Control", path.endsWith(".html") ? "no-store" : "max-age=3600");
+ server.sendHeader("Cache-Control", (path.endsWith(".html") || path == "/service-worker.js") ? "no-store" : "max-age=3600");
server.streamFile(file, contentTypeFor(path));
file.close();
return true;