Commit Graph

36 Commits

Author SHA1 Message Date
UNITRONIX 199a321fe5 Add peer metrics, PATCH updates & relay fixes
Introduce peer metrics persistence and partial peer updates, plus relay UUID recovery and soft-delete protections.

- DB: add PeerMetric type and new Database methods (SavePeerMetric, GetPeerMetrics, GetLatestPeerMetric, CleanupOldMetrics, UpdatePeerFields, IsPeerSoftDeleted). Add peer_metrics table and indexes in SQLite and PostgreSQL migrations; implement all methods for both backends.
- API: handleClientHeartbeat now parses cpu/memory/disk and saves metrics; new endpoints PATCH /api/peers/{id} to update note/user/tags and GET /api/peers/{id}/metrics for historical metrics. handleSetPeerTags now accepts either string or array JSON payloads. Added audit.ActionPeerUpdated.
- Signal server: add pendingRelayUUIDs store (with TTL cleanup, store/get helpers) to recover missing UUIDs from old clients when RelayResponse contains empty uuid; store pending UUIDs when forwarding RequestRelay/PunchHole. Add IsPeerSoftDeleted checks to reject re-registration of soft-deleted devices.
- Node.js panel: betterdeskApi.setPeerTags now sends tags as array and exposes updatePeer() for PATCH; serverBackend.updateDevice routes note/user updates through Go PATCH endpoint and preserves local auth.db writes as fallback; devices.routes deletes now call cleanupDeletedPeerData.
- dbAdapter: add cleanupDeletedPeerData implementations for SQLite and Postgres to remove related auth.db rows when a peer is deleted.

These changes fix zombie device re-registration, ensure metrics are stored & retrievable, centralize peer metadata updates through the Go API, and recover relay pairing failures with legacy clients.

Co-Authored-By: boruto79 <176351662+boruto79@users.noreply.github.com>
Co-Authored-By: БлагоЯр <3672314+blagoyar@users.noreply.github.com>
2026-03-18 22:09:48 +01:00
UNITRONIX c461a1aa13 Improve web client cursor, video and input handling
Fix several stability and UX issues in the web remote client: prevent ImageData crashes by validating and normalizing cursor bytes (skip zstd/compressed or truncated data) and wrapping updateCursor in try/catch; avoid unhandled promise rejections by adding a .catch() around renderer.updateCursor calls; reduce JMuxer-induced stutter and unnecessary seeks by increasing seek thresholds and offsets and tuning health-check intervals/playback-rate logic; send preferred FPS to the peer after login (default 30fps) and negotiate supported codecs dynamically based on WebCodecs/JMuxer availability; ensure focus management after login (blur hidden password input and focus canvas) and toggle a .streaming CSS class on the viewer container for cursor visibility. These changes improve robustness against malformed cursor payloads, reduce playback stutter, and improve input focus behavior.
2026-03-17 00:41:59 +01:00
UNITRONIX 60657da980 Add Address Book API, relay env & UI fixes
Implement address book support and related fixes: add address_books table and Get/SaveAddressBook to DB interface with SQLite/Postgres migrations and upsert, add handlers for /api/ab, /api/ab/personal and /api/ab/tags (GET/POST) and normalize/limit incoming data. Signal server: generate relay UUIDs, send RelayResponse (with UUID and signed PK) and forward RequestRelay to targets to ensure hbbr pairing. Docker/compose/supervisord/entrypoint: introduce RELAY_SERVERS env, expose it in Dockerfile and supervisord, add docker-compose hint, and add entrypoint auto-detection/warnings for public IP inside containers. Web UI fixes: align settings password field names and include confirmPassword, modal input supports inputType, fix change-id request body key, add i18n strings for device actions/errors, and improve device delete route error handling. Also update changelog (.github/copilot-instructions.md) and add some API logging and validations.
2026-03-16 22:30:44 +01:00
UNITRONIX 8a7fd86424 Fix relay IP detection, logging, and build scripts
Call startIPDetectionRetry and improve public IP detection to avoid returning an unusable bare :port; prefer LAN IP and log clear warnings when no public IP is available. Add retry goroutine (60s ticker) and extend detectPublicIP with HTTPS then HTTP fallbacks and longer timeout. Throttle frequent sysinfo log messages (per-device 5min cooldown) in heartbeat handler to prevent spam. Accept numeric IDs from RustDesk by coercing host_id/host_uuid/peer_id to strings in /api/audit/conn to fix 400 errors. Add force-recompile logic to PowerShell and shell install/update scripts so binaries are rebuilt when sources are newer (and expose ForceRecompile flag). Minor docs and .gitignore updates.
2026-03-15 19:50:57 +01:00
UNITRONIX e548f207bb Auto-generate API key + runtime reload on 401
Fix Docker single-container auth gap by ensuring an API key exists and is discoverable by both the Go server and Node.js console. Changes:
- betterdesk-server/main.go: loadAPIKey() now checks the server_config DB entry and, if absent, auto-generates a 32-byte hex API key, writes it to .api_key (with logging) and continues to sync to the DB.
- docker/entrypoint.sh: generates/persists a 32-byte hex API key at container startup (uses openssl with /dev/urandom fallback) and writes API_KEY env to file if provided.
- web-nodejs/services/betterdeskApi.js: adds fs import and an Axios 401 interceptor that reloads .api_key from disk once and retries the failed request to handle race conditions where the Go server generates the key after Node cached an empty value.
- .github/copilot-instructions.md: documents the Docker API key auto-generation (Phase 16) and related fixes.
- tasks/lessons.md and tasks/todo.md: add lightweight triage notes and actions.
This resolves the issue where the Devices page returned empty results due to missing X-API-Key in the single-container Docker setup and improves resilience during first-run key generation.
2026-03-15 19:20:11 +01:00
UNITRONIX 5b4408a190 Harden API/installer security & opt-in creds
Security hardening and installer fixes across the Go API, installers and Node console.

Key changes:
- WebSocket: removed InsecureSkipVerify and added API_WS_ALLOWED_ORIGINS allowlist (parsed in config) used by the API events WS endpoint.
- Node.js console: added HOST and API_HOST envs and used apiHost in the server; docker-compose and installer templates updated accordingly.
- Admin credentials: plaintext .admin_credentials persistence is now opt-in via STORE_ADMIN_CREDENTIALS (default false); installers and reset flows no longer persist creds unless explicitly enabled.
- Installer hardening: added sql_escape_literal for safe SQL literals, PostgreSQL identifier validation, and safer CREATE/ALTER/psql invocations; API key and password updates now pass secrets via environment variables to Python/Node fallbacks to avoid unsafe shell interpolation.
- Docker compose/scripts: preserve_compose_database_config to keep DB mode during regen, escaped API key insertion into sqlite, and various compose generation formatting fixes.
- Go toolchain & checks: go.mod toolchain set to go1.26.1 and installers now reject known-vulnerable Go 1.26.0 stdlib.
- Dependency: bumped web-nodejs tar override to ^7.5.11.

These changes reduce attack surface for cross-origin WS usage, eliminate unsafe credential persistence by default, and harden installer DB operations and password reset paths.
2026-03-15 14:53:55 +01:00
UNITRONIX 5676c6c65a Update TLS env handling and fix peer stats
Make the installer enable and propagate HTTPS settings to the Node.js console and systemd services when self-signed TLS certs are generated. Adds Update-EnvForTLS (PowerShell) and .env updates (bash) to set HTTPS_ENABLED, SSL_CERT_PATH, SSL_KEY_PATH, NODE_EXTRA_CA_CERTS and switch local API URLs to https. Systemd unit generation and do_configure_ssl now inject/sync HTTPS and cert paths (and NODE_EXTRA_CA_CERTS for self-signed CAs). Also fix a bug in web-nodejs/dbAdapter.getPeerStats by computing the total peer count so offline is calculated correctly.
2026-03-14 23:20:01 +01:00
UNITRONIX fc943e808d Streamline Docker builds, add .dockerignore
Add .dockerignore to trim Docker build context and exclude local artifacts (node_modules, dev files, secrets, runtime DBs, etc.). Simplify Dockerfiles: remove unnecessary sqlite-dev and rely on better-sqlite3's bundled SQLite; use npm install --production in build stages; copy application files first then overlay compiled node_modules from the builder to avoid local node_modules clobbering Alpine-compiled native modules. Update Docker console image similarly. Change supervisord to log to /dev/stdout and /dev/stderr so logs appear in docker logs. Remove explicit compose 'version' keys. Also set SQLite busy_timeout for main and auth DBs to reduce locking errors during concurrent access.
2026-03-14 23:05:02 +01:00
UNITRONIX e90a52a5e1 Await auth token validation calls
Make authenticateRequest and requireAuth async and add await before authService.validateAccessToken across multiple routes (e.g. /api/ab, /api/audit, /api/users, /api/peers, /api/currentUser). Also await authService.revokeClientTokens during logout. These changes ensure promised-based token validation is awaited to avoid race conditions and incorrect auth behavior.
2026-03-14 18:31:22 +01:00
UNITRONIX 6785063faa Serialize TOTP recovery codes before saving
Convert recovery code arrays to JSON strings before storing in the database to ensure consistent storage across adapters. Updates enableTotp and useRecoveryCode in both SQLite and Postgres adapters (web-nodejs/services/dbAdapter.js) to stringify arrays while leaving existing strings untouched.
2026-03-14 12:20:18 +01:00
UNITRONIX 556fad94bf Validate SQL identifiers and safer CPU parsing
Add safeIdentifier checks to SQLite code paths to validate table/column names (letters, digits, underscores, max 64 chars) and guard PRAGMA queries in betterdesk-server/db/sqlite.go and tools/migrate/main.go to reduce injection/invalid identifier risks. Replace a complex CPU regex in web-nodejs/routes/rustdesk-api.routes.js with a comma-split parsing approach to avoid ReDoS/backtracking and more robustly extract name, GHz and core counts. Also add clarifying comments in the Dockerfile about supervisord running services as non-root 'betterdesk' user.
2026-03-14 02:26:45 +01:00
UNITRONIX db46242023 Preserve DB config, PG compatibility & logging
Preserve existing DB config during update/repair and add PostgreSQL compatibility and reliability fixes. Added preserve_database_config()/Preserve-DatabaseConfig and invoked them before console reinstall in betterdesk.sh and betterdesk.ps1 to avoid unintentionally switching PostgreSQL → SQLite. Fixed folder/user route responses to use result.id (Postgres-compatible) in web-nodejs routes. Added automatic TOTP column migrations for both SQLite and Postgres in web-nodejs/services/dbAdapter.js. Improved relay error logging and write-error handling in betterdesk-server/relay (server.go, ws.go). Updated docs and tooling: added SELinux troubleshooting (DOCKER_TROUBLESHOOTING.md), Windows build/usage notes for the migrate tool (README.md), and updated changelog/instructions (.github/copilot-instructions.md) and last-updated date.
2026-03-13 23:14:06 +01:00
UNITRONIX 447c22af48 SELinux volume helper, folder fixes, Synology docs
Add create_data_directory helper to prepare Docker data volumes with proper permissions and optional SELinux (svirt_sandbox_file_t) support, and use it in install/migrate flows with user guidance on failures. Add comprehensive SYNOLOGY_INSTALLATION.md with Synology/Portainer/container-manager/docker-compose setup, firewall, troubleshooting and update instructions. Update DB adapters (SQLite/Postgres) to treat device_folder_assignments as the single source of truth: clear assignments on folder delete, stop writing folder_id into peer table, and make getUnassignedDeviceCount resilient by trying 'peers' then 'peer' schemas and returning -1 on error. Minor UI tweaks: add console.error on folder assignment failure and add WIP banners/margin adjustments to remote viewer pages.
2026-03-13 00:45:53 +01:00
UNITRONIX d717331041 Save credentials, handle paths, track folders
Multiple updates to improve cross-platform path handling, credential persistence, and folder assignment tracking.

- betterdesk.ps1: Check both console and RustDesk credential locations when backing up; save reset admin password to both console and RustDesk locations, create console data dir if missing, and print info messages.
- web-nodejs/reset-password.js & scripts/reset-password.js: Use platform-aware default DB/data paths (Windows/Linux), consider extra env vars, and default to a data subdirectory when not found.
- web-nodejs/routes/rustdesk-api.routes.js: Await async generateAccessToken calls to ensure tokens are generated before continuing.
- web-nodejs/services/dbAdapter.js: Update assignDeviceToFolder for SQLite and Postgres to maintain a device_folder_assignments table (insert/update or delete as appropriate) and remove assignments when folders are deleted; also fix a Postgres JSONB cast.

These changes unify credential storage, improve Windows support, fix an async bug, and add explicit folder assignment tracking used by getAllFolderAssignments.
2026-03-09 23:30:33 +01:00
UNITRONIX d2faa79477 Allow fallthrough for /api/users and /api/peers
Detect absent Bearer tokens in RustDesk API handlers and fall through to panel routes. Updated rustdesk-api.routes.js to accept next(), extract the Bearer token, call next('route') when no token is present so session-cookie-based panel requests reach their intended handlers, and return a clearer error for invalid tokens. Also updated .github/copilot-instructions.md changelog to record the fix (Phase 10) and update the last-modified date.
2026-03-08 12:51:23 +01:00
UNITRONIX 36365b4573 Docs: rename HBBS to BetterDesk, add client API
Rename HBBS configuration and docs to BETTERDESK (HBBS_API_URL/HBBS_API_KEY -> BETTERDESK_API_URL/BETTERDESK_API_KEY) and update web-nodejs README to use the new env var and API client name (hbbsApi.js -> betterdeskApi.js). Add a RustDesk Client Endpoints section documenting compatibility endpoints (login, ab, heartbeat, sysinfo, etc.) served on the management API port (21114). Clarify project status as a clean-room implementation, document the archive/ directory policy (AGPL legacy code excluded from releases), include a trademark notice for RustDesk, and add a commercial licensing note.
2026-03-06 23:54:28 +01:00
UNITRONIX 6f5c6b09bb Switch to Apache-2.0, update docs & Dockerfiles
Replace AGPL-3.0 with Apache License 2.0 across the repository and update related documentation and metadata. Remove legacy RustDesk-specific architecture docs, delete deprecated Dockerfile.hbbr, rename Dockerfile.hbbs → Dockerfile.server and update docker-compose / install scripts to use it. Add Apache license headers to protobuf defs, remove obsolete web service (hbbsApi.js), and adjust README, CONTRIBUTING and PROJECT_STRUCTURE to reflect the license and commercial/clean-room notices. Includes a small formatting tweak in client_api_handlers.go.
2026-03-06 23:45:46 +01:00
UNITRONIX 7605261a80 Add fallback for color sanitization
Add a _sanitizeColorFallback to provide a safe default ('#808080') when Utils.sanitizeColor is missing (older utils.js on server). Update folder rendering to use (Utils.sanitizeColor || _sanitizeColorFallback) to avoid runtime errors and ensure invalid or missing colors are handled gracefully.
2026-03-06 21:16:51 +01:00
UNITRONIX 35542b6088 Add folder device counts and tweak RustDesk API
• UI: Ensure folder counts update correctly — call updateFolderCounts after devices load, fix unassigned filtering, and compute per-folder counts from the devices array (web-nodejs/public/js/devices.js).
• API: Enrich folder objects with device_count by aggregating folder assignments (web-nodejs/routes/folders.routes.js).
• RustDesk compatibility: Add missing "grp" field to RustDesk user payloads in Go and JS, change /api/login-options responses to an empty string, and register POST /api/currentUser alongside GET to support client expectations (betterdesk-server and web-nodejs/rustdesk routes).
• Minor: Small comment formatting tweaks in server handlers.

These changes fix folder count display bugs in the web UI and align server responses with RustDesk client expectations.
2026-03-06 20:50:55 +01:00
UNITRONIX 4ed5888344 Expose peer platform and normalize status/os
Add a Platform field to peer JSON responses (list and get) so the frontend can read p.OS. Update serverBackend to overlay sysinfo from auth.db onto peers (hostname, platform, os, version) so richer client-reported data is available. Update frontend (deviceDetail.js, devices.js) to prefer platform or fallback to os, use that for platform icons/labels, and normalize status_tier to lowercase for consistent CSS classes and i18n keys (including status badge re-rendering). These changes ensure platform info is shown reliably and status styling/labels are consistent.
2026-03-06 02:06:51 +01:00
UNITRONIX 0496b1dbc4 Add client API, sysinfo endpoints and Docker
Add RustDesk-compatible client API and telemetry support and introduce a single-container Docker build. New client_api_handlers.go implements /api/login, /api/login-options, /api/logout, /api/currentUser, /api/ab, /api/heartbeat, /api/sysinfo and /api/sysinfo_ver with TOTP flow and an in-memory TFA session store; auth middleware and Server registration updated accordingly. Database interface and SQLite/Postgres implementations gain UpdatePeerSysinfo (with tests), audit actions for sysinfo, and handleGetPeer now returns live_online/live_status. Also add Dockerfile, docker-compose.single.yml, supervisord entrypoint, UI fixes (QR color inversion, 403 error view), labels file, README updates, and other ancillary changes.

Co-Authored-By: MrBrodacz - Design <215021251+MrBrodacz2025@users.noreply.github.com>
Co-Authored-By: boruto79 <176351662+boruto79@users.noreply.github.com>
Co-Authored-By: marcosacramento <marcosacramento@gmail.com>
Co-Authored-By: Charles Olivier Savignac <1275666+sircharlo@users.noreply.github.com>
2026-03-06 01:08:10 +01:00
UNITRONIX f3ad154e7a Force admin password update and CSRF fixes
Ensure freshly generated admin passwords are actually applied on reinstall and make CSRF handling more robust. Install scripts (Docker, POSH, sh) now remove stale auth.db from the console_data/data volume or data dir and create a .force_password_update sentinel (Docker also sets FORCE_PASSWORD_UPDATE=true) so the Node.js console will force-update the admin password. web-nodejs/services/authService.js adds checkForcePasswordUpdate() (env var or sentinel) and will forcibly update the admin bcrypt hash when requested; sentinel files are removed after detection. CSRF middleware now only generates tokens for safe methods (GET/HEAD/OPTIONS), avoids interfering with state-changing requests, and clears corrupt cookies using consistent options (httpOnly, sameSite: 'lax', secure based on config) to prevent spurious 403s. server.js mounts rustdeskApiRoutes before CSRF so bearer-token desktop clients are not blocked by cookie-based CSRF. Also unified the health check path from /api/health to /health in diagnostics checks and added required fs/path imports.

Co-Authored-By: MrBrodacz - Design <215021251+MrBrodacz2025@users.noreply.github.com>
Co-Authored-By: boruto79 <176351662+boruto79@users.noreply.github.com>
2026-03-05 22:42:14 +01:00
UNITRONIX 3f8e731db8 Add LAN relay, peer sync, QR & SSL updates
Multiple improvements across server, scripts and console:

- DB: add totp_recovery_codes column to users (Postgres + SQLite) and migration entries.
- Signal server: implement LAN-aware logic (isSameNetwork), detect LAN IP, add getLANRelayServer, use LAN relay for punchhole/relay flows, and enhance RelayResponse handling (IP-based sender lookup). Matches Rust hbbs behavior for local /24 detection.
- Node.js console: add server config QR generation (rustdesk://config/<b64-json>), fix address-book endpoints to safely return JSON strings, and implement Go↔Node peer sync bridges for both SQLite and Postgres (sync peers from Go 'peers' table into console 'peer' table with fallbacks).
- Scripts: update firewall port lists and add SSL-aware .env handling (switch HBBS/BETTERDESK API URLs to https when enabling TLS, set NODE_EXTRA_CA_CERTS for self-signed certs), and restart both server and console services after changes.

These changes improve LAN connectivity, keep the web console in sync with the Go signal server, and ensure console/server URLs and firewall rules match TLS configuration.

Co-Authored-By: MrBrodacz - Design <215021251+MrBrodacz2025@users.noreply.github.com>
Co-Authored-By: boruto79 <176351662+boruto79@users.noreply.github.com>
2026-03-05 21:43:32 +01:00
UNITRONIX f239f791fd Enhance diagnostics, API checks, TOTP updates
betterdesk.sh: Improve diagnostics and DB visibility by detecting DB type (SQLite vs PostgreSQL), masking passwords in DATABASE_URL, and reporting PostgreSQL counts via psql when available. Add clearer messages when SQLite file is missing and list DB type in diagnostics. Detect Go server TLS via systemd service args, switch API health checks to /api/health, default API port to 21114, and warn about TLS/HTTP mismatches between server and console. Also update service identifier strings in port definitions.

web-nodejs/middleware/security.js: Add browsing-topics to Permissions-Policy header to suppress Chrome warnings.

web-nodejs/routes/auth.routes.js: Fix async handling by awaiting authService methods (verifyRecoveryCode, verifyTotpCode, isTotpEnabled, verifyAndEnableTotp, disableTotp) and replace direct bcrypt compare with authService.verifyPassword to support multiple hash schemes. Make TOTP status endpoint async with error handling.

Overall: adds better runtime diagnostics, TLS mismatch detection, and fixes asynchronous/auth verification bugs.
Co-Authored-By: MrBrodacz - Design <215021251+MrBrodacz2025@users.noreply.github.com>
Co-Authored-By: boruto79 <176351662+boruto79@users.noreply.github.com>
2026-03-05 01:22:40 +01:00
UNITRONIX edba7c5da6 Improve password reset, auth logging, and i18n
Rework password reset flow and diagnostics: change reset-password.js argument order (password first, optional username) and update Docker/CLI scripts to call it accordingly; persist DEFAULT_ADMIN_PASSWORD to .env and restart betterdesk-console after resets to avoid overwrites. Add translations for an "invalid_credentials" message across supported locales. Harden reset-password.js with a bcrypt self-test, log hash info, and add additional data directory candidates. Enhance authService with detailed auth/logging (hash type, failures/success), safer admin-hash migration logic (avoid overwriting if admin has logged in), and self-tests when creating/updating admin password hashes to detect/retry corrupted hashes.

Co-Authored-By: MrBrodacz - Design <215021251+MrBrodacz2025@users.noreply.github.com>
Co-Authored-By: boruto79 <176351662+boruto79@users.noreply.github.com>
2026-03-05 00:55:58 +01:00
UNITRONIX aa9424845a Support Postgres, API key sync, and auth migration
Add PostgreSQL support for the web console password reset and install scripts, and improve cross-language auth handling.

Key changes:
- Introduce a unified reset-password.js that supports SQLite and PostgreSQL (reads DB_TYPE / DATABASE_URL) and make shell/PowerShell/Docker helpers prefer it with fallbacks.
- Update betterdesk-server to load an API key from API_KEY or .api_key (key/db dirs) and sync it into the database so Go server and Node console share the same key.
- Adjust docker-compose default command to run the all-in-one mode and point at the bundled DB/key paths.
- Improve dashboard health checks to avoid raw TCP probes in single-binary BetterDesk mode and derive signal/relay status from the API health; allow /api/currentUser to accept POST as well as GET.
- Enhance authService to recognize Go-style PBKDF2 hashes, verify them, auto-migrate verified PBKDF2 hashes to bcrypt, and migrate default admin if needed.

These changes improve interoperability between the Go server and Node console (shared API key and DB modes), add Postgres support for admin tooling, and provide a smooth auth migration path from the Go server's hashing scheme to bcrypt.

Co-Authored-By: MrBrodacz - Design <215021251+MrBrodacz2025@users.noreply.github.com>
2026-03-05 00:21:56 +01:00
UNITRONIX bc45956bb7 TCP/WS signaling fixes; branding & DB refactor
Make TCP and WebSocket signal handling consistent with UDP by sending immediate PunchHoleResponse/RelayResponse (including signed PK, socket_addr, relay server and NAT type) to initiators; add ForceRelay/AlwaysUseRelay handling and ensure WS uses TCP handler. Sign peer PKs for E2E verification and keep TCP keep-alive behavior for later updates.

Refactor web-nodejs branding and backup/database code: introduce async branding cache (loadBranding) and async save/reset/import APIs, add branding_config table and DB adapter methods (SQLite/Postgres) plus backup helper methods (getAllUsersForBackup, getAllAddressBooks, restoreUsers, getBackupStats). Update routes/services to use new async DB APIs, warm branding cache at server startup, and adjust heartbeat/register flows to use db helpers. Minor server error page i18n fallbacks and hbbs backend compatibility guard updated.

Also update docs (.github/copilot-instructions.md) to record the TCP signaling fix and Phase 7 resolution.

Co-Authored-By: Charles Olivier Savignac <1275666+sircharlo@users.noreply.github.com>
2026-03-04 22:58:35 +01:00
UNITRONIX 00451634c7 Await DB operations in route handlers
Convert many Express route handlers and helper functions to async and await database calls (e.g. getAccessToken, touchAccessToken, getPeerById, getDevice, getPeerSysinfo, upsertPeerSysinfo, logAction, insertAudit*, getAll*/count* etc.). Also made identifyDevice and several route callbacks async, adjusted session.regenerate callback to use async logging, and replaced db.getDatabase() usage with db.getDb() where applicable. These changes ensure DB operations complete before responding and reduce race conditions/unhandled-promise behavior across numerous route files (activity, auth, automation, bd-api, devices, folders, i18n, inventory, registration, remote, rustdesk-api, and related route handlers).

Co-Authored-By: Charles Olivier Savignac <1275666+sircharlo@users.noreply.github.com>
2026-03-03 22:57:10 +01:00
UNITRONIX 5784fc5365 fix: enforce ban across all connection paths (signal, relay, WS, Client API)
Critical security fix  banning a device in the web console now actually
blocks that device from:

Go Server (signal/handler.go):
- handleRegisterPeer: reject banned peers on UDP heartbeat
- handleRegisterPeer: check DB IsPeerBanned for new peer registration
- handlePunchHoleRequestTCP: reject connections to banned targets
- handleRequestRelay (UDP): reject relay to banned targets
- handleRequestRelayTCP: reject relay to banned targets

Go Server (signal/ws.go):
- handleRegisterPeerWS: reject banned peers on WS heartbeat
- handleRegisterPeerWS: check DB for new WS registrations

Go Server (api/server.go):
- handleBanPeer: remove peer from memory map (immediate disconnect)
- handleBanPeer: update DB peer status to OFFLINE

Node.js Client API (rustdesk-api.routes.js):
- POST /api/heartbeat: reject heartbeats from banned devices
- POST /api/sysinfo: reject sysinfo from banned devices
- POST /api/login: reject login from banned devices

Root cause: ban flag (entry.Banned / is_banned) was correctly stored in
database and memory but never checked in any signal handler. The signal
handler only checked the separate blocklist system (IsIPBlocked/IsIDBlocked)
which is a completely different feature. Banned peers continued to register,
heartbeat, and participate in PunchHole/Relay operations normally.

Added test: TestBanRemovesPeerFromMap verifies end-to-end that banning via
API removes the peer from the in-memory map and sets OFFLINE status.
2026-03-02 22:46:31 +01:00
UNITRONIX 8d952e4ba1 Add password auth helpers; remove legacy dev scripts
Add a new auth package implementing password hashing/verification (PBKDF2-HMAC-SHA256), a random-string generator, and unit tests. Update .gitignore to catch additional sensitive filenames and to ignore legacy dev scripts, migrations, templates and build artifacts. Remove many legacy/dev helper scripts (dev_modules/, scripts/legacy/, build_windows.sh, migrations/, templates/) and add web-nodejs reset-password scripts and a session secret placeholder. Changes consolidate authentication utilities and clean up old/unused development tooling and noise in the repo.
2026-03-02 07:59:24 +01:00
UNITRONIX e855f5786d Add Go server and security audit; update web console
Add a new betterdesk-server Go codebase (server, api, auth, db, relay, signal, metrics, audit, ratelimit, proto, tools, tests) and related deployment/migration scripts. Add a comprehensive SECURITY_AUDIT_2026-03-01 report and .gitattributes; update copilot-instructions (ALL-IN-ONE v2.4.0), README, VERSION, Dockerfiles, scripts, docker-compose and entrypoint. Large updates to web-nodejs (translations, routes, services, frontend assets and middleware) and numerous new utilities; remove legacy Flask web files and archive hbbs-patch-v2 artifacts. Prepares repository for PostgreSQL support, DB migration tooling and the new Go server as the production backend.
2026-03-02 00:43:04 +01:00
UNITRONIX 49241ed20e Bump server to v2.1.3 and add firewall checks
Release-related update to v2.1.3: replace hbbs/hbbr binaries and update all SHA256 checksums and CHECKSUMS.md. Add robust firewall/port diagnostics and auto-configuration: implements firewall rule checks and creation in betterdesk.ps1 and betterdesk.sh, enhances diagnostics (port conflict detection, external port test) and introduces Check-PortStatus/Configure-Firewall helpers. Make HBBS API key path flexible in Rust (env var / Windows-friendly .api_key fallback) and persist permissions correctly. Node.js console: load .env as a fallback for Windows NSSM, make KEYS_PATH default to C:\BetterDesk on Windows, improve JSON parsing for login/TOTP responses, ensure API routes return JSON on errors, and add periodic HBBS online-status sync. Misc: update server/client API port to include 21121 (client API), adjust docs, and minor service/env environment improvements for NSSM/systemd.

Co-Authored-By: PlasmPlayer <153363510+PlasmPlayer@users.noreply.github.com>
Co-Authored-By: boruto79 <176351662+boruto79@users.noreply.github.com>
Co-Authored-By: MrBrodacz - Design <215021251+MrBrodacz2025@users.noreply.github.com>
2026-02-24 00:01:44 +01:00
UNITRONIX 6ccf7c6130 Add Docker migration and branding UI
Introduce an interactive Docker migration flow and branding/theme support. Adds automatic/manual RustDesk-to-BetterDesk migration logic and menu option (betterdesk-docker.sh), plus a full migration guide (docs/DOCKER_MIGRATION.md) and README updates. Switches project license references to AGPL-3.0 and updates LICENSE locations for hbbs patches. Web console enhancements: new branding service and default theme, i18n middleware now injects branding, extended translations (en/pl), settings UI/JS and CSS for branding/theming, and login JS updated to include CSRF token. Also includes various view/template updates to surface branding across the UI.
2026-02-22 15:22:44 +01:00
UNITRONIX 12d195ff78 Release v2.3.0: Node.js console & security
Bump to v2.3.0 and switch to Node.js web console as the primary console (Flask deprecated). Add comprehensive security and feature updates: CSRF protection, session-fixation prevention, timing-safe auth, WebSocket auth, TOTP 2FA, operator/admin roles, address-book sync, desktop connect (URI handler), and SSL certificate configuration in installers. Introduce a dedicated RustDesk Client API (WAN port 21121) and related web-nodejs middleware, routes, views, protos, and client JS (rdclient) plus vendor libs. Add developer tooling and scripts (dev_modules), update hbbs-patch-v2 Rust sources, README and changelog/docs, and ignore Node.js artifacts in .gitignore.
2026-02-22 03:44:00 +01:00
UNITRONIX fd217bc385 Bump to v2.2.1: Node.js console env/admin fixes
Bump release to v2.2.1 and fix Node.js web-console installation and update flow. Changes include: generate and persist a random DEFAULT_ADMIN_PASSWORD for the Node.js console, always write a .env with corrected path variables (RUSTDESK_DIR/KEYS_PATH/DB_PATH/DATA_DIR/HBBS_API_URL), save admin creds to .admin_credentials and display them after install/update, load .env from systemd using EnvironmentFile and expose needed envs in the service unit, and ensure Do-Update installs services and creates the admin. The create_admin_user logic now detects Node.js vs Flask consoles (reading stored Node.js creds or creating Flask DB user). Also update web-nodejs config to accept multiple env var names and use a safe default for KEYS_PATH, and refresh project docs/version metadata.
2026-02-17 21:53:24 +01:00
UNITRONIX 32e29723e4 Add Node.js web console and update to v2.2.0
Introduce a new Node.js-based web console (Express + EJS + better-sqlite3) under web-nodejs/ and add installer support to choose between Node.js and the legacy Flask console. Update interactive ALL-IN-ONE installers (betterdesk.sh, betterdesk.ps1) with flags/options for --nodejs/--flask, automatic Node.js installation, migration logic, enhanced service handling and diagnostics. Bump VERSION to 2.2.0 and update README and project docs (.github/copilot-instructions.md) to reflect the new console, usage examples, and Docker/docs changes. Many new web-nodejs files and supporting middleware/services/routes/views/static assets were added to support the new console.
2026-02-17 10:59:46 +01:00