Jump to content
McKay Development

Recommended Posts

Posted (edited)

this is the middleware of my route 

when ai copy console.logged proxy and pasting in new loginsession it works but when im running the code with this : `http://${ListWithGeo.login}:${ListWithGeo.password}@${ListWithGeo.PROXY_GETEWAY_HOST}:${ListWithGeo.PROXY_GETEWAY_PORT}`
IT GIVES PROXY AUTH ERROR 407 



I DONT UNDERSTAND WHAT IM DOIN WRONG PLS SOMEONE HELP ME!!!!!!!!!!!!!!!!!!!!!!!

// proxyMiddleware.js
const net = require('net');
const { HttpsProxyAgent } = require('https-proxy-agent');
const axios = require('axios')
const geoip = require('geoip-lite')
const fs = require('fs').promises;
const path = require('path');
const jwt = require('jsonwebtoken');
const GEO_FILE_PATH = path.join(__dirname, 'geo.json');


 
const PROXY_API_KEY = 'APIKEY';
const PROXY_BASE_URL = `https://proxy-seller.com/personal/api/v1/${PROXY_API_KEY}`;
const PROXY_GATEWAY_HOST = 'res.proxy-seller.com';
const PROXY_GATEWAY_PORT = 10000;
const JWT_SECRET = 'SECRET';



 
module.exports = async function proxyMiddleware(req, res, next) {
  try {
 
    const token = req.cookies.auth;
   
    if (token) {
 
      const decoded = jwt.verify(token, JWT_SECRET);
 
      const proxy = decoded.proxy
 
      console.log('Decoded Proxy:',proxy)
 
      req.proxy = proxy
 
      return next(); // No token, continue to route
 
    }
 
    console.log('starting generation of proxy for new ip')
    //(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
    const userIp = (req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim().split(':')[3];
   
    const geo = geoip.lookup(userIp);
    console.log(geo);
 
    console.log('geo.city : ',geo.city)
    console.log('geo.country: ',geo.country)
 
    const ListWithGeo = await getProxyUrl(geo.country, geo.city, userIp)
 
    console.log('gotproxyfrommiddle:',ListWithGeo)
 
    req.proxy = ListWithGeo
 
    // If IPv6 localhost like ::1, ignore
    if (!userIp || userIp.startsWith('::1') || userIp === '127.0.0.1') {
      req.proxyConfig = { proxyAgent: null };
      return next();
    }
 
    next();
  } catch (err) {
    console.error('Proxy middleware error:', err);
    req.proxyConfig = { proxyAgent: null };
    next();
  }
};





























 
async function getProxyUrl(countryCodeOrName, city, ip) {
  const MY_AUTHORIZED_IP = ip;
 
  console.log('pfuncIP :',ip)
 
  const geoDataArray = await readGeoJson();
  const countryObj = findCountry(geoDataArray, countryCodeOrName);
  const targetCityObj = findCity(countryObj, city);
 
  if (!targetCityObj.isps?.length) {
    throw new Error(`No ISPs found for city "${city}" in geo.json`);
  }
 
  const isp = targetCityObj.isps[0];
  const credentials = await requestProxy(countryObj.code, targetCityObj.region, targetCityObj.name, isp, MY_AUTHORIZED_IP);
 
  const login = encodeURIComponent(credentials.login);
  const password = encodeURIComponent(credentials.password);
 
  const test_proxy = `http://${login}:${password}@${PROXY_GATEWAY_HOST}:${PROXY_GATEWAY_PORT}`;
 
  //return`https://${login}:${password}@${PROXY_GATEWAY_HOST}:${PROXY_GATEWAY_PORT}`;
  return test_proxy;
}
 
async function readGeoJson() {
  try {
    const content = await fs.readFile(GEO_FILE_PATH, 'utf8');
    const data = JSON.parse(content);
    if (!Array.isArray(data)) throw new Error('geo.json must be an array');
    return data;
  } catch (err) {
    throw new Error(`Failed to read geo.json: ${err.message}`);
  }
}
 
function findCountry(geoArray, search) {
  const lowered = search.toLowerCase();
  const country = geoArray.find(c =>
    (c.name && c.name.toLowerCase() === lowered) ||
    (c.code && c.code.toLowerCase() === lowered)
  );
  if (!country) throw new Error(`Country "${search}" not found in geo.json`);
  return country;
}
 
function findCity(countryObj, cityName) {
  // Сначала ищем точно нужный город
  for (const region of countryObj.regions) {
    const foundCity = region.cities.find(c => c.name.toLowerCase() === cityName.toLowerCase());
    if (foundCity && foundCity.isps?.length) return { ...foundCity, region: region.name };
  }
  for (const region of countryObj.regions) {
    const cityWithIsps = region.cities.find(c => c.isps?.length);
    if (cityWithIsps) return { ...cityWithIsps, region: region.name };
  }
  throw new Error(`No city with ISPs found in country "${countryObj.name}"`);
}
 
async function requestProxy(countryCode, region, city, isp, authorizedIp) { // <-- Добавлен authorizedIp
  try {
    const postData = {
      title: `API Test with IP Binding: ${Date.now()}`,
      geo: { country: countryCode, region, city, provider: isp },
      rotation: 0,
      export: { ext: 'login:password@ip:port', ports: 1 },
      ip: authorizedIp
     
    };
 
    console.log("3. Requesting credentials with IP BINDING:", postData);
    const res = await axios.post(`${PROXY_BASE_URL}/resident/list`, postData);
 
    if (res.data.status !== 'success' || !res.data.data?.login) {
      const errMsg = res.data.errors ? JSON.stringify(res.data.errors) : 'Invalid API response';
      throw new Error(`Proxy creation failed: ${errMsg}`);
    }
    return { login: res.data.data.login, password: res.data.data.password };
  } catch (err) {
    if (err.response) console.error('API error details:', err.response.data);
    throw new Error(`Failed to request proxy: ${err.message}`);
  }
}
 
 
 
 
 
/*************************************************          AND THIS IS MY ROUTE       *************************************************\








 
const express = require('express');
const router = express.Router();
const SteamUser = require('steam-user')
const { LoginSession, EAuthTokenPlatformType } = require('steam-session');
const SteamCommunity = require('steamcommunity');
const community = new SteamCommunity();
const QRCode = require('qrcode');
const https = require('https');
const geoip = require('geoip-lite')
const activeSessions = new Map();
const client = new SteamUser()
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid'); // დავამატეთ UUID გენერატორი
const { HttpsProxyAgent } = require('https-proxy-agent');
const axios = require('axios')
const fs = require('fs').promises;
const path = require('path');
const GEO_FILE_PATH = path.join(__dirname, 'geo.json');


 
const PROXY_API_KEY = 'KEY';
const PROXY_BASE_URL = `https://proxy-seller.com/personal/api/v1/${PROXY_API_KEY}`;
const PROXY_GATEWAY_HOST = 'res.proxy-seller.com';
const PROXY_GATEWAY_PORT = 10000;
const JWT_SECRET = 'SECRET';
 
router.use(proxyMiddleware);
 
router.post('/', async (req, res) => {
  let proxyUrl = req.proxy;
 
  try {
 
    const userIp = (req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim().split(':')[3];
 
    const geo = geoip.lookup(userIp);
    console.log(geo);
 
    const ListWithGeo = await getProxyUrl(geo.country, geo.city, userIp)
 
    console.log('listeith:',ListWithGeo)
 
    const session = new LoginSession(EAuthTokenPlatformType.WebBrowser, {
      httpProxy:`http://${ListWithGeo.login}:${ListWithGeo.password}@${ListWithGeo.PROXY_GATEWAY_HOST}:${ListWithGeo.PROXY_GATEWAY_PORT}`
    });
 
    const startResult = await session.startWithQR();
    const qrImageUrl = await QRCode.toDataURL(startResult.qrChallengeUrl);
 
    const sessionId = uuidv4();
    activeSessions.set(sessionId, session);
 
    const token = jwt.sign(
      {
        proxy:req.proxy,
        sessionId: sessionId // დავამატეთ sessionId ტოკენში
      },
      'KEY',
      { expiresIn: '30d' }
    );
 
    res.cookie('auth', token, {
      httpOnly: true,
      secure: true,        
      sameSite: 'none',
      path: '/',
      maxAge: 86400000
    });
 
    res.status(200).json({
      success: true,
      message: 'qr generated',
      qrImageUrl,
      sessionId // დავაბრუნეთ sessionId კლიენტს
    });
  } catch(error) {
    console.log('QR REFRESH ERROR:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});
 
// SSE Endpoint for real-time updates
router.get('/events/:sessionId', (req, res) => {
    const { sessionId } = req.params;
    const session = activeSessions.get(sessionId);
 
    if (!session) {
        return res.status(404).json({ success: false, error: 'Session not found' });
    }
 
    // SSE headers
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('Access-Control-Allow-Origin', '*');
 
    // Send initial connection confirmation
    res.write(`event: connected\ndata: ${JSON.stringify({ message: "SSE connection established" })}\n\n`);
 
    // Event handlers
    session.on('remoteInteraction', () => {
        res.write(`event: scanned\ndata: ${JSON.stringify({ message: "QR scanned! Waiting for approval..." })}\n\n`);
    });
 
    session.on('authenticated', async () => {
        try {
            const cookies = await session.getWebCookies();
            const inventory = await loginWithCookies(cookies);
            res.write(`event: authenticated\ndata: ${JSON.stringify({
                message: "Login successful!",
                cookies,
                inventory
            })}\n\n`);
            activeSessions.delete(sessionId); // Cleanup
            res.end();
        } catch (error) {
            res.write(`event: error\ndata: ${JSON.stringify({
                error: "Failed to get inventory",
                details: error.message
            })}\n\n`);
            res.end();
            activeSessions.delete(sessionId);
        }
    });
 
    session.on('timeout', () => {
        res.write(`event: timeout\ndata: ${JSON.stringify({ message: "Session timed out." })}\n\n`);
        activeSessions.delete(sessionId);
        res.end();
    });
 
    session.on('error', (err) => {
        res.write(`event: error\ndata: ${JSON.stringify({ error: err.message })}\n\n`);
        activeSessions.delete(sessionId);
        res.end();
    });
 
    // Handle client disconnect
    req.on('close', () => {
        if (session && !session.isAuthenticated) {
            session.cancelLoginAttempt();
            activeSessions.delete(sessionId);
        }
    });
});
 
module.exports = router;




 
// Game configurations
const GAMES = {
    CS2: { appid: 730, contextid: 2 },
    DOTA2: { appid: 570, contextid: 2 },
    RUST: { appid: 252490, contextid: 2 },
    TF2: { appid: 440, contextid: 2 }
};
 
async function loginWithCookies(cookies) {
    try {
      // Set cookies and get SteamID
      community.setCookies(cookies);
      const steamID =  community.steamID.getSteamID64();
     
      // Load all inventories in parallel
      const inventoryPromises = Object.entries(GAMES).map(async ([gameName, config]) => {
        try {
          const inventory = await getInventory(steamID, config.appid, config.contextid);
          return {
            game: gameName,
            items: processInventoryItems(inventory)
          };
        } catch (error) {
            console.error(`Failed to load ${gameName} inventory:`, error);
            return {
              game: gameName,
              items: [],
              error: error.message
            };
        }
      });
 
      // Wait for all inventories to load
      const gameInventories = await Promise.all(inventoryPromises);
 
      // Convert to object format { CS2: [...], DOTA2: [...], ... }
      const inventories = {};
      gameInventories.forEach(result => {
          inventories[result.game] = result.items;
      });
 
      return {
        steamID,
        inventories
      };
 
    } catch (error) {
      console.error('Error in loginWithCookies:', error);
      throw error;
    }
}
 
function getInventory(steamID, appid, contextid) {
  return new Promise((resolve, reject) => {
    community.getUserInventoryContents(
      steamID,
      appid,
      contextid,
      true, // tradable only
      (err, inventory) => {
        if (err) return reject(err);
        resolve(inventory);
      }
  );
  });
}
 
function processInventoryItems(inventory) {
  return inventory.map(item => ({
    assetid: item.assetid,
    name: item.market_hash_name,
    icon: item.icon_url,
    icon_large: item.icon_url_large,
    tradable: item.tradable,
    marketable: item.marketable,
    type: item.type,
    amount: item.amount
  }));
}





 
module.exports = router


















 
async function getProxyUrl(countryCodeOrName, city, ip) {
  const MY_AUTHORIZED_IP = ip;
 
  console.log('pfuncIP :',ip)
 
  const geoDataArray = await readGeoJson();
  const countryObj = findCountry(geoDataArray, countryCodeOrName);
  const targetCityObj = findCity(countryObj, city);
 
  if (!targetCityObj.isps?.length) {
    throw new Error(`No ISPs found for city "${city}" in geo.json`);
  }
 
  const isp = targetCityObj.isps[0];
  const credentials = await requestProxy(countryObj.code, targetCityObj.region, targetCityObj.name, isp, MY_AUTHORIZED_IP);
 
  const login = encodeURIComponent(credentials.login);
  const password = encodeURIComponent(credentials.password);
 
  const test_proxy = `http://${login}:${password}@${PROXY_GATEWAY_HOST}:${PROXY_GATEWAY_PORT}`;
 
  //return`https://${login}:${password}@${PROXY_GATEWAY_HOST}:${PROXY_GATEWAY_PORT}`;
  return {login,password,PROXY_GATEWAY_HOST, PROXY_GATEWAY_PORT};
}
 
async function readGeoJson() {
  try {
    const content = await fs.readFile(GEO_FILE_PATH, 'utf8');
    const data = JSON.parse(content);
    if (!Array.isArray(data)) throw new Error('geo.json must be an array');
    return data;
  } catch (err) {
    throw new Error(`Failed to read geo.json: ${err.message}`);
  }
}
 
function findCountry(geoArray, search) {
  const lowered = search.toLowerCase();
  const country = geoArray.find(c =>
    (c.name && c.name.toLowerCase() === lowered) ||
    (c.code && c.code.toLowerCase() === lowered)
  );
  if (!country) throw new Error(`Country "${search}" not found in geo.json`);
  return country;
}
 
function findCity(countryObj, cityName) {
  // Сначала ищем точно нужный город
  for (const region of countryObj.regions) {
    const foundCity = region.cities.find(c => c.name.toLowerCase() === cityName.toLowerCase());
    if (foundCity && foundCity.isps?.length) return { ...foundCity, region: region.name };
  }
  for (const region of countryObj.regions) {
    const cityWithIsps = region.cities.find(c => c.isps?.length);
    if (cityWithIsps) return { ...cityWithIsps, region: region.name };
  }
  throw new Error(`No city with ISPs found in country "${countryObj.name}"`);
}
 
async function requestProxy(countryCode, region, city, isp, authorizedIp) { // <-- Добавлен authorizedIp
  try {
    const postData = {
      title: `API Test with IP Binding: ${Date.now()}`,
      geo: { country: countryCode, region, city, provider: isp },
      rotation: 0,
      export: { ext: 'login:password@ip:port', ports: 1 },
 
      // --- ДОБАВЬТЕ ПАРАМЕТР ПРИВЯЗКИ IP ИЗ ДОКУМЕНТАЦИИ ---
      // Наиболее вероятное название - 'ip'.
      // Если не сработает, ищите в документации 'bind_ip', 'auth_ip' и т.п.
      ip: authorizedIp
      // ---------------------------------------------------------
    };
 
    console.log("3. Requesting credentials with IP BINDING:", postData);
    const res = await axios.post(`${PROXY_BASE_URL}/resident/list`, postData);
 
    if (res.data.status !== 'success' || !res.data.data?.login) {
      const errMsg = res.data.errors ? JSON.stringify(res.data.errors) : 'Invalid API response';
      throw new Error(`Proxy creation failed: ${errMsg}`);
    }
    return { login: res.data.data.login, password: res.data.data.password };
  } catch (err) {
    if (err.response) console.error('API error details:', err.response.data);
    throw new Error(`Failed to request proxy: ${err.message}`);
  }
}














 
// Example usage:
// const cookies = [...]; // Get these from your authentication flow
// loginWithCookies(cookies)
//     .then(data => console.log('Inventory data:', data))
//     .catch(err => console.error('Failed:', err));





 
Edited by Metroo

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...