Quais sites você consegue acessar através dos seus proxies e configurações de VPN? Confira nos perfis do Octo Browser


Alex Phillips
Customer Service Specialist
O Octo Browser é um navegador antidetecção para trabalhar com várias contas: cada perfil tem sua própria impressão digital e configurações de conexão. A conexão determina quais sites um perfil pode acessar: o mesmo site pode funcionar por meio de um proxy, exibir uma verificação "Você é humano?" por meio de outro e não responder por meio de um terceiro. Verificar tudo manualmente leva muito tempo: testar cinco proxies em cinquenta sites pode levar uma noite inteira. Neste artigo, mostraremos como criar um script em Node.js e Puppeteer que percorre sua lista de sites usando cada um dos seus proxies e VPNs em perfis do Octo Browser e, em seguida, relata se cada site está acessível e, se não estiver, o motivo.
Índice
Mantenha o anonimato on-line com Octo Browser. Sua verdadeira impressão digital não pode ser rastreada.
Gostaria de experimentar o Octo Browser com desconto?
Use o código promocional OCTOBLOG e ganhe 30% de desconto em qualquer assinatura. Esta oferta é válida somente para novos usuários.
O que o script pode fazer
Você fornece ao script três listas: sites, proxies e configurações de VPN. Para cada proxy e cada VPN, ele cria um perfil separado no Octo Browser, o inicializa, abre os sites um a um e registra os resultados. No final, você obtém uma tabela com uma linha por site e uma coluna por conexão, seguida de um resumo com os motivos de eventuais falhas.
Site GB_203.0.113.9 DE_198.51.100.7 google.com AVAILABLE AVAILABLE wikipedia.org AVAILABLE AVAILABLE amazon.com UNAVAILABLE AVAILABLE ebay.com AVAILABLE AVAILABLE GB_203.0.113.9: 3 AVAILABLE, 1 UNAVAILABLE (1 challenge) DE_198.51.100.7: 4 AVAILABLE, 0 UNAVAILABLE
Site GB_203.0.113.9 DE_198.51.100.7 google.com AVAILABLE AVAILABLE wikipedia.org AVAILABLE AVAILABLE amazon.com UNAVAILABLE AVAILABLE ebay.com AVAILABLE AVAILABLE GB_203.0.113.9: 3 AVAILABLE, 1 UNAVAILABLE (1 challenge) DE_198.51.100.7: 4 AVAILABLE, 0 UNAVAILABLE
Por exemplo, o script pode:
Verificar proxies e VPNs em uma única execução. Ele lê proxies do arquivo
proxies.txte VPNs de arquivos de configuração do WireGuard na pastaconfig. Ele suporta os mesmos protocolos e formatos de linha que a importação em massa de proxies no Octo Browser, incluindo endereços IPv6.Identificar o motivo. Se um site não carregar, o script informa o porquê: o próprio proxy não conseguiu estabelecer uma conexão, o site bloqueou o endereço IP, exigiu uma verificação do tipo "Você é humano?", está indisponível no país de conexão ou simplesmente não respondeu.
Diferenciar um bloqueio de uma falha aleatória. Se a conexão cair ou o site não responder, o script tenta novamente. Se o site exibir uma verificação do tipo "Você é humano?", o script aguarda para ver se ela se resolve sozinha. Se a página carregar normalmente, a mera presença de proteção antibot não é tratada como uma falha.
Executar verificações em paralelo. Ele verifica até dez conexões ao mesmo tempo, e o resultado para cada site é exibido assim que estiver pronto.
Nomear perfis por país e IP. Um perfil recebe um nome como
DE_198.51.100.7. Uma conexão inoperante é marcada comoDEAD, enquanto um perfil que falha ao iniciar por outro motivo é marcado comoERROR.Salvar um relatório. Ele cria um arquivo Excel com um resumo para cada conexão. Os sites acessíveis são destacados em verde e os inacessíveis em vermelho. O script também salva uma captura de tela de cada página com falha para que você possa ver exatamente o que o site exibiu.
Proteger credenciais de acesso. Senhas de proxy, chaves de VPN e o token não são incluídos na saída do console ou no relatório. Os perfis também são interrompidos corretamente, mesmo se você interromper a verificação.
O script apenas observa. Ele não resolve CAPTCHAs, não clica em botões nem digita nada. Tenha o seguinte em mente:
Um resultado
challengenão significa que você foi banido. O site está solicitando que você confirme que é humano, e geralmente é possível abri-lo manualmente no perfil.O script verifica apenas a URL exata que você fornecer. O carregamento com sucesso da página inicial não significa que o login na conta ou a finalização da compra funcionarão. Adicione a URL de uma seção específica à lista se for isso o que você precisa testar.
O resultado é preciso no momento da verificação. Um proxy rotativo pode usar um IP diferente um minuto depois, portanto, os resultados podem mudar.
Cada conexão obtém um novo perfil, e novos proxies são adicionados à lista de proxies do Octo. Ambos consomem os limites da sua assinatura. A Etapa 3 explica como evitar deixá-los salvos após a verificação.
Por que não usar o curl?
Você pode verificar um site por meio de um proxy com um único comando curl, mas ele responde a uma pergunta diferente: a solicitação alcançou o servidor? Ele não pode dizer se o site abrirá em um perfil de navegador.
O
curlnão é um navegador, e os sites conseguem perceber. Os sistemas de segurança o identificam pela sua impressão digital TLS e pelo conjunto de cabeçalhos, podendo rejeitar o próprio clientecurlem vez do seu proxy.O
curlnão executa JavaScript. Um navegador pode passar pela verificação "Só um momento" automaticamente em alguns segundos, enquanto ocurlfica travado nela.O
curlvisualiza o código de resposta, não a página. Uma página de restrição geográfica, um CAPTCHA ou uma recusa com código de status 200 parecem, para ele, um site aberto com sucesso.O
curlnão pode verificar VPNs. Ele pode se conectar por meio de proxies HTTP e SOCKS, mas você não pode passar uma configuração do WireGuard para ele.
O curl ainda tem suas utilidades: é uma maneira rápida de descobrir se um proxy está funcionando e qual é o seu endereço IP. Apenas o navegador dentro do perfil pode dizer se um site abrirá naquele perfil.
O que você vai precisar
Octo Browser com uma assinatura Base ou superior, o que oferece acesso à API.
Node.js versão 22.12 ou posterior.
Uma lista de proxies ou arquivos de configuração de VPN do WireGuard.
Etapa 1. Instalar o Node.js
Baixe o Node.js em nodejs.org e instale-o usando as configurações padrão. Em seguida, abra o PowerShell: pressione Win+R, digite PowerShell e pressione Enter. Verifique a instalação:
node --version
node --version
O comando deve exibir a versão 22.12 ou posterior. Isso é exigido pelo Puppeteer 25, que foi usado para testar o script. Se o PowerShell indicar que o comando não foi encontrado, feche o PowerShell, reabra-o e tente novamente.
Etapa 2. Preparar uma pasta
Escolha uma pasta para o script, por exemplo D:\proxy_check, crie-a e navegue até ela no PowerShell. Crie uma pasta config dentro dela para suas configurações de VPN:
cd D:\ mkdir proxy_check cd proxy_check mkdir config
cd D:\ mkdir proxy_check cd proxy_check mkdir config
Instale o Puppeteer. A versão é especificada explicitamente porque esta é a versão com a qual o script foi testado:
npm install puppeteer-core@25
npm install puppeteer-core@25
Etapa 3. O script site_access.mjs
No PowerShell, com proxy_check como a pasta atual, execute notepad site_access.mjs. Quando for perguntado se deseja criar um novo arquivo, clique em Sim, cole todo o código e salve pressionando Ctrl+S. Criar o arquivo a partir da linha de comando ajuda a evitar problemas de extensão de arquivo: se você o criar pelo menu do Bloco de Notas, ele poderá ser salvo como site_access.mjs.txt, e o script não será executado. Crie os outros arquivos nas etapas a seguir da mesma forma.
As configurações estão listadas no início do código, cada uma com um comentário explicativo. Uma configuração é obrigatória: cole seu token de API em API_TOKEN. Você pode encontrá-lo no Octo Browser, na aba API tokens nas configurações da sua conta principal.
const API_TOKEN = "your_token";
const API_TOKEN = "your_token";
Você pode manter as outras configurações com seus valores padrão. No entanto, preste atenção a estes dois parâmetros:
KEEP_PROFILES = false envia os perfis para a lixeira após a verificação.
SAVE_PROXIES = false impede que os proxies testados sejam adicionados à lista de proxies do Octo. Com essas definições, os perfis e proxies criados para o teste não vão sobrecarregar suas listas de trabalho no navegador. Isso é útil se o seu limite de perfis for baixo.
Aqui está uma descrição detalhada das configurações:
Configuração | O que ela controla |
|---|---|
| Token de API do Octo Browser |
| Porta da API local do cliente Octo, padrão 58888. Você pode encontrá-la nas configurações, na aba Adicional. |
| Sistema operacional do perfil: |
|
|
| Número de conexões verificadas simultaneamente, de 1 a 10. |
| Proxies especificados diretamente no código, além daqueles no arquivo. |
| Arquivo contendo proxies; padrão |
| Tipo usado para linhas de proxy que não especificam um. |
|
|
| Pasta contendo as configurações de VPN; padrão |
| Protocolo usado pelos arquivos de configuração e o modo usado para identificá-los na API do Octo. Os padrões são |
| Arquivo contendo a lista de sites; padrão |
|
|
| Se deve salvar capturas de tela das páginas com falha. |
| Quantos segundos aguardar para um site responder, para a verificação "Você é humano?" sumir e para o conteúdo da página aparecer. |
Aqui está o código:
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { crc32 } from "node:zlib"; const API_TOKEN = ""; // paste your Octo API token between the quotes const LOCAL_PORT = 58888; // port of the local API of the Octo client: Octo client, Settings, Additional const OS = "win"; // OS of the profiles: win, mac or android const HEADLESS = false; // true: profiles run without a window; false: with a window const PARALLEL = 5; // connections checked at the same time, from 1 to 10 const PROXIES = [ // one proxy per line, for example "socks5://login:password@proxy.example.com:10000", ]; const PROXY_FILE = "proxies.txt"; // a file next to the script with one proxy per line, read together with PROXIES const DEFAULT_TYPE = "socks5"; // type for proxy lines without one: http, https, socks5 or ssh const SAVE_PROXIES = true; // true: new proxies are saved to Octo's proxy list; false: a proxy lives only in its profile const VPN_FOLDER = "config"; // folder with WireGuard configs: one VPN profile per file const VPN_PROTOCOL = "wireguard"; // protocol of the configs, as the Octo API names it const VPN_SYN_MODE = "profile_based"; // syn_mode of the VPN, as the Octo API names it const SITES_FILE = "sites.txt"; // sites to check: one per line, # starts a comment const KEEP_PROFILES = true; // false: every profile goes to the trash after its check const SCREENSHOTS = true; // true: save a screenshot of every page that did not open const PAGE_TIMEOUT = 45; // seconds a site gets to answer const CHECK_WAIT = 15; // seconds a "checking your browser" page gets to clear by itself const EMPTY_WAIT = 10; // seconds a blank page gets to show something const HERE = dirname(fileURLToPath(import.meta.url)); const CLOUD = "https://app.octobrowser.net/api/v2/automation"; const LOCAL = `http://localhost:${LOCAL_PORT}/api`; const OS_NAMES = { win: "Windows", mac: "macOS", android: "Android" }; const PROXY_TYPES = ["http", "https", "socks5", "ssh"]; const SHORT_PAGE = 2500; const PAGE_LIMITS = { text: 200000, html: 400000, title: 2000 }; const RETRY_TIMEOUT = 20; const PROXY_FAILURES = 3; const BROWSER_TIMEOUT = 30; const RETRY = new Set(["timeout", "connection_reset", "dns_error", "proxy_refused", "unreachable"]); const sleep = (ms) => new Promise((done) => setTimeout(done, ms)); const anyOf = (phrases) => new RegExp(phrases.join("|")); const secrets = new Set(); const hide = (value) => String(value || "").length >= 4 && secrets.add(String(value)); const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " "); const redact = (text) => [...secrets] .sort((a, b) => b.length - a.length) .reduce((clean, secret) => clean.split(secret).join("***"), printable(text)) .replace(/\/\/[^\s/@]+@/g, "//***@"); const firstLine = (text) => redact(String(text).split("\n")[0]).slice(0, 200); const fileName = (text) => String(text).replace(/[^\w.-]+/g, "_"); const localStamp = () => new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace(/[:T]/g, "-"); const readText = (file) => readFileSync(file, "utf8").replace(/^\uFEFF/, ""); const fail = (message) => { console.error(message); process.exit(1); }; const GEO = anyOf([ "(not|isn.t|aren.t) (currently |yet )?(available|accessible|offered|permitted|allowed|supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "(unavailable|blocked|restricted|prohibited|banned|not supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "not available in this (country|region)", "access from your (country|region|location) (is|has been) (blocked|restricted|denied|disabled)", "(from|in) a restricted (country|territory|jurisdiction|region|location)", "your (country|region|location|territory) is (restricted|not supported|blocked|not allowed)", "(do|does) not accept (players|customers|users|visitors|residents) from", "(accessing|visiting|located|you are|you.re|you appear)[^.]{0,60}outside (of )?(the )?(uk|u[.]k[.]?|united kingdom|us|u[.]s[.]?|usa|united states|eu)([ .,!]|$)", "country (that |where )?you are (located in|in|accessing from|visiting from)[^.]{0,30}not (supported|allowed|available)", "(do not|don.t|cannot|can.t) allow access (in|from) your (current )?(country|region|location)", "(unavailable|not available|cannot be accessed|can.t be accessed)[^.]{0,120}european (economic area|union)", "unavailable (due to|for) legal reasons", "configured to block access from your country", "недоступ[а-яё]* (в|на территории|для) ваш[а-яё]* (стран|регион)", "nicht in (deinem|ihrem) land", "pas disponible dans votre (pays|région)", "no está disponible en (tu|su) (país|región)", "não está disponível (no|em) seu país", ]); const PROXY_SEEN = anyOf([ "(vpn|proxy|proxies|anonymizer|unblocker)[^.]{0,60}(detected|not (allowed|permitted|supported))", "(appear|seem)s? to be using (a |an )?(vpn|proxy|unblocker|anonymizer)", "(detected|blocked) (a |an |your )?(vpn|proxy|anonymous proxy)", "(disable|turn off|switch off) (your |the |any )?(vpn|proxy)", ]); const CHECKS = anyOf([ "checking (your browser|if the site connection is secure)", "verif(y|ying) (that )?you are (a )?human", "verify (that )?you are not a (robot|bot)", "(prove|confirm) (that )?you are (a )?human", "are you (a )?(human|robot)", "(complete|pass|performing) (a |the )?(security check|captcha)", "security checkpoint", "enable javascript and cookies to continue", "press (&|and) hold", "unusual (traffic|activity)", "suspicious (activity|traffic)", "automated (access|requests|queries|traffic)", "подтвердите, что вы не робот", "проверка браузера", ]); const REFUSALS = anyOf([ "access (to (this|the) (site|page|website|resource|service) )?(is |has been |was )?(denied|forbidden|blocked|restricted)", "you (have been|are|were) (blocked|banned)", "your (ip|ip address|request|access|connection) (has been|was|is) (temporarily )?(blocked|banned|denied|blacklisted|rejected|limited)", "request (blocked|rejected|denied)", "blocked (by|due to) [^.]{0,40}(security|firewall|policy|administrator|rules)", "403 forbidden", "error 403", "you (don.t|do not) have permission to (access|view)", "not authori[sz]ed to (access|view)", "доступ (к (сайту|ресурсу|странице) )?(запрещ|ограничен|заблокирован|закрыт)", "ваш ip[^.]{0,30}(заблокирован|забанен)", ]); const CLOUDFLARE_ERRORS = { 1005: "the network of this IP is banned", 1006: "this IP is banned", 1007: "this IP is banned", 1008: "this IP is banned", 1010: "the browser signature is banned", 1012: "access denied", 1020: "access denied by a firewall rule", }; function guardOf(header, html) { const server = header("server"); if (server.includes("cloudflare") || header("cf-ray")) return "Cloudflare "; if (server.includes("akamai")) return "Akamai "; if (server.includes("ddos-guard") || html.includes("ddos-guard")) return "DDoS-Guard "; return ""; } function cloudflareError(guard, html, short, words) { const onCloudflare = guard === "Cloudflare " || html.includes("cloudflare"); if (!short || !onCloudflare) return ""; return (words.match(/error(?: code)?:? ?(1\d{3})(?!\d)/) || [])[1] || ""; } function view(look) { const text = String(look.text || ""); const title = String(look.title || "").toLowerCase(); const heading = String(look.heading || "").toLowerCase(); const html = String(look.html || "").toLowerCase(); const header = (name) => String(look.headers?.[name] ?? "").toLowerCase(); const short = text.trim().length < SHORT_PAGE; const words = `${title} | ${heading} | ${text.toLowerCase()}`; const guard = guardOf(header, html); return { status: Number(look.status) || 0, url: String(look.url || "").toLowerCase(), html, title, top: `${title} | ${heading}`, words, short, empty: !text.trim(), refusal: short || Number(look.status) >= 400, header, guard, cloudflare: cloudflareError(guard, html, short, words), }; } const said = (page, phrases) => (page.top.match(phrases) || (page.short && page.words.match(phrases)) || [""])[0]; const quoted = (phrase) => (phrase ? `, the page says: "${phrase}"` : ""); const RULES = [ { verdict: "challenge", detail: "Cloudflare challenge", when: (page) => page.header("cf-mitigated").includes("challenge"), }, { verdict: "blocked", detail: (page, state) => `Cloudflare refused (cf-mitigated: ${state})`, when: (page) => page.header("cf-mitigated"), }, { verdict: "blocked", detail: "AWS WAF refused", when: (page) => page.header("x-amzn-waf-action") === "block", }, { verdict: "challenge", detail: (page, action) => `AWS WAF ${action}`, when: (page) => page.header("x-amzn-waf-action"), }, { verdict: "blocked", detail: "Sucuri firewall refused", when: (page) => page.header("x-sucuri-block") || (page.refusal && page.words.includes("sucuri website firewall")), }, { verdict: "challenge", detail: "Kasada check", when: (page) => (page.status >= 400 && (page.header("x-kpsdk-ct") || page.header("x-kpsdk-cd"))) || (page.short && page.html.includes("kpsdk")), }, { verdict: "geo_blocked", detail: "Cloudflare 1009: the site bans the country of this IP", when: (page) => page.cloudflare === "1009" || (page.refusal && page.words.includes("banned the country or region")), }, { verdict: "geo_blocked", detail: "HTTP 451: unavailable for legal reasons in this country", when: (page) => page.status === 451, }, { verdict: "geo_blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, GEO), }, { verdict: "rate_limited", detail: "Cloudflare 1015: too many requests from this IP", when: (page) => page.cloudflare === "1015", }, { verdict: "blocked", detail: (page, meaning) => `Cloudflare ${page.cloudflare}: ${meaning}`, when: (page) => CLOUDFLARE_ERRORS[page.cloudflare], }, { verdict: "blocked", detail: "Cloudflare: 'you have been blocked'", when: (page) => page.short && /sorry, you have been blocked|attention required! \| cloudflare/.test(page.words), }, { verdict: "challenge", detail: "Cloudflare 'Just a moment' check", when: (page) => page.refusal && (page.title.includes("just a moment") || page.html.includes("cf_chl_opt")), }, { verdict: "challenge", detail: "Cloudflare Turnstile check", when: (page) => page.short && page.html.includes("cf-turnstile"), }, { verdict: "blocked", detail: "Akamai: Access Denied", when: (page) => page.refusal && (page.html.includes("errors.edgesuite.net") || page.html.includes("reference #") || /reference #\d+\.[0-9a-f]{6,}/.test(page.words)), }, { verdict: "challenge", detail: "Akamai check", when: (page) => page.short && (page.html.includes("_sec/cp_challenge") || page.html.includes("sec-if-cpt")), }, { verdict: "blocked", detail: "DataDome refused", when: (page) => page.refusal && page.html.includes("captcha-delivery.com") && /temporarily restricted|you have been blocked|access (is |was )?(denied|blocked)/.test(page.words), }, { verdict: "challenge", detail: "DataDome captcha", when: (page) => page.refusal && page.html.includes("captcha-delivery.com"), }, { verdict: "challenge", detail: "PerimeterX (HUMAN) 'Press & Hold'", when: (page) => (page.refusal && page.html.includes("px-captcha")) || page.title.includes("access to this page has been denied") || (page.short && page.status >= 400 && /_pxappid|px-cloud\.net|px-cdn\.net/.test(page.html)), }, { verdict: "blocked", detail: "Imperva (Incapsula) refused", when: (page) => page.refusal && /incapsula incident id|request unsuccessful\. incapsula|this request was blocked by (our|the) security service/.test( page.words, ), }, { verdict: "challenge", detail: "Imperva check", when: (page) => (page.short && page.words.includes("pardon our interruption")) || (page.empty && page.html.includes("_incapsula_resource")), }, { verdict: "blocked", detail: "F5 BIG-IP refused", when: (page) => page.refusal && page.words.includes("the requested url was rejected"), }, { verdict: "blocked", detail: "AWS CloudFront refused", when: (page) => page.status === 403 && page.short && /request blocked|the request could not be satisfied/.test(page.words), }, { verdict: "challenge", detail: "AWS WAF check", when: (page) => page.short && /token\.awswaf\.com|awswafintegration/.test(page.html), }, { verdict: "challenge", detail: "Radware check", when: (page) => page.url.includes("perfdrive.com") || (page.short && page.html.includes("perfdrive.com")), }, { verdict: "challenge", detail: "Vercel security checkpoint", when: (page) => page.title.includes("vercel security checkpoint"), }, { verdict: "challenge", detail: "SiteGround captcha", when: (page) => page.url.includes("/.well-known/sgcaptcha"), }, { verdict: "blocked", detail: "Wordfence refused", when: (page) => page.short && /your access to this site has been limited|generated by wordfence/.test(page.words), }, { verdict: "blocked", detail: "the site blocked the request by its network policy", when: (page) => page.refusal && page.words.includes("blocked due to a network policy"), }, { verdict: "challenge", detail: "Google 'unusual traffic' check", when: (page) => (page.url.includes("google.") && page.url.includes("/sorry/")) || page.words.includes("our systems have detected unusual traffic"), }, { verdict: "challenge", detail: "Amazon captcha", when: (page) => page.refusal && /enter the characters you see below|to discuss automated access to amazon data/.test(page.words), }, { verdict: "challenge", detail: "captcha page", when: (page) => page.short && /recaptcha|hcaptcha|h-captcha|geetest|funcaptcha|arkoselabs/.test(page.html) && /captcha|robot|human|verify|security/.test(page.words), }, { verdict: "blocked", detail: (page, phrase) => `the site sees a proxy or VPN: "${phrase}"`, when: (page) => said(page, PROXY_SEEN), }, { verdict: "challenge", detail: (page, phrase) => `${page.guard}check page: "${phrase}"`, when: (page) => said(page, CHECKS), }, { verdict: "proxy_error", detail: "HTTP 407: the proxy wants another login or password", when: (page) => page.status === 407, }, { verdict: "rate_limited", detail: "HTTP 429: too many requests from this IP", when: (page) => page.status === 429, }, { verdict: "blocked", detail: (page) => `${page.guard}HTTP ${page.status}${quoted(said(page, REFUSALS))}`, when: (page) => [401, 403, 406].includes(page.status), }, { verdict: "blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, REFUSALS), }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: Cloudflare could not reach the site's own server`, when: (page) => page.status >= 520 && page.status <= 527, }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: the site itself fails`, when: (page) => page.status >= 500, }, { verdict: "http_error", detail: (page) => `HTTP ${page.status}`, when: (page) => page.status >= 400, }, ]; export function classify(look) { const page = view(look); for (const rule of RULES) { const match = rule.when(page); if (match) { return { verdict: rule.verdict, detail: typeof rule.detail === "function" ? rule.detail(page, match) : rule.detail, }; } } return { verdict: "ok", detail: `HTTP ${page.status || "?"}` }; } const NETWORK_ERRORS = [ { verdict: "proxy_error", codes: /ERR_SOCKS5_AUTH|ERR_SOCKS_AUTH|ERR_PROXY_AUTH_REQUESTED/, detail: "the proxy rejected its login or password: it may have expired or run out of traffic", }, { verdict: "proxy_error", codes: /ERR_PROXY_CONNECTION_FAILED|ERR_PROXY_AUTH|ERR_NO_SUPPORTED_PROXIES|ERR_PROXY_CERTIFICATE|ERR_MANDATORY_PROXY/, detail: "the proxy itself does not work", }, { verdict: "proxy_refused", codes: /ERR_TUNNEL_CONNECTION_FAILED|ERR_SOCKS_CONNECTION/, detail: "the proxy did not open a connection to this site, its provider may block the site", }, { verdict: "timeout", codes: /ERR_TIMED_OUT|ERR_CONNECTION_TIMED_OUT/, detail: "the site did not answer in time", }, { verdict: "connection_reset", codes: /ERR_CONNECTION_RESET|ERR_CONNECTION_CLOSED|ERR_CONNECTION_ABORTED|ERR_EMPTY_RESPONSE|ERR_SOCKET_NOT_CONNECTED/, detail: "the connection was cut before an answer came", }, { verdict: "connection_reset", codes: /ERR_HTTP2_PROTOCOL_ERROR|ERR_QUIC_PROTOCOL_ERROR/, detail: "the site cut the connection, the way some protection services refuse a visitor", }, { verdict: "connection_refused", codes: /ERR_CONNECTION_REFUSED/, detail: "the site refused the connection", }, { verdict: "dns_error", codes: /ERR_NAME_NOT_RESOLVED|ERR_NAME_RESOLUTION_FAILED|ERR_DNS/, detail: "the address of the site was not found", }, { verdict: "ssl_error", codes: /ERR_CERT_COMMON_NAME_INVALID/, detail: "the site's certificate is issued for another address", }, { verdict: "ssl_error", codes: /ERR_CERT_DATE_INVALID/, detail: "the site's certificate has expired or is not valid yet", }, { verdict: "ssl_error", codes: /ERR_SSL|ERR_CERT|ERR_BAD_SSL|ERR_TLS/, detail: "the secure connection failed, something on the way may replace the site's certificate", }, { verdict: "redirect_loop", codes: /ERR_TOO_MANY_REDIRECTS/, detail: "the site redirects in a circle", }, { verdict: "blocked", codes: /ERR_BLOCKED_BY/, detail: "the request was blocked", }, ]; export function networkError(message, timeout = PAGE_TIMEOUT) { const code = (String(message).match(/(?:net::)?\b(ERR_[A-Z0-9_]+)/) || [])[1]; if (!code) { return /timeout/i.test(message) ? { verdict: "timeout", detail: `no answer in ${timeout} s` } : { verdict: "unreachable", detail: firstLine(message) }; } const known = NETWORK_ERRORS.find((entry) => entry.codes.test(code)); return known ? { verdict: known.verdict, detail: `${code}: ${known.detail}` } : { verdict: "unreachable", detail: code }; } let token = ""; let spent = 0; let limits = null; const running = new Set(); const answerOf = async (response) => ({ status: response.status, ok: response.ok, data: await response.json().catch(() => ({})), }); async function cloud(method, path, body) { for (let attempt = 0; ; attempt++) { spent += 1; const response = await fetch(CLOUD + path, { method, headers: { "X-Octo-Api-Token": token, "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(120000), }); if (response.status === 429 && attempt < 5) { const wait = Number(response.headers.get("retry-after")) || 5; if (wait > 60) throw new Error(`Octo's rate limit is used up for ${wait} s, run the script again later`); await sleep(wait * 1000); continue; } const minute = response.headers.get("x-ratelimit-remaining"); const hour = response.headers.get("x-ratelimit-remaining-hour"); if (minute !== null && hour !== null) { limits = { minute, hour, minuteLimit: response.headers.get("x-ratelimit-limit"), hourLimit: response.headers.get("x-ratelimit-limit-hour"), }; if (Number(minute) < 5) await sleep(5000); } return answerOf(response); } } async function local(path, body) { spent += path === "/profiles/active" ? 0 : 1; const response = await fetch(LOCAL + path, { method: body ? "POST" : "GET", headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(180000), }); return answerOf(response); } async function stopProfile(uuid) { await local("/profiles/stop", { uuid }).catch(() => {}); running.delete(uuid); } process.on("SIGINT", async () => { console.log(`\nStopping ${running.size} running profile(s)...`); await Promise.all([...running].map(stopProfile)); process.exit(130); }); const splitOutsideBrackets = (text) => text.split(/:(?![^[]*\])/); const isPort = (text) => /^\d{1,5}$/.test(text || "") && Number(text) >= 1 && Number(text) <= 65535; const isAddress = (text) => /^\[.+\]$/.test(text) || text.includes(".") || text === "localhost"; export function parseProxy(line, defaultType = DEFAULT_TYPE) { const scheme = line.match(/^([a-z0-9]+):\/\//i); const type = scheme ? scheme[1].toLowerCase() : defaultType; const rest = scheme ? line.slice(scheme[0].length) : line; let host, port, login, secret; if (rest.includes("@")) { const at = rest.lastIndexOf("@"); [login, ...secret] = rest.slice(0, at).split(":"); [host, port] = splitOutsideBrackets(rest.slice(at + 1)); } else { const parts = splitOutsideBrackets(rest); const addressFirst = parts.length <= 2 || (isPort(parts[1]) && (isAddress(parts[0]) || !isPort(parts.at(-1)))); if (addressFirst) { [host, port, login, ...secret] = parts; } else { [login, ...secret] = parts.slice(0, -2); [host, port] = parts.slice(-2); } } const password = secret.join(":"); if (!PROXY_TYPES.includes(type) || !host || !isPort(port)) return null; const address = host.replace(/^\[(.+)\]$/, "$1"); return { type, host: address, port: Number(port), ...(login ? { login } : {}), ...(password ? { password } : {}) }; } function proxyLabel(proxy) { const host = proxy.host.includes(":") ? `[${proxy.host}]` : proxy.host; return `${proxy.type}://${proxy.login ? `…${proxy.login.slice(-10)}@` : ""}${host}:${proxy.port}`; } async function proxyUuid(job, saved) { const { proxy } = job; const same = (other) => proxy.type === String(other.type).toLowerCase() && proxy.host === other.host && String(proxy.port) === String(other.port) && (proxy.login || "") === (other.login || "") && (proxy.password || "") === (other.password || ""); const known = saved.find(same); if (known) return known.uuid; const added = await cloud("POST", "/proxies", { ...proxy, title: `proxy ${proxy.host}:${proxy.port} #${job.number}`, }); if (!added.data?.data?.uuid) { throw new Error(`could not add the proxy to Octo (HTTP ${added.status} ${added.data?.code || ""})`); } return added.data.data.uuid; } export function checkVpnConfig(text) { const keys = { interface: new Set(), peer: new Set() }; let section = ""; let endpoint = ""; for (const line of text.split("\n")) { const head = line.match(/^\s*\[(\w+)\]/); const pair = line.match(/^\s*(\w+)\s*=\s*(\S+)/); if (head) section = head[1].toLowerCase(); if (!pair || !keys[section]) continue; keys[section].add(pair[1].toLowerCase()); if (section === "peer" && pair[1].toLowerCase() === "endpoint") endpoint = pair[2]; } const required = [ ["Interface", "PrivateKey"], ["Interface", "Address"], ["Peer", "PublicKey"], ["Peer", "Endpoint"], ]; const missing = required .filter(([part, key]) => !keys[part.toLowerCase()].has(key.toLowerCase())) .map(([part, key]) => `${key} in [${part}]`); if (missing.length) return `no ${missing.join(", ")}`; if (!/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+):\d{1,5}$/i.test(endpoint)) { return `Endpoint must be address:port, without http://, not "${endpoint}"`; } return ""; } export function findVpns(folder) { const vpns = []; const skipped = []; if (!existsSync(folder) || !statSync(folder).isDirectory()) return { vpns, skipped }; const files = readdirSync(folder) .filter((file) => statSync(join(folder, file)).isFile()) .sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" })); for (const file of files) { const raw = readFileSync(join(folder, file)); const text = raw .toString("utf8") .replace(/^\uFEFF/, "") .replace(/\r\n/g, "\n"); if (!/^\s*\[Interface\]/im.test(text) || !/^\s*\[Peer\]/im.test(text)) { skipped.push(file); continue; } const problem = checkVpnConfig(text); if (problem) throw new Error(`${file}: ${problem}`); vpns.push({ file, conf: raw.toString("base64") }); } return { vpns, skipped }; } export function readSites(text) { const sites = []; for (const [index, raw] of text.split(/\r?\n/).entries()) { const line = raw.replace(/\s+#.*$/, "").trim(); if (!line || line.startsWith("#") || /^\[.*\]$/.test(line)) continue; let url; try { url = new URL(/^[a-z]+:\/\//i.test(line) ? line : `https://${line}`); } catch { url = null; } if (!url || !["http:", "https:"].includes(url.protocol) || !url.hostname.includes(".")) { throw new Error(`line ${index + 1}: "${line}" is not a site address`); } const site = url.href.replace(/\/$/, ""); if (!sites.includes(site)) sites.push(site); } return sites; } const REGION_NAMES = new Intl.DisplayNames(["en"], { type: "region" }); const COUNTRY_CODES = new Map(); for (let first = 65; first <= 90; first++) { for (let second = 65; second <= 90; second++) { const code = String.fromCharCode(first, second); try { const name = REGION_NAMES.of(code); if (new Intl.Locale(`und-${code}`).region === code && name && name !== code) { COUNTRY_CODES.set(name.toLowerCase(), code); } } catch { continue; } } } async function countryOf(exit) { const code = String(exit.countryCode || exit.country_code || ""); if (/^[A-Za-z]{2}$/.test(code)) return code.toUpperCase(); const byName = COUNTRY_CODES.get(String(exit.country || exit.countryName || "").toLowerCase()); if (byName) return byName; if (!exit.ip) return "XX"; try { const url = `https://get.geojs.io/v1/ip/country/${encodeURIComponent(exit.ip)}.json`; const found = (await (await fetch(url, { signal: AbortSignal.timeout(20000) })).json()).country; return /^[A-Z]{2}$/.test(found || "") ? found : "XX"; } catch { return "XX"; } } let androidModels = []; async function loadAndroidModels() { const answer = await cloud("GET", "/fingerprint/device_models?device_type=phone"); const models = Array.isArray(answer.data?.data) ? answer.data.data : []; androidModels = models.filter((model) => model?.value && model.os_versions?.length); if (!androidModels.length) fail(`Could not read the Android phone models: HTTP ${answer.status}. Nothing was done.`); } function fingerprint() { if (OS !== "android") return { os: OS }; const model = androidModels[Math.floor(Math.random() * androidModels.length)]; const version = model.os_versions[Math.floor(Math.random() * model.os_versions.length)]; return { os: "android", os_arch: "arm", device_type: "phone", device_model: model.value, os_version: String(version), }; } export function hostOf(url) { try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return String(url); } } export function siteName(url) { try { const path = new URL(url).pathname.replace(/\/$/, ""); return hostOf(url) + path; } catch { return String(url); } } export function brandOf(url) { const parts = hostOf(url).split("."); const secondLevel = ["co", "com", "org", "net", "gov", "ac", "edu", "ltd", "plc"]; const deep = parts.length > 2 && secondLevel.includes(parts[parts.length - 2]); return parts[parts.length - (deep ? 3 : 2)] || parts[0]; } const shows = (look) => String(look.text || "").trim().length >= 20 || /<(img|canvas|svg|video)\b/i.test(String(look.html || "")); async function read(page, answer) { const nothing = { ...answer, title: "", heading: "", text: "", html: "" }; for (let attempt = 0; attempt < 3; attempt++) { try { const seen = await page.evaluate( (limits) => ({ text: (document.body?.innerText || "").slice(0, limits.text), heading: (document.querySelector("h1")?.innerText || "").slice(0, limits.title), title: document.title.slice(0, limits.title), html: (document.documentElement?.outerHTML || "").slice(0, limits.html), }), PAGE_LIMITS, ); if (seen.text.trim().length < SHORT_PAGE) { const frames = page.frames().slice(1, 6); const inside = (frame) => frame.evaluate(() => document.body?.innerText || "").catch(() => ""); const texts = await Promise.all( frames.map((frame) => Promise.race([inside(frame), sleep(3000).then(() => "")])), ); seen.text = [seen.text, ...texts].join("\n").slice(0, PAGE_LIMITS.text); } return { ...answer, ...seen, url: page.url() }; } catch (error) { if (/timed out/i.test(error.message)) return { ...nothing, url: page.url(), unresponsive: true }; await sleep(1000); } } return { ...nothing, url: page.url() }; } const RESTRICTION_PAGE = /(^|[./_-])(restricted|restriction|geo-?block(ed)?|geo-?restrict(ed|ion)?|not-?available|unavailable|access-?denied|blocked|forbidden|country-?(not-?)?(allowed|supported|restricted))([./?#_-]|$)/i; export function restrictionPage(asked, reached) { try { const from = new URL(asked); const to = new URL(reached); if (from.hostname === to.hostname && from.pathname === to.pathname) return ""; const where = `${to.hostname}${to.pathname}`; return RESTRICTION_PAGE.test(where) && !RESTRICTION_PAGE.test(`${from.hostname}${from.pathname}`) ? where : ""; } catch { return ""; } } function moved(asked, look, found) { const to = hostOf(look.url); if (!look.url || to === hostOf(asked)) return found; if (brandOf(look.url) === brandOf(asked)) return { ...found, detail: `${found.detail}, opened as ${to}` }; const page = view(look); const lead = `${page.top} | ${String(look.text || "") .toLowerCase() .slice(0, 1500)}`; const phrase = [GEO, PROXY_SEEN, REFUSALS, CHECKS].map((list) => (lead.match(list) || [""])[0]).find(Boolean); if (!page.short && !phrase) { return { ...found, detail: `${found.detail}, but opened another site: ${to} (check that it is the one you need)` }; } return { verdict: "redirected", detail: `sent to another site, ${to}` + (phrase ? `, which says: "${phrase}"` : "") }; } function watchAnswer(page) { const answer = { status: 0, headers: {} }; page.on("response", (response) => { try { if (response.request().isNavigationRequest() && response.frame() === page.mainFrame()) { Object.assign(answer, { status: response.status(), headers: response.headers() }); } } catch { return; } }); return answer; } async function waitFor(page, answer, look, seconds, pause, settled) { for (const until = Date.now() + seconds * 1000; !settled(look) && Date.now() < until;) { await sleep(pause); look = await read(page, answer); } return look; } async function judge(page, answer, url, slow, timeout) { const stuck = (seen) => seen.unresponsive && { verdict: "unresponsive", detail: `the page stopped responding (HTTP ${seen.status})` }; let look = await read(page, answer); if (look.url.startsWith("chrome-error://") && look.status < 400) return networkError(look.text, timeout); let found = classify(look); if (found.verdict === "challenge") { const check = found.detail; look = await waitFor(page, answer, look, CHECK_WAIT, 2500, (seen) => classify(seen).verdict !== "challenge"); found = classify(look); if (found.verdict === "ok") found.detail += `, passed a check by itself (${check})`; } if (found.verdict === "ok" && !shows(look) && !stuck(look)) { look = await waitFor(page, answer, look, EMPTY_WAIT, 2000, (seen) => shows(seen) || seen.unresponsive); found = classify(look); if (found.verdict === "ok" && !shows(look) && !stuck(look)) { return slow ? { verdict: "timeout", detail: `the site answered (HTTP ${look.status}) but the page did not load in ${timeout} s`, } : { verdict: "empty", detail: `the page stayed empty for ${EMPTY_WAIT} s` }; } } if (stuck(look)) return stuck(look); const restriction = found.verdict === "ok" && restrictionPage(url, look.url); if (restriction) return { verdict: "geo_blocked", detail: `sent to a restriction page, ${restriction.replace(/\/$/, "")}` }; if (found.verdict === "ok") found = moved(url, look, found); if (found.verdict === "ok" && slow) found.detail += ", loaded slowly"; return found; } async function inspect(browser, url, shot, timeout) { const page = await browser.newPage(); const answer = watchAnswer(page); page.on("dialog", (dialog) => dialog.dismiss().catch(() => {})); try { let slow = false; try { await page.goto(url, { waitUntil: "domcontentloaded", timeout: timeout * 1000 }); } catch (error) { const failed = /net::ERR_/.test(error.message) && !error.message.includes("ERR_ABORTED"); if (!answer.status || failed) return networkError(error.message, timeout); slow = /timeout/i.test(error.message); } await page.waitForNetworkIdle({ idleTime: 800, timeout: 8000 }).catch(() => {}); const found = await judge(page, answer, url, slow, timeout); if (found.verdict !== "ok" && found.verdict !== "unresponsive" && shot) { found.screenshot = await page.screenshot({ path: shot }).then( () => shot, () => "", ); } return found; } finally { await page.close().catch(() => {}); } } export async function checkSite(browser, url, shot = "") { let found = await inspect(browser, url, shot, PAGE_TIMEOUT); if (RETRY.has(found.verdict)) { const first = found.verdict; await sleep(3000); found = await inspect(browser, url, shot, Math.min(PAGE_TIMEOUT, RETRY_TIMEOUT)); found.detail += found.verdict === first ? " (on the second try too)" : ` (the first try: ${first})`; } return { result: found.verdict === "ok" ? "AVAILABLE" : "UNAVAILABLE", reason: `${found.verdict}: ${printable(found.detail)}`, screenshot: found.screenshot || "", }; } function checkSettings() { const seconds = [PAGE_TIMEOUT, CHECK_WAIT, EMPTY_WAIT]; const problems = [ [!OS_NAMES[OS], `OS is win, mac or android, not "${OS}".`], [typeof HEADLESS !== "boolean", "HEADLESS is true or false, without quotes."], [typeof KEEP_PROFILES !== "boolean", "KEEP_PROFILES is true or false, without quotes."], [typeof SCREENSHOTS !== "boolean", "SCREENSHOTS is true or false, without quotes."], [!Number.isInteger(PARALLEL) || PARALLEL < 1 || PARALLEL > 10, "PARALLEL is a whole number from 1 to 10."], [!PROXY_TYPES.includes(DEFAULT_TYPE), `DEFAULT_TYPE is one of ${PROXY_TYPES.join(", ")}.`], [seconds.some((value) => !(value > 0)), "PAGE_TIMEOUT, CHECK_WAIT and EMPTY_WAIT are seconds above zero."], [!Number.isInteger(LOCAL_PORT) || LOCAL_PORT < 1 || LOCAL_PORT > 65535, "LOCAL_PORT is a port number, 1 to 65535."], [typeof SAVE_PROXIES !== "boolean", "SAVE_PROXIES is true or false, without quotes."], ]; const problem = problems.find(([wrong]) => wrong); if (problem) fail(`${problem[1]} Nothing was done.`); } function readToken() { const found = String(API_TOKEN).trim(); if (!found) fail("No API token: paste it into API_TOKEN at the top of the script. Nothing was done."); return found; } function readProxies() { const file = join(HERE, PROXY_FILE); const fromFile = PROXY_FILE && existsSync(file) ? readText(file).split(/\r?\n/) : []; const lines = [...PROXIES, ...fromFile].map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); const proxies = lines.map((line) => parseProxy(line)); const bad = proxies.flatMap((proxy, index) => (proxy ? [] : [index + 1])); if (bad.length) fail(`Proxy line(s) ${bad.join(", ")} not understood. Nothing was done.`); proxies.forEach((proxy) => hide(proxy.password)); return proxies; } function readVpns() { try { const { vpns, skipped } = findVpns(join(HERE, VPN_FOLDER)); if (skipped.length) console.log(`Not VPN configs, skipped in ${VPN_FOLDER}: ${skipped.join(", ")}`); if (vpns.length) console.log(`VPN configs found in ${VPN_FOLDER}: ${vpns.map((vpn) => vpn.file).join(", ")}`); if (vpns.length && !(String(VPN_PROTOCOL).trim() && String(VPN_SYN_MODE).trim())) { fail("VPN_PROTOCOL and VPN_SYN_MODE can't be empty. Nothing was done."); } for (const vpn of vpns) { hide(vpn.conf); const keys = Buffer.from(vpn.conf, "base64") .toString() .matchAll(/^\s*(?:PrivateKey|PresharedKey)\s*=\s*(\S+)/gim); for (const [, key] of keys) hide(key); } return vpns; } catch (error) { return fail(`VPN config ${error.message} (folder ${VPN_FOLDER}). Nothing was done.`); } } function readSitesFile() { const file = join(HERE, SITES_FILE); if (!existsSync(file)) fail(`${SITES_FILE} not found next to the script: put the sites there. Nothing was done.`); try { const sites = readSites(readText(file)); if (!sites.length) fail(`${SITES_FILE} has no sites. Nothing was done.`); return sites; } catch (error) { return fail(`${SITES_FILE}, ${error.message}. Nothing was done.`); } } async function connectionOf(job, saved) { if (job.vpn) return { type: "vpn", vpn_protocol: VPN_PROTOCOL, conf: job.vpn.conf, syn_mode: VPN_SYN_MODE }; return SAVE_PROXIES ? { uuid: await proxyUuid(job, saved) } : job.proxy; } async function createProfile(job, saved) { const connection = await connectionOf(job, saved); const profile = { title: `checking ${job.number}`, fingerprint: fingerprint(), proxy: connection }; const made = await cloud("POST", "/profiles", profile); if (made.data?.data?.uuid) return made.data.data.uuid; const errors = made.data?.errors ? JSON.stringify(made.data.errors).slice(0, 200) : ""; const why = [made.data?.code, made.data?.msg || made.data?.error, errors].filter(Boolean).join(" "); throw new Error(`could not create a profile (HTTP ${made.status} ${why})`); } async function startProfile(uuid) { const start = { uuid, headless: HEADLESS, debug_port: true, flags: ["--disable-backgrounding-occluded-windows"] }; const started = await local("/profiles/start", start).catch((error) => ({ ok: false, data: { error: error.message }, })); const works = Boolean(started.ok && started.data?.ws_endpoint); if (works) running.add(uuid); return { ...started, works }; } function progress(index, total, site, checked) { const count = `${String(index + 1).padStart(String(total).length)}/${total}`; const reason = /^ok: HTTP [\d?]+$/.test(checked.reason) ? "" : checked.reason; return `${count} ${checked.result.padEnd(11)} ${siteName(site).padEnd(30)} ${reason}`.trimEnd(); } async function visitSites(job, started, name, { sites, puppeteer, stamp }, say) { const entries = []; const ip = printable(started.data.connection_data?.ip || ""); const folder = join(HERE, `screens_${stamp}`, fileName(`${job.number}_${name}`)); if (SCREENSHOTS) mkdirSync(folder, { recursive: true }); let browser; let failures = 0; try { browser = await puppeteer.connect({ browserWSEndpoint: started.data.ws_endpoint, defaultViewport: null, protocolTimeout: BROWSER_TIMEOUT * 1000, }); for (const [index, site] of sites.entries()) { const number = String(index + 1).padStart(String(sites.length).length, "0"); const shot = SCREENSHOTS ? join(folder, `${number}_${fileName(siteName(site))}.png`) : ""; const checked = await checkSite(browser, site, shot); entries.push({ site, ...checked, ip }); say(progress(index, sites.length, site, checked)); failures = checked.reason.startsWith("proxy_error:") ? failures + 1 : 0; const rest = sites.slice(index + 1); if (failures === PROXY_FAILURES && rest.length) { const kind = job.vpn ? "VPN" : "proxy"; const reason = `not checked: the ${kind} stopped working after site ${index + 1}`; say(`the ${kind} stopped working: ${PROXY_FAILURES} proxy errors in a row, ${rest.length} site(s) not checked`); entries.push(...rest.map((left) => ({ site: left, result: "SKIPPED", reason, ip }))); break; } } } catch (error) { say(`stopped after ${entries.length} of ${sites.length} site(s): ${firstLine(error.message)}`); } finally { await browser?.disconnect().catch(() => {}); } return entries; } function startFailure(job, started, sites) { const reason = redact(started.data?.code || started.data?.error || `HTTP ${started.status}`); const dead = /proxy/i.test(reason) || [4, 5].includes(started.data?.error_code); const name = `${dead ? "DEAD" : "ERROR"}_${fileName(job.vpn ? job.vpn.file : job.proxy.host)}`; const problem = dead ? `the ${job.vpn ? "VPN" : "proxy"} does not work` : "could not start the profile"; return { name, message: `${job.label} -> ${name}: ${problem} (${reason})`, entries: sites.map((site) => ({ site, result: dead ? "DEAD" : "ERROR", reason })), }; } async function finishProfile(uuid, name, say) { const renamed = await cloud("PATCH", `/profiles/${uuid}`, { title: name }); if (!renamed.ok) say(`could not rename the profile (HTTP ${renamed.status})`); if (!KEEP_PROFILES) await cloud("DELETE", "/profiles", { uuids: [uuid], skip_trash_bin: false }); } async function checkConnection(job, context) { let tag = `#${job.number}`; const say = (text) => console.log(`[${tag}] ${text}`); const uuid = await createProfile(job, context.saved); say(`${job.label}: starting the profile...`); const started = await startProfile(uuid); let name, entries; if (started.works) { const exit = started.data.connection_data || {}; name = `${await countryOf(exit)}_${printable(exit.ip || "no-ip")}`; tag = `#${job.number} ${name}`; say(`${job.label}: started, ${context.sites.length} site(s) to check`); try { entries = await visitSites(job, started, name, context, say); } finally { await stopProfile(uuid); } } else { if (started.ok || started.status === undefined) await stopProfile(uuid); const failure = startFailure(job, started, context.sites); say(failure.message); ({ name, entries } = failure); } await finishProfile(uuid, name, say); const blank = { profile: name, proxy: `#${job.number} ${job.label}`, ip: "", screenshot: "" }; const rows = entries.map((entry) => ({ ...blank, ...entry })); if (rows.some((entry) => entry.result.endsWith("AVAILABLE"))) say(`done: ${summary(rows, context.sites.length)}`); return { name, rows }; } function reasonsOf(rows) { const reasons = new Map(); for (const entry of rows.filter((row) => row.result === "UNAVAILABLE")) { const reason = entry.reason.split(":")[0]; reasons.set(reason, (reasons.get(reason) || 0) + 1); } return [...reasons] .sort((a, b) => b[1] - a[1]) .map(([reason, times]) => `${times} ${reason}`) .join(", "); } function unchecked(rows, expected) { const skipped = rows.filter((entry) => entry.result === "SKIPPED"); const missed = expected - rows.length; return ( (skipped.length ? `, ${skipped.length} not checked: ${skipped[0].reason.replace(/^not checked: /, "")}` : "") + (missed ? `, ${missed} not checked` : "") ); } function summary(rows, expected) { const count = (result) => rows.filter((entry) => entry.result === result).length; if (count("DEAD")) return "does not work"; if (count("ERROR")) return `not checked: ${rows[0].reason}`; const why = reasonsOf(rows); return ( `${count("AVAILABLE")} AVAILABLE, ${count("UNAVAILABLE")} UNAVAILABLE` + (why ? ` (${why})` : "") + unchecked(rows, expected) ); } async function runAll(jobs, limit, work) { const results = new Array(jobs.length); let next = 0; const worker = async () => { while (next < jobs.length) { const index = next++; const job = jobs[index]; const done = await work(job).catch((error) => { console.log(`[#${job.number}] ${job.label}: ${firstLine(error.message)}`); return { name: "", rows: [] }; }); results[index] = { number: job.number, label: job.label, ...done }; } }; await Promise.all(Array.from({ length: limit }, worker)); return results; } function printTable(sites, results) { const columns = results.filter((column) => column.name); const repeated = (name) => columns.filter((column) => column.name === name).length > 1; const titles = columns.map((column) => (repeated(column.name) ? `${column.name} #${column.number}` : column.name)); const width = Math.max(11, ...titles.map((title) => title.length)) + 2; const siteWidth = Math.max(4, ...sites.map((site) => siteName(site).length)) + 2; console.log("Site".padEnd(siteWidth) + titles.map((title) => title.padEnd(width)).join("")); for (const site of sites) { const cells = columns.map((column) => column.rows.find((entry) => entry.site === site)?.result || "-"); console.log(siteName(site).padEnd(siteWidth) + cells.map((cell) => cell.padEnd(width)).join("")); } console.log(""); columns.forEach((column, index) => console.log(`${titles[index]}: ${summary(column.rows, sites.length)}`)); } const REPORT_COLUMNS = ["profile", "proxy", "site", "result", "reason", "ip"]; function zip(files) { const parts = []; const directory = []; let offset = 0; for (const [name, text] of files) { const title = Buffer.from(name); const data = Buffer.from(text); const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc32(data), 14); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(title.length, 26); const central = Buffer.alloc(46); central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); local.copy(central, 8, 6, 30); central.writeUInt32LE(offset, 42); parts.push(local, title, data); directory.push(central, title); offset += local.length + title.length + data.length; } const index = Buffer.concat(directory); const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10); end.writeUInt32LE(index.length, 12); end.writeUInt32LE(offset, 16); return Buffer.concat([...parts, index, end]); } const XLSX_ROW_STYLES = { AVAILABLE: 2, UNAVAILABLE: 3 }; const XLSX_OTHER_STYLE = 4; const XLSX_STYLES = '<fonts count="5"><font><sz val="11"/><name val="Calibri"/></font>' + '<font><b/><sz val="11"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF006100"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF9C0006"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF595959"/><name val="Calibri"/></font></fonts>' + '<fills count="5"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFC6EFCE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFFFC7CE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/></patternFill></fill></fills>' + '<borders count="1"><border/></borders>' + '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' + '<cellXfs count="5"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' + '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>' + '<xf numFmtId="0" fontId="2" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="3" fillId="3" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" xfId="0" applyFont="1" applyFill="1"/></cellXfs>' + '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'; const SUMMARY_COLUMNS = ["profile", "proxy", "AVAILABLE", "UNAVAILABLE", "why unavailable", "ip"]; function summaryRows(results, siteCount) { return results.map((result) => { const count = (word) => result.rows.filter((entry) => entry.result === word).length; const dead = count("DEAD") || count("ERROR"); const note = dead ? summary(result.rows, siteCount) : `${reasonsOf(result.rows)}${unchecked(result.rows, siteCount)}`.replace(/^, /, ""); return { values: [ result.name || "not started", `#${result.number} ${result.label}`, dead || !result.rows.length ? "" : count("AVAILABLE"), dead || !result.rows.length ? "" : count("UNAVAILABLE"), !result.rows.length ? "the profile was not created" : note, result.rows[0]?.ip || "", ], dead: dead || !result.rows.length, }; }); } function xlsxSheet(results, siteCount) { const escapes = { "<": "<", ">": ">", "&": "&" }; const text = (value) => printable(value ?? "") .replace(/[\uFFFE\uFFFF]/g, "") .slice(0, 32000) .replace(/[<>&]/g, (sign) => escapes[sign]); const cell = (column, line, value, style) => { const where = `${String.fromCharCode(65 + column)}${line}`; if (typeof value === "number") return `<c r="${where}" s="${style}"><v>${value}</v></c>`; return `<c r="${where}" t="inlineStr" s="${style}"><is><t xml:space="preserve">${text(value)}</t></is></c>`; }; const line = (values, number, styles) => `<row r="${number}">${values .map((value, column) => cell(column, number, value, Array.isArray(styles) ? styles[column] : styles)) .join("")}</row>`; const rows = results.flatMap((result) => result.rows); const lines = []; const add = (values, styles) => lines.push(line(values, lines.length + 1, styles)); add(["TOTAL", `${siteCount} site(s) through ${results.length} connection(s)`], 1); add(SUMMARY_COLUMNS, 1); for (const { values, dead } of summaryRows(results, siteCount)) { add(values, dead ? XLSX_OTHER_STYLE : [0, 0, XLSX_ROW_STYLES.AVAILABLE, XLSX_ROW_STYLES.UNAVAILABLE, 0, 0]); } lines.push(`<row r="${lines.length + 1}"/>`); const header = lines.length + 1; add(REPORT_COLUMNS, 1); for (const entry of rows) { add( REPORT_COLUMNS.map((column) => entry[column]), XLSX_ROW_STYLES[entry.result] || XLSX_OTHER_STYLE, ); } const widths = REPORT_COLUMNS.map((column, i) => Math.min( 90, Math.max( column.length, SUMMARY_COLUMNS[i].length, ...rows.map((entry) => String(entry[column] ?? "").length), ...summaryRows(results, siteCount).map((row) => String(row.values[i] ?? "").length), ) + 2, ), ); const last = `${String.fromCharCode(64 + REPORT_COLUMNS.length)}${lines.length}`; return ( `<cols>${widths.map((width, i) => `<col min="${i + 1}" max="${i + 1}" width="${width}" customWidth="1"/>`).join("")}</cols>` + `<sheetData>${lines.join("")}</sheetData><autoFilter ref="A${header}:${last}"/>` ); } function writeXlsx(results, siteCount, stamp) { const head = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; const main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; const office = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; const packageRels = "http://schemas.openxmlformats.org/package/2006/relationships"; const type = "application/vnd.openxmlformats-officedocument.spreadsheetml"; const file = join(HERE, `site_access_${stamp}.xlsx`); const files = [ [ "[Content_Types].xml", `${head}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` + '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' + '<Default Extension="xml" ContentType="application/xml"/>' + `<Override PartName="/xl/workbook.xml" ContentType="${type}.sheet.main+xml"/>` + `<Override PartName="/xl/worksheets/sheet1.xml" ContentType="${type}.worksheet+xml"/>` + `<Override PartName="/xl/styles.xml" ContentType="${type}.styles+xml"/></Types>`, ], [ "_rels/.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/officeDocument" Target="xl/workbook.xml"/></Relationships>`, ], [ "xl/workbook.xml", `${head}<workbook xmlns="${main}" xmlns:r="${office}">` + '<sheets><sheet name="Report" sheetId="1" r:id="rId1"/></sheets></workbook>', ], [ "xl/_rels/workbook.xml.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/worksheet" Target="worksheets/sheet1.xml"/>` + `<Relationship Id="rId2" Type="${office}/styles" Target="styles.xml"/></Relationships>`, ], [ "xl/styles.xml", `${head}<styleSheet xmlns="${main}">${XLSX_STYLES}</styleSheet>`], ["xl/worksheets/sheet1.xml", `${head}<worksheet xmlns="${main}">${xlsxSheet(results, siteCount)}</worksheet>`], ]; writeFileSync(file, zip(files)); return file; } async function main() { checkSettings(); token = readToken(); hide(token); const proxies = readProxies(); const vpns = readVpns(); if (!proxies.length && !vpns.length) { fail( `Nothing to check: put proxies into ${PROXY_FILE || "PROXIES"} or WireGuard configs into ${VPN_FOLDER}. Nothing was done.`, ); } const sites = readSitesFile(); const puppeteer = await import("puppeteer-core").then( (module) => module.default, () => fail("Puppeteer is not installed: run npm install puppeteer-core in this folder."), ); await local("/profiles/active").catch(() => fail(`The Octo client is not running, or its local port is not ${LOCAL_PORT}: set LOCAL_PORT. Nothing was done.`), ); if (OS === "android") await loadAndroidModels(); const list = SAVE_PROXIES && proxies.length ? await cloud("GET", "/proxies") : { ok: true }; if (!list.ok) fail(`Could not read the saved proxies: HTTP ${list.status}. Nothing was done.`); const saved = Array.isArray(list.data?.data) ? list.data.data : []; const jobs = [ ...proxies.map((proxy) => ({ proxy, label: proxyLabel(proxy) })), ...vpns.map((vpn) => ({ vpn, label: `VPN ${vpn.file}` })), ].map((job, index) => ({ ...job, number: index + 1 })); const workers = Math.min(PARALLEL, jobs.length); const stamp = localStamp(); console.log( `Checking ${sites.length} site(s) through ${proxies.length} proxy(ies) and ${vpns.length} VPN config(s), ` + `one ${OS_NAMES[OS]} profile each, ${HEADLESS ? "without a window" : "in a window"}, ${workers} at a time.\n`, ); const results = await runAll(jobs, workers, (job) => checkConnection(job, { sites, puppeteer, saved, stamp })); const rows = results.flatMap((result) => result.rows); console.log(""); printTable(sites, results); console.log(`\nReport: ${writeXlsx(results, sites.length, stamp)}`); if (rows.some((entry) => entry.screenshot)) console.log(`Screenshots: ${join(HERE, `screens_${stamp}`)}`); const left = limits ? ` Left: ${limits.minute}${limits.minuteLimit ? ` of ${limits.minuteLimit}` : ""} this minute, ` + `${limits.hour}${limits.hourLimit ? ` of ${limits.hourLimit}` : ""} this hour.` : ""; console.log(`${spent} request(s) counted by Octo's rate limits.${left}`); } main().catch((error) => fail(`Stopped: ${firstLine(error.message || error)}`));
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { crc32 } from "node:zlib"; const API_TOKEN = ""; // paste your Octo API token between the quotes const LOCAL_PORT = 58888; // port of the local API of the Octo client: Octo client, Settings, Additional const OS = "win"; // OS of the profiles: win, mac or android const HEADLESS = false; // true: profiles run without a window; false: with a window const PARALLEL = 5; // connections checked at the same time, from 1 to 10 const PROXIES = [ // one proxy per line, for example "socks5://login:password@proxy.example.com:10000", ]; const PROXY_FILE = "proxies.txt"; // a file next to the script with one proxy per line, read together with PROXIES const DEFAULT_TYPE = "socks5"; // type for proxy lines without one: http, https, socks5 or ssh const SAVE_PROXIES = true; // true: new proxies are saved to Octo's proxy list; false: a proxy lives only in its profile const VPN_FOLDER = "config"; // folder with WireGuard configs: one VPN profile per file const VPN_PROTOCOL = "wireguard"; // protocol of the configs, as the Octo API names it const VPN_SYN_MODE = "profile_based"; // syn_mode of the VPN, as the Octo API names it const SITES_FILE = "sites.txt"; // sites to check: one per line, # starts a comment const KEEP_PROFILES = true; // false: every profile goes to the trash after its check const SCREENSHOTS = true; // true: save a screenshot of every page that did not open const PAGE_TIMEOUT = 45; // seconds a site gets to answer const CHECK_WAIT = 15; // seconds a "checking your browser" page gets to clear by itself const EMPTY_WAIT = 10; // seconds a blank page gets to show something const HERE = dirname(fileURLToPath(import.meta.url)); const CLOUD = "https://app.octobrowser.net/api/v2/automation"; const LOCAL = `http://localhost:${LOCAL_PORT}/api`; const OS_NAMES = { win: "Windows", mac: "macOS", android: "Android" }; const PROXY_TYPES = ["http", "https", "socks5", "ssh"]; const SHORT_PAGE = 2500; const PAGE_LIMITS = { text: 200000, html: 400000, title: 2000 }; const RETRY_TIMEOUT = 20; const PROXY_FAILURES = 3; const BROWSER_TIMEOUT = 30; const RETRY = new Set(["timeout", "connection_reset", "dns_error", "proxy_refused", "unreachable"]); const sleep = (ms) => new Promise((done) => setTimeout(done, ms)); const anyOf = (phrases) => new RegExp(phrases.join("|")); const secrets = new Set(); const hide = (value) => String(value || "").length >= 4 && secrets.add(String(value)); const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " "); const redact = (text) => [...secrets] .sort((a, b) => b.length - a.length) .reduce((clean, secret) => clean.split(secret).join("***"), printable(text)) .replace(/\/\/[^\s/@]+@/g, "//***@"); const firstLine = (text) => redact(String(text).split("\n")[0]).slice(0, 200); const fileName = (text) => String(text).replace(/[^\w.-]+/g, "_"); const localStamp = () => new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace(/[:T]/g, "-"); const readText = (file) => readFileSync(file, "utf8").replace(/^\uFEFF/, ""); const fail = (message) => { console.error(message); process.exit(1); }; const GEO = anyOf([ "(not|isn.t|aren.t) (currently |yet )?(available|accessible|offered|permitted|allowed|supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "(unavailable|blocked|restricted|prohibited|banned|not supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "not available in this (country|region)", "access from your (country|region|location) (is|has been) (blocked|restricted|denied|disabled)", "(from|in) a restricted (country|territory|jurisdiction|region|location)", "your (country|region|location|territory) is (restricted|not supported|blocked|not allowed)", "(do|does) not accept (players|customers|users|visitors|residents) from", "(accessing|visiting|located|you are|you.re|you appear)[^.]{0,60}outside (of )?(the )?(uk|u[.]k[.]?|united kingdom|us|u[.]s[.]?|usa|united states|eu)([ .,!]|$)", "country (that |where )?you are (located in|in|accessing from|visiting from)[^.]{0,30}not (supported|allowed|available)", "(do not|don.t|cannot|can.t) allow access (in|from) your (current )?(country|region|location)", "(unavailable|not available|cannot be accessed|can.t be accessed)[^.]{0,120}european (economic area|union)", "unavailable (due to|for) legal reasons", "configured to block access from your country", "недоступ[а-яё]* (в|на территории|для) ваш[а-яё]* (стран|регион)", "nicht in (deinem|ihrem) land", "pas disponible dans votre (pays|région)", "no está disponible en (tu|su) (país|región)", "não está disponível (no|em) seu país", ]); const PROXY_SEEN = anyOf([ "(vpn|proxy|proxies|anonymizer|unblocker)[^.]{0,60}(detected|not (allowed|permitted|supported))", "(appear|seem)s? to be using (a |an )?(vpn|proxy|unblocker|anonymizer)", "(detected|blocked) (a |an |your )?(vpn|proxy|anonymous proxy)", "(disable|turn off|switch off) (your |the |any )?(vpn|proxy)", ]); const CHECKS = anyOf([ "checking (your browser|if the site connection is secure)", "verif(y|ying) (that )?you are (a )?human", "verify (that )?you are not a (robot|bot)", "(prove|confirm) (that )?you are (a )?human", "are you (a )?(human|robot)", "(complete|pass|performing) (a |the )?(security check|captcha)", "security checkpoint", "enable javascript and cookies to continue", "press (&|and) hold", "unusual (traffic|activity)", "suspicious (activity|traffic)", "automated (access|requests|queries|traffic)", "подтвердите, что вы не робот", "проверка браузера", ]); const REFUSALS = anyOf([ "access (to (this|the) (site|page|website|resource|service) )?(is |has been |was )?(denied|forbidden|blocked|restricted)", "you (have been|are|were) (blocked|banned)", "your (ip|ip address|request|access|connection) (has been|was|is) (temporarily )?(blocked|banned|denied|blacklisted|rejected|limited)", "request (blocked|rejected|denied)", "blocked (by|due to) [^.]{0,40}(security|firewall|policy|administrator|rules)", "403 forbidden", "error 403", "you (don.t|do not) have permission to (access|view)", "not authori[sz]ed to (access|view)", "доступ (к (сайту|ресурсу|странице) )?(запрещ|ограничен|заблокирован|закрыт)", "ваш ip[^.]{0,30}(заблокирован|забанен)", ]); const CLOUDFLARE_ERRORS = { 1005: "the network of this IP is banned", 1006: "this IP is banned", 1007: "this IP is banned", 1008: "this IP is banned", 1010: "the browser signature is banned", 1012: "access denied", 1020: "access denied by a firewall rule", }; function guardOf(header, html) { const server = header("server"); if (server.includes("cloudflare") || header("cf-ray")) return "Cloudflare "; if (server.includes("akamai")) return "Akamai "; if (server.includes("ddos-guard") || html.includes("ddos-guard")) return "DDoS-Guard "; return ""; } function cloudflareError(guard, html, short, words) { const onCloudflare = guard === "Cloudflare " || html.includes("cloudflare"); if (!short || !onCloudflare) return ""; return (words.match(/error(?: code)?:? ?(1\d{3})(?!\d)/) || [])[1] || ""; } function view(look) { const text = String(look.text || ""); const title = String(look.title || "").toLowerCase(); const heading = String(look.heading || "").toLowerCase(); const html = String(look.html || "").toLowerCase(); const header = (name) => String(look.headers?.[name] ?? "").toLowerCase(); const short = text.trim().length < SHORT_PAGE; const words = `${title} | ${heading} | ${text.toLowerCase()}`; const guard = guardOf(header, html); return { status: Number(look.status) || 0, url: String(look.url || "").toLowerCase(), html, title, top: `${title} | ${heading}`, words, short, empty: !text.trim(), refusal: short || Number(look.status) >= 400, header, guard, cloudflare: cloudflareError(guard, html, short, words), }; } const said = (page, phrases) => (page.top.match(phrases) || (page.short && page.words.match(phrases)) || [""])[0]; const quoted = (phrase) => (phrase ? `, the page says: "${phrase}"` : ""); const RULES = [ { verdict: "challenge", detail: "Cloudflare challenge", when: (page) => page.header("cf-mitigated").includes("challenge"), }, { verdict: "blocked", detail: (page, state) => `Cloudflare refused (cf-mitigated: ${state})`, when: (page) => page.header("cf-mitigated"), }, { verdict: "blocked", detail: "AWS WAF refused", when: (page) => page.header("x-amzn-waf-action") === "block", }, { verdict: "challenge", detail: (page, action) => `AWS WAF ${action}`, when: (page) => page.header("x-amzn-waf-action"), }, { verdict: "blocked", detail: "Sucuri firewall refused", when: (page) => page.header("x-sucuri-block") || (page.refusal && page.words.includes("sucuri website firewall")), }, { verdict: "challenge", detail: "Kasada check", when: (page) => (page.status >= 400 && (page.header("x-kpsdk-ct") || page.header("x-kpsdk-cd"))) || (page.short && page.html.includes("kpsdk")), }, { verdict: "geo_blocked", detail: "Cloudflare 1009: the site bans the country of this IP", when: (page) => page.cloudflare === "1009" || (page.refusal && page.words.includes("banned the country or region")), }, { verdict: "geo_blocked", detail: "HTTP 451: unavailable for legal reasons in this country", when: (page) => page.status === 451, }, { verdict: "geo_blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, GEO), }, { verdict: "rate_limited", detail: "Cloudflare 1015: too many requests from this IP", when: (page) => page.cloudflare === "1015", }, { verdict: "blocked", detail: (page, meaning) => `Cloudflare ${page.cloudflare}: ${meaning}`, when: (page) => CLOUDFLARE_ERRORS[page.cloudflare], }, { verdict: "blocked", detail: "Cloudflare: 'you have been blocked'", when: (page) => page.short && /sorry, you have been blocked|attention required! \| cloudflare/.test(page.words), }, { verdict: "challenge", detail: "Cloudflare 'Just a moment' check", when: (page) => page.refusal && (page.title.includes("just a moment") || page.html.includes("cf_chl_opt")), }, { verdict: "challenge", detail: "Cloudflare Turnstile check", when: (page) => page.short && page.html.includes("cf-turnstile"), }, { verdict: "blocked", detail: "Akamai: Access Denied", when: (page) => page.refusal && (page.html.includes("errors.edgesuite.net") || page.html.includes("reference #") || /reference #\d+\.[0-9a-f]{6,}/.test(page.words)), }, { verdict: "challenge", detail: "Akamai check", when: (page) => page.short && (page.html.includes("_sec/cp_challenge") || page.html.includes("sec-if-cpt")), }, { verdict: "blocked", detail: "DataDome refused", when: (page) => page.refusal && page.html.includes("captcha-delivery.com") && /temporarily restricted|you have been blocked|access (is |was )?(denied|blocked)/.test(page.words), }, { verdict: "challenge", detail: "DataDome captcha", when: (page) => page.refusal && page.html.includes("captcha-delivery.com"), }, { verdict: "challenge", detail: "PerimeterX (HUMAN) 'Press & Hold'", when: (page) => (page.refusal && page.html.includes("px-captcha")) || page.title.includes("access to this page has been denied") || (page.short && page.status >= 400 && /_pxappid|px-cloud\.net|px-cdn\.net/.test(page.html)), }, { verdict: "blocked", detail: "Imperva (Incapsula) refused", when: (page) => page.refusal && /incapsula incident id|request unsuccessful\. incapsula|this request was blocked by (our|the) security service/.test( page.words, ), }, { verdict: "challenge", detail: "Imperva check", when: (page) => (page.short && page.words.includes("pardon our interruption")) || (page.empty && page.html.includes("_incapsula_resource")), }, { verdict: "blocked", detail: "F5 BIG-IP refused", when: (page) => page.refusal && page.words.includes("the requested url was rejected"), }, { verdict: "blocked", detail: "AWS CloudFront refused", when: (page) => page.status === 403 && page.short && /request blocked|the request could not be satisfied/.test(page.words), }, { verdict: "challenge", detail: "AWS WAF check", when: (page) => page.short && /token\.awswaf\.com|awswafintegration/.test(page.html), }, { verdict: "challenge", detail: "Radware check", when: (page) => page.url.includes("perfdrive.com") || (page.short && page.html.includes("perfdrive.com")), }, { verdict: "challenge", detail: "Vercel security checkpoint", when: (page) => page.title.includes("vercel security checkpoint"), }, { verdict: "challenge", detail: "SiteGround captcha", when: (page) => page.url.includes("/.well-known/sgcaptcha"), }, { verdict: "blocked", detail: "Wordfence refused", when: (page) => page.short && /your access to this site has been limited|generated by wordfence/.test(page.words), }, { verdict: "blocked", detail: "the site blocked the request by its network policy", when: (page) => page.refusal && page.words.includes("blocked due to a network policy"), }, { verdict: "challenge", detail: "Google 'unusual traffic' check", when: (page) => (page.url.includes("google.") && page.url.includes("/sorry/")) || page.words.includes("our systems have detected unusual traffic"), }, { verdict: "challenge", detail: "Amazon captcha", when: (page) => page.refusal && /enter the characters you see below|to discuss automated access to amazon data/.test(page.words), }, { verdict: "challenge", detail: "captcha page", when: (page) => page.short && /recaptcha|hcaptcha|h-captcha|geetest|funcaptcha|arkoselabs/.test(page.html) && /captcha|robot|human|verify|security/.test(page.words), }, { verdict: "blocked", detail: (page, phrase) => `the site sees a proxy or VPN: "${phrase}"`, when: (page) => said(page, PROXY_SEEN), }, { verdict: "challenge", detail: (page, phrase) => `${page.guard}check page: "${phrase}"`, when: (page) => said(page, CHECKS), }, { verdict: "proxy_error", detail: "HTTP 407: the proxy wants another login or password", when: (page) => page.status === 407, }, { verdict: "rate_limited", detail: "HTTP 429: too many requests from this IP", when: (page) => page.status === 429, }, { verdict: "blocked", detail: (page) => `${page.guard}HTTP ${page.status}${quoted(said(page, REFUSALS))}`, when: (page) => [401, 403, 406].includes(page.status), }, { verdict: "blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, REFUSALS), }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: Cloudflare could not reach the site's own server`, when: (page) => page.status >= 520 && page.status <= 527, }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: the site itself fails`, when: (page) => page.status >= 500, }, { verdict: "http_error", detail: (page) => `HTTP ${page.status}`, when: (page) => page.status >= 400, }, ]; export function classify(look) { const page = view(look); for (const rule of RULES) { const match = rule.when(page); if (match) { return { verdict: rule.verdict, detail: typeof rule.detail === "function" ? rule.detail(page, match) : rule.detail, }; } } return { verdict: "ok", detail: `HTTP ${page.status || "?"}` }; } const NETWORK_ERRORS = [ { verdict: "proxy_error", codes: /ERR_SOCKS5_AUTH|ERR_SOCKS_AUTH|ERR_PROXY_AUTH_REQUESTED/, detail: "the proxy rejected its login or password: it may have expired or run out of traffic", }, { verdict: "proxy_error", codes: /ERR_PROXY_CONNECTION_FAILED|ERR_PROXY_AUTH|ERR_NO_SUPPORTED_PROXIES|ERR_PROXY_CERTIFICATE|ERR_MANDATORY_PROXY/, detail: "the proxy itself does not work", }, { verdict: "proxy_refused", codes: /ERR_TUNNEL_CONNECTION_FAILED|ERR_SOCKS_CONNECTION/, detail: "the proxy did not open a connection to this site, its provider may block the site", }, { verdict: "timeout", codes: /ERR_TIMED_OUT|ERR_CONNECTION_TIMED_OUT/, detail: "the site did not answer in time", }, { verdict: "connection_reset", codes: /ERR_CONNECTION_RESET|ERR_CONNECTION_CLOSED|ERR_CONNECTION_ABORTED|ERR_EMPTY_RESPONSE|ERR_SOCKET_NOT_CONNECTED/, detail: "the connection was cut before an answer came", }, { verdict: "connection_reset", codes: /ERR_HTTP2_PROTOCOL_ERROR|ERR_QUIC_PROTOCOL_ERROR/, detail: "the site cut the connection, the way some protection services refuse a visitor", }, { verdict: "connection_refused", codes: /ERR_CONNECTION_REFUSED/, detail: "the site refused the connection", }, { verdict: "dns_error", codes: /ERR_NAME_NOT_RESOLVED|ERR_NAME_RESOLUTION_FAILED|ERR_DNS/, detail: "the address of the site was not found", }, { verdict: "ssl_error", codes: /ERR_CERT_COMMON_NAME_INVALID/, detail: "the site's certificate is issued for another address", }, { verdict: "ssl_error", codes: /ERR_CERT_DATE_INVALID/, detail: "the site's certificate has expired or is not valid yet", }, { verdict: "ssl_error", codes: /ERR_SSL|ERR_CERT|ERR_BAD_SSL|ERR_TLS/, detail: "the secure connection failed, something on the way may replace the site's certificate", }, { verdict: "redirect_loop", codes: /ERR_TOO_MANY_REDIRECTS/, detail: "the site redirects in a circle", }, { verdict: "blocked", codes: /ERR_BLOCKED_BY/, detail: "the request was blocked", }, ]; export function networkError(message, timeout = PAGE_TIMEOUT) { const code = (String(message).match(/(?:net::)?\b(ERR_[A-Z0-9_]+)/) || [])[1]; if (!code) { return /timeout/i.test(message) ? { verdict: "timeout", detail: `no answer in ${timeout} s` } : { verdict: "unreachable", detail: firstLine(message) }; } const known = NETWORK_ERRORS.find((entry) => entry.codes.test(code)); return known ? { verdict: known.verdict, detail: `${code}: ${known.detail}` } : { verdict: "unreachable", detail: code }; } let token = ""; let spent = 0; let limits = null; const running = new Set(); const answerOf = async (response) => ({ status: response.status, ok: response.ok, data: await response.json().catch(() => ({})), }); async function cloud(method, path, body) { for (let attempt = 0; ; attempt++) { spent += 1; const response = await fetch(CLOUD + path, { method, headers: { "X-Octo-Api-Token": token, "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(120000), }); if (response.status === 429 && attempt < 5) { const wait = Number(response.headers.get("retry-after")) || 5; if (wait > 60) throw new Error(`Octo's rate limit is used up for ${wait} s, run the script again later`); await sleep(wait * 1000); continue; } const minute = response.headers.get("x-ratelimit-remaining"); const hour = response.headers.get("x-ratelimit-remaining-hour"); if (minute !== null && hour !== null) { limits = { minute, hour, minuteLimit: response.headers.get("x-ratelimit-limit"), hourLimit: response.headers.get("x-ratelimit-limit-hour"), }; if (Number(minute) < 5) await sleep(5000); } return answerOf(response); } } async function local(path, body) { spent += path === "/profiles/active" ? 0 : 1; const response = await fetch(LOCAL + path, { method: body ? "POST" : "GET", headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(180000), }); return answerOf(response); } async function stopProfile(uuid) { await local("/profiles/stop", { uuid }).catch(() => {}); running.delete(uuid); } process.on("SIGINT", async () => { console.log(`\nStopping ${running.size} running profile(s)...`); await Promise.all([...running].map(stopProfile)); process.exit(130); }); const splitOutsideBrackets = (text) => text.split(/:(?![^[]*\])/); const isPort = (text) => /^\d{1,5}$/.test(text || "") && Number(text) >= 1 && Number(text) <= 65535; const isAddress = (text) => /^\[.+\]$/.test(text) || text.includes(".") || text === "localhost"; export function parseProxy(line, defaultType = DEFAULT_TYPE) { const scheme = line.match(/^([a-z0-9]+):\/\//i); const type = scheme ? scheme[1].toLowerCase() : defaultType; const rest = scheme ? line.slice(scheme[0].length) : line; let host, port, login, secret; if (rest.includes("@")) { const at = rest.lastIndexOf("@"); [login, ...secret] = rest.slice(0, at).split(":"); [host, port] = splitOutsideBrackets(rest.slice(at + 1)); } else { const parts = splitOutsideBrackets(rest); const addressFirst = parts.length <= 2 || (isPort(parts[1]) && (isAddress(parts[0]) || !isPort(parts.at(-1)))); if (addressFirst) { [host, port, login, ...secret] = parts; } else { [login, ...secret] = parts.slice(0, -2); [host, port] = parts.slice(-2); } } const password = secret.join(":"); if (!PROXY_TYPES.includes(type) || !host || !isPort(port)) return null; const address = host.replace(/^\[(.+)\]$/, "$1"); return { type, host: address, port: Number(port), ...(login ? { login } : {}), ...(password ? { password } : {}) }; } function proxyLabel(proxy) { const host = proxy.host.includes(":") ? `[${proxy.host}]` : proxy.host; return `${proxy.type}://${proxy.login ? `…${proxy.login.slice(-10)}@` : ""}${host}:${proxy.port}`; } async function proxyUuid(job, saved) { const { proxy } = job; const same = (other) => proxy.type === String(other.type).toLowerCase() && proxy.host === other.host && String(proxy.port) === String(other.port) && (proxy.login || "") === (other.login || "") && (proxy.password || "") === (other.password || ""); const known = saved.find(same); if (known) return known.uuid; const added = await cloud("POST", "/proxies", { ...proxy, title: `proxy ${proxy.host}:${proxy.port} #${job.number}`, }); if (!added.data?.data?.uuid) { throw new Error(`could not add the proxy to Octo (HTTP ${added.status} ${added.data?.code || ""})`); } return added.data.data.uuid; } export function checkVpnConfig(text) { const keys = { interface: new Set(), peer: new Set() }; let section = ""; let endpoint = ""; for (const line of text.split("\n")) { const head = line.match(/^\s*\[(\w+)\]/); const pair = line.match(/^\s*(\w+)\s*=\s*(\S+)/); if (head) section = head[1].toLowerCase(); if (!pair || !keys[section]) continue; keys[section].add(pair[1].toLowerCase()); if (section === "peer" && pair[1].toLowerCase() === "endpoint") endpoint = pair[2]; } const required = [ ["Interface", "PrivateKey"], ["Interface", "Address"], ["Peer", "PublicKey"], ["Peer", "Endpoint"], ]; const missing = required .filter(([part, key]) => !keys[part.toLowerCase()].has(key.toLowerCase())) .map(([part, key]) => `${key} in [${part}]`); if (missing.length) return `no ${missing.join(", ")}`; if (!/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+):\d{1,5}$/i.test(endpoint)) { return `Endpoint must be address:port, without http://, not "${endpoint}"`; } return ""; } export function findVpns(folder) { const vpns = []; const skipped = []; if (!existsSync(folder) || !statSync(folder).isDirectory()) return { vpns, skipped }; const files = readdirSync(folder) .filter((file) => statSync(join(folder, file)).isFile()) .sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" })); for (const file of files) { const raw = readFileSync(join(folder, file)); const text = raw .toString("utf8") .replace(/^\uFEFF/, "") .replace(/\r\n/g, "\n"); if (!/^\s*\[Interface\]/im.test(text) || !/^\s*\[Peer\]/im.test(text)) { skipped.push(file); continue; } const problem = checkVpnConfig(text); if (problem) throw new Error(`${file}: ${problem}`); vpns.push({ file, conf: raw.toString("base64") }); } return { vpns, skipped }; } export function readSites(text) { const sites = []; for (const [index, raw] of text.split(/\r?\n/).entries()) { const line = raw.replace(/\s+#.*$/, "").trim(); if (!line || line.startsWith("#") || /^\[.*\]$/.test(line)) continue; let url; try { url = new URL(/^[a-z]+:\/\//i.test(line) ? line : `https://${line}`); } catch { url = null; } if (!url || !["http:", "https:"].includes(url.protocol) || !url.hostname.includes(".")) { throw new Error(`line ${index + 1}: "${line}" is not a site address`); } const site = url.href.replace(/\/$/, ""); if (!sites.includes(site)) sites.push(site); } return sites; } const REGION_NAMES = new Intl.DisplayNames(["en"], { type: "region" }); const COUNTRY_CODES = new Map(); for (let first = 65; first <= 90; first++) { for (let second = 65; second <= 90; second++) { const code = String.fromCharCode(first, second); try { const name = REGION_NAMES.of(code); if (new Intl.Locale(`und-${code}`).region === code && name && name !== code) { COUNTRY_CODES.set(name.toLowerCase(), code); } } catch { continue; } } } async function countryOf(exit) { const code = String(exit.countryCode || exit.country_code || ""); if (/^[A-Za-z]{2}$/.test(code)) return code.toUpperCase(); const byName = COUNTRY_CODES.get(String(exit.country || exit.countryName || "").toLowerCase()); if (byName) return byName; if (!exit.ip) return "XX"; try { const url = `https://get.geojs.io/v1/ip/country/${encodeURIComponent(exit.ip)}.json`; const found = (await (await fetch(url, { signal: AbortSignal.timeout(20000) })).json()).country; return /^[A-Z]{2}$/.test(found || "") ? found : "XX"; } catch { return "XX"; } } let androidModels = []; async function loadAndroidModels() { const answer = await cloud("GET", "/fingerprint/device_models?device_type=phone"); const models = Array.isArray(answer.data?.data) ? answer.data.data : []; androidModels = models.filter((model) => model?.value && model.os_versions?.length); if (!androidModels.length) fail(`Could not read the Android phone models: HTTP ${answer.status}. Nothing was done.`); } function fingerprint() { if (OS !== "android") return { os: OS }; const model = androidModels[Math.floor(Math.random() * androidModels.length)]; const version = model.os_versions[Math.floor(Math.random() * model.os_versions.length)]; return { os: "android", os_arch: "arm", device_type: "phone", device_model: model.value, os_version: String(version), }; } export function hostOf(url) { try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return String(url); } } export function siteName(url) { try { const path = new URL(url).pathname.replace(/\/$/, ""); return hostOf(url) + path; } catch { return String(url); } } export function brandOf(url) { const parts = hostOf(url).split("."); const secondLevel = ["co", "com", "org", "net", "gov", "ac", "edu", "ltd", "plc"]; const deep = parts.length > 2 && secondLevel.includes(parts[parts.length - 2]); return parts[parts.length - (deep ? 3 : 2)] || parts[0]; } const shows = (look) => String(look.text || "").trim().length >= 20 || /<(img|canvas|svg|video)\b/i.test(String(look.html || "")); async function read(page, answer) { const nothing = { ...answer, title: "", heading: "", text: "", html: "" }; for (let attempt = 0; attempt < 3; attempt++) { try { const seen = await page.evaluate( (limits) => ({ text: (document.body?.innerText || "").slice(0, limits.text), heading: (document.querySelector("h1")?.innerText || "").slice(0, limits.title), title: document.title.slice(0, limits.title), html: (document.documentElement?.outerHTML || "").slice(0, limits.html), }), PAGE_LIMITS, ); if (seen.text.trim().length < SHORT_PAGE) { const frames = page.frames().slice(1, 6); const inside = (frame) => frame.evaluate(() => document.body?.innerText || "").catch(() => ""); const texts = await Promise.all( frames.map((frame) => Promise.race([inside(frame), sleep(3000).then(() => "")])), ); seen.text = [seen.text, ...texts].join("\n").slice(0, PAGE_LIMITS.text); } return { ...answer, ...seen, url: page.url() }; } catch (error) { if (/timed out/i.test(error.message)) return { ...nothing, url: page.url(), unresponsive: true }; await sleep(1000); } } return { ...nothing, url: page.url() }; } const RESTRICTION_PAGE = /(^|[./_-])(restricted|restriction|geo-?block(ed)?|geo-?restrict(ed|ion)?|not-?available|unavailable|access-?denied|blocked|forbidden|country-?(not-?)?(allowed|supported|restricted))([./?#_-]|$)/i; export function restrictionPage(asked, reached) { try { const from = new URL(asked); const to = new URL(reached); if (from.hostname === to.hostname && from.pathname === to.pathname) return ""; const where = `${to.hostname}${to.pathname}`; return RESTRICTION_PAGE.test(where) && !RESTRICTION_PAGE.test(`${from.hostname}${from.pathname}`) ? where : ""; } catch { return ""; } } function moved(asked, look, found) { const to = hostOf(look.url); if (!look.url || to === hostOf(asked)) return found; if (brandOf(look.url) === brandOf(asked)) return { ...found, detail: `${found.detail}, opened as ${to}` }; const page = view(look); const lead = `${page.top} | ${String(look.text || "") .toLowerCase() .slice(0, 1500)}`; const phrase = [GEO, PROXY_SEEN, REFUSALS, CHECKS].map((list) => (lead.match(list) || [""])[0]).find(Boolean); if (!page.short && !phrase) { return { ...found, detail: `${found.detail}, but opened another site: ${to} (check that it is the one you need)` }; } return { verdict: "redirected", detail: `sent to another site, ${to}` + (phrase ? `, which says: "${phrase}"` : "") }; } function watchAnswer(page) { const answer = { status: 0, headers: {} }; page.on("response", (response) => { try { if (response.request().isNavigationRequest() && response.frame() === page.mainFrame()) { Object.assign(answer, { status: response.status(), headers: response.headers() }); } } catch { return; } }); return answer; } async function waitFor(page, answer, look, seconds, pause, settled) { for (const until = Date.now() + seconds * 1000; !settled(look) && Date.now() < until;) { await sleep(pause); look = await read(page, answer); } return look; } async function judge(page, answer, url, slow, timeout) { const stuck = (seen) => seen.unresponsive && { verdict: "unresponsive", detail: `the page stopped responding (HTTP ${seen.status})` }; let look = await read(page, answer); if (look.url.startsWith("chrome-error://") && look.status < 400) return networkError(look.text, timeout); let found = classify(look); if (found.verdict === "challenge") { const check = found.detail; look = await waitFor(page, answer, look, CHECK_WAIT, 2500, (seen) => classify(seen).verdict !== "challenge"); found = classify(look); if (found.verdict === "ok") found.detail += `, passed a check by itself (${check})`; } if (found.verdict === "ok" && !shows(look) && !stuck(look)) { look = await waitFor(page, answer, look, EMPTY_WAIT, 2000, (seen) => shows(seen) || seen.unresponsive); found = classify(look); if (found.verdict === "ok" && !shows(look) && !stuck(look)) { return slow ? { verdict: "timeout", detail: `the site answered (HTTP ${look.status}) but the page did not load in ${timeout} s`, } : { verdict: "empty", detail: `the page stayed empty for ${EMPTY_WAIT} s` }; } } if (stuck(look)) return stuck(look); const restriction = found.verdict === "ok" && restrictionPage(url, look.url); if (restriction) return { verdict: "geo_blocked", detail: `sent to a restriction page, ${restriction.replace(/\/$/, "")}` }; if (found.verdict === "ok") found = moved(url, look, found); if (found.verdict === "ok" && slow) found.detail += ", loaded slowly"; return found; } async function inspect(browser, url, shot, timeout) { const page = await browser.newPage(); const answer = watchAnswer(page); page.on("dialog", (dialog) => dialog.dismiss().catch(() => {})); try { let slow = false; try { await page.goto(url, { waitUntil: "domcontentloaded", timeout: timeout * 1000 }); } catch (error) { const failed = /net::ERR_/.test(error.message) && !error.message.includes("ERR_ABORTED"); if (!answer.status || failed) return networkError(error.message, timeout); slow = /timeout/i.test(error.message); } await page.waitForNetworkIdle({ idleTime: 800, timeout: 8000 }).catch(() => {}); const found = await judge(page, answer, url, slow, timeout); if (found.verdict !== "ok" && found.verdict !== "unresponsive" && shot) { found.screenshot = await page.screenshot({ path: shot }).then( () => shot, () => "", ); } return found; } finally { await page.close().catch(() => {}); } } export async function checkSite(browser, url, shot = "") { let found = await inspect(browser, url, shot, PAGE_TIMEOUT); if (RETRY.has(found.verdict)) { const first = found.verdict; await sleep(3000); found = await inspect(browser, url, shot, Math.min(PAGE_TIMEOUT, RETRY_TIMEOUT)); found.detail += found.verdict === first ? " (on the second try too)" : ` (the first try: ${first})`; } return { result: found.verdict === "ok" ? "AVAILABLE" : "UNAVAILABLE", reason: `${found.verdict}: ${printable(found.detail)}`, screenshot: found.screenshot || "", }; } function checkSettings() { const seconds = [PAGE_TIMEOUT, CHECK_WAIT, EMPTY_WAIT]; const problems = [ [!OS_NAMES[OS], `OS is win, mac or android, not "${OS}".`], [typeof HEADLESS !== "boolean", "HEADLESS is true or false, without quotes."], [typeof KEEP_PROFILES !== "boolean", "KEEP_PROFILES is true or false, without quotes."], [typeof SCREENSHOTS !== "boolean", "SCREENSHOTS is true or false, without quotes."], [!Number.isInteger(PARALLEL) || PARALLEL < 1 || PARALLEL > 10, "PARALLEL is a whole number from 1 to 10."], [!PROXY_TYPES.includes(DEFAULT_TYPE), `DEFAULT_TYPE is one of ${PROXY_TYPES.join(", ")}.`], [seconds.some((value) => !(value > 0)), "PAGE_TIMEOUT, CHECK_WAIT and EMPTY_WAIT are seconds above zero."], [!Number.isInteger(LOCAL_PORT) || LOCAL_PORT < 1 || LOCAL_PORT > 65535, "LOCAL_PORT is a port number, 1 to 65535."], [typeof SAVE_PROXIES !== "boolean", "SAVE_PROXIES is true or false, without quotes."], ]; const problem = problems.find(([wrong]) => wrong); if (problem) fail(`${problem[1]} Nothing was done.`); } function readToken() { const found = String(API_TOKEN).trim(); if (!found) fail("No API token: paste it into API_TOKEN at the top of the script. Nothing was done."); return found; } function readProxies() { const file = join(HERE, PROXY_FILE); const fromFile = PROXY_FILE && existsSync(file) ? readText(file).split(/\r?\n/) : []; const lines = [...PROXIES, ...fromFile].map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); const proxies = lines.map((line) => parseProxy(line)); const bad = proxies.flatMap((proxy, index) => (proxy ? [] : [index + 1])); if (bad.length) fail(`Proxy line(s) ${bad.join(", ")} not understood. Nothing was done.`); proxies.forEach((proxy) => hide(proxy.password)); return proxies; } function readVpns() { try { const { vpns, skipped } = findVpns(join(HERE, VPN_FOLDER)); if (skipped.length) console.log(`Not VPN configs, skipped in ${VPN_FOLDER}: ${skipped.join(", ")}`); if (vpns.length) console.log(`VPN configs found in ${VPN_FOLDER}: ${vpns.map((vpn) => vpn.file).join(", ")}`); if (vpns.length && !(String(VPN_PROTOCOL).trim() && String(VPN_SYN_MODE).trim())) { fail("VPN_PROTOCOL and VPN_SYN_MODE can't be empty. Nothing was done."); } for (const vpn of vpns) { hide(vpn.conf); const keys = Buffer.from(vpn.conf, "base64") .toString() .matchAll(/^\s*(?:PrivateKey|PresharedKey)\s*=\s*(\S+)/gim); for (const [, key] of keys) hide(key); } return vpns; } catch (error) { return fail(`VPN config ${error.message} (folder ${VPN_FOLDER}). Nothing was done.`); } } function readSitesFile() { const file = join(HERE, SITES_FILE); if (!existsSync(file)) fail(`${SITES_FILE} not found next to the script: put the sites there. Nothing was done.`); try { const sites = readSites(readText(file)); if (!sites.length) fail(`${SITES_FILE} has no sites. Nothing was done.`); return sites; } catch (error) { return fail(`${SITES_FILE}, ${error.message}. Nothing was done.`); } } async function connectionOf(job, saved) { if (job.vpn) return { type: "vpn", vpn_protocol: VPN_PROTOCOL, conf: job.vpn.conf, syn_mode: VPN_SYN_MODE }; return SAVE_PROXIES ? { uuid: await proxyUuid(job, saved) } : job.proxy; } async function createProfile(job, saved) { const connection = await connectionOf(job, saved); const profile = { title: `checking ${job.number}`, fingerprint: fingerprint(), proxy: connection }; const made = await cloud("POST", "/profiles", profile); if (made.data?.data?.uuid) return made.data.data.uuid; const errors = made.data?.errors ? JSON.stringify(made.data.errors).slice(0, 200) : ""; const why = [made.data?.code, made.data?.msg || made.data?.error, errors].filter(Boolean).join(" "); throw new Error(`could not create a profile (HTTP ${made.status} ${why})`); } async function startProfile(uuid) { const start = { uuid, headless: HEADLESS, debug_port: true, flags: ["--disable-backgrounding-occluded-windows"] }; const started = await local("/profiles/start", start).catch((error) => ({ ok: false, data: { error: error.message }, })); const works = Boolean(started.ok && started.data?.ws_endpoint); if (works) running.add(uuid); return { ...started, works }; } function progress(index, total, site, checked) { const count = `${String(index + 1).padStart(String(total).length)}/${total}`; const reason = /^ok: HTTP [\d?]+$/.test(checked.reason) ? "" : checked.reason; return `${count} ${checked.result.padEnd(11)} ${siteName(site).padEnd(30)} ${reason}`.trimEnd(); } async function visitSites(job, started, name, { sites, puppeteer, stamp }, say) { const entries = []; const ip = printable(started.data.connection_data?.ip || ""); const folder = join(HERE, `screens_${stamp}`, fileName(`${job.number}_${name}`)); if (SCREENSHOTS) mkdirSync(folder, { recursive: true }); let browser; let failures = 0; try { browser = await puppeteer.connect({ browserWSEndpoint: started.data.ws_endpoint, defaultViewport: null, protocolTimeout: BROWSER_TIMEOUT * 1000, }); for (const [index, site] of sites.entries()) { const number = String(index + 1).padStart(String(sites.length).length, "0"); const shot = SCREENSHOTS ? join(folder, `${number}_${fileName(siteName(site))}.png`) : ""; const checked = await checkSite(browser, site, shot); entries.push({ site, ...checked, ip }); say(progress(index, sites.length, site, checked)); failures = checked.reason.startsWith("proxy_error:") ? failures + 1 : 0; const rest = sites.slice(index + 1); if (failures === PROXY_FAILURES && rest.length) { const kind = job.vpn ? "VPN" : "proxy"; const reason = `not checked: the ${kind} stopped working after site ${index + 1}`; say(`the ${kind} stopped working: ${PROXY_FAILURES} proxy errors in a row, ${rest.length} site(s) not checked`); entries.push(...rest.map((left) => ({ site: left, result: "SKIPPED", reason, ip }))); break; } } } catch (error) { say(`stopped after ${entries.length} of ${sites.length} site(s): ${firstLine(error.message)}`); } finally { await browser?.disconnect().catch(() => {}); } return entries; } function startFailure(job, started, sites) { const reason = redact(started.data?.code || started.data?.error || `HTTP ${started.status}`); const dead = /proxy/i.test(reason) || [4, 5].includes(started.data?.error_code); const name = `${dead ? "DEAD" : "ERROR"}_${fileName(job.vpn ? job.vpn.file : job.proxy.host)}`; const problem = dead ? `the ${job.vpn ? "VPN" : "proxy"} does not work` : "could not start the profile"; return { name, message: `${job.label} -> ${name}: ${problem} (${reason})`, entries: sites.map((site) => ({ site, result: dead ? "DEAD" : "ERROR", reason })), }; } async function finishProfile(uuid, name, say) { const renamed = await cloud("PATCH", `/profiles/${uuid}`, { title: name }); if (!renamed.ok) say(`could not rename the profile (HTTP ${renamed.status})`); if (!KEEP_PROFILES) await cloud("DELETE", "/profiles", { uuids: [uuid], skip_trash_bin: false }); } async function checkConnection(job, context) { let tag = `#${job.number}`; const say = (text) => console.log(`[${tag}] ${text}`); const uuid = await createProfile(job, context.saved); say(`${job.label}: starting the profile...`); const started = await startProfile(uuid); let name, entries; if (started.works) { const exit = started.data.connection_data || {}; name = `${await countryOf(exit)}_${printable(exit.ip || "no-ip")}`; tag = `#${job.number} ${name}`; say(`${job.label}: started, ${context.sites.length} site(s) to check`); try { entries = await visitSites(job, started, name, context, say); } finally { await stopProfile(uuid); } } else { if (started.ok || started.status === undefined) await stopProfile(uuid); const failure = startFailure(job, started, context.sites); say(failure.message); ({ name, entries } = failure); } await finishProfile(uuid, name, say); const blank = { profile: name, proxy: `#${job.number} ${job.label}`, ip: "", screenshot: "" }; const rows = entries.map((entry) => ({ ...blank, ...entry })); if (rows.some((entry) => entry.result.endsWith("AVAILABLE"))) say(`done: ${summary(rows, context.sites.length)}`); return { name, rows }; } function reasonsOf(rows) { const reasons = new Map(); for (const entry of rows.filter((row) => row.result === "UNAVAILABLE")) { const reason = entry.reason.split(":")[0]; reasons.set(reason, (reasons.get(reason) || 0) + 1); } return [...reasons] .sort((a, b) => b[1] - a[1]) .map(([reason, times]) => `${times} ${reason}`) .join(", "); } function unchecked(rows, expected) { const skipped = rows.filter((entry) => entry.result === "SKIPPED"); const missed = expected - rows.length; return ( (skipped.length ? `, ${skipped.length} not checked: ${skipped[0].reason.replace(/^not checked: /, "")}` : "") + (missed ? `, ${missed} not checked` : "") ); } function summary(rows, expected) { const count = (result) => rows.filter((entry) => entry.result === result).length; if (count("DEAD")) return "does not work"; if (count("ERROR")) return `not checked: ${rows[0].reason}`; const why = reasonsOf(rows); return ( `${count("AVAILABLE")} AVAILABLE, ${count("UNAVAILABLE")} UNAVAILABLE` + (why ? ` (${why})` : "") + unchecked(rows, expected) ); } async function runAll(jobs, limit, work) { const results = new Array(jobs.length); let next = 0; const worker = async () => { while (next < jobs.length) { const index = next++; const job = jobs[index]; const done = await work(job).catch((error) => { console.log(`[#${job.number}] ${job.label}: ${firstLine(error.message)}`); return { name: "", rows: [] }; }); results[index] = { number: job.number, label: job.label, ...done }; } }; await Promise.all(Array.from({ length: limit }, worker)); return results; } function printTable(sites, results) { const columns = results.filter((column) => column.name); const repeated = (name) => columns.filter((column) => column.name === name).length > 1; const titles = columns.map((column) => (repeated(column.name) ? `${column.name} #${column.number}` : column.name)); const width = Math.max(11, ...titles.map((title) => title.length)) + 2; const siteWidth = Math.max(4, ...sites.map((site) => siteName(site).length)) + 2; console.log("Site".padEnd(siteWidth) + titles.map((title) => title.padEnd(width)).join("")); for (const site of sites) { const cells = columns.map((column) => column.rows.find((entry) => entry.site === site)?.result || "-"); console.log(siteName(site).padEnd(siteWidth) + cells.map((cell) => cell.padEnd(width)).join("")); } console.log(""); columns.forEach((column, index) => console.log(`${titles[index]}: ${summary(column.rows, sites.length)}`)); } const REPORT_COLUMNS = ["profile", "proxy", "site", "result", "reason", "ip"]; function zip(files) { const parts = []; const directory = []; let offset = 0; for (const [name, text] of files) { const title = Buffer.from(name); const data = Buffer.from(text); const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc32(data), 14); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(title.length, 26); const central = Buffer.alloc(46); central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); local.copy(central, 8, 6, 30); central.writeUInt32LE(offset, 42); parts.push(local, title, data); directory.push(central, title); offset += local.length + title.length + data.length; } const index = Buffer.concat(directory); const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10); end.writeUInt32LE(index.length, 12); end.writeUInt32LE(offset, 16); return Buffer.concat([...parts, index, end]); } const XLSX_ROW_STYLES = { AVAILABLE: 2, UNAVAILABLE: 3 }; const XLSX_OTHER_STYLE = 4; const XLSX_STYLES = '<fonts count="5"><font><sz val="11"/><name val="Calibri"/></font>' + '<font><b/><sz val="11"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF006100"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF9C0006"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF595959"/><name val="Calibri"/></font></fonts>' + '<fills count="5"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFC6EFCE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFFFC7CE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/></patternFill></fill></fills>' + '<borders count="1"><border/></borders>' + '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' + '<cellXfs count="5"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' + '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>' + '<xf numFmtId="0" fontId="2" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="3" fillId="3" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" xfId="0" applyFont="1" applyFill="1"/></cellXfs>' + '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'; const SUMMARY_COLUMNS = ["profile", "proxy", "AVAILABLE", "UNAVAILABLE", "why unavailable", "ip"]; function summaryRows(results, siteCount) { return results.map((result) => { const count = (word) => result.rows.filter((entry) => entry.result === word).length; const dead = count("DEAD") || count("ERROR"); const note = dead ? summary(result.rows, siteCount) : `${reasonsOf(result.rows)}${unchecked(result.rows, siteCount)}`.replace(/^, /, ""); return { values: [ result.name || "not started", `#${result.number} ${result.label}`, dead || !result.rows.length ? "" : count("AVAILABLE"), dead || !result.rows.length ? "" : count("UNAVAILABLE"), !result.rows.length ? "the profile was not created" : note, result.rows[0]?.ip || "", ], dead: dead || !result.rows.length, }; }); } function xlsxSheet(results, siteCount) { const escapes = { "<": "<", ">": ">", "&": "&" }; const text = (value) => printable(value ?? "") .replace(/[\uFFFE\uFFFF]/g, "") .slice(0, 32000) .replace(/[<>&]/g, (sign) => escapes[sign]); const cell = (column, line, value, style) => { const where = `${String.fromCharCode(65 + column)}${line}`; if (typeof value === "number") return `<c r="${where}" s="${style}"><v>${value}</v></c>`; return `<c r="${where}" t="inlineStr" s="${style}"><is><t xml:space="preserve">${text(value)}</t></is></c>`; }; const line = (values, number, styles) => `<row r="${number}">${values .map((value, column) => cell(column, number, value, Array.isArray(styles) ? styles[column] : styles)) .join("")}</row>`; const rows = results.flatMap((result) => result.rows); const lines = []; const add = (values, styles) => lines.push(line(values, lines.length + 1, styles)); add(["TOTAL", `${siteCount} site(s) through ${results.length} connection(s)`], 1); add(SUMMARY_COLUMNS, 1); for (const { values, dead } of summaryRows(results, siteCount)) { add(values, dead ? XLSX_OTHER_STYLE : [0, 0, XLSX_ROW_STYLES.AVAILABLE, XLSX_ROW_STYLES.UNAVAILABLE, 0, 0]); } lines.push(`<row r="${lines.length + 1}"/>`); const header = lines.length + 1; add(REPORT_COLUMNS, 1); for (const entry of rows) { add( REPORT_COLUMNS.map((column) => entry[column]), XLSX_ROW_STYLES[entry.result] || XLSX_OTHER_STYLE, ); } const widths = REPORT_COLUMNS.map((column, i) => Math.min( 90, Math.max( column.length, SUMMARY_COLUMNS[i].length, ...rows.map((entry) => String(entry[column] ?? "").length), ...summaryRows(results, siteCount).map((row) => String(row.values[i] ?? "").length), ) + 2, ), ); const last = `${String.fromCharCode(64 + REPORT_COLUMNS.length)}${lines.length}`; return ( `<cols>${widths.map((width, i) => `<col min="${i + 1}" max="${i + 1}" width="${width}" customWidth="1"/>`).join("")}</cols>` + `<sheetData>${lines.join("")}</sheetData><autoFilter ref="A${header}:${last}"/>` ); } function writeXlsx(results, siteCount, stamp) { const head = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; const main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; const office = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; const packageRels = "http://schemas.openxmlformats.org/package/2006/relationships"; const type = "application/vnd.openxmlformats-officedocument.spreadsheetml"; const file = join(HERE, `site_access_${stamp}.xlsx`); const files = [ [ "[Content_Types].xml", `${head}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` + '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' + '<Default Extension="xml" ContentType="application/xml"/>' + `<Override PartName="/xl/workbook.xml" ContentType="${type}.sheet.main+xml"/>` + `<Override PartName="/xl/worksheets/sheet1.xml" ContentType="${type}.worksheet+xml"/>` + `<Override PartName="/xl/styles.xml" ContentType="${type}.styles+xml"/></Types>`, ], [ "_rels/.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/officeDocument" Target="xl/workbook.xml"/></Relationships>`, ], [ "xl/workbook.xml", `${head}<workbook xmlns="${main}" xmlns:r="${office}">` + '<sheets><sheet name="Report" sheetId="1" r:id="rId1"/></sheets></workbook>', ], [ "xl/_rels/workbook.xml.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/worksheet" Target="worksheets/sheet1.xml"/>` + `<Relationship Id="rId2" Type="${office}/styles" Target="styles.xml"/></Relationships>`, ], [ "xl/styles.xml", `${head}<styleSheet xmlns="${main}">${XLSX_STYLES}</styleSheet>`], ["xl/worksheets/sheet1.xml", `${head}<worksheet xmlns="${main}">${xlsxSheet(results, siteCount)}</worksheet>`], ]; writeFileSync(file, zip(files)); return file; } async function main() { checkSettings(); token = readToken(); hide(token); const proxies = readProxies(); const vpns = readVpns(); if (!proxies.length && !vpns.length) { fail( `Nothing to check: put proxies into ${PROXY_FILE || "PROXIES"} or WireGuard configs into ${VPN_FOLDER}. Nothing was done.`, ); } const sites = readSitesFile(); const puppeteer = await import("puppeteer-core").then( (module) => module.default, () => fail("Puppeteer is not installed: run npm install puppeteer-core in this folder."), ); await local("/profiles/active").catch(() => fail(`The Octo client is not running, or its local port is not ${LOCAL_PORT}: set LOCAL_PORT. Nothing was done.`), ); if (OS === "android") await loadAndroidModels(); const list = SAVE_PROXIES && proxies.length ? await cloud("GET", "/proxies") : { ok: true }; if (!list.ok) fail(`Could not read the saved proxies: HTTP ${list.status}. Nothing was done.`); const saved = Array.isArray(list.data?.data) ? list.data.data : []; const jobs = [ ...proxies.map((proxy) => ({ proxy, label: proxyLabel(proxy) })), ...vpns.map((vpn) => ({ vpn, label: `VPN ${vpn.file}` })), ].map((job, index) => ({ ...job, number: index + 1 })); const workers = Math.min(PARALLEL, jobs.length); const stamp = localStamp(); console.log( `Checking ${sites.length} site(s) through ${proxies.length} proxy(ies) and ${vpns.length} VPN config(s), ` + `one ${OS_NAMES[OS]} profile each, ${HEADLESS ? "without a window" : "in a window"}, ${workers} at a time.\n`, ); const results = await runAll(jobs, workers, (job) => checkConnection(job, { sites, puppeteer, saved, stamp })); const rows = results.flatMap((result) => result.rows); console.log(""); printTable(sites, results); console.log(`\nReport: ${writeXlsx(results, sites.length, stamp)}`); if (rows.some((entry) => entry.screenshot)) console.log(`Screenshots: ${join(HERE, `screens_${stamp}`)}`); const left = limits ? ` Left: ${limits.minute}${limits.minuteLimit ? ` of ${limits.minuteLimit}` : ""} this minute, ` + `${limits.hour}${limits.hourLimit ? ` of ${limits.hourLimit}` : ""} this hour.` : ""; console.log(`${spent} request(s) counted by Octo's rate limits.${left}`); } main().catch((error) => fail(`Stopped: ${firstLine(error.message || error)}`));
Etapa 4. Criar uma lista de sites
Crie um arquivo executando notepad sites.txt. Siga estas regras:
Coloque cada endereço em uma nova linha.
Você pode incluir o prefixo
https://ou deixá-lo de fora.Comece as linhas de comentário com
#. Os comentários são úteis para dividir a lista em grupos.
# Search and reference sites google.com wikipedia.org # Online stores amazon.com ebay.com
# Search and reference sites google.com wikipedia.org # Online stores amazon.com ebay.com
Etapa 5. Adicionar proxies e VPNs
O script precisa de pelo menos uma conexão para funcionar: um proxy ou uma configuração de VPN. Você também pode configurar ambos os tipos de conexão.
Proxies. Crie um arquivo executando notepad proxies.txt e adicione seus proxies, um por linha. O script aceita os mesmos protocolos e formatos de linha da importação em massa de proxies no Octo Browser. Protocolos suportados: http, https, socks5 e ssh. Formatos suportados:
protocol://ip:port protocol://login:password:ip:port protocol://login:password@ip:port protocol://ip:port:login:password
protocol://ip:port protocol://login:password:ip:port protocol://login:password@ip:port protocol://ip:port:login:password
Endereços IPv6 devem estar entre colchetes: socks5://[2001:db8::1]:1080:login:password. Você também pode omitir o protocolo de uma linha; nesse caso, o tipo especificado em DEFAULT_TYPE é utilizado. Linhas que começam com # são ignoradas.
VPNs. Coloque seus arquivos de configuração do WireGuard na pasta config. O nome do arquivo pode ser qualquer um: o script identifica uma configuração por seu conteúdo, especificamente pelas seções [Interface] e [Peer]. A configuração não é adicionada à lista de proxies do Octo; ela existe apenas dentro do seu próprio perfil.
[Interface] PrivateKey = <client key> Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = <server key>
[Interface] PrivateKey = <client key> Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = <server key>
Antes de executar, o script verifica em cada configuração PrivateKey, Address, PublicKey e Endpoint, e valida se Endpoint está escrito como endereço e porta, sem http://. Se o script encontrar um erro, ele exibirá o nome do arquivo e uma descrição do problema, encerrando em seguida sem criar nenhum perfil.
A estrutura da sua pasta deve ficar assim:
D:\proxy_check\ site_access.mjs script sites.txt website list proxies.txt proxy list config\ VPN configs
D:\proxy_check\ site_access.mjs script sites.txt website list proxies.txt proxy list config\ VPN configs
Etapa 6. Executar a verificação
Abra o Octo Browser e execute o script a partir da sua pasta:
cd D:\proxy_check node site_access.mjs
cd D:\proxy_check node site_access.mjs
Para a primeira execução, use um proxy e três ou quatro sites. Você poderá ver os sites abrindo na janela do perfil. Depois de confirmar que tudo funciona, adicione o restante.
Quando o script inicia, ele verifica tudo o que poderia impedir sua execução: o token, os arquivos, as configurações de VPN e se o Octo está aberto. Se encontrar algum erro, exibe uma mensagem descrevendo o problema e encerra sem criar perfis. A verificação então começa, e o resultado de cada site é exibido assim que estiver disponível.

Os colchetes mostram o número da conexão, o nome do perfil e o contador de sites. Quando várias conexões são verificadas em paralelo, suas linhas de saída podem aparecer intercaladas. Use o rótulo para ver a qual conexão cada linha pertence. Nenhuma senha de proxy é exibida na saída, e apenas os últimos caracteres do nome de usuário são mostrados. Para interromper a verificação, pressione Ctrl+C. O script interromperá os perfis que já foram iniciados.
Como interpretar os resultados
Ao final, o script exibe uma tabela e um resumo para cada conexão:

AVAILABLE significa que o site foi aberto com sucesso e exibiu conteúdo. UNAVAILABLE significa que ele não abriu. Os motivos entre parênteses após o resultado final são listados em ordem decrescente de frequência. DEAD no nome de uma coluna indica que a própria conexão não está funcionando, e não que todos os sites verificados estão indisponíveis.
O rótulo ERROR significa que o perfil não pôde ser iniciado por um motivo não relacionado à conexão. A mensagem de erro do Octo aparece na linha dessa conexão no console e no relatório.
Os arquivos de saída são salvos na pasta. Os registros de data e hora em seus nomes usam a hora local:
site_access_<time>.xlsx— um relatório em Excel. A seção superior contém um resumo mostrando o número total de sites e, para cada conexão, quantos sites estão acessíveis, quantos estão inacessíveis e os motivos. Abaixo disso fica a verificação detalhada, com uma linha por resultado: perfil, conexão, site, resultado, motivo e IP. Linhas para sites acessíveis ficam em verde; inacessíveis, em vermelho. Linhas cinzas indicam uma conexão inoperante e sites que não foram verificados porque o proxy parou de funcionar.screens_<time>— capturas de tela das páginas de falha, com uma pasta separada para cada conexão e capturas numeradas na ordem da lista de sites. Se o site não respondeu ou o próprio proxy não conseguiu estabelecer uma conexão, não há nada a capturar, então nenhuma imagem é salva.
Os perfis permanecem no Octo Browser e são nomeados por país e IP.
Vejamos alguns problemas possíveis:
O que você vê no relatório | O que significa | O que fazer |
|---|---|---|
A conexão está marcada como | A própria conexão não está funcionando. | Verifique o nome de usuário, senha e tipo do proxy, ou os detalhes de configuração da VPN. |
A conexão está marcada como | O perfil não pôde ser iniciado, mas o problema não é a conexão. | Leia o erro no relatório ou console, corrija a causa e execute a verificação novamente. |
Várias entradas | O proxy parou de funcionar durante a verificação: sua franquia de dados acabou ou sua sessão expirou. | Verifique o proxy e execute a verificação novamente. |
Uma conexão tem muitos resultados | O provedor de proxy bloqueou esses sites. | Pergunte ao seu provedor quais categorias de sites estão bloqueadas no seu plano. |
Uma conexão recebe | O site não confia neste endereço IP ou na sua sub-rede. | Altere o IP ou use um tipo diferente de proxy. |
| O site não está disponível no país de saída. | Use um proxy de outro país. |
| O próprio site não está respondendo. | Tente a verificação novamente mais tarde. |
| A conexão está lenta ou continua caindo. | Substitua a conexão. |
| Muitas solicitações estão partindo do mesmo IP. | Aguarde e diminua o valor de |
O que significam os motivos
O código de resposta do servidor não é confiável neste caso. Uma recusa nem sempre vem acompanhada de um erro: a Akamai pode retornar "Access Denied" com um código de status 200, uma verificação do AWS WAF pode retornar 202 e um bloqueio do DataDome pode retornar 401. É por isso que o script lê a própria página. Sites de grande porte raramente criam páginas de recusa do zero: um dos sistemas de segurança conhecidos exibe a página de bloqueio, e cada um possui sua própria assinatura nos cabeçalhos e no texto.
Motivo no relatório | O que aconteceu | Como é identificado |
|---|---|---|
| O proxy não conseguiu estabelecer conexão com este site. | Um erro de túnel ou SOCKS no navegador. É assim que um site bloqueado pelo provedor de proxy se parece. |
| O próprio proxy não está funcionando. | O proxy não responde ou não aceitou o nome de usuário e a senha; código de status 407. |
| O site recusou o acesso a este IP. | Cloudflare 1005–1008, 1010, 1012, 1020 e "Sorry, you have been blocked"; Akamai "Access Denied"; Imperva, Sucuri, F5, Wordfence, AWS WAF, DataDome; códigos de status 401, 403 e 406; ou uma mensagem indicando que o site detectou um proxy ou VPN. |
| O site requer uma verificação do tipo "Você é humano?". | Cloudflare "Just a moment" e Turnstile; PerimeterX "Press & Hold"; páginas de CAPTCHA de DataDome, Akamai, AWS WAF, Kasada, Radware, DDoS-Guard e Vercel; mensagem de "tráfego incomum" do Google; CAPTCHA da Amazon; reCAPTCHA; hCaptcha. |
| O site está indisponível no país da conexão. | Cloudflare 1009, código de status 451, recusa do CloudFront baseada em país, frases como "not available in your country" ou redirecionamento para um endereço como |
| Muitas solicitações vieram deste IP. | Código de status 429 ou Cloudflare 1015. |
| O site não respondeu a tempo. | Nenhuma resposta chegou dentro do tempo estipulado, ou o site começou a responder e travou. |
| A conexão foi interrompida ou rejeitada. | A conexão foi interrompida, resposta vazia ou recusa de conexão antes do carregamento da página. |
| O endereço do site não pôde ser encontrado. | Um erro de DNS. |
| Uma conexão segura não pôde ser estabelecida. | Um erro de certificado ou TLS: o certificado foi emitido para um endereço diferente, expirou ou foi substituído no trajeto. |
| O site enviou o navegador para um endereço não relacionado. | O endereço final pertence a outro site, que exibe uma página curta ou uma recusa. |
| O site continua redirecionando em loop. | O navegador interrompeu a cadeia de redirecionamentos. |
| A página permaneceu em branco. | Nada apareceu nela dentro de 10 segundos. |
| A página parou de responder. | A página abriu, mas o navegador não conseguiu lê-la por 30 segundos porque um script nela travou. |
| O site retornou um erro. | Um código de status 4xx, como 404. |
| O próprio site está com problemas; a conexão não é o motivo. | Um código de status 5xx sem sinais de proteção de segurança. |
| Ocorreu outro erro de rede. | O código de erro do navegador é incluído no motivo. |
Os motivos se dividem em três grupos. proxy_refused e proxy_error significam que a conexão falhou: a solicitação nunca chegou ao site. blocked, challenge, geo_blocked e rate_limited significam que o proxy permitiu a passagem da solicitação, mas o site recusou o acesso. timeout, connection_reset, dns_error e ssl_error significam que nenhuma resposta foi retornada: a causa pode ser o proxy, o site ou a rede entre eles.
Como o script evita falsos resultados
Podem ocorrer erros em qualquer direção: uma falha temporária pode ser confundida com um bloqueio, ou uma página em branco pode ser interpretada como um site aberto com sucesso. Veja como o script lida com casos ambíguos:
Situação | O que o script faz |
|---|---|
A conexão cai, atinge o tempo limite ou o proxy recusa a solicitação. | Ele tenta novamente e espera até 20 segundos por uma resposta. |
O site exibe a verificação "Just a moment". | Ele aguarda até 15 segundos: essa verificação geralmente é resolvida automaticamente para um visitante comum. Se desaparecer, o resultado é |
A página demora para renderizar seus scripts. | Ele espera até 10 segundos para que o conteúdo apareça. |
O site começa a responder e depois trava. | Ele registra um motivo de |
O site abre uma caixa de diálogo | Ele descarta a caixa de diálogo cancelando-a; caso contrário, a página não pode prosseguir. O script então retoma a verificação. |
Um script na página trava. | Após 30 segundos, ele atribui o motivo |
O site redireciona para sua versão local do país, como | É o mesmo site: o resultado é |
O site redireciona para outro domínio, onde uma página comum é carregada. | O resultado é |
O site redireciona para uma página curta não relacionada ou para uma página de recusa. | O resultado é |
A página contém um script antibot, mas o site abre. | A presença de proteção não é tratada como uma recusa. Apenas a página de recusa em si conta. |
As palavras "access denied" aparecem no texto de um artigo normal. | As frases de recusa são verificadas no título da página e em páginas curtas, mas não no meio de um texto longo. |
Conclusão
O script automatiza as verificações de disponibilidade de sites por meio de proxies e VPNs. Ele mostra quais sites abrem através de cada conexão e ajuda a identificar por que os demais estão indisponíveis. Crie sua lista de sites uma vez e execute a verificação sempre que comprar novos proxies, trocar de provedor ou encontrar problemas de acesso a sites. Dessa forma, você não precisará testar cada conexão manualmente.
Perguntas frequentes
Quantas conexões podem ser verificadas simultaneamente?
Cada perfil é um navegador separado, portanto, o limite depende da sua memória e CPU. Em um dispositivo comum, de três a cinco é um número razoável; defina isso com a opção PARALLEL. Se todos os seus proxies usam o mesmo gateway de provedor, não defina um número muito alto: a conta do seu provedor pode limitar conexões simultâneas.
Quanto tempo leva uma verificação?
Um site que abre leva alguns segundos. Os sites que não respondem são os que mais demoram: o script espera 45 segundos e depois tenta novamente por mais 20. As conexões são verificadas em paralelo, portanto, verificar cinco proxies leva quase o mesmo tempo que verificar apenas um.
Por que todos os sites de uma conexão estão marcados como DEAD?
O Octo não conseguiu iniciar um perfil com esse proxy ou VPN: a conexão não está funcionando. Verifique o nome de usuário e senha do proxy, o protocolo e os dados de configuração da VPN. Se o rótulo for ERROR em vez de DEAD, o perfil não pôde ser iniciado por outro motivo não relacionado à conexão. Esse motivo é mostrado na linha da conexão.
Um site está marcado como challenge, mas abre manualmente. Por quê?
A verificação "Você é humano?" não foi concluída automaticamente em 15 segundos. Você pode completá-la manualmente com um clique, mas o script não clica em nada. O tempo de espera é controlado pela configuração CHECK_WAIT.
Por que os resultados diferem entre as execuções?
Na maioria das vezes, o proxy mudou seu endereço IP. Proxies rotativos usam IPs diferentes entre as conexões, e o site pode tratar o novo endereço de maneira distinta. Com alguns provedores, a lista de sites bloqueados também depende do nó de saída: um banco pode abrir por meio de um IP, enquanto o provedor o bloqueia por meio de outro. Outro motivo podem ser os próprios limites de taxa do site: após muitas solicitações, ele começa a retornar o código de status 429 ou a exibir uma verificação.
O perfil não inicia mesmo com o Octo aberto. O que devo fazer?
Verifique a porta da API local: abra as configurações do navegador, vá para a aba Adicional e verifique o Servidor HTTP local. Se a porta não for 58888, insira o valor correto na configuração LOCAL_PORT.
O script não consegue encontrar meu arquivo de configuração de VPN. Por quê?
O arquivo de configuração deve estar na pasta config ao lado do script e conter as seções [Interface] e [Peer]. O script ignora arquivos sem essas seções e os lista no início de sua saída.
O que acontece se um proxy parar de funcionar durante a verificação?
Isso pode acontecer quando uma sessão de proxy expira ou quando sua franquia de dados acaba: o proxy para de responder ou de aceitar o login. Após três erros consecutivos do próprio proxy, o script para de verificar sites por meio dessa conexão para não perder tempo com os sites restantes. Eles são marcados em cinza e como SKIPPED no relatório, e o resumo mostra após qual site o proxy parou de funcionar. As outras conexões continuam a ser verificadas normalmente. As recusas do provedor para sites individuais (proxy_refused) não contam: o proxy ainda está funcionando nesse caso.
O que permanece no Octo após a verificação?
Perfis nomeados por país e IP, além de eventuais novos proxies na lista de proxies. Para não deixar nada para trás, defina KEEP_PROFILES = false e SAVE_PROXIES = false: os perfis serão movidos para a lixeira e os proxies não serão adicionados à lista.
O script envia meus dados para outro lugar além do Octo?
O script envia o token apenas para o endereço da API do Octo. Ele faz uma solicitação a um serviço de terceiros: se o Octo não relatar o país de saída, o script faz a consulta por IP usando o GeoJS. Apenas o IP de saída do proxy é enviado ao GeoJS.
Mantenha o anonimato on-line com Octo Browser. Sua verdadeira impressão digital não pode ser rastreada.
Gostaria de experimentar o Octo Browser com desconto?
Use o código promocional OCTOBLOG e ganhe 30% de desconto em qualquer assinatura. Esta oferta é válida somente para novos usuários.
O que o script pode fazer
Você fornece ao script três listas: sites, proxies e configurações de VPN. Para cada proxy e cada VPN, ele cria um perfil separado no Octo Browser, o inicializa, abre os sites um a um e registra os resultados. No final, você obtém uma tabela com uma linha por site e uma coluna por conexão, seguida de um resumo com os motivos de eventuais falhas.
Site GB_203.0.113.9 DE_198.51.100.7 google.com AVAILABLE AVAILABLE wikipedia.org AVAILABLE AVAILABLE amazon.com UNAVAILABLE AVAILABLE ebay.com AVAILABLE AVAILABLE GB_203.0.113.9: 3 AVAILABLE, 1 UNAVAILABLE (1 challenge) DE_198.51.100.7: 4 AVAILABLE, 0 UNAVAILABLE
Por exemplo, o script pode:
Verificar proxies e VPNs em uma única execução. Ele lê proxies do arquivo
proxies.txte VPNs de arquivos de configuração do WireGuard na pastaconfig. Ele suporta os mesmos protocolos e formatos de linha que a importação em massa de proxies no Octo Browser, incluindo endereços IPv6.Identificar o motivo. Se um site não carregar, o script informa o porquê: o próprio proxy não conseguiu estabelecer uma conexão, o site bloqueou o endereço IP, exigiu uma verificação do tipo "Você é humano?", está indisponível no país de conexão ou simplesmente não respondeu.
Diferenciar um bloqueio de uma falha aleatória. Se a conexão cair ou o site não responder, o script tenta novamente. Se o site exibir uma verificação do tipo "Você é humano?", o script aguarda para ver se ela se resolve sozinha. Se a página carregar normalmente, a mera presença de proteção antibot não é tratada como uma falha.
Executar verificações em paralelo. Ele verifica até dez conexões ao mesmo tempo, e o resultado para cada site é exibido assim que estiver pronto.
Nomear perfis por país e IP. Um perfil recebe um nome como
DE_198.51.100.7. Uma conexão inoperante é marcada comoDEAD, enquanto um perfil que falha ao iniciar por outro motivo é marcado comoERROR.Salvar um relatório. Ele cria um arquivo Excel com um resumo para cada conexão. Os sites acessíveis são destacados em verde e os inacessíveis em vermelho. O script também salva uma captura de tela de cada página com falha para que você possa ver exatamente o que o site exibiu.
Proteger credenciais de acesso. Senhas de proxy, chaves de VPN e o token não são incluídos na saída do console ou no relatório. Os perfis também são interrompidos corretamente, mesmo se você interromper a verificação.
O script apenas observa. Ele não resolve CAPTCHAs, não clica em botões nem digita nada. Tenha o seguinte em mente:
Um resultado
challengenão significa que você foi banido. O site está solicitando que você confirme que é humano, e geralmente é possível abri-lo manualmente no perfil.O script verifica apenas a URL exata que você fornecer. O carregamento com sucesso da página inicial não significa que o login na conta ou a finalização da compra funcionarão. Adicione a URL de uma seção específica à lista se for isso o que você precisa testar.
O resultado é preciso no momento da verificação. Um proxy rotativo pode usar um IP diferente um minuto depois, portanto, os resultados podem mudar.
Cada conexão obtém um novo perfil, e novos proxies são adicionados à lista de proxies do Octo. Ambos consomem os limites da sua assinatura. A Etapa 3 explica como evitar deixá-los salvos após a verificação.
Por que não usar o curl?
Você pode verificar um site por meio de um proxy com um único comando curl, mas ele responde a uma pergunta diferente: a solicitação alcançou o servidor? Ele não pode dizer se o site abrirá em um perfil de navegador.
O
curlnão é um navegador, e os sites conseguem perceber. Os sistemas de segurança o identificam pela sua impressão digital TLS e pelo conjunto de cabeçalhos, podendo rejeitar o próprio clientecurlem vez do seu proxy.O
curlnão executa JavaScript. Um navegador pode passar pela verificação "Só um momento" automaticamente em alguns segundos, enquanto ocurlfica travado nela.O
curlvisualiza o código de resposta, não a página. Uma página de restrição geográfica, um CAPTCHA ou uma recusa com código de status 200 parecem, para ele, um site aberto com sucesso.O
curlnão pode verificar VPNs. Ele pode se conectar por meio de proxies HTTP e SOCKS, mas você não pode passar uma configuração do WireGuard para ele.
O curl ainda tem suas utilidades: é uma maneira rápida de descobrir se um proxy está funcionando e qual é o seu endereço IP. Apenas o navegador dentro do perfil pode dizer se um site abrirá naquele perfil.
O que você vai precisar
Octo Browser com uma assinatura Base ou superior, o que oferece acesso à API.
Node.js versão 22.12 ou posterior.
Uma lista de proxies ou arquivos de configuração de VPN do WireGuard.
Etapa 1. Instalar o Node.js
Baixe o Node.js em nodejs.org e instale-o usando as configurações padrão. Em seguida, abra o PowerShell: pressione Win+R, digite PowerShell e pressione Enter. Verifique a instalação:
node --version
O comando deve exibir a versão 22.12 ou posterior. Isso é exigido pelo Puppeteer 25, que foi usado para testar o script. Se o PowerShell indicar que o comando não foi encontrado, feche o PowerShell, reabra-o e tente novamente.
Etapa 2. Preparar uma pasta
Escolha uma pasta para o script, por exemplo D:\proxy_check, crie-a e navegue até ela no PowerShell. Crie uma pasta config dentro dela para suas configurações de VPN:
cd D:\ mkdir proxy_check cd proxy_check mkdir config
Instale o Puppeteer. A versão é especificada explicitamente porque esta é a versão com a qual o script foi testado:
npm install puppeteer-core@25
Etapa 3. O script site_access.mjs
No PowerShell, com proxy_check como a pasta atual, execute notepad site_access.mjs. Quando for perguntado se deseja criar um novo arquivo, clique em Sim, cole todo o código e salve pressionando Ctrl+S. Criar o arquivo a partir da linha de comando ajuda a evitar problemas de extensão de arquivo: se você o criar pelo menu do Bloco de Notas, ele poderá ser salvo como site_access.mjs.txt, e o script não será executado. Crie os outros arquivos nas etapas a seguir da mesma forma.
As configurações estão listadas no início do código, cada uma com um comentário explicativo. Uma configuração é obrigatória: cole seu token de API em API_TOKEN. Você pode encontrá-lo no Octo Browser, na aba API tokens nas configurações da sua conta principal.
const API_TOKEN = "your_token";
Você pode manter as outras configurações com seus valores padrão. No entanto, preste atenção a estes dois parâmetros:
KEEP_PROFILES = false envia os perfis para a lixeira após a verificação.
SAVE_PROXIES = false impede que os proxies testados sejam adicionados à lista de proxies do Octo. Com essas definições, os perfis e proxies criados para o teste não vão sobrecarregar suas listas de trabalho no navegador. Isso é útil se o seu limite de perfis for baixo.
Aqui está uma descrição detalhada das configurações:
Configuração | O que ela controla |
|---|---|
| Token de API do Octo Browser |
| Porta da API local do cliente Octo, padrão 58888. Você pode encontrá-la nas configurações, na aba Adicional. |
| Sistema operacional do perfil: |
|
|
| Número de conexões verificadas simultaneamente, de 1 a 10. |
| Proxies especificados diretamente no código, além daqueles no arquivo. |
| Arquivo contendo proxies; padrão |
| Tipo usado para linhas de proxy que não especificam um. |
|
|
| Pasta contendo as configurações de VPN; padrão |
| Protocolo usado pelos arquivos de configuração e o modo usado para identificá-los na API do Octo. Os padrões são |
| Arquivo contendo a lista de sites; padrão |
|
|
| Se deve salvar capturas de tela das páginas com falha. |
| Quantos segundos aguardar para um site responder, para a verificação "Você é humano?" sumir e para o conteúdo da página aparecer. |
Aqui está o código:
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { crc32 } from "node:zlib"; const API_TOKEN = ""; // paste your Octo API token between the quotes const LOCAL_PORT = 58888; // port of the local API of the Octo client: Octo client, Settings, Additional const OS = "win"; // OS of the profiles: win, mac or android const HEADLESS = false; // true: profiles run without a window; false: with a window const PARALLEL = 5; // connections checked at the same time, from 1 to 10 const PROXIES = [ // one proxy per line, for example "socks5://login:password@proxy.example.com:10000", ]; const PROXY_FILE = "proxies.txt"; // a file next to the script with one proxy per line, read together with PROXIES const DEFAULT_TYPE = "socks5"; // type for proxy lines without one: http, https, socks5 or ssh const SAVE_PROXIES = true; // true: new proxies are saved to Octo's proxy list; false: a proxy lives only in its profile const VPN_FOLDER = "config"; // folder with WireGuard configs: one VPN profile per file const VPN_PROTOCOL = "wireguard"; // protocol of the configs, as the Octo API names it const VPN_SYN_MODE = "profile_based"; // syn_mode of the VPN, as the Octo API names it const SITES_FILE = "sites.txt"; // sites to check: one per line, # starts a comment const KEEP_PROFILES = true; // false: every profile goes to the trash after its check const SCREENSHOTS = true; // true: save a screenshot of every page that did not open const PAGE_TIMEOUT = 45; // seconds a site gets to answer const CHECK_WAIT = 15; // seconds a "checking your browser" page gets to clear by itself const EMPTY_WAIT = 10; // seconds a blank page gets to show something const HERE = dirname(fileURLToPath(import.meta.url)); const CLOUD = "https://app.octobrowser.net/api/v2/automation"; const LOCAL = `http://localhost:${LOCAL_PORT}/api`; const OS_NAMES = { win: "Windows", mac: "macOS", android: "Android" }; const PROXY_TYPES = ["http", "https", "socks5", "ssh"]; const SHORT_PAGE = 2500; const PAGE_LIMITS = { text: 200000, html: 400000, title: 2000 }; const RETRY_TIMEOUT = 20; const PROXY_FAILURES = 3; const BROWSER_TIMEOUT = 30; const RETRY = new Set(["timeout", "connection_reset", "dns_error", "proxy_refused", "unreachable"]); const sleep = (ms) => new Promise((done) => setTimeout(done, ms)); const anyOf = (phrases) => new RegExp(phrases.join("|")); const secrets = new Set(); const hide = (value) => String(value || "").length >= 4 && secrets.add(String(value)); const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " "); const redact = (text) => [...secrets] .sort((a, b) => b.length - a.length) .reduce((clean, secret) => clean.split(secret).join("***"), printable(text)) .replace(/\/\/[^\s/@]+@/g, "//***@"); const firstLine = (text) => redact(String(text).split("\n")[0]).slice(0, 200); const fileName = (text) => String(text).replace(/[^\w.-]+/g, "_"); const localStamp = () => new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace(/[:T]/g, "-"); const readText = (file) => readFileSync(file, "utf8").replace(/^\uFEFF/, ""); const fail = (message) => { console.error(message); process.exit(1); }; const GEO = anyOf([ "(not|isn.t|aren.t) (currently |yet )?(available|accessible|offered|permitted|allowed|supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "(unavailable|blocked|restricted|prohibited|banned|not supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "not available in this (country|region)", "access from your (country|region|location) (is|has been) (blocked|restricted|denied|disabled)", "(from|in) a restricted (country|territory|jurisdiction|region|location)", "your (country|region|location|territory) is (restricted|not supported|blocked|not allowed)", "(do|does) not accept (players|customers|users|visitors|residents) from", "(accessing|visiting|located|you are|you.re|you appear)[^.]{0,60}outside (of )?(the )?(uk|u[.]k[.]?|united kingdom|us|u[.]s[.]?|usa|united states|eu)([ .,!]|$)", "country (that |where )?you are (located in|in|accessing from|visiting from)[^.]{0,30}not (supported|allowed|available)", "(do not|don.t|cannot|can.t) allow access (in|from) your (current )?(country|region|location)", "(unavailable|not available|cannot be accessed|can.t be accessed)[^.]{0,120}european (economic area|union)", "unavailable (due to|for) legal reasons", "configured to block access from your country", "недоступ[а-яё]* (в|на территории|для) ваш[а-яё]* (стран|регион)", "nicht in (deinem|ihrem) land", "pas disponible dans votre (pays|région)", "no está disponible en (tu|su) (país|región)", "não está disponível (no|em) seu país", ]); const PROXY_SEEN = anyOf([ "(vpn|proxy|proxies|anonymizer|unblocker)[^.]{0,60}(detected|not (allowed|permitted|supported))", "(appear|seem)s? to be using (a |an )?(vpn|proxy|unblocker|anonymizer)", "(detected|blocked) (a |an |your )?(vpn|proxy|anonymous proxy)", "(disable|turn off|switch off) (your |the |any )?(vpn|proxy)", ]); const CHECKS = anyOf([ "checking (your browser|if the site connection is secure)", "verif(y|ying) (that )?you are (a )?human", "verify (that )?you are not a (robot|bot)", "(prove|confirm) (that )?you are (a )?human", "are you (a )?(human|robot)", "(complete|pass|performing) (a |the )?(security check|captcha)", "security checkpoint", "enable javascript and cookies to continue", "press (&|and) hold", "unusual (traffic|activity)", "suspicious (activity|traffic)", "automated (access|requests|queries|traffic)", "подтвердите, что вы не робот", "проверка браузера", ]); const REFUSALS = anyOf([ "access (to (this|the) (site|page|website|resource|service) )?(is |has been |was )?(denied|forbidden|blocked|restricted)", "you (have been|are|were) (blocked|banned)", "your (ip|ip address|request|access|connection) (has been|was|is) (temporarily )?(blocked|banned|denied|blacklisted|rejected|limited)", "request (blocked|rejected|denied)", "blocked (by|due to) [^.]{0,40}(security|firewall|policy|administrator|rules)", "403 forbidden", "error 403", "you (don.t|do not) have permission to (access|view)", "not authori[sz]ed to (access|view)", "доступ (к (сайту|ресурсу|странице) )?(запрещ|ограничен|заблокирован|закрыт)", "ваш ip[^.]{0,30}(заблокирован|забанен)", ]); const CLOUDFLARE_ERRORS = { 1005: "the network of this IP is banned", 1006: "this IP is banned", 1007: "this IP is banned", 1008: "this IP is banned", 1010: "the browser signature is banned", 1012: "access denied", 1020: "access denied by a firewall rule", }; function guardOf(header, html) { const server = header("server"); if (server.includes("cloudflare") || header("cf-ray")) return "Cloudflare "; if (server.includes("akamai")) return "Akamai "; if (server.includes("ddos-guard") || html.includes("ddos-guard")) return "DDoS-Guard "; return ""; } function cloudflareError(guard, html, short, words) { const onCloudflare = guard === "Cloudflare " || html.includes("cloudflare"); if (!short || !onCloudflare) return ""; return (words.match(/error(?: code)?:? ?(1\d{3})(?!\d)/) || [])[1] || ""; } function view(look) { const text = String(look.text || ""); const title = String(look.title || "").toLowerCase(); const heading = String(look.heading || "").toLowerCase(); const html = String(look.html || "").toLowerCase(); const header = (name) => String(look.headers?.[name] ?? "").toLowerCase(); const short = text.trim().length < SHORT_PAGE; const words = `${title} | ${heading} | ${text.toLowerCase()}`; const guard = guardOf(header, html); return { status: Number(look.status) || 0, url: String(look.url || "").toLowerCase(), html, title, top: `${title} | ${heading}`, words, short, empty: !text.trim(), refusal: short || Number(look.status) >= 400, header, guard, cloudflare: cloudflareError(guard, html, short, words), }; } const said = (page, phrases) => (page.top.match(phrases) || (page.short && page.words.match(phrases)) || [""])[0]; const quoted = (phrase) => (phrase ? `, the page says: "${phrase}"` : ""); const RULES = [ { verdict: "challenge", detail: "Cloudflare challenge", when: (page) => page.header("cf-mitigated").includes("challenge"), }, { verdict: "blocked", detail: (page, state) => `Cloudflare refused (cf-mitigated: ${state})`, when: (page) => page.header("cf-mitigated"), }, { verdict: "blocked", detail: "AWS WAF refused", when: (page) => page.header("x-amzn-waf-action") === "block", }, { verdict: "challenge", detail: (page, action) => `AWS WAF ${action}`, when: (page) => page.header("x-amzn-waf-action"), }, { verdict: "blocked", detail: "Sucuri firewall refused", when: (page) => page.header("x-sucuri-block") || (page.refusal && page.words.includes("sucuri website firewall")), }, { verdict: "challenge", detail: "Kasada check", when: (page) => (page.status >= 400 && (page.header("x-kpsdk-ct") || page.header("x-kpsdk-cd"))) || (page.short && page.html.includes("kpsdk")), }, { verdict: "geo_blocked", detail: "Cloudflare 1009: the site bans the country of this IP", when: (page) => page.cloudflare === "1009" || (page.refusal && page.words.includes("banned the country or region")), }, { verdict: "geo_blocked", detail: "HTTP 451: unavailable for legal reasons in this country", when: (page) => page.status === 451, }, { verdict: "geo_blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, GEO), }, { verdict: "rate_limited", detail: "Cloudflare 1015: too many requests from this IP", when: (page) => page.cloudflare === "1015", }, { verdict: "blocked", detail: (page, meaning) => `Cloudflare ${page.cloudflare}: ${meaning}`, when: (page) => CLOUDFLARE_ERRORS[page.cloudflare], }, { verdict: "blocked", detail: "Cloudflare: 'you have been blocked'", when: (page) => page.short && /sorry, you have been blocked|attention required! \| cloudflare/.test(page.words), }, { verdict: "challenge", detail: "Cloudflare 'Just a moment' check", when: (page) => page.refusal && (page.title.includes("just a moment") || page.html.includes("cf_chl_opt")), }, { verdict: "challenge", detail: "Cloudflare Turnstile check", when: (page) => page.short && page.html.includes("cf-turnstile"), }, { verdict: "blocked", detail: "Akamai: Access Denied", when: (page) => page.refusal && (page.html.includes("errors.edgesuite.net") || page.html.includes("reference #") || /reference #\d+\.[0-9a-f]{6,}/.test(page.words)), }, { verdict: "challenge", detail: "Akamai check", when: (page) => page.short && (page.html.includes("_sec/cp_challenge") || page.html.includes("sec-if-cpt")), }, { verdict: "blocked", detail: "DataDome refused", when: (page) => page.refusal && page.html.includes("captcha-delivery.com") && /temporarily restricted|you have been blocked|access (is |was )?(denied|blocked)/.test(page.words), }, { verdict: "challenge", detail: "DataDome captcha", when: (page) => page.refusal && page.html.includes("captcha-delivery.com"), }, { verdict: "challenge", detail: "PerimeterX (HUMAN) 'Press & Hold'", when: (page) => (page.refusal && page.html.includes("px-captcha")) || page.title.includes("access to this page has been denied") || (page.short && page.status >= 400 && /_pxappid|px-cloud\.net|px-cdn\.net/.test(page.html)), }, { verdict: "blocked", detail: "Imperva (Incapsula) refused", when: (page) => page.refusal && /incapsula incident id|request unsuccessful\. incapsula|this request was blocked by (our|the) security service/.test( page.words, ), }, { verdict: "challenge", detail: "Imperva check", when: (page) => (page.short && page.words.includes("pardon our interruption")) || (page.empty && page.html.includes("_incapsula_resource")), }, { verdict: "blocked", detail: "F5 BIG-IP refused", when: (page) => page.refusal && page.words.includes("the requested url was rejected"), }, { verdict: "blocked", detail: "AWS CloudFront refused", when: (page) => page.status === 403 && page.short && /request blocked|the request could not be satisfied/.test(page.words), }, { verdict: "challenge", detail: "AWS WAF check", when: (page) => page.short && /token\.awswaf\.com|awswafintegration/.test(page.html), }, { verdict: "challenge", detail: "Radware check", when: (page) => page.url.includes("perfdrive.com") || (page.short && page.html.includes("perfdrive.com")), }, { verdict: "challenge", detail: "Vercel security checkpoint", when: (page) => page.title.includes("vercel security checkpoint"), }, { verdict: "challenge", detail: "SiteGround captcha", when: (page) => page.url.includes("/.well-known/sgcaptcha"), }, { verdict: "blocked", detail: "Wordfence refused", when: (page) => page.short && /your access to this site has been limited|generated by wordfence/.test(page.words), }, { verdict: "blocked", detail: "the site blocked the request by its network policy", when: (page) => page.refusal && page.words.includes("blocked due to a network policy"), }, { verdict: "challenge", detail: "Google 'unusual traffic' check", when: (page) => (page.url.includes("google.") && page.url.includes("/sorry/")) || page.words.includes("our systems have detected unusual traffic"), }, { verdict: "challenge", detail: "Amazon captcha", when: (page) => page.refusal && /enter the characters you see below|to discuss automated access to amazon data/.test(page.words), }, { verdict: "challenge", detail: "captcha page", when: (page) => page.short && /recaptcha|hcaptcha|h-captcha|geetest|funcaptcha|arkoselabs/.test(page.html) && /captcha|robot|human|verify|security/.test(page.words), }, { verdict: "blocked", detail: (page, phrase) => `the site sees a proxy or VPN: "${phrase}"`, when: (page) => said(page, PROXY_SEEN), }, { verdict: "challenge", detail: (page, phrase) => `${page.guard}check page: "${phrase}"`, when: (page) => said(page, CHECKS), }, { verdict: "proxy_error", detail: "HTTP 407: the proxy wants another login or password", when: (page) => page.status === 407, }, { verdict: "rate_limited", detail: "HTTP 429: too many requests from this IP", when: (page) => page.status === 429, }, { verdict: "blocked", detail: (page) => `${page.guard}HTTP ${page.status}${quoted(said(page, REFUSALS))}`, when: (page) => [401, 403, 406].includes(page.status), }, { verdict: "blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, REFUSALS), }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: Cloudflare could not reach the site's own server`, when: (page) => page.status >= 520 && page.status <= 527, }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: the site itself fails`, when: (page) => page.status >= 500, }, { verdict: "http_error", detail: (page) => `HTTP ${page.status}`, when: (page) => page.status >= 400, }, ]; export function classify(look) { const page = view(look); for (const rule of RULES) { const match = rule.when(page); if (match) { return { verdict: rule.verdict, detail: typeof rule.detail === "function" ? rule.detail(page, match) : rule.detail, }; } } return { verdict: "ok", detail: `HTTP ${page.status || "?"}` }; } const NETWORK_ERRORS = [ { verdict: "proxy_error", codes: /ERR_SOCKS5_AUTH|ERR_SOCKS_AUTH|ERR_PROXY_AUTH_REQUESTED/, detail: "the proxy rejected its login or password: it may have expired or run out of traffic", }, { verdict: "proxy_error", codes: /ERR_PROXY_CONNECTION_FAILED|ERR_PROXY_AUTH|ERR_NO_SUPPORTED_PROXIES|ERR_PROXY_CERTIFICATE|ERR_MANDATORY_PROXY/, detail: "the proxy itself does not work", }, { verdict: "proxy_refused", codes: /ERR_TUNNEL_CONNECTION_FAILED|ERR_SOCKS_CONNECTION/, detail: "the proxy did not open a connection to this site, its provider may block the site", }, { verdict: "timeout", codes: /ERR_TIMED_OUT|ERR_CONNECTION_TIMED_OUT/, detail: "the site did not answer in time", }, { verdict: "connection_reset", codes: /ERR_CONNECTION_RESET|ERR_CONNECTION_CLOSED|ERR_CONNECTION_ABORTED|ERR_EMPTY_RESPONSE|ERR_SOCKET_NOT_CONNECTED/, detail: "the connection was cut before an answer came", }, { verdict: "connection_reset", codes: /ERR_HTTP2_PROTOCOL_ERROR|ERR_QUIC_PROTOCOL_ERROR/, detail: "the site cut the connection, the way some protection services refuse a visitor", }, { verdict: "connection_refused", codes: /ERR_CONNECTION_REFUSED/, detail: "the site refused the connection", }, { verdict: "dns_error", codes: /ERR_NAME_NOT_RESOLVED|ERR_NAME_RESOLUTION_FAILED|ERR_DNS/, detail: "the address of the site was not found", }, { verdict: "ssl_error", codes: /ERR_CERT_COMMON_NAME_INVALID/, detail: "the site's certificate is issued for another address", }, { verdict: "ssl_error", codes: /ERR_CERT_DATE_INVALID/, detail: "the site's certificate has expired or is not valid yet", }, { verdict: "ssl_error", codes: /ERR_SSL|ERR_CERT|ERR_BAD_SSL|ERR_TLS/, detail: "the secure connection failed, something on the way may replace the site's certificate", }, { verdict: "redirect_loop", codes: /ERR_TOO_MANY_REDIRECTS/, detail: "the site redirects in a circle", }, { verdict: "blocked", codes: /ERR_BLOCKED_BY/, detail: "the request was blocked", }, ]; export function networkError(message, timeout = PAGE_TIMEOUT) { const code = (String(message).match(/(?:net::)?\b(ERR_[A-Z0-9_]+)/) || [])[1]; if (!code) { return /timeout/i.test(message) ? { verdict: "timeout", detail: `no answer in ${timeout} s` } : { verdict: "unreachable", detail: firstLine(message) }; } const known = NETWORK_ERRORS.find((entry) => entry.codes.test(code)); return known ? { verdict: known.verdict, detail: `${code}: ${known.detail}` } : { verdict: "unreachable", detail: code }; } let token = ""; let spent = 0; let limits = null; const running = new Set(); const answerOf = async (response) => ({ status: response.status, ok: response.ok, data: await response.json().catch(() => ({})), }); async function cloud(method, path, body) { for (let attempt = 0; ; attempt++) { spent += 1; const response = await fetch(CLOUD + path, { method, headers: { "X-Octo-Api-Token": token, "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(120000), }); if (response.status === 429 && attempt < 5) { const wait = Number(response.headers.get("retry-after")) || 5; if (wait > 60) throw new Error(`Octo's rate limit is used up for ${wait} s, run the script again later`); await sleep(wait * 1000); continue; } const minute = response.headers.get("x-ratelimit-remaining"); const hour = response.headers.get("x-ratelimit-remaining-hour"); if (minute !== null && hour !== null) { limits = { minute, hour, minuteLimit: response.headers.get("x-ratelimit-limit"), hourLimit: response.headers.get("x-ratelimit-limit-hour"), }; if (Number(minute) < 5) await sleep(5000); } return answerOf(response); } } async function local(path, body) { spent += path === "/profiles/active" ? 0 : 1; const response = await fetch(LOCAL + path, { method: body ? "POST" : "GET", headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(180000), }); return answerOf(response); } async function stopProfile(uuid) { await local("/profiles/stop", { uuid }).catch(() => {}); running.delete(uuid); } process.on("SIGINT", async () => { console.log(`\nStopping ${running.size} running profile(s)...`); await Promise.all([...running].map(stopProfile)); process.exit(130); }); const splitOutsideBrackets = (text) => text.split(/:(?![^[]*\])/); const isPort = (text) => /^\d{1,5}$/.test(text || "") && Number(text) >= 1 && Number(text) <= 65535; const isAddress = (text) => /^\[.+\]$/.test(text) || text.includes(".") || text === "localhost"; export function parseProxy(line, defaultType = DEFAULT_TYPE) { const scheme = line.match(/^([a-z0-9]+):\/\//i); const type = scheme ? scheme[1].toLowerCase() : defaultType; const rest = scheme ? line.slice(scheme[0].length) : line; let host, port, login, secret; if (rest.includes("@")) { const at = rest.lastIndexOf("@"); [login, ...secret] = rest.slice(0, at).split(":"); [host, port] = splitOutsideBrackets(rest.slice(at + 1)); } else { const parts = splitOutsideBrackets(rest); const addressFirst = parts.length <= 2 || (isPort(parts[1]) && (isAddress(parts[0]) || !isPort(parts.at(-1)))); if (addressFirst) { [host, port, login, ...secret] = parts; } else { [login, ...secret] = parts.slice(0, -2); [host, port] = parts.slice(-2); } } const password = secret.join(":"); if (!PROXY_TYPES.includes(type) || !host || !isPort(port)) return null; const address = host.replace(/^\[(.+)\]$/, "$1"); return { type, host: address, port: Number(port), ...(login ? { login } : {}), ...(password ? { password } : {}) }; } function proxyLabel(proxy) { const host = proxy.host.includes(":") ? `[${proxy.host}]` : proxy.host; return `${proxy.type}://${proxy.login ? `…${proxy.login.slice(-10)}@` : ""}${host}:${proxy.port}`; } async function proxyUuid(job, saved) { const { proxy } = job; const same = (other) => proxy.type === String(other.type).toLowerCase() && proxy.host === other.host && String(proxy.port) === String(other.port) && (proxy.login || "") === (other.login || "") && (proxy.password || "") === (other.password || ""); const known = saved.find(same); if (known) return known.uuid; const added = await cloud("POST", "/proxies", { ...proxy, title: `proxy ${proxy.host}:${proxy.port} #${job.number}`, }); if (!added.data?.data?.uuid) { throw new Error(`could not add the proxy to Octo (HTTP ${added.status} ${added.data?.code || ""})`); } return added.data.data.uuid; } export function checkVpnConfig(text) { const keys = { interface: new Set(), peer: new Set() }; let section = ""; let endpoint = ""; for (const line of text.split("\n")) { const head = line.match(/^\s*\[(\w+)\]/); const pair = line.match(/^\s*(\w+)\s*=\s*(\S+)/); if (head) section = head[1].toLowerCase(); if (!pair || !keys[section]) continue; keys[section].add(pair[1].toLowerCase()); if (section === "peer" && pair[1].toLowerCase() === "endpoint") endpoint = pair[2]; } const required = [ ["Interface", "PrivateKey"], ["Interface", "Address"], ["Peer", "PublicKey"], ["Peer", "Endpoint"], ]; const missing = required .filter(([part, key]) => !keys[part.toLowerCase()].has(key.toLowerCase())) .map(([part, key]) => `${key} in [${part}]`); if (missing.length) return `no ${missing.join(", ")}`; if (!/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+):\d{1,5}$/i.test(endpoint)) { return `Endpoint must be address:port, without http://, not "${endpoint}"`; } return ""; } export function findVpns(folder) { const vpns = []; const skipped = []; if (!existsSync(folder) || !statSync(folder).isDirectory()) return { vpns, skipped }; const files = readdirSync(folder) .filter((file) => statSync(join(folder, file)).isFile()) .sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" })); for (const file of files) { const raw = readFileSync(join(folder, file)); const text = raw .toString("utf8") .replace(/^\uFEFF/, "") .replace(/\r\n/g, "\n"); if (!/^\s*\[Interface\]/im.test(text) || !/^\s*\[Peer\]/im.test(text)) { skipped.push(file); continue; } const problem = checkVpnConfig(text); if (problem) throw new Error(`${file}: ${problem}`); vpns.push({ file, conf: raw.toString("base64") }); } return { vpns, skipped }; } export function readSites(text) { const sites = []; for (const [index, raw] of text.split(/\r?\n/).entries()) { const line = raw.replace(/\s+#.*$/, "").trim(); if (!line || line.startsWith("#") || /^\[.*\]$/.test(line)) continue; let url; try { url = new URL(/^[a-z]+:\/\//i.test(line) ? line : `https://${line}`); } catch { url = null; } if (!url || !["http:", "https:"].includes(url.protocol) || !url.hostname.includes(".")) { throw new Error(`line ${index + 1}: "${line}" is not a site address`); } const site = url.href.replace(/\/$/, ""); if (!sites.includes(site)) sites.push(site); } return sites; } const REGION_NAMES = new Intl.DisplayNames(["en"], { type: "region" }); const COUNTRY_CODES = new Map(); for (let first = 65; first <= 90; first++) { for (let second = 65; second <= 90; second++) { const code = String.fromCharCode(first, second); try { const name = REGION_NAMES.of(code); if (new Intl.Locale(`und-${code}`).region === code && name && name !== code) { COUNTRY_CODES.set(name.toLowerCase(), code); } } catch { continue; } } } async function countryOf(exit) { const code = String(exit.countryCode || exit.country_code || ""); if (/^[A-Za-z]{2}$/.test(code)) return code.toUpperCase(); const byName = COUNTRY_CODES.get(String(exit.country || exit.countryName || "").toLowerCase()); if (byName) return byName; if (!exit.ip) return "XX"; try { const url = `https://get.geojs.io/v1/ip/country/${encodeURIComponent(exit.ip)}.json`; const found = (await (await fetch(url, { signal: AbortSignal.timeout(20000) })).json()).country; return /^[A-Z]{2}$/.test(found || "") ? found : "XX"; } catch { return "XX"; } } let androidModels = []; async function loadAndroidModels() { const answer = await cloud("GET", "/fingerprint/device_models?device_type=phone"); const models = Array.isArray(answer.data?.data) ? answer.data.data : []; androidModels = models.filter((model) => model?.value && model.os_versions?.length); if (!androidModels.length) fail(`Could not read the Android phone models: HTTP ${answer.status}. Nothing was done.`); } function fingerprint() { if (OS !== "android") return { os: OS }; const model = androidModels[Math.floor(Math.random() * androidModels.length)]; const version = model.os_versions[Math.floor(Math.random() * model.os_versions.length)]; return { os: "android", os_arch: "arm", device_type: "phone", device_model: model.value, os_version: String(version), }; } export function hostOf(url) { try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return String(url); } } export function siteName(url) { try { const path = new URL(url).pathname.replace(/\/$/, ""); return hostOf(url) + path; } catch { return String(url); } } export function brandOf(url) { const parts = hostOf(url).split("."); const secondLevel = ["co", "com", "org", "net", "gov", "ac", "edu", "ltd", "plc"]; const deep = parts.length > 2 && secondLevel.includes(parts[parts.length - 2]); return parts[parts.length - (deep ? 3 : 2)] || parts[0]; } const shows = (look) => String(look.text || "").trim().length >= 20 || /<(img|canvas|svg|video)\b/i.test(String(look.html || "")); async function read(page, answer) { const nothing = { ...answer, title: "", heading: "", text: "", html: "" }; for (let attempt = 0; attempt < 3; attempt++) { try { const seen = await page.evaluate( (limits) => ({ text: (document.body?.innerText || "").slice(0, limits.text), heading: (document.querySelector("h1")?.innerText || "").slice(0, limits.title), title: document.title.slice(0, limits.title), html: (document.documentElement?.outerHTML || "").slice(0, limits.html), }), PAGE_LIMITS, ); if (seen.text.trim().length < SHORT_PAGE) { const frames = page.frames().slice(1, 6); const inside = (frame) => frame.evaluate(() => document.body?.innerText || "").catch(() => ""); const texts = await Promise.all( frames.map((frame) => Promise.race([inside(frame), sleep(3000).then(() => "")])), ); seen.text = [seen.text, ...texts].join("\n").slice(0, PAGE_LIMITS.text); } return { ...answer, ...seen, url: page.url() }; } catch (error) { if (/timed out/i.test(error.message)) return { ...nothing, url: page.url(), unresponsive: true }; await sleep(1000); } } return { ...nothing, url: page.url() }; } const RESTRICTION_PAGE = /(^|[./_-])(restricted|restriction|geo-?block(ed)?|geo-?restrict(ed|ion)?|not-?available|unavailable|access-?denied|blocked|forbidden|country-?(not-?)?(allowed|supported|restricted))([./?#_-]|$)/i; export function restrictionPage(asked, reached) { try { const from = new URL(asked); const to = new URL(reached); if (from.hostname === to.hostname && from.pathname === to.pathname) return ""; const where = `${to.hostname}${to.pathname}`; return RESTRICTION_PAGE.test(where) && !RESTRICTION_PAGE.test(`${from.hostname}${from.pathname}`) ? where : ""; } catch { return ""; } } function moved(asked, look, found) { const to = hostOf(look.url); if (!look.url || to === hostOf(asked)) return found; if (brandOf(look.url) === brandOf(asked)) return { ...found, detail: `${found.detail}, opened as ${to}` }; const page = view(look); const lead = `${page.top} | ${String(look.text || "") .toLowerCase() .slice(0, 1500)}`; const phrase = [GEO, PROXY_SEEN, REFUSALS, CHECKS].map((list) => (lead.match(list) || [""])[0]).find(Boolean); if (!page.short && !phrase) { return { ...found, detail: `${found.detail}, but opened another site: ${to} (check that it is the one you need)` }; } return { verdict: "redirected", detail: `sent to another site, ${to}` + (phrase ? `, which says: "${phrase}"` : "") }; } function watchAnswer(page) { const answer = { status: 0, headers: {} }; page.on("response", (response) => { try { if (response.request().isNavigationRequest() && response.frame() === page.mainFrame()) { Object.assign(answer, { status: response.status(), headers: response.headers() }); } } catch { return; } }); return answer; } async function waitFor(page, answer, look, seconds, pause, settled) { for (const until = Date.now() + seconds * 1000; !settled(look) && Date.now() < until;) { await sleep(pause); look = await read(page, answer); } return look; } async function judge(page, answer, url, slow, timeout) { const stuck = (seen) => seen.unresponsive && { verdict: "unresponsive", detail: `the page stopped responding (HTTP ${seen.status})` }; let look = await read(page, answer); if (look.url.startsWith("chrome-error://") && look.status < 400) return networkError(look.text, timeout); let found = classify(look); if (found.verdict === "challenge") { const check = found.detail; look = await waitFor(page, answer, look, CHECK_WAIT, 2500, (seen) => classify(seen).verdict !== "challenge"); found = classify(look); if (found.verdict === "ok") found.detail += `, passed a check by itself (${check})`; } if (found.verdict === "ok" && !shows(look) && !stuck(look)) { look = await waitFor(page, answer, look, EMPTY_WAIT, 2000, (seen) => shows(seen) || seen.unresponsive); found = classify(look); if (found.verdict === "ok" && !shows(look) && !stuck(look)) { return slow ? { verdict: "timeout", detail: `the site answered (HTTP ${look.status}) but the page did not load in ${timeout} s`, } : { verdict: "empty", detail: `the page stayed empty for ${EMPTY_WAIT} s` }; } } if (stuck(look)) return stuck(look); const restriction = found.verdict === "ok" && restrictionPage(url, look.url); if (restriction) return { verdict: "geo_blocked", detail: `sent to a restriction page, ${restriction.replace(/\/$/, "")}` }; if (found.verdict === "ok") found = moved(url, look, found); if (found.verdict === "ok" && slow) found.detail += ", loaded slowly"; return found; } async function inspect(browser, url, shot, timeout) { const page = await browser.newPage(); const answer = watchAnswer(page); page.on("dialog", (dialog) => dialog.dismiss().catch(() => {})); try { let slow = false; try { await page.goto(url, { waitUntil: "domcontentloaded", timeout: timeout * 1000 }); } catch (error) { const failed = /net::ERR_/.test(error.message) && !error.message.includes("ERR_ABORTED"); if (!answer.status || failed) return networkError(error.message, timeout); slow = /timeout/i.test(error.message); } await page.waitForNetworkIdle({ idleTime: 800, timeout: 8000 }).catch(() => {}); const found = await judge(page, answer, url, slow, timeout); if (found.verdict !== "ok" && found.verdict !== "unresponsive" && shot) { found.screenshot = await page.screenshot({ path: shot }).then( () => shot, () => "", ); } return found; } finally { await page.close().catch(() => {}); } } export async function checkSite(browser, url, shot = "") { let found = await inspect(browser, url, shot, PAGE_TIMEOUT); if (RETRY.has(found.verdict)) { const first = found.verdict; await sleep(3000); found = await inspect(browser, url, shot, Math.min(PAGE_TIMEOUT, RETRY_TIMEOUT)); found.detail += found.verdict === first ? " (on the second try too)" : ` (the first try: ${first})`; } return { result: found.verdict === "ok" ? "AVAILABLE" : "UNAVAILABLE", reason: `${found.verdict}: ${printable(found.detail)}`, screenshot: found.screenshot || "", }; } function checkSettings() { const seconds = [PAGE_TIMEOUT, CHECK_WAIT, EMPTY_WAIT]; const problems = [ [!OS_NAMES[OS], `OS is win, mac or android, not "${OS}".`], [typeof HEADLESS !== "boolean", "HEADLESS is true or false, without quotes."], [typeof KEEP_PROFILES !== "boolean", "KEEP_PROFILES is true or false, without quotes."], [typeof SCREENSHOTS !== "boolean", "SCREENSHOTS is true or false, without quotes."], [!Number.isInteger(PARALLEL) || PARALLEL < 1 || PARALLEL > 10, "PARALLEL is a whole number from 1 to 10."], [!PROXY_TYPES.includes(DEFAULT_TYPE), `DEFAULT_TYPE is one of ${PROXY_TYPES.join(", ")}.`], [seconds.some((value) => !(value > 0)), "PAGE_TIMEOUT, CHECK_WAIT and EMPTY_WAIT are seconds above zero."], [!Number.isInteger(LOCAL_PORT) || LOCAL_PORT < 1 || LOCAL_PORT > 65535, "LOCAL_PORT is a port number, 1 to 65535."], [typeof SAVE_PROXIES !== "boolean", "SAVE_PROXIES is true or false, without quotes."], ]; const problem = problems.find(([wrong]) => wrong); if (problem) fail(`${problem[1]} Nothing was done.`); } function readToken() { const found = String(API_TOKEN).trim(); if (!found) fail("No API token: paste it into API_TOKEN at the top of the script. Nothing was done."); return found; } function readProxies() { const file = join(HERE, PROXY_FILE); const fromFile = PROXY_FILE && existsSync(file) ? readText(file).split(/\r?\n/) : []; const lines = [...PROXIES, ...fromFile].map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); const proxies = lines.map((line) => parseProxy(line)); const bad = proxies.flatMap((proxy, index) => (proxy ? [] : [index + 1])); if (bad.length) fail(`Proxy line(s) ${bad.join(", ")} not understood. Nothing was done.`); proxies.forEach((proxy) => hide(proxy.password)); return proxies; } function readVpns() { try { const { vpns, skipped } = findVpns(join(HERE, VPN_FOLDER)); if (skipped.length) console.log(`Not VPN configs, skipped in ${VPN_FOLDER}: ${skipped.join(", ")}`); if (vpns.length) console.log(`VPN configs found in ${VPN_FOLDER}: ${vpns.map((vpn) => vpn.file).join(", ")}`); if (vpns.length && !(String(VPN_PROTOCOL).trim() && String(VPN_SYN_MODE).trim())) { fail("VPN_PROTOCOL and VPN_SYN_MODE can't be empty. Nothing was done."); } for (const vpn of vpns) { hide(vpn.conf); const keys = Buffer.from(vpn.conf, "base64") .toString() .matchAll(/^\s*(?:PrivateKey|PresharedKey)\s*=\s*(\S+)/gim); for (const [, key] of keys) hide(key); } return vpns; } catch (error) { return fail(`VPN config ${error.message} (folder ${VPN_FOLDER}). Nothing was done.`); } } function readSitesFile() { const file = join(HERE, SITES_FILE); if (!existsSync(file)) fail(`${SITES_FILE} not found next to the script: put the sites there. Nothing was done.`); try { const sites = readSites(readText(file)); if (!sites.length) fail(`${SITES_FILE} has no sites. Nothing was done.`); return sites; } catch (error) { return fail(`${SITES_FILE}, ${error.message}. Nothing was done.`); } } async function connectionOf(job, saved) { if (job.vpn) return { type: "vpn", vpn_protocol: VPN_PROTOCOL, conf: job.vpn.conf, syn_mode: VPN_SYN_MODE }; return SAVE_PROXIES ? { uuid: await proxyUuid(job, saved) } : job.proxy; } async function createProfile(job, saved) { const connection = await connectionOf(job, saved); const profile = { title: `checking ${job.number}`, fingerprint: fingerprint(), proxy: connection }; const made = await cloud("POST", "/profiles", profile); if (made.data?.data?.uuid) return made.data.data.uuid; const errors = made.data?.errors ? JSON.stringify(made.data.errors).slice(0, 200) : ""; const why = [made.data?.code, made.data?.msg || made.data?.error, errors].filter(Boolean).join(" "); throw new Error(`could not create a profile (HTTP ${made.status} ${why})`); } async function startProfile(uuid) { const start = { uuid, headless: HEADLESS, debug_port: true, flags: ["--disable-backgrounding-occluded-windows"] }; const started = await local("/profiles/start", start).catch((error) => ({ ok: false, data: { error: error.message }, })); const works = Boolean(started.ok && started.data?.ws_endpoint); if (works) running.add(uuid); return { ...started, works }; } function progress(index, total, site, checked) { const count = `${String(index + 1).padStart(String(total).length)}/${total}`; const reason = /^ok: HTTP [\d?]+$/.test(checked.reason) ? "" : checked.reason; return `${count} ${checked.result.padEnd(11)} ${siteName(site).padEnd(30)} ${reason}`.trimEnd(); } async function visitSites(job, started, name, { sites, puppeteer, stamp }, say) { const entries = []; const ip = printable(started.data.connection_data?.ip || ""); const folder = join(HERE, `screens_${stamp}`, fileName(`${job.number}_${name}`)); if (SCREENSHOTS) mkdirSync(folder, { recursive: true }); let browser; let failures = 0; try { browser = await puppeteer.connect({ browserWSEndpoint: started.data.ws_endpoint, defaultViewport: null, protocolTimeout: BROWSER_TIMEOUT * 1000, }); for (const [index, site] of sites.entries()) { const number = String(index + 1).padStart(String(sites.length).length, "0"); const shot = SCREENSHOTS ? join(folder, `${number}_${fileName(siteName(site))}.png`) : ""; const checked = await checkSite(browser, site, shot); entries.push({ site, ...checked, ip }); say(progress(index, sites.length, site, checked)); failures = checked.reason.startsWith("proxy_error:") ? failures + 1 : 0; const rest = sites.slice(index + 1); if (failures === PROXY_FAILURES && rest.length) { const kind = job.vpn ? "VPN" : "proxy"; const reason = `not checked: the ${kind} stopped working after site ${index + 1}`; say(`the ${kind} stopped working: ${PROXY_FAILURES} proxy errors in a row, ${rest.length} site(s) not checked`); entries.push(...rest.map((left) => ({ site: left, result: "SKIPPED", reason, ip }))); break; } } } catch (error) { say(`stopped after ${entries.length} of ${sites.length} site(s): ${firstLine(error.message)}`); } finally { await browser?.disconnect().catch(() => {}); } return entries; } function startFailure(job, started, sites) { const reason = redact(started.data?.code || started.data?.error || `HTTP ${started.status}`); const dead = /proxy/i.test(reason) || [4, 5].includes(started.data?.error_code); const name = `${dead ? "DEAD" : "ERROR"}_${fileName(job.vpn ? job.vpn.file : job.proxy.host)}`; const problem = dead ? `the ${job.vpn ? "VPN" : "proxy"} does not work` : "could not start the profile"; return { name, message: `${job.label} -> ${name}: ${problem} (${reason})`, entries: sites.map((site) => ({ site, result: dead ? "DEAD" : "ERROR", reason })), }; } async function finishProfile(uuid, name, say) { const renamed = await cloud("PATCH", `/profiles/${uuid}`, { title: name }); if (!renamed.ok) say(`could not rename the profile (HTTP ${renamed.status})`); if (!KEEP_PROFILES) await cloud("DELETE", "/profiles", { uuids: [uuid], skip_trash_bin: false }); } async function checkConnection(job, context) { let tag = `#${job.number}`; const say = (text) => console.log(`[${tag}] ${text}`); const uuid = await createProfile(job, context.saved); say(`${job.label}: starting the profile...`); const started = await startProfile(uuid); let name, entries; if (started.works) { const exit = started.data.connection_data || {}; name = `${await countryOf(exit)}_${printable(exit.ip || "no-ip")}`; tag = `#${job.number} ${name}`; say(`${job.label}: started, ${context.sites.length} site(s) to check`); try { entries = await visitSites(job, started, name, context, say); } finally { await stopProfile(uuid); } } else { if (started.ok || started.status === undefined) await stopProfile(uuid); const failure = startFailure(job, started, context.sites); say(failure.message); ({ name, entries } = failure); } await finishProfile(uuid, name, say); const blank = { profile: name, proxy: `#${job.number} ${job.label}`, ip: "", screenshot: "" }; const rows = entries.map((entry) => ({ ...blank, ...entry })); if (rows.some((entry) => entry.result.endsWith("AVAILABLE"))) say(`done: ${summary(rows, context.sites.length)}`); return { name, rows }; } function reasonsOf(rows) { const reasons = new Map(); for (const entry of rows.filter((row) => row.result === "UNAVAILABLE")) { const reason = entry.reason.split(":")[0]; reasons.set(reason, (reasons.get(reason) || 0) + 1); } return [...reasons] .sort((a, b) => b[1] - a[1]) .map(([reason, times]) => `${times} ${reason}`) .join(", "); } function unchecked(rows, expected) { const skipped = rows.filter((entry) => entry.result === "SKIPPED"); const missed = expected - rows.length; return ( (skipped.length ? `, ${skipped.length} not checked: ${skipped[0].reason.replace(/^not checked: /, "")}` : "") + (missed ? `, ${missed} not checked` : "") ); } function summary(rows, expected) { const count = (result) => rows.filter((entry) => entry.result === result).length; if (count("DEAD")) return "does not work"; if (count("ERROR")) return `not checked: ${rows[0].reason}`; const why = reasonsOf(rows); return ( `${count("AVAILABLE")} AVAILABLE, ${count("UNAVAILABLE")} UNAVAILABLE` + (why ? ` (${why})` : "") + unchecked(rows, expected) ); } async function runAll(jobs, limit, work) { const results = new Array(jobs.length); let next = 0; const worker = async () => { while (next < jobs.length) { const index = next++; const job = jobs[index]; const done = await work(job).catch((error) => { console.log(`[#${job.number}] ${job.label}: ${firstLine(error.message)}`); return { name: "", rows: [] }; }); results[index] = { number: job.number, label: job.label, ...done }; } }; await Promise.all(Array.from({ length: limit }, worker)); return results; } function printTable(sites, results) { const columns = results.filter((column) => column.name); const repeated = (name) => columns.filter((column) => column.name === name).length > 1; const titles = columns.map((column) => (repeated(column.name) ? `${column.name} #${column.number}` : column.name)); const width = Math.max(11, ...titles.map((title) => title.length)) + 2; const siteWidth = Math.max(4, ...sites.map((site) => siteName(site).length)) + 2; console.log("Site".padEnd(siteWidth) + titles.map((title) => title.padEnd(width)).join("")); for (const site of sites) { const cells = columns.map((column) => column.rows.find((entry) => entry.site === site)?.result || "-"); console.log(siteName(site).padEnd(siteWidth) + cells.map((cell) => cell.padEnd(width)).join("")); } console.log(""); columns.forEach((column, index) => console.log(`${titles[index]}: ${summary(column.rows, sites.length)}`)); } const REPORT_COLUMNS = ["profile", "proxy", "site", "result", "reason", "ip"]; function zip(files) { const parts = []; const directory = []; let offset = 0; for (const [name, text] of files) { const title = Buffer.from(name); const data = Buffer.from(text); const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc32(data), 14); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(title.length, 26); const central = Buffer.alloc(46); central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); local.copy(central, 8, 6, 30); central.writeUInt32LE(offset, 42); parts.push(local, title, data); directory.push(central, title); offset += local.length + title.length + data.length; } const index = Buffer.concat(directory); const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10); end.writeUInt32LE(index.length, 12); end.writeUInt32LE(offset, 16); return Buffer.concat([...parts, index, end]); } const XLSX_ROW_STYLES = { AVAILABLE: 2, UNAVAILABLE: 3 }; const XLSX_OTHER_STYLE = 4; const XLSX_STYLES = '<fonts count="5"><font><sz val="11"/><name val="Calibri"/></font>' + '<font><b/><sz val="11"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF006100"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF9C0006"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF595959"/><name val="Calibri"/></font></fonts>' + '<fills count="5"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFC6EFCE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFFFC7CE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/></patternFill></fill></fills>' + '<borders count="1"><border/></borders>' + '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' + '<cellXfs count="5"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' + '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>' + '<xf numFmtId="0" fontId="2" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="3" fillId="3" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" xfId="0" applyFont="1" applyFill="1"/></cellXfs>' + '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'; const SUMMARY_COLUMNS = ["profile", "proxy", "AVAILABLE", "UNAVAILABLE", "why unavailable", "ip"]; function summaryRows(results, siteCount) { return results.map((result) => { const count = (word) => result.rows.filter((entry) => entry.result === word).length; const dead = count("DEAD") || count("ERROR"); const note = dead ? summary(result.rows, siteCount) : `${reasonsOf(result.rows)}${unchecked(result.rows, siteCount)}`.replace(/^, /, ""); return { values: [ result.name || "not started", `#${result.number} ${result.label}`, dead || !result.rows.length ? "" : count("AVAILABLE"), dead || !result.rows.length ? "" : count("UNAVAILABLE"), !result.rows.length ? "the profile was not created" : note, result.rows[0]?.ip || "", ], dead: dead || !result.rows.length, }; }); } function xlsxSheet(results, siteCount) { const escapes = { "<": "<", ">": ">", "&": "&" }; const text = (value) => printable(value ?? "") .replace(/[\uFFFE\uFFFF]/g, "") .slice(0, 32000) .replace(/[<>&]/g, (sign) => escapes[sign]); const cell = (column, line, value, style) => { const where = `${String.fromCharCode(65 + column)}${line}`; if (typeof value === "number") return `<c r="${where}" s="${style}"><v>${value}</v></c>`; return `<c r="${where}" t="inlineStr" s="${style}"><is><t xml:space="preserve">${text(value)}</t></is></c>`; }; const line = (values, number, styles) => `<row r="${number}">${values .map((value, column) => cell(column, number, value, Array.isArray(styles) ? styles[column] : styles)) .join("")}</row>`; const rows = results.flatMap((result) => result.rows); const lines = []; const add = (values, styles) => lines.push(line(values, lines.length + 1, styles)); add(["TOTAL", `${siteCount} site(s) through ${results.length} connection(s)`], 1); add(SUMMARY_COLUMNS, 1); for (const { values, dead } of summaryRows(results, siteCount)) { add(values, dead ? XLSX_OTHER_STYLE : [0, 0, XLSX_ROW_STYLES.AVAILABLE, XLSX_ROW_STYLES.UNAVAILABLE, 0, 0]); } lines.push(`<row r="${lines.length + 1}"/>`); const header = lines.length + 1; add(REPORT_COLUMNS, 1); for (const entry of rows) { add( REPORT_COLUMNS.map((column) => entry[column]), XLSX_ROW_STYLES[entry.result] || XLSX_OTHER_STYLE, ); } const widths = REPORT_COLUMNS.map((column, i) => Math.min( 90, Math.max( column.length, SUMMARY_COLUMNS[i].length, ...rows.map((entry) => String(entry[column] ?? "").length), ...summaryRows(results, siteCount).map((row) => String(row.values[i] ?? "").length), ) + 2, ), ); const last = `${String.fromCharCode(64 + REPORT_COLUMNS.length)}${lines.length}`; return ( `<cols>${widths.map((width, i) => `<col min="${i + 1}" max="${i + 1}" width="${width}" customWidth="1"/>`).join("")}</cols>` + `<sheetData>${lines.join("")}</sheetData><autoFilter ref="A${header}:${last}"/>` ); } function writeXlsx(results, siteCount, stamp) { const head = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; const main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; const office = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; const packageRels = "http://schemas.openxmlformats.org/package/2006/relationships"; const type = "application/vnd.openxmlformats-officedocument.spreadsheetml"; const file = join(HERE, `site_access_${stamp}.xlsx`); const files = [ [ "[Content_Types].xml", `${head}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` + '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' + '<Default Extension="xml" ContentType="application/xml"/>' + `<Override PartName="/xl/workbook.xml" ContentType="${type}.sheet.main+xml"/>` + `<Override PartName="/xl/worksheets/sheet1.xml" ContentType="${type}.worksheet+xml"/>` + `<Override PartName="/xl/styles.xml" ContentType="${type}.styles+xml"/></Types>`, ], [ "_rels/.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/officeDocument" Target="xl/workbook.xml"/></Relationships>`, ], [ "xl/workbook.xml", `${head}<workbook xmlns="${main}" xmlns:r="${office}">` + '<sheets><sheet name="Report" sheetId="1" r:id="rId1"/></sheets></workbook>', ], [ "xl/_rels/workbook.xml.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/worksheet" Target="worksheets/sheet1.xml"/>` + `<Relationship Id="rId2" Type="${office}/styles" Target="styles.xml"/></Relationships>`, ], [ "xl/styles.xml", `${head}<styleSheet xmlns="${main}">${XLSX_STYLES}</styleSheet>`], ["xl/worksheets/sheet1.xml", `${head}<worksheet xmlns="${main}">${xlsxSheet(results, siteCount)}</worksheet>`], ]; writeFileSync(file, zip(files)); return file; } async function main() { checkSettings(); token = readToken(); hide(token); const proxies = readProxies(); const vpns = readVpns(); if (!proxies.length && !vpns.length) { fail( `Nothing to check: put proxies into ${PROXY_FILE || "PROXIES"} or WireGuard configs into ${VPN_FOLDER}. Nothing was done.`, ); } const sites = readSitesFile(); const puppeteer = await import("puppeteer-core").then( (module) => module.default, () => fail("Puppeteer is not installed: run npm install puppeteer-core in this folder."), ); await local("/profiles/active").catch(() => fail(`The Octo client is not running, or its local port is not ${LOCAL_PORT}: set LOCAL_PORT. Nothing was done.`), ); if (OS === "android") await loadAndroidModels(); const list = SAVE_PROXIES && proxies.length ? await cloud("GET", "/proxies") : { ok: true }; if (!list.ok) fail(`Could not read the saved proxies: HTTP ${list.status}. Nothing was done.`); const saved = Array.isArray(list.data?.data) ? list.data.data : []; const jobs = [ ...proxies.map((proxy) => ({ proxy, label: proxyLabel(proxy) })), ...vpns.map((vpn) => ({ vpn, label: `VPN ${vpn.file}` })), ].map((job, index) => ({ ...job, number: index + 1 })); const workers = Math.min(PARALLEL, jobs.length); const stamp = localStamp(); console.log( `Checking ${sites.length} site(s) through ${proxies.length} proxy(ies) and ${vpns.length} VPN config(s), ` + `one ${OS_NAMES[OS]} profile each, ${HEADLESS ? "without a window" : "in a window"}, ${workers} at a time.\n`, ); const results = await runAll(jobs, workers, (job) => checkConnection(job, { sites, puppeteer, saved, stamp })); const rows = results.flatMap((result) => result.rows); console.log(""); printTable(sites, results); console.log(`\nReport: ${writeXlsx(results, sites.length, stamp)}`); if (rows.some((entry) => entry.screenshot)) console.log(`Screenshots: ${join(HERE, `screens_${stamp}`)}`); const left = limits ? ` Left: ${limits.minute}${limits.minuteLimit ? ` of ${limits.minuteLimit}` : ""} this minute, ` + `${limits.hour}${limits.hourLimit ? ` of ${limits.hourLimit}` : ""} this hour.` : ""; console.log(`${spent} request(s) counted by Octo's rate limits.${left}`); } main().catch((error) => fail(`Stopped: ${firstLine(error.message || error)}`));
Etapa 4. Criar uma lista de sites
Crie um arquivo executando notepad sites.txt. Siga estas regras:
Coloque cada endereço em uma nova linha.
Você pode incluir o prefixo
https://ou deixá-lo de fora.Comece as linhas de comentário com
#. Os comentários são úteis para dividir a lista em grupos.
# Search and reference sites google.com wikipedia.org # Online stores amazon.com ebay.com
Etapa 5. Adicionar proxies e VPNs
O script precisa de pelo menos uma conexão para funcionar: um proxy ou uma configuração de VPN. Você também pode configurar ambos os tipos de conexão.
Proxies. Crie um arquivo executando notepad proxies.txt e adicione seus proxies, um por linha. O script aceita os mesmos protocolos e formatos de linha da importação em massa de proxies no Octo Browser. Protocolos suportados: http, https, socks5 e ssh. Formatos suportados:
protocol://ip:port protocol://login:password:ip:port protocol://login:password@ip:port protocol://ip:port:login:password
Endereços IPv6 devem estar entre colchetes: socks5://[2001:db8::1]:1080:login:password. Você também pode omitir o protocolo de uma linha; nesse caso, o tipo especificado em DEFAULT_TYPE é utilizado. Linhas que começam com # são ignoradas.
VPNs. Coloque seus arquivos de configuração do WireGuard na pasta config. O nome do arquivo pode ser qualquer um: o script identifica uma configuração por seu conteúdo, especificamente pelas seções [Interface] e [Peer]. A configuração não é adicionada à lista de proxies do Octo; ela existe apenas dentro do seu próprio perfil.
[Interface] PrivateKey = <client key> Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = <server key>
Antes de executar, o script verifica em cada configuração PrivateKey, Address, PublicKey e Endpoint, e valida se Endpoint está escrito como endereço e porta, sem http://. Se o script encontrar um erro, ele exibirá o nome do arquivo e uma descrição do problema, encerrando em seguida sem criar nenhum perfil.
A estrutura da sua pasta deve ficar assim:
D:\proxy_check\ site_access.mjs script sites.txt website list proxies.txt proxy list config\ VPN configs
Etapa 6. Executar a verificação
Abra o Octo Browser e execute o script a partir da sua pasta:
cd D:\proxy_check node site_access.mjs
Para a primeira execução, use um proxy e três ou quatro sites. Você poderá ver os sites abrindo na janela do perfil. Depois de confirmar que tudo funciona, adicione o restante.
Quando o script inicia, ele verifica tudo o que poderia impedir sua execução: o token, os arquivos, as configurações de VPN e se o Octo está aberto. Se encontrar algum erro, exibe uma mensagem descrevendo o problema e encerra sem criar perfis. A verificação então começa, e o resultado de cada site é exibido assim que estiver disponível.

Os colchetes mostram o número da conexão, o nome do perfil e o contador de sites. Quando várias conexões são verificadas em paralelo, suas linhas de saída podem aparecer intercaladas. Use o rótulo para ver a qual conexão cada linha pertence. Nenhuma senha de proxy é exibida na saída, e apenas os últimos caracteres do nome de usuário são mostrados. Para interromper a verificação, pressione Ctrl+C. O script interromperá os perfis que já foram iniciados.
Como interpretar os resultados
Ao final, o script exibe uma tabela e um resumo para cada conexão:

AVAILABLE significa que o site foi aberto com sucesso e exibiu conteúdo. UNAVAILABLE significa que ele não abriu. Os motivos entre parênteses após o resultado final são listados em ordem decrescente de frequência. DEAD no nome de uma coluna indica que a própria conexão não está funcionando, e não que todos os sites verificados estão indisponíveis.
O rótulo ERROR significa que o perfil não pôde ser iniciado por um motivo não relacionado à conexão. A mensagem de erro do Octo aparece na linha dessa conexão no console e no relatório.
Os arquivos de saída são salvos na pasta. Os registros de data e hora em seus nomes usam a hora local:
site_access_<time>.xlsx— um relatório em Excel. A seção superior contém um resumo mostrando o número total de sites e, para cada conexão, quantos sites estão acessíveis, quantos estão inacessíveis e os motivos. Abaixo disso fica a verificação detalhada, com uma linha por resultado: perfil, conexão, site, resultado, motivo e IP. Linhas para sites acessíveis ficam em verde; inacessíveis, em vermelho. Linhas cinzas indicam uma conexão inoperante e sites que não foram verificados porque o proxy parou de funcionar.screens_<time>— capturas de tela das páginas de falha, com uma pasta separada para cada conexão e capturas numeradas na ordem da lista de sites. Se o site não respondeu ou o próprio proxy não conseguiu estabelecer uma conexão, não há nada a capturar, então nenhuma imagem é salva.
Os perfis permanecem no Octo Browser e são nomeados por país e IP.
Vejamos alguns problemas possíveis:
O que você vê no relatório | O que significa | O que fazer |
|---|---|---|
A conexão está marcada como | A própria conexão não está funcionando. | Verifique o nome de usuário, senha e tipo do proxy, ou os detalhes de configuração da VPN. |
A conexão está marcada como | O perfil não pôde ser iniciado, mas o problema não é a conexão. | Leia o erro no relatório ou console, corrija a causa e execute a verificação novamente. |
Várias entradas | O proxy parou de funcionar durante a verificação: sua franquia de dados acabou ou sua sessão expirou. | Verifique o proxy e execute a verificação novamente. |
Uma conexão tem muitos resultados | O provedor de proxy bloqueou esses sites. | Pergunte ao seu provedor quais categorias de sites estão bloqueadas no seu plano. |
Uma conexão recebe | O site não confia neste endereço IP ou na sua sub-rede. | Altere o IP ou use um tipo diferente de proxy. |
| O site não está disponível no país de saída. | Use um proxy de outro país. |
| O próprio site não está respondendo. | Tente a verificação novamente mais tarde. |
| A conexão está lenta ou continua caindo. | Substitua a conexão. |
| Muitas solicitações estão partindo do mesmo IP. | Aguarde e diminua o valor de |
O que significam os motivos
O código de resposta do servidor não é confiável neste caso. Uma recusa nem sempre vem acompanhada de um erro: a Akamai pode retornar "Access Denied" com um código de status 200, uma verificação do AWS WAF pode retornar 202 e um bloqueio do DataDome pode retornar 401. É por isso que o script lê a própria página. Sites de grande porte raramente criam páginas de recusa do zero: um dos sistemas de segurança conhecidos exibe a página de bloqueio, e cada um possui sua própria assinatura nos cabeçalhos e no texto.
Motivo no relatório | O que aconteceu | Como é identificado |
|---|---|---|
| O proxy não conseguiu estabelecer conexão com este site. | Um erro de túnel ou SOCKS no navegador. É assim que um site bloqueado pelo provedor de proxy se parece. |
| O próprio proxy não está funcionando. | O proxy não responde ou não aceitou o nome de usuário e a senha; código de status 407. |
| O site recusou o acesso a este IP. | Cloudflare 1005–1008, 1010, 1012, 1020 e "Sorry, you have been blocked"; Akamai "Access Denied"; Imperva, Sucuri, F5, Wordfence, AWS WAF, DataDome; códigos de status 401, 403 e 406; ou uma mensagem indicando que o site detectou um proxy ou VPN. |
| O site requer uma verificação do tipo "Você é humano?". | Cloudflare "Just a moment" e Turnstile; PerimeterX "Press & Hold"; páginas de CAPTCHA de DataDome, Akamai, AWS WAF, Kasada, Radware, DDoS-Guard e Vercel; mensagem de "tráfego incomum" do Google; CAPTCHA da Amazon; reCAPTCHA; hCaptcha. |
| O site está indisponível no país da conexão. | Cloudflare 1009, código de status 451, recusa do CloudFront baseada em país, frases como "not available in your country" ou redirecionamento para um endereço como |
| Muitas solicitações vieram deste IP. | Código de status 429 ou Cloudflare 1015. |
| O site não respondeu a tempo. | Nenhuma resposta chegou dentro do tempo estipulado, ou o site começou a responder e travou. |
| A conexão foi interrompida ou rejeitada. | A conexão foi interrompida, resposta vazia ou recusa de conexão antes do carregamento da página. |
| O endereço do site não pôde ser encontrado. | Um erro de DNS. |
| Uma conexão segura não pôde ser estabelecida. | Um erro de certificado ou TLS: o certificado foi emitido para um endereço diferente, expirou ou foi substituído no trajeto. |
| O site enviou o navegador para um endereço não relacionado. | O endereço final pertence a outro site, que exibe uma página curta ou uma recusa. |
| O site continua redirecionando em loop. | O navegador interrompeu a cadeia de redirecionamentos. |
| A página permaneceu em branco. | Nada apareceu nela dentro de 10 segundos. |
| A página parou de responder. | A página abriu, mas o navegador não conseguiu lê-la por 30 segundos porque um script nela travou. |
| O site retornou um erro. | Um código de status 4xx, como 404. |
| O próprio site está com problemas; a conexão não é o motivo. | Um código de status 5xx sem sinais de proteção de segurança. |
| Ocorreu outro erro de rede. | O código de erro do navegador é incluído no motivo. |
Os motivos se dividem em três grupos. proxy_refused e proxy_error significam que a conexão falhou: a solicitação nunca chegou ao site. blocked, challenge, geo_blocked e rate_limited significam que o proxy permitiu a passagem da solicitação, mas o site recusou o acesso. timeout, connection_reset, dns_error e ssl_error significam que nenhuma resposta foi retornada: a causa pode ser o proxy, o site ou a rede entre eles.
Como o script evita falsos resultados
Podem ocorrer erros em qualquer direção: uma falha temporária pode ser confundida com um bloqueio, ou uma página em branco pode ser interpretada como um site aberto com sucesso. Veja como o script lida com casos ambíguos:
Situação | O que o script faz |
|---|---|
A conexão cai, atinge o tempo limite ou o proxy recusa a solicitação. | Ele tenta novamente e espera até 20 segundos por uma resposta. |
O site exibe a verificação "Just a moment". | Ele aguarda até 15 segundos: essa verificação geralmente é resolvida automaticamente para um visitante comum. Se desaparecer, o resultado é |
A página demora para renderizar seus scripts. | Ele espera até 10 segundos para que o conteúdo apareça. |
O site começa a responder e depois trava. | Ele registra um motivo de |
O site abre uma caixa de diálogo | Ele descarta a caixa de diálogo cancelando-a; caso contrário, a página não pode prosseguir. O script então retoma a verificação. |
Um script na página trava. | Após 30 segundos, ele atribui o motivo |
O site redireciona para sua versão local do país, como | É o mesmo site: o resultado é |
O site redireciona para outro domínio, onde uma página comum é carregada. | O resultado é |
O site redireciona para uma página curta não relacionada ou para uma página de recusa. | O resultado é |
A página contém um script antibot, mas o site abre. | A presença de proteção não é tratada como uma recusa. Apenas a página de recusa em si conta. |
As palavras "access denied" aparecem no texto de um artigo normal. | As frases de recusa são verificadas no título da página e em páginas curtas, mas não no meio de um texto longo. |
Conclusão
O script automatiza as verificações de disponibilidade de sites por meio de proxies e VPNs. Ele mostra quais sites abrem através de cada conexão e ajuda a identificar por que os demais estão indisponíveis. Crie sua lista de sites uma vez e execute a verificação sempre que comprar novos proxies, trocar de provedor ou encontrar problemas de acesso a sites. Dessa forma, você não precisará testar cada conexão manualmente.
Perguntas frequentes
Quantas conexões podem ser verificadas simultaneamente?
Cada perfil é um navegador separado, portanto, o limite depende da sua memória e CPU. Em um dispositivo comum, de três a cinco é um número razoável; defina isso com a opção PARALLEL. Se todos os seus proxies usam o mesmo gateway de provedor, não defina um número muito alto: a conta do seu provedor pode limitar conexões simultâneas.
Quanto tempo leva uma verificação?
Um site que abre leva alguns segundos. Os sites que não respondem são os que mais demoram: o script espera 45 segundos e depois tenta novamente por mais 20. As conexões são verificadas em paralelo, portanto, verificar cinco proxies leva quase o mesmo tempo que verificar apenas um.
Por que todos os sites de uma conexão estão marcados como DEAD?
O Octo não conseguiu iniciar um perfil com esse proxy ou VPN: a conexão não está funcionando. Verifique o nome de usuário e senha do proxy, o protocolo e os dados de configuração da VPN. Se o rótulo for ERROR em vez de DEAD, o perfil não pôde ser iniciado por outro motivo não relacionado à conexão. Esse motivo é mostrado na linha da conexão.
Um site está marcado como challenge, mas abre manualmente. Por quê?
A verificação "Você é humano?" não foi concluída automaticamente em 15 segundos. Você pode completá-la manualmente com um clique, mas o script não clica em nada. O tempo de espera é controlado pela configuração CHECK_WAIT.
Por que os resultados diferem entre as execuções?
Na maioria das vezes, o proxy mudou seu endereço IP. Proxies rotativos usam IPs diferentes entre as conexões, e o site pode tratar o novo endereço de maneira distinta. Com alguns provedores, a lista de sites bloqueados também depende do nó de saída: um banco pode abrir por meio de um IP, enquanto o provedor o bloqueia por meio de outro. Outro motivo podem ser os próprios limites de taxa do site: após muitas solicitações, ele começa a retornar o código de status 429 ou a exibir uma verificação.
O perfil não inicia mesmo com o Octo aberto. O que devo fazer?
Verifique a porta da API local: abra as configurações do navegador, vá para a aba Adicional e verifique o Servidor HTTP local. Se a porta não for 58888, insira o valor correto na configuração LOCAL_PORT.
O script não consegue encontrar meu arquivo de configuração de VPN. Por quê?
O arquivo de configuração deve estar na pasta config ao lado do script e conter as seções [Interface] e [Peer]. O script ignora arquivos sem essas seções e os lista no início de sua saída.
O que acontece se um proxy parar de funcionar durante a verificação?
Isso pode acontecer quando uma sessão de proxy expira ou quando sua franquia de dados acaba: o proxy para de responder ou de aceitar o login. Após três erros consecutivos do próprio proxy, o script para de verificar sites por meio dessa conexão para não perder tempo com os sites restantes. Eles são marcados em cinza e como SKIPPED no relatório, e o resumo mostra após qual site o proxy parou de funcionar. As outras conexões continuam a ser verificadas normalmente. As recusas do provedor para sites individuais (proxy_refused) não contam: o proxy ainda está funcionando nesse caso.
O que permanece no Octo após a verificação?
Perfis nomeados por país e IP, além de eventuais novos proxies na lista de proxies. Para não deixar nada para trás, defina KEEP_PROFILES = false e SAVE_PROXIES = false: os perfis serão movidos para a lixeira e os proxies não serão adicionados à lista.
O script envia meus dados para outro lugar além do Octo?
O script envia o token apenas para o endereço da API do Octo. Ele faz uma solicitação a um serviço de terceiros: se o Octo não relatar o país de saída, o script faz a consulta por IP usando o GeoJS. Apenas o IP de saída do proxy é enviado ao GeoJS.
Mantenha-se atualizado com as últimas notícias do Octo Browser
Ao clicar no botão, você concorda com a nossa Política de Privacidade.
Mantenha-se atualizado com as últimas notícias do Octo Browser
Ao clicar no botão, você concorda com a nossa Política de Privacidade.
Mantenha-se atualizado com as últimas notícias do Octo Browser
Ao clicar no botão, você concorda com a nossa Política de Privacidade.

Junte-se ao Octo Browser agora mesmo
Ou entre em contato com a equipe de suporte no chat para tirar dúvidas a qualquer momento.

Junte-se ao Octo Browser agora mesmo
Ou entre em contato com a equipe de suporte no chat para tirar dúvidas a qualquer momento.
Junte-se ao Octo Browser agora mesmo
Ou entre em contato com a equipe de suporte no chat para tirar dúvidas a qualquer momento.