Veröffentlichte Quellen
Quellen als ZIP herunterladen
CH-J Tools
Durchsuchen Sie Verzeichnisse und Dateien einer bestimmten Anwendungsausgabe.
CH-J / Server Manager
872 Dateien
core-20261030T220507Z-61e4558d889f
Hinzugefügt: · Erstellt:
1
"use strict";3
const api = window.chjPlugin;4
const i18n = window.chjPluginI18n.createI18n("cs");5
const t = i18n.t;6
let endedSessionId = "";7
let sessionsLoading = false;9
// Guard every continuation, including sudo retries and dialog answers, against a server switch.10
async function sessionResult(promise, token) {11
const value = await promise;12
if (token !== state.generation) throw new Error("CHJ_SESSION_CHANGED");13
return value;14
}16
// Marks a catalog key that is translated with t() only when it is shown.17
const k = (text) => text;18
const el = new Proxy({}, { get: (_target, id) => document.getElementById(id) });20
// Every asynchronous result is checked against these tokens, so data of a previous session or21
// account is never rendered after the user switched.22
const state = {23
sessions: [],24
sessionId: "",25
generation: 0,26
detailToken: 0,27
privilege: null,28
inventory: null,29
selected: null,30
detail: null,31
detailLoading: false,32
tab: "account",33
loading: false,34
mutating: false35
};37
const PRIVILEGE_TEXT = {38
root: ["root", "ok"],39
"sudo-nopasswd": [k("sudo bez hesla"), "ok"],40
"sudo-password": [k("sudo s heslem"), "warn"],41
none: [k("bez sudo – jen čtení"), "danger"],42
unknown: [k("neověřeno"), "muted"],43
"windows-elevated": [k("správce Windows (zvýšený token)"), "ok"],44
"windows-admin-unelevated": [k("člen Administrators bez zvýšeného tokenu – jen čtení"), "warn"],45
"windows-standard": [k("standardní účet Windows – jen čtení"), "danger"]46
};47
const SUDO_TEXT = {48
full: k("plné sudo"),49
"full-nopasswd": k("plné sudo bez hesla"),50
limited: k("omezené sudo"),51
none: k("bez sudo"),52
unavailable: k("sudo není nainstalováno"),53
unknown: k("neznámé")54
};55
const PASSWORD_TEXT = {56
set: [k("heslo nastaveno"), "ok"],57
locked: [k("heslo zamčeno"), "warn"],58
none: [k("bez hesla"), "muted"],59
empty: [k("prázdné heslo!"), "danger"],60
unknown: [k("stav hesla neznámý"), "muted"]61
};62
const PROTECTION_TEXT = {63
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."),64
system: k("Systémový účet je chráněný. CH-J ho zobrazuje jen pro čtení."),65
builtin: k("Vestavěný účet Windows (Administrator, Guest, DefaultAccount, WDAGUtilityAccount) je chráněný a zobrazuje se jen pro čtení."),66
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í.")67
};68
const ERROR_TEXT = {69
SUDO_PASSWORD_REQUIRED: k("Operace vyžaduje heslo pro sudo."),70
SUDO_PASSWORD_INCORRECT: k("Heslo pro sudo bylo odmítnuto."),71
SUDO_NOT_PERMITTED: k("Účet SSH relace nemá pro tuto operaci oprávnění sudo. Zadání hesla to nezmění."),72
SUDO_TTY_REQUIRED: k("Politika sudo na serveru vyžaduje terminál (requiretty). CH-J ji neobchází."),73
SUDO_AUTH_FAILED: k("Ověření sudo selhalo nebo je účet dočasně zablokován."),74
SUDO_UNAVAILABLE: k("Na serveru není sudo a relace neběží jako root."),75
SUDO_FAILED: k("sudo operaci nespustilo."),76
SUDO_PASSWORD_INVALID: k("Heslo pro sudo má neplatný formát."),77
SESSION_NOT_CONNECTED: k("SSH relace byla odpojena. Připojte se znovu v hlavním okně."),78
REMOTE_COMMAND_TIMEOUT: k("Server neodpověděl včas."),79
REMOTE_COMMAND_FAILED: k("Vzdálený příkaz se nepodařilo spustit."),80
REMOTE_OUTPUT_TOO_LARGE: k("Odpověď serveru je příliš velká."),81
PLUGIN_PERMISSION_DENIED: k("Modul nemá potřebné oprávnění."),82
USERS_NAME_INVALID: k("Neplatný název. Povolené jsou malé znaky a-z, číslice, _ a - (max. 32, nezačíná číslicí ani pomlčkou)."),83
USERS_GROUP_INVALID: k("Neplatný název skupiny."),84
USERS_SHELL_INVALID: k("Neplatný shell (musí existovat a být v /etc/shells, případně nologin/false)."),85
USERS_HOME_INVALID: k("Neplatný domovský adresář. Použijte absolutní cestu mimo systémové adresáře."),86
USERS_HOME_EXISTS: k("Cílový domovský adresář už existuje."),87
USERS_COMMENT_INVALID: k("Celé jméno může mít nejvýše 100 znaků bez dvojtečky a řídicích znaků."),88
USERS_PASSWORD_INVALID: k("Heslo musí mít 1–256 znaků a nesmí obsahovat zalomení řádku."),89
USERS_USER_EXISTS: k("Účet s tímto jménem už existuje."),90
USERS_GROUP_EXISTS: k("Skupina se stejným názvem už existuje; zvolte primární skupinu."),91
USERS_USER_NOT_FOUND: k("Účet na serveru neexistuje."),92
USERS_GROUP_NOT_FOUND: k("Skupina na serveru neexistuje."),93
USERS_GROUP_NOT_MEMBER: k("Účet není doplňkovým členem skupiny."),94
USERS_GROUP_PRIMARY: k("Primární skupinu nelze odebrat; nejprve změňte primární skupinu."),95
USERS_PROTECTED_USER: k("Účet je chráněný."),96
USERS_LAST_ADMIN: k("Jde o posledního funkčního administrátora; změna byla odmítnuta."),97
USERS_USER_HAS_PROCESSES: k("Účet má spuštěné procesy. Ukončete je a zkuste to znovu."),98
USERS_TOOL_MISSING: k("Na serveru chybí potřebný systémový nástroj."),99
USERS_SUDO_GROUP_UNAVAILABLE: k("Na serveru není skupina sudo/wheel/admin, na kterou by odkazoval sudoers. CH-J sudoers nemění."),100
USERS_USERADD_FAILED: k("useradd selhal:"),101
USERS_USERMOD_FAILED: k("usermod selhal:"),102
USERS_USERDEL_FAILED: k("userdel selhal:"),103
USERS_PASSWORD_FAILED: k("Nastavení hesla selhalo:"),104
USERS_GROUP_CHANGE_FAILED: k("Změna skupiny selhala:"),105
USERS_KEY_INVALID: k("Neplatný veřejný klíč. Vložte přesně jeden klíč OpenSSH bez voleb."),106
USERS_KEY_PRIVATE: k("Vložili jste soukromý klíč! Na server se smí nahrát jen veřejný klíč (.pub)."),107
USERS_KEY_TYPE_UNSUPPORTED: k("Přidat lze jen klíče Ed25519."),108
USERS_KEY_DUPLICATE: k("Tento klíč už je pro účet povolený."),109
USERS_KEY_NOT_FOUND: k("Klíč se mezitím změnil nebo neexistuje. Obnovte seznam."),110
USERS_KEY_IN_USE: k("Tento klíč používá aktivní relace CH-J, proto nebyl odebrán."),111
USERS_KEY_LAST: k("Poslední klíč účtu aktivní relace nelze odebrat."),112
USERS_KEYS_FILE_UNMANAGEABLE: k("Soubor authorized_keys nelze bezpečně upravit:"),113
USERS_KEYS_FILE_TOO_LARGE: k("Soubor authorized_keys by přesáhl 256 KiB."),114
USERS_KEYS_SYMLINK: k("authorized_keys nebo .ssh je symbolický odkaz; soubor nebyl změněn."),115
USERS_KEYS_CHANGED: k("Soubor s klíči se mezitím změnil. Obnovte seznam a zkuste to znovu."),116
USERS_KEYS_PATH_UNSUPPORTED: k("Cesta k authorized_keys mimo domovský adresář není podporovaná."),117
USERS_SSH_POLICY_INVALID: k("Neplatné nastavení SSH."),118
USERS_SSH_LAYOUT_UNSUPPORTED: k("sshd_config nenačítá sshd_config.d před prvním blokem Match. CH-J hlavní konfiguraci neupravuje."),119
USERS_SSH_MANAGED_FILE_MODIFIED: k("Soubor spravovaný CH-J byl ručně upraven; CH-J ho nepřepíše."),120
USERS_SSH_MANAGED_FILE_UNSAFE: k("Soubor spravovaný CH-J není běžný čitelný soubor."),121
USERS_SSH_CONFIG_ALREADY_INVALID: k("Současná konfigurace SSH je neplatná, změna nebyla provedena:"),122
USERS_SSH_CONFIG_INVALID: k("Nová konfigurace neprošla sshd -t a nebyla použita:"),123
USERS_SSH_POLICY_NOT_EFFECTIVE: k("Nastavení by se neprojevilo kvůli existujícím pravidlům s vyšší prioritou; vráceno zpět."),124
USERS_SSH_LOCKOUT_PREVENTED: k("Změna byla zablokována, aby nepřerušila přístup aktivní relace:"),125
USERS_SSH_PROBE_FAILED: k("Nové testovací přihlášení selhalo; konfigurace byla vrácena:"),126
USERS_SSH_PROBE_CREDENTIALS_REQUIRED: k("Pro ověření nového přihlášení je potřeba heslo nebo passphrase profilu."),127
USERS_SSH_RELOAD_FAILED: k("Reload SSH služby selhal; konfigurace byla vrácena:"),128
USERS_SSH_POLICY_CHANGED: k("Spravovaná SSH konfigurace se mezitím změnila. Obnovte detail a zkuste to znovu."),129
USERS_SSH_CLIENT_UNKNOWN: k("Adresu klienta SSH relace nelze zjistit, ochranu proti odříznutí proto nelze ověřit."),130
USERS_SSHD_MISSING: k("Na serveru nebyl nalezen OpenSSH server (sshd)."),131
USERS_PRIVILEGE_REQUIRED: k("Operace vyžaduje oprávnění root."),132
USERS_ROOT_PASSWORD_CONFIRMATION_REQUIRED: k("Povolení hesla pro root vyžaduje dodatečné potvrzení."),133
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."),134
USERS_SID_INVALID: k("Neplatný identifikátor účtu (SID)."),135
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:"),136
USERS_ACCESS_DENIED: k("Windows operaci zamítl (přístup odepřen bezpečnostní politikou):"),137
USERS_POWERSHELL_UNAVAILABLE: k("Na serveru nelze spustit Windows PowerShell (powershell.exe)."),138
USERS_POWERSHELL_RESTRICTED: k("PowerShell je omezen politikou (Constrained Language Mode / blokování skriptů); CH-J ji neobchází."),139
USERS_LOCALACCOUNTS_UNAVAILABLE: k("Modul Microsoft.PowerShell.LocalAccounts není v PowerShellu na serveru dostupný."),140
USERS_DOMAIN_READ_ONLY: k("Doménové a cloudové identity jsou jen pro čtení."),141
USERS_NOT_SUPPORTED_ON_PLATFORM: k("Tato operace na Windows neexistuje (shell, HOME, primární skupina, zamknutí hesla)."),142
USERS_PASSWORD_POLICY: k("Heslo nesplňuje politiku hesel Windows."),143
USERS_PROFILE_MISSING: k("Profil účtu zatím neexistuje (účet se ještě nepřihlásil), soubor klíčů nelze vytvořit."),144
USERS_SSH_NAME_UNSUPPORTED: k("Název účtu nelze bezpečně použít v sshd_config."),145
USERS_SSH_APPLY_IN_PROGRESS: k("Jiná změna SSH konfigurace ještě probíhá nebo čeká na potvrzení."),146
USERS_SSH_APPLY_NOT_STARTED: k("Úloha s automatickým rollbackem se nespustila; nic nebylo změněno."),147
USERS_SSH_ROLLED_BACK: k("Změna SSH nebyla ponechána, původní konfigurace byla obnovena:"),148
USERS_SSHD_QUERY_FAILED: k("Vyhodnocení sshd -T pod účtem SYSTEM se nepodařilo."),149
USERS_PLATFORM_UNSUPPORTED: k("Operační systém serveru nelze rozpoznat nebo není podporován:"),150
USERS_GROUP_MEMBER_EXISTS: k("Účet už je členem skupiny."),151
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."),152
USERS_WINDOWS_OPERATION_FAILED: k("Operace Windows selhala:")153
};154
const DETAIL_CODES = new Set(["USERS_USERADD_FAILED", "USERS_USERMOD_FAILED", "USERS_USERDEL_FAILED", "USERS_PASSWORD_FAILED", "USERS_GROUP_CHANGE_FAILED",155
"USERS_KEYS_FILE_UNMANAGEABLE", "USERS_SSH_CONFIG_ALREADY_INVALID", "USERS_SSH_CONFIG_INVALID", "USERS_SSH_POLICY_NOT_EFFECTIVE", "USERS_SSH_LOCKOUT_PREVENTED",156
"USERS_SSH_PROBE_FAILED", "USERS_SSH_RELOAD_FAILED", "USERS_PROTECTED_USER", "USERS_TOOL_MISSING", "USERS_WINDOWS_ELEVATION_REQUIRED", "USERS_ACCESS_DENIED",157
"USERS_SSH_ROLLED_BACK", "USERS_PLATFORM_UNSUPPORTED", "USERS_WINDOWS_OPERATION_FAILED", "USERS_PASSWORD_POLICY"]);158
const POLICY_ROWS = [159
{ 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")]] },160
{ 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")]] },161
{ 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")]] },162
{ key: "ipv4", label: k("Přístup z IPv4"), hint: k("Podle IP rodiny zdrojové adresy klienta."), options: [["allow", k("Povolit")], ["deny", k("Zakázat")]] },163
{ key: "ipv6", label: k("Přístup z IPv6"), hint: k("Podle IP rodiny zdrojové adresy klienta."), options: [["allow", k("Povolit")], ["deny", k("Zakázat")]] }164
];165
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."),166
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")]] };167
const CANCELLED = "CHJ_UI_CANCELLED";169
// ---------- small DOM helpers (text only, never innerHTML with server data) ----------170
function h(tag, props = {}, children = []) {171
const node = document.createElement(tag);172
for (const [key, value] of Object.entries(props)) {173
if (value === undefined || value === null || value === false) continue;174
if (key === "className") node.className = value;175
else if (key === "text") node.textContent = String(value);176
else if (key === "dataset") Object.assign(node.dataset, value);177
else if (key.startsWith("on") && typeof value === "function") node.addEventListener(key.slice(2), value);178
else if (typeof value === "boolean") node[key] = value;179
else node.setAttribute(key, String(value));180
}181
for (const child of [].concat(children)) {182
if (child === null || child === undefined || child === false) continue;183
node.append(child instanceof Node ? child : String(child));184
}185
return node;186
}187
function badge(text, tone = "muted") { return h("span", { className: `badge ${tone}`, text }); }188
function setStatus(message, error = false) { el.status.textContent = message; el.status.classList.toggle("error", error); }189
function connected() { return Boolean(state.sessionId); }190
function isWindows() { return state.inventory?.platform === "windows" || state.privilege?.platform === "windows"; }191
// Windows accounts are addressed by SID; Linux accounts by name.192
function identFor(username) {193
const user = state.inventory?.users.find((candidate) => candidate.username === username) || (state.detail?.username === username ? state.detail : null);194
return user?.sid && isWindows() ? { sid: user.sid, username } : { username };195
}197
function parseError(error) {198
const raw = String(error?.message || error || "");199
const match = raw.match(/\b([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+): ([\s\S]*)$/);200
if (match) return { code: match[1], detail: match[2].trim() };201
return { code: error?.code || "UNKNOWN", detail: raw.replace(/^Error invoking remote method '[^']+': (?:\w*Error: )?/, "") };202
}203
function describeError(error) {204
const { code, detail } = parseError(error);205
if (code === CANCELLED) return t("Operace byla zrušena.");206
const base = ERROR_TEXT[code] && t(ERROR_TEXT[code]);207
if (!base) return detail || code;208
return DETAIL_CODES.has(code) && detail ? `${base} ${detail}` : base;209
}210
function cancelled() { const error = new Error(`${CANCELLED}: cancelled`); error.code = CANCELLED; return error; }212
// ---------- dialogs ----------213
function runDialog(dialog, { init, submit }) {214
return new Promise((resolve) => {215
const form = dialog.querySelector("form");216
let finished = false;217
const finish = (value) => {218
if (finished) return;219
finished = true;220
form.removeEventListener("submit", onSubmit);221
dialog.removeEventListener("close", onClose);222
for (const button of dialog.querySelectorAll("[data-close]")) button.removeEventListener("click", onClose);223
if (dialog.open) dialog.close();224
resolve(value);225
};226
const onSubmit = async (event) => {227
event.preventDefault();228
const value = await submit();229
if (value !== undefined) finish(value);230
};231
const onClose = () => finish(null);232
form.addEventListener("submit", onSubmit);233
dialog.addEventListener("close", onClose);234
for (const button of dialog.querySelectorAll("[data-close]")) button.addEventListener("click", onClose);235
init?.();236
dialog.showModal();237
});238
}239
function showError(node, message) { node.textContent = message || ""; node.hidden = !message; }241
function askSudo(label, error) {242
return runDialog(el.sudoDialog, {243
init: () => {244
el.sudoMessage.textContent = t("Operace „{label}“ vyžaduje oprávnění správce.", { label });245
el.sudoUser.textContent = state.privilege?.username || "";246
el.sudoPassword.value = "";247
showError(el.sudoError, error);248
setTimeout(() => el.sudoPassword.focus(), 0);249
},250
submit: () => { const value = el.sudoPassword.value; el.sudoPassword.value = ""; return value || undefined; }251
}).finally(() => { el.sudoPassword.value = ""; });252
}254
function confirmAction({ title, message, details = [], confirmLabel = t("Potvrdit"), danger = false, typed = "", option = "" }) {255
return runDialog(el.confirmDialog, {256
init: () => {257
el.confirmTitle.textContent = `${title} — ${api.sessions.displayName(state.sessions.find((session) => session.sessionId === state.sessionId))}`;258
el.confirmMessage.textContent = message;259
el.confirmDetails.replaceChildren(...details.map((item) => h("li", { text: item })));260
el.confirmDetails.hidden = !details.length;261
el.confirmTypedLabel.hidden = !typed;262
el.confirmTypedValue.textContent = typed;263
el.confirmTyped.value = "";264
el.confirmOptionLabel.hidden = !option;265
el.confirmOptionText.textContent = option;266
el.confirmOption.checked = false;267
el.confirmSubmit.textContent = confirmLabel;268
el.confirmSubmit.className = `button ${danger ? "danger" : "primary"}`;269
},270
submit: () => {271
if (typed && el.confirmTyped.value.trim() !== typed) { el.confirmTyped.focus(); return undefined; }272
return { option: el.confirmOption.checked };273
}274
});275
}277
function askValue({ title, message = "", label, value = "", type = "text", label2 = "", option = "", validate }) {278
return runDialog(el.valueDialog, {279
init: () => {280
el.valueTitle.textContent = `${title} — ${api.sessions.displayName(state.sessions.find((session) => session.sessionId === state.sessionId))}`;281
el.valueMessage.textContent = message;282
el.valueLabelText.textContent = label;283
el.valueInput.type = type; el.valueInput.value = value;284
el.valueLabel2.hidden = !label2;285
el.valueLabelText2.textContent = label2;286
el.valueInput2.type = type; el.valueInput2.value = "";287
el.valueOptionLabel.hidden = !option;288
el.valueOptionText.textContent = option;289
el.valueOption.checked = false;290
showError(el.valueError, "");291
setTimeout(() => el.valueInput.focus(), 0);292
},293
submit: () => {294
const result = { value: el.valueInput.value, value2: el.valueInput2.value, option: el.valueOption.checked };295
const problem = validate?.(result);296
if (problem) { showError(el.valueError, problem); return undefined; }297
return result;298
}299
}).finally(() => { el.valueInput.value = ""; el.valueInput2.value = ""; });300
}302
function askProbeSecret(missing) {303
const passphrase = missing === "passphrase";304
return runDialog(el.probeDialog, {305
init: () => {306
el.probeLabel.textContent = passphrase ? t("Passphrase soukromého klíče profilu") : t("Heslo SSH profilu");307
el.probeSecret.value = "";308
setTimeout(() => el.probeSecret.focus(), 0);309
},310
submit: () => { const value = el.probeSecret.value; el.probeSecret.value = ""; return value ? (passphrase ? { passphrase: value } : { password: value }) : undefined; }311
});312
}314
// Calls Core without a password first. Only if Core reports that sudo needs one, the dialog is shown.315
async function withSudo(label, invoke) {316
const requestGeneration = state.generation;317
try {318
let password = "";319
let attempts = 0;320
try {321
for (;;) {322
try { return await sessionResult(invoke(password ? { sudoPassword: password } : {}), requestGeneration); }323
catch (error) { if (requestGeneration !== state.generation) return;324
const { code } = parseError(error);325
if ((code === "SUDO_PASSWORD_REQUIRED" || code === "SUDO_PASSWORD_INCORRECT") && attempts < 3) {326
attempts += 1;327
password = await sessionResult(askSudo(label, code === "SUDO_PASSWORD_INCORRECT" && password ? t("Heslo bylo odmítnuto. Zkuste to znovu.") : ""), requestGeneration);328
if (!password) throw cancelled();329
continue;330
}331
if (code === "SUDO_NOT_PERMITTED" || code === "SUDO_UNAVAILABLE") void refreshPrivilege();332
if (code === "SESSION_NOT_CONNECTED") void loadSessions();333
throw error;334
}335
}336
} finally { password = ""; }337
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }338
}340
// ---------- sessions and privileges ----------341
async function loadSessions() {342
if (sessionsLoading) return;343
sessionsLoading = true;344
try {345
state.sessions = (await api.sessions.list()).filter((session) => session.state === "connected");346
} catch (error) {347
sessionsLoading = false;348
setStatus(t("Relace nelze načíst: {error}", { error: describeError(error) }), true);349
return;350
}351
sessionsLoading = false;352
const previous = state.sessionId;353
el.sessionSelect.replaceChildren(new Option(state.sessions.length ? t("Vyberte relaci…") : t("Žádná připojená relace"), ""));354
for (const session of state.sessions) el.sessionSelect.add(new Option(api.sessions.displayName(session), session.sessionId));355
const { id: next, reason } = api.sessions.reconcile(endedSessionId || previous, state.sessions);356
if (reason === "gone") endedSessionId ||= previous;357
el.sessionSelect.value = next;358
if (reason === "choose") api.sessions.offerChoice(el.sessionSelect, state.sessions, t("Vyberte relaci…"));359
if (next !== previous) {360
const selecting = selectSession(next);361
const token = state.generation;362
await selecting;363
if (token !== state.generation) return;364
}365
else updateControls();366
if (reason === "gone") setStatus(t("Relace skončila. Vyberte server."), true);367
else if (!state.sessions.length) setStatus(t("Nejprve se v hlavním okně připojte k serveru přes SSH."));368
}370
async function selectSession(sessionId) {371
for (const dialog of document.querySelectorAll("dialog[open]")) dialog.close();372
state.sessionId = sessionId;373
state.generation += 1;374
state.detailToken += 1;375
Object.assign(state, { privilege: null, inventory: null, selected: null, detail: null, detailLoading: false, loading: false, mutating: false });376
renderPrivilege(); renderUsers(); renderDetail(); updateControls();377
if (!sessionId) return;378
await refreshPrivilege();379
await loadInventory();380
}382
async function refreshPrivilege() {383
const requestGeneration = state.generation;384
const token = state.generation;385
if (!connected()) return;386
try {387
const privilege = await sessionResult(api.users.privileges(state.sessionId, true), requestGeneration);388
if (token !== state.generation) return;389
state.privilege = privilege;390
} catch (error) { if (requestGeneration !== state.generation) return;391
if (token === state.generation) setStatus(t("Oprávnění nelze zjistit: {error}", { error: describeError(error) }), true);392
}393
renderPrivilege(); updateControls();394
}396
function renderPrivilege() {397
const mode = state.privilege?.mode || "unknown";398
const [text, tone] = PRIVILEGE_TEXT[mode] || PRIVILEGE_TEXT.unknown;399
const suffix = mode === "sudo-password" && !state.privilege?.verified ? ` (${t("neověřeno")})` : "";400
el.privilegeBadge.textContent = state.privilege ? `${state.privilege.username}: ${t(text)}${suffix}` : t("neověřeno");401
el.privilegeBadge.className = `badge ${tone}`;402
if (mode.startsWith("windows-")) {403
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.");404
return;405
}406
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.") : "";407
}409
function updateControls() {410
const busy = state.loading || state.mutating;411
el.sessionSelect.disabled = state.mutating;412
el.refreshSessionsButton.disabled = state.mutating;413
el.reloadButton.disabled = !connected() || busy;414
const readOnlyWindows = isWindows() && state.privilege?.mode !== "windows-elevated";415
el.createButton.disabled = !connected() || busy || !state.inventory || state.privilege?.mode === "none" || readOnlyWindows;416
const canElevate = !isWindows() && connected() && state.inventory && !state.inventory.privileged && ["sudo-password", "unknown"].includes(state.privilege?.mode || "unknown");417
el.elevatedButton.hidden = !canElevate;418
el.elevatedButton.disabled = busy;419
for (const button of document.querySelectorAll("[data-mutation]")) button.disabled = busy || !connected();420
}422
// ---------- inventory ----------423
async function loadInventory({ elevated = false } = {}) {424
const requestGeneration = state.generation;425
if (!connected()) return;426
const token = state.generation;427
const sessionId = state.sessionId;428
state.loading = true; updateControls();429
setStatus(elevated ? t("Načítám rozšířený stav účtů…") : t("Načítám účty…"));430
try {431
const run = (auth) => api.users.inventory(sessionId, { ...auth, privileged: elevated });432
const inventory = elevated ? await sessionResult(withSudo(t("Načtení rozšířeného stavu účtů"), run), requestGeneration) : await sessionResult(run({}), requestGeneration);433
if (token !== state.generation) return;434
applyInventory(inventory);435
const regular = inventory.users.filter((user) => !user.system).length;436
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")}`}.`);437
} catch (error) { if (requestGeneration !== state.generation) return;438
if (token === state.generation) setStatus(describeError(error), parseError(error).code !== CANCELLED);439
} finally { if (requestGeneration === state.generation) {440
if (token === state.generation) { state.loading = false; updateControls(); }441
} }442
}444
function applyInventory(inventory) {445
state.inventory = inventory;446
if (inventory.privilege) state.privilege = inventory.privilege;447
if (state.selected && !inventory.users.some((user) => user.username === state.selected)) {448
state.selected = null; state.detail = null; state.detailToken += 1;449
} else if (state.detail) {450
const user = inventory.users.find((candidate) => candidate.username === state.detail.username);451
if (user) mergeAccount(state.detail, user, inventory.privileged);452
}453
renderPrivilege(); renderUsers(); renderDetail(); updateControls();454
}456
function mergeAccount(detail, user, privileged) {457
const account = detail.account;458
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 });459
if (privileged) Object.assign(account, { password: user.password, expired: user.expired, expireDays: user.expireDays, sudo: user.sudo });460
}462
function filteredUsers() {463
const users = state.inventory?.users || [];464
const filter = el.filterSelect.value;465
const query = el.searchInput.value.trim().toLowerCase();466
return users.filter((user) => (filter === "all" || (filter === "system" ? user.system : !user.system))467
&& (!query || user.username.includes(query) || user.comment.toLowerCase().includes(query) || String(user.uid) === query));468
}470
function policySummary(policy) {471
if (!policy) return badge(t("dědí server"), "muted");472
if (policy.access === "deny") return badge(t("SSH zakázáno"), "danger");473
const parts = [];474
if (policy.password !== "inherit") parts.push(policy.password === "no" ? t("heslo ne") : t("heslo ano"));475
if (policy.pubkey !== "inherit") parts.push(policy.pubkey === "no" ? t("klíč ne") : t("klíč ano"));476
if (policy.ipv4 === "deny") parts.push(t("bez IPv4"));477
if (policy.ipv6 === "deny") parts.push(t("bez IPv6"));478
return badge(parts.join(" · ") || t("dědí server"), parts.length ? "warn" : "muted");479
}481
function accountState(user) {482
if (user.platform === "windows") {483
const items = [badge(user.enabled ? t("povolen") : t("zakázán"), user.enabled ? "ok" : "danger")];484
if (user.source && user.source !== "Local") items.push(badge(user.source === "MicrosoftAccount" ? t("účet Microsoft") : user.source, "muted"));485
if (user.passwordRequired === false && !user.passwordLastSet) items.push(badge(t("bez hesla"), "muted"));486
return items;487
}488
const items = [];489
if (user.expired) items.push(badge(t("deaktivován"), "danger"));490
const [text, tone] = PASSWORD_TEXT[user.password] || PASSWORD_TEXT.unknown;491
items.push(badge(t(text), tone));492
if (!user.loginShell) items.push(badge(t("bez shellu"), "muted"));493
return items;494
}496
function renderTableHead() {497
const labels = isWindows() ? [t("Účet"), "SID (RID)", t("Stav"), "Administrators", "SSH (CH-J)"] : [t("Účet"), "UID", t("Stav"), "Sudo", "SSH (CH-J)"];498
el.usersBody.closest("table").querySelector("thead").replaceChildren(h("tr", {}, labels.map((text) => h("th", { scope: "col", text }))));499
}501
function renderUsers() {502
renderTableHead();503
const users = filteredUsers();504
if (!state.inventory) {505
el.usersBody.replaceChildren(h("tr", {}, h("td", { colspan: 5, className: "empty", text: connected() ? t("Načítám…") : t("Nejsou načtena žádná data.") })));506
el.inventoryNote.textContent = "";507
return;508
}509
if (!users.length) {510
el.usersBody.replaceChildren(h("tr", {}, h("td", { colspan: 5, className: "empty", text: t("Žádný účet neodpovídá filtru.") })));511
} else {512
el.usersBody.replaceChildren(...users.map((user) => h("tr", { className: user.username === state.selected ? "selected" : "" }, [513
h("td", {}, h("button", { type: "button", className: "row-button", dataset: { username: user.username }, "aria-pressed": String(user.username === state.selected) }, [514
h("strong", { text: user.username }),515
user.protection ? h("small", { text: user.protection === "session" ? ` (${t("tato relace")})` : user.protection === "root" ? " (root)" : user.protection === "builtin" ? ` (${t("vestavěný")})` : "" }) : null,516
user.comment ? h("span", { className: "sub", text: user.comment }) : null517
])),518
h("td", { title: user.sid || "", text: user.platform === "windows" ? `…-${user.rid}` : String(user.uid) }),519
h("td", {}, h("div", { className: "badges" }, accountState(user))),520
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 }),521
h("td", {}, policySummary(user.sshPolicy))522
])));523
}524
const managed = state.inventory.managedPolicy;525
const notes = [];526
if (isWindows()) {527
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)."));528
if (state.inventory.server.serverCore) notes.push(t("Windows Server Core (bez GUI)."));529
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 }));530
} else if (!state.inventory.privileged) notes.push(t("Režim čtení: stav hesel, expirace a skutečná sudo práva vyžadují sudo."));531
if (state.inventory.server.sshLayout !== "ok" && isWindows()) notes.push(t("SSH politiku CH-J nelze v tomto sshd_config bezpečně spravovat (viz Diagnostika)."));532
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)."));533
if (managed.state === "present" && !managed.consistent) notes.push(t("Soubor SSH politiky CH-J byl ručně upraven – CH-J ho nepřepíše."));534
if (state.inventory.server.os) notes.push(t("Server: {os}.", { os: state.inventory.server.os }));535
el.inventoryNote.textContent = notes.join(" ");536
}538
// ---------- detail ----------539
async function loadDetail(username, { elevated = false } = {}) {540
const requestGeneration = state.generation;541
if (!connected()) return;542
const token = state.generation;543
const detailToken = ++state.detailToken;544
const sessionId = state.sessionId;545
if (state.selected !== username) { state.detail = null; state.tab = state.tab || "account"; }546
state.selected = username;547
state.detailLoading = true;548
renderUsers(); renderDetail();549
try {550
const run = (auth) => api.users.detail(sessionId, username, { ...auth, ...identFor(username), privileged: elevated });551
const detail = elevated ? await sessionResult(withSudo(t("Detail účtu {username}", { username }), run), requestGeneration) : await sessionResult(run({}), requestGeneration);552
if (token !== state.generation || detailToken !== state.detailToken) return;553
state.detail = detail;554
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 }));555
} catch (error) { if (requestGeneration !== state.generation) return;556
if (token !== state.generation || detailToken !== state.detailToken) return;557
setStatus(describeError(error), parseError(error).code !== CANCELLED);558
} finally { if (requestGeneration === state.generation) {559
if (token === state.generation && detailToken === state.detailToken) { state.detailLoading = false; renderDetail(); updateControls(); }560
} }561
}563
function renderDetail() {564
const detail = state.detail;565
el.detailEmpty.hidden = Boolean(state.selected);566
el.detailContent.hidden = !state.selected;567
el.detailEmpty.textContent = connected() ? t("Vyberte účet v seznamu.") : t("Nejprve vyberte připojenou relaci.");568
if (!state.selected) return;569
el.detailTitle.textContent = state.selected;570
if (!detail) {571
el.detailSubtitle.textContent = state.detailLoading ? t("Načítám detail…") : t("Detail se nepodařilo načíst.");572
el.detailBadges.replaceChildren();573
el.detailNotice.hidden = true;574
for (const panel of ["account", "groups", "ssh", "keys", "diagnostics"]) el[`panel-${panel}`].replaceChildren();575
return;576
}577
const account = detail.account;578
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…")}` : "");579
el["tab-groups"].textContent = account.platform === "windows" ? t("Skupiny a správci") : t("Skupiny a sudo");580
el.detailBadges.replaceChildren(...[581
account.protection ? badge(account.protection === "session" ? t("aktivní relace") : account.protection === "root" ? "root" : account.protection === "builtin" ? t("vestavěný") : t("systémový"), "warn") : null,582
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"),583
...accountState(account)584
].filter(Boolean));585
const notices = [];586
if (account.protection) notices.push(t(PROTECTION_TEXT[account.protection]));587
if (!detail.privileged) notices.push(detail.platform === "windows"588
? 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.")589
: t("Část údajů (stav hesla, sudo, skutečná SSH konfigurace, klíče jiných účtů) vyžaduje sudo."));590
el.detailNotice.replaceChildren(...notices.map((text) => h("p", { text })));591
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 }) }));592
el.detailNotice.hidden = !notices.length;593
renderAccountTab(detail); renderGroupsTab(detail); renderSshTab(detail); renderKeysTab(detail); renderDiagnosticsTab(detail);594
selectTab(state.tab, false);595
updateControls();596
}598
function infoGrid(rows) {599
return h("dl", { className: "info-grid" }, rows.flatMap(([label, value]) => [h("dt", { text: label }), h("dd", {}, value instanceof Node ? value : String(value ?? "—"))]));600
}601
function actionButton(label, onClick, { danger = false, sudo = true, title = "" } = {}) {602
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]);603
}604
function section(title, children, hint = "") {605
return h("section", { className: "sub-panel" }, [h("h4", { text: title }), hint ? h("p", { className: "hint", text: hint }) : null, ...[].concat(children)]);606
}608
function renderAccountTab(detail) {609
if (detail.platform === "windows") { renderWindowsAccountTab(detail); return; }610
const account = detail.account;611
const [passwordText] = PASSWORD_TEXT[account.password] || PASSWORD_TEXT.unknown;612
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í");613
const children = [infoGrid([614
[t("Uživatelské jméno"), account.username],615
[t("Celé jméno"), account.comment || "—"],616
["UID / GID", `${account.uid} / ${account.gid}`],617
[t("Primární skupina"), account.primaryGroup],618
[t("Domovský adresář"), `${account.home}${account.homeMeta && account.homeMeta !== "absent" ? ` (${account.homeMeta})` : account.homeMeta === "absent" ? ` (${t("neexistuje")})` : ""}`],619
["Shell", `${account.shell}${account.loginShell ? "" : ` – ${t("interaktivní přihlášení vypnuto")}`}`],620
[t("Heslo"), t(passwordText)],621
[t("Stav účtu"), expiry],622
[t("Typ"), account.uid === 0 ? "root" : account.system ? t("systémový účet") : t("běžný účet")],623
[t("Spuštěné procesy"), account.processes === null ? "—" : String(account.processes)]624
]), 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.") })];625
if (!account.protection) {626
const actions = [actionButton(t("Změnit heslo…"), () => changePassword(account.username))];627
if (account.password === "locked") actions.push(actionButton(t("Odemknout heslo"), () => simpleAction("unlock", account.username, t("Odemknutí hesla"))));628
else if (account.password === "set") actions.push(actionButton(t("Zamknout heslo"), () => simpleAction("lock", account.username, t("Zamknutí hesla"))));629
actions.push(account.expired630
? actionButton(t("Aktivovat účet"), () => simpleAction("unexpire", account.username, t("Aktivace účtu")))631
: 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."))));632
actions.push(actionButton(t("Upravit celé jméno…"), () => changeComment(account)));633
actions.push(actionButton(t("Změnit domovský adresář…"), () => changeHome(account)));634
actions.push(actionButton(t("Odstranit účet…"), () => deleteAccount(account), { danger: true }));635
children.push(h("div", { className: "inline-actions" }, actions));636
const shells = [...new Set([...(state.inventory?.shells || []), "/usr/sbin/nologin", "/bin/false", account.shell])].filter(Boolean);637
const shellSelect = h("select", { "aria-label": "Shell" }, shells.map((shell) => h("option", { value: shell, text: shell, selected: shell === account.shell })));638
children.push(section("Shell", h("div", { className: "inline-actions" }, [shellSelect, actionButton(t("Uložit shell"), () => {639
if (shellSelect.value === account.shell) return;640
void runMutation(t("Změna shellu"), (sessionId, auth) => api.users.manage(sessionId, { action: "setShell", ...identFor(account.username), shell: shellSelect.value, ...auth }));641
})]), t("nologin/false zablokuje interaktivní přihlášení, ale ne nutně všechny SSH funkce (např. přesměrování portů).")));642
}643
el["panel-account"].replaceChildren(...children);644
}646
function renderGroupsTab(detail) {647
if (detail.platform === "windows") { renderWindowsGroupsTab(detail); return; }648
const account = detail.account;649
const groups = state.inventory?.groups || [];650
const editable = !account.protection;651
const children = [];652
const memberRows = account.groups.length653
? 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]))654
: [h("li", { className: "muted", text: t("Žádné doplňkové skupiny.") })];655
children.push(section(t("Skupiny"), [656
infoGrid([[t("Primární skupina"), account.primaryGroup]]),657
h("ul", { className: "chip-list" }, memberRows)658
]));659
if (editable && groups.length) {660
const candidates = groups.filter((group) => !account.groups.includes(group.name) && group.name !== account.primaryGroup).sort((left, right) => left.name.localeCompare(right.name));661
const addSelect = h("select", { "aria-label": t("Přidat do skupiny") }, candidates.map((group) => h("option", { value: group.name, text: `${group.name} (${group.gid})` })));662
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 })));663
children.push(section(t("Změnit členství"), [664
h("div", { className: "inline-actions" }, [addSelect, actionButton(t("Přidat do skupiny"), () => addGroup(account.username, addSelect.value))]),665
h("div", { className: "inline-actions" }, [primarySelect, actionButton(t("Nastavit primární skupinu"), () => setPrimary(account.username, primarySelect.value, account.primaryGroup))])666
], t("Ostatní skupiny a nesouvisející oprávnění zůstávají zachované.")));667
}668
const sudoState = account.sudo || "unknown";669
const adminGroups = state.inventory?.adminGroups || [];670
const sudoChildren = [infoGrid([671
[t("Skutečný stav (sudo -l)"), sudoState === "unknown" ? t("neznámý – vyžaduje sudo") : SUDO_TEXT[sudoState] ? t(SUDO_TEXT[sudoState]) : sudoState],672
[t("Členství ve skupinách správců"), ["sudo", "wheel", "admin"].filter((name) => account.groups.includes(name) || account.primaryGroup === name).join(", ") || t("žádné")],673
[t("Skupiny s pravidlem v sudoers"), adminGroups.length ? adminGroups.join(", ") : state.inventory?.privileged ? t("žádná") : t("neznámé (vyžaduje sudo)")]674
]), h("p", { className: "hint", text: t("Členství ve skupině samo nezaručuje funkční sudo. CH-J nikdy nemění sudoers a nenastavuje NOPASSWD.") })];675
if (editable) {676
sudoChildren.push(h("div", { className: "inline-actions" }, [677
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."))),678
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 })679
]));680
}681
children.push(section("Sudo", sudoChildren));682
el["panel-groups"].replaceChildren(...children);683
}685
function effectiveCell(detail, family, key) {686
const effective = detail.ssh.effective[family];687
if (!effective) return h("span", { className: "muted", text: detail.privileged ? t("nedostupné") : t("vyžaduje sudo") });688
const yesNo = (value) => value === "yes" ? badge(t("povoleno"), "ok") : value === "no" ? badge(t("zakázáno"), "danger") : badge(value, "muted");689
if (key === "password") return yesNo(effective.methods.password ? "yes" : "no");690
if (key === "pubkey") return yesNo(effective.methods.publickey ? "yes" : "no");691
const listener = detail.ssh.effective.listener;692
if (listener && listener[family] === false) return badge(t("sshd nenaslouchá"), "danger");693
if (effective.allowed === true) return badge(t("povoleno"), "ok");694
if (effective.allowed === null) return badge(t("nejisté"), "warn");695
const managedOnly = effective.reasons.every((reason) => reason.managed);696
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"));697
}699
function renderSshTab(detail) {700
const ssh = detail.ssh;701
const account = detail.account;702
const children = [];703
if (!ssh.available && detail.privileged) {704
el["panel-ssh"].replaceChildren(h("p", { className: "notice", text: t("Na serveru nebyl nalezen OpenSSH server (sshd).") }));705
return;706
}707
const windows = detail.platform === "windows";708
const blocked = windows ? account.protection === "builtin" : account.system;709
const rows = !windows && account.uid === 0 ? [...POLICY_ROWS, ROOT_LOGIN_ROW] : POLICY_ROWS;710
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."))711
: !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."))712
: windows && !ssh.sshName ? t("Název účtu obsahuje znaky, které nelze bezpečně použít v sshd_config.")713
: !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."))714
: ssh.managed.state === "present" && !ssh.managed.consistent ? t("{path} byl ručně upraven – CH-J ho nepřepíše.", { path: ssh.managed.path })715
: ssh.syntaxOk === false ? t("Současná konfigurace SSH je neplatná: {message}", { message: ssh.syntaxMessage }) : "";716
const form = h("form", { className: "policy-form" });717
const table = h("table", { className: "policy-table" }, [718
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")})` : ""}` })])),719
h("tbody", {}, rows.map((row) => {720
const current = ssh.policy[row.key];721
const options = h("div", { className: "segmented", role: "radiogroup", "aria-label": t(row.label) }, row.options.map(([value, label]) => h("label", {}, [722
h("input", { type: "radio", name: `policy-${row.key}`, value, checked: current === value, disabled: Boolean(reason) }), h("span", { text: t(label) })723
])));724
const family = row.key === "ipv4" ? ["ipv4"] : row.key === "ipv6" ? ["ipv6"] : ["ipv4", "ipv6"];725
const effectiveKey = row.key === "ipv4" || row.key === "ipv6" ? "access" : row.key;726
if (row.key === "permitRootLogin") {727
const shown = (family) => {728
const value = detail.ssh.effective[family]?.permitRootLogin;729
const text = value === "without-password" ? "prohibit-password" : value;730
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") });731
};732
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"))]);733
}734
return h("tr", {}, [735
h("th", { scope: "row" }, [h("span", { text: t(row.label) }), h("small", { className: "sub", text: t(row.hint) })]),736
h("td", {}, options),737
h("td", {}, family.includes("ipv4") ? effectiveCell(detail, "ipv4", effectiveKey) : h("span", { className: "muted", text: "—" })),738
h("td", {}, family.includes("ipv6") ? effectiveCell(detail, "ipv6", effectiveKey) : h("span", { className: "muted", text: "—" }))739
]);740
}))741
]);742
form.append(table);743
if (reason) form.append(h("p", { className: "notice", text: reason }));744
else {745
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.") }));746
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í.") }));747
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)") })]));748
form.addEventListener("submit", (event) => { event.preventDefault(); void saveSshPolicy(detail, form); });749
}750
children.push(form);751
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í.") }));752
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.") }));753
for (const warning of ssh.warnings) children.push(h("p", { className: "notice warn", text: translateWarning(warning) }));754
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")}` : ""}`));755
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 })))));756
el["panel-ssh"].replaceChildren(...children);757
}759
function translateWarning(text) {760
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.");761
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.");762
if (/AuthorizedKeysCommand/.test(text)) return t("Je nastaven AuthorizedKeysCommand – klíče mohou pocházet i z externího zdroje, který CH-J nespravuje.");763
if (/edited manually/.test(text)) return t("Soubor SSH politiky CH-J byl ručně upraven; CH-J ho nepřepíše.");764
return text;765
}767
function renderKeysTab(detail) {768
const files = detail.keys.files;769
const account = detail.account;770
const children = [];771
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.") }));772
if (!files.length || (!detail.privileged && !detail.self)) {773
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).") }));774
}775
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") };776
for (const [index, file] of files.entries()) {777
if (!detail.privileged && !detail.self) break;778
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;779
const rows = file.entries.map((entry) => entry.valid780
? h("tr", {}, [781
h("td", { text: entry.type }), h("td", { className: "mono", text: entry.fingerprint }), h("td", { text: entry.comment || "—" }),782
h("td", { className: "mono", text: entry.options || "—" }), h("td", { text: String(entry.line) }),783
h("td", {}, account.protection === "system" || account.protection === "builtin" || !file.manageable ? null784
: h("button", { type: "button", className: "mini danger", dataset: { mutation: "1" }, text: t("Odebrat"), onclick: () => removeKey(detail, file, entry) }))785
])786
: 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 }) })]));787
children.push(section(index === 0 ? t("Primární soubor: {path}", { path: file.path }) : t("Další soubor: {path}", { path: file.path }), [788
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 })}`}` }),789
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)])) : null790
]));791
}792
const primary = files[0];793
if (!account.protection || account.protection === "session" || account.protection === "root") {794
if ((detail.platform === "windows" ? account.protection !== "builtin" : !account.system) && (detail.privileged || detail.self)) {795
children.push(h("div", { className: "inline-actions" }, [796
h("button", { type: "button", className: "button primary", dataset: { mutation: "1" }, disabled: !primary?.manageable, text: t("Přidat Ed25519 klíč…"), onclick: () => addKey(detail) })797
]));798
}799
}800
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.") }));801
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).") }));802
el["panel-keys"].replaceChildren(...children);803
}805
function renderDiagnosticsTab(detail) {806
if (detail.platform === "windows") { renderWindowsDiagnosticsTab(detail); return; }807
const ssh = detail.ssh;808
const privilege = state.privilege;809
const listener = ssh.effective.listener;810
const files = detail.keys.files;811
const rows = [812
[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")],813
[t("Adresa klienta (SSH_CLIENT)"), privilege?.clientAddress || t("neznámá")],814
["OpenSSH", ssh.version || (ssh.available ? t("neznámá verze") : t("nenalezen"))],815
[t("Služba SSH"), ssh.service || t("neznámý stav")],816
[t("Kontrola sshd -t"), ssh.syntaxOk === null ? t("vyžaduje sudo") : ssh.syntaxOk ? t("v pořádku") : t("CHYBA: {message}", { message: ssh.syntaxMessage })],817
[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],818
[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}`],819
[t("Naslouchání sshd"), listener ? `IPv4: ${listener.ipv4 ? t("ano") : t("ne")}, IPv6: ${listener.ipv6 ? t("ano") : t("ne")}` : t("vyžaduje sudo")],820
["AuthorizedKeysCommand", ssh.effective.authorizedKeysCommand || (detail.privileged ? t("není nastaven") : t("vyžaduje sudo"))],821
[t("Domovský adresář"), detail.account.homeMeta || "—"],822
...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 })}` : ""}`]),823
[t("Načteno"), new Date(detail.collectedAt).toLocaleString(i18n.locale())]824
];825
const strict = [];826
for (const file of files) {827
const [owner, , mode] = String(file.meta || "").split(":");828
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 }));829
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 }));830
}831
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) })));832
}834
function selectTab(name, focus = true) {835
state.tab = name;836
for (const tab of document.querySelectorAll("[role=tab]")) {837
const selected = tab.id === `tab-${name}`;838
tab.setAttribute("aria-selected", String(selected));839
tab.tabIndex = selected ? 0 : -1;840
el[tab.getAttribute("aria-controls")].hidden = !selected;841
if (selected && focus) tab.focus();842
}843
}845
// ---------- Windows variants (SID, Administrators, account state; no UID/shell/sudo) ----------846
function formatDate(value) { return value ? new Date(value).toLocaleString(i18n.locale()) : "—"; }848
function renderWindowsAccountTab(detail) {849
const account = detail.account;850
const children = [infoGrid([851
[t("Uživatelské jméno"), account.username],852
[t("Celé jméno"), account.fullName || "—"],853
[t("Popis"), account.description || "—"],854
["SID", account.sid],855
[t("Zdroj"), account.source === "MicrosoftAccount" ? t("lokální účet propojený s účtem Microsoft") : account.source || "—"],856
[t("Stav účtu"), account.enabled ? t("povolen") : t("zakázán")],857
[t("Heslo naposledy nastaveno"), formatDate(account.passwordLastSet)],858
[t("Platnost hesla"), account.passwordExpires ? formatDate(account.passwordExpires) : t("neomezená")],859
[t("Platnost účtu"), account.accountExpires ? formatDate(account.accountExpires) : t("neomezená")],860
[t("Poslední přihlášení"), formatDate(account.lastLogon)],861
[t("Profil"), account.profilePath || t("zatím nevytvořen")],862
[t("Typ"), account.protection === "builtin" ? t("vestavěný účet") : t("běžný lokální účet")],863
["Administrators (S-1-5-32-544)", account.admin ? t("člen") : t("není člen")]864
]), 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.") })];865
if (!account.protection && detail.privileged) {866
children.push(h("div", { className: "inline-actions" }, [867
actionButton(t("Změnit heslo…"), () => changePassword(account.username), { sudo: false }),868
account.enabled869
? 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 })870
: actionButton(t("Povolit účet"), () => simpleAction("enable", account.username, t("Povolení účtu")), { sudo: false }),871
actionButton(t("Upravit celé jméno…"), () => changeWindowsText(account, "setFullName", t("Celé jméno"), account.fullName, 256), { sudo: false }),872
actionButton(t("Upravit popis…"), () => changeWindowsText(account, "setDescription", t("Popis"), account.description, 48), { sudo: false }),873
actionButton(t("Odstranit účet…"), () => deleteAccount(account), { danger: true, sudo: false })874
]));875
} else if (!account.protection) {876
children.push(h("p", { className: "notice", text: t("Změny účtu vyžadují SSH relaci správce se zvýšeným tokenem.") }));877
}878
el["panel-account"].replaceChildren(...children);879
}881
function renderWindowsGroupsTab(detail) {882
const account = detail.account;883
const editable = !account.protection && detail.privileged;884
const groups = state.inventory?.groups || [];885
const memberSids = new Set(account.groups.map((group) => group.sid));886
const children = [section(t("Lokální skupiny"), [887
h("ul", { className: "chip-list" }, account.groups.length ? account.groups.map((group) => h("li", { title: group.sid }, [888
h("span", { text: group.name }),889
editable ? h("button", { type: "button", className: "mini", dataset: { mutation: "1" }, text: t("Odebrat"), onclick: () => removeWindowsGroup(account, group) }) : null890
])) : [h("li", { className: "muted", text: t("Účet není členem žádné lokální skupiny.") })])891
], t("Názvy skupin jsou lokalizované; CH-J pracuje se skupinami podle SID."))];892
if (editable) {893
const candidates = groups.filter((group) => !memberSids.has(group.sid) && group.sid !== "S-1-5-32-544").sort((left, right) => left.name.localeCompare(right.name));894
const select = h("select", { "aria-label": t("Přidat do skupiny") }, candidates.map((group) => h("option", { value: group.sid, text: group.name })));895
children.push(section(t("Přidat do skupiny"), h("div", { className: "inline-actions" }, [select, actionButton(t("Přidat"), () => {896
const group = candidates.find((candidate) => candidate.sid === select.value);897
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 }));898
}, { sudo: false })])));899
}900
const tokenMode = t((PRIVILEGE_TEXT[detail.privilege?.mode] || PRIVILEGE_TEXT.unknown)[0]);901
const adminChildren = [infoGrid([902
[t("Členství v Administrators"), account.admin ? t("člen (S-1-5-32-544)") : t("není člen")],903
[t("Token této SSH relace"), tokenMode]904
]), 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.") })];905
if (editable) {906
adminChildren.push(h("div", { className: "inline-actions" }, [907
account.admin908
? 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 })909
: 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 })910
]));911
}912
children.push(section(t("Správci"), adminChildren));913
const external = state.inventory?.externalIdentities || [];914
if (external.length) {915
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(", ")}` })))));916
}917
el["panel-groups"].replaceChildren(...children);918
}920
function renderWindowsDiagnosticsTab(detail) {921
const ssh = detail.ssh;922
const system = detail.system || {};923
const privilege = detail.privilege || state.privilege || {};924
const listener = ssh.effective.listener;925
const rows = [926
[t("Systém"), `${system.caption || "Windows"} ${system.version || ""} (build ${system.build || "?"})`],927
[t("Typ instalace"), system.installationType ? `${system.installationType}${system.serverCore ? ` – ${t("bez GUI")}` : ""}` : "—"],928
[t("Detekce platformy"), `${system.detectedBy || "?"}${system.unameOutput ? `, uname: ${system.unameOutput}` : ""}`],929
[t("Výchozí SSH shell"), `${system.defaultShell || "?"}${system.defaultShellPath ? ` (${system.defaultShellPath})` : ` (${t("výchozí cmd.exe")})`}`],930
[t("PowerShell pro CH-J"), `${system.powershell || "?"}${system.is64BitProcess ? ", 64bit" : ", 32bit!"}, ${system.languageMode || "?"}${system.pwsh ? `; PowerShell 7: ${system.pwsh}` : `; ${t("PowerShell 7 nenalezen")}`}`],931
["LocalAccounts", system.localAccounts ? t("dostupný") : t("nedostupný")],932
[t("Token relace"), `${privilege.username || "?"} – ${t((PRIVILEGE_TEXT[privilege.mode] || PRIVILEGE_TEXT.unknown)[0])}, ${t("integrita {level}", { level: privilege.integrity || "?" })}`],933
[t("Adresa klienta (SSH_CLIENT)"), privilege.clientAddress || t("neznámá")],934
["OpenSSH Server", ssh.version || (ssh.available ? t("neznámá verze") : t("nenainstalován"))],935
[t("Služba sshd"), ssh.service || "—"],936
["sshd_config", ssh.configPath || "—"],937
[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 })],938
[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("; ") })],939
[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")],940
[t("Aplikace změn"), t("restart služby sshd s nezávislým rollbackem (naplánovaná úloha SYSTEM, 120 s)")],941
...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(", ")}` : ""}`]),942
[t("Načteno"), new Date(detail.collectedAt).toLocaleString(i18n.locale())]943
];944
el["panel-diagnostics"].replaceChildren(infoGrid(rows), ...ssh.warnings.map((text) => h("p", { className: "notice warn", text: translateWarning(text) })));945
}947
async function changeWindowsText(account, action, label, value, limit) {948
const requestGeneration = state.generation;949
try {950
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);951
if (!answer) return;952
const field = action === "setDescription" ? "description" : "fullName";953
await sessionResult(runMutation(t("Úprava: {label}", { label }), (sessionId, auth) => api.users.manage(sessionId, { action, ...identFor(account.username), [field]: answer.value.trim(), ...auth })), requestGeneration);954
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }955
}957
async function removeWindowsGroup(account, group) {958
const requestGeneration = state.generation;959
try {960
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);961
if (!answer) return;962
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);963
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }964
}966
// ---------- mutations ----------967
async function runMutation(label, invoke, { successMessage } = {}) {968
const requestGeneration = state.generation;969
if (state.mutating || !connected()) return null;970
const token = state.generation;971
const sessionId = state.sessionId;972
if (!window.confirm(`${api.sessions.displayName(state.sessions.find((session) => session.sessionId === sessionId))}\n\n${label}`)) return null;973
state.mutating = true; updateControls();974
setStatus(`${label}…`);975
try {976
const result = await sessionResult(withSudo(label, (auth) => invoke(sessionId, auth)), requestGeneration);977
if (token !== state.generation) return null;978
if (result?.inventory) applyInventory(result.inventory);979
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; }980
if (result?.detail) {981
// Keep the list column in sync with the verified policy returned by Core.982
const listed = state.inventory?.users.find((user) => user.username === result.detail.username);983
if (listed) {984
const current = result.detail.ssh.policy;985
listed.sshPolicy = POLICY_ROWS.every((row) => current[row.key] === row.options[0][0]) ? null : { ...current };986
renderUsers();987
}988
if (state.selected === result.detail.username) { state.detailToken += 1; state.detail = result.detail; state.detailLoading = false; renderDetail(); }989
}990
const failedSteps = (result?.steps || []).filter((step) => step.status === "failed");991
const warnings = [...(result?.warnings || []), ...failedSteps.map((step) => t("Krok {step} selhal: {message}", { step: step.step, message: step.message }))];992
const partial = result?.result === "partial" || failedSteps.length > 0;993
setStatus(`${successMessage || t("{label}: hotovo, stav byl znovu načten ze serveru.", { label })}${partial ? ` ${t("Pouze částečně!")}` : ""}${warnings.length ? ` ${warnings.join(" ")}` : ""}`, partial);994
return result;995
} catch (error) { if (requestGeneration !== state.generation) return;996
if (token === state.generation) setStatus(describeError(error), parseError(error).code !== CANCELLED);997
return null;998
} finally { if (requestGeneration === state.generation) {999
state.mutating = false; updateControls();1000
} }1001
}1003
async function simpleAction(action, username, label, message = "") {1004
const requestGeneration = state.generation;1005
try {1006
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);1007
if (!answer) return;1008
await sessionResult(runMutation(label, (sessionId, auth) => api.users.manage(sessionId, { action, ...identFor(username), ...auth })), requestGeneration);1009
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1010
}1012
async function changePassword(username) {1013
const requestGeneration = state.generation;1014
try {1015
const answer = await sessionResult(askValue({1016
title: t("Nové heslo pro {user}", { user: username }), label: t("Nové heslo"), label2: t("Heslo znovu"), type: "password",1017
message: t("Heslo se přenese přes stdin SSH kanálu do chpasswd, nikdy v argumentech příkazu."),1018
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.") : ""1019
}), requestGeneration);1020
if (!answer) return;1021
let password = answer.value;1022
answer.value = ""; answer.value2 = "";1023
await sessionResult(runMutation(t("Změna hesla"), (sessionId, auth) => api.users.manage(sessionId, { action: "setPassword", ...identFor(username), password, ...auth })), requestGeneration);1024
password = "";1025
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1026
}1028
async function changeComment(account) {1029
const requestGeneration = state.generation;1030
try {1031
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);1032
if (!answer) return;1033
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);1034
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1035
}1037
async function changeHome(account) {1038
const requestGeneration = state.generation;1039
try {1040
const answer = await sessionResult(askValue({1041
title: t("Domovský adresář"), label: t("Nová cesta"), value: account.home, option: t("přesunout obsah (usermod -m, cíl nesmí existovat)"),1042
validate: ({ value }) => /^\/[A-Za-z0-9._/@+-]+$/.test(value.trim()) ? "" : t("Zadejte absolutní cestu bez mezer a speciálních znaků.")1043
}), requestGeneration);1044
if (!answer || answer.value.trim() === account.home) return;1045
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);1046
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1047
}1049
async function deleteAccount(account) {1050
const requestGeneration = state.generation;1051
try {1052
const answer = await sessionResult(confirmAction({1053
title: t("Odstranit účet {user}", { user: account.username }),1054
message: t("Účet bude odstraněn ze serveru. Operaci nelze vrátit."),1055
details: account.platform === "windows"1056
? [`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í).")]1057
: [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.")],1058
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 }),1059
typed: account.username, confirmLabel: t("Odstranit účet"), danger: true1060
}), requestGeneration);1061
if (!answer) return;1062
let removeHome = false;1063
if (answer.option) {1064
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);1065
if (!second) { setStatus(t("Odstranění bylo zrušeno.")); return; }1066
removeHome = true;1067
}1068
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);1069
if (result && state.selected === account.username) { state.selected = null; state.detail = null; renderUsers(); renderDetail(); }1070
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1071
}1073
async function addGroup(username, group) {1074
const requestGeneration = state.generation;1075
try {1076
if (!group) return;1077
await sessionResult(runMutation(t("Přidání do skupiny {group}", { group }), (sessionId, auth) => api.users.manage(sessionId, { action: "addGroup", ...identFor(username), group, ...auth })), requestGeneration);1078
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1079
}1081
async function removeGroup(username, group) {1082
const requestGeneration = state.generation;1083
try {1084
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);1085
if (!answer) return;1086
await sessionResult(runMutation(t("Odebrání ze skupiny {group}", { group }), (sessionId, auth) => api.users.manage(sessionId, { action: "removeGroup", ...identFor(username), group, ...auth })), requestGeneration);1087
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1088
}1090
async function setPrimary(username, group, current) {1091
const requestGeneration = state.generation;1092
try {1093
if (!group || group === current) return;1094
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);1095
if (!answer) return;1096
await sessionResult(runMutation(t("Změna primární skupiny"), (sessionId, auth) => api.users.manage(sessionId, { action: "setPrimaryGroup", username, group, ...auth })), requestGeneration);1097
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1098
}1100
async function saveSshPolicy(detail, form) {1101
const requestGeneration = state.generation;1102
try {1103
const rows = detail.platform !== "windows" && detail.account.uid === 0 ? [...POLICY_ROWS, ROOT_LOGIN_ROW] : POLICY_ROWS;1104
const policy = Object.fromEntries(rows.map((row) => [row.key, form.querySelector(`input[name="policy-${row.key}"]:checked`)?.value || detail.ssh.policy[row.key] || "inherit"]));1105
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])}`);1106
if (!changes.length) { setStatus(t("Nastavení SSH se nezměnilo.")); return; }1107
let confirmRootPassword = false;1108
if (detail.account.uid === 0 && detail.platform !== "windows" && (policy.password === "yes" || policy.permitRootLogin === "yes")) {1109
const warning = await sessionResult(confirmAction({1110
title: t("Povolit přihlášení root heslem?"),1111
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."),1112
typed: "root", confirmLabel: t("Rozumím, povolit heslo"), danger: true1113
}), requestGeneration);1114
if (!warning) { setStatus(t("Povolení hesla pro root nebylo potvrzeno; nic nebylo změněno.")); return; }1115
confirmRootPassword = true;1116
}1117
const risky = detail.self || policy.access === "deny" || policy.pubkey === "no" || policy.password === "no";1118
const answer = await sessionResult(confirmAction({1119
title: t("SSH přístup účtu {user}", { user: detail.username }),1120
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."),1121
details: changes, confirmLabel: t("Aplikovat a ověřit"), danger: risky1122
}), requestGeneration);1123
if (!answer) return;1124
let probeCredentials = null;1125
await sessionResult(runMutation(t("Změna SSH přístupu"), async (sessionId, auth) => {1126
const requestGeneration = state.generation;1127
try {1128
for (;;) {1129
try { return await sessionResult(api.users.sshPolicy(sessionId, { ...identFor(detail.username), policy, confirmRootPassword, ...auth, ...(probeCredentials ? { probeCredentials } : {}) }), requestGeneration); }1130
catch (error) { if (requestGeneration !== state.generation) return;1131
const { code, detail: message } = parseError(error);1132
if (code !== "USERS_SSH_PROBE_CREDENTIALS_REQUIRED" || probeCredentials) throw error;1133
probeCredentials = await sessionResult(askProbeSecret(/passphrase/.test(message) ? "passphrase" : "password"), requestGeneration);1134
if (!probeCredentials) throw cancelled();1135
}1136
}1137
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1138
}, { 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);1139
probeCredentials = null;1140
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1141
}1143
async function removeKey(detail, file, entry) {1144
const requestGeneration = state.generation;1145
try {1146
const answer = await sessionResult(confirmAction({1147
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 }),1148
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: true1149
}), requestGeneration);1150
if (!answer) return;1151
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);1152
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1153
}1155
async function addKey(detail) {1156
const requestGeneration = state.generation;1157
try {1158
const publicKey = await sessionResult(runDialog(el.keyDialog, {1159
init: () => {1160
el.keyText.value = ""; el.keyGenComment.value = `${detail.username}@${state.sessions.find((session) => session.sessionId === state.sessionId)?.host || "server"}`;1161
el.keyGenPassphrase.value = ""; el.keyGenerateFields.hidden = true;1162
showError(el.keyError, ""); el.keyInfo.hidden = true;1163
},1164
submit: () => {1165
const text = el.keyText.value.trim();1166
if (!/^(ssh-ed25519|sk-ssh-ed25519@openssh\.com) [A-Za-z0-9+/=]+( .*)?$/.test(text)) {1167
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."));1168
return undefined;1169
}1170
return text;1171
}1172
}).finally(() => { el.keyGenPassphrase.value = ""; }), requestGeneration);1173
if (!publicKey) return;1174
await sessionResult(runMutation(t("Přidání SSH klíče"), (sessionId, auth) => api.users.keys(sessionId, { action: "add", ...identFor(detail.username), publicKey, ...auth })), requestGeneration);1175
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1176
}1178
async function generateKeyPair() {1179
const requestGeneration = state.generation;1180
showError(el.keyError, ""); el.keyInfo.hidden = true;1181
el.keyGenRun.disabled = true;1182
let passphrase = el.keyGenPassphrase.value;1183
el.keyGenPassphrase.value = "";1184
try {1185
const generated = await sessionResult(api.keys.generate({ type: "ed25519", comment: el.keyGenComment.value, passphrase, privateKeyFormat: "openssh" }), requestGeneration);1186
passphrase = "";1187
for (const field of ["privateKey", "privateKeyPem", "privateKeyOpenSSH", "privateKeyPpk"]) generated[field] = "";1188
const saved = await sessionResult(api.keys.save(generated.generationId), requestGeneration);1189
if (!saved || saved.canceled) { showError(el.keyError, t("Soukromý klíč nebyl uložen, proto se veřejný klíč nepřidá.")); return; }1190
el.keyText.value = generated.publicKey;1191
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.")}`;1192
el.keyInfo.hidden = false;1193
} catch (error) { if (requestGeneration !== state.generation) return;1194
showError(el.keyError, t("Generování selhalo: {error}", { error: describeError(error) }));1195
} finally { if (requestGeneration === state.generation) {1196
passphrase = "";1197
el.keyGenRun.disabled = false;1198
} }1199
}1201
async function openCreateDialog() {1202
const requestGeneration = state.generation;1203
try {1204
const inventory = state.inventory;1205
if (!inventory) return;1206
const windows = inventory.platform === "windows";1207
const groups = windows1208
? 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))1209
: 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));1210
const payload = await sessionResult(runDialog(el.createDialog, {1211
init: () => {1212
for (const id of ["createUsername", "createComment", "createHome", "createPassword", "createPassword2"]) el[id].value = "";1213
el.createMakeHome.checked = true; el.createAdmin.checked = false; el.createDescription.value = "";1214
for (const id of ["createShell", "createHome", "createPrimary"]) el[id].closest("label").hidden = windows;1215
el.createMakeHomeLabel.hidden = windows;1216
el.createDescriptionLabel.hidden = !windows;1217
el.createUsername.pattern = windows ? "[A-Za-z0-9_][A-Za-z0-9._ \\-]{0,19}" : "[a-z_][a-z0-9_\\-]{0,31}";1218
el.createUsername.maxLength = windows ? 20 : 32;1219
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)");1220
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.");1221
const shells = inventory.shells.length ? inventory.shells : ["/bin/sh"];1222
el.createShell.replaceChildren(...shells.map((shell) => h("option", { value: shell, text: shell, selected: shell === "/bin/bash" })));1223
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 })));1224
el.createGroups.replaceChildren(...groups.map((group) => h("option", { value: windows ? group.sid : group.name, text: group.name })));1225
showError(el.createError, "");1226
setTimeout(() => el.createUsername.focus(), 0);1227
},1228
submit: () => {1229
const username = el.createUsername.value.trim();1230
const password = el.createPassword.value;1231
const home = el.createHome.value.trim();1232
let problem = "";1233
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);1234
else if (inventory.users.some((user) => user.username === username)) problem = t(ERROR_TEXT.USERS_USER_EXISTS);1235
else if (home && !/^\/[A-Za-z0-9._/@+-]+$/.test(home)) problem = t(ERROR_TEXT.USERS_HOME_INVALID);1236
else if (password !== el.createPassword2.value) problem = t("Hesla se neshodují.");1237
else if (/[\r\n]/.test(password)) problem = t(ERROR_TEXT.USERS_PASSWORD_INVALID);1238
if (problem) { showError(el.createError, problem); return undefined; }1239
if (windows) {1240
return { action: "create", username, fullName: el.createComment.value.trim(), description: el.createDescription.value.trim(),1241
groups: [...el.createGroups.selectedOptions].map((option) => option.value), admin: el.createAdmin.checked, ...(password ? { password } : {}) };1242
}1243
return {1244
action: "create", username, comment: el.createComment.value.trim(), shell: el.createShell.value, home, createHome: el.createMakeHome.checked,1245
primaryGroup: el.createPrimary.value, groups: [...el.createGroups.selectedOptions].map((option) => option.value), admin: el.createAdmin.checked,1246
...(password ? { password } : {})1247
};1248
}1249
}).finally(() => { el.createPassword.value = ""; el.createPassword2.value = ""; }), requestGeneration);1250
if (!payload) return;1251
const result = await sessionResult(runMutation(t("Vytvoření účtu {user}", { user: payload.username }), (sessionId, auth) => api.users.manage(sessionId, { ...payload, ...auth })), requestGeneration);1252
payload.password = "";1253
if (result) {1254
el.filterSelect.value = "regular"; renderUsers();1255
void loadDetail(result.username);1256
}1257
} catch (error) { if (requestGeneration !== state.generation) return; throw error; }1258
}1260
// ---------- events ----------1261
el.closeButton.addEventListener("click", () => api.close());1262
el.refreshSessionsButton.addEventListener("click", () => { void loadSessions(); });1263
el.sessionSelect.addEventListener("change", () => { endedSessionId = ""; void selectSession(el.sessionSelect.value); });1264
el.reloadButton.addEventListener("click", async () => {1265
await refreshPrivilege();1266
await loadInventory();1267
if (state.selected) void loadDetail(state.selected);1268
});1269
el.elevatedButton.addEventListener("click", () => { void loadInventory({ elevated: true }); });1270
el.searchInput.addEventListener("input", renderUsers);1271
el.filterSelect.addEventListener("change", renderUsers);1272
el.createButton.addEventListener("click", () => { void openCreateDialog(); });1273
el.usersBody.addEventListener("click", (event) => {1274
const button = event.target.closest("button[data-username]");1275
if (button) void loadDetail(button.dataset.username);1276
});1277
document.querySelector("[role=tablist]").addEventListener("click", (event) => {1278
const tab = event.target.closest("[role=tab]");1279
if (tab) selectTab(tab.id.replace("tab-", ""));1280
});1281
document.querySelector("[role=tablist]").addEventListener("keydown", (event) => {1282
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;1283
const tabs = [...document.querySelectorAll("[role=tab]")];1284
const index = tabs.findIndex((tab) => tab.id === `tab-${state.tab}`);1285
const next = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1 : (index + (event.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length;1286
event.preventDefault();1287
selectTab(tabs[next].id.replace("tab-", ""));1288
});1289
el.keyImportButton.addEventListener("click", () => el.keyFile.click());1290
el.keyFile.addEventListener("change", async () => {1291
const file = el.keyFile.files?.[0];1292
el.keyFile.value = "";1293
if (!file) return;1294
if (file.size > 16 * 1024) { showError(el.keyError, t("Soubor je příliš velký pro veřejný klíč.")); return; }1295
const text = await file.text();1296
if (/PRIVATE KEY/.test(text)) { showError(el.keyError, t(ERROR_TEXT.USERS_KEY_PRIVATE)); return; }1297
el.keyText.value = text.trim();1298
showError(el.keyError, "");1299
});1300
el.keyGenerateButton.addEventListener("click", () => { el.keyGenerateFields.hidden = !el.keyGenerateFields.hidden; });1301
el.keyGenRun.addEventListener("click", () => { void generateKeyPair(); });1303
(async () => {1304
try { i18n.setLanguage(await api.ui.getLanguage()); } catch {}1305
i18n.apply(document);1306
api.ui.onLanguageChanged((language) => { i18n.setLanguage(language); i18n.apply(document); renderPrivilege(); renderUsers(); renderDetail(); });1307
try {1308
const info = await api.getInfo();1309
el.pluginVersion.textContent = `${info.name} v${info.version} · ${info.publisher}`;1310
} catch {}1311
await loadSessions();1312
})().catch((error) => setStatus(describeError(error), true));1314
setInterval(() => { if (!document.hidden) void loadSessions().catch(() => {}); }, 3000);SHA-256
c2893b854422cbb0bc203b837d8cec44eb12f78ce3d705116092d40ed1878469CH-J Proprietary Software License 1.14 · Die Quellen werden unter der CH-J Proprietary Software License 1.14 bereitgestellt. Ihre Verfügbarkeit ändert die Lizenzbedingungen nicht und gewährt keine zusätzlichen Rechte.
SHA-256 des Archivs
77380d4805485ffa4027fbe7858b5836f197a4aa9d52358a43e2d12d018744df