प्रकाशित सोर्स
सोर्स ZIP डाउनलोड करें
CH-J Server Manager
किसी विशेष ऐप्लिकेशन रिलीज़ की डायरेक्टरी और फ़ाइलें देखें।
CH-J / Server Manager
377 फ़ाइलें
core-20261019T111616Z-160a00bfcddc
जोड़ा गया: · बिल्ड किया गया:
1
"use strict";2
const APP_THEME = "dark";4
const api = window.chjCore;5
const i18n = window.chjI18n;6
const t = (key, values) => i18n.t(key, values);7
const TERMINAL_SESSION_ID = "terminal-main";8
const HASH_TOOL_ID = "chj.hash-checksum";9
if (api?.platform) document.body.classList.add(`platform-${api.platform}`);10
const state = {11
info: null,12
config: null,13
plugins: [],14
pluginState: null,15
pluginWindows: [],16
update: null,17
vault: null,18
profiles: [],19
selectedProfileId: "",20
terminalConnected: false,21
terminalStateKind: "disconnected"22
};24
const $ = (selector) => document.querySelector(selector);25
const hashToolButton = $("#hashToolButton");26
const coreNavigationButtons = [...$("#mainNavigation").querySelectorAll("[data-view]")];27
const selectedExportIds = new Set();28
let importPreview = null;30
const elements = {31
viewTitle: $("#viewTitle"), runtimeText: $("#runtimeText"), sidebarVersion: $("#sidebarVersion"),32
coreApiValue: $("#coreApiValue"), dataSchemaValue: $("#dataSchemaValue"), pluginCountValue: $("#pluginCountValue"),33
currentVersion: $("#currentVersion"), updateChannel: $("#updateChannel"), updateHeadline: $("#updateHeadline"),34
updateMessage: $("#updateMessage"), updateHash: $("#updateHash"), checkUpdateButton: $("#checkUpdateButton"),35
downloadUpdateButton: $("#downloadUpdateButton"), installUpdateButton: $("#installUpdateButton"), revealUpdateButton: $("#revealUpdateButton"),36
updateReleaseRows: $("#updateReleaseRows"), updateReleaseCount: $("#updateReleaseCount"), pluginRows: $("#pluginRows"),37
pluginCatalogRows: $("#pluginCatalogRows"), pluginCatalogSource: $("#pluginCatalogSource"), checkPluginCatalogButton: $("#checkPluginCatalogButton"),38
pluginTaskbar: $("#pluginTaskbar"), pluginTaskbarItems: $("#pluginTaskbarItems"),39
updateViewChannelSelect: $("#updateViewChannelSelect"), pluginViewChannelSelect: $("#pluginViewChannelSelect"),40
settingsForm: $("#settingsForm"), languageSelect: $("#languageSelect"), channelSelect: $("#channelSelect"), pluginChannelSelect: $("#pluginChannelSelect"), autoCheckInput: $("#autoCheckInput"),41
baseUrlsText: $("#baseUrlsText"), settingsStatus: $("#settingsStatus"), lockVaultButton: $("#lockVaultButton"),42
vaultOverlay: $("#vaultOverlay"), vaultForm: $("#vaultForm"), vaultLanguageSelect: $("#vaultLanguageSelect"), vaultModeText: $("#vaultModeText"), vaultTitle: $("#vaultTitle"),43
vaultDescription: $("#vaultDescription"), vaultPassword: $("#vaultPassword"), vaultConfirmLabel: $("#vaultConfirmLabel"),44
vaultPasswordConfirm: $("#vaultPasswordConfirm"), vaultMessage: $("#vaultMessage"), vaultSubmit: $("#vaultSubmit"),45
showVaultResetButton: $("#showVaultResetButton"), vaultResetPanel: $("#vaultResetPanel"),46
vaultResetConfirmation: $("#vaultResetConfirmation"), cancelVaultResetButton: $("#cancelVaultResetButton"),47
confirmVaultResetButton: $("#confirmVaultResetButton"),48
profileRows: $("#profileRows"), profileForm: $("#profileForm"), profileId: $("#profileId"), profileLabel: $("#profileLabel"),49
profileHost: $("#profileHost"), profilePort: $("#profilePort"), profileUsername: $("#profileUsername"),50
profileAuthMethod: $("#profileAuthMethod"), privateKeyField: $("#privateKeyField"), passwordStorageField: $("#passwordStorageField"),51
profileStorePassword: $("#profileStorePassword"), profileStoredPassword: $("#profileStoredPassword"),52
profilePrivateKeyPath: $("#profilePrivateKeyPath"), selectPrivateKeyButton: $("#selectPrivateKeyButton"),53
profileMessage: $("#profileMessage"), deleteProfileButton: $("#deleteProfileButton"), newProfileButton: $("#newProfileButton"),54
terminalProfileSelect: $("#terminalProfileSelect"), credentialLabelText: $("#credentialLabelText"), terminalCredential: $("#terminalCredential"),55
connectButton: $("#connectButton"), disconnectButton: $("#disconnectButton"), terminalState: $("#terminalState"),56
terminalHost: $("#terminalHost"), terminalElement: $("#terminal")57
};59
const titles = {60
overview: "nav.overview", terminal: "terminal.title", profiles: "nav.servers",61
updates: "nav.updates", plugins: "nav.plugins", diagnostics: "nav.diagnostics", settings: "nav.settings"62
};64
let diagnosticsView = null;65
let terminal = null;66
let fitAddon = null;68
function errorText(error) {69
const code = error?.code || String(error?.message || "").match(/BIOMETRIC_[A-Z_]+/)?.[0];70
if (code?.startsWith("BIOMETRIC_")) return t(`biometrics.${code}`);71
if (["SSH_LOCAL_NETWORK_DENIED", "SSH_MAC_NETWORK_UNREACHABLE"].includes(code)) return `${t(`ssh.${code}`)}\n${error.message || ""}`;72
return error?.message || String(error || t("errors.unknown"));73
}75
let biometricStatus = null;76
function renderBiometrics() {77
const status = biometricStatus;78
$("#biometricUnlockButton").hidden = !status?.enabled || !status.available || state.vault?.unlocked || !state.vault?.initialized;79
$("#biometricUnlockButton").textContent = t(`biometrics.${status?.provider || "touch-id"}`);80
$("#biometricStatus").textContent = status ? `${status.provider}: ${t(`biometrics.${status.code}`)} · ${t(status.enabled ? "security.enabled" : "security.disabled")}` : "";81
$("#biometricProtection").textContent = status ? t(status.protection === "biometry-current-set" ? "security.strong" : "security.convenience") : "";82
$("#enableBiometricsButton").disabled = !state.vault?.unlocked || !status?.available || status.enabled;83
$("#disableBiometricsButton").disabled = !state.vault?.unlocked || !status?.enrolled;84
$("#testBiometricsButton").disabled = !state.vault?.unlocked || !status?.available;85
}86
// Automatic Touch ID / Windows Hello prompt. Main decides whether it is armed and keeps it87
// single-flight; the renderer only reports that the window is visible and focused.88
let autoUnlockRunning = false;89
async function maybeAutoUnlock() {90
if (autoUnlockRunning || !api?.autoUnlockVaultWithBiometrics) return;91
if (!state.vault || state.vault.unlocked || !state.vault.initialized || state.vault.needsSetup) return;92
if (!biometricStatus?.enabled || !biometricStatus.available) return;93
if (document.visibilityState !== "visible" || !document.hasFocus() || elements.vaultPassword.value) return;94
autoUnlockRunning = true;95
$("#biometricUnlockButton").disabled = true;96
elements.vaultMessage.textContent = t("biometrics.autoPrompt");97
try {98
const result = await api.autoUnlockVaultWithBiometrics();99
if (result.status?.unlocked) { configureVault(result.status); await loadProfiles(); }100
else if (result.error) {101
elements.vaultMessage.textContent = `${errorText(result.error)} ${t("biometrics.usePassword")}`;102
elements.vaultPassword.focus();103
} else elements.vaultMessage.textContent = "";104
} catch (error) { elements.vaultMessage.textContent = errorText(error); }105
finally { autoUnlockRunning = false; $("#biometricUnlockButton").disabled = false; void refreshBiometrics(); }106
}107
async function refreshBiometrics() {108
try { biometricStatus = await api.getBiometricStatus(); renderBiometrics(); }109
catch (error) { $("#securityMessage").textContent = errorText(error); }110
}112
function showView(name) {113
document.querySelectorAll("[data-view]").forEach((button) => button.classList.toggle("active", button.dataset.view === name));114
document.querySelectorAll("[data-view-panel]").forEach((panel) => panel.classList.toggle("active", panel.dataset.viewPanel === name));115
elements.viewTitle.textContent = titles[name] ? t(titles[name]) : "CH-J Server Manager";116
if (name === "terminal") requestAnimationFrame(fitTerminal);117
}119
function pluginDisplay(id) {120
return state.config?.plugins.display?.[id] || (id === HASH_TOOL_ID ? "navigation" : "visible");121
}123
let preferenceSave = Promise.resolve();124
function saveUiPreferences(patch) {125
preferenceSave = preferenceSave.then(async () => {126
state.config = await api.updateConfig(patch());127
renderPlugins();128
}).catch((error) => { window.alert(errorText(error)); renderPlugins(); });129
return preferenceSave;130
}132
function moveNavigation(key, targetKey, after = false) {133
if (!$("#navigationEditToggle").checked) return;134
const keys = [...$("#mainNavigation").children].map((row) => row.dataset.navKey);135
const from = keys.indexOf(key), to = keys.indexOf(targetKey);136
if (from < 0 || to < 0 || from === to) return;137
keys.splice(from, 1); keys.splice(keys.indexOf(targetKey) + Number(after), 0, key);138
saveUiPreferences(() => ({ ui: { navigationOrder: [...keys, ...state.config.ui.navigationOrder.filter((id) => !keys.includes(id))] } }))139
.then(() => [...$("#mainNavigation").children].find((row) => row.dataset.navKey === key)?.querySelector(".nav-button").focus());140
}142
function renderNavigation() {143
const navigation = $("#mainNavigation");144
const buttons = new Map(coreNavigationButtons.map((button) => [button.dataset.view, button]));145
if (pluginDisplay(HASH_TOOL_ID) === "navigation") buttons.set(`plugin:${HASH_TOOL_ID}`, hashToolButton);146
for (const plugin of state.plugins) {147
if (plugin.id === HASH_TOOL_ID || pluginDisplay(plugin.id) !== "navigation") continue;148
const button = document.createElement("button"); button.type = "button"; button.className = "nav-button";149
const icon = document.createElement("span"); icon.textContent = "◇";150
const label = document.createElement("span"); label.className = "nav-label"; label.textContent = plugin.name;151
button.append(icon, label);152
button.addEventListener("click", async () => { try { await api.openPlugin(plugin.id); } catch (error) { window.alert(errorText(error)); } });153
buttons.set(`plugin:${plugin.id}`, button);154
}155
hashToolButton.querySelector(".nav-label").textContent = t("nav.hash");156
const defaults = [...coreNavigationButtons.map((button) => button.dataset.view)];157
defaults.splice(defaults.indexOf("settings"), 0, `plugin:${HASH_TOOL_ID}`);158
const order = [...new Set([...(state.config?.ui.navigationOrder || []), ...defaults, ...buttons.keys()])].filter((key) => buttons.has(key));159
navigation.replaceChildren();160
const editing = $("#navigationEditToggle").checked;161
navigation.classList.toggle("navigation-editing", editing);162
order.forEach((key) => {163
const row = document.createElement("div"); row.className = "navigation-row"; row.dataset.navKey = key;164
const button = buttons.get(key);165
button.title = editing ? t("nav.drag") : "";166
row.draggable = editing;167
const handle = document.createElement("span"); handle.className = "navigation-drag"; handle.textContent = "⠿"; handle.setAttribute("aria-hidden", "true");168
row.addEventListener("dragstart", (event) => {169
if (!$("#navigationEditToggle").checked) { event.preventDefault(); return; }170
event.dataTransfer.setData("text/chj-navigation", key); event.dataTransfer.effectAllowed = "move";171
row.classList.add("navigation-dragging");172
});173
row.addEventListener("dragend", () => navigation.querySelectorAll(".navigation-row").forEach((item) => item.classList.remove("navigation-dragging", "navigation-drop-before", "navigation-drop-after")));174
row.addEventListener("dragover", (event) => {175
if (!$("#navigationEditToggle").checked || ![...event.dataTransfer.types].includes("text/chj-navigation")) return;176
event.preventDefault(); event.dataTransfer.dropEffect = "move";177
const after = event.clientY >= row.getBoundingClientRect().top + row.offsetHeight / 2;178
row.classList.toggle("navigation-drop-before", !after); row.classList.toggle("navigation-drop-after", after);179
});180
row.addEventListener("dragleave", () => row.classList.remove("navigation-drop-before", "navigation-drop-after"));181
row.addEventListener("drop", (event) => {182
if (!$("#navigationEditToggle").checked) return;183
event.preventDefault(); row.classList.remove("navigation-drop-before", "navigation-drop-after");184
moveNavigation(event.dataTransfer.getData("text/chj-navigation"), key, event.clientY >= row.getBoundingClientRect().top + row.offsetHeight / 2);185
});186
row.append(button, handle); navigation.append(row);187
});188
}190
$("#navigationEditToggle").addEventListener("change", renderNavigation);191
$("#mainNavigation").addEventListener("click", (event) => {192
if ($("#navigationEditToggle").checked) { event.preventDefault(); event.stopPropagation(); }193
}, true);195
function cancelProfileImport() {196
importPreview = null;197
$("#profileImportDialog").close();198
$("#profileImportRows").replaceChildren();199
void api.cancelProfileImport().catch(() => {});200
}202
$("#importProfilesButton").addEventListener("click", async (event) => {203
const button = event.currentTarget; button.disabled = true;204
$("#profileTransferMessage").textContent = "";205
try {206
const preview = await api.previewProfileImport();207
if (preview.canceled) return;208
importPreview = preview;209
$("#profileImportRows").replaceChildren();210
for (const server of preview.servers) {211
const row = document.createElement("tr");212
for (const value of [server.name, server.host, server.username, server.port, server.duplicate ? t("transfer.yes") : "—"]) {213
const cell = document.createElement("td"); cell.textContent = value; row.append(cell);214
}215
$("#profileImportRows").append(row);216
}217
$("#profileImportSummary").textContent = t("transfer.summary", { count: preview.servers.length, duplicates: preview.servers.filter((server) => server.duplicate).length });218
$("#profileDuplicatePolicy").value = "skip";219
$("#profileImportMessage").textContent = "";220
$("#profileImportDialog").showModal();221
} catch (error) { $("#profileTransferMessage").textContent = errorText(error); }222
finally { button.disabled = false; }223
});224
$("#cancelProfileImport").addEventListener("click", cancelProfileImport);225
$("#profileImportDialog").addEventListener("cancel", (event) => { event.preventDefault(); cancelProfileImport(); });226
$("#confirmProfileImport").addEventListener("click", async (event) => {227
if (!importPreview) return;228
const button = event.currentTarget; button.disabled = true;229
try {230
const result = await api.commitProfileImport(importPreview.token, $("#profileDuplicatePolicy").value);231
cancelProfileImport();232
await loadProfiles();233
$("#profileTransferMessage").textContent = t("transfer.imported", result);234
} catch (error) { $("#profileImportMessage").textContent = errorText(error); }235
finally { button.disabled = false; }236
});237
$("#exportProfilesButton").addEventListener("click", async (event) => {238
const button = event.currentTarget; button.disabled = true;239
try {240
const result = await api.exportProfiles($("#profileExportFormat").value, $("#exportSelectedProfiles").checked ? [...selectedExportIds] : undefined);241
if (!result.canceled) $("#profileTransferMessage").textContent = t("transfer.exported", result);242
} catch (error) { $("#profileTransferMessage").textContent = errorText(error); }243
finally { button.disabled = false; }244
});246
function setBusy(button, busy, label) {247
button.disabled = busy;248
if (label) button.textContent = label;249
}251
function formatBytes(bytes) {252
const units = ["B", "KB", "MB", "GB"];253
let value = Number(bytes || 0);254
let index = 0;255
while (value >= 1024 && index < units.length - 1) { value /= 1024; index += 1; }256
return `${i18n.formatNumber(value, { maximumFractionDigits: 1 })} ${units[index]}`;257
}259
function applyLanguage(language) {260
const selected = i18n.setLanguage(language);261
document.documentElement.lang = selected;262
i18n.apply(document);263
elements.languageSelect.value = selected;264
elements.vaultLanguageSelect.value = selected;265
const activeView = document.querySelector("[data-view].active")?.dataset.view || "overview";266
showView(activeView);267
if (state.update) renderUpdate(state.update);268
if (state.config) elements.updateChannel.textContent = t("updates.channel", { channel: state.config.updates.channel });269
renderPlugins();270
renderProfiles();271
diagnosticsView?.refreshLanguage();272
renderTerminalProfileSelect();273
if (state.vault) configureVault(state.vault);274
renderBiometrics();275
const terminalStateKeys = { disconnected: "terminal.disconnected", connecting: "terminal.connecting", connected: "terminal.connected", error: "terminal.connectionError" };276
setTerminalState(state.terminalStateKind, t(terminalStateKeys[state.terminalStateKind] || "terminal.disconnected"));277
return selected;278
}280
function renderUpdate(updateState) {281
state.update = updateState;282
elements.currentVersion.textContent = `v${updateState.currentVersion || state.info?.version || "0.0.1"}`;283
const release = updateState.release;284
const currentReleaseSelected = updateState.releaseRelation === "sameVersionCurrentRelease";285
elements.downloadUpdateButton.hidden = currentReleaseSelected;286
elements.downloadUpdateButton.disabled = !release || currentReleaseSelected;287
renderReleaseCatalog(updateState);288
if (updateState.downloaded) {289
elements.updateHeadline.textContent = t("updates.downloaded", { version: release?.version || "?" });290
elements.updateMessage.textContent = `${updateState.downloaded.filename} · ${formatBytes(updateState.downloaded.size)} · ${t("updates.signatureVerified")}`;291
elements.updateHash.hidden = false;292
elements.updateHash.textContent = `SHA-512 ${updateState.downloaded.sha512}`;293
elements.revealUpdateButton.hidden = false;294
elements.installUpdateButton.hidden = false;295
} else if (release) {296
const relationKey = {297
newerVersion: "updates.newerVersion",298
sameVersionNewerRelease: "updates.sameVersionNewerRelease",299
sameVersionCurrentRelease: "updates.sameVersionCurrentRelease",300
sameVersionOlderRelease: "updates.sameVersionOlderRelease",301
olderVersion: "updates.olderVersion"302
}[updateState.releaseRelation] || "updates.selected";303
elements.updateHeadline.textContent = t(relationKey, { version: release.version });304
const published = t("updates.publishedAt", { date: formatReleaseDate(release.publishedAt) });305
elements.updateMessage.textContent = release.notes ? `${published} · ${release.notes}` : published;306
elements.updateHash.hidden = false;307
elements.updateHash.textContent = `SHA-512 ${release.sha512}`;308
elements.revealUpdateButton.hidden = true;309
elements.installUpdateButton.hidden = true;310
} else {311
elements.updateHeadline.textContent = t("updates.noneAvailable");312
elements.updateMessage.textContent = t("updates.noCompatible");313
elements.updateHash.hidden = true;314
elements.revealUpdateButton.hidden = true;315
elements.installUpdateButton.hidden = true;316
}317
}319
function formatReleaseDate(value) {320
const date = new Date(value);321
if (Number.isNaN(date.getTime())) return String(value || "—");322
return new Intl.DateTimeFormat(i18n.getLocale(), { dateStyle: "medium", timeStyle: "medium" }).format(date);323
}325
function renderReleaseCatalog(updateState) {326
const releases = Array.isArray(updateState.releases) ? updateState.releases : [];327
elements.updateReleaseCount.textContent = String(releases.length);328
elements.updateReleaseRows.replaceChildren();329
if (!releases.length) {330
const empty = document.createElement("div");331
empty.className = "update-release-empty";332
empty.textContent = t(updateState.status === "idle" ? "updates.catalogBeforeCheck" : "updates.catalogEmpty");333
elements.updateReleaseRows.append(empty);334
return;335
}336
for (const release of releases) {337
const row = document.createElement("button");338
row.type = "button";339
row.className = `update-release-row${release.id === updateState.selectedReleaseId ? " selected" : ""}`;340
const version = document.createElement("strong"); version.textContent = `v${release.version}`;341
const published = document.createElement("span"); published.textContent = formatReleaseDate(release.publishedAt);342
const file = document.createElement("span"); file.textContent = `${release.filename} · ${formatBytes(release.size)}`;343
const action = document.createElement("span"); action.className = "release-select-label"; action.textContent = t(release.id === updateState.selectedReleaseId ? "updates.selectedLabel" : "updates.selectLabel");344
row.append(version, published, file, action);345
row.addEventListener("click", async () => {346
try { renderUpdate(await api.selectUpdateRelease(release.id)); }347
catch (error) { elements.updateMessage.textContent = errorText(error); }348
});349
elements.updateReleaseRows.append(row);350
}351
}353
function renderPlugins() {354
const plugins = state.plugins;355
renderNavigation();356
elements.pluginCountValue.textContent = String(plugins.length);357
elements.pluginRows.replaceChildren();358
if (plugins.length === 0) {359
const empty = document.createElement("div");360
empty.className = "empty-state";361
const strong = document.createElement("strong"); strong.textContent = t("plugins.none");362
const span = document.createElement("span"); span.textContent = t("plugins.first");363
empty.append(strong, span); elements.pluginRows.append(empty); renderPluginCatalog(); renderPluginTaskbar(); return;364
}365
for (const plugin of plugins) {366
const row = document.createElement("div"); row.className = "plugin-row installed-plugin-row"; row.dataset.pluginId = plugin.id;367
const name = document.createElement("div"); name.className = "installed-plugin-name";368
const title = document.createElement("strong"); title.textContent = plugin.name; name.append(title);369
const details = document.createElement("details"); details.className = "installed-plugin-details";370
const summary = document.createElement("summary"); summary.textContent = t("plugins.details");371
const description = document.createElement("p"); description.textContent = plugin.description;372
const permissions = document.createElement("p"); permissions.textContent = `${t("plugins.permissions")}: ${plugin.permissions.join(", ") || t("plugins.noPermissions")}`;373
details.append(summary, description, permissions); name.append(details);374
const version = document.createElement("span"); version.textContent = plugin.version;375
const actions = document.createElement("div"); actions.className = "plugin-actions";376
const open = document.createElement("button"); open.type = "button"; open.className = "button"; open.textContent = t("plugins.open");377
open.addEventListener("click", async () => { try { await api.openPlugin(plugin.id); } catch (error) { window.alert(errorText(error)); } });378
const mode = pluginDisplay(plugin.id);379
row.classList.toggle("plugin-hidden", mode === "hidden");380
open.disabled = mode === "hidden";381
const visible = document.createElement("input"); visible.type = "checkbox"; visible.className = "plugin-visibility"; visible.checked = mode !== "hidden";382
visible.setAttribute("aria-label", `${plugin.name}: ${t("plugins.show")}`);383
const pinned = document.createElement("input"); pinned.type = "checkbox"; pinned.className = "plugin-pin"; pinned.checked = mode === "navigation"; pinned.disabled = mode === "hidden";384
pinned.setAttribute("aria-label", `${plugin.name}: ${t("plugins.inMenu")}`);385
const saveDisplay = (value) => {386
visible.disabled = true; pinned.disabled = true;387
saveUiPreferences(() => ({ plugins: { display: { ...state.config.plugins.display, [plugin.id]: value } } }));388
};389
visible.addEventListener("change", () => saveDisplay(visible.checked ? "visible" : "hidden"));390
pinned.addEventListener("change", () => saveDisplay(pinned.checked ? "navigation" : "visible"));391
actions.append(open);392
if (plugin.bundled) {393
version.title = t("plugins.bundled");394
} else {395
const remove = document.createElement("button"); remove.type = "button"; remove.className = "button danger"; remove.textContent = t("plugins.remove");396
remove.addEventListener("click", async () => {397
if (!window.confirm(t("plugins.removeConfirm", { name: plugin.name }))) return;398
remove.disabled = true;399
try {400
state.pluginState = await api.uninstallPlugin(plugin.id);401
state.plugins = state.pluginState.installed;402
renderPlugins();403
} catch (error) { window.alert(errorText(error)); remove.disabled = false; }404
});405
actions.append(remove);406
}407
row.append(name, version, visible, pinned, actions); elements.pluginRows.append(row);408
}409
renderPluginCatalog();410
renderPluginTaskbar();411
}413
function renderPluginTaskbar(windows = state.pluginWindows) {414
state.pluginWindows = Array.isArray(windows) ? windows : [];415
const minimized = state.pluginWindows.filter((item) => item.minimized);416
elements.pluginTaskbar.hidden = minimized.length === 0;417
elements.pluginTaskbarItems.replaceChildren();418
for (const plugin of minimized) {419
const button = document.createElement("button");420
button.type = "button";421
button.className = "plugin-taskbar-item";422
button.title = t("plugins.restore", { name: plugin.name });423
const icon = document.createElement("span");424
icon.className = "plugin-taskbar-icon";425
icon.textContent = String(plugin.name || plugin.pluginId).split(/\s+/).map((part) => part[0]).join("").slice(0, 2).toUpperCase();426
const name = document.createElement("strong");427
name.textContent = plugin.name;428
const action = document.createElement("small");429
action.textContent = t("plugins.restoreAction");430
button.append(icon, name, action);431
button.addEventListener("click", async () => {432
try { await api.openPlugin(plugin.pluginId); }433
catch (error) { window.alert(errorText(error)); }434
});435
elements.pluginTaskbarItems.append(button);436
}437
}439
function renderPluginCatalog() {440
if (!elements.pluginCatalogRows) return;441
const catalog = (state.pluginState?.catalog || []).filter((plugin) => plugin.id !== HASH_TOOL_ID);442
elements.pluginCatalogSource.textContent = state.pluginState?.sourceBaseUrl || "";443
elements.pluginCatalogRows.replaceChildren();444
if (!catalog.length) {445
const empty = document.createElement("div"); empty.className = "plugin-catalog-empty";446
empty.textContent = t(state.pluginState?.sourceBaseUrl ? "plugins.catalogEmpty" : "plugins.catalogBeforeCheck");447
elements.pluginCatalogRows.append(empty); return;448
}449
for (const plugin of catalog) {450
const row = document.createElement("div"); row.className = "plugin-row plugin-table-row";451
const name = document.createElement("div");452
const strong = document.createElement("strong"); strong.textContent = plugin.name;453
const notes = document.createElement("small"); notes.textContent = plugin.notes || plugin.id;454
name.append(strong, notes);455
const version = document.createElement("span"); version.textContent = `v${plugin.version} · ${plugin.channel}`;456
const permissions = document.createElement("span"); permissions.textContent = plugin.permissions.join(", ") || t("plugins.noPermissions");457
const install = document.createElement("button"); install.type = "button"; install.className = `button${plugin.installed ? "" : " primary"}`;458
install.disabled = plugin.installed;459
install.textContent = t(plugin.installed ? "plugins.installed" : plugin.updateAvailable ? "plugins.update" : "plugins.install");460
install.addEventListener("click", async () => {461
if (!window.confirm(t("plugins.installConfirm", { name: plugin.name, version: plugin.version, permissions: plugin.permissions.join(", ") || t("plugins.noPermissions") }))) return;462
install.disabled = true; install.textContent = t("plugins.installing");463
try {464
state.pluginState = await api.installPlugin(plugin.releaseId);465
state.plugins = state.pluginState.installed;466
renderPlugins();467
} catch (error) { window.alert(errorText(error)); install.disabled = false; install.textContent = t("plugins.install"); }468
});469
row.append(name, version, permissions, install); elements.pluginCatalogRows.append(row);470
}471
}473
function configureVault(status) {474
state.vault = status;475
renderBiometrics();476
$("#securityMasterPassword").value = "";477
elements.vaultOverlay.hidden = Boolean(status.unlocked);478
elements.vaultMessage.className = "form-message";479
elements.vaultMessage.textContent = "";480
elements.vaultPassword.value = "";481
elements.vaultPasswordConfirm.value = "";482
elements.vaultResetConfirmation.value = "";483
elements.vaultResetPanel.hidden = true;484
if (status.unlocked) return;485
if (status.damaged) {486
elements.vaultForm.dataset.mode = "damaged";487
elements.vaultModeText.textContent = t("vault.damagedMode");488
elements.vaultTitle.textContent = t("vault.damagedTitle");489
elements.vaultDescription.textContent = t("vault.damagedDescription");490
elements.vaultSubmit.disabled = true;491
elements.vaultConfirmLabel.hidden = true;492
elements.showVaultResetButton.hidden = false;493
return;494
}495
const setup = status.needsSetup;496
elements.vaultForm.dataset.mode = setup ? "setup" : "unlock";497
elements.vaultModeText.textContent = t(setup ? "vault.setupMode" : "vault.lockedMode");498
elements.vaultSubmit.disabled = false;499
elements.vaultConfirmLabel.hidden = !setup;500
elements.showVaultResetButton.hidden = setup;501
elements.vaultPassword.autocomplete = setup ? "new-password" : "current-password";502
elements.vaultTitle.textContent = t(setup ? "vault.setupTitle" : "vault.unlockTitle");503
elements.vaultDescription.textContent = t(setup ? "vault.setupDescription" : "vault.lockedDescription");504
elements.vaultSubmit.textContent = t(setup ? "vault.create" : "vault.unlock");505
setTimeout(() => elements.vaultPassword.focus(), 20);506
}508
function clearProtectedUi() {509
$("#navigationEditToggle").checked = false;510
renderNavigation();511
cancelProfileImport();512
selectedExportIds.clear();513
state.profiles = [];514
state.selectedProfileId = "";515
state.terminalConnected = false;516
renderProfiles();517
diagnosticsView?.refreshLanguage();518
renderTerminalProfileSelect();519
setTerminalState("disconnected", t("terminal.disconnected"));520
terminal?.reset();521
}523
async function loadProfiles(selectId = state.selectedProfileId) {524
state.profiles = await api.listProfiles();525
if (!state.profiles.some((profile) => profile.id === selectId)) selectId = state.profiles[0]?.id || "";526
state.selectedProfileId = selectId;527
renderProfiles();528
diagnosticsView?.refreshLanguage();529
renderTerminalProfileSelect();530
if (selectId) fillProfileForm(state.profiles.find((profile) => profile.id === selectId));531
else resetProfileForm();532
}534
function renderProfiles() {535
for (const id of selectedExportIds) if (!state.profiles.some((profile) => profile.id === id)) selectedExportIds.delete(id);536
elements.profileRows.replaceChildren();537
if (!state.profiles.length) {538
const empty = document.createElement("div"); empty.className = "profile-empty";539
empty.textContent = t("profiles.none"); elements.profileRows.append(empty); return;540
}541
for (const profile of state.profiles) {542
const row = document.createElement("button"); row.type = "button";543
row.className = `profile-row${profile.id === state.selectedProfileId ? " active" : ""}`;544
const name = document.createElement("strong"); name.textContent = profile.label;545
const address = document.createElement("span"); address.textContent = `${profile.username}@${profile.host}:${profile.port}`;546
const auth = document.createElement("span"); auth.className = "profile-auth"; auth.textContent = t(profile.authMethod === "privateKey" ? "profiles.key" : "profiles.password");547
row.append(name, address, auth);548
row.addEventListener("click", () => { state.selectedProfileId = profile.id; renderProfiles(); fillProfileForm(profile); });549
const wrapper = document.createElement("div"); wrapper.className = "profile-select-row";550
const select = document.createElement("input"); select.type = "checkbox"; select.checked = selectedExportIds.has(profile.id);551
select.setAttribute("aria-label", t("transfer.select", { name: profile.label }));552
select.addEventListener("change", () => { if (select.checked) selectedExportIds.add(profile.id); else selectedExportIds.delete(profile.id); });553
wrapper.append(select, row); elements.profileRows.append(wrapper);554
}555
}557
function renderTerminalProfileSelect() {558
const previous = elements.terminalProfileSelect.value || state.selectedProfileId;559
elements.terminalProfileSelect.replaceChildren(new Option(t("terminal.selectServer"), ""));560
for (const profile of state.profiles) elements.terminalProfileSelect.add(new Option(`${profile.label} — ${profile.host}`, profile.id));561
elements.terminalProfileSelect.value = state.profiles.some((profile) => profile.id === previous) ? previous : (state.profiles[0]?.id || "");562
updateTerminalProfile();563
}565
function resetProfileForm() {566
elements.profileForm.reset();567
elements.profileId.value = "";568
elements.profilePort.value = "22";569
elements.profileAuthMethod.value = "password";570
elements.profilePrivateKeyPath.value = "";571
elements.profileStorePassword.checked = false;572
elements.profileStoredPassword.value = "";573
elements.profileStoredPassword.placeholder = t("profiles.storePasswordPlaceholder");574
elements.deleteProfileButton.hidden = true;575
elements.profileMessage.textContent = "";576
updatePrivateKeyField();577
}579
function fillProfileForm(profile) {580
if (!profile) { resetProfileForm(); return; }581
elements.profileId.value = profile.id;582
elements.profileLabel.value = profile.label;583
elements.profileHost.value = profile.host;584
elements.profilePort.value = String(profile.port);585
elements.profileUsername.value = profile.username;586
elements.profileAuthMethod.value = profile.authMethod;587
elements.profilePrivateKeyPath.value = profile.privateKeyPath || "";588
elements.profileStorePassword.checked = Boolean(profile.hasStoredPassword);589
elements.profileStoredPassword.value = "";590
elements.profileStoredPassword.placeholder = t(profile.hasStoredPassword ? "profiles.passwordStoredPlaceholder" : "profiles.storePasswordPlaceholder");591
elements.deleteProfileButton.hidden = false;592
elements.profileMessage.textContent = "";593
updatePrivateKeyField();594
}596
function updatePrivateKeyField() {597
const privateKey = elements.profileAuthMethod.value === "privateKey";598
elements.privateKeyField.hidden = !privateKey;599
elements.passwordStorageField.hidden = privateKey;600
elements.profileStoredPassword.disabled = privateKey || !elements.profileStorePassword.checked;601
}603
function updateTerminalProfile() {604
const profile = state.profiles.find((item) => item.id === elements.terminalProfileSelect.value);605
if (!profile) {606
elements.terminalHost.textContent = t("terminal.noProfile");607
elements.credentialLabelText.textContent = t("terminal.password");608
elements.terminalCredential.placeholder = t("terminal.sshPassword");609
return;610
}611
elements.terminalHost.textContent = `${profile.username}@${profile.host}:${profile.port} · ${profile.authMethod === "privateKey" ? profile.privateKeyPath : t("terminal.passwordAuth")}`;612
elements.credentialLabelText.textContent = t(profile.authMethod === "privateKey" ? "terminal.passphrase" : "terminal.password");613
elements.terminalCredential.placeholder = t(profile.authMethod === "privateKey" ? "terminal.keyPassphrase" : profile.hasStoredPassword ? "terminal.savedPasswordHint" : "terminal.sshPassword");614
}616
function initTerminal() {617
if (!window.Terminal || !window.FitAddon?.FitAddon) {618
elements.terminalHost.textContent = t("terminal.libraryMissing");619
return;620
}621
terminal = new window.Terminal({622
cursorBlink: true,623
fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",624
fontSize: 13,625
scrollback: 8000,626
theme: { background: "#050b12", foreground: "#d8e7f5", cursor: "#43d6a0", selectionBackground: "#264c6d" }627
});628
fitAddon = new window.FitAddon.FitAddon();629
terminal.loadAddon(fitAddon);630
terminal.open(elements.terminalElement);631
terminal.writeln("\x1b[36mCH-J Server Manager Core\x1b[0m");632
terminal.writeln(`${t("terminal.welcome")}\r\n`);633
terminal.onData((data) => { if (state.terminalConnected) api.sendTerminalInput(TERMINAL_SESSION_ID, data); });634
new ResizeObserver(() => fitTerminal()).observe(elements.terminalElement);635
fitTerminal();636
}638
function fitTerminal() {639
if (!terminal || !fitAddon || elements.terminalElement.offsetParent === null) return;640
try {641
fitAddon.fit();642
if (state.terminalConnected) void api.resizeTerminal(TERMINAL_SESSION_ID, terminal.cols, terminal.rows);643
} catch {}644
}646
function setTerminalState(kind, text) {647
state.terminalStateKind = kind;648
elements.terminalState.className = `connection-badge ${kind}`;649
elements.terminalState.textContent = text;650
if (kind !== "connected") state.terminalLatency = null;651
renderTerminalLatency();652
elements.connectButton.disabled = kind === "connecting" || kind === "connected";653
elements.disconnectButton.disabled = kind !== "connected" && kind !== "connecting";654
elements.terminalProfileSelect.disabled = kind === "connecting" || kind === "connected";655
}657
function renderTerminalLatency() {658
const element = $("#terminalLatency");659
element.hidden = state.terminalStateKind !== "connected";660
const latency = state.terminalLatency;661
const ms = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? (value < 0.1 ? "<0.1 ms" : `${value.toFixed(1)} ms`) : null;662
const pingReasons = { timeout: "terminal.pingTimeout", denied: "terminal.pingDenied", unreachable: "terminal.pingUnreachable", unsupported: "terminal.pingUnsupported", error: "terminal.pingError" };663
let ping = `— (${t("terminal.measuring")})`;664
let ssh = ping;665
if (latency?.measuredAt) {666
const family = latency.pingFamily === 6 ? "IPv6" : latency.pingFamily === 4 ? "IPv4" : "";667
const pingValue = ms(latency.pingMs);668
const loss = typeof latency.pingLoss === "number" && latency.pingLoss > 0 ? `, ${t("terminal.pingLoss", { loss: Math.round(latency.pingLoss * 100) })}` : "";669
ping = pingValue ? `${latency.pingLessThan ? "<" : ""}${pingValue}${family ? ` ${family}` : ""}${loss}` : `— (${t(pingReasons[latency.pingStatus] || "terminal.latencyUnavailable")})`;670
const sshValue = ms(latency.sshRttMs);671
ssh = sshValue || `— (${t("terminal.latencyUnavailable")})`;672
}673
element.textContent = `${t("terminal.ping")}: ${ping} · ${t("terminal.sshRtt")}: ${ssh}`;674
const method = latency?.sshRttMethod === "transport" ? t("terminal.sshRttTransport") : latency?.sshRttMethod === "command" ? t("terminal.sshRttCommand") : "";675
element.title = [t("terminal.latencyMeaning"), method, latency?.pingReason, latency?.sshRttError].filter(Boolean).join("\n");676
}678
async function connectTerminal(retry = false) {679
const profile = state.profiles.find((item) => item.id === elements.terminalProfileSelect.value);680
if (!profile) { showView("profiles"); elements.profileMessage.textContent = t("terminal.noProfile"); return; }681
fitTerminal();682
if (!retry) {683
terminal?.clear();684
terminal?.writeln(`\x1b[33m${t("terminal.connectingTo", { target: `${profile.username}@${profile.host}:${profile.port}` })}\x1b[0m`);685
}686
setTerminalState("connecting", t("terminal.connecting"));687
const credential = elements.terminalCredential.value;688
const result = await api.connectSsh({689
sessionId: TERMINAL_SESSION_ID,690
profileId: profile.id,691
password: profile.authMethod === "password" ? credential : undefined,692
passphrase: profile.authMethod === "privateKey" ? credential : undefined,693
cols: terminal?.cols || 100,694
rows: terminal?.rows || 30695
});696
if (result.ok) {697
state.terminalConnected = true;698
elements.terminalCredential.value = "";699
setTerminalState("connected", t("terminal.connected"));700
terminal?.focus();701
return;702
}703
const issue = result.error || { code: "SSH_CONNECTION_FAILED", message: t("ssh.failed") };704
if (issue.code === "HOST_KEY_UNKNOWN") {705
const accepted = window.confirm(t("ssh.unknownHost", issue));706
if (accepted) {707
const trusted = await api.trustSshHostKey({ sessionId: TERMINAL_SESSION_ID, profileId: profile.id, fingerprint: issue.fingerprint });708
if (trusted.ok) { await connectTerminal(true); return; }709
terminal?.writeln(`\r\n\x1b[31m${trusted.error?.message || t("ssh.trustFailed")}\x1b[0m`);710
}711
} else if (issue.code === "HOST_KEY_MISMATCH") {712
terminal?.writeln(`\r\n\x1b[31m${t("ssh.keyChanged")}\x1b[0m`);713
terminal?.writeln(`${t("ssh.knownKey")}: ${issue.knownFingerprint}\r\n${t("ssh.newKey")}: ${issue.fingerprint}`);714
const accepted = window.confirm(t("ssh.changedHostConfirm", issue));715
if (accepted) {716
const trusted = await api.trustSshHostKey({717
sessionId: TERMINAL_SESSION_ID,718
profileId: profile.id,719
fingerprint: issue.fingerprint,720
knownFingerprint: issue.knownFingerprint,721
replaceKnown: true722
});723
if (trusted.ok) { await connectTerminal(true); return; }724
terminal?.writeln(`\r\n\x1b[31m${trusted.error?.message || t("ssh.trustFailed")}\x1b[0m`);725
}726
} else {727
terminal?.writeln(`\r\n\x1b[31m${errorText(issue)}\x1b[0m`);728
}729
state.terminalConnected = false;730
setTerminalState("error", t("terminal.connectionError"));731
}733
async function checkUpdates() {734
setBusy(elements.checkUpdateButton, true, t("updates.checking"));735
elements.updateHeadline.textContent = t("updates.checkingServer");736
elements.updateMessage.textContent = t("updates.tryingEndpoints");737
try { renderUpdate(await api.checkForUpdates()); }738
catch (error) { elements.updateHeadline.textContent = t("updates.checkFailed"); elements.updateMessage.textContent = errorText(error); }739
finally { setBusy(elements.checkUpdateButton, false, t("updates.check")); }740
}742
async function initialize() {743
if (!api || !i18n) throw new Error("Core preload or i18n API is unavailable.");744
[state.info, state.config, state.pluginState, state.update, state.vault] = await Promise.all([745
api.getInfo(), api.getConfig(), api.getPluginState(), api.getUpdateState(), api.getVaultStatus()746
]);747
state.plugins = state.pluginState.installed;748
state.pluginWindows = state.pluginState.windows || [];749
i18n.setLanguage(state.config.ui.language);750
document.documentElement.lang = i18n.getLanguage();751
i18n.apply(document);752
elements.runtimeText.textContent = `${state.info.platform} / ${state.info.arch}`;753
elements.sidebarVersion.textContent = `v${state.info.version}`;754
elements.coreApiValue.textContent = state.info.coreApi;755
elements.dataSchemaValue.textContent = String(state.info.dataSchema);756
elements.currentVersion.textContent = `v${state.info.version}`;757
elements.languageSelect.value = state.config.ui.language;758
elements.vaultLanguageSelect.value = state.config.ui.language;759
elements.vaultLanguageSelect.disabled = false;760
elements.channelSelect.value = state.config.updates.channel;761
elements.updateViewChannelSelect.value = state.config.updates.channel;762
elements.pluginChannelSelect.value = state.config.plugins.channel;763
elements.pluginViewChannelSelect.value = state.config.plugins.channel;764
elements.autoCheckInput.checked = state.config.updates.autoCheck;765
elements.baseUrlsText.textContent = state.config.updates.baseUrls.join("\n");766
elements.updateChannel.textContent = t("updates.channel", { channel: state.config.updates.channel });767
const security = state.config.security;768
$("#autoLockEnabled").checked = security.autoLockMinutes > 0;769
$("#autoLockMinutes").value = String(security.autoLockMinutes || 15);770
$("#autoLockMinutes").disabled = !security.autoLockMinutes;771
$("#lockOnBlur").checked = security.lockOnBlur;772
$("#requireSystemAuthentication").checked = security.requireSystemAuthentication;773
diagnosticsView = window.CHJ_DIAGNOSTICS.mount($("#diagnosticsView"), {774
// Diagnostics follows the application theme. The application shell is dark-only, so775
// the module must not fall back to the OS colour scheme (light on many Windows/Linux setups).776
api: api.diagnostics, language: () => i18n.getLanguage(), getTheme: () => APP_THEME777
});778
renderPlugins(); renderUpdate(state.update); initTerminal(); configureVault(state.vault);779
void refreshBiometrics().then(maybeAutoUnlock);780
window.addEventListener("focus", () => void maybeAutoUnlock());781
document.addEventListener("visibilitychange", () => void maybeAutoUnlock());782
if (state.vault.unlocked) await loadProfiles();783
}785
document.querySelectorAll("[data-view]").forEach((button) => button.addEventListener("click", () => showView(button.dataset.view)));786
hashToolButton.addEventListener("click", async () => {787
try { await api.openPlugin(HASH_TOOL_ID); }788
catch (error) { window.alert(errorText(error)); }789
});790
elements.vaultForm.addEventListener("submit", async (event) => {791
event.preventDefault();792
const password = elements.vaultPassword.value;793
const passwordLength = Array.from(password).length;794
if (passwordLength < 4 || passwordLength > 64) { elements.vaultMessage.textContent = t("vault.passwordLength"); return; }795
if (state.vault.needsSetup && password !== elements.vaultPasswordConfirm.value) { elements.vaultMessage.textContent = t("vault.passwordMismatch"); return; }796
setBusy(elements.vaultSubmit, true, t(state.vault.needsSetup ? "vault.creating" : "vault.unlocking"));797
try {798
const status = state.vault.needsSetup ? await api.createVault(password) : await api.unlockVault(password);799
configureVault(status);800
await loadProfiles();801
} catch (error) { elements.vaultMessage.className = "form-message"; elements.vaultMessage.textContent = errorText(error); }802
finally { if (!state.vault.unlocked) setBusy(elements.vaultSubmit, false, t(state.vault.needsSetup ? "vault.create" : "vault.unlock")); }803
});804
elements.lockVaultButton.addEventListener("click", async () => {805
configureVault(await api.lockVault());806
clearProtectedUi();807
terminal?.writeln(`${t("terminal.vaultLocked")}\r\n`);808
});809
$("#biometricUnlockButton").addEventListener("click", async event => {810
event.currentTarget.disabled = true;811
try { configureVault(await api.unlockVaultWithBiometrics()); await loadProfiles(); }812
catch (error) { elements.vaultMessage.textContent = errorText(error); }813
finally { $("#biometricUnlockButton").disabled = false; void refreshBiometrics(); }814
});815
for (const [id, action, message] of [816
["enableBiometricsButton", () => api.enableBiometrics(), "security.enabled"],817
["disableBiometricsButton", () => api.disableBiometrics(), "security.disabled"],818
["testBiometricsButton", () => api.authenticateSensitiveAction(), "security.testPassed"]819
]) {820
$("#" + id).addEventListener("click", async event => {821
event.currentTarget.disabled = true;822
try { await action(); $("#securityMessage").textContent = t(message); }823
catch (error) { $("#securityMessage").textContent = errorText(error); }824
finally { await refreshBiometrics(); }825
});826
}827
$("#autoLockEnabled").addEventListener("change", event => {828
$("#autoLockMinutes").disabled = !event.target.checked;829
if (event.target.checked && $("#autoLockMinutes").value === "0") $("#autoLockMinutes").value = "15";830
});831
$("#securityForm").addEventListener("submit", async event => {832
event.preventDefault();833
const password = $("#securityMasterPassword").value; $("#securityMasterPassword").value = "";834
try {835
state.config = await api.updateConfig({ masterPassword: password, security: {836
autoLockMinutes: $("#autoLockEnabled").checked ? Number($("#autoLockMinutes").value) : 0,837
lockOnBlur: $("#lockOnBlur").checked, requireSystemAuthentication: $("#requireSystemAuthentication").checked838
} });839
$("#securityMessage").textContent = t("settings.saved");840
} catch (error) { $("#securityMessage").textContent = errorText(error); }841
});842
elements.showVaultResetButton.addEventListener("click", () => {843
elements.vaultResetPanel.hidden = false;844
elements.showVaultResetButton.hidden = true;845
elements.vaultResetConfirmation.focus();846
});847
elements.cancelVaultResetButton.addEventListener("click", () => {848
elements.vaultResetPanel.hidden = true;849
elements.showVaultResetButton.hidden = false;850
elements.vaultResetConfirmation.value = "";851
});852
elements.confirmVaultResetButton.addEventListener("click", async () => {853
if (elements.vaultResetConfirmation.value !== "SMAZAT") {854
elements.vaultMessage.textContent = t("vault.typeDelete");855
return;856
}857
if (!window.confirm(t("vault.finalResetConfirm"))) return;858
setBusy(elements.confirmVaultResetButton, true, t("vault.deleting"));859
try {860
const status = await api.resetVault("SMAZAT");861
clearProtectedUi();862
configureVault(status);863
elements.vaultMessage.className = "form-message success";864
elements.vaultMessage.textContent = t("vault.resetDone");865
} catch (error) {866
elements.vaultMessage.className = "form-message";867
elements.vaultMessage.textContent = errorText(error);868
} finally {869
setBusy(elements.confirmVaultResetButton, false, t("vault.resetAction"));870
}871
});872
elements.newProfileButton.addEventListener("click", () => { state.selectedProfileId = ""; renderProfiles(); resetProfileForm(); elements.profileLabel.focus(); });873
elements.profileAuthMethod.addEventListener("change", updatePrivateKeyField);874
elements.profileStorePassword.addEventListener("change", updatePrivateKeyField);875
elements.selectPrivateKeyButton.addEventListener("click", async () => {876
const result = await api.selectPrivateKey();877
if (!result.canceled) elements.profilePrivateKeyPath.value = result.path;878
});879
elements.profileForm.addEventListener("submit", async (event) => {880
event.preventDefault(); elements.profileMessage.className = "form-message"; elements.profileMessage.textContent = "";881
try {882
const saved = await api.saveProfile({883
id: elements.profileId.value || undefined, label: elements.profileLabel.value, host: elements.profileHost.value,884
port: Number(elements.profilePort.value), username: elements.profileUsername.value,885
authMethod: elements.profileAuthMethod.value, privateKeyPath: elements.profilePrivateKeyPath.value,886
storePassword: elements.profileAuthMethod.value === "password" && elements.profileStorePassword.checked,887
password: elements.profileStoredPassword.value888
});889
await loadProfiles(saved.id); elements.profileMessage.className = "form-message success"; elements.profileMessage.textContent = t("profiles.saved");890
} catch (error) { elements.profileMessage.textContent = errorText(error); }891
});892
elements.deleteProfileButton.addEventListener("click", async () => {893
const id = elements.profileId.value;894
if (!id || !window.confirm(t("profiles.deleteConfirm"))) return;895
await api.deleteProfile(id); state.selectedProfileId = ""; await loadProfiles("");896
});897
elements.terminalProfileSelect.addEventListener("change", () => { elements.terminalCredential.value = ""; updateTerminalProfile(); });898
elements.connectButton.addEventListener("click", () => connectTerminal().catch((error) => { setTerminalState("error", t("terminal.error")); terminal?.writeln(`\r\n\x1b[31m${errorText(error)}\x1b[0m`); }));899
elements.disconnectButton.addEventListener("click", async () => { await api.disconnectSsh(TERMINAL_SESSION_ID); });900
elements.checkUpdateButton.addEventListener("click", checkUpdates);901
elements.downloadUpdateButton.addEventListener("click", async () => {902
setBusy(elements.downloadUpdateButton, true, t("updates.downloadingAndVerifying"));903
elements.updateHeadline.textContent = t("updates.verifyingSignature");904
try { renderUpdate(await api.downloadUpdate()); }905
catch (_error) {906
elements.updateHeadline.textContent = t("updates.downloadRejected");907
elements.updateMessage.textContent = t("updates.signatureFailure");908
elements.installUpdateButton.hidden = true;909
elements.revealUpdateButton.hidden = true;910
}911
finally { setBusy(elements.downloadUpdateButton, false, t("updates.download")); }912
});913
elements.installUpdateButton.addEventListener("click", async () => {914
const release = state.update?.release;915
if (!release || !window.confirm(t("updates.installConfirm", { version: release.version, date: formatReleaseDate(release.publishedAt) }))) return;916
setBusy(elements.installUpdateButton, true, t("updates.verifyingSignature"));917
try { await api.installUpdate(); }918
catch (_error) {919
try { renderUpdate(await api.getUpdateState()); } catch {}920
elements.updateHeadline.textContent = t("updates.installFailed");921
elements.updateMessage.textContent = t("updates.installFailure");922
elements.installUpdateButton.hidden = true;923
} finally { setBusy(elements.installUpdateButton, false, t("updates.install")); }924
});925
elements.revealUpdateButton.addEventListener("click", () => api.revealUpdate());926
elements.updateViewChannelSelect.addEventListener("change", async () => {927
state.config = await api.updateConfig({ updates: { channel: elements.updateViewChannelSelect.value } });928
elements.channelSelect.value = state.config.updates.channel;929
elements.updateChannel.textContent = t("updates.channel", { channel: state.config.updates.channel });930
await checkUpdates();931
});932
elements.pluginViewChannelSelect.addEventListener("change", async () => {933
state.config = await api.updateConfig({ plugins: { channel: elements.pluginViewChannelSelect.value } });934
elements.pluginChannelSelect.value = state.config.plugins.channel;935
elements.checkPluginCatalogButton.click();936
});937
elements.checkPluginCatalogButton.addEventListener("click", async () => {938
setBusy(elements.checkPluginCatalogButton, true, t("plugins.checking"));939
try { state.pluginState = await api.checkPluginCatalog(); state.plugins = state.pluginState.installed; renderPlugins(); }940
catch (error) { window.alert(errorText(error)); }941
finally { setBusy(elements.checkPluginCatalogButton, false, t("plugins.checkCatalog")); }942
});943
elements.settingsForm.addEventListener("submit", async (event) => {944
event.preventDefault();945
state.config = await api.updateConfig({946
ui: { language: elements.languageSelect.value },947
updates: { channel: elements.channelSelect.value, autoCheck: elements.autoCheckInput.checked },948
plugins: { channel: elements.pluginChannelSelect.value }949
});950
elements.updateViewChannelSelect.value = state.config.updates.channel;951
elements.pluginViewChannelSelect.value = state.config.plugins.channel;952
applyLanguage(state.config.ui.language);953
elements.updateChannel.textContent = t("updates.channel", { channel: state.config.updates.channel });954
elements.settingsStatus.textContent = t("settings.saved"); setTimeout(() => { elements.settingsStatus.textContent = ""; }, 1800);955
});956
elements.languageSelect.addEventListener("change", () => applyLanguage(elements.languageSelect.value));957
document.querySelectorAll("[data-legal-document]").forEach((button) => {958
button.addEventListener("click", async () => {959
try { await api.openLegalDocument(button.dataset.legalDocument); }960
catch (error) { window.alert(errorText(error)); }961
});962
});963
elements.vaultLanguageSelect.addEventListener("change", async () => {964
const language = applyLanguage(elements.vaultLanguageSelect.value);965
state.config = await api.updateConfig({ ui: { language } });966
});968
api?.onUpdateState((payload) => renderUpdate(payload));969
api?.onPluginWindowState((windows) => renderPluginTaskbar(windows));970
api?.onSshData((payload) => { if (payload.sessionId === TERMINAL_SESSION_ID) terminal?.write(payload.data); });971
api?.onSshState((payload) => {972
if (payload.sessionId !== TERMINAL_SESSION_ID) return;973
state.terminalConnected = payload.state === "connected";974
state.terminalLatency = payload.latency;975
if (payload.state === "connecting") setTerminalState("connecting", t("terminal.connecting"));976
else if (payload.state === "connected") setTerminalState("connected", t("terminal.connected"));977
else setTerminalState("disconnected", t("terminal.disconnected"));978
});979
api?.onSshError((payload) => { if (payload.sessionId === TERMINAL_SESSION_ID) terminal?.writeln(`\r\n\x1b[31m${errorText(payload)}\x1b[0m`); });980
api?.onVaultLocked(status => {981
configureVault(status); clearProtectedUi(); void refreshBiometrics().then(maybeAutoUnlock);982
terminal?.writeln(`${t("terminal.vaultLocked")}\r\n`);983
});985
initialize().catch((error) => {986
elements.runtimeText.textContent = t("errors.initialization");987
elements.updateMessage.textContent = errorText(error);988
});SHA-256
6cbb1d3dacb105098d6fb7523f3efcd9e3fa9c5698f9b1c57d41af5700ced878CH-J Proprietary Software License 1.14 · सोर्स CH-J Proprietary Software License 1.14 के तहत उपलब्ध कराया जाता है। इसकी उपलब्धता लाइसेंस की शर्तें नहीं बदलती और न ही अतिरिक्त अधिकार देती है।
आर्काइव SHA-256
a9605c0870a223b6a8542bb0705edd51d8b04f3069582653417a8397fabcc09a