Commit Graph

20 Commits

Author SHA1 Message Date
UNITRONIX e556b181df Gate agent admin UI by OS privileges
Add OS-level admin detection and use it to gate sensitive agent UI and tray actions. Introduce privileges.rs (Windows TokenElevation / Unix geteuid) and expose is_os_admin as a Tauri command; wire it into tray setup to hide admin-only menu items (Settings, Quit) and re-check privileges before executing those actions. Add show_window helper and emit navigate events from the tray; frontend listens for navigate and conditionally renders /settings (shows AdminRequired component for non-admins). Update App.tsx to query is_os_admin on startup and include navigation listener; add AdminRequired component, styles, and i18n keys. Update Cargo.toml with platform deps (windows features + libc for unix). Also add UI/locale assets and CSS for agent lazy-loaded device tabs and a notifications dropdown, plus several web-nodejs route/view/style updates and new task docs describing phase work.
2026-04-18 01:18:57 +02:00
UNITRONIX 7b453d852f Security hardening and audit cleanup
Multiple security and maintenance fixes across components:

- betterdesk-mgmt: validate peer_id format to prevent injection in connect_to_peer (reject empty/oversized/invalid chars).
- betterdesk-mgmt (tauri.conf.json): tighten CSP by removing 'unsafe-eval' from script-src.
- betterdesk-agent-client: increase device ID entropy from 4 to 8 bytes (BD- prefix) to reduce collision/brute-force risk.
- betterdesk-server: enforce RBAC (operator+) before upgrading CDAP video WebSocket to block unauthorized access.
- betterdesk-server DBs: exclude soft_deleted peers in GetPeer queries for Postgres and SQLite.
- web-nodejs: add audit log housekeeping (hourly cleanup), add indices for audit_log, and implement cleanupOldAuditLogs(days) in sqlite adapter.
- web-nodejs brandingService: validate logo/favicon URLs to allow only http(s) or relative paths, preventing javascript:/data: XSS/SSRF vectors.
- docs: add AUDIT_BETTERDESK_2026-04-17.md (security audit summary).

These changes tighten client CSP, improve input validation, increase device identifier entropy, ensure RBAC is enforced before websocket upgrades, hide soft-deleted peers from normal queries, and add audit log maintenance and DB indexes for better performance and retention management.
2026-04-17 23:21:11 +02:00
UNITRONIX a710580b7a Add RBAC permissions UI and server handlers
Implement RBAC Phase 52: add server-side role & permission handlers and wire API routes, plus frontend UI, styles and translations.

Server: new role_handlers.go exposing endpoints to list roles, get effective role permissions, list/set/delete role permission overrides; routes registered in server.go with permission checks (PermUserView / PermServerConfig). Protects super-admin defaults and validates inputs.

Frontend (management & web UI): add permissions page assets (CSS, JS, view), add i18n strings for en/pl/zh, update sidebar to filter items by canView, show user role badge in topbar and empty access-denied state when no permission. Add role badges styling in users.css and small UX/i18n improvements in organizationDetail.js.

Also several route and service adjustments to support the new permissions UI. This change introduces RBAC UI/API plumbing for managing role-based permissions and overrides.
2026-04-11 00:47:08 +02:00
UNITRONIX 45e5fda9d0 Implement RBAC v52, org scoping and assorted fixes
Adds a full Phase-52 RBAC implementation and multiple server/frontend fixes. Key changes: new auth/permissions.go with 28 granular permissions and DefaultRolePermissions, expanded 7-role hierarchy and helpers in auth/roles.go, JWT org context and GenerateOrgToken, requirePermission/requireOrgMembership middlewares (Go + Node.js), DB schema & adapter changes for role_permissions and is_server_admin, org role boundary checks and peer org scoping, and guards for last-admin demotion and self-demotion. Also: TCP EOF/connection-reset log filtering in signal/relay servers, improved startup banner port display, KEYS_PATH auto-detect warning, CSS hover/transition layout fixes, admin password race mitigation, ID-change ghost peer cleanup, added Tauri ACL schema files, and a new RBAC_PHASE52.md doc. Misc: numerous web-nodejs i18n, CSS, JS and route updates and an updated .github/copilot-instructions.md timestamp/summary.
2026-04-10 23:40:55 +02:00
UNITRONIX a87654ce5e fix: move auth.db migration to ensureAuthTables + MGMT client improvements
- Fix critical SQLite migration bug: auth.db column migrations (last_login,
  totp_*, settings.updated_at) were in ensureInventoryTables() which receives
  main DB handle — PRAGMA table_info(users) returned empty on main DB, so
  ALTER TABLE never executed. Moved to ensureAuthTables() (auth DB handle).
- Add migration logging (console.log for each added column)
- Add branding_config.updated_at migration
- Fix bd-api.routes.js: session cookie fallback auth for desktop client
- Fix auth.routes.js: rate limiter improvements
- MGMT client: add logging module, improve auth store with TOTP + token
  acquisition, enhance RemoteView with session logging, improve relay
  connection handling in bd_relay.rs
2026-04-09 10:13:08 +02:00
UNITRONIX 9436e90f8a Fix user ID type mismatch causing broken buttons (#85)
- users.js: Change parseInt(userId, 10) to Number() on both sides of
  comparison to handle BigInt/string/number ID types correctly
- dbAdapter.js: Wrap all lastInsertRowid with Number() to prevent
  BigInt leak from better-sqlite3 v9+ (BigInt === Number is always false)

Root cause: better-sqlite3 v9+ returns lastInsertRowid as BigInt.
If user objects with BigInt IDs ended up in the users array, strict
equality (===) with parseInt result (Number) always fails silently,
making edit/reset-password/delete buttons appear unresponsive.
2026-04-06 21:07:40 +02:00
UNITRONIX dd0889e3d6 Add SessionManager; update docs, i18n & CI
Introduce a SessionManager for relay-based remote sessions in the Tauri MGMT client: new SessionCommand API, start/stop/session input routing, clipboard/recording/quality controls, and notification read/dismiss state. Wire AppState with new mutexes and show main window on startup. CI: add SBOM generation (anchore) and Trivy vulnerability scan steps. Misc: change console Docker DB path, large README/CHANGELOG updates (chat E2E, unattended access/WOL, i18n expansion, CDAP/SDK docs), and many web-nodejs assets/locales/routes/views/services and server-side changes.
2026-04-05 13:42:07 +02:00
UNITRONIX 1e2047c033 BetterDesk 3.0.0 Alpha 2026-03-24 00:26:25 +01:00
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 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 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 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 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 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 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 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