// 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 = '
';
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');
var label = !state.enabled ? 'Set up users' : state.user ? state.user + ' (' + state.role + ')' : 'Sign in';
if (btn) {
btn.textContent = label;
}
renderUsersTab();
}
/* ------------------------------------------------------------ sign in */
function askLogin() {
if (pendingLogin) {
return pendingLogin;
}
pendingLogin = new Promise(function (resolve) {
dialog('Sign in', function (body, close) {
body.innerHTML = [
'',
].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 = [
'',
].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 */
// The lists of users and roles, drawn into `urHost` (the Users tab of Settings or a dialog).
// Each row opens its editor: the user and role editors are modals in the page.
var urHost = null;
var urRoles = [];
var urUsers = [];
var urEditing = null; // { kind: 'user' | 'role', name: '' when adding }
function byId(id) { return document.getElementById(id); }
function showModal(id) { byId(id).classList.add('active'); }
function hideModal(id) { byId(id).classList.remove('active'); }
function editorError(id, message) {
var p = byId(id + '-error');
p.textContent = message || '';
p.hidden = !message;
}
// One call to the auth API. A failure rejects with the server's message.
function urRequest(method, url, data) {
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) { throw new Error(m); });
}
return res.json().catch(function () { return {}; });
});
}
// The users and roles lists in a dialog, for when there is no Settings window
function openUsersDialog() {
dialog('Users & roles', function (body) { usersAndRoles(body); });
}
// The users and roles lists, drawn into `host` (the Users tab of Settings)
function usersAndRoles(host) {
urHost = host;
host.innerHTML = 'Loading…
';
var content = host.querySelector('#auth-content');
content.onclick = function (e) {
var b = e.target.closest('button');
if (!b) return;
if (b.id === 'add-user') openUserEditor('');
else if (b.id === 'add-role') openRoleEditor('');
else if (b.dataset.editUser !== undefined) openUserEditor(b.dataset.editUser);
else if (b.dataset.editRole !== undefined) openRoleEditor(b.dataset.editRole);
};
loadLists();
}
function listError(message) {
var err = urHost.querySelector('#auth-err');
if (err) err.textContent = message;
}
function loadLists() {
Promise.all([urRequest('GET', '/auth/roles'), urRequest('GET', '/auth/users')]).then(function (res) {
urRoles = res[0];
urUsers = res[1];
drawLists();
}, function (e) {
urHost.querySelector('#auth-content').innerHTML = '';
listError(e.message || 'Could not load users and roles');
});
}
/* ------------------------------------------------------------ lists */
function drawLists() {
var content = urHost.querySelector('#auth-content');
listError('');
content.innerHTML = [
listHead('Users', 'add-user', 'Add user'),
urUsers.length ? urUsers.map(userRow).join('') : 'No users yet, so anyone can edit. Add the first admin to turn sign-in on.
',
listHead('Roles', 'add-role', 'New role', 'margin-top:18px;'),
urRoles.map(roleRow).join(''),
].join('');
}
function listHead(title, id, label, style) {
return '' +
'
' + title + '
' +
'';
}
// The same row as the device groups list: title and detail on the left, Edit on the right
function listRow(title, meta, attr) {
return '' +
'
' + esc(title) + '
' +
'
' + esc(meta) + '
' +
'
';
}
function userRow(u) {
return listRow(u.username, 'Role: ' + (u.role || 'none'), 'data-edit-user="' + esc(u.username) + '"');
}
function roleRow(r) {
var open = AREAS.filter(function (a) { return ((r.perms && r.perms[a]) || 0) > 0; }).length;
var meta = (r.builtin ? 'Built-in · ' : '') + open + ' of ' + AREAS.length + ' areas visible';
return listRow(r.name, meta, 'data-edit-role="' + esc(r.name) + '"');
}
function roleOptions(selected) {
return urRoles.map(function (r) {
return '';
}).join('');
}
/* ------------------------------------------------------------ user editor */
function openUserEditor(name) {
var u = name ? urUsers.find(function (x) { return x.username === name; }) : null;
urEditing = { kind: 'user', name: u ? u.username : '' };
byId('edit-user-title').textContent = u ? 'Edit user' : 'Add user';
byId('edit-user-name').value = u ? u.username : '';
byId('edit-user-name').readOnly = !!u;
// The first user is the admin, which turns sign-in on; later users start as guests
byId('edit-user-role').innerHTML = roleOptions(u ? u.role : urUsers.length ? 'guest' : 'admin');
byId('edit-user-pass').value = '';
byId('edit-user-pass').required = !u;
byId('edit-user-pass-help').textContent = u ? 'Leave empty to keep the current password.' : '8 to 128 characters.';
byId('edit-user-delete-btn').hidden = !u;
editorError('edit-user', '');
showModal('edit-user-modal');
}
function saveUser(e) {
e.preventDefault();
var name = byId('edit-user-name').value.trim();
var role = byId('edit-user-role').value;
var pw = byId('edit-user-pass').value;
var isNew = !urEditing.name;
var url = '/auth/users/' + encodeURIComponent(urEditing.name);
var job = isNew
? urRequest('POST', '/auth/users', { username: name, password: pw, role: role })
: urRequest('PUT', url, { role: role }).then(function () {
return pw ? urRequest('PUT', url, { password: pw }) : null;
});
job.then(function () {
hideModal('edit-user-modal');
toast(isNew ? 'User added' : 'User saved');
loadLists();
}, function (err) {
editorError('edit-user', err.message);
loadLists();
});
}
async function deleteUser() {
if (!await uiConfirm('Delete user ' + urEditing.name + '?')) return;
urRequest('DELETE', '/auth/users/' + encodeURIComponent(urEditing.name)).then(function () {
hideModal('edit-user-modal');
loadLists();
}, function (err) {
editorError('edit-user', err.message);
});
}
/* ------------------------------------------------------------ role editor */
function openRoleEditor(name) {
var r = name ? urRoles.find(function (x) { return x.name === name; }) : null;
var admin = !!r && r.name === 'admin'; // the admin role's permissions are fixed
urEditing = { kind: 'role', name: r ? r.name : '' };
byId('edit-role-title').textContent = r ? 'Edit role' : 'New role';
byId('edit-role-name').value = r ? r.name : '';
byId('edit-role-name').readOnly = !!r;
byId('edit-role-perms').innerHTML = AREAS.map(function (a) {
var lvl = (r && r.perms && r.perms[a]) || 0;
return '' +
'
' + esc(AREA_LABELS[a]) + '
' +
'
';
}).join('');
byId('edit-role-save-btn').hidden = admin;
byId('edit-role-delete-btn').hidden = !r || !!r.builtin;
editorError('edit-role', '');
showModal('edit-role-modal');
}
function saveRole(e) {
e.preventDefault();
var name = byId('edit-role-name').value.trim();
var perms = {};
AREAS.forEach(function (a) {
perms[a] = parseInt(byId('edit-role-perms').querySelector('[data-area="' + a + '"]').value, 10);
});
var isNew = !urEditing.name;
var job = isNew
? urRequest('POST', '/auth/roles', { name: name, perms: perms })
: urRequest('PUT', '/auth/roles/' + encodeURIComponent(urEditing.name), { perms: perms });
job.then(function () {
hideModal('edit-role-modal');
toast(isNew ? 'Role added' : 'Permissions saved');
loadLists();
}, function (err) {
editorError('edit-role', err.message);
});
}
async function deleteRole() {
if (!await uiConfirm('Delete role ' + urEditing.name + '?')) return;
urRequest('DELETE', '/auth/roles/' + encodeURIComponent(urEditing.name)).then(function () {
hideModal('edit-role-modal');
loadLists();
}, function (err) {
editorError('edit-role', err.message);
});
}
// Wired once: the editors are modals in the page, opened from the lists
function wireEditors() {
byId('edit-user-form').addEventListener('submit', saveUser);
byId('edit-user-delete-btn').addEventListener('click', deleteUser);
byId('edit-user-close-btn').addEventListener('click', function () { hideModal('edit-user-modal'); });
byId('edit-role-form').addEventListener('submit', saveRole);
byId('edit-role-delete-btn').addEventListener('click', deleteRole);
byId('edit-role-close-btn').addEventListener('click', function () { hideModal('edit-role-modal'); });
}
/* ------------------------------------------------------------ header button */
function accountMenu() {
if (window.openSettingsTab) {
window.openSettingsTab('users');
return;
}
dialog(state.user ? 'Signed in as ' + state.user : 'Users', buildAccount);
}
// The Users tab of Settings: the same actions, drawn in the tab
function renderUsersTab() {
var body = document.getElementById('settings-users-body');
if (body) {
buildAccount(body, renderUsersTab, true);
if (can('users', AREA_EDIT_LEVEL)) {
var roles = document.createElement('div');
roles.className = 'settings-roles';
body.appendChild(roles);
usersAndRoles(roles);
}
}
}
function buildAccount(body, close, inline) {
{
var rows = [];
if (!state.enabled) {
rows.push('No users yet, so anyone can edit. Create the first admin to turn sign-in on.
');
}
rows.push('');
if (!state.user && state.enabled) {
rows.push('');
}
if (state.user) {
rows.push('');
rows.push('');
}
if (!inline && can('users', AREA_EDIT_LEVEL)) {
rows.push('');
}
rows.push('
');
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', openUsersDialog);
if (inline) {
body.querySelector('#auth-do-close').remove();
body.insertAdjacentHTML('afterbegin', '' + (state.user ? 'Signed in as ' + esc(state.user) + ' (' + esc(state.role) + ').' : state.enabled ? 'Not signed in.' : '') + '
');
} else {
body.querySelector('#auth-do-close').onclick = close;
}
}
}
var AREA_EDIT_LEVEL = 3;
function addHeaderButton() {
// The button itself stays hidden; its click opens the Users tab of Settings
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;
btn.hidden = true;
host.insertBefore(btn, menu || host.firstChild);
document.addEventListener('settings-tab', function (e) {
if (e.detail === 'users') {
renderUsersTab();
}
});
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();
wireEditors();
addHeaderButton();
refresh();
window.authPerms = {
can: can,
refresh: refresh,
usersAndRoles: openUsersDialog,
};
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}
})();