mcp-ssh-manager 4.3.4 → 4.3.6

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,100 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [4.3.6] - 2026-11-25
11
+
12
+ **A security release: upgrade if an agent runs in a project folder you did not write.**
13
+ The `.env` of the folder an MCP client was started in could define a server whose
14
+ `PROXYCOMMAND` runs a command on your machine when a tool connects to it
15
+ ([GHSA-wxcj-q5hp-wjrw](https://github.com/bvisible/mcp-ssh-manager/security/advisories/GHSA-wxcj-q5hp-wjrw),
16
+ high). Every release from 3.3.0, where `PROXYCOMMAND` was added, is affected.
17
+ **One thing behaves differently on purpose:** that `.env` is no longer read unless you
18
+ placed it or set `SSH_MANAGER_TRUST_PROJECT_ENV=1` (details below). Servers in
19
+ `~/.ssh-manager/.env`, in a file named by `SSH_ENV_PATH` or `SSH_MANAGER_ENV`, in the
20
+ vault or in the process environment are not affected. Nothing else changes (the release
21
+ pipeline upgrades 3.8.5, 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,
22
+ 4.3.4 and 4.3.5 from the registry to this version and back).
23
+
24
+ The Windows installer is still **not Authenticode-signed**, for the same reason
25
+ as 4.0.0: Windows shows *"Windows protected your PC"*, *More info → Run anyway*,
26
+ and `ssh-manager app` checks the installer against the SHA-256 in
27
+ `release-manifest-win32.json`. macOS builds are signed and notarized.
28
+
29
+ ### Security
30
+
31
+ - **A project's `.env` could run a command on this machine**
32
+ ([GHSA-wxcj-q5hp-wjrw](https://github.com/bvisible/mcp-ssh-manager/security/advisories/GHSA-wxcj-q5hp-wjrw),
33
+ reported by Pythame). The engine read the `.env` of its working directory, which is
34
+ whatever project the MCP client was started in, when `~/.ssh-manager/.env` did not
35
+ exist. That file can define a server with `SSH_SERVER_<NAME>_PROXYCOMMAND`, or point
36
+ `SSH_CONFIG_PATH` at a TOML with a `proxy_command`, and the engine runs that command
37
+ through the shell when a tool connects to the server: before any SSH banner, whatever
38
+ the server's mode or approval, and even when the connection then fails. A repository
39
+ with such a file was enough. Every release from 3.3.0, where `PROXYCOMMAND` was
40
+ added, is affected.
41
+ **One thing behaves differently on purpose:** the `.env` of the working directory is
42
+ no longer read, unless it is also a file you placed (`~/.ssh-manager/.env`, your
43
+ home's `.env`, or the install directory's, which is what a run from a checkout
44
+ reads) or the environment of the MCP server says `SSH_MANAGER_TRUST_PROJECT_ENV=1`.
45
+ A project file cannot grant that itself, and a file it names through
46
+ `SSH_CONFIG_PATH` is not read either. When a project `.env` that defines servers is
47
+ left unread, the engine says so at startup, in `ssh_list_servers` and in "server not
48
+ found", with the three ways to have it read: move it to `~/.ssh-manager/.env`, name
49
+ it with `SSH_ENV_PATH`, or set the variable (in the `env` block of the MCP client's
50
+ configuration, where the client's own approval of a project server applies). With a
51
+ file in `~/.ssh-manager/.env`, `SSH_ENV_PATH` or `SSH_MANAGER_ENV`, nothing changes.
52
+ Two details that come with it: a project `.env` no longer hides your home `.env`, and
53
+ a `.env` written into the project while the engine runs is not picked up.
54
+
55
+ ## [4.3.5] - 2026-11-25
56
+
57
+ **A security release: upgrade if a server uses `restricted` or `readonly` mode.** A
58
+ command a `DENY_PATTERNS` entry (or the `readonly` list) names could still run behind an
59
+ allowed launcher such as `find -exec` or `xargs`, because the shell rewrites a word
60
+ before it runs it
61
+ ([GHSA-4fp4-fggm-cf5c](https://github.com/bvisible/mcp-ssh-manager/security/advisories/GHSA-4fp4-fggm-cf5c),
62
+ high). Every release from 3.5.0, where the security modes were added, is affected.
63
+ **Two things behave differently on purpose:** `restricted` mode now refuses `$_`,
64
+ brace expansions and a command whose own name has a quote, a backslash, a variable
65
+ or a glob; `readonly` mode refuses `$_` and reads a name after `/bin/` or `/sbin/`, so
66
+ `ls -l /usr/bin/su` is refused there (details below). Nothing else changes (the release pipeline upgrades 3.8.5,
67
+ 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
68
+ registry to this version and back).
69
+
70
+ The Windows installer is still **not Authenticode-signed**, for the same reason
71
+ as 4.0.0: Windows shows *"Windows protected your PC"*, *More info → Run anyway*,
72
+ and `ssh-manager app` checks the installer against the SHA-256 in
73
+ `release-manifest-win32.json`. macOS builds are signed and notarized.
74
+
75
+ ### Security
76
+
77
+ - **A command a `DENY_PATTERNS` entry names could still run, behind an allowed
78
+ launcher** ([GHSA-4fp4-fggm-cf5c](https://github.com/bvisible/mcp-ssh-manager/security/advisories/GHSA-4fp4-fggm-cf5c),
79
+ reported by Pythame). The patterns, and the built-in list of `readonly`, were
80
+ tested on the text as typed, and a shell does not run that text: `r\<newline>m`,
81
+ `r${x}m` (x unset), `r""m`, `r\m` and `"r"m` are all `rm`. With `^find` allowed and
82
+ `\brm\b` denied, `find . -exec r""m -rf x {} +` was allowed and deleted the target.
83
+ Every command is now also tested as the shell reads it: quotes, backslashes and
84
+ line continuations removed, variables read as unset and as blanks, `${x:-word}` as
85
+ its word, braces expanded, and the name of the command without its directory.
86
+ Found with a differential check against sh, dash, bash, ksh and zsh (1,500 random
87
+ spellings of `rm` behind `find`, `xargs` and `env`), which is now part of the tests.
88
+ - **Fixed alongside:** `/usr/bin/rm` and `find -exec /bin/rm` were not seen by the
89
+ `readonly` list; a command name written with a quote or a variable (`ls""x`) matched
90
+ an allow pattern for another name than the one the shell ran.
91
+
92
+ ### Changed
93
+
94
+ - **`restricted` mode now refuses what a line can use to spell a name:** `$_`,
95
+ brace expansions (`{a,b}`, `{1..3}`) and a command whose own name has a quote,
96
+ a backslash, a variable or a glob (`"ls" -l`, `\ls`). Arguments are not affected
97
+ (`ls "/var/log"`, `echo $HOME`, `find . -name "*.log"`).
98
+ - **`readonly` mode refuses `$_`, and reads a name after `/bin/` or `/sbin/`:**
99
+ `ls -l /usr/bin/su` is now refused. A quoted argument is still an argument
100
+ (`grep "kill -9" /var/log/syslog` runs); a quoted command name is not (`"rm" -rf x`).
101
+ - **A glob or an interpreter is still out of reach of a deny pattern.** The security
102
+ modes document lists what an allow pattern should not admit.
103
+
10
104
  ## [4.3.4] - 2026-11-23
11
105
 
12
106
  **A security release: upgrade.** `ssh_download` wrote any local path it was given,
@@ -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.3.tgz"
17
- sha256 "d8ee1b01cdc8238edee9c9bf0a6f83f7be98750ccd23976d273e7ad7f65df3cf"
16
+ url "https://registry.npmjs.org/mcp-ssh-manager/-/mcp-ssh-manager-4.3.5.tgz"
17
+ sha256 "43c0c08251bf15ebb3407e5371f26a065641c820eb9347f972408c03f8508aa7"
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.4-c04500?style=flat-square)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.4)
28
+ [![Version](https://img.shields.io/badge/release-4.3.6-c04500?style=flat-square)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.6)
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.4`):** one installation with its own runtime,
61
+ **Desktop application (`4.3.6`):** 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.4):
63
+ installation. [Download it](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.6):
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.4,
71
+ **Already using npm / the CLI?** `npm update -g mcp-ssh-manager` brings 4.3.6,
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
@@ -526,6 +526,8 @@ file people email each other and commit by accident.
526
526
 
527
527
  Two interchangeable formats, read by the same loader: `.env` is the usual choice with Claude Code, TOML with Codex (from `SSH_CONFIG_PATH`, or `~/.codex/ssh-config.toml`). Both can coexist — the loader merges them.
528
528
 
529
+ The `.env` is `~/.ssh-manager/.env`, or the file `SSH_ENV_PATH` names. One that only sits in the project folder your agent was started in is **not** read (a server entry can run a command on your machine): move it, name it, or set `SSH_MANAGER_TRUST_PROJECT_ENV=1` — see [docs/MIGRATION.md](docs/MIGRATION.md#which-env-is-read).
530
+
529
531
  ```env
530
532
  SSH_SERVER_[NAME]_HOST=hostname_or_ip
531
533
  SSH_SERVER_[NAME]_USER=username
@@ -720,6 +722,10 @@ The hero animation ships twice, light and dark, swapped by `<picture>` on `prefe
720
722
 
721
723
  ## What's new
722
724
 
725
+ **[4.3.6](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.6) — a security fix: a project folder's `.env` could run a command on your machine.** The `.env` of the folder an MCP client was started in could define a server whose `PROXYCOMMAND` ran when a tool connected to it, before any SSH login and whatever the server's mode. That `.env` is no longer read unless you placed it (`~/.ssh-manager/.env`, your home's, the install folder's) or set `SSH_MANAGER_TRUST_PROJECT_ENV=1` in the environment of the engine; the engine says which file it left unread. If your servers were in a `.env` next to the project, move it to `~/.ssh-manager/.env` or name it with `SSH_ENV_PATH`. Reported by @Pythame (GHSA-wxcj-q5hp-wjrw). See the [CHANGELOG](CHANGELOG.md#436---2026-11-25).
726
+
727
+ **[4.3.5](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.5) — a security fix: `restricted` and `readonly` modes could be made to run a command their patterns deny.** A shell rewrites a word before it runs it (`r""m`, `r\m` and `r${x}m` are all `rm`), and the patterns were tested on the text as typed, so a denied command could ride behind an allowed launcher such as `find -exec` or `xargs`. Every command is now also tested as the shell reads it. If you use `restricted` or `readonly` mode, upgrade. Reported by @Pythame (GHSA-4fp4-fggm-cf5c). See the [CHANGELOG](CHANGELOG.md#435---2026-11-25).
728
+
723
729
  **[4.3.4](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.4) — 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
730
 
725
731
  **[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).
package/cli/vault.js CHANGED
@@ -19,7 +19,7 @@ import { writeRecoveryFile, readRecoveryFile, describeRecoveryFile } from '../sr
19
19
  import { SecretStore, defaultVaultPath, SECRET_FIELDS } from '../src/secret-store.js';
20
20
  import { defaultSocketPath, isControlPlaneListening, VALID_APPROVAL_MODES } from '../src/approval.js';
21
21
  import { ConfigLoader } from '../src/config-loader.js';
22
- import { resolveEnvFilePath } from '../src/config-paths.js';
22
+ import { envFileChoice } from '../src/config-paths.js';
23
23
  import { GREEN, YELLOW, RED, DIM, RESET } from './style.js';
24
24
 
25
25
  /**
@@ -282,7 +282,8 @@ async function cmdRemove(store, name) {
282
282
  }
283
283
 
284
284
  async function cmdImport(store, fromPath) {
285
- const envPath = fromPath || resolveEnvFilePath();
285
+ const choice = fromPath ? null : envFileChoice();
286
+ const envPath = fromPath || choice.path;
286
287
  if (fromPath && !fs.existsSync(fromPath)) {
287
288
  console.error(`${RED}No configuration found at ${fromPath}${RESET}`);
288
289
  process.exit(1);
@@ -298,6 +299,8 @@ async function cmdImport(store, fromPath) {
298
299
 
299
300
  if (servers.size === 0) {
300
301
  console.log(`${YELLOW}No servers found in the configuration.${RESET}`);
302
+ // A .env in this folder is read only when named: a project file is not trusted by default.
303
+ if (choice?.skippedProject) console.log(`${YELLOW}${choice.skippedProject} was not read; to import it, name it.${RESET}`);
301
304
  console.log(`${DIM}Point at a file with: ssh-manager vault import --from /path/to/.env (or .toml)${RESET}`);
302
305
  return;
303
306
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "ssh-manager-desktop",
3
- "version": "4.3.4",
3
+ "version": "4.3.6",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "ssh-manager-desktop",
9
- "version": "4.3.4",
9
+ "version": "4.3.6",
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.4",
4
+ "version": "4.3.6",
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.4 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.4)).
3
+ **4.0 is released, on npm and as a desktop application**; the latest is 4.3.6 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.6)).
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
@@ -316,10 +316,28 @@ it; the engine never starts one.
316
316
  `SSH_MANAGER_ENV` — the CLI's variable, which 3.8.x's engine never read. A
317
317
  profile that still exports `SSH_MANAGER_ENV` towards a file that no longer
318
318
  exists is skipped with a warning, so the usual discovery (`~/.ssh-manager/.env`,
319
- then the working directory, then your home) applies as it did in 3.8.x. A missing
319
+ then your home, then the install directory) applies. A missing
320
320
  file named by `SSH_ENV_PATH` stays the choice and is reported at startup, in
321
321
  `ssh_list_servers` and in "server not found".
322
322
 
323
+ Up to 4.3.5 the discovery also read the `.env` of the working directory, second
324
+ in the list. That is the project the MCP client was started in, and a server
325
+ entry can carry a command that runs on your machine when it connects
326
+ (`PROXYCOMMAND`, or a `proxy_command` in a TOML), so it is no longer read unless
327
+ it is a file you placed or you say so
328
+ ([GHSA-wxcj-q5hp-wjrw](https://github.com/bvisible/mcp-ssh-manager/security/advisories/GHSA-wxcj-q5hp-wjrw)).
329
+ If your servers were in a `.env` next to the project, do one of:
330
+
331
+ - move it to `~/.ssh-manager/.env` (the place `llms-install.md` and the CLI use);
332
+ - name it: `SSH_ENV_PATH=/path/to/.env` in the `env` block of the MCP client;
333
+ - trust the project's file: `SSH_MANAGER_TRUST_PROJECT_ENV=1` in the same block.
334
+ It is read from the environment of the engine only; a `.env` cannot set it.
335
+
336
+ The engine says which file it left unread: in the log at startup, in
337
+ `ssh_list_servers` and in "server not found". The `.env` of the install
338
+ directory, which is what runs from a checkout read, and your home's, are read
339
+ as before.
340
+
323
341
  ## Rolling back to 3.8.7
324
342
 
325
343
  ```bash
@@ -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`
@@ -240,6 +269,14 @@ never code), `ssh_backup_list`, `ssh_session_start`,
240
269
  not as an unbreakable shell escape. `restricted` is the stronger of the two:
241
270
  every command must be one you allowed, so keep its patterns narrow — an
242
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.
243
280
  - **Aliases are expanded before policy evaluation** — you can't bypass a DENY
244
281
  by hiding `rm` behind an alias defined via `ssh_command_alias`.
245
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.4",
3
+ "version": "4.3.6",
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: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",
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:projectenv && 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",
@@ -42,6 +42,7 @@
42
42
  "test:agentannounce": "node tests/test-agent-announce.js",
43
43
  "test:autherrors": "node tests/test-auth-errors.js",
44
44
  "test:envchoice": "node tests/test-env-file-choice.js",
45
+ "test:projectenv": "node tests/test-project-env-trust.js",
45
46
  "test:lifecycle": "node tests/test-lifecycle.js",
46
47
  "test:tunnel": "node tests/test-tunnel-listen.js",
47
48
  "test:sync": "node tests/test-sync-stats.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.4",
9
+ "version": "4.3.6",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "mcp-ssh-manager",
14
- "version": "4.3.4",
14
+ "version": "4.3.6",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -31,6 +31,33 @@ export function expandHomePath(value) {
31
31
  return text;
32
32
  }
33
33
 
34
+ /** @param {unknown} value */
35
+ function isOn(value) {
36
+ return /^(1|true|yes|on)$/i.test(String(value ?? '').trim());
37
+ }
38
+
39
+ /**
40
+ * True when both names lead to the same file, links followed. A file that does
41
+ * not exist is the same as nothing.
42
+ * @param {string} first
43
+ * @param {string} second
44
+ */
45
+ function sameFile(first, second) {
46
+ try { return fs.realpathSync(first) === fs.realpathSync(second); } catch { return false; }
47
+ }
48
+
49
+ /**
50
+ * True when a .env sets up the SSH manager: a server, or a TOML to read. Any
51
+ * repository has a .env of its own, so only one that does is worth a word.
52
+ * @param {string} file
53
+ */
54
+ function configuresServers(file) {
55
+ try {
56
+ return Object.keys(dotenv.parse(fs.readFileSync(file)))
57
+ .some(key => key === 'SSH_CONFIG_PATH' || /^SSH_SERVER_[A-Z0-9_]+_HOST$/.test(key));
58
+ } catch { return false; }
59
+ }
60
+
34
61
  /**
35
62
  * Which .env the engine reads, and why.
36
63
  *
@@ -45,32 +72,60 @@ export function expandHomePath(value) {
45
72
  * the variable, and reported in `ignored`. SSH_ENV_PATH was always the
46
73
  * engine's own override: a missing file there stays the choice, reported as
47
74
  * `missing`, so nothing is silently read in place of what was asked for.
75
+ *
76
+ * The `.env` of the working directory is the one file in the list that nobody
77
+ * chose: it belongs to whatever project the MCP client was started in. A
78
+ * server entry can carry a command that runs on this machine when it connects
79
+ * (PROXYCOMMAND, or one in the TOML that SSH_CONFIG_PATH points to), so a
80
+ * repository that ships a `.env` could make the engine run its commands, with
81
+ * no SSH host and no approval involved. That file is therefore read only when
82
+ * it is also the file the user placed (the manager home, the home directory or
83
+ * the install directory, which is the case when the engine runs from a
84
+ * checkout), or when the process environment says SSH_MANAGER_TRUST_PROJECT_ENV.
85
+ * It is never read from a file: the project's own `.env` cannot vouch for itself.
86
+ * Otherwise it is left unread and named in `skippedProject`, and where a file is
87
+ * wanted but none exists the manager home is used, so that a `.env` an agent
88
+ * writes into the project later is not picked up by a running engine either.
48
89
  * @param {{ projectRoot?: string }} [options]
49
90
  * @returns {{path: string, variable: string|null, missing: boolean,
50
- * ignored: {variable: string, path: string}|null}}
91
+ * ignored: {variable: string, path: string}|null, skippedProject: string|null}}
51
92
  */
52
93
  export function envFileChoice({
53
94
  projectRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
54
95
  } = {}) {
55
96
  if (process.env.SSH_ENV_PATH) {
56
97
  const file = process.env.SSH_ENV_PATH;
57
- return { path: file, variable: 'SSH_ENV_PATH', missing: !fs.existsSync(file), ignored: null };
98
+ return { path: file, variable: 'SSH_ENV_PATH', missing: !fs.existsSync(file), ignored: null, skippedProject: null };
58
99
  }
59
100
  let ignored = null;
60
101
  if (process.env.SSH_MANAGER_ENV) {
61
102
  const file = process.env.SSH_MANAGER_ENV;
62
- if (fs.existsSync(file)) return { path: file, variable: 'SSH_MANAGER_ENV', missing: false, ignored: null };
103
+ if (fs.existsSync(file)) {
104
+ return { path: file, variable: 'SSH_MANAGER_ENV', missing: false, ignored: null, skippedProject: null };
105
+ }
63
106
  ignored = { variable: 'SSH_MANAGER_ENV', path: file };
64
107
  }
65
- const candidates = [
66
- path.join(managerHome(), '.env'),
67
- path.join(process.cwd(), '.env'),
68
- path.join(os.homedir(), '.env'),
69
- path.join(projectRoot, '.env'),
70
- ];
108
+ const managerEnv = path.join(managerHome(), '.env');
109
+ const homeEnv = path.join(os.homedir(), '.env');
110
+ const installEnv = path.join(projectRoot, '.env');
111
+ const projectEnv = path.join(process.cwd(), '.env');
112
+ const trustProject = isOn(process.env.SSH_MANAGER_TRUST_PROJECT_ENV)
113
+ || [managerEnv, homeEnv, installEnv].some(file => sameFile(file, projectEnv));
114
+ const candidates = [managerEnv, ...(trustProject ? [projectEnv] : []), homeEnv, installEnv];
71
115
  const found = candidates.find(candidate => fs.existsSync(candidate));
116
+ // Said only when it would have been read before: with a file in the manager home
117
+ // the project's was never looked at, and a project .env that sets up no server
118
+ // (most of them) has nothing to be missed.
119
+ const skippedProject = !trustProject && !fs.existsSync(managerEnv) && configuresServers(projectEnv)
120
+ ? projectEnv : null;
72
121
  // No file at all is a valid setup (servers from the environment or TOML).
73
- return { path: found || path.join(process.cwd(), '.env'), variable: null, missing: false, ignored };
122
+ return {
123
+ path: found || (trustProject ? projectEnv : managerEnv),
124
+ variable: null,
125
+ missing: false,
126
+ ignored,
127
+ skippedProject
128
+ };
74
129
  }
75
130
 
76
131
  /**
@@ -92,10 +147,26 @@ export function envFileProblem(choice) {
92
147
  if (choice.missing) {
93
148
  return `${choice.variable} names ${choice.path}, which does not exist: no server is loaded from a .env file`;
94
149
  }
150
+ const problems = [];
95
151
  if (choice.ignored) {
96
- return `${choice.ignored.variable} names ${choice.ignored.path}, which does not exist; using ${choice.path} instead`;
152
+ problems.push(`${choice.ignored.variable} names ${choice.ignored.path}, which does not exist; using ${choice.path} instead`);
97
153
  }
98
- return null;
154
+ if (choice.skippedProject) {
155
+ problems.push(projectEnvNotice(choice.skippedProject));
156
+ }
157
+ return problems.length ? problems.join('; ') : null;
158
+ }
159
+
160
+ /**
161
+ * What to tell the operator when the .env of the working directory was left
162
+ * unread, and the three ways to have it read.
163
+ * @param {string} file
164
+ * @returns {string}
165
+ */
166
+ export function projectEnvNotice(file) {
167
+ return `${file} was not read: a project file is not trusted to start commands on this machine. `
168
+ + `Move it to ${path.join(managerHome(), '.env')}, name it with SSH_ENV_PATH, `
169
+ + 'or set SSH_MANAGER_TRUST_PROJECT_ENV=1 in the environment of the MCP server';
99
170
  }
100
171
 
101
172
  /** Read file-selected TOML settings just as the MCP entry point does.
package/src/index.js CHANGED
@@ -13,7 +13,7 @@ import path from 'path';
13
13
  import crypto from 'node:crypto';
14
14
  import { AsyncLocalStorage } from 'node:async_hooks';
15
15
  import { isDeepStrictEqual } from 'node:util';
16
- import { envFileChoice, envFileProblem, expandHomePath } from './config-paths.js';
16
+ import { envFileChoice, envFileProblem, expandHomePath, projectEnvNotice } from './config-paths.js';
17
17
  import { fileURLToPath } from 'url';
18
18
  import { ServerConfigManager } from './server-config-manager.js';
19
19
  import {
@@ -272,7 +272,8 @@ async function getServerConfig(serverName) {
272
272
  const servers = await loadServerConfig();
273
273
  const name = serverName && resolveServerName(String(serverName), servers);
274
274
  if (!name) {
275
- throw new Error(`Server "${serverName}" not found${envProblem && !Object.keys(servers).length ? ` (${envProblem})` : ''}`);
275
+ // A project .env left unread is named even when other servers loaded: the one asked for may be in it.
276
+ throw new Error(`Server "${serverName}" not found${envProblem && (!Object.keys(servers).length || envChoice.skippedProject) ? ` (${envProblem})` : ''}`);
276
277
  }
277
278
  return servers[name];
278
279
  }
@@ -2419,6 +2420,7 @@ registerToolConditional(
2419
2420
  ];
2420
2421
  // The list stays the first item, unchanged, for anything that parses it.
2421
2422
  if (envProblem && !serverInfo.length) content.push({ type: 'text', text: `No server loaded: ${envProblem}.` });
2423
+ else if (envChoice.skippedProject) content.push({ type: 'text', text: `Note: ${projectEnvNotice(envChoice.skippedProject)}.` });
2422
2424
  return { content };
2423
2425
  }
2424
2426
  );
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
+