diff --git a/Dockerfile b/Dockerfile index 96caf40..3f3efc2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,6 +28,7 @@ RUN pnpm install --prod --frozen-lockfile COPY server ./server COPY public ./public COPY agent ./agent +COPY scripts ./scripts COPY --from=agent-exe /build/dist/rcs-agent.exe ./dist/rcs-agent.exe VOLUME ["/data"] diff --git a/README.md b/README.md index 015510b..bc16851 100644 --- a/README.md +++ b/README.md @@ -90,15 +90,61 @@ LAN as the hub. ### Agent (the machine dials out) -**Invite a machine** produces a link. Open it on the target machine and it shows a -one-liner: +**Invite a machine** produces a link. Open it on the target machine and it shows the +command with the token already in it. The full walkthrough — per OS, with service +management and troubleshooting — is served at +[`/docs`](https://support.freakma.com/docs). + +## Registering a device + +One command per platform. The hub substitutes its own address and the enrolment token +into the script before serving it, so there is nothing to fill in but `TOKEN`. + +**macOS and Linux** ```bash -curl -fsSL https://your-hub/download/agent.js -o rcs-agent.js \ - && node rcs-agent.js enroll https://your-hub/enroll/TOKEN \ - && node rcs-agent.js run +curl -fsSL https://support.freakma.com/install.sh?token=TOKEN | sh ``` +**Windows** + +```powershell +irm https://support.freakma.com/install.ps1?token=TOKEN | iex +``` + +**Windows 7 / Server 2008 R2** — PowerShell 2.0 has no `irm`, and .NET 3.5 does not +negotiate TLS 1.2 without [KB3154518](https://support.microsoft.com/kb/3154518), so +the short form fails twice over. From `cmd.exe`: + +```bat +powershell -c "[Net.ServicePointManager]::SecurityProtocol=3072; (New-Object Net.WebClient).DownloadString('https://support.freakma.com/install.ps1?token=TOKEN') | iex" +``` + +What the scripts do, in order: check for a usable runtime and stop with instructions +rather than guessing; warn if nothing is listening on `127.0.0.1:5900`; download the +agent into a per-user directory; enrol, exchanging the one-time token for an agent key +written `0600`; and register a login-scoped service. + +| Platform | Installs to | Kept alive by | +|---|---|---| +| macOS | `~/.rcs-agent` | launchd agent, `com.freakma.rcs-agent` | +| Linux | `~/.rcs-agent` | systemd **user** service `rcs-agent`, with lingering enabled | +| Windows | `%LOCALAPPDATA%\RemoteControlSupport` | logon task `RemoteControlSupportAgent` | + +Nothing needs root or administrator. On Windows the installer uses Node 22 if it is +already there and falls back to the self-contained `rcs-agent.exe` otherwise, so the +same command works on a fresh Windows 11 box and on Server 2008 R2. + +The Windows installer deliberately registers a **logon task, not a service**: services +run in session 0 and cannot draw on the interactive desktop, so the *ask first* consent +prompt would never appear and every session would time out waiting for an answer. + +Both scripts are plain text and worth reading before piping them into a shell — +[`/install.sh`](https://support.freakma.com/install.sh) and +[`/install.ps1`](https://support.freakma.com/install.ps1) are exactly what runs. + +### Doing it by hand + The agent needs Node 22+ and a VNC server listening on `127.0.0.1:5900`: | OS | VNC server | @@ -233,6 +279,9 @@ Everything is environment variables — see [.env.example](.env.example). | `POST` | `/api/sessions/:id/kill` | admin | | `GET` | `/api/sessions/history` | | | `GET` | `/api/sessions/audit` | admin | +| `GET` | `/docs` | setup guide, no auth | +| `GET` | `/download/agent.js` · `/download/agent.exe` | no auth | +| `GET` | `/install.sh` · `/install.ps1` | no auth, `?token=` is stamped in | | `POST` | `/api/public/enroll` | no auth, enrolment token | | `POST` | `/api/public/session/:token` | no auth, support link | | WS | `/ws/vnc?ticket=` | browser session | diff --git a/public/docs.html b/public/docs.html new file mode 100644 index 0000000..6840907 --- /dev/null +++ b/public/docs.html @@ -0,0 +1,339 @@ + + + + + + + Registering a device — Remote Support + + + + + + + +
+ +
+
RC
+
+ Remote Support + Documentation +
+
Back to console
+
+ + Setup guide +

Registering a device

+

+ How to put a machine under remote support, on macOS, Windows and Linux — what to install, + what the one-command installer actually does, and how to keep it running. +

+ +

Before you start

+

+ Every registered machine needs two things: a VNC server serving its screen on + 127.0.0.1:5900, and the agent, which dials out to this + hub and forwards that port over an authenticated WebSocket. The agent is what makes NAT and + firewalls stop mattering — nothing inbound is ever opened on the machine. +

+

+ You also need an enrollment link. In the console, open + Machines → Invite a machine. The link carries a one-time token and expires; + open it on the machine being registered and it shows the exact command with the token already + filled in. +

+ +
+ The alternative is direct mode, where this hub connects straight to the + machine's VNC port. That only works when the hub can route to it. If the machine is on another + subnet, behind NAT, or reachable only through a VPN or SSH tunnel, use the agent — a direct + entry will just time out. +
+ +

Pick a platform

+ + + +
+

1. Turn on Screen Sharing

+

+ System Settings → General → Sharing → Screen Sharing. Under + Computer Settings, enable VNC viewers may control screen with password and + set a password — the hub authenticates with it and never passes it to the browser. +

+

+ macOS serves VNC on port 5900 on all interfaces. The agent only ever connects to it over + loopback, so you can firewall the port off from the network. +

+ +

2. Install Node.js 22 or newer

+

+ brew install node, or the installer from + nodejs.org. Check with + node -v. +

+ +

3. Run the installer

+

Paste this in Terminal, replacing TOKEN with the one from your enrollment link:

+
+

+      
+    
+

+ It installs to ~/.rcs-agent, enrolls the machine, and loads a + launchd agent so it starts at login and restarts if it dies. +

+ +

Managing it

+ + + + + + +
Do thisCommand
Stoplaunchctl unload ~/Library/LaunchAgents/com.freakma.rcs-agent.plist
Startlaunchctl load ~/Library/LaunchAgents/com.freakma.rcs-agent.plist
Watch the logtail -f ~/.rcs-agent/agent.log
Removelaunchctl unload …plist && rm -rf ~/.rcs-agent
+
+ + + + + + + +

Registering a machine that cannot run the agent

+

+ Printers, appliances, locked-down boxes, anything too old for a current runtime — the agent + does not have to run on the machine it serves. Run it on any other machine on the same + LAN and point it across: +

+
+

+    
+  
+

+ That host now needs to reach the target's VNC port, and it becomes the machine whose uptime + determines whether the target is reachable. +

+ +

Checking it worked

+ + +

When it does not

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SymptomCause
timed out connecting to …:5900This hub cannot route to that address. A direct-mode entry on a subnet the hub cannot + reach — register it with the agent instead.
cannot reach …:5900 (ECONNREFUSED)Routing is fine, nothing is listening. The VNC server is not running.
VNC authentication failedWrong stored password. Note that VNC authentication only uses the first 8 characters.
Enrollment says the link expiredEnrollment tokens are one-time and time-limited. Mint a new one.
Machine shows offline right after installThe agent is not running. Check the service commands for your platform above.
Sessions hang on "waiting for consent"Ask first is on and the agent cannot show a dialog — it is running headless, as + a Windows service, or on Linux without zenity/kdialog.
+ +

What the installer does

+

+ Both scripts are served by this hub with its address and your token already substituted in, so + there is nothing to fill in. They are worth reading before you pipe them into a shell — + install.sh and + install.ps1 are the exact text that runs. In order they: +

+ + +

+ Access control, support links and session policy are covered in the project README. +

+
+ + + + + + diff --git a/public/enroll.html b/public/enroll.html index 614eaf9..956d3c4 100644 --- a/public/enroll.html +++ b/public/enroll.html @@ -36,47 +36,81 @@ until you stop the agent.

-
    + + +
    1. - Make sure a VNC server is running on this machine, listening on - 127.0.0.1:5900. + Turn on Screen Sharing — System Settings → General → Sharing.
      - macOS: System Settings → General → Sharing → Screen Sharing.
      - Windows: install TightVNC or UltraVNC.
      - Linux: x11vnc -localhost -rfbport 5900. + Under Computer Settings, allow VNC viewers and set a password.
    2. Install Node.js 22+ if it is not already there.
    3. - Run this in a terminal: -
      
      +            Paste this into Terminal:
      +            
      
                   
      - - +
    -
    - On Windows 7 or Server 2008 R2? + + + + +
    @@ -88,10 +122,20 @@ const origin = location.origin; const link = `${origin}/enroll/${token}`; - const unix = `curl -fsSL ${origin}/download/agent.js -o rcs-agent.js \\\n && node rcs-agent.js enroll ${link} \\\n && node rcs-agent.js run`; - const win = `iwr ${origin}/download/agent.js -OutFile rcs-agent.js; ` - + `node rcs-agent.js enroll ${link}; node rcs-agent.js run`; - const exe = `rcs-agent.exe enroll ${link}\r\nrcs-agent.exe run`; + // The hub stamps its own address and this token into the install scripts, so + // each of these really is the whole command — nothing to fill in by hand. + const commands = { + 'cmd-macos': `curl -fsSL ${origin}/install.sh?token=${token} | sh`, + 'cmd-linux': `curl -fsSL ${origin}/install.sh?token=${token} | sh`, + 'cmd-windows': `irm ${origin}/install.ps1?token=${token} | iex`, + 'cmd-windows-legacy': `powershell -c "[Net.ServicePointManager]::SecurityProtocol=3072; (New-Object Net.WebClient).DownloadString('${origin}/install.ps1?token=${token}') | iex"`, + 'cmd-linux-x11vnc': 'x11vnc -localhost -rfbport 5900 -forever -shared -passwd YOURPASSWORD', + }; + + for (const [id, text] of Object.entries(commands)) { + const el = document.getElementById(id); + if (el) el.textContent = text; + } function copy(text, button) { navigator.clipboard.writeText(text).then(() => { @@ -101,11 +145,27 @@ }); } - document.getElementById('oneliner').textContent = unix; - document.getElementById('copy-unix').onclick = (e) => copy(unix, e.currentTarget); - document.getElementById('copy-win').onclick = (e) => copy(win, e.currentTarget); - document.getElementById('exe-oneliner').textContent = exe; - document.getElementById('copy-exe').onclick = (e) => copy(exe, e.currentTarget); + document.querySelectorAll('[data-copy]').forEach((button) => { + button.onclick = () => copy(commands[button.dataset.copy], button); + }); + + const tabs = document.getElementById('os-tabs'); + const legacyNotice = document.getElementById('legacy-windows'); + tabs.onclick = (event) => { + const button = event.target.closest('button[data-os]'); + if (!button) return; + tabs.querySelectorAll('button').forEach((b) => b.classList.toggle('active', b === button)); + document.querySelectorAll('.os-panel').forEach((panel) => { + panel.hidden = panel.dataset.os !== button.dataset.os; + }); + legacyNotice.classList.toggle('hidden', button.dataset.os !== 'windows'); + }; + + // Open on the tab for whatever this machine is — it is the machine being set up. + const guess = /Mac/i.test(navigator.platform) ? 'macos' + : /Win/i.test(navigator.platform) ? 'windows' + : /Linux/i.test(navigator.platform) ? 'linux' : null; + if (guess) tabs.querySelector(`button[data-os="${guess}"]`).click(); fetch(`/api/public/invite/${encodeURIComponent(token)}`) .then((r) => r.json().then((body) => ({ ok: r.ok, body }))) diff --git a/public/index.html b/public/index.html index 9f16d2f..9a27e35 100644 --- a/public/index.html +++ b/public/index.html @@ -87,6 +87,7 @@
    + Setup guide diff --git a/public/styles.css b/public/styles.css index 6411f3e..4ecdc02 100644 --- a/public/styles.css +++ b/public/styles.css @@ -205,6 +205,36 @@ button.ghost.danger:hover:not(:disabled) { background: rgba(244,98,111,.12); } button.small { padding: 5px 11px; font-size: 12.5px; border-radius: 6px; } +/* Links that have to read as controls: downloads, and anything that navigates + rather than acts. Same surface as a button, minus the states a link cannot + have. Keep the modifiers in sync with the button rules above. */ +a.btn { + display: inline-flex; + align-items: center; + text-decoration: none; + font: 500 13.5px/1.2 var(--sans); + letter-spacing: .005em; + padding: 8px 14px; + border-radius: var(--r-sm); + border: 1px solid var(--line-strong); + background: var(--surface-2); + color: var(--text); + white-space: nowrap; + transition: border-color var(--t-fast), background var(--t-fast), + color var(--t-fast), box-shadow var(--t-fast); +} +a.btn:hover { background: var(--surface-3); border-color: var(--line-hover); } +a.btn.small { padding: 5px 11px; font-size: 12.5px; border-radius: 6px; } +a.btn.ghost { background: transparent; border-color: transparent; color: var(--text-dim); } +a.btn.ghost:hover { background: var(--surface-2); color: var(--text); } +a.btn.primary { + background: var(--mint); + border-color: var(--mint); + color: var(--mint-ink); + font-weight: 650; +} +a.btn.primary:hover { background: var(--mint-bright); border-color: var(--mint-bright); } + /* ------------------------------------------------------------------ forms */ input, select, textarea { diff --git a/scripts/install.ps1 b/scripts/install.ps1 new file mode 100644 index 0000000..290b608 --- /dev/null +++ b/scripts/install.ps1 @@ -0,0 +1,106 @@ +# Remote Control Support - agent installer for Windows. +# +# Served from the hub, which substitutes HUB and TOKEN below before sending it: +# +# irm https://support.freakma.com/install.ps1?token=TOKEN | iex +# +# Windows 7 / Server 2008 R2 ship PowerShell 2.0, which has no Invoke-RestMethod +# and no TLS 1.2, so those machines need the longer form instead: +# +# powershell -c "[Net.ServicePointManager]::SecurityProtocol=3072; (New-Object Net.WebClient).DownloadString('https://support.freakma.com/install.ps1?token=TOKEN') | iex" +# +# Everything is written under %LOCALAPPDATA%. No administrator rights needed. + +$ErrorActionPreference = 'Stop' + +$Hub = '__HUB__' +$Token = '__TOKEN__' + +# .NET 3.5 has no Tls12 enum member, so the numeric value is the portable way. +# Harmless on modern Windows, essential on 2008 R2 (which also needs KB3154518). +try { [Net.ServicePointManager]::SecurityProtocol = 3072 } catch { } + +function Write-Step { param($m) Write-Host "> $m" -ForegroundColor Cyan } +function Write-Warn { param($m) Write-Host "! $m" -ForegroundColor Yellow } +function Write-Die { param($m) Write-Host "x $m" -ForegroundColor Red; exit 1 } + +if (-not $Token) { + Write-Die "no enrolment token. Open the invite link on this machine to get the full command." +} + +$InstallDir = Join-Path $env:LOCALAPPDATA 'RemoteControlSupport' +$Config = Join-Path $InstallDir 'config.json' +$TaskName = 'RemoteControlSupportAgent' + +if (-not (Test-Path $InstallDir)) { New-Item -ItemType Directory -Path $InstallDir | Out-Null } + +$client = New-Object Net.WebClient + +# ------------------------------------------------------------------ runtime + +# Node 22 is preferred where it exists: smaller download, current runtime. Where +# it does not - which includes every Windows 7 and Server 2008 R2 box, since +# Node 14 dropped them - the self-contained executable carries its own Node 12. +$NodeMajor = 0 +try { $NodeMajor = [int]((& node -p 'process.versions.node.split(".")[0]') 2>$null) } catch { } + +if ($NodeMajor -ge 22) { + Write-Step "using the Node.js $NodeMajor already installed here" + $AgentPath = Join-Path $InstallDir 'agent.js' + $client.DownloadFile("$Hub/download/agent.js", $AgentPath) + $Exe = 'node' + $Args = @($AgentPath) +} else { + Write-Step "no Node.js 22+ here - downloading the self-contained agent (about 30 MB)" + $AgentPath = Join-Path $InstallDir 'rcs-agent.exe' + $client.DownloadFile("$Hub/download/agent.exe", $AgentPath) + $Exe = $AgentPath + $Args = @() +} + +# ---------------------------------------------------------------------- vnc + +# Advisory: the agent enrols fine without it, but a session cannot start until +# something is actually serving RFB on the loopback port. +$vncUp = $false +try { + $probe = New-Object Net.Sockets.TcpClient + $probe.Connect('127.0.0.1', 5900) + $vncUp = $probe.Connected + $probe.Close() +} catch { } +if (-not $vncUp) { + Write-Warn "nothing is listening on 127.0.0.1:5900 - install TightVNC or UltraVNC and let it start on boot" +} + +# ------------------------------------------------------------------ enrol + +Write-Step "enrolling with $Hub" +& $Exe @($Args + @('enroll', "$Hub/enroll/$Token", '--config', $Config)) +if ($LASTEXITCODE -ne 0) { Write-Die "enrolment failed - the link may have expired" } + +# --------------------------------------------------------------- scheduled + +# A Windows *service* runs in session 0 and cannot draw on the interactive +# desktop, so the "ask first" consent dialog would never appear. A logon task +# runs in the console session, where it can. schtasks.exe is used rather than +# Register-ScheduledTask because PowerShell 2.0 does not have that cmdlet. +Write-Step "registering a logon task so it starts with Windows" + +if ($Args.Count -gt 0) { + $run = '"' + $Exe + '" "' + $Args[0] + '" run --config "' + $Config + '"' +} else { + $run = '"' + $Exe + '" run --config "' + $Config + '"' +} + +& schtasks.exe /create /tn $TaskName /tr $run /sc onlogon /f | Out-Null +if ($LASTEXITCODE -ne 0) { + Write-Warn "could not register the logon task - start the agent by hand with: $run" +} else { + & schtasks.exe /run /tn $TaskName | Out-Null +} + +Write-Host "" +Write-Host "Done. This machine is registered and should now appear in the console." +Write-Host "Installed in: $InstallDir" +Write-Host "Remove with: schtasks /delete /tn $TaskName /f" diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100644 index 0000000..b095973 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,167 @@ +#!/bin/sh +# Remote Control Support — agent installer for macOS and Linux. +# +# Served from the hub, which substitutes HUB and TOKEN below before sending it, +# so the published one-liner carries the enrolment token in its URL: +# +# curl -fsSL https://support.freakma.com/install.sh?token=TOKEN | sh +# +# Fetched without a token it still works, taking one as an argument instead: +# +# curl -fsSL https://support.freakma.com/install.sh | sh -s -- TOKEN +# +# Everything lands under ~/.rcs-agent. Nothing here needs root. + +set -eu + +HUB="__HUB__" +TOKEN="__TOKEN__" + +# Written long-hand rather than `[ $# -gt 0 ] && TOKEN="$1"`: under `set -e` the +# short-circuit form leaves the script's exit status at 1 when no argument was +# given, which is the normal case for the piped one-liner. +if [ $# -gt 0 ]; then TOKEN="$1"; fi + +INSTALL_DIR="$HOME/.rcs-agent" +AGENT="$INSTALL_DIR/agent.js" +CONFIG="$INSTALL_DIR/config.json" +SERVICE_NAME="rcs-agent" + +say() { printf '%s\n' "$*"; } +warn() { printf '\033[33m!\033[0m %s\n' "$*" >&2; } +die() { printf '\033[31mx\033[0m %s\n' "$*" >&2; exit 1; } +step() { printf '\033[36m>\033[0m %s\n' "$*"; } + +[ -n "$TOKEN" ] || die "no enrolment token. Open the invite link on this machine, or pass one: + curl -fsSL $HUB/install.sh | sh -s -- YOUR_TOKEN" + +case "$(uname -s)" in + Darwin) PLATFORM=macos ;; + Linux) PLATFORM=linux ;; + *) die "$(uname -s) is not supported by this script — see $HUB/docs" ;; +esac + +# ------------------------------------------------------------------ node + +# The agent uses the global WebSocket, which is only on by default from Node 22. +command -v node >/dev/null 2>&1 || die "Node.js 22 or newer is required and was not found. + macOS: brew install node (or https://nodejs.org) + Debian: curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt install -y nodejs + Fedora: sudo dnf install nodejs" + +NODE_MAJOR=$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0) +[ "$NODE_MAJOR" -ge 22 ] 2>/dev/null || die "Node.js 22 or newer is required — this machine has $(node -v). + Upgrade it, or run the agent on another machine on this LAN and point it here: + node agent.js enroll --vnc-host $(hostname)" + +# ------------------------------------------------------------------- vnc + +# Advisory only: the VNC server can be started after enrolment, and on a fresh +# macOS the Screen Sharing toggle is usually the last thing someone does. +vnc_listening() { + if command -v nc >/dev/null 2>&1; then nc -z -w 2 127.0.0.1 5900 >/dev/null 2>&1; return $?; fi + return 1 +} + +if ! vnc_listening; then + case "$PLATFORM" in + macos) warn "nothing is listening on 127.0.0.1:5900 — turn on System Settings > General > Sharing > Screen Sharing" ;; + linux) warn "nothing is listening on 127.0.0.1:5900 — start one, e.g. x11vnc -localhost -rfbport 5900" ;; + esac +fi + +# --------------------------------------------------------------- install + +step "installing to $INSTALL_DIR" +mkdir -p "$INSTALL_DIR" +curl -fsSL "$HUB/download/agent.js" -o "$AGENT" || die "could not download the agent from $HUB" + +step "enrolling with $HUB" +node "$AGENT" enroll "$HUB/enroll/$TOKEN" --config "$CONFIG" + +# --------------------------------------------------------------- service + +NODE_BIN=$(command -v node) + +install_launchd() { + PLIST="$HOME/Library/LaunchAgents/com.freakma.rcs-agent.plist" + mkdir -p "$HOME/Library/LaunchAgents" + cat > "$PLIST" < + + + + Labelcom.freakma.rcs-agent + ProgramArguments + + $NODE_BIN + $AGENT + run + --config + $CONFIG + + RunAtLoad + KeepAlive + StandardOutPath$INSTALL_DIR/agent.log + StandardErrorPath$INSTALL_DIR/agent.log + + +PLIST_EOF + launchctl unload "$PLIST" >/dev/null 2>&1 || true + launchctl load "$PLIST" + say "" + say "Running as a launchd agent. Useful commands:" + say " launchctl unload $PLIST # stop" + say " launchctl load $PLIST # start" + say " tail -f $INSTALL_DIR/agent.log" +} + +install_systemd_user() { + UNIT_DIR="$HOME/.config/systemd/user" + mkdir -p "$UNIT_DIR" + cat > "$UNIT_DIR/$SERVICE_NAME.service" </dev/null 2>&1 \ + || warn "run 'sudo loginctl enable-linger $(id -un)' so the agent survives logout" +} + +install_manual() { + say "" + say "No supported service manager found. Start the agent by hand:" + say " node $AGENT run --config $CONFIG" +} + +step "setting it to start automatically" +case "$PLATFORM" in + macos) install_launchd ;; + linux) + if command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; then + install_systemd_user + else + install_manual + fi + ;; +esac + +say "" +say "Done. This machine is registered and should now appear in the console." +say "Config: $CONFIG" diff --git a/server/config.js b/server/config.js index b0c2bbd..f2ca540 100644 --- a/server/config.js +++ b/server/config.js @@ -48,4 +48,17 @@ const config = { logLevel: process.env.LOG_LEVEL || 'info', }; +/** + * Public base URL for links this hub hands out — invite URLs, and the hub + * address baked into the install scripts. `PUBLIC_URL` wins; without it the + * request's own host is used, which is right behind a proxy that sets + * `X-Forwarded-Proto` and wrong when someone hits the container directly. + */ +function baseUrl(req) { + if (config.publicUrl) return config.publicUrl; + const proto = req.headers['x-forwarded-proto'] || req.protocol; + return `${proto}://${req.get('host')}`; +} + module.exports = config; +module.exports.baseUrl = baseUrl; diff --git a/server/index.js b/server/index.js index 3680a8a..19757e5 100644 --- a/server/index.js +++ b/server/index.js @@ -82,10 +82,46 @@ app.get('/download/agent.exe', (_req, res) => { res.download(AGENT_EXE, 'rcs-agent.exe'); }); +/* ------------------------------------------------------ install scripts */ + +// One-command registration: the hub stamps its own address and the enrolment +// token into the script before serving it, so the whole thing is a single +// copy-paste with nothing to fill in. +// +// curl -fsSL https://host/install.sh?token=TOKEN | sh +// irm https://host/install.ps1?token=TOKEN | iex +const SCRIPTS_DIR = path.join(__dirname, '..', 'scripts'); + +// Tokens are base64url (see randomToken). This output is piped straight into a +// shell, so anything that is not shaped like a token is refused rather than +// interpolated — a token is the only untrusted value in these files. +const TOKEN_PATTERN = /^[A-Za-z0-9_-]{16,128}$/; + +function serveInstallScript(file, contentType) { + return (req, res) => { + const token = String(req.query.token || ''); + if (token && !TOKEN_PATTERN.test(token)) { + return res.status(400).type('text/plain').send('that is not a valid enrolment token'); + } + let body; + try { + body = fs.readFileSync(path.join(SCRIPTS_DIR, file), 'utf8'); + } catch { + return res.status(500).type('text/plain').send('install script missing from this deployment'); + } + body = body.split('__HUB__').join(config.baseUrl(req)).split('__TOKEN__').join(token); + res.type(contentType).send(body); + }; +} + +app.get('/install.sh', serveInstallScript('install.sh', 'text/x-shellscript; charset=utf-8')); +app.get('/install.ps1', serveInstallScript('install.ps1', 'text/plain; charset=utf-8')); + app.use('/novnc', express.static(NOVNC_DIR, { maxAge: '7d', immutable: true })); app.use(express.static(PUBLIC_DIR)); app.get('/viewer', (_req, res) => res.sendFile(path.join(PUBLIC_DIR, 'viewer.html'))); +app.get('/docs', (_req, res) => res.sendFile(path.join(PUBLIC_DIR, 'docs.html'))); app.get('/enroll/:token', (_req, res) => res.sendFile(path.join(PUBLIC_DIR, 'enroll.html'))); app.get('/s/:token', (_req, res) => res.sendFile(path.join(PUBLIC_DIR, 'share.html'))); diff --git a/server/routes/invites.js b/server/routes/invites.js index bfcaaf5..818a49a 100644 --- a/server/routes/invites.js +++ b/server/routes/invites.js @@ -8,11 +8,7 @@ const { requireAuth, requireAdmin } = require('../auth'); const router = express.Router(); -function baseUrl(req) { - if (config.publicUrl) return config.publicUrl; - const proto = req.headers['x-forwarded-proto'] || req.protocol; - return `${proto}://${req.get('host')}`; -} +const { baseUrl } = config; function inviteLink(req, kind, token) { return `${baseUrl(req)}/${kind === 'enroll' ? 'enroll' : 's'}/${token}`;