DEV Community

loading...
Cover image for Run Node.js scripts from under a TOR / HTTP proxy

Run Node.js scripts from under a TOR / HTTP proxy

koistya profile image Konstantin Tarkus Updated on ・1 min read

Requirements:

$ npm install got tunnel cross-spawn --save
Enter fullscreen mode Exit fullscreen mode
const got = require("got");
const tunnel = require("tunnel");
const spawn = require("cross-spawn");

/**
 * Launch a TOR proxy via Docker
 * @see https://hub.docker.com/r/dperson/torproxy/
 * @type {import("child_process").ChildProcess}
 */
const proxy = spawn(
  "docker",
  [
    ...["run", "--rm", "-i", "-a", "stderr"],
    ...["-p", "8118:8118", "dperson/torproxy", "-e"],
  ],
  { stdio: ["inherit", "inherit", "pipe"] },
);

/**
 * Once TOR was fully bootstrapped, execute the rest of the script.
 */
proxy.stderr.on("data", (data) => {
  process.stderr.write(data);
  if (data.toString().includes("Bootstrapped 100%")) {
    run().finally(() => proxy.kill("SIGINT"));
  }
});

/**
 * Configure an HTTP client using TOR proxy
 * @type {import("got").Got}
 */
const client = got.extend({
  agent: {
    https: tunnel.httpsOverHttp({
      proxy: { host: "localhost", port: 8118 },
    }),
  },
});

async function run() {
  const body = await client.get("http://jsonip.com/").json();
  console.log("Client IP:", body.ip);

  // TODO: Do some stuff from under the proxy
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app