-
|
I have an instance of TOR running on 127.0.0.1:9150. |
Beta Was this translation helpful? Give feedback.
Answered by
koistya
Jan 21, 2022
Replies: 1 comment
-
Requirements:
npm install got socks-proxy-agent
# Docker Desktop must be installed & running// tor-proxy-example.mjs
import got from "got";
import { SocksProxyAgent } from "socks-proxy-agent";
import { spawn } from "node:child_process";
const TOR_IMAGE = "osminogin/tor-simple:latest"; // or another maintained Tor proxy image
const TOR_PORT = 9050;
const TOR_ADDR = `socks5h://127.0.0.1:${TOR_PORT}`;
function startTorContainer() {
// Pull latest image & run in foreground so we can watch logs
const args = [
"run",
"--rm",
"-i",
"-a",
"stdout",
"-p",
`127.0.0.1:${TOR_PORT}:${TOR_PORT}/tcp`,
TOR_IMAGE,
];
const ps = spawn("docker", args, { stdio: ["ignore", "pipe", "inherit"] });
ps.on("error", (err) => {
console.error("Failed to start Docker:", err);
});
return ps;
}
function waitForTorReady(proc, { timeoutMs = 30_000 } = {}) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error("Timed out waiting for Tor to bootstrap."));
}, timeoutMs);
proc.stdout.on("data", (buf) => {
const line = buf.toString();
// Forward logs to stderr for visibility
process.stderr.write(line);
// Tor prints this when fully ready
if (line.includes("Bootstrapped 100%")) {
clearTimeout(timer);
resolve();
}
});
proc.on("exit", (code) => {
clearTimeout(timer);
reject(new Error(`Tor container exited early with code ${code}`));
});
});
}
async function main() {
const tor = startTorContainer();
const stop = () => {
try {
tor.kill("SIGINT");
} catch {}
};
process.on("SIGINT", stop);
process.on("SIGTERM", stop);
process.on("exit", stop);
try {
await waitForTorReady(tor);
const socksAgent = new SocksProxyAgent(TOR_ADDR);
const client = got.extend({
agent: {
http: socksAgent,
https: socksAgent,
},
timeout: { request: 15_000 },
http2: false, // keep it simple; enable if your target supports it
});
// Example: check outbound IP (should be a Tor exit node)
const { ip } = await client.get("https://api.ipify.org?format=json").json();
console.log("Client IP via Tor:", ip);
} finally {
stop();
}
}
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});Source: https://dev.to/koistya/run-node-js-scripts-from-under-a-tor-http-proxy-b1 |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
sindresorhus
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requirements:
got,socks-proxy-agentnpm install got socks-proxy-agent # Docker Desktop must be installed & running