Best JavaScript code snippet using playwright-internal
socksProxy.js
Source:socksProxy.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.SocksProxyHandler = exports.SocksProxy = void 0;6var _dns = _interopRequireDefault(require("dns"));7var _events = _interopRequireDefault(require("events"));8var _net = _interopRequireDefault(require("net"));9var _util = _interopRequireDefault(require("util"));10var _debugLogger = require("./debugLogger");11var _netUtils = require("./netUtils");12var _utils = require("./utils");13function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }14/**15 * Copyright (c) Microsoft Corporation.16 *17 * Licensed under the Apache License, Version 2.0 (the "License");18 * you may not use this file except in compliance with the License.19 * You may obtain a copy of the License at20 *21 * http://www.apache.org/licenses/LICENSE-2.022 *23 * Unless required by applicable law or agreed to in writing, software24 * distributed under the License is distributed on an "AS IS" BASIS,25 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.26 * See the License for the specific language governing permissions and27 * limitations under the License.28 */29const dnsLookupAsync = _util.default.promisify(_dns.default.lookup); // https://tools.ietf.org/html/rfc192830var SocksAuth;31(function (SocksAuth) {32 SocksAuth[SocksAuth["NO_AUTHENTICATION_REQUIRED"] = 0] = "NO_AUTHENTICATION_REQUIRED";33 SocksAuth[SocksAuth["GSSAPI"] = 1] = "GSSAPI";34 SocksAuth[SocksAuth["USERNAME_PASSWORD"] = 2] = "USERNAME_PASSWORD";35 SocksAuth[SocksAuth["NO_ACCEPTABLE_METHODS"] = 255] = "NO_ACCEPTABLE_METHODS";36})(SocksAuth || (SocksAuth = {}));37var SocksAddressType;38(function (SocksAddressType) {39 SocksAddressType[SocksAddressType["IPv4"] = 1] = "IPv4";40 SocksAddressType[SocksAddressType["FqName"] = 3] = "FqName";41 SocksAddressType[SocksAddressType["IPv6"] = 4] = "IPv6";42})(SocksAddressType || (SocksAddressType = {}));43var SocksCommand;44(function (SocksCommand) {45 SocksCommand[SocksCommand["CONNECT"] = 1] = "CONNECT";46 SocksCommand[SocksCommand["BIND"] = 2] = "BIND";47 SocksCommand[SocksCommand["UDP_ASSOCIATE"] = 3] = "UDP_ASSOCIATE";48})(SocksCommand || (SocksCommand = {}));49var SocksReply;50(function (SocksReply) {51 SocksReply[SocksReply["Succeeded"] = 0] = "Succeeded";52 SocksReply[SocksReply["GeneralServerFailure"] = 1] = "GeneralServerFailure";53 SocksReply[SocksReply["NotAllowedByRuleSet"] = 2] = "NotAllowedByRuleSet";54 SocksReply[SocksReply["NetworkUnreachable"] = 3] = "NetworkUnreachable";55 SocksReply[SocksReply["HostUnreachable"] = 4] = "HostUnreachable";56 SocksReply[SocksReply["ConnectionRefused"] = 5] = "ConnectionRefused";57 SocksReply[SocksReply["TtlExpired"] = 6] = "TtlExpired";58 SocksReply[SocksReply["CommandNotSupported"] = 7] = "CommandNotSupported";59 SocksReply[SocksReply["AddressTypeNotSupported"] = 8] = "AddressTypeNotSupported";60})(SocksReply || (SocksReply = {}));61class SocksConnection {62 constructor(uid, socket, client) {63 this._buffer = Buffer.from([]);64 this._offset = 0;65 this._fence = 0;66 this._fenceCallback = void 0;67 this._socket = void 0;68 this._boundOnData = void 0;69 this._uid = void 0;70 this._client = void 0;71 this._uid = uid;72 this._socket = socket;73 this._client = client;74 this._boundOnData = this._onData.bind(this);75 socket.on('data', this._boundOnData);76 socket.on('close', () => this._onClose());77 socket.on('end', () => this._onClose());78 socket.on('error', () => this._onClose());79 this._run().catch(() => this._socket.end());80 }81 async _run() {82 (0, _utils.assert)(await this._authenticate());83 const {84 command,85 host,86 port87 } = await this._parseRequest();88 if (command !== SocksCommand.CONNECT) {89 this._writeBytes(Buffer.from([0x05, SocksReply.CommandNotSupported, 0x00, // RSV90 0x01, // IPv491 0x00, 0x00, 0x00, 0x00, // Address92 0x00, 0x00 // Port93 ]));94 return;95 }96 this._socket.off('data', this._boundOnData);97 this._client.onSocketRequested({98 uid: this._uid,99 host,100 port101 });102 }103 async _authenticate() {104 // Request:105 // +----+----------+----------+106 // |VER | NMETHODS | METHODS |107 // +----+----------+----------+108 // | 1 | 1 | 1 to 255 |109 // +----+----------+----------+110 // Response:111 // +----+--------+112 // |VER | METHOD |113 // +----+--------+114 // | 1 | 1 |115 // +----+--------+116 const version = await this._readByte();117 (0, _utils.assert)(version === 0x05, 'The VER field must be set to x05 for this version of the protocol, was ' + version);118 const nMethods = await this._readByte();119 (0, _utils.assert)(nMethods, 'No authentication methods specified');120 const methods = await this._readBytes(nMethods);121 for (const method of methods) {122 if (method === 0) {123 this._writeBytes(Buffer.from([version, method]));124 return true;125 }126 }127 this._writeBytes(Buffer.from([version, SocksAuth.NO_ACCEPTABLE_METHODS]));128 return false;129 }130 async _parseRequest() {131 // Request.132 // +----+-----+-------+------+----------+----------+133 // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |134 // +----+-----+-------+------+----------+----------+135 // | 1 | 1 | X'00' | 1 | Variable | 2 |136 // +----+-----+-------+------+----------+----------+137 // Response.138 // +----+-----+-------+------+----------+----------+139 // |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |140 // +----+-----+-------+------+----------+----------+141 // | 1 | 1 | X'00' | 1 | Variable | 2 |142 // +----+-----+-------+------+----------+----------+143 const version = await this._readByte();144 (0, _utils.assert)(version === 0x05, 'The VER field must be set to x05 for this version of the protocol, was ' + version);145 const command = await this._readByte();146 await this._readByte(); // skip reserved.147 const addressType = await this._readByte();148 let host = '';149 switch (addressType) {150 case SocksAddressType.IPv4:151 host = (await this._readBytes(4)).join('.');152 break;153 case SocksAddressType.FqName:154 const length = await this._readByte();155 host = (await this._readBytes(length)).toString();156 break;157 case SocksAddressType.IPv6:158 const bytes = await this._readBytes(16);159 const tokens = [];160 for (let i = 0; i < 8; ++i) tokens.push(bytes.readUInt16BE(i * 2));161 host = tokens.join(':');162 break;163 }164 const port = (await this._readBytes(2)).readUInt16BE(0);165 this._buffer = Buffer.from([]);166 this._offset = 0;167 this._fence = 0;168 return {169 command,170 host,171 port172 };173 }174 async _readByte() {175 const buffer = await this._readBytes(1);176 return buffer[0];177 }178 async _readBytes(length) {179 this._fence = this._offset + length;180 if (!this._buffer || this._buffer.length < this._fence) await new Promise(f => this._fenceCallback = f);181 this._offset += length;182 return this._buffer.slice(this._offset - length, this._offset);183 }184 _writeBytes(buffer) {185 if (this._socket.writable) this._socket.write(buffer);186 }187 _onClose() {188 this._client.onSocketClosed({189 uid: this._uid190 });191 }192 _onData(buffer) {193 this._buffer = Buffer.concat([this._buffer, buffer]);194 if (this._fenceCallback && this._buffer.length >= this._fence) {195 const callback = this._fenceCallback;196 this._fenceCallback = undefined;197 callback();198 }199 }200 socketConnected(host, port) {201 this._writeBytes(Buffer.from([0x05, SocksReply.Succeeded, 0x00, // RSV202 0x01, // IPv4203 ...parseIP(host), // Address204 port << 8, port & 0xFF // Port205 ]));206 this._socket.on('data', data => this._client.onSocketData({207 uid: this._uid,208 data209 }));210 }211 socketFailed(errorCode) {212 const buffer = Buffer.from([0x05, 0, 0x00, // RSV213 0x01, // IPv4214 ...parseIP('0.0.0.0'), // Address215 0, 0 // Port216 ]);217 switch (errorCode) {218 case 'ENOENT':219 case 'ENOTFOUND':220 case 'ETIMEDOUT':221 case 'EHOSTUNREACH':222 buffer[1] = SocksReply.HostUnreachable;223 break;224 case 'ENETUNREACH':225 buffer[1] = SocksReply.NetworkUnreachable;226 break;227 case 'ECONNREFUSED':228 buffer[1] = SocksReply.ConnectionRefused;229 break;230 }231 this._writeBytes(buffer);232 this._socket.end();233 }234 sendData(data) {235 this._socket.write(data);236 }237 end() {238 this._socket.end();239 }240 error(error) {241 this._socket.destroy(new Error(error));242 }243}244function parseIP(address) {245 if (!_net.default.isIPv4(address)) throw new Error('IPv6 is not supported');246 return address.split('.', 4).map(t => +t);247}248class SocksProxy extends _events.default {249 constructor() {250 super();251 this._server = void 0;252 this._connections = new Map();253 this._server = new _net.default.Server(socket => {254 const uid = (0, _utils.createGuid)();255 const connection = new SocksConnection(uid, socket, this);256 this._connections.set(uid, connection);257 });258 }259 async listen(port) {260 return new Promise(f => {261 this._server.listen(port, () => {262 const port = this._server.address().port;263 _debugLogger.debugLogger.log('proxy', `Starting socks proxy server on port ${port}`);264 f(port);265 });266 });267 }268 async close() {269 await new Promise(f => this._server.close(f));270 }271 onSocketRequested(payload) {272 this.emit(SocksProxy.Events.SocksRequested, payload);273 }274 onSocketData(payload) {275 this.emit(SocksProxy.Events.SocksData, payload);276 }277 onSocketClosed(payload) {278 this.emit(SocksProxy.Events.SocksClosed, payload);279 }280 socketConnected({281 uid,282 host,283 port284 }) {285 var _this$_connections$ge;286 (_this$_connections$ge = this._connections.get(uid)) === null || _this$_connections$ge === void 0 ? void 0 : _this$_connections$ge.socketConnected(host, port);287 }288 socketFailed({289 uid,290 errorCode291 }) {292 var _this$_connections$ge2;293 (_this$_connections$ge2 = this._connections.get(uid)) === null || _this$_connections$ge2 === void 0 ? void 0 : _this$_connections$ge2.socketFailed(errorCode);294 }295 sendSocketData({296 uid,297 data298 }) {299 var _this$_connections$ge3;300 (_this$_connections$ge3 = this._connections.get(uid)) === null || _this$_connections$ge3 === void 0 ? void 0 : _this$_connections$ge3.sendData(data);301 }302 sendSocketEnd({303 uid304 }) {305 var _this$_connections$ge4;306 (_this$_connections$ge4 = this._connections.get(uid)) === null || _this$_connections$ge4 === void 0 ? void 0 : _this$_connections$ge4.end();307 }308 sendSocketError({309 uid,310 error311 }) {312 var _this$_connections$ge5;313 (_this$_connections$ge5 = this._connections.get(uid)) === null || _this$_connections$ge5 === void 0 ? void 0 : _this$_connections$ge5.error(error);314 }315}316exports.SocksProxy = SocksProxy;317SocksProxy.Events = {318 SocksRequested: 'socksRequested',319 SocksData: 'socksData',320 SocksClosed: 'socksClosed'321};322class SocksProxyHandler extends _events.default {323 constructor(redirectPortForTest) {324 super();325 this._sockets = new Map();326 this._redirectPortForTest = void 0;327 this._redirectPortForTest = redirectPortForTest;328 }329 cleanup() {330 for (const uid of this._sockets.keys()) this.socketClosed({331 uid332 });333 }334 async socketRequested({335 uid,336 host,337 port338 }) {339 if (host === 'local.playwright') host = 'localhost';340 try {341 if (this._redirectPortForTest) port = this._redirectPortForTest;342 const {343 address344 } = await dnsLookupAsync(host);345 const socket = await (0, _netUtils.createSocket)(address, port);346 socket.on('data', data => {347 const payload = {348 uid,349 data350 };351 this.emit(SocksProxyHandler.Events.SocksData, payload);352 });353 socket.on('error', error => {354 const payload = {355 uid,356 error: error.message357 };358 this.emit(SocksProxyHandler.Events.SocksError, payload);359 this._sockets.delete(uid);360 });361 socket.on('end', () => {362 const payload = {363 uid364 };365 this.emit(SocksProxyHandler.Events.SocksEnd, payload);366 this._sockets.delete(uid);367 });368 const localAddress = socket.localAddress;369 const localPort = socket.localPort;370 this._sockets.set(uid, socket);371 const payload = {372 uid,373 host: localAddress,374 port: localPort375 };376 this.emit(SocksProxyHandler.Events.SocksConnected, payload);377 } catch (error) {378 const payload = {379 uid,380 errorCode: error.code381 };382 this.emit(SocksProxyHandler.Events.SocksFailed, payload);383 }384 }385 sendSocketData({386 uid,387 data388 }) {389 var _this$_sockets$get;390 (_this$_sockets$get = this._sockets.get(uid)) === null || _this$_sockets$get === void 0 ? void 0 : _this$_sockets$get.write(data);391 }392 socketClosed({393 uid394 }) {395 var _this$_sockets$get2;396 (_this$_sockets$get2 = this._sockets.get(uid)) === null || _this$_sockets$get2 === void 0 ? void 0 : _this$_sockets$get2.destroy();397 this._sockets.delete(uid);398 }399}400exports.SocksProxyHandler = SocksProxyHandler;401SocksProxyHandler.Events = {402 SocksConnected: 'socksConnected',403 SocksData: 'socksData',404 SocksError: 'socksError',405 SocksFailed: 'socksFailed',406 SocksEnd: 'socksEnd'...
socks.js
Source:socks.js
1var stream = require('stream'),2 util = require('util'),3 net = require('net'),4 tls = require('tls'),5 ipaddr = require('ipaddr.js');67var SocksConnection = function (remote_options, socks_options) {8 var that = this;910 stream.Duplex.call(this);1112 this.remote_options = defaults(remote_options, {13 host: 'localhost',14 ssl: false,15 rejectUnauthorized: false16 });17 socks_options = defaults(socks_options, {18 localAddress: '0.0.0.0',19 allowHalfOpen: false,20 host: 'localhost',21 port: 1080,22 user: null,23 pass: null24 });2526 this._socksSetup = false;2728 this.socksAddress = null;29 this.socksPort = null;3031 this.socksSocket = net.createConnection({32 host: socks_options.host,33 port: socks_options.port,34 localAddress: socks_options.localAddress,35 allowHalfOpen: socks_options.allowHalfOpen36 }, socksConnected.bind(this, !(!socks_options.user)));3738 this.socksSocket.on('error', function (err) {39 that.emit('error', err);40 });4142 socksAuth.call(this, {user: socks_options.user, pass: socks_options.pass});4344 this.outSocket = this.socksSocket;45};4647util.inherits(SocksConnection, stream.Duplex);4849SocksConnection.connect = function (remote_options, socks_options, connection_listener) {50 var socks_connection = new SocksConnection(remote_options, socks_options);51 if (typeof connection_listener === 'function') {52 socks_connection.on('connect', connection_listener);53 }54 return socks_connection;55};5657SocksConnection.prototype._read = function () {58 var data;59 if (this._socksSetup) {60 while ((data = this.outSocket.read()) !== null) {61 if ((this.push(data)) === false) {62 break;63 }64 }65 } else {66 this.push('');67 }68};6970SocksConnection.prototype._write = function (chunk, encoding, callback) {71 if (this._socksSetup) {72 this.outSocket.write(chunk, 'utf8', callback);73 } else {74 callback("Not connected");75 }76};7778SocksConnection.prototype.dispose = function () {79 this.outSocket.destroy();80 this.outSocket.removeAllListeners();81 if (this.outSocket !== this.socksSocket) {82 this.socksSocket.destroy();83 this.socksSocket.removeAllListeners();84 }85 this.removeAllListeners();86};8788var getData = function (socket, bytes, callback) {89 var dataReady = function () {90 var data = socket.read(bytes);91 if (data !== null) {92 socket.removeListener('readable', dataReady);93 callback(data);94 } else {95 socket.on('readable', dataReady);96 }97 };98 dataReady();99};100101var socksConnected = function (auth) {102 if (auth) {103 this.socksSocket.write('\x05\x02\x02\x00'); // SOCKS version 5, supporting two auth methods104 // username/password and 'no authentication'105 } else {106 this.socksSocket.write('\x05\x01\x00'); // SOCKS version 5, only supporting 'no auth' scheme107 }108109};110111var socksAuth = function (auth) {112 var that = this;113 getData(this.socksSocket, 2, function (data) {114 if (data.readUInt8(0) !== 5) {115 that.emit('error', 'Only SOCKS version 5 is supported');116 that.socksSocket.destroy();117 return;118 }119 switch (data.readUInt8(1)) {120 case 255:121 that.emit('error', 'SOCKS: No acceptable authentication methods');122 that.socksSocket.destroy();123 return;124 case 2:125 that.socksSocket.write(Buffer.concat([126 new Buffer([1]),127 new Buffer([Buffer.byteLength(auth.user)]),128 new Buffer(auth.user),129 new Buffer([Buffer.byteLength(auth.pass)]),130 new Buffer(auth.pass)131 ]));132 socksAuthStatus.call(that);133 break;134 default:135 socksRequest.call(that, that.remote_options.host, that.remote_options.port);136 }137 });138};139140var socksAuthStatus = function (data) {141 var that = this;142 getData(this.socksSocket, 2, function (data) {143 if (data.readUInt8(1) === 0) {144 socksRequest.call(that, that.remote_options.host, that.remote_options.port);145 } else {146 that.emit('error', 'SOCKS: Authentication failed');147 that.socksSocket.destroy();148 }149 });150};151152var socksRequest = function (host, port) {153 var header, type, hostBuf, portBuf;154 if (net.isIP(host)) {155 if (net.isIPv4(host)) {156 type = new Buffer([1]);157 } else if (net.isIPv6(host)) {158 type = new Buffer([4]);159 }160 hostBuf = new Buffer(ipaddr.parse(host).toByteArray());161 } else {162 type = new Buffer([3]);163 hostBuf = new Buffer(host);164 hostBuf = Buffer.concat([new Buffer([Buffer.byteLength(host)]), hostBuf]);165 }166 header = new Buffer([5, 1, 0]);167 portBuf = new Buffer(2);168 portBuf.writeUInt16BE(port, 0);169 this.socksSocket.write(Buffer.concat([header, type, hostBuf, portBuf]));170 socksReply.call(this);171};172173var socksReply = function (data) {174 var that = this;175 getData(this.socksSocket, 4, function (data) {176 var status, err, cont;177178 cont = function (addr, port) {179 that.socksAddress = addr;180 that.socksPort = port;181182 if (that.remote_options.ssl) {183 startTLS.call(that);184 } else {185 proxyData.call(that);186 that.emit('connect');187 }188 };189 status = data.readUInt8(1);190 if (status === 0) {191 switch(data.readUInt8(3)) {192 case 1:193 getData(that.socksSocket, 6, function (data2) {194 var addr = '', port, i;195 for (i = 0; i < 4; i++) {196 if (i !== 0) {197 addr += '.';198 }199 addr += data2.readUInt8(i).toString();200 }201 port = data2.readUInt16BE(4);202 cont(addr, port);203 });204 break;205 case 3:206 getData(that.socksSocket, 1, function (data2) {207 var length = data2.readUInt8(0);208 getData(that.socksSocket, length + 2, function (data3) {209 var addr, port;210 addr = (data3.slice(0, -2)).toString();211 port = data3.readUInt16BE(length);212 cont(addr, port);213 });214 });215 break;216 case 4:217 getData(that.socksSocket, 18, function (data2) {218 var addr = '', port, i;219 for (i = 0; i < 16; i++) {220 if (i !== 0) {221 addr += ':';222 }223 addr += data2.readUInt8(i);224 }225 port = data2.readUInt16BE(16);226 cont(addr, port);227 });228 break;229 default:230 that.emit('error', "Invalid address type");231 that.socksSocket.destroy();232 break;233 }234 } else {235 switch (status) {236 case 1:237 err = 'SOCKS: general SOCKS server failure';238 break;239 case 2:240 err = 'SOCKS: Connection not allowed by ruleset';241 break;242 case 3:243 err = 'SOCKS: Network unreachable';244 break;245 case 4:246 err = 'SOCKS: Host unreachable';247 break;248 case 5:249 err = 'SOCKS: Connection refused';250 break;251 case 6:252 err = 'SOCKS: TTL expired';253 break;254 case 7:255 err = 'SOCKS: Command not supported';256 break;257 case 8:258 err = 'SOCKS: Address type not supported';259 break;260 default:261 err = 'SOCKS: Unknown error';262 }263 that.emit('error', err);264 }265 });266};267268var startTLS = function () {269 var that = this;270 var plaintext = tls.connect({271 socket: this.socksSocket,272 rejectUnauthorized: this.remote_options.rejectUnauthorized,273 key: this.remote_options.key,274 cert: this.remote_options.cert,275 requestCert: this.remote_options.requestCert276 });277278 plaintext.on('error', function (err) {279 that.emit('error', err);280 });281282 plaintext.on('secureConnect', function () {283 that.emit('connect');284 });285286 this.outSocket = plaintext;287 this.getPeerCertificate = function(){ return plaintext.getPeerCertificate(); };288289 proxyData.call(this);290};291292var proxyData = function () {293 var that = this;294295 this.outSocket.on('readable', function () {296 var data;297 while ((data = that.outSocket.read()) !== null) {298 if ((that.push(data)) === false) {299 break;300 }301 }302 });303304 this.outSocket.on('end', function () {305 that.push(null);306 });307308 this.outSocket.on('close', function (had_err) {309 that.emit('close', had_err);310 });311312 this._socksSetup = true;313};314315var defaults = function(obj) {316 Array.prototype.slice.call(arguments, 1).forEach(function(source) {317 if (source) {318 for (var prop in source) {319 if (obj[prop] === null) {320 obj[prop] = source[prop];321 }322 }323 }324 });325 return obj;326};327
...
socksjs.js
Source:socksjs.js
1var stream = require('stream'),2 util = require('util'),3 net = require('net'),4 tls = require('tls'),5 ipaddr = require('ipaddr.js');6var SocksConnection = function (remote_options, socks_options) {7 var that = this;8 stream.Duplex.call(this);9 this.remote_options = defaults(remote_options, {10 host: 'localhost',11 ssl: false,12 rejectUnauthorized: false13 });14 socks_options = defaults(socks_options, {15 localAddress: '0.0.0.0',16 allowHalfOpen: false,17 host: 'localhost',18 port: 1080,19 user: null,20 pass: null21 });22 this._socksSetup = false;23 this.socksAddress = null;24 this.socksPort = null;25 this.socksSocket = net.createConnection({26 host: socks_options.host,27 port: socks_options.port,28 localAddress: socks_options.localAddress,29 allowHalfOpen: socks_options.allowHalfOpen30 }, socksConnected.bind(this, !(!socks_options.user)));31 this.socksSocket.on('error', function (err) {32 that.emit('error', err);33 });34 socksAuth.call(this, {user: socks_options.user, pass: socks_options.pass});35 this.outSocket = this.socksSocket;36};37util.inherits(SocksConnection, stream.Duplex);38SocksConnection.connect = function (remote_options, socks_options, connection_listener) {39 var socks_connection = new SocksConnection(remote_options, socks_options);40 if (typeof connection_listener === 'function') {41 socks_connection.on('connect', connection_listener);42 }43 return socks_connection;44};45SocksConnection.prototype._read = function () {46 var data;47 if (this._socksSetup) {48 while ((data = this.outSocket.read()) !== null) {49 if ((this.push(data)) === false) {50 break;51 }52 }53 } else {54 this.push('');55 }56};57SocksConnection.prototype._write = function (chunk, encoding, callback) {58 if (this._socksSetup) {59 this.outSocket.write(chunk, 'utf8', callback);60 } else {61 callback("Not connected");62 }63};64SocksConnection.prototype.dispose = function () {65 this.outSocket.destroy();66 this.outSocket.removeAllListeners();67 if (this.outSocket !== this.socksSocket) {68 this.socksSocket.destroy();69 this.socksSocket.removeAllListeners();70 }71 this.removeAllListeners();72};73var getData = function (socket, bytes, callback) {74 var dataReady = function () {75 var data = socket.read(bytes);76 if (data !== null) {77 socket.removeListener('readable', dataReady);78 callback(data);79 } else {80 socket.on('readable', dataReady);81 }82 };83 dataReady();84};85var socksConnected = function (auth) {86 if (auth) {87 this.socksSocket.write('\x05\x02\x02\x00'); // SOCKS version 5, supporting two auth methods88 // username/password and 'no authentication'89 } else {90 this.socksSocket.write('\x05\x01\x00'); // SOCKS version 5, only supporting 'no auth' scheme91 }92};93var socksAuth = function (auth) {94 var that = this;95 getData(this.socksSocket, 2, function (data) {96 if (data.readUInt8(0) !== 5) {97 that.emit('error', 'Only SOCKS version 5 is supported');98 that.socksSocket.destroy();99 return;100 }101 switch (data.readUInt8(1)) {102 case 255:103 that.emit('error', 'SOCKS: No acceptable authentication methods');104 that.socksSocket.destroy();105 return;106 case 2:107 that.socksSocket.write(Buffer.concat([108 new Buffer([1]),109 new Buffer([Buffer.byteLength(auth.user)]),110 new Buffer(auth.user),111 new Buffer([Buffer.byteLength(auth.pass)]),112 new Buffer(auth.pass)113 ]));114 socksAuthStatus.call(that);115 break;116 default:117 socksRequest.call(that, that.remote_options.host, that.remote_options.port);118 }119 });120};121var socksAuthStatus = function (data) {122 var that = this;123 getData(this.socksSocket, 2, function (data) {124 if (data.readUInt8(1) === 0) {125 socksRequest.call(that, that.remote_options.host, that.remote_options.port);126 } else {127 that.emit('error', 'SOCKS: Authentication failed');128 that.socksSocket.destroy();129 }130 });131};132var socksRequest = function (host, port) {133 var header, type, hostBuf, portBuf;134 if (net.isIP(host)) {135 if (net.isIPv4(host)) {136 type = new Buffer([1]);137 } else if (net.isIPv6(host)) {138 type = new Buffer([4]);139 }140 hostBuf = new Buffer(ipaddr.parse(host).toByteArray());141 } else {142 type = new Buffer([3]);143 hostBuf = new Buffer(host);144 hostBuf = Buffer.concat([new Buffer([Buffer.byteLength(host)]), hostBuf]);145 }146 header = new Buffer([5, 1, 0]);147 portBuf = new Buffer(2);148 portBuf.writeUInt16BE(port, 0);149 this.socksSocket.write(Buffer.concat([header, type, hostBuf, portBuf]));150 socksReply.call(this);151};152var socksReply = function (data) {153 var that = this;154 getData(this.socksSocket, 4, function (data) {155 var status, err, cont;156 cont = function (addr, port) {157 that.socksAddress = addr;158 that.socksPort = port;159 if (that.remote_options.ssl) {160 startTLS.call(that);161 } else {162 proxyData.call(that);163 that.emit('connect');164 }165 };166 status = data.readUInt8(1);167 if (status === 0) {168 switch(data.readUInt8(3)) {169 case 1:170 getData(that.socksSocket, 6, function (data2) {171 var addr = '', port, i;172 for (i = 0; i < 4; i++) {173 if (i !== 0) {174 addr += '.';175 }176 addr += data2.readUInt8(i).toString();177 }178 port = data2.readUInt16BE(4);179 cont(addr, port);180 });181 break;182 case 3:183 getData(that.socksSocket, 1, function (data2) {184 var length = data2.readUInt8(0);185 getData(that.socksSocket, length + 2, function (data3) {186 var addr, port;187 addr = (data3.slice(0, -2)).toString();188 port = data3.readUInt16BE(length);189 cont(addr, port);190 });191 });192 break;193 case 4:194 getData(that.socksSocket, 18, function (data2) {195 var addr = '', port, i;196 for (i = 0; i < 16; i++) {197 if (i !== 0) {198 addr += ':';199 }200 addr += data2.readUInt8(i);201 }202 port = data2.readUInt16BE(16);203 cont(addr, port);204 });205 break;206 default:207 that.emit('error', "Invalid address type");208 that.socksSocket.destroy();209 break;210 }211 } else {212 switch (status) {213 case 1:214 err = 'SOCKS: general SOCKS server failure';215 break;216 case 2:217 err = 'SOCKS: Connection not allowed by ruleset';218 break;219 case 3:220 err = 'SOCKS: Network unreachable';221 break;222 case 4:223 err = 'SOCKS: Host unreachable';224 break;225 case 5:226 err = 'SOCKS: Connection refused';227 break;228 case 6:229 err = 'SOCKS: TTL expired';230 break;231 case 7:232 err = 'SOCKS: Command not supported';233 break;234 case 8:235 err = 'SOCKS: Address type not supported';236 break;237 default:238 err = 'SOCKS: Unknown error';239 }240 that.emit('error', err);241 }242 });243};244var startTLS = function () {245 var that = this;246 var plaintext = tls.connect({247 socket: this.socksSocket,248 rejectUnauthorized: this.remote_options.rejectUnauthorized,249 key: this.remote_options.key,250 cert: this.remote_options.cert,251 requestCert: this.remote_options.requestCert252 });253 plaintext.on('error', function (err) {254 that.emit('error', err);255 });256 plaintext.on('secureConnect', function () {257 that.emit('connect');258 });259 this.outSocket = plaintext;260 this.getPeerCertificate = function(){ return plaintext.getPeerCertificate(); };261 proxyData.call(this);262};263var proxyData = function () {264 var that = this;265 this.outSocket.on('readable', function () {266 var data;267 while ((data = that.outSocket.read()) !== null) {268 if ((that.push(data)) === false) {269 break;270 }271 }272 });273 this.outSocket.on('end', function () {274 that.push(null);275 });276 this.outSocket.on('close', function (had_err) {277 that.emit('close', had_err);278 });279 this._socksSetup = true;280};281var defaults = function(obj) {282 Array.prototype.slice.call(arguments, 1).forEach(function(source) {283 if (source) {284 for (var prop in source) {285 if (obj[prop] === null) {286 obj[prop] = source[prop];287 }288 }289 }290 });291 return obj;292};...
browserTypeDispatcher.js
Source:browserTypeDispatcher.js
...127 } catch (e) {}128 };129 }130 });131 this._handler.on(socks.SocksProxyHandler.Events.SocksConnected, payload => this._channel.socksConnected(payload));132 this._handler.on(socks.SocksProxyHandler.Events.SocksData, payload => this._channel.socksData({133 uid: payload.uid,134 data: payload.data.toString('base64')135 }));136 this._handler.on(socks.SocksProxyHandler.Events.SocksError, payload => this._channel.socksError(payload));137 this._handler.on(socks.SocksProxyHandler.Events.SocksFailed, payload => this._channel.socksFailed(payload));138 this._handler.on(socks.SocksProxyHandler.Events.SocksEnd, payload => this._channel.socksEnd(payload));139 this._channel.on('socksRequested', payload => this._handler.socketRequested(payload));140 this._channel.on('socksClosed', payload => this._handler.socketClosed(payload));141 this._channel.on('socksData', payload => this._handler.sendSocketData({142 uid: payload.uid,143 data: Buffer.from(payload.data, 'base64')144 }));145 }...
playwrightDispatcher.js
Source:playwrightDispatcher.js
...57 this._socksProxy = new SocksProxy(this);58 this._object.options.socksProxyPort = await this._socksProxy.listen(0);59 _debugLogger.debugLogger.log('proxy', `Starting socks proxy server on port ${this._object.options.socksProxyPort}`);60 }61 async socksConnected(params) {62 var _this$_socksProxy;63 (_this$_socksProxy = this._socksProxy) === null || _this$_socksProxy === void 0 ? void 0 : _this$_socksProxy.socketConnected(params);64 }65 async socksFailed(params) {66 var _this$_socksProxy2;67 (_this$_socksProxy2 = this._socksProxy) === null || _this$_socksProxy2 === void 0 ? void 0 : _this$_socksProxy2.socketFailed(params);68 }69 async socksData(params) {70 var _this$_socksProxy3;71 (_this$_socksProxy3 = this._socksProxy) === null || _this$_socksProxy3 === void 0 ? void 0 : _this$_socksProxy3.sendSocketData(params);72 }73 async socksError(params) {74 var _this$_socksProxy4;75 (_this$_socksProxy4 = this._socksProxy) === null || _this$_socksProxy4 === void 0 ? void 0 : _this$_socksProxy4.sendSocketError(params);...
playwright.js
Source:playwright.js
...84 const socksSupport = this._initializer.socksSupport;85 if (!socksSupport) return;86 const handler = new socks.SocksProxyHandler(redirectPortForTest);87 this._socksProxyHandler = handler;88 handler.on(socks.SocksProxyHandler.Events.SocksConnected, payload => socksSupport.socksConnected(payload).catch(() => {}));89 handler.on(socks.SocksProxyHandler.Events.SocksData, payload => socksSupport.socksData({90 uid: payload.uid,91 data: payload.data.toString('base64')92 }).catch(() => {}));93 handler.on(socks.SocksProxyHandler.Events.SocksError, payload => socksSupport.socksError(payload).catch(() => {}));94 handler.on(socks.SocksProxyHandler.Events.SocksFailed, payload => socksSupport.socksFailed(payload).catch(() => {}));95 handler.on(socks.SocksProxyHandler.Events.SocksEnd, payload => socksSupport.socksEnd(payload).catch(() => {}));96 socksSupport.on('socksRequested', payload => handler.socketRequested(payload));97 socksSupport.on('socksClosed', payload => handler.socketClosed(payload));98 socksSupport.on('socksData', payload => handler.sendSocketData({99 uid: payload.uid,100 data: Buffer.from(payload.data, 'base64')101 }));102 }...
app-store.js
Source:app-store.js
1var Store = require('./store');2var MediaManager = require('../libs/media-manager');3var _ = require('underscore');4var AppStore = new Store({5 scheme: {6 incompatible: {7 calculate: function () {8 return !MediaManager.browserHasSupport();9 }10 },11 app: {12 deps: ['socks', 'has_configuration'],13 calculate: function() {14 return this.state.socks && this.state.has_configuration;15 }16 },17 permission_granted: false,18 permission_dialog: false,19 permission_denied: false,20 extension_loaded: false,21 ice_servers: null,22 ice_servers_expire_at: null,23 user_id: null,24 organization_id: null,25 muted: false,26 online: true,27 stream: null,28 level: null,29 has_configuration: false,30 gcm_registration_id: null,31 socks: false,32 typing: false,33 modal: false34 },35 actions: {36 'app.modal': 'showModal',37 'extension.loaded': 'extensionLoaded',38 'user.extension_registered': 'extensionRegistered',39 'user.configuration': 'reset',40 'user.typing': 'typing',41 'user.mute': 'mute',42 'user.unnmute': 'unmute',43 'webrtc.stream.local': 'webrtcPermissionsGranted',44 'webrtc.stream.remote': 'webrtcConnected',45 'webrtc.permissions': 'webrtcPermissions',46 'webrtc.permissions_granted': 'webrtcPermissionsGranted',47 'webrtc.disconnected': 'webrtcDisconnected',48 'socks.connected': 'socksConnected',49 'socks.disconnected': 'socksDisconnected'50 },51 reset: function(data) {52 this.set({53 ice_servers: data.ice_servers,54 ice_servers_expire_at: data.ice_servers_expire_at,55 user_id: data.user.id,56 has_configuration: true,57 level: data.user.level58 });59 },60 61 extensionLoaded: function() {62 this.set({extension_loaded: true});63 },64 65 extensionRegistered: function(data) {66 this.set({gcm_registration_id: data.registration_id});67 },68 69 showModal: function(name) {70 this.set({modal: name});71 },72 73 typing: function() {74 this.set({typing: true});75 },76 mute: function() {77 this.set({muted: true});78 },79 80 unmute: function() {81 this.set({muted: false});82 },83 socksConnected: function(){84 this.set({socks: true});85 },86 87 socksDisconnected: function() {88 this.set({socks: false});89 },90 webrtcPermissions: function(value) {91 if (value) this.set({permission_dialog: true});92 if (!value) this.set({permission_denied: true});93 },94 95 webrtcPermissionsGranted: function() {96 this.set({97 permission_granted: true,98 permission_dialog: false, 99 permission_denied: false100 });101 },102 103 webrtcConnected: function(stream_id) {104 this.set({stream: stream_id});105 },106 107 webrtcDisconnected: function() {108 this.set({stream: null});109 }110});...
Using AI Code Generation
1const {socksConnected} = require('playwright/lib/utils/utils');2(async () => {3 const browser = await chromium.launch({4 proxy: {5 },6 });7 const page = await browser.newPage();8 await socksConnected(page);9 await page.screenshot({ path: 'example.png' });10 await browser.close();11})();
Using AI Code Generation
1const {socksConnected} = require('playwright/lib/server/supplements/socksProxy/supplement.js');2const {socksServer} = require('playwright/lib/server/socksServer.js');3const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');4const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');5const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');6const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');7const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');8const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');9const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');10const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');11const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');12const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');13const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');14const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');15const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');16const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');17const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');18const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');19const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');20const {createProxy} = require('playwright/lib/server/supplements/socksProxy/proxy.js');
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!