cli.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. #!/usr/bin/env node
  2. import { quote } from "./utils/shell-quote.js";
  3. import { Command } from "commander";
  4. import { SandboxManager } from "./index.js";
  5. import type { SandboxRuntimeConfig } from "./sandbox/sandbox-config.js";
  6. import { spawn } from "child_process";
  7. import { logForDebugging } from "./utils/debug.js";
  8. import { loadConfig, loadConfigFromString } from "./utils/config-loader.js";
  9. import * as readline from "readline";
  10. import * as fs from "fs";
  11. import * as path from "path";
  12. import * as os from "os";
  13. /**
  14. * Get default config path
  15. */
  16. function getDefaultConfigPath(): string {
  17. return path.join(os.homedir(), ".srt-settings.json");
  18. }
  19. /**
  20. * Create a minimal default config if no config file exists
  21. */
  22. function getDefaultConfig(): SandboxRuntimeConfig {
  23. return {
  24. network: {
  25. allowedDomains: [],
  26. deniedDomains: [],
  27. },
  28. filesystem: {
  29. denyRead: [],
  30. allowRead: [],
  31. allowWrite: [],
  32. denyWrite: [],
  33. },
  34. };
  35. }
  36. async function main(): Promise<void> {
  37. const program = new Command();
  38. program
  39. .name("srt")
  40. .description(
  41. "Run commands in a sandbox with network and filesystem restrictions",
  42. )
  43. .version(process.env.npm_package_version || "1.0.0");
  44. // ── Windows install/uninstall ─────────────────────────────────
  45. // Self-elevating one-shot install (one UAC prompt). Also
  46. // available programmatically as installWindowsSandbox().
  47. program
  48. .command("windows-install")
  49. .description(
  50. "Windows: provision the `srt-sandbox` user account + install WFP " +
  51. "filters (one UAC prompt). No logout needed.",
  52. )
  53. .option("--sublayer-guid <guid>", "WFP sublayer GUID")
  54. .option(
  55. "--proxy-port-range <lo-hi>",
  56. "loopback PERMIT port range (e.g. 60080-60089)",
  57. )
  58. .option(
  59. "--sandbox-user <name>",
  60. "name for the sandbox user account (default: srt-sandbox)",
  61. )
  62. .option("--force", "replace an existing install with different config")
  63. .action(async (o: Record<string, string | boolean | undefined>) => {
  64. const { installWindowsSandbox, resolveSrtWin, VENDORED_SRT_WIN_EXE } =
  65. await import("./sandbox/windows-sandbox-utils.js");
  66. const range =
  67. typeof o.proxyPortRange === "string"
  68. ? (o.proxyPortRange.split("-").map(Number) as [number, number])
  69. : undefined;
  70. try {
  71. const r = installWindowsSandbox({
  72. sublayerGuid: o.sublayerGuid as string | undefined,
  73. proxyPortRange: range,
  74. sandboxUser: o.sandboxUser as string | undefined,
  75. force: Boolean(o.force),
  76. // Our own CLI opts into the packaged exe explicitly —
  77. // there is no ambient vendor fallback.
  78. srtWin: resolveSrtWin({ path: VENDORED_SRT_WIN_EXE }),
  79. });
  80. if (r.cancelled) {
  81. console.error(
  82. "Install cancelled at the UAC prompt. Nothing changed.",
  83. );
  84. process.exit(2);
  85. }
  86. console.log(
  87. `Installed.\n` +
  88. ` sandbox user: ${r.user.provisioned ? "provisioned" : "MISSING"}` +
  89. (r.user.sid ? ` (${r.user.sid})` : "") +
  90. `\n` +
  91. ` WFP: ${r.wfp.state}, ${r.wfp.filters} filters` +
  92. (r.wfp.portRange
  93. ? `, port range ${r.wfp.portRange[0]}-${r.wfp.portRange[1]}`
  94. : "") +
  95. `\n\n` +
  96. `No logout needed — the WFP filter keys on the dedicated ` +
  97. `\`srt-sandbox\` user's SID, so your network is unaffected.`,
  98. );
  99. } catch (e) {
  100. console.error(`Error: ${(e as Error).message}`);
  101. process.exit(1);
  102. }
  103. });
  104. program
  105. .command("windows-uninstall")
  106. .description(
  107. "Windows: remove WFP filters + the `srt-sandbox` account (one UAC prompt).",
  108. )
  109. .option("--sublayer-guid <guid>", "WFP sublayer GUID")
  110. .action(async (o: Record<string, string | undefined>) => {
  111. const { uninstallWindowsSandbox, resolveSrtWin, VENDORED_SRT_WIN_EXE } =
  112. await import("./sandbox/windows-sandbox-utils.js");
  113. try {
  114. const r = uninstallWindowsSandbox({
  115. sublayerGuid: o.sublayerGuid,
  116. srtWin: resolveSrtWin({ path: VENDORED_SRT_WIN_EXE }),
  117. });
  118. if (r.cancelled) {
  119. console.error("Uninstall cancelled at the UAC prompt.");
  120. process.exit(2);
  121. }
  122. console.log("WFP filters and `srt-sandbox` account removed.");
  123. } catch (e) {
  124. console.error(`Error: ${(e as Error).message}`);
  125. process.exit(1);
  126. }
  127. });
  128. // Default command - run command in sandbox
  129. program
  130. .argument("[command...]", "command to run in the sandbox")
  131. .option("-d, --debug", "enable debug logging")
  132. .option(
  133. "-s, --settings <path>",
  134. "path to config file (default: ~/.srt-settings.json)",
  135. )
  136. .option(
  137. "-c <command>",
  138. "run command string directly (like sh -c), no escaping applied",
  139. )
  140. .option(
  141. "--control-fd <fd>",
  142. "read config updates from file descriptor (JSON lines protocol)",
  143. parseInt,
  144. )
  145. .allowUnknownOption()
  146. .action(
  147. async (
  148. commandArgs: string[],
  149. options: {
  150. debug?: boolean;
  151. settings?: string;
  152. c?: string;
  153. controlFd?: number;
  154. },
  155. ) => {
  156. try {
  157. // Enable debug logging if requested. logForDebugging() reads
  158. // SRT_DEBUG (not DEBUG, to avoid clashing with the npm `debug`
  159. // package and other tools) — keep this in sync with utils/debug.ts.
  160. if (options.debug) {
  161. process.env.SRT_DEBUG = "true";
  162. }
  163. // Load config from file
  164. const configPath = options.settings || getDefaultConfigPath();
  165. let runtimeConfig = loadConfig(configPath);
  166. if (!runtimeConfig) {
  167. // An explicitly requested settings file must load successfully —
  168. // silently falling back to the default config would run the
  169. // command without the restrictions the caller asked for.
  170. if (options.settings) {
  171. console.error(
  172. `Error: Could not load settings from ${configPath} (missing, unreadable, or invalid). ` +
  173. "Refusing to run with the default config.",
  174. );
  175. process.exit(1);
  176. }
  177. logForDebugging(
  178. `No config found at ${configPath}, using default config`,
  179. );
  180. runtimeConfig = getDefaultConfig();
  181. }
  182. // Windows: srtWin.path is required (no ambient vendor
  183. // fallback). When the user's config doesn't set it, this
  184. // CLI opts into the packaged exe explicitly — that's our
  185. // code making the choice, not a library default.
  186. if (
  187. process.platform === "win32" &&
  188. runtimeConfig.windows?.srtWin?.path === undefined
  189. ) {
  190. const { VENDORED_SRT_WIN_EXE } = await import(
  191. "./sandbox/windows-sandbox-utils.js"
  192. );
  193. runtimeConfig = {
  194. ...runtimeConfig,
  195. windows: {
  196. ...runtimeConfig.windows,
  197. srtWin: { path: VENDORED_SRT_WIN_EXE },
  198. },
  199. };
  200. }
  201. // Initialize sandbox with config
  202. logForDebugging("Initializing sandbox...");
  203. await SandboxManager.initialize(runtimeConfig);
  204. // Set up control fd for dynamic config updates if specified
  205. let controlReader: readline.Interface | null = null;
  206. if (options.controlFd !== undefined) {
  207. try {
  208. const controlStream = fs.createReadStream("", {
  209. fd: options.controlFd,
  210. });
  211. controlReader = readline.createInterface({
  212. input: controlStream,
  213. crlfDelay: Infinity,
  214. });
  215. controlReader.on("line", (line) => {
  216. const newConfig = loadConfigFromString(line);
  217. if (newConfig) {
  218. logForDebugging(
  219. `Config updated from control fd: ${JSON.stringify(newConfig)}`,
  220. );
  221. SandboxManager.updateConfig(newConfig);
  222. } else if (line.trim()) {
  223. // Only log non-empty lines that failed to parse
  224. logForDebugging(
  225. `Invalid config on control fd (ignored): ${line}`,
  226. );
  227. }
  228. });
  229. controlReader.on("error", (err) => {
  230. logForDebugging(`Control fd error: ${err.message}`);
  231. });
  232. logForDebugging(
  233. `Listening for config updates on fd ${options.controlFd}`,
  234. );
  235. } catch (err) {
  236. logForDebugging(
  237. `Failed to open control fd ${options.controlFd}: ${err instanceof Error ? err.message : String(err)}`,
  238. );
  239. }
  240. }
  241. // Cleanup control reader on exit
  242. process.on("exit", () => {
  243. controlReader?.close();
  244. });
  245. // Determine command string based on mode
  246. let command: string;
  247. if (options.c) {
  248. // -c mode: use command string directly, no escaping
  249. command = options.c;
  250. logForDebugging(`Command string mode (-c): ${command}`);
  251. } else if (commandArgs.length > 0) {
  252. // Default mode: argv-style invocation. The result is later
  253. // executed via `bash -c <command>`, so each arg must be
  254. // shell-quoted to survive that re-parse — a plain join(' ')
  255. // splits arguments containing whitespace (#157).
  256. command = quote(commandArgs);
  257. logForDebugging(`Original command: ${command}`);
  258. } else {
  259. console.error(
  260. "Error: No command specified. Use -c <command> or provide command arguments.",
  261. );
  262. process.exit(1);
  263. }
  264. logForDebugging(
  265. JSON.stringify(
  266. SandboxManager.getNetworkRestrictionConfig(),
  267. null,
  268. 2,
  269. ),
  270. );
  271. // Wrap the command with sandbox restrictions. On Windows
  272. // the wrapper returns an argv array that MUST be spawned
  273. // with {shell:false} — that's the boundary keeping the
  274. // command bytes off the host shell. On other platforms
  275. // we keep the existing shell-string path.
  276. let child;
  277. if (process.platform === "win32") {
  278. // env carries the proxy vars the sandboxed child must inherit.
  279. const { argv, env } =
  280. await SandboxManager.wrapWithSandboxArgv(command);
  281. child = spawn(argv[0], argv.slice(1), {
  282. shell: false,
  283. stdio: "inherit",
  284. env,
  285. });
  286. } else {
  287. const sandboxedCommand =
  288. await SandboxManager.wrapWithSandbox(command);
  289. child = spawn(sandboxedCommand, {
  290. shell: true,
  291. stdio: "inherit",
  292. });
  293. }
  294. // Handle process exit
  295. child.on("exit", (code, signal) => {
  296. // Clean up bwrap mount point artifacts before exiting.
  297. // On Linux, bwrap creates empty files on the host when protecting
  298. // non-existent deny paths. This removes them.
  299. SandboxManager.cleanupAfterCommand();
  300. if (signal) {
  301. if (signal === "SIGINT" || signal === "SIGTERM") {
  302. process.exit(0);
  303. } else {
  304. console.error(`Process killed by signal: ${signal}`);
  305. process.exit(1);
  306. }
  307. }
  308. process.exit(code ?? 0);
  309. });
  310. child.on("error", (error) => {
  311. console.error(`Failed to execute command: ${error.message}`);
  312. process.exit(1);
  313. });
  314. // Handle cleanup on interrupt
  315. process.on("SIGINT", () => {
  316. child.kill("SIGINT");
  317. });
  318. process.on("SIGTERM", () => {
  319. child.kill("SIGTERM");
  320. });
  321. } catch (error) {
  322. console.error(
  323. `Error: ${error instanceof Error ? error.message : String(error)}`,
  324. );
  325. process.exit(1);
  326. }
  327. },
  328. );
  329. program.parse();
  330. }
  331. main().catch((error) => {
  332. console.error("Fatal error:", error);
  333. process.exit(1);
  334. });