The controller checks every route against the signed-in user's role, with levels none, view, control and edit per area. Guests get the permissions of a built-in guest role. Auth stays off until the first user exists; LED_ADMIN_USER and LED_ADMIN_PASSWORD create the first admin. Sessions are cookies, passwords are PBKDF2-SHA256, and logins lock per username after five failures. The simulator's WebSocket checks the view permission at handshake and per frame; /ws needs devices control. The web UI gets a sign-in button, a sign-in prompt on refused changes, and a users and roles screen. Also: the device build gets the bridge include path and forward type it was missing, Dockerfile.sim runs non-root, and Dockerfile.prod with docker-compose.prod.yml runs the controller on an internal network behind Caddy for HTTPS. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
425 lines
19 KiB
JavaScript
425 lines
19 KiB
JavaScript
// Sign-in, users and roles. Loaded before the other scripts, so every request the page makes goes
|
|
// through the permission handling below: a 401 asks for a sign-in and then retries, a 403 shows a notice.
|
|
(function () {
|
|
'use strict';
|
|
|
|
var AREAS = ['presets', 'sequences', 'zones', 'groups', 'devices', 'outputs', 'patterns', 'sim', 'settings', 'users'];
|
|
var AREA_LABELS = {
|
|
presets: 'Presets', sequences: 'Sequences', zones: 'Zones & profiles', groups: 'Groups', devices: 'Devices',
|
|
outputs: 'Outputs', patterns: 'Patterns & palettes', sim: 'Simulator', settings: 'Settings & updates', users: 'Users & roles',
|
|
};
|
|
var LEVELS = ['none', 'view', 'control', 'edit'];
|
|
var state = { enabled: false, user: '', role: '', perms: {} };
|
|
var origFetch = window.fetch.bind(window);
|
|
var pendingLogin = null;
|
|
|
|
function esc(s) {
|
|
return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
|
|
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
|
|
});
|
|
}
|
|
|
|
function isAuthUrl(url) {
|
|
return String(url).indexOf('/auth') === 0;
|
|
}
|
|
|
|
function can(area, level) {
|
|
return !state.enabled || (state.perms[area] || 0) >= level;
|
|
}
|
|
|
|
function errorText(res) {
|
|
return res.json().then(function (j) { return j.error || ('Error ' + res.status); }, function () { return 'Error ' + res.status; });
|
|
}
|
|
|
|
/* ------------------------------------------------------------ styles and small UI */
|
|
|
|
function injectStyle() {
|
|
var st = document.createElement('style');
|
|
st.textContent = [
|
|
'[data-need][hidden]{display:none !important}',
|
|
'.auth-toast{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);background:#3a1d1d;color:#fff;padding:10px 16px;border-radius:8px;z-index:10000;box-shadow:0 4px 16px rgba(0,0,0,.35);max-width:90vw;font-size:14px}',
|
|
'.auth-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;z-index:9000;padding:16px}',
|
|
'.auth-dialog{background:var(--panel,#1e1e24);color:var(--text,#eee);border-radius:10px;padding:18px;min-width:280px;max-width:900px;width:100%;max-height:90vh;overflow:auto;box-shadow:0 8px 32px rgba(0,0,0,.5)}',
|
|
'.auth-dialog h3{margin:0 0 12px}',
|
|
'.auth-dialog label{display:block;margin:8px 0 4px;font-size:13px;opacity:.85}',
|
|
'.auth-dialog input,.auth-dialog select{width:100%;box-sizing:border-box;padding:6px 8px;border-radius:6px;border:1px solid #555;background:#111;color:#eee}',
|
|
'.auth-dialog table{border-collapse:collapse;width:100%;margin:8px 0}',
|
|
'.auth-dialog th,.auth-dialog td{padding:6px 8px;border-bottom:1px solid #333;text-align:left;font-size:13px}',
|
|
'.auth-dialog .auth-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}',
|
|
'.auth-dialog .auth-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px;flex-wrap:wrap}',
|
|
'.auth-dialog button{padding:6px 12px;border-radius:6px;border:1px solid #555;background:#2a2a33;color:#eee;cursor:pointer}',
|
|
'.auth-dialog button.primary{background:#2d6cdf;border-color:#2d6cdf}',
|
|
'.auth-dialog button.danger{background:#7a2323;border-color:#7a2323}',
|
|
'.auth-err{color:#ff8a8a;font-size:13px;min-height:1em;margin-top:6px}',
|
|
'.auth-button{margin-left:8px;padding:4px 10px;border-radius:6px;border:1px solid #555;background:#2a2a33;color:#eee;cursor:pointer;font-size:13px;white-space:nowrap}',
|
|
].join('\n');
|
|
document.head.appendChild(st);
|
|
}
|
|
|
|
function toast(msg) {
|
|
var t = document.createElement('div');
|
|
t.className = 'auth-toast';
|
|
t.textContent = msg;
|
|
document.body.appendChild(t);
|
|
setTimeout(function () { t.remove(); }, 3500);
|
|
}
|
|
|
|
// A modal dialog. build(body) fills it; it returns a close function.
|
|
function dialog(title, build) {
|
|
var back = document.createElement('div');
|
|
back.className = 'auth-backdrop';
|
|
back.innerHTML = '<div class="auth-dialog" role="dialog" aria-modal="true" aria-label="' + esc(title) + '"><h3>' + esc(title) + '</h3><div class="auth-body"></div></div>';
|
|
document.body.appendChild(back);
|
|
var body = back.querySelector('.auth-body');
|
|
function close() {
|
|
back.remove();
|
|
document.removeEventListener('keydown', onKey);
|
|
}
|
|
function onKey(e) {
|
|
if (e.key === 'Escape') {
|
|
close();
|
|
}
|
|
}
|
|
back.addEventListener('mousedown', function (e) {
|
|
if (e.target === back) {
|
|
close();
|
|
}
|
|
});
|
|
document.addEventListener('keydown', onKey);
|
|
build(body, close);
|
|
return close;
|
|
}
|
|
|
|
/* ------------------------------------------------------------ state */
|
|
|
|
function refresh() {
|
|
return origFetch('/auth', { credentials: 'same-origin' })
|
|
.then(function (r) { return r.json(); })
|
|
.then(function (s) {
|
|
state = s;
|
|
applyPerms();
|
|
return s;
|
|
})
|
|
.catch(function () { return state; });
|
|
}
|
|
|
|
function applyPerms() {
|
|
document.body.dataset.authRole = state.role || '';
|
|
document.body.dataset.authUser = state.user || '';
|
|
document.querySelectorAll('[data-need]').forEach(function (el) {
|
|
var need = el.getAttribute('data-need').split(':');
|
|
el.hidden = !can(need[0], LEVELS.indexOf(need[1]));
|
|
});
|
|
var btn = document.getElementById('auth-button');
|
|
if (btn) {
|
|
btn.textContent = !state.enabled ? 'Set up users' : state.user ? state.user + ' (' + state.role + ')' : 'Sign in';
|
|
}
|
|
}
|
|
|
|
/* ------------------------------------------------------------ sign in */
|
|
|
|
function askLogin() {
|
|
if (pendingLogin) {
|
|
return pendingLogin;
|
|
}
|
|
pendingLogin = new Promise(function (resolve) {
|
|
dialog('Sign in', function (body, close) {
|
|
body.innerHTML = [
|
|
'<form>',
|
|
'<label for="auth-user">Username</label><input id="auth-user" autocomplete="username" required>',
|
|
'<label for="auth-pass">Password</label><input id="auth-pass" type="password" autocomplete="current-password" required>',
|
|
'<div class="auth-err" id="auth-err"></div>',
|
|
'<div class="auth-actions"><button type="button" id="auth-cancel">Cancel</button><button type="submit" class="primary">Sign in</button></div>',
|
|
'</form>',
|
|
].join('');
|
|
var form = body.querySelector('form');
|
|
body.querySelector('#auth-user').focus();
|
|
body.querySelector('#auth-cancel').onclick = function () { close(); resolve(false); };
|
|
form.onsubmit = function (e) {
|
|
e.preventDefault();
|
|
var user = body.querySelector('#auth-user').value.trim(), pw = body.querySelector('#auth-pass').value;
|
|
origFetch('/auth/login', {
|
|
method: 'POST', credentials: 'same-origin',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username: user, password: pw }),
|
|
}).then(function (res) {
|
|
if (!res.ok) {
|
|
return errorText(res).then(function (m) { body.querySelector('#auth-err').textContent = m; });
|
|
}
|
|
close();
|
|
return refresh().then(function () { resolve(true); });
|
|
});
|
|
};
|
|
});
|
|
}).then(function (ok) {
|
|
pendingLogin = null;
|
|
return ok;
|
|
});
|
|
return pendingLogin;
|
|
}
|
|
|
|
function changePassword() {
|
|
dialog('Change password', function (body, close) {
|
|
body.innerHTML = [
|
|
'<form>',
|
|
'<label for="auth-old">Current password</label><input id="auth-old" type="password" autocomplete="current-password" required>',
|
|
'<label for="auth-new">New password (8 to 128 characters)</label><input id="auth-new" type="password" autocomplete="new-password" required>',
|
|
'<div class="auth-err" id="auth-err"></div>',
|
|
'<div class="auth-actions"><button type="button" id="auth-cancel">Cancel</button><button type="submit" class="primary">Change</button></div>',
|
|
'</form>',
|
|
].join('');
|
|
body.querySelector('#auth-cancel').onclick = close;
|
|
body.querySelector('form').onsubmit = function (e) {
|
|
e.preventDefault();
|
|
origFetch('/auth/password', {
|
|
method: 'PUT', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ old: body.querySelector('#auth-old').value, new: body.querySelector('#auth-new').value }),
|
|
}).then(function (res) {
|
|
if (!res.ok) {
|
|
return errorText(res).then(function (m) { body.querySelector('#auth-err').textContent = m; });
|
|
}
|
|
close();
|
|
toast('Password changed');
|
|
});
|
|
};
|
|
});
|
|
}
|
|
|
|
function signOut() {
|
|
origFetch('/auth/logout', { method: 'POST', credentials: 'same-origin' }).then(refresh).then(function () {
|
|
toast('Signed out');
|
|
});
|
|
}
|
|
|
|
/* ------------------------------------------------------------ users and roles */
|
|
|
|
function usersAndRoles() {
|
|
dialog('Users & roles', function (body) {
|
|
body.innerHTML = '<div class="auth-err" id="auth-err"></div><div id="auth-content">Loading…</div>';
|
|
var err = body.querySelector('#auth-err');
|
|
var content = body.querySelector('#auth-content');
|
|
var roles = [];
|
|
|
|
function req(method, url, data) {
|
|
err.textContent = '';
|
|
return origFetch(url, {
|
|
method: method, credentials: 'same-origin',
|
|
headers: data ? { 'Content-Type': 'application/json' } : undefined,
|
|
body: data ? JSON.stringify(data) : undefined,
|
|
}).then(function (res) {
|
|
if (!res.ok) {
|
|
return errorText(res).then(function (m) { err.textContent = m; throw new Error(m); });
|
|
}
|
|
return res.json().catch(function () { return {}; });
|
|
});
|
|
}
|
|
|
|
function roleOptions(selected) {
|
|
return roles.map(function (r) {
|
|
return '<option value="' + esc(r.name) + '"' + (r.name === selected ? ' selected' : '') + '>' + esc(r.name) + '</option>';
|
|
}).join('');
|
|
}
|
|
|
|
function render(users) {
|
|
var userRows = users.map(function (u) {
|
|
return '<tr><td>' + esc(u.username) + '</td>' +
|
|
'<td><select data-user-role="' + esc(u.username) + '">' + roleOptions(u.role) + '</select></td>' +
|
|
'<td class="auth-row"><button data-reset="' + esc(u.username) + '">Set password</button>' +
|
|
'<button class="danger" data-delete-user="' + esc(u.username) + '">Delete</button></td></tr>';
|
|
}).join('');
|
|
var head = '<tr><th>Area</th>' + roles.map(function (r) { return '<th>' + esc(r.name) + '</th>'; }).join('') + '</tr>';
|
|
var matrix = AREAS.map(function (a) {
|
|
return '<tr><td>' + esc(AREA_LABELS[a]) + '</td>' + roles.map(function (r) {
|
|
var lvl = (r.perms && r.perms[a]) || 0;
|
|
var locked = r.name === 'admin';
|
|
return '<td><select data-perm-role="' + esc(r.name) + '" data-area="' + a + '"' + (locked ? ' disabled' : '') + '>' +
|
|
LEVELS.map(function (l, i) { return '<option value="' + i + '"' + (i === lvl ? ' selected' : '') + '>' + l + '</option>'; }).join('') +
|
|
'</select></td>';
|
|
}).join('') + '</tr>';
|
|
}).join('');
|
|
content.innerHTML = [
|
|
'<h4>Users</h4>',
|
|
'<table><tr><th>Username</th><th>Role</th><th></th></tr>' + (userRows || '<tr><td colspan="3">No users yet</td></tr>') + '</table>',
|
|
'<div class="auth-row"><input id="new-user" placeholder="username" style="width:140px">',
|
|
'<input id="new-pass" type="password" placeholder="password (8+)" style="width:160px">',
|
|
'<select id="new-role" style="width:140px">' + roleOptions('guest') + '</select>',
|
|
'<button class="primary" id="add-user">Add user</button></div>',
|
|
'<h4 style="margin-top:18px">Permissions</h4>',
|
|
'<p style="font-size:12px;opacity:.75;margin:4px 0">none: hidden · view: read · control: play, stop, brightness, identify · edit: change anything.</p>',
|
|
'<div style="overflow:auto"><table>' + head + matrix + '</table></div>',
|
|
'<div class="auth-row"><input id="new-role-name" placeholder="new role name" style="width:180px">',
|
|
'<button id="add-role">New role</button><span style="flex:1"></span>',
|
|
'<button class="primary" id="save-roles">Save permissions</button></div>',
|
|
'<div class="auth-row" style="margin-top:10px">' + roles.filter(function (r) { return !r.builtin; }).map(function (r) {
|
|
return '<button class="danger" data-delete-role="' + esc(r.name) + '">Delete role ' + esc(r.name) + '</button>';
|
|
}).join(' ') + '</div>',
|
|
].join('');
|
|
wire();
|
|
}
|
|
|
|
function wire() {
|
|
content.querySelectorAll('[data-user-role]').forEach(function (sel) {
|
|
sel.onchange = function () {
|
|
req('PUT', '/auth/users/' + encodeURIComponent(sel.dataset.userRole), { role: sel.value })
|
|
.then(load, function () { load(); });
|
|
};
|
|
});
|
|
content.querySelectorAll('[data-reset]').forEach(function (b) {
|
|
b.onclick = function () {
|
|
var pw = window.prompt('New password for ' + b.dataset.reset + ' (8 to 128 characters)');
|
|
if (pw) {
|
|
req('PUT', '/auth/users/' + encodeURIComponent(b.dataset.reset), { password: pw }).then(load, function () {});
|
|
}
|
|
};
|
|
});
|
|
content.querySelectorAll('[data-delete-user]').forEach(function (b) {
|
|
b.onclick = function () {
|
|
if (window.confirm('Delete user ' + b.dataset.deleteUser + '?')) {
|
|
req('DELETE', '/auth/users/' + encodeURIComponent(b.dataset.deleteUser)).then(load, function () {});
|
|
}
|
|
};
|
|
});
|
|
content.querySelector('#add-user').onclick = function () {
|
|
req('POST', '/auth/users', {
|
|
username: content.querySelector('#new-user').value.trim(),
|
|
password: content.querySelector('#new-pass').value,
|
|
role: content.querySelector('#new-role').value,
|
|
}).then(load, function () {});
|
|
};
|
|
content.querySelector('#add-role').onclick = function () {
|
|
var name = content.querySelector('#new-role-name').value.trim();
|
|
var perms = {};
|
|
AREAS.forEach(function (a) { perms[a] = 0; });
|
|
req('POST', '/auth/roles', { name: name, perms: perms }).then(load, function () {});
|
|
};
|
|
content.querySelector('#save-roles').onclick = function () {
|
|
var jobs = roles.filter(function (r) { return r.name !== 'admin'; }).map(function (r) {
|
|
var perms = {};
|
|
AREAS.forEach(function (a) {
|
|
var sel = content.querySelector('[data-perm-role="' + r.name + '"][data-area="' + a + '"]');
|
|
perms[a] = sel ? parseInt(sel.value, 10) : 0;
|
|
});
|
|
return req('PUT', '/auth/roles/' + encodeURIComponent(r.name), { perms: perms });
|
|
});
|
|
Promise.all(jobs).then(function () { toast('Permissions saved'); load(); }, function () { load(); });
|
|
};
|
|
content.querySelectorAll('[data-delete-role]').forEach(function (b) {
|
|
b.onclick = function () {
|
|
if (window.confirm('Delete role ' + b.dataset.deleteRole + '?')) {
|
|
req('DELETE', '/auth/roles/' + encodeURIComponent(b.dataset.deleteRole)).then(load, function () {});
|
|
}
|
|
};
|
|
});
|
|
}
|
|
|
|
function load() {
|
|
Promise.all([req('GET', '/auth/roles'), req('GET', '/auth/users')]).then(function (res) {
|
|
try {
|
|
roles = res[0];
|
|
render(res[1]);
|
|
} catch (e) {
|
|
err.textContent = 'Could not show users and roles: ' + e.message;
|
|
}
|
|
}, function () {
|
|
if (!err.textContent) {
|
|
err.textContent = 'Could not load users and roles';
|
|
}
|
|
});
|
|
}
|
|
|
|
load();
|
|
});
|
|
}
|
|
|
|
/* ------------------------------------------------------------ header button */
|
|
|
|
function accountMenu() {
|
|
dialog(state.user ? 'Signed in as ' + state.user : 'Users', function (body, close) {
|
|
var rows = [];
|
|
if (!state.enabled) {
|
|
rows.push('<p style="font-size:13px;opacity:.85">No users yet, so anyone can edit. Create the first admin to turn sign-in on.</p>');
|
|
}
|
|
rows.push('<div class="auth-actions" style="justify-content:flex-start;flex-direction:column;align-items:stretch">');
|
|
if (!state.user && state.enabled) {
|
|
rows.push('<button class="primary" id="auth-do-login">Sign in</button>');
|
|
}
|
|
if (state.user) {
|
|
rows.push('<button id="auth-do-pass">Change password</button>');
|
|
rows.push('<button id="auth-do-out">Sign out</button>');
|
|
}
|
|
if (can('users', AREA_EDIT_LEVEL)) {
|
|
rows.push('<button id="auth-do-users">Users & roles</button>');
|
|
}
|
|
rows.push('<button id="auth-do-close">Close</button></div>');
|
|
body.innerHTML = rows.join('');
|
|
var bind = function (id, fn) { var el = body.querySelector('#' + id); if (el) { el.onclick = function () { close(); fn(); }; } };
|
|
bind('auth-do-login', askLogin);
|
|
bind('auth-do-pass', changePassword);
|
|
bind('auth-do-out', signOut);
|
|
bind('auth-do-users', usersAndRoles);
|
|
body.querySelector('#auth-do-close').onclick = close;
|
|
});
|
|
}
|
|
|
|
var AREA_EDIT_LEVEL = 3;
|
|
|
|
function addHeaderButton() {
|
|
// Beside the Menu button, which stays visible; the header actions inside the menu are hidden until it opens
|
|
var menu = document.getElementById('main-menu-btn');
|
|
var host = menu ? menu.parentElement : document.querySelector('header');
|
|
if (!host || document.getElementById('auth-button')) {
|
|
return;
|
|
}
|
|
var btn = document.createElement('button');
|
|
btn.id = 'auth-button';
|
|
btn.type = 'button';
|
|
btn.className = 'auth-button';
|
|
btn.title = 'Sign in, change password, users and roles';
|
|
btn.onclick = accountMenu;
|
|
host.insertBefore(btn, menu || host.firstChild);
|
|
applyPerms();
|
|
}
|
|
|
|
/* ------------------------------------------------------------ fetch wrapper */
|
|
|
|
window.fetch = function (input, init) {
|
|
var url = typeof input === 'string' ? input : (input && input.url) || '';
|
|
var auth = isAuthUrl(url);
|
|
var method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase();
|
|
return origFetch(input, init).then(function (res) {
|
|
if (auth) {
|
|
return res;
|
|
}
|
|
// Only a change asks for a sign-in; a read the page cannot do just fails quietly
|
|
if (res.status === 401 && method !== 'GET') {
|
|
return askLogin().then(function (ok) {
|
|
return ok ? origFetch(input, init) : res;
|
|
});
|
|
}
|
|
if (res.status === 403 && method !== 'GET') {
|
|
errorText(res.clone()).then(toast);
|
|
}
|
|
return res;
|
|
});
|
|
};
|
|
|
|
/* ------------------------------------------------------------ start */
|
|
|
|
function start() {
|
|
injectStyle();
|
|
addHeaderButton();
|
|
refresh();
|
|
window.authPerms = {
|
|
can: can,
|
|
refresh: refresh,
|
|
usersAndRoles: usersAndRoles,
|
|
};
|
|
}
|
|
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', start);
|
|
} else {
|
|
start();
|
|
}
|
|
})();
|