fauxnix-cli 2.1.0 → 2.2.0

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/README.md CHANGED
@@ -15,10 +15,10 @@ back output that looks like GNU/Linux: `ls -l` columns, bash-style error message
15
15
  codes, UTF-8/GBK handled automatically.
16
16
 
17
17
  One-command install for **Claude Code · Codex · OpenCode · Kimi Code · Qwen Code**, plus any MCP
18
- client. **109 translated commands · 1,044 automated tests · 270-case Git Bash differential
18
+ client. **109 translated commands · 1,469 automated tests · 270-case Git Bash differential
19
19
  corpus plus 41 supplementary checks · zero LLM calls at runtime.**
20
20
 
21
- This checkout prepares **v2.0.0**. See [migration and release notes](docs/releases/v2.0.0.md)
21
+ This checkout is **v2.2.0**. See [migration and release notes](docs/releases/v2.0.0.md)
22
22
  for the Node.js requirement, changed file-operation contracts and verification limits.
23
23
  The npm badge and `@latest` examples show the published version until publication completes.
24
24
 
@@ -60,6 +60,12 @@ config files yourself.
60
60
  <details>
61
61
  <summary><b>Manual config per harness</b></summary>
62
62
 
63
+ `fauxnix install --<harness>` writes the **spawn-safe** form shown below: the absolute Node
64
+ executable plus this installation's absolute entry. A bare `command: "fauxnix"` is an
65
+ extension-less npm shim on Windows — MCP clients that spawn the server directly (CreateProcess)
66
+ cannot execute it (#252). Shell-wrapping clients like Claude Code accept either form; the
67
+ absolute form works everywhere.
68
+
63
69
  **Claude Code**
64
70
  ```bash
65
71
  claude mcp add fauxnix -- fauxnix mcp
@@ -68,8 +74,8 @@ claude mcp add fauxnix -- fauxnix mcp
68
74
  **Codex** (`~/.codex/config.toml` or `codex mcp add fauxnix -- fauxnix mcp`)
69
75
  ```toml
70
76
  [mcp_servers.fauxnix]
71
- command = "fauxnix"
72
- args = ["mcp"]
77
+ command = 'C:\Program Files\nodejs\node.exe'
78
+ args = ['C:\Users\<you>\AppData\Roaming\npm\node_modules\fauxnix-cli\dist\index.js', 'mcp']
73
79
  ```
74
80
  Note: in non-interactive `codex exec` mode, MCP tool calls are auto-denied by the approval
75
81
  layer; pass `--dangerously-bypass-approvals-and-sandbox` (or run interactively and approve
@@ -79,7 +85,10 @@ once).
79
85
  ```json
80
86
  {
81
87
  "mcp": {
82
- "fauxnix": { "type": "local", "command": ["fauxnix", "mcp"] }
88
+ "fauxnix": {
89
+ "type": "local",
90
+ "command": ["C:\\Program Files\\nodejs\\node.exe", "C:\\Users\\<you>\\AppData\\Roaming\\npm\\node_modules\\fauxnix-cli\\dist\\index.js", "mcp"]
91
+ }
83
92
  }
84
93
  }
85
94
  ```
@@ -88,7 +97,10 @@ once).
88
97
  ```json
89
98
  {
90
99
  "mcpServers": {
91
- "fauxnix": { "command": "fauxnix", "args": ["mcp"] }
100
+ "fauxnix": {
101
+ "command": "C:\\Program Files\\nodejs\\node.exe",
102
+ "args": ["C:\\Users\\<you>\\AppData\\Roaming\\npm\\node_modules\\fauxnix-cli\\dist\\index.js", "mcp"]
103
+ }
92
104
  }
93
105
  }
94
106
  ```
@@ -97,9 +109,8 @@ once).
97
109
  ```bash
98
110
  fauxnix install --qwen
99
111
  ```
100
- The installer preserves the rest of `settings.json` and writes an absolute Node + package-entry
101
- launcher so Qwen startup does not depend on its working directory or `PATH` order. See
102
- [the Qwen example](docs/examples/qwen.md) for the generated JSON shape.
112
+ The installer preserves the rest of `settings.json` and writes the same absolute launcher.
113
+ See [the Qwen example](docs/examples/qwen.md) for the generated JSON shape.
103
114
 
104
115
  **Any MCP client** — stdio server: `fauxnix mcp`. The tool name is `bash` (override with
105
116
  `FAUXNIX_TOOL_NAME`). The tool description already teaches the model the supported subset, so no
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { FauxnixSession } from './executor.js';
2
+ import { FauxnixSession, installSessionExitCleanup } from './executor.js';
3
3
  import { parseCommand } from './parser.js';
4
4
  import { EXECUTE_TRANSLATION, PURE_TRANSLATION, translateCommandList, } from './translator.js';
5
5
  import { listCommandsJson, registeredNames, specsMarkdown } from './registry.js';
@@ -30,6 +30,22 @@ Usage:
30
30
  Notes:
31
31
  FAUXNIX_PS=pwsh selects the opt-in PowerShell 7 host (5.1 is the default).
32
32
  Unknown commands (git, node, npm, python, cargo, ...) pass through and run natively.`;
33
+ /**
34
+ * POSIX word quoting (#259): a single token is a whole command line (the
35
+ * common `-c "echo hi"` shape) and passes through verbatim; multiple tokens
36
+ * are separate shell words, so any token carrying whitespace/quotes/metachars
37
+ * is single-quoted — `fauxnix translate echo "a b"` keeps the double space.
38
+ */
39
+ function shellQuoteWord(s) {
40
+ if (/^[A-Za-z0-9_@%+=:,./-]*$/.test(s))
41
+ return s;
42
+ return "'" + s.replace(/'/g, "'\\''") + "'";
43
+ }
44
+ function joinArgv(tokens) {
45
+ if (tokens.length <= 1)
46
+ return tokens[0] ?? '';
47
+ return tokens.map(shellQuoteWord).join(' ');
48
+ }
33
49
  export async function runCli(argv) {
34
50
  if (argv.length === 0) {
35
51
  console.log(USAGE);
@@ -40,6 +56,11 @@ export async function runCli(argv) {
40
56
  console.log(`fauxnix ${packageVersion}`);
41
57
  return;
42
58
  }
59
+ // Help must never spawn PowerShell (#259): it answers on any OS.
60
+ if (verb === '--help' || verb === '-h' || verb === 'help') {
61
+ console.log(USAGE);
62
+ return;
63
+ }
43
64
  if (verb === 'list') {
44
65
  if (rest[0] === '--json') {
45
66
  console.log(JSON.stringify(listCommandsJson(), null, 2));
@@ -94,19 +115,20 @@ export async function runCli(argv) {
94
115
  return;
95
116
  }
96
117
  if (verb === 'translate') {
97
- const cmd = rest.join(' ');
118
+ const cmd = joinArgv(rest);
98
119
  const list = parseCommand(cmd);
99
120
  const plans = translateCommandList(list, PURE_TRANSLATION);
100
121
  console.log(plans.map((p) => p.script).join('\n# ---- next segment ----\n'));
101
122
  return;
102
123
  }
103
- const cmd = verb === '-c' || verb === '-e' ? rest.join(' ') : argv.join(' ');
124
+ const cmd = verb === '-c' || verb === '-e' ? joinArgv(rest) : joinArgv(argv);
104
125
  if (!cmd.trim()) {
105
126
  console.log(USAGE);
106
127
  return;
107
128
  }
108
129
  const list = parseCommand(cmd);
109
130
  const plans = translateCommandList(list, EXECUTE_TRANSLATION);
131
+ installSessionExitCleanup();
110
132
  const session = new FauxnixSession();
111
133
  try {
112
134
  const result = await session.run(plans);
@@ -434,6 +434,7 @@ const unzip = (args) => {
434
434
  const arc = operandExpr(rest[0]);
435
435
  const dirExpr = dir ? operandExpr(dir) : "'.'";
436
436
  return [
437
+ 'Add-Type -AssemblyName System.IO.Compression',
437
438
  'Add-Type -AssemblyName System.IO.Compression.FileSystem',
438
439
  '$fx_arc = ' + arc,
439
440
  'if (-not (Test-Path -LiteralPath $fx_arc -PathType Leaf)) {',
@@ -462,10 +463,107 @@ const unzip = (args) => {
462
463
  ' } finally { $fx_z.Dispose() }',
463
464
  ].join('\n')
464
465
  : [
466
+ // Extract entry by entry so every target is proven to stay inside
467
+ // the destination (zip-slip, #257) regardless of which Archive
468
+ // module / .NET version the host has. Nothing is written unless
469
+ // every entry passes validation.
470
+ // Known limitations: names without the UTF-8 flag are decoded by
471
+ // .NET (OEM code page on Windows PowerShell 5.1, UTF-8 on pwsh 7);
472
+ // targets beyond MAX_PATH fail per entry on 5.1 unless long paths
473
+ // are enabled. Duplicate/case-colliding names: first wins without
474
+ // -o (warning), last wins with -o.
465
475
  ' $fx_dir = ' + dirExpr,
476
+ ' $fx_z = $null',
466
477
  ' try {',
467
- ' Expand-Archive -LiteralPath $fx_arc -DestinationPath $fx_dir -Force:' + (over ? '$true' : '$false') + ' -ErrorAction Stop',
468
- " } catch { [Console]::Error.WriteLine('unzip: fauxnix: ' + $_.Exception.Message + ' (use -o to overwrite)'); $script:fx_exit = 1 }",
478
+ ' $fx_root = [IO.Path]::GetFullPath($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath([string]$fx_dir))',
479
+ // root with exactly one trailing separator ("C:\" stays "C:\")
480
+ " $fx_rootT = $fx_root.TrimEnd([char[]]@('\\', '/')) + [IO.Path]::DirectorySeparatorChar",
481
+ ' $fx_z = [IO.Compression.ZipFile]::OpenRead((Resolve-Path -LiteralPath $fx_arc).ProviderPath)',
482
+ ' $fx_bad = @()',
483
+ ' $fx_plan = @()',
484
+ ' foreach ($fx_e in $fx_z.Entries) {',
485
+ ' $fx_n = [string]$fx_e.FullName',
486
+ ' $fx_t = $null',
487
+ " $fx_why = 'outside destination'",
488
+ " $fx_dev = @($fx_n -split '[\\\\/]' | Where-Object { (($_ -split '\\.')[0]).TrimEnd(' ') -match '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$' })",
489
+ // rooted, drive-qualified (or NTFS stream) names are never relative
490
+ // Directory entries end in a separator; some writers instead set the
491
+ // MS-DOS directory attribute (0x10) on a zero-length entry.
492
+ " $fx_isDir = $fx_n.EndsWith('/') -or $fx_n.EndsWith('\\') -or ($fx_e.Length -eq 0 -and ($fx_e.ExternalAttributes -band 0x10) -ne 0)",
493
+ " if ($fx_n -match '^[\\\\/]') { $fx_why = 'absolute path' }",
494
+ " elseif ($fx_n.IndexOf(':') -ge 0) { $fx_why = 'drive or stream name' }",
495
+ " elseif ($fx_dev.Count -gt 0) { $fx_why = 'reserved device name' }",
496
+ ' else {',
497
+ " try { $fx_t = [IO.Path]::GetFullPath([IO.Path]::Combine($fx_rootT, $fx_n)) } catch { $fx_why = 'invalid name' }",
498
+ // "./" or "a/.." resolve to the root itself: inside, not an escape
499
+ " if ($null -ne $fx_t) {",
500
+ " $fx_tT = $fx_t.TrimEnd([char[]]@('\\', '/')) + [IO.Path]::DirectorySeparatorChar",
501
+ " if (-not $fx_tT.StartsWith($fx_rootT, [StringComparison]::OrdinalIgnoreCase)) { $fx_t = $null }",
502
+ // only a directory entry may name the destination itself
503
+ " elseif ($fx_tT.Length -eq $fx_rootT.Length -and -not $fx_isDir) { $fx_t = $null; $fx_why = 'names the destination itself' }",
504
+ " }",
505
+ ' }',
506
+ ' if ($null -eq $fx_t) { $fx_bad += ,@($fx_n, $fx_why) } else { $fx_plan += ,@($fx_e, $fx_t, $fx_isDir) }',
507
+ ' }',
508
+ ' if ($fx_bad.Count -gt 0) {',
509
+ " foreach ($fx_b in $fx_bad) { [Console]::Error.WriteLine(\"unzip: fauxnix: refusing unsafe entry '\" + $fx_b[0] + \"' (\" + $fx_b[1] + \")\") }",
510
+ ' $script:fx_exit = 1',
511
+ ' } else {',
512
+ // targets written by this run (case-insensitive, like NTFS)
513
+ ' $fx_done = @{}',
514
+ ' foreach ($fx_p in $fx_plan) {',
515
+ ' $fx_e = $fx_p[0]',
516
+ ' $fx_t = $fx_p[1]',
517
+ ' try {',
518
+ // An existing symlink/junction below the root (or at the target)
519
+ // would redirect the write outside the destination.
520
+ ' $fx_linked = $false',
521
+ " $fx_cur = $fx_t.TrimEnd([char[]]@('\\', '/'))",
522
+ ' while ($null -ne $fx_cur -and $fx_cur.Length -ge $fx_rootT.Length) {',
523
+ ' $fx_attr = $null',
524
+ ' try { $fx_attr = [IO.File]::GetAttributes($fx_cur) } catch {}',
525
+ ' if ($null -ne $fx_attr -and ($fx_attr -band [IO.FileAttributes]::ReparsePoint)) { $fx_linked = $true; break }',
526
+ ' $fx_cur = [IO.Path]::GetDirectoryName($fx_cur)',
527
+ ' }',
528
+ ' if ($fx_linked) {',
529
+ " [Console]::Error.WriteLine(\"unzip: fauxnix: refusing entry '\" + $fx_e.FullName + \"' (path goes through a symbolic link or junction)\")",
530
+ ' $script:fx_exit = 1',
531
+ ' continue',
532
+ ' }',
533
+ ' if ($fx_p[2]) {',
534
+ ' [void][IO.Directory]::CreateDirectory($fx_t)',
535
+ ' continue',
536
+ ' }',
537
+ // Duplicate or case-colliding names inside the archive: without -o
538
+ // the first one wins (warning only, like declining unzip's
539
+ // overwrite prompt); with -o the later one replaces it.
540
+ (over ? " if ($false) {" : " if ($fx_done.ContainsKey($fx_t)) {"),
541
+ " [Console]::Error.WriteLine('unzip: fauxnix: skipping ' + $fx_e.FullName + ': same name as an entry already extracted (' + $fx_done[$fx_t] + ')')",
542
+ ' continue',
543
+ ' }',
544
+ " if (Test-Path -LiteralPath $fx_t -PathType Container) {",
545
+ " [Console]::Error.WriteLine('unzip: fauxnix: cannot extract ' + $fx_e.FullName + ': a directory with that name exists')",
546
+ ' $script:fx_exit = 1',
547
+ ' continue',
548
+ ' }',
549
+ ' if ((Test-Path -LiteralPath $fx_t) -and ' + (over ? '$false' : '$true') + ') {',
550
+ " [Console]::Error.WriteLine('unzip: fauxnix: ' + $fx_e.FullName + ' already exists (use -o to overwrite)')",
551
+ ' $script:fx_exit = 1',
552
+ ' continue',
553
+ ' }',
554
+ ' [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($fx_t))',
555
+ ...(over
556
+ ? [
557
+ // -o: a ReadOnly file would make ExtractToFile throw
558
+ " if ([IO.File]::Exists($fx_t)) { $fx_a = [IO.File]::GetAttributes($fx_t); if ($fx_a -band [IO.FileAttributes]::ReadOnly) { [IO.File]::SetAttributes($fx_t, $fx_a -band (-bnot [IO.FileAttributes]::ReadOnly)) } }",
559
+ ]
560
+ : []),
561
+ ' [IO.Compression.ZipFileExtensions]::ExtractToFile($fx_e, $fx_t, $true)',
562
+ ' $fx_done[$fx_t] = $fx_e.FullName',
563
+ " } catch { [Console]::Error.WriteLine('unzip: fauxnix: cannot extract ' + $fx_e.FullName + ': ' + $_.Exception.Message); $script:fx_exit = 1 }",
564
+ ' }',
565
+ ' }',
566
+ " } catch { [Console]::Error.WriteLine('unzip: fauxnix: ' + $_.Exception.Message); $script:fx_exit = 1 } finally { if ($null -ne $fx_z) { $fx_z.Dispose() } }",
469
567
  ].join('\n'),
470
568
  '}',
471
569
  ].join('\n');
@@ -1,4 +1,12 @@
1
1
  import { CommandSpec, Handler } from '../registry.js';
2
+ /**
3
+ * PS helper: map a caught ErrorRecord/exception to the GNU strerror text that
4
+ * coreutils would print. The whole InnerException chain is inspected (an
5
+ * outer generic IOException may wrap the specific cause); only Win32-facility
6
+ * HResults (0x8007xxxx) are decoded. Unknown failures return the caller's
7
+ * deterministic fallback, never the localized .NET message.
8
+ */
9
+ export declare const PS_IOERR_FN: string;
2
10
  /** Destructive file commands migrated first (#130). Unspec'd handlers stay unchecked.
3
11
  * cp `-f` is always-on overwrite. mv `-f` retains safe same-volume regular-file
4
12
  * replacement and never overrides preservation limits or permissions. */
@@ -1,6 +1,6 @@
1
1
  import { FauxnixParseError, wordToString } from '../ast.js';
2
2
  import { parseWords, psStr, } from '../registry.js';
3
- import { argListExpr, exprOfWord, operandExpr } from '../translator.js';
3
+ import { argListExpr, exprOfWord, globOperandExpr, operandExpr } from '../translator.js';
4
4
  import { PS_WRITE_FN, fxTermLine } from './text-output.js';
5
5
  import { PS_MOVE_REPLACE_FN } from './move-native.js';
6
6
  /* ------------------------------------------------------------------ */
@@ -15,9 +15,12 @@ const PS_GLOB_FN = [
15
15
  'function fx-glob($p) {',
16
16
  " if ($p -notlike '*[*?]*') { return @($p) }",
17
17
  ' $m = @(Get-Item -Path $p -ErrorAction SilentlyContinue)',
18
- ' if ($m.Count -eq 0) { return @($p) }',
18
+ ' if ($m.Count -eq 0) { return @(fx-wclit $p) }',
19
19
  ' return @($m | ForEach-Object { $_.FullName })',
20
20
  '}',
21
+ // Unescape wildcard-escaped literals (#255): quoted glob characters that
22
+ // matched nothing keep their shell spelling as the literal operand.
23
+ "function fx-wclit($p) { return ($p -replace '`(?=[*?[])', '') }",
21
24
  ].join('\n');
22
25
  /** PS helper: read a file as text, UTF-8 first then GBK fallback. */
23
26
  const PS_READTEXT_FN = [
@@ -67,7 +70,7 @@ const ls = (args) => {
67
70
  const sortByTime = flags.has('t');
68
71
  const sortBySize = flags.has('S');
69
72
  const reverse = flags.has('r');
70
- const targets = operandWords.length ? argListExpr(operandWords) : "@('.')";
73
+ const targets = operandWords.length ? argListExpr(operandWords, globOperandExpr) : "@('.')";
71
74
  return [
72
75
  PS_GLOB_FN,
73
76
  PS_FTIME_FN,
@@ -150,7 +153,7 @@ const cp = (args) => {
150
153
  const noclobber = flags.has('n') || longs.has('--no-clobber');
151
154
  return [
152
155
  PS_GLOB_FN,
153
- '$fx_all = ' + argListExpr(operandWords),
156
+ '$fx_all = ' + argListExpr(operandWords, globOperandExpr),
154
157
  "if ($fx_all.Count -lt 2) { $fx_srcs = @(); $fx_dst = '' } else { $fx_dst = [string]$fx_all[$fx_all.Count - 1]; $fx_srcs = @($fx_all[0..($fx_all.Count - 2)]) }",
155
158
  '$fx_srcs = @($fx_srcs | ForEach-Object { fx-glob $_ })',
156
159
  "if ($fx_srcs.Count -eq 0) { [Console]::Error.WriteLine('cp: missing file operand'); $script:fx_exit = 1 }",
@@ -179,7 +182,7 @@ const mv = (args) => {
179
182
  return [
180
183
  PS_GLOB_FN,
181
184
  PS_MOVE_REPLACE_FN,
182
- '$fx_all = ' + argListExpr(operandWords),
185
+ '$fx_all = ' + argListExpr(operandWords, globOperandExpr),
183
186
  "if ($fx_all.Count -lt 2) { $fx_srcs = @(); $fx_dst = '' } else { $fx_dst = [string]$fx_all[$fx_all.Count - 1]; $fx_srcs = @($fx_all[0..($fx_all.Count - 2)]) }",
184
187
  '$fx_srcs = @($fx_srcs | ForEach-Object { fx-glob $_ })',
185
188
  "if ($fx_srcs.Count -eq 0) { [Console]::Error.WriteLine('mv: missing file operand'); $script:fx_exit = 1 }",
@@ -224,27 +227,121 @@ const mv = (args) => {
224
227
  '}',
225
228
  ].join('\n');
226
229
  };
230
+ /**
231
+ * PS helper: map a caught ErrorRecord/exception to the GNU strerror text that
232
+ * coreutils would print. The whole InnerException chain is inspected (an
233
+ * outer generic IOException may wrap the specific cause); only Win32-facility
234
+ * HResults (0x8007xxxx) are decoded. Unknown failures return the caller's
235
+ * deterministic fallback, never the localized .NET message.
236
+ */
237
+ export const PS_IOERR_FN = [
238
+ 'function fx-ioerr1($x) {',
239
+ " if ($x -is [UnauthorizedAccessException] -or $x -is [Security.SecurityException]) { return 'Permission denied' }",
240
+ " if ($x -is [IO.PathTooLongException]) { return 'File name too long' }",
241
+ " if ($x -is [IO.DirectoryNotFoundException] -or $x -is [IO.FileNotFoundException] -or $x -is [IO.DriveNotFoundException] -or $x -is [System.Management.Automation.ItemNotFoundException] -or $x -is [System.Management.Automation.DriveNotFoundException]) { return 'No such file or directory' }",
242
+ ' if ((($x.HResult -shr 16) -band 0xFFFF) -ne 0x8007) { return $null }',
243
+ ' switch ($x.HResult -band 0xFFFF) {',
244
+ " { $_ -in 2, 3 } { return 'No such file or directory' }",
245
+ " 5 { return 'Permission denied' }",
246
+ " 19 { return 'Read-only file system' }",
247
+ " { $_ -in 32, 33 } { return 'Device or resource busy' }",
248
+ " { $_ -in 80, 183 } { return 'File exists' }",
249
+ " 112 { return 'No space left on device' }",
250
+ " 123 { return 'Invalid argument' }",
251
+ " 145 { return 'Directory not empty' }",
252
+ " 206 { return 'File name too long' }",
253
+ " 267 { return 'Not a directory' }",
254
+ ' }',
255
+ ' return $null',
256
+ '}',
257
+ 'function fx-ioerr($e, [string]$fallback) {',
258
+ ' $x = $e',
259
+ ' if ($x -is [System.Management.Automation.ErrorRecord]) { $x = $x.Exception }',
260
+ ' $fx_depth = 0',
261
+ ' while ($null -ne $x -and $fx_depth -lt 16) {',
262
+ ' $fx_r = fx-ioerr1 $x',
263
+ ' if ($null -ne $fx_r) { return $fx_r }',
264
+ ' $x = $x.InnerException',
265
+ ' $fx_depth++',
266
+ ' }',
267
+ ' return $fallback',
268
+ '}',
269
+ ].join('\n');
270
+ /**
271
+ * GNU rm's preserve-root failsafe. The last of --preserve-root /
272
+ * --no-preserve-root wins; preserving is the default. (`--preserve-root=all`
273
+ * is rejected by the spec layer: its cross-device check is not implemented.)
274
+ */
275
+ function rmPreservesRoot(args) {
276
+ let preserve = true;
277
+ for (const w of args) {
278
+ const t = wordToString(w);
279
+ if (t === '--')
280
+ break;
281
+ if (t === '--preserve-root')
282
+ preserve = true;
283
+ else if (t === '--no-preserve-root')
284
+ preserve = false;
285
+ }
286
+ return preserve;
287
+ }
227
288
  const rm = (args) => {
228
289
  const { flags, longs, operandWords } = parseWords(args);
229
290
  const recurse = flags.has('r') || flags.has('R') || longs.has('--recursive');
230
291
  const force = flags.has('f') || longs.has('--force');
231
292
  const verbose = flags.has('v') || longs.has('--verbose');
293
+ const guardRoot = recurse && rmPreservesRoot(args);
294
+ const b = (v) => (v ? '$true' : '$false');
295
+ const danger = (operand) => "if (" + operand + " -eq '/') { [Console]::Error.WriteLine(\"rm: it is dangerous to operate recursively on '/'\") } " +
296
+ "else { [Console]::Error.WriteLine(\"rm: it is dangerous to operate recursively on '\" + " + operand + " + \"' (same as '/')\") }; " +
297
+ "[Console]::Error.WriteLine('rm: use --no-preserve-root to override this failsafe'); $script:fx_exit = 1; continue";
232
298
  return [
233
299
  PS_GLOB_FN,
234
- '$fx_files = ' + psArray(operandWords),
235
- 'if ($fx_files.Count -eq 0 -and ' + (force ? '$false' : '$true') + ') { [Console]::Error.WriteLine(\'rm: missing operand\'); $script:fx_exit = 1 }',
300
+ PS_IOERR_FN,
301
+ '$fx_files = ' + psArray(operandWords, globOperandExpr),
302
+ 'if ($fx_files.Count -eq 0 -and ' + b(!force) + ") { [Console]::Error.WriteLine('rm: missing operand'); $script:fx_exit = 1 }",
303
+ '$fx_guardroot = ' + b(guardRoot),
236
304
  'foreach ($fx_f in $fx_files) {',
305
+ ' $fx_s = [string]$fx_f',
306
+ // GNU always refuses a last component of "." or ".."; on Windows a drive
307
+ // prefix ("C:..", drive-relative) is also a component boundary.
308
+ " $fx_leaf = ($fx_s -replace '^[A-Za-z]:', '').TrimEnd([char[]]@('/', '\\'))",
309
+ " $fx_leaf = $fx_leaf.Substring($fx_leaf.LastIndexOfAny([char[]]@('/', '\\')) + 1)",
310
+ " if ($fx_leaf -eq '.' -or $fx_leaf -eq '..') { [Console]::Error.WriteLine(\"rm: refusing to remove '.' or '..' directory: skipping '\" + $fx_s + \"'\"); $script:fx_exit = 1; continue }",
311
+ // "/", "//", "///" all name the root; refuse before Test-Path, which may
312
+ // treat "//"-prefixed text as a (malformed) UNC path and report it absent.
313
+ " if ($fx_guardroot -and $fx_s -match '^[/\\\\]+$') { " + danger('$fx_s') + ' }',
237
314
  ' foreach ($fx_g in (fx-glob $fx_f)) {',
238
315
  ' if (-not (Test-Path -LiteralPath $fx_g)) {',
239
- ' if (' + (force ? '$false' : '$true') + ') { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': No such file or directory"); $script:fx_exit = 1 }',
316
+ ' if (' + b(!force) + ') { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': No such file or directory"); $script:fx_exit = 1 }',
240
317
  ' continue',
241
318
  ' }',
242
319
  ' $fx_isdir = (Test-Path -LiteralPath $fx_g -PathType Container)',
243
- ' if ($fx_isdir -and ' + (recurse ? '$false' : '$true') + ') { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': Is a directory"); $script:fx_exit = 1; continue }',
320
+ ' if ($fx_isdir -and ' + b(!recurse) + ') { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': Is a directory"); $script:fx_exit = 1; continue }',
321
+ ' if ($fx_isdir -and $fx_guardroot) {',
322
+ // Fail closed: if the path cannot be canonicalized, do not delete it.
323
+ ' $fx_rp = $null',
324
+ ' try { $fx_rp = [IO.Path]::GetFullPath((Resolve-Path -LiteralPath $fx_g -ErrorAction Stop).ProviderPath) } catch {}',
325
+ ' if ($null -eq $fx_rp) { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': cannot resolve path for the --preserve-root check"); $script:fx_exit = 1; continue }',
326
+ ' $fx_root = [IO.Path]::GetPathRoot($fx_rp)',
327
+ " if ([string]::IsNullOrEmpty($fx_root) -or $fx_rp.TrimEnd([char[]]@('/', '\\')) -ieq ([string]$fx_root).TrimEnd([char[]]@('/', '\\'))) { " + danger('$fx_g') + ' }',
328
+ ' }',
329
+ // A directory symlink/junction is removed as a link; never traverse into
330
+ // its target (Windows PowerShell 5.1 Remove-Item -Recurse can follow it).
331
+ ' if ($fx_isdir -and ' + b(recurse) + ') {',
332
+ ' $fx_item = Get-Item -LiteralPath $fx_g -Force -ErrorAction SilentlyContinue',
333
+ ' if ($null -ne $fx_item -and ($fx_item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {',
334
+ ' try {',
335
+ ' [IO.Directory]::Delete($fx_item.FullName, $false)',
336
+ ' if (' + b(verbose) + ') { [Console]::Error.WriteLine("removed \'" + $fx_g + "\'") }',
337
+ ' } catch { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': " + (fx-ioerr $_ \'Permission denied\')); $script:fx_exit = 1 }',
338
+ ' continue',
339
+ ' }',
340
+ ' }',
244
341
  ' try {',
245
- ' Remove-Item -LiteralPath $fx_g -Recurse:' + (recurse ? '$true' : '$false') + ' -Force -ErrorAction Stop',
246
- ' if (' + (verbose ? '$true' : '$false') + ') { [Console]::Error.WriteLine("removed \'" + $fx_g + "\'") }',
247
- ' } catch { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': Permission denied"); $script:fx_exit = 1 }',
342
+ ' Remove-Item -LiteralPath $fx_g -Recurse:' + b(recurse) + ' -Force -ErrorAction Stop',
343
+ ' if (' + b(verbose) + ') { [Console]::Error.WriteLine("removed \'" + $fx_g + "\'") }',
344
+ ' } catch { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': " + (fx-ioerr $_ \'Permission denied\')); $script:fx_exit = 1 }',
248
345
  ' }',
249
346
  '}',
250
347
  ].join('\n');
@@ -257,6 +354,7 @@ const mkdir = (args) => {
257
354
  const parents = flags.has('p') || longs.has('--parents');
258
355
  const verbose = flags.has('v') || longs.has('--verbose');
259
356
  return [
357
+ PS_IOERR_FN,
260
358
  '$fx_dirs = ' + psArray(operandWords),
261
359
  "if ($fx_dirs.Count -eq 0) { [Console]::Error.WriteLine('mkdir: missing operand'); $script:fx_exit = 1 }",
262
360
  'foreach ($fx_d in $fx_dirs) {',
@@ -265,9 +363,18 @@ const mkdir = (args) => {
265
363
  ' continue',
266
364
  ' }',
267
365
  ' try {',
268
- ' New-Item -ItemType Directory -Path $fx_d -Force:' + (parents ? '$true' : '$false') + ' -ErrorAction Stop | Out-Null',
366
+ // Literal creation (#255): [IO.Directory] never interprets wildcard
367
+ // characters or PS provider prefixes (Env:, Function:) the way
368
+ // New-Item -Path does.
369
+ ...(parents
370
+ ? [' [void][IO.Directory]::CreateDirectory($fx_d)']
371
+ : [
372
+ ' $fx_par = [IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($fx_d))',
373
+ ' if ($null -ne $fx_par -and -not (Test-Path -LiteralPath $fx_par -PathType Container)) { throw [IO.DirectoryNotFoundException]::new() }',
374
+ ' [void][IO.Directory]::CreateDirectory($fx_d)',
375
+ ]),
269
376
  ' if (' + (verbose ? '$true' : '$false') + ') { [Console]::Error.WriteLine("mkdir: created directory \'" + $fx_d + "\'") }',
270
- ' } catch { [Console]::Error.WriteLine("mkdir: cannot create directory \'" + $fx_d + "\': " + $_.Exception.Message); $script:fx_exit = 1 }',
377
+ ' } catch { [Console]::Error.WriteLine("mkdir: cannot create directory \'" + $fx_d + "\': " + (fx-ioerr $_ \'No such file or directory\')); $script:fx_exit = 1 }',
271
378
  '}',
272
379
  ].join('\n');
273
380
  };
@@ -287,15 +394,18 @@ const touch = (args) => {
287
394
  const { flags, longs, operandWords } = parseWords(args);
288
395
  const noCreate = flags.has('c') || longs.has('--no-create');
289
396
  return [
397
+ PS_IOERR_FN,
290
398
  '$fx_files = ' + psArray(operandWords),
291
399
  "if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('touch: missing file operand'); $script:fx_exit = 1 }",
292
400
  'foreach ($fx_f in $fx_files) {',
293
401
  ' if (Test-Path -LiteralPath $fx_f) {',
294
- ' try { (Get-Item -LiteralPath $fx_f).LastWriteTime = Get-Date } catch { [Console]::Error.WriteLine("touch: cannot touch \'" + $fx_f + "\': Permission denied"); $script:fx_exit = 1 }',
402
+ ' try { (Get-Item -LiteralPath $fx_f -Force -ErrorAction Stop).LastWriteTime = Get-Date } catch { [Console]::Error.WriteLine("touch: cannot touch \'" + $fx_f + "\': " + (fx-ioerr $_ \'Permission denied\')); $script:fx_exit = 1 }',
295
403
  ' } else {',
296
404
  ' if (' + (noCreate ? '$true' : '$false') + ') { continue }',
297
- ' try { New-Item -ItemType File -Path $fx_f -ErrorAction Stop | Out-Null }',
298
- ' catch { [Console]::Error.WriteLine("touch: cannot touch \'" + $fx_f + "\': No such file or directory"); $script:fx_exit = 1 }',
405
+ // Literal creation (#255): .NET File.Create never reads wildcard
406
+ // characters or PS provider prefixes into the name.
407
+ ' try { $fx_nfs = [IO.File]::Create($fx_f); $fx_nfs.Close() }',
408
+ ' catch { [Console]::Error.WriteLine("touch: cannot touch \'" + $fx_f + "\': " + (fx-ioerr $_ \'No such file or directory\')); $script:fx_exit = 1 }',
299
409
  ' }',
300
410
  '}',
301
411
  ].join('\n');
@@ -470,7 +580,7 @@ const stat = (args, ctx) => {
470
580
  PS_FTIME_FN,
471
581
  PS_GLOB_FN,
472
582
  ...(printfMode ? [PS_WRITE_FN, fxTermLine(ctx.position), '$fx_stat_out = New-Object System.Text.StringBuilder'] : []),
473
- '$fx_files = ' + psArray(operandWords),
583
+ '$fx_files = ' + psArray(operandWords, globOperandExpr),
474
584
  "if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('stat: missing operand'); $script:fx_exit = 1 }",
475
585
  'foreach ($fx_f in $fx_files) {',
476
586
  ' foreach ($fx_g in (fx-glob $fx_f)) {',
@@ -504,7 +614,7 @@ const file = (args) => {
504
614
  return [
505
615
  PS_GLOB_FN,
506
616
  PS_READTEXT_FN,
507
- '$fx_files = ' + psArray(operandWords),
617
+ '$fx_files = ' + psArray(operandWords, globOperandExpr),
508
618
  "if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('file: missing operand'); $script:fx_exit = 1 }",
509
619
  'foreach ($fx_f in $fx_files) {',
510
620
  ' foreach ($fx_g in (fx-glob $fx_f)) {',
@@ -1050,6 +1160,8 @@ export const specs = [
1050
1160
  opt('R', '--recursive'),
1051
1161
  opt('f', '--force'),
1052
1162
  opt('v', '--verbose'),
1163
+ opt(undefined, '--preserve-root'),
1164
+ opt(undefined, '--no-preserve-root'),
1053
1165
  opt('i', '--interactive', 'unsupported', INTERACTIVE),
1054
1166
  ], rm),
1055
1167
  fileSpec(['touch'], ['write'], [opt('c', '--no-create')], touch),
@@ -37,6 +37,10 @@ const { pipeline } = require('node:stream/promises');
37
37
  if (leased) {
38
38
  process.stdin.on('end', stopDecoder);
39
39
  process.stdin.on('error', stopDecoder);
40
+ // #240 hardening: 'close' fires when the stream is torn down without a
41
+ // clean 'end' - exactly the intermittent CI-hang shape. Listening for
42
+ // both costs nothing and stops the decoder either way.
43
+ process.stdin.on('close', stopDecoder);
40
44
  process.stdin.resume();
41
45
  }
42
46
  const parent = Number(process.argv[3]);