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