feat(guest): enforce scoped guest access lifecycle

Bind guest WebSocket sessions to a single target peer, enforce grant lifecycle and atomic usage, add the guest issuer scope, and document the password-less security boundary.\n\nRefs #440\n\nThanks: INSOLVE (Honorary); Marco Jakobs (@jacotec); MyNameisStitch (@MyNameisStitch); Redspin (@playerumpknow)
This commit is contained in:
UNITRONIX
2026-10-03 10:22:20 +02:00
parent 343dd5d20e
commit abc00b8804
43 changed files with 3009 additions and 96 deletions
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
# GitHub Actions does not configure core.hooksPath from this repository.
# Keep this guard so an explicitly configured CI checkout never runs the
# local-only gate.
if [[ "${CI:-}" == "true" || "${GITHUB_ACTIONS:-}" == "true" ]]; then
printf '%s\n' "Skipping local-only BetterDesk gate in CI."
exit 0
fi
REPO_ROOT="$(git rev-parse --show-toplevel)"
cd "$REPO_ROOT"
if command -v node >/dev/null 2>&1; then
exec node scripts/local-gate.js
elif command -v node.exe >/dev/null 2>&1; then
exec node.exe scripts/local-gate.js
elif command -v powershell.exe >/dev/null 2>&1; then
exec powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass \
-File scripts/local-gate.ps1
else
printf '%s\n' "BLOCKED: Node.js or PowerShell is not available to run the local gate." >&2
exit 1
fi
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
# GitHub Actions does not configure core.hooksPath from this repository.
# Keep this guard so an explicitly configured CI checkout never runs the
# local-only gate.
if [[ "${CI:-}" == "true" || "${GITHUB_ACTIONS:-}" == "true" ]]; then
printf '%s\n' "Skipping local-only BetterDesk gate in CI."
exit 0
fi
REPO_ROOT="$(git rev-parse --show-toplevel)"
cd "$REPO_ROOT"
if command -v node >/dev/null 2>&1; then
exec node scripts/local-gate.js
elif command -v node.exe >/dev/null 2>&1; then
exec node.exe scripts/local-gate.js
elif command -v powershell.exe >/dev/null 2>&1; then
exec powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass \
-File scripts/local-gate.ps1
else
printf '%s\n' "BLOCKED: Node.js or PowerShell is not available to run the local gate." >&2
exit 1
fi
+1
View File
@@ -123,6 +123,7 @@ docs/_internal/
.coverage
htmlcov/
.pytest_cache/
.local-test-results/
test_*.sh
verify_*.sh
TESTING.local.md
+2 -1
View File
@@ -1185,7 +1185,8 @@ func (s *Server) authMiddleware(next http.Handler) http.Handler {
path == "/api/devices/register" || path == "/api/devices/register/status" ||
path == "/api/devices/self/access-policy" || path == "/api/devices/self/help-request" ||
path == "/api/devices/self/totp" ||
path == "/api/guest/access-links/validate" || path == "/api/guest/access-links/peers" {
path == "/api/guest/access-links/validate" ||
path == "/api/guest/access-links/peers" {
next.ServeHTTP(w, r)
return
}
+68 -4
View File
@@ -79,6 +79,70 @@ func (s *Server) handleGuestAccessValidate(w http.ResponseWriter, r *http.Reques
writeJSON(w, http.StatusOK, pub)
}
// POST /api/guest/access-links/consume
// Atomically consumes one use after the panel has accepted a guest session.
func (s *Server) handleGuestAccessConsume(w http.ResponseWriter, r *http.Request) {
var body struct {
Token string `json:"token"`
PeerID string `json:"peer_id"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
grant, err := s.guestAccessStore().Consume(body.Token, body.PeerID)
if err != nil {
writeJSON(w, http.StatusForbidden, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, guestaccess.ToPublic(grant))
}
// POST /api/guest/access-links/events
// Receives bridge lifecycle events from the authenticated panel proxy. Secrets
// are deliberately not accepted or persisted here.
func (s *Server) handleGuestAccessEvent(w http.ResponseWriter, r *http.Request) {
var body struct {
Event string `json:"event"`
GrantID string `json:"grant_id"`
PeerID string `json:"peer_id"`
SessionID string `json:"session_id"`
Transport string `json:"transport"`
SourceIP string `json:"source_ip"`
DurationMS int64 `json:"duration_ms"`
Reason string `json:"reason"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
if body.Event != "opened" && body.Event != "closed" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid guest event"})
return
}
if body.GrantID == "" || body.PeerID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "grant_id and peer_id required"})
return
}
action := audit.ActionGuestSessionOpened
if body.Event == "closed" {
action = audit.ActionGuestSessionClosed
}
details := map[string]string{
"grant_id": body.GrantID,
"peer_id": body.PeerID,
"session_id": body.SessionID,
"transport": body.Transport,
"source_ip": body.SourceIP,
"duration_ms": strconv.FormatInt(body.DurationMS, 10),
"reason": body.Reason,
}
if s.auditLog != nil {
s.auditLog.Log(action, body.SourceIP, body.PeerID, details)
}
writeJSON(w, http.StatusAccepted, map[string]bool{"recorded": true})
}
// GET /api/guest/access-links
func (s *Server) handleGuestAccessList(w http.ResponseWriter, r *http.Request) {
username := usernameFromRequest(r)
@@ -170,10 +234,10 @@ func (s *Server) handleGuestAccessPeers(w http.ResponseWriter, r *http.Request)
devices = append(devices, item)
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"valid": true,
"view_only": grant.ViewOnly,
"valid": true,
"view_only": grant.ViewOnly,
"expires_at": grant.ExpiresAt.Format(time.RFC3339),
"label": grant.Label,
"devices": devices,
"label": grant.Label,
"devices": devices,
})
}
+5 -3
View File
@@ -586,10 +586,12 @@ func (s *Server) Start(ctx context.Context) error {
mux.HandleFunc("GET /api/mesh/share/validate", s.handleMeshShareValidate)
// Guest Access Links (temporary RdClient allowlist links)
mux.HandleFunc("POST /api/guest/access-links", s.requirePermission(auth.PermDeviceConnect, s.handleGuestAccessCreate))
mux.HandleFunc("GET /api/guest/access-links", s.requirePermission(auth.PermDeviceConnect, s.handleGuestAccessList))
mux.HandleFunc("DELETE /api/guest/access-links/{id}", s.requirePermission(auth.PermDeviceConnect, s.handleGuestAccessRevoke))
mux.HandleFunc("POST /api/guest/access-links", s.requirePermission(auth.PermGuestCreate, s.handleGuestAccessCreate))
mux.HandleFunc("GET /api/guest/access-links", s.requirePermission(auth.PermGuestCreate, s.handleGuestAccessList))
mux.HandleFunc("DELETE /api/guest/access-links/{id}", s.requirePermission(auth.PermGuestCreate, s.handleGuestAccessRevoke))
mux.HandleFunc("GET /api/guest/access-links/validate", s.handleGuestAccessValidate)
mux.HandleFunc("POST /api/guest/access-links/consume", s.requirePermission(auth.PermGuestCreate, s.handleGuestAccessConsume))
mux.HandleFunc("POST /api/guest/access-links/events", s.requirePermission(auth.PermGuestCreate, s.handleGuestAccessEvent))
mux.HandleFunc("GET /api/guest/access-links/peers", s.handleGuestAccessPeers)
mux.HandleFunc("POST /api/mesh/devices/{id}/tcp", s.requirePermission(auth.PermDeviceConnect, s.handleMeshTcpRelay))
mux.HandleFunc("POST /api/mesh/devices/{id}/udp", s.requirePermission(auth.PermDeviceConnect, s.handleMeshUdpRelay))
+2
View File
@@ -69,6 +69,8 @@ const (
ActionOrgPeerCredentialSet Action = "org_peer_credential_set"
ActionOrgPeerCredentialClear Action = "org_peer_credential_clear"
ActionOrgPeerCredentialFetch Action = "org_peer_credential_fetch"
ActionGuestSessionOpened Action = "guest_session_opened"
ActionGuestSessionClosed Action = "guest_session_closed"
)
// Event represents a single audit log entry.
+6 -2
View File
@@ -12,6 +12,7 @@ const (
// Device permissions
PermDeviceView = "device.view"
PermDeviceConnect = "device.connect"
PermGuestCreate = "guest.create"
PermDeviceEdit = "device.edit" // notes, tags, display name
PermDeviceDelete = "device.delete" // soft-delete + revoke
PermDeviceBan = "device.ban" // ban/unban
@@ -71,7 +72,7 @@ const (
// AllPermissions is the complete list of permission strings for validation.
var AllPermissions = []string{
PermDeviceView, PermDeviceConnect, PermDeviceEdit, PermDeviceDelete,
PermDeviceView, PermDeviceConnect, PermGuestCreate, PermDeviceEdit, PermDeviceDelete,
PermDeviceBan, PermDeviceChangeID, PermDeviceConnectionMode,
PermUserView, PermUserCreate, PermUserEdit, PermUserDelete,
PermServerConfig, PermServerKeys, PermServerAttestation,
@@ -118,6 +119,7 @@ var DefaultRolePermissions = map[string]map[string]bool{
PermUserView, PermUserCreate, PermUserEdit, PermUserDelete,
PermOrgCreate, PermOrgEdit, PermOrgDelete, PermOrgManageUsers, PermOrgManageDevices,
PermDeviceView, PermDeviceConnect, PermDeviceEdit, PermDeviceDelete,
PermGuestCreate,
PermDeviceBan, PermDeviceChangeID, PermDeviceConnectionMode,
PermAuditView, PermMetricsView,
PermCDAPView, PermCDAPCommand, PermCDAPTerminal, PermCDAPFiles,
@@ -130,6 +132,7 @@ var DefaultRolePermissions = map[string]map[string]bool{
RoleOperator: buildPermMap([]string{
PermDeviceView, PermDeviceConnect, PermDeviceEdit, PermDeviceConnectionMode,
PermGuestCreate,
PermUserView,
PermAuditView, PermMetricsView,
PermCDAPView, PermCDAPCommand,
@@ -144,7 +147,8 @@ var DefaultRolePermissions = map[string]map[string]bool{
PermCDAPView,
PermChatAccess,
}),
RolePro: buildPermMap([]string{}),
RolePro: buildPermMap([]string{}),
RoleGuestIssuer: buildPermMap([]string{PermDeviceView, PermGuestCreate}),
// Device credentials authenticate an agent to its own transport only.
// They never confer panel/API permissions.
RoleDevice: buildPermMap([]string{}),
+10 -6
View File
@@ -15,10 +15,11 @@ const (
RoleGlobalAdmin = "global_admin"
// Legacy global roles (backward-compatible)
RoleAdmin = "admin" // maps to super_admin in permission terms
RoleOperator = "operator"
RoleViewer = "viewer"
RolePro = "pro" // API-only RustDesk PRO activation; no device access
RoleAdmin = "admin" // maps to super_admin in permission terms
RoleOperator = "operator"
RoleViewer = "viewer"
RolePro = "pro" // API-only RustDesk PRO activation; no device access
RoleGuestIssuer = "guest_issuer" // device view + temporary guest link issuance
// RoleDevice is an internal, device-scoped principal used for authenticated
// agents. It is intentionally not a user-assignable role.
@@ -42,6 +43,8 @@ func RoleLevel(role string) int {
return 1
case RolePro:
return 0
case RoleGuestIssuer:
return 1
case RoleDevice:
return 0
default:
@@ -71,7 +74,8 @@ func CanAssignRole(callerRole, targetRole string) bool {
// Global Admin can assign roles below global_admin
// (operator, viewer, pro — NOT super_admin, server_admin, global_admin, admin)
case callerRole == RoleGlobalAdmin:
return targetRole == RoleOperator || targetRole == RoleViewer || targetRole == RolePro
return targetRole == RoleOperator || targetRole == RoleViewer || targetRole == RolePro ||
targetRole == RoleGuestIssuer
// Server Admin cannot assign any roles
case callerRole == RoleServerAdmin:
@@ -103,7 +107,7 @@ func IsDeviceRole(role string) bool {
func ValidRole(r string) bool {
switch r {
case RoleSuperAdmin, RoleServerAdmin, RoleGlobalAdmin,
RoleAdmin, RoleOperator, RoleViewer, RolePro:
RoleAdmin, RoleOperator, RoleViewer, RolePro, RoleGuestIssuer:
return true
}
return false
+1
View File
@@ -541,6 +541,7 @@ type Database interface {
// Config
GetConfig(key string) (string, error)
SetConfig(key, value string) error
CompareAndSwapConfig(key, expected, replacement string) (bool, error)
DeleteConfig(key string) error
ListConfigByPrefix(prefix string) ([]ServerConfig, error)
+14
View File
@@ -1311,6 +1311,20 @@ func (pg *PostgresDB) SetConfig(key, value string) error {
return err
}
// CompareAndSwapConfig updates a configuration value only when it still
// matches expected. It is used for atomic counters stored as JSON payloads.
func (pg *PostgresDB) CompareAndSwapConfig(key, expected, replacement string) (bool, error) {
result, err := pg.pool.Exec(pg.ctx,
`UPDATE server_config SET value = $1
WHERE key = $2 AND value = $3`,
replacement, key, expected,
)
if err != nil {
return false, err
}
return result.RowsAffected() == 1, nil
}
// DeleteConfig removes a configuration key.
func (pg *PostgresDB) DeleteConfig(key string) error {
_, err := pg.pool.Exec(pg.ctx, `DELETE FROM server_config WHERE key = $1`, key)
+18
View File
@@ -1484,6 +1484,24 @@ func (s *SQLiteDB) SetConfig(key, value string) error {
return err
}
// CompareAndSwapConfig updates a configuration value only when it still
// matches expected. It is used for atomic counters stored as JSON payloads.
func (s *SQLiteDB) CompareAndSwapConfig(key, expected, replacement string) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
result, err := s.db.Exec(
`UPDATE server_config SET value = ?
WHERE key = ? AND value = ?`,
replacement, key, expected,
)
if err != nil {
return false, err
}
n, err := result.RowsAffected()
return n == 1, err
}
// DeleteConfig removes a configuration key.
func (s *SQLiteDB) DeleteConfig(key string) error {
s.mu.Lock()
+81 -36
View File
@@ -40,6 +40,7 @@ type Grant struct {
// PublicGrant is safe metadata returned by validate (no secrets).
type PublicGrant struct {
ID string `json:"id"`
Valid bool `json:"valid"`
PeerIDs []string `json:"peer_ids"`
ViewOnly bool `json:"view_only"`
@@ -167,14 +168,6 @@ func (s *Store) loadByHash(tokenHash string) (*Grant, error) {
return &g, nil
}
func (s *Store) save(tokenHash string, g *Grant) error {
b, err := json.Marshal(g)
if err != nil {
return err
}
return s.DB.SetConfig(s.configKey(tokenHash), string(b))
}
func (g *Grant) allowsPeer(peerID string) bool {
peerID = strings.TrimSpace(peerID)
for _, id := range g.PeerIDs {
@@ -224,45 +217,96 @@ func (s *Store) Validate(token, peerID string) (*Grant, error) {
return g, nil
}
// Touch increments use_count after a successful session open (optional).
func (s *Store) Touch(token string) error {
// Consume atomically reserves one successful session opening for a peer.
// The compare-and-swap loop is required because grant payloads are stored as
// JSON in a shared config row and both SQLite and PostgreSQL may serve
// concurrent WebSocket upgrades.
func (s *Store) Consume(token, peerID string) (*Grant, error) {
return s.consume(token, peerID, true)
}
func (s *Store) consume(token, peerID string, enforcePeer bool) (*Grant, error) {
token = strings.TrimSpace(token)
peerID = strings.TrimSpace(peerID)
if token == "" {
return fmt.Errorf("missing guest token")
return nil, fmt.Errorf("missing guest token")
}
if enforcePeer && peerID == "" {
return nil, fmt.Errorf("missing guest peer")
}
tokenHash := hashToken(token)
g, err := s.loadByHash(tokenHash)
if err != nil {
return err
key := s.configKey(tokenHash)
for attempt := 0; attempt < 8; attempt++ {
raw, err := s.DB.GetConfig(key)
if err != nil || raw == "" {
return nil, fmt.Errorf("invalid or expired guest link")
}
var g Grant
if err := json.Unmarshal([]byte(raw), &g); err != nil {
return nil, fmt.Errorf("invalid guest grant")
}
if err := g.isActive(); err != nil {
return nil, err
}
if enforcePeer && !g.allowsPeer(peerID) {
return nil, fmt.Errorf("guest link does not allow this device")
}
g.UseCount++
replacement, err := json.Marshal(&g)
if err != nil {
return nil, err
}
swapped, err := s.DB.CompareAndSwapConfig(key, raw, string(replacement))
if err != nil {
return nil, err
}
if swapped {
return &g, nil
}
time.Sleep(time.Millisecond)
}
g.UseCount++
return s.save(tokenHash, g)
return nil, fmt.Errorf("guest link update conflicted")
}
// Touch increments use_count after a successful session open (legacy helper).
func (s *Store) Touch(token string) error {
_, err := s.consume(token, "", false)
return err
}
// RevokeByID marks a grant revoked. Returns true if found.
func (s *Store) RevokeByID(id, createdBy string, admin bool) (bool, error) {
entries, err := s.DB.ListConfigByPrefix(configPrefix)
if err != nil {
return false, err
}
for _, e := range entries {
var g Grant
if err := json.Unmarshal([]byte(e.Value), &g); err != nil {
continue
}
if g.ID != id {
continue
}
if !admin && createdBy != "" && g.CreatedBy != createdBy {
return false, fmt.Errorf("forbidden")
}
now := time.Now().UTC()
g.RevokedAt = &now
tokenHash := strings.TrimPrefix(e.Key, configPrefix)
if err := s.save(tokenHash, &g); err != nil {
for attempt := 0; attempt < 8; attempt++ {
entries, err := s.DB.ListConfigByPrefix(configPrefix)
if err != nil {
return false, err
}
return true, nil
for _, e := range entries {
var g Grant
if err := json.Unmarshal([]byte(e.Value), &g); err != nil {
continue
}
if g.ID != id {
continue
}
if !admin && createdBy != "" && g.CreatedBy != createdBy {
return false, fmt.Errorf("forbidden")
}
now := time.Now().UTC()
g.RevokedAt = &now
replacement, err := json.Marshal(&g)
if err != nil {
return false, err
}
swapped, err := s.DB.CompareAndSwapConfig(e.Key, e.Value, string(replacement))
if err != nil {
return false, err
}
if swapped {
return true, nil
}
}
}
return false, nil
}
@@ -295,6 +339,7 @@ func (s *Store) ListActive(createdBy string, admin bool) ([]*Grant, error) {
// ToPublic builds the public validate response.
func ToPublic(g *Grant) PublicGrant {
return PublicGrant{
ID: g.ID,
Valid: true,
PeerIDs: append([]string(nil), g.PeerIDs...),
ViewOnly: g.ViewOnly,
@@ -3,6 +3,7 @@ package guestaccess
import (
"encoding/json"
"path/filepath"
"sync"
"testing"
"time"
@@ -75,3 +76,34 @@ func TestExpiry(t *testing.T) {
t.Fatal("expected expired")
}
}
func TestConsumeEnforcesPeerAndMaxUsesAtomically(t *testing.T) {
store := newStore(t)
token, grant, err := store.Create([]string{"PEER01"}, "alice", 30, false, "", 2)
if err != nil {
t.Fatalf("Create: %v", err)
}
const attempts = 8
var wg sync.WaitGroup
var mu sync.Mutex
successes := 0
for i := 0; i < attempts; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if _, err := store.Consume(token, "PEER01"); err == nil {
mu.Lock()
successes++
mu.Unlock()
}
}()
}
wg.Wait()
if successes != grant.MaxUses {
t.Fatalf("successful consumes = %d, want %d", successes, grant.MaxUses)
}
if _, err := store.Consume(token, "OTHER"); err == nil {
t.Fatal("expected peer outside grant to be rejected")
}
}
+14 -13
View File
@@ -435,17 +435,18 @@ function Generate-Checksums {
$checksumFile = "CHECKSUMS.md"
$dateNow = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$content = @"
# BetterDesk Server - Binary Checksums
Generated: $dateNow
RustDesk Base Version: $Script:RustDeskVersion
BetterDesk Version: 2.0.0
## SHA256 Checksums
``````
"@
$content = @(
'# BetterDesk Server - Binary Checksums'
''
"Generated: $dateNow"
"RustDesk Base Version: $Script:RustDeskVersion"
'BetterDesk Version: 2.0.0'
''
'## SHA256 Checksums'
''
'```'
) -join [Environment]::NewLine
$content += [Environment]::NewLine
$binaries = Get-ChildItem -Filter "hbbs-*" -File
$binaries += Get-ChildItem -Filter "hbbr-*" -File
@@ -455,11 +456,11 @@ BetterDesk Version: 2.0.0
$content += "$hash $($binary.Name)`n"
}
$content += "```"
$content += '```'
$content | Out-File -FilePath $checksumFile -Encoding UTF8
Write-Success "Checksums saved to: $Script:OutputDir\$checksumFile"
Write-Success ("Checksums saved to: {0}\{1}" -f $Script:OutputDir, $checksumFile)
} catch {
Write-Warning2 "Could not generate checksums: $_"
} finally {
+46
View File
@@ -79,6 +79,52 @@ go test -race -count=1 ./...
go vet ./...
```
### Local-only diagnostic gate
Before enabling the local hooks, install the required local tools:
- Node.js and npm versions accepted by `web-nodejs/package.json`
- Go accepted by `betterdesk-server/go.mod` and `govulncheck`
- Docker Desktop with the Compose plugin and the `postgres:16-alpine` image
- Bash, ShellCheck, PowerShell, ripgrep, gitleaks, Trivy
- Python 3.9+ and `pip-audit` for the SDK and bridge manifests
On Windows, run the one-time setup from PowerShell:
```powershell
.\scripts\setup-local-gates.ps1
```
The setup stores `core.hooksPath` in this clone's local Git configuration.
It does not change the repository or GitHub workflows. Both `pre-commit` and
`pre-push` then run the complete local gate:
```powershell
npm run local:gate
```
The gate runs the Node.js console and SDK tests, Go vet/race/vulnerability
checks/builds, Python compilation/tests and `pip-audit`, all npm audits,
gitleaks, the sensitive-path scan, Trivy filesystem and local-image scans,
installer syntax/unit checks, protocol/i18n/provenance/version checks, Compose
validation, isolated PostgreSQL tests, and local Docker health/login/restart
smoke tests. It creates JSON and Markdown diagnostics in
`.local-test-results/`.
The gate fails closed. Missing required tools, failed tests, unexpected skips,
security findings, unavailable Docker/PostgreSQL, or incomplete integration
checks block the operation with a non-zero exit code. Use
`npm run local:gate:dry-run` only to inspect the categories; it is not a
passing test result. `--no-verify` bypasses Git's hooks and must be treated as
an exceptional, explicitly documented action.
The Docker smoke tests build images from this checkout and use temporary
containers and volumes. They do not run a native installation, touch
`/opt`/`C:\BetterDeskConsole`, restart host services, call GitHub Actions, or
test an external RustDesk client. Those host/client lifecycle checks remain
manual checks in a disposable VM and are shown as explicit boundaries in the
local report.
Read [BetterDesk Update Flow](../important/betterdesk-update-flow.md) before
changing update, installer, service, or deployment behavior.
+107
View File
@@ -0,0 +1,107 @@
# BetterDesk local diagnostic gate
The local gate is the authoritative pre-commit and pre-push check for a
developer checkout. It is intentionally separate from GitHub Actions: the
repository does not enable these hooks automatically on a clone, and the
workflow files do not call the local gate.
## First-time setup on Windows
Install the following commands and make them available on `PATH`:
- Node.js 22 or newer and npm
- Go 1.25 or newer and `govulncheck`
- Docker Desktop with the Compose plugin
- Bash and ShellCheck (Git Bash or WSL can provide Bash)
- PowerShell, ripgrep, gitleaks, and Trivy
- Python 3.9 or newer and `pip-audit`
The gate detects Python requirements in the bridges and the Python SDK
`pyproject.toml`. It detects Rust manifests if they are restored to the
checkout and then requires `cargo-audit` as well.
From the repository root:
```powershell
.\scripts\setup-local-gates.ps1
```
This runs the prerequisite check and sets only the clone-local Git setting:
```text
core.hooksPath=.githooks
```
It does not edit `.gitignore`, repository workflows, global Git settings, or
any host service configuration.
## Running the gate
Run the complete gate manually:
```powershell
npm run local:gate
```
The same command is called by both local hooks. A non-zero exit code blocks
the commit or push. The report files are written to `.local-test-results/`:
- `latest.json` contains machine-readable statuses, commands, exit codes,
durations, captured output, branch, commit, and environment.
- `latest.md` contains the human-readable summary and explicit coverage
boundaries.
To inspect the planned categories without claiming a pass:
```powershell
npm run local:gate:dry-run
```
## What is checked
The gate fails closed when any required stage is missing or incomplete.
- Node.js: clean installs and audits for the root package, console, and Node
SDK; frontend syntax; protocol artifacts; all locale parity; provenance;
full Jest tests; and SDK tests.
- Go: `go vet`, race-enabled tests, `govulncheck`, native build/help,
Linux amd64/arm64 and Windows amd64 cross-builds, and PostgreSQL tests.
- Python: bytecode compilation for SDK/bridges, Python SDK unit tests, and
`pip-audit` for each requirements file and SDK project dependency.
- Security: gitleaks, operator-specific path scan, Trivy source scan, npm
audit, Go vulnerability analysis, Python dependency analysis, and Trivy
scans of local Docker images.
- Installers: Bash syntax, ShellCheck, mocked installer regression tests,
non-mutating help paths, and PowerShell AST parsing.
- Runtime: every Compose manifest, local image builds, temporary PostgreSQL,
isolated SQLite/PostgreSQL Docker smoke tests, panel/API health, admin
login, protocol/port checks, restart persistence, and hardened bind mounts.
The test runner builds from the checkout and does not pull the official
BetterDesk image from GHCR. Dependency and vulnerability databases may still
be contacted by npm, Go, pip, Docker base-image, or security-scanner tools;
the test execution and runtime stack remain local.
## Status meanings
- `PASS`: the required check completed successfully.
- `FAIL`: the check ran and found a defect, test failure, vulnerability, or
leak.
- `BLOCKED`: a required tool, service, integration, or test was unavailable,
or a test silently skipped.
- `OUT_OF_SCOPE`: an explicit boundary that cannot be proved by this checkout,
such as a real RustDesk client, physical device, native host service
lifecycle, or desktop source tree that is not present.
`OUT_OF_SCOPE` is never presented as a pass. `FAIL` and `BLOCKED` always
produce a non-zero gate result.
## Safety boundaries
The Docker checks use unique temporary containers and volumes and clean them
up in `finally` paths. The local gate never runs the native installer against
`/opt`, `C:\BetterDeskConsole`, NSSM, systemd, or production data. Native
install/update/rollback/uninstall lifecycle tests belong in a disposable VM.
Git's `--no-verify` option can bypass a local hook. Such a bypass is
intentional and must not be treated as evidence that the gate passed.
+75
View File
@@ -0,0 +1,75 @@
# Guest Access Links
Guest Access Links provide temporary Web Remote access without creating a
BetterDesk Console account for the recipient.
## Security model
- A link is an opaque, time-limited grant. The raw token is returned only when
the link is created; the server stores only its hash.
- Every WebSocket upgrade must include the selected `peer_id` and a
`guest_session` value. BetterDesk validates both the token and the peer
allowlist before opening the bridge.
- The rendezvous bridge checks `PunchHoleRequest` and `RequestRelay` targets
server-side. Changing the URL or sending a different protobuf target cannot
escape the grant.
- TTL and revocation apply to active bridges. The panel closes locally revoked
bridges immediately and periodically revalidates grants for revocations made
by another panel process.
- `max_uses` is consumed atomically after the first valid session-opening
protocol message. Failed upgrades do not consume a use.
- Guest session open/close events contain grant ID, peer, transport, source IP,
duration and close reason. Tokens and passwords are never written to audit
records.
For customer self-service, create a grant containing one peer. Existing
operator-created grants may still contain multiple peers, but each individual
WebSocket remains bound to one selected peer.
## Password-less access
The organization peer vault (#367) encrypts unattended passwords at rest and
is available to authorized operators. Guest grants do not contain passwords
and public guest endpoints never return vault plaintext.
The current RustDesk Web Remote protocol performs the password challenge and
hash calculation in the browser. Therefore, simply attaching a vault reference
to a grant would either expose the password to the browser or require a
protocol-aware proxy that terminates part of the end-to-end handshake. The
second option needs a separate design and security review before it can be
enabled for customer links.
Until that design is approved, guests must complete the normal target-device
password or approval handshake.
## Issuing links with a restricted API identity
The `guest_issuer` role has only:
- `device.view`
- `guest.create`
Use device and organization scoping to restrict which peer IDs the issuer may
select. It does not grant general `device.connect` or Console administration.
The panel endpoints are:
- `POST /api/guest/access-links`
- `GET /api/guest/access-links`
- `DELETE /api/guest/access-links/:id`
## Troubleshooting 403 responses
Check the response from the panel's
`GET /api/guest/access-links/peers?token=...` first. It must return
`valid: true`. Then verify:
1. The link has not expired or been revoked.
2. The URL still contains the complete token.
3. The selected peer is in `peer_ids`.
4. The panel can reach the Go API and has the current API key.
5. For split-container or reverse-proxy deployments, `PANEL_SIGNAL_PROXY_CIDRS`
contains the panel-to-signal source network.
The WebSocket URLs generated by the current client include `guest`,
`peer_id`, and `guest_session` on both rendezvous and relay connections.
+4 -1
View File
@@ -1,6 +1,9 @@
{
"scripts": {
"i18n:check": "node web-nodejs/scripts/i18n-check.js --system web-nodejs"
"i18n:check": "node web-nodejs/scripts/i18n-check.js --system web-nodejs",
"local:gate": "node scripts/local-gate.js",
"local:gate:dry-run": "node scripts/local-gate.js --dry-run",
"test:local-gate": "node --test scripts/local-gate.test.js"
},
"devDependencies": {
"vitest": "^3.2.5"
+7 -3
View File
@@ -5,8 +5,12 @@ set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
if ! command -v rg >/dev/null 2>&1; then
echo "ERROR: ripgrep (rg) is required" >&2
RG_BIN="${BETTERDESK_RG_BIN:-}"
if [[ -z "$RG_BIN" ]]; then
RG_BIN="$(command -v rg 2>/dev/null || command -v rg.exe 2>/dev/null || true)"
fi
if [[ -z "$RG_BIN" ]]; then
echo "ERROR: ripgrep (rg or rg.exe) is required" >&2
exit 1
fi
@@ -30,7 +34,7 @@ PATTERNS=(
FAIL=0
for pat in "${PATTERNS[@]}"; do
if matches=$(rg -n "$pat" "${SCAN_PATHS[@]}" \
if matches=$("$RG_BIN" -n "$pat" "${SCAN_PATHS[@]}" \
--glob '!docs/private/**' \
--glob '!scripts/check-no-sensitive-paths.sh' \
--glob '!*.plan.md' 2>/dev/null); then
+42
View File
@@ -0,0 +1,42 @@
param(
[string[]]$Path = @(
"betterdesk.ps1",
"build-betterdesk.ps1",
"scripts/check-powershell-syntax.ps1",
"scripts/check-wiki-staleness.ps1",
"scripts/local-gate.ps1",
"scripts/setup-local-gates.ps1",
"scripts/sync-wiki.ps1"
)
)
$ErrorActionPreference = "Stop"
$failures = @()
foreach ($file in $Path) {
$resolved = Join-Path (Split-Path -Parent $PSScriptRoot) $file
if (-not (Test-Path -LiteralPath $resolved -PathType Leaf)) {
$failures += "$file is missing"
continue
}
$tokens = $null
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile(
(Resolve-Path -LiteralPath $resolved),
[ref]$tokens,
[ref]$errors
) | Out-Null
if ($errors.Count -gt 0) {
$messages = $errors | ForEach-Object { $_.Message }
$failures += "$file failed to parse: $($messages -join '; ')"
}
}
if ($failures.Count -gt 0) {
$failures | ForEach-Object { Write-Error $_ }
exit 1
}
Write-Output "PowerShell installer syntax checks passed."
+362
View File
@@ -0,0 +1,362 @@
#!/usr/bin/env node
'use strict';
/**
* Destructive-looking but isolated local smoke test.
*
* The test uses a temporary Docker container and named volumes with a unique
* label. It never touches the host installation paths or the project's
* production Compose container names.
*/
const http = require('http');
const https = require('https');
const { spawnSync } = require('child_process');
const ROOT = require('path').join(__dirname, '..');
const IMAGE = process.env.BETTERDESK_LOCAL_IMAGE || 'betterdesk:local';
const PASSWORD = 'BetterDesk-Local-Gate-Only-2026!';
const REQUEST_TIMEOUT_MS = 5_000;
const STARTUP_TIMEOUT_MS = 120_000;
function parseArgs(argv) {
const options = {
databaseUrl: '',
databaseType: 'sqlite',
keep: false,
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === '--database-url') {
options.databaseUrl = argv[++index] || '';
} else if (arg === '--database-type') {
options.databaseType = argv[++index] || 'sqlite';
} else if (arg === '--keep') {
options.keep = true;
} else if (arg === '--help' || arg === '-h') {
options.help = true;
} else {
throw new Error(`Unknown option: ${arg}`);
}
}
if (!['sqlite', 'postgres'].includes(options.databaseType)) {
throw new Error('--database-type must be sqlite or postgres');
}
if (options.databaseType === 'postgres' && !options.databaseUrl) {
throw new Error('--database-url is required for postgres smoke tests');
}
return options;
}
function docker(args, { allowFailure = false } = {}) {
const result = spawnSync('docker', args, {
cwd: ROOT,
encoding: 'utf8',
windowsHide: true,
maxBuffer: 4 * 1024 * 1024,
});
if (!allowFailure && (result.error || result.status !== 0)) {
const detail = result.error?.message
|| String(result.stderr || result.stdout || '').trim()
|| `exit code ${result.status}`;
throw new Error(`docker ${args.join(' ')} failed: ${detail}`);
}
return result;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function request(url, options = {}) {
const target = new URL(url);
const transport = target.protocol === 'https:' ? https : http;
return new Promise((resolve, reject) => {
const req = transport.request(target, {
method: options.method || 'GET',
timeout: options.timeoutMs || REQUEST_TIMEOUT_MS,
headers: options.headers || {},
}, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
resolve({
statusCode: res.statusCode || 0,
headers: res.headers,
body,
});
});
});
req.on('timeout', () => req.destroy(new Error('request timed out')));
req.on('error', reject);
if (options.body) req.write(options.body);
req.end();
});
}
function firstCookie(headers) {
return (headers['set-cookie'] || [])
.map((cookie) => String(cookie).split(';', 1)[0])
.filter(Boolean)
.join('; ');
}
function getCsrfToken(html) {
const patterns = [
/csrfToken:\s*'([^']+)'/,
/csrfToken:\s*"([^"]+)"/,
/name=["']_csrf["'][^>]+value=["']([^"']+)["']/i,
];
for (const pattern of patterns) {
const match = pattern.exec(html);
if (match) return match[1];
}
return '';
}
async function login(panelUrl) {
const page = await request(`${panelUrl}/login`);
if (page.statusCode < 200 || page.statusCode >= 300) {
throw new Error(`login page returned HTTP ${page.statusCode}`);
}
const csrf = getCsrfToken(page.body);
if (!csrf) throw new Error('login page did not expose a CSRF token');
const cookie = firstCookie(page.headers);
const body = JSON.stringify({ username: 'admin', password: PASSWORD });
const response = await request(`${panelUrl}/api/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
'Cookie': cookie,
'X-CSRF-Token': csrf,
},
body,
});
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(`login returned HTTP ${response.statusCode}: ${response.body}`);
}
let payload;
try {
payload = JSON.parse(response.body);
} catch {
throw new Error(`login returned invalid JSON: ${response.body}`);
}
if (payload.success !== true) {
throw new Error(`login was rejected: ${response.body}`);
}
const loginCookie = [cookie, firstCookie(response.headers)].filter(Boolean).join('; ');
const verify = await request(`${panelUrl}/api/auth/verify`, {
headers: { Cookie: loginCookie },
});
if (verify.statusCode < 200 || verify.statusCode >= 300) {
throw new Error(`session verification returned HTTP ${verify.statusCode}`);
}
let verifyPayload;
try {
verifyPayload = JSON.parse(verify.body);
} catch {
throw new Error(`session verification returned invalid JSON: ${verify.body}`);
}
if (verifyPayload.success !== true || !verifyPayload.user) {
throw new Error(`session verification failed: ${verify.body}`);
}
}
function mappedPort(container, port) {
const result = docker(['port', container, `${port}/tcp`]);
const match = String(result.stdout).match(/:(\d+)\s*$/m);
if (!match) throw new Error(`could not determine mapped port ${port} for ${container}`);
return Number(match[1]);
}
async function waitForHealth(apiUrl, panelUrl) {
const deadline = Date.now() + STARTUP_TIMEOUT_MS;
let lastError = 'services have not started';
while (Date.now() < deadline) {
try {
const [api, panel] = await Promise.all([
request(`${apiUrl}/api/health`),
request(`${panelUrl}/health`),
]);
if (api.statusCode >= 200 && api.statusCode < 300
&& panel.statusCode >= 200 && panel.statusCode < 300) {
return;
}
lastError = `API ${api.statusCode}, panel ${panel.statusCode}`;
} catch (error) {
lastError = error.message;
}
await sleep(1_000);
}
throw new Error(`services did not become healthy: ${lastError}`);
}
async function waitForContainerHealthy(container) {
const deadline = Date.now() + 60_000;
let status = 'unknown';
while (Date.now() < deadline) {
status = String(docker([
'inspect', '--format', '{{.State.Health.Status}}', container,
]).stdout).trim();
if (status === 'healthy') return;
if (status === 'unhealthy') throw new Error('container health status is unhealthy');
await sleep(1_000);
}
throw new Error(`container health status remained ${status || 'unknown'}`);
}
function containerExec(container, args) {
return docker(['exec', container, ...args]);
}
async function run(options) {
const suffix = `${process.pid}-${Date.now()}`;
const container = `betterdesk-local-gate-${suffix}`;
const dataVolume = `betterdesk-local-gate-data-${suffix}`;
const consoleVolume = `betterdesk-local-gate-console-${suffix}`;
let apiUrl = '';
let panelUrl = '';
const environment = [
'NODE_ENV=production',
'PORT=5000',
'HOST=0.0.0.0',
'API_HOST=0.0.0.0',
'API_ENABLED=false',
'SERVER_BACKEND=betterdesk',
'BETTERDESK_API_URL=http://127.0.0.1:21121/api',
'HBBS_API_URL=http://127.0.0.1:21121/api',
'RUSTDESK_PATH=/opt/rustdesk',
'DATA_DIR=/app/data',
'DB_PATH=/opt/rustdesk/db_v2.sqlite3',
'AUTH_DB_PATH=/app/data/auth.db',
'SQLITE_AUTH_DB_MODE=',
'ADMIN_PASSWORD=' + PASSWORD,
'INIT_ADMIN_USER=admin',
'INIT_ADMIN_PASS=' + PASSWORD,
'DEFAULT_ADMIN_USERNAME=admin',
'DEFAULT_ADMIN_PASSWORD=' + PASSWORD,
'DOCKER=true',
'AGENT_BUILD_WORKER=off',
'BETTERDESK_GITHUB_TOKEN=',
'PUID=10001',
'PGID=10001',
'ENROLLMENT_MODE=managed',
];
if (options.databaseType === 'postgres') {
environment.push('DB_TYPE=postgres', `DATABASE_URL=${options.databaseUrl}`, `DB_URL=${options.databaseUrl}`);
} else {
environment.push('DB_TYPE=sqlite');
}
try {
docker(['volume', 'create', dataVolume]);
docker(['volume', 'create', consoleVolume]);
docker([
'run', '--detach',
'--name', container,
'--label', 'com.betterdesk.local-gate=true',
'--publish', '127.0.0.1::5000',
'--publish', '127.0.0.1::21121',
'--volume', `${dataVolume}:/opt/rustdesk`,
'--volume', `${consoleVolume}:/app/data`,
'--add-host', 'host.docker.internal:host-gateway',
...environment.flatMap((value) => ['--env', value]),
IMAGE,
]);
const panelPort = mappedPort(container, 5000);
const apiPort = mappedPort(container, 21121);
panelUrl = `http://127.0.0.1:${panelPort}`;
apiUrl = `http://127.0.0.1:${apiPort}`;
await waitForHealth(apiUrl, panelUrl);
await login(panelUrl);
const firstKey = String(containerExec(container, ['sh', '-c', 'cat /opt/rustdesk/.api_key']).stdout)
.trim();
if (!firstKey) throw new Error('container did not create an API key');
const protocol = spawnSync(process.execPath, [
require('path').join(__dirname, 'installer-protocol-check.js'),
'--api-url', `${apiUrl}/api/health`,
'--panel-url', `${panelUrl}/health`,
'--port', `127.0.0.1:${apiPort}`,
], {
cwd: ROOT,
encoding: 'utf8',
windowsHide: true,
maxBuffer: 2 * 1024 * 1024,
});
process.stdout.write(protocol.stdout || '');
process.stderr.write(protocol.stderr || '');
if (protocol.error || protocol.status !== 0) {
throw new Error(`installer protocol check failed with exit code ${protocol.status}`);
}
docker(['restart', container]);
const restartedPanelPort = mappedPort(container, 5000);
const restartedApiPort = mappedPort(container, 21121);
panelUrl = `http://127.0.0.1:${restartedPanelPort}`;
apiUrl = `http://127.0.0.1:${restartedApiPort}`;
await waitForHealth(apiUrl, panelUrl);
await login(panelUrl);
const secondKey = String(containerExec(container, ['sh', '-c', 'cat /opt/rustdesk/.api_key']).stdout)
.trim();
if (firstKey !== secondKey) {
throw new Error('API key changed after a container restart');
}
await waitForContainerHealthy(container);
console.log(`PASS local Docker smoke (${options.databaseType}) ${apiUrl} ${panelUrl}`);
return { apiUrl, panelUrl, container, dataVolume, consoleVolume };
} catch (error) {
const logs = docker(['logs', '--tail', '200', container], { allowFailure: true });
if (logs.stdout) process.stderr.write(logs.stdout);
if (logs.stderr) process.stderr.write(logs.stderr);
throw error;
} finally {
if (!options.keep) {
docker(['rm', '--force', container], { allowFailure: true });
docker(['volume', 'rm', '--force', dataVolume], { allowFailure: true });
docker(['volume', 'rm', '--force', consoleVolume], { allowFailure: true });
}
}
}
async function main() {
try {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
console.log('Usage: node scripts/local-docker-smoke.js [--database-type sqlite|postgres] [--database-url URL] [--keep]');
return;
}
await run(options);
} catch (error) {
console.error(`FAIL local Docker smoke: ${error.message}`);
process.exitCode = 1;
}
}
if (require.main === module) main();
module.exports = {
parseArgs,
getCsrfToken,
firstCookie,
mappedPort,
waitForHealth,
waitForContainerHealthy,
login,
run,
};
File diff suppressed because it is too large Load Diff
+20
View File
@@ -0,0 +1,20 @@
param(
[switch]$DryRun,
[switch]$PreflightOnly,
[string]$ReportDir
)
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
Set-Location -LiteralPath $repoRoot
$arguments = @("scripts/local-gate.js")
if ($DryRun) { $arguments += "--dry-run" }
if ($PreflightOnly) { $arguments += "--preflight-only" }
if ($ReportDir) {
$arguments += "--report-dir"
$arguments += $ReportDir
}
& node @arguments
exit $LASTEXITCODE
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$REPO_ROOT"
if command -v node >/dev/null 2>&1; then
exec node scripts/local-gate.js "$@"
elif command -v node.exe >/dev/null 2>&1; then
exec node.exe scripts/local-gate.js "$@"
elif command -v powershell.exe >/dev/null 2>&1; then
exec powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass \
-File scripts/local-gate.ps1 "$@"
else
printf '%s\n' "BLOCKED: Node.js or PowerShell is not available to run the local gate." >&2
exit 1
fi
+116
View File
@@ -0,0 +1,116 @@
'use strict';
const assert = require('node:assert/strict');
const test = require('node:test');
const {
OUT_OF_SCOPE,
atLeastVersion,
calculateOverall,
containsUnexpectedSkip,
discoverSecurityManifests,
extractPyprojectDependencies,
formatCommand,
parseArgs,
parseVersion,
processInvocation,
redactSensitive,
resultStatus,
run,
} = require('./local-gate');
test('argument parsing keeps the gate local and supports dry runs', () => {
const options = parseArgs(['--dry-run', '--report-dir', '.local-test-results/test']);
assert.equal(options.dryRun, true);
assert.match(options.reportDir, /local-test-results[\\/]+test$/u);
});
test('command formatting redacts database credentials', () => {
const command = formatCommand('node', [
'scripts/local-docker-smoke.js',
'--database-url',
'postgres://user:password@example.test:5432/db?sslmode=disable',
]);
assert.match(command, /postgres:\/\/user:\[REDACTED\]@example\.test/u);
assert.doesNotMatch(command, /password/u);
});
test('captured diagnostics redact passwords and bearer tokens', () => {
const safe = redactSensitive(
'password=plain-secret token:plain-token Authorization: Bearer bearer-secret',
);
assert.doesNotMatch(safe, /plain-secret|plain-token|bearer-secret/u);
assert.match(safe, /\[REDACTED\]/u);
});
test('Windows command shims are invoked through cmd.exe', () => {
const invocation = processInvocation('npm.cmd', ['--version']);
if (process.platform === 'win32') {
assert.equal(invocation.command, 'cmd.exe');
assert.deepEqual(invocation.args.slice(0, 3), ['/d', '/s', '/c']);
assert.match(invocation.args[3], /npm\.cmd --version/u);
} else {
assert.equal(invocation.command, 'npm.cmd');
}
});
test('skips are blocking unless explicitly allowed', () => {
assert.equal(containsUnexpectedSkip('--- SKIP: Docker is not available'), true);
assert.equal(containsUnexpectedSkip('Tests: 12 passed, 0 skipped'), false);
assert.equal(resultStatus({ code: 0, stdout: 'SKIP: unavailable', stderr: '' }), 'BLOCKED');
assert.equal(
resultStatus({ code: 0, stdout: 'SKIP: unavailable', stderr: '' }, { allowSkip: true }),
'PASS',
);
assert.equal(
resultStatus({ code: 0, stdout: '1 skipped', stderr: '' }, { expectedSkip: true }),
'OUT_OF_SCOPE',
);
assert.equal(resultStatus({ code: null, error: { code: 'ENOENT' } }), 'BLOCKED');
});
test('version checks compare semantic versions conservatively', () => {
assert.deepEqual(parseVersion('go version go1.26.6 windows/amd64'), {
major: 1,
minor: 26,
patch: 6,
});
assert.equal(atLeastVersion(parseVersion('v22.1.0'), { major: 22, minor: 0, patch: 0 }), true);
assert.equal(atLeastVersion(parseVersion('v21.9.0'), { major: 22, minor: 0, patch: 0 }), false);
});
test('security manifest discovery includes all dependency ecosystems', () => {
const manifests = discoverSecurityManifests();
assert.ok(manifests.pythonRequirements.some((file) => file.endsWith('bridges\\modbus\\requirements.txt')
|| file.endsWith('bridges/modbus/requirements.txt')));
assert.ok(manifests.pythonProjects.some((file) => file.endsWith('sdks\\python\\pyproject.toml')
|| file.endsWith('sdks/python/pyproject.toml')));
assert.deepEqual(manifests.rustProjects, []);
});
test('Python project dependencies can be converted for pip-audit', () => {
const dependencies = extractPyprojectDependencies('sdks/python/pyproject.toml');
assert.deepEqual(dependencies, ['websockets>=12.0']);
});
test('overall status blocks on required failures but ignores explicit boundaries', () => {
const report = {
results: [
{ status: 'PASS', required: true },
{ status: 'OUT_OF_SCOPE', required: false },
],
};
assert.equal(calculateOverall(report), 'PASS');
report.results.push({ status: 'BLOCKED', required: true });
assert.equal(calculateOverall(report), 'BLOCKED');
report.results.push({ status: 'FAIL', required: true });
assert.equal(calculateOverall(report), 'FAIL');
assert.equal(OUT_OF_SCOPE.length >= 1, true);
});
test('dry run does not execute the external test suites', async () => {
const report = await run({ dryRun: true });
assert.equal(report.dryRun, true);
assert.equal(report.overall, 'PASS');
assert.equal(report.results.length, 0);
});
+19
View File
@@ -0,0 +1,19 @@
param()
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
Set-Location -LiteralPath $repoRoot
Write-Output "Checking local BetterDesk gate prerequisites..."
& node scripts/local-gate.js --preflight-only
if ($LASTEXITCODE -ne 0) {
throw "Prerequisite check failed. Install the missing tools before enabling local hooks."
}
& git config --local core.hooksPath .githooks
if ($LASTEXITCODE -ne 0) {
throw "Could not configure the local Git hooks path."
}
Write-Output "Local hooks enabled at .githooks."
Write-Output "Both pre-commit and pre-push run the complete local gate."
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$REPO_ROOT"
printf '%s\n' "Checking local BetterDesk gate prerequisites..."
if command -v node >/dev/null 2>&1; then
node scripts/local-gate.js --preflight-only
elif command -v node.exe >/dev/null 2>&1; then
node.exe scripts/local-gate.js --preflight-only
elif command -v powershell.exe >/dev/null 2>&1; then
powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass \
-File scripts/local-gate.ps1 -PreflightOnly
else
printf '%s\n' "BLOCKED: Node.js or PowerShell is not available." >&2
exit 1
fi
git config --local core.hooksPath .githooks
printf '%s\n' "Local hooks enabled at .githooks."
+3 -1
View File
@@ -11,7 +11,9 @@ mkdir -p "$FAKE_BIN" "$STATE_DIR"
trap 'rm -rf "$TEST_ROOT"' EXIT
# Load the production functions without invoking the interactive installer.
sed '$d' "$INSTALLER" > "$FUNCTIONS_FILE"
# The installer has a direct-execution guard, so sourcing the complete file is
# safer than deleting an assumed final line.
cp "$INSTALLER" "$FUNCTIONS_FILE"
cat > "$FAKE_BIN/curl" <<'EOF'
#!/usr/bin/env bash
+11 -2
View File
@@ -7,6 +7,15 @@ IMAGE="${BETTERDESK_HARDENING_IMAGE:-ghcr.io/unitronix/betterdesk:${IMAGE_TAG}}"
PROJECT="betterdesk-hardening-$RANDOM"
TEST_DIR="$(mktemp -d)"
OVERRIDE_FILE="$TEST_DIR/compose.override.yml"
DOCKER_BIN="${BETTERDESK_DOCKER_BIN:-}"
if [[ -z "$DOCKER_BIN" ]]; then
DOCKER_BIN="$(command -v docker 2>/dev/null || command -v docker.exe 2>/dev/null || true)"
fi
docker() {
"$DOCKER_BIN" "$@"
}
if command -v cygpath >/dev/null 2>&1; then
DOCKER_TEST_DIR="$(cygpath -m "$TEST_DIR")"
else
@@ -15,7 +24,7 @@ fi
fail() {
printf 'FAIL: %s\n' "$*" >&2
if [[ -f "$OVERRIDE_FILE" ]] && command -v docker >/dev/null 2>&1; then
if [[ -f "$OVERRIDE_FILE" ]] && [[ -n "$DOCKER_BIN" ]]; then
docker compose -p "$PROJECT" \
-f "$SCRIPT_ROOT/docker-compose.quick.single.yml" \
-f "$OVERRIDE_FILE" logs --tail=120 >&2 || true
@@ -49,7 +58,7 @@ cleanup() {
}
trap cleanup EXIT
if ! command -v docker >/dev/null 2>&1 || ! docker info >/dev/null 2>&1; then
if [[ -z "$DOCKER_BIN" ]] || ! docker info >/dev/null 2>&1; then
printf 'SKIP: Docker is not available\n'
exit 0
fi
+3 -1
View File
@@ -11,7 +11,9 @@ STATE_DIR="$TEST_ROOT/state"
mkdir -p "$FAKE_BIN" "$STATE_DIR"
trap 'rm -rf "$TEST_ROOT"' EXIT
sed '$d' "$INSTALLER" > "$FUNCTIONS_FILE"
# The installer has a direct-execution guard, so source the complete file
# instead of deleting an assumed final line.
cp "$INSTALLER" "$FUNCTIONS_FILE"
cat > "$FAKE_BIN/sudo" <<'EOF'
#!/usr/bin/env bash
+1 -1
View File
@@ -9,7 +9,7 @@
"./protocol": "./src/protocol.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "node --test"
},
"keywords": ["betterdesk", "cdap", "iot", "scada", "bridge", "remote-management"],
"license": "AGPL-3.0",
+111
View File
@@ -0,0 +1,111 @@
'use strict';
const assert = require('node:assert/strict');
const test = require('node:test');
const {
CDAPBridge,
Widget,
Action,
Severity,
WidgetType,
button,
createMessage,
gauge,
parseMessage,
toggle,
} = require('../src');
const {
authApiKey,
authDeviceToken,
authUserPassword,
} = require('../src/protocol');
test('protocol messages round-trip with strings and buffers', () => {
const raw = createMessage('telemetry', { temperature: 21 }, 'message-1');
const parsed = parseMessage(raw);
assert.equal(parsed.type, 'telemetry');
assert.deepEqual(parsed.payload, { temperature: 21 });
assert.equal(parsed.id, 'message-1');
assert.match(parsed.timestamp, /^\d{4}-\d{2}-\d{2}T/);
const fromBuffer = parseMessage(Buffer.from(raw));
assert.deepEqual(fromBuffer, parsed);
});
test('protocol constants and authentication payloads are stable', () => {
assert.equal(Action.SET, 'set');
assert.equal(Severity.WARNING, 'warning');
assert.equal(WidgetType.GAUGE, 'gauge');
assert.deepEqual(authApiKey('key', 'device', '2.0.0'), {
method: 'api_key',
key: 'key',
device_id: 'device',
client_version: '2.0.0',
});
assert.deepEqual(authDeviceToken('token'), {
method: 'device_token',
token: 'token',
device_id: '',
client_version: '1.0.0',
});
assert.deepEqual(authUserPassword('admin', 'password'), {
method: 'user_password',
username: 'admin',
password: 'password',
device_id: '',
client_version: '1.0.0',
});
});
test('widget factories produce CDAP-compatible manifests', () => {
const temperature = gauge('temperature', 'Temperature', { unit: 'C', max: 50 });
const heater = toggle('heater', 'Heater');
const restart = button('restart', 'Restart', { confirm: true });
assert.ok(temperature instanceof Widget);
assert.deepEqual(temperature.toJSON(), {
type: 'gauge',
id: 'temperature',
label: 'Temperature',
unit: 'C',
max: 50,
precision: 1,
permissions: { read: 'viewer' },
});
assert.deepEqual(heater.toJSON(), {
type: 'toggle',
id: 'heater',
label: 'Heater',
permissions: { read: 'viewer', control: 'operator' },
});
assert.equal(restart.toJSON().confirm, true);
});
test('bridge registration and command handling are testable without a network', async () => {
const bridge = new CDAPBridge({
server: 'ws://127.0.0.1:1/cdap',
apiKey: 'test-only-key',
deviceId: 'device-1',
heartbeatSec: 5,
});
const sent = [];
bridge._send = (type, payload) => sent.push({ type, payload });
bridge.addWidget(toggle('heater', 'Heater'));
bridge.onCommand('heater', ({ value }) => Boolean(value));
bridge._register();
assert.equal(sent[0].type, 'register');
assert.equal(sent[0].payload.widgets[0].id, 'heater');
assert.deepEqual(sent[0].payload.capabilities, ['telemetry', 'commands', 'alerts', 'logs']);
await bridge._handleCommand({
id: 'command-1',
payload: { widget_id: 'heater', action: Action.SET, value: true },
});
const response = sent.at(-1);
assert.equal(response.type, 'command_response');
assert.equal(response.payload.success, true);
assert.equal(response.payload.value, true);
});
+98
View File
@@ -0,0 +1,98 @@
"""Offline tests for the BetterDesk CDAP Python SDK."""
from __future__ import annotations
import asyncio
import json
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from betterdesk_cdap import CDAPBridge, gauge, toggle # noqa: E402
from betterdesk_cdap.protocol import ( # noqa: E402
Message,
auth_payload_api_key,
auth_payload_device_token,
auth_payload_user_password,
)
class ProtocolTests(unittest.TestCase):
def test_message_round_trip(self) -> None:
original = Message(type="telemetry", payload={"temperature": 21}, id="message-1")
encoded = original.to_json()
decoded = Message.from_json(encoded)
self.assertEqual(decoded.type, "telemetry")
self.assertEqual(decoded.payload, {"temperature": 21})
self.assertEqual(decoded.id, "message-1")
self.assertIsNotNone(decoded.timestamp)
self.assertEqual(json.loads(encoded)["type"], "telemetry")
def test_auth_payloads(self) -> None:
self.assertEqual(
auth_payload_api_key("key", "device", "2.0.0"),
{
"method": "api_key",
"key": "key",
"device_id": "device",
"client_version": "2.0.0",
},
)
self.assertEqual(auth_payload_device_token("token")["method"], "device_token")
self.assertEqual(auth_payload_user_password("admin", "password")["method"], "user_password")
class BridgeTests(unittest.TestCase):
def test_widget_defaults_and_manifest(self) -> None:
bridge = CDAPBridge(
"ws://127.0.0.1:1/cdap",
device_id="device-1",
device_name="Test bridge",
heartbeat_sec=1,
)
bridge.add_widget(gauge("temperature", "Temperature", max_val=50))
bridge.add_widget(toggle("heater", "Heater"))
manifest = bridge._build_manifest()
self.assertEqual(manifest["manifest_version"], "1.0")
self.assertEqual(manifest["device"]["name"], "Test bridge")
self.assertEqual(manifest["device"]["type"], "iot")
self.assertEqual([widget["id"] for widget in manifest["widgets"]], ["temperature", "heater"])
self.assertEqual(bridge.heartbeat_sec, 5)
def test_command_handler_success_and_failure(self) -> None:
async def exercise() -> list[dict]:
bridge = CDAPBridge("ws://127.0.0.1:1/cdap")
sent: list[dict] = []
async def fake_send(message_type: str, payload: dict) -> None:
sent.append({"type": message_type, "payload": payload})
bridge._send = fake_send # type: ignore[method-assign]
bridge.add_widget(toggle("heater", "Heater"))
@bridge.on_command("heater")
async def handle_heater(**kwargs):
return kwargs["value"]
await bridge._handle_command(
{
"command_id": "command-1",
"widget_id": "heater",
"action": "set",
"value": True,
}
)
return sent
sent = asyncio.run(exercise())
self.assertEqual(sent[0]["type"], "command_response")
self.assertEqual(sent[0]["payload"]["status"], "ok")
self.assertTrue(sent[0]["payload"]["result"])
if __name__ == "__main__":
unittest.main()
+6
View File
@@ -30,6 +30,7 @@ const DEFAULT_ROLE_PERMISSIONS = {
'user.view', 'user.create', 'user.edit', 'user.delete',
'org.create', 'org.edit', 'org.delete', 'org.manage_users', 'org.manage_devices',
'device.view', 'device.connect', 'device.edit', 'device.delete',
'guest.create',
'device.ban', 'device.change_id', 'device.connection_mode',
'audit.view', 'metrics.view',
'cdap.view', 'cdap.command',
@@ -41,6 +42,7 @@ const DEFAULT_ROLE_PERMISSIONS = {
operator: new Set([
'device.view', 'device.connect', 'device.edit', 'device.connection_mode',
'guest.create',
'user.view',
'audit.view', 'metrics.view',
'cdap.view', 'cdap.command',
@@ -55,6 +57,10 @@ const DEFAULT_ROLE_PERMISSIONS = {
'cdap.view',
'chat.access',
]),
guest_issuer: new Set([
'device.view',
'guest.create',
]),
pro: new Set(),
};
+1 -1
View File
@@ -47,7 +47,7 @@ class RDClient {
this._connectionParams = resolvedTimeouts.connection || opts.connection || null;
// Sub-modules
this.conn = new RDConnection();
this.conn = new RDConnection({ deviceId: this.deviceId });
this.proto = new RDProtocol();
this.crypto = new RDCrypto();
this.video = new RDVideo();
+14 -1
View File
@@ -14,6 +14,13 @@ class RDConnection {
const loc = window.location;
const wsProtocol = loc.protocol === 'https:' ? 'wss:' : 'ws:';
this.wsBase = opts.baseUrl || `${wsProtocol}//${loc.host}`;
this.deviceId = String(opts.deviceId || '');
this.guestSessionId = String(opts.guestSessionId || '');
if (!this.guestSessionId && this.deviceId) {
this.guestSessionId = (window.crypto && typeof window.crypto.randomUUID === 'function')
? window.crypto.randomUUID()
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
}
/** @type {WebSocket|null} */
this.rendezvousWs = null;
@@ -35,7 +42,13 @@ class RDConnection {
try {
const q = new URLSearchParams(window.location.search);
const token = q.get('guest') || q.get('t') || window.__guestToken || '';
if (token) return `?guest=${encodeURIComponent(token)}`;
if (token) {
const params = new URLSearchParams();
params.set('guest', token);
if (this.deviceId) params.set('peer_id', this.deviceId);
if (this.guestSessionId) params.set('guest_session', this.guestSessionId);
return `?${params.toString()}`;
}
} catch (_) { /* ignore */ }
return '';
}
@@ -18,7 +18,7 @@ class RDFileConnection {
if (!opts.deviceId) throw new Error('deviceId required');
this.deviceId = opts.deviceId;
this.opts = opts;
this.conn = new RDConnection();
this.conn = new RDConnection({ deviceId: this.deviceId });
this.proto = opts.proto || new RDProtocol();
this.crypto = new RDCrypto();
this._state = 'idle'; // idle | connecting | authenticating | ready | error | disconnected
@@ -115,7 +115,7 @@ class RDFileConnection {
if (this.conn) {
try { this.conn.close(); } catch (_e) { /* ignore */ }
}
this.conn = new RDConnection();
this.conn = new RDConnection({ deviceId: this.deviceId });
this.crypto = new RDCrypto();
this._setState('connecting');
this._emit('log', 'Opening file transfer session…');
+12 -4
View File
@@ -15,6 +15,7 @@ const {
attachGuestGrant,
peerAllowedByGrant,
} = require('../middleware/guestAccess');
const { invalidateGuestGrant } = require('../services/wsRelay');
const { rdClientPageLimiter } = require('../middleware/rateLimiter');
async function assertPeersInScope(req, peerIds) {
@@ -25,7 +26,7 @@ async function assertPeersInScope(req, peerIds) {
// --- Operator APIs ---
router.post('/api/guest/access-links', requireAuth, requirePermission('device.connect'), async (req, res) => {
router.post('/api/guest/access-links', requireAuth, requirePermission('guest.create'), async (req, res) => {
try {
const peerIds = Array.isArray(req.body?.peer_ids) ? req.body.peer_ids.map(String) : [];
if (!peerIds.length) {
@@ -47,13 +48,20 @@ router.post('/api/guest/access-links', requireAuth, requirePermission('device.co
}
});
router.get('/api/guest/access-links', requireAuth, requirePermission('device.connect'), async (req, res) => {
router.get('/api/guest/access-links', requireAuth, requirePermission('guest.create'), async (req, res) => {
return proxyToGo(betterdeskApi.apiClient, req, res, 'GET', '/guest/access-links');
});
router.delete('/api/guest/access-links/:id', requireAuth, requirePermission('device.connect'), async (req, res) => {
router.delete('/api/guest/access-links/:id', requireAuth, requirePermission('guest.create'), async (req, res) => {
const id = encodeURIComponent(req.params.id);
return proxyToGo(betterdeskApi.apiClient, req, res, 'DELETE', `/guest/access-links/${id}`);
try {
const result = await betterdeskApi.apiClient.delete(`/guest/access-links/${id}`);
invalidateGuestGrant(req.params.id);
return res.status(result.status || 200).json(result.data);
} catch (err) {
const status = err.response?.status || 500;
return res.status(status).json(err.response?.data || { error: err.message });
}
});
// --- Public guest APIs (token-gated; no panel session) ---
+259 -13
View File
@@ -14,6 +14,8 @@
const WebSocket = require('ws');
const net = require('net');
const os = require('os');
const path = require('path');
const protobuf = require('protobufjs');
const config = require('../config/config');
const { enforceOrigin } = require('../middleware/wsOrigin');
const { roleHasPermission } = require('../middleware/auth');
@@ -25,6 +27,88 @@ const MAX_CONNECTIONS_PER_IP = 5;
const IDLE_TIMEOUT_MS = 120000;
// RustDesk desktop frames can exceed the small control-message limit.
const MAX_RELAY_FRAME_SIZE = 64 * 1024 * 1024;
const GUEST_REVALIDATION_INTERVAL_MS = 15000;
// grant_id → active bridge cleanup callbacks. This is intentionally local for
// immediate revocation in the current panel process; each bridge also
// revalidates against Go so revocations made by another process are enforced.
const activeGuestBridges = new Map();
const guestSessionStates = new Map();
let rendezvousType = null;
function getRendezvousType() {
if (!rendezvousType) {
const root = protobuf.loadSync(path.join(__dirname, '../protos/rendezvous.proto'));
rendezvousType = root.lookupType('hbb.RendezvousMessage');
}
return rendezvousType;
}
function decodeRendezvousPayload(payload) {
try {
return getRendezvousType().decode(payload);
} catch {
return null;
}
}
function guestTargetMatches(message, peerId) {
if (!message || !peerId) return false;
const request = message.punchHoleRequest || message.requestRelay;
return !request || String(request.id || '') === peerId;
}
function registerGuestBridge(grantId, cleanup) {
if (!grantId || typeof cleanup !== 'function') return () => {};
let bridges = activeGuestBridges.get(grantId);
if (!bridges) {
bridges = new Set();
activeGuestBridges.set(grantId, bridges);
}
bridges.add(cleanup);
return () => {
bridges.delete(cleanup);
if (bridges.size === 0) activeGuestBridges.delete(grantId);
};
}
function invalidateGuestGrant(grantId) {
const normalizedId = String(grantId || '');
const bridges = activeGuestBridges.get(normalizedId);
for (const key of guestSessionStates.keys()) {
if (key.startsWith(`${normalizedId}\0`)) guestSessionStates.delete(key);
}
if (!bridges) return 0;
for (const cleanup of [...bridges]) cleanup('guest-grant-revoked');
return bridges.size;
}
async function consumeGuestSession(grant, token, peerId, sessionId) {
const key = `${grant.id || 'unknown'}\0${sessionId}`;
const existing = guestSessionStates.get(key);
if (existing) return existing;
const pending = (async () => {
const betterdeskApi = require('./betterdeskApi');
await betterdeskApi.apiClient.post('/guest/access-links/consume', {
token,
peer_id: peerId,
});
const expiresAt = new Date(grant.expires_at).getTime();
const lifetime = Number.isFinite(expiresAt)
? Math.max(1000, expiresAt - Date.now())
: GUEST_REVALIDATION_INTERVAL_MS;
setTimeout(() => guestSessionStates.delete(key), lifetime).unref?.();
return true;
})();
guestSessionStates.set(key, pending);
try {
return await pending;
} catch (err) {
guestSessionStates.delete(key);
throw err;
}
}
function encodeRelayFrame(data) {
const payload = Buffer.isBuffer(data) ? data : Buffer.from(data);
@@ -190,11 +274,13 @@ function initWsProxy(server, sessionMiddleware) {
let hasGuest = false;
if (!hasUser) {
let guestToken = '';
let guestPeerId = '';
try {
// Prefer ?guest= on WS URL (session pages always append it for guests)
guestToken = String(
url.searchParams.get('guest') || url.searchParams.get('t') || ''
).trim();
guestPeerId = String(url.searchParams.get('peer_id') || '').trim();
if (!guestToken) {
const { GUEST_COOKIE } = require('../middleware/guestAccess');
const raw = request.headers.cookie || '';
@@ -212,11 +298,22 @@ function initWsProxy(server, sessionMiddleware) {
}
if (guestToken) {
const guestSessionId = String(
url.searchParams.get('guest_session') || ''
).trim();
if (!guestPeerId || !/^[A-Za-z0-9_-]{3,64}$/.test(guestPeerId)
|| !guestSessionId || guestSessionId.length > 128) {
console.warn(`WS proxy: rejected guest upgrade without valid peer_id for ${pathname}`);
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
try {
// Must validate against Go store — non-empty guest= alone is not auth.
// Must validate against Go store and bind the token to
// the requested peer — non-empty guest= alone is not auth.
const betterdeskApi = require('./betterdeskApi');
const result = await betterdeskApi.apiClient.get('/guest/access-links/validate', {
params: { token: guestToken },
params: { token: guestToken, peer_id: guestPeerId },
timeout: 5000,
});
const data = result.data || {};
@@ -224,6 +321,8 @@ function initWsProxy(server, sessionMiddleware) {
hasGuest = true;
request.guestToken = guestToken;
request.guestGrant = data;
request.guestPeerId = guestPeerId;
request.guestSessionId = guestSessionId;
}
} catch (err) {
console.warn(
@@ -283,13 +382,22 @@ function initWsProxy(server, sessionMiddleware) {
// Rendezvous connections
rendezvousWss.on('connection', (ws, req) => {
handleProxyConnection(ws, req, hbbsHost, hbbsPort, 'rendezvous');
handleProxyConnection(ws, req, hbbsHost, hbbsPort, 'rendezvous', {
guestGrant: req.guestGrant,
guestToken: req.guestToken,
guestPeerId: req.guestPeerId,
guestSessionId: req.guestSessionId,
});
});
// Relay connections
relayWss.on('connection', (ws, req) => {
handleProxyConnection(ws, req, hbbrHost, hbbrPort, 'relay', {
messageTransport: ws._betterdeskMessageTransport === true,
guestGrant: req.guestGrant,
guestToken: req.guestToken,
guestPeerId: req.guestPeerId,
guestSessionId: req.guestSessionId,
});
});
@@ -320,6 +428,19 @@ function handleProxyConnection(ws, req, targetHost, targetPort, label, options =
let idleTimer = null;
const messageTransport = options.messageTransport === true;
const relayDecoder = messageTransport ? createRelayFrameDecoder() : null;
const guestGrant = options.guestGrant || null;
const guestToken = String(options.guestToken || '').trim();
const guestPeerId = String(options.guestPeerId || '').trim();
const guestRendezvousDecoder = guestGrant && label === 'rendezvous'
? createRelayFrameDecoder()
: null;
let guestRelayBuffer = Buffer.alloc(0);
let guestRelayValidated = false;
let guestSessionConsumed = false;
let guestOpenedAt = 0;
let guestOpenedReported = false;
let guestValidationTimer = null;
let unregisterGuestBridge = () => {};
let cleanupCause = 'unknown';
let wsCloseCode = null;
let wsCloseReason = '';
@@ -331,6 +452,26 @@ function handleProxyConnection(ws, req, targetHost, targetPort, label, options =
}, IDLE_TIMEOUT_MS);
};
function reportGuestEvent(event, reason = '') {
if (!guestGrant || !guestPeerId) return;
const betterdeskApi = require('./betterdeskApi');
const duration = guestOpenedAt
? Math.max(0, Date.now() - guestOpenedAt)
: 0;
betterdeskApi.apiClient.post('/guest/access-links/events', {
event,
grant_id: guestGrant.id || '',
peer_id: guestPeerId,
session_id: options.guestSessionId || '',
transport: label,
source_ip: clientIp,
duration_ms: duration,
reason,
}).catch((err) => {
console.warn(`WS proxy [${label}]: guest audit event failed: ${err.message || err}`);
});
}
// Connect to target TCP server
const tcp = net.createConnection({ host: targetHost, port: targetPort }, () => {
resetIdleTimer();
@@ -366,17 +507,80 @@ function handleProxyConnection(ws, req, targetHost, targetPort, label, options =
// WebSocket -> TCP
ws.on('message', (data) => {
resetIdleTimer();
if (!tcp.destroyed) {
// Ensure we send Buffer, not string
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
try {
tcp.write(messageTransport ? encodeRelayFrame(buf) : buf);
} catch (err) {
console.error(`WS proxy [${label}]: invalid relay WS frame:`, err.message);
cleanup('invalid-ws-frame', { error: err.message });
void (async () => {
resetIdleTimer();
if (!tcp.destroyed) {
// Ensure we send Buffer, not string
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
try {
let isGuestSessionOpening = false;
if (guestGrant) {
if (label === 'rendezvous') {
for (const payload of guestRendezvousDecoder.feed(buf)) {
const message = decodeRendezvousPayload(payload);
if (!message || !guestTargetMatches(message, guestPeerId)) {
console.warn(
`WS proxy [${label}]: guest target mismatch for grant ${guestGrant.id || 'unknown'}`
);
cleanup('guest-target-mismatch');
return;
}
if (message.punchHoleRequest || message.requestRelay) {
isGuestSessionOpening = true;
}
}
} else if (!guestRelayValidated) {
if (guestRelayBuffer.length + buf.length > 1024 * 1024) {
cleanup('guest-invalid-relay-frame');
return;
}
guestRelayBuffer = Buffer.concat([guestRelayBuffer, buf]);
const message = decodeRendezvousPayload(guestRelayBuffer);
if (!message) return;
const request = message.requestRelay;
if (!request || String(request.id || '') !== guestPeerId) {
console.warn(
`WS proxy [${label}]: guest relay target mismatch for grant ${guestGrant.id || 'unknown'}`
);
cleanup('guest-target-mismatch');
return;
}
guestRelayValidated = true;
isGuestSessionOpening = true;
}
}
if (guestGrant && isGuestSessionOpening && !guestSessionConsumed) {
try {
await consumeGuestSession(
guestGrant,
guestToken,
guestPeerId,
options.guestSessionId
);
if (cleaned) return;
guestSessionConsumed = true;
guestOpenedAt = Date.now();
if (!guestOpenedReported) {
guestOpenedReported = true;
reportGuestEvent('opened');
}
} catch (err) {
console.warn(
`WS proxy [${label}]: guest session rejected: ${err.message || err}`
);
cleanup('guest-use-rejected');
return;
}
}
tcp.write(messageTransport ? encodeRelayFrame(buf) : buf);
} catch (err) {
console.error(`WS proxy [${label}]: invalid relay WS frame:`, err.message);
cleanup('invalid-ws-frame', { error: err.message });
}
}
}
})();
});
ws.on('close', (code, reason) => {
@@ -397,6 +601,9 @@ function handleProxyConnection(ws, req, targetHost, targetPort, label, options =
cleanupCause = cause;
if (idleTimer) clearTimeout(idleTimer);
if (guestValidationTimer) clearTimeout(guestValidationTimer);
unregisterGuestBridge();
if (guestOpenedReported) reportGuestEvent('closed', cause);
if (!tcp.destroyed) {
tcp.destroy();
@@ -421,9 +628,48 @@ function handleProxyConnection(ws, req, targetHost, targetPort, label, options =
: '';
console.log(`WS proxy [${label}]: closed for ${clientIp} cause=${cleanupCause}${closeSuffix}${detailSuffix}`);
}
if (guestGrant && guestToken && guestPeerId) {
unregisterGuestBridge = registerGuestBridge(guestGrant.id, cleanup);
const revalidateGuestGrant = async () => {
if (cleaned) return;
try {
const betterdeskApi = require('./betterdeskApi');
const result = await betterdeskApi.apiClient.get('/guest/access-links/validate', {
params: { token: guestToken, peer_id: guestPeerId },
timeout: 5000,
});
if (!result.data?.valid) {
cleanup('guest-grant-invalid');
return;
}
} catch (err) {
console.warn(
`WS proxy [${label}]: guest grant revalidation failed: ${err.message || err}`
);
// A failed dependency check is not proof of revocation. Retry
// until the grant's own expiry, then close deterministically.
}
if (cleaned) return;
const expiresAt = new Date(guestGrant.expires_at).getTime();
const remaining = Number.isFinite(expiresAt) ? expiresAt - Date.now() : 0;
if (remaining <= 0) {
cleanup('guest-grant-expired');
return;
}
guestValidationTimer = setTimeout(
revalidateGuestGrant,
Math.min(GUEST_REVALIDATION_INTERVAL_MS, remaining)
);
};
revalidateGuestGrant();
}
}
module.exports = {
initWsProxy,
invalidateGuestGrant,
_guestProtocol: { decodeRendezvousPayload, guestTargetMatches },
_relayFraming: { encodeRelayFrame, createRelayFrameDecoder, MAX_RELAY_FRAME_SIZE },
};
@@ -0,0 +1,133 @@
'use strict';
const path = require('path');
const express = require('express');
const request = require('supertest');
jest.mock('../services/betterdeskApi', () => ({
apiClient: Object.assign(jest.fn(), {
get: jest.fn(),
post: jest.fn(),
}),
}));
jest.mock('../services/deviceGroupService', () => ({
getDeviceScopeForUser: jest.fn().mockResolvedValue(new Set(['TARGET01'])),
}));
jest.mock('../services/database', () => ({
getDevice: jest.fn().mockResolvedValue(null),
}));
jest.mock('../services/keyService', () => ({
resolvePublicKey: jest.fn().mockResolvedValue(''),
}));
jest.mock('../services/serverConnectionConfigService', () => ({
getConnectionMode: jest.fn().mockResolvedValue({ mode: 'p2p_first', p2p_fallback_ms: 2000 }),
}));
const betterdeskApi = require('../services/betterdeskApi');
const remoteRoutes = require('../routes/remote.routes');
const guestRoutes = require('../routes/guest.routes');
function buildApp() {
const app = express();
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
Object.assign(app.locals, {
appName: 'BetterDesk',
cacheVersion: 'test',
cspNonce: 'test-nonce',
lang: 'en',
translations: {},
branding: {},
availableLanguageList: [],
user: null,
});
app.use((req, res, next) => {
req.session = {
userId: 7,
user: { username: 'issuer', role: 'guest_issuer' },
};
req.t = (_key, fallback) => fallback || _key;
res.locals._ = (_key, fallback) => fallback || _key;
next();
});
app.use(express.json());
app.use(remoteRoutes);
app.use(guestRoutes);
return app;
}
describe('Guest Access Link page integration', () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('renders the guest page for a valid token', async () => {
betterdeskApi.apiClient.get.mockResolvedValueOnce({
status: 200,
data: {
valid: true,
view_only: true,
expires_at: new Date(Date.now() + 60000).toISOString(),
devices: [{ id: 'TARGET01', online: true }],
},
});
const response = await request(buildApp()).get('/remote/guest?t=guest-token');
expect(response.status).toBe(200);
expect(response.text).toContain('window.__guestAccess =');
expect(response.headers['set-cookie'][0]).toContain('guest-token');
expect(betterdeskApi.apiClient.get).toHaveBeenCalledWith(
'/guest/access-links/peers',
{ params: { token: 'guest-token' } }
);
});
test('returns 403 for an expired or invalid token instead of a 500 page', async () => {
betterdeskApi.apiClient.get.mockResolvedValueOnce({
status: 403,
data: { valid: false, error: 'guest link expired' },
});
const response = await request(buildApp()).get('/remote/guest?t=expired-token');
expect(response.status).toBe(403);
expect(response.text).toContain('403 - Forbidden');
expect(response.text).not.toContain('500 - Server Error');
});
test('creates an allowlisted link and reaches the guest page with its token', async () => {
betterdeskApi.apiClient.mockResolvedValueOnce({
status: 201,
data: {
path: '/remote/guest?t=created-token',
token: 'created-token',
peer_ids: ['TARGET01'],
},
});
const create = await request(buildApp())
.post('/api/guest/access-links')
.send({ peer_ids: ['TARGET01'], ttl_minutes: 30, view_only: true });
expect(create.status).toBe(201);
expect(create.body.path).toBe('/remote/guest?t=created-token');
expect(betterdeskApi.apiClient).toHaveBeenCalledWith(expect.objectContaining({
method: 'POST',
url: '/guest/access-links',
data: expect.objectContaining({ peer_ids: ['TARGET01'] }),
}));
betterdeskApi.apiClient.get.mockResolvedValueOnce({
status: 200,
data: {
valid: true,
view_only: true,
expires_at: new Date(Date.now() + 60000).toISOString(),
devices: [{ id: 'TARGET01', online: true }],
},
});
const page = await request(buildApp()).get(create.body.path);
expect(page.status).toBe(200);
expect(page.text).toContain('window.__guestAccess =');
});
});
@@ -11,6 +11,7 @@ function loadBrowserScript(relativePath, globals = {}) {
Uint8Array,
ArrayBuffer,
URL,
URLSearchParams,
...globals,
};
sandbox.window = sandbox;
@@ -71,6 +72,37 @@ describe('RDConnection native relay WebSocket transport', () => {
await expect(opening).resolves.toBe(sockets[0]);
});
test('binds guest relay URLs to the target and logical session', async () => {
const sockets = [];
class MockWebSocket {
static OPEN = 1;
constructor(url) {
this.url = url;
sockets.push(this);
}
}
const sandbox = loadBrowserScript('public/js/rdclient/connection.js', {
location: {
protocol: 'https:',
host: 'console.example.test',
search: '?guest=guest-token',
},
crypto: { randomUUID: () => 'guest-session-1' },
__guestToken: 'guest-token',
WebSocket: MockWebSocket,
});
const connection = new sandbox.RDConnection({ deviceId: 'TARGET01' });
const opening = connection.connectRelay();
expect(new URL(sockets[0].url).searchParams.get('guest')).toBe('guest-token');
expect(new URL(sockets[0].url).searchParams.get('peer_id')).toBe('TARGET01');
expect(new URL(sockets[0].url).searchParams.get('guest_session')).toBe('guest-session-1');
sockets[0].onopen();
await expect(opening).resolves.toBe(sockets[0]);
});
test('preserves WebSocket close code and reason for relay diagnostics', async () => {
const sockets = [];
class MockWebSocket {
+35 -1
View File
@@ -227,10 +227,44 @@ describe('wsRelay — security: session validation on WS upgrade', () => {
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
address = server.address();
const result = await rawUpgrade(address, '/ws/rendezvous?guest=not-a-real-token');
const result = await rawUpgrade(
address,
'/ws/rendezvous?guest=not-a-real-token&peer_id=TARGET01&guest_session=test-session'
);
expect(result.statusLine).toBe('HTTP/1.1 401 Unauthorized');
});
test('rejects guest upgrade without a target binding', async () => {
const noSession = (req, _res, next) => {
req.session = null;
next();
};
const { initWsProxy } = require('../services/wsRelay');
server = http.createServer((req, res) => { res.writeHead(404); res.end(); });
initWsProxy(server, noSession);
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
address = server.address();
const result = await rawUpgrade(address, '/ws/rendezvous?guest=valid-token');
expect(result.statusLine).toBe('HTTP/1.1 403 Forbidden');
});
test('does not trust a guest page when the protobuf target changes', () => {
const protobuf = require('protobufjs');
const root = protobuf.loadSync(require('path').join(__dirname, '../protos/rendezvous.proto'));
const type = root.lookupType('hbb.RendezvousMessage');
const payload = type.encode(type.create({
punchHoleRequest: { id: 'OTHER01' },
})).finish();
const { _guestProtocol } = require('../services/wsRelay');
const message = _guestProtocol.decodeRendezvousPayload(payload);
expect(_guestProtocol.guestTargetMatches(message, 'TARGET01')).toBe(false);
expect(_guestProtocol.guestTargetMatches(message, 'OTHER01')).toBe(true);
});
// ── Test: non-ws-relay paths are not handled by initWsProxy ──────────────
test('does not intercept paths outside /ws/rendezvous and /ws/relay', () => {
const EventEmitter = require('events');