ensure-rm-shim.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. /**
  2. * Seed the recoverable-delete `rm` shim into `<dataDir>/shims/`.
  3. *
  4. * WHY A SHIM INSTEAD OF MORE COMMAND REWRITING
  5. * --------------------------------------------
  6. * "Every delete is recoverable" is an EXECUTION-layer promise. Rewriting
  7. * command text can only honour it for shapes a parser recognises, and that set
  8. * is never complete: `xargs rm`, `find … -exec rm {} \;`, or an `rm` inside a
  9. * shell script the agent just wrote all slip through, because the literal token
  10. * `rm` never appears where a rewriter can reach it.
  11. *
  12. * PATH resolution has no such blind spot. Whatever invokes `rm` — the agent
  13. * directly, `xargs`, `find`, or a nested script — the shell resolves the name
  14. * through PATH, so a shim at the front of PATH is reached in every case. The
  15. * permission layer therefore stays a pure judgement (allow / deny / ask) and the
  16. * sandbox stays a pure kernel-level interceptor; neither needs to know that
  17. * deletes are recoverable at all.
  18. *
  19. * WHY NOT `<dataDir>/bin`
  20. * ----------------------
  21. * `ensurePathIntegration` appends `<dataDir>/bin` to the USER's `~/.zshrc` /
  22. * `~/.bashrc`. Dropping an `rm` in there would silently replace `rm` in the
  23. * user's own interactive terminal, which we must never do. `<dataDir>/shims` is
  24. * injected only into the agent's bash environment (see `BashEnvPolicy.
  25. * prependPath`), never into a user-facing shell.
  26. *
  27. * Windows is intentionally skipped: it has no sandbox, and PowerShell resolves
  28. * `rm` as an alias for `Remove-Item` rather than through PATH, so recoverable
  29. * deletion stays on the existing host-side launcher there.
  30. *
  31. * Idempotent: only rewrites when the on-disk content differs.
  32. */
  33. import { accessSync, chmodSync, constants, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
  34. import path from 'node:path';
  35. import { resolveBashEnvPolicy, type BashEnvPolicy } from '@mavis/agent-core/bash-subprocess-env';
  36. /**
  37. * Delegates to the sibling `../bin/mavis-trash` rather than an absolute path so
  38. * the shim keeps working if the dataDir is moved or mounted elsewhere.
  39. *
  40. * `exec` replaces the shim process, so the caller observes mavis-trash's own
  41. * exit status and stderr directly — an `rm` failure must stay an `rm` failure.
  42. * Arguments are forwarded verbatim: mavis-trash already accepts rm's surface
  43. * (`-f`, `-r`/`-R`, `-rf`, `--`) and mirrors `rm -f`'s empty-operand success.
  44. */
  45. export const RM_SHIM_CONTENT = `#!/bin/bash
  46. # Managed by MiniMax Code. Do not edit.
  47. #
  48. # Recoverable-delete shim: resolves ahead of /bin/rm on the agent's PATH so
  49. # every delete — including those reached through xargs, find -exec, or a
  50. # generated script — lands in the platform trash instead of being unlinked.
  51. #
  52. # This file is NOT on the user's interactive PATH; it applies to agent bash only.
  53. set -u
  54. shim_dir="$(cd -- "$(dirname -- "\${BASH_SOURCE[0]}")" && pwd -P)"
  55. trash_bin="$shim_dir/../bin/mavis-trash"
  56. if [ ! -x "$trash_bin" ]; then
  57. echo "rm: recoverable-delete runtime is missing at $trash_bin" >&2
  58. echo "rm: refusing to fall back to an unrecoverable delete" >&2
  59. exit 1
  60. fi
  61. exec "$trash_bin" "$@"
  62. `;
  63. /** Absolute path of the directory injected at the front of the agent's PATH. */
  64. export function resolveRmShimDir(dataDir: string): string {
  65. return path.join(dataDir, 'shims');
  66. }
  67. /**
  68. * Bash env policy for agent subprocesses, with the shim directory installed
  69. * ahead of the inherited PATH and a spawn preflight that keeps the
  70. * recoverable-delete promise fail-closed WITHOUT being fragile: if the shim is
  71. * missing or lost its execute bit (cache cleaner, restored backup, chmod), the
  72. * preflight first re-seeds it in place — `ensureRmShim` is idempotent — and
  73. * only refuses the spawn when that repair also fails (e.g. read-only dataDir).
  74. * A silent fall-through to `/bin/rm` is never possible. Without a dataDir
  75. * there is no shim to install, and Windows never uses the shim (see
  76. * `ensureRmShim`), so both return the shared resolver unchanged.
  77. */
  78. export function resolveAgentBashEnvPolicy(
  79. dataDir?: string,
  80. platform: NodeJS.Platform = process.platform,
  81. ): BashEnvPolicy {
  82. if (!dataDir || platform === 'win32') return resolveBashEnvPolicy({});
  83. const shimDir = resolveRmShimDir(dataDir);
  84. const shimPath = path.join(shimDir, 'rm');
  85. return resolveBashEnvPolicy({
  86. prependPath: [shimDir],
  87. spawnPreflight: () => {
  88. try {
  89. accessSync(shimPath, constants.X_OK);
  90. return;
  91. } catch {
  92. // Missing or not executable — attempt the in-place repair below.
  93. }
  94. try {
  95. ensureRmShim(dataDir, platform);
  96. accessSync(shimPath, constants.X_OK);
  97. } catch (cause) {
  98. throw new Error(
  99. `The recoverable-delete rm shim at ${shimPath} is missing or not executable and could not be re-seeded. ` +
  100. 'Refusing to start bash, because deletes would bypass the trash and become unrecoverable. ' +
  101. 'Check that the MiniMax Code data directory is writable, then restart the app to re-seed the shim.',
  102. { cause },
  103. );
  104. }
  105. },
  106. });
  107. }
  108. /**
  109. * Seed the shim. Returns the directory to prepend to PATH, or `undefined` when
  110. * the platform has no PATH-resolvable `rm` to shadow.
  111. */
  112. export function ensureRmShim(
  113. dataDir: string,
  114. platform: NodeJS.Platform = process.platform,
  115. ): string | undefined {
  116. if (platform === 'win32') return undefined;
  117. const shimDir = resolveRmShimDir(dataDir);
  118. mkdirSync(shimDir, { recursive: true });
  119. const shimPath = path.join(shimDir, 'rm');
  120. seedFileIfChanged(shimPath, RM_SHIM_CONTENT, 0o755);
  121. return shimDir;
  122. }
  123. function seedFileIfChanged(filePath: string, content: string, mode?: number): void {
  124. let existing: string | undefined;
  125. try {
  126. existing = readFileSync(filePath, 'utf8');
  127. } catch {
  128. existing = undefined;
  129. }
  130. if (existing !== content) {
  131. writeFileSync(filePath, content, mode === undefined ? undefined : { mode });
  132. }
  133. if (mode !== undefined) {
  134. // Repair the execute bit even when the content already matched: a shim that
  135. // is present but not executable would make bash fall through to /bin/rm.
  136. try {
  137. chmodSync(filePath, mode);
  138. } catch {
  139. // Best effort — a read-only dataDir surfaces at spawn time instead.
  140. }
  141. }
  142. }