"use strict"; const api = window.chjPlugin; const i18n = window.chjPluginI18n.createI18n("cs"); const t = i18n.t; let endedSessionId = ""; let sessionsLoading = false; // Guard every continuation, including sudo retries and dialog answers, against a server switch. async function sessionResult(promise, token) { const value = await promise; if (token !== state.generation) throw new Error("CHJ_SESSION_CHANGED"); return value; } // Marks a catalog key that is translated with t() only when it is shown. const k = (text) => text; const el = new Proxy({}, { get: (_target, id) => document.getElementById(id) }); // Every asynchronous result is checked against these tokens, so data of a previous session or // account is never rendered after the user switched. const state = { sessions: [], sessionId: "", generation: 0, detailToken: 0, privilege: null, inventory: null, selected: null, detail: null, detailLoading: false, tab: "account", loading: false, mutating: false }; const PRIVILEGE_TEXT = { root: ["root", "ok"], "sudo-nopasswd": [k("sudo bez hesla"), "ok"], "sudo-password": [k("sudo s heslem"), "warn"], none: [k("bez sudo – jen čtení"), "danger"], unknown: [k("neověřeno"), "muted"], "windows-elevated": [k("správce Windows (zvýšený token)"), "ok"], "windows-admin-unelevated": [k("člen Administrators bez zvýšeného tokenu – jen čtení"), "warn"], "windows-standard": [k("standardní účet Windows – jen čtení"), "danger"] }; const SUDO_TEXT = { full: k("plné sudo"), "full-nopasswd": k("plné sudo bez hesla"), limited: k("omezené sudo"), none: k("bez sudo"), unavailable: k("sudo není nainstalováno"), unknown: k("neznámé") }; const PASSWORD_TEXT = { set: [k("heslo nastaveno"), "ok"], locked: [k("heslo zamčeno"), "warn"], none: [k("bez hesla"), "muted"], empty: [k("prázdné heslo!"), "danger"], unknown: [k("stav hesla neznámý"), "muted"] }; const PROTECTION_TEXT = { root: k("Chráněný systémový účet root: nelze ho smazat ani měnit UID/GID, skupiny, shell či domovský adresář. SSH přístup (včetně PermitRootLogin) a SSH klíče lze spravovat s bezpečnostními kontrolami."), system: k("Systémový účet je chráněný. CH-J ho zobrazuje jen pro čtení."), builtin: k("Vestavěný účet Windows (Administrator, Guest, DefaultAccount, WDAGUtilityAccount) je chráněný a zobrazuje se jen pro čtení."), session: k("Tímto účtem je CH-J právě připojeno. Změny, které by mohly přerušit přístup, jsou zablokované; SSH klíče a SSH přístup lze měnit s ochranou proti odříznutí.") }; const ERROR_TEXT = { SUDO_PASSWORD_REQUIRED: k("Operace vyžaduje heslo pro sudo."), SUDO_PASSWORD_INCORRECT: k("Heslo pro sudo bylo odmítnuto."), SUDO_NOT_PERMITTED: k("Účet SSH relace nemá pro tuto operaci oprávnění sudo. Zadání hesla to nezmění."), SUDO_TTY_REQUIRED: k("Politika sudo na serveru vyžaduje terminál (requiretty). CH-J ji neobchází."), SUDO_AUTH_FAILED: k("Ověření sudo selhalo nebo je účet dočasně zablokován."), SUDO_UNAVAILABLE: k("Na serveru není sudo a relace neběží jako root."), SUDO_FAILED: k("sudo operaci nespustilo."), SUDO_PASSWORD_INVALID: k("Heslo pro sudo má neplatný formát."), SESSION_NOT_CONNECTED: k("SSH relace byla odpojena. Připojte se znovu v hlavním okně."), REMOTE_COMMAND_TIMEOUT: k("Server neodpověděl včas."), REMOTE_COMMAND_FAILED: k("Vzdálený příkaz se nepodařilo spustit."), REMOTE_OUTPUT_TOO_LARGE: k("Odpověď serveru je příliš velká."), PLUGIN_PERMISSION_DENIED: k("Modul nemá potřebné oprávnění."), USERS_NAME_INVALID: k("Neplatný název. Povolené jsou malé znaky a-z, číslice, _ a - (max. 32, nezačíná číslicí ani pomlčkou)."), USERS_GROUP_INVALID: k("Neplatný název skupiny."), USERS_SHELL_INVALID: k("Neplatný shell (musí existovat a být v /etc/shells, případně nologin/false)."), USERS_HOME_INVALID: k("Neplatný domovský adresář. Použijte absolutní cestu mimo systémové adresáře."), USERS_HOME_EXISTS: k("Cílový domovský adresář už existuje."), USERS_COMMENT_INVALID: k("Celé jméno může mít nejvýše 100 znaků bez dvojtečky a řídicích znaků."), USERS_PASSWORD_INVALID: k("Heslo musí mít 1–256 znaků a nesmí obsahovat zalomení řádku."), USERS_USER_EXISTS: k("Účet s tímto jménem už existuje."), USERS_GROUP_EXISTS: k("Skupina se stejným názvem už existuje; zvolte primární skupinu."), USERS_USER_NOT_FOUND: k("Účet na serveru neexistuje."), USERS_GROUP_NOT_FOUND: k("Skupina na serveru neexistuje."), USERS_GROUP_NOT_MEMBER: k("Účet není doplňkovým členem skupiny."), USERS_GROUP_PRIMARY: k("Primární skupinu nelze odebrat; nejprve změňte primární skupinu."), USERS_PROTECTED_USER: k("Účet je chráněný."), USERS_LAST_ADMIN: k("Jde o posledního funkčního administrátora; změna byla odmítnuta."), USERS_USER_HAS_PROCESSES: k("Účet má spuštěné procesy. Ukončete je a zkuste to znovu."), USERS_TOOL_MISSING: k("Na serveru chybí potřebný systémový nástroj."), USERS_SUDO_GROUP_UNAVAILABLE: k("Na serveru není skupina sudo/wheel/admin, na kterou by odkazoval sudoers. CH-J sudoers nemění."), USERS_USERADD_FAILED: k("useradd selhal:"), USERS_USERMOD_FAILED: k("usermod selhal:"), USERS_USERDEL_FAILED: k("userdel selhal:"), USERS_PASSWORD_FAILED: k("Nastavení hesla selhalo:"), USERS_GROUP_CHANGE_FAILED: k("Změna skupiny selhala:"), USERS_KEY_INVALID: k("Neplatný veřejný klíč. Vložte přesně jeden klíč OpenSSH bez voleb."), USERS_KEY_PRIVATE: k("Vložili jste soukromý klíč! Na server se smí nahrát jen veřejný klíč (.pub)."), USERS_KEY_TYPE_UNSUPPORTED: k("Přidat lze jen klíče Ed25519."), USERS_KEY_DUPLICATE: k("Tento klíč už je pro účet povolený."), USERS_KEY_NOT_FOUND: k("Klíč se mezitím změnil nebo neexistuje. Obnovte seznam."), USERS_KEY_IN_USE: k("Tento klíč používá aktivní relace CH-J, proto nebyl odebrán."), USERS_KEY_LAST: k("Poslední klíč účtu aktivní relace nelze odebrat."), USERS_KEYS_FILE_UNMANAGEABLE: k("Soubor authorized_keys nelze bezpečně upravit:"), USERS_KEYS_FILE_TOO_LARGE: k("Soubor authorized_keys by přesáhl 256 KiB."), USERS_KEYS_SYMLINK: k("authorized_keys nebo .ssh je symbolický odkaz; soubor nebyl změněn."), USERS_KEYS_CHANGED: k("Soubor s klíči se mezitím změnil. Obnovte seznam a zkuste to znovu."), USERS_KEYS_PATH_UNSUPPORTED: k("Cesta k authorized_keys mimo domovský adresář není podporovaná."), USERS_SSH_POLICY_INVALID: k("Neplatné nastavení SSH."), USERS_SSH_LAYOUT_UNSUPPORTED: k("sshd_config nenačítá sshd_config.d před prvním blokem Match. CH-J hlavní konfiguraci neupravuje."), USERS_SSH_MANAGED_FILE_MODIFIED: k("Soubor spravovaný CH-J byl ručně upraven; CH-J ho nepřepíše."), USERS_SSH_MANAGED_FILE_UNSAFE: k("Soubor spravovaný CH-J není běžný čitelný soubor."), USERS_SSH_CONFIG_ALREADY_INVALID: k("Současná konfigurace SSH je neplatná, změna nebyla provedena:"), USERS_SSH_CONFIG_INVALID: k("Nová konfigurace neprošla sshd -t a nebyla použita:"), USERS_SSH_POLICY_NOT_EFFECTIVE: k("Nastavení by se neprojevilo kvůli existujícím pravidlům s vyšší prioritou; vráceno zpět."), USERS_SSH_LOCKOUT_PREVENTED: k("Změna byla zablokována, aby nepřerušila přístup aktivní relace:"), USERS_SSH_PROBE_FAILED: k("Nové testovací přihlášení selhalo; konfigurace byla vrácena:"), USERS_SSH_PROBE_CREDENTIALS_REQUIRED: k("Pro ověření nového přihlášení je potřeba heslo nebo passphrase profilu."), USERS_SSH_RELOAD_FAILED: k("Reload SSH služby selhal; konfigurace byla vrácena:"), USERS_SSH_POLICY_CHANGED: k("Spravovaná SSH konfigurace se mezitím změnila. Obnovte detail a zkuste to znovu."), USERS_SSH_CLIENT_UNKNOWN: k("Adresu klienta SSH relace nelze zjistit, ochranu proti odříznutí proto nelze ověřit."), USERS_SSHD_MISSING: k("Na serveru nebyl nalezen OpenSSH server (sshd)."), USERS_PRIVILEGE_REQUIRED: k("Operace vyžaduje oprávnění root."), USERS_ROOT_PASSWORD_CONFIRMATION_REQUIRED: k("Povolení hesla pro root vyžaduje dodatečné potvrzení."), USERS_NAME_INVALID_WINDOWS: k("Neplatný název účtu Windows: písmena, číslice, mezera, tečka, _ nebo - (max. 20), nesmí končit tečkou ani mezerou."), USERS_SID_INVALID: k("Neplatný identifikátor účtu (SID)."), USERS_WINDOWS_ELEVATION_REQUIRED: k("Operace vyžaduje SSH relaci správce se zvýšeným tokenem. Windows nemá sudo a CH-J neobchází UAC:"), USERS_ACCESS_DENIED: k("Windows operaci zamítl (přístup odepřen bezpečnostní politikou):"), USERS_POWERSHELL_UNAVAILABLE: k("Na serveru nelze spustit Windows PowerShell (powershell.exe)."), USERS_POWERSHELL_RESTRICTED: k("PowerShell je omezen politikou (Constrained Language Mode / blokování skriptů); CH-J ji neobchází."), USERS_LOCALACCOUNTS_UNAVAILABLE: k("Modul Microsoft.PowerShell.LocalAccounts není v PowerShellu na serveru dostupný."), USERS_DOMAIN_READ_ONLY: k("Doménové a cloudové identity jsou jen pro čtení."), USERS_NOT_SUPPORTED_ON_PLATFORM: k("Tato operace na Windows neexistuje (shell, HOME, primární skupina, zamknutí hesla)."), USERS_PASSWORD_POLICY: k("Heslo nesplňuje politiku hesel Windows."), USERS_PROFILE_MISSING: k("Profil účtu zatím neexistuje (účet se ještě nepřihlásil), soubor klíčů nelze vytvořit."), USERS_SSH_NAME_UNSUPPORTED: k("Název účtu nelze bezpečně použít v sshd_config."), USERS_SSH_APPLY_IN_PROGRESS: k("Jiná změna SSH konfigurace ještě probíhá nebo čeká na potvrzení."), USERS_SSH_APPLY_NOT_STARTED: k("Úloha s automatickým rollbackem se nespustila; nic nebylo změněno."), USERS_SSH_ROLLED_BACK: k("Změna SSH nebyla ponechána, původní konfigurace byla obnovena:"), USERS_SSHD_QUERY_FAILED: k("Vyhodnocení sshd -T pod účtem SYSTEM se nepodařilo."), USERS_PLATFORM_UNSUPPORTED: k("Operační systém serveru nelze rozpoznat nebo není podporován:"), USERS_GROUP_MEMBER_EXISTS: k("Účet už je členem skupiny."), USERS_PROFILE_IN_USE: k("Profil účtu je stále načten (uživatel je přihlášen nebo ho Windows po SSH přihlášení ještě neuvolnil). Zkuste to později, nebo odstraňte účet bez profilu."), USERS_WINDOWS_OPERATION_FAILED: k("Operace Windows selhala:") }; const DETAIL_CODES = new Set(["USERS_USERADD_FAILED", "USERS_USERMOD_FAILED", "USERS_USERDEL_FAILED", "USERS_PASSWORD_FAILED", "USERS_GROUP_CHANGE_FAILED", "USERS_KEYS_FILE_UNMANAGEABLE", "USERS_SSH_CONFIG_ALREADY_INVALID", "USERS_SSH_CONFIG_INVALID", "USERS_SSH_POLICY_NOT_EFFECTIVE", "USERS_SSH_LOCKOUT_PREVENTED", "USERS_SSH_PROBE_FAILED", "USERS_SSH_RELOAD_FAILED", "USERS_PROTECTED_USER", "USERS_TOOL_MISSING", "USERS_WINDOWS_ELEVATION_REQUIRED", "USERS_ACCESS_DENIED", "USERS_SSH_ROLLED_BACK", "USERS_PLATFORM_UNSUPPORTED", "USERS_WINDOWS_OPERATION_FAILED", "USERS_PASSWORD_POLICY"]); const POLICY_ROWS = [ { key: "access", label: k("SSH přístup"), hint: k("Úplné povolení nebo zákaz SSH bez zrušení systémového účtu."), options: [["allow", k("Povolit")], ["deny", k("Zakázat")]] }, { key: "password", label: k("Přihlášení heslem"), hint: k("Dědit = platí globální nastavení serveru."), options: [["inherit", k("Dědit")], ["yes", k("Povolit")], ["no", k("Zakázat")]] }, { key: "pubkey", label: k("Přihlášení veřejným klíčem"), hint: k("Zákaz zablokuje i Ed25519 klíče."), options: [["inherit", k("Dědit")], ["yes", k("Povolit")], ["no", k("Zakázat")]] }, { key: "ipv4", label: k("Přístup z IPv4"), hint: k("Podle IP rodiny zdrojové adresy klienta."), options: [["allow", k("Povolit")], ["deny", k("Zakázat")]] }, { key: "ipv6", label: k("Přístup z IPv6"), hint: k("Podle IP rodiny zdrojové adresy klienta."), options: [["allow", k("Povolit")], ["deny", k("Zakázat")]] } ]; const ROOT_LOGIN_ROW = { key: "permitRootLogin", label: "PermitRootLogin (root)", hint: k("Doporučeno: Jen klíč (prohibit-password). „Povolit“ dovolí i heslo podle ostatních pravidel."), options: [["inherit", k("Dědit")], ["no", k("Zakázat")], ["prohibit-password", k("Jen klíč (doporučeno)")], ["forced-commands-only", k("Klíč s vynuceným příkazem")], ["yes", k("Povolit")]] }; const CANCELLED = "CHJ_UI_CANCELLED"; // ---------- small DOM helpers (text only, never innerHTML with server data) ---------- function h(tag, props = {}, children = []) { const node = document.createElement(tag); for (const [key, value] of Object.entries(props)) { if (value === undefined || value === null || value === false) continue; if (key === "className") node.className = value; else if (key === "text") node.textContent = String(value); else if (key === "dataset") Object.assign(node.dataset, value); else if (key.startsWith("on") && typeof value === "function") node.addEventListener(key.slice(2), value); else if (typeof value === "boolean") node[key] = value; else node.setAttribute(key, String(value)); } for (const child of [].concat(children)) { if (child === null || child === undefined || child === false) continue; node.append(child instanceof Node ? child : String(child)); } return node; } function badge(text, tone = "muted") { return h("span", { className: `badge ${tone}`, text }); } function setStatus(message, error = false) { el.status.textContent = message; el.status.classList.toggle("error", error); } function connected() { return Boolean(state.sessionId); } function isWindows() { return state.inventory?.platform === "windows" || state.privilege?.platform === "windows"; } // Windows accounts are addressed by SID; Linux accounts by name. function identFor(username) { const user = state.inventory?.users.find((candidate) => candidate.username === username) || (state.detail?.username === username ? state.detail : null); return user?.sid && isWindows() ? { sid: user.sid, username } : { username }; } function parseError(error) { const raw = String(error?.message || error || ""); const match = raw.match(/\b([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+): ([\s\S]*)$/); if (match) return { code: match[1], detail: match[2].trim() }; return { code: error?.code || "UNKNOWN", detail: raw.replace(/^Error invoking remote method '[^']+': (?:\w*Error: )?/, "") }; } function describeError(error) { const { code, detail } = parseError(error); if (code === CANCELLED) return t("Operace byla zrušena."); const base = ERROR_TEXT[code] && t(ERROR_TEXT[code]); if (!base) return detail || code; return DETAIL_CODES.has(code) && detail ? `${base} ${detail}` : base; } function cancelled() { const error = new Error(`${CANCELLED}: cancelled`); error.code = CANCELLED; return error; } // ---------- dialogs ---------- function runDialog(dialog, { init, submit }) { return new Promise((resolve) => { const form = dialog.querySelector("form"); let finished = false; const finish = (value) => { if (finished) return; finished = true; form.removeEventListener("submit", onSubmit); dialog.removeEventListener("close", onClose); for (const button of dialog.querySelectorAll("[data-close]")) button.removeEventListener("click", onClose); if (dialog.open) dialog.close(); resolve(value); }; const onSubmit = async (event) => { event.preventDefault(); const value = await submit(); if (value !== undefined) finish(value); }; const onClose = () => finish(null); form.addEventListener("submit", onSubmit); dialog.addEventListener("close", onClose); for (const button of dialog.querySelectorAll("[data-close]")) button.addEventListener("click", onClose); init?.(); dialog.showModal(); }); } function showError(node, message) { node.textContent = message || ""; node.hidden = !message; } function askSudo(label, error) { return runDialog(el.sudoDialog, { init: () => { el.sudoMessage.textContent = t("Operace „{label}“ vyžaduje oprávnění správce.", { label }); el.sudoUser.textContent = state.privilege?.username || ""; el.sudoPassword.value = ""; showError(el.sudoError, error); setTimeout(() => el.sudoPassword.focus(), 0); }, submit: () => { const value = el.sudoPassword.value; el.sudoPassword.value = ""; return value || undefined; } }).finally(() => { el.sudoPassword.value = ""; }); } function confirmAction({ title, message, details = [], confirmLabel = t("Potvrdit"), danger = false, typed = "", option = "" }) { return runDialog(el.confirmDialog, { init: () => { el.confirmTitle.textContent = `${title} — ${api.sessions.displayName(state.sessions.find((session) => session.sessionId === state.sessionId))}`; el.confirmMessage.textContent = message; el.confirmDetails.replaceChildren(...details.map((item) => h("li", { text: item }))); el.confirmDetails.hidden = !details.length; el.confirmTypedLabel.hidden = !typed; el.confirmTypedValue.textContent = typed; el.confirmTyped.value = ""; el.confirmOptionLabel.hidden = !option; el.confirmOptionText.textContent = option; el.confirmOption.checked = false; el.confirmSubmit.textContent = confirmLabel; el.confirmSubmit.className = `button ${danger ? "danger" : "primary"}`; }, submit: () => { if (typed && el.confirmTyped.value.trim() !== typed) { el.confirmTyped.focus(); return undefined; } return { option: el.confirmOption.checked }; } }); } function askValue({ title, message = "", label, value = "", type = "text", label2 = "", option = "", validate }) { return runDialog(el.valueDialog, { init: () => { el.valueTitle.textContent = `${title} — ${api.sessions.displayName(state.sessions.find((session) => session.sessionId === state.sessionId))}`; el.valueMessage.textContent = message; el.valueLabelText.textContent = label; el.valueInput.type = type; el.valueInput.value = value; el.valueLabel2.hidden = !label2; el.valueLabelText2.textContent = label2; el.valueInput2.type = type; el.valueInput2.value = ""; el.valueOptionLabel.hidden = !option; el.valueOptionText.textContent = option; el.valueOption.checked = false; showError(el.valueError, ""); setTimeout(() => el.valueInput.focus(), 0); }, submit: () => { const result = { value: el.valueInput.value, value2: el.valueInput2.value, option: el.valueOption.checked }; const problem = validate?.(result); if (problem) { showError(el.valueError, problem); return undefined; } return result; } }).finally(() => { el.valueInput.value = ""; el.valueInput2.value = ""; }); } function askProbeSecret(missing) { const passphrase = missing === "passphrase"; return runDialog(el.probeDialog, { init: () => { el.probeLabel.textContent = passphrase ? t("Passphrase soukromého klíče profilu") : t("Heslo SSH profilu"); el.probeSecret.value = ""; setTimeout(() => el.probeSecret.focus(), 0); }, submit: () => { const value = el.probeSecret.value; el.probeSecret.value = ""; return value ? (passphrase ? { passphrase: value } : { password: value }) : undefined; } }); } // Calls Core without a password first. Only if Core reports that sudo needs one, the dialog is shown. async function withSudo(label, invoke) { const requestGeneration = state.generation; try { let password = ""; let attempts = 0; try { for (;;) { try { return await sessionResult(invoke(password ? { sudoPassword: password } : {}), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; const { code } = parseError(error); if ((code === "SUDO_PASSWORD_REQUIRED" || code === "SUDO_PASSWORD_INCORRECT") && attempts < 3) { attempts += 1; password = await sessionResult(askSudo(label, code === "SUDO_PASSWORD_INCORRECT" && password ? t("Heslo bylo odmítnuto. Zkuste to znovu.") : ""), requestGeneration); if (!password) throw cancelled(); continue; } if (code === "SUDO_NOT_PERMITTED" || code === "SUDO_UNAVAILABLE") void refreshPrivilege(); if (code === "SESSION_NOT_CONNECTED") void loadSessions(); throw error; } } } finally { password = ""; } } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } // ---------- sessions and privileges ---------- async function loadSessions() { if (sessionsLoading) return; sessionsLoading = true; try { state.sessions = (await api.sessions.list()).filter((session) => session.state === "connected"); } catch (error) { sessionsLoading = false; setStatus(t("Relace nelze načíst: {error}", { error: describeError(error) }), true); return; } sessionsLoading = false; const previous = state.sessionId; el.sessionSelect.replaceChildren(new Option(state.sessions.length ? t("Vyberte relaci…") : t("Žádná připojená relace"), "")); for (const session of state.sessions) el.sessionSelect.add(new Option(api.sessions.displayName(session), session.sessionId)); const { id: next, reason } = api.sessions.reconcile(endedSessionId || previous, state.sessions); if (reason === "gone") endedSessionId ||= previous; el.sessionSelect.value = next; if (reason === "choose") api.sessions.offerChoice(el.sessionSelect, state.sessions, t("Vyberte relaci…")); if (next !== previous) { const selecting = selectSession(next); const token = state.generation; await selecting; if (token !== state.generation) return; } else updateControls(); if (reason === "gone") setStatus(t("Relace skončila. Vyberte server."), true); else if (!state.sessions.length) setStatus(t("Nejprve se v hlavním okně připojte k serveru přes SSH.")); } async function selectSession(sessionId) { for (const dialog of document.querySelectorAll("dialog[open]")) dialog.close(); state.sessionId = sessionId; state.generation += 1; state.detailToken += 1; Object.assign(state, { privilege: null, inventory: null, selected: null, detail: null, detailLoading: false, loading: false, mutating: false }); renderPrivilege(); renderUsers(); renderDetail(); updateControls(); if (!sessionId) return; await refreshPrivilege(); await loadInventory(); } async function refreshPrivilege() { const requestGeneration = state.generation; const token = state.generation; if (!connected()) return; try { const privilege = await sessionResult(api.users.privileges(state.sessionId, true), requestGeneration); if (token !== state.generation) return; state.privilege = privilege; } catch (error) { if (requestGeneration !== state.generation) return; if (token === state.generation) setStatus(t("Oprávnění nelze zjistit: {error}", { error: describeError(error) }), true); } renderPrivilege(); updateControls(); } function renderPrivilege() { const mode = state.privilege?.mode || "unknown"; const [text, tone] = PRIVILEGE_TEXT[mode] || PRIVILEGE_TEXT.unknown; const suffix = mode === "sudo-password" && !state.privilege?.verified ? ` (${t("neověřeno")})` : ""; el.privilegeBadge.textContent = state.privilege ? `${state.privilege.username}: ${t(text)}${suffix}` : t("neověřeno"); el.privilegeBadge.className = `badge ${tone}`; if (mode.startsWith("windows-")) { el.privilegeBadge.title = mode === "windows-elevated" ? t("Relace má zvýšený token; administrativní operace jsou dostupné.") : t("Windows nemá sudo. Administrativní operace vyžadují zvýšený token správce; CH-J neobchází UAC."); return; } el.privilegeBadge.title = mode === "none" ? t("Účet nemá sudo. Modul funguje v režimu čtení.") : mode === "sudo-password" ? t("Administrativní operace si vyžádají heslo pro sudo.") : ""; } function updateControls() { const busy = state.loading || state.mutating; el.sessionSelect.disabled = state.mutating; el.refreshSessionsButton.disabled = state.mutating; el.reloadButton.disabled = !connected() || busy; const readOnlyWindows = isWindows() && state.privilege?.mode !== "windows-elevated"; el.createButton.disabled = !connected() || busy || !state.inventory || state.privilege?.mode === "none" || readOnlyWindows; const canElevate = !isWindows() && connected() && state.inventory && !state.inventory.privileged && ["sudo-password", "unknown"].includes(state.privilege?.mode || "unknown"); el.elevatedButton.hidden = !canElevate; el.elevatedButton.disabled = busy; for (const button of document.querySelectorAll("[data-mutation]")) button.disabled = busy || !connected(); } // ---------- inventory ---------- async function loadInventory({ elevated = false } = {}) { const requestGeneration = state.generation; if (!connected()) return; const token = state.generation; const sessionId = state.sessionId; state.loading = true; updateControls(); setStatus(elevated ? t("Načítám rozšířený stav účtů…") : t("Načítám účty…")); try { const run = (auth) => api.users.inventory(sessionId, { ...auth, privileged: elevated }); const inventory = elevated ? await sessionResult(withSudo(t("Načtení rozšířeného stavu účtů"), run), requestGeneration) : await sessionResult(run({}), requestGeneration); if (token !== state.generation) return; applyInventory(inventory); const regular = inventory.users.filter((user) => !user.system).length; setStatus(`${t("Načteno {count} účtů ({regular} běžných)", { count: inventory.users.length, regular })}${inventory.privileged ? "" : ` – ${t("stav hesel a sudo vyžaduje sudo")}`}.`); } catch (error) { if (requestGeneration !== state.generation) return; if (token === state.generation) setStatus(describeError(error), parseError(error).code !== CANCELLED); } finally { if (requestGeneration === state.generation) { if (token === state.generation) { state.loading = false; updateControls(); } } } } function applyInventory(inventory) { state.inventory = inventory; if (inventory.privilege) state.privilege = inventory.privilege; if (state.selected && !inventory.users.some((user) => user.username === state.selected)) { state.selected = null; state.detail = null; state.detailToken += 1; } else if (state.detail) { const user = inventory.users.find((candidate) => candidate.username === state.detail.username); if (user) mergeAccount(state.detail, user, inventory.privileged); } renderPrivilege(); renderUsers(); renderDetail(); updateControls(); } function mergeAccount(detail, user, privileged) { const account = detail.account; Object.assign(account, { shell: user.shell, home: user.home, comment: user.comment, primaryGroup: user.primaryGroup, groups: user.groups, loginShell: user.loginShell, uid: user.uid, gid: user.gid }); if (privileged) Object.assign(account, { password: user.password, expired: user.expired, expireDays: user.expireDays, sudo: user.sudo }); } function filteredUsers() { const users = state.inventory?.users || []; const filter = el.filterSelect.value; const query = el.searchInput.value.trim().toLowerCase(); return users.filter((user) => (filter === "all" || (filter === "system" ? user.system : !user.system)) && (!query || user.username.includes(query) || user.comment.toLowerCase().includes(query) || String(user.uid) === query)); } function policySummary(policy) { if (!policy) return badge(t("dědí server"), "muted"); if (policy.access === "deny") return badge(t("SSH zakázáno"), "danger"); const parts = []; if (policy.password !== "inherit") parts.push(policy.password === "no" ? t("heslo ne") : t("heslo ano")); if (policy.pubkey !== "inherit") parts.push(policy.pubkey === "no" ? t("klíč ne") : t("klíč ano")); if (policy.ipv4 === "deny") parts.push(t("bez IPv4")); if (policy.ipv6 === "deny") parts.push(t("bez IPv6")); return badge(parts.join(" · ") || t("dědí server"), parts.length ? "warn" : "muted"); } function accountState(user) { if (user.platform === "windows") { const items = [badge(user.enabled ? t("povolen") : t("zakázán"), user.enabled ? "ok" : "danger")]; if (user.source && user.source !== "Local") items.push(badge(user.source === "MicrosoftAccount" ? t("účet Microsoft") : user.source, "muted")); if (user.passwordRequired === false && !user.passwordLastSet) items.push(badge(t("bez hesla"), "muted")); return items; } const items = []; if (user.expired) items.push(badge(t("deaktivován"), "danger")); const [text, tone] = PASSWORD_TEXT[user.password] || PASSWORD_TEXT.unknown; items.push(badge(t(text), tone)); if (!user.loginShell) items.push(badge(t("bez shellu"), "muted")); return items; } function renderTableHead() { const labels = isWindows() ? [t("Účet"), "SID (RID)", t("Stav"), "Administrators", "SSH (CH-J)"] : [t("Účet"), "UID", t("Stav"), "Sudo", "SSH (CH-J)"]; el.usersBody.closest("table").querySelector("thead").replaceChildren(h("tr", {}, labels.map((text) => h("th", { scope: "col", text })))); } function renderUsers() { renderTableHead(); const users = filteredUsers(); if (!state.inventory) { el.usersBody.replaceChildren(h("tr", {}, h("td", { colspan: 5, className: "empty", text: connected() ? t("Načítám…") : t("Nejsou načtena žádná data.") }))); el.inventoryNote.textContent = ""; return; } if (!users.length) { el.usersBody.replaceChildren(h("tr", {}, h("td", { colspan: 5, className: "empty", text: t("Žádný účet neodpovídá filtru.") }))); } else { el.usersBody.replaceChildren(...users.map((user) => h("tr", { className: user.username === state.selected ? "selected" : "" }, [ h("td", {}, h("button", { type: "button", className: "row-button", dataset: { username: user.username }, "aria-pressed": String(user.username === state.selected) }, [ h("strong", { text: user.username }), user.protection ? h("small", { text: user.protection === "session" ? ` (${t("tato relace")})` : user.protection === "root" ? " (root)" : user.protection === "builtin" ? ` (${t("vestavěný")})` : "" }) : null, user.comment ? h("span", { className: "sub", text: user.comment }) : null ])), h("td", { title: user.sid || "", text: user.platform === "windows" ? `…-${user.rid}` : String(user.uid) }), h("td", {}, h("div", { className: "badges" }, accountState(user))), user.platform === "windows" ? h("td", { text: user.admin ? t("člen") : "—" }) : h("td", { text: user.sudo === "unknown" ? (user.adminGroups.length ? t("skupina {groups}", { groups: user.adminGroups.join(", ") }) : "—") : SUDO_TEXT[user.sudo] ? t(SUDO_TEXT[user.sudo]) : user.sudo }), h("td", {}, policySummary(user.sshPolicy)) ]))); } const managed = state.inventory.managedPolicy; const notes = []; if (isWindows()) { if (!state.inventory.privileged) notes.push(t("Režim čtení: správa účtů, SSH a cizích klíčů vyžaduje SSH relaci správce se zvýšeným tokenem (Windows nemá sudo).")); if (state.inventory.server.serverCore) notes.push(t("Windows Server Core (bez GUI).")); if (state.inventory.server.partOfDomain) notes.push(t("Počítač je v doméně {domain}; doménové identity jsou jen pro čtení ({count} v lokálních skupinách).", { domain: state.inventory.server.domain, count: state.inventory.externalIdentities.length })); } else if (!state.inventory.privileged) notes.push(t("Režim čtení: stav hesel, expirace a skutečná sudo práva vyžadují sudo.")); if (state.inventory.server.sshLayout !== "ok" && isWindows()) notes.push(t("SSH politiku CH-J nelze v tomto sshd_config bezpečně spravovat (viz Diagnostika).")); else if (state.inventory.server.sshLayout !== "ok") notes.push(t("SSH politiku CH-J nelze na tomto serveru spravovat (sshd_config nenačítá sshd_config.d před Match).")); if (managed.state === "present" && !managed.consistent) notes.push(t("Soubor SSH politiky CH-J byl ručně upraven – CH-J ho nepřepíše.")); if (state.inventory.server.os) notes.push(t("Server: {os}.", { os: state.inventory.server.os })); el.inventoryNote.textContent = notes.join(" "); } // ---------- detail ---------- async function loadDetail(username, { elevated = false } = {}) { const requestGeneration = state.generation; if (!connected()) return; const token = state.generation; const detailToken = ++state.detailToken; const sessionId = state.sessionId; if (state.selected !== username) { state.detail = null; state.tab = state.tab || "account"; } state.selected = username; state.detailLoading = true; renderUsers(); renderDetail(); try { const run = (auth) => api.users.detail(sessionId, username, { ...auth, ...identFor(username), privileged: elevated }); const detail = elevated ? await sessionResult(withSudo(t("Detail účtu {username}", { username }), run), requestGeneration) : await sessionResult(run({}), requestGeneration); if (token !== state.generation || detailToken !== state.detailToken) return; state.detail = detail; setStatus(detail.privileged ? t("Detail účtu {username} načten včetně údajů vyžadujících sudo.", { username }) : t("Detail účtu {username} načten (režim čtení).", { username })); } catch (error) { if (requestGeneration !== state.generation) return; if (token !== state.generation || detailToken !== state.detailToken) return; setStatus(describeError(error), parseError(error).code !== CANCELLED); } finally { if (requestGeneration === state.generation) { if (token === state.generation && detailToken === state.detailToken) { state.detailLoading = false; renderDetail(); updateControls(); } } } } function renderDetail() { const detail = state.detail; el.detailEmpty.hidden = Boolean(state.selected); el.detailContent.hidden = !state.selected; el.detailEmpty.textContent = connected() ? t("Vyberte účet v seznamu.") : t("Nejprve vyberte připojenou relaci."); if (!state.selected) return; el.detailTitle.textContent = state.selected; if (!detail) { el.detailSubtitle.textContent = state.detailLoading ? t("Načítám detail…") : t("Detail se nepodařilo načíst."); el.detailBadges.replaceChildren(); el.detailNotice.hidden = true; for (const panel of ["account", "groups", "ssh", "keys", "diagnostics"]) el[`panel-${panel}`].replaceChildren(); return; } const account = detail.account; el.detailSubtitle.textContent = (account.platform === "windows" ? [account.fullName, account.sid, account.profilePath] : [account.comment, `UID ${account.uid}`, account.home]).filter(Boolean).join(" · ") + (state.detailLoading ? ` · ${t("obnovuji…")}` : ""); el["tab-groups"].textContent = account.platform === "windows" ? t("Skupiny a správci") : t("Skupiny a sudo"); el.detailBadges.replaceChildren(...[ account.protection ? badge(account.protection === "session" ? t("aktivní relace") : account.protection === "root" ? "root" : account.protection === "builtin" ? t("vestavěný") : t("systémový"), "warn") : null, badge(detail.privileged ? (detail.platform === "windows" ? t("ověřeno se zvýšeným tokenem") : t("ověřeno se sudo")) : t("režim čtení"), detail.privileged ? "ok" : "muted"), ...accountState(account) ].filter(Boolean)); const notices = []; if (account.protection) notices.push(t(PROTECTION_TEXT[account.protection])); if (!detail.privileged) notices.push(detail.platform === "windows" ? t("Skutečná SSH konfigurace (sshd -T), klíče jiných účtů a změny vyžadují SSH relaci správce se zvýšeným tokenem. Windows nemá sudo a CH-J neobchází UAC.") : t("Část údajů (stav hesla, sudo, skutečná SSH konfigurace, klíče jiných účtů) vyžaduje sudo.")); el.detailNotice.replaceChildren(...notices.map((text) => h("p", { text }))); if (!detail.privileged && detail.platform !== "windows") el.detailNotice.append(h("button", { type: "button", className: "button", text: t("Načíst údaje se sudo"), onclick: () => loadDetail(detail.username, { elevated: true }) })); el.detailNotice.hidden = !notices.length; renderAccountTab(detail); renderGroupsTab(detail); renderSshTab(detail); renderKeysTab(detail); renderDiagnosticsTab(detail); selectTab(state.tab, false); updateControls(); } function infoGrid(rows) { return h("dl", { className: "info-grid" }, rows.flatMap(([label, value]) => [h("dt", { text: label }), h("dd", {}, value instanceof Node ? value : String(value ?? "—"))])); } function actionButton(label, onClick, { danger = false, sudo = true, title = "" } = {}) { return h("button", { type: "button", className: `button${danger ? " danger" : ""}`, dataset: { mutation: "1" }, title: title || (sudo ? t("Vyžaduje oprávnění správce (sudo)") : ""), onclick: onClick }, [label, sudo ? h("span", { className: "sudo-mark", text: " sudo" }) : null]); } function section(title, children, hint = "") { return h("section", { className: "sub-panel" }, [h("h4", { text: title }), hint ? h("p", { className: "hint", text: hint }) : null, ...[].concat(children)]); } function renderAccountTab(detail) { if (detail.platform === "windows") { renderWindowsAccountTab(detail); return; } const account = detail.account; const [passwordText] = PASSWORD_TEXT[account.password] || PASSWORD_TEXT.unknown; const expiry = account.expired ? t("deaktivován (expirovaný účet)") : account.expireDays ? t("platný do {date}", { date: new Date(account.expireDays * 86400000).toISOString().slice(0, 10) }) : account.password === "unknown" ? t("neznámý (vyžaduje sudo)") : t("aktivní"); const children = [infoGrid([ [t("Uživatelské jméno"), account.username], [t("Celé jméno"), account.comment || "—"], ["UID / GID", `${account.uid} / ${account.gid}`], [t("Primární skupina"), account.primaryGroup], [t("Domovský adresář"), `${account.home}${account.homeMeta && account.homeMeta !== "absent" ? ` (${account.homeMeta})` : account.homeMeta === "absent" ? ` (${t("neexistuje")})` : ""}`], ["Shell", `${account.shell}${account.loginShell ? "" : ` – ${t("interaktivní přihlášení vypnuto")}`}`], [t("Heslo"), t(passwordText)], [t("Stav účtu"), expiry], [t("Typ"), account.uid === 0 ? "root" : account.system ? t("systémový účet") : t("běžný účet")], [t("Spuštěné procesy"), account.processes === null ? "—" : String(account.processes)] ]), h("p", { className: "hint", text: t("Zamknutí hesla (passwd -l) nebrání přihlášení SSH klíčem. Úplné zablokování: Deaktivovat účet, nebo SSH přístup → Zakázat.") })]; if (!account.protection) { const actions = [actionButton(t("Změnit heslo…"), () => changePassword(account.username))]; if (account.password === "locked") actions.push(actionButton(t("Odemknout heslo"), () => simpleAction("unlock", account.username, t("Odemknutí hesla")))); else if (account.password === "set") actions.push(actionButton(t("Zamknout heslo"), () => simpleAction("lock", account.username, t("Zamknutí hesla")))); actions.push(account.expired ? actionButton(t("Aktivovat účet"), () => simpleAction("unexpire", account.username, t("Aktivace účtu"))) : actionButton(t("Deaktivovat účet"), () => simpleAction("expire", account.username, t("Deaktivace účtu"), t("Účet se nebude moci přihlásit žádnou metodou (ani SSH klíčem). Data zůstanou zachována.")))); actions.push(actionButton(t("Upravit celé jméno…"), () => changeComment(account))); actions.push(actionButton(t("Změnit domovský adresář…"), () => changeHome(account))); actions.push(actionButton(t("Odstranit účet…"), () => deleteAccount(account), { danger: true })); children.push(h("div", { className: "inline-actions" }, actions)); const shells = [...new Set([...(state.inventory?.shells || []), "/usr/sbin/nologin", "/bin/false", account.shell])].filter(Boolean); const shellSelect = h("select", { "aria-label": "Shell" }, shells.map((shell) => h("option", { value: shell, text: shell, selected: shell === account.shell }))); children.push(section("Shell", h("div", { className: "inline-actions" }, [shellSelect, actionButton(t("Uložit shell"), () => { if (shellSelect.value === account.shell) return; void runMutation(t("Změna shellu"), (sessionId, auth) => api.users.manage(sessionId, { action: "setShell", ...identFor(account.username), shell: shellSelect.value, ...auth })); })]), t("nologin/false zablokuje interaktivní přihlášení, ale ne nutně všechny SSH funkce (např. přesměrování portů)."))); } el["panel-account"].replaceChildren(...children); } function renderGroupsTab(detail) { if (detail.platform === "windows") { renderWindowsGroupsTab(detail); return; } const account = detail.account; const groups = state.inventory?.groups || []; const editable = !account.protection; const children = []; const memberRows = account.groups.length ? account.groups.map((group) => h("li", {}, [h("span", { text: group }), editable && group !== account.primaryGroup ? h("button", { type: "button", className: "mini", dataset: { mutation: "1" }, text: t("Odebrat"), onclick: () => removeGroup(account.username, group) }) : null])) : [h("li", { className: "muted", text: t("Žádné doplňkové skupiny.") })]; children.push(section(t("Skupiny"), [ infoGrid([[t("Primární skupina"), account.primaryGroup]]), h("ul", { className: "chip-list" }, memberRows) ])); if (editable && groups.length) { const candidates = groups.filter((group) => !account.groups.includes(group.name) && group.name !== account.primaryGroup).sort((left, right) => left.name.localeCompare(right.name)); const addSelect = h("select", { "aria-label": t("Přidat do skupiny") }, candidates.map((group) => h("option", { value: group.name, text: `${group.name} (${group.gid})` }))); const primarySelect = h("select", { "aria-label": t("Primární skupina") }, groups.slice().sort((left, right) => left.name.localeCompare(right.name)).map((group) => h("option", { value: group.name, text: `${group.name} (${group.gid})`, selected: group.name === account.primaryGroup }))); children.push(section(t("Změnit členství"), [ h("div", { className: "inline-actions" }, [addSelect, actionButton(t("Přidat do skupiny"), () => addGroup(account.username, addSelect.value))]), h("div", { className: "inline-actions" }, [primarySelect, actionButton(t("Nastavit primární skupinu"), () => setPrimary(account.username, primarySelect.value, account.primaryGroup))]) ], t("Ostatní skupiny a nesouvisející oprávnění zůstávají zachované."))); } const sudoState = account.sudo || "unknown"; const adminGroups = state.inventory?.adminGroups || []; const sudoChildren = [infoGrid([ [t("Skutečný stav (sudo -l)"), sudoState === "unknown" ? t("neznámý – vyžaduje sudo") : SUDO_TEXT[sudoState] ? t(SUDO_TEXT[sudoState]) : sudoState], [t("Členství ve skupinách správců"), ["sudo", "wheel", "admin"].filter((name) => account.groups.includes(name) || account.primaryGroup === name).join(", ") || t("žádné")], [t("Skupiny s pravidlem v sudoers"), adminGroups.length ? adminGroups.join(", ") : state.inventory?.privileged ? t("žádná") : t("neznámé (vyžaduje sudo)")] ]), h("p", { className: "hint", text: t("Členství ve skupině samo nezaručuje funkční sudo. CH-J nikdy nemění sudoers a nenastavuje NOPASSWD.") })]; if (editable) { sudoChildren.push(h("div", { className: "inline-actions" }, [ actionButton(t("Přidat sudo"), () => simpleAction("grantAdmin", account.username, t("Přidání sudo"), t("Účet bude přidán do skupiny správců, na kterou odkazuje sudoers."))), actionButton(t("Odebrat sudo"), () => simpleAction("revokeAdmin", account.username, t("Odebrání sudo"), t("Účet bude odebrán ze skupin sudo/wheel/admin. Pravidla sudoers pro konkrétní účet zůstanou beze změny.")), { danger: true }) ])); } children.push(section("Sudo", sudoChildren)); el["panel-groups"].replaceChildren(...children); } function effectiveCell(detail, family, key) { const effective = detail.ssh.effective[family]; if (!effective) return h("span", { className: "muted", text: detail.privileged ? t("nedostupné") : t("vyžaduje sudo") }); const yesNo = (value) => value === "yes" ? badge(t("povoleno"), "ok") : value === "no" ? badge(t("zakázáno"), "danger") : badge(value, "muted"); if (key === "password") return yesNo(effective.methods.password ? "yes" : "no"); if (key === "pubkey") return yesNo(effective.methods.publickey ? "yes" : "no"); const listener = detail.ssh.effective.listener; if (listener && listener[family] === false) return badge(t("sshd nenaslouchá"), "danger"); if (effective.allowed === true) return badge(t("povoleno"), "ok"); if (effective.allowed === null) return badge(t("nejisté"), "warn"); const managedOnly = effective.reasons.every((reason) => reason.managed); return h("span", { title: effective.reasons.map((reason) => `${reason.rule} ${reason.entry}`).join(", ") }, badge(managedOnly ? t("zakázáno (CH-J)") : t("zakázáno (pravidla serveru)"), "danger")); } function renderSshTab(detail) { const ssh = detail.ssh; const account = detail.account; const children = []; if (!ssh.available && detail.privileged) { el["panel-ssh"].replaceChildren(h("p", { className: "notice", text: t("Na serveru nebyl nalezen OpenSSH server (sshd).") })); return; } const windows = detail.platform === "windows"; const blocked = windows ? account.protection === "builtin" : account.system; const rows = !windows && account.uid === 0 ? [...POLICY_ROWS, ROOT_LOGIN_ROW] : POLICY_ROWS; const reason = blocked ? (windows ? t("SSH přístup vestavěných účtů Windows CH-J nespravuje.") : t("SSH přístup systémových účtů CH-J nespravuje.")) : !detail.privileged ? (windows ? t("Skutečný stav a změny SSH vyžadují SSH relaci správce se zvýšeným tokenem.") : t("Skutečný stav a změny SSH vyžadují sudo.")) : windows && !ssh.sshName ? t("Název účtu obsahuje znaky, které nelze bezpečně použít v sshd_config.") : !ssh.layoutSupported ? (windows ? t("sshd_config nelze bezpečně upravit: {problems}", { problems: (ssh.layoutProblems || []).join("; ") }) : t("sshd_config nenačítá sshd_config.d před prvním blokem Match – CH-J hlavní konfiguraci neupravuje.")) : ssh.managed.state === "present" && !ssh.managed.consistent ? t("{path} byl ručně upraven – CH-J ho nepřepíše.", { path: ssh.managed.path }) : ssh.syntaxOk === false ? t("Současná konfigurace SSH je neplatná: {message}", { message: ssh.syntaxMessage }) : ""; const form = h("form", { className: "policy-form" }); const table = h("table", { className: "policy-table" }, [ h("thead", {}, h("tr", {}, [h("th", { text: t("Nastavení") }), h("th", { text: t("Požadováno (CH-J)") }), h("th", { text: `${t("Skutečně IPv4")}${ssh.effective.ipv4?.sample ? ` (${t("vzorová adresa")})` : ""}` }), h("th", { text: `${t("Skutečně IPv6")}${ssh.effective.ipv6?.sample ? ` (${t("vzorová adresa")})` : ""}` })])), h("tbody", {}, rows.map((row) => { const current = ssh.policy[row.key]; const options = h("div", { className: "segmented", role: "radiogroup", "aria-label": t(row.label) }, row.options.map(([value, label]) => h("label", {}, [ h("input", { type: "radio", name: `policy-${row.key}`, value, checked: current === value, disabled: Boolean(reason) }), h("span", { text: t(label) }) ]))); const family = row.key === "ipv4" ? ["ipv4"] : row.key === "ipv6" ? ["ipv6"] : ["ipv4", "ipv6"]; const effectiveKey = row.key === "ipv4" || row.key === "ipv6" ? "access" : row.key; if (row.key === "permitRootLogin") { const shown = (family) => { const value = detail.ssh.effective[family]?.permitRootLogin; const text = value === "without-password" ? "prohibit-password" : value; return text ? badge({ no: t("zakázáno"), "prohibit-password": t("jen klíč"), "forced-commands-only": t("klíč s vynuceným příkazem"), yes: t("heslo i klíč") }[text] || text, text === "no" ? "danger" : text === "yes" ? "warn" : "ok") : h("span", { className: "muted", text: detail.privileged ? t("nedostupné") : t("vyžaduje sudo") }); }; return h("tr", {}, [h("th", { scope: "row" }, [h("span", { text: t(row.label) }), h("small", { className: "sub", text: t(row.hint) })]), h("td", {}, options), h("td", {}, shown("ipv4")), h("td", {}, shown("ipv6"))]); } return h("tr", {}, [ h("th", { scope: "row" }, [h("span", { text: t(row.label) }), h("small", { className: "sub", text: t(row.hint) })]), h("td", {}, options), h("td", {}, family.includes("ipv4") ? effectiveCell(detail, "ipv4", effectiveKey) : h("span", { className: "muted", text: "—" })), h("td", {}, family.includes("ipv6") ? effectiveCell(detail, "ipv6", effectiveKey) : h("span", { className: "muted", text: "—" })) ]); })) ]); form.append(table); if (reason) form.append(h("p", { className: "notice", text: reason })); else { if (windows) form.append(h("p", { className: "notice warn", text: t("Windows OpenSSH vyžaduje po změně restart služby sshd. Před restartem se na serveru aktivuje nezávislá úloha (SYSTEM), která do 120 s vrátí původní sshd_config, pokud změnu nepotvrdí nové SSH přihlášení. Původní relace se může přerušit.") })); if (detail.self) form.append(h("p", { className: "notice warn", text: t("Měníte účet aktivní relace. Core ověří přes sshd -T, že vaše současné přihlášení zůstane povolené, a po reloadu zkusí nové SSH přihlášení. Při selhání se konfigurace automaticky vrátí.") })); form.append(h("div", { className: "inline-actions" }, [h("button", { type: "submit", className: "button primary", dataset: { mutation: "1" }, text: windows ? t("Uložit, restartovat sshd a ověřit") : t("Uložit a ověřit (sudo)") })])); form.addEventListener("submit", (event) => { event.preventDefault(); void saveSshPolicy(detail, form); }); } children.push(form); if (windows) children.push(h("p", { className: "hint", text: t("Na Windows zapisuje CH-J dvě označené sekce přímo do C:\\ProgramData\\ssh\\sshd_config: DenyUsers před první existující blok Match a vlastní Match User na konec. KbdInteractiveAuthentication se nepoužívá (Windows OpenSSH ji nepodporuje). Před restartem proběhne sshd -t a sshd -T -C nad kandidátní konfigurací.") })); else children.push(h("p", { className: "hint", text: t("Pravidla zapisuje CH-J do vlastního souboru sshd_config.d (DenyUsers user@0.0.0.0/0, user@::/0 a Match User). Před reloadem proběhne sshd -t a kontrola účinného nastavení sshd -T -C; neplatná nebo neúčinná změna se vrátí. Používá se reload, ne restart.") })); for (const warning of ssh.warnings) children.push(h("p", { className: "notice warn", text: translateWarning(warning) })); const reasons = ["ipv4", "ipv6"].flatMap((family) => (ssh.effective[family]?.reasons || []).map((item) => `${family.toUpperCase()}: ${item.rule} ${item.entry}${item.managed ? " (CH-J)" : ""}${item.uncertain ? ` – ${t("nelze vyhodnotit bez DNS")}` : ""}`)); if (reasons.length) children.push(section(t("Pravidla omezující přístup"), h("ul", { className: "details-list" }, [...new Set(reasons)].map((text) => h("li", { text }))))); el["panel-ssh"].replaceChildren(...children); } function translateWarning(text) { if (/does not listen on IPv6/.test(text)) return t("sshd nenaslouchá na IPv6 – přihlášení přes IPv6 není možné bez ohledu na nastavení účtu."); if (/does not listen on IPv4/.test(text)) return t("sshd nenaslouchá na IPv4 – přihlášení přes IPv4 není možné bez ohledu na nastavení účtu."); if (/AuthorizedKeysCommand/.test(text)) return t("Je nastaven AuthorizedKeysCommand – klíče mohou pocházet i z externího zdroje, který CH-J nespravuje."); if (/edited manually/.test(text)) return t("Soubor SSH politiky CH-J byl ručně upraven; CH-J ho nepřepíše."); return text; } function renderKeysTab(detail) { const files = detail.keys.files; const account = detail.account; const children = []; if (files.some((file) => file.shared)) children.push(h("p", { className: "notice warn", text: t("Účet je správce: Windows OpenSSH používá sdílený soubor administrators_authorized_keys. Každý klíč v něm umožní přihlášení ke všem účtům ze skupiny Administrators; klíče proto nelze přiřadit jednomu účtu.") })); if (!files.length || (!detail.privileged && !detail.self)) { children.push(h("p", { className: "notice", text: detail.privileged || detail.self ? t("Soubor authorized_keys nebyl nalezen.") : detail.platform === "windows" ? t("Klíče jiného účtu lze číst jen ze SSH relace správce se zvýšeným tokenem.") : t("Klíče jiného účtu lze číst jen se sudo (soubor má práva 0600).") })); } const reasons = { "needs-elevation": k("vyžaduje zvýšený token správce"), "profile-missing": k("profil účtu zatím neexistuje (účet se ještě nepřihlásil)"), "outside-home": k("mimo domovský adresář"), symlink: k("symbolický odkaz"), "not-regular": k("není běžný soubor"), unreadable: k("nelze přečíst"), "unsupported-token": k("nepodporovaný token v AuthorizedKeysFile"), "too-large": k("příliš velký"), unknown: k("neznámý stav") }; for (const [index, file] of files.entries()) { if (!detail.privileged && !detail.self) break; const status = file.type === "file" ? t("počet klíčů: {count}", { count: file.entries.filter((entry) => entry.valid).length }) : file.type === "absent" || file.type === "absent-dir" ? t("zatím neexistuje") : file.type; const rows = file.entries.map((entry) => entry.valid ? h("tr", {}, [ h("td", { text: entry.type }), h("td", { className: "mono", text: entry.fingerprint }), h("td", { text: entry.comment || "—" }), h("td", { className: "mono", text: entry.options || "—" }), h("td", { text: String(entry.line) }), h("td", {}, account.protection === "system" || account.protection === "builtin" || !file.manageable ? null : h("button", { type: "button", className: "mini danger", dataset: { mutation: "1" }, text: t("Odebrat"), onclick: () => removeKey(detail, file, entry) })) ]) : h("tr", { className: "invalid" }, [h("td", { colspan: 6, text: t("Řádek {line}: nerozpoznaný záznam ({type}) – zůstane beze změny.", { line: entry.line, type: entry.type || entry.reason }) })])); children.push(section(index === 0 ? t("Primární soubor: {path}", { path: file.path }) : t("Další soubor: {path}", { path: file.path }), [ h("p", { className: "hint", text: `${status} · ${file.meta || ""}${file.dirMeta ? ` · ${t("adresář {meta}", { meta: file.dirMeta })}` : ""}${file.manageable ? "" : ` · ${t("nelze spravovat: {reason}", { reason: reasons[file.reason] ? t(reasons[file.reason]) : file.reason })}`}` }), rows.length ? h("div", { className: "table-wrap" }, h("table", {}, [h("thead", {}, h("tr", {}, [t("Typ"), t("Otisk SHA256"), t("Komentář"), t("Volby"), t("Řádek"), ""].map((text) => h("th", { text })))), h("tbody", {}, rows)])) : null ])); } const primary = files[0]; if (!account.protection || account.protection === "session" || account.protection === "root") { if ((detail.platform === "windows" ? account.protection !== "builtin" : !account.system) && (detail.privileged || detail.self)) { children.push(h("div", { className: "inline-actions" }, [ h("button", { type: "button", className: "button primary", dataset: { mutation: "1" }, disabled: !primary?.manageable, text: t("Přidat Ed25519 klíč…"), onclick: () => addKey(detail) }) ])); } } if (detail.platform === "windows") children.push(h("p", { className: "hint", text: t("Soukromé klíče se nikdy neodesílají na server. Úprava zachová ostatní řádky beze změny a zachová existující ACL souboru (ReplaceFile). Nový soubor dostane ACL jen pro SYSTEM, Administrators a u běžného účtu jeho vlastníka.") })); else children.push(h("p", { className: "hint", text: t("Soukromé klíče se nikdy neodesílají na server. Úprava zachová všechny ostatní řádky, komentáře a volby klíčů beze změny; zápis probíhá atomicky pod identitou cílového účtu (0700 .ssh, 0600 authorized_keys).") })); el["panel-keys"].replaceChildren(...children); } function renderDiagnosticsTab(detail) { if (detail.platform === "windows") { renderWindowsDiagnosticsTab(detail); return; } const ssh = detail.ssh; const privilege = state.privilege; const listener = ssh.effective.listener; const files = detail.keys.files; const rows = [ [t("Oprávnění relace"), privilege ? `${privilege.username}: ${t((PRIVILEGE_TEXT[privilege.mode] || PRIVILEGE_TEXT.unknown)[0])}${privilege.verified ? "" : ` (${t("neověřeno")})`}` : t("neověřeno")], [t("Adresa klienta (SSH_CLIENT)"), privilege?.clientAddress || t("neznámá")], ["OpenSSH", ssh.version || (ssh.available ? t("neznámá verze") : t("nenalezen"))], [t("Služba SSH"), ssh.service || t("neznámý stav")], [t("Kontrola sshd -t"), ssh.syntaxOk === null ? t("vyžaduje sudo") : ssh.syntaxOk ? t("v pořádku") : t("CHYBA: {message}", { message: ssh.syntaxMessage })], [t("Struktura konfigurace"), { ok: t("Include sshd_config.d před Match – podporováno"), "include-missing": t("sshd_config.d se nenačítá – nepodporováno"), "include-after-match": t("Include až za blokem Match – nepodporováno") }[ssh.layout] || ssh.layout], [t("Soubor spravovaný CH-J"), `${ssh.managed.path} – ${{ absent: t("neexistuje"), present: ssh.managed.consistent ? t("v pořádku") : t("ručně upraven"), unsafe: t("není běžný soubor"), unreadable: t("nečitelný") }[ssh.managed.state] || ssh.managed.state}`], [t("Naslouchání sshd"), listener ? `IPv4: ${listener.ipv4 ? t("ano") : t("ne")}, IPv6: ${listener.ipv6 ? t("ano") : t("ne")}` : t("vyžaduje sudo")], ["AuthorizedKeysCommand", ssh.effective.authorizedKeysCommand || (detail.privileged ? t("není nastaven") : t("vyžaduje sudo"))], [t("Domovský adresář"), detail.account.homeMeta || "—"], ...files.map((file) => [t("Klíče {spec}", { spec: file.spec || file.path }), `${file.path} – ${file.type}${file.meta ? `, ${file.meta}` : ""}${file.dirMeta ? `, ${t("adresář {meta}", { meta: file.dirMeta })}` : ""}`]), [t("Načteno"), new Date(detail.collectedAt).toLocaleString(i18n.locale())] ]; const strict = []; for (const file of files) { const [owner, , mode] = String(file.meta || "").split(":"); if (file.type === "file" && owner && owner !== detail.username && owner !== "root") strict.push(t("{path} nevlastní {user} (StrictModes může klíče ignorovat).", { path: file.path, user: detail.username })); if (file.type === "file" && mode && /[2367]$|[2367].$/.test(mode)) strict.push(t("{path} je zapisovatelný pro skupinu/ostatní ({mode}); sshd s StrictModes klíče odmítne.", { path: file.path, mode })); } el["panel-diagnostics"].replaceChildren(infoGrid(rows), ...strict.map((text) => h("p", { className: "notice warn", text })), ...ssh.warnings.map((text) => h("p", { className: "notice warn", text: translateWarning(text) }))); } function selectTab(name, focus = true) { state.tab = name; for (const tab of document.querySelectorAll("[role=tab]")) { const selected = tab.id === `tab-${name}`; tab.setAttribute("aria-selected", String(selected)); tab.tabIndex = selected ? 0 : -1; el[tab.getAttribute("aria-controls")].hidden = !selected; if (selected && focus) tab.focus(); } } // ---------- Windows variants (SID, Administrators, account state; no UID/shell/sudo) ---------- function formatDate(value) { return value ? new Date(value).toLocaleString(i18n.locale()) : "—"; } function renderWindowsAccountTab(detail) { const account = detail.account; const children = [infoGrid([ [t("Uživatelské jméno"), account.username], [t("Celé jméno"), account.fullName || "—"], [t("Popis"), account.description || "—"], ["SID", account.sid], [t("Zdroj"), account.source === "MicrosoftAccount" ? t("lokální účet propojený s účtem Microsoft") : account.source || "—"], [t("Stav účtu"), account.enabled ? t("povolen") : t("zakázán")], [t("Heslo naposledy nastaveno"), formatDate(account.passwordLastSet)], [t("Platnost hesla"), account.passwordExpires ? formatDate(account.passwordExpires) : t("neomezená")], [t("Platnost účtu"), account.accountExpires ? formatDate(account.accountExpires) : t("neomezená")], [t("Poslední přihlášení"), formatDate(account.lastLogon)], [t("Profil"), account.profilePath || t("zatím nevytvořen")], [t("Typ"), account.protection === "builtin" ? t("vestavěný účet") : t("běžný lokální účet")], ["Administrators (S-1-5-32-544)", account.admin ? t("člen") : t("není člen")] ]), h("p", { className: "hint", text: t("Windows účty se identifikují podle SID. UID/GID, shell ani sudo se na Windows nepoužívají. Zakázaný účet se nepřihlásí žádnou metodou včetně SSH klíče.") })]; if (!account.protection && detail.privileged) { children.push(h("div", { className: "inline-actions" }, [ actionButton(t("Změnit heslo…"), () => changePassword(account.username), { sudo: false }), account.enabled ? actionButton(t("Zakázat účet"), () => simpleAction("disable", account.username, t("Zakázání účtu"), t("Účet se nebude moci přihlásit žádnou metodou. Data a profil zůstanou zachovány.")), { sudo: false, danger: true }) : actionButton(t("Povolit účet"), () => simpleAction("enable", account.username, t("Povolení účtu")), { sudo: false }), actionButton(t("Upravit celé jméno…"), () => changeWindowsText(account, "setFullName", t("Celé jméno"), account.fullName, 256), { sudo: false }), actionButton(t("Upravit popis…"), () => changeWindowsText(account, "setDescription", t("Popis"), account.description, 48), { sudo: false }), actionButton(t("Odstranit účet…"), () => deleteAccount(account), { danger: true, sudo: false }) ])); } else if (!account.protection) { children.push(h("p", { className: "notice", text: t("Změny účtu vyžadují SSH relaci správce se zvýšeným tokenem.") })); } el["panel-account"].replaceChildren(...children); } function renderWindowsGroupsTab(detail) { const account = detail.account; const editable = !account.protection && detail.privileged; const groups = state.inventory?.groups || []; const memberSids = new Set(account.groups.map((group) => group.sid)); const children = [section(t("Lokální skupiny"), [ h("ul", { className: "chip-list" }, account.groups.length ? account.groups.map((group) => h("li", { title: group.sid }, [ h("span", { text: group.name }), editable ? h("button", { type: "button", className: "mini", dataset: { mutation: "1" }, text: t("Odebrat"), onclick: () => removeWindowsGroup(account, group) }) : null ])) : [h("li", { className: "muted", text: t("Účet není členem žádné lokální skupiny.") })]) ], t("Názvy skupin jsou lokalizované; CH-J pracuje se skupinami podle SID."))]; if (editable) { const candidates = groups.filter((group) => !memberSids.has(group.sid) && group.sid !== "S-1-5-32-544").sort((left, right) => left.name.localeCompare(right.name)); const select = h("select", { "aria-label": t("Přidat do skupiny") }, candidates.map((group) => h("option", { value: group.sid, text: group.name }))); children.push(section(t("Přidat do skupiny"), h("div", { className: "inline-actions" }, [select, actionButton(t("Přidat"), () => { const group = candidates.find((candidate) => candidate.sid === select.value); if (group) void runMutation(t("Přidání do skupiny {group}", { group: group.name }), (sessionId, auth) => api.users.manage(sessionId, { action: "addGroup", ...identFor(account.username), group: group.sid, ...auth })); }, { sudo: false })]))); } const tokenMode = t((PRIVILEGE_TEXT[detail.privilege?.mode] || PRIVILEGE_TEXT.unknown)[0]); const adminChildren = [infoGrid([ [t("Členství v Administrators"), account.admin ? t("člen (S-1-5-32-544)") : t("není člen")], [t("Token této SSH relace"), tokenMode] ]), h("p", { className: "hint", text: t("Členství ve skupině Administrators neznamená automaticky zvýšený token procesu (UAC). Na Windows se nepoužívá sudo a CH-J neobchází UAC ani bezpečnostní politiku.") })]; if (editable) { adminChildren.push(h("div", { className: "inline-actions" }, [ account.admin ? actionButton(t("Odebrat z Administrators"), () => simpleAction("revokeAdmin", account.username, t("Odebrání administrátorských oprávnění"), t("Účet bude odebrán ze skupiny Administrators (S-1-5-32-544). Posledního povoleného správce CH-J neodebere.")), { danger: true, sudo: false }) : actionButton(t("Přidat do Administrators"), () => simpleAction("grantAdmin", account.username, t("Přidání administrátorských oprávnění"), t("Účet bude přidán do skupiny Administrators (S-1-5-32-544). Jeho SSH klíče se pak čtou ze sdíleného administrators_authorized_keys.")), { sudo: false }) ])); } children.push(section(t("Správci"), adminChildren)); const external = state.inventory?.externalIdentities || []; if (external.length) { children.push(section(t("Doménové a cloudové identity v lokálních skupinách (jen pro čtení)"), h("ul", { className: "details-list" }, external.map((item) => h("li", { text: `${item.name} (${item.sid}, ${item.source}) – ${item.groups.join(", ")}` }))))); } el["panel-groups"].replaceChildren(...children); } function renderWindowsDiagnosticsTab(detail) { const ssh = detail.ssh; const system = detail.system || {}; const privilege = detail.privilege || state.privilege || {}; const listener = ssh.effective.listener; const rows = [ [t("Systém"), `${system.caption || "Windows"} ${system.version || ""} (build ${system.build || "?"})`], [t("Typ instalace"), system.installationType ? `${system.installationType}${system.serverCore ? ` – ${t("bez GUI")}` : ""}` : "—"], [t("Detekce platformy"), `${system.detectedBy || "?"}${system.unameOutput ? `, uname: ${system.unameOutput}` : ""}`], [t("Výchozí SSH shell"), `${system.defaultShell || "?"}${system.defaultShellPath ? ` (${system.defaultShellPath})` : ` (${t("výchozí cmd.exe")})`}`], [t("PowerShell pro CH-J"), `${system.powershell || "?"}${system.is64BitProcess ? ", 64bit" : ", 32bit!"}, ${system.languageMode || "?"}${system.pwsh ? `; PowerShell 7: ${system.pwsh}` : `; ${t("PowerShell 7 nenalezen")}`}`], ["LocalAccounts", system.localAccounts ? t("dostupný") : t("nedostupný")], [t("Token relace"), `${privilege.username || "?"} – ${t((PRIVILEGE_TEXT[privilege.mode] || PRIVILEGE_TEXT.unknown)[0])}, ${t("integrita {level}", { level: privilege.integrity || "?" })}`], [t("Adresa klienta (SSH_CLIENT)"), privilege.clientAddress || t("neznámá")], ["OpenSSH Server", ssh.version || (ssh.available ? t("neznámá verze") : t("nenainstalován"))], [t("Služba sshd"), ssh.service || "—"], ["sshd_config", ssh.configPath || "—"], [t("Kontrola sshd -t"), ssh.syntaxOk === null ? t("vyžaduje zvýšený token") : ssh.syntaxOk ? t("v pořádku") : t("CHYBA: {message}", { message: ssh.syntaxMessage })], [t("Spravované sekce CH-J"), ssh.layoutSupported ? (ssh.managed.state === "present" ? (ssh.managed.consistent ? t("přítomny, v pořádku") : t("ručně upraveny")) : t("zatím nejsou")) : t("nepodporováno: {problems}", { problems: (ssh.layoutProblems || []).join("; ") })], [t("Naslouchání sshd"), listener ? `IPv4: ${listener.ipv4 ? t("ano") : t("ne")}, IPv6: ${listener.ipv6 ? t("ano") : t("ne")}` : t("vyžaduje zvýšený token")], [t("Aplikace změn"), t("restart služby sshd s nezávislým rollbackem (naplánovaná úloha SYSTEM, 120 s)")], ...detail.keys.files.map((file) => [t("Klíče {spec}", { spec: file.spec || "" }), `${file.path || t("nevyřešeno")} – ${file.type}${file.shared ? ` (${t("sdílený")})` : ""}${file.acl?.length ? `; ACL: ${file.acl.map((entry) => `${entry.sid}:${entry.rights}`).join(", ")}` : ""}`]), [t("Načteno"), new Date(detail.collectedAt).toLocaleString(i18n.locale())] ]; el["panel-diagnostics"].replaceChildren(infoGrid(rows), ...ssh.warnings.map((text) => h("p", { className: "notice warn", text: translateWarning(text) }))); } async function changeWindowsText(account, action, label, value, limit) { const requestGeneration = state.generation; try { const answer = await sessionResult(askValue({ title: label, label, value: value || "", validate: ({ value: text }) => text.length > limit || /[\x00-\x1f]/.test(text) ? t("Max. {limit} znaků bez řídicích znaků.", { limit }) : "" }), requestGeneration); if (!answer) return; const field = action === "setDescription" ? "description" : "fullName"; await sessionResult(runMutation(t("Úprava: {label}", { label }), (sessionId, auth) => api.users.manage(sessionId, { action, ...identFor(account.username), [field]: answer.value.trim(), ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function removeWindowsGroup(account, group) { const requestGeneration = state.generation; try { const answer = await sessionResult(confirmAction({ title: t("Odebrat ze skupiny {group}", { group: group.name }), message: t("Účet {user} přestane být členem skupiny {group} ({sid}). Ostatní skupiny zůstanou.", { user: account.username, group: group.name, sid: group.sid }), confirmLabel: t("Odebrat"), danger: true }), requestGeneration); if (!answer) return; await sessionResult(runMutation(t("Odebrání ze skupiny {group}", { group: group.name }), (sessionId, auth) => api.users.manage(sessionId, { action: "removeGroup", ...identFor(account.username), group: group.sid, ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } // ---------- mutations ---------- async function runMutation(label, invoke, { successMessage } = {}) { const requestGeneration = state.generation; if (state.mutating || !connected()) return null; const token = state.generation; const sessionId = state.sessionId; if (!window.confirm(`${api.sessions.displayName(state.sessions.find((session) => session.sessionId === sessionId))}\n\n${label}`)) return null; state.mutating = true; updateControls(); setStatus(`${label}…`); try { const result = await sessionResult(withSudo(label, (auth) => invoke(sessionId, auth)), requestGeneration); if (token !== state.generation) return null; if (result?.inventory) applyInventory(result.inventory); if (result?.sessionLost) { setStatus(t("Změna byla potvrzena, ale původní SSH relace se restartem sshd ukončila. Připojte se znovu v hlavním okně."), true); void loadSessions(); return result; } if (result?.detail) { // Keep the list column in sync with the verified policy returned by Core. const listed = state.inventory?.users.find((user) => user.username === result.detail.username); if (listed) { const current = result.detail.ssh.policy; listed.sshPolicy = POLICY_ROWS.every((row) => current[row.key] === row.options[0][0]) ? null : { ...current }; renderUsers(); } if (state.selected === result.detail.username) { state.detailToken += 1; state.detail = result.detail; state.detailLoading = false; renderDetail(); } } const failedSteps = (result?.steps || []).filter((step) => step.status === "failed"); const warnings = [...(result?.warnings || []), ...failedSteps.map((step) => t("Krok {step} selhal: {message}", { step: step.step, message: step.message }))]; const partial = result?.result === "partial" || failedSteps.length > 0; setStatus(`${successMessage || t("{label}: hotovo, stav byl znovu načten ze serveru.", { label })}${partial ? ` ${t("Pouze částečně!")}` : ""}${warnings.length ? ` ${warnings.join(" ")}` : ""}`, partial); return result; } catch (error) { if (requestGeneration !== state.generation) return; if (token === state.generation) setStatus(describeError(error), parseError(error).code !== CANCELLED); return null; } finally { if (requestGeneration === state.generation) { state.mutating = false; updateControls(); } } } async function simpleAction(action, username, label, message = "") { const requestGeneration = state.generation; try { const answer = await sessionResult(confirmAction({ title: label, message: message || t("Provést „{label}“ pro účet {user}?", { label, user: username }), confirmLabel: label, danger: ["expire", "revokeAdmin", "lock"].includes(action) }), requestGeneration); if (!answer) return; await sessionResult(runMutation(label, (sessionId, auth) => api.users.manage(sessionId, { action, ...identFor(username), ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function changePassword(username) { const requestGeneration = state.generation; try { const answer = await sessionResult(askValue({ title: t("Nové heslo pro {user}", { user: username }), label: t("Nové heslo"), label2: t("Heslo znovu"), type: "password", message: t("Heslo se přenese přes stdin SSH kanálu do chpasswd, nikdy v argumentech příkazu."), validate: ({ value, value2 }) => !value ? t("Zadejte heslo.") : value !== value2 ? t("Hesla se neshodují.") : value.length > 256 || /[\r\n]/.test(value) ? t("Heslo má neplatný formát.") : "" }), requestGeneration); if (!answer) return; let password = answer.value; answer.value = ""; answer.value2 = ""; await sessionResult(runMutation(t("Změna hesla"), (sessionId, auth) => api.users.manage(sessionId, { action: "setPassword", ...identFor(username), password, ...auth })), requestGeneration); password = ""; } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function changeComment(account) { const requestGeneration = state.generation; try { const answer = await sessionResult(askValue({ title: t("Celé jméno"), label: t("Celé jméno (GECOS)"), value: account.comment, validate: ({ value }) => value.length > 100 || /[:\\]/.test(value) ? t("Max. 100 znaků bez dvojtečky.") : "" }), requestGeneration); if (!answer) return; await sessionResult(runMutation(t("Úprava celého jména"), (sessionId, auth) => api.users.manage(sessionId, { action: "setComment", ...identFor(account.username), comment: answer.value.trim(), ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function changeHome(account) { const requestGeneration = state.generation; try { const answer = await sessionResult(askValue({ title: t("Domovský adresář"), label: t("Nová cesta"), value: account.home, option: t("přesunout obsah (usermod -m, cíl nesmí existovat)"), validate: ({ value }) => /^\/[A-Za-z0-9._/@+-]+$/.test(value.trim()) ? "" : t("Zadejte absolutní cestu bez mezer a speciálních znaků.") }), requestGeneration); if (!answer || answer.value.trim() === account.home) return; await sessionResult(runMutation(t("Změna domovského adresáře"), (sessionId, auth) => api.users.manage(sessionId, { action: "setHome", ...identFor(account.username), home: answer.value.trim(), moveHome: answer.option, ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function deleteAccount(account) { const requestGeneration = state.generation; try { const answer = await sessionResult(confirmAction({ title: t("Odstranit účet {user}", { user: account.username }), message: t("Účet bude odstraněn ze serveru. Operaci nelze vrátit."), details: account.platform === "windows" ? [`SID ${account.sid}`, t("Profil {path}", { path: account.profilePath || t("neexistuje") }), t("Pravidla SSH spravovaná CH-J pro tento účet budou také odstraněna (vyžaduje restart sshd a testovací přihlášení).")] : [t("UID {uid}, domovský adresář {home}", { uid: account.uid, home: account.home }), account.processes ? t("Účet má {count} spuštěných procesů – odstranění bude odmítnuto.", { count: account.processes }) : t("Pravidla SSH spravovaná CH-J pro tento účet budou také odstraněna.")], option: account.platform === "windows" ? (account.profilePath ? t("odstranit také profil {path} (samostatné potvrzení)", { path: account.profilePath }) : "") : t("odstranit také domovský adresář {path} (samostatné potvrzení)", { path: account.home }), typed: account.username, confirmLabel: t("Odstranit účet"), danger: true }), requestGeneration); if (!answer) return; let removeHome = false; if (answer.option) { const second = await sessionResult(confirmAction({ title: account.platform === "windows" ? t("Odstranit profil?") : t("Odstranit domovský adresář?"), message: t("Obsah {path} bude nevratně smazán.", { path: account.platform === "windows" ? account.profilePath : account.home }), confirmLabel: t("Ano, smazat i data"), danger: true }), requestGeneration); if (!second) { setStatus(t("Odstranění bylo zrušeno.")); return; } removeHome = true; } const result = await sessionResult(runMutation(t("Odstranění účtu"), (sessionId, auth) => api.users.manage(sessionId, { action: "delete", ...identFor(account.username), removeHome, removeProfile: removeHome, ...auth })), requestGeneration); if (result && state.selected === account.username) { state.selected = null; state.detail = null; renderUsers(); renderDetail(); } } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function addGroup(username, group) { const requestGeneration = state.generation; try { if (!group) return; await sessionResult(runMutation(t("Přidání do skupiny {group}", { group }), (sessionId, auth) => api.users.manage(sessionId, { action: "addGroup", ...identFor(username), group, ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function removeGroup(username, group) { const requestGeneration = state.generation; try { const answer = await sessionResult(confirmAction({ title: t("Odebrat ze skupiny {group}", { group }), message: t("Účet {user} přestane být členem skupiny {group}. Ostatní skupiny zůstanou.", { user: username, group }), confirmLabel: t("Odebrat"), danger: true }), requestGeneration); if (!answer) return; await sessionResult(runMutation(t("Odebrání ze skupiny {group}", { group }), (sessionId, auth) => api.users.manage(sessionId, { action: "removeGroup", ...identFor(username), group, ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function setPrimary(username, group, current) { const requestGeneration = state.generation; try { if (!group || group === current) return; const answer = await sessionResult(confirmAction({ title: t("Změna primární skupiny"), message: t("Primární skupina účtu {user} bude {group}. Vlastnictví existujících souborů se nemění.", { user: username, group }), confirmLabel: t("Změnit") }), requestGeneration); if (!answer) return; await sessionResult(runMutation(t("Změna primární skupiny"), (sessionId, auth) => api.users.manage(sessionId, { action: "setPrimaryGroup", username, group, ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function saveSshPolicy(detail, form) { const requestGeneration = state.generation; try { const rows = detail.platform !== "windows" && detail.account.uid === 0 ? [...POLICY_ROWS, ROOT_LOGIN_ROW] : POLICY_ROWS; const policy = Object.fromEntries(rows.map((row) => [row.key, form.querySelector(`input[name="policy-${row.key}"]:checked`)?.value || detail.ssh.policy[row.key] || "inherit"])); const changes = rows.filter((row) => policy[row.key] !== detail.ssh.policy[row.key]).map((row) => `${t(row.label)}: ${t(row.options.find(([value]) => value === detail.ssh.policy[row.key])?.[1])} → ${t(row.options.find(([value]) => value === policy[row.key])?.[1])}`); if (!changes.length) { setStatus(t("Nastavení SSH se nezměnilo.")); return; } let confirmRootPassword = false; if (detail.account.uid === 0 && detail.platform !== "windows" && (policy.password === "yes" || policy.permitRootLogin === "yes")) { const warning = await sessionResult(confirmAction({ title: t("Povolit přihlášení root heslem?"), message: t("Přihlášení root heslem výrazně zvyšuje riziko útoků hádáním hesel. Doporučená volba je „Jen klíč“ (prohibit-password). Pro přihlášení Ed25519 klíčem není heslo root potřeba."), typed: "root", confirmLabel: t("Rozumím, povolit heslo"), danger: true }), requestGeneration); if (!warning) { setStatus(t("Povolení hesla pro root nebylo potvrzeno; nic nebylo změněno.")); return; } confirmRootPassword = true; } const risky = detail.self || policy.access === "deny" || policy.pubkey === "no" || policy.password === "no"; const answer = await sessionResult(confirmAction({ title: t("SSH přístup účtu {user}", { user: detail.username }), message: detail.platform === "windows" ? t("sshd bude restartován. Změna se ponechá jen tehdy, když ji do 120 s potvrdí nové SSH přihlášení; jinak ji úloha na serveru sama vrátí.") : detail.self ? t("Měníte SSH přístup účtu této relace. Nechte relaci otevřenou; při neúspěšném testu nového přihlášení se změna vrátí.") : t("Změna se ověří (sshd -t, sshd -T -C) a aplikuje reloadem SSH služby."), details: changes, confirmLabel: t("Aplikovat a ověřit"), danger: risky }), requestGeneration); if (!answer) return; let probeCredentials = null; await sessionResult(runMutation(t("Změna SSH přístupu"), async (sessionId, auth) => { const requestGeneration = state.generation; try { for (;;) { try { return await sessionResult(api.users.sshPolicy(sessionId, { ...identFor(detail.username), policy, confirmRootPassword, ...auth, ...(probeCredentials ? { probeCredentials } : {}) }), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; const { code, detail: message } = parseError(error); if (code !== "USERS_SSH_PROBE_CREDENTIALS_REQUIRED" || probeCredentials) throw error; probeCredentials = await sessionResult(askProbeSecret(/passphrase/.test(message) ? "passphrase" : "password"), requestGeneration); if (!probeCredentials) throw cancelled(); } } } catch (error) { if (requestGeneration !== state.generation) return; throw error; } }, { successMessage: detail.platform === "windows" ? t("SSH přístup byl změněn, ověřen přes sshd -T, sshd byl restartován a změnu potvrdilo nové SSH přihlášení.") : t("SSH přístup byl změněn, ověřen přes sshd -T a SSH služba byla znovu načtena.") }), requestGeneration); probeCredentials = null; } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function removeKey(detail, file, entry) { const requestGeneration = state.generation; try { const answer = await sessionResult(confirmAction({ title: t("Odebrat SSH klíč"), message: t("Z {path} bude odebrán pouze tento klíč. Ostatní řádky zůstanou beze změny.", { path: file.path }), details: [`${entry.type} ${entry.fingerprint}`, entry.comment ? t("Komentář: {comment}", { comment: entry.comment }) : "", t("Řádek {line}", { line: entry.line })].filter(Boolean), confirmLabel: t("Odebrat klíč"), danger: true }), requestGeneration); if (!answer) return; await sessionResult(runMutation(t("Odebrání SSH klíče"), (sessionId, auth) => api.users.keys(sessionId, { action: "remove", ...identFor(detail.username), path: file.path, line: entry.line, fingerprint: entry.fingerprint, ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function addKey(detail) { const requestGeneration = state.generation; try { const publicKey = await sessionResult(runDialog(el.keyDialog, { init: () => { el.keyText.value = ""; el.keyGenComment.value = `${detail.username}@${state.sessions.find((session) => session.sessionId === state.sessionId)?.host || "server"}`; el.keyGenPassphrase.value = ""; el.keyGenerateFields.hidden = true; showError(el.keyError, ""); el.keyInfo.hidden = true; }, submit: () => { const text = el.keyText.value.trim(); if (!/^(ssh-ed25519|sk-ssh-ed25519@openssh\.com) [A-Za-z0-9+/=]+( .*)?$/.test(text)) { showError(el.keyError, /PRIVATE KEY/.test(text) ? t(ERROR_TEXT.USERS_KEY_PRIVATE) : t("Vložte jeden veřejný klíč Ed25519 ve formátu OpenSSH.")); return undefined; } return text; } }).finally(() => { el.keyGenPassphrase.value = ""; }), requestGeneration); if (!publicKey) return; await sessionResult(runMutation(t("Přidání SSH klíče"), (sessionId, auth) => api.users.keys(sessionId, { action: "add", ...identFor(detail.username), publicKey, ...auth })), requestGeneration); } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } async function generateKeyPair() { const requestGeneration = state.generation; showError(el.keyError, ""); el.keyInfo.hidden = true; el.keyGenRun.disabled = true; let passphrase = el.keyGenPassphrase.value; el.keyGenPassphrase.value = ""; try { const generated = await sessionResult(api.keys.generate({ type: "ed25519", comment: el.keyGenComment.value, passphrase, privateKeyFormat: "openssh" }), requestGeneration); passphrase = ""; for (const field of ["privateKey", "privateKeyPem", "privateKeyOpenSSH", "privateKeyPpk"]) generated[field] = ""; const saved = await sessionResult(api.keys.save(generated.generationId), requestGeneration); if (!saved || saved.canceled) { showError(el.keyError, t("Soukromý klíč nebyl uložen, proto se veřejný klíč nepřidá.")); return; } el.keyText.value = generated.publicKey; el.keyInfo.textContent = `${t("Soukromý klíč byl uložen lokálně: {path} ({format}).", { path: saved.privatePath, format: saved.privateKeyFormat })} ${generated.notice || ""} ${t("Potvrďte přidání veřejného klíče na server.")}`; el.keyInfo.hidden = false; } catch (error) { if (requestGeneration !== state.generation) return; showError(el.keyError, t("Generování selhalo: {error}", { error: describeError(error) })); } finally { if (requestGeneration === state.generation) { passphrase = ""; el.keyGenRun.disabled = false; } } } async function openCreateDialog() { const requestGeneration = state.generation; try { const inventory = state.inventory; if (!inventory) return; const windows = inventory.platform === "windows"; const groups = windows ? inventory.groups.filter((group) => !["S-1-5-32-544", "S-1-5-32-545"].includes(group.sid)).sort((left, right) => left.name.localeCompare(right.name)) : inventory.groups.filter((group) => group.gid >= (inventory.server.uidMin || 1000) || ["sudo", "wheel", "adm", "users", "docker", "www-data"].includes(group.name)).sort((left, right) => left.name.localeCompare(right.name)); const payload = await sessionResult(runDialog(el.createDialog, { init: () => { for (const id of ["createUsername", "createComment", "createHome", "createPassword", "createPassword2"]) el[id].value = ""; el.createMakeHome.checked = true; el.createAdmin.checked = false; el.createDescription.value = ""; for (const id of ["createShell", "createHome", "createPrimary"]) el[id].closest("label").hidden = windows; el.createMakeHomeLabel.hidden = windows; el.createDescriptionLabel.hidden = !windows; el.createUsername.pattern = windows ? "[A-Za-z0-9_][A-Za-z0-9._ \\-]{0,19}" : "[a-z_][a-z0-9_\\-]{0,31}"; el.createUsername.maxLength = windows ? 20 : 32; el.createAdminText.textContent = windows ? t("přidat do skupiny Administrators (S-1-5-32-544)") : t("přidat do administrátorské skupiny (sudo/wheel podle serveru)"); el.createHint.textContent = windows ? t("Účet se přidá do skupiny Users. Bez hesla se lze přihlásit jen SSH klíčem (je-li to povoleno politikou). Profil vznikne při prvním přihlášení.") : t("Bez hesla se účet může přihlásit jen SSH klíčem. Sudo práva se po vytvoření ověří pomocí sudo -l."); const shells = inventory.shells.length ? inventory.shells : ["/bin/sh"]; el.createShell.replaceChildren(...shells.map((shell) => h("option", { value: shell, text: shell, selected: shell === "/bin/bash" }))); el.createPrimary.replaceChildren(h("option", { value: "", text: t("Vlastní skupina se jménem účtu") }), ...groups.map((group) => h("option", { value: group.name, text: group.name }))); el.createGroups.replaceChildren(...groups.map((group) => h("option", { value: windows ? group.sid : group.name, text: group.name }))); showError(el.createError, ""); setTimeout(() => el.createUsername.focus(), 0); }, submit: () => { const username = el.createUsername.value.trim(); const password = el.createPassword.value; const home = el.createHome.value.trim(); let problem = ""; if (windows ? !/^[A-Za-z0-9_][A-Za-z0-9._ -]{0,19}$/.test(username) || /[. ]$/.test(username) : !/^[a-z_][a-z0-9_-]{0,31}$/.test(username)) problem = windows ? t(ERROR_TEXT.USERS_NAME_INVALID_WINDOWS) : t(ERROR_TEXT.USERS_NAME_INVALID); else if (inventory.users.some((user) => user.username === username)) problem = t(ERROR_TEXT.USERS_USER_EXISTS); else if (home && !/^\/[A-Za-z0-9._/@+-]+$/.test(home)) problem = t(ERROR_TEXT.USERS_HOME_INVALID); else if (password !== el.createPassword2.value) problem = t("Hesla se neshodují."); else if (/[\r\n]/.test(password)) problem = t(ERROR_TEXT.USERS_PASSWORD_INVALID); if (problem) { showError(el.createError, problem); return undefined; } if (windows) { return { action: "create", username, fullName: el.createComment.value.trim(), description: el.createDescription.value.trim(), groups: [...el.createGroups.selectedOptions].map((option) => option.value), admin: el.createAdmin.checked, ...(password ? { password } : {}) }; } return { action: "create", username, comment: el.createComment.value.trim(), shell: el.createShell.value, home, createHome: el.createMakeHome.checked, primaryGroup: el.createPrimary.value, groups: [...el.createGroups.selectedOptions].map((option) => option.value), admin: el.createAdmin.checked, ...(password ? { password } : {}) }; } }).finally(() => { el.createPassword.value = ""; el.createPassword2.value = ""; }), requestGeneration); if (!payload) return; const result = await sessionResult(runMutation(t("Vytvoření účtu {user}", { user: payload.username }), (sessionId, auth) => api.users.manage(sessionId, { ...payload, ...auth })), requestGeneration); payload.password = ""; if (result) { el.filterSelect.value = "regular"; renderUsers(); void loadDetail(result.username); } } catch (error) { if (requestGeneration !== state.generation) return; throw error; } } // ---------- events ---------- el.closeButton.addEventListener("click", () => api.close()); el.refreshSessionsButton.addEventListener("click", () => { void loadSessions(); }); el.sessionSelect.addEventListener("change", () => { endedSessionId = ""; void selectSession(el.sessionSelect.value); }); el.reloadButton.addEventListener("click", async () => { await refreshPrivilege(); await loadInventory(); if (state.selected) void loadDetail(state.selected); }); el.elevatedButton.addEventListener("click", () => { void loadInventory({ elevated: true }); }); el.searchInput.addEventListener("input", renderUsers); el.filterSelect.addEventListener("change", renderUsers); el.createButton.addEventListener("click", () => { void openCreateDialog(); }); el.usersBody.addEventListener("click", (event) => { const button = event.target.closest("button[data-username]"); if (button) void loadDetail(button.dataset.username); }); document.querySelector("[role=tablist]").addEventListener("click", (event) => { const tab = event.target.closest("[role=tab]"); if (tab) selectTab(tab.id.replace("tab-", "")); }); document.querySelector("[role=tablist]").addEventListener("keydown", (event) => { if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return; const tabs = [...document.querySelectorAll("[role=tab]")]; const index = tabs.findIndex((tab) => tab.id === `tab-${state.tab}`); const next = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1 : (index + (event.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length; event.preventDefault(); selectTab(tabs[next].id.replace("tab-", "")); }); el.keyImportButton.addEventListener("click", () => el.keyFile.click()); el.keyFile.addEventListener("change", async () => { const file = el.keyFile.files?.[0]; el.keyFile.value = ""; if (!file) return; if (file.size > 16 * 1024) { showError(el.keyError, t("Soubor je příliš velký pro veřejný klíč.")); return; } const text = await file.text(); if (/PRIVATE KEY/.test(text)) { showError(el.keyError, t(ERROR_TEXT.USERS_KEY_PRIVATE)); return; } el.keyText.value = text.trim(); showError(el.keyError, ""); }); el.keyGenerateButton.addEventListener("click", () => { el.keyGenerateFields.hidden = !el.keyGenerateFields.hidden; }); el.keyGenRun.addEventListener("click", () => { void generateKeyPair(); }); (async () => { try { i18n.setLanguage(await api.ui.getLanguage()); } catch {} i18n.apply(document); api.ui.onLanguageChanged((language) => { i18n.setLanguage(language); i18n.apply(document); renderPrivilege(); renderUsers(); renderDetail(); }); try { const info = await api.getInfo(); el.pluginVersion.textContent = `${info.name} v${info.version} · ${info.publisher}`; } catch {} await loadSessions(); })().catch((error) => setStatus(describeError(error), true)); setInterval(() => { if (!document.hidden) void loadSessions().catch(() => {}); }, 3000);