check if vpn is enabled in javascript

To check if a VPN is enabled in Javascript, we can use the WebRTC API, which allows websites to access network information such as the IP address and network interfaces.

The idea behind this method is to create a test where we create a connection to a server and check if the connection IP matches the user's public IP. If the IP is different, it means that some form of VPN or proxy is active.

Here's an example code snippet:

index.tsx
const checkVPN = async () => {
  const url = 'https://api.ipify.org/';
  const response = await fetch(url);
  const text = await response.text();
  const ip = text.trim();
  const rtcConfig = { iceServers: [ { urls: "stun:stun.l.google.com:19302" } ] };
  const pc = new RTCPeerConnection(rtcConfig);
  try {
    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);
    const { candidate } = pc.localDescription;
    const isVPN = candidate
      .split('\n')
      .find((line) => line.includes('srflx'))
      .split(' ')[4] !== ip;
    return isVPN;
  } catch (err) {
    console.error(err);
  } finally {
    pc.close();
  }
}

const isVPNEnabled = await checkVPN();
console.log(`Is VPN enabled? ${isVPNEnabled}`);
745 chars
26 lines

In this example, we are first obtaining the user's public IP address using a free API provided by ipify. We then create an RTCPeerConnection object, which is used to create a test connection to a STUN server.

We then create a local offer object and set it as the local description for the RTCPeerConnection. We then obtain the candidate property from the local description, which contains a list of network interfaces and their respective IP addresses.

We then check if candidate list has an entry with type srflx which represents the public IP obtained by the STUN server. If this IP is different from the user's public IP, we can conclude that a VPN is enabled.

Note: It is important to handle errors and close the RTCPeerConnection object in order to prevent resource leaks. Also, keep in mind that this method is not foolproof and may not work in some scenarios, such as when the user is accessing the site using a VPN and the VPN provider uses a NAT.

gistlibby LogSnag