open-browser.ts 933 B

123456789101112131415161718192021222324
  1. import { spawn } from "node:child_process";
  2. /**
  3. * Open a URL or file in the platform browser/default handler.
  4. *
  5. * This intentionally never invokes a shell. On Windows, do not use
  6. * `cmd /c start`: cmd.exe re-parses metacharacters (&, |, ^, ...) before
  7. * `start` runs, which would make attacker-controlled URLs injectable.
  8. */
  9. export function openBrowser(target: string): void {
  10. const [cmd, args]: [string, string[]] =
  11. process.platform === "darwin"
  12. ? ["open", [target]]
  13. : process.platform === "win32"
  14. ? ["rundll32", ["url.dll,FileProtocolHandler", target]]
  15. : ["xdg-open", [target]];
  16. // spawn reports launcher failures (for example, missing xdg-open) via an
  17. // error event. Browser launch is best-effort: callers still present the target
  18. // to the user, so keep the launcher failure from becoming a process crash.
  19. spawn(cmd, args, { stdio: "ignore", detached: true })
  20. .on("error", () => {})
  21. .unref();
  22. }