Files
ProxmoxVE-Local/server.js
CanbiZ (MickLesk) d2e8ac91d1 v1.0.0: Major UI/UX Overhaul, Performance & New Features (#566)
* Add GeneratorTab and UI refactor/styles

Introduce a full-featured GeneratorTab component for building and exporting script configuration (script selector, CPU/RAM/Disk sliders, advanced networking/features, generate/copy/export/import, and execute). Apply visual and structural UI refactors: new glass-card styles across ScriptCard, ScriptCardList, ScriptDetailModal, Terminal and Footer; update button variants and interaction classes; add Heart icon and extra footer links; update layout to use Manrope + JetBrains Mono fonts, sticky navbar, ambient backgrounds and metadata tweaks. Wire GeneratorTab into the main page and add related icon imports. Misc: small code-style/formatting adjustments and improved deriveScriptPath / handler signatures for clarity.

* Add script notes, server presets & APT proxy

Add persistent script notes and server presets, plus APT proxy settings and various UI/behavior improvements.

- DB: new migration adds script_notes and server_presets tables and indexes; Prisma schema updated with ScriptNote and ServerPreset models.
- Notes: new client component ScriptNotesPanel with CRUD using a new TRPC router (scriptNotes) and integration into ScriptDetailModal to show/manage private/shared notes.
- APT proxy: new Next.js API route /api/settings/apt-proxy that reads/writes .env vars; GeneralSettingsModal and ConfigurationModal load/save the proxy and pre-fill advanced install vars.
- UX/UI: add copyable install command, version badges on script cards/detail, container ID input in advanced configuration, and styling tweaks (glass-card-static).
- Server/script detection: installedScripts router now attempts to resolve the actual Proxmox node name via SSH and relaxes ID parsing to numeric-only.
- Notifications: appriseService extended to support Gotify endpoints and allow gotify:// scheme, and URL validation adjusted accordingly.

These changes enable user-maintained notes/presets, persistent APT-cacher defaults, improved install UX, better server detection, and additional notification backend support.

* Add server presets and silent batch updates

Introduce server presets and silent batch update support across API, server, and UI. Added a new serverPresets TRPC router and wired it into the API root. ConfigurationModal now lets users save/load/delete presets tied to a server. InstalledScriptsTab adds a "Silent update" option, a sequential "Update All Containers" batch flow that runs updates with PHS_SILENT=1, and passes envVars into update executions. ScriptExecutionHandler (server.js) now accepts envVars for updates and injects export commands into both local and SSH update flows so environment flags (e.g. PHS_SILENT) are honored. Also added "updated" sort handling in ScriptsGrid, DownloadedScriptsTab and FilterBar, and small typing fixes in appriseService.

* Use per-router Prisma client with Better SQLite3

Replace usage of the shared prisma import with per-router PrismaClient instances configured with @prisma/adapter-better-sqlite3. Add getNotesDb/getPresetsDb helpers (with DATABASE_URL fallback) and update scriptNotes and serverPresets to use the new client. Also add error handling in read endpoints to return empty arrays on DB failures and ensure create/update/delete use the new client.

* Icon-only action buttons; use presets DB

Convert HelpButton, ResyncButton, ServerSettingsButton and SettingsButton from labeled outline controls to compact ghost icon-only buttons with aria-labels and smaller icons/spinners for a more compact header UI. Simplify ResyncButton markup (smaller spinner/SVG, removed extra contextual text/lastSync layout) and tweak sync message styling. Add Server icon import in ServerSettingsButton. In serverPresets router, replace direct prisma calls with getPresetsDb() and use the returned db instance for all queries and mutations to support the presets DB connection.

* Add quick filters, Dev/ARM badges, and CSS tweaks

Introduce quick filter support and visual indicators for developer/ARM scripts. Added QuickFilter type and quickFilter to FilterState (getDefaultFilters/mergeFiltersWithDefaults) and a quick-filter UI in FilterBar (All, New, Updated, In Dev, ARM). Implemented filtering logic in ScriptsGrid and added category dev counts to surface per-category "dev" counts in CategorySidebar. Added DevBadge and ArmBadge components, used in ScriptCard and ScriptDetailModal; ScriptCard also gets a subtle violet highlight when script.is_dev is true. Fixed script path generation in GeneratorTab to include a `scripts/` prefix. Minor dark-theme adjustments to .glass-card/.glass-card-static background and border-color for improved contrast.

* Add appearance settings and persist UI prefs

Introduce an Appearance tab in the Settings modal to control theme, text size and layout width (default vs wide). Preferences are saved to localStorage and applied immediately via helper functions (applyTextSize/applyLayoutWidth) and a small inline script injected into <head> to apply saved settings on first paint. Add CSS utility classes for text-size variants and wire up theme buttons (using lucide icons). Also include minor cleanup: optional chaining fix in CategorySidebar and removal of an unused import in ResyncButton.

* Normalize quotes and format components

Apply consistent formatting across several components: convert single quotes to double quotes, reformat the QuickFilter union type and quick-filters array in FilterBar, adjust JSX prop and className string formatting in HelpButton, ScriptCard, ServerSettingsButton, and SettingsButton. These are cosmetic/formatting changes only and do not alter runtime behavior.

* Refactor Badge & CategorySidebar types/styles

Normalize formatting and strengthen typings for Badge; convert single quotes to double, expand variant/type unions, and tidy JSX/props and helper badge components. Rework CategorySidebar: refactor CategoryIcon SVGs for readability, standardize className usage, improve collapsed-state layout and buttons, and ensure categories are filtered/sorted by count with correct icon mapping and counts display. Overall cleanup improves consistency, readability, and type safety across these components.

* Add modal stacking and portal support

Introduce a modal stacking system and portal to ensure modals escape parent stacking contexts. ModalStackProvider now computes a zIndex for each registered modal and returns an unregister handle; useRegisterModal returns the zIndex. A ModalPortal component (createPortal to document.body) was added and all modal components were updated to: capture the returned zIndex, wrap their markup in <ModalPortal>, and apply the dynamic zIndex instead of a hardcoded z-50 class. This improves correct layering of multiple modals and avoids backdrop-filter / transform stacking issues.

* Wrap modals in portal and use zIndex

Use ModalPortal and zIndex values from useRegisterModal across modal components to avoid hardcoded z-50 stacking. Updated ExecutionModeModal, LXCSettingsModal, PublicKeyModal, ReleaseNotesModal, SetupModal, StorageSelectionModal, and TextViewer to import ModalPortal, capture the zIndex returned by useRegisterModal, wrap modal markup in <ModalPortal>, and apply style={{ zIndex }} to backdrops; LXC result overlay uses zIndex + 10 for proper stacking. Also changed LoadingOverlay in VersionDisplay to render with createPortal(document.body) and added the import. These changes centralize stacking behavior and prevent z-index conflicts when multiple modals/overlays are present.

* Use categoryIconColorMap for sidebar icons

Update CategorySidebar.tsx to derive non-selected icon color classes from categoryIconColorMap for both the "template" and per-category icons. Selected icons still use text-primary; fallbacks preserve previous muted and group-hover classes to retain existing styling when a mapping is absent.

* Standardize modal layout and form styles

Refactor modal markup across many components to use a consistent wrapper structure and unified Tailwind utility ordering (moved zIndex to outer container, standardized backdrop and centering). Clean up form layouts: align icons, labels and inputs, normalize spacing, error styling, and button variants (including icon/ghost adjustments). Improve AuthModal and CloneCountInputModal UX (loading/error states, closer placement, validation), and normalize BackupWarningModal and other modal presentations. Update ConfigurationModal advanced UI: reorganize network fields and add/handle extra options (IPv6 static, gateway, MTU, MAC, VLAN, DNS), refine presets save/cancel flow, and apply general formatting/whitespace cleanups.

* Escape env var values; update favicons & logo

Fix shell escaping when building env export commands by escaping backslashes and quotes (prevents broken exported values) in ScriptExecutionHandler (two locations). Update app metadata to point to favicon files under /favicon, add site manifest, and replace the header Package icon with a next/image using the android-chrome PNG (import Image and adjust markup) for consistent asset handling.

* Add favicon set and logo; remove old favicon

Replace legacy root favicon.png with a full favicon set under public/favicon (android-chrome 192/512, apple-touch-icon, favicon-16x16, favicon-32x32, favicon.ico, favicon.png) and add site.webmanifest. Also add public/logo.png. This organizes favicon assets for multiple platforms and adds a webmanifest for PWA/icon declarations.

* Portalize script dropdown and add outside click

Render the script selector dropdown into document.body via createPortal to escape stacking/overflow contexts. Add triggerRef/dropdownRef, compute fixed position from the trigger on open, and attach an outside-click handler to close the dropdown. Also import useRef/useEffect and createPortal; preserve existing search, selection, and reset behaviors while adjusting z-index/positioning.

* Update favicon and logo assets

Replace favicon and logo image files with updated versions to refresh branding. Updated files: public/favicon/android-chrome-192x192.png, public/favicon/android-chrome-512x512.png, public/favicon/apple-touch-icon.png, public/favicon/favicon-16x16.png, public/favicon/favicon-32x32.png, public/favicon/favicon.ico, public/logo.png.

* Add appearance modal & improve script detail UI

Add an AppearanceModal and AppearanceButton to let users change theme, text size and layout width (persisted in localStorage). Enhance FilterBar with category filtering (selectedCategory, dropdown UI, counts, and outside-click handling). Heavily refactor ScriptDetailModal: layout and visual refresh, new icons, better loading/update/delete/install flows, memoized install command, improved copy behavior, keyboard navigation between scripts (using orderedSlugs + onSelectSlug), clearer status/messages, and various performance/UX tweaks. Wire DownloadedScriptsTab to pass orderedSlugs and onSelectSlug into the ScriptDetailModal. Overall small UI/UX and state-management improvements across components.

* Optimize rendering, lazy-load tabs, add sync modal

Performance and UX improvements: memoize computed values in InstalledScriptsTab (scriptsWithStatus, filteredScripts, uniqueServers) and use useCallback/useMemo in ScriptsGrid to avoid unnecessary re-renders. Memoize ScriptCard and ScriptCardList components and tighten their ScriptCard type alias. Introduce a new SyncModal (ResyncButton) component to run/resync scripts with a progress UI and retry/close behavior, and replace the previous ResyncButton import in page.tsx. Lazy-load heavy tab components (Downloaded, Installed, Backups, Generator) with next/dynamic and add a TabSkeleton loader; consolidate tab definitions into a memoized tabs array. Misc: small prop/prop-name fixes and minor JSX formatting adjustments.

* Add Arcane script, status UI, validation & cache

Multiple changes improving UX, reliability, and CI permissions:

- Add scripts/tools/addon/arcane.sh: installer/update/uninstall helper for Arcane (Docker Compose), creates update helper and generates secrets.
- Add ServerStatusIndicator component and integrate into header (src/app/_components/ServerStatusIndicator.tsx, src/app/page.tsx); adjust hero/layout to accommodate inline version + status.
- Enhance GeneratorTab (src/app/_components/GeneratorTab.tsx): fetch full script details by slug, derive and apply default resource values from install_methods, and show an App Defaults info panel.
- Harden repo provider detection (src/server/lib/repositoryUrlValidation.js/.ts): use URL parsing for hostname matching with safe fallback to 'custom'.
- Tune client caching (src/trpc/query-client.ts): increase staleTime to 30min, set gcTime to 1h, and disable automatic refetches on mount/window focus/reconnect.
- Update GitHub Actions permissions: node.js.yml grants contents: read; release-drafter.yml grants contents: write and pull-requests: read.

These changes aim to provide better default resource handling for scripts, visible server reachability, more robust URL parsing, improved client-side cache behavior, and explicit workflow permissions.

* Add suppressHydrationWarning to <html>

Add the React prop suppressHydrationWarning to the <html> element in RootLayout (src/app/layout.tsx) to suppress hydration mismatch warnings. This helps avoid noisy console warnings when server-rendered markup and client rendering differ (e.g., due to dynamic font class injection or other runtime-only differences).

* Refactor GeneratorTab layout and add SSH imports

Rework GeneratorTab rendering and small UI/format fixes: tidy the scriptDetail useMemo formatting and restructure the Script Defaults block so defaults (CPU, RAM, HDD) are always shown and OS/version/variant badges render correctly. Minor formatting change to ServerStatusIndicator's fetch call and a small spacing fix on the home page title. Also add imports for getSSHService and the Server type to servers router in preparation for SSH-related functionality.

* Add explicit typing for servers in indicator

Annotate the `servers` variable with an explicit array type (id, name, ip, online) and cast `data?.servers` to that type, defaulting to an empty array. This clarifies TypeScript inference and prevents `servers` from being undefined for downstream logic without changing runtime behavior.

* perf/cleanup: audit fixes - hoist iconMap, pin Next.js, strip console.log, lighten glass-card, fix dev badge

* Refactor icons, remove debug logs, pin Next

Replace the large inline SVG icon map with a compact iconPaths mapping and fallback path, simplifying CategoryIcon rendering. Tighten the dev-count badge markup/styles for better layout. Remove leftover console.debug/log statements from InstalledScriptsTab and LXCSettingsModal. Pin Next.js version to 16.2.1 in package.json (deps and devDeps). Slightly adjust dark glass-card background opacity/hover values in globals.css.

* refactor: migrate server TS files to structured logger, accessibility improvements

* perf: fix 14s page load - remove SSH from initial query, defer tab-specific data

- getAllInstalledScripts: removed SSH batchDetectContainerTypes, use DB-only
  heuristic (lxc_config presence) for VM/LXC detection
- Defer installedScripts + backups queries until their tab is activated
- Initial batch now only fires 3 fast DB queries instead of 7 (incl. SSH)

* perf: split SSH queries from tRPC batch, skip save-on-mount

- Use splitLink to route servers.checkServersStatus through a separate
  non-batched httpLink. SSH queries no longer block fast DB queries from
  returning (was causing 14s+ batch response holding all data hostage).
- Add initialization refs in ScriptsGrid and DownloadedScriptsTab so
  save-filter/view-mode POST effects skip their first fire after load,
  eliminating 2-4 unnecessary network requests per tab mount.

* refactor: restore SSH detection for installed scripts, cache badge counts

- Restore batchDetectContainerTypes SSH calls in getAllInstalledScripts
  (shows real VM/LXC state, not just DB heuristic)
- Route getAllInstalledScripts through splitLink (non-batched) so SSH
  never blocks fast DB queries
- Cache installed/backups badge counts in localStorage so tabs show
  last-known counts instantly, updated when fresh data arrives
- Query still deferred until tab is visited (no eager SSH on page load)

* Refactor init checks, footer, and parallel fetch

Make several small refactors and updates across the app:

- Expand single-line early-return checks into multi-line blocks in DownloadedScriptsTab and ScriptsGrid for clarity when skipping initial effect triggers.
- Update Footer links: add separate GitHub (ProxmoxVE-Local) and GitHub (ProxmoxVE) buttons and change the site link to community-scripts.org.
- Minor formatting tweaks in page.tsx (useState initializer and backups ternary) for readability.
- In the scripts API router, fetch script cards and metadata in parallel via Promise.all to reduce latency and return both together.

These changes improve readability and slightly optimize the scripts fetch path.

* Add in-memory PB cache and invalidate on resync

Introduce a simple server-side in-memory cache for PocketBase data with a 10-minute TTL to reduce PB requests for rarely-changing data. Adds getCached/setCache helpers and a shared _cache store, and exports invalidatePbCache() to clear cached entries. Apply caching to getScriptCards, getCategories, and getScriptTypes, and call invalidatePbCache() in the resyncScripts mutation so fresh data is fetched after a resync.

* Update react.tsx

* Show script download flow & per-node server status

GeneratorTab: add detection of locally downloaded scripts (query + mutation), compute a slug set for O(1) lookup, and gate selection/execution on download state. Update script list UI to indicate downloadable items, grayscale/opacity non-downloaded entries, and show a download confirmation modal that triggers loadScript mutation and invalidates cache. Add Loader2 and AlertTriangle icons and disable Execute when the selected script isn't downloaded.

ServerStatusIndicator: change from a single aggregate dot to per-node indicators showing each host name and status (green online with ping animation, red offline). Improve handling of loading vs no-configured-servers states and update tooltip/title text for clarity.

* Improve updater script and minor UI tweaks

Refactor update.sh to make the updater more robust and flexible: add support for specifying a target release (get_release), include tar in dependency checks, strengthen download/extract logic and error logging, improve source-dir detection, and tighten backup/restore, install/build and service start/rollback flows. Also normalize indentation and logging output and add clearer diagnostic messages on failures. Minor UI cleanups in TSX: simplify GeneratorTab conditional formatting and adjust ServerStatusIndicator class ordering.

* Bump deps and add VSCode Next.js prompt setting

Update multiple dependencies to newer patch/minor versions (Prisma, @tanstack/react-query, axios, better-sqlite3, dotenv, lucide-react, next, react, react-dom, vite, vitest tooling, eslint, jsdom, postcss, prettier, prisma, etc.). Replace legacy typescript-eslint package with @typescript-eslint/eslint-plugin and @typescript-eslint/parser. Add .vscode/settings.json to mark WillLuke.nextjs.hasPrompted as true to suppress the Next.js prompt in VS Code.

* Normalize indentation in core scripts

Reformat scripts/core/alpine-install.func and scripts/core/api.func for consistent indentation and whitespace. Changes are formatting-only (no logic changes): converted leading tabs to spaces, aligned multiline blocks, and adjusted a comment reference (error-handler → error_handler) for consistency. Improves readability and maintainability without affecting behavior.

* Show/hide install command UI and service fixes

UI: Add a Terminal icon, show/hide toggle, and display block for the install command in ScriptDetailModal (new showCommand state and button).
Server: installedScripts - default unknown container types to LXC (safe default) and simplify VM/LXC detection comments.
AppriseService: support gotifys:// (HTTPS) and gotify:// formats, select protocol correctly, and update URL regex.
BackupService: include PBS namespace (--ns) when storage.namespace is configured so proxmox-backup-client commands include the namespace.
ScriptDownloader: add fallback to attempt downloading a ct/<slug>.sh when install_methods is empty for CT/LXC scripts, improve returned success/message semantics, better 404-aware error messaging, and check for fallback CT script presence when scanning downloaded files.
Other: add /examples to .gitignore and remove restore.log.
These changes improve robustness for missing install metadata, add HTTPS Gotify support, ensure PBS namespace usage, and improve UX for viewing install commands.

* Prefer local install scripts; add envVars & token

Allow using local copies of helper/install scripts during development and forward environment variables and a GitHub token through the UI and websocket layer.

Changes:
- scripts/core/alpine-install.func & scripts/core/install.func: try to load misc/tools.func from the local scripts directory before falling back to downloading from GitHub; improved error messaging on failure.
- scripts/core/build.func: resolve SCRIPT_DIR, prefer local alpine/install function files and export their contents to FUNCTIONS_FILE_PATH; fall back to remote download if local files are missing; use local install scripts for lxc-attach when available (fallback to remote). Adjusted dev MOTD path to source from /tmp.
- src/app/_components/ConfigurationModal.tsx: added a password input for var_github_token (passed as GITHUB_TOKEN to mitigate API rate limits).
- src/server/api/websocket/handler.ts: websocket handler now accepts an envVars object and forwards it into startScriptExecution so environment variables from the client can be supplied to script runs.

Overall this improves local development workflows and enables passing custom env vars and a GitHub token to scripts.

* Replace *_json with install_methods/notes

Adapt code to the updated PocketBase schema by renaming install_methods_json and notes_json to install_methods and notes across services and routers. Update parsing in pbScripts.ts, mappings in scripts.ts, autoSyncService.js, and localScripts.ts, and adjust scriptDownloader fallback comment/logic to reference the new field. Also add new PBScript metadata fields (github_data, deleted_message, disable_message, last_update_commit) so the PBScript type reflects the extended record shape.

* Add InstallCommandBlock and integrate installer UI

Introduce a full InstallCommandBlock React component (new file) that builds, previews, and copies install commands with support for GitHub/Gitea, Alpine/Advanced modes, ARM flag, resource presets, and dev gating. Integrate it into ScriptDetailModal: compute hasAlpine and installDefaults from script.install_methods, remove the old simple install command UI/handlers, and embed the new component for non-misc scripts. Update ScriptsGrid to allow aborting batch downloads, invalidate downloaded-scripts cache after downloads, and adjust orderedSlugs passed to the modal (prefer newest when no active filters). On the server, make ScriptDownloaderService resolve dev scripts to the ProxmoxVED repository (dev-specific repo path) while preserving explicit repository_url and default repo behavior.

* Fix envStr possibly undefined in InstallCommandBlock

* Redesign Install section: inline node picker, remove old modals, drop My Notes

* Remove bash command display, pass envVars to SSH, inline Terminal below Install

* Fix envVars: always pass mode to skip whiptail dialog; fix terminal clipping

* Remove dangerous source envVar, fix View button gating, clean dead onInstallScript prop chains

* Tidy JSX formatting and remove extra whitespace

Clean up minor JSX formatting and stray blank lines across components. Removed extra blank lines in DownloadedScriptsTab and ScriptsGrid modal props, reformatted the terminal container div in InstallCommandBlock for clearer attribute layout, and simplified conditional JSX in page.tsx to single-line renders. No functional changes intended—only stylistic/formatting adjustments to improve readability.

* refactor: comprehensive code quality improvements

- Move Terminal component into GeneratorTab (self-contained)
- Replace all alert()/confirm() with modal dialogs
- Type server prop as Server instead of any
- Fix deprecated onKeyPress -> onKeyDown
- Memoize stat counters + fix O(n^2) scriptCounts with Set lookups
- Remove dead hasActions function (always returned true)
- Decompose InstalledScriptsTab: extract Stats, Filters, StatusMessage
- Add buildServerFromScript helper (deduplicates 5 identical blocks)
- Fix eslint-disable blanket: targeted disables + void floating promises

* fix: resolve LXCSettingsModal rootfs_size TS error blocking build

- Type configData as Record<string,unknown> so TS union includes rootfs_size
- Include formatter fixes for extracted sub-components

* feat: bootstrap updater - self-updating update engine

Split update system into two files:
- update.sh: Thin bootstrap (~100 lines) that fetches the latest
  update-engine.sh from main branch before executing it
- update-engine.sh: Full update logic (moved from old update.sh)
- UPDATER_VERSION: Version tracker for the engine

How it works:
1. User runs 'bash update.sh' (unchanged workflow)
2. Bootstrap checks UPDATER_VERSION on main vs local
3. If different, downloads latest update-engine.sh from main
4. Hands off to update-engine.sh with all arguments

This ensures bugfixes to the update logic reach users automatically,
without requiring a manual intervention or a new app release.

* fix: widen terminal - collapse sidebar to single column when terminal active

- Add onTerminalChange callback to InstallCommandBlock
- ScriptDetailModal switches from 2-col grid to single column when terminal runs
- Sidebar (ACCESS/DETAILS/INSTALL PROFILES) moves below terminal
- Remove max-w-4xl cap from Terminal.tsx so it fills full container width
- Reset terminalActive state when navigating between scripts

* Release prep: bump to 1.0.0-pre1 + add updater

Update project to pre-release 1.0.0-pre1 and add an interactive updater.

- Bump VERSION and package.json version to 1.0.0-pre1.
- Add pre-release-updater.sh: interactive script to list GitHub prereleases, backup current install, download/extract a selected prerelease, install deps, run migrations, build, and restart the service.
- Minor JSX formatting cleanup in ScriptDetailModal.tsx (split long className into multiple lines for readability; no functional change).

* fix: correct INSTALL_DIR to /opt/ProxmoxVE-Local

* fix(modal): resolve z-index race in ModalStackProvider; refactor(installed-scripts): UI overhaul - stats cards, filters, toolbar, table

* feat(installed-scripts): add Restart/Reboot action; fix orphaned cleanup for missing-server records

* fix(cleanup): delete SSH records with server but no container_id (Pass 1.5); feat(backups): add Create Backup via vzdump in BackupsTab

* fix(generator): await refetch after download; add server selection for SSH execution

- Fix download race condition: await getAllDownloadedScripts.refetch() before
  closing dialog and selecting script so isScriptDownloaded returns true
- Add Server type import + state + useEffect to fetch /api/servers on mount
- Add server selection pill buttons above Execute (auto-selects single server)
- Execute button label changes to 'Execute on <name>' or 'Execute Locally'
- Pass mode + server to Terminal for correct local vs SSH execution
- Add selectedServer to handleExecute useCallback dependencies

* fix(generator): restore missing setTimeout body (syntax error)

* style: auto-format BackupsTab and GeneratorTab

* feat(pre2): ProxmoxVED toggle, floating shell dialog, settings UI polish

- Settings: remove Theme block (use AppearanceButton instead), restyle tabs
  to match main nav pill style
- Settings: add ProxmoxVED / Dev Scripts toggle (default: off); persisted in
  localStorage; StorageEvent keeps ScriptsGrid in sync without context
- ScriptsGrid: filter is_dev scripts from Newest carousel and full grid when
  ProxmoxVED is disabled; add showDevScripts -> FilterBar prop
- FilterBar: hide 'In Dev' quick-filter pill when ProxmoxVED is disabled
- ShellContext: new React context (open/minimize/restore/close) for shell sessions
- FloatingShell: new floating dialog with minimize-to-pill, maximize, close;
  persists across tab switches; renders via createPortal
- InstalledScriptsTab: delegate shell open to useShell() context instead of
  local inline terminal; remove inline shell JSX
- page.tsx: wrap Home in ShellProvider, render FloatingShell at page level

* feat: implement execute_in container picker for addon scripts

- Add execute_in?: string[] | null to Script type
- Forward execute_in from PocketBase via pbToScript() mapper
- Add listContainersOnServer tRPC query (pct list + qm list via SSH)
- GeneratorTab: show container/VM picker when script has execute_in flags
  - lxc, pbs, pmg -> show LXC picker (pbs/pmg pin matching containers)
  - vm -> show VM picker
  - Passes CTID env var to the script on execution
- Picker resets on server or script change

* fix(generator): move container-reset useEffect after selectedSlug declaration

* feat: add prerelease update channel toggle + bump version to 1.0.0-pre2

- Add ALLOW_PRERELEASE env var to env.js
- Add /api/settings/prerelease GET/POST route (persists to .env)
- version.ts: getVersionStatus + getLatestRelease use /releases (all) when
  ALLOW_PRERELEASE=true, otherwise /releases/latest (stable only)
- GitHubRelease interface: add prerelease boolean field
- GeneralSettingsModal: add Update Channel toggle in General tab
- VERSION: bump to 1.0.0-pre2
- page.tsx: destructure isAuthenticated from useAuth()
- GeneratorTab.tsx: move container-reset useEffect after selectedSlug decl

* fix(page): destructure logout from useAuth

* feat: floating terminal for backup + New Backup dialog + fixes

- FloatingShell: support backup task mode (isBackup Terminal when
  session.backupStorage is set); adds HardDrive icon, onComplete callback
- ShellContext: extend ShellSession with backupStorage, title, onComplete
- BackupsTab: replace blocking createBackupMutation with FloatingShell backup;
  add 'New Backup' dialog (server -> container -> storage selection)
- InstalledScriptsTab: fix fetchStorages to not show blocking error modal
- VERSION: bump to 1.0.0-pre3, fixed UTF-8 BOM encoding

* fix: keep Terminal mounted on minimize, add drag-to-move support

- FloatingShell is now a single always-mounted window instead of
  conditional branches — visibility:hidden on minimize keeps the
  xterm.js WebSocket alive so 'starting shell session' no longer
  appears on restore
- Header acts as drag handle: mouse-drag repositions the floating
  window freely so the background remains usable
- Maximize still covers full viewport; restore returns to last
  dragged position (or CSS-centered if never dragged)

* fix: Server.host -> Server.ip in BackupsTab new backup dialog

* fix: use lxc/vm fields from listContainersOnServer (no containers/vmid)

* fix: bundle core.func+error-handler.func into FUNCTIONS_FILE_PATH

* fix: typed container list in New Backup dialog (no unsafe any)

* feat: v1.0.0-pre4 - multi-session shell, multi-LXC backup, auto-discover after backup, local generator command, addon execute_in

* feat: add Refresh button to Downloaded Scripts tab

* fix: add executeInContainer to WebSocketMessage typedef

* fix: installationId typedef + verbose logo error logging

* fix: add JSDoc type annotations to implicit any callback params

* fix: guard against undefined results[j] in logo cache loop

* Refactor Backups modal and minor UI cleanups

Refactor the Backups create dialog for clarity and better state handling: reorganized JSX, normalized formatting, extract typed container lists, and ensure closing the dialog clears selected storage. Adjust server/container/storage selection flows and button behaviors to improve readability and UX. Also apply small readability/formatting fixes in DownloadedScriptsTab (expand onClick), FloatingShell (simplify Math.min expression), and GeneratorTab (wrap ternary for containerId). These are mostly non-functional cleanup and UI clarity changes across the mentioned components.

* feat: execute_in container routing + install UI overhaul

- GeneratorTab: remove && !!selectedServer from execInContainer so addon
  scripts work in local mode (pct exec works without SSH)
- InstallCommandBlock: add executeIn prop + container picker via tRPC
  listContainersOnServer; pass executeInContainer/containerId/containerType
  to Terminal so addon scripts run inside the container, not on the host
- InstallCommandBlock: remove GitHub/Gitea source toggle; promote
  My Defaults + App Defaults to top-level tabs alongside Default/Alpine/Advanced
- ScriptDetailModal: pass execute_in to InstallCommandBlock; add Runs In
  badges to Details panel

* fix: GitHub PAT not applied at runtime + light mode contrast

- route.ts: also set process.env.GITHUB_TOKEN in memory after writing to
  .env file - tokens saved via UI now take effect immediately without restart
- github.ts: read process.env.GITHUB_TOKEN directly instead of the frozen
  t3-env snapshot (env.GITHUB_TOKEN is captured once at startup)
- github.ts: switch Authorization to 'Bearer' scheme (works for both classic
  ghp_ and fine-grained github_pat_ tokens per GitHub docs)
- GeneralSettingsModal: fix text-success-foreground / text-error-foreground
  -> text-success / text-error so messages are readable in light mode
  (success-foreground is white, which is invisible on bg-success/10)
- GeneralSettingsModal: update PAT description to mention both token types

* fix: unblock pre-release updater TypeScript build + cut pre5

- InstallCommandBlock: fix trpc input type for listContainersOnServer
  (serverId now numeric fallback instead of string)
- InstallCommandBlock: align container list mapping to API response shape
  (use id/name instead of vmid)
- InstallCommandBlock: narrow running.containerType type to 'lxc' | 'vm'
- VERSION: bump to 1.0.0-pre5
- package.json: bump app version to 1.0.0-pre5 (installer/build logs)

This resolves the pre4 updater build failures reported in PR comments.

* feat: backup dialog UX + generator local-node workflow fixes

Backups:
- render create-backup dialog in portal with full-screen backdrop
- fix multi-select flow: explicit steps (server -> containers -> storage)
- keep container selection until user clicks Continue
- show storage free capacity (GB) from pvesm status
- show estimated max backup size from selected container disk templates

Generator:
- remove 'This machine (local)' execution option
- require node selection; execute over SSH only
- generated command now always uses local script path (scripts/...)
  instead of remote curl command
- add install mode tabs: Default / My Defaults / App Defaults / Advanced
- apply mode to command/envVars (mode=default|mydefaults|appdefaults|generated)
- use selected container resources as template defaults (cpu/ram/disk)

API:
- getBackupStorages now enriches storages with available/used/total GB
- add getContainersResourceTemplates for per-container cpu/ram/disk templates

* Add advanced options to generator tab

Expose many new advanced/container, network and feature settings in GeneratorTab: password, tags, timezone, container/template storage, protection, IPv6 method/ip/gateway, search domain, nameserver, TUN, keyctl, mknod, verbose, APT cacher (with IP), mount filesystems and SSH authorized key. Wire these into command overrides, env-vars generation, export/import and reset logic. UI updated with grouped sections, IPv6 selector buttons, new inputs and toggles, and FieldInput now supports input type and hint. Also minor refactor to templateDefaults lookup formatting.

* Format JSX in BackupsTab and GeneralSettingsModal

Apply code style/formatting updates across BackupsTab.tsx and GeneralSettingsModal.tsx: reflow JSX props and elements, add consistent line breaks/commas and minor spacing adjustments (including a spacing fix in the GitHub token text). No logic or behavioral changes.

* feat: filter addon/pve types from sync, display, and script loading

- Add UNSUPPORTED_TYPES constant ['addon', 'pve'] in scripts router
- Filter these types from getScriptCards, getScriptCardsWithCategories
- Block loadScript and loadMultipleScripts for unsupported types
- Remove addon/pve filter options from FilterBar UI
- Remove unused Wrench/Server icon imports from FilterBar

* chore: bump version to 1.0.0-pre6

* fix: add pbs_username to hand-written PBSStorageCredential type

* chore: update dependencies and regenerate lockfile

* feat: hide dev count badge in category sidebar when dev mode is off

* feat: add DHCP/STATIC IPv4 mode pills to generator, show IP/gateway fields only when static

* Fix CategorySidebar JSX and format GeneratorTab

Close a mismatched <span> in CategorySidebar so the inner "dev" badge is properly nested and rendered. Also reformat several single-line conditionals and adjust className ordering/formatting in GeneratorTab for improved readability; these are stylistic changes with no functional behavior changes.

* fix: keep floating shell windows mounted when minimized to preserve session state

Instead of unmounting FloatingShellWindow (which destroyed xterm + WebSocket),
all session windows are now kept in the DOM and hidden via CSS (display: none)
when minimized. This preserves the terminal session, history, and WebSocket
connection across minimize/restore cycles.

* feat: add floating shell access to Scripts, Downloaded, and Detail modal

Shell buttons now appear everywhere an installed container is recognized:

- ScriptDetailModal sidebar: 'Containers' section shows each matching
  installed container with a direct Shell button (covers Scripts +
  Downloaded tabs via the modal)
- ScriptsGrid / ScriptCard: shell button appears on cards (card and list
  view) for scripts that have an installed container
- DownloadedScriptsTab: same shell button on cards and list rows
- ScriptCardList: shell button in the header row alongside website link

Matching is done by normalizing the installed script_name against the
card slug (lowercase, strip extension, replace non-alphanumeric with dash).
Only containers with a valid container_id and non-failed status are shown.

* fix: restore downloaded addon/pve scripts visibility in Downloaded tab

The UNSUPPORTED_TYPES filter was applied at the router level in
getScriptCardsWithCategories and getScriptCards. Since DownloadedScriptsTab
builds its list by cross-referencing local files against the GitHub cards
from this endpoint, addon/pve scripts that were already downloaded locally
were invisibly dropped.

Fix: remove the filter from the router, apply it client-side in
ScriptsGrid's combinedScripts memo instead. This means:
- Scripts grid: still hides addon/pve (can't install them)
- Downloaded tab: shows ALL locally downloaded scripts regardless of type
- loadScript / loadMultipleScripts: still block new addon/pve downloads

* Format imports and object indentation

Reformat code in DownloadedScriptsTab.tsx and ScriptDetailModal.tsx for readability: split the React import across multiple lines, adjust placement/indentation of eslint-disable comments, and reflow object property lines in ScriptDetailModal. These are stylistic changes only and do not modify runtime behavior.

* feat: v1.0.0-pre7 - updater channel fix, configurable detection tag, static IP guard

Fixes:
- fix: updater no longer downgrades prerelease installs to stable
  version.ts executeUpdate now uses the v1.0.0 branch when VERSION
  contains 'pre', so prerelease users always get the prerelease update.sh
- fix: static IP guard in build.func - if NET is the literal word 'static'
  (no CIDR entered), fall back to dhcp with a warning instead of creating
  a container with ip=static
- fix: ConfigurationModal no longer sends var_net=static to the script
  when no IP address was entered in the static IP field

Features:
- feat: configurable container detection tag (Settings > General)
  Users can override 'community-script' with any tag (e.g. 'cs')
  Stored in .env as CONTAINER_DETECTION_TAG, used by autoDetectLXCContainers

Version:
- bump VERSION + package.json to 1.0.0-pre7

* fix: preserve downloaded scripts across updates

- pre-release updater now backs up/restores scripts ct/tools/vm/vw
- prevent rsync from overwriting downloaded script directories
- include scripts/vw in update-engine backup/restore/rollback/excludes

This prevents downloaded scripts from disappearing after update and
explains why only bundled defaults (e.g. debian + arcane) remained.

* feat(ui): unify floating terminals and enable addon execution

* chore: bump version to 1.0.0-pre8

* fix(updater): skip engine self-update gracefully when UPDATER_VERSION not on main (pre-release)

* fix: SSH interactive input, suppress rsync output, 4-theme picker, sort containers by ID

* fix(ui): overhaul terminal themes with strong contrast and real preview cards

* feat(pre9): execute_in policy matrix, full type visibility, lxc-only generator

* fix(pre9): make VM/LXC status and type detection server-scoped

---------

Co-authored-by: MickLesk <mickey.leskowitz@levelbuild.com>
2026-05-05 15:26:13 +02:00

1947 lines
67 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createServer } from 'http';
import { parse } from 'url';
import next from 'next';
import { WebSocketServer } from 'ws';
import { spawn } from 'child_process';
import { existsSync } from 'fs';
import { join, resolve } from 'path';
import stripAnsi from 'strip-ansi';
import { spawn as ptySpawn } from 'node-pty';
import { getSSHExecutionService } from './src/server/ssh-execution-service.js';
import { getDatabase } from './src/server/database-prisma.js';
import dotenv from 'dotenv';
// Dynamic import for auto sync init to avoid tsx caching issues
/** @type {any} */
let autoSyncModule = null;
// Load environment variables from .env file
dotenv.config();
// Fallback minimal global error handlers for Node runtime (avoid TS import)
function registerGlobalErrorHandlers() {
if (registerGlobalErrorHandlers._registered) return;
registerGlobalErrorHandlers._registered = true;
process.on('uncaughtException', (err) => {
console.error('uncaught_exception', err);
});
process.on('unhandledRejection', (reason) => {
console.error('unhandled_rejection', reason);
});
}
registerGlobalErrorHandlers._registered = false;
const dev = process.env.NODE_ENV !== 'production';
const hostname = '::';
const port = parseInt(process.env.PORT || '3000', 10);
const app = next({ dev, hostname, port });
// Register global handlers once at bootstrap
registerGlobalErrorHandlers();
const handle = app.getRequestHandler();
// WebSocket handler for script execution
/**
* @typedef {import('ws').WebSocket & {connectionTime?: number, clientIP?: string}} ExtendedWebSocket
*/
/**
* @typedef {Object} Execution
* @property {any} process
* @property {ExtendedWebSocket} ws
*/
/**
* @typedef {Object} ServerInfo
* @property {string} name
* @property {string} ip
* @property {string} user
* @property {string} password
* @property {number} [id]
* @property {string} [auth_type]
* @property {string} [ssh_key_path]
*/
/**
* @typedef {Object} ExecutionResult
* @property {any} process
* @property {Function} kill
*/
/**
* @typedef {Object} WebSocketMessage
* @property {string} action
* @property {string} [scriptPath]
* @property {string} [executionId]
* @property {string} [input]
* @property {string} [mode]
* @property {ServerInfo} [server]
* @property {boolean} [isUpdate]
* @property {boolean} [isShell]
* @property {boolean} [isBackup]
* @property {boolean} [isClone]
* @property {boolean} [executeInContainer]
* @property {string} [containerId]
* @property {string} [storage]
* @property {string} [backupStorage]
* @property {number} [cloneCount]
* @property {string[]} [hostnames]
* @property {'lxc'|'vm'} [containerType]
* @property {Record<string, string|number|boolean>} [envVars]
*/
class ScriptExecutionHandler {
/**
* @param {import('http').Server} server
*/
constructor(server) {
// Create WebSocketServer without attaching to server
// We'll handle upgrades manually to avoid interfering with Next.js HMR
this.wss = new WebSocketServer({
noServer: true
});
this.activeExecutions = new Map();
this.db = getDatabase();
this.setupWebSocket();
}
/**
* Handle WebSocket upgrade for our endpoint
* @param {import('http').IncomingMessage} request
* @param {import('stream').Duplex} socket
* @param {Buffer} head
*/
handleUpgrade(request, socket, head) {
this.wss.handleUpgrade(request, socket, head, (ws) => {
this.wss.emit('connection', ws, request);
});
}
/**
* Parse Container ID from terminal output
* @param {string} output - Terminal output to parse
* @returns {string|null} - Container ID if found, null otherwise
*/
parseContainerId(output) {
// First, strip ANSI color codes to make pattern matching more reliable
const cleanOutput = output.replace(/\x1b\[[0-9;]*m/g, '');
// Look for various patterns that Proxmox scripts might use
const patterns = [
// Primary pattern - the exact format from the output
/🆔\s+Container\s+ID:\s+(\d+)/i,
// Standard patterns with flexible spacing
/🆔\s*Container\s*ID:\s*(\d+)/i,
/Container\s*ID:\s*(\d+)/i,
/CT\s*ID:\s*(\d+)/i,
/Container\s*(\d+)/i,
// Alternative patterns
/CT\s*(\d+)/i,
/Container\s*created\s*with\s*ID\s*(\d+)/i,
/Created\s*container\s*(\d+)/i,
/Container\s*(\d+)\s*created/i,
/ID:\s*(\d+)/i,
// Patterns with different spacing and punctuation
/Container\s*ID\s*:\s*(\d+)/i,
/CT\s*ID\s*:\s*(\d+)/i,
/Container\s*#\s*(\d+)/i,
/CT\s*#\s*(\d+)/i,
// Patterns that might appear in success messages
/Successfully\s*created\s*container\s*(\d+)/i,
/Container\s*(\d+)\s*is\s*ready/i,
/Container\s*(\d+)\s*started/i,
// Generic number patterns that might be container IDs (3-4 digits)
/(?:^|\s)(\d{3,4})(?:\s|$)/m,
];
// Try patterns on both original and cleaned output
const outputsToTry = [output, cleanOutput];
for (const testOutput of outputsToTry) {
for (const pattern of patterns) {
const match = testOutput.match(pattern);
if (match && match[1]) {
const containerId = match[1];
// Additional validation: container IDs are typically 3-4 digits
if (containerId.length >= 3 && containerId.length <= 4) {
return containerId;
}
}
}
}
return null;
}
/**
* Parse Web UI URL from terminal output
* @param {string} output - Terminal output to parse
* @returns {{ip: string, port: number}|null} - Object with ip and port if found, null otherwise
*/
parseWebUIUrl(output) {
// First, strip ANSI color codes to make pattern matching more reliable
const cleanOutput = output.replace(/\x1b\[[0-9;]*m/g, '');
// Look for URL patterns with any valid IP address (private or public)
const patterns = [
// HTTP/HTTPS URLs with IP and port
/https?:\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)/gi,
// URLs without explicit port (assume default ports)
/https?:\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?:\/|$|\s)/gi,
// URLs with trailing slash and port
/https?:\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)\//gi,
// URLs with just IP and port (no protocol)
/(?:^|\s)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)(?:\s|$)/gi,
// URLs with just IP (no protocol, no port)
/(?:^|\s)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?:\s|$)/gi,
];
// Try patterns on both original and cleaned output
const outputsToTry = [output, cleanOutput];
for (const testOutput of outputsToTry) {
for (const pattern of patterns) {
const matches = [...testOutput.matchAll(pattern)];
for (const match of matches) {
if (match[1]) {
const ip = match[1];
const port = match[2] || (match[0].startsWith('https') ? '443' : '80');
// Validate IP address format
if (ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) {
return {
ip: ip,
port: parseInt(port, 10)
};
}
}
}
}
}
return null;
}
/**
* Create installation record
* @param {string} scriptName - Name of the script
* @param {string} scriptPath - Path to the script
* @param {string} executionMode - 'local' or 'ssh'
* @param {number|null} serverId - Server ID for SSH executions
* @returns {Promise<number|null>} - Installation record ID
*/
async createInstallationRecord(scriptName, scriptPath, executionMode, serverId = null) {
try {
const result = await this.db.createInstalledScript({
script_name: scriptName,
script_path: scriptPath,
container_id: undefined,
server_id: serverId ?? undefined,
execution_mode: executionMode,
status: 'in_progress',
output_log: ''
});
return Number(result.id);
} catch (error) {
console.error('Error creating installation record:', error);
return null;
}
}
/**
* Update installation record
* @param {number} installationId - Installation record ID
* @param {Object} updateData - Data to update
*/
async updateInstallationRecord(installationId, updateData) {
try {
await this.db.updateInstalledScript(installationId, updateData);
} catch (error) {
console.error('Error updating installation record:', error);
}
}
setupWebSocket() {
this.wss.on('connection', (ws, request) => {
// Set connection metadata
/** @type {ExtendedWebSocket} */ (ws).connectionTime = Date.now();
/** @type {ExtendedWebSocket} */ (ws).clientIP = request.socket.remoteAddress || 'unknown';
ws.on('message', (data) => {
try {
const rawMessage = data.toString();
const message = JSON.parse(rawMessage);
this.handleMessage(/** @type {ExtendedWebSocket} */ (ws), message);
} catch (error) {
console.error('Error parsing WebSocket message:', error);
this.sendMessage(ws, {
type: 'error',
data: 'Invalid message format',
timestamp: Date.now()
});
}
});
ws.on('close', (code, reason) => {
this.cleanupActiveExecutions(/** @type {ExtendedWebSocket} */ (ws));
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
this.cleanupActiveExecutions(/** @type {ExtendedWebSocket} */ (ws));
});
});
}
/**
* Resolve full server from DB when client sends server with id but no ssh_key_path (e.g. for Shell/Update over SSH).
* @param {ServerInfo|null} server - Server from WebSocket message
* @returns {Promise<ServerInfo|null>} Same server or full server from DB
*/
async resolveServerForSSH(server) {
if (!server?.id) return server;
if (server.auth_type === 'key' && (!server.ssh_key_path || !existsSync(server.ssh_key_path))) {
const full = await this.db.getServerById(server.id);
return /** @type {ServerInfo|null} */ (full ?? server);
}
return server;
}
/**
* @param {ExtendedWebSocket} ws
* @param {WebSocketMessage} message
*/
async handleMessage(ws, message) {
const { action, scriptPath, executionId, input, mode, server, isUpdate, isShell, isBackup, isClone, executeInContainer, containerId, storage, backupStorage, cloneCount, hostnames, containerType, envVars } = message;
switch (action) {
case 'start':
if (scriptPath && executionId) {
let serverToUse = server;
if (serverToUse?.id) {
serverToUse = await this.resolveServerForSSH(serverToUse) ?? serverToUse;
}
const resolved = serverToUse ?? server;
if (isClone && containerId && storage && server && cloneCount && hostnames && containerType) {
await this.startSSHCloneExecution(ws, containerId, executionId, storage, /** @type {ServerInfo} */ (resolved), containerType, cloneCount, hostnames);
} else if (isBackup && containerId && storage) {
await this.startBackupExecution(ws, containerId, executionId, storage, mode, resolved);
} else if (isUpdate && containerId) {
await this.startUpdateExecution(ws, containerId, executionId, mode, resolved, backupStorage, envVars);
} else if (isShell && containerId) {
await this.startShellExecution(ws, containerId, executionId, mode, resolved, containerType);
} else if (executeInContainer && containerId) {
await this.startInContainerScriptExecution(ws, scriptPath, executionId, mode, resolved, envVars, containerId, containerType ?? 'lxc');
} else {
await this.startScriptExecution(ws, scriptPath, executionId, mode, resolved, envVars);
}
} else {
this.sendMessage(ws, {
type: 'error',
data: 'Missing scriptPath or executionId',
timestamp: Date.now()
});
}
break;
case 'stop':
if (executionId) {
this.stopScriptExecution(executionId);
}
break;
case 'input':
if (executionId && input !== undefined) {
this.sendInputToProcess(executionId, input);
}
break;
default:
this.sendMessage(ws, {
type: 'error',
data: 'Unknown action',
timestamp: Date.now()
});
}
}
/**
* @param {ExtendedWebSocket} ws
* @param {string} scriptPath
* @param {string} executionId
* @param {string} mode
* @param {ServerInfo|null} server
* @param {Object} [envVars] - Optional environment variables to pass to the script
*/
async startScriptExecution(ws, scriptPath, executionId, mode = 'local', server = null, envVars = {}) {
/** @type {number|null} */
let installationId = null;
try {
// Check if execution is already running
if (this.activeExecutions.has(executionId)) {
this.sendMessage(ws, {
type: 'error',
data: 'Script execution already running',
timestamp: Date.now()
});
return;
}
// Extract script name from path
const scriptName = scriptPath.split('/').pop() ?? scriptPath.split('\\').pop() ?? 'Unknown Script';
// Create installation record
const serverId = server ? (server.id ?? null) : null;
installationId = await this.createInstallationRecord(scriptName, scriptPath, mode, serverId);
if (!installationId) {
console.error('Failed to create installation record');
}
// Handle SSH execution
if (mode === 'ssh' && server) {
await this.startSSHScriptExecution(ws, scriptPath, executionId, server, installationId, envVars);
return;
}
if (mode === 'ssh' && !server) {
// SSH mode requested but no server provided, falling back to local execution
}
// Basic validation for local execution
const scriptsDir = join(process.cwd(), 'scripts');
const resolvedPath = resolve(scriptPath);
if (!resolvedPath.startsWith(resolve(scriptsDir))) {
this.sendMessage(ws, {
type: 'error',
data: 'Script path is not within the allowed scripts directory',
timestamp: Date.now()
});
// Update installation record with failure
if (installationId) {
await this.updateInstallationRecord(installationId, { status: 'failed' });
}
return;
}
// Format environment variables for local execution
// Convert envVars object to environment variables
const envWithVars = {
...process.env,
TERM: 'xterm-256color', // Enable proper terminal support
FORCE_ANSI: 'true', // Allow ANSI codes for proper display
COLUMNS: '80', // Set terminal width
LINES: '24' // Set terminal height
};
// Add envVars to environment
if (envVars && typeof envVars === 'object') {
for (const [key, value] of Object.entries(envVars)) {
/** @type {Record<string, string>} */
const envRecord = envWithVars;
envRecord[key] = String(value);
}
}
// Start script execution with pty for proper TTY support
const childProcess = ptySpawn('bash', [resolvedPath], {
cwd: scriptsDir,
name: 'xterm-256color',
cols: 80,
rows: 24,
env: envWithVars
});
// pty handles encoding automatically
// Store the execution with installation ID
this.activeExecutions.set(executionId, {
process: childProcess,
ws,
installationId,
outputBuffer: ''
});
// Send start message
this.sendMessage(ws, {
type: 'start',
data: `Starting execution of ${scriptPath}`,
timestamp: Date.now()
});
// Handle pty data (both stdout and stderr combined)
childProcess.onData(async (data) => {
const output = data.toString();
// Store output in buffer for logging
const execution = this.activeExecutions.get(executionId);
if (execution) {
execution.outputBuffer += output;
// Keep only last 1000 characters to avoid memory issues
if (execution.outputBuffer.length > 1000) {
execution.outputBuffer = execution.outputBuffer.slice(-1000);
}
}
// Parse for Container ID
const containerId = this.parseContainerId(output);
if (containerId && installationId) {
await this.updateInstallationRecord(installationId, { container_id: containerId });
}
// Parse for Web UI URL
const webUIUrl = this.parseWebUIUrl(output);
if (webUIUrl && installationId) {
const { ip, port } = webUIUrl;
if (ip && port) {
await this.updateInstallationRecord(installationId, {
web_ui_ip: ip,
web_ui_port: port
});
}
}
this.sendMessage(ws, {
type: 'output',
data: output,
timestamp: Date.now()
});
});
// Handle process exit
childProcess.onExit((e) => {
const execution = this.activeExecutions.get(executionId);
const isSuccess = e.exitCode === 0;
// Update installation record with final status and output
if (installationId && execution) {
this.updateInstallationRecord(installationId, {
status: isSuccess ? 'success' : 'failed',
output_log: execution.outputBuffer
});
}
this.sendMessage(ws, {
type: 'end',
data: `Script execution finished with code: ${e.exitCode}, signal: ${e.signal}`,
timestamp: Date.now()
});
// Clean up
this.activeExecutions.delete(executionId);
});
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `Failed to start script: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
// Update installation record with failure
if (installationId) {
await this.updateInstallationRecord(installationId, { status: 'failed' });
}
}
}
/**
* Execute a script INSIDE a container via `pct exec` (LXC) or `qm guest exec` (VM).
* For SSH mode the scripts folder is already transferred to /tmp/scripts on the PVE host by
* startSSHScriptExecution; we re-use that mechanism and then run the script inside the CT.
* For local mode we pipe the script through `pct exec`.
*
* @param {ExtendedWebSocket} ws
* @param {string} scriptPath
* @param {string} executionId
* @param {string} mode
* @param {ServerInfo|null} server
* @param {Object} envVars
* @param {string} containerId
* @param {'lxc'|'vm'} containerType
*/
async startInContainerScriptExecution(ws, scriptPath, executionId, mode = 'local', server = null, envVars = {}, containerId, containerType = 'lxc') {
/** @type {number|null} */
let installationId = null;
try {
if (this.activeExecutions.has(executionId)) {
this.sendMessage(ws, { type: 'error', data: 'Script execution already running', timestamp: Date.now() });
return;
}
const scriptName = scriptPath.split('/').pop() ?? scriptPath.split('\\').pop() ?? 'Unknown Script';
const serverId = server ? (server.id ?? null) : null;
installationId = await this.createInstallationRecord(scriptName, scriptPath, mode, serverId);
// Build env-var export prefix
const envExports = Object.entries(envVars ?? {})
.map(([k, v]) => `export ${k}=${JSON.stringify(String(v))}`)
.join('; ');
const envPrefix = envExports ? `${envExports}; ` : '';
if (mode === 'ssh' && server) {
// Transfer scripts folder to PVE host, then exec inside container
const sshService = getSSHExecutionService();
this.sendMessage(ws, { type: 'start', data: `Connecting to ${server.ip}`, timestamp: Date.now() });
const relScript = scriptPath.replace(/^scripts[/\\]/, '');
const remoteScript = `/tmp/scripts/${relScript}`;
// Transfer scripts folder silently — suppress verbose rsync file listing
this.sendMessage(ws, { type: 'output', data: 'Syncing scripts…\r\n', timestamp: Date.now() });
await sshService.transferScriptsFolder(server,
() => {}, // suppress rsync stdout (verbose file listing)
(/** @type {string} */ err) => {
// Ignore harmless SSH host-key / known-hosts notices from rsync stderr
if (!err.includes('Warning:') && !err.includes('Permanently added')) {
this.sendMessage(ws, { type: 'error', data: err, timestamp: Date.now() });
}
}
);
let inContainerCmd;
if (containerType === 'lxc') {
// For LXC we must copy the script from host (/tmp/scripts/...) into the container first.
// Otherwise pct exec tries to run a host path that does not exist inside the CT.
const remoteTarget = `/tmp/${scriptName}`;
const pushCmd = `pct push ${containerId} ${remoteScript} ${remoteTarget}`;
// Run pct push silently (no terminal output needed for this bookkeeping step)
await new Promise((resolve, reject) => {
sshService.executeCommand(server, pushCmd,
() => {}, // suppress push output
() => {}, // suppress push stderr
(/** @type {number} */ code) => {
if (code === 0) resolve(true);
else reject(new Error(`pct push failed with exit code ${code}`));
},
);
});
inContainerCmd = `pct exec ${containerId} -- bash -c "chmod +x ${remoteTarget}; ${envPrefix}bash ${remoteTarget}"`;
} else {
// VM execution currently relies on guest exec and assumes script path exists in guest context.
inContainerCmd = `qm guest exec ${containerId} -- bash -c "${envPrefix}bash ${remoteScript}"`;
}
this.activeExecutions.set(executionId, { process: null, ws, installationId, outputBuffer: '' });
// executeCommand resolves immediately with the PTY process — store it so
// interactive input (y/n prompts etc.) can be forwarded via sendInputToProcess.
const execResult = await sshService.executeCommand(server, inContainerCmd,
(/** @type {string} */ data) => {
const execution = this.activeExecutions.get(executionId);
if (execution) execution.outputBuffer += data;
this.sendMessage(ws, { type: 'output', data, timestamp: Date.now() });
},
(/** @type {string} */ err) => {
this.sendMessage(ws, { type: 'error', data: err, timestamp: Date.now() });
},
async (/** @type {number} */ exitCode) => {
const execution = this.activeExecutions.get(executionId);
if (installationId && execution) {
await this.updateInstallationRecord(installationId, {
status: exitCode === 0 ? 'success' : 'failed',
output_log: execution.outputBuffer
});
}
this.sendMessage(ws, { type: 'end', data: `Finished with code: ${exitCode}`, timestamp: Date.now() });
this.activeExecutions.delete(executionId);
}
);
// Attach the real PTY process so keyboard input can reach interactive prompts
const storedExec = this.activeExecutions.get(executionId);
if (storedExec && execResult && /** @type {any} */(execResult).process) {
storedExec.process = /** @type {any} */(execResult).process;
}
return;
}
// Local mode: pipe the script content into `pct exec <ctid> -- bash`
const scriptsDir = join(process.cwd(), 'scripts');
const resolvedPath = resolve(scriptPath);
if (!resolvedPath.startsWith(resolve(scriptsDir))) {
this.sendMessage(ws, { type: 'error', data: 'Script path outside scripts directory', timestamp: Date.now() });
if (installationId) await this.updateInstallationRecord(installationId, { status: 'failed' });
return;
}
const bashCmd = `${envPrefix}bash ${resolvedPath}`;
const args = containerType === 'lxc'
? ['exec', containerId, '--', 'bash', '-c', bashCmd]
: ['guest', 'exec', containerId, '--', 'bash', '-c', bashCmd];
const cmd = containerType === 'lxc' ? 'pct' : 'qm';
const childProcess = ptySpawn(cmd, args, {
cwd: scriptsDir,
name: 'xterm-256color',
cols: 80,
rows: 24,
env: { ...process.env, TERM: 'xterm-256color' }
});
this.activeExecutions.set(executionId, { process: childProcess, ws, installationId, outputBuffer: '' });
this.sendMessage(ws, { type: 'start', data: `Executing inside container ${containerId}`, timestamp: Date.now() });
childProcess.onData((data) => {
const execution = this.activeExecutions.get(executionId);
if (execution) execution.outputBuffer += data;
this.sendMessage(ws, { type: 'output', data, timestamp: Date.now() });
});
childProcess.onExit(async (e) => {
const execution = this.activeExecutions.get(executionId);
if (installationId && execution) {
await this.updateInstallationRecord(installationId, {
status: e.exitCode === 0 ? 'success' : 'failed',
output_log: execution.outputBuffer
});
}
this.sendMessage(ws, { type: 'end', data: `Script finished with code: ${e.exitCode}`, timestamp: Date.now() });
this.activeExecutions.delete(executionId);
});
} catch (error) {
this.sendMessage(ws, { type: 'error', data: `Failed to start in-container script: ${error instanceof Error ? error.message : String(error)}`, timestamp: Date.now() });
if (installationId) await this.updateInstallationRecord(installationId, { status: 'failed' });
}
}
/**
* Start SSH script execution
* @param {ExtendedWebSocket} ws
* @param {string} scriptPath
* @param {string} executionId
* @param {ServerInfo} server
* @param {number|null} installationId
* @param {Object} [envVars] - Optional environment variables to pass to the script
*/
async startSSHScriptExecution(ws, scriptPath, executionId, server, installationId = null, envVars = {}) {
const sshService = getSSHExecutionService();
// Send start message
this.sendMessage(ws, {
type: 'start',
data: `Starting SSH execution of ${scriptPath} on ${server.name} (${server.ip})`,
timestamp: Date.now()
});
try {
const execution = /** @type {ExecutionResult} */ (await sshService.executeScript(
server,
scriptPath,
/** @param {string} data */ async (data) => {
// Store output in buffer for logging
const exec = this.activeExecutions.get(executionId);
if (exec) {
exec.outputBuffer += data;
// Keep only last 1000 characters to avoid memory issues
if (exec.outputBuffer.length > 1000) {
exec.outputBuffer = exec.outputBuffer.slice(-1000);
}
}
// Parse for Container ID
const containerId = this.parseContainerId(data);
if (containerId && installationId) {
await this.updateInstallationRecord(installationId, { container_id: containerId });
}
// Parse for Web UI URL
const webUIUrl = this.parseWebUIUrl(data);
if (webUIUrl && installationId) {
const { ip, port } = webUIUrl;
if (ip && port) {
await this.updateInstallationRecord(installationId, {
web_ui_ip: ip,
web_ui_port: port
});
}
}
// Handle data output
this.sendMessage(ws, {
type: 'output',
data: data,
timestamp: Date.now()
});
},
/** @param {string} error */ (error) => {
// Store error in buffer for logging
const exec = this.activeExecutions.get(executionId);
if (exec) {
exec.outputBuffer += error;
// Keep only last 1000 characters to avoid memory issues
if (exec.outputBuffer.length > 1000) {
exec.outputBuffer = exec.outputBuffer.slice(-1000);
}
}
// Handle errors
this.sendMessage(ws, {
type: 'error',
data: error,
timestamp: Date.now()
});
},
/** @param {number} code */ async (code) => {
const exec = this.activeExecutions.get(executionId);
const isSuccess = code === 0;
// Update installation record with final status and output
if (installationId && exec) {
await this.updateInstallationRecord(installationId, {
status: isSuccess ? 'success' : 'failed',
output_log: exec.outputBuffer
});
}
// Handle process exit
this.sendMessage(ws, {
type: 'end',
data: `SSH script execution finished with code: ${code}`,
timestamp: Date.now()
});
// Clean up
this.activeExecutions.delete(executionId);
},
envVars
));
// Store the execution with installation ID
this.activeExecutions.set(executionId, {
process: execution.process,
ws,
installationId,
outputBuffer: ''
});
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `Failed to start SSH execution: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
// Update installation record with failure
if (installationId) {
await this.updateInstallationRecord(installationId, { status: 'failed' });
}
}
}
/**
* @param {string} executionId
*/
stopScriptExecution(executionId) {
const execution = this.activeExecutions.get(executionId);
if (execution) {
execution.process.kill('SIGTERM');
this.activeExecutions.delete(executionId);
this.sendMessage(execution.ws, {
type: 'end',
data: 'Script execution stopped by user',
timestamp: Date.now()
});
}
}
/**
* @param {string} executionId
* @param {string} input
*/
sendInputToProcess(executionId, input) {
const execution = this.activeExecutions.get(executionId);
if (execution && execution.process.write) {
execution.process.write(input);
}
}
/**
* @param {ExtendedWebSocket} ws
* @param {any} message
*/
sendMessage(ws, message) {
if (ws.readyState === 1) { // WebSocket.OPEN
ws.send(JSON.stringify(message));
}
}
/**
* @param {ExtendedWebSocket} ws
*/
cleanupActiveExecutions(ws) {
for (const [executionId, execution] of this.activeExecutions.entries()) {
if (execution.ws === ws) {
execution.process.kill('SIGTERM');
this.activeExecutions.delete(executionId);
}
}
}
/**
* Start backup execution
* @param {ExtendedWebSocket} ws
* @param {string} containerId
* @param {string} executionId
* @param {string} storage
* @param {string} mode
* @param {ServerInfo|null} server
*/
async startBackupExecution(ws, containerId, executionId, storage, mode = 'local', server = null) {
try {
// Send start message
this.sendMessage(ws, {
type: 'start',
data: `Starting backup for container ${containerId} to storage ${storage}...`,
timestamp: Date.now()
});
if (mode === 'ssh' && server) {
await this.startSSHBackupExecution(ws, containerId, executionId, storage, server);
} else {
this.sendMessage(ws, {
type: 'error',
data: 'Backup is only supported via SSH',
timestamp: Date.now()
});
}
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `Failed to start backup: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
}
}
/**
* Start SSH backup execution
* @param {ExtendedWebSocket} ws
* @param {string} containerId
* @param {string} executionId
* @param {string} storage
* @param {ServerInfo} server
* @param {Function} [onComplete] - Optional callback when backup completes
*/
startSSHBackupExecution(ws, containerId, executionId, storage, server, onComplete = undefined) {
const sshService = getSSHExecutionService();
return new Promise((resolve, reject) => {
try {
const backupCommand = `vzdump ${containerId} --storage ${storage} --mode snapshot`;
// Wrap the onExit callback to resolve our promise
let promiseResolved = false;
sshService.executeCommand(
server,
backupCommand,
/** @param {string} data */
(data) => {
this.sendMessage(ws, {
type: 'output',
data: data,
timestamp: Date.now()
});
},
/** @param {string} error */
(error) => {
this.sendMessage(ws, {
type: 'error',
data: error,
timestamp: Date.now()
});
},
/** @param {number} code */
(code) => {
// Don't send 'end' message here if this is part of a backup+update flow
// The update flow will handle completion messages
const success = code === 0;
if (!success) {
this.sendMessage(ws, {
type: 'error',
data: `Backup failed with exit code: ${code}`,
timestamp: Date.now()
});
}
// Send a completion message (but not 'end' type to avoid stopping terminal)
this.sendMessage(ws, {
type: 'output',
data: `\n[Backup ${success ? 'completed' : 'failed'} with exit code: ${code}]\n`,
timestamp: Date.now()
});
if (onComplete) onComplete(success);
// Resolve the promise when backup completes
// Use setImmediate to ensure resolution happens in the right execution context
if (!promiseResolved) {
promiseResolved = true;
const result = { success, code };
// Use setImmediate to ensure promise resolution happens in the next tick
// This ensures the await in startUpdateExecution can properly resume
setImmediate(() => {
try {
resolve(result);
} catch (resolveError) {
console.error('Error resolving backup promise:', resolveError);
reject(resolveError);
}
});
}
this.activeExecutions.delete(executionId);
}
).then((execution) => {
// Store the execution
this.activeExecutions.set(executionId, {
process: /** @type {any} */ (execution).process,
ws
});
// Note: Don't resolve here - wait for onExit callback
}).catch((error) => {
console.error('Error starting backup execution:', error);
this.sendMessage(ws, {
type: 'error',
data: `SSH backup execution failed: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
if (onComplete) onComplete(false);
if (!promiseResolved) {
promiseResolved = true;
reject(error);
}
});
} catch (error) {
console.error('Error in startSSHBackupExecution:', error);
this.sendMessage(ws, {
type: 'error',
data: `SSH backup execution failed: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
if (onComplete) onComplete(false);
reject(error);
}
});
}
/**
* Start SSH clone execution
* Gets next IDs sequentially: get next ID → clone → get next ID → clone, etc.
* @param {ExtendedWebSocket} ws
* @param {string} containerId
* @param {string} executionId
* @param {string} storage
* @param {ServerInfo} server
* @param {'lxc'|'vm'} containerType
* @param {number} cloneCount
* @param {string[]} hostnames
*/
async startSSHCloneExecution(ws, containerId, executionId, storage, server, containerType, cloneCount, hostnames) {
const sshService = getSSHExecutionService();
this.sendMessage(ws, {
type: 'start',
data: `Starting clone operation: Creating ${cloneCount} clone(s) of ${containerType.toUpperCase()} ${containerId}...`,
timestamp: Date.now()
});
try {
// Step 1: Stop source container/VM
this.sendMessage(ws, {
type: 'output',
data: `\n[Step 1/${4 + cloneCount}] Stopping source ${containerType.toUpperCase()} ${containerId}...\n`,
timestamp: Date.now()
});
const stopCommand = containerType === 'lxc' ? `pct stop ${containerId}` : `qm stop ${containerId}`;
await new Promise(/** @type {(resolve: (value?: void) => void, reject: (error?: any) => void) => void} */ ((resolve, reject) => {
sshService.executeCommand(
server,
stopCommand,
/** @param {string} data */
(data) => {
this.sendMessage(ws, {
type: 'output',
data: data,
timestamp: Date.now()
});
},
/** @param {string} error */
(error) => {
this.sendMessage(ws, {
type: 'error',
data: error,
timestamp: Date.now()
});
},
/** @param {number} code */
(code) => {
if (code === 0) {
this.sendMessage(ws, {
type: 'output',
data: `\n[Step 1/${4 + cloneCount}] Source ${containerType.toUpperCase()} stopped successfully.\n`,
timestamp: Date.now()
});
resolve();
} else {
// Continue even if stop fails (might already be stopped)
this.sendMessage(ws, {
type: 'output',
data: `\n[Step 1/${4 + cloneCount}] Stop command completed with exit code ${code} (container may already be stopped).\n`,
timestamp: Date.now()
});
resolve();
}
}
);
}));
// Step 2: Clone for each clone count (get next ID sequentially before each clone)
const clonedIds = [];
for (let i = 0; i < cloneCount; i++) {
const cloneNumber = i + 1;
const hostname = hostnames[i];
// Get next ID for this clone
this.sendMessage(ws, {
type: 'output',
data: `\n[Step ${2 + i}/${4 + cloneCount}] Getting next available ID for clone ${cloneNumber}...\n`,
timestamp: Date.now()
});
let nextId = '';
try {
let output = '';
await new Promise(/** @type {(resolve: (value?: void) => void, reject: (error?: any) => void) => void} */ ((resolve, reject) => {
sshService.executeCommand(
server,
'pvesh get /cluster/nextid',
/** @param {string} data */
(data) => {
output += data;
},
/** @param {string} error */
(error) => {
reject(new Error(`Failed to get next ID: ${error}`));
},
/** @param {number} exitCode */
(exitCode) => {
if (exitCode === 0) {
resolve();
} else {
reject(new Error(`pvesh command failed with exit code ${exitCode}`));
}
}
);
}));
nextId = output.trim();
if (!nextId || !/^\d+$/.test(nextId)) {
throw new Error('Invalid next ID received');
}
this.sendMessage(ws, {
type: 'output',
data: `\n[Step ${2 + i}/${4 + cloneCount}] Got next ID: ${nextId}\n`,
timestamp: Date.now()
});
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `\n[Step ${2 + i}/${4 + cloneCount}] Failed to get next ID: ${error instanceof Error ? error.message : String(error)}\n`,
timestamp: Date.now()
});
throw error;
}
clonedIds.push(nextId);
// Clone the container/VM
this.sendMessage(ws, {
type: 'output',
data: `\n[Step ${2 + i}/${4 + cloneCount}] Cloning ${containerType.toUpperCase()} ${containerId} to ${nextId} with hostname ${hostname}...\n`,
timestamp: Date.now()
});
const cloneCommand = containerType === 'lxc'
? `pct clone ${containerId} ${nextId} --hostname ${hostname} --storage ${storage}`
: `qm clone ${containerId} ${nextId} --name ${hostname} --storage ${storage}`;
await new Promise(/** @type {(resolve: (value?: void) => void, reject: (error?: any) => void) => void} */ ((resolve, reject) => {
sshService.executeCommand(
server,
cloneCommand,
/** @param {string} data */
(data) => {
this.sendMessage(ws, {
type: 'output',
data: data,
timestamp: Date.now()
});
},
/** @param {string} error */
(error) => {
this.sendMessage(ws, {
type: 'error',
data: error,
timestamp: Date.now()
});
},
/** @param {number} code */
(code) => {
if (code === 0) {
this.sendMessage(ws, {
type: 'output',
data: `\n[Step ${2 + i}/${4 + cloneCount}] Clone ${cloneNumber} created successfully.\n`,
timestamp: Date.now()
});
resolve();
} else {
this.sendMessage(ws, {
type: 'error',
data: `\nClone ${cloneNumber} failed with exit code: ${code}\n`,
timestamp: Date.now()
});
reject(new Error(`Clone ${cloneNumber} failed with exit code ${code}`));
}
}
);
}));
}
// Step 3: Start source container/VM
this.sendMessage(ws, {
type: 'output',
data: `\n[Step ${2 + cloneCount + 1}/${4 + cloneCount}] Starting source ${containerType.toUpperCase()} ${containerId}...\n`,
timestamp: Date.now()
});
const startSourceCommand = containerType === 'lxc' ? `pct start ${containerId}` : `qm start ${containerId}`;
await new Promise(/** @type {(resolve: (value?: void) => void, reject: (error?: any) => void) => void} */ ((resolve) => {
sshService.executeCommand(
server,
startSourceCommand,
/** @param {string} data */
(data) => {
this.sendMessage(ws, {
type: 'output',
data: data,
timestamp: Date.now()
});
},
/** @param {string} error */
(error) => {
this.sendMessage(ws, {
type: 'error',
data: error,
timestamp: Date.now()
});
},
/** @param {number} code */
(code) => {
if (code === 0) {
this.sendMessage(ws, {
type: 'output',
data: `\n[Step ${2 + cloneCount + 1}/${4 + cloneCount}] Source ${containerType.toUpperCase()} started successfully.\n`,
timestamp: Date.now()
});
} else {
this.sendMessage(ws, {
type: 'output',
data: `\n[Step ${2 + cloneCount + 1}/${4 + cloneCount}] Start command completed with exit code ${code}.\n`,
timestamp: Date.now()
});
}
resolve();
}
);
}));
// Step 4: Start target containers/VMs
this.sendMessage(ws, {
type: 'output',
data: `\n[Step ${2 + cloneCount + 2}/${4 + cloneCount}] Starting cloned ${containerType.toUpperCase()}(s)...\n`,
timestamp: Date.now()
});
for (let i = 0; i < cloneCount; i++) {
const cloneNumber = i + 1;
const nextId = clonedIds[i];
const startTargetCommand = containerType === 'lxc' ? `pct start ${nextId}` : `qm start ${nextId}`;
await new Promise(/** @type {(resolve: (value?: void) => void, reject: (error?: any) => void) => void} */ ((resolve) => {
sshService.executeCommand(
server,
startTargetCommand,
/** @param {string} data */
(data) => {
this.sendMessage(ws, {
type: 'output',
data: data,
timestamp: Date.now()
});
},
/** @param {string} error */
(error) => {
this.sendMessage(ws, {
type: 'error',
data: error,
timestamp: Date.now()
});
},
/** @param {number} code */
(code) => {
if (code === 0) {
this.sendMessage(ws, {
type: 'output',
data: `\nClone ${cloneNumber} (ID: ${nextId}) started successfully.\n`,
timestamp: Date.now()
});
} else {
this.sendMessage(ws, {
type: 'output',
data: `\nClone ${cloneNumber} (ID: ${nextId}) start completed with exit code ${code}.\n`,
timestamp: Date.now()
});
}
resolve();
}
);
}));
}
// Step 5: Add to database
this.sendMessage(ws, {
type: 'output',
data: `\n[Step ${2 + cloneCount + 3}/${4 + cloneCount}] Adding cloned ${containerType.toUpperCase()}(s) to database...\n`,
timestamp: Date.now()
});
for (let i = 0; i < cloneCount; i++) {
const nextId = clonedIds[i];
const hostname = hostnames[i];
try {
// Read config file to get hostname/name (node-specific path)
const nodeName = server.name;
const configPath = containerType === 'lxc'
? `/etc/pve/nodes/${nodeName}/lxc/${nextId}.conf`
: `/etc/pve/nodes/${nodeName}/qemu-server/${nextId}.conf`;
let configContent = '';
await new Promise(/** @type {(resolve: (value?: void) => void) => void} */ ((resolve) => {
sshService.executeCommand(
server,
`cat "${configPath}" 2>/dev/null || echo ""`,
/** @param {string} data */
(data) => {
configContent += data;
},
() => resolve(),
() => resolve()
);
}));
// Parse config for hostname/name
let finalHostname = hostname;
if (configContent.trim()) {
const lines = configContent.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (containerType === 'lxc' && trimmed.startsWith('hostname:')) {
finalHostname = trimmed.substring(9).trim();
break;
} else if (containerType === 'vm' && trimmed.startsWith('name:')) {
finalHostname = trimmed.substring(5).trim();
break;
}
}
}
if (!finalHostname) {
finalHostname = `${containerType}-${nextId}`;
}
// Create installed script record
const script = await this.db.createInstalledScript({
script_name: finalHostname,
script_path: `cloned/${finalHostname}`,
container_id: nextId,
server_id: server.id,
execution_mode: 'ssh',
status: 'success',
output_log: `Cloned ${containerType.toUpperCase()}`
});
// For LXC, store config in database
if (containerType === 'lxc' && configContent.trim()) {
// Simple config parser
/** @type {any} */
const configData = {};
const lines = configContent.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const [key, ...valueParts] = trimmed.split(':');
const value = valueParts.join(':').trim();
if (key === 'hostname') configData.hostname = value;
else if (key === 'arch') configData.arch = value;
else if (key === 'cores') configData.cores = parseInt(value) || null;
else if (key === 'memory') configData.memory = parseInt(value) || null;
else if (key === 'swap') configData.swap = parseInt(value) || null;
else if (key === 'onboot') configData.onboot = parseInt(value) || null;
else if (key === 'ostype') configData.ostype = value;
else if (key === 'unprivileged') configData.unprivileged = parseInt(value) || null;
else if (key === 'tags') configData.tags = value;
else if (key === 'rootfs') {
const match = value.match(/^([^:]+):([^,]+)/);
if (match) {
configData.rootfs_storage = match[1];
const sizeMatch = value.match(/size=([^,]+)/);
if (sizeMatch) {
configData.rootfs_size = sizeMatch[1];
}
}
}
}
await this.db.createLXCConfig(script.id, configData);
}
this.sendMessage(ws, {
type: 'output',
data: `\nClone ${i + 1} (ID: ${nextId}, Hostname: ${finalHostname}) added to database successfully.\n`,
timestamp: Date.now()
});
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `\nError adding clone ${i + 1} (ID: ${nextId}) to database: ${error instanceof Error ? error.message : String(error)}\n`,
timestamp: Date.now()
});
}
}
this.sendMessage(ws, {
type: 'output',
data: `\n\n[Clone operation completed successfully!]\nCreated ${cloneCount} clone(s) of ${containerType.toUpperCase()} ${containerId}.\n`,
timestamp: Date.now()
});
this.activeExecutions.delete(executionId);
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `\n\n[Clone operation failed!]\nError: ${error instanceof Error ? error.message : String(error)}\n`,
timestamp: Date.now()
});
this.activeExecutions.delete(executionId);
}
}
/**
* Start update execution (pct enter + update command)
* @param {ExtendedWebSocket} ws
* @param {string} containerId
* @param {string} executionId
* @param {string} mode
* @param {ServerInfo|undefined} server
* @param {string} [backupStorage] - Optional storage to backup to before update
*/
async startUpdateExecution(ws, containerId, executionId, mode = 'local', server = undefined, backupStorage = undefined, envVars = {}) {
try {
// If backup storage is provided, run backup first
if (backupStorage && mode === 'ssh' && server) {
this.sendMessage(ws, {
type: 'start',
data: `Starting backup before update for container ${containerId}...`,
timestamp: Date.now()
});
// Create a separate execution ID for backup
const backupExecutionId = `backup_${executionId}`;
// Run backup and wait for it to complete
try {
const backupResult = await this.startSSHBackupExecution(
ws,
containerId,
backupExecutionId,
backupStorage,
server
);
// Backup completed (successfully or not)
if (!backupResult || !backupResult.success) {
// Backup failed, but we'll still allow update (per requirement 1b)
this.sendMessage(ws, {
type: 'output',
data: '\n⚠ Backup failed, but proceeding with update as requested...\n',
timestamp: Date.now()
});
} else {
// Backup succeeded
this.sendMessage(ws, {
type: 'output',
data: '\n✅ Backup completed successfully. Starting update...\n',
timestamp: Date.now()
});
}
} catch (error) {
console.error('Backup error before update:', error);
// Backup failed to start, but allow update to proceed
this.sendMessage(ws, {
type: 'output',
data: `\n⚠️ Backup error: ${error instanceof Error ? error.message : String(error)}. Proceeding with update...\n`,
timestamp: Date.now()
});
}
// Small delay before starting update
await new Promise(resolve => setTimeout(resolve, 1000));
}
// Send start message for update (only if we're actually starting an update)
this.sendMessage(ws, {
type: 'start',
data: `Starting update for container ${containerId}...`,
timestamp: Date.now()
});
if (mode === 'ssh' && server) {
await this.startSSHUpdateExecution(ws, containerId, executionId, server, envVars);
} else {
await this.startLocalUpdateExecution(ws, containerId, executionId, envVars);
}
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `Failed to start update: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
}
}
/**
* Start local update execution
* @param {ExtendedWebSocket} ws
* @param {string} containerId
* @param {string} executionId
*/
async startLocalUpdateExecution(ws, containerId, executionId, envVars = {}) {
const { spawn } = await import('node-pty');
// Create a shell process that will run pct enter and then update
const childProcess = spawn('bash', ['-c', `pct enter ${containerId}`], {
name: 'xterm-color',
cols: 80,
rows: 24,
cwd: process.cwd(),
env: process.env
});
// Store the execution
this.activeExecutions.set(executionId, {
process: childProcess,
ws
});
// Handle pty data
childProcess.onData((data) => {
this.sendMessage(ws, {
type: 'output',
data: data.toString(),
timestamp: Date.now()
});
});
// Build env export commands (e.g. for PHS_SILENT=1)
const envExports = Object.entries(envVars)
.filter(([key]) => key.startsWith('PHS_') || key.startsWith('var_'))
.map(([key, value]) => {
const safeValue = String(value)
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"');
return `export ${key}="${safeValue}"`;
})
.join('; ');
// Send the update command after a delay to ensure we're in the container
setTimeout(() => {
if (envExports) {
childProcess.write(`${envExports}; update\n`);
} else {
childProcess.write('update\n');
}
}, 4000);
// Handle process exit
childProcess.onExit((e) => {
this.sendMessage(ws, {
type: 'end',
data: `Update completed with exit code: ${e.exitCode}`,
timestamp: Date.now()
});
this.activeExecutions.delete(executionId);
});
}
/**
* Start SSH update execution
* @param {ExtendedWebSocket} ws
* @param {string} containerId
* @param {string} executionId
* @param {ServerInfo} server
*/
async startSSHUpdateExecution(ws, containerId, executionId, server, envVars = {}) {
const sshService = getSSHExecutionService();
try {
const execution = await sshService.executeCommand(
server,
`pct enter ${containerId}`,
/** @param {string} data */
(data) => {
this.sendMessage(ws, {
type: 'output',
data: data,
timestamp: Date.now()
});
},
/** @param {string} error */
(error) => {
this.sendMessage(ws, {
type: 'error',
data: error,
timestamp: Date.now()
});
},
/** @param {number} code */
(code) => {
this.sendMessage(ws, {
type: 'end',
data: `Update completed with exit code: ${code}`,
timestamp: Date.now()
});
this.activeExecutions.delete(executionId);
}
);
// Store the execution
this.activeExecutions.set(executionId, {
process: /** @type {any} */ (execution).process,
ws
});
// Build env export commands (e.g. for PHS_SILENT=1)
const envExports = Object.entries(envVars)
.filter(([key]) => key.startsWith('PHS_') || key.startsWith('var_'))
.map(([key, value]) => {
const safeValue = String(value)
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"');
return `export ${key}="${safeValue}"`;
})
.join('; ');
// Send the update command after a delay to ensure we're in the container
setTimeout(() => {
if (envExports) {
/** @type {any} */ (execution).process.write(`${envExports}; update\n`);
} else {
/** @type {any} */ (execution).process.write('update\n');
}
}, 4000);
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `SSH execution failed: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
}
}
/**
* Start shell execution
* @param {ExtendedWebSocket} ws
* @param {string} containerId
* @param {string} executionId
* @param {string} mode
* @param {ServerInfo|null} server
* @param {'lxc'|'vm'} [containerType='lxc']
*/
async startShellExecution(ws, containerId, executionId, mode = 'local', server = null, containerType = 'lxc') {
try {
const typeLabel = containerType === 'vm' ? 'VM' : 'container';
this.sendMessage(ws, {
type: 'start',
data: `Starting shell session for ${typeLabel} ${containerId}...`,
timestamp: Date.now()
});
if (mode === 'ssh' && server) {
await this.startSSHShellExecution(ws, containerId, executionId, server, containerType);
} else {
await this.startLocalShellExecution(ws, containerId, executionId, containerType);
}
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `Failed to start shell: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
}
}
/**
* Start local shell execution
* @param {ExtendedWebSocket} ws
* @param {string} containerId
* @param {string} executionId
* @param {'lxc'|'vm'} [containerType='lxc']
*/
async startLocalShellExecution(ws, containerId, executionId, containerType = 'lxc') {
const { spawn } = await import('node-pty');
const shellCommand = containerType === 'vm' ? `qm terminal ${containerId}` : `pct enter ${containerId}`;
const childProcess = spawn('bash', ['-c', shellCommand], {
name: 'xterm-color',
cols: 80,
rows: 24,
cwd: process.cwd(),
env: process.env
});
// Store the execution
this.activeExecutions.set(executionId, {
process: childProcess,
ws
});
// Handle pty data
childProcess.onData((data) => {
this.sendMessage(ws, {
type: 'output',
data: data.toString(),
timestamp: Date.now()
});
});
// Note: No automatic command is sent - user can type commands interactively
// Handle process exit
childProcess.onExit((e) => {
this.sendMessage(ws, {
type: 'end',
data: `Shell session ended with exit code: ${e.exitCode}`,
timestamp: Date.now()
});
this.activeExecutions.delete(executionId);
});
}
/**
* Start SSH shell execution
* @param {ExtendedWebSocket} ws
* @param {string} containerId
* @param {string} executionId
* @param {ServerInfo} server
* @param {'lxc'|'vm'} [containerType='lxc']
*/
async startSSHShellExecution(ws, containerId, executionId, server, containerType = 'lxc') {
const sshService = getSSHExecutionService();
const shellCommand = containerType === 'vm' ? `qm terminal ${containerId}` : `pct enter ${containerId}`;
try {
const execution = await sshService.executeCommand(
server,
shellCommand,
/** @param {string} data */
(data) => {
this.sendMessage(ws, {
type: 'output',
data: data,
timestamp: Date.now()
});
},
/** @param {string} error */
(error) => {
this.sendMessage(ws, {
type: 'error',
data: error,
timestamp: Date.now()
});
},
/** @param {number} code */
(code) => {
this.sendMessage(ws, {
type: 'end',
data: `Shell session ended with exit code: ${code}`,
timestamp: Date.now()
});
this.activeExecutions.delete(executionId);
}
);
// Store the execution
this.activeExecutions.set(executionId, {
process: /** @type {any} */ (execution).process,
ws
});
// Note: No automatic command is sent - user can type commands interactively
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `SSH shell execution failed: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
}
}
}
// TerminalHandler removed - not used by current application
app.prepare().then(() => {
console.log('> Next.js app prepared successfully');
const httpServer = createServer(async (req, res) => {
try {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url || '', true);
const { pathname, query } = parsedUrl;
// Check if this is a WebSocket upgrade request
const isWebSocketUpgrade = req.headers.upgrade === 'websocket';
// Only intercept WebSocket upgrades for /ws/script-execution
// Let Next.js handle all other WebSocket upgrades (like HMR) and all HTTP requests
if (isWebSocketUpgrade && pathname === '/ws/script-execution') {
// WebSocket upgrade will be handled by the WebSocket server
// Don't call handle() for this path - let WebSocketServer handle it
return;
}
// Let Next.js handle all other requests including:
// - HTTP requests to /ws/script-execution (non-WebSocket)
// - WebSocket upgrades to other paths (like /_next/webpack-hmr)
// - All static assets (_next routes)
// - All other routes
await handle(req, res, parsedUrl);
} catch (err) {
console.error('Error occurred handling', req.url, err);
res.statusCode = 500;
res.end('internal server error');
}
});
// Create WebSocket handlers
const scriptHandler = new ScriptExecutionHandler(httpServer);
// Handle WebSocket upgrades manually to avoid interfering with Next.js HMR
// We need to preserve Next.js's upgrade handlers and call them for non-matching paths
// Save any existing upgrade listeners (Next.js might have set them up)
const existingUpgradeListeners = httpServer.listeners('upgrade').slice();
httpServer.removeAllListeners('upgrade');
// Add our upgrade handler that routes based on path
httpServer.on('upgrade', (request, socket, head) => {
const parsedUrl = parse(request.url || '', true);
const { pathname } = parsedUrl;
if (pathname === '/ws/script-execution') {
// Handle our custom WebSocket endpoint
scriptHandler.handleUpgrade(request, socket, head);
} else {
// For all other paths (including Next.js HMR), call existing listeners
// This allows Next.js to handle its own WebSocket upgrades
for (const listener of existingUpgradeListeners) {
try {
listener.call(httpServer, request, socket, head);
} catch (err) {
console.error('Error in upgrade listener:', err);
}
}
}
});
// Note: TerminalHandler removed as it's not being used by the current application
httpServer
.once('error', (err) => {
console.error(err);
process.exit(1);
})
.listen(port, hostname, async () => {
console.log(`> Ready on http://${hostname}:${port}`);
console.log(`> WebSocket server running on ws://${hostname}:${port}/ws/script-execution`);
// Initialize auto sync module and run initialization
if (!autoSyncModule) {
try {
console.log('Dynamically importing autoSyncInit...');
autoSyncModule = await import('./src/server/lib/autoSyncInit.js');
console.log('autoSyncModule loaded, exports:', Object.keys(autoSyncModule));
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
console.error('Failed to import autoSyncInit:', err.message);
console.error('Stack:', err.stack);
throw error;
}
}
// Initialize default repositories
if (typeof autoSyncModule.initializeRepositories === 'function') {
console.log('Calling initializeRepositories...');
await autoSyncModule.initializeRepositories();
} else {
console.warn('initializeRepositories is not a function, type:', typeof autoSyncModule.initializeRepositories);
}
// Initialize auto-sync service
if (typeof autoSyncModule.initializeAutoSync === 'function') {
console.log('Calling initializeAutoSync...');
autoSyncModule.initializeAutoSync();
}
// Setup graceful shutdown handlers
if (typeof autoSyncModule.setupGracefulShutdown === 'function') {
console.log('Setting up graceful shutdown...');
autoSyncModule.setupGracefulShutdown();
}
});
}).catch((err) => {
console.error('> Failed to start server:', err.message);
console.error('> If you see "Could not find a production build", run: npm run build');
console.error('> Full error:', err);
process.exit(1);
});