CH-J Server Managerspráva serverů přes SSH
Menu
Vydané zdroje

CH-J Server Manager

Procházejte adresáře a soubory konkrétního vydání aplikace.

Stáhnout zdroje ZIP
CH-J / Server Manager 368 souborů
core-20261017T201717Z-057348c4a70f Přidáno: Datum není evidováno · Sestaveno:
pluginRuntime.js Přidáno: Datum není evidováno 17.3 KB · 301 řádků
Kód Stáhnout soubor
1"use strict";
3const fs = require("node:fs");
4const path = require("node:path");
5const { windowChromeOptions } = require("../bootstrap/windowChrome");
7const MIME_TYPES = Object.freeze({
8 ".css": "text/css; charset=utf-8",
9 ".gif": "image/gif",
10 ".html": "text/html; charset=utf-8",
11 ".jpeg": "image/jpeg",
12 ".jpg": "image/jpeg",
13 ".js": "text/javascript; charset=utf-8",
14 ".json": "application/json; charset=utf-8",
15 ".png": "image/png",
16 ".svg": "image/svg+xml",
17 ".webp": "image/webp",
18 ".woff": "font/woff",
19 ".woff2": "font/woff2",
20 ".ttf": "font/ttf"
21});
22const PLUGIN_CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; worker-src 'self'; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'";
24class PluginRuntime {
25 constructor(options) {
26 this.BrowserWindow = options.BrowserWindow;
27 this.registry = options.registry;
28 this.sessionManager = options.sessionManager;
29 this.keyGeneratorService = options.keyGeneratorService;
30 this.logService = options.logService;
31 this.remoteFileService = options.remoteFileService;
32 this.localHashService = options.localHashService;
33 this.userAdmin = options.userAdmin;
34 this.virtualMemory = options.virtualMemory;
35 this.getLanguage = options.getLanguage || (() => "en");
36 this.getMainWindow = options.getMainWindow;
37 this.isVaultUnlocked = options.isVaultUnlocked;
38 this.preload = options.preload;
39 this.icon = options.icon;
40 this.onWindowState = options.onWindowState;
41 this.logger = options.logger;
42 this.contexts = new Map();
43 this.windows = new Map();
44 this.localHashService?.on("progress", ({ pluginId, job }) => {
45 const window = this.windows.get(pluginId);
46 if (window && !window.isDestroyed()) window.webContents.send("plugin:hashing:progress", job);
47 });
48 }
50 registerIpc(ipcMain) {
51 const handle = (channel, permission, action) => {
52 ipcMain.handle(channel, async (event, payload = {}) => {
53 const context = this._context(event.sender.id);
54 if (permission && !context.manifest.permissions.includes(permission)) {
55 const error = new Error(`Plugin permission denied: ${permission}`);
56 error.code = "PLUGIN_PERMISSION_DENIED";
57 throw error;
58 }
59 try {
60 return await action(context, payload);
61 } catch (error) {
62 // Electron serializes the message, but drops custom error properties.
63 const exposeCode = error?.code?.startsWith("HASH_") || ((channel.startsWith("plugin:users:") || channel.startsWith("plugin:system:")) && /^[A-Z][A-Z0-9_]{2,63}$/.test(String(error?.code || "")));
64 if (exposeCode && !error.message.startsWith(`${error.code}:`)) error.message = `${error.code}: ${error.message}`;
65 throw error;
66 }
67 });
68 };
69 handle("plugin:getInfo", null, (context) => context.manifest);
70 handle("plugin:ui:getLanguage", null, () => this.getLanguage());
71 handle("plugin:close", null, (context) => { context.window.close(); return { ok: true }; });
72 handle("plugin:window:minimize", null, (context) => { this._minimize(context); return { ok: true }; });
73 handle("plugin:sessions:list", "session.read", () => this.sessionManager.list());
74 handle("plugin:system:metrics", "system.metrics.read", (_context, payload) => this.sessionManager.readSystemMetrics(payload.sessionId));
75 handle("plugin:system:virtualMemory", "system.metrics.read", (_context, payload) => this.virtualMemory.read(payload.sessionId, { sudoPassword: payload.sudoPassword, privileged: payload.privileged === true }));
76 handle("plugin:system:manageVirtualMemory", "system.memory.manage", (_context, payload) => this.virtualMemory.manage(payload.sessionId, payload));
77 handle("plugin:keys:generate", "keys.generate", (_context, payload) => this.keyGeneratorService.generate(payload));
78 handle("plugin:keys:save", "keys.generate", (_context, payload) => this.keyGeneratorService.save(payload.generationId));
79 handle("plugin:logs:read", "logs.read", (_context, payload) => this.logService.readTail(payload));
80 handle("plugin:users:list", "users.read", (_context, payload) => this.userAdmin.list(payload.sessionId));
81 handle("plugin:users:privileges", "users.read", (_context, payload) => this.userAdmin.privileges(payload.sessionId, { refresh: payload.refresh === true }));
82 handle("plugin:users:inventory", "users.read", (_context, payload) => this.userAdmin.inventory(payload.sessionId, payload));
83 handle("plugin:users:detail", "users.read", (_context, payload) => this.userAdmin.detail(payload.sessionId, payload));
84 handle("plugin:users:manage", "users.manage", (_context, payload) => this.userAdmin.manage(payload.sessionId, payload));
85 handle("plugin:users:keys", "users.manage", (_context, payload) => this.userAdmin.keys(payload.sessionId, payload));
86 handle("plugin:users:sshPolicy", "users.manage", (_context, payload) => this.userAdmin.sshPolicy(payload.sessionId, payload));
87 handle("plugin:nginx:inspect", "nginx.read", (_context, payload) => this.sessionManager.inspectNginx(payload.sessionId));
88 handle("plugin:nginx:readConfig", "nginx.read", (_context, payload) => this.sessionManager.readNginxConfig(payload.sessionId, payload));
89 handle("plugin:nginx:dumpConfig", "nginx.read", (_context, payload) => this.sessionManager.dumpNginxConfig(payload.sessionId, payload));
90 handle("plugin:nginx:testConfig", "nginx.read", (_context, payload) => this.sessionManager.testNginxConfig(payload.sessionId, payload));
91 handle("plugin:nginx:saveConfig", "nginx.manage", (_context, payload) => this.sessionManager.saveNginxConfig(payload.sessionId, payload));
92 handle("plugin:nginx:reload", "nginx.manage", (_context, payload) => this.sessionManager.reloadNginx(payload.sessionId, payload));
93 handle("plugin:files:list", "files.read", (_context, payload) => this.remoteFileService.list(payload.sessionId, payload.path));
94 handle("plugin:files:readText", "files.read", (context, payload) => this.remoteFileService.readText(payload.sessionId, payload.path, payload.options || {}, context.manifest.id));
95 handle("plugin:files:writeText", "files.write", (context, payload) => this.remoteFileService.writeText(payload.sessionId, payload.path, payload.text, payload.options || {}, context.manifest.id));
96 handle("plugin:files:saveText", "files.write", (context, payload) => this.remoteFileService.saveText(payload.sessionId, payload.path, payload.text, payload.options || {}, context.manifest.id));
97 handle("plugin:files:listRecovery", "files.read", (_context, payload) => this.remoteFileService.listRecovery(payload.sessionId, payload.options || {}));
98 handle("plugin:files:readRecovery", "files.read", (_context, payload) => this.remoteFileService.readRecovery(payload.sessionId, payload.recoveryId, payload.options || {}));
99 handle("plugin:files:cleanupRecovery", "files.write", (_context, payload) => this.remoteFileService.cleanupRecovery(payload.sessionId, payload.recoveryId, payload.options || {}));
100 handle("plugin:files:closeText", "files.read", (context, payload) => this.remoteFileService.closeText(payload.editId, context.manifest.id));
101 handle("plugin:files:createFile", "files.write", (_context, payload) => this.remoteFileService.createFile(payload.sessionId, payload.path));
102 handle("plugin:files:mkdir", "files.write", (_context, payload) => this.remoteFileService.mkdir(payload.sessionId, payload.path));
103 handle("plugin:files:rename", "files.write", (_context, payload) => this.remoteFileService.rename(payload.sessionId, payload.from, payload.to));
104 handle("plugin:files:remove", "files.write", (_context, payload) => this.remoteFileService.remove(payload.sessionId, payload.path));
105 handle("plugin:files:removeMany", "files.write", (_context, payload) => this.remoteFileService.removeMany(payload.sessionId, payload.paths, payload.recursive));
106 handle("plugin:files:upload", "files.transfer", (_context, payload) => this.remoteFileService.upload(payload.sessionId, payload.directory));
107 handle("plugin:files:download", "files.transfer", (_context, payload) => this.remoteFileService.download(payload.sessionId, payload.path));
108 handle("plugin:files:downloadMany", "files.transfer", (_context, payload) => this.remoteFileService.downloadMany(payload.sessionId, payload.paths));
109 handle("plugin:files:downloadArchive", "files.transfer", (_context, payload) => this.remoteFileService.downloadArchive(payload.sessionId, payload.paths, payload.format));
110 handle("plugin:hashing:algorithms", "local.hash", () => this.localHashService.getAlgorithms());
111 handle("plugin:hashing:selectFiles", "local.hash", (context, payload) => this.localHashService.selectFiles(context.manifest.id, payload));
112 handle("plugin:hashing:selectDirectory", "local.hash", (context) => this.localHashService.selectDirectory(context.manifest.id));
113 handle("plugin:hashing:selectManifest", "local.hash", (context) => this.localHashService.selectManifest(context.manifest.id));
114 handle("plugin:hashing:selectManifestDestination", "local.hash", (context, payload) => this.localHashService.selectManifestDestination(context.manifest.id, payload));
115 handle("plugin:hashing:start", "local.hash", (context, payload) => this.localHashService.start(context.manifest.id, payload));
116 handle("plugin:hashing:verify", "local.hash", (context, payload) => this.localHashService.verify(context.manifest.id, payload));
117 handle("plugin:hashing:compare", "local.hash", (context, payload) => this.localHashService.compare(context.manifest.id, payload));
118 handle("plugin:hashing:generateManifest", "local.hash", (context, payload) => this.localHashService.generateManifest(context.manifest.id, payload));
119 handle("plugin:hashing:verifyManifest", "local.hash", (context, payload) => this.localHashService.verifyManifest(context.manifest.id, payload));
120 handle("plugin:hashing:exportResults", "local.hash", (context, payload) => this.localHashService.exportResults(context.manifest.id, payload));
121 handle("plugin:hashing:copyResult", "local.hash", (context, payload) => this.localHashService.copyResult(context.manifest.id, payload));
122 handle("plugin:hashing:status", "local.hash", (context, payload) => this.localHashService.status(context.manifest.id, payload.jobId));
123 handle("plugin:hashing:cancel", "local.hash", (context, payload) => this.localHashService.cancel(context.manifest.id, payload.jobId));
124 }
126 notifyLanguageChanged(language) {
127 for (const window of this.windows.values()) {
128 if (!window.isDestroyed()) window.webContents.send("plugin:ui:languageChanged", language);
129 }
130 }
132 async handleRequest(request) {
133 try {
134 const url = new URL(request.url);
135 const pluginId = url.hostname;
136 const resolved = this.registry.resolveEntry(pluginId);
137 const requested = decodeURIComponent(url.pathname.replace(/^\/+/, "") || resolved.manifest.entry).replace(/\\/g, "/");
138 if (!requested || requested.startsWith(".") || requested.split("/").some((segment) => !segment || segment === ".." || segment.startsWith("."))) {
139 return new Response("Not found", { status: 404 });
140 }
141 const isChrome = requested === "__chj_core__/window-chrome.css";
142 const root = isChrome ? path.join(__dirname, "..", "bootstrap") : resolved.root;
143 const filePath = isChrome ? path.join(root, "pluginWindowChrome.css") : path.join(root, ...requested.split("/"));
144 const relative = path.relative(root, filePath);
145 if (relative.startsWith("..") || path.isAbsolute(relative)) return new Response("Not found", { status: 404 });
146 const stat = await fs.promises.stat(filePath);
147 if (!stat.isFile() || stat.size > 10 * 1024 * 1024) return new Response("Not found", { status: 404 });
148 const data = await fs.promises.readFile(filePath);
149 return new Response(data, {
150 status: 200,
151 headers: {
152 "Content-Type": MIME_TYPES[path.extname(filePath).toLowerCase()] || "application/octet-stream",
153 "Content-Security-Policy": PLUGIN_CSP,
154 "Cache-Control": "no-store",
155 "X-Content-Type-Options": "nosniff"
156 }
157 });
158 } catch (error) {
159 this.logger?.warn("Plugin resource request rejected.", { url: request.url, message: error?.message || String(error) });
160 return new Response("Not found", { status: 404 });
161 }
162 }
164 open(pluginId) {
165 if (!this.isVaultUnlocked()) throw new Error("Unlock the vault before opening a plugin.");
166 const resolved = this.registry.resolveEntry(pluginId);
167 const existing = this.windows.get(resolved.manifest.id);
168 if (existing && !existing.isDestroyed()) {
169 if (existing.isMinimized()) existing.restore();
170 const context = this.contexts.get(existing.webContents.id);
171 if (context) context.minimized = false;
172 existing.show();
173 existing.focus();
174 this._emitWindowState();
175 return resolved.manifest;
176 }
177 const manager = this.getMainWindow?.();
178 const window = new this.BrowserWindow({
179 title: `${resolved.manifest.name} · CH-J Server Manager`,
180 width: 980,
181 height: 700,
182 minWidth: 760,
183 minHeight: 520,
184 backgroundColor: "#07111f",
185 icon: this.icon,
186 show: false,
187 parent: manager && !manager.isDestroyed() ? manager : undefined,
188 modal: false,
189 ...windowChromeOptions(),
190 webPreferences: {
191 preload: this.preload,
192 contextIsolation: true,
193 nodeIntegration: false,
194 sandbox: true,
195 webSecurity: true,
196 allowRunningInsecureContent: false,
197 spellcheck: false,
198 partition: `plugin-${resolved.manifest.id}`
199 }
200 });
201 const pluginSession = window.webContents.session;
202 if (!pluginSession.protocol.isProtocolHandled("chj-plugin")) {
203 pluginSession.protocol.handle("chj-plugin", (request) => this.handleRequest(request));
204 }
205 pluginSession.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false));
206 pluginSession.setPermissionCheckHandler(() => false);
207 window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
208 window.webContents.on("will-navigate", (event, url) => {
209 if (!url.startsWith(`chj-plugin://${resolved.manifest.id}/`)) event.preventDefault();
210 });
211 const context = { manifest: resolved.manifest, window, minimized: false };
212 const webContentsId = window.webContents.id;
213 this.contexts.set(webContentsId, context);
214 this.windows.set(resolved.manifest.id, window);
215 window.once("ready-to-show", () => {
216 if (window.isDestroyed() || context.minimized) return;
217 window.show();
218 window.focus();
219 this._emitWindowState();
220 });
221 window.on("minimize", () => this._minimize(context, { focusManager: !manager?.isMinimized() }));
222 const onManagerMinimize = () => this._minimize(context, { focusManager: false });
223 manager?.on("minimize", onManagerMinimize);
224 window.on("closed", () => {
225 manager?.removeListener("minimize", onManagerMinimize);
226 this.localHashService?.cleanupPlugin(resolved.manifest.id);
227 this.remoteFileService?.cleanupPlugin?.(resolved.manifest.id);
228 this.contexts.delete(webContentsId);
229 this.windows.delete(resolved.manifest.id);
230 this._emitWindowState();
231 });
232 const pluginUrl = `chj-plugin://${resolved.manifest.id}/${resolved.manifest.entry}`;
233 void window.loadURL(pluginUrl).catch((error) => {
234 this.logger?.error("Plugin window failed to load.", {
235 pluginId: resolved.manifest.id,
236 url: pluginUrl,
237 message: error?.message || String(error)
238 });
239 });
240 this.logger?.info("Plugin window opened.", { pluginId: resolved.manifest.id, version: resolved.manifest.version });
241 return resolved.manifest;
242 }
244 closeAll() {
245 for (const window of this.windows.values()) {
246 if (!window.isDestroyed()) window.close();
247 }
248 }
250 _minimize(context, { focusManager = true } = {}) {
251 if (context.window.isDestroyed()) return;
252 context.minimized = true;
253 context.window.hide();
254 const manager = this.getMainWindow?.();
255 if (focusManager && manager && !manager.isDestroyed()) {
256 if (manager.isMinimized()) manager.restore();
257 manager.show();
258 manager.focus();
259 }
260 this._emitWindowState();
261 this.logger?.info("Plugin window minimized to the Core taskbar.", { pluginId: context.manifest.id });
262 }
264 close(pluginId) {
265 const window = this.windows.get(String(pluginId || ""));
266 if (window && !window.isDestroyed()) window.close();
267 }
269 listWindows() {
270 const result = [];
271 for (const [pluginId, window] of this.windows) {
272 if (window.isDestroyed()) continue;
273 const context = this.contexts.get(window.webContents.id);
274 if (!context) continue;
275 result.push({
276 pluginId,
277 name: context.manifest.name,
278 version: context.manifest.version,
279 minimized: context.minimized === true
280 });
281 }
282 return result;
283 }
285 _emitWindowState() {
286 try { this.onWindowState?.(this.listWindows()); }
287 catch (error) { this.logger?.warn("Plugin window state could not be delivered.", { message: error?.message || String(error) }); }
288 }
290 _context(webContentsId) {
291 const context = this.contexts.get(webContentsId);
292 if (!context || context.window.isDestroyed()) {
293 const error = new Error("Untrusted plugin IPC sender.");
294 error.code = "UNTRUSTED_PLUGIN_SENDER";
295 throw error;
296 }
297 return context;
298 }
301module.exports = { MIME_TYPES, PLUGIN_CSP, PluginRuntime };
SHA-2566b0165fa9fc0240b93ce30bdde31e8ad824e3eb52898503332f802c0533e640d

CH-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 archivucf4455b698f0f28e456a37b1834976a0194d8486acb7101052d59a838745cca3
Soubory