mcp-ssh-manager 4.3.3 → 4.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,93 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [4.3.5] - 2026-11-25
11
+
12
+ **A security release: upgrade if a server uses `restricted` or `readonly` mode.** A
13
+ command a `DENY_PATTERNS` entry (or the `readonly` list) names could still run behind an
14
+ allowed launcher such as `find -exec` or `xargs`, because the shell rewrites a word
15
+ before it runs it
16
+ ([GHSA-4fp4-fggm-cf5c](https://github.com/bvisible/mcp-ssh-manager/security/advisories/GHSA-4fp4-fggm-cf5c),
17
+ high). Every release from 3.5.0, where the security modes were added, is affected.
18
+ **Two things behave differently on purpose:** `restricted` mode now refuses `$_`,
19
+ brace expansions and a command whose own name has a quote, a backslash, a variable
20
+ or a glob; `readonly` mode refuses `$_` and reads a name after `/bin/` or `/sbin/`, so
21
+ `ls -l /usr/bin/su` is refused there (details below). Nothing else changes (the release pipeline upgrades 3.8.5,
22
+ 3.8.6, 3.8.7, every 4.0.x, 4.1.0, 4.2.0, 4.3.0, 4.3.1, 4.3.2, 4.3.3 and 4.3.4 from the
23
+ registry to this version and back).
24
+
25
+ The Windows installer is still **not Authenticode-signed**, for the same reason
26
+ as 4.0.0: Windows shows *"Windows protected your PC"*, *More info → Run anyway*,
27
+ and `ssh-manager app` checks the installer against the SHA-256 in
28
+ `release-manifest-win32.json`. macOS builds are signed and notarized.
29
+
30
+ ### Security
31
+
32
+ - **A command a `DENY_PATTERNS` entry names could still run, behind an allowed
33
+ launcher** ([GHSA-4fp4-fggm-cf5c](https://github.com/bvisible/mcp-ssh-manager/security/advisories/GHSA-4fp4-fggm-cf5c),
34
+ reported by Pythame). The patterns, and the built-in list of `readonly`, were
35
+ tested on the text as typed, and a shell does not run that text: `r\<newline>m`,
36
+ `r${x}m` (x unset), `r""m`, `r\m` and `"r"m` are all `rm`. With `^find` allowed and
37
+ `\brm\b` denied, `find . -exec r""m -rf x {} +` was allowed and deleted the target.
38
+ Every command is now also tested as the shell reads it: quotes, backslashes and
39
+ line continuations removed, variables read as unset and as blanks, `${x:-word}` as
40
+ its word, braces expanded, and the name of the command without its directory.
41
+ Found with a differential check against sh, dash, bash, ksh and zsh (1,500 random
42
+ spellings of `rm` behind `find`, `xargs` and `env`), which is now part of the tests.
43
+ - **Fixed alongside:** `/usr/bin/rm` and `find -exec /bin/rm` were not seen by the
44
+ `readonly` list; a command name written with a quote or a variable (`ls""x`) matched
45
+ an allow pattern for another name than the one the shell ran.
46
+
47
+ ### Changed
48
+
49
+ - **`restricted` mode now refuses what a line can use to spell a name:** `$_`,
50
+ brace expansions (`{a,b}`, `{1..3}`) and a command whose own name has a quote,
51
+ a backslash, a variable or a glob (`"ls" -l`, `\ls`). Arguments are not affected
52
+ (`ls "/var/log"`, `echo $HOME`, `find . -name "*.log"`).
53
+ - **`readonly` mode refuses `$_`, and reads a name after `/bin/` or `/sbin/`:**
54
+ `ls -l /usr/bin/su` is now refused. A quoted argument is still an argument
55
+ (`grep "kill -9" /var/log/syslog` runs); a quoted command name is not (`"rm" -rf x`).
56
+ - **A glob or an interpreter is still out of reach of a deny pattern.** The security
57
+ modes document lists what an allow pattern should not admit.
58
+
59
+ ## [4.3.4] - 2026-11-23
60
+
61
+ **A security release: upgrade.** `ssh_download` wrote any local path it was given,
62
+ including for servers in `readonly` or `restricted` mode
63
+ ([GHSA-2v9g-gm8g-mxgj](https://github.com/bvisible/mcp-ssh-manager/security/advisories/GHSA-2v9g-gm8g-mxgj),
64
+ high, found by the maintainer). Every release from 3.0.0 is affected. **One thing
65
+ behaves differently on purpose:** a download from a `readonly` or `restricted`
66
+ server is now refused outside `~/.ssh-manager/transfers`; if you download to a
67
+ folder of your own, set `TRANSFER_ROOT` for that server (see below). Nothing else
68
+ changes (the release pipeline upgrades 3.8.5, 3.8.6, 3.8.7, every 4.0.x, 4.1.0,
69
+ 4.2.0, 4.3.0, 4.3.1, 4.3.2 and 4.3.3 from the registry to this version and back).
70
+
71
+ The Windows installer is still **not Authenticode-signed**, for the same reason
72
+ as 4.0.0: Windows shows *"Windows protected your PC"*, *More info → Run anyway*,
73
+ and `ssh-manager app` checks the installer against the SHA-256 in
74
+ `release-manifest-win32.json`. macOS builds are signed and notarized.
75
+
76
+ ### Security
77
+
78
+ - **A server in `readonly` or `restricted` mode can no longer have a download written
79
+ anywhere on this machine.** `ssh_download` writes a local file and never looked at
80
+ the path, in any mode, and is not blocked in `readonly` or `restricted` because it
81
+ changes nothing on the server. An agent that cannot run a command on such a server
82
+ could still create a file there (a redirect to `/tmp` is allowed in `readonly`) and
83
+ download it over `~/.zshrc`, or into `~/.ssh/authorized_keys`, which a later shell
84
+ or login then ran. The local side of a transfer now has a **transfer root**: a
85
+ `readonly` or `restricted` server downloads into `~/.ssh-manager/transfers` (made
86
+ the first time, private to you; a relative local path is read from it), and any
87
+ server can name its own folder with `SSH_SERVER_<NAME>_TRANSFER_ROOT` (TOML:
88
+ `transfer_root`), which then also holds `ssh_upload` and `ssh_sync` to it. A path is
89
+ judged by where it really is after following links, a link as the file is refused,
90
+ and a download is received beside its place and moved there, so a failed one leaves
91
+ no half file. Servers in `unrestricted` mode with no root are not filtered, as
92
+ before. **If you download from a `readonly` or `restricted` server to a folder of
93
+ your own, set `TRANSFER_ROOT` to it**: a download elsewhere is refused with a message
94
+ that names the folder. Found while comparing this project with another SSH server
95
+ for MCP that confines its transfers the same way.
96
+
10
97
  ## [4.3.3] - 2026-11-21
11
98
 
12
99
  **A security release: upgrade if you use `restricted` mode.** On a server in
package/CLAUDE.md CHANGED
@@ -193,6 +193,7 @@ SSH_SERVER_[NAME]_PLATFORM=windows # Optional: "linux" (default) or "win
193
193
  SSH_SERVER_[NAME]_PROXYJUMP=bastion # Optional: name of another server to use as jump host
194
194
  SSH_SERVER_[NAME]_PROXYCOMMAND=command # Optional: custom proxy command (ncat, ssh -W, etc.)
195
195
  SSH_SERVER_[NAME]_FORWARD_AGENT=true # Optional: forward local ssh-agent to remote (needs SSH_AUTH_SOCK; security risk)
196
+ SSH_SERVER_[NAME]_TRANSFER_ROOT=~/transfers # Optional: the only local folder the file tools may use (readonly/restricted servers default to ~/.ssh-manager/transfers for downloads)
196
197
  SSH_SERVER_[NAME]_ANNOUNCE_AGENT=true # Optional: send AI_AGENT=mcp-ssh-manager to this host (off by default; SSH_MANAGER_ANNOUNCE_AGENT=true for all)
197
198
  ```
198
199
 
@@ -213,6 +214,7 @@ proxy_jump = "bastion" # Optional: name of another server to
213
214
  proxy_command = "command" # Optional: custom proxy command (ncat, ssh -W, etc.)
214
215
  forward_agent = true # Optional: forward local ssh-agent to remote (needs SSH_AUTH_SOCK; security risk)
215
216
  announce_agent = true # Optional: send AI_AGENT=mcp-ssh-manager to this host (off by default; false keeps it silent under the global switch)
217
+ transfer_root = "~/transfers" # Optional: the only local folder the file tools may use (see docs/SECURITY_MODES.md)
216
218
  ```
217
219
 
218
220
  ### Selecting an SSH agent key
@@ -13,8 +13,8 @@
13
13
  class SshManager < Formula
14
14
  desc "SSH server management for AI agents, with approval and audit"
15
15
  homepage "https://github.com/bvisible/mcp-ssh-manager"
16
- url "https://registry.npmjs.org/mcp-ssh-manager/-/mcp-ssh-manager-4.3.2.tgz"
17
- sha256 "5463cb719c00124432b7e8a835a8254888ddecb2006c631ff3651ddba3d0e267"
16
+ url "https://registry.npmjs.org/mcp-ssh-manager/-/mcp-ssh-manager-4.3.4.tgz"
17
+ sha256 "1704646ab3a16cb315bb9402f3eae21366d8a6c4f2323cff67665e7efc23d4db"
18
18
  license "MIT"
19
19
 
20
20
  depends_on "node"
package/README.md CHANGED
@@ -25,7 +25,7 @@
25
25
  [![Desktop app downloads](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbvisible%2Fmcp-ssh-manager%2Fstats%2Fdesktop.json&style=flat-square)](https://github.com/bvisible/mcp-ssh-manager/releases/latest)
26
26
  [![GitHub stars](https://img.shields.io/github/stars/bvisible/mcp-ssh-manager?style=flat-square&color=c04500)](https://github.com/bvisible/mcp-ssh-manager/stargazers)
27
27
  [![MCP Toplist](https://mcptoplist.com/badge/io.github.bvisible%2Fmcp-ssh-manager.svg)](https://mcptoplist.com/server/io.github.bvisible%2Fmcp-ssh-manager)
28
- [![Version](https://img.shields.io/badge/release-4.3.3-c04500?style=flat-square)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.3)
28
+ [![Version](https://img.shields.io/badge/release-4.3.5-c04500?style=flat-square)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.5)
29
29
  [![Claude Code](https://img.shields.io/badge/Claude_Code-Compatible-5A67D8?style=flat-square&logo=anthropic)](https://claude.ai/code)
30
30
  [![OpenAI Codex](https://img.shields.io/badge/OpenAI_Codex-Compatible-00A67E?style=flat-square&logo=openai)](https://openai.com/codex)
31
31
  [![MCP](https://img.shields.io/badge/MCP-Server-orange?style=flat-square)](https://modelcontextprotocol.io)
@@ -58,9 +58,9 @@ An MCP SSH server is the most dangerous tool you can hand an agent: a shell on m
58
58
 
59
59
  ## Choose your workspace
60
60
 
61
- **Desktop application (`4.3.3`):** one installation with its own runtime,
61
+ **Desktop application (`4.3.5`):** one installation with its own runtime,
62
62
  terminal, file browser and server settings. No separate Node.js or npm
63
- installation. [Download it](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.3):
63
+ installation. [Download it](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.5):
64
64
 
65
65
  | Platform | File | Signature |
66
66
  |---|---|---|
@@ -68,7 +68,7 @@ installation. [Download it](https://github.com/bvisible/mcp-ssh-manager/releases
68
68
  | Windows x64 / arm64 | `…-setup.exe` | **Not code-signed yet.** Windows shows *"Windows protected your PC"*: *More info → Run anyway*. Check the file against the SHA-256 in `release-manifest-win32.json` on the release (`ssh-manager app` does it for you). Signing comes in a later release. |
69
69
  | Linux x64 | `.deb`, `.AppImage` | Unsigned, as Linux packages usually are |
70
70
 
71
- **Already using npm / the CLI?** `npm update -g mcp-ssh-manager` brings 4.3.3,
71
+ **Already using npm / the CLI?** `npm update -g mcp-ssh-manager` brings 4.3.5,
72
72
  and the V4 engine runs without an interface, from your existing `.env`, TOML or
73
73
  process variables — no automatic import, no forced wizard, no approval prompt
74
74
  unless you enable one per server. The one behaviour that tightens is **SSH
@@ -720,6 +720,8 @@ The hero animation ships twice, light and dark, swapped by `<picture>` on `prefe
720
720
 
721
721
  ## What's new
722
722
 
723
+ **[4.3.4](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.5) — a security fix: `ssh_download` could write any file on your machine, even from a `readonly` server.** An agent that could not run a command on a `readonly` or `restricted` server could still have a file it had put on the server downloaded over `~/.zshrc` or into `~/.ssh/authorized_keys`. The local side of a transfer now has a transfer root: `readonly` and `restricted` servers download into `~/.ssh-manager/transfers`, and any server can name its own folder with `TRANSFER_ROOT`. If you download from such a server to a folder of your own, set `TRANSFER_ROOT` to it. (GHSA-2v9g-gm8g-mxgj) See the [CHANGELOG](CHANGELOG.md#434---2026-11-23).
724
+
723
725
  **[4.3.3](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.3) — a security fix: `restricted` mode could be made to run a command its allowlist never saw.** A comment, a here-document, an ANSI-C quote (`$'…'`) or a parenthesis could hide a command from the check while the shell ran it. The allowlist now reads comments as comments and refuses those constructs, with a reason. Servers in `readonly` mode and servers without a mode are unaffected; if you use `restricted` mode, upgrade. Reported by @Fastyyy123 (GHSA-86xm-rv3h-r4f2). See the [CHANGELOG](CHANGELOG.md#433---2026-11-21).
724
726
 
725
727
  **[4.3.2](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.2) — a command that fails no longer stays "running" on the Live page.** When a call threw instead of returning (a timeout, a dropped connection), or when the engine was closed mid-command, the Live entry read "running" until the control plane restarted. It now ends, as `exit -1`. Display only: nothing about the commands themselves changes. Found and traced by @TillNano (#159). See the [CHANGELOG](CHANGELOG.md#432---2026-11-21).
package/cli/lib/config.sh CHANGED
@@ -123,7 +123,7 @@ load_servers() {
123
123
  # The settings of a server, as the engine reads them (src/config-loader.js; a test
124
124
  # keeps the two lists in step). A server's lines are found by these names and never
125
125
  # by the bare prefix: removing "prod" used to remove the lines of "prod_eu" too.
126
- SERVER_ENV_FIELDS="HOST USER PASSWORD KEYPATH CERTPATH AGENT_PUBLIC_KEY_PATH PASSPHRASE PORT DEFAULT_DIR SUDO_PASSWORD DESCRIPTION GROUP PLATFORM PROXYJUMP PROXYCOMMAND FORWARD_AGENT ANNOUNCE_AGENT MODE ALLOW_PATTERNS DENY_PATTERNS AUDIT_LOG APPROVAL"
126
+ SERVER_ENV_FIELDS="HOST USER PASSWORD KEYPATH CERTPATH AGENT_PUBLIC_KEY_PATH PASSPHRASE PORT DEFAULT_DIR SUDO_PASSWORD DESCRIPTION GROUP PLATFORM PROXYJUMP PROXYCOMMAND FORWARD_AGENT ANNOUNCE_AGENT TRANSFER_ROOT MODE ALLOW_PATTERNS DENY_PATTERNS AUDIT_LOG APPROVAL"
127
127
 
128
128
  # Copy stdin to stdout without the lines of server $1 (upper case) whose setting is
129
129
  # in $2 (space separated). With a file as $3, its lines take the place of the first
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "ssh-manager-desktop",
3
- "version": "4.3.3",
3
+ "version": "4.3.5",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "ssh-manager-desktop",
9
- "version": "4.3.3",
9
+ "version": "4.3.5",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "electron-updater": "^6.8.9",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ssh-manager-desktop",
3
3
  "productName": "SSH Manager",
4
- "version": "4.3.3",
4
+ "version": "4.3.5",
5
5
  "private": true,
6
6
  "description": "The SSH Manager control plane as a desktop application",
7
7
  "main": "main.js",
package/docs/MIGRATION.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Upgrading from 3.8 to 4.0
2
2
 
3
- **4.0 is released, on npm and as a desktop application**; the latest is 4.3.3 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.3)).
3
+ **4.0 is released, on npm and as a desktop application**; the latest is 4.3.5 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.5)).
4
4
  The last 3.8 release is 3.8.7, for anyone who pins the 3.8 line.
5
5
 
6
6
  The upgrade path preserves headless npm/CLI use. The application, vault import
@@ -57,6 +57,35 @@ fewer commands than the shell ran
57
57
  `readonly` mode also checks the commands inside `$(…)` and backticks against its
58
58
  built-in list.
59
59
 
60
+ ### What the shell does to a command before it runs it
61
+
62
+ A shell does not run the text it was given: it removes quotes and backslashes, joins
63
+ a line at a backslash and a newline, replaces a variable that is not set with
64
+ nothing, and expands braces. `r""m`, `r\m`, `r${x}m` and a backslash and a
65
+ newline between the `r` and the `m` are all `rm`. Up to 4.3.4 a `DENY_PATTERNS`
66
+ entry such as `\brm\b`, and the built-in list of `readonly`, were tested on the text
67
+ as typed, so an allowed command that starts another one (`find -exec`, `xargs`)
68
+ could start the command they deny
69
+ ([GHSA-4fp4-fggm-cf5c](https://github.com/bvisible/mcp-ssh-manager/security/advisories/GHSA-4fp4-fggm-cf5c)).
70
+ Since 4.3.5 each command is tested on the text as typed **and** on what the shell
71
+ makes of it: with quotes, backslashes and line continuations removed, with every
72
+ variable read as unset and as holding blanks, with `${x:-word}` read as its word,
73
+ with brace expansions carried out, and, for the name of the command, without its
74
+ directory (`/usr/bin/rm`). `ALLOW_PATTERNS` are still matched on the text as typed.
75
+
76
+ `restricted` mode refuses what a line can use to spell a name on purpose, because
77
+ no reading can follow it: `$_` (the last argument of the command before it:
78
+ `echo m; r$_`), `${x:-word}`, and brace expansions (`{r,}m`, `{1..3}`; `sh` does
79
+ not expand them and bash, ksh and zsh do). It also refuses a command whose own
80
+ name is written with a quote, a backslash, a variable or a glob (`ls""x`, `\ls`,
81
+ `/bin/r?`): the allow pattern was matched against another name than the one the
82
+ shell runs. Arguments may use all of them: `ls "/var/log"`, `echo $HOME`,
83
+ `find . -name "*.log"` are fine. `readonly` mode refuses `$_` and reads the rest.
84
+ A name read after `/bin/` or `/sbin/` is the command in `readonly` (`/usr/bin/rm`),
85
+ so `ls -l /usr/bin/su` is refused there. A word that is only a quoted string is
86
+ read as typed unless it can be the command (the first word, or the one after
87
+ `-exec`, `xargs`, `env` and the like), so `grep "kill -9" /var/log/syslog` still runs.
88
+
60
89
  ## Configuration
61
90
 
62
91
  ### Environment variables / `.env`
@@ -95,6 +124,39 @@ audit_log = "/var/log/mcp-ssh-prod.jsonl"
95
124
  TOML arrays are preferred. A `;`-separated string is also accepted for
96
125
  parity with the `.env` form.
97
126
 
127
+ ### Where the file tools may write on this machine: the transfer root
128
+
129
+ `ssh_download` writes a file on the machine that runs the engine, and `ssh_upload`
130
+ and `ssh_sync` read from it. `readonly` and `restricted` are about what runs on the
131
+ *server*, and an agent that cannot run a command there could still put a file of its
132
+ choosing on the server (a redirect to `/tmp` is allowed in `readonly`) and have it
133
+ downloaded over `~/.zshrc` or into `~/.ssh/authorized_keys` here. Up to 4.3.3 nothing
134
+ looked at the local path. A **transfer root** is the one folder the local side of a
135
+ transfer may use:
136
+
137
+ ```bash
138
+ SSH_SERVER_PROD_TRANSFER_ROOT=~/transfers/prod # TOML: transfer_root = "~/transfers/prod"
139
+ ```
140
+
141
+ - A server with a `TRANSFER_ROOT` is held to it in every mode, by all three tools.
142
+ - A server in `readonly` or `restricted` mode with none is held to
143
+ `~/.ssh-manager/transfers` for `ssh_download` (`ssh_upload` and `ssh_sync` are refused
144
+ there already). The folder is made, private to you, the first time a download needs it.
145
+ - A server in `unrestricted` mode with none is not filtered, as before.
146
+
147
+ A relative local path is read from the root, so `ssh_download` with the local path
148
+ `logs/app.log` writes `~/.ssh-manager/transfers/logs/app.log`. A path is accepted when
149
+ its real location, after following every link, is inside the root; `..`, a sibling
150
+ folder that starts like the root, and a folder link that leads out are refused, and so
151
+ is a link as the file itself. A download is received beside its place and moved there,
152
+ so a transfer that fails leaves no half file, and a link put there meanwhile is replaced,
153
+ not followed. The check runs just before the transfer: it does not stop someone who can
154
+ already change files inside the root while it runs, and for `ssh_sync` it covers the
155
+ folder named, not what rsync does inside it.
156
+
157
+ If you download to a folder of your own from a `readonly` or `restricted` server, set
158
+ `TRANSFER_ROOT` to that folder.
159
+
98
160
  ## Audit log
99
161
 
100
162
  When `AUDIT_LOG` (`.env`) or `audit_log` (TOML) is set to a file path, every
@@ -186,7 +248,8 @@ SSH_SERVER_CLIENT_PROD_AUDIT_LOG=~/.ssh-manager/audit/client-prod.jsonl
186
248
  `ssh_key_manage` (only `accept` / `remove`), `ssh_alert_setup` (only `set`),
187
249
  `ssh_process_manager` (only `kill`).
188
250
 
189
- **Not gated** (pure reads or local-only state — no remote effect to block):
251
+ **Not gated** (pure reads or local-only state — no remote effect to block; the
252
+ local side of `ssh_download` is held to the transfer root, see above):
190
253
  `ssh_list_servers`, `ssh_download`, `ssh_tail`, `ssh_monitor`, `ssh_history`,
191
254
  `ssh_health_check`, `ssh_service_status`, `ssh_db_list`, `ssh_db_query`
192
255
  (one SELECT run in a read-only transaction; for MongoDB a filter document,
@@ -206,6 +269,14 @@ never code), `ssh_backup_list`, `ssh_session_start`,
206
269
  not as an unbreakable shell escape. `restricted` is the stronger of the two:
207
270
  every command must be one you allowed, so keep its patterns narrow — an
208
271
  allowed interpreter (`^python`, `^bash`, `^sh`) allows everything.
272
+ - **A deny pattern cannot follow what only the remote machine knows.** A glob
273
+ (`find -exec /bin/r? {} +` runs `rm`), the value of a variable the line does not
274
+ set, and the text an interpreter runs (`sh -c`, `python -c`, `awk 'BEGIN{system(…)}'`)
275
+ are out of its reach. So is anything an allowed command can start: `find -exec`,
276
+ `xargs`, `env`, `nice`, `timeout`, `sed`, `awk`, `tar`, `git`, `make`, an editor.
277
+ **If an allow pattern admits one of them, a deny pattern is a guard rail, not a
278
+ boundary:** allow it only with the arguments you mean (`^find [^ ]+ -name [^ ]+$`),
279
+ or not at all.
209
280
  - **Aliases are expanded before policy evaluation** — you can't bypass a DENY
210
281
  by hiding `rm` behind an alias defined via `ssh_command_alias`.
211
282
  - **No transport-level / per-client policies.** All clients see the same
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "4.3.3",
3
+ "version": "4.3.5",
4
4
  "mcpName": "io.github.bvisible/mcp-ssh-manager",
5
5
  "description": "MCP server for SSH: let AI agents (Claude Code, Codex, any MCP client) run commands, transfer files and manage servers over SSH, with human approval, an encrypted vault and a live audit trail.",
6
6
  "main": "src/index.js",
@@ -14,7 +14,7 @@
14
14
  "setup": "npm install && pip install -r tools/requirements.txt",
15
15
  "configure": "python tools/server-manager.py",
16
16
  "test-connection": "python tools/test-connection.py",
17
- "test": "npm run test:lockfile && npm run test:sudostdin && npm run test:vault && npm run test:recovery && npm run test:upgrade && npm run test:notify && npm run test:commands && npm run test:commandlog && npm run test:portability && npm run test:approval && npm run test:controlplane && npm run test:terminal && npm run test:files && npm run test:livestream && npm run test:livefailure && npm run test:skills && npm run test:redaction && npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:shellsegments && npm run test:policynames && npm run test:auditsuccess && npm run test:ping && npm run test:config && npm run test:fieldnames && npm run test:groups && npm run test:agentforward && npm run test:agentkey && npm run test:certpath && npm run test:agentannounce && npm run test:autherrors && npm run test:envchoice && npm run test:lifecycle && npm run test:tunnel && npm run test:sync && npm run test:sync-path && npm run test:dbquoting && npm run test:dbinjection && npm run test:quoteprops && npm run test:backupinjection && npm run test:dbrowcount && npm run test:dbclientcmds && npm run test:migration && npm run test:security && npm run test:hostkeys && npm run test:proxy && npm run test:working-directory && npm run test:groups-persistence && npm run test:release && npm run test:cli-experience && npm run test:desktop-install && npm run test:agent-clients && npm run test:appupdate && npm run test:preview && npm run test:desktop-smoke && npm run test:local-shell && npm run test:cli-edit && npm run test:timeoutwrap && npm run test:downloadstats && npm run test:remotetunnel && npm run test:connsharing && npm run test:auditcoverage && npm run test:background && npm run test:quietstderr && npm run test:sshguard && npm run test:locale && npm run test:langtool && npm run test:healthdisks && npm run test:backupintegrity && npm run test:clienvlines && npm run test:clicodex",
17
+ "test": "npm run test:lockfile && npm run test:sudostdin && npm run test:vault && npm run test:recovery && npm run test:upgrade && npm run test:notify && npm run test:commands && npm run test:commandlog && npm run test:portability && npm run test:approval && npm run test:controlplane && npm run test:terminal && npm run test:files && npm run test:livestream && npm run test:livefailure && npm run test:transferpaths && npm run test:skills && npm run test:redaction && npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:shellsegments && npm run test:policynames && npm run test:auditsuccess && npm run test:ping && npm run test:config && npm run test:fieldnames && npm run test:groups && npm run test:agentforward && npm run test:agentkey && npm run test:certpath && npm run test:agentannounce && npm run test:autherrors && npm run test:envchoice && npm run test:lifecycle && npm run test:tunnel && npm run test:sync && npm run test:sync-path && npm run test:dbquoting && npm run test:dbinjection && npm run test:quoteprops && npm run test:backupinjection && npm run test:dbrowcount && npm run test:dbclientcmds && npm run test:migration && npm run test:security && npm run test:hostkeys && npm run test:proxy && npm run test:working-directory && npm run test:groups-persistence && npm run test:release && npm run test:cli-experience && npm run test:desktop-install && npm run test:agent-clients && npm run test:appupdate && npm run test:preview && npm run test:desktop-smoke && npm run test:local-shell && npm run test:cli-edit && npm run test:timeoutwrap && npm run test:downloadstats && npm run test:remotetunnel && npm run test:connsharing && npm run test:auditcoverage && npm run test:background && npm run test:quietstderr && npm run test:sshguard && npm run test:locale && npm run test:langtool && npm run test:healthdisks && npm run test:backupintegrity && npm run test:clienvlines && npm run test:clicodex",
18
18
  "test:lockfile": "node tests/test-lockfile.js",
19
19
  "test:sudostdin": "node tests/test-sudo-stdin.js",
20
20
  "test:vault": "node tests/test-secret-store.js",
@@ -22,6 +22,7 @@
22
22
  "test:controlplane": "node tests/test-control-plane.js",
23
23
  "test:livestream": "node tests/test-live-stream.js",
24
24
  "test:livefailure": "node tests/test-live-stream-failure.js",
25
+ "test:transferpaths": "node tests/test-transfer-paths.js",
25
26
  "test:skills": "node tests/test-skills.js",
26
27
  "test:redaction": "node tests/test-logger-redaction.js",
27
28
  "test:profiles": "node tests/test-profiles.js",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/bvisible/mcp-ssh-manager",
7
7
  "source": "github"
8
8
  },
9
- "version": "4.3.3",
9
+ "version": "4.3.5",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "mcp-ssh-manager",
14
- "version": "4.3.3",
14
+ "version": "4.3.5",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -38,6 +38,7 @@ import { resolveConfigOptions } from './config-paths.js';
38
38
  * @property {string} [proxyJump] Name of another configured server to jump through.
39
39
  * @property {string} [proxyCommand] Custom proxy command (`%h` / `%p` placeholders).
40
40
  * @property {boolean} [forwardAgent] Forward the local ssh-agent to this server.
41
+ * @property {string} [transferRoot] The only folder the local side of ssh_download, ssh_upload and ssh_sync may use. Unset: no limit in unrestricted mode, and ~/.ssh-manager/transfers for ssh_download in readonly and restricted mode.
41
42
  * @property {boolean} [announceAgent] Send AI_AGENT=mcp-ssh-manager on each command channel. Unset defers to SSH_MANAGER_ANNOUNCE_AGENT (off by default); false keeps a host silent even when that is on.
42
43
  * @property {string} [mode] Security mode: `unrestricted`, `readonly` or `restricted`.
43
44
  * @property {string} [approval] Human approval mode: `never`, `destructive` or `always`.
@@ -280,6 +281,7 @@ export class ConfigLoader {
280
281
  proxyCommand: serverConfig.proxy_command || serverConfig.proxycommand,
281
282
  forwardAgent: parseBool(serverConfig.forward_agent),
282
283
  announceAgent: parseOptionalBool(serverConfig.announce_agent),
284
+ transferRoot: serverConfig.transfer_root,
283
285
  mode,
284
286
  // approval is deliberately NOT read here — see loadEnvConfig below.
285
287
 
@@ -359,6 +361,7 @@ export class ConfigLoader {
359
361
  proxyCommand: env[`SSH_SERVER_${match[1]}_PROXYCOMMAND`],
360
362
  forwardAgent: parseBool(env[`SSH_SERVER_${match[1]}_FORWARD_AGENT`]),
361
363
  announceAgent: parseOptionalBool(env[`SSH_SERVER_${match[1]}_ANNOUNCE_AGENT`]),
364
+ transferRoot: env[`SSH_SERVER_${match[1]}_TRANSFER_ROOT`],
362
365
  mode,
363
366
  // approval is deliberately NOT read from files. It is the switch
364
367
  // that makes an agent stop and wait for a human, and a switch that
@@ -447,6 +450,7 @@ export class ConfigLoader {
447
450
  // Either explicit value is a decision worth keeping; unset is not written,
448
451
  // so the global switch still applies after a round trip.
449
452
  if (typeof server.announceAgent === 'boolean') serverConfig.announce_agent = server.announceAgent;
453
+ if (server.transferRoot) serverConfig.transfer_root = server.transferRoot;
450
454
  // Only emit security fields if they diverge from defaults — keeps generated
451
455
  // TOML files clean for users who never opted in.
452
456
  if (server.mode && server.mode !== 'unrestricted') serverConfig.mode = server.mode;
@@ -493,6 +497,7 @@ export class ConfigLoader {
493
497
  // Written whenever it was set, true or false: an explicit false has to
494
498
  // survive a round trip, or a global switch would re-enable that host.
495
499
  if (typeof server.announceAgent === 'boolean') lines.push(`SSH_SERVER_${upperName}_ANNOUNCE_AGENT=${server.announceAgent}`);
500
+ if (server.transferRoot) lines.push(`SSH_SERVER_${upperName}_TRANSFER_ROOT=${server.transferRoot}`);
496
501
  if (server.proxyJump) lines.push(`SSH_SERVER_${upperName}_PROXYJUMP=${server.proxyJump}`);
497
502
  if (server.proxyCommand) lines.push(`SSH_SERVER_${upperName}_PROXYCOMMAND=${server.proxyCommand}`);
498
503
  // Security fields — only emit when non-default to avoid clutter in
package/src/index.js CHANGED
@@ -10,6 +10,7 @@ import { connectSSH, connectServer } from './ssh-connection.js';
10
10
  import * as dotenv from 'dotenv';
11
11
  import fs from 'fs';
12
12
  import path from 'path';
13
+ import crypto from 'node:crypto';
13
14
  import { AsyncLocalStorage } from 'node:async_hooks';
14
15
  import { isDeepStrictEqual } from 'node:util';
15
16
  import { envFileChoice, envFileProblem, expandHomePath } from './config-paths.js';
@@ -158,6 +159,7 @@ import { buildBackgroundCommand, parseBackgroundStart } from './background-job.j
158
159
  import { needsApproval, isControlPlaneListening, requestDecision, buildRequest, isApprovalExempt, isReadOnlyAction, HANDLER_GATED_TOOLS } from './approval.js';
159
160
  import { shellQuote, shellPath, safeInteger, withRemoteTimeout } from './shell-quote.js';
160
161
  import { openStream } from './live-stream.js';
162
+ import { transferPolicy, confineLocalPath } from './transfer-paths.js';
161
163
  import { auditLog, sanitize } from './audit.js';
162
164
 
163
165
  const __filename = fileURLToPath(import.meta.url);
@@ -918,7 +920,7 @@ registerToolConditional(
918
920
  registerToolConditional(
919
921
  'ssh_upload',
920
922
  {
921
- description: 'Uploads one local file to a remote destination path over SFTP on the named server, overwriting any existing remote file at that path. Mutates remote state and is not idempotent beyond replacing the target. Creates no backup. Requires the local file to exist. Does not use sudo, so the remote path must be writable by the configured SSH user. This tool is blocked entirely on servers set to readonly or restricted security mode. For directory trees use ssh_sync instead.',
923
+ description: 'Uploads one local file to a remote destination path over SFTP on the named server, overwriting any existing remote file at that path. Mutates remote state and is not idempotent beyond replacing the target. Creates no backup. Requires the local file to exist. Does not use sudo, so the remote path must be writable by the configured SSH user. This tool is blocked entirely on servers set to readonly or restricted security mode. On a server with a transferRoot the local file must be inside that folder. For directory trees use ssh_sync instead.',
922
924
  inputSchema: {
923
925
  server: z.string().describe('Server name'),
924
926
  localPath: z.string().describe('Local file path'),
@@ -928,14 +930,18 @@ registerToolConditional(
928
930
  async ({ server: serverName, localPath, remotePath }) => {
929
931
 
930
932
  try {
933
+ // With a transferRoot on the server, the local file must be inside it (readonly
934
+ // and restricted servers never get here: the tool is refused for them).
935
+ const policy = transferPolicy(await getServerConfig(serverName), 'ssh_upload');
936
+ const source = policy ? confineLocalPath(policy, localPath, { direction: 'read' }) : localPath;
931
937
  const ssh = await getConnection(serverName);
932
938
 
933
939
  logger.logTransfer('upload', serverName, localPath, remotePath);
934
940
  const startTime = Date.now();
935
941
 
936
- await ssh.putFile(localPath, remotePath);
942
+ await ssh.putFile(source, remotePath);
937
943
 
938
- const fileStats = fs.statSync(localPath);
944
+ const fileStats = fs.statSync(source);
939
945
  logger.logTransfer('upload', serverName, localPath, remotePath, {
940
946
  success: true,
941
947
  size: fileStats.size,
@@ -977,7 +983,7 @@ registerToolConditional(
977
983
  registerToolConditional(
978
984
  'ssh_download',
979
985
  {
980
- description: 'Downloads one remote file from the named server to a local destination path over SFTP, overwriting any existing local file at that path. Affects only the local filesystem and is read-only on the remote side, so it stays allowed even on servers in readonly or restricted security mode. Reads the remote file using the configured SSH user, which must have permission to read it. Handles single files only; use ssh_sync for directories.',
986
+ description: 'Downloads one remote file from the named server to a local destination path over SFTP, overwriting any existing local file at that path. Affects only the local filesystem and is read-only on the remote side, so it stays allowed even on servers in readonly or restricted security mode, where the local path must be inside the transfer folder (~/.ssh-manager/transfers, or the transferRoot set on the server): a relative path is read from it, and anything outside it, or reached through a link, is refused. On other servers the local path is unrestricted unless a transferRoot is set. Reads the remote file using the configured SSH user, which must have permission to read it. Handles single files only; use ssh_sync for directories.',
981
987
  inputSchema: {
982
988
  server: z.string().describe('Server name'),
983
989
  remotePath: z.string().describe('Remote file path'),
@@ -986,15 +992,32 @@ registerToolConditional(
986
992
  },
987
993
  async ({ server: serverName, remotePath, localPath }) => {
988
994
  try {
995
+ // A server in readonly or restricted mode, or with a transferRoot, writes only
996
+ // inside that folder: the file is received beside its place and moved there, so a
997
+ // failed transfer never leaves half a file, and a link put there meanwhile is
998
+ // replaced, not followed.
999
+ const policy = transferPolicy(await getServerConfig(serverName), 'ssh_download');
1000
+ const target = policy ? confineLocalPath(policy, localPath, { direction: 'write' }) : localPath;
989
1001
  const ssh = await getConnection(serverName);
990
1002
 
991
- logger.logTransfer('download', serverName, remotePath, localPath);
1003
+ logger.logTransfer('download', serverName, remotePath, target);
992
1004
  const startTime = Date.now();
993
1005
 
994
- await ssh.getFile(localPath, remotePath);
1006
+ if (policy) {
1007
+ const partial = `${target}.part-${crypto.randomBytes(4).toString('hex')}`;
1008
+ try {
1009
+ await ssh.getFile(partial, remotePath);
1010
+ fs.renameSync(partial, target);
1011
+ } catch (error) {
1012
+ fs.rmSync(partial, { force: true });
1013
+ throw error;
1014
+ }
1015
+ } else {
1016
+ await ssh.getFile(target, remotePath);
1017
+ }
995
1018
 
996
- const fileStats = fs.statSync(localPath);
997
- logger.logTransfer('download', serverName, remotePath, localPath, {
1019
+ const fileStats = fs.statSync(target);
1020
+ logger.logTransfer('download', serverName, remotePath, target, {
998
1021
  success: true,
999
1022
  size: fileStats.size,
1000
1023
  duration: `${Date.now() - startTime}ms`
@@ -1006,7 +1029,7 @@ registerToolConditional(
1006
1029
  content: [
1007
1030
  {
1008
1031
  type: 'text',
1009
- text: `✅ File downloaded successfully\nServer: ${serverName}\nRemote: ${remotePath}\nLocal: ${localPath}`,
1032
+ text: `✅ File downloaded successfully\nServer: ${serverName}\nRemote: ${remotePath}\nLocal: ${target}`,
1010
1033
  },
1011
1034
  ],
1012
1035
  };
@@ -1035,7 +1058,7 @@ registerToolConditional(
1035
1058
  registerToolConditional(
1036
1059
  'ssh_sync',
1037
1060
  {
1038
- description: 'Synchronizes files or directories between local and remote using rsync over SSH on the named server. Each of source and destination must carry a local: or remote: prefix and one side must be local and the other remote; with no prefix it assumes a push from local to remote. On Windows MCP hosts, provide native Windows local paths such as C:\\project or .\\project; the tool converts drive-letter and UNC paths to MSYS2 format before spawning rsync. Do not pre-convert a local path to /c/project because Node performs local filesystem checks using Windows path semantics. Mutates the destination. Setting delete true removes destination files absent from source, which is destructive; dryRun true previews without changing anything. Compression is on by default. Password authentication requires sshpass installed locally. Blocked on readonly or restricted servers. Timeout defaults to 30000 ms.',
1061
+ description: 'Synchronizes files or directories between local and remote using rsync over SSH on the named server. Each of source and destination must carry a local: or remote: prefix and one side must be local and the other remote; with no prefix it assumes a push from local to remote. On Windows MCP hosts, provide native Windows local paths such as C:\\project or .\\project; the tool converts drive-letter and UNC paths to MSYS2 format before spawning rsync. Do not pre-convert a local path to /c/project because Node performs local filesystem checks using Windows path semantics. Mutates the destination. Setting delete true removes destination files absent from source, which is destructive; dryRun true previews without changing anything. Compression is on by default. Password authentication requires sshpass installed locally. Blocked on readonly or restricted servers. On a server with a transferRoot the local side must be inside that folder. Timeout defaults to 30000 ms.',
1039
1062
  inputSchema: {
1040
1063
  server: z.string().describe('Server name from configuration'),
1041
1064
  source: z.string().describe('Source path with a "local:" or "remote:" prefix. On Windows, use a native local path such as "local:C:\\project" or "local:.\\project"; do not pre-convert it to MSYS2 /c/... syntax.'),
@@ -1123,8 +1146,11 @@ registerToolConditional(
1123
1146
  let localPath;
1124
1147
  let remotePath;
1125
1148
 
1149
+ // With a transferRoot on the server, the local side stays inside it. (readonly
1150
+ // and restricted servers never get here: the tool is refused for them.)
1151
+ const syncPolicy = transferPolicy(serverConfig, 'ssh_sync');
1126
1152
  if (direction === 'push') {
1127
- localPath = cleanSource;
1153
+ localPath = syncPolicy ? confineLocalPath(syncPolicy, cleanSource, { direction: 'read', allowRoot: true }) : cleanSource;
1128
1154
  remotePath = cleanDest;
1129
1155
 
1130
1156
  // Check if local path exists
@@ -1132,7 +1158,7 @@ registerToolConditional(
1132
1158
  throw new Error(`Local path does not exist: ${localPath}`);
1133
1159
  }
1134
1160
  } else {
1135
- localPath = cleanDest;
1161
+ localPath = syncPolicy ? confineLocalPath(syncPolicy, cleanDest, { direction: 'write', allowRoot: true }) : cleanDest;
1136
1162
  remotePath = cleanSource;
1137
1163
  }
1138
1164
 
package/src/policy.js CHANGED
@@ -18,7 +18,7 @@
18
18
  */
19
19
 
20
20
  import { logger } from './logger.js';
21
- import { splitShellCommand } from './shell-segments.js';
21
+ import { commandWordProblem, readSegments, splitShellCommand } from './shell-segments.js';
22
22
 
23
23
  const MODE_UNRESTRICTED = 'unrestricted';
24
24
  const MODE_READONLY = 'readonly';
@@ -61,34 +61,39 @@ export const COMMAND_BEARING_TOOLS = new Set([
61
61
  //
62
62
  // The user can layer their own DENY_PATTERNS on top via restricted mode for
63
63
  // finer control.
64
+ //
65
+ // A command name is also read after `/bin/` and `/sbin/` (so `/usr/bin/rm`, and
66
+ // `./bin/rm` behind `find -exec`, are `rm`). They are the folders programs live
67
+ // in; a directory of any other name is not read as one, or `cat /etc/pam.d/su`
68
+ // would be a `su`.
64
69
  const READONLY_DENY_REGEX = [
65
- /(^|[\s;&|])rm(\s|$)/,
66
- /(^|[\s;&|])rmdir(\s|$)/,
67
- /(^|[\s;&|])mv(\s|$)/,
68
- /(^|[\s;&|])dd(\s|$)/,
69
- /(^|[\s;&|])mkfs(\.|\s|$)/,
70
- /(^|[\s;&|])chmod(\s|$)/,
71
- /(^|[\s;&|])chown(\s|$)/,
72
- /(^|[\s;&|])truncate(\s|$)/,
73
- /(^|[\s;&|])tee(\s|$)/,
74
- /(^|[\s;&|])sudo(\s|$)/,
75
- /(^|[\s;&|])su(\s|$)/,
76
- /(^|[\s;&|])kill(\s|$)/,
77
- /(^|[\s;&|])pkill(\s|$)/,
78
- /(^|[\s;&|])killall(\s|$)/,
79
- /(^|[\s;&|])shutdown(\s|$)/,
80
- /(^|[\s;&|])reboot(\s|$)/,
81
- /(^|[\s;&|])halt(\s|$)/,
82
- /(^|[\s;&|])poweroff(\s|$)/,
83
- /(^|[\s;&|])systemctl\s+(restart|stop|reload|start|enable|disable|mask)/,
84
- /(^|[\s;&|])service\s+\S+\s+(restart|stop|reload|start)/,
85
- /(^|[\s;&|])docker\s+(rm|stop|restart|kill|prune|system)/,
86
- /(^|[\s;&|])apt(-get)?\s+(install|remove|purge|upgrade|update)/,
87
- /(^|[\s;&|])yum\s+(install|remove|update|upgrade)/,
88
- /(^|[\s;&|])dnf\s+(install|remove|update|upgrade)/,
89
- /(^|[\s;&|])pip\s+(install|uninstall)/,
90
- /(^|[\s;&|])npm\s+(install|uninstall|publish)/,
91
- /(^|[\s;&|])git\s+(reset\s+--hard|push\s+.*--force|clean\s+-fd?)/,
70
+ /(^|[\s;&|]|\/s?bin\/)rm(\s|$)/,
71
+ /(^|[\s;&|]|\/s?bin\/)rmdir(\s|$)/,
72
+ /(^|[\s;&|]|\/s?bin\/)mv(\s|$)/,
73
+ /(^|[\s;&|]|\/s?bin\/)dd(\s|$)/,
74
+ /(^|[\s;&|]|\/s?bin\/)mkfs(\.|\s|$)/,
75
+ /(^|[\s;&|]|\/s?bin\/)chmod(\s|$)/,
76
+ /(^|[\s;&|]|\/s?bin\/)chown(\s|$)/,
77
+ /(^|[\s;&|]|\/s?bin\/)truncate(\s|$)/,
78
+ /(^|[\s;&|]|\/s?bin\/)tee(\s|$)/,
79
+ /(^|[\s;&|]|\/s?bin\/)sudo(\s|$)/,
80
+ /(^|[\s;&|]|\/s?bin\/)su(\s|$)/,
81
+ /(^|[\s;&|]|\/s?bin\/)kill(\s|$)/,
82
+ /(^|[\s;&|]|\/s?bin\/)pkill(\s|$)/,
83
+ /(^|[\s;&|]|\/s?bin\/)killall(\s|$)/,
84
+ /(^|[\s;&|]|\/s?bin\/)shutdown(\s|$)/,
85
+ /(^|[\s;&|]|\/s?bin\/)reboot(\s|$)/,
86
+ /(^|[\s;&|]|\/s?bin\/)halt(\s|$)/,
87
+ /(^|[\s;&|]|\/s?bin\/)poweroff(\s|$)/,
88
+ /(^|[\s;&|]|\/s?bin\/)systemctl\s+(restart|stop|reload|start|enable|disable|mask)/,
89
+ /(^|[\s;&|]|\/s?bin\/)service\s+\S+\s+(restart|stop|reload|start)/,
90
+ /(^|[\s;&|]|\/s?bin\/)docker\s+(rm|stop|restart|kill|prune|system)/,
91
+ /(^|[\s;&|]|\/s?bin\/)apt(-get)?\s+(install|remove|purge|upgrade|update)/,
92
+ /(^|[\s;&|]|\/s?bin\/)yum\s+(install|remove|update|upgrade)/,
93
+ /(^|[\s;&|]|\/s?bin\/)dnf\s+(install|remove|update|upgrade)/,
94
+ /(^|[\s;&|]|\/s?bin\/)pip\s+(install|uninstall)/,
95
+ /(^|[\s;&|]|\/s?bin\/)npm\s+(install|uninstall|publish)/,
96
+ /(^|[\s;&|]|\/s?bin\/)git\s+(reset\s+--hard|push\s+.*--force|clean\s+-fd?)/,
92
97
  />\s*\/(?!dev\/null|dev\/stdout|dev\/stderr|tmp)/, // redirect to non-tmp/non-devnull file
93
98
  />>\s*\/(?!dev\/null|tmp)/, // append-redirect to non-tmp file
94
99
  /\|\s*sh(\s|$)/,
@@ -177,8 +182,16 @@ export function evaluatePolicy(serverConfig, toolName, command) {
177
182
  if (COMMAND_BEARING_TOOLS.has(toolName) && typeof command === 'string') {
178
183
  // The whole line, then each command in it, including those inside $(…)
179
184
  // and backticks: `echo $(rm -rf x)` has no space before its `rm`.
185
+ // Each of them as the shell reads it too: `r\<newline>m`, `r""m` and `r${x}m` are `rm`.
180
186
  const { segments, substitutions } = splitShellCommand(command);
181
- for (const text of [command, ...segments, ...substitutions]) {
187
+ const { texts, unreadable } = readSegments([...segments, ...substitutions]);
188
+ if (unreadable) {
189
+ return {
190
+ allowed: false,
191
+ reason: `Command refused on server "${serverConfig.name}" (mode: readonly): it uses ${unreadable}, which the destructive patterns cannot follow.`,
192
+ };
193
+ }
194
+ for (const text of [command, ...texts]) {
182
195
  for (const re of READONLY_DENY_REGEX) {
183
196
  if (re.test(text)) {
184
197
  return {
@@ -226,8 +239,12 @@ export function evaluatePolicy(serverConfig, toolName, command) {
226
239
  // started, and `docker ps; id` passed (GHSA-rfxw-26h6-7w42).
227
240
  const { segments, substitutions, writes, problem } = splitShellCommand(command);
228
241
 
242
+ // A DENY pattern is tested on what each command is as typed and on what the
243
+ // shell makes of it: `r""m`, `r\m`, `r${x}m` and a backslash-newline inside the
244
+ // name all run `rm` (GHSA-4fp4-fggm-cf5c). The ALLOW patterns stay on the text as typed.
245
+ const { texts: readings, unreadable, guessed } = readSegments(segments);
229
246
  for (const re of deny) {
230
- for (const text of [command, ...segments]) {
247
+ for (const text of [command, ...readings]) {
231
248
  if (re.test(text)) return refuse(`matches DENY pattern ${re}`);
232
249
  }
233
250
  }
@@ -237,6 +254,7 @@ export function evaluatePolicy(serverConfig, toolName, command) {
237
254
  }
238
255
 
239
256
  if (problem) return refuse(`the command could not be checked (${problem})`);
257
+ if (unreadable || guessed) return refuse(`the command could not be checked (${unreadable ?? guessed})`);
240
258
  if (substitutions.length) {
241
259
  return refuse('command substitution ($(…), backticks, <(…)) runs commands the allowlist cannot check');
242
260
  }
@@ -246,6 +264,8 @@ export function evaluatePolicy(serverConfig, toolName, command) {
246
264
  if (!segments.length) return refuse('empty command');
247
265
 
248
266
  for (const segment of segments) {
267
+ const unsafeName = commandWordProblem(segment);
268
+ if (unsafeName) return refuse(`the command could not be checked (${unsafeName})`);
249
269
  if (!allow.some(re => re.test(segment))) {
250
270
  return refuse(segments.length > 1
251
271
  ? `"${segment}" does not match any ALLOW_PATTERNS (every command in a list or pipeline must)`
@@ -281,3 +281,386 @@ export function splitShellCommand(command) {
281
281
  endSegment();
282
282
  return result;
283
283
  }
284
+
285
+ // ── What the shell makes of a command before it runs ───────────────────────────────
286
+ //
287
+ // The deny patterns are written against the name of a command (`\brm\b`, `^rm `). A
288
+ // shell does not run the text it was given: it removes quotes and backslashes,
289
+ // joins lines at a backslash-newline, replaces a name that holds nothing with
290
+ // nothing, splits a word at the blanks a name holds, and expands braces. `r""m`,
291
+ // `r\m`, `r${x}m` and a backslash and a newline between the `r` and the `m` are all
292
+ // `rm` (GHSA-4fp4-fggm-cf5c). A pattern tested only against what was typed
293
+ // is therefore tested against a command the shell does not run, and any
294
+ // allowed command that starts another one (`find -exec`, `xargs`, `env`, `sed`,
295
+ // `awk`, `tar`, `git`, `make`, an interpreter) lets the rest through.
296
+ //
297
+ // Everything above is a fixed rewrite, so it is read the same way the shell reads
298
+ // it and the pattern is tested on the result as well. What stands for text the
299
+ // reader cannot know (`$_`, `${x:-word}`, `{a,b}`: a line can make any of them
300
+ // spell a name) is reported, and restricted mode refuses it.
301
+ // What no reader can follow stays out of reach: a glob (`/bin/r?`), the value of a
302
+ // variable the line does not set, the text an interpreter runs (`sh -c`, `python -c`).
303
+ // A deny pattern is a guard rail against those, never a boundary around them.
304
+
305
+ const BRACE_GROUP = /^(?:\{[^{}\s,]*(?:,[^{}\s,]*)+\}|\{[^{}\s,]*\.\.[^{}\s,]*\})/;
306
+ /** A word before the command: `NAME=value`, or a redirection. */
307
+ const ASSIGNMENT_OR_REDIRECTION = /^(?:[A-Za-z_][A-Za-z0-9_]*=|\d*[<>]|&>)/;
308
+ const NAME_EXPANSION = /^\$([A-Za-z_][A-Za-z0-9_]*)/;
309
+ /** Combinations a brace expansion is read to, so `{a,b}{c,d}{e,f}…` cannot grow without end. */
310
+ const BRACE_READINGS = 64;
311
+
312
+ /**
313
+ * Length of the `${…}` at the start of `text`, nested ones counted; the rest of the text when it never closes.
314
+ * @param {string} text
315
+ */
316
+ function bracedLength(text) {
317
+ let depth = 0;
318
+ for (let i = 0; i < text.length; i++) {
319
+ if (text[i] === '\\') { i++; continue; }
320
+ if (text[i] === '$' && text[i + 1] === '{') { depth++; i++; continue; }
321
+ if (text[i] === '}' && --depth === 0) return i + 1;
322
+ }
323
+ return text.length;
324
+ }
325
+
326
+ /**
327
+ * Index of the quote ending the `$'…'` at the start of `text`, where bash, ksh
328
+ * and zsh read `\'` as a quote inside the string; -1 when it never ends.
329
+ * @param {string} text
330
+ */
331
+ function ansiCEnd(text) {
332
+ for (let i = 2; i < text.length; i++) {
333
+ if (text[i] === '\\') { i++; continue; }
334
+ if (text[i] === '\'') return i;
335
+ }
336
+ return -1;
337
+ }
338
+
339
+ /**
340
+ * The characters a `$'…'` string stands for: hexadecimal, octal and unicode
341
+ * escapes and the usual letters; any other escaped character stands for itself.
342
+ * @param {string} body
343
+ */
344
+ function decodeAnsiC(body) {
345
+ const letters = { a: '\x07', b: '\b', e: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v' };
346
+ return body.replace(/\\(x[0-9a-fA-F]{1,2}|u[0-9a-fA-F]{1,4}|U[0-9a-fA-F]{1,8}|[0-7]{1,3}|[\s\S])/g, (_all, code) => {
347
+ if (code[0] === 'x' && code.length > 1) return String.fromCharCode(parseInt(code.slice(1), 16));
348
+ if (/^[uU]/.test(code) && code.length > 1) return String.fromCodePoint(Math.min(parseInt(code.slice(1), 16), 0x10ffff));
349
+ if (/^[0-7]+$/.test(code)) return String.fromCharCode(parseInt(code, 8) & 0xff);
350
+ return Object.hasOwn(letters, code) ? letters[code] : code;
351
+ });
352
+ }
353
+
354
+ /**
355
+ * Remove every backslash-newline pair the shell would remove: all of them outside
356
+ * single quotes, and before anything else is read (`$\<newline>@` is `$@`).
357
+ * @param {string} text
358
+ */
359
+ function joinLines(text) {
360
+ let out = '';
361
+ let inSingle = false;
362
+ let inDouble = false;
363
+ for (let i = 0; i < text.length; i++) {
364
+ const ch = text[i];
365
+ if (ch === '\\' && !inSingle) {
366
+ if (text[i + 1] === '\n') { i++; continue; }
367
+ out += ch + (text[i + 1] ?? '');
368
+ i++;
369
+ continue;
370
+ }
371
+ if (ch === '\'' && !inDouble) inSingle = !inSingle;
372
+ else if (ch === '"' && !inSingle) inDouble = !inDouble;
373
+ out += ch;
374
+ }
375
+ return out;
376
+ }
377
+
378
+ /**
379
+ * Read one simple command the way the shell does before running it.
380
+ *
381
+ * @param {string} original - One segment, as `splitShellCommand` returned it
382
+ * @returns {{unquoted: string, bare: string, spaced: string, defaulted: string, unreadable: string|null, guessed: string|null}}
383
+ * `unquoted`: quotes, backslashes and line continuations removed, names left in;
384
+ * `bare`: also with every name removed, as when it is unset;
385
+ * `spaced`: with every name replaced by a blank, as when it holds blanks;
386
+ * `defaulted`: with `${name:-word}` replaced by its word, as when the name is unset;
387
+ * `unreadable`: the first thing found that no reading follows (`$_`);
388
+ * `guessed`: the first thing found that is read by guesses (`${x:-word}`, `{a,b}`)
389
+ */
390
+ function readOne(original) {
391
+ const text = joinLines(original);
392
+ let unquoted = '';
393
+ let bare = '';
394
+ let spaced = '';
395
+ let defaulted = '';
396
+ /** @type {string|null} */
397
+ let unreadable = null;
398
+ /** @type {string|null} */
399
+ let guessed = null;
400
+ let inDouble = false;
401
+ /** @param {string} s */
402
+ const plain = s => { unquoted += s; bare += s; spaced += s; defaulted += s; };
403
+ /** @param {string} s */
404
+ const expansion = s => { unquoted += s; spaced += ' '; };
405
+ /**
406
+ * `$_` is the last argument of the command before it: a line can set it
407
+ * (`echo m; r$_`), so it is the one name the reader cannot treat as empty.
408
+ * Every other name is read as unset, or as holding blanks, and the line cannot give it a value.
409
+ * @param {string} name
410
+ */
411
+ const classify = name => {
412
+ if (name.replace(/^#/, '') === '_') unreadable ||= 'the parameter $_, which holds the last argument of the command before it';
413
+ };
414
+
415
+ for (let i = 0; i < text.length;) {
416
+ const ch = text[i];
417
+ if (ch === '\\') {
418
+ const next = text[i + 1];
419
+ // A backslash that ends the text is dropped by sh, bash, ksh and zsh (dash keeps it).
420
+ if (next === undefined) { i++; continue; }
421
+ if (next === '\n') { i += 2; continue; }
422
+ // In double quotes a backslash only escapes these four characters.
423
+ if (inDouble && !'$`"\\'.includes(next)) plain(ch);
424
+ plain(next);
425
+ i += 2;
426
+ continue;
427
+ }
428
+ if (ch === '\'' && !inDouble) {
429
+ const end = text.indexOf('\'', i + 1);
430
+ plain(text.slice(i + 1, end < 0 ? text.length : end));
431
+ i = end < 0 ? text.length : end + 1;
432
+ continue;
433
+ }
434
+ if (ch === '"') { inDouble = !inDouble; i++; continue; }
435
+ if (ch === '$') {
436
+ const rest = text.slice(i);
437
+ // $"…" is a quote with a translation; $'…' is a quote with escapes (bash, ksh, zsh).
438
+ if (!inDouble && rest[1] === '"') { i++; continue; }
439
+ if (!inDouble && rest[1] === '\'') {
440
+ const end = ansiCEnd(rest);
441
+ plain(decodeAnsiC(rest.slice(2, end < 0 ? rest.length : end)));
442
+ i += end < 0 ? rest.length : end + 1;
443
+ continue;
444
+ }
445
+ const braced = PLAIN_EXPANSION.exec(rest);
446
+ if (braced) {
447
+ classify(braced[0].slice(2, -1));
448
+ expansion(braced[0]);
449
+ i += braced[0].length;
450
+ continue;
451
+ }
452
+ if (rest[1] === '{') {
453
+ guessed ||= 'a ${…} with an operator or a word in it, which can stand for any text';
454
+ const length = bracedLength(rest);
455
+ // ${name:-word}, ${name-word}, ${name:=word}, ${name=word}: the word, when the name is unset.
456
+ const fallback = /^\$\{[A-Za-z_][A-Za-z0-9_]*:?[-=]([\s\S]*)\}$/.exec(rest.slice(0, length));
457
+ if (fallback) defaulted += readOne(fallback[1]).unquoted;
458
+ expansion(rest.slice(0, length));
459
+ i += length;
460
+ continue;
461
+ }
462
+ if (rest[1] === '(') {
463
+ // $(…) and $((…)): read as holding nothing, as `r$(true)m` is `rm`; what is inside is checked on its own.
464
+ const end = closingParen(rest, 1);
465
+ const length = end < 0 ? rest.length : end + 1;
466
+ expansion(rest.slice(0, length));
467
+ i += length;
468
+ continue;
469
+ }
470
+ const named = NAME_EXPANSION.exec(rest);
471
+ if (named) {
472
+ classify(named[1]);
473
+ expansion(named[0]);
474
+ i += named[0].length;
475
+ continue;
476
+ }
477
+ // $! is the last background job, and there is none in a command line of its own.
478
+ if (/^\$[0-9@*!-]/.test(rest)) {
479
+ expansion(rest.slice(0, 2));
480
+ i += 2;
481
+ continue;
482
+ }
483
+ if (/^\$[?#$]/.test(rest)) { plain(rest.slice(0, 2)); i += 2; continue; }
484
+ plain('$');
485
+ i++;
486
+ continue;
487
+ }
488
+ if (ch === '`') {
489
+ const end = closingBacktick(text, i + 1);
490
+ const length = (end < 0 ? text.length : end + 1) - i;
491
+ expansion(text.slice(i, i + length));
492
+ i += length;
493
+ continue;
494
+ }
495
+ if (ch === '{' && !inDouble && BRACE_GROUP.test(text.slice(i))) {
496
+ guessed ||= 'a brace expansion ({a,b}, {1..3}), which sh does not expand and bash, ksh and zsh do';
497
+ }
498
+ plain(ch);
499
+ i++;
500
+ }
501
+ return { unquoted, bare, spaced, defaulted, unreadable, guessed };
502
+ }
503
+
504
+ /**
505
+ * What a text becomes when its brace expansions are carried out, for the
506
+ * groups a shell would expand: `r{m,}` is `rm` and `r`.
507
+ * @param {string} text
508
+ * @returns {string[]}
509
+ */
510
+ function expandBraces(text) {
511
+ let results = [text];
512
+ for (let round = 0; round < 8; round++) {
513
+ const next = [];
514
+ let changed = false;
515
+ for (const current of results) {
516
+ const group = /\{([^{}\s,]*(?:,[^{}\s,]*)+)\}/.exec(current);
517
+ if (!group) { next.push(current); continue; }
518
+ changed = true;
519
+ for (const alternative of group[1].split(',')) {
520
+ next.push(current.slice(0, group.index) + alternative + current.slice(group.index + group[0].length));
521
+ }
522
+ }
523
+ results = next.slice(0, BRACE_READINGS);
524
+ if (!changed) break;
525
+ }
526
+ return results;
527
+ }
528
+
529
+ /**
530
+ * `/bin/rm -rf x` runs `rm`: the same command with the directory of its name left out.
531
+ * @param {string} text
532
+ */
533
+ function withoutDirectory(text) {
534
+ const words = text.split(/([ \t]+)/);
535
+ let index = 0;
536
+ while (index < words.length && ASSIGNMENT_OR_REDIRECTION.test(words[index])) index += 2;
537
+ if (index >= words.length || !words[index].includes('/')) return null;
538
+ words[index] = words[index].slice(words[index].lastIndexOf('/') + 1);
539
+ return words.join('');
540
+ }
541
+
542
+ /** A word that is one quoted string with nothing the shell would act on inside it. */
543
+ const QUOTED_STRING = /^(?:'[^']*'|"[^"$`\\]*")$/;
544
+ /** What a word that starts another command follows: `find -exec "rm"`, `xargs "rm"`, `env "rm"`. */
545
+ const LAUNCHERS = new Set(['-exec', '-execdir', '-ok', '-okdir', 'xargs', 'env', 'nice', 'nohup', 'time', 'timeout',
546
+ 'exec', 'command', 'builtin', 'setsid', 'stdbuf', 'ionice', 'watch', 'parallel', 'flock', 'doas']);
547
+
548
+ /**
549
+ * The words of a simple command, each with the blanks after it: split at a space or a tab that is not
550
+ * quoted, escaped or inside `$(…)`, backticks or `${…}`.
551
+ * @param {string} text
552
+ * @returns {{text: string, gap: string}[]}
553
+ */
554
+ function splitWords(text) {
555
+ /** @type {{text: string, gap: string}[]} */
556
+ const words = [];
557
+ let start = 0;
558
+ let i = 0;
559
+ while (i < text.length) {
560
+ const ch = text[i];
561
+ if (ch === '\\') { i += 2; continue; }
562
+ if (ch === '\'') {
563
+ const end = text.indexOf('\'', i + 1);
564
+ i = end < 0 ? text.length : end + 1;
565
+ continue;
566
+ }
567
+ if (ch === '"') {
568
+ i++;
569
+ while (i < text.length && text[i] !== '"') i += text[i] === '\\' ? 2 : 1;
570
+ i++;
571
+ continue;
572
+ }
573
+ if (ch === '$' && text[i + 1] === '(') {
574
+ const end = closingParen(text, i + 1);
575
+ i = end < 0 ? text.length : end + 1;
576
+ continue;
577
+ }
578
+ if (ch === '$' && text[i + 1] === '{') { i += bracedLength(text.slice(i)); continue; }
579
+ if (ch === '`') {
580
+ const end = closingBacktick(text, i + 1);
581
+ i = end < 0 ? text.length : end + 1;
582
+ continue;
583
+ }
584
+ if (ch === ' ' || ch === '\t') {
585
+ let end = i;
586
+ while (text[end] === ' ' || text[end] === '\t') end++;
587
+ words.push({ text: text.slice(start, i), gap: text.slice(i, end) });
588
+ start = end;
589
+ i = end;
590
+ continue;
591
+ }
592
+ i++;
593
+ }
594
+ if (start < text.length) words.push({ text: text.slice(start), gap: '' });
595
+ return words;
596
+ }
597
+
598
+ /**
599
+ * Every reading of each command, for patterns that name a command to refuse:
600
+ * the text as typed first, then what the shell makes of it (see above).
601
+ *
602
+ * @param {string[]} segments - What `splitShellCommand` returned
603
+ * @returns {{texts: string[], unreadable: string|null, guessed: string|null}}
604
+ * `unreadable`: something no reading follows (`$_`), to refuse in every mode;
605
+ * `guessed`: something read by guesses (`${x:-word}`, `{a,b}`), which a mode
606
+ * that holds the line to an allowlist refuses
607
+ */
608
+ export function readSegments(segments) {
609
+ const texts = new Set();
610
+ /** @type {string|null} */
611
+ let unreadable = null;
612
+ /** @type {string|null} */
613
+ let guessed = null;
614
+ for (const segment of segments) {
615
+ texts.add(segment);
616
+ const words = splitWords(segment);
617
+ const readings = words.map(word => readOne(word.text));
618
+ for (const reading of readings) {
619
+ unreadable ||= reading.unreadable;
620
+ guessed ||= reading.guessed;
621
+ }
622
+ // A word that is only a quoted string (`"kill -9"`) is an argument: it is read
623
+ // as typed, or `grep "service x restart" log` would be a `service x restart`.
624
+ // It is read when it can be the command: the first word, or the one after a launcher.
625
+ let commandSeen = false;
626
+ const kept = words.map((word, index) => {
627
+ const isCommand = !commandSeen && !ASSIGNMENT_OR_REDIRECTION.test(word.text);
628
+ if (isCommand) commandSeen = true;
629
+ return !isCommand && !LAUNCHERS.has(words[index - 1]?.text ?? '') && QUOTED_STRING.test(word.text);
630
+ });
631
+ for (const kind of /** @type {const} */ (['unquoted', 'bare', 'spaced', 'defaulted'])) {
632
+ const text = words.map((word, index) => (kept[index] ? word.text : readings[index][kind]) + word.gap).join('');
633
+ for (const variant of expandBraces(text)) {
634
+ const trimmed = variant.trim();
635
+ texts.add(trimmed);
636
+ const bare = withoutDirectory(trimmed);
637
+ if (bare) texts.add(bare);
638
+ }
639
+ }
640
+ }
641
+ texts.delete('');
642
+ return { texts: [...texts], unreadable, guessed };
643
+ }
644
+
645
+ /**
646
+ * Why the name of the command in a segment cannot be trusted as typed, or null.
647
+ * An allow pattern is tested on the text as typed, so a name that is written with
648
+ * a quote, a backslash, a name or a glob (`ls""x`, `\ls`, `/bin/r?`) is not
649
+ * the name the pattern was matched against.
650
+ *
651
+ * @param {string} segment
652
+ * @returns {string|null}
653
+ */
654
+ export function commandWordProblem(segment) {
655
+ const words = segment.split(/[ \t]+/);
656
+ let index = 0;
657
+ // `NAME=value` before the command, and a redirection, are not the command.
658
+ while (index < words.length && ASSIGNMENT_OR_REDIRECTION.test(words[index])) index++;
659
+ const word = words[index] ?? '';
660
+ if (word === '[' || word === '[[') return null;
661
+ if (/['"\\$*?[{`]/.test(word)) {
662
+ return 'the name of the command is written with a quote, a backslash, a variable or a glob, so it is not the name the pattern was matched against';
663
+ }
664
+ return null;
665
+ }
666
+
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Where the file tools may touch the local disk.
3
+ *
4
+ * `ssh_download` writes a local file, `ssh_upload` reads one, `ssh_sync` does
5
+ * either. None of them looked at the local path, so an agent that could not run
6
+ * a single command on a `readonly` server could still have `ssh_download` write
7
+ * `~/.zshrc` or `~/.ssh/authorized_keys` on this machine, with content it had
8
+ * just put on the server (`printf … > /tmp/x` is allowed in `readonly`).
9
+ *
10
+ * A transfer root is the one directory the local side of a transfer may use:
11
+ *
12
+ * - `transferRoot` on a server (`SSH_SERVER_<NAME>_TRANSFER_ROOT`,
13
+ * `transfer_root` in TOML) turns it on for that server, in every mode, for
14
+ * all three tools;
15
+ * - a server in `readonly` or `restricted` mode has one even when none is set,
16
+ * for `ssh_download` (the other two are refused there already): the
17
+ * `transfers` folder of the manager home (`~/.ssh-manager/transfers`). It is
18
+ * created, private to the user, the first time a download needs it;
19
+ * - a server in `unrestricted` mode with no `transferRoot` is exactly what it
20
+ * was: no filter at all, by design.
21
+ *
22
+ * A path is accepted when its real location, after following every link, is
23
+ * inside the root. A relative path is read from the root. A link as the file
24
+ * itself is refused, in either direction, and so is a link directory that leads
25
+ * out. The checks run just before the transfer; they do not stop somebody who
26
+ * can already change files in the root while it runs.
27
+ */
28
+
29
+ import fs from 'fs';
30
+ import path from 'path';
31
+ import { expandHomePath, managerHome } from './config-paths.js';
32
+
33
+ const CONFINED_MODES = new Set(['readonly', 'restricted']);
34
+
35
+ /**
36
+ * @typedef {object} TransferPolicy
37
+ * @property {string} root - Where the local side of a transfer must stay
38
+ * @property {boolean} explicit - The server names its own root
39
+ */
40
+
41
+ /**
42
+ * The transfer policy of a server for a tool, or null when its local paths are
43
+ * not filtered.
44
+ *
45
+ * @param {{mode?: string, transferRoot?: string}|null|undefined} serverConfig
46
+ * @param {string} toolName - ssh_download, ssh_upload or ssh_sync
47
+ * @returns {TransferPolicy|null}
48
+ */
49
+ export function transferPolicy(serverConfig, toolName) {
50
+ const configured = typeof serverConfig?.transferRoot === 'string' ? serverConfig.transferRoot.trim() : '';
51
+ if (configured) return { root: path.resolve(expandHomePath(configured)), explicit: true };
52
+ // Without a named root only the download is held to the default one: the
53
+ // upload and the sync cannot run at all in these two modes.
54
+ if (toolName === 'ssh_download' && CONFINED_MODES.has(String(serverConfig?.mode ?? '').toLowerCase())) {
55
+ return { root: path.join(managerHome(), 'transfers'), explicit: false };
56
+ }
57
+ return null;
58
+ }
59
+
60
+ /**
61
+ * True when `candidate` is `root` or below it.
62
+ * @param {string} root
63
+ * @param {string} candidate
64
+ * @param {boolean} allowRoot
65
+ */
66
+ function within(root, candidate, allowRoot) {
67
+ const relative = path.relative(root, candidate);
68
+ if (relative === '') return allowRoot;
69
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
70
+ }
71
+
72
+ /** @param {string} target */
73
+ function lstatOrNull(target) {
74
+ try { return fs.lstatSync(target); } catch { return null; }
75
+ }
76
+
77
+ /**
78
+ * Where `target` really is: the part that exists with every link followed, then
79
+ * the part that does not exist yet as written.
80
+ * @param {string} target - Absolute path
81
+ * @returns {string}
82
+ */
83
+ function realLocation(target) {
84
+ const missing = [];
85
+ let current = target;
86
+ while (!lstatOrNull(current)) {
87
+ const parent = path.dirname(current);
88
+ if (parent === current) break;
89
+ missing.unshift(path.basename(current));
90
+ current = parent;
91
+ }
92
+ return path.join(fs.realpathSync.native(current), ...missing);
93
+ }
94
+
95
+ /**
96
+ * Resolve the local side of a transfer to the path the tool must use, or throw
97
+ * with the reason it may not.
98
+ *
99
+ * @param {TransferPolicy} policy
100
+ * @param {string} localPath - As the caller gave it
101
+ * @param {{direction: 'read'|'write', allowRoot?: boolean}} options
102
+ * `read`: the path must exist. `write`: its folder is made inside the root when missing.
103
+ * `allowRoot`: the root itself is acceptable (a folder for a sync).
104
+ * @returns {string} An absolute path under the real root; a trailing separator is kept
105
+ */
106
+ export function confineLocalPath(policy, localPath, { direction, allowRoot = false }) {
107
+ const given = String(localPath);
108
+ if (!given || given.includes('\0')) throw new Error('The local path is empty or not a valid path');
109
+ const hint = policy.explicit
110
+ ? 'the transfer root set for this server (transferRoot)'
111
+ : 'the transfer folder of a server in readonly or restricted mode (~/.ssh-manager/transfers, or set transferRoot on the server)';
112
+ const outside = () => new Error(`Local path "${given}" is outside ${hint}: ${policy.root}`);
113
+
114
+ fs.mkdirSync(policy.root, { recursive: true, mode: 0o700 });
115
+ const realRoot = fs.realpathSync.native(policy.root);
116
+ const trailing = /[\\/]$/.test(given) ? path.sep : '';
117
+
118
+ // A relative path is read from the root; an absolute one is taken as written. Either
119
+ // way what counts is where it really is: its folder with every link followed (so
120
+ // /tmp/x and /private/tmp/x, or the root by another name, are the same place, and a
121
+ // link folder that leads out is out). The file itself is looked at below.
122
+ const absolute = path.isAbsolute(given) ? path.resolve(given) : path.resolve(realRoot, given);
123
+ const target = path.join(realLocation(path.dirname(absolute)), path.basename(absolute));
124
+ if (!within(realRoot, target, allowRoot)) throw outside();
125
+
126
+ const existing = lstatOrNull(target);
127
+ if (existing?.isSymbolicLink()) throw new Error(`Local path "${given}" is a link; a transfer does not follow links`);
128
+ if (direction === 'read' && !existing) throw new Error(`Local path does not exist: ${given}`);
129
+ if (direction === 'write' && existing?.isDirectory() && !allowRoot) throw new Error(`Local path "${given}" is a folder`);
130
+ if (direction === 'write' && !existing) {
131
+ fs.mkdirSync(trailing ? target : path.dirname(target), { recursive: true, mode: 0o700 });
132
+ }
133
+ return trailing && !target.endsWith(path.sep) ? target + trailing : target;
134
+ }